以下代码试图编写一个如下所示的可变函数:
bind_variadic mx f = mx >>= f
bind_variadic mx my f = do { x <- mx; y <- my; f x y }
如果将“其余绑定”表示为变量k
,我可以编写它,但是为了编写类型类,我需要根据另一个编写一个函数。确切地说,我想用l1
表示l0
l2
,l1
等等。
import Prelude hiding ((>>=), (>>), Monad, return)
-- override the default monad so we don't get confusing
-- instances like "Monad (->)".
class Monad m where
(>>=) :: m a -> (a -> m b) -> m b
(>>) :: m a -> m b -> m b
return :: a -> m a
fail :: String -> m a
h :: Monad m => m a -> (t -> m b) -> (a -> t) -> m b
h mx k f = mx >>= \x -> k (f x)
l0 = h (return 3) id (\x -> return x)
l1 = h (return 3) (h (return 4) id) (\x y -> return x)
l2 = h (return 3) (h (return 4) (h (return 5) id)) (\x y z -> return x)
也许解决方案涉及另一个延续?
这是一个需要额外加入的想法......
-- if not using Control.Monad, use this
join :: Monad => ( α) -> α
join mx = mx >>= id
-- idea: get side effects of evaluating first arguments first
h' mz k f = k f >>= \f' -> mz >>= (return . f')
l1' = h' (return 3) return
unary = join (l1' (\x -> return x))
l2' = h' (return 4) l1'
binary = join (l2' (\x y -> return x))
l3' = h' (return 5) l2'
ternary = join (l3' (\x y z -> return x))
答案 0 :(得分:1)
如果你想表达这个:
ap_variadic mx f = mx >>= f
ap_variadic mx my f = do { x <- mx; y <- my; f x y }
我会改用Control.Applicative
。然后:
join (f <$> mx)
join (f <$> mx <*> my)
join (f <$> mx <*> my <*> mz)
我认为这比任何多变量解决方案都更好(更简单,更易于维护)。