gpt4 book ai didi

haskell - 在应用方面实现 Monoidal

转载 作者:行者123 更新时间:2023-12-02 10:48:49 25 4
gpt4 key购买 nike

Typeclassopedia提出以下练习:

Implement pure and (<*>) in terms of unit and (**), and vice versa.

这是MonoidalMyApplicative :

class Functor f => Monoidal f where
u :: f () -- using `u` rather than `unit`
dotdot :: f a -> f b -> f (a,b) -- using instead of `(**)`

class Functor f => MyApplicative f where
p :: a -> f a -- using instead of `pure`
apply :: f (a -> b) -> f a -> f b -- using instead of `(<**>)`

首先,让我展示 Maybe -类似数据类型:

data Option a = Some a 
| None deriving Show

然后,我定义了instance MyApplicative Option :

instance MyApplicative Option where
p = Some
apply None _ = None
apply _ None = None
apply (Some g) f = fmap g f

最后,我尝试实现 Monoidal Optionp而言和applyMyApplicative :

instance Monoidal Option where
u = p ()
dotdot None _ = None
dotdot _ None = None
dotdot (Some x) (Some y) = Some id <*> Some (x, y)

这是对的吗?我的实现dotdotapply似乎没有

instance Monoidal Option where
u = p ()
dotdot None _ = None
dotdot _ None = None
dotdot (Some x) (Some y) = apply (Some id) (Some (x, y))

特别是,我很好奇如何正确实现 dotdot :: f a -> f b -> f (a, b)与应用程序的(<*>) - 就我而言,它是 apply .

最佳答案

ApplicativeMonoidal 的简洁替代演示文稿。两个类型类是等效的,您可以在两者之间进行转换,而无需考虑特定的数据类型,例如 OptionApplicative 的“简洁替代演示”基于以下两个等价

pure a = fmap (const a) unit
unit = pure ()

ff <*> fa = fmap (\(f,a) -> f a) $ ff ** fa
fa ** fb = pure (,) <*> fa <*> fb

获得 Applicative 的“简洁替代演示文稿”的技巧与 zipWith 的技巧相同- 将接口(interface)中的显式类型和构造函数替换为可以传递类型或构造函数以恢复原始接口(interface)的内容。

unit :: f ()

替换为pure我们可以替换类型 ()和构造函数() :: ()进入恢复unit .

pure :: a  -> f a
pure () :: f ()

类似地(尽管不那么简单)替换类型 (a,b)和构造函数(,) :: a -> b -> (a,b)进入liftA2恢复** .

liftA2 :: (a -> b -> c) -> f a -> f b -> f c
liftA2 (,) :: f a -> f b -> f (a,b)

Applicative然后得到很好的<*>运算符(operator)通过提升功能应用($) :: (a -> b) -> a -> b进入仿函数。

(<*>) :: f (a -> b) -> f a -> f b
(<*>) = liftA2 ($)

<*> 出发返回liftA2很常见, liftA2 is included in Control.Applicative <$>是中缀 fmap .

liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c
liftA2 f a b = f <$> a <*> b

关于haskell - 在应用方面实现 Monoidal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27262232/

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