control-dsl-0.2.1.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 as the updated state.

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

append returns a Cont, which can be used in other do blocks.

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"