Constants in Haskell and pattern matching [duplicate]

六月ゝ 毕业季﹏ 提交于 2019-12-23 15:58:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!