Saturday, October 25, 2008

F# Seq Module

Many of the features that make F# so powerful, are the modules that make up the FSLib library. One of my favorites is the Seq module which can be found in Microsoft.FSharp.Collections namespace.

This simple example demonstrates how to use the "sum" function of the Seq module. In this example, four integers are added together. The result is then squared.

Note: I have chosen to write these sample tests in C# to help emphasis the interoperability of the languages. These tests could have just as easily been written in F#. For examples of this, check out the book Expert F#.

Test:

[TestMethod]
public void CanCalculateSeqExample()
{
List<int> numbersToCalculate = new List<int>();
numbersToCalculate.Add(1);
numbersToCalculate.Add(2);
numbersToCalculate.Add(3);
numbersToCalculate.Add(4);
int result = FSharpSample.CalculateSeqExample(numbersToCalculate);

Assert.AreEqual(result, 100);
}


.fs File:

#light
let CalculateNumberSquared x = x*x

let CalculateSeqExample args =
Seq.sum args |> CalculateNumberSquared


.fsi File:

#light
val CalculateNumberSquared: int -> int

val CalculateSeqExample: seq -> int


Explanation:

While this example is very simple, it provides a brief view into the power that some of these modules provides. This example also shows how functions can be chained together. The astute observer will have noticed the "|>" operator in the
CalculateSeqExample function. This operator is known as the pipe-forward or forward operator. It allows the result of the preceding function to be forwarded on to the next function in the chain.


3 comments:

  1. Way cool... the |> operator!

    You have been tweeted!

    ReplyDelete
  2. I am the kind of hombre who passions to taste brand-new stuff. Right now I am making my own pv panels. I'm making it all by myself without the help of my men. I'm utilizing the internet as the only way to acheive this. I encountered a really amazing website that explains how to make pv panels and so on. The place explains all the steps needed for solar panel construction.

    I'm not sure bout how accurate the data given there iz. If some guys over here who had xp with these things can have a look and give your feedback in the page it will be grand and I would really treasure it, because I truly would love to try solar panel construction.

    Tnx for reading this. You guys are great.

    ReplyDelete
  3. Way cool... the |> operator!

    You have been tweeted!

    ReplyDelete