mikeobrien.net Curriculum Vitae Blog Labs
Tuesday, February 02, 2010

I’m currently working on an F# library that will be accessed from C#. When doing this the obvious question is; “How will this look from C#?” This wasn't quite clear to me at first so I’ll go through a couple custom F# types and show how they are compiled.

Record type, Fermion.fs:

type Spin = 
    | Up = 0
    | Down = 1

type Class = 
    | Quark = 0
    | Lepton = 1

type Type = 
    ...
    | Electron = 6
    ...
type Fermion = 
    { spin: Spin; particleClass: Class; particleType: Type }
    member yada.Spin = yada.spin
    member v.Class = v.particleClass
    member v.Type = v.particleType
    member stuff.GetDescription() = 
        System.String.Format(
            "This {0} is a spin {1} {2}.", 
            stuff.particleType.ToString(), 
            stuff.spin.ToString(), 
            stuff.particleClass.ToString())

Using the record type in F#

let electron = { 
    spin = Spin.Down; 
    particleClass = Class.Lepton; 
    particleType = Type.Electron }

In Reflector:

public static class Fermion
{
    public sealed class Fermion : 
        IStructuralEquatable, 
        IComparable, 
        IStructuralComparable
    {
        internal Particles.Class particleClass@;
        internal Particles.Type particleType@;
        internal Particles.Spin spin@;

        public Fermion(
            Particles.Spin spin, 
            Particles.Class particleClass, 
            Particles.Type particleType)
        {
            this.spin@ = spin;
            this.particleClass@ = particleClass;
            this.particleType@ = particleType;
        }

        public string GetDescription()
        {
            return string.Format("This {0} is a spin {1} {2}.",
                this.particleType@.ToString(), 
                this.spin@.ToString(), 
                this.particleClass@.ToString());
        }

        public Particles.Class Class { get { return this.particleClass@; } }
        public Particles.Class particleClass { get { return this.particleClass@; } }
        public Particles.Type particleType { get { return this.particleType@; } }
        public Particles.Spin spin { get { return this.spin@; } }
        public Particles.Spin Spin { get { return this.spin@; } }
        public Particles.Type Type { get { return this.particleType@; } }

        public int CompareTo(Particles.Fermion obj);
        public sealed override int CompareTo(object obj);
        public sealed override int CompareTo(object obj, IComparer comp);
        public bool Equals(Particles.Fermion obj);
        public sealed override bool Equals(object obj);
        public sealed override bool Equals(object obj, IEqualityComparer comp);
        public override int GetHashCode();
        public sealed override int GetHashCode(IEqualityComparer comp);
    }
}

Some things to note:

  • This is a “record type” so a constructor is generated to set all the private fields. No initialization is performed other than this. So record types are essentially a DTO.
  • It is sealed.
  • When creating an instance of this type it it not necessary to explicitly specify it because of F# type inference.
  • The IComparable, IStructuralComparable and IStructuralEquatable interfaces are all automatically implemented by the F# compiler.
  • A namespace was not explicitly defined in the example so the type has no namespace and the type is nested in a static class with the name of the file it was declared in. If a namespace had been defined then this would not have been nested in a static class and would have simply resided under said namespace.
  • The identifiers (“v”, “yada”, “stuff”) which are equivalent to the “this” keyword in C# are all converted to "this" in the output. And as an aside they do not need to be the same throughout the type, just in the method or property declaration.
  • Fields are publicly exposed via a property that is named as you named the field in the F# source. The fields are suffixed with an “@”.
  • As an aside, enumerations must explicitly have a value defined or they will be compiled as discriminated unions.

Now lets mix things up a bit…

Constructed type, Fermion.fs:

namespace Particles

    type Spin = 
        | Up = 0
        | Down = 1

    type Class = 
        | Quark = 0
        | Lepton = 1

    type Type = 
        ...
        | Electron = 6
        ...
    type Fermion(spin: Spin, particleClass: Class, particleType: Type) = 
        let _description = System.String.Format(
                                "This {0} is a spin {1} {2}.", 
                                particleType.ToString(), 
                                spin.ToString(), 
                                particleClass.ToString())
        member yada.Spin = spin
        member v.Class = particleClass
        member v.Type = particleType
        member stuff.GetDescription() = _description

