gpt4 book ai didi

haskell - 没有由文字 '2' (Haskell) 产生的 (Num[t0]) 实例

转载 作者:行者123 更新时间:2023-12-05 00:28:19 25 4
gpt4 key购买 nike

我是 Haskell 的初学者,我正在尝试将一个列表分成两个大小大致相等的子列表。该模块可以加载,但是当我尝试运行 ghci 时,它不起作用。
例如:
divideList [1,2,3,4] = [1,2] [3,4] divideList [1,2,3,4,5] = [1,2,3] [4,5]

divideList [] = ([],[])
divideList [x] = ([x],[])

divideList ((x:xs):ys) = if a < b
then splitAt (a+1) ((x:xs):ys)
else divideList (xs:ys)
where a = length xs
b = length ys

它说“没有(Num [t0])的实例来自文字'2'”。我不知道如何解决它。谁能帮我???谢谢!

这是我在 ghci 中输入 divideList [2,3,5] 时显示的错误。
<interactive>:2:13:
No instance for (Num[a0]) arising from literal '2'
Possible fix: add an instance declaration for (Num[a0])
In the expression: 2
In the first argument of 'divideList', namely "[2,3,5]
In the expression: divideList [2,3,5]

最佳答案

首先:伙计,我的{格式化,类型签名}呢?

第二:您所说的错误表明您在类型说值应该是列表的地方使用了数字文字(例如: 1 )。因为解释文字是灵活的(多态的),类型检查器提示你需要告诉它如何将数字解释为列表。

第三:发布的代码(重新格式化并在下面提供了类型签名)不会产生您声称的错误。

第四:发布的代码不执行您描述的任务 - 单独的类型签名是一个强有力的提示 - 您描述的函数应该将列表带到列表对( [a] -> ([a],[a]) 但您定义了一个使用列表列表的函数( [[a]] -> ([[a]],[[a]]) ).. .

divideList :: [[a]] -> ([[a]], [[a]])
divideList [] = ([],[])
divideList [x] = ([x],[])
divideList ((x:xs):ys) =
if a < b
then splitAt (a+1) ((x:xs):ys)
else divideList (xs:ys)
where a = length xs
b = length ys

关于haskell - 没有由文字 '2' (Haskell) 产生的 (Num[t0]) 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19086904/

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