Friday 29 April 2016

Haskell: Variables

A variable is a named memory location used to store a value. Variables and function names must always start with lower case letter.


interest.hs
p = 100000
t = 1.10
r = 5

interest = p * t * r *0.01

In above program, I defined four variables p, t, r and interest. All these variables store a number.


Prelude> :load interest.hs
[1 of 1] Compiling Main             ( interest.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> p
100000.0
*Main> t
1.1
*Main> r
5.0
*Main> interest
5500.000000000001
*Main> 10*p
1000000.0
*Main> 10-p
-99990.0

Variables in Haskell are immutable, that means you can’t change the value of a variable after its definition.


sample.hs
var1 = 10
var1 = 13.24


When you try to load sample.hs file, you will get an error saying multiple declarations of variable var1.

Prelude> :load sample.hs
[1 of 1] Compiling Main             ( sample.hs, interpreted )

sample.hs:2:1:
    Multiple declarations of var1
    Declared at: sample.hs:1:1
                 sample.hs:2:1
Failed, modules loaded: none.

Since variables in Haskell are immutable, following program works absolutely fine.


sample.hs

y = x + 10
x = 10


Observe I defined the value x after its usage (y = x + 10). Since the variables are immutable, above program works absolutely fine.

*Main> :load sample.hs
[1 of 1] Compiling Main             ( sample.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> x
10
*Main> 
*Main> y
20

Specifying type to a variable

variable.hs

x :: Int
x = 10


Prelude> :load variable.hs
[1 of 1] Compiling Main             ( variable.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> x
10
*Main> 

x::Int
Above statement tells that variable ‘x’ is of type Int.

x=10
Above statement assign value 10 to the variable x.

Variables in Haskell are immutable, you can’t redefine them. For example, Update ‘variable.hs’ like below.


variable.hs

x :: Int
x = 10

x = 11


Try to reload above program, you will get following error.

*Main> :load variable.hs
[1 of 1] Compiling Main             ( variable.hs, interpreted )

variable.hs:4:1:
    Multiple declarations of x
    Declared at: variable.hs:2:1
                 variable.hs:4:1
Failed, modules loaded: none.
Prelude>



Previous                                                 Next                                                 Home

No comments:

Post a Comment