Using the constructed type in F#:

let electron = new Fermion(Spin.Down, Class.Lepton, Type.Electron)

In Reflector:

public class Fermion
{
    internal string _description;
    internal Class particleClass;
    internal Type particleType;
    internal Spin spin;

    public Fermion(Spin spin, Class particleClass, Type particleType)
    {
        this.spin = spin;
        this.particleClass = particleClass;
        this.particleType = particleType;
        this._description = string.Format("This {0} is a spin {1} {2}.", 
                    this.particleType.ToString(), 
                    this.spin.ToString(), 
                    this.particleClass.ToString());
    }

    public string GetDescription() { return this._description; }

    public Class Class {  get { return this.particleClass; } }
    public Spin Spin { get { return this.spin; } }
    public Type Type { get { return this.particleType; } }
}

Some things to note:

  • This is a “constructed type” so there is a constructor. You’re constructor code is simply put in the body of the type and not in a special function like C#.
  • Requires you to explicitly new up the type and pass the parameters in.
  • No interfaces get automatically implemented as in the case of the record type.
  • This class is not sealed.
  • This type was defined under a namespace so it is not wrapped in a static class.
C# | F#
Tuesday, February 02, 2010 6:16:27 PM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  |  Trackback
Friday, January 29, 2010

The following is an implementation of a safe handle for a device info set:

type DeviceInfoSetSafeHandle() = 
    inherit SafeHandleMinusOneIsInvalid(true)
    [<DllImport("setupapi.dll")>]
    static extern bool SetupDiDestroyDeviceInfoList(IntPtr deviceInfoSet)
    override s.ReleaseHandle() = SetupDiDestroyDeviceInfoList(base.DangerousGetHandle())

It’s extremely trivial to set this up that it’s almost not worth blogging about but maybe someone can benefit from the example...

.NET | F#
Friday, January 29, 2010 4:40:39 AM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  |  Trackback

Functional programming never ceases to amaze me. The more I code in F# the more I’ve come to appreciate how succinct and terse you can write your code. I’ll sometimes start out with an imperative solution but there always seems to be a functional one that is fewer lines of code and much clearer. I’m working on rewriting a project in F#, that allows you to interact with USB HID devices, in order to learn F#. One of the things I ran into is creating an enumerable and disposable type that wraps a couple of API calls.

type DeviceInfoSet(connectedOnly:bool) = 
    let handle = GetDeviceInfoSet connectedOnly
    member private c.ToSeq = 
        Seq.unfold (fun index -> 
                            let info, more = GetDeviceInfo handle index
                            match more with
                            | true -> Some (info, index + 1)
                            | _ -> None
                    ) 0
    interface IEnumerable with
        member c.GetEnumerator () = c.ToSeq.GetEnumerator() :> IEnumerator
    interface IEnumerable<SP_DEVINFO_DATA> with
        member c.GetEnumerator () = c.ToSeq.GetEnumerator()
    interface IDisposable with
        member c.Dispose () = handle.Dispose()

Here we have a constructed class type that takes in a parameter required by the native call. Unlike a C# type definition, the construction doesn't occur in a constructor function but in the body of the type. The ToSeq property generates the sequence. I absolutely love the unfold function, it is so powerful. Here the native method requires an integer to be incremented until an error code is returned to indicate that there are no more records (Not shown). As long as there are more records we return the item and increment the index. Once there are no more we return None. Now we get to the interface implementation. This is pretty straight forward, the only thing you have to do with the non generic IEnumerable implementation is downcast it to IEnumerator with the :> operator.

Here is an example of the usage:

let enumerate = 
    use devices = new DeviceInfoSet(false)
    devices |> Seq.iter (fun item -> Console.WriteLine(item.ClassGuid.ToString()))
The “use” keyword is equivalent to a using statement in C#. Once the “devices” value goes out of scope it is disposed of. 
.NET | F#
Friday, January 29, 2010 4:28:40 AM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  |  Trackback
Monday, December 28, 2009

If your developing F# applications and using SVN then you’ll be happy to know that the latest version of VisualSVN supports F# in VS2010.

image

One bummer is that it looks like they aren’t considering a Git offering (At least in the “short term” anyways). I inquired about this and here was the answer Olga Dolidze from VisualSVN support gave:

