SlideShare une entreprise Scribd logo
1  sur  45
Télécharger pour lire hors ligne
Transducers
What are they?
How can you use them in JavaScript?
Pavel Forkert
Programming languages &
design patterns geek
Basics
map
[1, 2, 3, 4, 5].map(function(element) {
return element * 2;
});
=> [2, 4, 6, 8, 10]
filter
[1, 2, 3, 4, 5].filter(function(element) {
return element % 2 === 0;
});
=> [2, 4]
reduce
[1, 2, 3, 4, 5].reduce(function(accumulator, element) {
console.log(accumulator, element);
return accumulator + element;
}, 0);
0 1
1 2
3 3
6 4
10 5
=> 15
Reducers
[0, 1, 2, 3, 4, 5, 6, 7]
.map(function(element) { return 1 << element; })
.reduce(function(acc, element) {
return acc + element;
}, 0);
=> 255
Reducers
var powerOfTwo = function(element) { return 1 << element; };
var map = function(fn, coll) { return coll.map(fn); };
var reduce = function(step, initial, coll) {
return coll.reduce(step, initial);
};
reduce(
function(acc, element) { return acc + element; },
0,
map(powerOfTwo, [0, 1, 2, 3, 4, 5, 6, 7]));
Reducers
var map = function(fn, coll) {
return { fn: fn, coll: coll };
};
var reduce = function(step, initial, transformResult) {
var coll = transformResult.coll;
var tfn = transformResult.fn;
var newStep = function(acc, element) {
return step(acc, tfn(element));
};
return coll.reduce(newStep, initial);
};
Reducers
var map = function(fn, coll) {
return {
reduce: function(step, initial) {
return coll.reduce(function(acc, element) {
return step(acc, fn(element));
}, initial);
}
};
};
Reducers
var reduce = function(initial, step, coll) {
return coll.reduce(step, initial);
};
Reducers
var filter = function(pred, coll) {
return {
reduce: function(step, initial) {
return coll.reduce(function(acc, element) {
return pred(element) ? step(acc, element) : acc;
}, initial);
}
};
};
Reducers
var even = function(element) { return element % 2 === 0; };
reduce(
function(acc, element) { return acc + element; },
0,
filter(even, map(powerOfTwo, [0, 1, 2, 3, 4, 5, 6, 7])));
=> 254
reduce(
function(acc, element) { return acc + element; },
0,
map(powerOfTwo, filter(even, [0, 1, 2, 3, 4, 5, 6, 7])));
=> 85
–Rich Hickey
“Using these directly is somewhat odd”
Why?
Keep advantages of reducers
Decouple transformations from inputs and outputs
Allow transformations to work in different contexts (channels, eager
collections, lazy collections, queues, event streams)
Composability!
transducers
transforming reducers
Transducers
(accumulator, element) -> accumulator
((accumulator, element) -> accumulator) ->

((accumulator, element) -> accumulator)
function map(fn) {
return function(step) {
return function(accumulator, element) {
return step(accumulator, fn(element));
};
};
};
Reducers
var map = function(fn, coll) {
return {
reduce: function(step, initial) {
return coll.reduce(function(acc, element) {
return step(acc, fn(element));
}, initial);
}
};
};
Transducers
var map = function(fn, coll) {
return {
reduce: function(step, initial) {
return coll.reduce(function(acc, element) {
return step(acc, fn(element));
}, initial);
}
};
};
Reducers
reduce(
function(acc, element) { return acc + element; },
0,
map(powerOfTwo, [0, 1, 2, 3, 4, 5, 6, 7]));
Transducers
transduce(
map(powerOfTwo),
function(acc, element) { return acc + element; },
0,
[0, 1, 2, 3, 4, 5, 6, 7]);
https://github.com/cognitect-labs/transducers-js
Transducers
reduce(
map(powerOfTwo)(function(acc, element) { return acc +
element; }),
0,
[0, 1, 2, 3, 4, 5, 6, 7]);
Reduce as collection builder
var append = function(acc, element) {
acc.push(element);
return acc;
};
reduce(
append,
[],
[0, 1, 2, 3, 4, 5, 6, 7]);

