Saturday, 30 April 2016

Haskell: Type system

In this post, I am going to explain about Haskell type system.

Haskell is strongly typed
Haskell is a strongly typed language. A strongly typed language does not allow you to use one type as another.

For example, you had written a function to calculate sum of two integers. If you try to call the function with any other type Haskell thrown an error.


sample.hs
addition :: Integer -> Integer -> Integer
addition x y = x + y

*Main> :load sample.hs
[1 of 1] Compiling Main             ( sample.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> addition 10 20
30
*Main> 
*Main> addition 10 20.0

<interactive>:20:13:
    No instance for (Fractional Integer)
      arising from the literal 20.0
    In the second argument of addition, namely 20.0
    In the expression: addition 10 20.0
    In an equation for it: it = addition 10 20.0
*Main> 

Haskell don't perform automatic type conversions. In languages like Java, If the types are compatible, then a lower size data type can be converted to upper size data type. For example, a byte variable can be converted to int, int can be converted to double etc., But it is not the case with Haskell, Haskell don't perform automatic conversions.

Haskell is statically typed language
For statically typed languages, type of the variable is known at compile time. C, C++, Java, Haskell etc. are examples of statically typed languages. In static type checking, types are associated with variables not values. Following post explains about the differences between statically and dynamically typed languages.


Haskell Infer the types
If you don't specify type to a variable (or) any function, then Haskell automatically deduce the types.

Prelude> let a = 10
Prelude> let b = "Krishna"
Prelude> let c = True
Prelude> 
Prelude> :t a
a :: Num a => a
Prelude> :t b
b :: [Char]
Prelude> :t c
c :: Bool
Prelude>



Previous                                                 Next                                                 Home

No comments:

Post a Comment