Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Elmのさわれる副作用

 Elmのさわれる副作用

M3 tech meetup! #2 ~フロントエンドの副作用~ にて
http://m3-engineer.connpass.com/event/33802/

Yosuke Torii

July 14, 2016
Tweet

More Decks by Yosuke Torii

Other Decks in Technology

Transcript

  1. main = span [class "message"] [text "Hello, World!"] ・関数型言語 ・静的型付き言語

    ・ JavaScript にコンパイルされる ・ 2012 年誕生 Elm is 何?
  2. Elm = 言語 + フレームワーク ・ Virtual DOM 採用 ・

    Redux を生み出すきっかけになった  「 Elm Architecture 」 ・ http://guide.elm-lang.org/
  3. Elm = 言語 + フレームワーク ・ Virtual DOM 採用 ・

    Redux を生み出すきっかけになった  「 Elm Architecture 」 ・ http://guide.elm-lang.org/ React.js/Flux を追っている人なら Elm を楽しめるはず!
  4. add() は number を返す関数 function add(a, b): number { callCount++;

    sendLogToServer('Hey'); clearLocalStorage(); return a + b; }
  5. add() は number を返す関数 function add(a, b): number { callCount++;

    sendLogToServer('Hey'); clearLocalStorage(); fireMissiles(); return a + b; }
  6. Elm で副作用を扱う方法 submit : State -> (State, Cmd Msg) submit

    state = ( { state | inputField = “” , disableSend = True } , send state.inputField )
  7. Elm で副作用を扱う方法 submit : State -> (State, Cmd Msg) submit

    state = ( { state | inputField = “” , disableSend = True } , send state.inputField )
  8. 型に書いていないことをすると… submit : State -> State submit state = (

    { state | inputField = “” , disableSend = True } , send state.inputField )
  9. -- TYPE MISMATCH ----------------------------------------------- The type annotation for `update` does

    not match its definition. 50| update : Msg -> Model -> Model ^^^^^^^^^^^^^^^^^^^^^ The type annotation is saying: Msg -> Model -> { disableSend : Bool, inputField : String } But I am inferring that the definition has this type: Msg -> Model -> ( Model, Cmd a )
  10. あえて返さないでみる submit : State -> State submit model = let

    unused = send model.inputField in { model | inputField = “” , disableSend = True }
  11. 副作用を起こす関数はどれ? parse(s: string): AST format(s: string): string update(model: Model, action:

    Action): Model register(model: Model, user: User): Model makeURL(model: Model): string
  12. parse : String → AST format : String → String

    update : Model → Action → Model register : Model → User → Model makeURL : Model → (String, Cmd Msg) 副作用を起こす関数はどれ?
  13. 設計上、副作用を禁止したい http://redux.js.org/docs/basics/Reducers.html ”Given the same arguments, it should calculate the

    next state and return it. No surprises. No side effects. No API calls. No mutations. Just a calculation.” var newState = reduce(oldState, action);
  14. しかし、保証はできない var newState = reduce(oldState, action); ”Given the same arguments,

    it should calculate the next state and return it. No surprises. No side effects. No API calls. No mutations. Just a calculation.” http://redux.js.org/docs/basics/Reducers.html
  15. Elm なら型で拘束できる update : Msg → Model → (Model, Cmd

    Msg) view : Model → Html Msg update 関数では副作用を起こせる view 関数では絶対に副作用を起こせない