Reputation: 497
I'm a Haskell beginner trying to understand currying. I've seen examples that are supposed to demonstrate it, but they involve binary operators, which themselves are curried, plunging my mind into infinite recursion. If operators in Haskell are functions, and all functions are unary and curried, could I define my own addition function in terms of only unary functions?
Upvotes: 2
Views: 1221
Reputation: 43
If you want to add tuples using curry use the following code:
addPair :: Num a => (a,a) -> a
addPair = \(a ,b) -> a + b
i.e. No argument is passed in the function.
Upvotes: 1
Reputation: 1441
Functions in haskell are unary only in the sense that they look unary to the
user. The Haskell language says nothing about the implementation of those functions.
It's perfectly alright for a haskell implementation to have (+)
implemented as a
binary function if it also provides some way to represent values like (+) 2
. Usually
this is done by bundling the binary function and the argument list, 2
in this case.
If you really want to implement (+) in terms of unary functions only you could do somthing like:
plus a b
| a > 0 = plus (pred a) (succ b)
| a < 0 = plus (succ a) (pred b)
| otherwise = b
But I don't think this gives you anything when it comes to understanding Haskell (or Haskell implementations) better.
Upvotes: 2
Reputation: 3766
Yes.
add :: Num a => a -> a -> a
add = \a -> \b -> a + b
This is also an example of a closure. \b -> a + b
has access to a
through a closure because a is defined outside the scope of that lambda.
Edit
These are called Peano number values
data Nat = Zero | Succ Nat
add Zero = \n -> n
add (Succ a) = \b -> Succ (add a b)
toNat 0 = Zero
toNat n = Succ (toNat (n-1))
fromNat Zero = 0
fromNat (Succ n) = 1 + fromNat n
λ: fromNat $ add (toNat 3) (toNat 4)
7
Upvotes: 4