LoginSignup
3
0

More than 3 years have passed since last update.

Haskellことはじめ~パターンマッチ~

Posted at

Maybe値

  • Maybe値はJustまたはNothingのいずれかの値を返す
    例えば、null値が与えられて処理の続行が不可能な場合、Nothingを用いて処理落ちを防ぐことができる。

パターンマッチ

  • 値がパターンにマッチするかしないかを評価する
  • 関数として複数定義することで上から順番にパターンマッチの評価を行う
  • ワイルドカード_は必ずマッチする
  • 変数は必ずマッチする※パッチした上で変数に値を格納する
  • パターンマッチによって複合的な値から結果の値を取り出せる
sample.hs
-- パターンマッチの例
inc (Just x) = x + 1
inc Nothing = -1
-- 関数を複数定義したパターンマッチ
advance 'a' = 'b'
advance 'b' = 'c'
advance 'c' = 'd'
-- ワイルドカードを使ったパターンマッチ
advance _ = 'x'

-- 引数が0ならNothingをそうでなければJust値を返すnotZero関数を定義
notZero 0 = Nothing
notZero x = Just x

実行結果

# パターンマッチの例
*Main> inc (Just 9)
10
*Main> inc Nothing
-1

# 関数を複数定義したパターンマッチ
*Main> advance 'a'
'b'
*Main> advance 'b'
'c'
# ワイルドカードを使ったパターンマッチ
*Main> advance '0'
'x'

# 引数が0ならNothingをそうでなければJust値を返すnotZero関数を定義
*Main> notZero 0
Nothing
*Main> notZero 1
Just 1

ガード

  • if elseみたいなやつは別の記法が用意されているらしい
sample.hs
-- ガードを使わないバージョン
-- 0以上だったら平方根を返す関数safeSqrtを定義
safeSqrt x = sqrtBool (x >= 0) x
-- True ならsqrtを実行
sqrtBool True x = Just (sqrt x)
sqrtBool False _ = Nothing

-- ガードを使って実装するとこんなにシンプルに
safaSqrtG x
  |  x >= 0 = Just (sqrt x)
  |  otherwise = Nothing

-- ガードの構文
関数名
 | 条件1 = 処理1 -- if
 | 条件2 = 処理2 -- else if
 | otherwise = それ以外の場合の処理 -- else

実行結果

# パターンマッチで実装
*Main> safeSqrt (5)
Just 2.23606797749979
*Main> safeSqrt (-5)
Nothing

# ガードを使って実装
*Main> safaSqrtG (5)
Just 2.23606797749979
*Main> safaSqrtG (-5)
Nothing
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0