简体   繁体   中英

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. 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. 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 . 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 :

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

The issue you are having is due to R.tap not being variadic.

 // 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


A simple solution could be calling R.tap after providing the prefix to the logger:

 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> 


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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