views:

51

answers:

2

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

+2  A: 

GHCi runs in the IO monad (I think) so you have to use the let keyword like that in order for it to understand what you mean.

And why don't you just write the code to a file called 'soma.hs' and then load it into ghci with a:

:l soma.hs

That should work just as well.

Robert Massaioli
+2  A: 

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.

sepp2k
Perfect! Just one more question, I've tried saving and running the first piece of code just as it is, and it's giving me some error when doing :l soma.hs. I guess I need some other code for making this work, how would that be?
devoured elysium
@devoured: Just the code you showed or also the `aluno` function? If I put `aluno = id` and then the code from your question into a file and load that into ghci, it works fine. So maybe the error is in your `aluno` function? What's the error message you get?
sepp2k
doh, so obvious. You were right, I forgot to put a reference to aluno. Thanks!
devoured elysium