Home Web Front-end JS Tutorial Transducer: A powerful function composition pattern

Transducer: A powerful function composition pattern

Jan 13, 2025 pm 02:28 PM

Transducer: A powerful function composition pattern

alias:: Transducer: A powerful function composition pattern
notebook:: Transducer: 一种强大的函数组合模式

map & filter

The semantics of map is "mapping," which means performing a transformation on all elements in a set once.

  const list = [1, 2, 3, 4, 5]

  list.map(x => x + 1)
  // [ 2, 3, 4, 5, 6 ]
Copy after login
Copy after login
Copy after login
  function map(f, xs) {
    const ret = []
    for (let i = 0; i < xs.length; i++) {
      ret.push(f(xs[i]))
    }
    return ret
  }
Copy after login
Copy after login
Copy after login
  map(x => x + 1, [1, 2, 3, 4, 5])
  // [ 2, 3, 4, 5, 6 ]
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

The above intentionally uses a for statement to clearly express that the implementation of map relies on the collection type.
Sequential execution;
Immediate evaluation, not lazy.
Let's look at filter:

  function filter(f, xs) {
    const ret = []
    for (let i = 0; i < xs.length; i++) {
      if (f(xs[i])) {
        ret.push(xs[i])
      }
    }
    return ret
  }
Copy after login
Copy after login
Copy after login
  var range = n => [...Array(n).keys()]
Copy after login
Copy after login
  filter(x => x % 2 === 1, range(10))
  // [ 1, 3, 5, 7, 9 ]
Copy after login
Copy after login
Copy after login
Copy after login

Similarly, the implementation of filter also depends on the specific collection type, and the current implementation requires xs to be an array.
How can map support different data types? For example, Set , Map , and custom data types.
There is a conventional way: it relies on the interface (protocol) of the collection.
Different languages have different implementations, JS has relatively weak native support in this regard, but it is also feasible:
Iterate using Symbol.iterator .
Use Object#constractor to obtain the constructor.
So how do we abstractly support different data types in push ?
Imitating the ramdajs library, it can rely on the custom @@transducer/step function.

  function map(f, xs) {
    const ret = new xs.constructor()  // 1. construction
    for (const x of xs) { // 2. iteration
      ret['@@transducer/step'](f(x))  // 3. collection
    }
    return ret
  }
Copy after login
Copy after login
  Array.prototype['@@transducer/step'] = Array.prototype.push
  // [Function: push]
Copy after login
Copy after login
  map(x => x + 1, [1, 2, 3, 4, 5])
  // [ 2, 3, 4, 5, 6 ]
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
  Set.prototype['@@transducer/step'] = Set.prototype.add
  // [Function: add]
Copy after login
Copy after login
  map(x => x + 1, new Set([1, 2, 3, 4, 5]))
  // Set (5) {2, 3, 4, 5, 6}
Copy after login
Copy after login

By using this method, we can implement functions such as map , filter , etc., which are more axial.
The key is to delegate operations such as construction, iteration, and collection to specific collection classes, because only the collection itself knows how to complete these operations.

  function filter(f, xs) {
    const ret = new xs.constructor()
    for (const x of xs) {
      if (f(x)) {
        ret['@@transducer/step'](x)
      }
    }
    return ret
  }
Copy after login
Copy after login
  filter(x => x % 2 === 1, range(10))
  // [ 1, 3, 5, 7, 9 ]
Copy after login
Copy after login
Copy after login
Copy after login
  filter(x => x > 3, new Set(range(10)))
  // Set (6) {4, 5, 6, 7, 8, 9}
Copy after login
Copy after login

compose

There will be some issues when the above map and filter are used in combination.

  range(10)
    .map(x => x + 1)
    .filter(x => x % 2 === 1)
    .slice(0, 3)
  // [ 1, 3, 5 ]
Copy after login
Copy after login

Although only 5 elements are used, all elements in the collection will be traversed.
Each step will generate an intermediate collection object.
We use compose to implement this logic again

  function compose(...fns) {
    return fns.reduceRight((acc, fn) => x => fn(acc(x)), x => x)
  }
Copy after login
Copy after login

