Reputation: 61
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.
Upvotes: 1
Views: 346
Reputation: 116174
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.
Upvotes: 3