“I regret to say but we do not have short-terms plans for developing a
GIT-version of our products...”

Although I’m not tied to having VCS functionality in the IDE, it is convenient at times.

Monday, December 28, 2009 2:25:03 AM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  |  Trackback
Saturday, December 12, 2009

Here are the slides and code from the lightning talk on Map/Reduce with Linq and F#:

MapReduceLinqFSharpDemo.zip (310.77 KB)
F# | Linq | Presentation
Saturday, December 12, 2009 4:39:27 PM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  |  Trackback
Wednesday, November 25, 2009

Since the MatchCollection doesn’t implement the generic IEnumerable<> so you cant use it OOB with the Seq functions. You can use the Seq.cast to convert it to a generic IEnumerable<> as follows:

open System
open System.IO
open System.Text.RegularExpressions

let matches = Regex.Matches(File.ReadAllText("Page.html"), "(href\\s*=\\s*(['\"])(?<url>.*?)\\2)")

matches |> Seq.cast |> Seq.iter (fun (regMatch:Match) -> Console.WriteLine(regMatch.Value))

Console.WriteLine()
Console.ReadKey() |> ignore
Wednesday, November 25, 2009 4:58:44 PM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  |  Trackback
Tuesday, October 20, 2009

F# October CTP for VS2008 announcement & download.

VS2010 Beta2 announcement (Download is available for MSDN subscribers).

Tuesday, October 20, 2009 2:27:32 AM (GMT Daylight Time, UTC+01:00)  #   |  Comments [1]  |  Trackback
Sunday, October 11, 2009

I’m working on an application where I’m sending output to a console window. If the output is an integer or double I wanted the print function to perform special formatting. For everything else just call .ToString(). Page 115 in Expert F# shows an example of how to do this sort of thing with pattern matching, here is an example (Stripped down for clarity):

let Print (t:obj) =
    let text =
        match t with
        | :? int -> (t :?> int).ToString("#,###")
        | :? double -> (t :?> double).ToString("#,###.0")
        | _ -> t.ToString()
    ...
    Console.Write(text)

Update: Like Don mentioned in the comments there is a much more succinct way to write this using “:? int as i”. Thanks Don!

let Print (t:obj) =
    let text =
        match t with
        | :? int as t -> t.ToString("#,###")
        | :? double as t -> t.ToString("#,###.0")
        | _ -> t.ToString()
    ...
    Console.Write(text)

A few points:

  1. The compiler complained that I didn’t have a type annotation on the parameter. Not sure why this is but book shows that annotating it as an obj does the trick.
  2. The :? <type> construct looks at the type of the value.
  3. The :?> operator casts the value down to a particular type.
.NET | F#
Sunday, October 11, 2009 6:39:53 PM (GMT Daylight Time, UTC+01:00)  #   |  Comments [2]  |  Trackback
Wednesday, October 07, 2009

I didn't really understand this until today when I asked the following on hubFS:

“I'm wondering if the F# compiler has an optimization that will make it so that the sqrt5 and Phi functions only execute once, no matter how many times the fibn function is called, since the results of those functions are always constant.

let sqrt5 = sqrt 5.0
let Phi = (1.0 + sqrt5) / 2.0
let fibn n = Phi ** float n / sqrt5 |> round |> int
let fib2 = Seq.unfold (fun index -> Some (fibn index,index + 1)) 1

I'm trying to figure out if the compiler automagically makes this happen or if I have to make it happen.”

Keith kindly broke it down (Thanks Keith!):

“In the code that you've written, sqrt5 and Phi are not functions but values (they don't take any arguments).  As such, their definitions will never be re-evaluated… For top level definitions, something is a value if it doesn't take parameters.  For instance, given the two definitions:

let now = System.DateTime.Now
let add x y = x + y


"now" is a value, and will never change.  add is a function taking two arguments, and each time both arguments are supplied, the definition on the right will be evaluated to give the return value.

However, when defining .NET classes, things become more complicated, because classes can contain fields, methods, events, properties, etc.  Properties are re-evaluated whenever they are gotten, and DateTime.Now is a property, which is why the value appears to change over time.

Things can also be a bit confusing when using functions in a first-class way.  For instance:

let myFun =
  let time = System.DateTime.Now
  fun () -> System.DateTime.Now - time


