【发布时间】:2014-11-05 09:24:25
【问题描述】:
我想知道标准包中是否定义了bind2、bind3等函数?
bind2 :: (Monad m, Applicative m) => (a -> b -> m c) -> m a -> m b -> m c
bind2 f a b = join (liftA2 a b)
为什么我想要那个?因为我想将绑定减少到最低限度。例如,如果我们使用免费的 monad 方法来构建自动并发异步计算,或者像 Haxl 中那样获取:
fetchForSuggestions :: Artist -> [Like] -> Async [Suggestions]
fetchForSuggestions = error "implement me"
-- Two binds!
action :: ArtistId -> UserId -> Async [Suggestions]
action artistId userId = do
artist <- fetchArtist artistId
likes <- fetchUserLikes userId
fetchForSuggestions artist likes
-- Single bind
-- here artist and user likes could be fetched concurrently
action :: ArtistId -> UserId -> Async [Suggestions]
action artistId userId = bind2 fetchForSuggestions (fetchArtist artistId) (fetchUserLikes userId)
我在这里介绍某种反模式吗?我应该尝试做什么:
complexAction :: ParamA -> ParamB -> ParamC -> Async Result
complexAction a b c = do
(x, y, z) <- (,,) <$> subActionX a b <*> subActionY b c <*> subActionZ c a
(i, j, k) <- (,,) <$> subActionI a x <*> subActionJ b y <*> subActionK c z
finalAction i j k x y z
每个subAction 函数在哪里是无绑定的? IE。去掉action,取ArtistId和UserId,只留下fetchForSuggestions?
【问题讨论】:
-
听起来您可能会从
{-# LANGUAGE ApplicativeDo #-}中受益。 :) ghc.haskell.org/trac/ghc/wiki/ApplicativeDo
标签: haskell monads applicative