JavaScript 中的 Monad?
使用 Monad 的 JavaScript 代码示例会是什么样子?我这样问是因为如果我能看到代码示例,理解 Monad 就会更清楚(JavaScript 是一种简单的函数式语言,它可能是学习它的最佳语言)。
How would an example JavaScript code look like that uses Monad? I'm asking because understanding Monad is much clearer if I can see a code example (and JavaScript being a simple, functional language it could be the best language to use to learn it).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我首先会用 JavaScript 编写您自己的 monad。列表 monad 是一个很好的起点;我发现它是迄今为止最有用的。只需定义执行以下操作的函数:
mreturn
)。mzero
)。mplus
)。map
)。join
),将列表列表“展平”为简单列表。这定义了所谓的“加法单子”(
mzero
和mplus
构成“加法”部分)。尝试一下,仅使用这些函数对列表进行操作可以做哪些有趣的事情。例如,您可以计算学生乘法表上所有偶数的列表,如下所示:或者,将
map
和join
组合在一起作为定义为的单个函数函数绑定(l,f){返回join(map(l,f))}
。bind
可以用来代替map
和join
,并且在例如 Haskell 中使用得更频繁。然后可以编写与上面相同的练习:最后,您可能希望将这些函数合并为新列表原型的一部分(或者当今任何 JavaScript 所具有的类),因此您可以编写 jQuery 式的:
I would start by writing your own monad in JavaScript. The list monad is a great place to start; I find it by far the most useful. Simply define functions which do the following:
mreturn
).mzero
).mplus
).map
).join
).This defines what's known as an "additive monad" (
mzero
andmplus
form the "additive" part). Play around to see what interesting things you can do using only these functions to operate on lists. For example, you can compute the list of all even numbers on a schoolkid's multiplication table like so:Alternatively, combine
map
andjoin
together as a single function defined asfunction bind(l, f) { return join(map(l, f)) }
.bind
can be used instead ofmap
andjoin
and is used more often in e.g. Haskell. The same exercise above can then be written:Finally, you may want to incorporate these functions as part of a new list prototype (or whatever JavaScript has that passes for classes these days), so you can instead write the jQuery-esque: