简体   繁体   English

Ramda中的简单无点功能

[英]Simple Point-free functions in Ramda

I'm still learning Ramda and often have trouble converting seemingly simple lamda functions into point-free pure Ramda functions. 我仍在学习Ramda,经常遇到将看似简单的lamda函数转换为无点纯Ramda函数的麻烦。 Here is a simple example: 这是一个简单的示例:

export const consoleTap = arg =>
  R.compose(
    R.tap,
    R.curryN(2, console[arg])
  );

export const errorTap = consoleTap("error");
export const logTap = consoleTap("log");

// example usage
R.map(logTap("Value"))([1, 2]) // Results in printing "Value 1" "Value 2"

The functions work fine and I've even written tests for them. 这些功能运行良好,我什至为它们编写了测试。 I just get the feeling consoleTap could be written point-free, and there's just something I'm not seeing or understanding correctly. 我只是觉得consoleTap可以写成没有意义的东西,只是有些我没有正确看到或理解。 Can the function be rewritten? 可以重写功能吗?

I couldn't come up with a point-free version that didn't look overly complicated. 我无法提出一种看上去不太复杂的无点版本。 I think what you have is pretty good already. 我认为您所拥有的已经很不错了。

The only suggestion I'd make, would be to split things up: separate logging from tap . 我唯一提出的建议是将事情分解:将记录与tap分开。 You could reuse your "prefixed" version of logging on its own: 您可以自己重用日志的“前缀”版本:

const logWith = (method, prefix) => curryN(2, console[method])(prefix);
const log = logWith('log', 'INFO: ');
const error = logWith('error', 'ERR: ');
log(10); // INFO: 10
error(10); // ERR: 10

and with tap : tap

const logTap = tap(logWith('error', 'ERR: '));
logTap(10);
// ERR: 10
// => 10

The issue you are having is due to R.tap not being variadic. 您遇到的问题是由于R.tap不可变。

 // tap is a unary function const log = R.tap(console.log); // logs only `1` log(1, 2, 3, 4); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js" integrity="sha256-xB25ljGZ7K2VXnq087unEnoVhvTosWWtqXB4tAtZmHU=" crossorigin="anonymous"></script> 

So you cannot do log('Value is, 1) , a workaround could be grouping the arguments for tap with R.unapply and then applying them back to the logger via R.apply 因此,您无法执行log('Value is, 1) ,一种解决方法是将tap参数与R.unapply分组,然后通过R.apply将其应用回记录器


A simple solution could be calling R.tap after providing the prefix to the logger: 一个简单的解决方案是在为记录器提供前缀后调用R.tap

 const logger = R.pipe( R.prop(R.__, console), R.curryN(2), ); const error = logger('error'); const log = logger('log'); const result = R.map( R.tap(log('value is')), )([1, 2]); // tap didn't alter any item inside the functor. console.log('result is', result) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js" integrity="sha256-xB25ljGZ7K2VXnq087unEnoVhvTosWWtqXB4tAtZmHU=" crossorigin="anonymous"></script> 


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

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