Haskell中的常量和模式匹配 [英] Constants in Haskell and pattern matching

查看:141
本文介绍了Haskell中的常量和模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Haskell中如何定义一个宏常量?尤其是,我想让下面的代码片段在没有第二个模式匹配的情况下运行重叠。

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"


推荐答案

您可以定义模式同义词

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"

但是也要考虑在自定义变体类型上进行匹配而不是 Int

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

这篇关于Haskell中的常量和模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