How do you curry the 2nd (or 3rd, 4th, …) parameter in F# or any functional language?

前端 未结 5 1536
予麋鹿
予麋鹿 2021-02-19 06:58

I\'m just starting up with F# and see how you can use currying to pre-load the 1st parameter to a function. But how would one do it with the 2nd, 3rd, or whatever other paramet

5条回答
  •  佛祖请我去吃肉
    2021-02-19 07:41

    Typically you just use a lambda:

    fun x y z -> f x y 42
    

    is a function like 'f' but with the third parameter bound to 42.

    You can also use combinators (like someone mentioned Haskell's "flip" in a comment), which reorder arguments, but I sometimes find that confusing.

    Note that most curried functions are written so that the argument-most-likely-to-be-partially-applied comes first.

    F# has named parameters for methods (not let-bound function values), but the names apply to 'tupled' parameters. Named curried parameters do not make much sense; if I have a two-argument curried function 'f', I would expect that given

    let g = f
    let h x y = f x y
    

    then 'g' or 'h' would be substitutable for 'f', but 'named' parameters make this not necessarily true. That is to say, 'named parameters' can interact poorly with other aspects of the language design, and I personally don't know of a good design offhand for 'named parameters' that interacts well with 'first class curried function values'.

提交回复
热议问题