Saturday 30 April 2016

Haskell: Type inference

In previous post, I explain how to specify the signature to a function. But it is optional to specify type to variable, functions. Haskell infer the type, if you don’t specify.


For example,
*Main> let a = 10
*Main> let b = 'a'
*Main> let c = "Hello"
*Main> let d = 10.09
*Main> let e = True
*Main> 
*Main> :t a
a :: Num a => a
*Main> 
*Main> :t b
b :: Char
*Main> 
*Main> :t c
c :: [Char]
*Main> 
*Main> :t d
d :: Fractional a => a
*Main> 
*Main> :t e
e :: Bool

Observe above snippet, I assigned 10 to the variable ‘a’, but not mentioned the data type, Haskell infers ‘a’ is of type Num based on the value assigned to it.

Haskell infer the types to a function also.


sample.hs
is3 x = (x == 3)

addition x y = (x + y)

*Main> :load sample.hs
[1 of 1] Compiling Main             ( sample.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> :t is3
is3 :: (Eq a, Num a) => a -> Bool
*Main> 
*Main> :t addition
addition :: Num a => a -> a -> a



Previous                                                 Next                                                 Home

No comments:

Post a Comment