Samuel
Samuel

Reputation: 1374

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)

Upvotes: 5

Views: 607

Answers (4)

J D
J D

Reputation: 48687

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)

Upvotes: 2

Keith
Keith

Reputation: 2861

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

Upvotes: 1

Huusom
Huusom

Reputation: 5912

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.

Upvotes: 0

Robert
Robert

Reputation: 6437

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

Upvotes: 10

Related Questions