类型类声明中“类型”声明的含义

时间:2018-09-12 12:36:41

标签: haskell type-families associated-types

我只是沉迷于这段代码:

-- | Gathers common slice operations.
class Slice a where
    type Loc a

    sliceEvents :: a -> [ResolvedEvent]
    -- ^ Gets slice's 'ResolvedEvent's.
    sliceDirection :: a -> ReadDirection
    -- ^ Gets slice's reading direction.
    sliceEOS :: a -> Bool
    -- ^ If the slice reaches the end of the stream.
    sliceFrom :: a -> Loc a
    -- ^ Gets the starting location of this slice.
    sliceNext :: a -> Loc a
    -- ^ Gets the next location of this slice.
    toSlice :: a -> SomeSlice
    -- ^ Returns a common view of a slice.

我不明白type Loc a在做什么...

1 个答案:

答案 0 :(得分:4)

Loc a是关联的类型,这是一种声明与类实例关联的类型族实例的方法。 Loc a表示的类型由a的类型确定,并在实例中指定:例如

instance Slice Foo where
    type Loc Foo = Bar
    ...

Loc a出现在类声明中时,它将被实例中的相应类型替换-因此Foo的实例函数看起来像

sliceEvents :: Foo -> [ResolvedEvent]
...
sliceFrom :: Foo -> Bar
...

关联的类型还可以通过给出类约束在类声明之外的其他函数中使用:

myFunction :: (Slice a) => a -> Loc a
相关问题