Reputation:
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?
Upvotes: 5
Views: 3724
Reputation: 152707
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.
case token of
NUM {} -> ...
ID {} -> ...
EOF {} -> ...
Upvotes: 8
Reputation: 8266
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.
Upvotes: 12