Generate JavaScript with great performance and no runtime exceptions
module Counter exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onClick)
-- MODEL
type alias Model =
Int
emptyModel : Model
emptyModel =
0
-- UPDATE
type Msg
= Decrement
| Increment
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Decrement ->
( model - 1
, Cmd.none
)
Increment ->
( model + 1
, Cmd.none
)
-- VIEW
view : Model -> Html Msg
view model =
div []
[ button [ onClick Decrement ] [ text "-" ]
, div [] [ text (toString model) ]
, button [ onClick Increment ] [ text "+" ]
]
Compile Error Vs Runtime Mistakes
Types 101
type Bool = False | True
type alias Name
= String
type UserType
= Anonymous
| Authenticated Name
| Premium Name Date
Cart example
Maybe values
type alias User =
{ avatarUrl : String
, name : String
}
emptyUser =
{ avatarUrl = ""
, name = ""
}
type alias Model =
{ user : User
}
emptyModel =
{ user = emptyUser
}
type alias Model =
{ user : Maybe User
}
emptyModel : Model
emptyModel =
{ user = Nothing
}
modelWithUser : Model
modelWithUser =
{ user = Just <| User "https://example.com/avatar" "amitaibu"
}
viewUser : Maybe User -> Html msg
viewUser mUser =
case mUser of
Nothing ->
text "Loading"
Just user ->
text user.name
type RemoteData e a
= NotAsked
| Loading
| Failure e
| Success a
type alias WebData a =
RemoteData Http.Error a
type alias Model =
{ user : WebData User
}
emptyModel =
{ user = NotAsked
}
debugUser =
{ user = Success <| User "https://example.com/avatar" "amitaibu"
}
viewUser : WebData User -> Html msg
viewUser webDataUser =
case webDataUser of
Success user ->
text user.name
Failure err ->
text "Something went wrong"
_ ->
text "Loading..."