SlideShare ist ein Scribd-Unternehmen logo
1 von 45
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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

Was ist angesagt? (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Dr.Costas Sachpazis
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
rknatarajan
 

Kürzlich hochgeladen (20)

Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.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 Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICSUNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
 
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...
 
Vivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design SpainVivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design Spain
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
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
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
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
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 

Transducers in JavaScript