问题
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:
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
.
来源:https://stackoverflow.com/questions/35417305/constants-in-haskell-and-pattern-matching