【问题标题】:Can I have a default type value for an associated type family?我可以为关联的类型族设置默认类型值吗?
【发布时间】:2018-10-14 12:30:49
【问题描述】:

考虑这段代码:

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

module Study where

class C a where
    type T a = r | r -> a
    pred :: T a -> Bool
    pred _ = True

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

class C' a where
    ...
    pred' = not . null

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

有办法吗?

【问题讨论】:

    标签: haskell types type-families


    【解决方案1】:

    您需要default signature

    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| :}
    

    (感谢@luqui。) 请注意,如果您希望能够写入一个空的instance C Integer,您还应该通过添加@987654325 行来为T 提供默认值@。

    【讨论】:

    • 嗯,这样的作品。我仍然不能写一个空的instance C Integer。我必须指定type T Integer = [Integer]。但至少我可以省略pred的定义。
    • @IgnatInsarov,如果您想要一个空实例,您还可以通过添加type T a = [a] 行来为T 提供默认值。
    猜你喜欢
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2017-02-06
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    相关资源
    最近更新 更多