Constants in Haskell and pattern matching

323 views Asked by At

How is it possible to define a macro constant in Haskell? Especially, I would like the following snippet to run without the second pattern match to be overlapped.

someconstant :: Int
someconstant = 3

f :: Int -> IO ()
f someconstant = putStrLn "Arg is 3"
f _            = putStrLn "Arg is not 3"
1

There are 1 answers

0
leftaroundabout On BEST ANSWER

You can define a pattern synonym:

{-# LANGUAGE PatternSynonyms #-}

pattern SomeConstant :: Int
pattern SomeConstant = 3

f :: Int -> IO ()
f SomeConstant = putStrLn "Arg is 3"
f _            = putStrLn "Arg is not 3"

But also consider whether it's not better to match on a custom variant type instead of an Int.