So I have been playing around with more Euler problems and I have found it a great way to learn some of the basic functions of F# and Seq specifically. The more I play the more I am really loving F# and how succinct the language is.

Today I thought I would put up a brief post on the Seq.unfold function.

So, I see this function being used everywhere… my understanding of it is that it is a way that one can build a sequence based on a series of commands. I will use a small code snippet to show an example implementation of it…

let SeqTo10 startnum =
startnum
|> Seq.unfold(fun x -> if (x<10) then Some(x,x+1) else None)

Basically what this function does is takes a number “startNum”, and generates a sequence of all the numbers between startNum and 10 (provided startNum is less than 10).

So the first thing we do is pass the starting number (or initial state argument) into the sequence generator.

Then using the anonymous functions and the lambda expression generate the generator expression.

fun

x -> if (x<10) then Some(x,x+1) else None

The anonymous function can basically have any number of expressions in it, but it will only stop generating the sequence when a None value is passed to the generator.

So for instance in the code snippet above if x is less than ten, then we add the current value of x to the “new sequence” and pass a new value value to the anonymous function (x+1) in this case. This is done by the Some(x, x+1).

Once x is less than 10 we pass the value None to the anonymous function and the sequence ends.

To illustrate this in another way, we can show another example of the unfold function, this time passing more than one value to the generator.

let SeqTo2D =
(1,1)
|> Seq.unfold(fun (x,y) -> if (x<10) then Some((x,y),(x+1,y)) else None)

In this instance the (1,1) is the initial state argument. The Some((x,y), (x+1,y)) means that it will add an element to the sequence (x,y) and then pass to the generator.

Posted on Wednesday, June 23, 2010 7:28 PM
F#
| Back to top

Related Posts on Geeks With Blogs
Matching Categories

Some where I saw below code for fibonacci

let fibo = Seq.unfold(fun (a, b) -> Some(a+b, (b, a+b))) (0,1)

In it what is usage and meaning of last (0,1) ?

let fibo = Seq.unfold(fun (a, b) -> Some(a+b, (b, a+b))) (0,1)

here, initially value '0' is being assigned to 'a' and 1 to 'b'