control-dsl-0.2.0.1: An alternative to monads

Safe HaskellSafe
LanguageHaskell2010

Control.Dsl.State

Description

This module provides keywords to Put and Get the value of multiple mutable variables in a do block.

Synopsis

Documentation

type State = (->) Source #

The type that holds states, which is defined as a plain function.

Examples

Expand
>>> :set -XFlexibleContexts
>>> :set -XTypeApplications
>>> :set -XRebindableSyntax
>>> import Prelude hiding ((>>), (>>=), return, fail)
>>> import Control.Dsl
>>> import Control.Dsl.Cont
>>> import Control.Dsl.Shift
>>> import Control.Dsl.State
>>> import Data.Sequence (Seq, (|>))
>>> import qualified Data.Sequence
>>> import Data.Foldable

The following append function Gets a Seq String state, appends s to the Seq, and Puts the new Seq to the updated state.

>>> :{
append s = do
  buffer <- Get @(Seq String)
  Put $ buffer |> s
  Cont ($ ())
:}

($ ()) creates a CPS function , which can be then converted to Conts.

A formatter appends String to its internal buffer, and return the concatenated buffer.

>>> :{
formatter = do
  append "x="
  d <- Get @Double
  append $ show d
  append ",y="
  i <- Get @Integer
  append $ show i
  buffer <- Get @(Seq String)
  return $ concat buffer
:}
>>> x = 0.5 :: Double
>>> y = 42 :: Integer
>>> initialBuffer = Data.Sequence.empty :: Seq String
>>> formatter x y initialBuffer :: String
"x=0.5,y=42"

Note that formatter accepts arbitrary order of the parameters, or additional unused parameters.

>>> formatter "unused parameter" initialBuffer y x :: String
"x=0.5,y=42"