为什么这段代码中的非法非交易模式匹配?

sti*_*ian 1 haskell pattern-matching

我写了一个基于模式匹配的代码(注释掉),工作得很好.我希望使用"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 []
Run Code Online (Sandbox Code Playgroud)

Sib*_*ibi 5

问题出在这一行:

mutate(f:s:t:rest)= case(f:s:t:rest)of

你是第一行本身的模式匹配.因此,只有在列表的最小元素为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
Run Code Online (Sandbox Code Playgroud)