Skip to content

Instantly share code, notes, and snippets.

@Ikechukwunwachukwu
Forked from mfonism/karlverter.elm
Created December 3, 2023 20:23
Show Gist options
  • Save Ikechukwunwachukwu/3dab1c55eafab373cbc060c487a22adc to your computer and use it in GitHub Desktop.
Save Ikechukwunwachukwu/3dab1c55eafab373cbc060c487a22adc to your computer and use it in GitHub Desktop.
Temperature converter (ELM)
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