跳转到内容

Haskell/幽灵类型

来自维基教科书,开放世界中的开放书籍

幽灵类型是一种方法,可以将语言嵌入到比 Haskell 更强大的类型系统中。

幽灵类型

[编辑 | 编辑源代码]

普通类型

data T = TI Int | TS String

plus :: T -> T -> T
concat :: T -> T -> T

它的幽灵类型版本

data T a = TI Int | TS String

没有变化 - 只是我们没有接触到的新参数 a。但是神奇!

 
plus :: T Int -> T Int -> T Int
concat :: T String -> T String -> T String

现在我们可以强制执行更多一点!

如果您想提高代码的类型安全性,但又不想增加额外的运行时开销,这将非常有用。

-- Peano numbers at the type level.
data Zero = Zero
data Succ a = Succ a
-- Example: 3 can be modeled as the type
-- Succ (Succ (Succ Zero)))

type D2 = Succ (Succ Zero)
type D3 = Succ (Succ (Succ Zero))

data Vector n a = Vector [a] deriving (Eq, Show)

vector2d :: Vector D2 Int
vector2d = Vector [1,2]

vector3d :: Vector D3 Int
vector3d = Vector [1,2,3]

-- vector2d == vector3d raises a type error
-- at compile-time:

--   Couldn't match expected type `Zero'
--               with actual type `Succ Zero'
--   Expected type: Vector D2 Int
--     Actual type: Vector D3 Int
--   In the second argument of `(==)', namely `vector3d'
--   In the expression: vector2d == vector3d

-- while vector2d == Vector [1,2,3] works


华夏公益教科书