Leandro Moreira <leandro.rhc...@gmail.com> writes:

Hi Leandro,

> I'm starting to learn about functional programming and I reach the
> concept *"Currying functions".* It is the technique of *transforming*
> a function that takes *multiple arguments* (or an n-tuple of
> arguments) in such a way that it can be called as a *chain of
> functions* each with a *single argument* (partial
> application). *(Wikipedia)*
>
> Then I try to curry the simplest sum of two numbers.
> (+ 2 4)
>
> But I couldn't do that. I tried ( + 2 ( + 4 )) but I think the outer
> plus function is receiving two parameters so how can I curry a
> function using Clojure?

As Stuart said, clojure doesn't curry functions automatically.  If you
want, you can create a curried version of, say, + with arity 3 like so:

--8<---------------cut here---------------start------------->8---
user> (defn curried-arity-3-+ [z]
        (fn [y]
          (fn [x]
            (+ x y z))))
#'user/curried-arity-3-+
user> (curried-arity-3-+ 1)
#<user$curried_arity_3__PLUS_$fn__17178 
user$curried_arity_3__PLUS_$fn__17178@735b46ef>
user> ((curried-arity-3-+ 1) 2)
#<user$curried_arity_3__PLUS_$fn__17178$fn__17179 
user$curried_arity_3__PLUS_$fn__17178$fn__17179@36298619>
user> (((curried-arity-3-+ 1) 2) 3)
6
--8<---------------cut here---------------end--------------->8---

The usual signature of a + function with arity 3 is

  arity-3-+: N x N x N -> N

which we've transformed to this sequence of arity-1 functions:

  curried-arity-3-+: N -> (N -> (N -> N))

> By the way, I also notice a strange concept (that I still didn't
> investigate) "Currying and *partial function* application are often
> conflated" but it seems related to it.

With partial function application, you can fix the first few function
parameters just as Stuart demonstrated.  For example,

  (partial arity-3-+ 1)

returns a function with signature: N x N -> N, which gets 2 numbers and
returns the sum of 1 and those two numbers.  But the returned function
is not (completely) curried, it still wants 2 parameters.  

With currying you can give any number i of parameters (i <= n) to a
function of arity n, and for i < n the result is a function that accepts
one more parameter, which in turn returns another function accepting one
more parameter, ...  The last function in that chain eventually returns
the value.

Bye,
Tassilo

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to