跳轉到內容

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


華夏公益教科書