javascript - Tap 的函数签名(K 组合器)

标签 javascript functional-programming function-signature k-combinator

我在一本书上看到tap函数(也叫K-Combinator)的函数签名如下:

tap :: (a -> *) -> a -> a

"This function takes an input object a and a function that performs some action on a. It runs the given function with the supplied object and then returns the object."

  1. 谁能帮我解释一下函数签名中的星号 (*) 是什么意思?
  2. 以下实现是否正确?
  3. 如果三种实现方式都正确,应该在什么时候使用哪一种?有什么例子吗?

实现1:

const tap = fn => a => { fn(a); return a; };

tap((it) => console.log(it))(10); //10

实现2:

const tap = a => fn => { fn(a); return a; }; 

tap(10)((it) => console.log(it)); //10

实现3:

const tap = (a, fn) => {fn(a); return a; };

tap(10, (it) => console.log(it)); //10

最佳答案

这看起来很像 Ramda definition .里面的*应该是错误的。 (免责声明:我是 Ramda 的作者之一。)它可能应该是

// tap :: (a -> b) -> a -> a

类似于您的第一个实现:

const tap = fn => a => { fn(a); return a; };

或者 Ramda 的版本:

const tap = curry((fn, a) => { fn(a); return a; });

匹配该签名并且恕我直言,主要在调试上下文中很有用。我用它临时将日志记录语句引入功能管道1:

// :: Map String User
const users = fetchUsersFromSomewhere();

// :: [Comment] -> [Number]  
const userRatingForComments = R.pipe(
    R.pluck('username'),     // [Comment] -> [String]
    R.tap(console.log),      // for debugging, need to include `bind` in browser envs
//  ^^^^^^^^^^^^^^^^^^      
    R.map(R.propOf(users)),  // [String] -> [User]
    R.pluck('rating')        // [User] -> [Number]
);

不过,这实际上不是 K 组合器。


1 此代码示例来自 old article我在 Ramda 上的。

关于javascript - Tap 的函数签名(K 组合器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38614679/

相关文章:

javascript - 在javascript中将各种日期格式转换为yyyy-mm-dd

javascript - jquery - 如何确定一个 div 是否改变了它的高度或任何 css 属性?

javascript - 如何在 JavaScript ES6 中功能性地遍历矩阵?

c++ - 根据参数返回指向具有不同签名的函数的指针

c++ - 自动用指向部分专用函数成员的指针填充 vector

javascript - AWS 从客户端上传文件到 S3

javascript - 为什么 Node.js 会查找错误作为回调中的第一个参数

recursion - 不在尾部位置重复

Haskell monad流理解

c++ - 为什么名称修改没有破坏我的程序?