Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I initialize a sequence in F# with existing items?

Tags:

sequence

f#

In C#, you can initialize a list like so:

var list = new List<int> { obj1, obj2, obj3 };

I was expecting to do something similar in F# but keep getting errors:

let list =  { obj1, obj2, obj3 }

Is this possible in F#?

like image 777
Joshua Belden Avatar asked Dec 09 '12 02:12

Joshua Belden


People also ask

What is SEQ in F#?

Seq. groupBy takes a sequence and a function that generates a key from an element. The function is executed on each element of the sequence. Seq. groupBy returns a sequence of tuples, where the first element of each tuple is the key and the second is a sequence of elements that produce that key.

What is yield in F#?

F# Sequence Workflows yield and yield! (pronounced yield bang) inserts all the items of another sequence into this sequence being built. Or, in other words, it appends a sequence. (In relation to monads, it is bind .)

What is the underlying difference between a sequence and a list in F #?

The list is created on declaration, but elements in the sequence are created as they are needed. As a result, sequences are able to represent a data structure with an arbitrary number of elements: > seq { 1I ..


1 Answers

To create an (immutable) F# list, you can write:

let list = [ obj1; obj2; obj3 ]

There is a number of other options. You can create arrays by using [| .. |] instead of [ .. ] and you can also write sequence expressions that allow you to generate data - similarly to C# iterator methods. For more information, refer to:

  • Sequences at F# WikiBook
  • Sequences (F#) at MSDN
like image 68
Tomas Petricek Avatar answered Sep 24 '22 00:09

Tomas Petricek