gpt4 book ai didi

haskell - 类型类声明中 "type"声明的含义

转载 作者:行者123 更新时间:2023-12-02 12:53:39 25 4
gpt4 key购买 nike

我刚刚陷入了那段代码:

-- | 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在做什么...

最佳答案

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

关于haskell - 类型类声明中 "type"声明的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52295362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com