e.g。 lines "One string\non\neach line"
= ["One string","on","each line"]
在列表,列表构造函数上使用模式匹配和递归,但没有其他函数。
这是我的解决方案,我从逻辑上思考,但它仍然给我一个错误。
lines :: [Char] -> [[Char]]
lines [] = [[]]
lines (x:'\n':xs) = [x] : lines xs
lines (x:xs) = x : lines xs
答案 0 :(得分:6)
假设您已经知道lines
除了输入的第一个字符之外的所有结果。你如何将第一个字符添加到该结果中?
charon :: Char -> [[Char]] -> [[Char]]
charon '\n' css = [] : css -- to begin with newline, insert blank line
charon c [] = [[c]] -- very last char is in line of its own
charon c (cs : css) = (c : cs) : css -- else put char in first line
随着这个谜团的解决,
lines = foldr charon []
多年来,我一直让学生用拳头敲打家具,用 emp 吟唱 ty list ?使用 x cons xs ?" 有时它会有所帮助。
答案 1 :(得分:1)
首先,您需要一种在第一个换行符之前检索所有文本的方法。这是简单的递归:
beforeNewLine :: [Char] -> [Char]
beforeNewLine "" = ""
beforeNewLine ('\n':xs) = ""
beforeNewLine (x:xs) = x : beforeNewLine xs
同样,我们需要能够在第一个换行符之后获取所有文本:
afterNewLine :: [Char] -> [Char]
afterNewLine "" = ""
afterNewLine ('\n':xs) = xs
afterNewLine (x:xs) = afterNewLine xs
把它们放在一起:
myLines :: [Char] -> [[Char]]
myLines "" = []
myLines xs = (beforeNewLine xs) : myLines (afterNewLine xs)