Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Impure Elm Function #21

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions impure_elm_function/Main.elm
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
module Main exposing (main)

import Browser
import Html exposing (Html, button, div, text)
import Html.Events exposing (onClick)
import Json.Decode as D


type alias Model =
{ num : Float, obj : D.Value }


init : D.Value -> ( Model,Cmd Msg )
init flags =
({ num = 0, obj = flags }, Cmd.none)


type Msg
= Clicked


-- The impure function
generate : D.Value -> Float
generate =
D.decodeValue (D.field "n" D.float) >> Result.withDefault 0


update : Msg -> Model -> (Model,Cmd Msg)
update msg model =
case msg of
Clicked ->
( { model
| num = generate model.obj
}
,Cmd.none)


view : Model -> Html Msg
view model =
div []
[ button [ onClick Clicked ] [ text "generate" ]
, div [] [ text <| String.fromFloat model.num ]
]


main : Program D.Value Model Msg
main =
Browser.element
{ init = init
, view = view
, update = update
, subscriptions = always Sub.none
}
17 changes: 17 additions & 0 deletions impure_elm_function/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<html>
<head></head>
<body>
<main></main>
<script>
var obj = {
get n() {
return Math.random();
},
};
var app = Elm.Main.init({
node: document.querySelector('main'),
flags: obj,
});
</script>
</body>
</html>