SlideShare a Scribd company logo
1 of 74
Functional Javascript
snowmantw@gmail.com
2012/5/24 JS Group
http://goo.gl/5WCjI
snowmantw
: Vimer
/ Linux User
λ Haskell learner
G self-studier
JS developer
MS student -> Dept. of Computer Science, NCCU
C C++ PHP JS Haskell Java
Functional Javascript
What ?
JavaScript's C-like syntax, including curly braces
and the clunky for statement, makes it appear
to be an ordinary procedural language. This is
misleading because JavaScript has more in
common with functional languages like Lisp or
Scheme than with C or Java. It has arrays
instead of lists and objects instead of property
lists. Functions are first class. It has closures.
You get lambdas without having to balance all
those parens.
“JavaScript: The World's Most Misunderstood Programming Language”
by Douglas Crockford
JavaScript's C-like syntax, including curly braces
and the clunky for statement, makes it appear
to be an ordinary procedural language. This is
misleading because JavaScript has more in
common with functional languages like Lisp or
Scheme than with C or Java. It has arrays
instead of lists and objects instead of property
lists. Functions are first class. It has closures.
You get lambdas without having to balance all
those parens.
“JavaScript: The World's Most Misunderstood Programming Language”
by Douglas Crockford
So, Javascript is a
Functional
Programming
Language
function id( a )
{
return a;
}
function curried( a )
{
return function ( b ) {
return a + b;
}
}
First-Class Function
Curry
function compose( gn )
{
return function ( fn ) {
return function( a ) {
return gn( fn ( a ) ) ;
}
}
} High-Order Function
curried( a )
curried( a ) ( b )
curried( a ) ( c )
curried( b ) ( c )
curried( a ) :: a function
curried( b ) :: another fn
Curry can make a
new function
without definition
curried( a )
curried( a ) ( b )
curried( a ) ( c )
curried( b ) ( c )
curried( a )
curried( a ) ( b )
curried( a ) ( c )
curried( b ) ( c )
new_fn1 = curried( 1 )
new_fn2 = curried( 2 )
new_fn1 ( 1 ) == 1 + 1
new_fn2 ( 1 ) == 2 + 1
We “defined” two functions
without definition !
curried( a )
curried( a ) ( b )
High-Order Function
take one or more fn as an input
OR output a function ( like Curry )
curried( a )
curried( a ) ( b )
compose( curried( a ) )
compose( curried( a ) ) ( curried( b ) )
compose( curried( a ) ) ( curried( b ) ) ( a )
Yet another high-order function
A normal function
A value
curried( a )
curried( a ) ( b )
compose( curried( 3 ) ) ( curried( 4 ) )
compose( curried( 3 ) ) ( curried( 4 ) ) ( 5 )
Generate value when all conditions are satisfied
Now We Have…
First-Class
Function
Now We Have…
That’s all; It’s so sad
Now We Have…
High-Order
Function
- Pure Function
- Immutable Variable
- Encapsulated Impure Features
- ( More ) High Order Function
- Lazy Evaluation
- Functional Data Structure
- Type System
Javascript lacks
Why they
matter ?
Immutable Variable
mut = 1 ;
function victim( ) {
return 10 / mut ;
}
$.get ( ‘/change/mut’ , function(data) {
mut = 0;
});
Immutable Variable
function bad_fn ( arr )
{
var mut = 0;
for( ; mut != arr.length ; mut ++ )
{
arr[ mut ] += mut;
}
return mut;
}
Pure Function
Side-Effect Free
Impure Function
OOPs… It may cause serious problems
gn(3) = 3
gn(3) = 3
gn(3) = 3
gn(3) = 3
gn(3) = 3
gn(3) = 4
Impure Function
i_m_an_innocent_fn
:: ( ) -> Int
function i_m_an_innocent_fn()
{
launch_nuclear_missles();
return 3;
}
Need to be Encapsulated
Pure X Impure
var innocent_var =
3 * 4 + pow ( 2, 4 ) -
i_m_an_innocent_fn() +
floor ( 10 * varA ) …
… It’s just a numerical expression
( I lied )
We ( the laugnage ! )
shouldn’t allow pure
functions to mix with
impure functions.
A Real World Case ( 2 x 4 hr )
render : function(nst) {
var t = this, s = t.settings, id = t.id, sl = tinymce.ScriptLoader;
// Page is not loaded yet, wait for it
// DEBUG : No, we don't need 'tinymce style' check here......
// Because we use bigpipe tech, this condition statement
// will always keep failed.
//
// snowmantw @ 2012-04-25 18:00:41+08:00
//
// if (!Event.domLoaded) {
// Event.add(window, 'ready', function() {
// t.render();
// });
// return;
// }
Encapsulated Impure
Features
Pure Functions need to be ‘wrapped’
Encapsulated Impure
Features
Encapsulated Impure
Features
This is why type system matters
Encapsulated Impure
Features
‘return’ can “lift” one pure fn‘s result
Encapsulated Impure
Features
make pure ‘digitToInt’ impure
Encapsulated Impure
Features
It is the Monad version ‘。’
。
Encapsulated Impure
Features
Encapsulated Impure
Features
(>>=) ‘bind’ can glue another Action
( functions return Monadic value)
No pure function can
get and use values
from Monad,
unless we wrap it and
make it impure, too.
Monad also make “Statements”
in functional way
main =
printStrLn “This is a interactive program !” >>
printStrLn “----” >>
printStrLn “Input Something: ” >>
readline >>= maybe_str -> case maybe_str of
Nothing -> return ()
Just line -> printStrLn “Input from user: ” >>
printStrLn line
Monad also make “Statements”
in functional way
function main( ) {
console.log( “ This is a interactive program ! ” ) ;
console.log( “ ---- “ ) ;
var input = readline( ) ;
if ( “” == input ) { return ; }
console.log( “Input from user: ” ) ;
console.log( input ) ;
}
Why Bother ?
We can assume that
there are no impure
functions leaking to
the pure world
And pure functions
still can be reusable
components
in our program
Just need to be wrapped first
It’s important because…
In most cases we
just need
Modular Programming,
not Object-Oriented
Programming
And the concepts of
pureness and
composition
just fit the need
Welcome to The World of Composition
Function composition ( pure ) ‘。’
: make larger and pure function
Monad bind ( impure ) ‘ >>=’
: make useful and larger COMPUTATION
Arrow compose ( purer than Monad ) ‘>>>’
: make useful and larger COMPUTATION
You can build your whole program with composition
BTW: Composite "Pattern" is Nothing
fa a = b ; fb b = c ; fc = fb . fa
class functorA {
<Tb> public Tb exec( Ta a ) {
return Tb b;
} }
class functorB{
<Tc> public Tc exec( Tb b ) {
return Tc c;
} }
BTW: Composite "Pattern" is Nothing
fa a = b ; fb b = c ; fc = fb . fa
class FunctorCompose
{ public Functor compose( fa, fb )
{
//.......
}
}
// Use in some method
(new FunctorCompose()).compose(fa ,fb)
Sounds good, but…
“It’s not Javascript !”
The Problem:
How can we program
more functionally in the
Javascript world ?
Concepts
id; map; foldl; getChar; putStrLn; (+) ....
map (+1) ; getChar >>= putChar ; f . g
prog = map putStrLn >> getChar >>=
return . digitToInt >>=
x-> return (!!) x str_xs >>=
putStrLn
Libraries
Keep your functions pure ( Dot )
function fn( x ){
return x;
}
$IO.impure = function( x ){
return x + read_from_server ( );
}
All we can use is the '$' and '_'
Impure functions should be restricted in some contexts
Underscore.js ( Line )
_.reduce ( [ 1,2,3 ], function(m,n){ return m+n; },0)
`map` and other high order functions
_.map ( [ 1,2,3 ], function(n){ return n+1; } )
http://underscorejs.org/
Functional Javascript ( Line )
' x -> y -> x+y '.lambda()(2);
More functional features than Underscore.js
' y x -> x+2*y '.lambda()(2, 3);
http://osteele.com/sources/javascript/functional/
jQuery ( Plane )
var pure_val =
$( DOM ) . manipulateDOM ( )
. pureCB ( function ( ) { ... } )
. it_has_unwrapper_fns () ;
"jQuery is Monad“: http://goo.gl/cFErM
http://importantshock.wordpress.com/2009/01/18/jquery-is-a-monad/
http://jquery.com//
It's ( almost ) a " DOM Monad "
Javascript Arrowlet ( Plane )
http://www.cs.umd.edu/projects/PL/arrowlets/api-arrowlets.xhtml
Redefine the "Process"
Javascript Arrowlet ( Plane )
targetA
.next(EventA("click"))
.next(start2)
.next(EventA("click"))
.next(cancel2)
.next(Repeat).repeat().run();
http://www.cs.umd.edu/projects/PL/arrowlets/api-arrowlets.xhtml
Fully event-driven programming
Redefine the "Process"
Flapjax ( Plane )
<p>
The time is {! timerB(100) !}.
</p>
Functional Reactive Programming
Need supported compilers
http://www.flapjax-lang.org/
Languages
CoffeeScript ( Language )
function curried ( a ) {
return function ( b ){
return a + b;
} }
f a b = a + b
f = a->b-> a + b
Why syntax matters
a >>=
b >>=
c >>=
d >>=
e
a >>=
( b >>=
c >>=
d >>=
e )
a >>=
( b >>=
( c >>=
d >>=
e ))
a >>=
( b >>=
( c >>=
( d >>=
e )))
Why syntax matters
a >>=
b >>=
c >>=
d >>=
e ......
a >>=
( b >>=
( c >>=
( d >>=
e ...... ))))))))))))))))))))
Parenthesis Hell
Why syntax matters
First-Class Function + Monad
$( R.id.ButtonToClick ). click ( function(event){
$( R.id.TextViewToShow ).text(
( new SimpleDataFormat( “h:mm:ss a” ) ).format( new Date() ) ;
);
} );
But CoffeeScript is just a little language…
- Pure Function
- Immutable Variable
- Encapsulated Impure Features
- ( More ) High Order Function
- Lazy Evaluation
- Functional Data Structure
- Type System
Personal Project: FunTang language
https://github.com/snowmantw/FunTang
Personal Project: FunTang language
CoffeeScript
Functional Features
+
Personal Project: FunTang language
Will focus on
- Compile into CoffeeScript
- Immutable Variable
- Pure Function
- Integrated Arrow
- Fully Event-Driven Process
In early stage
Thanks for
Your Attention

More Related Content

What's hot

ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016Manoj Kumar
 
Future vs. Monix Task
Future vs. Monix TaskFuture vs. Monix Task
Future vs. Monix TaskHermann Hueck
 
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur..."How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...Fwdays
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScriptGarth Gilmour
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6Solution4Future
 
Functional Programming with JavaScript
Functional Programming with JavaScriptFunctional Programming with JavaScript
Functional Programming with JavaScriptAung Baw
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Datagreenwop
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)James Titcumb
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Arnaud Giuliani
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.boyney123
 
Why Every Tester Should Learn Ruby
Why Every Tester Should Learn RubyWhy Every Tester Should Learn Ruby
Why Every Tester Should Learn RubyRaimonds Simanovskis
 
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 JasmineRaimonds Simanovskis
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsColin DeCarlo
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvmArnaud Giuliani
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 

What's hot (20)

EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
Future vs. Monix Task
Future vs. Monix TaskFuture vs. Monix Task
Future vs. Monix Task
 
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur..."How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
 
Functional Programming with JavaScript
Functional Programming with JavaScriptFunctional Programming with JavaScript
Functional Programming with JavaScript
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017
 
ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Why Every Tester Should Learn Ruby
Why Every Tester Should Learn RubyWhy Every Tester Should Learn Ruby
Why Every Tester Should Learn Ruby
 
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
 
Rails on Oracle 2011
Rails on Oracle 2011Rails on Oracle 2011
Rails on Oracle 2011
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Anonymous functions in JavaScript
Anonymous functions in JavaScriptAnonymous functions in JavaScript
Anonymous functions in JavaScript
 

Similar to Things about Functional JavaScript

JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchainedEduard Tomàs
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015Michiel Borkent
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyDavid Padbury
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойSigma Software
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
 
Big Data Scala by the Bay: Interactive Spark in your Browser
Big Data Scala by the Bay: Interactive Spark in your BrowserBig Data Scala by the Bay: Interactive Spark in your Browser
Big Data Scala by the Bay: Interactive Spark in your Browsergethue
 
Journey of a C# developer into Javascript
Journey of a C# developer into JavascriptJourney of a C# developer into Javascript
Journey of a C# developer into JavascriptMassimo Franciosa
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsBartosz Kosarzycki
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016STX Next
 
Integrating Flex And Rails With Ruby Amf
Integrating Flex And Rails With Ruby AmfIntegrating Flex And Rails With Ruby Amf
Integrating Flex And Rails With Ruby Amfrailsconf
 
PHP 5.3 Part 2 - Lambda Functions & Closures
PHP 5.3 Part 2 - Lambda Functions & ClosuresPHP 5.3 Part 2 - Lambda Functions & Closures
PHP 5.3 Part 2 - Lambda Functions & Closuresmelechi
 
Tasks: you gotta know how to run them
Tasks: you gotta know how to run themTasks: you gotta know how to run them
Tasks: you gotta know how to run themFilipe Ximenes
 

Similar to Things about Functional JavaScript (20)

JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
CppTutorial.ppt
CppTutorial.pptCppTutorial.ppt
CppTutorial.ppt
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
Fabric Python Lib
Fabric Python LibFabric Python Lib
Fabric Python Lib
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
Big Data Scala by the Bay: Interactive Spark in your Browser
Big Data Scala by the Bay: Interactive Spark in your BrowserBig Data Scala by the Bay: Interactive Spark in your Browser
Big Data Scala by the Bay: Interactive Spark in your Browser
 
Journey of a C# developer into Javascript
Journey of a C# developer into JavascriptJourney of a C# developer into Javascript
Journey of a C# developer into Javascript
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 
Integrating Flex And Rails With Ruby Amf
Integrating Flex And Rails With Ruby AmfIntegrating Flex And Rails With Ruby Amf
Integrating Flex And Rails With Ruby Amf
 
Flex With Rubyamf
Flex With RubyamfFlex With Rubyamf
Flex With Rubyamf
 
PHP 5.3 Part 2 - Lambda Functions & Closures
PHP 5.3 Part 2 - Lambda Functions & ClosuresPHP 5.3 Part 2 - Lambda Functions & Closures
PHP 5.3 Part 2 - Lambda Functions & Closures
 
Tasks: you gotta know how to run them
Tasks: you gotta know how to run themTasks: you gotta know how to run them
Tasks: you gotta know how to run them
 

More from ChengHui Weng

Rust + python: lessons learnt from building a toy filesystem
Rust + python: lessons learnt from building a toy filesystemRust + python: lessons learnt from building a toy filesystem
Rust + python: lessons learnt from building a toy filesystemChengHui Weng
 
12 Monkeys Inside JS Engine
12 Monkeys Inside JS Engine12 Monkeys Inside JS Engine
12 Monkeys Inside JS EngineChengHui Weng
 
Gatekeeper: API gateway
Gatekeeper: API gatewayGatekeeper: API gateway
Gatekeeper: API gatewayChengHui Weng
 
Catch a spider monkey
Catch a spider monkeyCatch a spider monkey
Catch a spider monkeyChengHui Weng
 
Even more java script best practices
Even more java script best practicesEven more java script best practices
Even more java script best practicesChengHui Weng
 
JavaScript Best Pratices
JavaScript Best PraticesJavaScript Best Pratices
JavaScript Best PraticesChengHui Weng
 
Yampa AFRP Introduction
Yampa AFRP IntroductionYampa AFRP Introduction
Yampa AFRP IntroductionChengHui Weng
 
Introduction to Basic Haskell Components (In Chinese)
Introduction to Basic Haskell Components (In Chinese)Introduction to Basic Haskell Components (In Chinese)
Introduction to Basic Haskell Components (In Chinese)ChengHui Weng
 
JSDC 2014 - functional java script, why or why not
JSDC 2014 - functional java script, why or why notJSDC 2014 - functional java script, why or why not
JSDC 2014 - functional java script, why or why notChengHui Weng
 

More from ChengHui Weng (9)

Rust + python: lessons learnt from building a toy filesystem
Rust + python: lessons learnt from building a toy filesystemRust + python: lessons learnt from building a toy filesystem
Rust + python: lessons learnt from building a toy filesystem
 
12 Monkeys Inside JS Engine
12 Monkeys Inside JS Engine12 Monkeys Inside JS Engine
12 Monkeys Inside JS Engine
 
Gatekeeper: API gateway
Gatekeeper: API gatewayGatekeeper: API gateway
Gatekeeper: API gateway
 
Catch a spider monkey
Catch a spider monkeyCatch a spider monkey
Catch a spider monkey
 
Even more java script best practices
Even more java script best practicesEven more java script best practices
Even more java script best practices
 
JavaScript Best Pratices
JavaScript Best PraticesJavaScript Best Pratices
JavaScript Best Pratices
 
Yampa AFRP Introduction
Yampa AFRP IntroductionYampa AFRP Introduction
Yampa AFRP Introduction
 
Introduction to Basic Haskell Components (In Chinese)
Introduction to Basic Haskell Components (In Chinese)Introduction to Basic Haskell Components (In Chinese)
Introduction to Basic Haskell Components (In Chinese)
 
JSDC 2014 - functional java script, why or why not
JSDC 2014 - functional java script, why or why notJSDC 2014 - functional java script, why or why not
JSDC 2014 - functional java script, why or why not
 

Recently uploaded

Genshin Impact PPT Template by EaTemp.pptx
Genshin Impact PPT Template by EaTemp.pptxGenshin Impact PPT Template by EaTemp.pptx
Genshin Impact PPT Template by EaTemp.pptxJohnree4
 
Mathan flower ppt.pptx slide orchids ✨🌸
Mathan flower ppt.pptx slide orchids ✨🌸Mathan flower ppt.pptx slide orchids ✨🌸
Mathan flower ppt.pptx slide orchids ✨🌸mathanramanathan2005
 
miladyskindiseases-200705210221 2.!!pptx
miladyskindiseases-200705210221 2.!!pptxmiladyskindiseases-200705210221 2.!!pptx
miladyskindiseases-200705210221 2.!!pptxCarrieButtitta
 
OSCamp Kubernetes 2024 | A Tester's Guide to CI_CD as an Automated Quality Co...
OSCamp Kubernetes 2024 | A Tester's Guide to CI_CD as an Automated Quality Co...OSCamp Kubernetes 2024 | A Tester's Guide to CI_CD as an Automated Quality Co...
OSCamp Kubernetes 2024 | A Tester's Guide to CI_CD as an Automated Quality Co...NETWAYS
 
SBFT Tool Competition 2024 -- Python Test Case Generation Track
SBFT Tool Competition 2024 -- Python Test Case Generation TrackSBFT Tool Competition 2024 -- Python Test Case Generation Track
SBFT Tool Competition 2024 -- Python Test Case Generation TrackSebastiano Panichella
 
Open Source Camp Kubernetes 2024 | Monitoring Kubernetes With Icinga by Eric ...
Open Source Camp Kubernetes 2024 | Monitoring Kubernetes With Icinga by Eric ...Open Source Camp Kubernetes 2024 | Monitoring Kubernetes With Icinga by Eric ...
Open Source Camp Kubernetes 2024 | Monitoring Kubernetes With Icinga by Eric ...NETWAYS
 
PHYSICS PROJECT BY MSC - NANOTECHNOLOGY
PHYSICS PROJECT BY MSC  - NANOTECHNOLOGYPHYSICS PROJECT BY MSC  - NANOTECHNOLOGY
PHYSICS PROJECT BY MSC - NANOTECHNOLOGYpruthirajnayak525
 
Work Remotely with Confluence ACE 2.pptx
Work Remotely with Confluence ACE 2.pptxWork Remotely with Confluence ACE 2.pptx
Work Remotely with Confluence ACE 2.pptxmavinoikein
 
Simulation-based Testing of Unmanned Aerial Vehicles with Aerialist
Simulation-based Testing of Unmanned Aerial Vehicles with AerialistSimulation-based Testing of Unmanned Aerial Vehicles with Aerialist
Simulation-based Testing of Unmanned Aerial Vehicles with AerialistSebastiano Panichella
 
Open Source Strategy in Logistics 2015_Henrik Hankedvz-d-nl-log-conference.pdf
Open Source Strategy in Logistics 2015_Henrik Hankedvz-d-nl-log-conference.pdfOpen Source Strategy in Logistics 2015_Henrik Hankedvz-d-nl-log-conference.pdf
Open Source Strategy in Logistics 2015_Henrik Hankedvz-d-nl-log-conference.pdfhenrik385807
 
OSCamp Kubernetes 2024 | SRE Challenges in Monolith to Microservices Shift at...
OSCamp Kubernetes 2024 | SRE Challenges in Monolith to Microservices Shift at...OSCamp Kubernetes 2024 | SRE Challenges in Monolith to Microservices Shift at...
OSCamp Kubernetes 2024 | SRE Challenges in Monolith to Microservices Shift at...NETWAYS
 
Call Girls In Aerocity 🤳 Call Us +919599264170
Call Girls In Aerocity 🤳 Call Us +919599264170Call Girls In Aerocity 🤳 Call Us +919599264170
Call Girls In Aerocity 🤳 Call Us +919599264170Escort Service
 
James Joyce, Dubliners and Ulysses.ppt !
James Joyce, Dubliners and Ulysses.ppt !James Joyce, Dubliners and Ulysses.ppt !
James Joyce, Dubliners and Ulysses.ppt !risocarla2016
 
Call Girls in Rohini Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Rohini Delhi 💯Call Us 🔝8264348440🔝Call Girls in Rohini Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Rohini Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Event 4 Introduction to Open Source.pptx
Event 4 Introduction to Open Source.pptxEvent 4 Introduction to Open Source.pptx
Event 4 Introduction to Open Source.pptxaryanv1753
 
Anne Frank A Beacon of Hope amidst darkness ppt.pptx
Anne Frank A Beacon of Hope amidst darkness ppt.pptxAnne Frank A Beacon of Hope amidst darkness ppt.pptx
Anne Frank A Beacon of Hope amidst darkness ppt.pptxnoorehahmad
 
OSCamp Kubernetes 2024 | Zero-Touch OS-Infrastruktur für Container und Kubern...
OSCamp Kubernetes 2024 | Zero-Touch OS-Infrastruktur für Container und Kubern...OSCamp Kubernetes 2024 | Zero-Touch OS-Infrastruktur für Container und Kubern...
OSCamp Kubernetes 2024 | Zero-Touch OS-Infrastruktur für Container und Kubern...NETWAYS
 
Gaps, Issues and Challenges in the Implementation of Mother Tongue Based-Mult...
Gaps, Issues and Challenges in the Implementation of Mother Tongue Based-Mult...Gaps, Issues and Challenges in the Implementation of Mother Tongue Based-Mult...
Gaps, Issues and Challenges in the Implementation of Mother Tongue Based-Mult...marjmae69
 
The Ten Facts About People With Autism Presentation
The Ten Facts About People With Autism PresentationThe Ten Facts About People With Autism Presentation
The Ten Facts About People With Autism PresentationNathan Young
 
Open Source Camp Kubernetes 2024 | Running WebAssembly on Kubernetes by Alex ...
Open Source Camp Kubernetes 2024 | Running WebAssembly on Kubernetes by Alex ...Open Source Camp Kubernetes 2024 | Running WebAssembly on Kubernetes by Alex ...
Open Source Camp Kubernetes 2024 | Running WebAssembly on Kubernetes by Alex ...NETWAYS
 

Recently uploaded (20)

Genshin Impact PPT Template by EaTemp.pptx
Genshin Impact PPT Template by EaTemp.pptxGenshin Impact PPT Template by EaTemp.pptx
Genshin Impact PPT Template by EaTemp.pptx
 
Mathan flower ppt.pptx slide orchids ✨🌸
Mathan flower ppt.pptx slide orchids ✨🌸Mathan flower ppt.pptx slide orchids ✨🌸
Mathan flower ppt.pptx slide orchids ✨🌸
 
miladyskindiseases-200705210221 2.!!pptx
miladyskindiseases-200705210221 2.!!pptxmiladyskindiseases-200705210221 2.!!pptx
miladyskindiseases-200705210221 2.!!pptx
 
OSCamp Kubernetes 2024 | A Tester's Guide to CI_CD as an Automated Quality Co...
OSCamp Kubernetes 2024 | A Tester's Guide to CI_CD as an Automated Quality Co...OSCamp Kubernetes 2024 | A Tester's Guide to CI_CD as an Automated Quality Co...
OSCamp Kubernetes 2024 | A Tester's Guide to CI_CD as an Automated Quality Co...
 
SBFT Tool Competition 2024 -- Python Test Case Generation Track
SBFT Tool Competition 2024 -- Python Test Case Generation TrackSBFT Tool Competition 2024 -- Python Test Case Generation Track
SBFT Tool Competition 2024 -- Python Test Case Generation Track
 
Open Source Camp Kubernetes 2024 | Monitoring Kubernetes With Icinga by Eric ...
Open Source Camp Kubernetes 2024 | Monitoring Kubernetes With Icinga by Eric ...Open Source Camp Kubernetes 2024 | Monitoring Kubernetes With Icinga by Eric ...
Open Source Camp Kubernetes 2024 | Monitoring Kubernetes With Icinga by Eric ...
 
PHYSICS PROJECT BY MSC - NANOTECHNOLOGY
PHYSICS PROJECT BY MSC  - NANOTECHNOLOGYPHYSICS PROJECT BY MSC  - NANOTECHNOLOGY
PHYSICS PROJECT BY MSC - NANOTECHNOLOGY
 
Work Remotely with Confluence ACE 2.pptx
Work Remotely with Confluence ACE 2.pptxWork Remotely with Confluence ACE 2.pptx
Work Remotely with Confluence ACE 2.pptx
 
Simulation-based Testing of Unmanned Aerial Vehicles with Aerialist
Simulation-based Testing of Unmanned Aerial Vehicles with AerialistSimulation-based Testing of Unmanned Aerial Vehicles with Aerialist
Simulation-based Testing of Unmanned Aerial Vehicles with Aerialist
 
Open Source Strategy in Logistics 2015_Henrik Hankedvz-d-nl-log-conference.pdf
Open Source Strategy in Logistics 2015_Henrik Hankedvz-d-nl-log-conference.pdfOpen Source Strategy in Logistics 2015_Henrik Hankedvz-d-nl-log-conference.pdf
Open Source Strategy in Logistics 2015_Henrik Hankedvz-d-nl-log-conference.pdf
 
OSCamp Kubernetes 2024 | SRE Challenges in Monolith to Microservices Shift at...
OSCamp Kubernetes 2024 | SRE Challenges in Monolith to Microservices Shift at...OSCamp Kubernetes 2024 | SRE Challenges in Monolith to Microservices Shift at...
OSCamp Kubernetes 2024 | SRE Challenges in Monolith to Microservices Shift at...
 
Call Girls In Aerocity 🤳 Call Us +919599264170
Call Girls In Aerocity 🤳 Call Us +919599264170Call Girls In Aerocity 🤳 Call Us +919599264170
Call Girls In Aerocity 🤳 Call Us +919599264170
 
James Joyce, Dubliners and Ulysses.ppt !
James Joyce, Dubliners and Ulysses.ppt !James Joyce, Dubliners and Ulysses.ppt !
James Joyce, Dubliners and Ulysses.ppt !
 
Call Girls in Rohini Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Rohini Delhi 💯Call Us 🔝8264348440🔝Call Girls in Rohini Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Rohini Delhi 💯Call Us 🔝8264348440🔝
 
Event 4 Introduction to Open Source.pptx
Event 4 Introduction to Open Source.pptxEvent 4 Introduction to Open Source.pptx
Event 4 Introduction to Open Source.pptx
 
Anne Frank A Beacon of Hope amidst darkness ppt.pptx
Anne Frank A Beacon of Hope amidst darkness ppt.pptxAnne Frank A Beacon of Hope amidst darkness ppt.pptx
Anne Frank A Beacon of Hope amidst darkness ppt.pptx
 
OSCamp Kubernetes 2024 | Zero-Touch OS-Infrastruktur für Container und Kubern...
OSCamp Kubernetes 2024 | Zero-Touch OS-Infrastruktur für Container und Kubern...OSCamp Kubernetes 2024 | Zero-Touch OS-Infrastruktur für Container und Kubern...
OSCamp Kubernetes 2024 | Zero-Touch OS-Infrastruktur für Container und Kubern...
 
Gaps, Issues and Challenges in the Implementation of Mother Tongue Based-Mult...
Gaps, Issues and Challenges in the Implementation of Mother Tongue Based-Mult...Gaps, Issues and Challenges in the Implementation of Mother Tongue Based-Mult...
Gaps, Issues and Challenges in the Implementation of Mother Tongue Based-Mult...
 
The Ten Facts About People With Autism Presentation
The Ten Facts About People With Autism PresentationThe Ten Facts About People With Autism Presentation
The Ten Facts About People With Autism Presentation
 
Open Source Camp Kubernetes 2024 | Running WebAssembly on Kubernetes by Alex ...
Open Source Camp Kubernetes 2024 | Running WebAssembly on Kubernetes by Alex ...Open Source Camp Kubernetes 2024 | Running WebAssembly on Kubernetes by Alex ...
Open Source Camp Kubernetes 2024 | Running WebAssembly on Kubernetes by Alex ...
 

Things about Functional JavaScript

  • 3. snowmantw : Vimer / Linux User λ Haskell learner G self-studier JS developer MS student -> Dept. of Computer Science, NCCU C C++ PHP JS Haskell Java
  • 6. JavaScript's C-like syntax, including curly braces and the clunky for statement, makes it appear to be an ordinary procedural language. This is misleading because JavaScript has more in common with functional languages like Lisp or Scheme than with C or Java. It has arrays instead of lists and objects instead of property lists. Functions are first class. It has closures. You get lambdas without having to balance all those parens. “JavaScript: The World's Most Misunderstood Programming Language” by Douglas Crockford
  • 7. JavaScript's C-like syntax, including curly braces and the clunky for statement, makes it appear to be an ordinary procedural language. This is misleading because JavaScript has more in common with functional languages like Lisp or Scheme than with C or Java. It has arrays instead of lists and objects instead of property lists. Functions are first class. It has closures. You get lambdas without having to balance all those parens. “JavaScript: The World's Most Misunderstood Programming Language” by Douglas Crockford
  • 8. So, Javascript is a Functional Programming Language
  • 9.
  • 10. function id( a ) { return a; } function curried( a ) { return function ( b ) { return a + b; } } First-Class Function Curry
  • 11. function compose( gn ) { return function ( fn ) { return function( a ) { return gn( fn ( a ) ) ; } } } High-Order Function
  • 12. curried( a ) curried( a ) ( b ) curried( a ) ( c ) curried( b ) ( c ) curried( a ) :: a function curried( b ) :: another fn
  • 13. Curry can make a new function without definition curried( a ) curried( a ) ( b ) curried( a ) ( c ) curried( b ) ( c )
  • 14. curried( a ) curried( a ) ( b ) curried( a ) ( c ) curried( b ) ( c ) new_fn1 = curried( 1 ) new_fn2 = curried( 2 ) new_fn1 ( 1 ) == 1 + 1 new_fn2 ( 1 ) == 2 + 1 We “defined” two functions without definition !
  • 15. curried( a ) curried( a ) ( b ) High-Order Function take one or more fn as an input OR output a function ( like Curry )
  • 16. curried( a ) curried( a ) ( b ) compose( curried( a ) ) compose( curried( a ) ) ( curried( b ) ) compose( curried( a ) ) ( curried( b ) ) ( a ) Yet another high-order function A normal function A value
  • 17. curried( a ) curried( a ) ( b ) compose( curried( 3 ) ) ( curried( 4 ) ) compose( curried( 3 ) ) ( curried( 4 ) ) ( 5 ) Generate value when all conditions are satisfied
  • 20. That’s all; It’s so sad Now We Have… High-Order Function
  • 21. - Pure Function - Immutable Variable - Encapsulated Impure Features - ( More ) High Order Function - Lazy Evaluation - Functional Data Structure - Type System Javascript lacks
  • 23. Immutable Variable mut = 1 ; function victim( ) { return 10 / mut ; } $.get ( ‘/change/mut’ , function(data) { mut = 0; });
  • 24. Immutable Variable function bad_fn ( arr ) { var mut = 0; for( ; mut != arr.length ; mut ++ ) { arr[ mut ] += mut; } return mut; }
  • 26. Impure Function OOPs… It may cause serious problems gn(3) = 3 gn(3) = 3 gn(3) = 3 gn(3) = 3 gn(3) = 3 gn(3) = 4
  • 27. Impure Function i_m_an_innocent_fn :: ( ) -> Int function i_m_an_innocent_fn() { launch_nuclear_missles(); return 3; } Need to be Encapsulated
  • 28. Pure X Impure var innocent_var = 3 * 4 + pow ( 2, 4 ) - i_m_an_innocent_fn() + floor ( 10 * varA ) … … It’s just a numerical expression
  • 29. ( I lied )
  • 30.
  • 31. We ( the laugnage ! ) shouldn’t allow pure functions to mix with impure functions.
  • 32. A Real World Case ( 2 x 4 hr ) render : function(nst) { var t = this, s = t.settings, id = t.id, sl = tinymce.ScriptLoader; // Page is not loaded yet, wait for it // DEBUG : No, we don't need 'tinymce style' check here...... // Because we use bigpipe tech, this condition statement // will always keep failed. // // snowmantw @ 2012-04-25 18:00:41+08:00 // // if (!Event.domLoaded) { // Event.add(window, 'ready', function() { // t.render(); // }); // return; // }
  • 35. Encapsulated Impure Features This is why type system matters
  • 36. Encapsulated Impure Features ‘return’ can “lift” one pure fn‘s result
  • 37. Encapsulated Impure Features make pure ‘digitToInt’ impure
  • 38. Encapsulated Impure Features It is the Monad version ‘。’ 。
  • 40. Encapsulated Impure Features (>>=) ‘bind’ can glue another Action ( functions return Monadic value)
  • 41. No pure function can get and use values from Monad, unless we wrap it and make it impure, too.
  • 42. Monad also make “Statements” in functional way main = printStrLn “This is a interactive program !” >> printStrLn “----” >> printStrLn “Input Something: ” >> readline >>= maybe_str -> case maybe_str of Nothing -> return () Just line -> printStrLn “Input from user: ” >> printStrLn line
  • 43. Monad also make “Statements” in functional way function main( ) { console.log( “ This is a interactive program ! ” ) ; console.log( “ ---- “ ) ; var input = readline( ) ; if ( “” == input ) { return ; } console.log( “Input from user: ” ) ; console.log( input ) ; }
  • 45. We can assume that there are no impure functions leaking to the pure world
  • 46. And pure functions still can be reusable components in our program Just need to be wrapped first
  • 47. It’s important because… In most cases we just need Modular Programming, not Object-Oriented Programming
  • 48. And the concepts of pureness and composition just fit the need
  • 49. Welcome to The World of Composition Function composition ( pure ) ‘。’ : make larger and pure function Monad bind ( impure ) ‘ >>=’ : make useful and larger COMPUTATION Arrow compose ( purer than Monad ) ‘>>>’ : make useful and larger COMPUTATION You can build your whole program with composition
  • 50. BTW: Composite "Pattern" is Nothing fa a = b ; fb b = c ; fc = fb . fa class functorA { <Tb> public Tb exec( Ta a ) { return Tb b; } } class functorB{ <Tc> public Tc exec( Tb b ) { return Tc c; } }
  • 51. BTW: Composite "Pattern" is Nothing fa a = b ; fb b = c ; fc = fb . fa class FunctorCompose { public Functor compose( fa, fb ) { //....... } } // Use in some method (new FunctorCompose()).compose(fa ,fb)
  • 52. Sounds good, but… “It’s not Javascript !”
  • 53. The Problem: How can we program more functionally in the Javascript world ?
  • 55. id; map; foldl; getChar; putStrLn; (+) .... map (+1) ; getChar >>= putChar ; f . g
  • 56. prog = map putStrLn >> getChar >>= return . digitToInt >>= x-> return (!!) x str_xs >>= putStrLn
  • 58. Keep your functions pure ( Dot ) function fn( x ){ return x; } $IO.impure = function( x ){ return x + read_from_server ( ); } All we can use is the '$' and '_' Impure functions should be restricted in some contexts
  • 59. Underscore.js ( Line ) _.reduce ( [ 1,2,3 ], function(m,n){ return m+n; },0) `map` and other high order functions _.map ( [ 1,2,3 ], function(n){ return n+1; } ) http://underscorejs.org/
  • 60. Functional Javascript ( Line ) ' x -> y -> x+y '.lambda()(2); More functional features than Underscore.js ' y x -> x+2*y '.lambda()(2, 3); http://osteele.com/sources/javascript/functional/
  • 61. jQuery ( Plane ) var pure_val = $( DOM ) . manipulateDOM ( ) . pureCB ( function ( ) { ... } ) . it_has_unwrapper_fns () ; "jQuery is Monad“: http://goo.gl/cFErM http://importantshock.wordpress.com/2009/01/18/jquery-is-a-monad/ http://jquery.com// It's ( almost ) a " DOM Monad "
  • 62. Javascript Arrowlet ( Plane ) http://www.cs.umd.edu/projects/PL/arrowlets/api-arrowlets.xhtml Redefine the "Process"
  • 63. Javascript Arrowlet ( Plane ) targetA .next(EventA("click")) .next(start2) .next(EventA("click")) .next(cancel2) .next(Repeat).repeat().run(); http://www.cs.umd.edu/projects/PL/arrowlets/api-arrowlets.xhtml Fully event-driven programming Redefine the "Process"
  • 64. Flapjax ( Plane ) <p> The time is {! timerB(100) !}. </p> Functional Reactive Programming Need supported compilers http://www.flapjax-lang.org/
  • 66. CoffeeScript ( Language ) function curried ( a ) { return function ( b ){ return a + b; } } f a b = a + b f = a->b-> a + b
  • 67. Why syntax matters a >>= b >>= c >>= d >>= e a >>= ( b >>= c >>= d >>= e ) a >>= ( b >>= ( c >>= d >>= e )) a >>= ( b >>= ( c >>= ( d >>= e )))
  • 68. Why syntax matters a >>= b >>= c >>= d >>= e ...... a >>= ( b >>= ( c >>= ( d >>= e ...... )))))))))))))))))))) Parenthesis Hell
  • 69. Why syntax matters First-Class Function + Monad $( R.id.ButtonToClick ). click ( function(event){ $( R.id.TextViewToShow ).text( ( new SimpleDataFormat( “h:mm:ss a” ) ).format( new Date() ) ; ); } );
  • 70. But CoffeeScript is just a little language… - Pure Function - Immutable Variable - Encapsulated Impure Features - ( More ) High Order Function - Lazy Evaluation - Functional Data Structure - Type System
  • 71. Personal Project: FunTang language https://github.com/snowmantw/FunTang
  • 72. Personal Project: FunTang language CoffeeScript Functional Features +
  • 73. Personal Project: FunTang language Will focus on - Compile into CoffeeScript - Immutable Variable - Pure Function - Integrated Arrow - Fully Event-Driven Process In early stage

Editor's Notes

  1. 「不是標準 Haskell 語法!」
  2. 某語言…
  3. 某語言…
  4. 因為太可怕所以被迫用 pattern ?