Skip to content

Instantly share code, notes, and snippets.

@agrafix
Created July 26, 2015 11:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agrafix/a267a7e0e34566aad829 to your computer and use it in GitHub Desktop.
Save agrafix/a267a7e0e34566aad829 to your computer and use it in GitHub Desktop.
My first Elm app
module Main where
import StartApp
import String
import Html
import Html.Events as Html
import Html.Attributes as Html
import Html.Shorthand exposing (..)
import Bootstrap.Html exposing (..)
import Html exposing (blockquote)
import Html exposing (Html, text, toElement, fromElement)
main =
StartApp.start
{ model = init
, update = update
, view = view
}
type Operation
= AddOp
| SubOp
runOp : Operation -> Int -> Int -> Int
runOp op a b =
case op of
AddOp -> a + b
SubOp -> a - b
type alias Model =
{ displayed : Int
, lastResult : Int
, op : Operation
}
init : Model
init =
{ displayed = 0
, lastResult = 0
, op = AddOp
}
type Action
= PressNumber Int
| Add
| Subtract
| Result
| Clear
| ClearAll
update : Action -> Model -> Model
update action model =
case action of
PressNumber i ->
let (Ok newNumber) = String.toInt (toString model.displayed ++ toString i)
in { model | displayed <- newNumber }
Add ->
{ model | displayed <- 0, lastResult <- model.displayed, op <- AddOp }
Subtract ->
{ model | displayed <- 0, lastResult <- model.displayed, op <- SubOp }
Result ->
{ model | displayed <- runOp model.op model.lastResult model.displayed, lastResult <- 0 }
Clear ->
{ model | displayed <- 0 }
ClearAll ->
{ model | displayed <- 0, lastResult <- 0 }
header : Html
header =
div' { class = "header clearfix "}
[ nav_ []
, h3' { class = "text-muted" } [ text "Elm Calculator" ]
]
view : Signal.Address Action -> Model -> Html
view address model =
let numBtn i =
colXs_ 3 [ btnDefault_ { btnParam | label <- Just (toString i) } address (PressNumber i) ]
opBtn desc op =
colXs_ 3 [ btnPrimary_ { btnParam | label <- Just desc } address op ]
in container_
[ header
, div' { class = "result" } [ text (toString model.displayed) ]
, div' { class = "num-pad "}
[ row_ [ numBtn 1, numBtn 2, numBtn 3, opBtn "+" Add ]
, row_ [ numBtn 4, numBtn 5, numBtn 6, opBtn "-" Subtract ]
, row_ [ numBtn 7, numBtn 8, numBtn 9, opBtn "=" Result ]
, row_ [ opBtn "Clear" Clear, opBtn "Clear All" ClearAll ]
]
]
@FranklinChen
Copy link

A small change is required now: import StartApp.Simple as StartApp.

Also, for reference, the following packages were used:

  • circuithub/elm-bootstrap-html
  • circuithub/elm-html-shorthand
  • elm-lang/core
  • evancz/elm-html
  • evancz/start-app

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