Best way to create a sequence with 1 element

In F #, I can create a sequence of 1 element

seq [42]          // inefficient, since a list is created
seq { yield 42}   // verbose, would prefer { 42 } or seq { 42 }
seq { 42 .. 42 }  // bizarre

While I find this a bit strange, I am curious if anyone knows a short and effective way. Or: Why

{ 42 }  // invalid syntax. in other words, not a valid sequence expression

not valid?

+4
source share
2 answers

You can use:

Seq.singleton 42
+10
source

If you need a true sequence (i.e. IEnumerable, elements of which are created lazily), this seq { yield <expr> }is probably the most concise syntax.

If you do not need an element that will be evaluated only when it is consumed (the expected rating is in order), you can use the function Seq.singleton.

, IEnumerable, : [ <expr> ] [| <expr> |], , , , .

{ <expr> } , (, , generator Python) . seq { yield <stuff> } , , , , (seq , ). seq, F # , , , (, , , ).

+7

All Articles