Haskell模式匹配 - 如何使用常量变量 [英] Haskell pattern matching - how to use constants variable

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

问题描述

我最好喜欢写这样的内容:

 
myValue1 = 1 :: Int
myValue2 = 2 :: Int

myFunc :: Int - > Bool
myFunc myValue1 = True
myFunc myValue2 = False

调用 myFunc myValue2 返回 True - 不是我想要的。我知道为什么会发生这种情况,但有没有办法在Haskell中表达这一点,而不诉诸C风格 #define 语句?

解决方案

好吧,Haskell不会统一这样的名字。这些新的'myValue1'和'2'标识符是您绑定的新变量。



大多数Haskelly方法都是使用强类型和模式匹配:

  data数值
= D1
| D2

myFunc :: Values - > Bool
myFunc D1 = True
myFunc D2 = False

给你一个静态的只保证1或2可以传递给myFunc,正确的符号匹配,你甚至可以通过派生Enum保留转换为整数。


I would ideally like to write something like this:

myValue1 = 1 :: Int
myValue2 = 2 :: Int

myFunc :: Int -> Bool
myFunc myValue1 = True
myFunc myValue2 = False

Calling myFunc myValue2 returns True - not what I intend. I know why this happens, but is there a way to express this in Haskell without resorting to C-style #define statements?

解决方案

Well, Haskell doesn't unify names like this. Those new 'myValue1' and '2' identifiers are new variables you're binding.

The most Haskelly way is to use strong types and pattern matching:

data Values
   = D1
   | D2

myFunc :: Values -> Bool
myFunc D1 = True
myFunc D2 = False

Giving you a static guarantee only "1" or "2" can be passed to myFunc, proper symbolic matching and you even retain conversion to integers by deriving Enum.

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

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