[英]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.