Curried Lua

lua-users home
wiki

Currying is defined by Wikipedia[1] as follows:

"In computer science, currying is the technique of transforming a function taking multiple arguments into a function that takes a single argument (the first of the arguments to the original function) and returns a new function that takes the remainder of the arguments and returns the result"

You can implement curried functions in all languages that support functions as first-class objects. For example, there's a little [tutorial about curried JavaScript].

Here is a small Lua example:

function sum(number) 
  return function(anothernumber) 
    return number + anothernumber
  end
end

local f = sum(5)
print(f(3)) --> 8

-- WalterCruz

Here is another [GavinWraith]:

do
  local f
  local sum = 0
  f = function (n)
        if type(n) == "number" then
          sum = sum + n
          return f
        else
          return sum
        end -- if
      end -- function
  addup = f
end -- do

x = addup (1) (2) (3) ()
print(x) --> 6

The "()" style is interesting because it allows any type to be curried. (Remember: the parenthesis can be omitted for strings and tables.) However, doesn't the following make more sense?

function addup(x)
  local sum = 0
  local function f(n)
    if type(n) == "number" then
      sum = sum + n
      return f
    else
      return sum
    end
  end
  return f(x)
end

print(addup (1) (2) (3) ())  --> 6
print(addup (4) (5) (6) ())  --> 15

For truly powerful curry we need to realize that functions can be operated upon. A function that takes two arguments can be curried automatically by the machine. The following curry function is an example of a HigherOrderFunction?:

function curry(f)
    return function (x) return function (y) return f(x,y) end end
end

powcurry = curry(math.pow)
powcurry (2) (4) --> 16
pow2 = powcurry(2)
pow2(3) --> 8
pow2(4) --> 16
pow2(8) --> 256

The above code is Lua 5.1 compatible.

See Also


FindPage · RecentChanges · preferences
edit · history
Last edited January 20, 2007 3:39 am GMT (diff)