感谢newtype和GeneralizedNewtypeDeriving扩展,可以轻松定义不同的轻量级类型:
newtype PersonId = PersonId Int deriving (Eq, Ord, Show, NFData, ...)
newtype GroupId = GroupId Int deriving (Eq, Ord, Show, NFData, ...)
Run Code Online (Sandbox Code Playgroud)
这允许类型系统确保a PersonId不会被意外使用GroupId,但仍然从中继承选定的类型类实例Int.
现在可以简单地定义PersonIdSet和GroupIdSet作为
import Data.Set (Set)
import qualified Data.Set as Set
type PersonIdSet = Set PersonId
type GroupIdSet = Set GroupId
noGroups :: GroupIdSet
noGroups = Set.empty
-- should not type-check
foo = PersonId 123 `Set.member` noGroups
-- should type-check
bar = GroupId 123 …Run Code Online (Sandbox Code Playgroud)