I'm a Haskell newbie so I may be missing something basic -- apologies in that case, but I just can't find out what's wrong with the following code and why it overflows the stack. It's for finding the smallest number that is equally divisible by all numbers in [1..x], here using [1,2] (Project Euler Problem 5 is for [1..20]).
module Main where
main::IO()
main = do
putStrLn $ show s where s = func 1
func :: Int -> Int
func x
| foldr1 (&&) [x `mod` y == 0 | y <- [1..2]] == True = x
| otherwise = func x+1
I guess it should print out '2'.
I also tried using and [mod x y == 0 | y <- [1..2]] == True = x
instead of the first guard. In both cases I'm getting a stack overflow when trying to run this.
I've solved the problem by putting everything in main plus one more list comprehension, but I'd like to understand what's wrong with this one. Thanks!
The problem (or at least, a problem --- I haven't checked for others) is in this line:
| otherwise = func x+1
You intend this to be
| otherwise = func (x+1)
but it is parsed as
| otherwise = (func x)+1
Function application has a higher priority than any operator.
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