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)
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)
This is minor stylistic change but I find this more readable:
let input = 5
let result =
if input > 0 && input < 5 then
(calculateA input + calculateB input) / 2
else
calculateC input
This is not really an answer because Robert is correct. But it looks like you are working with series of functions, so you could write it like this:
let Calculate input =
let calc = function | [f] -> f input | fl -> fl |> List.map ((|>) input) |> List.sum |> (fun s -> s / fl.Length)
if input > 0 && input < 5
then calc [CalculateA; CalculateB]
else calc [CalculateC]
You could decompose to something with this signature: ((int -> int) list) -> ((int -> int) list) -> (int -> bool) -> int -> int
and then build your function by applying the first 3 parameters.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.