-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMain05.elm
81 lines (66 loc) · 1.75 KB
/
Main05.elm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
module Main exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import String
type alias Model =
{ calories : Int
, input : Int
, error : Maybe String
}
initModel : Model
initModel =
-- Model 0 0 Nothing
{ calories = 0
, input = 0
, error = Nothing
}
type Msg
= AddCalorie
| Input String
| Clear
update : Msg -> Model -> Model
update msg model =
case msg of
AddCalorie ->
{ model
| calories = model.calories + model.input
, input = 0
}
Input val ->
case String.toInt val of
Ok input ->
{ model
| input = input
, error = Nothing
}
Err err ->
{ model
| input = 0
, error = Just err
}
Clear ->
initModel
view : Model -> Html Msg
view model =
div []
[ h3 [] [ text ("Total Calories: " ++ (toString model.calories)) ]
, input
[ type_ "text"
, onInput Input
, value
(if model.input == 0 then
""
else
toString model.input
)
]
[]
, div [] [ text (Maybe.withDefault "" model.error) ]
, button [ type_ "button", onClick AddCalorie ] [ text "Add" ]
, button [ type_ "button", onClick Clear ] [ text "Clear" ]
, p [] [ text (toString model) ]
]
main : Program Never Model Msg
main =
beginnerProgram { model = initModel, view = view, update = update }