测试Haskell变量是否与用户定义的数据类型选项匹配 [英] Test if Haskell variable matches user-defined data type option
问题描述
$ p $
数据Token = NUM Int | ID字符串| EOF
我有一个类似于的功能:
doStuff list = let
(token,rest)= getToken list
in
....
所以我想在 ...
部分做的事是测试我得到的令牌是 NUM
或 INT
或 EOF
。我可以说标记== EOF
来测试这种情况,但是我找不到一种方法来测试标记是否为 NUM
或 INT
使用条件,因为标记==(NUM n)
和标记== NUM
都会导致错误。我知道我可以编写一个帮助函数来执行 ...
中的内容,并利用模式匹配,但这确实伤害了我正在做的事情的可读性,似乎应该有办法做这个检查。任何人都知道如何?
你想要一个 case
的情况标记NUM n - > foo n
ID s - > bar s
_ - > hoho
如果您单独定义了一个函数,那么这与模式匹配相同。 / p>
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?
You want a case
expression, like:
case token of
NUM n -> foo n
ID s -> bar s
_ -> hoho
That's the same sort of pattern matching as you'd get if you defined a function separately.
这篇关于测试Haskell变量是否与用户定义的数据类型选项匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!