gpt4 book ai didi

haskell:调试 <> 异常

转载 作者:行者123 更新时间:2023-12-02 20:32:28 24 4
gpt4 key购买 nike

为了练习 Haskell,我实现了 Fermat 的因式分解方法(参见 https://en.wikipedia.org/wiki/Fermat%27s_factorization_method )。然而,当我运行我的程序时,Haskell 不断告诉我:

$ ./fermat 7
fermat: <<loop>>

看来,我的代码中有一个无限循环(cmp.http://www.haskell.org/pipermail/haskell-cafe/2013-June/108826.html)。谁能给我提示,我做错了什么?

我还想扩展这个问题How to debug Haskell code?有关如何调试此特定异常的提示。

import Data.List
import System.Environment
import Debug.Trace

isQuad :: Integer -> Bool
isQuad x = a == b
where
a = ceiling $ s
b = floor $ s
s = sqrt (fromIntegral x :: Double)

test :: Integer -> Integer -> Integer -> Bool
test nr n s = trace(show nr ++ " " ++ show n ++ " " ++ show s)
isQuad(
(+)
( (\j -> j * j) s + nr )
(-n)
)

fermat :: Integer -> (Integer, Integer)
fermat n = (s + x, s - x)
where
s = ceiling $ sqrt (fromIntegral x :: Double)
r = trace
(show s ++ " " ++ show n)
(\(Just i) -> i) $
find
(\nr -> test nr n s)
[0..n]
x = floor $ sqrt (fromIntegral r :: Double)

fact :: Integer -> (Integer, Integer)
fact x
| x == 1 = (1, 1)
| even x = (2, x `div` 2)
| otherwise = fermat x

f :: String -> String
f x = x ++ " = " ++ show a ++ " x " ++ show b
where
(a, b) = fact $ (read x :: Integer)

main = do
args <- getArgs
putStrLn $ unlines $ map f args

最佳答案

fermat , s取决于x , x取决于r ,和r取决于s .

有时懒惰可能会使这种循环依赖关系正常,但在这种情况下,所有依赖关系似乎都是严格的。

这只是来自检查,除了链接帖子中的内容之外,我对如何调试问题没有任何具体建议。

我想说<<loop>>意味着运行时系统已经能够检测到无限循环,这意味着取决于自身,例如let x = x + 1 in x 。所以这是追踪问题的一点线索。

如果您在函数调用中编写了无限循环,例如let f x = f x + 1 in f 1 ,它通常会永远运行。有时优化器可能会将这些函数调用转换为值,但一般情况下它不能这样做。

关于haskell:调试 <<loop>> 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25673900/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com