SlideShare a Scribd company logo
ElmDetroit–PlantingSeedswithElm
September7,2017 11
Elm Detroit
Planting Seeds
with Elm
An introduction to the Elm programming language
ElmDetroit–PlantingSeedswithElm
September7,2017 2
What is Elm?
ElmDetroit–PlantingSeedswithElm
September7,2017 3
 Functional language for the browser
 Strongly and statically typed
 Compiles to JavaScript
 ML style language, written in Haskell
 Declarative syntax
What is Elm?
ElmDetroit–PlantingSeedswithElm
September7,2017 4
What makes Elm special?
ElmDetroit–PlantingSeedswithElm
September7,2017 5
 A beginner friendly language with a minimal but powerful set of
features
 A quick and kind compiler that provides type inference
 Advertises “No” runtime exceptions
 An architecture designed for the language
 Fully interoperable with JavaScript
 Enforces semantic versioning
 A helpful and friendly community
 A really nice formatter that eliminates the need for a linter
What makes Elm special?
ElmDetroit–PlantingSeedswithElm
September7,2017 6
 A quick and kind compiler that provides type inference
What makes Elm special?
ElmDetroit–PlantingSeedswithElm
September7,2017 7
 A quick and kind compiler that provides type inference
What makes Elm special?
ElmDetroit–PlantingSeedswithElm
September7,2017 8
 A note on type inference:
 Type inference allows the compiler to “infer” the types in your app
without you explicitly defining them.
 For instance, the following function definition examples are both
valid:
 In spite of this, it’s a good practice to provide the type annotations
to improve readability and general code quality.
What makes Elm special?
or
ElmDetroit–PlantingSeedswithElm
September7,2017 9
 A quick and kind compiler that provides type inference
 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
What makes Elm special?
ElmDetroit–PlantingSeedswithElm
September7,201710
 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
What makes Elm special?
ElmDetroit–PlantingSeedswithElm
September7,201711
 Advertises “No” runtime exceptions
From personal and professional experience, I have experienced this firsthand.
Clarity has had 5 projects in production over the past 18 months and these stats still hold true.
What makes Elm special?
This article has more insight on the subject:
http://elm-lang.org/blog/compilers-as-assistants
ElmDetroit–PlantingSeedswithElm
September7,201712
The Elm Architecture
or “TEA” as it’s sometimes called
ElmDetroit–PlantingSeedswithElm
September7,201713
 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
The Elm Architecture
View
Model Update
ElmDetroit–PlantingSeedswithElm
September7,201714
A simple example…
ElmDetroit–PlantingSeedswithElm
September7,201715
A simple example…
ElmDetroit–PlantingSeedswithElm
September7,201716
 After compilation, the code below produces a simple counter app
A simple example…
ElmDetroit–PlantingSeedswithElm
September7,201717
Building something more complex
but not too complex…
ElmDetroit–PlantingSeedswithElm
September7,201718
 This is a walkthrough of code I modified from the original HTTP
example from the Elm site:
https://ellie-app.com/4fgzBGyFzcYa1/0
 Original example: http://elm-lang.org/examples/http
An example of The Elm Architecture
ElmDetroit–PlantingSeedswithElm
September7,201719
 Elm uses modules as method to split up code
 The code (..) exposes everything to the consuming module.
 Consider exposed functions your “public” API for a module
 Anything not exposed is “private” to the module.
 Next, we move on to our application’s imports
A module system
ElmDetroit–PlantingSeedswithElm
September7,201720
 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
A module system
ElmDetroit–PlantingSeedswithElm
September7,201721
 Code that 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)
Setting up the application
ElmDetroit–PlantingSeedswithElm
September7,201722
 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.
 The main three types of programs exposed by the Html module are:
 Html.beginnerProgram
 Html.program
 Html.programWithFlags
Setting up the application
ElmDetroit–PlantingSeedswithElm
September7,201723
 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.
Setting up the application
ElmDetroit–PlantingSeedswithElm
September7,201724
 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.
The Model
ElmDetroit–PlantingSeedswithElm
September7,201725
 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
Union Types and modeling data
ElmDetroit–PlantingSeedswithElm
September7,201726
 A more complex union type example:
 Referenced from RemoteData package by Kris Jenkins:
http://package.elm-lang.org/packages/krisajenkins/remotedata/latest
Union Types and modeling data
ElmDetroit–PlantingSeedswithElm
September7,201727
 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:
 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.
Union Types and modeling data
ElmDetroit–PlantingSeedswithElm
September7,201728
 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!
Union Types and modeling data
ElmDetroit–PlantingSeedswithElm
September7,201729
 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.
Updating State
ElmDetroit–PlantingSeedswithElm
September7,201730
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
ElmDetroit–PlantingSeedswithElm
September7,201731
 Your applications View code defines what is displayed to the end user at any given time
 A view can also be comprised of other functions that serve as sub views or partial views.
 As with all Elm code, view is just a pure function and starts with a type and function definition
 The type definition here says that this function takes in a Model and emits an Html Msg
The View
ElmDetroit–PlantingSeedswithElm
September7,201732
 Elm has let statements which allow you to define variables that are local to the scope
between let and in.
 In the code below, let..in is being used to assign multiple variables (ex: waitingGifUrl,
buttonText etc.) at once that will be used in the context below the in keyword.
 The code(firstRun, gifUrl) uses destructuring to assign multiple variables at once based on the
case.
The View
ElmDetroit–PlantingSeedswithElm
September7,201733
 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):
The View
ElmDetroit–PlantingSeedswithElm
September7,201734
 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
 An example of using the pipe-operator from the official site: http://elm-lang.org/examples/pipes/code
A simple Http request
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.
ElmDetroit–PlantingSeedswithElm
September7,201735
 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).
Decoding the data
ElmDetroit–PlantingSeedswithElm
September7,201736
 Since everything in Elm is a function, we can easily cleanup our codebase as it grows. For instance, the
following three functions were originally part of the let..in block of my view code
 As my code grew, it seems intuitive to break those out into their own bite sized chunks of code. This also lends
itself well to reuse.
Functions everywhere!
ElmDetroit–PlantingSeedswithElm
September7,201737
 More on scaling and reuse in Elm:
 From the official guide: https://guide.elm-lang.org/reuse/
 An example of scalable SPA in Elm:
https://github.com/rtfeldman/elm-spa-example
Scaling and reuse
ElmDetroit–PlantingSeedswithElm
September7,201738
 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.
JavaScript Interop
ElmDetroit–PlantingSeedswithElm
September7,201739
 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:
JavaScript Interop
ElmDetroit–PlantingSeedswithElm
September7,201740
 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:
JavaScript Interop
ElmDetroit–PlantingSeedswithElm
September7,201741
 To subscribe (listen) for messages coming in on this port, we need to add a subscription to our
subscriptions function:
JavaScript Interop
When we receive messages from this
port the update function will be
called with ExecuteInboundPort
as the message
ElmDetroit–PlantingSeedswithElm
September7,201742
 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
Commands and Subscriptions
ElmDetroit–PlantingSeedswithElm
September7,201743
A more complete diagram of the
Elm Architecture
ElmDetroit–PlantingSeedswithElm
September7,201744
 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
Getting started with Elm
ElmDetroit–PlantingSeedswithElm
September7,201745
 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.
Getting started with Elm
ElmDetroit–PlantingSeedswithElm
September7,201746
 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
Resources
ElmDetroit–PlantingSeedswithElm
September7,201747
Questions?

More Related Content

Similar to Elm Detroit 9/7/17 - Planting Seeds with Elm

ALMOsT.js: an Agile Model to Model and Model to Text Transformation Framework
ALMOsT.js: an Agile Model to Model and Model to Text Transformation FrameworkALMOsT.js: an Agile Model to Model and Model to Text Transformation Framework
ALMOsT.js: an Agile Model to Model and Model to Text Transformation Framework
Carlo Bernaschina
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)
Chiew Carol
 
Plug-in Architectures
Plug-in ArchitecturesPlug-in Architectures
Plug-in Architectureselliando dias
 
Marionette - TorontoJS
Marionette - TorontoJSMarionette - TorontoJS
Marionette - TorontoJS
matt-briggs
 
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
Bill Heaton
 
Implementing the Genetic Algorithm in XSLT: PoC
Implementing the Genetic Algorithm in XSLT: PoCImplementing the Genetic Algorithm in XSLT: PoC
Implementing the Genetic Algorithm in XSLT: PoC
jimfuller2009
 
Beyond JavaScript Frameworks: Writing Reliable Web Apps With Elm - Erik Wende...
Beyond JavaScript Frameworks: Writing Reliable Web Apps With Elm - Erik Wende...Beyond JavaScript Frameworks: Writing Reliable Web Apps With Elm - Erik Wende...
Beyond JavaScript Frameworks: Writing Reliable Web Apps With Elm - Erik Wende...
Codemotion
 
Eclipse DemoCamp Toulouse 2017 - Mr. Robot : The modeling Society
Eclipse DemoCamp Toulouse 2017 - Mr. Robot : The modeling SocietyEclipse DemoCamp Toulouse 2017 - Mr. Robot : The modeling Society
Eclipse DemoCamp Toulouse 2017 - Mr. Robot : The modeling Society
melbats
 
The Benefits of Cogility
The Benefits of CogilityThe Benefits of Cogility
The Benefits of Cogility
Cogility
 
MODEL DRIVEN ARCHITECTURE, CONTROL SYSTEMS AND ECLIPSE
MODEL DRIVEN ARCHITECTURE, CONTROL SYSTEMS AND ECLIPSEMODEL DRIVEN ARCHITECTURE, CONTROL SYSTEMS AND ECLIPSE
MODEL DRIVEN ARCHITECTURE, CONTROL SYSTEMS AND ECLIPSE
Anže Vodovnik
 
.Net framework by naveen kumar veligeti
.Net framework by naveen kumar veligeti.Net framework by naveen kumar veligeti
.Net framework by naveen kumar veligeti
Naveen Kumar Veligeti
 
The Economics of OptimJ
The Economics of OptimJThe Economics of OptimJ
The Economics of OptimJ
Patrick Viry
 
The OptimJ Manual
The OptimJ ManualThe OptimJ Manual
The OptimJ Manual
Patrick Viry
 
Standards-Based Executable UML: Today's Reality and Tomorrow's Promise
Standards-Based Executable UML: Today's Reality and Tomorrow's PromiseStandards-Based Executable UML: Today's Reality and Tomorrow's Promise
Standards-Based Executable UML: Today's Reality and Tomorrow's Promise
Ed Seidewitz
 
Basic iOS Training with SWIFT - Part 1
Basic iOS Training with SWIFT - Part 1Basic iOS Training with SWIFT - Part 1
Basic iOS Training with SWIFT - Part 1
Manoj Ellappan
 
Rethinking Best Practices
Rethinking Best PracticesRethinking Best Practices
Rethinking Best Practices
floydophone
 
Spring aop
Spring aopSpring aop
Spring aop
Hamid Ghorbani
 
STATICMOCK : A Mock Object Framework for Compiled Languages
STATICMOCK : A Mock Object Framework for Compiled Languages STATICMOCK : A Mock Object Framework for Compiled Languages
STATICMOCK : A Mock Object Framework for Compiled Languages
ijseajournal
 
Software development effort reduction with Co-op
Software development effort reduction with Co-opSoftware development effort reduction with Co-op
Software development effort reduction with Co-op
lbergmans
 

Similar to Elm Detroit 9/7/17 - Planting Seeds with Elm (20)

ALMOsT.js: an Agile Model to Model and Model to Text Transformation Framework
ALMOsT.js: an Agile Model to Model and Model to Text Transformation FrameworkALMOsT.js: an Agile Model to Model and Model to Text Transformation Framework
ALMOsT.js: an Agile Model to Model and Model to Text Transformation Framework
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)
 
Plug-in Architectures
Plug-in ArchitecturesPlug-in Architectures
Plug-in Architectures
 
Marionette - TorontoJS
Marionette - TorontoJSMarionette - TorontoJS
Marionette - TorontoJS
 
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
 
Implementing the Genetic Algorithm in XSLT: PoC
Implementing the Genetic Algorithm in XSLT: PoCImplementing the Genetic Algorithm in XSLT: PoC
Implementing the Genetic Algorithm in XSLT: PoC
 
Jmp108
Jmp108Jmp108
Jmp108
 
Beyond JavaScript Frameworks: Writing Reliable Web Apps With Elm - Erik Wende...
Beyond JavaScript Frameworks: Writing Reliable Web Apps With Elm - Erik Wende...Beyond JavaScript Frameworks: Writing Reliable Web Apps With Elm - Erik Wende...
Beyond JavaScript Frameworks: Writing Reliable Web Apps With Elm - Erik Wende...
 
Eclipse DemoCamp Toulouse 2017 - Mr. Robot : The modeling Society
Eclipse DemoCamp Toulouse 2017 - Mr. Robot : The modeling SocietyEclipse DemoCamp Toulouse 2017 - Mr. Robot : The modeling Society
Eclipse DemoCamp Toulouse 2017 - Mr. Robot : The modeling Society
 
The Benefits of Cogility
The Benefits of CogilityThe Benefits of Cogility
The Benefits of Cogility
 
MODEL DRIVEN ARCHITECTURE, CONTROL SYSTEMS AND ECLIPSE
MODEL DRIVEN ARCHITECTURE, CONTROL SYSTEMS AND ECLIPSEMODEL DRIVEN ARCHITECTURE, CONTROL SYSTEMS AND ECLIPSE
MODEL DRIVEN ARCHITECTURE, CONTROL SYSTEMS AND ECLIPSE
 
.Net framework by naveen kumar veligeti
.Net framework by naveen kumar veligeti.Net framework by naveen kumar veligeti
.Net framework by naveen kumar veligeti
 
The Economics of OptimJ
The Economics of OptimJThe Economics of OptimJ
The Economics of OptimJ
 
The OptimJ Manual
The OptimJ ManualThe OptimJ Manual
The OptimJ Manual
 
Standards-Based Executable UML: Today's Reality and Tomorrow's Promise
Standards-Based Executable UML: Today's Reality and Tomorrow's PromiseStandards-Based Executable UML: Today's Reality and Tomorrow's Promise
Standards-Based Executable UML: Today's Reality and Tomorrow's Promise
 
Basic iOS Training with SWIFT - Part 1
Basic iOS Training with SWIFT - Part 1Basic iOS Training with SWIFT - Part 1
Basic iOS Training with SWIFT - Part 1
 
Rethinking Best Practices
Rethinking Best PracticesRethinking Best Practices
Rethinking Best Practices
 
Spring aop
Spring aopSpring aop
Spring aop
 
STATICMOCK : A Mock Object Framework for Compiled Languages
STATICMOCK : A Mock Object Framework for Compiled Languages STATICMOCK : A Mock Object Framework for Compiled Languages
STATICMOCK : A Mock Object Framework for Compiled Languages
 
Software development effort reduction with Co-op
Software development effort reduction with Co-opSoftware development effort reduction with Co-op
Software development effort reduction with Co-op
 

Recently uploaded

Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 

Recently uploaded (20)

Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 

