haskell intro
安装
参考官网,有三种方案,通常选stack方案,用stack来管理,ghc也在stack沙箱中运行: stack ghc。
只是有时候需要系统环境下安装一个ghc,ghci用来方便测试,
就需要Minimal installers方案。但网上推荐的用ghcup,只是此方案下载一个巨大的文件不能走国内镜像加速,好在我用的是macOS,可以这样装ghc:
brew install ghc
当配置走清华镜像后,速度很快,哈哈!
Values, Types
haskell是纯functional language
每个value都有对应的type,type可看做value的集合。
values是一等公民,可作为参数,返回值或数据成员。types则不是,types可理解为values的描述。
expressions就是通常意义上的表达式
type expressions则是type的值,例如Integer,Char,Integer -> Integer, [Integer], (Integer, Char)
Functions由一系列的equations定义,例如:
inc n = n + 1
equations是一种declaration,还有一种declaration是type signature declaration,如:
inc :: Integer -> Integer
Haskell的static type system定义了types和values之间的关系,static type system 确保了Haskell类型安全,静态类型帮助程序员reasoning about programs
也帮助编译器生产更高效的代码(例如不需要运行期的type tags)
Polymorphic Types
例如:
length :: [a] -> Integer
length [] = 0
length (x:xs) = 1 + length xs
head :: [a] -> a
head(x:xs) = x
tail :: [a] -> [a]
tail(x:xs) = xs
其中a就用于多态类型,称为type variables,在Haskell中为了区别,specific types用首字母大写,例如Int
而universal types用首字母小写
可以发现[a]比[Char]更通用,后者应该可由前者推导得到(derived),Haskell的类型系统有两个重要性质来保证这种generalization ordering
- every well-typed expression is guaranteed to have a unique principal type
- the principal type can be inferred automatically
我当前的理解就是每个表达式都有个具体的类型(the least general type),可由抽象的类型推导得到。
The existence of *unique principal types* is the hallmark feature of the *Hindley-Milner* type system, which forms the basis of the type systems of Haskell
User-Defined Types
例如:
data Bool = False | True
data Color = Red | Green | Blue
data Point a = Pt a a
其中Color称为type constructors,Red之类称为data constructors
Bool和Color都是枚举类型(enumerated types)其包含有限数量的data constructors
而Point只含有一个data constructors,称为tuple type,它本质上是其他类型的笛卡尔积cartesian product,
multi constructors types,例如Bool和Color则称为(disjoint) union 或 sum types