### Basic Browser.application Example Source: https://guide.elm-lang.org/webapps/navigation A foundational example of a Browser.application program in Elm. This setup includes the main function, model definition, init, update, subscriptions, and view functions, demonstrating how to handle URL changes and link clicks. ```elm import Browser import Browser.Navigation as Nav import Html exposing (..) import Html.Attributes exposing (..) import Url -- MAIN main : Program () Model Msg main = Browser.application { init = init , view = view , update = update , subscriptions = subscriptions , onUrlChange = UrlChanged , onUrlRequest = LinkClicked } -- MODEL type alias Model = { key : Nav.Key , url : Url.Url } init : () -> Url.Url -> Nav.Key -> ( Model, Cmd Msg ) init flags url key = ( Model key url, Cmd.none ) -- UPDATE type Msg = LinkClicked Browser.UrlRequest | UrlChanged Url.Url update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of LinkClicked urlRequest -> case urlRequest of Browser.Internal url -> ( model, Nav.pushUrl model.key (Url.toString url) ) Browser.External href -> ( model, Nav.load href ) UrlChanged url -> ( { model | url = url } , Cmd.none ) -- SUBSCRIPTIONS subscriptions : Model -> Sub Msg subscriptions _ = Sub.none -- VIEW view : Model -> Browser.Document Msg view model = { title = "URL Interceptor" , body = [ text "The current URL is: " , b [] [ text (Url.toString model.url) ] , ul [] [ viewLink "/home" , viewLink "/profile" , viewLink "/reviews/the-century-of-the-self" , viewLink "/reviews/public-opinion" , viewLink "/reviews/shah-of-shahs" ] ] } viewLink : String -> Html msg viewLink path = li [] [ a [ href path ] [ text path ] ] ``` -------------------------------- ### Making an HTTP GET Request Source: https://guide.elm-lang.org/effects/http Use `Http.get` in your `init` function to fetch data when the application starts. Specify the URL and how to expect the response, linking it to a message type. ```elm import Http -- MAIN main = Browser.element { init = init , update = update , subscriptions = subscriptions , view = view } -- MODEL type Model = Failure | Loading | Success String init : () -> (Model, Cmd Msg) init _ = ( Loading, Http.get { url = "https://elm-lang.org/assets/public-opinion.txt", expect = Http.expectString GotText } ) -- UPDATE type Msg = GotText (Result Http.Error String) update : Msg -> Model -> (Model, Cmd Msg) update msg model = case msg of GotText result -> case result of Ok fullText -> (Success fullText, Cmd.none) Err _ -> (Failure, Cmd.none) -- SUBSCRIPTIONS subscriptions : Model -> Sub Msg subscriptions model = Sub.none -- VIEW view : Model -> Html Msg view model = case model of Failure -> text "I was unable to load your book." Loading -> text "Loading..." Success fullText -> pre [] [ text fullText ] ``` -------------------------------- ### Initialize Elm Project and Install Packages Source: https://guide.elm-lang.org/effects Use these terminal commands to initialize a new Elm project and install necessary packages like elm/http and elm/random. ```bash elm init elm install elm/http elm install elm/random ``` -------------------------------- ### Digital Clock Example with Time Subscriptions Source: https://guide.elm-lang.org/effects/time This is a complete example of a digital clock that updates every second. It uses Time.Posix for storing time and Time.Zone for displaying it in the user's local time. The `subscriptions` function is key to getting regular time updates. ```elm import Browser import Html exposing (..) import Task import Time -- MAIN main = Browser.element { init = init , view = view , update = update , subscriptions = subscriptions } -- MODEL type alias Model = { zone : Time.Zone , time : Time.Posix } init : () -> (Model, Cmd Msg) init _ = ( Model Time.utc (Time.millisToPosix 0) , Task.perform AdjustTimeZone Time.here ) -- UPDATE type Msg = Tick Time.Posix | AdjustTimeZone Time.Zone update : Msg -> Model -> (Model, Cmd Msg) update msg model = case msg of Tick newTime -> ({ model | time = newTime }, Cmd.none) AdjustTimeZone newZone -> ({ model | zone = newZone }, Cmd.none) -- SUBSCRIPTIONS subscriptions : Model -> Sub Msg subscriptions model = Time.every 1000 Tick -- VIEW view : Model -> Html Msg view model = let hour = String.fromInt (Time.toHour model.zone model.time) minute = String.fromInt (Time.toMinute model.zone model.time) second = String.fromInt (Time.toSecond model.zone model.time) in h1 [] [ text (hour ++ ":" ++ minute ++ ":" ++ second) ] ``` -------------------------------- ### Start Elm Reactor Source: https://guide.elm-lang.org/install/elm Launch the Elm Reactor development server. This command starts a local server at `http://localhost:8000` for live previewing Elm files. ```bash elm reactor ``` -------------------------------- ### List.length Usage Examples Source: https://guide.elm-lang.org/types/reading_types Demonstrates List.length with different list types, showing that the type variable 'a' can be any type. ```elm List.length [1,1,2,3,5,8] 6 : Int ``` ```elm List.length [ "a", "b", "c" ] 3 : Int ``` ```elm List.length [ True, False ] 2 : Int ``` -------------------------------- ### Negate Function Usage Examples Source: https://guide.elm-lang.org/types/reading_types Provides examples of using the negate function with different numeric types. ```elm negate 3.1415 ``` ```elm negate (round 3.1415) ``` ```elm negate "hi" ``` -------------------------------- ### Parse Routes with Query Parameters using Url.Parser.Query Source: https://guide.elm-lang.org/webapps/url_parsing Extend URL parsing to include query parameters like `?q=seiza` by importing and using `Url.Parser.Query`. This example defines parsers for blog posts and blog overviews with optional query parameters. ```elm import Url.Parser exposing (Parser, (), (), int, map, oneOf, s, string) import Url.Parser.Query as Query type Route = BlogPost Int String | BlogQuery (Maybe String) routeParser : Parser (Route -> a) a routeParser = oneOf [ map BlogPost (s "blog" int string) , map BlogQuery (s "blog" Query.string "q") ] -- /blog/14/whale-facts ==> Just (BlogPost 14 "whale-facts") -- /blog/14 ==> Nothing -- /blog/whale-facts ==> Nothing -- /blog/ ==> Just (BlogQuery Nothing) -- /blog ==> Just (BlogQuery Nothing) -- /blog?q=chabudai ==> Just (BlogQuery (Just "chabudai")) -- /blog/?q=whales ==> Just (BlogQuery (Just "whales")) -- /blog/?query=whales ==> Just (BlogQuery Nothing) ``` -------------------------------- ### Install Elm Packages Source: https://guide.elm-lang.org/install/elm Add external packages to your project. These commands fetch and integrate specified packages, updating your `elm.json` file. ```bash elm install elm/http ``` ```bash elm install elm/json ``` -------------------------------- ### Elm Counter Example Source: https://guide.elm-lang.org/ A basic Elm program demonstrating The Elm Architecture for a simple counter. It initializes a model, defines messages for increment/decrement, and provides a view function to render the UI. ```elm import Browser import Html exposing (Html, button, div, text) import Html.Events exposing (onClick) main = Browser.sandbox { init = 0, update = update, view = view } type Msg = Increment | Decrement update msg model = case msg of Increment -> model + 1 Decrement -> model - 1 view model = div [] [ button [ onClick Decrement ] [ text "-" ] , div [] [ text (String.fromInt model) ] , button [ onClick Increment ] [ text "+" ] ] ``` -------------------------------- ### Dice Rolling App Example Source: https://guide.elm-lang.org/effects/random This is a complete example of a simple dice rolling application in Elm. It demonstrates how to use `Random.generate` to create a command that produces a random integer between 1 and 6. ```elm import Browser import Html exposing (..) import Html.Events exposing (..) import Random -- MAIN main = Browser.element { init = init , update = update , subscriptions = subscriptions , view = view } -- MODEL type alias Model = { dieFace : Int } init : () -> (Model, Cmd Msg) init _ = ( Model 1 , Cmd.none ) -- UPDATE type Msg = Roll | NewFace Int update : Msg -> Model -> (Model, Cmd Msg) update msg model = case msg of Roll -> ( model , Random.generate NewFace (Random.int 1 6) ) NewFace newFace -> ( Model newFace , Cmd.none ) -- SUBSCRIPTIONS subscriptions : Model -> Sub Msg subscriptions model = Sub.none -- VIEW view : Model -> Html Msg view model = div [] [ h1 [] [ text (String.fromInt model.dieFace) ] , button [ onClick Roll ] [ text "Roll" ] ] ``` -------------------------------- ### Example JSON with Name and Age Source: https://guide.elm-lang.org/effects/json This example shows a simple JSON object with string and integer fields. Elm decoders can be defined to extract specific fields and their types. ```json { "name": "Tom", "age": 42 } ``` -------------------------------- ### Using Html.lazy for optimization Source: https://guide.elm-lang.org/optimization/lazy This example shows how to use `Html.lazy` to defer the creation of virtual DOM nodes. It takes a function and its arguments, creating a lazy node that only generates the virtual DOM when necessary. ```elm lazy : (a -> Html msg) -> a -> Html msg ``` ```elm lazy viewChairAlts ["seiza","chabudai"] ``` -------------------------------- ### Parse URL Fragments with Url.Parser Source: https://guide.elm-lang.org/webapps/url_parsing Handle URL fragments (the part after '#') using the `fragment` parser from `Url.Parser`. This example parses documentation paths that include optional fragments. ```elm type alias Docs = (String, Maybe String) docsParser : Parser (Docs -> a) a docsParser = map Tuple.pair (string fragment identity) -- /Basics ==> Just ("Basics", Nothing) -- /Maybe ==> Just ("Maybe", Nothing) -- /List ==> Just ("List", Nothing) -- /List#map ==> Just ("List", Just "map") -- /List# ==> Just ("List", Just "") -- /List/map ==> Nothing -- / ==> Nothing ``` -------------------------------- ### List.reverse Usage Examples Source: https://guide.elm-lang.org/types/reading_types Shows List.reverse with different list types, demonstrating that the type variable 'a' determines the type of both the input and output lists. ```elm List.reverse [ "a", "b", "c" ] ["c","b","a"] : List String ``` ```elm List.reverse [ True, False ] [False,True] : List Bool ``` -------------------------------- ### Full Elm Form Example Source: https://guide.elm-lang.org/architecture/forms This snippet shows a complete Elm program for a form with name, password, and password confirmation fields, including basic validation. It requires the Browser, Html, and Html.Events modules. ```elm import Browser import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (onInput) -- MAIN main = Browser.sandbox { init = init, update = update, view = view } -- MODEL type alias Model = { name : String , password : String , passwordAgain : String } init : Model init = Model "" "" "" -- UPDATE type Msg = Name String | Password String | PasswordAgain String update : Msg -> Model -> Model update msg model = case msg of Name name -> { model | name = name } Password password -> { model | password = password } PasswordAgain password -> { model | passwordAgain = password } -- VIEW view : Model -> Html Msg view model = div [] [ viewInput "text" "Name" model.name Name , viewInput "password" "Password" model.password Password , viewInput "password" "Re-enter Password" model.passwordAgain PasswordAgain , viewValidation model ] viewInput : String -> String -> String -> (String -> msg) -> Html msg viewInput t p v toMsg = input [ type_ t, placeholder p, value v, onInput toMsg ] [] viewValidation : Model -> Html msg viewValidation model = if model.password == model.passwordAgain then div [ style "color" "green" ] [ text "OK" ] else div [ style "color" "red" ] [ text "Passwords do not match!" ] ``` -------------------------------- ### Example JSON Structure Source: https://guide.elm-lang.org/effects/json This is an example of the JSON structure returned by the random quotes API. Elm decoders are used to parse this data safely. ```json { "quote": "December used to be a month but it is now a year", "source": "Letters from a Stoic", "author": "Seneca", "year": 54 } ``` -------------------------------- ### Get Help for Elm Commands Source: https://guide.elm-lang.org/install/elm Access help information for the Elm compiler and its subcommands. Use `elm --help` for general assistance or `elm --help` for specific command details. ```bash elm --help ``` ```bash elm make --help ``` ```bash elm repl --help ``` -------------------------------- ### List Manipulation in Elm Source: https://guide.elm-lang.org/core_language Work with ordered collections of same-typed values using functions from the `List` module. Examples include checking emptiness, getting length, reversing, and sorting. ```Elm names = [ "Alice", "Bob", "Chuck" ] ``` ```Elm List.isEmpty names ``` ```Elm List.length names ``` ```Elm List.reverse names ``` ```Elm numbers = [4,3,2,1] ``` ```Elm List.sort numbers ``` ```Elm increment n = n + 1 ``` ```Elm List.map increment numbers ``` -------------------------------- ### Custom Type Cases (Color) Source: https://guide.elm-lang.org/appendix/types_as_bits Demonstrates assigning numerical values to cases of a custom type, enabling their representation using bits. This example uses a simple Color type. ```elm type Color = Red | Yellow | Green ``` -------------------------------- ### Elm Initial Model Value Source: https://guide.elm-lang.org/architecture/buttons Sets the starting state for the application's model. For the counter, it begins at zero. ```elm init : Model init = 0 ``` -------------------------------- ### Modeling Friend Data with Custom Types Source: https://guide.elm-lang.org/error_handling/maybe This example demonstrates a more precise way to model friend data using custom types, distinguishing between having only a name and having a name with additional information. This approach eliminates ambiguity about missing data. ```elm type Friend = Less String | More String Info type alias Info = { age : Int , height : Float , weight : Float } ``` -------------------------------- ### Modeling Friend Data with Maybe Source: https://guide.elm-lang.org/error_handling/maybe This example shows how to model friend data using the Maybe type for optional fields like age, height, and weight. Consider if a custom type would be more precise for your application's logic. ```elm type alias Friend = { name : String , age : Maybe Int , height : Maybe Float , weight : Maybe Float } ``` -------------------------------- ### Fetch and Decode Random Quotes in Elm Source: https://guide.elm-lang.org/effects/json This example demonstrates fetching JSON data from an API and decoding it into a structured Elm type. It handles loading, success, and failure states, and allows users to request more data. ```elm import Browser import Html exposing (..) import Html.Attributes exposing (style) import Html.Events (..) import Http import Json.Decode exposing (Decoder, map4, field, int, string) -- MAIN main = Browser.element { init = init , update = update , subscriptions = subscriptions , view = view } -- MODEL type Model = Failure | Loading | Success Quote type alias Quote = { quote : String , source : String , author : String , year : Int } init : () -> (Model, Cmd Msg) init _ = (Loading, getRandomQuote) -- UPDATE type Msg = MorePlease | GotQuote (Result Http.Error Quote) update : Msg -> Model -> (Model, Cmd Msg) update msg model = case msg of MorePlease -> (Loading, getRandomQuote) GotQuote result -> case result of Ok quote -> (Success quote, Cmd.none) Err _ -> (Failure, Cmd.none) -- SUBSCRIPTIONS subscriptions : Model -> Sub Msg subscriptions model = Sub.none -- VIEW view : Model -> Html Msg view model = div [] [ h2 [] [ text "Random Quotes" ] , viewQuote model ] viewQuote : Model -> Html Msg viewQuote model = case model of Failure -> div [] [ text "I could not load a random quote for some reason. " , button [ onClick MorePlease ] [ text "Try Again!" ] ] Loading -> text "Loading..." Success quote -> div [] [ button [ onClick MorePlease, style "display" "block" ] [ text "More Please!" ] , blockquote [] [ text quote.quote ] , p [ style "text-align" "right" ] [ text "— " , cite [] [ text quote.source ] , text (" by " ++ quote.author ++ " (" ++ String.fromInt quote.year ++ ")") ] ] -- HTTP getRandomQuote : Cmd Msg getRandomQuote = Http.get { url = "https://elm-lang.org/api/random-quotes" , expect = Http.expectJson GotQuote quoteDecoder } quoteDecoder : Decoder Quote quoteDecoder = map4 Quote (field "quote" string) (field "source" string) (field "author" string) (field "year" int) ``` -------------------------------- ### Perform Task to Get Time Zone Source: https://guide.elm-lang.org/effects/time Use `Task.perform` to command the runtime to provide the `Time.Zone` where the code is executing. Refer to the `Task` documentation for a deeper understanding. ```elm Task.perform AdjustTimeZone Time.here ``` -------------------------------- ### Initialize an Elm Project Source: https://guide.elm-lang.org/install/elm Run this command to create a new Elm project. It generates an `elm.json` file and a `src/` directory. ```bash elm init ``` -------------------------------- ### Initial State and Commands Source: https://guide.elm-lang.org/effects/http The `init` function can return both an initial model and a command. This command, like `Http.get`, will eventually produce a message that is processed by the `update` function. ```elm init : () -> (Model, Cmd Msg) init _ = ( Loading, Http.get { url = "https://elm-lang.org/assets/public-opinion.txt", expect = Http.expectString GotText } ) ``` -------------------------------- ### Setting up Time Subscriptions Source: https://guide.elm-lang.org/effects/time This function sets up a subscription to receive time updates. `Time.every` takes an interval in milliseconds and a function to convert the current time into a message. ```elm subscriptions : Model -> Sub Msg subscriptions model = Time.every 1000 Tick ``` -------------------------------- ### Creating User Records with Maybe Age Source: https://guide.elm-lang.org/error_handling/maybe Shows how to create `User` records, one with `Nothing` for age and another with `Just` an integer age. This illustrates the practical application of optional fields. ```elm sue : User sue = { name = "Sue", age = Nothing } tom : User tom = { name = "Tom", age = Just 24 } ``` -------------------------------- ### Helper Function for Partial Application Source: https://guide.elm-lang.org/appendix/function_types Demonstrates creating a top-level helper function to encapsulate partial application logic, improving readability and testability. ```elm -- List.map reduplicate ["ha","choo"] reduplicate : String -> String reduplicate string = String.repeat 2 string ``` -------------------------------- ### Elm Model Definition Source: https://guide.elm-lang.org/architecture/buttons Defines the data structure for the application's state. In this counter example, the model is a simple integer. ```elm type alias Model = Int ``` -------------------------------- ### Navigate to Desktop in Terminal Source: https://guide.elm-lang.org/install/elm Change the current directory to your desktop. Use the appropriate command for your operating system. ```bash # Mac and Linux cd ~/Desktop ``` ```bash # Windows (but with filled in with your user name) cd C:\Users\\Desktop ``` -------------------------------- ### Function Application with Type Matching Source: https://guide.elm-lang.org/types/reading_types Demonstrates how providing the correct argument type to a function results in the expected output type. ```Elm String.length "Supercalifragilisticexpialidocious" : Int ``` -------------------------------- ### Defining Functions with Type Annotations Source: https://guide.elm-lang.org/types/reading_types Illustrates how to explicitly define the types for function arguments and return values using type annotations. ```Elm half : Float -> Float half n = n / 2 ``` ```Elm hypotenuse : Float -> Float -> Float hypotenuse a b = sqrt (a^2 + b^2) ``` ```Elm checkPower : Int -> String checkPower powerLevel = if powerLevel > 9000 then "It's over 9000!!!" else "Meh" ``` -------------------------------- ### Decode Nested JSON with map4 Source: https://guide.elm-lang.org/effects/json Use `map4` to decode a JSON object with nested structures. This example decodes a `Quote` type which includes a nested `Person` type. ```elm import Json.Decode exposing (Decoder, map2, map4, field, int, string) type alias Quote = { quote : String , source : String , author : Person , year : Int } quoteDecoder : Decoder Quote quoteDecoder = map4 Quote (field "quote" string) (field "source" string) (field "author" personDecoder) (field "year" int) type alias Person = { name : String , age : Int } personDecoder : Decoder Person personDecoder = map2 Person (field "name" string) (field "age" int) ``` -------------------------------- ### Elm Compiler Type Mismatch Error Source: https://guide.elm-lang.org/types This is an example of a compiler error message in Elm. It indicates a type mismatch because a record field name was misspelled, preventing the program from running. ```elm -- TYPE MISMATCH --------------------------------------------------------------- The argument to function `toFullName` is causing a mismatch. 6│ toFullName { fistName = "Hermann", lastName = "Hesse" } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Function `toFullName` is expecting the argument to be: { …, firstName : … } But it is: { …, fistName : … } Hint: I compared the record fields and found some potential typos. firstName <-> fistName ``` -------------------------------- ### Basic Function Type Signatures Source: https://guide.elm-lang.org/appendix/function_types Illustrates the type signatures for functions like String.repeat and String.join, showing multiple arrows indicating curried arguments. ```elm String.repeat : Int -> String -> String String.join : String -> List String -> String ``` -------------------------------- ### Initializing Elm with Flags in HTML Source: https://guide.elm-lang.org/interop/flags Pass initial data to your Elm application by providing a `flags` argument to `Elm.Main.init()` in your HTML. Any JSON-decodable JavaScript value can be used as a flag. ```html Main
``` -------------------------------- ### Using Html.keyed for Lists Source: https://guide.elm-lang.org/optimization/keyed This snippet demonstrates how to use `Keyed.node` to render a list of items with unique keys. Each item is associated with a key (e.g., `president.name`) and uses `lazy` to defer rendering until necessary. ```elm import Html exposing (..) import Html.Keyed as Keyed import Html.Lazy exposing (lazy) viewPresidents : List President -> Html msg viewPresidents presidents = Keyed.node "ul" [] (List.map viewKeyedPresident presidents) viewKeyedPresident : President -> (String, Html msg) viewKeyedPresident president = ( president.name, lazy viewPresident president ) viewPresident : President -> Html msg viewPresident president = li [] [ ... ] ``` -------------------------------- ### Compile Elm to JavaScript Source: https://guide.elm-lang.org/interop Use the `--output` flag with `elm make` to generate a JavaScript file instead of an HTML file. This file will expose an `Elm..init()` function. ```bash elm make src/Main.elm --output=main.js ``` -------------------------------- ### HTML and JavaScript for WebSocket Communication Source: https://guide.elm-lang.org/interop/ports This HTML file sets up a WebSocket connection and integrates an Elm application. It subscribes to an Elm port to send messages to the WebSocket and listens for WebSocket messages to send them back to Elm. ```html Elm + Websockets
``` -------------------------------- ### Basic Elm Compilation Source: https://guide.elm-lang.org/interop This command compiles an Elm module to an HTML file by default. ```bash elm make src/Main.elm ``` -------------------------------- ### Combining Random Generators with map3 Source: https://guide.elm-lang.org/effects/random Shows how to combine multiple random generators into a more complex one using `Random.map3`. This is useful for scenarios like creating a slot machine where multiple random outcomes need to be coordinated. ```elm import Random type Symbol = Cherry | Seven | Bar | Grapes symbol : Random.Generator Symbol symbol = Random.uniform Cherry [ Seven, Bar, Grapes ] type alias Spin = { one : Symbol , two : Symbol , three : Symbol } spin : Random.Generator Spin spin = Random.map3 Spin symbol symbol symbol ``` -------------------------------- ### Import Elm Module with Alias Source: https://guide.elm-lang.org/webapps/modules Use this to import a module and give it a shorter alias, especially useful for long module names. Access values using the alias as a prefix. ```elm import Post as P -- P.Post, P.estimatedReadTime, P.encode, P.decoder ``` -------------------------------- ### Compile and Minify Elm JavaScript Source: https://guide.elm-lang.org/optimization/asset_size Compile your Elm application with the `--optimize` flag and then minify the output JavaScript using `uglifyjs`. This process involves two steps of `uglifyjs` to ensure all optimizations are applied. ```bash elm make src/Main.elm --optimize --output=elm.js uglifyjs elm.js --compress 'pure_funcs=[F2,F3,F4,F5,F6,F7,F8,F9,A2,A3,A4,A5,A6,A7,A8,A9],pure_getters,keep_fargs=false,unsafe_comps,unsafe' | uglifyjs --mangle --output elm.min.js ``` -------------------------------- ### Displaying Human Time from Posix and Zone Source: https://guide.elm-lang.org/effects/time This snippet shows how to convert Time.Posix and Time.Zone into human-readable hour, minute, and second components. Use this in your view functions to display time to the user. ```elm view : Model -> Html Msg view model = let hour = String.fromInt (Time.toHour model.zone model.time) minute = String.fromInt (Time.toMinute model.zone model.time) second = String.fromInt (Time.toSecond model.zone model.time) in h1 [] [ text (hour ++ ":" ++ minute ++ ":" ++ second) ] ``` -------------------------------- ### Handling Flags in Elm Application Source: https://guide.elm-lang.org/interop/flags Define the `init` function in your Elm module to accept a flag argument. This argument's type must match the type of the flag passed from JavaScript. The `init` function then uses this value to set up the initial model. ```elm module Main exposing (..) import Browser import Html exposing (Html, text) -- MAIN main : Program Int Model Msg main = Browser.element { init = init, view = view, update = update, subscriptions = subscriptions } -- MODEL type alias Model = { currentTime : Int } init : Int -> ( Model, Cmd Msg ) init currentTime = ( { currentTime = currentTime }, Cmd.none ) -- UPDATE type Msg = NoOp update : Msg -> Model -> ( Model, Cmd Msg ) update _ model = ( model, Cmd.none ) -- VIEW view : Model -> Html Msg view model = text (String.fromInt model.currentTime) -- SUBSCRIPTIONS subscriptions : Model -> Sub Msg subscriptions _ = Sub.none ``` -------------------------------- ### Generating Random Values in Elm Source: https://guide.elm-lang.org/effects/random Demonstrates how to create different types of random generators in Elm. These generators describe how to produce random values but do not generate them directly. ```elm import Random probability : Random.Generator Float probability = Random.float 0 1 roll : Random.Generator Int roll = Random.int 1 6 usuallyTrue : Random.Generator Bool usuallyTrue = Random.weighted (80, True) [ (20, False) ] ``` -------------------------------- ### Browser.document Function Signature Source: https://guide.elm-lang.org/webapps Use `Browser.document` to create Elm applications that control the entire HTML document. It requires `init`, `view`, `update`, and `subscriptions` functions. ```elm document : { init : flags -> ( model, Cmd msg ) , view : model -> Document msg , update : msg -> model -> ( model, Cmd msg ) , subscriptions : model -> Sub msg } -> Program flags model msg ``` -------------------------------- ### Compile Elm Code Source: https://guide.elm-lang.org/install/elm Compile your Elm source files. The first command creates an `index.html` file, while the second creates an optimized JavaScript file. ```bash # Create an index.html file that you can open in your browser. elm make src/Main.elm ``` ```bash # Create an optimized JS file to embed in a custom HTML document. elm make src/Main.elm --optimize --output=elm.js ``` -------------------------------- ### Elm Counter Application Source: https://guide.elm-lang.org/architecture/buttons This is the complete Elm program for a counter. It initializes the model, defines how messages update the model, and how the model is viewed as HTML. User input triggers messages that are processed by the update function. ```elm import Browser import Html exposing (Html, button, div, text) import Html.Events exposing (onClick) -- MAIN main = Browser.sandbox { init = init, update = update, view = view } -- MODEL type alias Model = Int init : Model init = 0 -- UPDATE type Msg = Increment | Decrement update : Msg -> Model -> Model update msg model = case msg of Increment -> model + 1 Decrement -> model - 1 -- VIEW view : Model -> Html Msg view model = div [] [ button [ onClick Decrement ] [ text "-" ] , div [] [ text (String.fromInt model) ] , button [ onClick Increment ] [ text "+" ] ] ``` -------------------------------- ### Import Elm Module with Alias and Specific Values Source: https://guide.elm-lang.org/webapps/modules Combines aliasing with exposing specific values. This provides a concise way to access frequently used module members while still allowing access to others via the alias. ```elm import Post as P exposing (Post, estimatedReadTime) -- Post, estimatedReadTime -- P.Post, P.estimatedReadTime, P.encode, P.decoder ``` -------------------------------- ### Basic Arithmetic in Elm Source: https://guide.elm-lang.org/core_language Perform mathematical calculations directly. Supports standard operators like +, -, *, /, and exponentiation (^). ```Elm 1 + 1 ``` ```Elm 2 + 2 ``` ```Elm 30 * 60 * 1000 ``` ```Elm 2 ^ 4 ``` -------------------------------- ### Compile Elm to JavaScript Source: https://guide.elm-lang.org/webapps Compile your Elm code to a JavaScript file using the `elm make` command with the `--output` flag. This allows for integration with custom HTML. ```bash elm make src/Main.elm --output=main.js ``` -------------------------------- ### String to Float Conversion with Maybe Source: https://guide.elm-lang.org/error_handling/maybe Demonstrates `String.toFloat` which returns a `Maybe Float`. Use this when a string might not be convertible to a float, ensuring explicit handling of invalid inputs. ```elm String.toFloat : String -> Maybe Float String.toFloat "3.1415" -- Just 3.1415 : Maybe Float String.toFloat "abc" -- Nothing : Maybe Float ``` -------------------------------- ### Integer Bit Sequences Source: https://guide.elm-lang.org/appendix/types_as_bits Illustrates how integers can be represented by sequences of bits. Each unique sequence corresponds to a different integer value. ```plaintext 00000000 00000001 00000010 00000011 ... ``` -------------------------------- ### Define User Type with Status and Name Source: https://guide.elm-lang.org/types/custom_types Represents a user with a status and a name using a type alias and a custom type for status. ```elm type UserStatus = Regular | Visitor type alias User = { status : UserStatus , name : String } thomas = { status = Regular, name = "Thomas" } kate95 = { status = Visitor, name = "kate95" } ``` -------------------------------- ### Import Elm Module Directly Source: https://guide.elm-lang.org/webapps/modules Use this to import all exposed values from a module without an alias. Access values using the module name as a prefix. ```elm import Post -- Post.Post, Post.estimatedReadTime, Post.encode, Post.decoder ``` -------------------------------- ### List.reverse Type Annotation Source: https://guide.elm-lang.org/types/reading_types Illustrates the type annotation for List.reverse, where 'a' is a type variable that must be consistent between input and output. ```elm List.reverse : List a -> List a ``` -------------------------------- ### Basic HTML structure Source: https://guide.elm-lang.org/optimization/lazy This is a standard HTML structure. It represents a simple list of items. ```html

