Is there another .. idiomatic way to write things in F #?

What would be the idiomatic way of F # to write the following? Or will you leave it as it 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)
+5
source share
4 answers

For one, if ... then ... else ...I would probably leave it this way, if you had more cases, I would either use pattern matching when the guard:

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

or you can also see active templates: http://msdn.microsoft.com/en-us/library/dd233248.aspx

+10
source

What would be the idiomatic way of F # to write the following? Or will you leave it as it is?

There is nothing wrong with the way you wrote 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)
+2
source

, , :

let input = 5
let result = 
     if input > 0 && input < 5 then
         (calculateA input + calculateB input) / 2
     else
         calculateC input
+1

, . , , :

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 can decompose something with this signature: ((int -> int) list) -> ((int -> int) list) -> (int -> bool) -> int -> intand then build your function by applying the first 3 parameters.

0
source

All Articles