SlideShare une entreprise Scribd logo
1  sur  101
Télécharger pour lire hors ligne
Functional Web
Programming using Elm
Spencer Schneidenbach
@schneidenbach
schneids.net
Common element?
JavaScript
this
https://
www.christosmonogios.
com/2016/08/15/The-
This-Keyword-In-
JavaScript-Must-Know-
JavaScript-Features-
Every-Programmer-
Should-Learn-To-
Master-The-Language/
http://odetocode.com/
blogs/scott/archive/
2016/09/01/the-
troubles-with-
javascript-arrow-
functions.aspx
https://
derickbailey.com/
2016/08/22/
undefined-is-not-
a-function/
http://
www.bitnative.co
m/2016/08/18/
react-binding-
patterns-this-
keyword/
http://
www.javascripthive.info/
javascript/context-this/
var customer = repo.getCustomer(id);
var orders = customer.getOrders();
var customer = repo.getCustomer(id);
var orders = customer.getHorDoeuvres();
var customer = repo.getCustomer(id);
var orders = customer.getOrderes();
JavaScript Isn’t Bad.
JavaScript Is Weird.
Elm “just works.”
Not like a Mac “just
works”
That’s pretty vague
So let’s dig in
Four things
One: handling null
null
–Tony Hoare
“I call it my billion-dollar mistake. It was the
invention of the null reference in 1965.”
null/undefined
What about in Elm?
type alias Order = {
name: String,
date: Date,
amount: Float
}
type alias Order = {
name: String,
date: Date,
amount: Float
}
myOrder: Order
myOrder : Order
myOrder = {

--no name
date = today,
amount = 123.45 }
myOrder : Order
myOrder = {
name = null,
date = today,
amount = 123.45
}
So where is null?
Easy: there IS no null
Easy: there IS no null
(loud applause and
cheering)
type Maybe a = Just a | Nothing
getAmount : Maybe Int -> String
getAmount maybeInt =
case maybeInt of
Just i -> "You have: " ++ toString i
Nothing -> "You don't have any!"
type Maybe a = Just a | Nothing
type ContactType =
Email String
| Phone Int
| Twitter String
| Address MailingAddress
type ContactType =
Email String
| Phone Int
| Twitter String
| Address MailingAddress
contactPerson : ContactType -> String
contactPerson contact =
case contact of
Email email -> email
Phone phoneNumber -> "Phone: " ++ toString phoneNumber
Twitter twitterHandle -> "Twitter: " ++ twitterHandle
type ContactType =
Email String
| Phone Int
| Twitter String
| Address MailingAddress
contactPerson : ContactType -> String
contactPerson contact =
case contact of
Email email -> email
Phone phoneNumber -> "Phone: " ++ toString phoneNumber
Twitter twitterHandle -> "Twitter: " ++ twitterHandle
Address myAddress -> "No one sends mail anymore"
No void
Two: immutability
Let’s set the stage
Feature request:

Order amounts that are negative
should have a red name
Feature request:

