Friday 29 April 2016

Haskell: Arithmetic operators



Operator
Performs
+
Addition
-
Subtraction
*
Multiplication
/
Division
mod
Get the remainder
rem
Get the remainder, Sign of the result is same as sign of x.
^
Calculates power, a^x return a to the power x.

*Main> let a = 10
*Main> let b = 5
*Main> 
*Main> a + b
15
*Main> 
*Main> a - b
5
*Main> 
*Main> a * b
50
*Main> 
*Main> a / b
2.0
*Main> 
*Main> mod a b
0
*Main> 
*Main> mod b a
5
*Main> 
*Main> rem a b
0
*Main> 
*Main> rem b a
5
*Main> 
*Main> a ^ b
100000
*Main> 
*Main> b ^ a
9765625

As you observe, I used mod, rem operators in prefix form. By using `backtics`, you can use mod and rem operators in infix notation.

*Main> 10 `mod` 3
1
*Main> 10 `rem` 3
1


Always surround negative numbers in parenthesis, other wise you will end up in following kind of error.
*Main> 10 / -3

<interactive>:86:1:
    Precedence parsing error
        cannot mix / [infixl 7] and prefix `-' [infixl 6] in the same infix expression


To solve above problem, we need to put negative number in parenthesis like below.
*Main> 10 / (-3)
-3.3333333333333335


Haskell doesn’t do implicit conversions
Haskell doesn’t do implicit type conversions, you must explicitly perform them.

For example,
arithmetic.hs
a :: Int
a = 10

b :: Float
b = 10.90

c :: Int
c = 11


As you observe above snippet, variables a, c are of type Int and b is of type Float. We can perform operations between a and c, but we can't perform operation between a,b and c, b since types of a and b, c and b are different.
*Main> :load arithmetic.hs
[1 of 1] Compiling Main             ( arithmetic.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> :t a
a :: Int
*Main> :t b
b :: Float
*Main> :t c
c :: Int
*Main> 
*Main> a + c
21
*Main> 
*Main> a + b

<interactive>:114:5:
    Couldn't match expected type Int with actual type Float
    In the second argument of (+), namely b
    In the expression: a + b
*Main> 
*Main> c + b

<interactive>:116:5:
    Couldn't match expected type Int with actual type Float
    In the second argument of (+), namely b
    In the expression: c + b
*Main> 


You can explicitly cast the variables before performing operations. Following functions are used to cast variables of one type to another.

Function
Description
fromIntegral
Converts from any integral type (Int or Integer) to any other numeric type.
round, floor, ceiling
Convert floating-point numbers to Int or Integer.

*Main> a + b

<interactive>:132:5:
    Couldn't match expected type Int with actual type Float
    In the second argument of (+), namely b
    In the expression: a + b
*Main> 
*Main> a + round(b)
21
*Main> a + ceiling(b)
21
*Main> a + floor(b)
20









Previous                                                 Next                                                 Home

No comments:

Post a Comment