Logo

Programming-Idioms

  • Lisp
  • Haskell

Idiom #37 Currying

Transform a function that takes multiple arguments into a function for which some of the arguments are preset.

import Data.Ix
curry range

range(a,b) = [a..b]
(curry range 1) = \ i -> [1..i]
curry range :: a -> a -> [a]
curry :: ((a, b) -> c) -> a -> b -> c
"::" means "is of type"

Haskell begins with most functions already curried and allowing partial projection, hence the uncurried range sprang to mind as a notable exception for this illustration.

Data.Ix contains range
addThem :: Num a => a -> a -> a
addThem = (+)

add5 :: Num a => a -> a
add5 = addThem 5
(defun curry (fn &rest args)
  (lambda (&rest remaining-args)
    (apply fn (append args remaining-args))))

(defun add (a b)
  (+ a b))

(funcall (curry add 2) 1) 
  
(def add5 (partial + 5))

New implementation...
< >
Adrian