Test if Haskell variable matches user-defined data type option

梦想与她 提交于 2020-01-02 04:29:11

问题


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?


回答1:


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.




回答2:


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 {} -> ...


来源:https://stackoverflow.com/questions/7897559/test-if-haskell-variable-matches-user-defined-data-type-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!