相关疑难解决方法(0)

如何"newtype"IntSet?

感谢newtypeGeneralizedNewtypeDeriving扩展,可以轻松定义不同的轻量级类型:

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.

现在可以简单地定义PersonIdSetGroupIdSet作为

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)

haskell types

3
推荐指数
1
解决办法
468
查看次数

标签 统计

haskell ×1

types ×1