user3928256
user3928256

Reputation: 1003

What does the type of "+" mean in Haskell

Prelude> :t (+)
(+) :: (Num a) => a -> a -> a

My lecture slide says that

a -> a -> a

means a function take two parameters and return one, and all of them are the same type. Which two are the parameters and which one is the return value?

Thank you.

Upvotes: 2

Views: 141

Answers (3)

MathematicalOrchid
MathematicalOrchid

Reputation: 62848

Suppose we have a type like this:

a -> b -> c -> d -> e

The last thing in the sequence is the return type. So this function returns something of type e. Everything else is the argument types. So this function takes 4 arguments, who's types are a, b, c and d.

Lower-case letters denote "type variables" — variables which can stand for any type. (It doesn't have to be a single letter, but it often is.) Anything beginning with an upper-case letter is a specific type, not a variable. (For example, Int is a type, int is a type variable.)

The Num a part means that a stands for any type, but that type must implement the Num type-class. Other common contexts are Eq (defines the == operator), Ord (defines <, >, and so forth) and Show (defines the show function that converts stuff into a string).

Upvotes: 1

Random Dev
Random Dev

Reputation: 52290

There are some levels you have to master here:

level 0

a -> b -> c

is a function taking one a and one b and producing one c

level 1

well there is more to it:

a -> b -> c

which is really

a -> (b -> c)

is a function taking one a and producing another function, that takes a b and produces a c

level 2

f :: (Num a) => a -> a -> a

Adds a constraint to a (here Num - this means that a should be a number - a is an instance of the Num type-class)

So you get a function that takes an a and produces a function that takes another a and returns a a, and a needs to be an instance of Num

so every input to f has to be of the same type of number:

  • f 1 2 is ok
  • f 'a' 'b' is not ok
  • f (1::Int) (2::Int) is ok
  • f (1::Float) (2::Float) is ok
  • f (1::Int) (2::Float) is not ok

level 3 (understanding (+))

The last thing you have to understand here is that, (+) is defined as a part of Num so there are different + based on the used types ... and the same is true for the number literals like 0, 1, ... thats why 0 can be a Float or a Int or whatever type that is a instance of Num

Upvotes: 13

Oleg
Oleg

Reputation: 9359

The first two are parameters, the last one is the return value.

In fact, due to currying, it can be read like this: the + function (which only accepts numeric values) takes a parameter a and returns a function that takes a parameter of the same type and returns the result of the same type.

Here's a contrived example:

let addTwo = (+) 2 -- the + function takes one argument and returns a function
addTwo 3 -- we can add the second argument here and obtain 5 as returned value

Upvotes: 1

Related Questions