Search code examples
haskellfunctional-programmingwinghci

Some issues when using WinGHCi


With WinGHCi, how can one implement the following code?

soma :: Int -> Int
soma 1 = aluno 1
soma n = aluno n + soma (n-1)

I am currently writing multiline code using

:{
...
:}

but that doesn't seem to solve the issue, in this case. Also, why doesn't something as

soma x y = x + y

work, when I'm working in WinGHCi? I can only do it if I use the let keyword

let soma x y = x + y -- valid Haskell code

although in most literature it seems people don't use it (I'm assuming it's because they are compiling the code?).

Thanks


Solution

  • The usual workflow for haskell programming is to put the function definition into a file and then load that file with ghci to test the function.

    To define functions (or variables) in ghci you need to use let like you would inside a do-block, i.e. let f x = x+1. To define functions, with type signatures or mutliple cases, separate the lines with ; like this:

    let soma :: Int -> Int; soma 1 = aluno 1; soma n = aluno n + soma (n-1)
    

    You can use :{ } to write this in several lines, but you'll still need the ; at the end of each line.