Here, myFun is a value (which happens to be a function!), and its definition is only evaluated once (so, in particular, "time" is only ever set once, when myFun is first defined).  However, calling the myFun function then results in the evaluation of the function's body (that is, the right hand side of the last line of myFun's definition, which calls System.DateTime.Now and subtracts the original time).”

F#
Wednesday, October 07, 2009 11:50:43 PM (GMT Daylight Time, UTC+01:00)  #   |  Comments [0]  |  Trackback
Sunday, October 04, 2009

Project Euler rocks! I think it’s an especially good way to learn another programming language. I’m planning to try to solve the problems in 2 ways. First, if possible, the brute force method (Which I think helps you to learn the language better) and second, if possible, the formula method (Which I think helps you learn the mathematical concepts better).

Problem #2 states:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

Find the sum of all the even-valued terms in the sequence which do not exceed four million.

Solution 1

So the first approach is using the brute force method where we iterate through all the numbers and determine the next Fibonacci number by adding the last two. I used the Seq.unfold method to do this (Which I discuss further here). Short and sweet:

let max = 4000000
    
let fib = Seq.unfold (fun (last, current) -> Some (last, (current, current + last))) (1, 1)
     
let Run1 _ = 
    fib 
    |> Seq.takeWhile (fun i -> i <= max)
    |> Seq.filter (fun i -> i % 2 = 0)
    |> Seq.fold(fun state item -> state + item) 0
    |> Display.PrintInteger

Solution 2

The second approach actually calculates each Fibonacci number using the Binet formula. Now this is still pretty much brute force in that we still have to iterate from 0 to the max and include only the positive values, but at least we’re using a formula that doesn't require knowledge of the previous values in the sequence. Ron Knott has a nice page on calculating Fibonacci numbers and a “reduced” Binet for calculating positive integers.  The reduced Binet formula is round(φn / √5). The rounding is required because of the irrational numbers in the equation. Theoretically the result would be an integer but because of limits on the number of digits we can calculate, the result will be slightly off and the rounding fixes this. I discuss calculating φ (Or the Golden Ratio) in my last post. Check that out to get a better understanding of how we calculate it.

let max = 4000000

let sqrt5 = sqrt 5.0
let Phi = (1.0 + sqrt5) / 2.0
let fibn n = Phi ** float n / sqrt5 |> round |> int
let fib2 = Seq.unfold (fun index -> Some (fibn index,index + 1)) 1

let Run2 _ = 
    fib2 
    |> Seq.takeWhile (fun i -> i <= max)
    |> Seq.filter (fun i -> i % 2 = 0)
    |> Seq.fold(fun state item -> state + item) 0
    |> Display.PrintInteger

Results

EDIT: After the fact I realized that my original results were skewed by the JIT compiler. Anyways, made some modifications to take this out of the equation and got more accurate results. As you can see in this case that the heavier calculations in solution 2 don’t buy us any performance since we have to iterate through and find the positive numbers starting from 0 anyways. So solution 1 was the best solution in this case. However if we needed to target a specific range of Fibonacci numbers (Especially a high range) the second solution would most definitely win out. 

image

Sunday, October 04, 2009 2:31:26 AM (GMT Daylight Time, UTC+01:00)  #   |  Comments [0]  |  Trackback
Monday, September 07, 2009

I just learned that there is an equivalent in F# to the using statement in C# and VB.NET. There are actually two approaches; one a using function that is passed a function or lambda and the second is a binding similar to the let statement except that it also acts as a using statement when the value goes out of scope. The docs do a good job explaining it. Here is a little demo of the two approaches:

#light

open System
open System.IO

let readFile path = 
    use r = new StreamReader(new FileStream(path, FileMode.Open))
    Console.WriteLine(r.ReadToEnd())

let readFile2 path = 
    using (new StreamReader(new FileStream(path, FileMode.Open)))  
        (fun r -> Console.WriteLine(r.ReadToEnd()))

readFile @"D:\temp\test.txt"
readFile2 @"D:\temp\test.txt"

Console.ReadKey() |> ignore
F#
Monday, September 07, 2009 2:31:25 AM (GMT Daylight Time, UTC+01:00)  #   |  Comments [0]  |  Trackback