Salespeople who are not active
should not be displayed
What about Elm?
No mutation.
Can’t modify existing
objects.
Instead, you create
copies
myOrder : Order
myOrder = {
name = "Lumber",
contact = Email "sas.projects@me.com",
amount = 123.45 }
myOrder : Order
myOrder = {
name = "Lumber",
contact = Email "sas.projects@me.com",
amount = 123.45 }
myOrder.contact = Phone 5551234
myOrder : Order
myOrder = {
name = "Lumber",
contact = Email "sas.projects@me.com",
amount = 123.45 }
myOrder = {
name = "Lumber",
contact = Phone 5551234,
amount = 123.45 }
myOrder : Order
myOrder = {
name = "Lumber",
contact = Email "sas.projects@me.com",
amount = 123.45 }
myNewOrder : Order
myNewOrder = { myOrder | contact = Phone 5551234 }
Three: error handling
Guess what?
There are
NO RUNTIME ERRORS
in Elm
type Maybe a = Just a | Nothing
function getInputCount() {
var input = $(".count").val();
return parseInt(input);
}
function getInputCount() {
var input = $(".count").val(); //bgggs
return parseInt(input); //NaN
}
type Result error value
= Err error
| Ok value
String.toInt : String -> Result String Int
multiplyStrings : String -> String -> Maybe Int
multiplyStrings str1 str2 =
let
intStringOne = String.toInt str1
intStringTwo = String.toInt str2
in
case (intStringOne, intStringTwo) of
(Ok int, Ok int2) -> Just (int * int2)
(_, _) -> Nothing
No try/catch blocks
Elm makes you handle
errors.
Four: The Elm Architecture
function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
let store = createStore(counter)
store.dispatch({ type: 'INCREMENT' })
function employeeStore(state = [], action) {
switch (action.type) {
case 'ADD':
return [...state, action.employee]
default:
return state
}
}
let store = createStore(employeeStore)
store.dispatch({
type: 'ADD',
employee: { firstName: 'Spencer' }
})
function employeeStore(state = [], action) {
switch (action.type) {
case 'ADD':
state.push(action.employee);
return state;
default:
return state
}
}
let store = createStore(employeeStore)
store.dispatch({
type: 'ADD',
employee: { firstName: 'Spencer' }
})
function employeeStore(state = [], action) {
switch (action.type) {
case 'ADD':
return state.push(action.employee);
default:
return state
}
}
let store = createStore(employeeStore)
store.dispatch({
type: 'ADD',
employee: { firstName: 'Spencer' }
})
Array.push -> number
Model
Update
View
-- MODEL
type alias Model = Int
model : Model
model = 0
-- UPDATE
type Msg = Increment | Decrement
update : Msg -> Model -> Model
update msg model =
case msg of
Increment ->
model + 1
Decrement ->
model - 1
-- UPDATE
type Msg = Increment | Decrement
update : Msg -> Model -> Model
update msg model =
case msg of
Increment ->
model + 1
-- UPDATE
type Msg = Increment | Decrement
update : Msg -> Model -> Model
update msg model =
case msg of
Increment ->
model + 1
Decrement ->
model - 1
-- VIEW
view : Model -> Html Msg
view model =
div []
[ button [ onClick Decrement ] [ text "-" ]
, div [] [ text (toString model) ]
, button [ onClick Increment ] [ text "+" ]
]
1. null handling
2. immutability
3. error handling
4. The Elm Architecture
Thank you!
@schneidenbach
schneids.net

Contenu connexe

Tendances

Posts ‹ teslaecoenergy — word press php
Posts ‹ teslaecoenergy — word press phpPosts ‹ teslaecoenergy — word press php
Posts ‹ teslaecoenergy — word press php
Miroslav Miskovic
 

Tendances (18)

Documentadsbyadbrite1
Documentadsbyadbrite1Documentadsbyadbrite1
Documentadsbyadbrite1
 
mondrian-olap JRuby library
mondrian-olap JRuby librarymondrian-olap JRuby library
mondrian-olap JRuby library
 
Posts ‹ teslaecoenergy — word press php
Posts ‹ teslaecoenergy — word press phpPosts ‹ teslaecoenergy — word press php
Posts ‹ teslaecoenergy — word press php
 
Merb jQuery
Merb jQueryMerb jQuery
Merb jQuery
 
HTML5 workshop, forms
HTML5 workshop, formsHTML5 workshop, forms
HTML5 workshop, forms
 
Borrador del blog
Borrador del blogBorrador del blog
Borrador del blog
 
Testing ASP.net Web Applications using Ruby
Testing ASP.net Web Applications using RubyTesting ASP.net Web Applications using Ruby
Testing ASP.net Web Applications using Ruby
 
Javascript validating form
Javascript validating formJavascript validating form
Javascript validating form
 
Form validation and animation
Form validation and animationForm validation and animation
Form validation and animation
 
The War is Over, and JavaScript has won: Living Under the JS Regime
The War is Over, and JavaScript has won: Living Under the JS RegimeThe War is Over, and JavaScript has won: Living Under the JS Regime
The War is Over, and JavaScript has won: Living Under the JS Regime
 