=> [0, 1, 2, 3, 4, 5, 6, 7]
Transducers
transduce(
map(powerOfTwo),
append,
[],
[0, 1, 2, 3, 4, 5, 6, 7]);
=> [1, 2, 4, 8, 16, 32, 64, 128]
Transducers
var map = function(fn, coll) {
return transduce(
transducers.map(fn),
append,
[],
coll);
}
Transducers / map-into
var array = [];
array = transduce(map(powerOfTwo), append, array,
[0, 1, 2, 3]);
=> [ 1, 2, 4, 8 ]
array = transduce(map(powerOfTwo), append, array,
[4, 5, 6, 7]);
=> [1, 2, 4, 8, 16, 32, 64, 128]
Transducers
var put = function(object, pair) {
object[pair[1]] = pair[0];
return object;
};
transduce(
map(function(pair) { return [pair[1], pair[0]]; }),
put,
{},
{ hello: 'world', transduce: 'reduce', ecmascript: 6 });
=> { 6: 'ecmascript', world: 'hello', reduce: 'transduce' }
Transducers / into
into(
[],
map(powerOfTwo),
[0, 1, 2, 3, 4, 5, 6, 7]);
=> [1, 2, 4, 8, 16, 32, 64, 128]
into(
{},
map(swapKeysAndValues),
{ hello: 'world', transduce: 'reduce', ecmascript: 6 });
=> { 6: 'ecmascript', world: 'hello', reduce: 'transduce' }
Transducers
map(fn)
cat()
mapcat(fn)
filter(pred)
remove(pred)
take(number)
take-while(pred)
drop(number)
drop-while(pred)
take-nth(number)
distinct()
replace(object)
interpose(separator)
partition-by(fn)
partition-all(number)
map-indexed(fn)
keep(fn)
keep-indexed(fn)
dedupe()
Example
Select filenames that are not directories and which size is less than 5kb.
Extract lines that are longer than 80 chars from selected files.
Show distributions of line sizes.
Example
var fs = require(‘bluebird')
.promisifyAll(require('fs'));
var t = require('transducers-js');
var map = t.map,
filter = t.filter,
mapcat = t.mapcat;
var ta = require('transduce-async');
https://github.com/transduce/transduce-async
Select filenames that are not directories
and which size is less than 5kb
var filterFilenames = ta.compose(
map(function(fileName) {
return fs.statAsync(fileName).then(function(stat) {
return { size: stat.size, isDirectory: stat.isDirectory(),
fileName: fileName };
});
}),
filter(function(file) {
return !file.isDirectory && file.size < 5000;
}),
map(function(file) {
return file.fileName;
})
);
Extract lines that are longer than 80
chars from selected files
var extractLines = ta.compose(
map(function(fileName) {
return fs.readFileAsync(fileName, 'utf8');
}),
mapcat(function(contents) {
return contents.split("n");
}),
filter(function(line) {
return line.length > 80;
})
);
Show distributions of line sizes
var sizes = ta.compose(
filterFilenames,
extractLines,
map(function(line) { return line.length; }));
var putCounts = function(o, e) {
o[e] = o[e] || 0;
o[e]++;
return o;
}
ta.transduce(sizes, putCounts, {}, fs.readdirSync('.'))
.then(function(count) {
console.log(count);
});
Transducers
Just functions… and objects
The essence of map/filter/etc (expressed through step-functions)
Completely decoupled from inputs and outputs
Composable way to build algorithmic transformations
Go-like channels
var ch = chan();
go(function*() {
var val;
while((val = yield take(ch)) !== csp.CLOSED) {
console.log(val);
}
});
go(function*() {
yield put(ch, 1);
yield take(timeout(1000));
yield put(ch, 2);
ch.close();
});
… with transducers
var xform = comp(
map(function(x) {
return x * 2;
}),
filter(function(x) {
return x > 5;
}));
var ch = chan(1, xform);
go(function*() {
yield put(ch, 1);
yield put(ch, 2);
yield put(ch, 3);
yield put(ch, 4);
});
go(function*() {
while(!ch.closed) {
console.log(yield take(ch));
}
});
=> 6, 8
Issues
No support for async stuff by default. transduce-async does workarounds,
but something like `filter` cannot be converted to async from the outside. IE:
filter-async is needed.
No groupBy, sort, etc.
Thanks
@fxposter
github.com/fxposter
blog.fxposter.org
fxposter@gmail.com
https://www.youtube.com/watch?v=6mTbuzafcII
https://www.youtube.com/watch?v=4KqUvG8HPYo
http://clojure.com/blog/2012/05/08/reducers-a-library-and-model-for-
collection-processing.html
http://clojure.com/blog/2012/05/15/anatomy-of-reducer.html
http://blog.cognitect.com/blog/2014/8/6/transducers-are-coming
http://jlongster.com/Transducers.js--A-JavaScript-Library-for-
Transformation-of-Data
http://jlongster.com/Taming-the-Asynchronous-Beast-with-CSP-in-
JavaScript

Contenu connexe

Tendances

Logic Equations Resolver J Script
Logic Equations Resolver   J ScriptLogic Equations Resolver   J Script
Logic Equations Resolver J Script
Roman Agaev
 

Tendances (20)

RxJS Evolved
RxJS EvolvedRxJS Evolved
RxJS Evolved
 
Functional Patterns for the non-mathematician
Functional Patterns for the non-mathematicianFunctional Patterns for the non-mathematician
Functional Patterns for the non-mathematician
 
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)
 
