LoginSignup
1
0

More than 5 years have passed since last update.

【Elm】パターンマッチとは何か?分岐と何が違うのか?

Last updated at Posted at 2018-06-01

パターンマッチ

パターンマッチはデータの構造通りに値を比較することが出来る。普通の条件分岐(if文)は値に比較をするだけで、データ構造のマッチングは行わない。

例えば以下のように値を扱える。

record = {a = 1, b = 2}

case record of
    { a, b } ->
        a + b

-- -> 3

個人的には配列を以下のように扱えるのが斬新だった。

-- String型のidをもつ任意のRecord型aをIdentifiable型と定義
type alias Identifiable a = { a | id : String } 

-- Identifiable型とその配列を引数として新たな配列をつくるupdateListを定義
updateList : Identifiable a -> List (Identifiable a) -> List (Identifiable a)
updateList e es =
  case es of
-- 配列の1番目の要素と2番目以降の要素でパターンマッチ
    h :: t ->
      if h.id == e.id 
        then
          e :: t
        else
          h :: (updateEpic e t)
    _ ->
      es ++ [e]
1
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
1
0