javascript - JavaScript 示例中 Function Monoids 的二元运算符是什么

标签 javascript functional-programming monoids

this article函数幺半群是通过 C# 代码和 Haskell 类型定义引入的。

A function a -> b is a monoid if b is a monoid. This means that you can combine two functions with the same type. In an object-oriented context, it means that you can combine two methods with the same signature into one method as long as the return type forms a monoid.

Generalisation

While the above C# code is only an example, the general rule is that any function that returns a monoid is itself a monoid. In Haskell, this rule is articulated in the standard library:

instance Monoid b => Monoid (a -> b)

This means that for any monoid b, a function a -> b is also (automatically) a monoid.

问题是 C# 中的示例对“GUID”过于具体,我不知道作者试图在代码中做什么,Haskell 类型定义仅仅是类型定义。

用 JavaScript 实现此函数幺半群的示例代码是什么?

比较) Why is instance Monoid b => Monoid (a -> b) in base?

最佳答案

Monoid Laws

identity law:
combine (identity, a) == combine (a, identity)

associativity law:
combine (a, combine (b, c)) == combine (combine (a, b), c)

我们可以为函数实现一个身份元素 (identity) 和二元运算 (combine) -

// identity element
const identity =
  x => x

// binary operation
const combine = (a, b) =>
  x => a (b (x))
 
// sample functions
const a =
  x => x + 3
  
const b =
  x => x - 1

const c =
  x => x * x

// uphold laws
console.log
  ( combine (identity, a) (2) === combine (a, identity) (2)
  , combine (a, combine (b, c)) (2) === combine (combine (a, b), c) (2)
  )
  
// => true
// => true

二元运算和标识元素因您的域而异。请参阅 Wikipedia 上的表格更深入地了解如何为各种集合实现标识元素和二元运算。

当然,您不仅限于这些域。您的自定义类型可能具有满足幺半群法则的各种二元运算和标识元素。如果遵守法律,则您的类型属于幺半群类别。

关于javascript - JavaScript 示例中 Function Monoids 的二元运算符是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55289369/

相关文章:

haskell - 折叠一个可折叠的 Maybe (Monoid),忽略 Haskell 中的缺失值

javascript - 为什么我们在 Angular 上将 Controller 变量设置为 "this"?

javascript - 记录客户端错误和 "Script error"

javascript - .js 文件后的 ?history=1 是什么意思?

javascript - 将PHP字符串传递给HTML href“属性撇号问题

class - Haskell 单体可折叠玫瑰树

haskell - 如何将 Pair 定义为 Monoid?

list - 从元组列表中删除反向重复项

javascript - 有哪些学习 JavaScript 和编程架构的好网站?

haskell - 用于交换函数参数的函数类型