简体   繁体   English

如何在 Haskell 中将守卫与模式匹配结合起来? (我可以吗?)

[英]How can i combine guards with pattern matching in Haskell? (And can I at all?)

Now I know that after I declare function signature with Haskell, I can do pattern matching with function overloading like so:现在我知道,在我用 Haskell 声明 function 签名后,我可以像这样使用 function 重载进行模式匹配:

frog :: Int -> String
frog 1 = "Ribbit"
frog 7 = "Croak"
frog 12 = "Pop!"
frog x = replicate x "Z"

I know I also can use guards in a similar fashion:我知道我也可以以类似的方式使用警卫:

frog :: Int -> String
frog x = 
    | x == 1 = "Ribbit"
    | x == 7 = "Croak"
    | x == 12 = "Pop!"
    | otherwise = replicate x "Z"

However I would rather prefer to combine the two ways using both a Boolean guard and a pattern to determine which arm would be executed.但是,我宁愿结合使用 Boolean 保护和模式来确定将执行哪个 arm 的两种方式。 Something similar to this rust snippet:类似于此 rust 片段的内容:

fn frog(x: u32) -> String {
    match x {
        k if k >= 1000 => todo!()
        k if k >= 100 => todo!()
        k if k >= 10 => todo!()
        9 | 8 | 7 => todo!()
        6 | 5 | 4 => todo!()
        3 => todo!()
        2 => todo!()
        1 => todo!()
        0 => todo!()
    }
}

I would like to know if that's possible to do in Haskell, and if so how to do it.我想知道在 Haskell 中是否可以这样做,如果可以,该怎么做。 Thank you in advance先感谢您

You can't match multiple cases with a single pattern (the 9 | 8 | 7 thing), but you can straightforwardly combine patterns and guards:你不能用一个模式匹配多个案例( 9 | 8 | 7东西),但你可以直接组合模式和守卫:

foo 1 = "one"
foo 2 = "two"
foo k
    | k > 1000 = "greater than 1000"
    | k > 100 = "between 100 and 1000"
    | otherwise = "some other number"

The guards are part of the pattern - if none of the guards attached to a case succeed, then control falls through to the next case in the way you'd expect.守卫是模式的一部分——如果附加到一个案例的守卫都没有成功,那么控制会以您期望的方式传递给下一个案例。 (To put it another way, a single pattern's guards don't have to be exhaustive.) (换句话说,单一模式的守卫不必详尽无遗。)

bar k | k > 1000 = "greater than 1000"
bar _ = "smaller than 1000"

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

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