首页 > 解决方案 > 避免在 rambda 中重复参数

问题描述

import { pipe } from 'rambda';
function readFile(filePath) { // reading the file return fileContents }
function editFile(fileContents) { // edit the file return newFileContents }
function writeFile(fileContents, filePath) { // write content  }

function manipulateFile(filePath) {
  return writeFile(pipe(readFile, editFile)(filePath))(filePath);
}

有什么方法可以避免filePath参数重复manipulateFile

理想情况下,我想像这样管道它。但filePath不会提供给writeFile

function manipulateFile(filePath) {
  return pipe(
    readFile,
    editFile,
    writeFile
  )(filePath)
}

标签: javascriptrambda.js

解决方案


您可以使用chain组合器将相同的参数传递给多个嵌套函数调用。

以下是JavaScript 中常见组合子的摘录:

const S_ = f => g => x => f (g (x)) (x)

[...]

姓名 # 哈斯克尔 拉姆达 避难所 签名
S_ (=<<) chain chain (a → b → c) → (b → a) → b → c

为了使其在这里的相关性更加明显,请考虑这一点-您manipulateFile可以将其重写为:

function manipulateFile(filePath) {
  const f = writeFile;
  const g = pipe(readFile, editFile);
  const x = filePath;

  return f (g (x)) (x);
}

它与主体完全匹配,S_因此可以表示为S_(f)(g)(x)

使用Rambdachain,您可以使用:

import { pipe, chain } from 'ramda';
function readFile(filePath) { // reading the file return fileContents }
function editFile(fileContents) { // edit the file return newFileContents }
function writeFile(fileContents, filePath) { // write content  }

function manipulateFile(filePath) {
  return chain(writeFile, pipe(readFile, editFile))(filePath);
}

或将其减少为无点:

const manipulateFile = chain(writeFile, pipe(readFile, editFile));

似乎Rambdachain的工作方式与 Ramda 不同。


推荐阅读