If I write
let x = true
[ 1
2
if x then
3
4
]
I get [1; 2; 3; 4]
Similarly, I can one-line it as
[ 1; 2; if x then 3; 4 ]
and get the same thing. However if x is false, the first will output [1; 2; 4] while the one-liner will just output [1; 2].
I haven't found a way to parenthesize this, add yield or add begin / end to get it right.
Edit: given the apparent lack of "real" solutions that don't involve swapping out types, and the surprising behavior of nonsolutions, I opened an issue on GitHub.
I note Roland's answer...
I came up with using two lines (but not quite as verbose as Roland's):
let f x = if x then [3] else []
[ yield 1; yield 2; yield! f x; yield 4]
And then this:
[ yield 1; yield 2; yield! (fun b -> if b then [3] else []) x; yield 4]
See comments...
A little time with FSI, and I get:
[ 1; 2; if x then 3 else (); 4 ];;
responds with
val it: int list = [1; 2; 4]
I think what is happening here is that without the else you essentially have
let x = false
[ 1
2
if x then
3
4
]
but putting in the explicit else closes the if expression.
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