Pattern matching variables in a case statement in Haskell

前端 未结 3 1934
春和景丽
春和景丽 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:40

    See Don's answer for why. A common idiom for doing what you are trying to do is this:

    var1 = "abc"
    var2 = "def"
    
    foo x = case () of
        () | x == var1 -> "Fail"
           | x == var2 -> "Failzor"
           | otherwise -> "WIN"
    

    Of course in this case we would lose the case and just write the guards directly on the function:

    foo x | x == var1 = "Fail"
          | ...
    

    UPDATE

    These days the MultiWayIf extension does this with slightly less syntactic noise.

    {-# LANGUAGE MultiWayIf #-}
    
    foo x = if | x == var1 -> "Fail"
               | x == var2 -> "Failzor"
               | otherwise -> "WIN"
    

提交回复
热议问题