Friday 29 April 2016

Introduction to GHCi


You can learn Haskell in interactive mode by using ghci command. Open terminal and type ‘ghci’, it opens window like below. (GHC stands for Glasgow Haskell Compiler, in GHCi I stands for interactive). From GHCi prompt you can evaluate expression, load Haskel files, reload Haskell files, get the type of expression, variables etc.,

$ ghci
GHCi, version 7.10.3: http://www.haskell.org/ghc/  :? for help
Prelude> 


Observe above snippet, it is telling that I am using ghci version 7.10.3. You can evaluate any kind of Haskell expressions in interactive mode.

Prelude> 2 + 3 + 5 + 7
17
Prelude> 2 - 3 * 8
-22
Prelude> 18/23.45678
0.76736875223283


As you observe, by default, prompt is opened using Preclude>, Prelude is a library which is loaded by default. You can change this by using the statement ‘:set prompt "hari>"’.

Prelude> :set prompt "hari>"
hari>10+20
30
hari>(20 + 30)*12.34
617.0


Always surround –ve numbers in parenthesis (), to get rid of the parsing error like below.

Prelude> 5 * -2

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

<interactive>:15:2:
    Not in scope: ‘/-’
    Perhaps you meant one of these:
      ‘-’ (imported from Prelude), ‘/’ (imported from Prelude),
      ‘/=’ (imported from Prelude)


Surround –ve numbers in parenthesis and re-run, you will get proper output.

Prelude> 5 * (-2)
-10
Prelude> 5 / (-3)
-1.6666666666666667


Operators can be used in prefix form also (To use an operator in prefix form, you must enclose the operator in parenthesis).

*Main> (+) 5 10
15
*Main> (*) 5 10
50
*Main> (/) 5 10
0.5





Previous                                                 Next                                                 Home

No comments:

Post a Comment