gpt4 book ai didi

haskell - 帮助我理解这个 Haskell (GHCI) 类型错误 : (Num [Char]) when appending number to string

转载 作者:行者123 更新时间:2023-12-01 23:19:15 25 4
gpt4 key购买 nike

这个周末我一直在努力学习 Haskell,但当我真正尝试编写一个递归函数(而不是仅仅从教程中输入一个)时,我得到了一个类型错误。

如果您能帮助我理解 (1) 错误的含义(我不理解“修复”),我将不胜感激; (2) 为什么会抛出错误 - 我相当确定我在传递的类型方面没有犯任何错误。

我的代码:

tell :: (Show a) => [a] -> String  
tell'in :: (Show a, Num n) => [a] -> n -> String -> (n, String)
tell [] = "The list is empty"
tell (x:[]) = "The list has one element: " ++ show x
tell (x:xs) = "The list has " ++ n ++ " elements: " ++ s where (n, s) = (tell'in (xs) (1) (show x))


tell'in (x:[]) n s = ((n + 1), (s ++ " and " ++ (show x)))
tell'in (x:xs) n s = tell'in xs (n+1) (s ++ " and " ++ show x)

当我尝试将其加载到 GHCI 时出现的错误:

[1 of 1] Compiling Main             ( example.hs, interpreted )

example.hs:13:88:
Could not deduce (Num [Char]) arising from the literal `1'
from the context (Show a)
bound by the type signature for tell :: Show a => [a] -> String
at example.hs:(11,1)-(13,99)
Possible fix:
add (Num [Char]) to the context of
the type signature for tell :: Show a => [a] -> String
or add an instance declaration for (Num [Char])
In the second argument of `tell'in', namely `(1)'
In the expression: (tell'in (xs) (1) (show x))
In a pattern binding: (n, s) = (tell'in (xs) (1) (show x))
Failed, modules loaded: none.
Prelude>

最佳答案

tell'in 返回一个 Num n => n,然后你用 (++)ing tell 的最后一个等式中的字符串(又名[Char])。您可能想在那里使用 show n 而不是 n

关于haskell - 帮助我理解这个 Haskell (GHCI) 类型错误 : (Num [Char]) when appending number to string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6248391/

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