gpt4 book ai didi

haskell - 免费 monad 的应用实例

转载 作者:行者123 更新时间:2023-12-03 23:32:14 27 4
gpt4 key购买 nike

在尝试找到可以逐步执行/允许线程的haskell monad时,我发现了免费的monad

data Free f a = Return a | Roll (f (Free f a))

及其 monad 实例
instance (Functor f) => Monad (Free f) where
return = Return
Return x >>= f = f x
Roll action >>= f = Roll $ fmap (>>= f) action

及其仿函数实例
instance (Functor f) => Functor (Free f) where
fmap f (Return x) = Return (f x)
fmap f (Roll x) = Roll $ fmap (fmap f) x

我知道每个单子(monad)都是 pure = return 的应用仿函数和 (<*>) = ap .
对我来说,应用仿函数在概念上比单子(monad)更难。为了更好地理解应用仿函数,我喜欢使用应用实例而不求助于 ap。 .
<*> 的第一行简单:
instance (Applicative f) => Applicative (Free f) where
pure = Return
Return f <*> x = fmap f x -- follows immediately from pure f <*> x = f <$> x
--Roll f <*> x = Roll $ (fmap ((fmap f) <*>)) x -- wrong, does not type-check

如何定义 Roll f <*> xfmap 的基本术语和 <*> ?

最佳答案

这会吗?

instance (Functor f) => Applicative (Free f) where
pure = Return
Return f <*> as = fmap f as
Roll faf <*> as = Roll (fmap (<*> as) faf)

计划是只作用于产生函数的树的叶子,所以对于 Return , 我们
通过将函数应用于参数操作产生的所有参数值来执行操作。对于 Roll ,我们只是对所有子 Action 做我们打算对整体 Action 做的事情。

至关重要的是,当我们到达 Return 时我们会做什么在我们开始之前已经设置好了。我们不会根据我们在树中的位置来改变我们的计划。这就是成为 Applicative 的标志。 :计算的结构是固定的,因此值依赖于值,但 Action 不依赖于值。

关于haskell - 免费 monad 的应用实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22121960/

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