我需要以下类功能:
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
函数。例如String
Monoid 和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