ジンジャー研究室

長めのつぶやき。難しいことは書きません。

Elm の update 関数を綺麗に書くための Tips

生活の知恵です。

No more Task.perform identity (Task.succeed Bar)

Bad

update msg model =
  case msg of
    Foo ->
      ( model
      , Task.perform identity (Task.succeed Bar)
      )

非同期にしたせいで2回レンダリングが走る。 Lazy を使えばある程度緩和できるが、できることなら無駄な処理を避けたい。

Good

update msg model =
  case msg of
    Foo ->
      update Bar model

update 関数をそのまま呼び出せばいい。

No more model, model_, model__, model___ ...

Bad

update msg model =
  case msg of
    Foo ->
      let
        (model_, cmd) =
          updateSomething "something" model

        (model__, cmd_) =
          updateAnother "another" model_
      in
        model__ ! [ cmd, cmd_ ]

どの model がなんだったか混乱する(実際これを書きながら間違えた)。

Good

update msg model =
  case msg of
    Foo -> 
      updateSomething "something" model
        |> andThen (updateAnother "another")


andThen f (model, msg) =
  let
    (newModel, newMsg) =
      f model
  in
    newModel ! [ msg, newMsg ]

ヘルパー関数 andThen でスッキリする。