To support composition, we implement functions like map and filter in the form of curry .

  function curry(f) {
    return (...args) => data => f(...args, data)
  }
Copy after login
Copy after login
  var rmap = curry(map)
  var rfilter = curry(filter)

  function take(n, xs) {
    const ret = new xs.constructor()
    for (const x of xs) {
      if (n <= 0) {
        break
      }
      n--
      ret['@@transducer/step'](x)
    }
    return ret
  }
  var rtake = curry(take)
Copy after login
Copy after login
  take(3, range(10))
  // [ 0, 1, 2 ]
Copy after login
Copy after login
  take(4, new Set(range(10)))
  // Set (4) {0, 1, 2, 3}
Copy after login
Copy after login
  const takeFirst3Odd = compose(
    rtake(3),
    rfilter(x => x % 2 === 1),
    rmap(x => x + 1)
  )

  takeFirst3Odd(range(10))
  // [ 1, 3, 5 ]
Copy after login
Copy after login

So far, our implementation is clear and concise in expression but wasteful in runtime.

The shape of the function

Transformer

The map function in version curry is like this:

  const map = f => xs => ...
Copy after login
Copy after login

That is, map(x => ...) returns a single-parameter function.

  const list = [1, 2, 3, 4, 5]

  list.map(x => x + 1)
  // [ 2, 3, 4, 5, 6 ]
Copy after login
Copy after login
Copy after login

Functions with a single parameter can be easily composed.
Specifically, the input of these functions is "data", the output is the processed data, and the function is a data transformer (Transformer).

  function map(f, xs) {
    const ret = []
    for (let i = 0; i < xs.length; i++) {
      ret.push(f(xs[i]))
    }
    return ret
  }
Copy after login
Copy after login
Copy after login
  map(x => x + 1, [1, 2, 3, 4, 5])
  // [ 2, 3, 4, 5, 6 ]
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
  function filter(f, xs) {
    const ret = []
    for (let i = 0; i < xs.length; i++) {
      if (f(xs[i])) {
        ret.push(xs[i])
      }
    }
    return ret
  }
Copy after login
Copy after login
Copy after login

Transformer is a single-parameter function, convenient for function composition.

  var range = n => [...Array(n).keys()]
Copy after login
Copy after login

Reducer

A reducer is a two-parameter function that can be used to express more complex logic.

  filter(x => x % 2 === 1, range(10))
  // [ 1, 3, 5, 7, 9 ]
Copy after login
Copy after login
Copy after login
Copy after login

sum

  function map(f, xs) {
    const ret = new xs.constructor()  // 1. construction
    for (const x of xs) { // 2. iteration
      ret['@@transducer/step'](f(x))  // 3. collection
    }
    return ret
  }
Copy after login
Copy after login

map

  Array.prototype['@@transducer/step'] = Array.prototype.push
  // [Function: push]
Copy after login
Copy after login
  map(x => x + 1, [1, 2, 3, 4, 5])
  // [ 2, 3, 4, 5, 6 ]
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

filter

  Set.prototype['@@transducer/step'] = Set.prototype.add
  // [Function: add]
Copy after login
Copy after login

take

How to implement take ? This requires reduce to have functionality similar to break .

  map(x => x + 1, new Set([1, 2, 3, 4, 5]))
  // Set (5) {2, 3, 4, 5, 6}
Copy after login
Copy after login
  function filter(f, xs) {
    const ret = new xs.constructor()
    for (const x of xs) {
      if (f(x)) {
        ret['@@transducer/step'](x)
      }
    }
    return ret
  }
Copy after login
Copy after login
  filter(x => x % 2 === 1, range(10))
  // [ 1, 3, 5, 7, 9 ]
Copy after login
Copy after login
Copy after login
Copy after login

Transducer

Finally, we meet our protagonist
First re-examine the previous map implementation

  filter(x => x > 3, new Set(range(10)))
  // Set (6) {4, 5, 6, 7, 8, 9}
Copy after login
Copy after login

We need to find a way to separate the logic that depends on the array (Array) mentioned above and abstract it into a Reducer .

  range(10)
    .map(x => x + 1)
    .filter(x => x % 2 === 1)
    .slice(0, 3)
  // [ 1, 3, 5 ]
Copy after login
Copy after login

The construction disappeared, the iteration disappeared, and the collection of elements also disappeared.
Through a reducer , our map only contains the logic within its responsibilities.
Take another look at filter

  function compose(...fns) {
    return fns.reduceRight((acc, fn) => x => fn(acc(x)), x => x)
  }
Copy after login
Copy after login

Notice rfilter and the return type of rmap above:

  function curry(f) {
    return (...args) => data => f(...args, data)
  }
Copy after login
Copy after login

It is actually a Transfomer , with both parameters and return values being Reducer , it is Transducer .
Transformer is composable, so Transducer is also composable.

  var rmap = curry(map)
  var rfilter = curry(filter)

  function take(n, xs) {
    const ret = new xs.constructor()
    for (const x of xs) {
      if (n <= 0) {
        break
      }
      n--
      ret['@@transducer/step'](x)
    }
    return ret
  }
  var rtake = curry(take)
Copy after login
Copy after login

into & transduce

However, how to use transducer ?

  take(3, range(10))
  // [ 0, 1, 2 ]
Copy after login
Copy after login
  take(4, new Set(range(10)))
  // Set (4) {0, 1, 2, 3}
Copy after login
Copy after login

We need to implement iteration and collection using a reducer.

  const takeFirst3Odd = compose(
    rtake(3),
    rfilter(x => x % 2 === 1),
    rmap(x => x + 1)
  )

  takeFirst3Odd(range(10))
  // [ 1, 3, 5 ]
Copy after login
Copy after login

It can work now, and we also noticed that the iteration is "on-demand". Although there are 100 elements in the collection, only the first 10 elements were iterated.
Next, we will encapsulate the above logic into a function.

  const map = f => xs => ...
Copy after login
Copy after login
  type Transformer = (xs: T) => R
Copy after login

Flow

Fibonacci generator.

Suppose we have some kind of asynchronous data collection, such as an asynchronous infinite Fibonacci generator.

  data ->> map(...) ->> filter(...) ->> reduce(...) -> result
Copy after login
  function pipe(...fns) {
    return x => fns.reduce((ac, f) => f(ac), x)
  }
Copy after login
  const reduce = (f, init) => xs => xs.reduce(f, init)

  const f = pipe(
    rmap(x => x + 1),
    rfilter(x => x % 2 === 1),
    rtake(5),
    reduce((a, b) => a + b, 0)
  )

  f(range(100))
  // 25
Copy after login

We need to implement the into function that supports the above data structures.
Post the array version of the code next to it as a reference:

  type Transformer = (x: T) => T
Copy after login

Here is our implementation code:

  type Reducer = (ac: R, x: T) => R
Copy after login

The collection operation is the same, the iteration operation is different.

  // add is an reducer
  const add = (a, b) => a + b
  const sum = xs => xs.reduce(add, 0)

  sum(range(11))
  // 55
Copy after login

The same logic applies to different data structures.

Orders

You, who are attentive, may notice that the parameter order of the compose version based on curry and the version based on reducer are different.

curry version

  const list = [1, 2, 3, 4, 5]

  list.map(x => x + 1)
  // [ 2, 3, 4, 5, 6 ]
Copy after login
Copy after login
Copy after login
  function map(f, xs) {
    const ret = []
    for (let i = 0; i < xs.length; i++) {
      ret.push(f(xs[i]))
    }
    return ret
  }
Copy after login
Copy after login
Copy after login

The execution of the function is right-associative.

transducer version

  map(x => x + 1, [1, 2, 3, 4, 5])
  // [ 2, 3, 4, 5, 6 ]
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
  function filter(f, xs) {
    const ret = []
    for (let i = 0; i < xs.length; i++) {
      if (f(xs[i])) {
        ret.push(xs[i])
      }
    }
    return ret
  }
Copy after login
Copy after login
Copy after login

Reference

Transducers are Coming
Transducers - Clojure Reference

The above is the detailed content of Transducer: A powerful function composition pattern. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

See all articles