Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I capture values from a pattern synonym?

Assuming a pattern:

pattern P :: [Int]
pattern P <- a:_

Can I somehow use a in the function f?

f :: [Int] -> Int
f P = a

The code above generates an error of Not in scope: 'a'.

like image 505
Bartek Banachewicz Avatar asked Feb 03 '26 23:02

Bartek Banachewicz


1 Answers

Ok, this is slightly embarrasing, but I found that just doing this works:

{-# LANGUAGE PatternSynonyms #-}

pattern P :: Int -> [Int]
pattern P a <- a:_

f :: [Int] -> Int
f (P b) = b

main = print $ f [42]

The key point here is that the pattern parameter becomes explicit, but then it's also passed as an b pattern1 which will be matched. I was missing this one piece of the puzzle.

The drawback is that obviously you need to enumerate all parts of the pattern you want to use.


1Of course this can still be called a, I just named it differently for illustration.

like image 82
Bartek Banachewicz Avatar answered Feb 06 '26 13:02

Bartek Banachewicz