日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Functor、Applicative 和 Monad x

發布時間:2025/3/20 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Functor、Applicative 和 Monad x 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

首先,我們來看一下 Functor typeclass 的定義:

?

1

2

class Functor f where

? ? fmap :: (a -> b) -> f a -> f b

Functor typeclass fmap (a -> b) f a f b f Functor :fmap 函數可類比 Swift 中的 map 方法。

?

Applicative typeclass

同樣的,我們先來看一下 Applicative typeclass 的定義:

?

1

2

3

class Functor f => Applicative f where

? ? pure :: a -> f a

? ? (<*>) :: f (a -> b) -> f a -> f b

我們注意到,與 Functor typeclass 的定義不同的是,在 Applicative typeclass 的定義中多了一個類約束 Functor f ,表示的意思是數據類型 f 要實現 Applicative typeclass 的前提條件是它必須要實現 Functor typeclass ,也就是說它必須是一個 Functor 。

在 Applicative typeclass 中定義了兩個函數:

  • pure a (<*>) :將一個在上下文中的函數 f (a -> b) 應用到一個在上下文中的值 f a ,并返回另一個在上下文中的值 f b 。

同樣的,我們先來看一下 Monad typeclass 的定義:

?

1

2

3

4

5

6

7

8

9

10

class Applicative m => Monad m where

? ? return :: a -> m a

?

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

?

? ? (>>) :: m a -> m b -> m b

? ? x >> y = x >>= \_ -> y

?

? ? fail :: String -> m a

? ? fail msg = error msg

Monad typeclass return(>>=)(>>) fail (>>) fail Monad typeclass

1

2

3

class Applicative m => Monad m where

? ? return :: a -> m a

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

怎么樣?現在看上去就好多了吧。跟 Applicative typeclass 的定義一樣,在 Monad typeclass 的定義中也有一個類約束 Applicative m ,表示的意思是一種數據類型 m 要成為 Monad 的前提條件是它必須是 Applicative 。另外,其實 return 函數的功能與 Applicative 中的 pure 函數的功能是一樣的,只不過換了一個名字而已,它們的作用都是將一個值 a 放入上下文中。而 (>>=) 函數的功能則是應用一個(接收一個普通值 a 但是返回一個在上下文中的值 m b 的)函數 (a -> m b) 到一個上下文中的值 m a ,并返回另一個在相同上下文中的值 m b 。

?

總結

以上是生活随笔為你收集整理的Functor、Applicative 和 Monad x的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。