SlideShare a Scribd company logo
Luca Mugnaini
Functional Programming
and Elm
Functional Programming
Originated from lambda calculus developed in
the 1930s by Alonzo Church
What is Functional Programming?
Programming with
mathematical functions*
*It doesn’t mean you need to know math
• Do this, then do that
• Any effect (Unsafe)
• Commands (statements)
• Control Flow
• Name of a location
Imperative
• No notion of sequence
• Limited effect (Safe)
• Expressions
• Data Flow
• Name of a value
vs. Functional
f : a à World à (World, b)
If there are no side-effects, how can
we change the state of the world?
f... takes in the state of the
world and returns a new
world, thus remaining pure
No Side-effects
update : Msg à Model à ( Model, Cmd Msg )
https://channel9.msdn.com/Shows/Going+Deep/Erik-Meijer-Functional-Programming
Functional-flavored
• Lisp 1958 (Scheme, Clojure,
Racket)
• ML ”Lisp with types” =>
Ocaml (F#, Scala, Reason)
• Erlang (Elixir)
• Javascript, Java 8, Kotlin,
Perl, Python, PHP, etc.
Functional-first, Pure
• Haskell (Elm)
Nirvana
“Haskell is useless”
Simon Peyton Jones
Honesty/Dishonesty
Erik Meijer
https://www.youtube.com/watch?v=iSmkqocn0oQ&t=22s
https://www.youtube.com/watch?v=z0N1aZ6SnBk&t=533
https://www.infoq.com/presentations/Taming-Effect-Simon-Peyton-Jones
Web Development
Web Development Fatigue3
Javascript fatigue +
CSS fatigue +
Framework/Npm fatigue =
Web
Development
Fatigue
What if I told you
Front-end can be done
without Javascript, HTML, CSS?
Elm
● Pure Functional Language
● Compiles to Javascript
● Statically typed + inferred
● Support Immutability and Currying
● Virtual DOM
What is Elm?
● Designed by Evan Czaplicki
● April 2012: Version 0.1
● August 2018: Latest version 0.19
● Stable (21 months since 0.18)
● Community in elmlang.slack.com
History
● No loops (“i = i + 1” doesn’t compile)
● No “null” and no “undefined”
● No “return”, everything is an expression
● “if” always need “else”
● No “this”, no callbacks, no closures, no hoisting
● No automatic type conversion
● JSON decoder/encoder instead of stringify/parse
Differences with Javascript
Javascript Elm
npm / yarn Built in
React / Angular / Vue
Flux / Redux / MobX
Built in
Built in
Immutable.js
Typescript / Flow
Built in
Built in
Without HTML, CSS: elm-ui
row [ padding 10, spacing 7 ]
[ el [] none
, el [] none
, el [] none
]
spacing : Distance between children
padding : Parent Padding
[ centerX
, centerY
]
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform:
translate(-50%, -50%);
}
CSS elm-ui
No more CSS tricks
10
nice
things
about
Elm
Nice thing #1
Helpful, friendly errors
Nice thing #2
No runtime exceptions
Nice thing #3
Performance
Nice thing #4
Enforced Semantic
Nice thing #5
Time-travelling debugger
Nice thing #6
Type inference
Nice thing #7
elm-format
Nice thing #8
Demystify FP concepts
Functors
Monads Category Theory
Algebraic Data Type
The Elm Architecture is a simple pattern for
architecting webapps. It is made of thee parts
Nice thing #9
The Elm Architecture (TEA)
Model the state of your application
View a way to view your state as HTML
Update a way to update your state
28
Cartoon cute unicorns vectors design by loutpany from https://freedesignfile.com
Safe AreaUnsafe Area
Elm Runtime
DOM
MsgModel
Model
Model
Html
Model
New!
Effects
http requests,
ports Cmd
EventEvent!
New!
New!
Cmd
DOM
Html
EventEvent!
update
view
[1,2] + [3,4] = ?
[1,2] + [3,4] = ?
Error [1,2,3,4]
[4,6] “1,23,4”
A B
C D
"1,23,4"
Javascript Elm
-- TYPE MISMATCH ---------------------
I cannot do addition with lists:
[1,2] + [3,4]
^^^^^
The left side of (+) is a list of type:
List number
But (+) only works with Int and Float
values.
Hint: Switch to the (++) operator to
append lists!
[1,2] + [3,4] = ?
What can go wrong with
automatic type conversion?
https://itnext.io/things-that-can-go-wrong-without-a-strictly-typed-language-d91d418a53a1
“If you want user input to be automatically typecast as a
number, you can add the number modifier to your v-
model managed inputs”
<input type="number" v-model="product.quantity">
<input type="number" v-model.number="product.quantity">
totalProducts() {
return this.products.reduce((sum, product) => {
return sum + product.quantity
}, 0)
}
totalProducts() {
return this.products.reduce((sum, product) => {
if (typeof product.quantity === "number") {
return sum + product.quantity;
} else {
return sum;
}
}, 0)
}
<button @click="product.quantity += 1">
<button @click="product.quantity = Number(product.quantity) + 1">
Now it works but...
type alias Product =
{ id : Int
, quantity : Int
, name : String
}
changeQuantity : Product -> String -> Product
changeQuantity product newQuantity =
{ product
| quantity =
Maybe.withDefault product.quantity
(String.toInt newQuantity)
}
“If the user typed a valid number, replace the old number with the
new one, otherwise keep the old number”
Typos <input v-model.number="product.quanity">
t
Elm
Fail silently
Input fields are
empty but buttons
work.
-- TYPE MISMATCH --------------------
The 2nd argument to `map` is not what I
expect:
84| products
^^^^^^^^
This `products` value is a:
List Product
But `map` needs the 2nd argument to be:
List { a | id : Int, name : String, quanity
: Int, quantity : Int }
Hint: Seems like a record field typo. Maybe
quanity should be quantity?
Vue
C de
module Main exposing (main)
import Html exposing (..)
import Html.Attributes exposing (..)
main =
div []
[ button [id "counter"] [ text "+1" ]
, div [] [ text <| String.fromInt 0 ]
, button [] [ text ”-1" ]
]
<div id="counter">
<button>+1</button>
<div>0</div>
<button>-1</button>
</div>
-- MODEL
type alias Model =
{ count : Int }
init : Model
init =
{ count = 0 }
-- UPDATE
type Msg
= Increment
| Decrement
update : Msg -> Model -> Model
update msg model =
case msg of
Increment ->
{ model | count = model.count + 1 }
Decrement ->
{ model | count = model.count - 1 }
-- VIEW
view : Model -> Html Msg
view model =
layout [] <|
column []
[ button []
{ onPress = Just Increment
, label = text "+1"
}
, el [] <|
text (String.fromInt model.count)
, button []
{ onPress = Just Decrement
, label = text "-1"
}
]
main : Program () Model Msg
main =
Browser.sandbox
{ init = init
, view = view
, update = update
}
Examples
ellie-app.comhttps://ellie-app.com/4ddCRdyx4Rta1
www.nsb.no
unsoundscapes.itch.io/cubik
malax.github.io/elmboy
● The ideas of Functional Programming are
becoming mainstream (for a reason)
● Learning Elm will make you a better [Javascript,
React, Angular, Vue, etc.] developer
● Writing pure code is an enjoyable experience
that make front-end development fun again!

More Related Content

What's hot

GNU octave
GNU octaveGNU octave
GNU octave
gauravmalav
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
nikshaikh786
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
RaginiJain21
 
User Defined Functions in MATLAB Part-4
User Defined Functions in MATLAB Part-4User Defined Functions in MATLAB Part-4
User Defined Functions in MATLAB Part-4
Shameer Ahmed Koya
 
Getting started in c++
Getting started in c++Getting started in c++
Getting started in c++
Neeru Mittal
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
Andraž Bajt
 
Stack_Data_Structure.pptx
Stack_Data_Structure.pptxStack_Data_Structure.pptx
Stack_Data_Structure.pptx
sandeep54552
 
Stacks Implementation and Examples
Stacks Implementation and ExamplesStacks Implementation and Examples
Stacks Implementation and Examplesgreatqadirgee4u
 
Seminar 2 coding_principles
Seminar 2 coding_principlesSeminar 2 coding_principles
Seminar 2 coding_principles
moduledesign
 
Reasoning about laziness
Reasoning about lazinessReasoning about laziness
Reasoning about lazinessJohan Tibell
 
Seminar 2 coding_principles
Seminar 2 coding_principlesSeminar 2 coding_principles
Seminar 2 coding_principles
moduledesign
 
Stack data structure
Stack data structureStack data structure
Stack data structureTech_MX
 
Lecture 6
Lecture 6Lecture 6
Lecture 6
Tanveer Malik
 
MATLAB Programming
MATLAB Programming MATLAB Programming
MATLAB Programming
محمدعبد الحى
 
A taste of Functional Programming
A taste of Functional ProgrammingA taste of Functional Programming
A taste of Functional Programming
Jordan Open Source Association
 
Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)
Saket Pathak
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Nikhil Pandit
 

What's hot (20)

Loop Statements [5] M
Loop Statements [5] MLoop Statements [5] M
Loop Statements [5] M
 
GNU octave
GNU octaveGNU octave
GNU octave
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
 
User Defined Functions in MATLAB Part-4
User Defined Functions in MATLAB Part-4User Defined Functions in MATLAB Part-4
User Defined Functions in MATLAB Part-4
 
Getting started in c++
Getting started in c++Getting started in c++
Getting started in c++
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
 
Stack_Data_Structure.pptx
Stack_Data_Structure.pptxStack_Data_Structure.pptx
Stack_Data_Structure.pptx
 
Stacks Implementation and Examples
Stacks Implementation and ExamplesStacks Implementation and Examples
Stacks Implementation and Examples
 
Seminar 2 coding_principles
Seminar 2 coding_principlesSeminar 2 coding_principles
Seminar 2 coding_principles
 
Reasoning about laziness
Reasoning about lazinessReasoning about laziness
Reasoning about laziness
 
Stack
StackStack
Stack
 
Seminar 2 coding_principles
Seminar 2 coding_principlesSeminar 2 coding_principles
Seminar 2 coding_principles
 
Queue
QueueQueue
Queue
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
Lecture 6
Lecture 6Lecture 6
Lecture 6
 
MATLAB Programming
MATLAB Programming MATLAB Programming
MATLAB Programming
 
A taste of Functional Programming
A taste of Functional ProgrammingA taste of Functional Programming
A taste of Functional Programming
 
Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 

Similar to Functional programming and Elm

Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
Scott Wlaschin
 
Mechanical Engineering Homework Help
Mechanical Engineering Homework HelpMechanical Engineering Homework Help
Mechanical Engineering Homework Help
Matlab Assignment Experts
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
Yuan Wang
 
Functional go
Functional goFunctional go
Functional go
Geison Goes
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
MuskanSony
 
ScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin Odersky
Typesafe
 
Python For Machine Learning
Python For Machine LearningPython For Machine Learning
Python For Machine Learning
YounesCharfaoui
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
RichardWarburton
 
elm-d3 @ NYC D3.js Meetup (30 June, 2014)
elm-d3 @ NYC D3.js Meetup (30 June, 2014)elm-d3 @ NYC D3.js Meetup (30 June, 2014)
elm-d3 @ NYC D3.js Meetup (30 June, 2014)Spiros
 
Mat lab workshop
Mat lab workshopMat lab workshop
Mat lab workshop
Vinay Kumar
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
Movel
 
Matlab-3.pptx
Matlab-3.pptxMatlab-3.pptx
Matlab-3.pptx
aboma2hawi
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2Mohamed Ahmed
 
.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#
Bertrand Le Roy
 
Enrich enriching mathematics conversi biner 16 pada sisikomputerize indoensia...
Enrich enriching mathematics conversi biner 16 pada sisikomputerize indoensia...Enrich enriching mathematics conversi biner 16 pada sisikomputerize indoensia...
Enrich enriching mathematics conversi biner 16 pada sisikomputerize indoensia...
Dadangsachir WANDA ir.mba
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programming
Dhaval Dalal
 
Go Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional ProgrammingGo Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional Programming
Lex Sheehan
 
London F-Sharp User Group : Don Syme on F# - 09/09/2010
London F-Sharp User Group : Don Syme on F# - 09/09/2010London F-Sharp User Group : Don Syme on F# - 09/09/2010
London F-Sharp User Group : Don Syme on F# - 09/09/2010Skills Matter
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
Ivano Malavolta
 

Similar to Functional programming and Elm (20)

Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
Mechanical Engineering Homework Help
Mechanical Engineering Homework HelpMechanical Engineering Homework Help
Mechanical Engineering Homework Help
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
Functional go
Functional goFunctional go
Functional go
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
 
ScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin Odersky
 
Python For Machine Learning
Python For Machine LearningPython For Machine Learning
Python For Machine Learning
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
elm-d3 @ NYC D3.js Meetup (30 June, 2014)
elm-d3 @ NYC D3.js Meetup (30 June, 2014)elm-d3 @ NYC D3.js Meetup (30 June, 2014)
elm-d3 @ NYC D3.js Meetup (30 June, 2014)
 
Mat lab workshop
Mat lab workshopMat lab workshop
Mat lab workshop
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
 
Matlab-3.pptx
Matlab-3.pptxMatlab-3.pptx
Matlab-3.pptx
 
Clojure intro
Clojure introClojure intro
Clojure intro
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2
 
.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#
 
Enrich enriching mathematics conversi biner 16 pada sisikomputerize indoensia...
Enrich enriching mathematics conversi biner 16 pada sisikomputerize indoensia...Enrich enriching mathematics conversi biner 16 pada sisikomputerize indoensia...
Enrich enriching mathematics conversi biner 16 pada sisikomputerize indoensia...
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programming
 
Go Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional ProgrammingGo Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional Programming
 
London F-Sharp User Group : Don Syme on F# - 09/09/2010
London F-Sharp User Group : Don Syme on F# - 09/09/2010London F-Sharp User Group : Don Syme on F# - 09/09/2010
London F-Sharp User Group : Don Syme on F# - 09/09/2010
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 

More from Fangda Wang

[WWCode] How aware are you of your deciding model?
[WWCode] How aware are you of your deciding model?[WWCode] How aware are you of your deciding model?
[WWCode] How aware are you of your deciding model?
Fangda Wang
 
Under the hood of architecture interviews at indeed
Under the hood of architecture interviews at indeedUnder the hood of architecture interviews at indeed
Under the hood of architecture interviews at indeed
Fangda Wang
 
How Indeed asks coding interview questions
How Indeed asks coding interview questionsHow Indeed asks coding interview questions
How Indeed asks coding interview questions
Fangda Wang
 
Types are eating the world
Types are eating the worldTypes are eating the world
Types are eating the world
Fangda Wang
 
From ic to tech lead
From ic to tech leadFrom ic to tech lead
From ic to tech lead
Fangda Wang
 
Introduction to japanese tokenizer
Introduction to japanese tokenizerIntroduction to japanese tokenizer
Introduction to japanese tokenizer
Fangda Wang
 
Gentle Introduction to Scala
Gentle Introduction to ScalaGentle Introduction to Scala
Gentle Introduction to Scala
Fangda Wang
 
To pair or not to pair
To pair or not to pairTo pair or not to pair
To pair or not to pair
Fangda Wang
 
Balanced Team
Balanced TeamBalanced Team
Balanced Team
Fangda Wang
 
Elm at large (companies)
Elm at large (companies)Elm at large (companies)
Elm at large (companies)
Fangda Wang
 
Data science tools of the trade
Data science tools of the tradeData science tools of the trade
Data science tools of the trade
Fangda Wang
 

More from Fangda Wang (11)

[WWCode] How aware are you of your deciding model?
[WWCode] How aware are you of your deciding model?[WWCode] How aware are you of your deciding model?
[WWCode] How aware are you of your deciding model?
 
Under the hood of architecture interviews at indeed
Under the hood of architecture interviews at indeedUnder the hood of architecture interviews at indeed
Under the hood of architecture interviews at indeed
 
How Indeed asks coding interview questions
How Indeed asks coding interview questionsHow Indeed asks coding interview questions
How Indeed asks coding interview questions
 
Types are eating the world
Types are eating the worldTypes are eating the world
Types are eating the world
 
From ic to tech lead
From ic to tech leadFrom ic to tech lead
From ic to tech lead
 
Introduction to japanese tokenizer
Introduction to japanese tokenizerIntroduction to japanese tokenizer
Introduction to japanese tokenizer
 
Gentle Introduction to Scala
Gentle Introduction to ScalaGentle Introduction to Scala
Gentle Introduction to Scala
 
To pair or not to pair
To pair or not to pairTo pair or not to pair
To pair or not to pair
 
Balanced Team
Balanced TeamBalanced Team
Balanced Team
 
Elm at large (companies)
Elm at large (companies)Elm at large (companies)
Elm at large (companies)
 
Data science tools of the trade
Data science tools of the tradeData science tools of the trade
Data science tools of the trade
 

Recently uploaded

Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABSDESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
itech2017
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
Fundamentals of Induction Motor Drives.pptx
Fundamentals of Induction Motor Drives.pptxFundamentals of Induction Motor Drives.pptx
Fundamentals of Induction Motor Drives.pptx
manasideore6
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
Kerry Sado
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
gestioneergodomus
 
Steel & Timber Design according to British Standard
Steel & Timber Design according to British StandardSteel & Timber Design according to British Standard
Steel & Timber Design according to British Standard
AkolbilaEmmanuel1
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
SyedAbiiAzazi1
 
Basic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparelBasic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparel
top1002
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
The Role of Electrical and Electronics Engineers in IOT Technology.pdf
The Role of Electrical and Electronics Engineers in IOT Technology.pdfThe Role of Electrical and Electronics Engineers in IOT Technology.pdf
The Role of Electrical and Electronics Engineers in IOT Technology.pdf
Nettur Technical Training Foundation
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Water billing management system project report.pdf
Water billing management system project report.pdfWater billing management system project report.pdf
Water billing management system project report.pdf
Kamal Acharya
 

Recently uploaded (20)

Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABSDESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
Fundamentals of Induction Motor Drives.pptx
Fundamentals of Induction Motor Drives.pptxFundamentals of Induction Motor Drives.pptx
Fundamentals of Induction Motor Drives.pptx
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
 
Steel & Timber Design according to British Standard
Steel & Timber Design according to British StandardSteel & Timber Design according to British Standard
Steel & Timber Design according to British Standard
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
 
Basic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparelBasic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparel
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
The Role of Electrical and Electronics Engineers in IOT Technology.pdf
The Role of Electrical and Electronics Engineers in IOT Technology.pdfThe Role of Electrical and Electronics Engineers in IOT Technology.pdf
The Role of Electrical and Electronics Engineers in IOT Technology.pdf
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Water billing management system project report.pdf
Water billing management system project report.pdfWater billing management system project report.pdf
Water billing management system project report.pdf
 

Functional programming and Elm

  • 3. Originated from lambda calculus developed in the 1930s by Alonzo Church What is Functional Programming? Programming with mathematical functions* *It doesn’t mean you need to know math
  • 4. • Do this, then do that • Any effect (Unsafe) • Commands (statements) • Control Flow • Name of a location Imperative • No notion of sequence • Limited effect (Safe) • Expressions • Data Flow • Name of a value vs. Functional
  • 5. f : a à World à (World, b) If there are no side-effects, how can we change the state of the world? f... takes in the state of the world and returns a new world, thus remaining pure No Side-effects update : Msg à Model à ( Model, Cmd Msg ) https://channel9.msdn.com/Shows/Going+Deep/Erik-Meijer-Functional-Programming
  • 6. Functional-flavored • Lisp 1958 (Scheme, Clojure, Racket) • ML ”Lisp with types” => Ocaml (F#, Scala, Reason) • Erlang (Elixir) • Javascript, Java 8, Kotlin, Perl, Python, PHP, etc. Functional-first, Pure • Haskell (Elm)
  • 7. Nirvana “Haskell is useless” Simon Peyton Jones Honesty/Dishonesty Erik Meijer https://www.youtube.com/watch?v=iSmkqocn0oQ&t=22s https://www.youtube.com/watch?v=z0N1aZ6SnBk&t=533 https://www.infoq.com/presentations/Taming-Effect-Simon-Peyton-Jones
  • 9. Web Development Fatigue3 Javascript fatigue + CSS fatigue + Framework/Npm fatigue = Web Development Fatigue
  • 10. What if I told you Front-end can be done without Javascript, HTML, CSS?
  • 11. Elm
  • 12. ● Pure Functional Language ● Compiles to Javascript ● Statically typed + inferred ● Support Immutability and Currying ● Virtual DOM What is Elm?
  • 13. ● Designed by Evan Czaplicki ● April 2012: Version 0.1 ● August 2018: Latest version 0.19 ● Stable (21 months since 0.18) ● Community in elmlang.slack.com History
  • 14. ● No loops (“i = i + 1” doesn’t compile) ● No “null” and no “undefined” ● No “return”, everything is an expression ● “if” always need “else” ● No “this”, no callbacks, no closures, no hoisting ● No automatic type conversion ● JSON decoder/encoder instead of stringify/parse Differences with Javascript
  • 15. Javascript Elm npm / yarn Built in React / Angular / Vue Flux / Redux / MobX Built in Built in Immutable.js Typescript / Flow Built in Built in
  • 16. Without HTML, CSS: elm-ui row [ padding 10, spacing 7 ] [ el [] none , el [] none , el [] none ] spacing : Distance between children padding : Parent Padding
  • 17. [ centerX , centerY ] .parent { position: relative; } .child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } CSS elm-ui No more CSS tricks
  • 19. Nice thing #1 Helpful, friendly errors
  • 20. Nice thing #2 No runtime exceptions
  • 24. Nice thing #6 Type inference
  • 26. Nice thing #8 Demystify FP concepts Functors Monads Category Theory Algebraic Data Type
  • 27. The Elm Architecture is a simple pattern for architecting webapps. It is made of thee parts Nice thing #9 The Elm Architecture (TEA) Model the state of your application View a way to view your state as HTML Update a way to update your state
  • 28. 28 Cartoon cute unicorns vectors design by loutpany from https://freedesignfile.com
  • 29. Safe AreaUnsafe Area Elm Runtime DOM MsgModel Model Model Html Model New! Effects http requests, ports Cmd EventEvent! New! New! Cmd DOM Html EventEvent! update view
  • 31. [1,2] + [3,4] = ? Error [1,2,3,4] [4,6] “1,23,4” A B C D
  • 32. "1,23,4" Javascript Elm -- TYPE MISMATCH --------------------- I cannot do addition with lists: [1,2] + [3,4] ^^^^^ The left side of (+) is a list of type: List number But (+) only works with Int and Float values. Hint: Switch to the (++) operator to append lists! [1,2] + [3,4] = ?
  • 33. What can go wrong with automatic type conversion? https://itnext.io/things-that-can-go-wrong-without-a-strictly-typed-language-d91d418a53a1
  • 34.
  • 35. “If you want user input to be automatically typecast as a number, you can add the number modifier to your v- model managed inputs” <input type="number" v-model="product.quantity"> <input type="number" v-model.number="product.quantity">
  • 36. totalProducts() { return this.products.reduce((sum, product) => { return sum + product.quantity }, 0) } totalProducts() { return this.products.reduce((sum, product) => { if (typeof product.quantity === "number") { return sum + product.quantity; } else { return sum; } }, 0) }
  • 37. <button @click="product.quantity += 1"> <button @click="product.quantity = Number(product.quantity) + 1">
  • 38. Now it works but...
  • 39. type alias Product = { id : Int , quantity : Int , name : String } changeQuantity : Product -> String -> Product changeQuantity product newQuantity = { product | quantity = Maybe.withDefault product.quantity (String.toInt newQuantity) } “If the user typed a valid number, replace the old number with the new one, otherwise keep the old number”
  • 40. Typos <input v-model.number="product.quanity"> t Elm Fail silently Input fields are empty but buttons work. -- TYPE MISMATCH -------------------- The 2nd argument to `map` is not what I expect: 84| products ^^^^^^^^ This `products` value is a: List Product But `map` needs the 2nd argument to be: List { a | id : Int, name : String, quanity : Int, quantity : Int } Hint: Seems like a record field typo. Maybe quanity should be quantity? Vue
  • 41. C de
  • 42. module Main exposing (main) import Html exposing (..) import Html.Attributes exposing (..) main = div [] [ button [id "counter"] [ text "+1" ] , div [] [ text <| String.fromInt 0 ] , button [] [ text ”-1" ] ] <div id="counter"> <button>+1</button> <div>0</div> <button>-1</button> </div>
  • 43. -- MODEL type alias Model = { count : Int } init : Model init = { count = 0 }
  • 44. -- UPDATE type Msg = Increment | Decrement update : Msg -> Model -> Model update msg model = case msg of Increment -> { model | count = model.count + 1 } Decrement -> { model | count = model.count - 1 }
  • 45. -- VIEW view : Model -> Html Msg view model = layout [] <| column [] [ button [] { onPress = Just Increment , label = text "+1" } , el [] <| text (String.fromInt model.count) , button [] { onPress = Just Decrement , label = text "-1" } ]
  • 46. main : Program () Model Msg main = Browser.sandbox { init = init , view = view , update = update }
  • 52. ● The ideas of Functional Programming are becoming mainstream (for a reason) ● Learning Elm will make you a better [Javascript, React, Angular, Vue, etc.] developer ● Writing pure code is an enjoyable experience that make front-end development fun again!