/
main.elm
155 lines (118 loc) · 3.08 KB
/
main.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
module Calc exposing (..)
-- exposes everything
import Html
-- shorten module name
import Html.Attributes as Attr
import Html.Events as Ev
type alias Button =
{ text : String
, message : Message
}
type alias Model =
{ acc : Float
, nextOp : Float -> Float
}
type Message
= NumberPressed Int
| OperatorPressed Operator
type Operator
= Plus
| Minus
| Divide
| Multiply
| Equals
| Comma
-- define type for `main` value
main : Program Never Model Message
main =
Html.beginnerProgram
-- identity == (\x -> x)
{ model = Model 0 identity
, view = view
, update = update
}
update : Message -> Model -> Model
update msg model =
case msg of
NumberPressed n ->
-- Model (model.acc * 10 + n) model.nextOp
-- is the same as below:
{ model | acc = model.acc * 10 + (toFloat n) }
OperatorPressed Equals ->
{ model
| acc = model.nextOp model.acc
, nextOp = identity
}
OperatorPressed Plus ->
{ model
| acc = 0
, nextOp = \x -> model.acc + model.nextOp x
}
OperatorPressed Multiply ->
{ model
| acc = 0
, nextOp = \x -> model.acc * model.nextOp x
}
OperatorPressed Minus ->
{ model
| acc = 0
, nextOp = \x -> model.acc - model.nextOp x
}
OperatorPressed Divide ->
{ model
| acc = 0
, nextOp = \x -> model.acc / model.nextOp x
}
_ ->
model
view : Model -> Html.Html Message
view model =
let
n n =
Button (toString n) (NumberPressed n)
o l o =
Button l (OperatorPressed o)
in
Html.div
[ Attr.style
[ ( "margin", "1rem" )
, ( "width", "10rem" )
]
]
[ display model.acc
, keyboard
[ [ n 7, n 8, n 9, o "*" Multiply ]
, [ n 4, n 5, n 6, o "/" Divide ]
, [ n 1, n 2, n 3, o "+" Plus ]
, [ n 0, o "," Comma, o "=" Equals, o "-" Minus ]
]
]
keyboard : List (List Button) -> Html.Html Message
keyboard buttons_ =
Html.div
[]
(List.map buttons buttons_)
buttons : List Button -> Html.Html Message
buttons labels =
Html.div []
(List.map button labels)
button : Button -> Html.Html Message
button button =
Html.button
[ Attr.style
[ ( "width", "2rem" )
, ( "height", "2rem" )
, ( "margin", "0 .5rem .5rem 0" )
]
, Ev.onClick button.message
]
[ Html.text button.text ]
display : Float -> Html.Html Message
display number =
Html.h1
[ Attr.style
[ ( "background", "lightgray" )
, ( "text-align", "right" )
]
]
[ Html.text (toString number) ]