How to implement currying in clojure?


#1

Hello Team,

I am new to functional programming and when look into it, there are lots of functional programming technique are there like tail recursion, HOF, Currying, Partial Functional and more. I want to know, What is currying and how to implement currying in clojure ?

While look into web, some of the writer said, currying and partial functions are same. Kindly please explore, difference between curry and partial function ?


#2

Hi @Harmeet,

FYI there’s a lesson about this: https://purelyfunctional.tv/lesson/partial/

Currying and partial function application are just about the same thing. Let’s say you have a function with three arguments a, b, and c.

(defn my-fn-3 [a b c]
 ...)

It doesn’t matter what it does. But let’s say we know the first argument already, but we don’t know the others. We could keep the argument around in a variable and then use it when we finally know b and c. But where do we put the variable? We have to have it in the right scope, etc.

There’s another thing we can do, which is to make a new function that already has the a closed inside it:

(defn my-fn-2 [b c]
  (my-fn-3 17 b c))

Notice that we have the first argument already defined, and the other two arguments are passed along. What if we want to do it again?

(defn my-fn-1 [c]
  (my-fn-2 "hello" c))

And we can do it again until there are no more arguments.

This pattern is so regular we can write a function that does this for us. In Clojure, it’s called clojure.core/partial.

Let’s write our own version:

(defn partial* [f x]
  (fn [& unknown-args]
    (apply f x unknown-args)))

Notice you pass it a function and one known argument. It returns a new function that applies the function to your known argument followed by all the arguments you don’t know yet.

This is how you would run it:

(def my-fn-2 (partial* my-fn-3 17))
(def my-fn-1 (partial* my-fn-2 "hello"))

Do take a look at the API docs and ClojureDocs examples. It’s more sophisticated than the simple one I wrote above.

Currying is basically the language doing this for you automatically. Haskell does that, for instance. It’s actually a really cool principle: you only need functions of one argument. Any function of two arguments a and b can be made with a function that takes a and returns a function that takes b. Which is the same principle that clojure.core/partial exploits.

I hope that helps!

Rock on!
Eric


#3

I recently wrote an article about currying in Clojure that might be interesting to you:

https://dragan.rocks/articles/18/Fluokitten-080-Fast-function-currying-in-Clojure