gpt4 book ai didi

debugging - 尝试在函数中调用 putStrLn 时出错

转载 作者:行者123 更新时间:2023-12-04 16:15:28 26 4
gpt4 key购买 nike

我正在尝试在 Haskell 函数中调用“打印输出”函数。

(一个简单的调试消息)。

以下是来自编译器(GHC 6.10)的代码和错误消息。

我不太明白为什么它把 putStr 混为一谈。调用和空数组。

空数组是该特定情况的返回值(打印出的消息实际上现在只是一个 stub )。

知道为什么这不起作用吗?

我的代码:

isAFactor::整数 -> 整数 -> bool
isAFactor x y = x `mod` y == 0

findFactors::整数 -> 整数 -> [整数]
findFactors 计数器编号 =
让商 = div num 2

如果(计数器>商)
然后做
putStrLn ("factorList is : "++ show quotient) (*** Line 10***)
[]
else if(isAFactor num 计数器)
然后 [counter]++ [quotient]++ findFactors (counter + 1) num
别的
findFactors (counter + 1) 数量

来自 ghc 的错误

测试.hs:10:4:
无法匹配预期类型 `[a] -> [Integer]'
针对推断类型‘IO()’
在表达式中:
putStrLn("factorList is :"++ show quotient) []
在表达式中:
do putStrLn("factorList is :"++ show quotient) []
在表达式中:
如果(计数器>商)那么
do putStrLn("factorList is :"++ show quotient) []
别的
if (isAFactor num counter) then
[counter]++ [quotient]++ findFactors (counter + 1) num
别的
findFactors (counter + 1) 数量

最佳答案

重要的是要记住 Haskell 是 pure功能语言。这意味着函数根本不允许有任何副作用,包括将调试消息打印到屏幕上。

然而,有可能打破这种纯度,它在调试中很有用。看看模块Debug.Trace .在那里你会找到一个函数trace :: String -> a -> a .您可以像这样在代码中使用它:

import Debug.Trace

isAFactor :: Integer -> Integer -> Bool
isAFactor x y = x `mod` y == 0

findFactors :: Integer -> Integer -> [Integer]
findFactors counter num =
let quotient = div num 2
in
if(counter > quotient)
then trace ("factorList is: " ++ show quotient) []
else if(isAFactor num counter)
then [counter] ++ [quotient] ++ findFactors (counter + 1) num
else
findFactors (counter + 1) num

正如评论所建议的:

Haskell 也是 lazy语。在实际需要结果之前不会评估表达式。在惰性设置中使用跟踪功能可能会有点困惑,因为当跟踪消息打印到屏幕时(如果打印的话)并不总是很容易理解。

由于 haskell 是一种非常不同的语言,因此最好尝试以同样不同的方式开发程序。尝试推理你的函数而不是使用 trace和类似的“不纯”结构。学习利用 haskells 强大的类型系统和使用(例如) QuickCheck在通过类型检查器后测试您的函数。

关于debugging - 尝试在函数中调用 putStrLn 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/684552/

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