SlideShare ist ein Scribd-Unternehmen logo
1 von 43
z
Sprouting into the
world of Elm
An introduction to the Elm programming language
Presenter: Mike Onslow @mike_onslow
z
What is Elm?
z
What is Elm?
 A functional language for the browser
 Compiles to (ECMAScript 5 compliant) JavaScript
 ML style language, written in Haskell
 Declarative syntax
z
What makes Elm
special?
z
What makes Elm special?
 A beginner friendly language with a minimal but powerful set of features
 A quick and kind compiler
 Advertises “No” runtime exceptions
 An architecture designed for the language
 Fully interoperable with JavaScript
 Enforces semantic versioning
 A helpful and friendly community
 Provides type inference
 A really nice formatter that eliminates the need for a linter
z
What makes Elm special?
A quick and kind compiler
z
What makes Elm special?
A quick and kind compiler
z
What makes Elm special?
A quick and kind compiler
There are a few helpful files here that may be useful to read before you run into
compiler errors https://github.com/elm-lang/elm-compiler/tree/master/hints
z
What makes Elm special?
Advertises “No” runtime exceptions
From the Elm website:
“Unlike hand-written JavaScript, Elm code does not
produce runtime exceptions in practice. Instead, Elm uses
type inference to detect problems during compilation and
give friendly hints. This way problems never make it to
your users. NoRedInk has 80k+ lines of Elm, and after
more than a year in production, it still has not produced a
single runtime exception.”
This article has more insight on the subject:
http://elm-lang.org/blog/compilers-as-assistants
z
What makes Elm special?
Advertises “No” runtime exceptions
From personal and professional experience, I have experienced this firsthand.
Clarity has had 4 projects in production over the past 18 months and these stats still hold true.
This article has more insight on the subject:
http://elm-lang.org/blog/compilers-as-assistants
The Elm
Architecture
or “TEA” as it’s sometimes called
z
The Elm Architecture
 The logic of every Elm program will break up into three cleanly
separated parts:
 Model — the state of your application (a single state atom)
 Update — a way to update your state
 View — a way to view your state as HTML
View
Model Update
A simple example…
z
Simple Example
z
After compilation, the code below produces simple counter app:
Building something
more complex
but not too complex…
z
Building something more complex
 This is a walkthrough of code I modified from the original HTTP
example from the Elm site:
https://ellie-app.com/3r2wFkFJBr6a1/0
 Original example: http://elm-lang.org/examples/http
