pig*_*ker 19
列表形成一个幺半群结构,具有关联二元运算++
和中性元素[]
.也就是说,我们有
[] ++ xs = xs = xs ++ [] (xs ++ ys) ++ zs = xs ++ (ys ++ zs)
Run Code Online (Sandbox Code Playgroud)
同时,数字有很多幺半群结构,但这里的相关结构是操作的位置*
和中性元素1
.
1 * x = x = x * 1 (x * y) * z = x * (y * z)
Run Code Online (Sandbox Code Playgroud)
该product
函数不仅是从数字列表到数字的映射:它是一个单形同态,反映了数字幺半群中的列表幺半群结构.最重要的是,
product (xs ++ ys) = product xs * product ys
Run Code Online (Sandbox Code Playgroud)
和
product [] = 1
Run Code Online (Sandbox Code Playgroud)
事实上,为了获得前者,我们几乎将后者强加给我们.
因为这是乘法类别中的身份.
更实际:
product [1,2,3] == 1 * product 2:3:[]
== 1 * 2 * product 3:[]
== 1 * 2 * 3 * product []
Run Code Online (Sandbox Code Playgroud)
这反过来允许您通过简单的递归实现它:
product [] = 1
product (x:xs) = x * product xs
Run Code Online (Sandbox Code Playgroud)