jQuery Presentation to Rails Developers
jQuery Presentation to Rails DevelopersjQuery Presentation to Rails Developers
jQuery Presentation to Rails Developers
 
Ruby-ying Javascript: Avoiding jQuery Spaghetti
Ruby-ying Javascript: Avoiding jQuery SpaghettiRuby-ying Javascript: Avoiding jQuery Spaghetti
Ruby-ying Javascript: Avoiding jQuery Spaghetti
 
A Journey with React
A Journey with ReactA Journey with React
A Journey with React
 
WordPress REST API: Expert Advice & Practical Use Cases
WordPress REST API: Expert Advice & Practical Use CasesWordPress REST API: Expert Advice & Practical Use Cases
WordPress REST API: Expert Advice & Practical Use Cases
 
How Reactive do we need to be
How Reactive do we need to beHow Reactive do we need to be
How Reactive do we need to be
 
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
 
Building complex User Interfaces with Sitecore and React
Building complex User Interfaces with Sitecore and ReactBuilding complex User Interfaces with Sitecore and React
Building complex User Interfaces with Sitecore and React
 
Creating a-pagination-with-php
Creating a-pagination-with-phpCreating a-pagination-with-php
Creating a-pagination-with-php
 

En vedette

JavaScript für Java-Entwickler W-JAX 2013
JavaScript für Java-Entwickler W-JAX 2013JavaScript für Java-Entwickler W-JAX 2013
JavaScript für Java-Entwickler W-JAX 2013
Oliver Zeigermann
 
track1 05. 스타트업 1인 개발 극복기’와 ‘javascript vs Scala, (함수형 언어 관점으로)방황기/ I/O Inc, ...
track1 05. 스타트업 1인 개발 극복기’와 ‘javascript vs Scala, (함수형 언어 관점으로)방황기/ I/O Inc, ...track1 05. 스타트업 1인 개발 극복기’와 ‘javascript vs Scala, (함수형 언어 관점으로)방황기/ I/O Inc, ...
track1 05. 스타트업 1인 개발 극복기’와 ‘javascript vs Scala, (함수형 언어 관점으로)방황기/ I/O Inc, ...
양 한빛
 

En vedette (20)

Elm: delightful web development
Elm: delightful web developmentElm: delightful web development
Elm: delightful web development
 
Introduction to Elm
Introduction to ElmIntroduction to Elm
Introduction to Elm
 
Elm intro
Elm introElm intro
Elm intro
 
Elm presentation
Elm presentationElm presentation
Elm presentation
 
Elm a possible future for web frontend
Elm   a possible future for web frontendElm   a possible future for web frontend
Elm a possible future for web frontend
 
Claudia Doppioslash - Time Travel for game development with Elm
Claudia Doppioslash - Time Travel for game development with ElmClaudia Doppioslash - Time Travel for game development with Elm
Claudia Doppioslash - Time Travel for game development with Elm
 
Elm: frontend code without runtime exceptions
Elm: frontend code without runtime exceptionsElm: frontend code without runtime exceptions
Elm: frontend code without runtime exceptions
 
Very basic functional design patterns
Very basic functional design patternsVery basic functional design patterns
Very basic functional design patterns
 
Elixir and elm - the perfect couple
Elixir and elm - the perfect coupleElixir and elm - the perfect couple
Elixir and elm - the perfect couple
 
ASP.NET Core - Phillosophies, Processes and Tooling
ASP.NET Core - Phillosophies, Processes and ToolingASP.NET Core - Phillosophies, Processes and Tooling
ASP.NET Core - Phillosophies, Processes and Tooling
 
JavaScript für Java-Entwickler W-JAX 2013
JavaScript für Java-Entwickler W-JAX 2013JavaScript für Java-Entwickler W-JAX 2013
JavaScript für Java-Entwickler W-JAX 2013
 
Lebenslauf
LebenslaufLebenslauf
Lebenslauf
 
