Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to create a sequence with 1 item

Tags:

sequence

f#

In F# I can create a sequence of 1 item by

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 someone knows a short and efficient way. Or: Why is

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

not valid?

like image 539
citykid Avatar asked Nov 30 '22 19:11

citykid


2 Answers

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

If you don't need the item to be evaluated only when it is consumed (eager evaluation is fine), then you can use the Seq.singleton function.

If you only need something that implements IEnumerable, you can achieve shorter syntax by using a list or an array constructor: [ <expr> ] or [| <expr> |], the difference being that array constructor will be probably more efficient in this case.

The { <expr> } syntax won't work because there is no such special syntax for creating a sequence (as, for example, a generator expression in Python). The seq { yield <stuff> } is a computation expression, and it has to follow several rules, one of which being that it has to say what kind of computation it defines (the seq part says that). If you wanted to omit the seq part, you'd need F# to support generic computation expressions, which I don't think is currently possible (and would probably require some capability similar to typeclasses).

like image 34
MisterMetaphor Avatar answered Dec 03 '22 09:12

MisterMetaphor


You could use:

Seq.singleton 42
like image 114
Simon Dickson Avatar answered Dec 03 '22 08:12

Simon Dickson