【问题标题】:Haskell redefine words function with recursionHaskell 用递归重新定义单词函数
【发布时间】:2020-03-01 22:18:46
【问题描述】:

我需要用递归重新定义单词函数。我有 2 个辅助功能,但我无法真正将最终功能放在一起。有什么想法吗?

takeWord :: String -> String
takeWord  ""      = ""
takeWord (' ':xs) = ""
takeWord (x  :xs) = x : takeWord xs

dropWord :: String -> String
dropWord  ""      = ""
dropWord (' ':xs) =  ' ' : xs
dropWord (x  :xs) =  dropWord xs

words' :: String -> [String]
words' "" = []
words' (' ':xs) = takeWord xs : words' xs
words' (x:xs) =  takeWord (x:xs) : words' (dropWord xs)

这个输入" Correct answer is this" 的结果应该是["Correct","answer","is","this"]。现在我得到了这个输出:["","","Correct","Correct","","","answer","answer","","","is","is","","","this","this"]

【问题讨论】:

  • (1) 每次取词都需要从尾部掉一个词。 (2) 取词时,需要检查是否为空。
  • 当您尝试时,您遇到了什么问题?在上面包含您尝试的代码。
  • @Michael Litchard 它在那里,单词的功能是它应该做的工作。 takeWord 正在获取字符串的第一个单词 dropWord 正在删除字符串的第一个单词,而 words' 应该在前两个函数的帮助下从字符串中生成单词列表。
  • 噢!我现在看到了。
  • words' (' ':xs) = takeWord xs : words' xs 看起来像是在重复单词,因为xs 被使用了两次。你确定你不需要递归为words' (dropWords xs) 或类似的东西吗?

标签: function haskell recursion


【解决方案1】:

从@chi 那里得到了有效的解决方案

“也许我会尝试代替 words' (' ':xs) = words' xs 来跳过前导空格,看看会发生什么。”

【讨论】:

    猜你喜欢
    • 2011-02-14
    • 2019-02-28
    • 1970-01-01
    • 2020-05-08
    • 2015-05-27
    • 2012-05-24
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    相关资源
    最近更新 更多