📕
Dan Fitz's Notes
  • README
  • Ai
    • Supervised Machine Learning
      • Introduction To Machine Learning
      • Regression With Multiple Input Variables
      • Classification
  • Csharp
    • C Sharp Advanced
      • Generics
      • Delegates
      • Lambda Expressions
      • Events
    • C Sharp Fundamentals
      • Intro To C
      • Primitive Types And Expressions
      • Non Primitive Types
      • Control Flow
      • Arrays And Lists
      • Working With Dates
      • Working With Text
      • Working With Files
      • Debugging Applications
    • C Sharp Intermediate
      • Classes
      • Association Between Classes
      • Inheritance
      • Polymorphism
      • Interfaces
  • Java
    • Inheritance Data Structures Java
      • Inheritance Polymorphism Using Overriding And Access Modifiers
      • Abstract Classes And Debugging
      • File I O And Exceptions
      • Collections Maps And Regular Expressions
    • Intro To Java
      • Introduction To Java Classes And Eclipse
      • Unit Testing Arrays And Array Lists
      • Static Variables Methods And Polymorphism Using Overloading
  • Javascript
    • Algorithms Data Structures
      • Big O Notation
      • Analyzing Performance Of Arrays And Objects
      • Problem Solving Approach
      • Problem Solving Patterns
      • Recursion
      • Searching Algorithms
      • Bubble Selection And Insertion Sort
      • Merge Sort
      • Quick Sort
      • Radix Sort
      • Data Structures Introduction
      • Singly Linked Lists
      • Doubly Linked Lists
      • Stacks And Queues
      • Binary Search Trees
      • Tree Traversal
      • Binary Heaps
    • Complete Nodejs
      • Understanding Node.js
      • REST AP Is And Mongoose
      • API Authentication And Security
      • Node.js Module System
      • File System And Command Line Args
      • Debugging Node.js
      • Asynchronous Node.js
      • Web Servers
      • Accessing API From Browser
      • Application Deployment
      • Mongo DB And Promises
    • Complete React Native
      • Working With Content
      • Building Lists
      • Navigating Users Between Screens
      • State Management
      • Handling Screen Layout
      • Setting Up An App
      • More On Navigation
      • Advanced Statement Management With Context
      • Building A Custom Express API
      • In App Authentication
    • Epic React
      • React Fundamentals
      • React Hooks
      • Advanced React Hooks
      • Advanced React Patterns
      • React Performance
    • Fireship Firestore
      • Firestore Queries And Data Modeling Course
      • Model Relational Data In Firestore No SQL
    • Functional Light Javascript
      • Intro
      • Function Purity
      • Argument Adapters
      • Point Free
      • Closure
      • Composition
      • Immutability
      • Recursion
      • List Operations
      • Transduction
      • Data Structure Operations
      • Async
    • Js Weird Parts
      • Execution Contexts And Lexical Environments
      • Types And Operators
      • Objects And Functions
      • Object Oriented Java Script And Prototypal Inheritance
      • Defining Objects
    • Mastering Chrome Dev Tools
      • Introduction
      • Editing
      • Debugging
      • Networking
      • Auditing
      • Node.js Profiling
      • Performance Monitoring
      • Image Performance
      • Memory
    • React Complete Guide
      • What Is React
      • React Basics
      • Rendering Lists And Conditionals
      • Styling React Components
      • Debugging React Apps
      • Component Deep Dive
      • Building A React App
      • Reaching Out To The Web
      • Routing
    • React Testing
      • Intro To Jest Enzyme And TDD
      • Basic Testing
      • Redux Testing
      • Redux Thunk Testing
    • Serverless Bootcamp
      • Introduction
      • Auction Service Setup
      • Auction Service CRUD Operations
      • Auction Service Processing Auctions
    • Testing Javascript
      • Fundamentals Of Testing
      • Static Analysis Testing
      • Mocking Fundamentals
      • Configuring Jest
      • Test React Components With Jest And React Testing Library
    • Typescript Developers Guide
      • Getting Started With Type Script
      • What Is A Type System
      • Type Annotations In Action
      • Annotations With Functions And Objects
      • Mastering Typed Arrays
      • Tuples In Type Script
      • The All Important Interface
      • Building Functionality With Classes
    • Web Performance With Webpack
      • Intro
      • Code Splitting
      • Module Methods Magic Comments
  • Other
    • Algo Expert
      • Defining Data Structures And Complexity Analysis
      • Memory
      • Big O Notation
      • Logarithm
      • Arrays
      • Linked Lists
      • Hash Tables
      • Stacks And Queues
      • Strings
      • Graphs
      • Trees
    • Aws Solutions Architect
      • AWS Fundamentals IAM EC 2
    • Fundamentals Math
      • Numbers And Negative Numbers
      • Factors And Multiples
      • Fractions
    • Mysql Bootcamp
      • Overview And Installation
      • Creating Databases And Tables
      • Inserting Data
      • CRUD Commands
      • The World Of String Functions
      • Refining Our Selections
      • The Magic Of Aggregate Functions
    • Random Notes
      • Understanding React Hooks
  • Python
    • Data Analysis Using Python
      • Loading Querying And Filtering Data Using The Csv Module
      • Loading Querying Joining And Filtering Data Using Pandas
      • Summarizing And Visualizing Data
    • Intro To Python
      • Course Introduction Intro To Programming And The Python Language Variables Conditionals Jupyter Notebook And IDLE
      • Intro To Lists Loops And Functions
      • More With Lists Strings Tuples Sets And Py Charm
      • Dictionaries And Files
