递归类型的约束

Wil*_*ack 2 haskell types constraints recursive-type

我有类型data A a = B (a (A a))。如何a在函数中对var类型施加约束something :: Eq (a b) => A a -> SomeType

chi*_*chi 6

对我来说,要实现的目标还不是很清楚,但这可以编译为:

{-# LANGUAGE QuantifiedConstraints, StandaloneDeriving, UndecidableInstances #-}

data A a = B (a (A a))

deriving instance (forall t. Eq t => Eq (a t)) => Eq (A a)

something :: (forall t. Eq t => Eq (a t)) => A a -> String
something x 
   | x==x      = "hello"
   | otherwise = "world"
Run Code Online (Sandbox Code Playgroud)

这里的诀窍是要求Eq (a t)保持一切可能t。那需要QuantifiedConstraints

当然,您也可以使用更适度的方法,而是要求

something :: Eq (a Bool) => A a -> String
Run Code Online (Sandbox Code Playgroud)

但这不允许您==在参数上使用。

或者,

something :: Eq (A a) => A a -> String
Run Code Online (Sandbox Code Playgroud)

应该会起作用,即使它会触发警告。