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

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.





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

Share the post

Haskell: Specifying signature to a function

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×