Pattern matching variables in a case statement in Haskell

前端 未结 3 1925
春和景丽
春和景丽 2020-12-06 10:53

If I compare a string literal to a string literal using the case statement, I get the expected behavior: if they are the same - it matches, if they are not - it does not.

3条回答
  •  伪装坚强ぢ
    2020-12-06 11:23

    Pattern matching in Haskell binds new variables. So when you write:

    case x of
        y -> ...
    

    you have now bound a new variable 'y' to the value of 'x'. This is the trivial "pattern". You can see more clearly how the binding works when a constructor is involved:

    case x of 
        (a, b) -> ...
    

    Now a and b bind to components of the tuple. And so on for deconstructing and binding other data types. Thus, to match a string literal, you would write:

    case x of
        "def" -> ....
    

提交回复
热议问题