【问题标题】:Simple Point-free functions in RamdaRamda 中的简单无点函数
【发布时间】:2019-08-13 02:18:53
【问题描述】:

我还在学习 Ramda,经常无法将看似简单的 lamda 函数转换为无点纯 Ramda 函数。这是一个简单的例子:

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"

这些函数运行良好,我什至为它们编写了测试。我只是觉得consoleTap 可以写成无意义的,只是有些东西我没有正确看到或理解。函数可以改写吗?

【问题讨论】:

    标签: javascript ramda.js


    【解决方案1】:

    我想不出一个看起来不太复杂的无点版本。我觉得你的已经很不错了。

    我提出的唯一建议是将事情分开:将日志记录与tap 分开。您可以自己重用您的“前缀”版本的日志记录:

    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
    

    tap:

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

    【讨论】:

      【解决方案2】:

      您遇到的问题是由于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>

      所以你不能这样做log('Value is, 1),一种解决方法可以是使用R.unapply 将tap 的参数分组,然后通过R.apply 将它们应用回记录器


      一个简单的解决方案是在向记录器提供前缀后调用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>

      【讨论】:

        猜你喜欢
        • 2017-10-07
        • 2017-01-24
        • 2016-07-11
        • 2017-02-22
        • 2018-11-12
        • 2020-07-22
        • 1970-01-01
        • 2018-06-23
        • 2018-03-13
        相关资源
        最近更新 更多