Real World Haskell - 第3章 Part10 The case expression, Common beginner mistakes with patterns

Real World HaskellHaskell を継続的に勉強中。


Defining Types, Streamlining Functions

Chapter 3. Defining Types, Streamlining Functions

The case expression
  • case を使えば関数定義のときのようにパターンマッチできる
fromMaybe defval wrapped =
    case wrapped of
      Nothing     -> defval
      Just value  -> value
Common beginner mistakes with patterns
  • Incorrectly matching against a variable

これは誤り。

data Fruit = Apple | Orange

apple = "apple"

orange = "orange"        

whichFruit :: String -> Fruit

whichFruit f = case f of
                 apple  -> Apple
                 orange -> Orange

こう定義すべし。

betterFruit f = case f of
                  "apple"  -> Apple
                  "orange" -> Orange
  • Incorrectly matching against a variable

これは誤り。

bad_nodesAreSame (Node a _ _) (Node a _ _) = Just a
bad_nodesAreSame _            _            = Nothing

guards を使いましょう。(次回に続く)