Bor*_*per -1 haskell pattern-matching
我知道我可以使用守卫来检查列表中是否出现一个值,但我想知道是否也可以单独使用模式匹配。
-- Using guards
f :: [Int] -> Int
f xs
| 42 `elem` xs = 42
| otherwise = 0
-- Using pattern matching?
g :: [Int] -> Int
g (_:)*42:_ = 42 -- i.e. zero or more elements: we discard until 42, followed by whatever.
g _ = 0
Run Code Online (Sandbox Code Playgroud)
是的。Int只有文字值;递归地。
-- Using pattern matching alone
g :: [Int] -> Int
g (42:_) = 42
g [] = 0
g (_:r) = g r
Run Code Online (Sandbox Code Playgroud)
测试:
> g [1..50]
42
> g [1]
0
Run Code Online (Sandbox Code Playgroud)
但是,模式中没有类似正则表达式的结构。我希望我们可以写一些类似的东西
foo [...xs, 42, ...ys] = xs ++ ys
foo _ = []
Run Code Online (Sandbox Code Playgroud)
但我们不能。
{-# LANGUAGE ViewPatterns #-}
g2 (break (== 42) -> (_,[])) = 0 -- 0, if not found
g2 _ = 42 -- 42, otherwise
Run Code Online (Sandbox Code Playgroud)
不过,我不确定它是否算作“单独的模式”,因为它使用“常规”标准函数break. 优点是,它不再只是文字。