Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FSharp order of function parameters

Since functions in FSharp with multiple parameters get curried inherently into functions with only one parameter, should the signature of Seq.filter have to be

Seq.filter predicate source

? How different will it be from

Seq.filter source predicate

Thanks

like image 682
Prasanna K Rao Avatar asked Nov 30 '22 00:11

Prasanna K Rao


2 Answers

The first order (predicate, sequence) is more appropriate for chaining sequence combinators via the |> operator. Typically, you have a single sequence to which you apply a number of operations/transformations, consider something like

xs |> Seq.map ... |> Seq.filter ... |> Seq. ...

etc. Reversing the order of the parameters to (source, predicate) would prohibit that (or at least make it much more awkward to express). That (and maybe also partial application) is why for (almost) all the default Seq combinators the last parameter is the sequence the operation is applied to.

like image 146
Frank Avatar answered Mar 05 '23 08:03

Frank


The reason it is

Seq.filter predicate source 

instead of

Seq.filter soure predicate 

is so that you can do this

source
|> Seq.filter predicate

Since you are more likely to build a new function using Seq.filter predicate

let isEven = Seq.filter (fun x -> x % 2 = 0)

you can now do

source |> isEven

There are functions in F# where the order of parameters are not done like this because of it's history of coming from OCaml. See: Different argument order for getting N-th element of Array, List or Seq

like image 30
Guy Coder Avatar answered Mar 05 '23 07:03

Guy Coder