【问题标题】:split function 'no instance for' error拆分函数“没有实例”错误
【发布时间】:2014-06-26 18:13:43
【问题描述】:

这个函数应该标记一个字符串:

    split s c xs i j =
        if head s == c
        then split s c (subStr s i j : xs) j (j + 1)
        else if j == length s
        then (subStr s i j) : xs
        else split s c xs i j + 1
    subStr s i j = take j(drop i s)

但是我收到以下错误消息: (Num [[Char]]) 没有因使用“split”而产生的实例 可能的解决方法:在 (Num [[Char]]) 处添加实例声明

谢谢。

Ok 函数现在是:

split s c xs i j =
        if j == length s
        then (subStr s i j) : xs
        else if head (drop j s) == c
        then split s c (subStr s i j : xs) (j + 1) (j + 1)
        else split s c xs i (j + 1)

subStr s i j = take j(drop i s)

现在当我使用以下参数应用函数时: split "123,456,789" ',' [] 0 0 我得到结果 ["789", "456,789", "123"] 这里发生了什么?

【问题讨论】:

  • 你应该包含你的函数类型签名。它使我们更容易说出您要做什么。但我最初的猜测是你只需要在倒数第二行加上括号j+1
  • 我同意cdk的观点,这个函数可以重写得更清楚。但如果你只是想让这个工作,请substr s i j = take (j-i) (drop i s)

标签: haskell split tokenize


【解决方案1】:

问题出在else split s c xs i j + 1线上。似乎您正在尝试将 1 添加到 split 的结果中。你可能忘记了(j + 1)周围的括号

我假设split 返回一个[String],是吗?

编辑:您的功能难以遵循。奇怪的排序可能是你在第三行添加子字符串(subStr s i j) : xs的结果。

尝试使用takeWhile, dropWhile :: (a -> Bool) -> [a] -> [a] 重写您的函数,或者更好的是,使用适当的字符串处理库,如ByteString,它提供了

Data.ByteString.Char8.split :: (Char -> Bool) -> ByteString -> [ByteString]

【讨论】:

  • 谢谢,现在逻辑上有问题:所以函数看起来像这样: split s c xs i j = if j == length s then (subStr s i j) : xs else if head (drop j s) = = c then split s c (subStr s i j : xs) (j + 1) (j + 1) else split s c xs i (j + 1) subStr s i j = take j(drop i s) 当我申请时: split "123,456,789" 'c ' [] 0 0 我得到输出 ["789", "456, 789", "123"] 知道中间发生了什么吗?
  • 我无法阅读您提供的代码。所以不,我不知道发生了什么。我建议接受这个答案(一旦你能够)并就你的问题提出一个新问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-04
相关资源
最近更新 更多