Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Going more idiomatic with F#

A very simple example of what I'm trying to do: I know it's possible to write:

let myFunc = anotherFunc

instead of

let myFunc = fun x -> anotherFunc x

I've got two functions fDate1, fDate2 - both of type DateTime -> bool. I need to construct a function that takes a date and verifies if any of fDate1, fDate2 returns true. For now I've invented the following expression:

let myDateFunc = fun x -> (fDate1 x) || (fDate2 x)

Is there a better way of doing these (e.g. using '>>' or high order funcions) ?

like image 592
Alojzy Leszcz Avatar asked Jan 22 '26 10:01

Alojzy Leszcz


2 Answers

I don't think there is anything non-idiomatic with your code. In my opinion, one of the strong points about F# is that you can use it to write simple and easy-to-understand code. From that perspective, nothing could be simpler than writing just:

let myDateFunc x = fDate1 x || fDate2 x

If you had more functions than just two, then it might make sense to write something like:

let dateChecks = [ fDate1; fDate2 ]
let myDateFunc x = dateChecks |> Seq.exists (fun f -> f x)

But again, this only makes sense when you actually need to use a larger number of checks or when you are adding checks often. Unnecessary abstraction is also a bad thing.

like image 126
Tomas Petricek Avatar answered Jan 24 '26 01:01

Tomas Petricek


You can define a choice combinator:

let (<|>) f g = fun x -> f x || g x

let myDateFunc = fDate1 <|> fDate2

In general, you should use explicit function arguments. The elaborated form of myDateFunc can be written as:

let myDateFunc x = fDate1 x || fDate2 x
like image 26
pad Avatar answered Jan 24 '26 02:01

pad