Elm Detroit 9/7/17 - Planting Seeds with Elm

  • 1. ElmDetroit–PlantingSeedswithElm September7,2017 11 Elm Detroit Planting Seeds with Elm An introduction to the Elm programming language
  • 3. ElmDetroit–PlantingSeedswithElm September7,2017 3  Functional language for the browser  Strongly and statically typed  Compiles to JavaScript  ML style language, written in Haskell  Declarative syntax What is Elm?
  • 5. ElmDetroit–PlantingSeedswithElm September7,2017 5  A beginner friendly language with a minimal but powerful set of features  A quick and kind compiler that provides type inference  Advertises “No” runtime exceptions  An architecture designed for the language  Fully interoperable with JavaScript  Enforces semantic versioning  A helpful and friendly community  A really nice formatter that eliminates the need for a linter What makes Elm special?
  • 6. ElmDetroit–PlantingSeedswithElm September7,2017 6  A quick and kind compiler that provides type inference What makes Elm special?
  • 7. ElmDetroit–PlantingSeedswithElm September7,2017 7  A quick and kind compiler that provides type inference What makes Elm special?
  • 8. ElmDetroit–PlantingSeedswithElm September7,2017 8  A note on type inference:  Type inference allows the compiler to “infer” the types in your app without you explicitly defining them.  For instance, the following function definition examples are both valid:  In spite of this, it’s a good practice to provide the type annotations to improve readability and general code quality. What makes Elm special? or
  • 9. ElmDetroit–PlantingSeedswithElm September7,2017 9  A quick and kind compiler that provides type inference  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 What makes Elm special?
  • 10. ElmDetroit–PlantingSeedswithElm September7,201710  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 What makes Elm special?
  • 11. ElmDetroit–PlantingSeedswithElm September7,201711  Advertises “No” runtime exceptions From personal and professional experience, I have experienced this firsthand. Clarity has had 5 projects in production over the past 18 months and these stats still hold true. What makes Elm special? This article has more insight on the subject: http://elm-lang.org/blog/compilers-as-assistants
  • 13. ElmDetroit–PlantingSeedswithElm September7,201713  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 The Elm Architecture View Model Update
  • 16. ElmDetroit–PlantingSeedswithElm September7,201716  After compilation, the code below produces a simple counter app A simple example…
  • 18. ElmDetroit–PlantingSeedswithElm September7,201718  This is a walkthrough of code I modified from the original HTTP example from the Elm site: https://ellie-app.com/4fgzBGyFzcYa1/0  Original example: http://elm-lang.org/examples/http An example of The Elm Architecture
  • 19. ElmDetroit–PlantingSeedswithElm September7,201719  Elm uses modules as method to split up code  The code (..) exposes everything to the consuming module.  Consider exposed functions your “public” API for a module  Anything not exposed is “private” to the module.  Next, we move on to our application’s imports A module system
  • 20. ElmDetroit–PlantingSeedswithElm September7,201720  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 A module system
  • 21. ElmDetroit–PlantingSeedswithElm September7,201721  Code that 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) Setting up the application
  • 22. ElmDetroit–PlantingSeedswithElm September7,201722  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.  The main three types of programs exposed by the Html module are:  Html.beginnerProgram  Html.program  Html.programWithFlags Setting up the application
  • 23. ElmDetroit–PlantingSeedswithElm September7,201723  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. Setting up the application
  • 24. ElmDetroit–PlantingSeedswithElm September7,201724  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. The Model
  • 25. ElmDetroit–PlantingSeedswithElm September7,201725  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 Union Types and modeling data
  • 26. ElmDetroit–PlantingSeedswithElm September7,201726  A more complex union type example:  Referenced from RemoteData package by Kris Jenkins: http://package.elm-lang.org/packages/krisajenkins/remotedata/latest Union Types and modeling data
  • 27. ElmDetroit–PlantingSeedswithElm September7,201727  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:  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. Union Types and modeling data
  • 28. ElmDetroit–PlantingSeedswithElm September7,201728  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! Union Types and modeling data
  • 29. ElmDetroit–PlantingSeedswithElm September7,201729  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. Updating State
  • 30. ElmDetroit–PlantingSeedswithElm September7,201730 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
  • 31. ElmDetroit–PlantingSeedswithElm September7,201731  Your applications View code defines what is displayed to the end user at any given time  A view can also be comprised of other functions that serve as sub views or partial views.  As with all Elm code, view is just a pure function and starts with a type and function definition  The type definition here says that this function takes in a Model and emits an Html Msg The View
  • 32. ElmDetroit–PlantingSeedswithElm September7,201732  Elm has let statements which allow you to define variables that are local to the scope between let and in.  In the code below, let..in is being used to assign multiple variables (ex: waitingGifUrl, buttonText etc.) at once that will be used in the context below the in keyword.  The code(firstRun, gifUrl) uses destructuring to assign multiple variables at once based on the case. The View
  • 33. ElmDetroit–PlantingSeedswithElm September7,201733  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): The View
  • 34. ElmDetroit–PlantingSeedswithElm September7,201734  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  An example of using the pipe-operator from the official site: http://elm-lang.org/examples/pipes/code A simple Http request 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.
  • 35. ElmDetroit–PlantingSeedswithElm September7,201735  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). Decoding the data
  • 36. ElmDetroit–PlantingSeedswithElm September7,201736  Since everything in Elm is a function, we can easily cleanup our codebase as it grows. For instance, the following three functions were originally part of the let..in block of my view code  As my code grew, it seems intuitive to break those out into their own bite sized chunks of code. This also lends itself well to reuse. Functions everywhere!
  • 37. ElmDetroit–PlantingSeedswithElm September7,201737  More on scaling and reuse in Elm:  From the official guide: https://guide.elm-lang.org/reuse/  An example of scalable SPA in Elm: https://github.com/rtfeldman/elm-spa-example Scaling and reuse
  • 38. ElmDetroit–PlantingSeedswithElm September7,201738  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. JavaScript Interop
  • 39. ElmDetroit–PlantingSeedswithElm September7,201739  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: JavaScript Interop
  • 40. ElmDetroit–PlantingSeedswithElm September7,201740  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: JavaScript Interop
  • 41. ElmDetroit–PlantingSeedswithElm September7,201741  To subscribe (listen) for messages coming in on this port, we need to add a subscription to our subscriptions function: JavaScript Interop When we receive messages from this port the update function will be called with ExecuteInboundPort as the message
  • 42. ElmDetroit–PlantingSeedswithElm September7,201742  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 Commands and Subscriptions
  • 44. ElmDetroit–PlantingSeedswithElm September7,201744  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 Getting started with Elm
  • 45. ElmDetroit–PlantingSeedswithElm September7,201745  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. Getting started with Elm
  • 46. ElmDetroit–PlantingSeedswithElm September7,201746  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 Resources