LoginSignup
2
1

More than 5 years have passed since last update.

【Elm】特定のフィールドを持つレコードをパターンマッチさせる

Posted at

Elmのパターンマッチ

関数型言語であるElmはパターンマッチが使える。
便利な使い方を教えてもらったのでメモ。
例えば、Int型のidを持つレコードを表す場合は以下のように定義する。

-- elmではtype aliasで任意の型定義をすることが出来る
type alias Identifiable a = { a | id : Int }

活用例

特定のidをもつレコードの値を入れ替える時には以下のような書き方が出来る。

type alias Record = 
  { id: Int
  , name: String
   -- 以下のようなフィールドがあってもマッチする。
   --, hogehoge : hogehoge
  }

preRecords : List Record
preRecords = 
  [ Record 1 "A"
  , Record 2 "B"
  , Record 8 "C"
  , Record 4 "D"
  ]


main =
  let 
    newRecord = 
      Record 8 "NEW!"

    postRecords= 
      updateRecord newRecord preRecords

  in
    postRecords
      |> toString
      |> text


type alias Identifiable a = { a | id : Int } 

updateRecord : Identifiable a -> List (Identifiable a) -> List (Identifiable a)
updateRecord e es =
  case es of
    -- 配列のheadとtailでパターンマッチ
    h :: t ->
      if h.id == e.id 
        then
          e :: t
        else
          h :: (updateRecord e t)
    _ ->
      es ++ [e]

2
1
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
2
1