Moggi documentation

IO and effects

Moggi separates computation from effect. A pure function returns a value; a function that talks to the world returns IO a, where a is what it produces. An IO a value is a description of effects — building one does nothing. main is the description the runtime executes.

main :: IO ()
main = do
  putStr "a"
  putStrLn "b"
  putStrLn (show (1 :: Int))
ab
1

The lines run in the order written, and putStr "a" really does write before putStrLn "b". There is no deferred evaluation to reorder them: evaluation is strict, and do sequences actions in bind order.

print x is putStr (show x): it adds no trailing newline. Write putStrLn (show x) when you want a line.

do notation

do is sugar for >>= and >>, with two extra forms:

import System.Environment (getArgs)

main :: IO ()
main = do
  args <- getArgs                       -- run it and bind the result
  let count = length args               -- a pure binding, no `in`
  putStrLn (show count <> " argument(s)")  -- run it, discard the result
  pure ()                                -- an action that does nothing

The last statement is the block’s result, so a do block of type IO () normally ends with pure () or with an action that returns ().

do works for any type with a Monad instance, not only IO (Classes); for IO the sequencing is the effect order.

main and the entry point

main is the entry point of the module compiled as the program. It must be an IO action for the program to have an entry:

main :: IO Int
main = pure 42

This compiles and runs; the 42 is discarded. main :: IO a is accepted for any a, so a function can return a value nobody reads.

A main of a non-IO type is not rejected, but it is not an entry point either — moggi run reports that there is nothing to run:

error: no entry `main` found to run

If you see that message with a main in the file, its type is the reason.

The purity boundary

IO may appear only as the result of a function that performs effects. It cannot be stored in a data type, a record field or a tuple:

data X = X (IO ())
Main.mog:1:13: type error: IO values are forbidden outside an IO-returning function

The rule is what keeps “pure” meaningful: a function whose signature has no IO cannot perform effects, directly or by unpacking one, and there is no IO value to pattern-match on. The one way across the line is unsafePerformIO, whose name is the warning.

Running an action from pure code

import System.IO.Unsafe

answer :: Int -> Int
answer n = unsafePerformIO (pure (n + n))

unsafePerformIO :: IO a -> a runs the action and answers its result. The action runs when the expression is evaluated: inside a function body that is on every call, and in a top-level binding when the binding is initialised.

Use it only where the effect is invisible to the rest of the program or happens once by construction: a memo table, an identifier supply, a counter that pure code reads. It does not make the effect pure, and the type of a function that uses it no longer describes what that function does. Four consequences to plan for:

When the effect is local, ST says so in the type and needs no promise; when it is not local, the code belongs in IO.

In a foreign declaration, IO may appear only outermost in the result (FFI).

Advanced from here. Local mutation is a separate tool from IO, needed by some algorithms and avoidable in most programs. Skip to the next page if your program only reads input, writes output and returns values.

Local mutation with ST

Some algorithms want a mutable cell or array without touching the world. ST is a thread of local mutation that is run purely: runST turns an ST s a into an a, and the compiler refuses any thread whose cell could escape.

import Control.Monad.ST
import Data.STRef

answer :: ST s Int
answer = do
  ref <- newSTRef 41
  modifySTRef ref (+ 1)
  readSTRef ref

main :: IO ()
main = putStrLn (show (runST answer))
42

STRef s a is a cell in thread s. The thread variable keeps one run’s cells apart from another’s, and runST requires that s does not appear in the result. A cell that would escape is rejected:

Main.mog:6:1: type error: ST values are forbidden outside an ST-returning function

For a loop, pass the cell to a recursive helper. A top-level function keeps the helper’s signature and guards out of the do block:

import Control.Monad.ST
import Data.STRef

total :: Int -> STRef s Int -> Int -> ST s Int
total n ref i
  | i > n = readSTRef ref
  | otherwise = do
      x <- readSTRef ref
      writeSTRef ref (x + i)
      total n ref (i + 1)

sumTo :: Int -> Int
sumTo n = runST do
  ref <- newSTRef 0
  total n ref 1

main :: IO ()
main = putStrLn (show (sumTo 10))
55

stToIO runs a RealWorld thread as an IO action when the mutation has to meet the outside world:

import Control.Monad.ST
import Data.STRef

main :: IO ()
main = do
  x <- stToIO do
    ref <- newSTRef 1
    modifySTRef ref (+ 1)
    readSTRef ref
  putStrLn (show x)
2

Mutable arrays use the same split: Data.Array is immutable, Data.Array.ST and Data.Array.IO are the mutable variants, and Data.Array.MArray is the class over both. They live in the array package, which is a separate library root (Standard library).

IO or ST?

Need Use
Read or write the world: files, arguments, console, clock IO
A mutable cell or array inside one pure function ST
Mutation whose result must be visible to IO ST with stToIO, or IO directly
A value that outlives the computation neither: a cell cannot escape its run

Limits

Where next


Moggi compiles to PHP, the JVM and .NET. This site is generated from docs/ in the moggi-lang/moggi repository; the same pages are readable there as Markdown.