SlideShare uma empresa Scribd logo
1 de 27
To Infinity & Beyond!
   Protocols & Lazy Sequences in Node
                  Part 1

Bahul Neel Upadhyaya (@bahulneel)
BraveNewTalent
http://github.com/bahulneel
http://www.bravenewtalent.com
JavaScript
●   Imperative
●   Dynamic
●   OOP
    –   Prototypes
    –   Constructors
●   Functional
    –   First Class Functions       Brendan Eich
    –   Closures
List Comprehension
●   Loops
    –   for (init; while; step)
●   Stack & Queue
    –   push/pop/shift/unshift
●   Iterators
    –   forEach, etc
●   Map/Reduce


               No standard way of doing these
Collections
    How do I know if collection x works with my function?
●   Extends Array?
●   Implements Array?
●   Impements some iterator?
●   Do I need to monkey patch?
Collections
Lisp




John McCarthy                 Structure and
                       Interpretation of Computer
                                Programs
Lists


first   rest   first    rest   first   rest
Using Lists
map = function(list, fn) {                            reduce = function(list, fn) {
         var head = first(list), tail = rest(list);           var head = first(list), tail = rest(list);
         if (!head) return [];                                if (!head) return null;
         result = map(tail, fn);                              result = reduce(tail, fn);
         return [fn(head)].append(result);                    return fn(head, result);
};                                                    };
filter = function(list, fn) {                         forEach = function(list, fn) {
     var head = first(list), tail = rest(list);            var head = first(list), tail = rest(list);
     if (!head) return [];                                 if (!head) return null;
     result = map(tail, fn);                               fn(head);
     if (fn(head)) return [head].append(result);           forEach(tail, fn);
     else return result;
                                                      };
};
Sequences
●   collection.first()
    –   Returns the first item
●   collection.rest()
    –   Returns a sequence of the the tail of the
        collection
●   collection.cons(item)
    –   Returns a new collection with item at the head
        and the collection at the tail
Lazy Sequences
●   Only really care about the data in
    the list when we call first()
●   rest() can be lazily evaluated
Using Lazy Seqences
map = function(coll, fn) {
     return lazySeq(function() {
       var head = coll.first(list), tail = coll.rest(list);
       return lazySeq.cons(map(tail, fn), fn(head));
     });
};
The Interface Problem
●   How do we check for the sequence
    interface?
●   How do we apply the interface
    implementation if it's missing?
●   What do we do if some object already
    has a first, rest or cons which are
    different from the ones we expect?
