Currying is a powerful programming technique that allows you to apply parameters to a function, even if you don’t have all of the parameters quite yet! This example is written in F#.
Lets start with a simple example.
let curry f a = f a let adder = (curry (fun x -> x + 1)) printf "%A" (adder 1)
This code does several things.
First, we declare a function named curry with the following type: val curry : (‘a -> ‘b) -> ‘a -> ‘b. The function curry accepts two thigns: a function that takes one argument and an argument.
Second, we declare a variable that will hold the intermediate value of applying the function curry with the first argument, namely, a function that takes in one argument. For our example, this function is named adder and just increments whatever value (hopefully a numeric) by one.
Lastly, we apply the number 1 to the intermediate value of curry we stored in adder. The result should be 2. All we did here was use curry to save the first parameter (a function we used to add one a parameter) to a argument we didn’t feel like passing right away.
This example is trivial. There is no reason we would use currying because we could simply apply the function to the argument directly to increment a number. But what if we had more arguments to our curry function? The following example is a slightly more complicated example of currying. The example solves the problem: given a source list and a query list, output a list of booleans that indicate whether each item in the query list appears in the source list.
let curry2 f a b = f a b let rec inList l sym = match l with | [] -> false | h::t -> if h = sym then true else inList t sym let inListMany source query = List.map ((curry2 inList) source) query inListMany ["a";"b";"c";"d";"e"] ["a";"x";"e";"d"];;
As you can see, currying can solve some pretty obscure problems, and this is just a simple example!