Powered by GitBook
On this page
  • Deriving Transduction
  • Extracting reduce
  • Combiner and currying
  • Single reduce
  • Composing transducers
  • Simplifying reducer inputs
  1. Javascript
  2. Functional Light Javascript

Transduction

Fusion only works if our data operations are all the same—all maps, all filters, or all reduces.

The trouble with combining any of these operations is that they have incompatible shapes:

  • Mapper takes an item and returns another item

  • Filter takes an item and returns a boolean

  • Reducer takes 2 items and returns an accumulator

nums.map(multiply2).filter(isEven).reduce(sumUp);

If we want to compose these operations together, this is known as transduction.

High-level, transduction works by reshaping the functions into compatible shapes that can be composed together. Specifically, it reshapes them all into reducers because transduction is composition of reducers.

Here's how a functional programming library would perform transduction:

const transducer = compose(filterReducer(isEven), mapReducer(multiply2));

Note how we don't pass the reducer sumUp. That's because a transducer is a special type of reducer that only becomes a regular reducer when you pass it a reducer as an argument. It's a higher-order reducer.

To do this, you use the utility function transduce and pass in the following:

  • Transducer

  • Combinator/reducer

  • Initial value

  • Data structure

transduce(transducer, sumUp, 0, nums);

Alternatively, we can use into, which looks at the data type of the initial value and uses a default combinator.

into(transducer, 0, nums);
  • Numbers use an addition combinator

  • Strings use a string concatenation combinator

  • Arrays use a push combinator

Note: If the default combinators don't fit your use case, you want to use transduce.

Deriving Transduction

Topics:

  • Modeling mappers and filters as reducers

Extracting reduce

How do you model a mapper and a filter as a reducer?

Let's look at the manual implementation using the array methods:

function mapWithReduce(arr, mapper) {
  return arr.reduce(function reducer(list, v) {
    list.push(mapper(v));
    return list;
  }, []);
}

function filterWithReduce(arr, predicate) {
  return arr.reduce(function reducer(list, v) {
    if (predicate(v)) list.push(v);
    return list;
  }, []);
}

let list = [1, 2, 3];
list = mapWithReduce(list, multiply2);
list = filterWithReduce(list, isEven);
list.reduce(sumUp);

Instead of performing the reductions, let's now refactor mapWithReduce and filterWithReduce into functions that return the reducer itself.

function mapReducer(mapper) {
  return function reducer(list, v) {
    list.push(mapper(v)); // hard-coded via closure
    return list;
  };
}

function filterReducer(predicate) {
  return function reducer(list, v) {
    if (predicate(v)) list.push(v); // hard-coded via closure
    return list;
  };
}

let list = [1, 2, 3];
list
  .reduce(mapReducer(multiply2), [])
  .reduce(filterReducer(isEven), [])
  .reduce(sumUp);

Combiner and currying

In both reducers returned by mapReducer and filterReducer, there is a generic action happening: given list and v, these values are combined to return a new list.

We are going to create a generic combiner to and apply them to our specialized ones.

function listCombine(list, v) {
  list.push(v);
  return list;
}

function mapReducer(mapper) {
  return function reducer(list, v) {
    return listCombine(list, mapper(v));
  };
}

function filterReducer(predicate) {
  return function reducer(list, v) {
    if (predicate(v)) return listCombine(list, v);
    return list;
  };
}

let list = [1, 2, 3];
list
  .reduce(mapReducer(multiply2), [])
  .reduce(filterReducer(isEven), [])
  .reduce(sumUp);

We can take this a step further and make mapReducer and filterReducer into higher-order reducers—i.e. transducers—by

  • Moving the combiner to a parameter, and

  • Currying the inputs.

const mapReducer = curry(2, function mapReducer(mapper, combiner) {
  return function reducer(list, v) {
    return combiner(list, mapper(v));
  };
});

const filterReducer = curry(2, function filterReducer(predicate, combiner) {
  return function reducer(list, v) {
    if (predicate(v)) return combiner(list, v);
    return list;
  };
});

That way when we pass the mapper or the predicate into either mapReducer or filterReducer (respectively), we get back a higher-order reducer that accepts a reducer in order to become a reducer.

const mapTransducer = mapReducer(multiply2);
const filterTransducer = filterReducer(isEven);

let list = [1, 2, 3];
list
  .reduce(mapTransducer(listCombine), [])
  .reduce(filterTransducer(listCombine), [])
  .reduce(sumUp);

Single reduce

Composing transducers

If you notice, mapTransducer and filterTransducer now have the same shape: they both accept a reducer as an input and return a reducer as output. That means you can compose them!

const transducer = compose(mapReducer(multiply2), filterReducer(isEven));

let list = [1, 2, 3];
list.reduce(transducer(listCombine), []).reduce(sumUp);

Effectively, what's happening is

  1. listCombine gets passed as input to filterReducer(isEven), generating a filter reducer

  2. That filter reducer gets passed as an input to mapReducer(multiply2), generating a map + filter reducer

    • In other words, the filter reducer becomes the combiner argument in mapReducer

    • So, combiner(list, mapper(v)) takes a mapped value and then filters it

Simplifying reducer inputs

Finally, now we have 2 reducers left. But how do we simplify it to just 1 reducer? Simple: just pass sumUp directly as the reducer. Why bother using the intermediary reducer listCombiner at all?

const transducer = compose(mapReducer(multiply2), filterReducer(isEven));

let list = [1, 2, 3];
list.reduce(transducer(sumUp), 0);
PreviousList OperationsNextData Structure Operations

Last updated 3 years ago