VB.NET and C# have a convenient way to embed an executable icon in the Application properties. As of v1.9.6.16 F# does not. Nevertheless its fairly simple to add one, albeit with a few additional steps.

1) First you’ll need to install the .NET 2.0 Framework SDK.

2) Create a resource script as follows (Including the number one, that’s not a line number… Also replace your icon name) and save it as AppIcon.rc (Or whatever):

1 ICON MyAppIcon.ico

3) Next compile the script with the resource compiler utility as follows (Make sure the icon file is in the same folder as the resource script. Also remove the “ (x86)” from the resource compiler path if your working in a 32 bit OS):

“C:\Program Files (x86)\Microsoft.NET\SDK\v2.0\Bin\rc" AppIcon.rc

This will create a win32 resource file called AppIcon.RES in the same folder. Once this is done you wont have to do this again unless you want to change the icon (So you can delete the .rc file if you want at this point or hang onto it in case you want to change the icon in the future).

4) Now we need to tell the F# compiler to include the resource file in the resulting assembly. You’ll notice that there is a textbox under the Application properties tab for a resource file, but this is for a .NET resource file not a win32 one. So we’ll have to specify our win32 resource file with a compiler flag under the Build properties tab, in the “Other flags” textbox using the “—win32res” compiler flag:

image

Now when we compile, the resource will be included in the resulting file and the assembly icon will show up in Windows Explorer.

image

On a side note. you’ll probably want to include different sizes of icons for the different views in Windows Explorer (Detail, small, etc). Most icon or image libraries ship with multiple sizes of all their images. Instead of using a single icon file (Which will only give you one icon size in Windows Explorer and look distorted in other views) you can create a multi-icon file with different sizes of the same icon. Windows explorer will automatically pick the appropriate size for the current view (Which looks a lot better!). One free tool you can use to create mutli-icon files is @icon sushi. To do this open icon sushi and drag all the different sizes of images (They can be almost any image format not just icons) onto the window. Then select them all and right-click “Save|Save as Multiple Icon...” click “File|Save as Multiple Icon...”. Using this type of file as your icon resource will result in what is seen in the image above where there are multiple icon resources of different sizes for Explorer to choose from.

image

F#
Monday, September 07, 2009 1:58:13 AM (GMT Daylight Time, UTC+01:00)  #   |  Comments [0]  |  Trackback
Friday, August 14, 2009

I'll say up front that there is a lot of good information out there about this from folks who actually know what their doing... :) I'm mainly blogging about this to help me understand and remember it. One of the best resources I found is Matthew Podwysocki's blog. He blogs regularly about FP and has some nice posts on folds here and here.

Folding

So a fold basically takes a sequence and turns it (Or "folds" it) into a single result. So for example if you have an array of integers you want to add together. Folds come in 2 flavors, right and left. Right folds iterate from the last element the the first whereas left folds iterate from the first element to the last. A right fold is not available out of the box for an F# sequence (Which is an IEnumerable) or Enumerable/Queryable since the last element of an enumeration is unknown and the enumeration could possibly be infinite (Although there are ways to make a right fold out of a left fold as seen here). In the case of summation it doesn't really matter which direction we fold since addition is commutative. Folding can be done with the following:

F#

Microsoft.FSharp.Collections.List

