SlideShare uma empresa Scribd logo
1 de 23
Maybe Functor
in Javascript
Another approach to
null handling
1
2
Origin of Null Pointer Exception
● Sir Tony Hoare was designing type systems for the
language ALGOL W and he put “Null Pointer Exception” as
part of the language, because “because it was so easy to
implement”
● In 2009, he called it “The Billion Dollar Mistake”
3
What we want:
getCountry('vn').getCity('HCMC').population;
What we have to do
var country = getCountry('vn');
if (country !== null) {
var city = country.getCity('HCMC');
if (city !== null) {
var population = city.population;
}
}
How do we fight NULL?
4
Drawbacks:
● Looks complicated
● Error-prone, especially
when there are many
nesting ifs
● Tedious to write
● Declares a lot of useless
variables
● A Functor is a container of a value
Introduction to Functor
5
A value A container of value
● A simple Functor can be implemented through an ES6 class
class Functor {
constructor(value) {
this.value = value;
}
}
One important thing about Functor
6
By definition, a functor needs to implement a
map function
Remember Array Map?
7
Let’s look at Array’s map function.
var addOne = (x) => x + 1;
var square = (x) => x * x;
var result = [1, 2, 3]
.map(addOne) // [2, 3, 4]
.map(square); // [4, 9, 16]
Implement map for Functor
8
class Functor {
constructor(value) {
this.value = value;
}
map(fn) {
var newValue = fn(this.value);
return new Functor(newValue);
}
}
Let’s see it in action (1)
9
var addOne = (x) => x + 1;
var functorOf6 = new Functor(5).map(addOne); // Functor(6)
It can also work with any value, for example, an object:
var toUpperCase = (str) => str.toUpperCase();
var exciting = (someName) => someName + ’!!!!!!!’;
var value = { name: 'grokking' };
var containerOfValue = new Functor(value)
.map(thing => thing.name) // Functor(‘grokking’)
.map(toUpperCase) // Functor(‘GROKKING’)
.map(exciting); // Functor(‘GROKKING!!!!!!!’)
Let’s see it in action (2)
10
Notice that our actual value is still inside the Functor.
var functorOf36 = new Functor(5)
.map(addOne) // Functor(6)
.map(square); // Functor(36)
var result = functorOf36 + 100; // Functor(36) + 100 ???????
How to get the value inside Functor
11
Let’s add another method to Functor to extract the value.
class Functor {
get() { return this.value; }
}
var valueInside = new Functor(5)
.map(addOne) // Functor(6)
.map(square); // Functor(36)
.get(); // 36
var toUpperCase = (str) => str.toUpperCase();
var exciting = (someName) => someName + '!!!!!!';
var valueInside = new Functor({ name: 'grokking' })
.map(people => people.name) // Functor(‘grokking’)
.map(toUpperCase) // Functor(‘GROKKING’)
.map(exciting); // Functor(‘GROKKING!!!!!!!’)
.get(); // 'GROKKING!!!!!!!'
Now we can get the value inside Functor
12
class Functor {
constructor(value) {
this.value = value;
}
map(fn) {
var newValue = fn(this.value);
return new Maybe(newValue);
}
get() {
return this.value;
}
}
Full implementation of Functor
13
var addOne = (x) => null; // we return Null
var square = (x) => x * x;
var valueInside = new Functor(1)
.map(addOne) // Functor(null)
.map(square); // Functor(null * null) ????
.get(); // ????
But we are still affected by NULL
14
The solution is to turn our functor into a Maybe
● Maybe is a kind of Functor that is Null-
friendly. Real magic happens in the map
function
● Maybe that contains a real value (not null)
is usually called a Just / Some
● Maybe that contains null value is usually
called a Nothing / None
Introduction to Maybe
15
Maybe(value) = Just(value)
Maybe(null) = Nothing
class Maybe {
constructor(value) { this.value = value; }
map(fn) {
if (this.value !== null) { // Magic happens here
var newValue = fn(this.value);
return new Maybe(newValue);
}
return new Maybe(null);
}
getOrElse(fallBackValue) {
return (this.value === null) ? this.value : fallBackValue;
}
}
Let’s implement Maybe
16
It’s pretty much the same as Functor’s example. The only difference is that we use
getOrElse instead of get
var addOne = (x) => x + 1;
var square = (x) => x * x;
var result = new Maybe(3)
.map(addOne) // Maybe(4)
.map(square) // Maybe(16)
.getOrElse(0); // 16
Maybe in action
17
When Maybe contains NULL, it will not map anymore
var result = new Maybe(3)
.map(x => null) // Maybe(null)
.map(x => x * x) // Maybe(null)
.getOrElse(0); // 0
var result = new Maybe(3)
.map(x => x + 1) // Maybe(4)
.map(x => null) // Maybe(null)
.getOrElse(0); // 0
When Null happens
18
Some real world examples
var family = {
grandma: {
mother: {
you: 'YOUR NAME HERE'
}
}
};
var you = new Maybe(family.grandma)
.map(grandma => grandma.mother)
.map(mother => mother.you)
.getOrElse('DEFAULT NAME');
// returns “YOUR NAME HERE”
var family = {
grandma: null
};
var you = new Maybe(family.grandma)
.map(grandma => grandma.mother)
.map(mother => mother.you)
.getOrElse('DEFAULT NAME');
// returns “DEFAULT NAME”
19
We can use it to safely access nested objects
Compare with what we used to do
20
var you = family.grandma.mother.you || 'DEFAULT NAME';
var you = 'DEFAULT NAME';
if (family.grandma &&
family.grandma.mother &&
family.grandma.mother.you)
{
you = family.grandma.mother.you;
}
var you = new Maybe(family.grandma)
.map(grandma => grandma.mother)
.map(mother => mother.you)
.getOrElse('DEFAULT NAME');
Short, but unsafe
Safe, but long and
nested
Safe and flattened
var population = new Maybe(getCountry('vn'))
.map(country => country.getCity('HCMC'))
.map(city => city.population)
.getOrElse(0);
Some real world examples
var country = getCountry('vn');
if (country !== null) {
var city = country.getCity('HCMC');
if (city !== null) {
var population = city.population;
}
}
21
We can rewrite our example earlier
Into shorter and flattened code
● Is just a container of value
● Is a fundamental concept in
Functional Programming. From
there you can explore Applicative
and Monad
● Is a kind of functor that checks null on each map
● Helps flatten your code
● Is used widely in many other languages:
- Haskell, Elm: Maybe
Recap
22
Maybe
Functor
References
● https://github.com/fantasyland/fantasy-land Fantasy Land Specification
● https://cwmyers.github.io/monet.js/ Powerful abstractions for Javascript
● http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html
Functor, Applicatives, Monads in pictures
● https://en.wikipedia.org/wiki/Functor (looks scary with all the math)
● http://www.mokacoding.com/blog/functor-applicative-monads-in-pictures/ (Maybe in
Swift)
● http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html Java 8
Optional
23

Mais conteúdo relacionado

Mais procurados

6 new ES6 features
6 new ES6 features6 new ES6 features
6 new ES6 features
Kyle Dorman
 

Mais procurados (15)

DS- Stack ADT
DS- Stack ADTDS- Stack ADT
DS- Stack ADT
 
The Ring programming language version 1.6 book - Part 84 of 189
The Ring programming language version 1.6 book - Part 84 of 189The Ring programming language version 1.6 book - Part 84 of 189
The Ring programming language version 1.6 book - Part 84 of 189
 
week-15x
week-15xweek-15x
week-15x
 
Git avançado
Git avançadoGit avançado
Git avançado
 
Functional php
Functional phpFunctional php
Functional php
 
Golang勉強会
Golang勉強会Golang勉強会
Golang勉強会
 
6 new ES6 features
6 new ES6 features6 new ES6 features
6 new ES6 features
 
Functional Programming: An Introduction
Functional Programming: An IntroductionFunctional Programming: An Introduction
Functional Programming: An Introduction
 
Recognize Godzilla
Recognize GodzillaRecognize Godzilla
Recognize Godzilla
 
C++ programs
C++ programsC++ programs
C++ programs
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 
Circular linked list
Circular linked listCircular linked list
Circular linked list
 
Single linked list
Single linked listSingle linked list
Single linked list
 
Stack using Array
Stack using ArrayStack using Array
Stack using Array
 
Debug like a doctor
Debug like a doctorDebug like a doctor
Debug like a doctor
 

Destaque

Destaque (20)

Grokking TechTalk #16: F**k bad CSS
Grokking TechTalk #16: F**k bad CSSGrokking TechTalk #16: F**k bad CSS
Grokking TechTalk #16: F**k bad CSS
 
Grokking TechTalk #16: React stack at lozi
Grokking TechTalk #16: React stack at loziGrokking TechTalk #16: React stack at lozi
Grokking TechTalk #16: React stack at lozi
 
Grokking TechTalk #16: Html js and three way binding
Grokking TechTalk #16: Html js and three way bindingGrokking TechTalk #16: Html js and three way binding
Grokking TechTalk #16: Html js and three way binding
 
Expressing your UI in JSON – plain, data binding, advanced data binding
Expressing your UI in JSON – plain, data binding, advanced data bindingExpressing your UI in JSON – plain, data binding, advanced data binding
Expressing your UI in JSON – plain, data binding, advanced data binding
 
Grokking: Data Engineering Course
Grokking: Data Engineering CourseGrokking: Data Engineering Course
Grokking: Data Engineering Course
 
TechTalk #15 Grokking: The data processing journey at AhaMove
TechTalk #15 Grokking:  The data processing journey at AhaMoveTechTalk #15 Grokking:  The data processing journey at AhaMove
TechTalk #15 Grokking: The data processing journey at AhaMove
 
Fashion blog
Fashion blogFashion blog
Fashion blog
 
Askourt - using the power of social networks to increase sales in eCommerce s...
Askourt - using the power of social networks to increase sales in eCommerce s...Askourt - using the power of social networks to increase sales in eCommerce s...
Askourt - using the power of social networks to increase sales in eCommerce s...
 
TDC São Paulo - React presentation
TDC São Paulo - React presentationTDC São Paulo - React presentation
TDC São Paulo - React presentation
 
Breaking the Server-Client Divide with Node.js and React
Breaking the Server-Client Divide with Node.js and ReactBreaking the Server-Client Divide with Node.js and React
Breaking the Server-Client Divide with Node.js and React
 
Creating Omnichannel Experiences with Loblaw Digital - eCommerce Toronto Meetup
Creating Omnichannel Experiences with Loblaw Digital - eCommerce Toronto MeetupCreating Omnichannel Experiences with Loblaw Digital - eCommerce Toronto Meetup
Creating Omnichannel Experiences with Loblaw Digital - eCommerce Toronto Meetup
 
Introduction to React Native & Redux
Introduction to React Native & ReduxIntroduction to React Native & Redux
Introduction to React Native & Redux
 
Get MEAN! Node.js and the MEAN stack
Get MEAN!  Node.js and the MEAN stackGet MEAN!  Node.js and the MEAN stack
Get MEAN! Node.js and the MEAN stack
 
TDC2016SP - Trilha Frameworks JavaScript
TDC2016SP - Trilha Frameworks JavaScriptTDC2016SP - Trilha Frameworks JavaScript
TDC2016SP - Trilha Frameworks JavaScript
 
Using ReactJS in AngularJS
Using ReactJS in AngularJSUsing ReactJS in AngularJS
Using ReactJS in AngularJS
 
Digital Marketing for a Modest Islamic Clothing store
Digital Marketing for a Modest Islamic Clothing storeDigital Marketing for a Modest Islamic Clothing store
Digital Marketing for a Modest Islamic Clothing store
 
How to increase engagement in fashion eCommerce stores
How to increase engagement in fashion eCommerce storesHow to increase engagement in fashion eCommerce stores
How to increase engagement in fashion eCommerce stores
 
Backbone.js with React Views - Server Rendering, Virtual DOM, and More!
Backbone.js with React Views - Server Rendering, Virtual DOM, and More!Backbone.js with React Views - Server Rendering, Virtual DOM, and More!
Backbone.js with React Views - Server Rendering, Virtual DOM, and More!
 
The MEAN Stack: MongoDB, ExpressJS, AngularJS and Node.js
The MEAN Stack: MongoDB, ExpressJS, AngularJS and Node.jsThe MEAN Stack: MongoDB, ExpressJS, AngularJS and Node.js
The MEAN Stack: MongoDB, ExpressJS, AngularJS and Node.js
 
The Evolution of Airbnb's Frontend
The Evolution of Airbnb's FrontendThe Evolution of Airbnb's Frontend
The Evolution of Airbnb's Frontend
 

Semelhante a Grokking TechTalk #16: Maybe functor in javascript

TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
Eelco Visser
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 

Semelhante a Grokking TechTalk #16: Maybe functor in javascript (20)

EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
Javascript development done right
Javascript development done rightJavascript development done right
Javascript development done right
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of Go
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Monads in javascript
Monads in javascriptMonads in javascript
Monads in javascript
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oop
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
Java Question help needed In the program Fill the Add statements.pdf
Java Question  help needed In the program Fill the Add statements.pdfJava Question  help needed In the program Fill the Add statements.pdf
Java Question help needed In the program Fill the Add statements.pdf
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)
 
Kotlin
KotlinKotlin
Kotlin
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
 
Functional programming
Functional programming Functional programming
Functional programming
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursion
 
Internal workshop es6_2015
Internal workshop es6_2015Internal workshop es6_2015
Internal workshop es6_2015
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 

Mais de Grokking VN

Grokking Techtalk #46: Lessons from years hacking and defending Vietnamese banks
Grokking Techtalk #46: Lessons from years hacking and defending Vietnamese banksGrokking Techtalk #46: Lessons from years hacking and defending Vietnamese banks
Grokking Techtalk #46: Lessons from years hacking and defending Vietnamese banks
Grokking VN
 
Grokking Techtalk #45: First Principles Thinking
Grokking Techtalk #45: First Principles ThinkingGrokking Techtalk #45: First Principles Thinking
Grokking Techtalk #45: First Principles Thinking
Grokking VN
 
Grokking Techtalk #43: Payment gateway demystified
Grokking Techtalk #43: Payment gateway demystifiedGrokking Techtalk #43: Payment gateway demystified
Grokking Techtalk #43: Payment gateway demystified
Grokking VN
 
Grokking Techtalk #34: K8S On-premise: Incident & Lesson Learned ZaloPay Mer...
 Grokking Techtalk #34: K8S On-premise: Incident & Lesson Learned ZaloPay Mer... Grokking Techtalk #34: K8S On-premise: Incident & Lesson Learned ZaloPay Mer...
Grokking Techtalk #34: K8S On-premise: Incident & Lesson Learned ZaloPay Mer...
Grokking VN
 

Mais de Grokking VN (20)

Grokking Techtalk #46: Lessons from years hacking and defending Vietnamese banks
Grokking Techtalk #46: Lessons from years hacking and defending Vietnamese banksGrokking Techtalk #46: Lessons from years hacking and defending Vietnamese banks
Grokking Techtalk #46: Lessons from years hacking and defending Vietnamese banks
 
Grokking Techtalk #45: First Principles Thinking
Grokking Techtalk #45: First Principles ThinkingGrokking Techtalk #45: First Principles Thinking
Grokking Techtalk #45: First Principles Thinking
 
Grokking Techtalk #42: Engineering challenges on building data platform for M...
Grokking Techtalk #42: Engineering challenges on building data platform for M...Grokking Techtalk #42: Engineering challenges on building data platform for M...
Grokking Techtalk #42: Engineering challenges on building data platform for M...
 
Grokking Techtalk #43: Payment gateway demystified
Grokking Techtalk #43: Payment gateway demystifiedGrokking Techtalk #43: Payment gateway demystified
Grokking Techtalk #43: Payment gateway demystified
 
Grokking Techtalk #40: Consistency and Availability tradeoff in database cluster
Grokking Techtalk #40: Consistency and Availability tradeoff in database clusterGrokking Techtalk #40: Consistency and Availability tradeoff in database cluster
Grokking Techtalk #40: Consistency and Availability tradeoff in database cluster
 
Grokking Techtalk #40: AWS’s philosophy on designing MLOps platform
Grokking Techtalk #40: AWS’s philosophy on designing MLOps platformGrokking Techtalk #40: AWS’s philosophy on designing MLOps platform
Grokking Techtalk #40: AWS’s philosophy on designing MLOps platform
 
Grokking Techtalk #39: Gossip protocol and applications
Grokking Techtalk #39: Gossip protocol and applicationsGrokking Techtalk #39: Gossip protocol and applications
Grokking Techtalk #39: Gossip protocol and applications
 
Grokking Techtalk #39: How to build an event driven architecture with Kafka ...
 Grokking Techtalk #39: How to build an event driven architecture with Kafka ... Grokking Techtalk #39: How to build an event driven architecture with Kafka ...
Grokking Techtalk #39: How to build an event driven architecture with Kafka ...
 
Grokking Techtalk #38: Escape Analysis in Go compiler
 Grokking Techtalk #38: Escape Analysis in Go compiler Grokking Techtalk #38: Escape Analysis in Go compiler
Grokking Techtalk #38: Escape Analysis in Go compiler
 
Grokking Techtalk #37: Data intensive problem
 Grokking Techtalk #37: Data intensive problem Grokking Techtalk #37: Data intensive problem
Grokking Techtalk #37: Data intensive problem
 
Grokking Techtalk #37: Software design and refactoring
 Grokking Techtalk #37: Software design and refactoring Grokking Techtalk #37: Software design and refactoring
Grokking Techtalk #37: Software design and refactoring
 
Grokking TechTalk #35: Efficient spellchecking
Grokking TechTalk #35: Efficient spellcheckingGrokking TechTalk #35: Efficient spellchecking
Grokking TechTalk #35: Efficient spellchecking
 
Grokking Techtalk #34: K8S On-premise: Incident & Lesson Learned ZaloPay Mer...
 Grokking Techtalk #34: K8S On-premise: Incident & Lesson Learned ZaloPay Mer... Grokking Techtalk #34: K8S On-premise: Incident & Lesson Learned ZaloPay Mer...
Grokking Techtalk #34: K8S On-premise: Incident & Lesson Learned ZaloPay Mer...
 
Grokking TechTalk #33: High Concurrency Architecture at TIKI
Grokking TechTalk #33: High Concurrency Architecture at TIKIGrokking TechTalk #33: High Concurrency Architecture at TIKI
Grokking TechTalk #33: High Concurrency Architecture at TIKI
 
Grokking TechTalk #33: Architecture of AI-First Systems - Engineering for Big...
Grokking TechTalk #33: Architecture of AI-First Systems - Engineering for Big...Grokking TechTalk #33: Architecture of AI-First Systems - Engineering for Big...
Grokking TechTalk #33: Architecture of AI-First Systems - Engineering for Big...
 
SOLID & Design Patterns
SOLID & Design PatternsSOLID & Design Patterns
SOLID & Design Patterns
 
Grokking TechTalk #31: Asynchronous Communications
Grokking TechTalk #31: Asynchronous CommunicationsGrokking TechTalk #31: Asynchronous Communications
Grokking TechTalk #31: Asynchronous Communications
 
Grokking TechTalk #30: From App to Ecosystem: Lessons Learned at Scale
Grokking TechTalk #30: From App to Ecosystem: Lessons Learned at ScaleGrokking TechTalk #30: From App to Ecosystem: Lessons Learned at Scale
Grokking TechTalk #30: From App to Ecosystem: Lessons Learned at Scale
 
Grokking TechTalk #29: Building Realtime Metrics Platform at LinkedIn
Grokking TechTalk #29: Building Realtime Metrics Platform at LinkedInGrokking TechTalk #29: Building Realtime Metrics Platform at LinkedIn
Grokking TechTalk #29: Building Realtime Metrics Platform at LinkedIn
 
Grokking TechTalk #27: Optimal Binary Search Tree
Grokking TechTalk #27: Optimal Binary Search TreeGrokking TechTalk #27: Optimal Binary Search Tree
Grokking TechTalk #27: Optimal Binary Search Tree
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Último (20)

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
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
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
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...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

Grokking TechTalk #16: Maybe functor in javascript

  • 1. Maybe Functor in Javascript Another approach to null handling 1
  • 2. 2
  • 3. Origin of Null Pointer Exception ● Sir Tony Hoare was designing type systems for the language ALGOL W and he put “Null Pointer Exception” as part of the language, because “because it was so easy to implement” ● In 2009, he called it “The Billion Dollar Mistake” 3
  • 4. What we want: getCountry('vn').getCity('HCMC').population; What we have to do var country = getCountry('vn'); if (country !== null) { var city = country.getCity('HCMC'); if (city !== null) { var population = city.population; } } How do we fight NULL? 4 Drawbacks: ● Looks complicated ● Error-prone, especially when there are many nesting ifs ● Tedious to write ● Declares a lot of useless variables
  • 5. ● A Functor is a container of a value Introduction to Functor 5 A value A container of value ● A simple Functor can be implemented through an ES6 class class Functor { constructor(value) { this.value = value; } }
  • 6. One important thing about Functor 6 By definition, a functor needs to implement a map function
  • 7. Remember Array Map? 7 Let’s look at Array’s map function. var addOne = (x) => x + 1; var square = (x) => x * x; var result = [1, 2, 3] .map(addOne) // [2, 3, 4] .map(square); // [4, 9, 16]
  • 8. Implement map for Functor 8 class Functor { constructor(value) { this.value = value; } map(fn) { var newValue = fn(this.value); return new Functor(newValue); } }
  • 9. Let’s see it in action (1) 9 var addOne = (x) => x + 1; var functorOf6 = new Functor(5).map(addOne); // Functor(6)
  • 10. It can also work with any value, for example, an object: var toUpperCase = (str) => str.toUpperCase(); var exciting = (someName) => someName + ’!!!!!!!’; var value = { name: 'grokking' }; var containerOfValue = new Functor(value) .map(thing => thing.name) // Functor(‘grokking’) .map(toUpperCase) // Functor(‘GROKKING’) .map(exciting); // Functor(‘GROKKING!!!!!!!’) Let’s see it in action (2) 10
  • 11. Notice that our actual value is still inside the Functor. var functorOf36 = new Functor(5) .map(addOne) // Functor(6) .map(square); // Functor(36) var result = functorOf36 + 100; // Functor(36) + 100 ??????? How to get the value inside Functor 11 Let’s add another method to Functor to extract the value. class Functor { get() { return this.value; } }
  • 12. var valueInside = new Functor(5) .map(addOne) // Functor(6) .map(square); // Functor(36) .get(); // 36 var toUpperCase = (str) => str.toUpperCase(); var exciting = (someName) => someName + '!!!!!!'; var valueInside = new Functor({ name: 'grokking' }) .map(people => people.name) // Functor(‘grokking’) .map(toUpperCase) // Functor(‘GROKKING’) .map(exciting); // Functor(‘GROKKING!!!!!!!’) .get(); // 'GROKKING!!!!!!!' Now we can get the value inside Functor 12
  • 13. class Functor { constructor(value) { this.value = value; } map(fn) { var newValue = fn(this.value); return new Maybe(newValue); } get() { return this.value; } } Full implementation of Functor 13
  • 14. var addOne = (x) => null; // we return Null var square = (x) => x * x; var valueInside = new Functor(1) .map(addOne) // Functor(null) .map(square); // Functor(null * null) ???? .get(); // ???? But we are still affected by NULL 14 The solution is to turn our functor into a Maybe
  • 15. ● Maybe is a kind of Functor that is Null- friendly. Real magic happens in the map function ● Maybe that contains a real value (not null) is usually called a Just / Some ● Maybe that contains null value is usually called a Nothing / None Introduction to Maybe 15 Maybe(value) = Just(value) Maybe(null) = Nothing
  • 16. class Maybe { constructor(value) { this.value = value; } map(fn) { if (this.value !== null) { // Magic happens here var newValue = fn(this.value); return new Maybe(newValue); } return new Maybe(null); } getOrElse(fallBackValue) { return (this.value === null) ? this.value : fallBackValue; } } Let’s implement Maybe 16
  • 17. It’s pretty much the same as Functor’s example. The only difference is that we use getOrElse instead of get var addOne = (x) => x + 1; var square = (x) => x * x; var result = new Maybe(3) .map(addOne) // Maybe(4) .map(square) // Maybe(16) .getOrElse(0); // 16 Maybe in action 17
  • 18. When Maybe contains NULL, it will not map anymore var result = new Maybe(3) .map(x => null) // Maybe(null) .map(x => x * x) // Maybe(null) .getOrElse(0); // 0 var result = new Maybe(3) .map(x => x + 1) // Maybe(4) .map(x => null) // Maybe(null) .getOrElse(0); // 0 When Null happens 18
  • 19. Some real world examples var family = { grandma: { mother: { you: 'YOUR NAME HERE' } } }; var you = new Maybe(family.grandma) .map(grandma => grandma.mother) .map(mother => mother.you) .getOrElse('DEFAULT NAME'); // returns “YOUR NAME HERE” var family = { grandma: null }; var you = new Maybe(family.grandma) .map(grandma => grandma.mother) .map(mother => mother.you) .getOrElse('DEFAULT NAME'); // returns “DEFAULT NAME” 19 We can use it to safely access nested objects
  • 20. Compare with what we used to do 20 var you = family.grandma.mother.you || 'DEFAULT NAME'; var you = 'DEFAULT NAME'; if (family.grandma && family.grandma.mother && family.grandma.mother.you) { you = family.grandma.mother.you; } var you = new Maybe(family.grandma) .map(grandma => grandma.mother) .map(mother => mother.you) .getOrElse('DEFAULT NAME'); Short, but unsafe Safe, but long and nested Safe and flattened
  • 21. var population = new Maybe(getCountry('vn')) .map(country => country.getCity('HCMC')) .map(city => city.population) .getOrElse(0); Some real world examples var country = getCountry('vn'); if (country !== null) { var city = country.getCity('HCMC'); if (city !== null) { var population = city.population; } } 21 We can rewrite our example earlier Into shorter and flattened code
  • 22. ● Is just a container of value ● Is a fundamental concept in Functional Programming. From there you can explore Applicative and Monad ● Is a kind of functor that checks null on each map ● Helps flatten your code ● Is used widely in many other languages: - Haskell, Elm: Maybe Recap 22 Maybe Functor
  • 23. References ● https://github.com/fantasyland/fantasy-land Fantasy Land Specification ● https://cwmyers.github.io/monet.js/ Powerful abstractions for Javascript ● http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html Functor, Applicatives, Monads in pictures ● https://en.wikipedia.org/wiki/Functor (looks scary with all the math) ● http://www.mokacoding.com/blog/functor-applicative-monads-in-pictures/ (Maybe in Swift) ● http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html Java 8 Optional 23