RHadoop, R meets Hadoop
RHadoop, R meets HadoopRHadoop, R meets Hadoop
RHadoop, R meets Hadoop
 
Using Grafana with InfluxDB 2.0 and Flux Lang by Jacob Lisi
Using Grafana with InfluxDB 2.0 and Flux Lang by Jacob LisiUsing Grafana with InfluxDB 2.0 and Flux Lang by Jacob Lisi
Using Grafana with InfluxDB 2.0 and Flux Lang by Jacob Lisi
 
Stack queue
Stack queueStack queue
Stack queue
 
Mysql
MysqlMysql
Mysql
 
Mysql
MysqlMysql
Mysql
 
05 pig user defined functions (udfs)
05 pig user defined functions (udfs)05 pig user defined functions (udfs)
05 pig user defined functions (udfs)
 
The Ring programming language version 1.3 book - Part 25 of 88
The Ring programming language version 1.3 book - Part 25 of 88The Ring programming language version 1.3 book - Part 25 of 88
The Ring programming language version 1.3 book - Part 25 of 88
 
Logic Equations Resolver J Script
Logic Equations Resolver   J ScriptLogic Equations Resolver   J Script
Logic Equations Resolver J Script
 
Stack, queue and hashing
Stack, queue and hashingStack, queue and hashing
Stack, queue and hashing
 
ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Flux and InfluxDB 2.0
Flux and InfluxDB 2.0Flux and InfluxDB 2.0
Flux and InfluxDB 2.0
 
The Ring programming language version 1.9 book - Part 43 of 210
The Ring programming language version 1.9 book - Part 43 of 210The Ring programming language version 1.9 book - Part 43 of 210
The Ring programming language version 1.9 book - Part 43 of 210
 
Optimizing the Grafana Platform for Flux
Optimizing the Grafana Platform for FluxOptimizing the Grafana Platform for Flux
Optimizing the Grafana Platform for Flux
 
Flux and InfluxDB 2.0 by Paul Dix
Flux and InfluxDB 2.0 by Paul DixFlux and InfluxDB 2.0 by Paul Dix
Flux and InfluxDB 2.0 by Paul Dix
 
삼성 바다 앱개발 실패 노하우 2부
삼성 바다 앱개발 실패 노하우 2부삼성 바다 앱개발 실패 노하우 2부
삼성 바다 앱개발 실패 노하우 2부
 
decision tree regression
decision tree regressiondecision tree regression
decision tree regression
 

Similaire à Transducers 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
 

Similaire à Transducers in JavaScript (20)

Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
Javascript
JavascriptJavascript
Javascript
 
Spark_Documentation_Template1
Spark_Documentation_Template1Spark_Documentation_Template1
Spark_Documentation_Template1
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
8558537werr.pptx
8558537werr.pptx8558537werr.pptx
8558537werr.pptx
 
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
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheet
 
Data-Oriented Programming with Clojure and Jackdaw (Charles Reese, Funding Ci...
Data-Oriented Programming with Clojure and Jackdaw (Charles Reese, Funding Ci...Data-Oriented Programming with Clojure and Jackdaw (Charles Reese, Funding Ci...
Data-Oriented Programming with Clojure and Jackdaw (Charles Reese, Funding Ci...
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
The secrets of inverse brogramming
The secrets of inverse brogrammingThe secrets of inverse brogramming
The secrets of inverse brogramming
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
Eta
EtaEta
Eta
 
Monadologie
MonadologieMonadologie
Monadologie
 
Seminar PSU 10.10.2014 mme
Seminar PSU 10.10.2014 mmeSeminar PSU 10.10.2014 mme
Seminar PSU 10.10.2014 mme
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Declare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term RewritingDeclare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term Rewriting
 
Full Stack Clojure
Full Stack ClojureFull Stack Clojure
Full Stack Clojure
 

Dernier

notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
MsecMca
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
dollysharma2066
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
amitlee9823
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 

Dernier (20)

(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 

Transducers in JavaScript