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?
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).
You could use:
Seq.singleton 42
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With