我喜欢Haskell类型同义词的想法,因为它们允许区分共享基本表示形式的抽象数据类型。不幸的是,当我写一个程序像
data Vector a = Vec a a
-- Some definitions here about (+) and (*) for Vector ...
type Position = Vector Float
type Velocity = Vector Float
type Time = Float
step :: Position -> Velocity -> Time -> Position
step p v dt = p + v*dt
p :: Position
p = Vec 0.0 0.0
v :: Velocity
v = Vec 1.0 1.0
p' = step v p 0.01
这是完全有效的Haskell代码,尽管v
并p
在错误的地点是。我想加强类型同义词之间的区别,以使它们仍然共享基础表示,但在函数应用程序中彼此不被接受。这可能吗?
你可以做Vector
一个假体类型如下:
data Vector t a = Vec a a
data Pos
data Vel
type Position = Vector Pos Float
type Velocity = Vector Vel Float
现在,您可以像通常一样定义Position
和的实例Velocity
:
p :: Position
p = Vec 0.0 0.0
v :: Velocity
v = Vec 1.0 1.0
但是,它不允许您互换使用它们:
type Time = Float
step :: Position -> Velocity -> Time -> Position
step p v dt = p + v*dt -- you might have to change this definition
p' = step v p 0.01 -- won't compile
您还可以使用DataKinds
和来使事情更精确KindSignatures
:
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
data VectorType = Pos | Vel
data Vector (t :: VectorType) a = Vec a a
type Position = Vector Pos Float
type Velocity = Vector Vel Float
希望能有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句