Currying functions (was "theory vs practice" ceases power)

Currying functions (was "theory vs practice" ceases power)

"Eric J. Roode" < XXXX@XXXXX.COM > writes:

I think it is mostly a matter of syntax. In Haskell and many other
functional languages function application is simply

f x

not f(x) as in C, Perl etc. If application is left-associative, then

f x y

is the same as

(f x) y

that is, f takes one argument and returns a function taking one
argument, which is then applied to y.

You have a choice of writing a tupled style:

f (a, b) = something
x = f (1, 2)

or a curried style:

f a b = something
x = f 1 2

Purely from syntax the second is a bit cleaner. It also lets you
write things like

g = f 1
newlist = map (f 2) list

to partially apply a function, instead of

g (x, y) = f (1, y)
newlist = map (\y -> f (1, y)) list

or similar workarounds. (The syntax '\x -> r' is a lambda expression

In a language that needs more punctuation to call a function, currying
isn't so attractive; you might not enjoy writing f(2)(3) instead of
f(2, 3). But note that C did use a similar idea for array access.

--
Ed Avis < XXXX@XXXXX.COM >

Currying functions (was "theory vs practice" ceases power)

Well, if we assume a function of one argument, we can generalize a lot. The
most common, obvious example (in my opinion) is the "map" function, which as
you probably know takes a list and applies a function to each element in the
list, returning a list of the results. Now, what if we wanted to use "map",
but the function we wanted to use to map the input list takes two
parameters, not one, and the first parameter is going to be given the same
value for each call?

For example, say we have a function that does a regex match and returns true
or false. It looks like this:

regex_match(pattern, input)

Where pattern is a regular expression, input is whatever string you want to
match, and the result is a boolean. Now, suppose we want a list that
contains [true, false, true, true, ...] for a given input list, depending on
whether or not each string in the input list matches a particular regular
expression.

If we can curry regex_match, we can produce a new function that already
knows the pattern, and just takes the input. Then, we can just use the
regular map function to apply the curried function to the list:

map(curry(regex_match, pattern), input)

Or, Perl-style:

fmap(curry(\®ex_match, \$pattern), @input)

Or, in a language like Haskell that does currying implicitly:

map (regex_match pattern) input

This is just a ficticious example, since Perl's built-in map can easily do
regular expression matches within its code blocks, and other languages like
Python and Java use a more OO (and efficient) way of caching the pattern
than using the method I described. I'm just trying to provide a simple
illustration.

Hope this helped a little,
(and apologies to Ed for continuing to abuse the word,)
Dave