gpt4 book ai didi

haskell - ZipList Monoid haskell

转载 作者:行者123 更新时间:2023-12-02 07:19:31 26 4
gpt4 key购买 nike

GHC Prelude 中列表的默认 monoid 是串联。

[1,2,3] <> [4,5,6]变成 [1,2,3] ++ [4,5,6]因此[1,2,3,4,5,6]

我想编写一个行为如下的 ZipList Monoid 实例:

[
1 <> 4
, 2 <> 5
, 3 <> 6
]

结果是[5,7,9]假设我正在使用 sum monoid。请注意,它的行为类似于 zipWith (+)

它的行为可能是这样的:

[
Sum 1 <> Sum 4
, Sum 2 <> Sum 5
, Sum 3 <> Sum 6
]

我需要围绕 ZipList 创建一个新类型newtype 和 Sum newtype 以便为 Monoid 创建一个实例, Arbitrary , 和 EqProp .从而避免孤儿实例。这就是 ZipList 的方式和 Sum看起来像 Prelude :

newtype ZipList a = ZipList { getZipList :: [a] }
newtype Sum a = Sum { getSum :: a }

这就是我的新类型 MyZipList看起来:看起来对吗?

newtype MyZipList a =
MyZipList (ZipList [a])
deriving (Eq, Show)

instance Monoid a => Monoid (MyZipList a) where
mempty = MyZipList (ZipList [])

mappend (MyZipList z) (MyZipList z') =
MyZipList $ liftA2 mappend z z'

instance Arbitrary a => Arbitrary (MyZipList a) where
arbitrary = MyZipList <$> arbitrary

instance Eq a => EqProp (MyZipList a) where
(=-=) = eq

这就是我的新类型 MySum好像:这看起来对吗?

newtype MySum a =
MySum (Sum a)
deriving (Eq, Show)

instance (Num a, Monoid a) => Monoid (MySum a) where
mempty = MySum mempty

mappend (MySum s) (MySum s') = MySum $ s <> s'

instance Arbitrary a => Arbitrary (MySum a) where
arbitrary = MySum <$> arbitrary

我需要帮助找出我出错的地方。

最佳答案

首先要注意 ZipListApplicative实例已经具有您想要的 zippy 行为。

ghci> liftA2 (<>) (Sum <$> ZipList [1,2,3]) (Sum <$> ZipList [4,5,6]) :: ZipList Int
ZipList [Sum 5, Sum 7, Sum 9]

然后使用任何 Applicative 的事实产生 Monoid通过 monoidal 仿函数本身提升其内容的 monoidal 行为。计划是抽象 liftA2 (<>)我上面写的表达式的模式。

newtype Ap f a = Ap { getAp :: f a }
instance (Applicative f, Monoid a) => Monoid (Ap f a) where
mempty = Ap $ pure mempty
Ap xs `mappend` Ap ys = Ap $ liftA2 mappend xs ys

(据我所知 newtype 中缺少 base ,这对我来说似乎是一个疏忽,尽管可能有充分的理由。事实上,我认为 ZipList 应该有一个开箱即用的 zippy Monoid 实例,但是,唉,它没有。)

您想要的Monoid那么只是Ap ZipList (Sum Int) .这相当于 MyZipList Monoid你是手写的(除了你的 mempty 中的错误 - 它应该是 MyZipList $ ZipList $ repeat mempty ),但是用可重复使用的 newtype 编写它像这样的方式不那么特别,需要的样板也更少。

关于haskell - ZipList Monoid haskell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50130388/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com