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?
There are 2 ways to do this:
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With