This chapter develop a small language of numbers and booleans, serving as a straightforward vehicle for the introduction of serveral fundamental concepts like, abstract syntax tree, evaluation and runtime errors.
Syntax
BNF-like Definition
Terms of this language are defined as below:
t ::=
true
false
i继续阅读 »
一个依赖于外部状态 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) }
由于 -> 的右结合性,继续阅读 »
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 -> 继续阅读 »
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 继续阅读 »
新类型有自己的 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 -继续阅读 »