Seq.find—Neat!


As I continue to build more F# code, I keep finding interesting usage of the language and its features. Today, I’m going to talk about Seq.find. Seq.find loops through a sequence (an IEnumerable in .NET speak) looking for some item that satisfies a function that returns a boolean. As soon as the function returns true, the iteration stops and the found item is returned. Maybe it will just be easier to show what the code looks like:

#light

 

let thelist = [|("joe", 1); ("jim", 3); ("scott", 6); ("kenn", 29)|]

let scottsNumber = thelist |> Seq.find(fun (a, b) -> a = "scott") |> (fun (a,b) -> b)

printfn "%d" scottsNumber

The code has an array of tuples. It then pipes that list into Seq.find. Because our tuple has two values, the function will also take a two value tuple. The result of the evaluation will be the first tuple that has the first value set to scott. The final function takes the second value and returns it. This final value is then assigned to scottsNumber and written to the standard output. What would this same code look like in C#? Well, if we want to stick to keeping the intent identical, then the evaluation would be:

var theList = new[]

                  {

                      new {name="joe", number=1},

                      new {name="jim", number=3},

                      new {name="scott", number=6},

                      new {name="kenn", number=29},

                  };

int foundItem = -1;

foreach (var listItem in theList)

{

    if (listItem.name == "scott")

    {

        foundItem = listItem.number;

        break;

    }

}

Console.WriteLine(foundItem);

This is as close as I can get to the same pithiness of the F# code while preserving the notion that we bail out on the first item. Given evaluation semantics of LINQ, the following is even closer:

var theList = new[]

                  {

                      new {name="joe", number=1},

                      new {name="jim", number=3},

                      new {name="scott", number=6},

                      new {name="kenn", number=29},

                  };

var scottsNumber = (from listItem in theList where listItem.name == "scott" select listItem.number).First();

Console.WriteLine(scottsNumber);

Personally, I’m finding that the F# part is easier to read, though the LINQ syntax is also becoming more apparent to me as I write more F#. I guess you have to get your head in the right mode in order to see how this stuff works.

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: