Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack overflow in very simple code

Tags:

haskell

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!

like image 451
Costas Kotsokalis Avatar asked Nov 21 '12 09:11

Costas Kotsokalis


1 Answers

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.

like image 109
dave4420 Avatar answered Sep 21 '22 02:09

dave4420