简体   繁体   English

堆栈溢出非常简单的代码

[英]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. 我是一个Haskell新手,所以我可能会遗漏一些基本的东西 - 在这种情况下道歉,但我不知道下面的代码有什么问题以及为什么它溢出堆栈。 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]). 这是为了找到[1..x]中所有数字都能被整除的最小数字,这里使用[1,2](项目欧拉问题5是[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'. 我想它应该打印出'2'。

I also tried using and [mod xy == 0 | y <- [1..2]] == True = x 我也试过用and [mod xy == 0 | y <- [1..2]] == True = x and [mod xy == 0 | y <- [1..2]] == True = x instead of the first guard. and [mod xy == 0 | y <- [1..2]] == True = x而不是第一个后卫。 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. 功能应用程序的优先级高于任何运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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