Saturday 30 April 2016

Haskell: Specifying signature to a function

In my previous posts, I explained about functions and types. In this post, I am going to explain how to define a function with signature.


For example
addition :: Int -> Int -> Int


Above statement tells that addition function takes two Integer arguments as input and returns an integer as output. You can’t call addition with any other types like Char, string ([Char]), (or) any fractional numbers.
*Main> addition 10.01 10

<interactive>:18:10:
    No instance for (Fractional Int) arising from the literal 10.01
    In the first argument of addition, namely 10.01
    In the expression: addition 10.01 10
    In an equation for it: it = addition 10.01 10
*Main> 
*Main> addition 10 10
20


arithmetic.hs
{-Simple Haskell program to demonstrate Arithmetic operations -}
addition :: Int -> Int -> Int
addition x y = x + y

subtraction :: Int -> Int -> Int
subtraction x y = x - y

multiplication :: Int -> Int -> Int
multiplication x y = x * y

square :: Int -> Int
square x = x * x

cube :: Int -> Int
cube x = x * x * x


It is optional to specify a type to a variable (or) function. But it is always good to mention to specify type.

Why to specify types
a.   Type signatures make your code easier to understand.
b.   It is easy to debug by specifying types, prevent most of the errors at compile time.





Previous                                                 Next                                                 Home

No comments:

Post a Comment