Skip to content

Instantly share code, notes, and snippets.

@freakingawesome
Created May 24, 2016 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save freakingawesome/847dd0f6059738b95c81273c568b7067 to your computer and use it in GitHub Desktop.
Save freakingawesome/847dd0f6059738b95c81273c568b7067 to your computer and use it in GitHub Desktop.
import Html exposing (..)
import Html.App exposing (program)
import Html.Events exposing (onClick, on, targetValue)
import Html.Attributes exposing (..)
import Json.Decode as Json
import String
{-
Summary of changes since: https://gist.github.com/freakingawesome/2a021ddeaf0fb3592c4714885339ca2a
- Replaced hardcoded 10 with a multiplier value that is selected in a dropdown
- Removed `cost` field from Model in favor of a `calculateCost` function
-}
main =
program { init = (initialModel, Cmd.none), view = view, update = update, subscriptions = always Sub.none }
initialModel =
{ month = 0
, multiplier = 0
, email = "my@email.com"
}
intOption i =
let s = toString i
in option [value s ] [ text s ]
view : Model -> Html Msg
view model =
Html.div []
[ input [ placeholder "my@email.com" ] []
, select [ on "change" (Json.map MonthChanged targetValueIntDecoder) ]
(List.map intOption [0..12]) -- month selector
, select [ on "change" (Json.map MultiplierChanged targetValueIntDecoder) ]
(List.map intOption (List.map ((*) 10) [0..10]))
, Html.span [][text (toString <| calculateCost model)]
, button [ onClick Submit ] [text "Send"]
]
targetValueIntDecoder : Json.Decoder Int
targetValueIntDecoder =
targetValue `Json.andThen` \val ->
case String.toInt val of
Ok i -> Json.succeed i
Err err -> Json.fail err
calculateCost : Model -> Int
calculateCost m =
m.month * m.multiplier
type Msg
= Submit
| MonthChanged Int
| MultiplierChanged Int
type alias Model =
{ month : Int
, multiplier : Int
, email : String
}
update msg model =
case msg of
Submit ->
(model, Cmd.none)
MonthChanged month ->
({ model | month = month }, Cmd.none)
MultiplierChanged multiplier ->
({ model | multiplier = multiplier }, Cmd.none)
@smorele
Copy link

smorele commented May 24, 2016

thanks again :)

I had the idea to do:

actions can be Submit or Calculate
each time user change select values, it calls Calculate. When user click on the submit button it calls Submit

Then instead of having a function to manage each select, can I have an unique fonction ? This function is suppose to update model.month or model.multiplier then I thought it can be possible to do with an unique action.
For your information, my full example is here, it's a simple calculator supposed to estimate your project costs.
As you can see, I'm not really comfortable with elm and FP (and my English, sorry I'm French :)) but I really try to understand how do Elm and Haskell work (with http://learnyouahaskell.com/).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment