Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to add element at the beginning of F# sequence

Tags:

sequence

f#

F# List provides the cons (::) operator to add an item at the front of a list. Is there a function to do the same for the Seq? The only way I came across is using Seq.append as follows. Is there a more efficient/elegant way of doing this?

> let myLst = [1..5]
> 0::myLst;;
val it : int list = [0; 1; 2; 3; 4; 5]


> let mySeq = {1..5}
> Seq.append (seq [0]) mySeq;;
val it : seq<int> = seq [0; 1; 2; 3; ...]

Possible duplicate, but not really answering my question.

[1] uses Seq.append as above

like image 250
vis Avatar asked Mar 19 '12 16:03

vis


1 Answers

It may help to recall that F# sequence is a calculation, indeed. No matter how you are going to achieve it, in the end of the day you should have a new calculation that, if being enumerated, first yields the appended element, and then yields the old sequence. In most direct form this can be achieved using a sequence expression:

> let mySeq = {1..5}
> seq { yield 0; yield! mySeq };;
val it : seq<int> = seq [0; 1; 2; 3; ...]

Seq.append library function is just an optimized implementation of semantically the same action.

like image 181
Gene Belitski Avatar answered Sep 22 '22 08:09

Gene Belitski