Haskell walkthrough – III

Types

Types

  1. Haskell is statically typed meaning everything has to have a type. This allows the compiler to catch a lot of erros (unlike Python, like Java)
  2. Haskell has type inference, meaning you dont have to specify the type all the time. It can infer the type from the context (most of the time)
Finding the Type with the type operator

Prelude> :t ‘a’
‘a’ :: Char

The :: operator here is read as “has type of.” Explicit types are always denoted with the first letter in uppercase. ‘a’ has a type of Char, which stands for character.

What type is a tuple ? Each tuple length has its own type.

Prelude> :t (‘a’, ‘b’, ‘c’)
(‘a’, ‘b’, ‘c’) :: (Char, Char, Char)

Type Variables

Type of a List

Prelude> :t [1,2,3]
[1,2,3] :: Num t => [t]

Notice how the type says ‘[t]’. This is a Type Variable. Basically it means that it can be substituted with any type variable. This is similar to generics in Java.

Functions also have types

add x y = x + y
*Main> :t add
add :: Num a => a -> a -> a

This means that the function take two inputs of type ‘a’ and returns a result of type ‘a’
Note the part before the ‘=>‘. This symbol is a class constraint. It constrains the type ‘a’ to be of the type Num i.e the inputs to the add function can only be of the type Num

Type class

A type class is an interface that defines some behavior. If a type is an instance of a type class, then it supports and implements the behavior the type class describes. Because a type class defines an abstract interface, one type can be an instance of many type classes.

More on this later

Advertisements
This entry was posted in Book review, Tech bits and tagged , . Bookmark the permalink.

One Response to Haskell walkthrough – III

  1. Very nice series. I also like the format.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s