Monkey Patching
MyColl.protoype.first = function(coll) {}
MyColl.protoype.rest = function(coll) {}
MyColl.protoype.cons = function(coll, item) {}
The Adapter Pattern
mySeq =mySeqAdapter(myColl);
head = mySeq.first();
tail = mySeq.rest();
newSeq = myColl.cons(item);
Switching
function first(coll) {
    if (coll === null)
       return null;
    else if (isArray(coll))
       return coll[0];
    else if ('function' === typeof coll.first)
       return coll.first();
    else
      throw new Error('not a sequence');
}
Protocols
var Sequence = protocol.define(
     'Sequence',
     [ 'first', [ 'coll' ] ],
     [ 'rest', [ 'coll' ] ],
     [ 'cons', [ 'coll' ] ]
);
protocol.extend(
     Sequence
     MyCollection,
     [ 'first', function (coll) { return coll.head(); } ],
     [ 'rest', function (coll) { return coll.tail(); } ],
     [ 'cons', function (coll, item) { return coll.cons(item); }
);
Protocols vs. Interfaces
 Protocol          Interface
      Object          Interface

         Calls
                           Implements
  Implementation

         Calls
                       Object

     Protocol
                           Calls
         Calls

  someFunction      someFunction
Using Protocols
var first = Sequence.first, rest = Sequence.rest,
       cons = Sequence.cons;

map = function(coll, fn) {
     return lazySeq(function() {
       var head = first(coll, list), tail = rest(coll, list);
       return cons(map(tail, fn), fn(head));
     });
};
What about Node?
●   Sequences are synchronous
●   Node is aynchronous


             Pull vs. Push
Async in Node
      Streams          Promises
●   Evented      ●   Single shot
●   Callbacks    ●   Callbacks
●   Buffered     ●   Unbuffered
●   Composable   ●   Composable
Async Map
map = function(stream, fn) {
     var result = stream.Stream();
     result.writable = true;
     stream.on(“data”, function(data) {
       result.write(fn(data));
     });
     return result;
};
Async Sequences
●   first(stream)
    –   A promise to the first item in the first buffer in the
        stream.
●   rest(stream)
    –   A sequence of the rest of the items in the first buffer
        with the original stream at the tail.
●   cons(stream, item)
    –   A sequence with a promise to the item at the head and
        the stream as the tail.
Observations
●   Lazy Sequences are like promises
●   Syncronous values can be
    reresented as promises that
    resolve immediately
●   With protocols we can conjoin
    sequences.
Potential Uses
●   Higher level abstractions
●   Mix and match sync & async
●   Write once run anywhere
●   Leverage new technologies e.g.
    WebCL
Get cosy
●   cosy.lang
    –   Protocols
    –   Lazy Sequences
    –   Tail Recursion
http://bnt.getcosy.org (v0)
http://getcosy.org (v1+)
To be continued...

Part 2
●   Async Sequences
●   Tail Recursion
●   Live Demos
Questions

Mais conteúdo relacionado

Mais procurados

Programación funcional con haskell
Programación funcional con haskellProgramación funcional con haskell
Programación funcional con haskellAgustin Ramos
 
Advanced perl finer points ,pack&unpack,eval,files
Advanced perl   finer points ,pack&unpack,eval,filesAdvanced perl   finer points ,pack&unpack,eval,files
Advanced perl finer points ,pack&unpack,eval,filesShankar D
 
ZCA: A component architecture for Python
ZCA: A component architecture for PythonZCA: A component architecture for Python
ZCA: A component architecture for PythonTimo Stollenwerk
 
Parsers Combinators in Scala, Ilya @lambdamix Kliuchnikov
Parsers Combinators in Scala, Ilya @lambdamix KliuchnikovParsers Combinators in Scala, Ilya @lambdamix Kliuchnikov
Parsers Combinators in Scala, Ilya @lambdamix KliuchnikovVasil Remeniuk
 
Something about Golang
Something about GolangSomething about Golang
Something about GolangAnton Arhipov
 
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5PyNSK
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrencyjgrahamc
 
Promise of an API
Promise of an APIPromise of an API
Promise of an APIMaxim Zaks
 
ภาษา C โปรแกรมย่อยและฟังก์ชันมาตรฐาน
ภาษา C โปรแกรมย่อยและฟังก์ชันมาตรฐานภาษา C โปรแกรมย่อยและฟังก์ชันมาตรฐาน
ภาษา C โปรแกรมย่อยและฟังก์ชันมาตรฐานNoppanon YourJust'one
 
Oral presentation v2
Oral presentation v2Oral presentation v2
Oral presentation v2Yeqi He
 
Alfresco the clojure way
Alfresco the clojure wayAlfresco the clojure way
Alfresco the clojure wayCarlo Sciolla
 
The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202Mahmoud Samir Fayed
 
Practical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan HodorogPractical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan Hodorog3Pillar Global
 
The Ring programming language version 1.3 book - Part 60 of 88
The Ring programming language version 1.3 book - Part 60 of 88The Ring programming language version 1.3 book - Part 60 of 88
The Ring programming language version 1.3 book - Part 60 of 88Mahmoud Samir Fayed
 
Stackless Python 101
Stackless Python 101Stackless Python 101
Stackless Python 101guest162fd90
 
GoLightly: A Go Library For Building Virtual Machines
GoLightly: A Go Library For Building Virtual MachinesGoLightly: A Go Library For Building Virtual Machines
GoLightly: A Go Library For Building Virtual MachinesEleanor McHugh
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance PythonIan Ozsvald
 

Mais procurados (20)

Programación funcional con haskell
Programación funcional con haskellProgramación funcional con haskell
Programación funcional con haskell
 
Advanced perl finer points ,pack&unpack,eval,files
Advanced perl   finer points ,pack&unpack,eval,filesAdvanced perl   finer points ,pack&unpack,eval,files
Advanced perl finer points ,pack&unpack,eval,files
 
ZCA: A component architecture for Python
ZCA: A component architecture for PythonZCA: A component architecture for Python
ZCA: A component architecture for Python
 
Parsers Combinators in Scala, Ilya @lambdamix Kliuchnikov
Parsers Combinators in Scala, Ilya @lambdamix KliuchnikovParsers Combinators in Scala, Ilya @lambdamix Kliuchnikov
Parsers Combinators in Scala, Ilya @lambdamix Kliuchnikov
 
Something about Golang
Something about GolangSomething about Golang
Something about Golang
 
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
 
Promise of an API
Promise of an APIPromise of an API
Promise of an API
 
ภาษา C โปรแกรมย่อยและฟังก์ชันมาตรฐาน
ภาษา C โปรแกรมย่อยและฟังก์ชันมาตรฐานภาษา C โปรแกรมย่อยและฟังก์ชันมาตรฐาน
ภาษา C โปรแกรมย่อยและฟังก์ชันมาตรฐาน
 
Oral presentation v2
Oral presentation v2Oral presentation v2
Oral presentation v2
 
Alfresco the clojure way
Alfresco the clojure wayAlfresco the clojure way
Alfresco the clojure way
 
Golang Channels
Golang ChannelsGolang Channels
Golang Channels
 
Pythonの紹介
Pythonの紹介Pythonの紹介
Pythonの紹介
 
The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202
 
Practical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan HodorogPractical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan Hodorog
 
The Ring programming language version 1.3 book - Part 60 of 88
The Ring programming language version 1.3 book - Part 60 of 88The Ring programming language version 1.3 book - Part 60 of 88
The Ring programming language version 1.3 book - Part 60 of 88
 
Stackless Python 101
Stackless Python 101Stackless Python 101
Stackless Python 101
 
GoLightly: A Go Library For Building Virtual Machines
GoLightly: A Go Library For Building Virtual MachinesGoLightly: A Go Library For Building Virtual Machines
GoLightly: A Go Library For Building Virtual Machines
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance Python
 
asyncio internals
asyncio internalsasyncio internals
asyncio internals
 

Semelhante a To Infinity & Beyond: Protocols & sequences in Node - Part 1

Transducers in JavaScript
Transducers in JavaScriptTransducers in JavaScript
Transducers in JavaScriptPavel Forkert
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsPiotr Pelczar
 
Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scalaStratio
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In JavaAndrei Solntsev
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
Practically Functional
Practically FunctionalPractically Functional
Practically Functionaldjspiewak
 
Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaKnolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaAyush Mishra
 
エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理maruyama097
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
Functional programming
Functional programmingFunctional programming
Functional programmingHideshi Ogoshi
 
To Infinity & Beyond: Protocols & sequences in Node - Part 2
To Infinity & Beyond: Protocols & sequences in Node - Part 2To Infinity & Beyond: Protocols & sequences in Node - Part 2
To Infinity & Beyond: Protocols & sequences in Node - Part 2Bahul Neel Upadhyaya
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойSigma Software
 
Queue Data Structure (w/ php egs)
Queue Data Structure (w/ php egs)Queue Data Structure (w/ php egs)
Queue Data Structure (w/ php egs)Roman Rodomansky
 
Functional Programming in F#
Functional Programming in F#Functional Programming in F#
Functional Programming in F#Dmitri Nesteruk
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 

Semelhante a To Infinity & Beyond: Protocols & sequences in Node - Part 1 (20)

Flow control in node.js
Flow control in node.jsFlow control in node.js
Flow control in node.js
 
Transducers in JavaScript
Transducers in JavaScriptTransducers in JavaScript
Transducers in JavaScript
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scala
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In Java
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Practically Functional
Practically FunctionalPractically Functional
Practically Functional
 
Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaKnolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in Scala
 
エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
01. haskell introduction
01. haskell introduction01. haskell introduction
01. haskell introduction
 
To Infinity & Beyond: Protocols & sequences in Node - Part 2
To Infinity & Beyond: Protocols & sequences in Node - Part 2To Infinity & Beyond: Protocols & sequences in Node - Part 2
To Infinity & Beyond: Protocols & sequences in Node - Part 2
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
Queue Data Structure (w/ php egs)
Queue Data Structure (w/ php egs)Queue Data Structure (w/ php egs)
Queue Data Structure (w/ php egs)
 
Functional Programming in F#
Functional Programming in F#Functional Programming in F#
Functional Programming in F#
 
Hands on lua
Hands on luaHands on lua
Hands on lua
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 

Último

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...apidays
 
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 slidevu2urc
 
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.pdfEnterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
[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.pdfhans926745
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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...Martijn de Jong
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
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 educationjfdjdjcjdnsjd
 
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 Takeoffsammart93
 

Último (20)

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...
 
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
 
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
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
[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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
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
 
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
 

To Infinity & Beyond: Protocols & sequences in Node - Part 1

  • 1. To Infinity & Beyond! Protocols & Lazy Sequences in Node Part 1 Bahul Neel Upadhyaya (@bahulneel) BraveNewTalent http://github.com/bahulneel http://www.bravenewtalent.com
  • 2. JavaScript ● Imperative ● Dynamic ● OOP – Prototypes – Constructors ● Functional – First Class Functions Brendan Eich – Closures
  • 3. List Comprehension ● Loops – for (init; while; step) ● Stack & Queue – push/pop/shift/unshift ● Iterators – forEach, etc ● Map/Reduce No standard way of doing these
  • 4. Collections How do I know if collection x works with my function? ● Extends Array? ● Implements Array? ● Impements some iterator? ● Do I need to monkey patch?
  • 6. Lisp John McCarthy Structure and Interpretation of Computer Programs
  • 7. Lists first rest first rest first rest
  • 8. Using Lists map = function(list, fn) { reduce = function(list, fn) { var head = first(list), tail = rest(list); var head = first(list), tail = rest(list); if (!head) return []; if (!head) return null; result = map(tail, fn); result = reduce(tail, fn); return [fn(head)].append(result); return fn(head, result); }; }; filter = function(list, fn) { forEach = function(list, fn) { var head = first(list), tail = rest(list); var head = first(list), tail = rest(list); if (!head) return []; if (!head) return null; result = map(tail, fn); fn(head); if (fn(head)) return [head].append(result); forEach(tail, fn); else return result; }; };
  • 9. Sequences ● collection.first() – Returns the first item ● collection.rest() – Returns a sequence of the the tail of the collection ● collection.cons(item) – Returns a new collection with item at the head and the collection at the tail
  • 10. Lazy Sequences ● Only really care about the data in the list when we call first() ● rest() can be lazily evaluated
  • 11. Using Lazy Seqences map = function(coll, fn) { return lazySeq(function() { var head = coll.first(list), tail = coll.rest(list); return lazySeq.cons(map(tail, fn), fn(head)); }); };
  • 12. The Interface Problem ● How do we check for the sequence interface? ● How do we apply the interface implementation if it's missing? ● What do we do if some object already has a first, rest or cons which are different from the ones we expect?
  • 13. Monkey Patching MyColl.protoype.first = function(coll) {} MyColl.protoype.rest = function(coll) {} MyColl.protoype.cons = function(coll, item) {}
  • 14. The Adapter Pattern mySeq =mySeqAdapter(myColl); head = mySeq.first(); tail = mySeq.rest(); newSeq = myColl.cons(item);
  • 15. Switching function first(coll) { if (coll === null) return null; else if (isArray(coll)) return coll[0]; else if ('function' === typeof coll.first) return coll.first(); else throw new Error('not a sequence'); }
  • 16. Protocols var Sequence = protocol.define( 'Sequence', [ 'first', [ 'coll' ] ], [ 'rest', [ 'coll' ] ], [ 'cons', [ 'coll' ] ] ); protocol.extend( Sequence MyCollection, [ 'first', function (coll) { return coll.head(); } ], [ 'rest', function (coll) { return coll.tail(); } ], [ 'cons', function (coll, item) { return coll.cons(item); } );
  • 17. Protocols vs. Interfaces Protocol Interface Object Interface Calls Implements Implementation Calls Object Protocol Calls Calls someFunction someFunction
  • 18. Using Protocols var first = Sequence.first, rest = Sequence.rest, cons = Sequence.cons; map = function(coll, fn) { return lazySeq(function() { var head = first(coll, list), tail = rest(coll, list); return cons(map(tail, fn), fn(head)); }); };
  • 19. What about Node? ● Sequences are synchronous ● Node is aynchronous Pull vs. Push
  • 20. Async in Node Streams Promises ● Evented ● Single shot ● Callbacks ● Callbacks ● Buffered ● Unbuffered ● Composable ● Composable
  • 21. Async Map map = function(stream, fn) { var result = stream.Stream(); result.writable = true; stream.on(“data”, function(data) { result.write(fn(data)); }); return result; };
  • 22. Async Sequences ● first(stream) – A promise to the first item in the first buffer in the stream. ● rest(stream) – A sequence of the rest of the items in the first buffer with the original stream at the tail. ● cons(stream, item) – A sequence with a promise to the item at the head and the stream as the tail.
  • 23. Observations ● Lazy Sequences are like promises ● Syncronous values can be reresented as promises that resolve immediately ● With protocols we can conjoin sequences.
  • 24. Potential Uses ● Higher level abstractions ● Mix and match sync & async ● Write once run anywhere ● Leverage new technologies e.g. WebCL
  • 25. Get cosy ● cosy.lang – Protocols – Lazy Sequences – Tail Recursion http://bnt.getcosy.org (v0) http://getcosy.org (v1+)
  • 26. To be continued... Part 2 ● Async Sequences ● Tail Recursion ● Live Demos

Notas do Editor

  1. Designed by Brendan Eich in 1994 for Mozilla. Originally called Mocha it was based on Self and Scheme Brings in features from both languages Allows the developer to adopt any style or any combination of those styles.
  2. One of the things we spend most of our time doing is manipulating lists of things (numbers, objects, etc). Currently, in the javascript world, we have a number of ways available to us. Classic for loop, push/pop, forEach, map, etc. Javascript has no standard way to deal with this.
  3. Collections add a extra layer of complexity. Do they extend the Array prototype? If not do they implement the common array functions and/or patterns? If so which ones? Do I need to add these functions myself? When do I add them? Will they collide with someone elses functions? => Complexity & bloat
  4. Is there a better way? Can we find a common set of methods that will let us write a universal function that should work with anyone's collection? I think there is and all we need to do is borrow a few ideas from the Lisp guys.
  5. Designed by John McCarthy in 1958 Made popular in AI circles by scheme written by Guy Lewis Steele Jr. and Gerald Jay Sussman. Sussman went on to write Structure & Interpetation of Computer Programs with Harold Abelson (must read!) The name LISP was derrived from LISt Processing and had a very simple but powerful way to look at lists
  6. In lisp a list is linked list that has a head and a tail. Where calling first on a list returns the data at the head of the list and calling rest returns a list of all the elements in the tail. It turns out that this representation gets us pretty far if we want a common way to deal with lists.
  7. In Rich Hickey's Clojure dialect of LISP he added the concept of sequences which is any collection implementing the first, rest and cons methods I've shown it on the slide in JS form. Now that we depend on an interface we can now also make an interresting observation.
  8. Until we actually ask for an element of the sequence we're not obliged to evaluate it. That means so long as we're able to evaluate the head at will we never need to bother with the rest until we need it. This means we can save on some unncecessary computation and also have potentially infinite sequences.
  9. Is there some way to do this automatically? Yes: protocols
  10. Think of the boxes as source files Meaning the responsibility is decoulpled.