Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to one-line this list in F#?

Tags:

f#

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.

like image 326
Adam Avatar asked Oct 29 '25 05:10

Adam


1 Answers

Updated

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]

Original & Wrong...

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.

like image 147
Richard Avatar answered Nov 01 '25 13:11

Richard