有了量化的约束,我可以Eq (A f)很好地推导出来吗?但是,当我尝试推导 Ord (A f) 时,它失败了。当约束类具有超类时,我不明白如何使用量化约束。我如何派生Ord (A f)和其他具有超类的类?
> newtype A f = A (f Int)
> deriving instance (forall a. Eq a => Eq (f a)) => Eq (A f)
> deriving instance (forall a. Ord a => Ord (f a)) => Ord (A f)
<interactive>:3:1: error:
• Could not deduce (Ord a)
arising from the superclasses of an instance declaration
from the context: forall a. Ord a => Ord (f a)
bound by …Run Code Online (Sandbox Code Playgroud) 我在使用使用可重新填充迭代器的生成器时遇到问题。
这是我的简单生成器:
def hi(iterable):
for val in iterable:
yield val
Run Code Online (Sandbox Code Playgroud)
我传递到 hi 生成器的可迭代对象是来自function_pipes 存储库的Reservoir 类,它可以在耗尽其元素后重新填充。
我想使用 hi 生成器直到 StopIteration 被引发,然后重新填充可迭代对象,然后再次使用它,就像
refillable = Reservoir((1, 2, 3, 4))
hi_iter = hi(refillable)
print(tuple(hi_iter))
refillable((5, 6, 7, 8))
print(tuple(hi_iter))
Run Code Online (Sandbox Code Playgroud)
但这打印
(1, 2, 3, 4)
()
Run Code Online (Sandbox Code Playgroud)
第二个元组也应该是 (5,6,7,8)。
我找到的唯一解决方案是用一个类包装 hi 生成器
def super_gener(function):
class wrapper_class:
def __init__(self, iterable):
self.iterable = iterable
self.zipped = None
def __iter__(self):
return self
def __next__(self):
try:
return next(self.zipped)
except TypeError:
self.zipped = function(self.iterable)
return next(self)
except StopIteration as …Run Code Online (Sandbox Code Playgroud) 我有类型data A a = B (a (A a))。如何a在函数中对var类型施加约束something :: Eq (a b) => A a -> SomeType?