Scrapbook-0.4.0: code examples
Copyright© Frank Jung 2020
LicenseGPL-3
Safe HaskellSafe-Inferred
LanguageHaskell2010

Cps

Description

Example from Wikibooks Continuation Passing Style

This uses the Cont Monad from the transformers package.

Using callCC is better than using return as argument it returns a suspended computation.

A function of type a -> b would become a -> (b -> r) -> r in CPS, where b -> r is the continuation.

Synopsis

Types

newtype CPS a Source #

Type CPS for Continuation-passing style.

See CpsSpec.hs for usage.

Constructors

CPS 

Fields

  • runCPS :: forall r. (a -> r) -> r
     

Instances

Instances details
Applicative CPS Source #

Application instance for CPS.

Instance details

Defined in Cps

Methods

pure :: a -> CPS a #

(<*>) :: CPS (a -> b) -> CPS a -> CPS b #

liftA2 :: (a -> b -> c) -> CPS a -> CPS b -> CPS c #

(*>) :: CPS a -> CPS b -> CPS b #

(<*) :: CPS a -> CPS b -> CPS a #

Functor CPS Source #

Functor instance for CPS.

Instance details

Defined in Cps

Methods

fmap :: (a -> b) -> CPS a -> CPS b #

(<$) :: a -> CPS b -> CPS a #

Monad CPS Source #

Monad instance for CPS.

Instance details

Defined in Cps

Methods

(>>=) :: CPS a -> (a -> CPS b) -> CPS b #

(>>) :: CPS a -> CPS b -> CPS b #

return :: a -> CPS a #

Custom continuation passing style (CPS)

toCPS :: a -> forall r. (a -> r) -> r Source #

Custom continuation passing style.

The following example uses a custom continuation-passing style (CPS) to demonstrate the general concept.

This converts any value into a suspended computation.

flip ($) :: b -> (b -> c) -> c

Longhand this is: toCPS a = k -> k a

Or more simply as: toCPS a k = k a

fromCPS :: (forall r. (a -> r) -> r) -> a Source #

From custom continuation.

The following example calls the continuation function with id.

Passing id to the continuation function will return the value.

($ id) :: ((a -> a) -> b) -> b

Longhand this is: fromCPS f = f id

CPS Function Examples

addCont :: Int -> Int -> Cont r Int Source #

Continuation passing style (CPS) examples.

The following uses the Cont Monad from the transformers package.

Continuation for add function.

pythagorasCont :: Int -> Int -> Cont r Int Source #

Continuation for pythagoras function.

releaseString :: String Source #

Return version, timestamp and OS as pyramid of doom.

releaseStringCPS :: CPS String Source #

Return version, timestamp and OS using the CPS type.

squareCont :: Int -> Cont r Int Source #

Continuation for square function.

withOS :: (String -> r) -> r Source #

Returns (fixed) OS.

withTimestamp :: (Int -> r) -> r Source #

Returns (fixed) timestamp.

withVersionNumber :: (Double -> r) -> r Source #

Returns (fixed) version.