Skip to content

Instantly share code, notes, and snippets.

@3kezoh
Created February 12, 2023 21:11
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 3kezoh/a7145d67c60681f5db4cf85a2d0aa1d5 to your computer and use it in GitHub Desktop.
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
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