简体   繁体   English

Haskell“否则”模式匹配?

[英]Haskell “otherwise” pattern match?

I have the following code: 我有以下代码:

swapInPairs :: [a] -> [a]
swapInPairs [] = []
swapInPairs [x] = [x]
swapInPairs (x:y:ys) = y : x : swapInPairs ys

is there any way to do something like 有什么办法可以做

swapInPairs :: [a] -> [a]
swapInPairs (x:y:ys) = y : x : swapInPairs ys
otherwise = id

I know it's not really a big deal, and only gets rid of one line of code, but I'm curious if there's something like this for pattern matching since guards have "otherwise". 我知道这并不是什么大不了的事,只摆脱了一行代码,但是我很好奇模式匹配是否存在这样的东西,因为后卫有“否则”的感觉。

Pattern matching in general gets applied sequentially. 模式匹配通常是顺序应用的。

So if you have a 'catch-all' version after a more specific pattern, more specific pattern will get matched first, and if it's impossible, a 'catch-all' will do its thing. 因此,如果您使用更具体的模式拥有一个“包罗万象”的版本,则会首先匹配更具体的模式,并且如果不可能,那么“包罗万象”将完成它的工作。

So you can do 所以你可以做

swapInPairs :: [a] -> [a]
swapInPairs (x:y:ys) = y : x : swapInPairs ys
swapInPairs x = x

Turns out order matters in pattern matching, and I didn't know that: 原来模式匹配中的顺序很重要,我不知道:

swapInPairs :: [a] -> [a]
swapInPairs (x:y:ys) = y : x : swapInPairs ys
swapInPairs x = x

works. 作品。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM