【问题标题】:Specifying that a type can only exist in one class if it already exists in other classes in Haskell指定一个类型只能存在于一个类中,如果它已经存在于 Haskell 中的其他类中
【发布时间】:2016-11-05 21:10:22
【问题描述】:

我正在处理一个涉及统一的问题,使用用户定义的类型 Subst a。问题如下:

"定义一个类型类Unifiable,指定一个函数unify::a -> a -> Maybe (Subst a) 必须为此类内的任何类型 a 定义。类型 a 只能在 Unifiable 类,如果它已经在 Eq 和 Substitutable 类中,这应该 在你的定义中表示出来。”

到目前为止,这就是我定义 Substitutable 和 Unifiable 的方式:

class Substitutable a where
subst :: Subst a -> a -> a

class Unifiable a where
unify :: a -> a -> Maybe (Subst a)

但是,我不确定如何指定类型 a 只能在 Unifiable 类中,前提是它已经在 Eq 和 Substitutable 类中。

我不是在寻找这个特定问题的答案,但总的来说,如果类型已经在其他类中,我将如何指定它只能在一个类中?

谢谢。

【问题讨论】:

    标签: haskell instance typeclass unification


    【解决方案1】:

    类定义可以包含约束,就像函数一样。

    class (Eq a, Substitutable a) => Unifiable a where
        unify :: a -> a -> Maybe (Subst a)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-30
      • 2012-03-19
      • 2021-12-23
      • 2022-11-19
      • 1970-01-01
      • 2018-08-23
      • 2013-08-21
      • 2013-06-16
      相关资源
      最近更新 更多