Chair alternatives include:

  • seiza
  • chabudai
``` -------------------------------- ### Use Case Expression for User Type in Elm Source: https://guide.elm-lang.org/types/pattern_matching Demonstrates how to use a `case` expression to pattern match on the `User` type and extract data from its variants. This function returns the name for both `Regular` and `Visitor` users. ```elm toName : User -> String toName user = case user of Regular name age -> name Visitor name -> name -- toName (Regular "Thomas" 44) == "Thomas" -- toName (Visitor "kate95") == "kate95" ``` -------------------------------- ### Representing Traffic Light Colors with a Record Source: https://guide.elm-lang.org/appendix/types_as_sets Using a record with boolean flags for each color reduces invalid states but still allows for combinations that don't represent a single color. This approach has a finite but larger set of possible values than necessary. ```Elm type alias Color = { red : Bool, yellow : Bool, green : Bool } ``` -------------------------------- ### Define a Function with Two Arguments in Elm Source: https://guide.elm-lang.org/core_language Create a function that accepts multiple arguments. Arguments can be primitive values or grouped expressions in parentheses. ```Elm madlib animal adjective = "The ostentatious " ++ animal ++ " wears " ++ adjective ++ " shorts." ``` ```Elm madlib "cat" "ergonomic" ``` ```Elm madlib ("butter" ++ "fly") "metallic" ``` -------------------------------- ### Embed Elm in HTML Source: https://guide.elm-lang.org/interop Include the compiled Elm JavaScript file in your HTML `` and initialize the Elm application in a `
``` -------------------------------- ### Import Specific Elm Module Values Source: https://guide.elm-lang.org/webapps/modules Use this to import only specific values from a module, making them directly accessible without a prefix. This can reduce verbosity but may impact readability if overused. ```elm import Post exposing (Post, estimatedReadTime) -- Post, estimatedReadTime -- Post.Post, Post.estimatedReadTime, Post.encode, Post.decoder ``` -------------------------------- ### Custom HTML for Elm App Source: https://guide.elm-lang.org/webapps A basic HTML structure to load and initialize an Elm web application compiled to JavaScript. The Elm program is initialized in the ``. ```html Main ``` -------------------------------- ### Define Basic User Status Type Source: https://guide.elm-lang.org/types/custom_types Use this to define a simple type with distinct variants like 'Regular' or 'Visitor'. ```elm type UserStatus = Regular | Visitor ``` -------------------------------- ### Default Main Module Declaration Source: https://guide.elm-lang.org/webapps/modules This is the default module declaration Elm uses if none is explicitly provided, making it easier for beginners. ```elm module Main exposing ( ..) ``` -------------------------------- ### Define Routes with Url.Parser Source: https://guide.elm-lang.org/webapps/url_parsing Use `Url.Parser` to define a parser for various route types including topics, blog posts, users, and user comments. Handles nested paths and different data types. ```elm import Url.Parser exposing (Parser, (), int, map, oneOf, s, string) type Route = Topic String | Blog Int | User String | Comment String Int routeParser : Parser (Route -> a) a routeParser = oneOf [ map Topic (s "topic" string) , map Blog (s "blog" int) , map User (s "user" string) , map Comment (s "user" string s "comment" int) ] -- /topic/pottery ==> Just (Topic "pottery") -- /topic/collage ==> Just (Topic "collage") -- /topic/ ==> Nothing -- /blog/42 ==> Just (Blog 42) -- /blog/123 ==> Just (Blog 123) -- /blog/mosaic ==> Nothing -- /user/tom/ ==> Just (User "tom") -- /user/sue/ ==> Just (User "sue") -- /user/bob/comment/42 ==> Just (Comment "bob" 42) -- /user/sam/comment/35 ==> Just (Comment "sam" 35) -- /user/sam/comment/ ==> Nothing -- /user/ ==> Nothing ``` -------------------------------- ### Bash Script for Elm Optimization Source: https://guide.elm-lang.org/optimization/asset_size A bash script to automate the Elm compilation and JavaScript minification process. It compiles the Elm code, minifies it using `uglifyjs`, and then reports the sizes of the compiled, minified, and gzipped files. ```bash #!/bin/sh set -e js="elm.js" min="elm.min.js" elm make --optimize --output=$js "$@" uglifyjs $js --compress 'pure_funcs=[F2,F3,F4,F5,F6,F7,F8,F9,A2,A3,A4,A5,A6,A7,A8,A9],pure_getters,keep_fargs=false,unsafe_comps,unsafe' | uglifyjs --mangle --output $min echo "Compiled size:$(wc $js -c) bytes ($js)" echo "Minified size:$(wc $min -c) bytes ($min)" echo "Gzipped size: $(gzip $min -c | wc -c) bytes" ``` -------------------------------- ### Interpreting Function Types Source: https://guide.elm-lang.org/types/reading_types Understand how Elm displays the type signature of functions, indicating input and output types. ```Elm String.length : String -> Int ``` ```Elm String.repeat : Int -> String -> String ``` -------------------------------- ### Function Type with Explicit Parentheses Source: https://guide.elm-lang.org/appendix/function_types Shows how a function type signature can be written with explicit parentheses to clarify the curried nature, where a function returns another function. ```elm String.repeat : Int -> (String -> String) ``` -------------------------------- ### Time.every Function Signature Source: https://guide.elm-lang.org/effects/time This is the signature for the `Time.every` function, which is used to create time-based subscriptions. It allows you to specify the interval and how to generate messages from the time. ```elm every : Float -> (Time.Posix -> msg) -> Sub msg ``` -------------------------------- ### Elm Helper Function for Input Fields Source: https://guide.elm-lang.org/architecture/forms This helper function abstracts the creation of input elements, taking type, placeholder, current value, and a message constructor as arguments. It simplifies the main view function by reducing boilerplate code for common input fields. ```elm viewInput : String -> String -> String -> (String -> msg) -> Html msg viewInput t p v toMsg = input [ type_ t, placeholder p, value v, onInput toMsg ] [] ``` -------------------------------- ### Define a Post Module in Elm Source: https://guide.elm-lang.org/webapps/modules Defines a `Post` type and associated functions for reading time and JSON encoding/decoding. Use this to structure data related to blog posts. ```elm module Post exposing (Post, estimatedReadTime, encode, decoder) import Json.Decode as D import Json.Encode as E -- POST type alias Post = { title : String , author : String , content : String } -- READ TIME estimatedReadTime : Post -> Float estimatedReadTime post = toFloat (wordCount post) / 220 wordCount : Post -> Int wordCount post = List.length (String.words post.content) -- JSON encode : Post -> E.Value encode post = E.object [ ("title", E.string post.title) , ("author", E.string post.author) , ("content", E.string post.content) ] decoder : D.Decoder Post decoder = D.map3 Post (D.field "title" D.string) (D.field "author" D.string) (D.field "content" D.string) ``` -------------------------------- ### Interpreting Primitive Types Source: https://guide.elm-lang.org/types/reading_types Observe how Elm infers and displays the types of basic values like strings, booleans, integers, and floats. ```Elm "hello" : String ``` ```Elm False : Bool ``` ```Elm 3 : Int ``` ```Elm 3.1415 : Float ``` -------------------------------- ### Model Data Loading States Source: https://guide.elm-lang.org/types/custom_types Represents states for asynchronous operations like loading, success, or failure, simplifying UI logic. ```elm type Profile = Failure | Loading | Success { name : String, description : String } ``` -------------------------------- ### Define Function and Call with Record Source: https://guide.elm-lang.org/types This code defines a function `toFullName` that concatenates first and last names from a record. It then calls this function with a record that has a typo in the field name. ```elm toFullName person = person.firstName ++ " " ++ person.lastName fullName = toFullName { fistName = "Hermann", lastName = "Hesse" } ``` -------------------------------- ### Conditional Logic with If-Expressions in Elm Source: https://guide.elm-lang.org/core_language Implement conditional behavior using `if`, `then`, and `else`. Ensures a value is returned in all branches. ```Elm greet name = if name == "Abraham Lincoln" then "Greetings Mr. President!" else "Hey!" ``` ```Elm greet "Tom" ``` ```Elm greet "Abraham Lincoln" ``` -------------------------------- ### Use Wildcard in Case Expression in Elm Source: https://guide.elm-lang.org/types/pattern_matching Shows how to use a wildcard `_` in a `case` expression to ignore unused associated data, such as the `age` in the `Regular` user variant. This improves code clarity when data is not needed. ```elm toName : User -> String toName user = case user of Regular name _ -> name Visitor name -> name ``` -------------------------------- ### Custom Type for Post Creation Source: https://guide.elm-lang.org/error_handling Model various failure conditions for creating a 'Post' with a custom type. This allows for specific error messages based on missing title or content. ```elm type MaybePost = Post { title : String, content : String } | NoTitle | NoContent toPost : String -> String -> MaybePost toPost title content = ... -- toPost "hi" "sup?" == Post { title = "hi", content = "sup?" } -- toPost "" "" == NoTitle -- toPost "hi" "" == NoContent ``` -------------------------------- ### Representing Traffic Light Colors with String Source: https://guide.elm-lang.org/appendix/types_as_sets Using a String to represent colors can lead to invalid data due to typos or case differences. The cardinality of String is infinite, making it difficult to ensure only valid values are used. ```Elm type alias Color = String ```