2018-11-16 Xie Jingyi
新类型有自己的 data constructor (literals 可以看成特殊的 data constructor),由这一点来区分是否创建了新类型。 data 创建了新类型,可以有多个 data constructor。 newtype 创建了新类型,只能有一个 data constructor,同时新类型的内存布局与原来的类型相同。 type 没有创建新类型,只是建立了 alias,没有新的 data constructor。 type 常用于语义化类型,是业务逻辑层的概念。 ```haskell type ID = Int a = 1 :: ID b = a + 2 -- legal showID :: ID - 继续阅读 »
2018-11-10 Xie Jingyi
Prelude.foldl foldl 为 left-associative folding。 haskell foldl :: (b -> a -> b) -> b -> [a] -> b foldl f acc [] = acc foldl f acc (x:xs) = foldl f (f acc x) xs foldl (+) 0 [1..3] 等价于 (((0 + 1) + 2) + 3)。 尾递归,因此有 strict 版本 foldl' 求值时必须先到达栈底,遍历完列表,因此无法处理无穷列表 Data.List.foldl' foldl' 为 foldl 的 TRO 版本。 Prelude.foldr 继续阅读 »
2018-12-15 Xie Jingyi
一个依赖于外部状态 s 的伪函数 f' :: a -> b,我们可以将其改写为 f :: a -> s -> (b, s) 使其良定。即,在输入输出中显式传递状态 s。现在,我们需要利用 Monad 将状态传递过程隐藏起来。 注意到,输出值 (b, s) 中的末状态 s 不仅依赖于输入状态,更依赖于之前更改过状态的一系列函数及其逻辑。因此我们不能简单地将 Monad 定义为 (a, s) 类似的形式,否则两个函数用 >=> 结合的结果将与函数逻辑无关,这与我们的期望不符。 考虑如下定义: haskell newtype State s a = { runState :: s -> (a, s) } 由于 -> 的右结合性, 继续阅读 »
2018-12-14 Xie Jingyi
动机 pure functions 看似完美,但却不能模拟现实世界中的诸多任务。这是由于 pure functions 是良定的映射,对于特定的输入值会返回唯一的输出。这种模式在面对如下任务时会显得苍白无力: 有可能失败的任务。如大多数的 IO。 依赖外部状态的任务。如(伪)随机数生成器。 非确定性任务,即对于确定的输入可能有多个输出。这种在 IP 中较为少见。 对外界会造成影响的任务。如大多数的写入过程。 这些问题可以用数学中的域扩充技巧来解决。 域扩充 在数学中,当定义问题的范畴不足以容纳问题的解时,我们通常会对相关的范畴进行扩充。类似的技巧同样也可以应用在这里。 假设一个不良定的函数 f: A -> B: 如果 f 继续阅读 »
2018-11-18 Xie Jingyi
Motivation Functor solves the problem of mapping regular one-parameter functions into a sub-category, but that's not easy for functions with more than one parameters. Let's consider a function with two parameters f :: a -> b -> c, which can also read as a -> (b -> c). Applying fmap on f, we will get fmap f :: m a -> 继续阅读 »
2018-11-18 Xie Jingyi
Category Theory A category has three components: A collection of objects. A collection of morphisms, each of which map one object to another. A notion of composition of these morphisms, i.e. morphisms can be composed. If f: A -> B and g: B -> C are morphisms, f.g generates a new morphism A -> C. Note that a morphism 继续阅读 »