[英]Writing generic instances for Fix/Mu in F-algebras
After reading Milewski's F-algebra article , I tried to implement it and use for a real-world problem. 在阅读了Milewski的F-algebra文章后 ,我尝试实现它并用于解决现实问题。 However, I can't seem to figure out how to write instances for
Fix
, 但是,我似乎无法弄清楚如何为
Fix
编写实例,
newtype Fix f = Fx { unFix :: f (Fix f) }
cata :: Functor f => (f a -> a) -> Fix f -> a
cata alg = alg . fmap (cata alg) . unFix
For example, let's say I this simple algebra: 例如,让我说我这个简单的代数:
data NatF a = Zero | Succ a deriving Eq
type Nat = Fix NatF
and now I try to implement an instance of Eq
(note: deriving
doesn't work): 现在我尝试实现
Eq
的实例(注意: deriving
不起作用):
instance ??? => Eq (Fix f) where
(==) = ???
And this is where I get stuck. 这就是我陷入困境的地方。 How do I fill in the
???
我怎么填写
???
to make this work? 使这项工作? Is this even possible to do?
这甚至可能吗?
The simplest instance I could find was just 我能找到的最简单的例子就是
{-# LANGUAGE UndecidableInstances, FlexibleContexts #-}
import Data.Function (on)
instance Eq (f (Fix f)) => Eq (Fix f) where
(==) = (==) `on` unFix
All that we require is that Fix f
is an instance of Eq
precisely when f (Fix f)
is an instance of Eq
. 所有这一切我们需要的是
Fix f
是实例Eq
精确当f (Fix f)
是一个实例Eq
。 Since in general we have instances like Eq a => Eq (fa)
this works just fine. 因为一般来说我们有像
Eq a => Eq (fa)
这样的实例,所以这很好用。
> Fx Zero == Fx Zero
True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.