Can "Cont r a" process the result of its continuation
Type Cont r adenotes a function that takes a continuation a->rand produces the result of the type r. Thus, both the continuation and the whole Cont r aproduce a result of the same type r.
My question is: do both results necessarily have the same value, or can they Cont r aprocess the result from a continuation and produce a different value, although of the same type r?
I tried to use (+1)for post processing (pay attention to + 1 --<--):
c1 :: Int -> Cont r Int
c1 x = let y = 2*x
in cont $ \k -> (k y) + 1 --<--
Now this is not typecheck, because my post-processing function (+1)accepts only an argument whose type belongs to the class Num. However, I pass the result of the continuation (k y), which is of some type r, which is not guaranteed to belong to the class Num.
Whatever I do with (k y), it should be a type function r->r. The only function that can do this for everyone ris a function id, and use idfor post processing is not post processing at all.
However, it is all a matter of typecheck if I restrict it to a rtype class Numor even a specific type Int. Then it gives the expected result:
*Main> runCont (c1 1) id
3
I'm completely unsure
- -
r, , rr,r.
- ?
, , . Cont r a to Num r => Cont r a , Reader r a to Num r => Reader r a.
, CPS () , , - , , , !
, , , , , :
mapCont :: (r -> r) -> Cont r a -> Cont r a
r, id , , .
c1 mapCont :
c2 :: (Num r) => Int -> Cont r Int
c2 x = mapCont (+1) $ return (2*x)
:
> runCont (c2 10) id
21
> runCont (c2 10) (const 5)
6
> runCont (c2 10) show
... No instance for (Num String) arising from a use of 'c2' ...
, , . . , ( -):
override x = cont (const x)
:
> runCont (return 2 >>= \x -> cont (\f -> f (x*3))) id
6
> runCont (return 2 >> override 1000 >>= \x -> cont (\f -> f (x*3))) id
1000
>
, :
annotate note comp = mapCont (\(a, w) -> (a, note:w)) comp
:
runCont (annotate "two" (return 2)
>>= \x -> annotate "times three" (cont (\f -> f (x*3))))
(\a -> (a, []))
:
(6,["two","times three"])
.