The best way to add an element at the beginning of an F # sequence

F # List provides a cons ( :: cons operator to add an item to the top of the list. Is there a function to do the same for Seq ? The only way I came across is to use Seq.append as follows. Is there a more efficient / elegant way to do 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; ...] 

A possible duplicate, but not really answering my question.

[1] uses Seq.append as above

+8
f # sequence
source share
1 answer

This can help remember that the F # sequence is a calculation. Regardless of how you are going to achieve this, at the end of the day you should have a new calculation, which, being enumerated, first gives the added element, and then returns the old sequence. In its most direct form, this can be achieved by expressing the sequence :

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

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

+8
source share

All Articles