1

So, what I try to do is to define recursively a function that calculates how much money I have after n years, if I start with an amount a and receive p percent of interest per year.

interest (n,a,p)
 | n > 0          = interest (n-1,a,p)
       where a = (a*p)/100
 | otherwise      = a

And it gives me this error:

E:\\Module1\week3\scripts.hs:35:2: error: parse error on input `|'
   |
35 |  | otherwise      = a
   |  ^

Can anyone tell me what I do wrong? Thank you.

1
  • Although that is not the error, defining functions that are not "curried" are rather uncommon in Haskell. Typically the functions are defined as interest n a p = ..., and thus called with interest (n-1) a p. Commented Sep 24, 2018 at 17:01

1 Answer 1

3

where can only be used after all the guards, and applies to all of them. For instance

f x y =
  | x > 0     = g a + x   -- a is visible here
  | otherwise = h a + y   -- and here
  where a = x + y

Further, note that your where a = (a*p)/100 will likely lead to non-termination, since a is recursively defined in terms of itself ((a*p)/100). You should use a new variable name e.g. a' = (a*p)/100. It is in general a bad idea to "redefine" an outer variable in Haskell: turning on warnings with the -Wall flag helps in detecting these issues.

Finally, note that you can also use let instead of where, and use that inside any expression. For instance

f x y =
  | x > 0 =
     let a = x + y
     in g a + x
  | otherwise = y  -- a is not visible here

One could even write

(let a = x + y in g a) + x

albeit I can not recommend this style.

Sign up to request clarification or add additional context in comments.

1 Comment

I succeeded using if instead of guards. I will try this way, as well. Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.