我写了一个基于模式匹配的代码(已注释掉),它运行良好。我希望使用“case of”以希望压缩我的代码,但是它不喜欢我如何声明空列表情况(最后一个)。我查看了一些例子,虽然不相同但似乎支持我的声明。因此,我不确定我做错了什么,非常感谢帮助。
--1st way
mutate::[Char] ->Int
--mutate::[Char] ->[Int]
--mutate ('P':'E':'R':rest) = 0:mutate rest
--mutate ('P':'E':_:rest) = 1:mutate rest
--mutate ('P':_:'R':rest) = 1:mutate rest
--mutate (_:'E':'R':rest) = 1:mutate rest
--mutate (_:_:'R':rest) = 2:mutate rest
--mutate (_:'E':_:rest) = 2:mutate rest
--mutate ('P':_:_:rest) = 2:mutate rest
--mutate (_:_:_:rest) = 3:[]
--mutate [] = [0]
--2nd way
mutate (f:s:t:rest) = case (f:s:t:rest) of
('P':'E':'R':rest) -> 0
('P':'E':_:rest) -> 1
('P':_:'R':rest) -> 1
(_:'E':'R':rest) -> 1
(_:_:'R':rest) -> 2
(_:'E':_:rest) -> 2
('P':_:_:rest) -> 2
(_:_:_:rest) -> 3
([]) -> 0
main = print $ mutate []
答案 0 :(得分:5)
问题在于这一行:
mutate(f:s:t:rest)= case(f:s:t:rest)的
你是第一行本身的模式匹配。因此,只有在列表的最小元素为3时才会输入这种情况。这样的事情应该有效:
mutate :: [Char] -> Int
mutate xs = case xs of
('P':'E':'R':rest) -> 0
('P':'E':_:rest) -> 1
('P':_:'R':rest) -> 1
(_:'E':'R':rest) -> 1
(_:_:'R':rest) -> 2
(_:'E':_:rest) -> 2
('P':_:_:rest) -> 2
(_:_:_:rest) -> 3
([]) -> 0