val fold : ('State -> 'T -> 'State) -> 'State -> 'T list -> 'State
val foldBack : ('T -> 'State -> 'State) -> 'T list -> 'State -> 'State

Microsoft.FSharp.Collections.Seq

val fold : ('State -> 'T -> 'State) -> 'State -> seq<'T> -> 'State

Linq:

public static TResult Aggregate<TSource, TAccumulate, TResult>(
    this IEnumerable<TSource> source,
    TAccumulate seed,
    Func<TAccumulate, TSource, TAccumulate> func
) 

public static TResult Aggregate<TSource, TAccumulate, TResult>(
    this IQueryable<TSource> source,
    TAccumulate seed,
    Expression<Func<TAccumulate, TSource, TAccumulate>> func
)

Folds take an accumulator function that operates on each element and a seed value. The function that operates on each element is passed the element and current state and returns the new state. So addition using a left fold would be as follows:

F#

let values = [1; 5; 22; 45] 
// List.fold [function [state] [item]] [seed] [list]
let total = List.fold (fun state item -> state + item) 0 values

Linq/C#

int[] values = { 1, 5, 22, 45 };
// [IEnumerable/IQueryable].Aggregate([seed], [function [state], [item]])
int total = values.Aggregate(0, (state, item) => state + item);

The F# foldBack function, a right fold, is similar to the fold function except that it starts with the last element and works toward the first.

Folds Using the First or Last Element as a Seed

There are also times where you might want to use the first or last element as the seed. For example if you wanted to create a comma separated list of elements in an array you might use the String.Join() method in .NET. This creates a string that contains the elements separated by a specified value. In this case first element is simply a seed and the other elements are concatenated with the specified value (Like a comma). We can do this with the following:

F#:

Microsoft.FSharp.Collections.List

val reduce : ('T -> 'T -> 'T) -> 'T list -> 'T
val reduceBack : ('T -> 'T -> 'T) -> 'T list -> 'T

Microsoft.FSharp.Collections.Seq

val reduce : ('T -> 'T -> 'T) -> seq<'T> -> 'T

Linq:

public static TSource Aggregate<TSource>(
    this IEnumerable<TSource> source,
    Func<TSource, TSource, TSource> func
)

public static TSource Aggregate<TSource>(
    this IQueryable<TSource> source,
    Expression<Func<TSource, TSource, TSource>> func
)

When using F# the reduce function, the first element is the seed, on the other hand when using the F# reduceBack function the last element is the seed. Note that the Linq version is simply an overload of Aggregate method that does not take a seed. Lets say we have a list of strings we want to join together into a comma separated list:

F#:

let values = ["Alpha";"Beta";"Gamma";"Delta"] 
// List.reduce [function [state] [item]] [list]
let value = values |> List.reduce (fun state item -> state + ", " + item) 

Linq/C#:

string[] values = { "Alpha", "Beta", "Gamma", "Delta" };
// [IEnumerable/IQueryable].Aggregate([function [state], [item]])
string value = values.Aggregate((state, item) => state + ", " + item);

This produces the string Alpha, Beta, Gamma, Delta

The calls to the accumulator looks like this:

1) (fun "Alpha" "Beta" -> "Alpha" + ", " + "Beta")
2) (fun "Alpha, Beta" "Gamma" -> "Alpha, Beta" + ", " + "Gamma")
3) (fun "Alpha, Beta, Gamma" "Delta" -> "Alpha, Beta, Gamma" + ", " + "Delta")

Map/Reduce

Now what if you have a list of one type but want to reduce it to another. For example, what if we have a list of integers we want to reduce to a comma separated string. In that case we can us a map/reduce approach (See a recent discussion about this here on hubFS, mad props to Kha). First we map every element in the array to a string then reduce results:

F#

let primes = [2;3;5;7]  
// Seq.map [function [item]] [list]
// Seq.reduce [function [state] [item]] [list]
let output = 
    primes 
    |> Seq.map (fun i -> i.ToString()) 
    |> Seq.reduce (fun state item -> state + ", " + item)

Linq/C#:

int[] primes = { 2, 3, 5, 7 };
// [IEnumerable/IQueryable].Select([function [item]])
// [IEnumerable/IQueryable].Aggregate([function [state], [item]])
string value = primes.Select(i => i.ToString()).Aggregate((state, item) => state + ", " + item);

This first converts the integer sequence to a list of strings. We could also format the strings as desired, for example if we were converting a list of datetimes or real numbers. Then that converted list can be reduced. Note that the reduce/Aggregate function requires that the state value be of the same type as the elements thus the need for the map/Select to convert them first.

One thing to note about folds is that many other functions in F# and Linq are based on folds. For example the F# sum and Linq Sum functions are really just folds, as are others.

Unfolding

Now you may interested in doing the opposite of a fold; taking a single value and turning it into a list, or "unfolding" it. Linq doesn't offer an unfold function out of the box as of .NET 3.5 but Matthew Podwysocki discusses and implementation in C# here. F# offers an unfold method in the Seq module:

Microsoft.FSharp.Collections.Seq

val unfold : ('State -> ('T * 'State) option) -> 'State -> seq<'T>

As a very simple example lets generate the even numbers between zero and ten:

// Seq.unfold [function [currentState]] [initialState]
let values = Seq.unfold (fun state -> Some (state, 2 + state)) 0
let output = 
    values 
    |> Seq.takeWhile(fun i -> i <= 10) 
    |> Seq.map (fun i -> i.ToString()) 
    |> Seq.reduce (fun state item -> state + ", " + item)

This produces 0, 2, 4, 6, 8, 10.

So lets take a look at the unfold function. The first parameter is an generator function that accepts the current state. For the first iteration, the value passed in is the initial state parameter, which is the second parameter passed to the unfold function (To get things started) which is zero in the example above. The generator function must return an option type of a two element tuple. The first element of the tuple is the item to be yielded and the second element is the state to pass on the generator function in the next iteration (Which in the example above is the current state plus two). You return Some when there are results or None when there are no more results. In cases where the sequence is infinite you would never pass None (As is the case in the example above).

As more complex example (And one that shows the true power of unfold) we can generate the Fibonacci sequence (As Erik describes here). Lets say we want elements of the Fibonacci sequence that are less than 50.

let fib = Seq.unfold (fun (lastValue, currentValue) -> Some (lastValue, (currentValue, lastValue + currentValue))) (1, 1)
let output = 
    fib 
    |> Seq.takeWhile(fun i -> i <= 50) 
    |> Seq.map (fun i -> i.ToString()) 
    |> Seq.reduce (fun state item -> state + ", " + item)

This produces 1, 1, 2, 3, 5, 8, 13, 21, 34

You'll notice in this case that the state is now a two element tuple, the first element being the last value and the second element being the current value.

Folding/unfolding are very powerful concepts. I've found that learning these functional concepts has really helped my imperative programming as these concepts enable you to create very succinct yet expressive code. Chuck Jazdzewski expressed it well on his blog where he quoted the professor teaching his APL course; "If you are using a loop, you're doing it wrong"... Well said.

F#
Friday, August 14, 2009 9:58:21 PM (GMT Daylight Time, UTC+01:00)  #   |  Comments [0]  |  Trackback
Monday, June 08, 2009

I'm now to the point where I have more than one source file in an F# project (Woo hoo!) and the issue of entry point came up. Here is what the language spec says about it (As of 1.9.6):

"12.1.4 Explicit “Main” Entry Point

The last file specified in the compilation order for a .EXE may additionally contain an explicit entry point, indicated by annotating a function in a module with EntryPointAttribute.

     - The attribute can be applied only to a let-bound function in a module. It may not be a member.

     - Only one function may be given this attribute, and this must be the last declaration in the last file processed on the command line. The function may be in a nested module.

     - The function is asserted to have type “string[] -> int” prior to being checked. If this assertion fails an error is reported.

     - At runtime the arguments passed on startup are an array containing the same as entries as System.Environment.GetCommandLineArgs(), minus the first entry in that array.

The function becomes the entry point to the program. It immediately forces the static initializer for the file in which the function exists. It will then run the body of the function."

.NET 3.5 | F#
Monday, June 08, 2009 2:12:30 PM (GMT Daylight Time, UTC+01:00)  #   |  Comments [1]  |  Trackback
Wednesday, April 22, 2009

Hamlet D'Arcy has posted a nice F# cheat sheet here.

F#
Wednesday, April 22, 2009 2:39:31 PM (GMT Daylight Time, UTC+01:00)  #   |  Comments [0]  |  Trackback
Wednesday, April 08, 2009

Matthew Podwysocki's blog has been a great help to me in my quest to learn F# and FP concepts. He has a series of beginner posts (F# 101) that are very helpful:

Part 1 - Basic functional programming
Part 2 - Currying and Tuples
Part 3 - Scope, Recursion and Anonymous Functions
Part 4 - History of F#, Operators and Lists
Part 5 - Pattern Matching
Part 6 - Lazy Evaluation
Part 7 - Creating Types
Part 8 - Mutables and Reference Cells
Part 9 - Control Flow

I took the liberty of converting the posts into a PDF if you just want to print them all out and kill a few trees:

Adventures in FSharp - Podwysocki.pdf (364.22 KB)
.NET | F#
Wednesday, April 08, 2009 2:56:53 PM (GMT Daylight Time, UTC+01:00)  #   |  Comments [0]  |  Trackback
Tuesday, February 05, 2008

There are much better explanations by people who really know about functional programming so the next few posts on F# are more an exercise for my brain than anything else. But maybe you will find them useful...

So I haven't heard of the tuple since watching boring educational videos on database theory 10 years ago. But alas the tuple appears again as I'm learning F# and also digging into some mathematical concepts again. It's actually been there all along as I declared a singleton or joined database tables. A tuple is basically a finite sequence of objects that are in a particular order and can contain the same object more than once. It is also immutable (Aka, cant be modified). An example of a tuple could be a first name, last name and age. In C# we may define it as a generic triple (a tuple with three items) class as follows:

public class Triple<A,B,C>
{
    private A value1;
    private B value2;
    private C value3;

    public Person(
        A value1,
        B value2,
        C value3)
    {
        this.value1 = value1;
        this.value2 = value2;
        this.value3 = value3;
    }

    public A Value1 { get { return this.value1; } }
    public B Value2 { get { return this.value2; } }
    public C Value3 { get { return this.value3; } }
}

Then define our person as this triple:

Triple<string, string, int> person = 
    new Triple<string, string, int>("Richard", "Nixon", 61);

We could then set other values to the contents of the triple if we wanted:

string firstName = person.ValueA;
string lastName = person.ValueB;
int age = person.ValueC;

Easy enough right? Well lets see how we could do the same thing in F#. First off we don't have to create or instantiate a tuple class (This is actually done under the covers as we will see in a moment). We simply set the variable equal to a comma separated list of objects as follows:

let person = "Richard", "Nixon", 61

And voila! We have a tuple (A triple to be precise)... Now to set the contents of the tuple to other variables we simply do the following:

let firstName, lastName, age = person

Here we just set the individual firstName, lastName and age variables to the corresponding values in the tuple. On the other hand if we just want the first name we can block out the last name and age with the underscore placeholder ("_") and just get the first name:

let firstName, _, _ = person

or we can just get the last name and the age by blocking out the first name. You get the point...

let _, lastName, age = person

F# uses "pattern matching" to match up the variables listed, with the values in the tuple. Now as mentioned before, under the covers F# does actually use generic tuple types as seen when working with a tuple from F#...

in C#...

image

In reflector we can see that there are tuple definitions for up to 7 items:

image

Edgar Sanchez has a nice blog entry on tuples here.

F#
Tuesday, February 05, 2008 2:46:15 AM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  |  Trackback
Monday, January 28, 2008

Mike Jones has posted an analysis of an adaptation of the Concurrent Life app (That ships with the F# distro) here. I haven't gotten through the entire article yet but so far it is great. The sample app has a C# interface and consumes an F# library. He suggests that C#'ers not familiar with functional programming use F# imperatively to get comfortable with the language syntax then tackle the functional style.

Also, I came across these articles by Thomas Petricek that are proving very helpfull:

  • F# Overview (I.) - Introduction
  • F# Overview (II.) - Functional Programming
  • F# Overview (III.) - Object Oriented and Imperative Programming
  • F# Overview (IV.) - Language Oriented Programming
  • And also a nice intro by The Flying Frog Consultancy...

    C# | F#
    Monday, January 28, 2008 4:38:04 PM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  |  Trackback
    Friday, November 09, 2007

    I have been wanting to dig into F# for quite some time and finally got an opportunity. My first stab at it implements the calculation of kinetic energy given a weight in lbs, speed in mph and output in kJ. Pretty basic, but ya gotta start some where right? :)

    KineticEnergy.zip (.95 KB)

    // Get info from the user
    do Printf.printf "Enter the weight (LBS): "
    let m = read_line()
    do Printf.printf "Enter the velocity (MPH): "
    let mph = read_line()

    // Pound to kilogram conversion
    let kg lbs = lbs / 2.2

    // Miles/h to Meters/s conversion
    let mps mph = (((mph * 1.6) * 1000.0) / 60.0) /60.0

    // Kinetic energy calculation
    let Ek m v = (0.5 * m * (v * v)) / 1000.0

    // Show me the money
    do Printf.printf "\nEk = %fkJ\n\n" (Ek (kg (float_of_string m)) (mps (float_of_string mph)))

    // Wait! Let me see the answer...
    do Printf.printf "Press enter to continue..."
    let x = read_line()

    Friday, November 09, 2007 9:52:37 PM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  |  Trackback
    Creative Commons License