• 追加された行はこの色です。
  • 削除された行はこの色です。
#author("2019-11-10T07:09:49+00:00","default:sagasite","sagasite")
#author("2019-11-10T07:53:03+00:00","default:sagasite","sagasite")
[[Program]] > [[JavaScript]] > [[AltJS]] > [[Elm]] > [[Elmガイド>Elm_guide]] > [[Elmアーキテクチャー>Elm_guide_The-Elm-Architecture]] > ボタン

#norelated
#contents

//----------------------------------------
*ボタン [#c13b2ac0]
-ボタン · An Introduction to Elm https://guide.elm-lang.jp/architecture/buttons.html

#code(haskell){{
import Browser
import Html exposing (Html, button, div, text)
import Html.Events exposing (onClick)


main =
  Browser.sandbox { init = init, update = update, view = view }


-- MODEL

type alias Model = Int

init : Model
init =
  0


-- UPDATE

type Msg = Increment | Decrement

update : Msg -> Model -> Model
update msg model =
  case msg of
    Increment ->
      model + 1

    Decrement ->
      model - 1


-- VIEW

view : Model -> Html Msg
view model =
  div []
    [ button [ onClick Decrement ] [ text "-" ]
    , div [] [ text (String.fromInt model) ]
    , button [ onClick Increment ] [ text "+" ]
    ]
}}

パッと見、雰囲気だけは伝わりますが、個々の部分を見ていくと、よく分からないコードですね。

UPDATEやVIEWの部分を見ると、関数の宣言方法が何となく分かります。
-関数の型注釈を書いてから、関数を書く。
--型注釈は、「関数名:引数の型 -> 戻り値の型」という形で、引数の型は複数書ける。
--関数は、「関数名 引数 = 関数の本体」という形で書ける。(これはすでに学習済みの項目)

*練習問題 [#j76fd44c]
>練習問題: The Elm Architectureが優れていることの一つに、プロダクトに変更が必要な場合はとても簡単に拡張できることが挙げられます。あなたのプロダクトマネージャが"reset"機能を思い付いたとしましょう。新しいボタンはカウンタを0にリセットします。
>この機能を追加するにはMsg型の実装部分にもどってもう一つの可能性のResetを追加しましょう。メッセージを受け取ったときに何をすべきかをupdate関数に記述して下さい。最後はviewにボタンを追加して下さい。
それでは、"reset"機能を実装してみましょう!

適当に勘でやったらうまくいった!

#code(haskell){{
-- UPDATE

type Msg
  = Increment
  | Decrement
  | Reset


update : Msg -> Model -> Model
update msg model =
  case msg of
    Increment ->
      model + 1

    Decrement ->
      model - 1
    
    Reset -> 
      model - model
      

-- VIEW

view : Model -> Html Msg
view model =
  div []
    [ button [ onClick Decrement ] [ text "-" ]
    , div [] [ text (String.fromInt model) ]
    , button [ onClick Increment ] [ text "+" ]
    , div [] []
    , button [ onClick Reset ] [ text "Reset" ]
    ]
}}

-Msg型に「Reset」も追加。
-case式に「Reset」も追加。
--最初model = 0にしたら、再代入不可のエラーになったけど、model - modelに変えたらうまくいった。
 -- UNEXPECTED EQUALS ------------------------------------------- Jump To Problem
 
 I was not expecting to see this equals sign:
 
 55|       model = 0
                 ^
 Maybe you want == instead? To check if two values are equal?
 
 Note: I may be getting confused by your indentation. I think I am still parsing
 the `update` definition. Is this supposed to be part of a definition after that?
 If so, the problem may be a bit before the equals sign. I need all definitions
 to be indented exactly the same amount, so the problem may be that this new
 definition has too many spaces in front of it.

-view関数に「onClick Reset」のボタンも追加。
--改行の目的で「, div [] []」も追加してみた。

自分なりの工夫は、model - modelという計算式を入れたことかな。
本当はどうやるのがスマートなのだろう?


トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS