Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

f# multi line ternary expressions

Tags:

f#

let a = [
    1;
    2;
    3;
    if 3 > 2 then
        4;
    else
        5;
    6
]

Which fails with a "this construct is depracated ... ... Paranthesize this expression to indicate it is an individual element of the list...", which I do,

let a = [
    1;
    2;
    3;
    (if 3 > 2 then
        4
    else
        5);
    6
]

causing the compiler to tell me "unmatched '('". Obviously the compiler does not like the paranthesized multi-line conditional. Why is that? And is there any way around it?

This is a trivial case, but in the actual use I will have arbitrarily complex recursive expressions (hence needing to split it over multiple lines), and I do not want to break up the expression and do it imperitively via list-appending and what not.

EDIT: this works :

let a = [
    1;
    2;
    3;
    if 3 > 2 then yield(
        4
    )else yield(
        5);
    6
]

but is somewhat more wordy than I would prefer (5 keywords and 4 parenthesis for a simple ternary operation!). The search for something cleaner continues

like image 577
Li Haoyi Avatar asked Jan 18 '23 07:01

Li Haoyi


2 Answers

You just need to indent the else as it is to the left of the if after you add the (

let a = [
    1;
    2;
    3;
    (if 3 > 2 then
        4
     else //same column as matching if
        5);
6
]
like image 79
John Palmer Avatar answered Jan 24 '23 17:01

John Palmer


Multi-line when a semicolon is not required.

let a = [
    1
    2
    3
    (if 3 > 2 then 4 else 5)
    6
]
like image 39
BLUEPIXY Avatar answered Jan 24 '23 18:01

BLUEPIXY