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)
Use an if/else statement if the two conditions are mutually exclusive meaning if one condition is true the other condition must be false.
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.
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.
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.
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
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)
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