Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 parameter? Would named parameters to make this easier? Are there any other functional languages that have named parameters or some other way to make currying indifferent to parameter-order?

like image 994
Dax Fohl Avatar asked Dec 15 '09 23:12

Dax Fohl


People also ask

What does it mean to curry a function?

In mathematics and computer science, currying is the technique of converting a function that takes multiple arguments into a sequence of functions that each takes a single argument.

How do you use currying function?

In other terms, currying is when a function — instead of taking all arguments at one time — takes the first one and returns a new function, which takes the second one and returns a new function, which takes the third one, etc. until all arguments are completed.

What do you mean by curried function with example?

Currying is when you break down a function that takes multiple arguments into a series of functions that each take only one argument. Here's an example in JavaScript: function add (a, b) { return a + b; } add(3, 4); // returns 7. This is a function that takes two arguments, a and b, and returns their sum.

What is currying in lambda calculus?

Currying All functions in lambda calculus are prefix and take exactly one argument. If we want to apply a function to more than one argument, we can use a technique called currying that treats a function applied to more than one argument to a sequence of applications of one-argument functions.


1 Answers

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'.

like image 130
Brian Avatar answered Sep 22 '22 08:09

Brian