Skip to content
if and case
step 1/5

Reading — step 1 of 5

Learn

~1 min readControl Flow

Haskell's if is an expression — it always returns a value, so it must have both branches:

label :: Int -> String
label n = if n > 0 then "positive"
          else if n < 0 then "negative"
          else "zero"

case is more flexible — it pattern-matches:

grade :: Int -> Char
grade score = case score of
    s | s >= 90  -> 'A'      -- guard clause
      | s >= 80  -> 'B'
      | s >= 70  -> 'C'
      | otherwise -> 'F'

Most Haskell code uses function-clause pattern matching — much cleaner than case:

grade :: Int -> Char
grade s | s >= 90  = 'A'
        | s >= 80  = 'B'
        | s >= 70  = 'C'
        | otherwise = 'F'

otherwise is just a synonym for True. Falls through if all earlier guards fail.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…