我完成了 Oleg 的定界延续教程:
newtype Cont r a = Cont{runCont :: (a -> r) -> r}
instance Monad (Cont r) where
return x = Cont (\k -> k x)
Cont m >>= f = Cont (\k -> m (\v -> runCont (f v) k))
runC :: Cont r r -> r
runC m = runCont m id
reset :: Cont a a -> Cont r a
reset = return . runC
shift :: ((a -> r) -> Cont r r) -> Cont r a
shift f = Cont (runC . f)
liftM2 (-)
(reset
(liftM2 (+) (return 3)
(shift (\k -> return (5*2))))) -- drop the continuation
(return 1) -- 9
由于延续基本上是函数并且reset
/shift
甚至不是 monad api 的一部分,我想知道如何在没有newtype
and monad 机制的情况下实现分隔延续。
到目前为止,这是我想出的:
reset :: Cont a a -> Cont r a -- becomes
reset :: ((a -> a) -> a) -> (a -> r) -> r
reset k f = f $ k id
shift :: ((a -> r) -> Cont r r) -> Cont r a -- becomes
shift :: ((a -> r) -> (r -> r) -> r) -> (a -> r) -> r
shift f k = f k id
我很确定这是完全错误的,如果不是,我不知道如何正确应用运算符:
(1-) (reset ((3+) (shift (\k -> 5*2)))) -- yields
• Non type-variable argument in the constraint: Num ((a -> a) -> a)
(Use FlexibleContexts to permit this)
• When checking the inferred type
t1 :: forall a r.
(Num ((a -> a) -> a), Num ((a -> r) -> r)) =>
(a -> r) -> r