在this article函数幺半群是通过 C# 代码和 Haskell 类型定义引入的。
A function
a -> b
is a monoid ifb
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 functiona -> b
is also (automatically) a monoid.
问题是 C# 中的示例对“GUID”过于具体,我不知道作者试图在代码中做什么,Haskell 类型定义仅仅是类型定义。
用 JavaScript 实现此函数幺半群的示例代码是什么?
最佳答案
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/