简体   繁体   中英

Stack overflow in very simple code

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 xy == 0 | y <- [1..2]] == True = x and [mod xy == 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM