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

前端 未结 5 1519
予麋鹿
予麋鹿 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:57

    Just for completeness - and since you asked about other functional languages - this is how you would do it in OCaml, arguably the "mother" of F#:

    $ ocaml
    # let foo ~x ~y = x - y ;;
    val foo : x:int -> y:int -> int = 
    # foo 5 3;;
    - : int = 2
    # let bar = foo ~y:3;;
    val bar : x:int -> int = 
    # bar 5;;
    - : int = 2
    

    So in OCaml you can hardcode any named parameter you want, just by using its name (y in the example above).

    Microsoft chose not to implement this feature, as you found out... In my humble opinion, it's not about "poor interaction with other aspects of the language design"... it is more likely because of the additional effort this would require (in the language implementation) and the delay it would cause in bringing the language to the world - when in fact only few people would (a) be aware of the "stepdown" from OCaml, (b) use named function arguments anyway.

    I am in the minority, and do use them - but it is indeed something easily emulated in F# with a local function binding:

    let foo x y = x - y
    let bar x = foo x 3
    bar ...
    

提交回复
热议问题