Created
November 5, 2023 15:54
-
-
Save mfonism/9ff40b4a020162dd39d5b493ebaeaf86 to your computer and use it in GitHub Desktop.
Temperature converter (ELM)
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 (main) | |
import Browser | |
import Html exposing (Html, div, h1, input, label, text) | |
import Html.Attributes exposing (value) | |
import Html.Events exposing (onInput) | |
main : Program () Model Msg | |
main = | |
Browser.sandbox | |
{ init = myInit | |
, view = myView | |
, update = myUpdate | |
} | |
-- MODEL | |
type alias Model = | |
{ fahrenheit : Float | |
, celsius : Float | |
} | |
myInit : Model | |
myInit = | |
{ fahrenheit = 0 | |
, celsius = -17.7778 | |
} | |
-- VIEW | |
myView : Model -> Html Msg | |
myView model = | |
div [] | |
[ h1 [] [ text "Temperature converter" ] | |
, div [] | |
[ label [] | |
[ text "Fahrenheit: " | |
, input | |
[ value (String.fromFloat model.fahrenheit) | |
, onInput UserEnteredFahrenheit | |
] | |
[] | |
] | |
] | |
, div [] | |
[ label [] | |
[ text "Celsius: " | |
, input | |
[ value (String.fromFloat model.celsius) | |
, onInput UserEnteredCelsius | |
] | |
[] | |
] | |
] | |
] | |
-- UPDATE | |
type Msg | |
= UserEnteredFahrenheit String | |
| UserEnteredCelsius String | |
myUpdate : Msg -> Model -> Model | |
myUpdate msg model = | |
case msg of | |
UserEnteredFahrenheit fahrenheitString -> | |
let | |
fahrenheitFloat = | |
case String.toFloat fahrenheitString of | |
Nothing -> | |
0 | |
Just float -> | |
float | |
in | |
{ model | |
| fahrenheit = fahrenheitFloat | |
, celsius = fahrenheitToCelsius fahrenheitFloat | |
} | |
UserEnteredCelsius celsiusString -> | |
let | |
celsiusFloat = | |
case String.toFloat celsiusString of | |
Nothing -> | |
0 | |
Just float -> | |
float | |
in | |
{ model | |
| celsius = celsiusFloat | |
, fahrenheit = celsiusToFahrenheit celsiusFloat | |
} | |
fahrenheitToCelsius : Float -> Float | |
fahrenheitToCelsius fahrenheit = | |
(fahrenheit - 32) * (5 / 9) | |
celsiusToFahrenheit : Float -> Float | |
celsiusToFahrenheit celsius = | |
(celsius * 9 / 5) + 32 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment