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

标签 haskell

我是 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/

相关文章:

haskell - 用数字输入歧义

haskell - Aeson 构建测试 yesod-sqlite 项目时出错

string - 高阶函数haskell

haskell - Parsec.Expr 以不同优先级重复 Prefix

haskell - 如何创建在Servant中的任何路径上触发的路由?

haskell - 在 Haskell 中访问二维 newListArray

将 [(K,[V])] 转置为 [(V,[K])] 时出现内存故障

haskell - 为什么 Haskell/unpack 会弄乱我的字节?

haskell - 如何在 Haskell 应用程序中固定依赖项

haskell - 我如何构造一个函数/类型来观察这个状态机中的每个转换?