z
A module system
The definition for a module can be as simple as something like my app below:
Similar to Elixir, Elm uses modules as way to split up code
This exposes everything (..) to the consuming module (the module in which this
module is imported). This is fine for a top level App (or Main) definition but
considerations should be made to only expose functions and types that are necessary
for working with the module. Consider these your “public” API for a module and
anything not exposed is “private” to the module.
Next, we move on to our application’s imports
z
A module system
The import statement tells the compiler that we want to bring something into our
module to use. An app without imports is extremely rare, as a matter of fact, even the
most basic “Hello, World!” example has an import:
For our application, we need to use some standard libraries (ex: Html*) as well as some
non-standard ones (ex: RemoteData) :
Similar to how module’s are defined, imports let us choose which functions to expose to
our application via the exposing keyword. Again (..) here means we’re bringing
everything the imported module expose into the local namespace. You can also alias
imported modules using the as keyword
z
Setting up the application
The following code is similar to what you’ll see in most Elm applications:
The program’s execution will start in the main function and continue from there. Record value
assignment is done using the = operator (ex: init = init "cats") as in many languages. Here
we are passing in an initialization function for our program’s init to run upon startup. This function
should transform any inputs (in this case “cats”) into an initial state for our application.
In our case, the init function does this by taking a String as an input
and emitting a (Model, Cmd Msg)
z
Setting up the application
More on the program module:
program is a function of the Html module in the Elm language core (http://package.elm-
lang.org/packages/elm-lang/html/2.0.0/Html). This module also exposes a couple of other handy
functions for starting a your program (as well as others related to Html) that you may want to use
based on what your application is doing.
• Html.beginnerProgram can be used if your application does not have any side effects that
need to occur outside the input and Dom events. Basically, this version of Program does not
allow for adding asynchronous commands, subscriptions etc. (this includes Tasks) input from
DOM Events
• Html.program can be used if your application needs access to run commands or use
subscriptions (this includes interop with JavaScript). Not every application needs this but this is
likely to be the most common version of Program used.
• Html.programWithFlags allows for all of the functionality of Html.program but can also
consume inputs from the JavaScript environment at startup. Some common uses are to pull
values from localStorage upon loading the page.
z
The Model
The Model in Elm is a single state atom of your application’s state. Here is the Model
for the example application:
This Model encompasses the entire “state” portion of my application. As seen in a
previous slide, the init function is used to setup the initial state of this Model when
the application starts.
A Model can pretty much be of any type, but as your application grows, most of the
time an Elm “Record” (http://elm-lang.org/docs/records) is the appropriate storage
mechanism for this state.
z
Union Types and modeling data
One of the features of Elm are it’s Union Types, these are sometimes called “tagged
unions” or “ADTs” in other languages.
A common use of Union Types in Elm is to setup the message structure for an
application. Below is example of how Union Types are used in the example
application:
More on Union Types can be found here:
https://guide.elm-lang.org/types/union_types.html
z
Union Types and modeling data
A more complex union type example:
Referenced from RemoteData package by Kris Jenkins:
http://package.elm-lang.org/packages/krisajenkins/remotedata/latest
z
Union Types and modeling data
For something as simple as the last example, you could just use a value of type Bool
which, just so happens to be a union type itself.
But what’s nice is that, with the custom union type, you get more expressiveness from
the statement, which (generally) makes things easier to read.
As I’ve used Elm more, I’ve found that Union Types are effective way to model pretty
much anything. For instance, let’s say you have a toggle button and you want to
represent either on ”On” or “Off” state:
z
Union Types and modeling data
In practice, union types allow for actions based on a pattern match which we’ll
see in the next slide as we move on to the update function!
z
Updating state
Now that we’ve established that our Model holds the state for our entire application, how to we
update it? That’s where the update function comes into play.
Here is the update function for the example application:
The type definition for update implies that it takes two arguments a Msg and a Model. It then
emits a tuple in the form of (Model, Cmd Msg) based on those inputs.
z
Updating state
In this case, pattern matching is being used to determine what should be returned by the update
function (how the model should change based on the current model) as well as any additional
commands that may need to be run based on the condition. This is a fairly standard thing to see
in an Elm update function
However, as an application scales, this section can grow and it may be beneficial to break out
some of the smaller blocks of execution into their own function (or even their own module)
Update the Model
Schedule a Cmd to be run upon the
next cycle of the Elm runtime
loop (after the View is rendered)
Update the Model
In this case, we don’t need to run
Any additional commands, just
process the response so we use
Cmd.none
z
The View
Here’s a small rendition of our view code. We’ll take this in bite sized chunks…
The type definition says that this function takes in a Model and emits an Html Msg
z
The View
Elm has let statements which allow you to define variables local to the scope between let and in. In
the code below, this is being used to assign multiple variables (ex: waitingGifUrl, buttonText etc.)
that will be used in the context below the in keyword.
(firstRun, gifUrl) use destructuring to assign multiple variables at once based on the case.
z
The View
Last, but not least, the code below the in keyword is used to declaratively state what should be displayed
on the page. Rather than using plain HTML here, Elm uses functions for everything (including HTML).
Most of the Html functions have the following type signature (h1 example):
z
A simple Http request
In order to fetch the data from a remote server, the example application has a function called getRandomGif. This function is in
charge of taking in a String as an input and emitting a Cmd Msg
A new Cmd is scheduled…
ImgResponse is the designated message endpoint
Using the pipe-operators |> or <| one can pass through the
result to the next function where it is used as the last argument
for the function it gets piped into. The data can flow in both
directions, though the usual way of chaining functions with the
pipe operator is using |> and having a single line per function
call:
An example of using the pipe-operator from the official site: http://elm-lang.org/examples/pipes/code
z
Decoding the data
When we schedule the Http request, one of the arguments we pass into the Http.get function is the
Decoder that should be used to parse the resultant JSON.
When we schedule the Http request, one of the arguments we pass into the Http.get function is the
Decoder that should be used to parse the resultant JSON.
In this case, we’re just using Decode.at to quickly extract only the data.image_url field from the
JSON data (shown below)
z
JavaScript Interop
In Elm JavaScript interop is done through a pub/sub system called “Ports”. The notion of a Port is that it is a pipe between Elm
and JavaScript. The basic flow of ports is shown in the diagram below:
Reference article: https://hackernoon.com/how-elm-ports-work-with-a-picture-just-one-25144ba43cdd
Ports have either an inbound or an outbound flow. An example of an outbound port in Elm looks like the following:
port myOutboundPort: String -> Cmd msg
Here we are defining a port that sends one String argument to the native JavaScript code that it can use in it’s function.
z
JavaScript Interop
We can schedule myOutboundPort to run at either startup of the application (in our init function) or in
our update function
Example of scheduling an outbound port to run upon startup:
Example of scheduling an outbound port to run at update:
z
JavaScript Interop
Inbound ports are handled via subscriptions. To listen for inbound messages, a subscription needs to be setup (in our app the
subscriptions function would handle this). We’ll jump into the subscription code on the next slide.
For now, here is the syntax to setup an inbound port:
In the example above DataStore is a type with the same shape as the data we expect
to come in. Let’s say we are being sent the following JSON payload:
In this case, DataStore should be defined as follows:
z
JavaScript Interop
To subscribe (listen) for messages coming in on this port, we need to add a subscription to our
subscriptions function:
When we receive messages from this
port the update function will be
called with ExecuteInboundPort
as the message
z
Commands and Subscriptions
A few notes on subscriptions (Sub) and commands (Cmd) :
• If you need to subscribe to multiple endpoints (Phoenix channels, Ports etc.), you can use Sub.batch
with a List of subscriptions rather than just listing one
• Similar to Sub.batch, Cmd.batch allows you to schedule multiple commands to run
• There are other functions for working with subscriptions and commands, their respective
documentation pages are:
• Subscriptions: http://package.elm-lang.org/packages/elm-lang/core/5.1.1/Platform-Sub
Commands: http://package.elm-lang.org/packages/elm-lang/core/5.1.1/Platform-Cmd
z
A more complete diagram of the Elm
Architecture
z
Getting started with Elm
• Elm is a generally considered a very easy language to get started with. To get Elm installed, you can visit
https://guide.elm-lang.org/install.html and follow the directions.
• Installers are available for Windows, Mac and Anywhere (via npm)
• Language plugins are available for many popular editors and IDEs including Sublime, VS Code, Atom and JetBrains
(WebStorm etc.)
• It’s highly recommended that you use elm-format to auto format code upon save (via a watcher). Directions for install
and setup are here: https://github.com/avh4/elm-format
z
Getting started with Elm
Elm is a compiled language and as uses a tool called “elm-make” to compile it’s code from Elm to JavaScript.
One cool feature of the compiler is, by adding the –warn flag, you’ll be alerted to many to unused imports. Similar to
the normal compiler issues that cause a failure, these messages are helpful and friendly.
z
Resources
 Examples from the official site: http://elm-lang.org/examples
 The Official Guide: https://guide.elm-lang.org/
 Ellie App (In browser editor): https://ellie-app.com/
 Elm in Action (Book): https://www.manning.com/books/elm-in-action
 Elm Town (Podcast): https://elmtown.github.io/
 Awesome Elm (collection of resources and libraries):
https://github.com/isRuslan/awesome-elm libraries
Questions?

Weitere ähnliche Inhalte

Was ist angesagt?

Java applets
Java appletsJava applets
Java applets
lopjuan
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran Toch
Adil Jafri
 

Was ist angesagt? (20)

27 applet programming
27  applet programming27  applet programming
27 applet programming
 
Java applets
Java appletsJava applets
Java applets
 
Eclipse World 2007: Fundamentals of the Eclipse Modeling Framework
Eclipse World 2007: Fundamentals of the Eclipse Modeling FrameworkEclipse World 2007: Fundamentals of the Eclipse Modeling Framework
Eclipse World 2007: Fundamentals of the Eclipse Modeling Framework
 
Applet in java
Applet in javaApplet in java
Applet in java
 
Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4
 
Java applets
Java appletsJava applets
Java applets
 
Xamarin Development
Xamarin DevelopmentXamarin Development
Xamarin Development
 
Intro To C++ - Class 03 - An Introduction To C++ Programming, Part II
Intro To C++ - Class 03 - An Introduction To C++ Programming, Part IIIntro To C++ - Class 03 - An Introduction To C++ Programming, Part II
Intro To C++ - Class 03 - An Introduction To C++ Programming, Part II
 
Azure rev002
Azure rev002Azure rev002
Azure rev002
 
ASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation ControlsASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation Controls
 
first-applet
first-appletfirst-applet
first-applet
 
Cordovilla
CordovillaCordovilla
Cordovilla
 
Java Applet
Java AppletJava Applet
Java Applet
 
Applet execution
Applet execution Applet execution
Applet execution
 
E learning excel vba programming lesson 2
E learning excel vba programming  lesson 2E learning excel vba programming  lesson 2
E learning excel vba programming lesson 2
 
Unified Expression Language
Unified Expression LanguageUnified Expression Language
Unified Expression Language
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran Toch
 
LEARNING  iPAD STORYBOARDS IN OBJ-­‐C LESSON 1
LEARNING	 iPAD STORYBOARDS IN OBJ-­‐C LESSON 1LEARNING	 iPAD STORYBOARDS IN OBJ-­‐C LESSON 1
LEARNING  iPAD STORYBOARDS IN OBJ-­‐C LESSON 1
 
Switch statement
Switch statementSwitch statement
Switch statement
 
Immutable Data and TypeScript in an Ember.js Application
Immutable Data and TypeScript in an Ember.js ApplicationImmutable Data and TypeScript in an Ember.js Application
Immutable Data and TypeScript in an Ember.js Application
 

Ähnlich wie Sprouting into the world of Elm

Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!
olracoatalub
 
Macasu, gerrell c.
Macasu, gerrell c.Macasu, gerrell c.
Macasu, gerrell c.
gerrell
 

Ähnlich wie Sprouting into the world of Elm (20)

Elm Detroit 9/7/17 - Planting Seeds with Elm
Elm Detroit 9/7/17 - Planting Seeds with ElmElm Detroit 9/7/17 - Planting Seeds with Elm
Elm Detroit 9/7/17 - Planting Seeds with Elm
 
SEMjs - Planting Seeds with Elm
SEMjs - Planting Seeds with ElmSEMjs - Planting Seeds with Elm
SEMjs - Planting Seeds with Elm
 
Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!
 
My final requirement
My final requirementMy final requirement
My final requirement
 
.Net framework by naveen kumar veligeti
.Net framework by naveen kumar veligeti.Net framework by naveen kumar veligeti
.Net framework by naveen kumar veligeti
 
Functional programming in TypeScript
Functional programming in TypeScriptFunctional programming in TypeScript
Functional programming in TypeScript
 
Tutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng verTutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng ver
 
EclipseCon 2009: TmL Tutorial Exercises
EclipseCon 2009: TmL Tutorial ExercisesEclipseCon 2009: TmL Tutorial Exercises
EclipseCon 2009: TmL Tutorial Exercises
 
Macasu, gerrell c.
Macasu, gerrell c.Macasu, gerrell c.
Macasu, gerrell c.
 
The future of DSLs - functions and formal methods
The future of DSLs - functions and formal methodsThe future of DSLs - functions and formal methods
The future of DSLs - functions and formal methods
 
Switch case and looping new
Switch case and looping newSwitch case and looping new
Switch case and looping new
 
Class notes(week 10) on applet programming
Class notes(week 10) on applet programmingClass notes(week 10) on applet programming
Class notes(week 10) on applet programming
 
A tutorial on C++ Programming
A tutorial on C++ ProgrammingA tutorial on C++ Programming
A tutorial on C++ Programming
 
Switch case and looping jam
Switch case and looping jamSwitch case and looping jam
Switch case and looping jam
 
EGL Conference 2011 - EGL Open
EGL Conference 2011 - EGL OpenEGL Conference 2011 - EGL Open
EGL Conference 2011 - EGL Open
 
Angular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdfAngular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdf
 
Book management system
Book management systemBook management system
Book management system
 
Angular kickstart slideshare
Angular kickstart   slideshareAngular kickstart   slideshare
Angular kickstart slideshare
 
Applet &amp; graphics programming
Applet &amp; graphics programmingApplet &amp; graphics programming
Applet &amp; graphics programming
 
Class notes(week 10) on applet programming
Class notes(week 10) on applet programmingClass notes(week 10) on applet programming
Class notes(week 10) on applet programming
 

Kürzlich hochgeladen

Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 

Kürzlich hochgeladen (20)

WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
WSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - Kanchana
 
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 

Sprouting into the world of Elm

  • 1. z Sprouting into the world of Elm An introduction to the Elm programming language Presenter: Mike Onslow @mike_onslow
  • 3. z What is Elm?  A functional language for the browser  Compiles to (ECMAScript 5 compliant) JavaScript  ML style language, written in Haskell  Declarative syntax
  • 5. z What makes Elm special?  A beginner friendly language with a minimal but powerful set of features  A quick and kind compiler  Advertises “No” runtime exceptions  An architecture designed for the language  Fully interoperable with JavaScript  Enforces semantic versioning  A helpful and friendly community  Provides type inference  A really nice formatter that eliminates the need for a linter
  • 6. z What makes Elm special? A quick and kind compiler
  • 7. z What makes Elm special? A quick and kind compiler
  • 8. z What makes Elm special? A quick and kind compiler There are a few helpful files here that may be useful to read before you run into compiler errors https://github.com/elm-lang/elm-compiler/tree/master/hints
  • 9. z What makes Elm special? Advertises “No” runtime exceptions From the Elm website: “Unlike hand-written JavaScript, Elm code does not produce runtime exceptions in practice. Instead, Elm uses type inference to detect problems during compilation and give friendly hints. This way problems never make it to your users. NoRedInk has 80k+ lines of Elm, and after more than a year in production, it still has not produced a single runtime exception.” This article has more insight on the subject: http://elm-lang.org/blog/compilers-as-assistants
  • 10. z What makes Elm special? Advertises “No” runtime exceptions From personal and professional experience, I have experienced this firsthand. Clarity has had 4 projects in production over the past 18 months and these stats still hold true. This article has more insight on the subject: http://elm-lang.org/blog/compilers-as-assistants
  • 11. The Elm Architecture or “TEA” as it’s sometimes called
  • 12. z The Elm Architecture  The logic of every Elm program will break up into three cleanly separated parts:  Model — the state of your application (a single state atom)  Update — a way to update your state  View — a way to view your state as HTML View Model Update
  • 15. z After compilation, the code below produces simple counter app:
  • 17. z Building something more complex  This is a walkthrough of code I modified from the original HTTP example from the Elm site: https://ellie-app.com/3r2wFkFJBr6a1/0  Original example: http://elm-lang.org/examples/http
  • 18. z A module system The definition for a module can be as simple as something like my app below: Similar to Elixir, Elm uses modules as way to split up code This exposes everything (..) to the consuming module (the module in which this module is imported). This is fine for a top level App (or Main) definition but considerations should be made to only expose functions and types that are necessary for working with the module. Consider these your “public” API for a module and anything not exposed is “private” to the module. Next, we move on to our application’s imports
  • 19. z A module system The import statement tells the compiler that we want to bring something into our module to use. An app without imports is extremely rare, as a matter of fact, even the most basic “Hello, World!” example has an import: For our application, we need to use some standard libraries (ex: Html*) as well as some non-standard ones (ex: RemoteData) : Similar to how module’s are defined, imports let us choose which functions to expose to our application via the exposing keyword. Again (..) here means we’re bringing everything the imported module expose into the local namespace. You can also alias imported modules using the as keyword
  • 20. z Setting up the application The following code is similar to what you’ll see in most Elm applications: The program’s execution will start in the main function and continue from there. Record value assignment is done using the = operator (ex: init = init "cats") as in many languages. Here we are passing in an initialization function for our program’s init to run upon startup. This function should transform any inputs (in this case “cats”) into an initial state for our application. In our case, the init function does this by taking a String as an input and emitting a (Model, Cmd Msg)
  • 21. z Setting up the application More on the program module: program is a function of the Html module in the Elm language core (http://package.elm- lang.org/packages/elm-lang/html/2.0.0/Html). This module also exposes a couple of other handy functions for starting a your program (as well as others related to Html) that you may want to use based on what your application is doing. • Html.beginnerProgram can be used if your application does not have any side effects that need to occur outside the input and Dom events. Basically, this version of Program does not allow for adding asynchronous commands, subscriptions etc. (this includes Tasks) input from DOM Events • Html.program can be used if your application needs access to run commands or use subscriptions (this includes interop with JavaScript). Not every application needs this but this is likely to be the most common version of Program used. • Html.programWithFlags allows for all of the functionality of Html.program but can also consume inputs from the JavaScript environment at startup. Some common uses are to pull values from localStorage upon loading the page.
  • 22. z The Model The Model in Elm is a single state atom of your application’s state. Here is the Model for the example application: This Model encompasses the entire “state” portion of my application. As seen in a previous slide, the init function is used to setup the initial state of this Model when the application starts. A Model can pretty much be of any type, but as your application grows, most of the time an Elm “Record” (http://elm-lang.org/docs/records) is the appropriate storage mechanism for this state.
  • 23. z Union Types and modeling data One of the features of Elm are it’s Union Types, these are sometimes called “tagged unions” or “ADTs” in other languages. A common use of Union Types in Elm is to setup the message structure for an application. Below is example of how Union Types are used in the example application: More on Union Types can be found here: https://guide.elm-lang.org/types/union_types.html
  • 24. z Union Types and modeling data A more complex union type example: Referenced from RemoteData package by Kris Jenkins: http://package.elm-lang.org/packages/krisajenkins/remotedata/latest
  • 25. z Union Types and modeling data For something as simple as the last example, you could just use a value of type Bool which, just so happens to be a union type itself. But what’s nice is that, with the custom union type, you get more expressiveness from the statement, which (generally) makes things easier to read. As I’ve used Elm more, I’ve found that Union Types are effective way to model pretty much anything. For instance, let’s say you have a toggle button and you want to represent either on ”On” or “Off” state:
  • 26. z Union Types and modeling data In practice, union types allow for actions based on a pattern match which we’ll see in the next slide as we move on to the update function!
  • 27. z Updating state Now that we’ve established that our Model holds the state for our entire application, how to we update it? That’s where the update function comes into play. Here is the update function for the example application: The type definition for update implies that it takes two arguments a Msg and a Model. It then emits a tuple in the form of (Model, Cmd Msg) based on those inputs.
  • 28. z Updating state In this case, pattern matching is being used to determine what should be returned by the update function (how the model should change based on the current model) as well as any additional commands that may need to be run based on the condition. This is a fairly standard thing to see in an Elm update function However, as an application scales, this section can grow and it may be beneficial to break out some of the smaller blocks of execution into their own function (or even their own module) Update the Model Schedule a Cmd to be run upon the next cycle of the Elm runtime loop (after the View is rendered) Update the Model In this case, we don’t need to run Any additional commands, just process the response so we use Cmd.none
  • 29. z The View Here’s a small rendition of our view code. We’ll take this in bite sized chunks… The type definition says that this function takes in a Model and emits an Html Msg
  • 30. z The View Elm has let statements which allow you to define variables local to the scope between let and in. In the code below, this is being used to assign multiple variables (ex: waitingGifUrl, buttonText etc.) that will be used in the context below the in keyword. (firstRun, gifUrl) use destructuring to assign multiple variables at once based on the case.
  • 31. z The View Last, but not least, the code below the in keyword is used to declaratively state what should be displayed on the page. Rather than using plain HTML here, Elm uses functions for everything (including HTML). Most of the Html functions have the following type signature (h1 example):
  • 32. z A simple Http request In order to fetch the data from a remote server, the example application has a function called getRandomGif. This function is in charge of taking in a String as an input and emitting a Cmd Msg A new Cmd is scheduled… ImgResponse is the designated message endpoint Using the pipe-operators |> or <| one can pass through the result to the next function where it is used as the last argument for the function it gets piped into. The data can flow in both directions, though the usual way of chaining functions with the pipe operator is using |> and having a single line per function call: An example of using the pipe-operator from the official site: http://elm-lang.org/examples/pipes/code
  • 33. z Decoding the data When we schedule the Http request, one of the arguments we pass into the Http.get function is the Decoder that should be used to parse the resultant JSON. When we schedule the Http request, one of the arguments we pass into the Http.get function is the Decoder that should be used to parse the resultant JSON. In this case, we’re just using Decode.at to quickly extract only the data.image_url field from the JSON data (shown below)
  • 34. z JavaScript Interop In Elm JavaScript interop is done through a pub/sub system called “Ports”. The notion of a Port is that it is a pipe between Elm and JavaScript. The basic flow of ports is shown in the diagram below: Reference article: https://hackernoon.com/how-elm-ports-work-with-a-picture-just-one-25144ba43cdd Ports have either an inbound or an outbound flow. An example of an outbound port in Elm looks like the following: port myOutboundPort: String -> Cmd msg Here we are defining a port that sends one String argument to the native JavaScript code that it can use in it’s function.
  • 35. z JavaScript Interop We can schedule myOutboundPort to run at either startup of the application (in our init function) or in our update function Example of scheduling an outbound port to run upon startup: Example of scheduling an outbound port to run at update:
  • 36. z JavaScript Interop Inbound ports are handled via subscriptions. To listen for inbound messages, a subscription needs to be setup (in our app the subscriptions function would handle this). We’ll jump into the subscription code on the next slide. For now, here is the syntax to setup an inbound port: In the example above DataStore is a type with the same shape as the data we expect to come in. Let’s say we are being sent the following JSON payload: In this case, DataStore should be defined as follows:
  • 37. z JavaScript Interop To subscribe (listen) for messages coming in on this port, we need to add a subscription to our subscriptions function: When we receive messages from this port the update function will be called with ExecuteInboundPort as the message
  • 38. z Commands and Subscriptions A few notes on subscriptions (Sub) and commands (Cmd) : • If you need to subscribe to multiple endpoints (Phoenix channels, Ports etc.), you can use Sub.batch with a List of subscriptions rather than just listing one • Similar to Sub.batch, Cmd.batch allows you to schedule multiple commands to run • There are other functions for working with subscriptions and commands, their respective documentation pages are: • Subscriptions: http://package.elm-lang.org/packages/elm-lang/core/5.1.1/Platform-Sub Commands: http://package.elm-lang.org/packages/elm-lang/core/5.1.1/Platform-Cmd
  • 39. z A more complete diagram of the Elm Architecture
  • 40. z Getting started with Elm • Elm is a generally considered a very easy language to get started with. To get Elm installed, you can visit https://guide.elm-lang.org/install.html and follow the directions. • Installers are available for Windows, Mac and Anywhere (via npm) • Language plugins are available for many popular editors and IDEs including Sublime, VS Code, Atom and JetBrains (WebStorm etc.) • It’s highly recommended that you use elm-format to auto format code upon save (via a watcher). Directions for install and setup are here: https://github.com/avh4/elm-format
  • 41. z Getting started with Elm Elm is a compiled language and as uses a tool called “elm-make” to compile it’s code from Elm to JavaScript. One cool feature of the compiler is, by adding the –warn flag, you’ll be alerted to many to unused imports. Similar to the normal compiler issues that cause a failure, these messages are helpful and friendly.
  • 42. z Resources  Examples from the official site: http://elm-lang.org/examples  The Official Guide: https://guide.elm-lang.org/  Ellie App (In browser editor): https://ellie-app.com/  Elm in Action (Book): https://www.manning.com/books/elm-in-action  Elm Town (Podcast): https://elmtown.github.io/  Awesome Elm (collection of resources and libraries): https://github.com/isRuslan/awesome-elm libraries