haskellpattern-matchingpattern-synonyms

Constants in Haskell and pattern matching


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"

Solution

  • 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.