【发布时间】: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