下面的代码尝试编写一个可变参数函数,其行为如下:
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))