<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>{(something&#124;&#124;other).soft()} &#187; f#</title>
	<atom:link href="http://www.somethingorothersoft.com/tag/f/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.somethingorothersoft.com</link>
	<description>About Software Development And Other Stuff By Igor Zevaka</description>
	<lastBuildDate>Fri, 18 Jun 2010 00:15:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>F# &#8211; Combinators And Tail Recursion</title>
		<link>http://www.somethingorothersoft.com/2010/03/01/f-combinators-and-tail-recursion/</link>
		<comments>http://www.somethingorothersoft.com/2010/03/01/f-combinators-and-tail-recursion/#comments</comments>
		<pubDate>Sun, 28 Feb 2010 21:37:08 +0000</pubDate>
		<dc:creator>igor</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[f#]]></category>

		<guid isPermaLink="false">http://www.somethingorothersoft.com/?p=312</guid>
		<description><![CDATA[Perhaps combinators and tail recursion are not the best beginner topics in F# but they are the ones I got stuck into pretty much straight away. I blame Google. After reading a few google hits on functional programming I of course found out about combinators and I just had to understand them. I finally got <a href="http://www.somethingorothersoft.com/2010/03/01/f-combinators-and-tail-recursion/" rel="bookmark" title="Read on...">[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Perhaps combinators and tail recursion are not the best beginner topics in F# but they are the ones I got stuck into pretty much straight away. I blame Google. After reading a few google hits on functional programming I of course found out about combinators and I just had to understand them.</p>

<p>I finally got it but it took a while. The issue, particularly in F#, is that combinators don&#8217;t make all that much sense as a substitute for non-recursive functions. After all, the only way to run the combinator recursively is with a recursive function (as in <code>let rec</code>). A different solution might be to use recursive types, but that&#8217;s is pretty pointless. There was a great <a href="http://stackoverflow.com/questions/1998407/how-do-i-define-y-combinator-without-let-rec">StackOverflow question</a> about that by the way.</p>

<h3>What is a combinator</h3>

<p>I am getting ahead of myself though. Combinators are a mathematical concept pioneered by Haskell Curry. The essence of combinators is that they allow sophisticated computation by combining simple functions. Hence the term combinator. Combinators allow a recursive algorithm to be written using a function that does not call itself but instead invokes another function that is passed in as one of the arguments.</p>

<p>One distinct characteristic of a combinator function is that all of its variables are bound. That means that the function only depends on its parameters, not any other data structures or function defined elsewhere. Just about the best description of what is a combinator and what isn&#8217;t can be found <a href="http://mvanier.livejournal.com/2897.html">here</a></p>

<div>
<pre class="brush: fsharp;">
let freevar=3 //a variable

let IAmACombinator x = x*2;; //variable x is bound as a formal parameter
let IAmNotACombinator x = x*y;; x is bound but y is free. This is not a combinator
</pre>
</div>

<h3>Example</h3>

<p>Lets do some examples. An algorithm that I will implement is the sum of arithmetic  progression. It&#8217;s an algorithm that can really be solved in O(1) time (by using the formula (m+n)*(m-n+1)/2, but it makes for good tail recursion test (i.e. you can blow the stack quite easily, unlike the factorial, which runs out of the integer range at about 15).</p>

<p>This is the normal recursive arithmetic progression function:</p>

<div>
<pre class="brush: fsharp;">
let rec progsum x =  
    if x &lt;= 1 then 1 
    else x+progsum (x-1)
</pre>
</div>

<h3>Combinator Version</h3>

<p>Thanks to F# type inference, the  combinator function is pretty the same for any application and only depends on the number of parameters to the worker function.</p>

<p>This is the combinator version of the above function:</p>

<div>
<pre class="brush: fsharp;">
//Normal arithmentic progression sum combinator
let rec comb f = f (fun x -&gt; comb f x)
let progworker f x = 
    if x &lt;= 1 then 1 
    else x+f(x-1)
//Use partial application to wrap up the combinator call    
let progCombinator x = comb progworker x ;;
</pre>
</div>

<p>This might need a bit of explaining. <code>comb</code> is a higher order function that takes another function as a parameter and returns a function taking one argument. This returned function is what we actually want &#8211; a function taking one parameter and returning something of the same type as the parameter.</p>

<p>In the above snippet <code>progCombinator</code> is a convenient way to partially apply our combinator to the arithmetic progression worker function. We could have just as easily done for a factorial:</p>

<div>
<pre class="brush: fsharp;">
let factworker f x = 
    if x &lt;= 1 then 1
    else f(x-1) * x;;
//Use partial application to wrap up the combinator call    
let factCombinator x = comb factworker x ;;
</pre>
</div>

<h3>Tail recursion</h3>

<p><em>Tail Call Optimization</em> is an F# compiler feature (and in some cases <a href="http://blogs.msdn.com/jomo_fisher/archive/2007/09/19/adventures-in-f-tail-recursion-in-three-languages.aspx">JIT Compiler feature</a>) where it will transform a recursive function into a while loop if the recursive call is the last statement in the function. Let&#8217;s go back to the original arithmetic progression function and see if that is the case:</p>

<div>
<pre class="brush: fsharp;">
let rec progsum x =  
    if x &lt;= 1 then 1 
    else x+progsum(x-1)
</pre>
</div>

<p>And it isn&#8217;t. Even though it looks like the function call is the last statement of the function, <code>progsum(x+1)</code>  will be evaluated before <code>x+progsum(x+1)</code> can be computed. Let&#8217;s rewrite it to take advantage of tail recursion:</p>

<div>
<pre class="brush: fsharp;">
let progTR x =  
    let rec inner x sum = 
        if x &lt;= 1 then sum 
        else inner (x-1) (sum + x)
    inner x 1;;
</pre>
</div>

<p>So, what happened here? Well, for once we declared a wrapper function and the worker function inside it. This is not strictly necessary, but allows to hide some of the implementation semantics. So, if we can visualize how the original function worked, this is a crude diagram that shows the execution path for <code>x = 4</code>:</p>

<p><pre>
progsum 4
->calls progsum 3
  ->calls progsum 2
    ->calls progsum 1
       ->returns 1
    <-returns (progsum 1) + 2
  <-returns (progsum 2) + 3
<-returns (progsum 3) + 4
</pre></p>

<p>As you can see the result is computed "on the way out" - i.e. as the function returns. In the tail recursive version we compute the result "on the way in", which allows the recursive function invocation to be the last statement in the function. Here is the diagram:</p>

<p><pre>
inner 4 1
->calls inner 3 (1 + 4)
  ->calls inner 2 (5 + 3)
    ->calls inner 1 (8 + 2)
      -> returns 10
    <-returns 10
  <-returns 10
<-returns 10
</pre></p>

<p>An interesting side effect of this tail recursive function is the fact that the order in which sum happens is not quite the same as in the original function.</p>

<p>Original:</p>

<p><pre>
4 + (3 + (2 +(1)))
</pre></p>

<p>Tail Recursive:</p>

<p><pre>
((4 + 1) + 3) + 2
</pre></p>

<h3>Tail Recursive Combinator</h3>

<p>So, now that we've gone over combinator functions and tail recursive functions you may ask: "What about tail recursive combinators? Do those exist?". And the answer would be "Yes, indeed, such beasts do exist". Here is the same algorithm implemented as a tail recursive combinator:</p>

<div>
<pre class="brush: fsharp;">
let rec combTR f = f (fun x acc -&gt; combTR f x acc)
let progTR f x acc = 
    match x with
    | 1 -&gt; acc
    | x -&gt; f(x-1) (acc + x);;
    
let progCombTR x = combTR progTR x 1;;
</pre>
</div>

<p>Looking at the code, there is nothing groundbreaking there. Just as we converted the original function into a tail recursive function by adding a second parameter, we did the same for the both the combinator function and the inner function.</p>

<p>For more details on tail recursion and different ways to optimise it have a look <a href="http://thevalerios.net/matt/2009/01/recursion-in-f-and-the-tail-recursion-police/">here</a> and <a href="http://blogs.msdn.com/jomo_fisher/archive/2007/09/19/adventures-in-f-tail-recursion-in-three-languages.aspx">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.somethingorothersoft.com/2010/03/01/f-combinators-and-tail-recursion/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I Like Words &#8211; Or Introduction Into Functional Programming and F#.</title>
		<link>http://www.somethingorothersoft.com/2010/02/09/i-like-words-or-introduction-into-functional-programming-and-f/</link>
		<comments>http://www.somethingorothersoft.com/2010/02/09/i-like-words-or-introduction-into-functional-programming-and-f/#comments</comments>
		<pubDate>Tue, 09 Feb 2010 07:11:56 +0000</pubDate>
		<dc:creator>igor</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[f#]]></category>
		<category><![CDATA[functional-programming]]></category>

		<guid isPermaLink="false">http://www.somethingorothersoft.com/?p=270</guid>
		<description><![CDATA[If you hoped to find some sort of functional programming introduction here you are sadly mistaken. This is MY introduction into such said programming. Or it is more like &#8220;I&#8217;ve read up on F#, my brain exploded and spilled out into this blog post&#8221;. I would like to start off by comparing programming languages to <a href="http://www.somethingorothersoft.com/2010/02/09/i-like-words-or-introduction-into-functional-programming-and-f/" rel="bookmark" title="Read on...">[...]</a>]]></description>
			<content:encoded><![CDATA[<p>If you hoped to find some sort of functional programming introduction here you are sadly mistaken. This is MY introduction into such said programming. Or it is more like &#8220;I&#8217;ve read up on F#, my brain exploded and spilled out into this blog post&#8221;.</p>

<p>I would like to start off by comparing programming languages to spoken languages. Most will agree that the comparison is fair. Programming languages bear most hallmarks of real life languages. There is syntax, grammar, dictionary, there are historical reasons for why the language the way it is, etc. Generally speaking one is most fluent in their native tongue and could deal with a couple of others. Similarly in programming you have your native language &#8211; C family, VB, Pascal, Ruby, Python, Perl, hieroglyphics(PHP) etc.</p>

<p>My native language is Russian and that&#8217;s what I grew up with. From a reasonalby early age I learnt English and was reasonably fluent in it as a second language. I would like to equate this SECOND language to your FIRST programming language. The similarity, for the sake of this post, is that you think in your native language and translate it into code. The process, as those who speak other tongues would know, is similar. You form what you want to say in your head, translate all the words into the other language, rearrange the sentence if the target language requies so and then produce the output.</p>

<p>As with a second spoken language, writing programs eventually becomes second nature. Enter third (spoken) langague, e.g. French, that I learned in school. I found that my brain was stuck in this binary Russian/English mode and I could not add French to the mix, so my French was coming out very English like.</p>

<p>This is the problem I am facing with F#. It is SO compltely different that my C/C++/C#/Whatever-happy brain does not accept it. If comparing to spoken languages, it&#8217;s even further away from C than French is from English. It&#8217;s more like Japanese, where both the alphabet and the mindset are different.</p>

<p>So, coming back to the point of this dribble. I like words. I like the explicitness of procedural languages. I think it tends to follow how one thinks. <code>if</code> statements, <code>while</code> statements, assignment, parameter passing &#8211; they are all very logical.</p>

<p>My biggest hurdle understanding F# is the fact that the same syntax can be used for instantiation and matching. For example defining a function that takes a tuple with two members:</p>

<p><pre class="brush: fsharp;">let func (a, b) = printfn &quot;a: %d, b: %d&quot; a b;;</pre></p>

<p>The syntax is the same as when you define a tuple:</p>

<p><pre class="brush: fsharp;">let tuple = (4, 5);;</pre></p>

<p>Wheres a, say C++ would do something like this:</p>

<div>

<pre class="brush: cpp;">
Tuple&lt;int, int&gt; = new Tuple&lt;int, int&gt;(4,5);

void func(Tuple&lt;int, int&gt; tuple) {
}
</pre>
</div>

<p>F# seems to just use all these symbol operators for everything and I just can&#8217;t let go of my attachment to words. <code>List.Add</code> is logical, <code>[4;5;]@[6;7]</code> is less so, especially considering that the operands cound be either values or lists.</p>

<p>Speaking of words, here is some lingo that you will undoubttedly come across as you learn a functional programming language. The list is not complete and some words are not simple definitions, but quite complex concepts &#8211; like combinators &#8211; those will make your head hurt extra good :))</p>

<ul>
<li>High Order Function &#8211; Function that can take functions as parameters and/or return a function</li>
<li>Curried function &#8211; High Order Function that binds one or more of the parameters to a predetermined value and returns a function that takes less parameters.</li>
<li>Purity &#8211; Functions not having side effects &#8211; i.e. the function produces an output without chnaging the input or modifying state somewhere else. This normally invoves using immutable data structures and combinators.</li>
<li>Cons operator (<code>::</code>) &#8211; Adding an element to the beginning of the list.</li>
<li>Strictness &#8211; Evaluating parameters to the function before the function is evaluated.</li>
<li>combinator &#8211; High order function that has no free variables. Short version is that this function only operates on its parameters, not any other functions or values defined elsewhere.</li>
<li>Memoization &#8211; Remembering the result of a slow running function for future use (Caching).</li>
<li>Imperative programming &#8211; &#8220;normal&#8221; programming &#8211; i.e. Procedural, Object Orientated, etc.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.somethingorothersoft.com/2010/02/09/i-like-words-or-introduction-into-functional-programming-and-f/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
