A little extra

And just for completeness, the other classic stream example.

> // Define a function to combine two successive elements in a list
– let rec nextFib (x : bigint LazyList) =
–  LazyList.consf (LazyList.hd x + LazyList.hd (LazyList.tl x)) (fun _ -> nextFib  (LazyList.tl x));;

val nextFib : bigint LazyList -> Math.BigInt LazyList

> // Now apply to the list with first two elements 1
– let rec foo _ =
–   LazyList.cons 1I (LazyList.consf 1I (fun _ -> nextFib (foo ())));;

val foo : unit -> bigint LazyList

> // This is the Fibonacci sequence
– let fibonacci = foo();;

val fibonacci : bigint LazyList

> LazyList.to_array (LazyList.take 30 fibonacci);;
val it : bigint array
= [|1I; 1I; 2I; 3I; 5I; 8I; 13I; 21I; 34I; 55I; 89I; 144I; 233I; 377I; 610I;
    987I; 1597I; 2584I; 4181I; 6765I; 10946I; 17711I; 28657I; 46368I; 75025I;
    121393I; 196418I; 317811I; 514229I; 832040I|]
>

Advertisements
This entry was posted in Computers and Internet. Bookmark the permalink.

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