Actions and do blocks
Values of type IO, the do blocks that sequence them in any monad, IO/loop, and how omegyu run carries an action out.
A value of type IO a describes an interaction with the world that
produces an a. Computing it does nothing: omegyu run carries it out. An
action can produce a value of any universe, a type included, and lives in
the universe of what it produces:
IO/pure NaturalType
IO Typedo blocks
do {
IO/putStr "What is your name? ";
answer <- IO/getLine;
let name =
merge { None = "stranger", Some = \(n : Text) -> n } answer;
IO/putStr "Hello, ${name}!\n"
}Output
What is your name? Hello, Ada!The statements of a block are separated by semicolons. The first ; above ends the prompt:
x <- acarries out the actionaand names its resultx, andx : T <- aalso gives the type of the result.let x = eis a definition for the rest of the block.An expression alone is an action whose result is not named.
The last statement is an expression: the result of the block. In the next example it is IO/putStr "b". A block is
short for IO/bind: do { x <- a; b } is IO/bind a (\x -> b).
do {
IO/putStr "a";
IO/putStr "b"
}Elaborated term
IO/bind @0 @0 @unit @unit (IO/putStr "a") (\(_ : unit) -> IO/putStr "b")Blocks in other monads
A block works in any monad whose operations are given as a record
{ pure, bind } after do. Here the block uses std:Monad.optional:
do std:Monad.optional {
x <- Natural/parse "1";
y <- Natural/parse "2";
Some (x + y)
}Normal form
Some 3There are no type classes: the record is an ordinary value. A record written in that position is written between parentheses:
do ({ pure = std:Monad.optional.pure
, bind = std:Monad.optional.bind
}) {
x <- Some 1;
Some (x + 1)
}Normal form
Some 2Loops
IO/loop has type s -> (s -> IO (Optional s)) -> IO s for a state type s. It repeats a step for as long
as the step returns a new state, which may hold types. It is the only way
to write a program that runs for an unbounded time. This program adds the
numbers that it reads, one per line, until the end of its input. total holds the running sum:
IO/loop
0
(\(total : Natural) ->
do {
line <- IO/getLine;
merge
{ None =
do {
IO/putStr "${Natural/show total}\n";
IO/pure (None Natural)
}
, Some =
\(text : Text) ->
IO/pure
(Some
(total
+ std:Optional.default 0 (Natural/parse text)))
}
line
})Output
12The state is put in normal form as the loop goes, including the parts that no step looks at, so a loop that runs for long does not keep its past steps in memory.
Running a program
omegyu run FILE checks the program, then carries out its action.
IO/getLine reads a line of the standard input, and gives None at its
end. IO/args gives the arguments after --, IO/getEnv reads an
environment variable, and IO/readFile and IO/writeFile read and write
files:
$ omegyu run examples/fizzbuzz.omg -- 5
1
2
Fizz
4
BuzzIO/exit n stops the program, and omegyu run exits with the status n.
In the playground, files are kept in memory and there is
no environment.