+
+ + +
+
+

+ Introduction to Elm +

+ +

by Abadi Kurniawan

+ +

1904Labs Lunch and Learn

+
+
+
+

What is Elm?

+
    +
  • Functional Programming Language
  • +
  • Compiled to JavaScript, Run in Browser
  • +
  • Building Reliable Web Application
  • +
+
+
+

Why Elm?

+
+
+

No Runtime Exception

+
+
+

No Null Reference

+ +
+
+

+ I call it my billion-dollar mistake. It was the invention of the + null reference in 1965. +

+ + Tony Hoare -- Designer of ALGOL W + +
+
+
+
+
+
+ +
+
+

Helpful Compiler

+
+
+
+
+
+
+ +
+
+

More Helpful Compiler

+
+
+
+
+

Enforced Semantic Versioning

+
+
+

Friendly Community

+
+
+

Syntax

+
+
+

Hello World

+ +
+module Main exposing (main)
+
+import Html exposing (div, text)
+import Html.Attributes exposing (style)
+
+-- This is the main function
+main =
+    view "Hello World"
+
+-- This is the view function
+view content =
+    div 
+        [ style "border" "5px solid #ccc"
+        , style "padding" "10px"
+        ] 
+        [ text content ]
+              
+
+
+
+

Number

+ +
+
+n: Int
+n = 10
+
+m : Int
+m = 30 
+
+total = n + m 
+-- 40
+                
+
+
+
+

String

+ +
+
+hello : String
+hello = "hello"
+
+world : String
+world = "world"
+
+helloWorld = hello ++ " " ++ world -- "hello world"
+
+            
+
+ +
+

Function

+ +
+
+isNegative : Int -> Bool
+isNegative n = n < 0
+
+isNegative 10 -- False
+isNegative -10 -- True
+              
+
+
+
+

If Expressions

+ +
+
+content : String
+content = if True then "hello" else "world"
+-- "hello"
+
+error : String
+error = if True then "bad"
+-- Won't compile
+
+            
+
+
+
+

List

+ +
+
+dogs : List String
+dogs = [ "Husky", "Golden Retriever", "Dachshund" ]
+
+birds : List String
+birds = [ "Parakeet ",  "Macaw", "Cardinal" ]
+
+animals = dogs ++ birds
+-- [ "Husky", "Golden Retriever", "Dachshund", "Parakeet ",  "Macaw", "Cardinal" ]
+                
+
+
+
+

Tuple

+ +
+
+coordinate : (Int, Int)
+coordinate = ( 0, 100 )
+
+attendance : ( String, Bool )
+attendance = ( "Abadi", True )
+                
+
+
+
+

Records

+ +
+
+point : { x : Int, y : Int }
+point = { x = 4, y = 10 }
+
+person : { name : String, age : Int }
+person = { name = "Bill", age = 62 }
+            
+
+
+
+

The Elm Architecture

+
    +
  • Model
  • +
  • Update
  • +
  • View
  • +
+
+
+
+
+
+
+
+ +
+
+import Browser
+import Html exposing (Html, button, div, text)
+import Html.Events exposing (onClick)
+
+-- MODEL
+
+type alias Model = Int
+
+
+-- UPDATE
+
+type Msg = Increment | Decrement
+
+update msg model =
+  case msg of
+    Increment ->
+      model + 1
+
+    Decrement ->
+      model - 1
+
+
+-- VIEW
+
+view model =
+  div []
+    [ button [ onClick Decrement ] [ text "-" ]
+    , div [] [ text (String.fromInt model) ]
+    , button [ onClick Increment ] [ text "+" ]
+    ] 
+
+
+main =
+  Browser.sandbox 
+    { init = 0, update = update, view = view }
+
+            
+
+
+
+
+
+