Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is if .. else .. an idiomatic way of writing things in F#?

What would be an F# idiomatic way of writing the following ? Or would you leave this as is ?

let input = 5
let result = 
     if input > 0 && input  < 5 then
         let a = CalculateA(input)
         let b = CalculateB(input)
         (a+b)/2
     else
         CalculateC(input)
like image 805
Samuel Avatar asked Jan 26 '12 09:01

Samuel


People also ask

When should I use else if?

Use an if/else statement if the two conditions are mutually exclusive meaning if one condition is true the other condition must be false.

Why use else if instead of multiple if?

Furthermore ELSE IF is more efficient because the computer only has to check conditions until it finds a condition that returns the value TRUE. By using multiple IF-conditions the computer has to go through each and every condition and thus multiple IF-conditions require more time.

Can we use if in else?

The if statement executes a statement if a specified condition is truthy. If the condition is falsy, another statement in the optional else clause will be executed.

Which is equivalent to multiple if else if statements?

In this case, when one IF statement is used inside another IF statement, this is called the nested IF statement. This allows to use more than one condition simultaneously.


2 Answers

For one if ... then ... else ... I'd probably leave it like that, if you had more cases I'd either use pattern match with a when guard:

let result =
    match input with
    | _ when input > 0 && input < 5  -> ...
    | _ -> ...

or you might also want to look at active patterns: http://msdn.microsoft.com/en-us/library/dd233248.aspx

like image 124
Robert Avatar answered Nov 08 '22 17:11

Robert


What would be an F# idiomatic way of writing the following ? Or would you leave this as is ?

There's nothing wrong with the way you've written it but here is another alternative (inspired by Huusom):

let input = 5
let result =
  if input>0 && input<5 then [A; B] else [C]
  |> Seq.averageBy (fun f -> f input)
like image 23
J D Avatar answered Nov 08 '22 18:11

J D