以下面的函数为例(该函数没有任何意义,但至少说明了我的问题)。
myFunction :: [x] -> x
myFunction [] = "result"
myFunction [x] = "result"
myFunction (_:xs) = myFunction xs
...
由于myFunction []
和myFunction x
匹配会产生相同的结果,是否有可能将它们组合成单个模式匹配,而不是将每一个都写在单独的行上并剪切/粘贴结果?类似于“ OR”操作数:
myFunction [] || x = "result"
并不是这样,但是有两种选择可以用一个子句编写它:
myFunction' (_:xs@(_:_)) = foo xs -- note the changed order: `_:...` first, thus
myFunction' _ = "result" -- you'll get "result" for _every_ other input
myFunction'' xs | null $ drop 1 xs = "result" -- or `| [] <- drop 1 xs`
myFunction'' (_:xs) = foo xs
myFunction''' xs' = case drop 1 xs' of
[] -> result
xs -> foo xs
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加