Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to program haskell with ghci?

Tags:

haskell

ghci

I've been reading some material and here I have a question: I saw a fragment of code is like this:

>getNthElem 1 xs = head xs
>getNthElem n [] = error "'n' is greater than the length of the list"
>getNthElem n xs
>    | n < 1     = error "'n' is non-positive"
>    | otherwise = getNthElem (n-1) (tail xs)

Should I type all these lines exactly the same into ghci or should I create a .hs file and put them in, then load it in the ghci?

like image 565
user3928256 Avatar asked Aug 26 '14 08:08

user3928256


1 Answers

There are 2 ways to do this:

  1. Use multiline mode within ghci by setting the flag as:

     Prelude> :set +m
     Prelude> let getNthElem 1 xs = head xs
     Prelude|     getNthElem n [] = error "error1"
     Prelude|     getNthElem n xs
     Prelude|                | n < 1 = error "error2"
     Prelude|                | otherwise = getNthElem (n-1) (tail xs)
     Prelude|
     Prelude>       
    
  2. Create a file and load it as a module to access the types and functions defined in it as

    Prelude> :l myModule.hs
    

    And file contents:

    getNthElem :: Int -> [a] -> a
    getNthElem 1 xs = head xs
    getNthElem n [] = error "'n' is greater than the length of the list"
    getNthElem n xs
                   | n < 1     = error "'n' is non-positive"
                   | otherwise = getNthElem (n-1) (tail xs)
    

I would recommend using the second option since it's quite easy to mess up indentation in multiline mode within GHCI. Also, make it a habit of adding type signatures before you start defining the function body.

like image 73
shree.pat18 Avatar answered Oct 04 '22 22:10

shree.pat18