我可以为关联的类型系列设置默认类型值吗?

Ign*_*rov 5 haskell types type-families

考虑这个代码:

{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeFamilyDependencies #-}

module Study where

class C a where
    type T a = r | r -> a
    pred :: T a -> Bool
    pred _ = True
Run Code Online (Sandbox Code Playgroud)

我想有一个更有意义的默认定义pred,像这样:

class C' a where
    ...
    pred' = not . null
Run Code Online (Sandbox Code Playgroud)

(我想默认 T' a = [a]。)

有办法吗?

chi*_*chi 4

您需要一个默认签名

Prelude> :{
Prelude| class C a where
Prelude|   type T a = r | r -> a
Prelude|   pred :: T a -> Bool
Prelude|   default pred :: (T a ~ [a]) => T a -> Bool
Prelude|   pred = not . null
Prelude| :}
Run Code Online (Sandbox Code Playgroud)

(感谢@luqui。)请注意,如果您希望能够编写空的,您还应该通过添加行 来instance C Integer提供默认值。Ttype T a = [a]

  • @IgnatInsarov,如果您想要一个空实例,您还可以通过添加行“type T a = [a]”来为“T”提供默认值。 (4认同)