gpt4 book ai didi

javascript - 了解幻想世界 `ap`

转载 作者:行者123 更新时间:2023-12-03 01:41:08 28 4
gpt4 key购买 nike

我试图了解ap,但遇到了麻烦。

fantasyland ,詹姆斯·福布斯 说:

First we teach a function how to interact with our type, by storing that function in a container just like any other value. ( Functions are values too ya know! )

var square = Type.of(
a => a * a
)

//=> Type (number -> number)

Then we can apply that contained function to a contained value.

square.ap( Type.of(3) )

//=> Type(9)

ap calls map on a received type, with itself as the transform function.

function ap(type){
// recall our value
// is a function
// Type ( a -> a )
var transformer = this.__value

return type.map(transformer)
}

所以这看起来像 ap 仅当我们容器中的值是一个函数时才有效。这对我来说已经感觉很奇怪,因为我认为 The Perfect API 的全部意义在于这些函数每次都适用于所有事情。

我还想注意一下 square.ap(Type.of(3) ) 行,在我看来 ap 接受任何仿函数 ( map 的实现者)。

现在,如果我跳到 javascript fantasy-land spec ,我假设它基于 James Forbes 链接,ap 签名 (a.ap(b)) 的 1.i 定义指出

If b does not represent a function, the behaviour of ap is unspecified.

听起来这个规范期望 ap 采用与 The Perfect API 不同的函数。

总之,我想我不了解 ap 的规范或实现它的样子。当我尝试用谷歌搜索这个时,似乎大多数人只想谈论map,这对我来说已经很容易理解了。

最佳答案

FantasyLand 规范比 James Forbes 的文章早三年,由 Brian McKenna 创建,因此看起来 James Forbes 的文章是基于该规范的,而不是相反。

要回答您的问题,ab 必须都是同一类型的“容器”。如果a是Maybe,那么b也一定是Maybe。如果 a 是一个任务,那么 b 也必须是一个任务。

这在 FantasyLand 规范中有所说明:

b must be same Apply as a.

此外,其中之一必须包含一个函数作为其内部值。哪一个需要包含函数取决于 API。在 FantasyLand 规范中,b 将包含以下函数:

b must be an Apply of a function

在詹姆斯·福布斯的文章中,情况恰恰相反。我怀疑这是因为他的文章是围绕 Ramda 展开的,Ramda 的参数顺序与您在 JavaScript 中其他地方通常看到的顺序相反。

无论如何,ap的结果都是与ab具有相同容器类型的值:

The Apply returned by ap must be the same as a and b

结果包含将包含的函数应用于另一个包含的值的结果。

因此,如果a是某个值T[x]并且b是某个值T[f],那么a.ap(b) 将是 T[f(x)]

希望这是有道理的。

关于javascript - 了解幻想世界 `ap`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50841094/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com