Skip to content

Instantly share code, notes, and snippets.

@edwardw
Created June 27, 2011 15:50
Show Gist options
  • Save edwardw/1049126 to your computer and use it in GitHub Desktop.
Save edwardw/1049126 to your computer and use it in GitHub Desktop.
Haskell surprised me again

This time it is case expression. I was looking for a way in haskell to define constants so I wrote this:

one = 1
two = 2
three = 3

which n =
  case n of
    one -> "one"
    two -> "two"
    three -> "three"
    _ -> "unknown"

Compiler warned me that there were overlapped patterns. I only realized what the warning meant after a while. one, two and three in case patterns must have shadowed the definitions at the beginning of the file. Using guards worked:

one = 1
two = 2
three = 3

which n =
  case n of
    _ | n == one -> "one"
    _ | n == two -> "two"
    _ | n == three -> "three"
    _ -> "unknown"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment