加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

haskell – bind可以由fmap和join组成,所以我们必须使用monadic

发布时间:2020-12-12 06:28:55 所属栏目:MsSql教程 来源:网络整理
导读:我不太多使用 Haskell,但我理解Monads的概念. 我被Kleisli triple困惑了,然而,这个类别, fmap and join Although Haskell defines monads in terms of the return and bind functions,it is also possible to define a monad in terms of return and two othe
我不太多使用 Haskell,但我理解Monads的概念.

我被Kleisli triple困惑了,然而,这个类别,

fmap and join

Although Haskell defines monads in terms of the return and bind functions,it is also possible to define a monad in terms of return and two other operations,join and fmap. This formulation fits more closely with the original definition of monads in category theory. The fmap operation,with type (t → u) → M t → M u,takes a function between two types and produces a function that does the “same thing” to values in the monad. The join operation,with type M (M t) → M t,“flattens” two layers of monadic information into one.

帮助我了解Monads的背景原理.

The two formulations are related as follows:

fmap f m = m >>= (return . f)
join n   = n >>= id

fmap :: (a -> b) -> (m a -> m b)
unit :: a -> m a
join :: m (m a) -> m a
>>=  :: m a -> (a -> m b) -> m b

m >>= f  =  join $fmap f m

我的问题是:
我认为,因为>> =可以由fmap和join组成,这是一个monadic函数
a – > m b不是必需的并且正常功能a – > b将满足该操作,但是围绕网络的许多教程仍然坚持使用monadic函数,因为这是Kleisli三元组和monad定律.

那么,为了简单起见,我们不应该只使用非monadic函数,只要它们是endo-functions?我错过了什么?

相关主题是

Monad join function

Haskell Monad bind operator confusion

Difference in capability between fmap and bind?

解决方法

从某种意义上说,你是对的.由于每个monad m都是一个仿函数,我们可以使用带有函数f :: a – >的fmap f. b将m a变成m b,但有一个问题.什么是b?

我喜欢将这样的m视为“计划获取”,其中“计划”涉及除纯计算之外的某种额外交互.如果你有一个“计划获取Int”并且你想要一个“计划获取字符串”,你可以在Int – >中使用带有函数的fmap.字符串,但该函数的类型告诉您从Int获取String不涉及进一步的交互.

这并非总是如此:也许Int是学生注册号,而String是他们的名字,所以从一个转换到另一个的计划需要在某个表中进行外部查找.然后我没有从Int到String的纯函数,而是从Int到“plan-to-get String”的纯函数.如果我在我的“计划获取Int”中进行fmap,那很好,但我最终得到了“计划获取(计划获取字符串)”,我需要加入外部和内部计划.

一般情况是我们有足够的信息来计算计划以获得更多.那就是 – > m b型号.特别是,我们返回:: a – > m a,它将我们拥有的信息转化为计划,通过不采取进一步行动为我们提供准确的信息,并且我们有(> =>)::(a – > m b) – > (b – > m c) – > (a – > m c)组成两个这样的东西.我们还有(> =>)是关联的,并且在左右两侧吸收回报;在经典命令式编程中是联想和吸收跳过.

使用这种组合方法从较小的计划构建更大的计划更方便,使“计划获取”层的数量保持一致.否则,您需要使用fmap构建n层计划,然后在外部执行正确数量的连接(这将是计划的脆弱属性).

现在,因为Haskell是一种具有“自由变量”和“范围”概念的语言,所以a in

(>=>) :: (a -> m b) -> (b -> m c) -> (a -> m c)

代表“整体输入信息”只能来自我们已经拥有的东西,离开

(>>=) ::       m b  -> (b -> m c) ->       m c

然后我们回到“bind”,这是一个以最程序员友好的形式呈现组合结构的工具,类似于本地定义.

总而言之,您可以使用 – > b,但通常你需要b来“计划获得某些东西”,如果你想要在构图上构建计划,这是有用的选择.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读