测试 Haskell 变量是否与用户定义的数据类型选项匹配
所以我有一个类似的数据类型:
data Token = NUM Int | ID String | EOF
我有一个类似的函数:
doStuff list = let
(token, rest) = getToken list
in
....
所以我想在 ...
部分做的是测试我得到的令牌是否是 NUM
或 INT
或 EOF
。我可以说 token==EOF
来测试这种情况,但我无法找到一种方法来测试令牌是 NUM
还是 INT< /code> 使用条件,因为
token==(NUM n)
和 token==NUM
都会导致错误。我知道我可以编写一个辅助函数来执行 ...
中的操作并利用模式匹配,但这确实损害了我正在做的事情的可读性,而且似乎在那里应该是进行此检查的一种方法。有人知道怎么做吗?
So I have a data type sort of like:
data Token = NUM Int | ID String | EOF
and I have a function sort of like:
doStuff list = let
(token, rest) = getToken list
in
....
So what I want to do in the ...
part is test if the token I got is a NUM
or INT
or EOF
. I can say token==EOF
to test for that case, but I can't figure out a way to test if the token is a NUM
or INT
using a conditional, since token==(NUM n)
and token==NUM
both result in errors. I know that I could write a helper function to do the stuff in the ...
and take advantage of pattern matching, but that really hurts the readability of what I'm doing, and it seems like there should be a way to do this check. Anyone know how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要一个
case
表达式,例如:这与单独定义函数时获得的模式匹配类型相同。
You want a
case
expression, like:That's the same sort of pattern matching as you'd get if you defined a function separately.
一个可爱的技巧是使用记录语法。这种方法的优点是,即使特定构造函数的参数数量发生变化,它也能继续工作。请注意,数据类型本身无需使用记录语法来声明即可利用此技巧。
One cute trick for this is to use record syntax. The advantage of this approach is that it keeps working even if the number of arguments to a particular constructor changes. Note that the data type itself need not be declared using record syntax to take advantage of this trick.