Haskell Lesson:一些数学知识

时间:2023-01-31 17:02:42

补充一些数学知识

一、幺半群(monoids)

1.1 定义

一种元素构成幺半群只需满足两个条件:

  • 能找到一个满足结合律的二元操作符,称之为(*),使得表达式
    a * (b * c) = (a * b) * c

  • 存在一个单位元素,称为e,满足群的任意元素有:a * e = a且e * a = a

操作*和单位元e以及所有满足这两个条件的元素构成了幺半群。

1.2 举例一:

* = * (乘法符号)
e = 1

那么所有整数和*/1即构成了一个幺半群{'*', 1, Z}。

1.3 举例二

* = +(加法符号)
e = 0

同样的所有整数和+/0也构成了幺半群{'+', 0, Z}

二、函子(functor)

In mathematics, a functor is a type of mapping between categories arising in category theory.

Functor Wiki中对Functor是这样解释的,涉及到范畴论的概念,对应到haskell中的Functor类型类,定义如下:

class Functor f where
   fmap :: (a -> b) -> f a -> f b

f是带参类型。譬如定义一棵二叉树如下:

data Tree a = Node (Tree a) (Tree a)
           | Leaf a

声明其为Functor实例。

instance Functor Tree where
   fmap = treeMap

一句话概括就是所有可以map的类型即构成了Functor。

三、单子(monad)

Monad Wiki 定义如下: In functional programming, a monad is a design pattern that defines how functions, actions, inputs, and outputs can be used together to build generic types,[1] with the following organization:

Define a data type, and how values of that data type are combined.
Create functions that use the data type, and compose them together into actions, following the rules defined in the first step.

简单理解就是一种提供串联操作的类型类。

class Monad m where
   -- chain
   (>>=)  :: m a -> (a -> m b) -> m b
   -- inject
   return :: a -> m a