Seq.unfold explanation in F #

I am trying to create a sequence lazily using F #.

The sequence is defined as follows:

the nth term of the sequence of the number of triangles is given by the expression tn = Β½n (n + 1); so the first decimal of the number:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

Here is what I still have, but it doesn't seem to work:

let tri_seq = 1.0 |> Seq.unfold (fun x -> match x with | _ -> Some (x, 0.5*x*(x + 1.0))) 

Thank you very much who can help me figure out how the work unfolds. Thanks

Edit: I correctly defined the first answer, but dosnt works, however, I changed it a bit and it worked.

 let tri_seq = 1.0 |> Seq.unfold (fun x -> Some (0.5 * x * (x + 1.0),x + 1.0)) 
+4
source share
4 answers

First, why do you use match if you have only one case?

 let tri_seq = 1.0 |> Seq.unfold (fun x -> Some (x, 0.5 * x * (x + 1.0))) 

Secondly, what does "not work"? Do you know that you are creating an endless list?

/ Edit: for the sake of completeness, this is the correct solution that the OP found and posted as a comment:

 let tri_seq = 1.0 |> Seq.unfold (fun x -> Some (0.5 * x * (x + 1.0), x + 1.0)) 
+8
source

Another alternative to the code that Brian wrote is to use recursion instead of the imperative while loop:

 let tri = let rec loop(n, diff) = seq { yield n yield! loop(n + diff, diff + 1.0) } loop(1.0, 2.0) printfn "%A" (tri |> Seq.take 10 |> Seq.to_list) 

It is much less efficient (so you need to be a little careful here ...), but it is a more idiomatic functional solution, so it may be easier to see what the code does.

+4
source

Here is an alternative:

 let tri = seq { let n = ref 1.0 let diff = ref 2.0 while true do yield !n n := !n + !diff diff := !diff + 1.0 } printfn "%A" (tri |> Seq.take 10 |> Seq.to_list) 
+2
source

I know this is pretty old, but I can’t understand why to use float when you are sure that x * (x + 1) is an even number and divides by 2. Therefore, I would simply use this instead (not much difference I know, but at least you have int seq):

 let tri_seq = 1 |> Seq.unfold (fun x -> Some (x * (x + 1) / 2 , x + 1)) tri_seq |> Seq.take 6 |> Seq.toList //[1; 3; 6; 10; 15; 21] 

fiddle

(If you are not dealing with huge quantities of course ....)

+1
source

All Articles