tag:blogger.com,1999:blog-45854643096987082372024-02-20T22:27:03.636-05:00Consumed by CodeCode is a predator and I'm its prey.Ray Vernagushttp://www.blogger.com/profile/12678750838556666846noreply@blogger.comBlogger17125tag:blogger.com,1999:blog-4585464309698708237.post-84884266513005131262009-12-14T22:29:00.005-05:002009-12-15T11:01:50.628-05:00Towards FsUnit 1.0<p>I have been giving a lot of consideration recently to an <a href="http://code.google.com/p/fsunit/">FsUnit</a> 1.0 release and the direction of the project. The 0.6 release was meant to steer the project more in the direction of Behavioral-Driven Development but there is already a much better project out there for F# and BDD, <a href="http://code.google.com/p/natural/">NaturalSpec</a>. </p> <p>FsUnit 1.0 will instead be geared for more classical unit-testing and it now has two explicit goals: 1) to make unit-testing with F# more functional in nature and 2) to leverage existing unit-testing frameworks while at the same time exploring new possibilities offered by the F# language.</p> <p>The target audience for this project is the F# developer (new and veteran alike) who wishes to use the same unit-testing framework that they’re already knowledgeable about: <a href="http://www.nunit.org/index.php">NUnit</a>, <a href="http://www.mbunit.com/">MbUnit</a>, <a href="http://www.codeplex.com/xunit">xUnit</a>, and MsTest. The new 0.9 release supports only NUnit but the others will be added soon.</p> <p>The core syntax is pretty much the same as it has always been:</p> <pre class="f#" name="code">1 |> should equal 1<br /><br />1 |> should not (equal 2)<br /><br />[1] |> should contain 1<br /><br />true |> should be True</pre><p>But tests are once again contained within a test fixture and executed with a test runner. Here is the code for one of the project examples (UPDATE: removed non-standard use of self-identifier per reader's comments. Thanks, Alan!):</p><pre class="f#" name="code">type LightBulb(state) =<br /> member x.On = state<br /> override x.ToString() =<br /> match x.On with<br /> | true -> "On"<br /> | false -> "Off"<br /><br />[<TestFixture>] <br />type ``Given a LightBulb that has had its state set to true`` ()=<br /> let lightBulb = new LightBulb(true)<br /><br /> [<Test>] member test.<br /> ``when I ask whether it is On it answers true.`` ()=<br /> lightBulb.On |> should be True<br /><br /> [<Test>] member test.<br /> ``when I convert it to a string it becomes "On".`` ()=<br /> string lightBulb |> should equal "On"<br /><br />[<TestFixture>]<br />type ``Given a LightBulb that has had its state set to false`` ()=<br /> let lightBulb = new LightBulb(false)<br /> <br /> [<Test>] member test.<br /> ``when I ask whether it is On it answers false.`` ()=<br /> lightBulb.On |> should be False<br /> <br /> [<Test>] member test.<br /> ``when I convert it to a string it becomes "Off".`` ()=<br /> string lightBulb |> should equal "Off"</pre><p>I’m curious as to what people think about the use of back-ticked method names. I, for one, find it very helpful to be able to write in plain prose instead of CamelCase’d or snake_case’d method names.</p><p>Stay tuned to this blog for more information as FsUnit reaches a 1.0 release.</p>Ray Vernagushttp://www.blogger.com/profile/12678750838556666846noreply@blogger.com6tag:blogger.com,1999:blog-4585464309698708237.post-81118101394738528452009-01-26T10:24:00.005-05:002009-08-21T13:42:35.219-04:00F# and WCF: Data ContractsF# offers the WCF developer a number of options for defining data contracts. You can use standard classes, constructed classes, or record types to define your data contracts. The key thing to remember is that the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx">DataContractSerializer</a> requires writeable properties. Let's take a look at a simple data contract defined in each of the three ways mentioned.<br /><br /><span style="font-weight:bold;">Standard Types<span style="font-style:italic;"></span></span><br /><br /><pre class="f#" name="code">[<DataContract>]<br />type MyDataContract =<br /> val mutable x : string<br /> <br /> new() = { x = "" }<br /> <br /> [<DataMember>]<br /> member this.MyDataMember<br /> with get() = this.x<br /> and set v = this.x <- v</pre><br /><br /><span style="font-weight:bold;">Constructed Types<span style="font-style:italic;"></span></span><br /><br /><pre class="f#" name="code">[<DataContract>]<br />type MyDataContract() =<br /> let mutable x = ""<br /> <br /> [<DataMember>]<br /> member this.MyDataMember<br /> with get() = x<br /> and set v = x <- v</pre><br /><br /><span style="font-weight:bold;">Record Types<span style="font-style:italic;"></span></span><br /><br /><pre class="f#" name="code">[<DataContract>]<br />type MyDataContract =<br /> { [<DataMember>] mutable MyDataMember : string }</pre><br /><br />Of the three, I prefer to use record types to define my data contracts. A record type mirrors the intention behind defining a data contract where we are simply declaring a set of data fields by name and type. If you've used the <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx">XmlSerializer</a> much, you are probably aware of the default constructor requirement. This restricted the use of record types since they do not get a default constructor. Thankfully, that restriction does not apply with the DataContractSerializer. In addition, you can remove the DataContract and DataMember attributes from your type definition if you are using <a href="http://www.microsoft.com/downloads/details.aspx?familyid=ab99342f-5d1a-413d-8319-81da479ab0d7&displaylang=en">.NET 3.5 Service Pack 1</a> although I wouldn't recommend that you do this on a routine basis.<br /><br />You should use the DataContract attribute to control the namespace and name of your contract. Thus, a good data contract in F# would look something like this:<br /><pre class="f#" name="code">[<DataContract(<br /> Namespace = "http://schemas.vernagus.blogspot.com/01/2009",<br /> Name = "MyDataContract")>]<br />type MyDataContract =<br /> { [<DataMember>] mutable MyDataMember : string }</pre><br /><br />When we create an instance of our contract and serialize it, we get the following:<br /><pre class="f#" name="code"><MyDataContract xmlns="http://schemas.vernagus.blogspot.com/01/2009"<br /> xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><br /> <MyDataMember>my value</MyDataMember><br /></MyDataContract></pre><br /><br />In my next post I will explore more advanced data contract concepts like collections and enumerations.Ray Vernagushttp://www.blogger.com/profile/12678750838556666846noreply@blogger.com1tag:blogger.com,1999:blog-4585464309698708237.post-63901264079797901442009-01-19T07:58:00.004-05:002009-01-19T08:12:56.058-05:00F# and WCF ExamplesTed Neward recently <a href="http://blogs.tedneward.com/2009/01/18/Building+WCF+Services+With+F+Part+1.aspx">wrote</a> about using F# to write WCF services. I share his enthusiasm; so much so that I'm using F# to write examples as I study for <a href="http://www.microsoft.com/learning/en/us/exams/70-503.mspx">MCTS 70-503</a>.<br /><br />Good examples are hard to find. Most of the time books will give incomplete, or worse, erroneous examples. I have striven to boil each example down to just the essentials needed to get it to run. The examples use F# Interactive and each example is a fully encapsulated, self-sufficient demonstration of some WCF concept. To run an example, simply type <code>fsi --exec <script name></code>. You can see my examples here: <a href="http://code.google.com/p/wcf-examples/source/browse/#svn/trunk/FSharpExamples">http://code.google.com/p/wcf-examples/source/browse/#svn/trunk/FSharpExamples</a><br /><br />I am planning to run a series of posts based on my experience in using F# to write WCF services. Stay tuned for that!Ray Vernagushttp://www.blogger.com/profile/12678750838556666846noreply@blogger.com0tag:blogger.com,1999:blog-4585464309698708237.post-59688878831246973262008-09-18T07:53:00.009-04:002009-08-21T13:43:15.892-04:00Programming with State in F# (Part 2)In my last post, I talked about the contrast between F# where state is locked by default and your run-of-the-mill imperative language where it is very difficult to lock state. We also saw that F# allows us to explicitly use mutable state when we choose to do so but the point is that programmer must make an explicit <em>choice</em>. The theme of this series of posts is that F#'s answer to the "whether to use state or not to use state" question is the best: we try not to use state where we can get away with it but when we have to use state we make that decision explicitly and carefully.<br /><br />I just want to talk about one example from the F# Core library. Here is an example from the Seq module:<br /><pre class="f#" name="code">let length (ie : seq<'a>) = <br /> use e = ie.GetEnumerator() <br /> let mutable state = 0 <br /> while e.MoveNext() do<br /> state <- state + 1;<br /> state</pre>The <code>length</code> function takes any sequence and returns an int. The first line of the function retrieves the enumerator for the sequence. The second line declares a mutable identifier clearly labeled <code>state</code>. The rest of the function simply moves through the enumerator incrementing the count. Finally, the function returns the final count. Do the internals of the <code>length</code> function surprise you? This example is very similar to how a length might be determined in an imperative context and it highlights my favorite feature of F#: it's your choice. You certainly can implement <code>length</code> with a recursive function and an accumulating value but would it be as fast as the version shown above? Would it be as easy to understand? You decide.<br /><br />Choices abound when using F# and one of the most important choices you can make will be whether or not to use state. The point of these last two posts are to highlight this quality of F#. State is generally discouraged but it is always available should you choose to use it.Ray Vernagushttp://www.blogger.com/profile/12678750838556666846noreply@blogger.com3tag:blogger.com,1999:blog-4585464309698708237.post-5592484031373740802008-09-17T09:47:00.007-04:002009-08-21T13:44:57.889-04:00Programming with State in F# (Part 1)There is frequent talk these days about the use of state in programs--how to limit it and whether it should be used at all. The rising importance of concurrency and functional languages have a lot to do with this but state is hardly going to go away any time soon. For instance, Kent Beck writes favorably about state in his recent book, <a href="http://www.informit.com/store/product.aspx?isbn=0321413091&rll=1">Implementation Patterns</a>: <blockquote>I think state is a valuable metaphor for us since our brains are structured and conditioned to deal with changing state. Single assignment or variableless programming forces us to discard too many effective thinking strategies to be an attractive choice.</blockquote>Kent goes on to show his readers a set of patterns that can be used to manage and communicate state in a safe and effective manner. I agree that state is a valuable metaphor in programming but what is a programmer to do if they also see value in single assignment or "stateless" programming? I think F# offers the most compelling answer to this question and I'll explain why.<br /><br />You declare a value in F# with the <code>let</code> keyword:<br /><pre class="f#" name="code">> let x = 1;;<br /><br />val x : int</pre>We can later retrieve the value, 1, using our identifier, </code>x</code>:<br /><pre class="f#" name="code">> x;;<br /><br />val it : int = 1</pre>Suppose, however, that we wanted to change the value assigned to <code>x</code>. We would use the assignment operator like so:<br /><pre class="f#" name="code">> x <- 2;;<br /><br /><span style="color:#FF0000"> x <- 2;;<br /> ^^^^^^^<br /><br />stdin(13,1): error FS0027: This value is not mutable.</span></pre>As you can see, identifiers are immutable by default in F#. Once declared, they cannot be changed. This behavior extends to more complex value types. Consider this example:<br /><pre class="f#" name="code">> open System.Drawing;;<br />> let p1 = new Point(0,0);;<br /><br />val p1 : Point<br /><br />> p1.X <- 1;;<br /><br /><span style="color:#FF0000"> p1.X <- 1;;<br /> ^^^<br /><br />stdin(24,1): error FS0191: A value must be local and mutable in order to mutate<br />the contents of a value type, e.g. 'let mutable x = ...'.</span></pre>Even though the X property of System.Drawing.Point is settable, F# treats our Point as if it is immutable. We can see how the default behavior of F# compels the programmer to limit his use of state; that's just the way that it should be. By contrast, it takes <em>a lot</em> of forethought to limit state in an imperative language.<br /><br />You can opt-in to the use of state by using the <code>mutable</code> keyword:<br /><pre class="f#" name="code">> let mutable p2 = new Point(0,0);;<br /><br />val mutable p2 : Point<br /><br />> p2.X;;<br /><br />val it : int = 0<br /><br />> p2.X <- 1;;<br /><br />val it : unit = ()<br /><br />> p2.X;;<br /><br />val it : int = 1</pre>When you declare an identifier as mutable, you get a variable just like you may be used to in C# or Visual Basic. You can even change the reference entirely:<br /><pre class="f#" name="code">> p2 <- new Point(1,1);;<br /><br />val it : unit = ()<br /><br />> p2;;<br /><br />val it : Point = {X=1,Y=1} {IsEmpty = false;<br /> X = 1;<br /> Y = 1;}</pre>To conclude this post, I hope to have shown some very basic examples of how F# forces you to think about where you are using state and why. This is a very good thing and in my next post, we will explore the use of state in functions and types.Ray Vernagushttp://www.blogger.com/profile/12678750838556666846noreply@blogger.com0tag:blogger.com,1999:blog-4585464309698708237.post-31668973633811834762008-09-08T21:07:00.007-04:002008-09-14T14:34:45.636-04:00Book Samples in F#I'm fairly new to functional programming but I <i>am</i> on my second reading of a couple of great titles: <a href="http://mitpress.mit.edu/catalog/item/default.asp?ttype=2&tid=4787">The Little MLer</a> and <a href="http://www.cambridge.org/us/catalogue/catalogue.asp?isbn=0521663504">Purely Functional Data Structures</a>.<br /><br />Both of these books contain code samples in Standard ML (SML) (the latter contains a Haskell appendix). Readers with a background in functional languages would have no problem translating from SML to OCaml and F# but for newcomers this can be a very complicated endeavor and it greatly detracts from the reading.<br /><br />When I first read these books I failed to find any code examples in F# and I even struggled to find OCaml samples based on the books. In order to encourage newcomers to F# to take up a study of functional programming, I have started a <a href="http://code.google.com/p/book-samples-in-fsharp/">project</a> on Google Code to address this need. The project will host relative ports of code samples from various books.<br /><br />I do not intend for the ports to be literal translations. There are, for instance, constructs in SML that simply aren't available in F#. But the samples should convey the spirit of the book even if they use different means to achieve that end.<br /><br />If you have samples or suggestions, corrections, or improvements for the samples, please get in touch!Ray Vernagushttp://www.blogger.com/profile/12678750838556666846noreply@blogger.com5tag:blogger.com,1999:blog-4585464309698708237.post-55027121420614144732008-09-04T09:05:00.003-04:002008-09-04T09:23:39.028-04:00FsUnit 0.6.0I've just wrapped up a 0.6.0 release of the <a href="http://code.google.com/p/fsunit/">FsUnit</a> specification framework for F#! I'm really starting to appreciate the benefits of writing specifications or tests in a functional language. I hope that this project convinces others in the same way.<br /><br />The F# 1.9.6.0 release is a very important release. F# developers get much deeper support in Visual Studio, for one, and this led a complete overhaul of the tests behind FsUnit. I prefer to do test-driven development when I can, thus a rewrite of the tests meant a rewrite of the framework itself. Everything ended up pretty much the same as it was in the previous release (0.5.0) with a couple of minor changes.<br /><br />The first important change was better messages with failures and errors. The previous release didn't always provide informative messages. With this release, you should always receive enough information to identify the problem.<br /><br />The second important change involves better support for exceptions that may occur when running your specs. Exceptions should not prevent any other specification from running and should one occur, you should get a full stack trace along with the exception message.<br /><br />Finally, there was a slight change to the <code>spec</code> function. Use of <code>spec</code> still evaluates your specification, but it no longer adds it to the internal mutable results collection. I wanted to leave mutable state out of the framework wherever possible, thus, <code>spec</code> now returns a <code>string * Result</code> pair and programmers can choose to use or not to use state in their specifications. If you're lazy like me, you can use the <code>specs</code> function to have FsUnit track your results for you.<br /><br />See the <a href="http://code.google.com/p/fsunit/">project home page</a>, the <a href="http://code.google.com/p/fsunit/w/list">project wiki</a>, or the included <a href="http://code.google.com/p/fsunit/source/browse/#svn/trunk/Examples">examples</a> for more information about the project. Please check it out and let me know how I can make it better!Ray Vernagushttp://www.blogger.com/profile/12678750838556666846noreply@blogger.com0tag:blogger.com,1999:blog-4585464309698708237.post-77618045522321366922008-08-09T21:05:00.003-04:002008-08-09T21:15:14.384-04:00Get Going Quickly with F# and ASP.NET MVCWant a quick way to get going with F# and ASP.NET MVC?<br /><ol><li>Start a new MVC project.</li><li>Add an F# project to your solution with a source file in it.</li><li>Set the project type for your F# project to dll.</li><li>Set the output path to the bin folder of your MVC project.</li><li>Add a namespace declaration to your F# source file. The namespace must match your MVC project's namespace, for example, MvcApplication1.Controllers.</li><li>Write a controller in F# and compile your F# project.</li><li>Reference your F# output in your MVC project.</li></ol>If everything's wired up correctly, you can visit the appropriate URL in your browser and your F# controller will get called!Ray Vernagushttp://www.blogger.com/profile/12678750838556666846noreply@blogger.com0tag:blogger.com,1999:blog-4585464309698708237.post-61983317920074317922008-07-24T10:12:00.004-04:002008-07-25T22:49:39.310-04:00FsUnit 0.5.0!I'd like to announce the release of <a href="http://code.google.com/p/fsunit/">FsUnit 0.5.0</a>! What began as a stabilization release ended up as a complete rewrite. The core syntax is still the same, in fact, it got even better. One of the primary goals of FsUnit is to remain as clean as possible, from language constructs that is.<br /><br />This latest release actually removed the need for a pair of parens in many cases. So instead of:<br /><pre class="code">1 |> should (equal 1)</pre><br />you can now write:<br /><pre class="code">1 |> should equal 1</pre><br />Getting rid of parens at this level is pretty important to me so it's pleasure to bid them adieu!<br /><br />One of the other major changes was perhaps more for my sake than for the user's but then maybe not. Prior releases incorporated negation into the assertion bit itself. So if you wanted to say "1 should not equal 2" you had to write:<br /><pre class="code">1 |> should (notEqual 2)</pre><br />The <code>not'</code> keyword makes it possible to negate any assertion in FsUnit:<br /><pre class="code">1 |> should not' (equal 2)</pre>This removed a lot of duplicate code and it also just about cut the number of specs for FsUnit itself in half.<br /><br />Finally, the last major change is the <code>spec</code> keyword. This keyword is a shortcut for labeling and executing your specs. It also stores the result in a ResultStore object. With the <code>spec</code> keyword, specs look like this:<br /><pre class="code">spec "A number should equal itself."<br /> (1 |> should equal 1)</pre><br /><br />I like the way that this looks very much and I'm going to try to keep this syntax stable between releases.<br /><br />Let me know what you think of the new release!Ray Vernagushttp://www.blogger.com/profile/12678750838556666846noreply@blogger.com2tag:blogger.com,1999:blog-4585464309698708237.post-46602291108711677622008-07-22T09:52:00.001-04:002008-07-22T20:12:04.695-04:00Using LINQ with ArcObjectsAre you using .NET 3.5 to do <a href="http:///">ArcObjects</a> programming? Are you still manually enumerating through row or feature cursors? Listen up!<br /><br />It's really very simple to get LINQ running with ArcObjects. All you have to do is add an extension method to either ICursor or IFeatureCursor like so:<br /><pre class="code"><span class="kwrd">public static class</span> ICursorExtensions {<br /><br /> <span class="kwrd">public static</span> IEnumerable<IRow> AsEnumerable(this ICursor source) {<br /> <span class="kwrd">Func<IRow></span> next = () => source.NextRow();<br /> <span class="kwrd">IRow</span> current = next();<br /> <span class="kwrd">while</span> (current != <span class="kwrd">null</span>) {<br /> yield return current;<br /> current = next();<br /> } <br /> }<br />}<br /></pre><br /><br />With your new extension method in hand, you can unleash LINQ on your ArcObjects code. You can now write code like this:<br /><pre class="code"><span class="kwrd">Int32</span> count = cursor.AsEnumerable().Count();<br /></pre><br /><br />Or, you could write a query expression against two cursor objects:<br /><pre class="code"></span class="kwrd">var</span> resultSeq =<br /> </span class="kwrd">from</span> x </span class="kwrd">in</span> cursor1.AsEnumerable()<br /> </span class="kwrd">from</span> y </span class="kwrd">in</span> cursor2.AsEnumerable()<br /> </span class="kwrd">where</span> x.get_Value(0) = y.get_Value(0)<br /> </span class="kwrd">select new</span> { Left = x, Right = y };<br /></pre><br /><br />You can do a similar thing in F#:<br /><pre class="code"><span class="kwrd">type</span> ICursor <span class="kwrd">with</span><br /> member c.AsEnumerable() =<br /> <span class="kwrd">seq</span> { <br /> <span class="kwrd">let</span> next = c.NextRow<br /> <span class="kwrd">let</span> current = ref (next())<br /> <span class="kwrd">while</span> !current <> null do<br /> <span class="kwrd">yield</span> !current<br /> <span class="kwrd">do</span> current := next()<br /> }<br /></span class="kwrd">let</span> count = cursor.AsEnumerable() |> Seq.length<br /></pre><br />Sure beats manually manipulating an enumerator, doesn't it?Ray Vernagushttp://www.blogger.com/profile/12678750838556666846noreply@blogger.com3tag:blogger.com,1999:blog-4585464309698708237.post-34566410911368458082008-07-16T21:29:00.000-04:002008-07-16T21:40:21.737-04:00Kill That Annoying FlickerThe DataSamples sample (pp. 291-303) in Expert F# has an annoying flicker that can be fixed by adding the following line of code after line 101:<br /><pre class="code"><span class="kwrd">do</span> base.SetStyle(ControlStyles.AllPaintingInWmPaint |||<br /> ControlStyles.UserPaint |||<br /> ControlStyles.DoubleBuffer,<br /> true)<br /></pre><br /><br />If you're writing the code yourself, put the above line after this line:<br /><pre class="code"><span class="kwrd">do</span> base.BackColor <- Color.DarkBlue </pre>Ray Vernagushttp://www.blogger.com/profile/12678750838556666846noreply@blogger.com0tag:blogger.com,1999:blog-4585464309698708237.post-3058555854022950922007-10-14T09:00:00.000-04:002007-10-22T13:20:02.525-04:00Purely Functional Data Structures: An F# Binary TreeContinuing my <a href="http://vernagus.blogspot.com/search/label/datastructs">series</a> on Purely Functional Data Structures, here's my F# implementation of a binary tree:<br /><pre class="code"><span class="kwrd">#light</span><br /><br /><span class="kwrd">type</span> Elem = int<br /><br /><span class="kwrd">type</span> Tree = E | T of Tree * Elem * Tree<br /><br /><span class="kwrd">let</span> empty = E<br /><br /><span class="kwrd">let rec</span> mem = <span class="kwrd">function</span><br /> | x, E -> false<br /> | x, T(a, y, b) when x < y -> mem(x, a)<br /> | x, T(a, y, b) when y < x -> mem(x, b)<br /> | _ -> true<br /><br /><span class="kwrd">let rec</span> insert = <span class="kwrd">function</span><br /> | x, E -> T(E, x, E)<br /> | x, T(a, y, b) when x < y -> T(insert(x, a), y, b)<br /> | x, T(a, y, b) when y < x -> T(a, y, insert(x, b))<br /> | _, s -> s</pre><br /><br />Here's what the tree looks like in use:<br /><pre class="code">> let t = T(E, 1, E);;<br /><br />val t : Tree<br /><br />> t;;<br /><br />val it : Tree = T (E,1,E)<br /><br />> let t1 = insert(0, t);;<br /><br />val t1 : Tree<br /><br />> t1;;<br /><br />val it : Tree = T (T (E,0,E),1,E)<br /><br />> let t2 = insert(10, t1);;<br /><br />val t2 : Tree<br /><br />> t2;;<br /><br />val it : Tree = T (T (E,0,E),1,T (E,10,E))<br /><br />> let t3 = insert(5, t2);;<br /><br />val t3 : Tree<br /><br />> t3;;<br /><br />val it : Tree = T (T (E,0,E),1,T (T (E,5,E),10,E))<br /><br />> mem(10, t1);;<br /><br />val it : bool = false<br /><br />> mem(10, t2);;<br /><br />val it : bool = true<br /></pre>Ray Vernagushttp://www.blogger.com/profile/12678750838556666846noreply@blogger.com2tag:blogger.com,1999:blog-4585464309698708237.post-16763561921649458242007-10-13T23:09:00.001-04:002007-10-22T13:24:32.445-04:00Stack ExamplesHere is the <a href="http://vernagus.blogspot.com/2007/10/purely-functional-data-structures-f.html">previous</a> stack implementation in use.<br /><br /><pre class="code">> let xs = Cons(0, Cons(1, Cons(2, Nil)));;<br /><br />val xs : int Stack<br /><br />> xs;;<br /><br />val it : int Stack = Cons (0,Cons (1,Cons (2,Nil)))<br /><br />> let ys = Cons(3, Cons(4, Cons(5, Nil)));;<br /><br />val ys : int Stack<br /><br />> ys;;<br /><br />val it : int Stack = Cons (3,Cons (4,Cons (5,Nil)))<br /><br />> let zs = xs -||- ys;;<br /><br />val zs : int Stack<br /><br />> zs;;<br /><br />val it : int Stack = Cons (0,Cons (1,Cons (2,Cons (3,Cons (4,Cons (5,Nil))))))<br /><br />> head xs;;<br /><br />val it : int = 0<br /><br />> tail xs;;<br /><br />val it : int Stack = Cons (1,Cons (2,Nil))<br /><br />> update(xs, 1, 99);;<br /><br />val it : int Stack = Cons (0,Cons (99,Cons (2,Nil)))<br /></pre>Ray Vernagushttp://www.blogger.com/profile/12678750838556666846noreply@blogger.com0tag:blogger.com,1999:blog-4585464309698708237.post-80432393069220969482007-10-13T22:31:00.000-04:002007-10-14T09:04:51.879-04:00Purely Functional Data Structures: An F# StackOne of the beauties of F# is that it doesn't force you to follow one programming technique. If you want to code with objects in an imperative style, you're free to. If you want to write strict functional code, you're free to do that as well.<br /><br />I'm quite familiar with imperative modes of programming so I've been bending my mind in the functional direction by reading <a href="http://www.cambridge.org/us/catalogue/catalogue.asp?isbn=0521663504">Purely Functional Data Structures</a>. The book's examples are written in ML (with a Haskell appendix), so I'm re-writing them in F#. I'll post them here as I do in the hopes that it will help other .NET programmers bend their mind as well.<br /><br />Here is the code for a Stack implementation from Chapter 2.1:<br /><pre class="code"><span class="kwrd">#light</span><br /><br /><span class="kwrd">exception</span> Empty<br /><span class="kwrd">exception</span> Subscript<br /><br /><span class="kwrd">type</span> 'a Stack = Nil | Cons of 'a * 'a Stack<br /><br /><span class="kwrd">let</span> empty = Nil<br /><br /><span class="kwrd">let</span> isEmpty = <span class="kwrd">function</span><br /> | Nil -> true<br /> | _ -> false<br /><br /><span class="kwrd">let</span> head = <span class="kwrd">function</span><br /> | Nil -> raise Empty<br /> | Cons(x, s) -> x<br /> <br /><span class="kwrd">let</span> tail = <span class="kwrd">function</span><br /> | Nil -> raise Empty<br /> | Cons(x, s) -> s<br /><br /><span class="kwrd">let rec</span> (-||-) xs ys =<br /> if isEmpty xs then<br /> ys<br /> else<br /> Cons(head xs, tail xs -||- ys)<br /><br /><span class="kwrd">let rec</span> update = <span class="kwrd">function</span><br /> | Nil, i, y -> raise Subscript<br /> | xs, 0, y -> Cons(y, tail(xs))<br /> | xs, i, y -> Cons(head(xs), update(tail(xs), i-1, y))</pre>Ray Vernagushttp://www.blogger.com/profile/12678750838556666846noreply@blogger.com0tag:blogger.com,1999:blog-4585464309698708237.post-39497627072911684712007-09-25T13:10:00.001-04:002007-09-25T13:38:24.431-04:00F# and ArcObjectsInterested in programming with ArcObject using F#? It's easy!<br /><br />Start fsi referencing the appropriate ArcObjects assemblies:<br /><pre class="code">C:\>fsi -I C:\ArcGis\DotNet -r ESRI.ArcGIS.System.dll -r ESRI.ArcGIS.DataSourcesGDB.dll -r ESRI.ArcGIS.Geodatabase.dll</pre><br /><br />Now you can open some ArcObjects namespaces:<br /><pre class="code">> open ESRI.ArcGIS.esriSystem;;<br /><br />> open ESRI.ArcGIS.DataSourcesGDB;;<br /><br />> open ESRI.ArcGIS.Geodatabase;;</pre><br /><br />Next, we need to initialize our license:<br /><pre class="code">> let aoi = new AoInitializeClass();;<br /><br />val aoi : AoInitializeClass<br /><br />> aoi.Initialize(esriLicenseProductCode.esriLicenseProductCodeArcView);;<br /><br />val it : esriLicenseStatus = esriLicenseCheckedOut</pre><br /><br />Then we can connect to our geodatabase:<br /><pre class="code">> let workspaceString = "user=MyUserName;password=MyPassword;server=MyServer;instance=MyInstance;version=SDE.DEFAULT";;<br /><br />val workspaceString : string<br /><br />> let fact = new SdeWorkspaceFactoryClass();;<br /><br />val fact : SdeWorkspaceFactoryClass<br /><br />> let ws = fact.OpenFromString(workspaceString, 0);;<br /><br />val ws : IWorkspace<br /><br />> let featureWs = (box ws) :?> IFeatureWorkspace;;<br /><br />val featureWs : IFeatureWorkspace</pre><br /><br />Notice that we have to first box our Workspace object before we can cast it to the IFeatureWorkspace interface. I believe that this has to do with <a href="http://blogs.msdn.com/brada/archive/2003/11/15/50721.aspx">explicit member implementation</a>, but I could be wrong.<br /><br />Want to get a specific feature? OK:<br /><pre class="code">> let fc = featureWs.OpenFeatureClass("MyFeatureClass");;<br /><br />val fc : IFeatureClass<br /><br />> fc.GetFeature(1684597);;<br /><br />val it : IFeature = System.__ComObject</pre><br /><br />And so on...<br /><br />As you can see, F# has no problem working with ArcObjects. Throw in the Interactive Console and you have a very attractive platform for programming with ArcObjects.Ray Vernagushttp://www.blogger.com/profile/12678750838556666846noreply@blogger.com2tag:blogger.com,1999:blog-4585464309698708237.post-79533659330898838802007-09-20T18:20:00.000-04:002007-09-20T19:00:35.404-04:00Easy Testing in F#I've found a personally acceptable answer to the <a href="http://www.google.com/search?q=unit+testing+private+public&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a">debate</a> about whether or not to test private members. This is a technique that you can use in F#.<br /><br />Here are some of the issues that you might face in testing F# code:<br /><ul><li>I want to <a href="http://xunitpatterns.com/Test%20Logic%20in%20Production.html">keep my test code out</a> of my production assembly.<br /></li><li>I need a <a href="http://msdn2.microsoft.com/en-US/library/bhc3fa7f.aspx">CLS-friendly</a> API that doesn't expose F#-specific types.</li><li>I want to test at as <a href="http://xunitpatterns.com/Philosophy%20Of%20Test%20Automation.html">fine-grained</a> a level as I can.<br /></li></ul>Perhaps you see my quandary. I want my test code to be in a separate assembly from my production code, so the code-under-test needs to be exposed. The more CLS-friendly I make my assembly, the further away from the code I get. And finally, I want to test all of those little functions that I'll inevitably end up writing except I don't want to expose all of those little functions in my API.<br /><br />My answer? It's simple, I just compile my <a href="http://xunitpatterns.com/SUT.html">SUT</a> without including my interface (.fsi) file! When you do this, every value declared in your source (.fs) file is exposed to the world for testing. Then, when I compile for release, I include the interface file and all of that stuff is hidden.<br /><br />Thus far, I've found no issues with NUnit working in this manner and it's given me the Best of Both Worlds as far as test coverage and CLS-friendly API's go!Ray Vernagushttp://www.blogger.com/profile/12678750838556666846noreply@blogger.com0tag:blogger.com,1999:blog-4585464309698708237.post-39877072732070197302007-07-23T20:17:00.000-04:002007-09-12T18:43:52.277-04:00FsUnitI've really been getting into <a href="http://research.microsoft.com/fsharp/fsharp.aspx">F#</a> as of late. I <i>love</i> not having to declare types everywhere. The syntax is almost as beautiful as Ruby. I've had no problems interoperating with any other .NET library. This latter point was a particular breath of fresh air; I don't, for example, like how IronPython handles interfaces.<br /><br />It's a struggle to learn functional programming concepts at the same as you learn a new language but that's why I chose F# in the first place. :) It's not that bad actually since with F# you can code in the same manner as you would in Visual Basic or C#. It really lets you ease into the whole functional thing...you never feel forced into something you're not ready for which is a danger when learning a purely functional language like Haskell (which I also like very much).<br /><br />So the first thing I learn in a new language is a good testing framework. I love me some <a href="www.nunit.org">NUnit</a> just as much as the next guy, but I prefer the syntax of <a href="http://rspec.rubyforge.org/index.html">RSpec</a>. I'm working on a happy medium in a project that I'm calling FsUnit. You can get it <a href="http://code.google.com/p/fsunit/">here</a>.<br /><br />With FsUnit, you still write TestFixtures and Tests but you can write assertions like the following:<br /><pre class="code">1 |> should equal 1<br /></pre><br />or<br /><pre class="code">true |> should be True<br /></pre><br /><br />Please try it out, send me ideas or corrections, and otherwise, enjoy yourself testing in F#! :)Ray Vernagushttp://www.blogger.com/profile/12678750838556666846noreply@blogger.com0