Flask! - python web framework flask 튜토리얼
Flask! - python web framework flask 튜토리얼Flask! - python web framework flask 튜토리얼
Flask! - python web framework flask 튜토리얼
 
Play with Elm!
Play with Elm!Play with Elm!
Play with Elm!
 
Rethink Frontend Development With Elm
Rethink Frontend Development With ElmRethink Frontend Development With Elm
Rethink Frontend Development With Elm
 
Elm: Make Yourself A Happy Front-end Web Developer
Elm: Make Yourself A Happy Front-end Web DeveloperElm: Make Yourself A Happy Front-end Web Developer
Elm: Make Yourself A Happy Front-end Web Developer
 
track1 05. 스타트업 1인 개발 극복기’와 ‘javascript vs Scala, (함수형 언어 관점으로)방황기/ I/O Inc, ...
track1 05. 스타트업 1인 개발 극복기’와 ‘javascript vs Scala, (함수형 언어 관점으로)방황기/ I/O Inc, ...track1 05. 스타트업 1인 개발 극복기’와 ‘javascript vs Scala, (함수형 언어 관점으로)방황기/ I/O Inc, ...
track1 05. 스타트업 1인 개발 극복기’와 ‘javascript vs Scala, (함수형 언어 관점으로)방황기/ I/O Inc, ...
 
29. Treffen - Tobias Meier - TypeScript
29. Treffen - Tobias Meier - TypeScript29. Treffen - Tobias Meier - TypeScript
29. Treffen - Tobias Meier - TypeScript
 
An Intro to Angular 2
An Intro to Angular 2An Intro to Angular 2
An Intro to Angular 2
 
플라스크 템플릿
플라스크 템플릿플라스크 템플릿
플라스크 템플릿
 

Similaire à Functional Web Development using Elm

Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片
cfc
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Paulo Ragonha
 
Introduction to angular js july 6th 2014
Introduction to angular js   july 6th 2014Introduction to angular js   july 6th 2014
Introduction to angular js july 6th 2014
Simona Clapan
 

Similaire à Functional Web Development using Elm (20)

GraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedGraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learned
 
Angular js - 4developers 12 kwietnia 2013
Angular js - 4developers 12 kwietnia 2013Angular js - 4developers 12 kwietnia 2013
Angular js - 4developers 12 kwietnia 2013
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
 
Agile data presentation 3 - cambridge
Agile data   presentation 3 - cambridgeAgile data   presentation 3 - cambridge
Agile data presentation 3 - cambridge
 
How to make Ajax work for you
How to make Ajax work for youHow to make Ajax work for you
How to make Ajax work for you
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
 
Os Pruett
Os PruettOs Pruett
Os Pruett
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 
Scti 2011 minicurso jquery
Scti 2011 minicurso jqueryScti 2011 minicurso jquery
Scti 2011 minicurso jquery
 
Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片
 
React Native - Workshop
React Native - WorkshopReact Native - Workshop
React Native - Workshop
 
Func up your code
Func up your codeFunc up your code
Func up your code
 
oracle soa Examples
oracle soa Examplesoracle soa Examples
oracle soa Examples
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
Server side rendering with React and Symfony
Server side rendering with React and SymfonyServer side rendering with React and Symfony
Server side rendering with React and Symfony
 
Repensando o Desenvolvimento Web com Ruby on Rails
Repensando o Desenvolvimento Web com Ruby on RailsRepensando o Desenvolvimento Web com Ruby on Rails
Repensando o Desenvolvimento Web com Ruby on Rails
 
Introduction to angular js july 6th 2014
Introduction to angular js   july 6th 2014Introduction to angular js   july 6th 2014
Introduction to angular js july 6th 2014
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 
GraphQL, Redux, and React
GraphQL, Redux, and ReactGraphQL, Redux, and React
GraphQL, Redux, and React
 
Code is Cool - Products are Better
Code is Cool - Products are BetterCode is Cool - Products are Better
Code is Cool - Products are Better
 

Dernier

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

Functional Web Development using Elm