我需要以下类功能:
class InterleavedHomomorphic x where
interleaveHomomorphism :: (forall a . f a -> g a) -> x f -> x g
Run Code Online (Sandbox Code Playgroud)
显然,我为它发明的名称绝不是任何东西的官方术语,上面的类型不是很优雅.这是一个在某些库中有名称甚至实现的概念吗?有没有更合理的方法呢?
这个函数的目的是我有一些f注释一些数据的上下文(为了这个问题Foo,Bar它只是随机的示例数据结构):
data Foo f = One (f (Bar f)) | Product (f (Foo f)) (f (Foo f))
data Bar f = Zero | Succ (f (Bar f))
Run Code Online (Sandbox Code Playgroud)
我想以多态方式转换数据的上下文; 只知道上下文之间的同态,而不是(必然)关心数据本身.这可以通过提供instance InterleavedHomomorphic Foo和instance InterleavedHomomorphic Bar在上面的例子中完成.
我正在阅读“Scala 编程”一书(红皮书)。
在关于 Monoids 的章节中,我理解了 Monoid 同态是什么,例如:M具有串联和length函数的 String Monoidf保留了Monoid结构,因此是同态的。
M.op(f(x), f(y)) == M.op(f(x) + f(y))
// "Lorem".length + "ipsum".length == ("Lorem" + "ipsum").length
Run Code Online (Sandbox Code Playgroud)
引用这本书(根据记忆,如果我错了,请纠正我:
当这在两个方向上发生时,它被命名为 Monoid isomorphisim,这意味着对于 monoids
M, N和函数f, g,f andThen g和g andThen f是identity函数。例如StringMonoid 和List[Char]Monoid with concatenation 是同构的。
但我不能看到看到这一个实际的例子,我只能想到f的length功能,但会发生什么g?
注意:我看过这个问题:What are isomorphism and homomorphisms。
functional-programming scala isomorphism monoids homomorphism
我正在做Typeclassopedia的练习; 在Applicative节中,我写ZipList的pure功能,并检查它是否遵循Applicative法律.
我检查过:
但是当我试图检查"同态"定律时,我发现GHCi没有得到结果MZipList.
我想这是因为我错过了指定pure我的Applicative类型课程.如何立即运行pure没有<*>它的功能Applicative?
这是MZipList定义和类实例:
newtype MZipList a = MZipList { getZipList :: [a] }
deriving (Show)
instance Functor MZipList where
fmap gs x = pure gs <*> x
instance Applicative MZipList where
pure a= MZipList (repeat a)
(MZipList gs) <*> (MZipList xs) = MZipList (zipWith ($) gs xs)
Run Code Online (Sandbox Code Playgroud)
当我检查"交换"法时,例如:
*Main> (MZipList …Run Code Online (Sandbox Code Playgroud) homomorphism ×3
haskell ×2
applicative ×1
comonad ×1
functor ×1
isomorphism ×1
monoids ×1
proof ×1
scala ×1
typeclass ×1