mintchoco
mintchoco

Reputation: 41

Haskell Simple Function Definition

I started learning Haskell a few days ago, and I am now learning function types.

Using tuples, below code works.

add1 :: (Int,Int) -> Int
add1(x,y) = x + y

But what if I want to do the same function without using tuples?

I've tried both function definitions

add2 :: Int, Int -> Int
add2 :: Int Int -> Int

with

add2 a b = a + b

But those two function definitions do not compile. What am I doing wrong?

Upvotes: 0

Views: 72

Answers (2)

jamshidh
jamshidh

Reputation: 12070

Your type should be

add2 :: Int -> Int -> Int

Adding the parentheses will show you what this type actually means.

add2 :: Int -> (Int -> Int)

So, add2 is a function that takes an int, and returns another function (type Int -> Int). You use this as follows

add2 1 -- this returns a function, type Int -> Int

or, add the second parameter to get the final Int out

(add2 1) 2 --same as "add2 1 2", returns an Int value 1+2=3

Upvotes: 3

Sergei Iashin
Sergei Iashin

Reputation: 116

Also you can use curry (http://hackage.haskell.org/package/base-4.8.2.0/docs/Prelude.html#v:curry):

add2 :: Int -> Int -> Int
add2 = curry add1

> add1 (1,2)
3
> add2 1 2
3

Upvotes: 1

Related Questions