gpt4 book ai didi

haskell - 应用函数的组成

转载 作者:行者123 更新时间:2023-12-05 08:56:58 25 4
gpt4 key购买 nike

我可以编写纯函数:

let f x = x + 1
let g x = x + 2
let z = f . g
z 1 == 4

我似乎也可以组合单子(monad)函数:

let f x = Just (x + 1)
let g x = Just (x + 2)
let z x = f x >>= g
z 1 == Just 4

我认为我应该能够将上一个示例中的 fg 视为应用程序并组合它们,只是不确定如何:

let f x = Just (x + 1)
let g x = Just (x + 2)
let z x = f <*> g -- this doesn't work
z 1 == Just 4

这可行吗?

加分,z x = f x >>= g可以写成无点函数吗?像 z = f >>= g 这样的东西?

最佳答案

{-# LANGUAGE TypeOperators #-}

任意两个应用仿函数的(类型级)组合,

newtype (f :. g) a = Compose { getCompose :: f (g a)) }

is an applicative functor .

instance (Functor f, Functor g) => Functor (f :. g) where
fmap f = Compose . fmap (fmap f) . getCompose

instance (Applicative f, Applicative g) => Applicative (f :. g) where
pure = Compose . pure . pure
Compose fgf <*> Compose fgx = Compose ((<*>) <$> fgf <*> fgx)

你的例子是the Maybe applicative的组成与 the "function" or "reader" applicative (->) r .

type ReaderWithMaybe r = ((->) r) :. Maybe

x, y :: ReaderWithMaybe Int Int
x = Compose $ \x -> Just (x + 1)
y = Compose $ \x -> Just (x + 2)

ReaderWithMaybe r是一个 Applicative你可以做所有平常的事情 Applicative东西。在这里,我将我的两个值与 + 一起粉碎.

ghci> let z = (+) <$> x <*> y
ghci> getCompose z 3
Just 9 -- (3 + 1) + (3 + 2) == 9

请注意 xy两者都得到相同的输入 3 .这就是 (->) r 的行为的 Applicative实例。如果您想获取 f x = Just (x + 1)结果并将其输入 g x = Just (x + 2) (得到相当于 h x = Just (x + 3) 的东西),嗯,这就是 Monad是为了。


Bonus points, can z x = f x >>= g be written as a point-free function? Something like z = f >>= g?

您可以轻松地手动定义 Kleisli 构图。

(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c
f >=> g = \x -> f x >>= g

碰巧>=>已经存在于标准库中,连同它的姊妹<=< .他们被亲切地称为“鱼”运营商,他们住在 Control.Monad 。 .

关于haskell - 应用函数的组成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36839682/

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