7

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!

1
  • 2
    You can omit == True. Commented Apr 7, 2014 at 10:43

1 Answer 1

14

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.

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

1 Comment

Many thanks indeed, that solved it. It's a slippery road from Python to Haskell!

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.