<?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>Bugfree.dk - Ronnie Holm&#039;s blog &#187; F#</title>
	<atom:link href="http://www.bugfree.dk/blog/tag/f/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bugfree.dk/blog</link>
	<description>Not anti-anything, just pro-quality</description>
	<lastBuildDate>Mon, 28 Nov 2011 07:32:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Expressing a domain specific language of propositions in F#</title>
		<link>http://www.bugfree.dk/blog/2011/11/25/expressing-a-domain-specific-language-of-propositions-in-f/</link>
		<comments>http://www.bugfree.dk/blog/2011/11/25/expressing-a-domain-specific-language-of-propositions-in-f/#comments</comments>
		<pubDate>Fri, 25 Nov 2011 21:23:00 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[F#]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/?p=1077</guid>
		<description><![CDATA[One aspect of many functional languages that’s always fascinated me is the ease with which you can express a recursive structure, such as a language, and have it evaluated. Suppose you want to define the grammar of a DSL of propositions, in F# you could do so using the discriminated union type: type Proposition = [...]]]></description>
			<content:encoded><![CDATA[<p>One aspect of many functional languages that’s always fascinated me is the ease with which you can express a recursive structure, such as a language, and have it evaluated. Suppose you want to define the grammar of a <a href="http://en.wikipedia.org/wiki/Domain-specific_language">DSL</a> of propositions, in F# you could do so using the discriminated union type:</p>
<pre class="prettyprint lang-ml">type Proposition =
    | True
    | And of Proposition * Proposition
    | Or of Proposition * Proposition
    | Not of Proposition</pre>
<p>In an object-oriented language like C#, this definition would be analogous to a hierarchy of classes. Proposition would be the base class of True, And, Or, and Not. Each would then have a constructor that accepts some number of arguments, e.g., the And constructor would accept a two-tuple, two propositions, making the Proposition type recursive. In C# you might even model the recursive relationship using the <a href="http://en.wikipedia.org/wiki/Composite_pattern">Composite pattern</a>.</p>
<p>In F#, an instance of the Proposition type may be created using a constructor syntax that resembles that of a function call:</p>
<pre class="prettyprint lang-ml">let p = And(Or(True, Not(True)), Not(Not(True)))</pre>
<p>Now, because of the recursive nature of the Proposition type, instances of it form a <a href="http://en.wikipedia.org/wiki/Parse_tree">parse tree</a>-like structure:</p>
<pre>                        And
                        /\
                       /  \
                      Or  Not
                      /\    \
                     /  \    \
                  True  Not  Not
                          \    \
                           \    \
                          True  True</pre>
<p>Having a parse tree is not very useful in itself. What you need is some way to execute or evaluate it. Given the recursive nature of the grammar, it makes sense for the evaluator to be recursively defined as well. The evaluator would do pattern matching on the node type, deconstructing it into the parts needed to evaluate it. Since our language of propositions maps directly to the boolean operations of F#, it’s very simple to evaluate the parse tree:</p>
<pre class="prettyprint lang-ml">let rec eval (p: Proposition) =
    match p with
    | True -&gt; true
    | And(p1, p2) -&gt; eval p1 &amp;&amp; eval p2
    | Or (p1, p2) -&gt; eval p1 || eval p2
    | Not(p1) -&gt; not (eval p1)

let e = eval p // e : bool = true</pre>
<p>The simple language of propositions doesn’t take into account operator precedence and associativity, variables, and so on. But the features of F# used here allow for more complicated languages to be expressed and evaluated directly. With C#, you’d often fallback to describing the grammar of more complex languages in <a href="http://en.wikipedia.org/wiki/Backus%E2%80%93Naur_Form">Backus-Naur</a> form and feeding it to a <a href="http://en.wikipedia.org/wiki/Parser_generator">parser generator</a> that would map the node types of the parse tree to classes and be able to form a valid parse tree of some input.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2011%2F11%2F25%2Fexpressing-a-domain-specific-language-of-propositions-in-f%2F&amp;title=Expressing%20a%20domain%20specific%20language%20of%20propositions%20in%20F%23" id="wpa2a_2"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2011/11/25/expressing-a-domain-specific-language-of-propositions-in-f/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>F# + SharePoint = a list attachment versioning event receiver</title>
		<link>http://www.bugfree.dk/blog/2011/11/21/f-sharepoint-a-list-attachment-versioning-event-receiver/</link>
		<comments>http://www.bugfree.dk/blog/2011/11/21/f-sharepoint-a-list-attachment-versioning-event-receiver/#comments</comments>
		<pubDate>Mon, 21 Nov 2011 07:37:00 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[SharePoint]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/?p=1074</guid>
		<description><![CDATA[It’s been a while since I last took a serious look at F#. Back then I did a simple random fractal terrain generator which, even though the algorithm is simple, I found challenging to do. Nevertheless, functional programming is just one of those areas that I keep returning to. This time around I want to [...]]]></description>
			<content:encoded><![CDATA[<p>It’s been a while since I last took a serious look at F#. Back then I did a simple <a href="http://www.bugfree.dk/blog/2009/03/06/generating-2d-random-fractal-terrains-with-f/">random fractal terrain generator</a> which, even though the algorithm is simple, I found challenging to do. Nevertheless, functional programming is just one of those areas that I keep returning to. This time around I want to use the event receiver for <a href="http://www.bugfree.dk/blog/2011/11/17/versioning-attachments-in-a-sharepoint-list-using-snapshotting/">versioning attachments in SharePoint lists</a> to get familiar with object-oriented F#. Of course, translating a C# class to an F# class, the result will look like C# with different syntax and better type inference. The point here is to use classes in F# as a way to expose functionality to other .NET languages. In a real-world F# application the core logic would likely not be object-oriented.</p>
<pre class="prettyprint lang-ml">namespace Dk.Bugfree

open System
open System.Globalization
open Microsoft.SharePoint

type public ListAttachmentVersioningEventReceiver() =
    inherit SPItemEventReceiver()

    member private r.CustomVersion = &quot;CustomVersion&quot;
    member private r.ShadowLibrary = &quot;ShadowLibrary&quot;

    // override ItemAdded : properties:SPItemEventProperties -&gt; unit
    override r.ItemAdded properties =
        base.ItemAdded properties
        r.SetCustomVersionLabel properties.ListItem
        r.CreateSnapshot properties

    // override ItemUpdated : properties:SPItemEventProperties -&gt; unit
    override r.ItemUpdated properties =
        base.ItemUpdated properties
        let item = properties.ListItem

        if r.RollbackHappened item then
            r.RestoreSnapshot properties
            r.SetCustomVersionLabel item
            r.CreateSnapshot properties
        else
            r.CreateSnapshot properties
            r.SetCustomVersionLabel item

    // member private CreateSnapshot : properties:SPItemEventProperties -&gt; unit
    member private r.CreateSnapshot properties =
        use site = properties.OpenWeb()
        let item = properties.ListItem
        let shadowLibrary = site.Lists.[r.ShadowLibrary] :?&gt; SPDocumentLibrary
        let path = String.Format(&quot;Versions/{0}/{1}&quot;, item.ID, r.GetOfficialVersionLabel(item))
        let shadowFolder = r.CreateFolderPath shadowLibrary path

        item.Attachments |&gt; Seq.cast |&gt; Seq.iter (fun fileName -&gt;
            let existingFile = item.ParentList.ParentWeb.GetFile(item.Attachments.UrlPrefix + fileName)
            let newFile = shadowFolder.Files.Add(fileName, existingFile.OpenBinaryStream())
            newFile.Item.Update())

    // member private RollbackHappened : item:SPListItem -&gt; bool
    member private r.RollbackHappened item =
        let culture = CultureInfo.InvariantCulture
        let currentVersion = Single.Parse(r.GetOfficialVersionLabel(item), culture)
        let lastVersion = Single.Parse(r.GetCustomVersionLabel(item), culture)
        currentVersion &gt; lastVersion + 1.0f

    // member private RestoreSnapshot : properties:SPItemEventProperties -&gt; unit
    member private r.RestoreSnapshot properties =
        let item = properties.ListItem
        let restoreVersion = r.GetCustomVersionLabel item
        r.EventFiringEnabled &lt;- false    

        item.Attachments |&gt; Seq.cast |&gt; Seq.map (fun fileName -&gt; unbox&lt;string&gt; fileName) |&gt; Seq.toList
                         |&gt; Seq.iter (fun fileName -&gt; item.Attachments.Delete(fileName))

        use site = properties.OpenWeb()
        let path = String.Format(&quot;Versions/{0}/{1}&quot;, item.ID, restoreVersion)
        let shadowLibrary = site.Lists.[r.ShadowLibrary] :?&gt; SPDocumentLibrary
        let source = r.CreateFolderPath shadowLibrary path

        source.Files |&gt; Seq.cast |&gt; Seq.iter (fun file -&gt;
            let unboxedFile = unbox&lt;SPFile&gt; file
            item.Attachments.Add(unboxedFile.Name, unboxedFile.OpenBinary()))

        item.SystemUpdate false
        r.EventFiringEnabled &lt;- true

    // member private CreateFolderPath : list:SPDocumentLibrary -&gt; path:string -&gt; SPFolder
    member private r.CreateFolderPath list path : SPFolder =
        r.CreateFolderPathRecursive list.RootFolder (path.Split [|'/'|] |&gt; Array.toList)

    // member private CreateFolderPathRecursive : folder:SPFolder -&gt; pathComponents:string list -&gt; SPFolder
    member private r.CreateFolderPathRecursive folder pathComponents =
        match pathComponents with
        | [] -&gt; folder
        | head :: tail -&gt;
            try
                let existingFolder = folder.SubFolders.[head]
                r.CreateFolderPathRecursive existingFolder tail
            with
                :? ArgumentException -&gt;
                    let newFolder = folder.SubFolders.Add head
                    r.CreateFolderPathRecursive newFolder tail

    // member private SetCustomVersionLabel : item:SPListItem -&gt; unit
    member private r.SetCustomVersionLabel item =
        r.EventFiringEnabled &lt;- false
        item.[r.CustomVersion] &lt;- r.GetOfficialVersionLabel item
        item.SystemUpdate false
        r.EventFiringEnabled &lt;- true  

    // member private GetCustomVersionLabel : item:SPListItem -&gt; string
    member private r.GetCustomVersionLabel item =
        item.[r.CustomVersion] :?&gt; string

    // member private GetOfficialVersionLabel : item:SPListItem -&gt; string
    member private r.GetOfficialVersionLabel item =
        item.Versions.[0].VersionLabel</pre>
<p>A couple of things to note about the F# implementation: first, it hardly specifies any types. They’re inferred by the compiler. Where type names do appear, it’s mainly because they’re required to unbox elements of an IEnumerable collection. Secondly, F# has <a href="http://stackoverflow.com/questions/5355334/what-are-the-benefits-of-such-flexible-self-identifiers-in-f">flexible self identifiers</a>. Methods must explicitly specify the name of the this reference in C# and use it when accessing members. Thirdly, arguments to general .NET methods are passed as a tuple value, i.e., as comma-delimited arguments surrounded by parenthesis.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2011%2F11%2F21%2Ff-sharepoint-a-list-attachment-versioning-event-receiver%2F&amp;title=F%23%20%2B%20SharePoint%20%3D%20a%20list%20attachment%20versioning%20event%20receiver" id="wpa2a_4"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2011/11/21/f-sharepoint-a-list-attachment-versioning-event-receiver/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generating 2D random fractal terrains with F#</title>
		<link>http://www.bugfree.dk/blog/2009/03/06/generating-2d-random-fractal-terrains-with-f/</link>
		<comments>http://www.bugfree.dk/blog/2009/03/06/generating-2d-random-fractal-terrains-with-f/#comments</comments>
		<pubDate>Thu, 05 Mar 2009 22:14:48 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Math]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/2009/03/06/generating-2d-random-fractal-terrains-with-f/</guid>
		<description><![CDATA[In Generating 2D random fractal terrains with C# I implemented 1D midpoint displacement in an imperative language. Since I&#8217;m currently making my way through Robert Pickering&#8216;s Foundations of F#, in this post I want to redo it in F#. The first step along the way is the maxDisplacements function that, given a number of splits [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://www.bugfree.dk/blog/2009/02/23/generating-2d-random-fractal-terrains-with-c">Generating 2D random fractal terrains with C#</a> I implemented 1D midpoint displacement in an imperative language. Since I&#8217;m currently making my way through <a href="http://strangelights.com/blog">Robert Pickering</a>&#8216;s <a href="http://www.amazon.com/dp/1590597575?tag=strangelights-20&amp;camp=14573&amp;creative=327641&amp;linkCode=as1&amp;creativeASIN=1590597575&amp;adid=1T0HP42WA17EB83RZNFC&amp;">Foundations of F#</a>, in this post I want to redo it in F#.</p>
<p>The first step along the way is the maxDisplacements function that, given a number of splits of line segments, returns a list of maximum displacements. Here <a href="http://en.wikipedia.org/wiki/List_comprehension">list comprehension</a> comes in handy as a way to generate maximum displacements where the next is half of that of the previous, starting with 0.5:
</p>
<pre class="prettyprint lang-fs">
    let maxDisplacements n = [for i in 1 .. n -&gt; 2.0**(float)(-i)]
</pre>
<p>Next is the composeCoordinates function whose job it is to infer the x coordinates from the y coordinates. When splitting line segments, as defined later by the split function, only y coordinates need to be dealt with. But for displaying the result as a list of points, e.g., as input to a graphing program, composeCoordinates generates the (x, y) coordinate pairs given a list of y coordinates. Again list comprehension is used to uniformly distribute the x coordinates in the range 0 to 1. Next, the x and y coordinates are fused using the build-in zip function, i.e., [x1; x2] and [y1; y2] become [(x1, y1); (x2, y2)].
</p>
<pre class="prettyprint lang-fs">
    let composeCoordinates (ys : list&lt;float&gt;) =
        let dx = 1.0 / (float)(ys.Length - 1)
        let xs = [for x in 0 .. ys.Length - 1 -&gt; (float)x * dx]
        List.zip xs ys
</pre>
<p>Now for the crux of the fractal generation process: the split function. As is customary with functional languages, looping is done using recursion and split is no exception. Passing in a list of y coordinates, a maximum displacement as generated by maxDisplacements, and a random number generator, split is defined as:
</p>
<pre class="prettyprint lang-fs">
    let rec split (ys : list&lt;float&gt;) displacement (random : Random) =
        match ys with
        | a :: b :: tail -&gt;
            let m = b - a / 2.0
            let r = random.NextDouble() * displacement
            a :: a + m + r :: split (b :: tail) displacement random
        | a -&gt; a
</pre>
<p>Using <a href="http://en.wikipedia.org/wiki/Pattern_matching">pattern matching</a>, an if-then-else construct on steroids, split examines its input of y coordinates to determine if the inductive or the base case of the recursive implementation needs to be invoked. The first pattern matches a list starting with elements a and b following by zero or more elements. In case this pattern matches, a new list is returned. It&#8217;s composed of the original a element, a new displaced element, the original b element, and split applied to the original list with its first element removed. Removing one element at a time, at some point only one element is left in the list in which case the base case is invoked. When this happens, all the original line segments have been split in two.
</p>
<p>Finally, the main function ties together the previous ones. Given an initial line segment, the number of times to apply split to it, and a random number generator, the actual splitting is done using the build-in <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">fold_left</a> function. fold_left is an example of <a href="http://codebetter.com/blogs/matthew.podwysocki/archive/2009/02/14/fun-with-folds.aspx">fun with folds</a> and a function that is itself recursively defined to make looping implicit.
</p>
<pre class="prettyprint lang-fs">
    let main() =
        let initial = [0.0; 0.0]
        let splits = 8
        let r = new Random()
        let ys = List.fold_left (fun s d -&gt; split s d r) initial (maxDisplacements splits)
        print_any (composeCoordinates ys)
</pre>
<p>While initially hard to grog, the use of fold_left becomes clearer when applied to a list of integers to compute their product. Of the three arguments to fold_left the first is a function defined by a lambda expression (here the predefined multiplication operator is also applicable but less explicit). The second argument is the initial value of an accumulator. And finally, the third argument is the list to work on.
</p>
<pre class="prettyprint lang-fs">
    List.fold_left (fun x y -&gt; x * y) 1 [1;2;3]
    List.fold_left (*) 1 [1;2;3]
</pre>
<p>What fold_left does is recursively call itself passing along the first argument as is. The second argument is the new value of the accumulator, computed by passing to the function of the first argument the original value of the accumulator and the first element of the list. That way it&#8217;s up to the function passed as the first argument to decide what operation to apply to the elements in the list. The third argument is the original list with the first element removed. The recursive chain of calls with their arguments then takes on this form:
</p>
<pre class="prettyprint lang-fs">
    List.fold_left (fun 1 1 -&gt; 1 * 1) 1 [1;2;3]
    List.fold_left (fun 1 2 -&gt; 1 * 2) 1 [2;3]
    List.fold_left (fun 2 3 -&gt; 2 * 3) 2 [3]
</pre>
<p>Within the main function the first argument to fold_left is a lambda expression that applies the split function to a list. The second argument, the accumulator, isn&#8217;t a scalar like with the product example, but a list of line segments to be passed to split. Finally, the third argument is the maximum displacement list. And so for the original line segment to be split n times, n maximum displacements must be provided by the maxDisplacements function.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2009%2F03%2F06%2Fgenerating-2d-random-fractal-terrains-with-f%2F&amp;title=Generating%202D%20random%20fractal%20terrains%20with%20F%23" id="wpa2a_6"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2009/03/06/generating-2d-random-fractal-terrains-with-f/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

