简体   繁体   English

避免 rambda 中的参数重复

[英]Avoid argument duplication in 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);
}

is there any way to avoid filePath argument duplication in manipulateFile ?有没有什么办法,以避免filePath中的说法重复manipulateFile

Ideally I would like to pipe it like this.理想情况下,我想像这样管它。 But filePath will be not provided to writeFile但是filePath不会提供给writeFile

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

You can use the chain combinator to pass the same argument to multiple nested function calls.您可以使用chain组合器将相同的参数传递给多个嵌套函数调用。

Here is an excerpt from common combinators in JavaScript :以下是JavaScript 中常见组合器的摘录:

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

[...] [...]

Name名称 # # Haskell哈斯克尔 Ramda拉姆达 Sanctuary避难所 Signature签名
chain S_ S_ (=<<) chain chain (a → b → c) → (b → a) → b → c

To make it more obvious how it is relevant here, consider this - your manipulateFile can be re-written as:为了更明显地说明它在这里的相关性,请考虑这一点 - 您的manipulateFile可以重写为:

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

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

Which matches exactly with the S_ body and can thus be represented as S_(f)(g)(x) .它与S_ body 完全匹配,因此可以表示为S_(f)(g)(x)

Using the Rambda chain you can use:使用Rambda chain您可以使用:

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);
}

or reduce it to point-free:或将其减少到无点:

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

It seems that the Rambda chain does not work the same way as Ramda does. Rambda chain工作方式似乎与 Ramda不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM