Created
February 12, 2023 21:11
-
-
Save 3kezoh/a7145d67c60681f5db4cf85a2d0aa1d5 to your computer and use it in GitHub Desktop.
An elm program that calculates the average of input numbers separated by spaces
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
module Main exposing (..) | |
import Browser | |
import Html exposing (Html, div, input, text) | |
import Html.Attributes exposing (type_, value) | |
import Html.Events exposing (onInput) | |
-- MAIN | |
main : Program () Model Msg | |
main = | |
Browser.sandbox | |
{ init = init | |
, update = update | |
, view = view | |
} | |
-- MODEL | |
type alias Model = | |
{ grade : String } | |
init : Model | |
init = | |
Model "" | |
-- UPDATE | |
type Msg | |
= UpdateGrade String | |
update : Msg -> Model -> Model | |
update msg model = | |
case msg of | |
UpdateGrade grade -> | |
{ model | grade = grade } | |
-- VIEW | |
view : Model -> Html Msg | |
view model = | |
div [] | |
[ input [ type_ "text", onInput UpdateGrade, value model.grade ] [] | |
, viewGrades (getGrades model.grade) | |
] | |
viewGrades : List Float -> Html Msg | |
viewGrades grades = | |
case average grades of | |
Nothing -> | |
text "No grades" | |
Just float -> | |
text ("Average: " ++ String.fromFloat float) | |
-- HELPER | |
getGrades : String -> List Float | |
getGrades string = | |
List.filterMap String.toFloat (String.words string) | |
average : List Float -> Maybe Float | |
average floats = | |
if List.isEmpty floats then | |
Nothing | |
else | |
Just (List.sum floats / toFloat (List.length floats)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment