Monads & Gonads Douglas Crockford.

Slides:



Advertisements
Similar presentations
The JavaScript Programming Language
Advertisements

PHP Form and File Handling
JavaScript: A Language of Many Contrasts
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Intro to Javascript CS Client Side Scripting CS380 2.
CSE Lecture 12 – Linked Lists …
1 What is JavaScript? JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language A scripting language is a lightweight.
the javascript language BY SA.
Save this in an.html file. function log(arg) { document.writeln(arg); } function identity(x) { return x; } log(identity(3));
JavaScript FaaDoOEngineers.com FaaDoOEngineers.com.
Concurrency The need for speed. Why concurrency? Moore’s law: 1. The number of components on a chip doubles about every 18 months 2. The speed of computation.
JavaScript: JS301 Week 1: An Introduction to JavaScript.
I just met you, and 'this' is crazy, but here's my NaN, so call(me) maybe? JavaScript is so weird.
JSON, ADsafe, and Misty Douglas Crockford Yahoo!.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Javascript Client-side scripting. Up to now  We've seen a little about how to control  content with HTML  presentation with CSS  Javascript is a language.
COMS S1007 Object-Oriented Programming and Design in Java August 7, 2007.
JAVASCRIPT Introduction Kenny Lam. What is Javascript?  Client-side scripting language that can manipulate elements in the DOM  Event-driven language.
Interesting facts about node.js.  Asynchronous I/O  How do they do that?..threads (usually) What do Web Servers do?
 A JavaScript runtime environment running Google Chrome’s V8 engine ◦ a.k.a. a server-side solution for JS ◦ Compiles JS, making it really fast  Runs.
Serversideness Douglas Crockford Yahoo! Inc.. Server Side JavaScript 1996 Netscape LiveWire PHP-like. Fail. Now Node.js on V8. Event driven, turn based.
 George Chrysanthakopoulos Software Architect Microsoft Corporation.
JavaScript JavaScript is a scripting language that is most commonly used to add client- side programming to a web page. Some of the things it is used for.
CSCI 6962: Server-side Design and Programming Introduction to AJAX.
Monads Technion – Institute of Technology Software Design (236700) Author: Gal Lalouche - Technion 2015 © 1.
COMPUTER PROGRAMMING 2 Exceptions. What are Exceptions? Unexpected events that happen when the code is executing (during runtime). Exceptions are types.
WEEK 3 AND 4 USING CLIENT-SIDE SCRIPTS TO ENHANCE WEB APPLICATIONS.
1 JavaScript. 2 What’s wrong with JavaScript? A very powerful language, yet –Often hated –Browser inconsistencies –Misunderstood –Developers find it painful.
CISC474 - JavaScript 03/02/2011. Some Background… Great JavaScript Guides: –
Node.js - What is Node.js? -
SE-2840 Dr. Mark L. Hornick 1 Modifying webpage behavior using client-side scripting Javascript.
JavaScript davide morelli history LiveScript (1995) in Netscape java script is a misleading name started as a scripting counterpart.
JavaScript. Overview Introduction: JavaScript basics Expressions and types Expressions and types Arrays Arrays Objects and Associative Arrays Objects.
CHAPTER 4 Java Script อ. ยืนยง กันทะเนตร คณะเทคโนโลยีสารสนเทศและการสื่อสาร มหาวิทยาลัยพะเยา 1.
CNIT 133 Interactive Web Pags – JavaScript and AJAX Advanced topic - variable.
Using Client-Side Scripts to Enhance Web Applications 1.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
CSC 580 – Theory of Programming Languages, Spring, 2009 Week 9: Functional Languages ML and Haskell, Dr. Dale E. Parson.
Lecture 9: AJAX, Javascript review..  AJAX  Synchronous vs. asynchronous browsing.  Refreshing only “part of a page” from a URL.  Frameworks: Prototype,
4.4 JavaScript (JS) Deitel Ch. 7, 8, 9, JavaScript & Java: Similarities JS (JavaScript) is case-sensitive Operators –arithmetic: unary +, unary.
CSE 341 Lecture 29 a JavaScript, the bad parts slides created by Marty Stepp see also: JavaScript: The Good Parts, by.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
The Client-Server Model And the Socket API. Client-Server (1) The datagram service does not require cooperation between the peer applications but such.
CNIT 133 Interactive Web Pags – JavaScript and AJAX Objects.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Interactive Programs: I/O and Monads Dr. Hyunyoung Lee.
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
Concurrency case studies in UNIX John Chapin October 26, 1998.
“The world’s most misunderstood language has become the world’s most popular programming language” Akshay Arora
Rich Internet Applications 2. Core JavaScript. The importance of JavaScript Many choices open to the developer for server-side Can choose server technology.
Introduction to Javascript. What is javascript?  The most popular web scripting language in the world  Used to produce rich thin client web applications.
JavaScript and Ajax Week 10 Web site:
JavaScript Tutorial First lecture 19/2/2016. Javascript is a dynamic computer programming language. It is lightweight and most commonly used as a part.
INTERNET APPLICATIONS CPIT405 JavaScript Instructor: Rasha AlOmari
Process Management Process Concept Why only the global variables?
Learning to Program D is for Digital.
Advanced Topics in Distributed and Reactive Programming
CSE 775 – Distributed Objects Submitted by: Arpit Kothari
Web Systems Development (CSC-215)
Advanced Topics in Distributed and Reactive Programming
Building responsive apps and sites with HTML5 web workers
CS5220 Advanced Topics in Web Programming JavaScript Basics
University of Kurdistan
Week 01 Node.js Week 01
CS5220 Advanced Topics in Web Programming Node.js Basics
Lecture 12: The Fetch Api and AJAx
JavaScript CS 4640 Programming Languages for Web Applications
Lecture 12: The Fetch Api and AJAx
Advanced Topics in Functional and Reactive Programming
CS3220 Web and Internet Programming JavaScript Basics
JavaScript CS 4640 Programming Languages for Web Applications
Presentation transcript:

Monads & Gonads Douglas Crockford

Functional Programming Programming with functions.

FORTRAN II (1958) FUNCTION name(parameters) COMMON ... name = expression RETURN END

First Class Functions Higher Order Functions Lexical Closure

Pure Functional Programming More mathematical.

Functions as maps

Memoization Caching

Programming without side-effects. Remove assignment, loops (use recursion instead), freeze all array literals and object literals. Remove Date and Math.random.

In the real world, everything changes. Immutability makes it hard to interact with the world.

A loophole in the function contract. Monads A loophole in the function contract.

In order to understand monads, you need to first learn Haskell and Category Theory.

In order to understand burritos, you must first learn Spanish. In order to understand monads, you need to first learn Haskell and Category Theory. In order to understand burritos, you must first learn Spanish.

(M t) → (t → M u) → (M u) Not tonight, Josephine.

…you must first learn JavaScript function unit(value) function bind(monad, function (value)) All three functions return a monad.

Axioms bind(unit(value), f) ==== f(value) bind(monad, unit) ==== monad bind(bind(monad, f), g) ==== bind(monad, function (value) { return bind(f(value), g); })

bind(monad, func) monad.bind(func) The OO transform.

function MONAD() { return function unit(value) { var monad = Object function MONAD() { return function unit(value) { var monad = Object.create(null); monad.bind = function (func) { return func(value); }; return monad; } Context Coloring

function MONAD() { return function unit(value) { var monad = Object function MONAD() { return function unit(value) { var monad = Object.create(null); monad.bind = function (func) { return func(value); }; return monad; } Macroid

function MONAD() { return function unit(value) { var monad = Object function MONAD() { return function unit(value) { var monad = Object.create(null); monad.bind = function (func) { return func(value); }; return monad; } var identity = MONAD(); var monad = identity("Hello world."); monad.bind(alert);

Axioms unit(value).bind(f) ==== f(value) monad.bind(unit) ==== monad monad.bind(f).bind(g) ==== monad.bind(function (value) { return f(value).bind(g); })

Axioms bind(bind(monad, f), g) monad.bind(f).bind(g)

The Ajax Monad monad.bind(f).bind(g)

Interstate (2001) new Interform('text') .moveTo(100, 100) .setSize(400, 32) .moveInside() .setBgColor('pink') .select() .setZIndex(20000) .on('escapekey', 'erase');

ADsafe (2007) var input = dom.q("input_text") .on('enterkey', function (e) { dom.q('#ROMAN_RESULT') .value(roman(input .getValue())); input .select(); }) .focus();

monad. bind(func) monad. bind(func, [ a, b, c ]) monad. method() monad monad.bind(func) monad.bind(func, [ a, b, c ]) monad.method() monad.method(a, b, c)

monad. bind(func) monad. bind(func, [ a, b, c ]) monad. method() monad monad.bind(func) monad.bind(func, [ a, b, c ]) monad.method() monad.method(a, b, c)

function MONAD() { var prototype = Object function MONAD() { var prototype = Object.create(null); function unit(value) { var monad = Object.create(prototype); monad.bind = function (func) { return func(value); }; return monad; } return unit;

function MONAD() { var prototype = Object function MONAD() { var prototype = Object.create(null); function unit(value) { var monad = Object.create(prototype); monad.bind = function (func, args) { return func.apply(undefined, [value].concat(Array.prototype .slice.apply(args || []))); }; return monad; } return unit;

function MONAD() { var prototype = Object function MONAD() { var prototype = Object.create(null); function unit(value) { var monad = Object.create(prototype); monad.bind = function (func, args) { return func(value, ...args)); }; return monad; } return unit;

function MONAD() { var prototype = Object function MONAD() { var prototype = Object.create(null); function unit(value) { var monad = Object.create(prototype); monad.bind = function (func, args) { return func(value, ...args)); }; return monad; } unit.method = function (name, func) { prototype[name] = func; return unit;

function MONAD() { var prototype = Object function MONAD() { var prototype = Object.create(null); function unit(value) { var monad = Object.create(prototype); monad.bind = function (func, args) { return func(value, ...args)); }; return monad; } unit.lift = function (name, func) { prototype[name] = function (...args) { return unit(this.bind(func, args)); return unit;

var ajax = MONAD() .lift('alert', alert); var monad = ajax("Hello world."); monad.alert();

Null Pointer Exception

Maybe NaN

function MONAD(modifier) { var prototype = Object function MONAD(modifier) { var prototype = Object.create(null); function unit(value) { var monad = Object.create(prototype); monad.bind = function (func, args) { return func(value, ...args)); }; if (typeof modifier === 'function') { modifier(monad, value); } return monad; return unit;

var maybe = MONAD(function (monad, value) { if (value === null || value === undefined) { monad.is_null = true; monad.bind = function () { return monad; }; } }); var monad = maybe(null); monad.bind(alert);

The Identity Monad The Ajax Monad The Maybe Monad Our Friend the Monad The Identity Monad The Ajax Monad The Maybe Monad

Concurrency Threads are evil.

Turn Based Processing Single-threaded. Race free. Deadlock free. The Law of Turns: Never wait. Never block. Finish fast. Events. Message passing. Threads. Mutexs. Web browsers. Most UI frameworks. Servers: Elko, Twisted, Nodejs. Asynchronicity can be hard to manage.

Promises Promises are an excellent mechanism for managing asynchronicity. A promise is an object that represents a possible future value. Every promise has a corresponding resolver that is used to ultimately assign a value to the promise. A promise can have one of three states: 'kept', 'broken', or 'pending'.

Promises A promise is an event generator. It fires its event when the value of the promise is ultimately known. At any time after the making the promise, event handling functions can be registered with the promise, which will be called in order with the promise’s value when it is known.

Promises A promise can accept functions that will be called with the value once the promise has been kept or broken. promise.when(success, failure) returns another promise for the result of your success function.

Make a vow var my_vow = VOW.make(); .keep(value) .break(reason) .promise .when(kept, broken)

Filesystem API read_file(name) .when(function success(string) { ... }, failure);

Exceptions Exceptions modify the flow of control by unwinding the state. In a turn based system, the stack is empty at the end of every turn. Exceptions cannot be delivered across turns. Broken promises can.

Breakage flows to the end my_promise .when(success_a) .when(success_b) .when(success_c, failure); success_a gets the value of my_promise success_b gets the value of success_a success_c gets the value of success_b unless any promise breaks: failure gets the reason

Composition f() .when(function (f_value) { return g(f_value); }) .when(function (g_value) { ... ==== return g(f_value) });

A promise is a monad The value is not known when the monad is made. Each promise is linked to two resolver functions, keep and break, that determine the promise’s success and value. when can take two functions, bind only one.

var VOW = (function () { // function enlighten var VOW = (function () { // function enlighten... return { make: function make() { ... } }; })();

var VOW = (function () { // function enlighten var VOW = (function () { // function enlighten... return { make: function make() { ... } }; })(); Dog balls

var VOW = (function () { // function enlighten var VOW = (function () { // function enlighten... return { make: function make() { ... } }; }());

make: function make() { var breakers = [], fate, keepers = [], status = 'pending'; // function enqueue here... // function herald here... return { break: function (reason) { herald('broken', reason, breakers); }, keep: function (value) { herald('kept', value, keepers); promise: { ... } };

promise: { is_promise: true, when: function (kept, broken) { var vow = make(); switch (status) { case 'pending': enqueue('keep', kept, vow); enqueue('break', broken, vow); break; case 'kept': enlighten(keepers, fate); case 'broken': enlighten(breakers, fate); } return vow.promise;

make: function make() { var breakers = [], fate, keepers = [], status = 'pending'; // function enqueue here... // function herald here... return { break: function (reason) { herald('broken', reason, breakers); }, keep: function (value) { herald('kept', value, keepers); promise: { ... } };

function enqueue(resolution, func, vow) { var queue = resolution === 'keep' ? keepers : breakers; queue[queue.length] = typeof func !== 'function' ? vow[resolution] : function (value) { try { var result = func(value); if (result && result.is_promise === true) { result.when(vow.keep, vow['break']); } else { vow.keep(result); } } catch (e) { vow['break'](e); };

function herald(state, value, queue) { if (status function herald(state, value, queue) { if (status !== 'pending') { throw "overpromise"; } fate = value; status = state; enlighten(queue, fate); keepers.length = 0; breakers.length = 0;

function enlighten(queue, fate) { queue function enlighten(queue, fate) { queue.forEach(function (func) { setImmediate(func, fate); }); } https://github.com/douglascrockford/monad

var VOW = (function () { function enlighten(queue, fate) { queue var VOW = (function () { function enlighten(queue, fate) { queue.forEach(function (func) { setImmediate(func, fate); }); } return { make: function make() { var breakers = [], fate, keepers = [], status = 'pending'; function enqueue(resolution, func, vow) { var queue = resolution === 'keep' ? keepers : breakers; queue[queue.length] = typeof func !== 'function' ? vow[resolution] : function (value) { try { var result = func(value); if (result && result.is_promise === true) { result.when(vow.keep, vow['break']); } else { vow.keep(result); } catch (e) { vow['break'](e); }; function herald(state, value, queue) { if (status !== 'pending') { throw "overpromise"; fate = value; status = state; enlighten(queue, fate); keepers.length = 0; breakers.length = 0; break: function (reason) { herald('broken', reason, breakers); }, keep: function (value) { herald('kept', value, keepers); promise: { is_promise: true, when: function (kept, broken) { var vow = make(); switch (status) { case 'pending': enqueue('keep', kept, vow); enqueue('break', broken, vow); break; case 'kept': enlighten(keepers, fate); case 'broken': enlighten(breakers, fate); return vow.promise; }());

The Identity Monad The Ajax Monad The Maybe Monad The Promise Monad Our Friend the Monad The Identity Monad The Ajax Monad The Maybe Monad The Promise Monad

;

Further Viewing Carl Hewitt. The Actor Model (everything you wanted to know, but were afraid to ask) http://channel9.msdn.com/Shows/Going+Deep/ Hewitt-Meijer-and-Szyperski-The-Actor-Model-everything-you-wanted-to-know-but-were-afraid-to-ask Mark Miller. Secure Distributed Programming with Object-capabilities in JavaScript http://www.youtube.com/watch?v=w9hHHvhZ_HY http://www.youtube.com/watch?v=oBqeDYETXME