Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Haskell : get the type of variable


In Haskell, every expression is evaluated to a type. Including functions everything has a type. From ghci terminal, you can get the type of a variable (or) expression using :t (or) :type command.
*Main> :t 10
10 :: Num a => a
*Main>
*Main> :t 'a'
'a' :: Char
*Main>
*Main> :type 10.234
10.234 :: Fractional a => a
*Main>
*Main> :type "Hello World"
"Hello World" :: [Char]
*Main>
*Main> :type True
True :: Bool
*Main> :t 10>5
10>5 :: Bool

:: can be read as ‘is of type’.

'a' :: Char can be read as ‘a’ is of type Char.
10>5 :: Bool can be read as 10>5 is of type Bool

Difference between character and string
Character represents a single character, enclosed in single quotation marks. String is a collection of characters enclosed in double quotes.
*Main> :t 'h'
'h' :: Char
*Main>
*Main> :t "hello"
"hello" :: [Char]


Observe above snippet, type of character is represented as Char, where as type of string is represented in square brackets [Char].

Is functions has types as well?
Yes of course, functions also have types associated with them. For example all the operators in Haskell are internally implemented as functions, lets see how they behave with :t command.

*Main> :t not
not :: Bool -> Bool
*Main>
*Main> :t (&&)
(&&) :: Bool -> Bool -> Bool
*Main>
*Main> :t (||)
(||) :: Bool -> Bool -> Bool


‘:t not’ returns ‘not :: Bool -> Bool’ means not operator take one Bool variable as input and return one Bool variable as output.

‘:t (&&)’ returns ‘Bool -> Bool -> Bool’ means && operator take two Boolean variables as input and return Boolean variable as output. Last data type in the sequence ‘Bool -> Bool -> Bool’ represents the output.

Lets try to find the types of custom functions.

arithmetic.hs

{-Simple Haskell program todemonstrate Arithmetic operations -}
addition x y = x + y
subtraction x y = x - y
multiplication x y = x * y

square x = x * x
cube x = x * x * x

*Main> :load arithmetic.hs
[1 of 1] Compiling Main ( arithmetic.hs, interpreted )
Ok, modules loaded: Main.
*Main>
*Main> :t addition
addition :: Num a => a -> a -> a
*Main>
*Main> :t subtraction
subtraction :: Num a => a -> a -> a
*Main>
*Main> :t multiplication
multiplication :: Num a => a -> a -> a
*Main>
*Main> :t square
square :: Num a => a -> a
*Main>
*Main> :t cube
cube :: Num a => a -> a





Previous                                                 Next                                                 Home


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Haskell : get the type of variable

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×