Bar*_*icz 2 haskell pattern-matching pattern-synonyms
假设一种模式:
pattern P :: [Int]
pattern P <- a:_
Run Code Online (Sandbox Code Playgroud)
我可以以某种方式使用a该功能f吗?
f :: [Int] -> Int
f P = a
Run Code Online (Sandbox Code Playgroud)
上面的代码生成错误Not in scope: 'a'.
好吧,这有点令人尴尬,但我发现这样做有效:
{-# LANGUAGE PatternSynonyms #-}
pattern P :: Int -> [Int]
pattern P a <- a:_
f :: [Int] -> Int
f (P b) = b
main = print $ f [42]
Run Code Online (Sandbox Code Playgroud)
这里的关键点是模式参数变得明确,但它也作为b模式1传递,它将被匹配.我错过了这一块拼图.
缺点是显然你需要枚举你想要使用的模式的所有部分.
1当然这仍然可以调用a,我只是为了说明而命名.