4

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

Prasanna K Rao
  • 1,086
  • 2
  • 8
  • 18

4 Answers4

10

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.

Frank
  • 2,738
  • 19
  • 30
6

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

Community
  • 1
  • 1
Guy Coder
  • 24,501
  • 8
  • 71
  • 136
5

Yes Seq.filter takes the predicate followed by the sequence to filter. If you want to provide them in the other order you could write a function to reverse the arguments:

let flip f a b = f b a

then you could write

(flip Seq.filter) [1..10] (fun i -> i > 3)

The existing order is more convenient however since it makes partial application more useful e.g.

 [1..3] |> Seq.map ((*)2) |> Seq.filter (fun i -> i > 2)
Lee
  • 142,018
  • 20
  • 234
  • 287
1

and you have also ||> for piping functions accepting two arguments signature, or partially apply 2 arguments to a wider signature. : )

jkone27
  • 73
  • 1
  • 7