gpt4 book ai didi

haskell - 为什么会出现这种类型错误?

转载 作者:行者123 更新时间:2023-12-02 00:34:22 27 4
gpt4 key购买 nike

solveRPN :: String -> Double
solveRPN rpnString = head foldl . foldingFunction [] . words
where foldingFunction (x:y:ys) "*" = (x * y):ys
foldingFunction (x:y:ys) "+" = (x + y):ys
foldingFunction (x:y:ys) "-" = (x - y):ys
foldingFunction xs numberString = read numberString:xs

上面的代码产生下面的错误。我尝试将 String 更改为 [Char] 并将双引号替换为单引号,但我一直收到此错误:

_01.hs:874:50: error:
• Couldn't match type ‘Char’ with ‘[Char]’
Expected type: String
Actual type: Char
• In the first argument of ‘read’, namely ‘numberString’
In the first argument of ‘(:)’, namely ‘read numberString’
In the expression: read numberString : xs
| 874 | foldingFunction xs numberString = read numberString:xs
| ^^^^^^^^^^^^ Failed, 1 module loaded.

最佳答案

Learn you a Haskell 书中的原始解决方案如下所示

solveRPN :: (Num a, Read a) => String -> a  
solveRPN = head . foldl foldingFunction [] . words
where foldingFunction (x:y:ys) "*" = (x * y):ys
foldingFunction (x:y:ys) "+" = (x + y):ys
foldingFunction (x:y:ys) "-" = (y - x):ys
foldingFunction xs numberString = read numberString:xs

当我将它与您的代码段进行比较时,有两件事导致了错误:

1) 您在合成链中放错了合成运算符。而不是这个

head foldl . foldingFunction [] . words

你需要这个

head . foldl foldingFunction [] . words

调用words后,用foldingFunction折叠后,您可以将其理解为取head,其中每个“after”都是组合运算符。

2) 你使用了一个组合,但你仍然留下参数 rpnString。如果你想使用一个组合,你必须省略链中的参数。所以你可以省略参数:

solveRPN :: String -> Double
solveRPN = head . foldl foldingFunction [] . words
where foldingFunction (x:y:ys) "*" = (x * y):ys
foldingFunction (x:y:ys) "+" = (x + y):ys
foldingFunction (x:y:ys) "-" = (y - x):ys
foldingFunction xs numberString = read numberString:xs

或者你可以省略合成链:

solveRPN :: String -> Double
solveRPN rpnString = head (foldl foldingFunction [] (words rpnString))
where foldingFunction (x:y:ys) "*" = (x * y):ys
foldingFunction (x:y:ys) "+" = (x + y):ys
foldingFunction (x:y:ys) "-" = (y - x):ys
foldingFunction xs numberString = read numberString:xs

关于haskell - 为什么会出现这种类型错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50374560/

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