Created
January 14, 2017 16:35
-
-
Save dirv/6737405e09e3b33d1d3a4b228e420b6f to your computer and use it in GitHub Desktop.
Coin Changer in Elm, half-way converted to Dict
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Dict | |
import Html exposing (..) | |
import Html.Attributes exposing (..) | |
import Html.Events exposing (onInput) | |
import String | |
main = | |
beginnerProgram { model = model, view = view, update = update } | |
-- MODEL | |
type alias Model = List Int | |
coins = Dict.fromList [ | |
(200, "£2"), | |
(100, "£1"), | |
(50, "50p"), | |
(20, "20p"), | |
(10, "10p"), | |
(5, "5p"), | |
(2, "2p"), | |
(1, "1p") | |
] | |
model : Model | |
model = [ 0 ] | |
-- UPDATE | |
amounts = (Dict.keys coins) |> List.reverse | |
convert : Int -> List Int -> List Int | |
convert n amounts = | |
case amounts of | |
[] -> [] | |
(c::cs) -> | |
if n >= c then | |
[ n//c ] ++ convert (n % c) cs | |
else | |
[ 0 ] ++ convert n cs | |
safeToInt : String -> Int | |
safeToInt text = | |
String.toInt text | |
|> Result.toMaybe | |
|> Maybe.withDefault 0 | |
type Msg = SetChange String | |
update : Msg -> Model -> Model | |
update (SetChange text) _ = | |
convert (text |> safeToInt) amounts | |
-- VIEW | |
coinOutput : Int -> (Int, String) -> Html Msg | |
coinOutput c (_,label) = li [] [toString c ++ " x " ++ label |> text] | |
view : Model -> Html Msg | |
view model = | |
div [] | |
[ input [ placeholder "Enter an amount in pence", onInput SetChange ] [] | |
, ul [] (List.map2 coinOutput model (Dict.toList coins |> List.reverse)) | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment