Commands
.
update
cannot touch the outside world. So how does a program read a file, ask a server, or roll a die? It returns a command
: a value that says what it wants done. The runtime does it, and the result comes back as a message.Note:
In the loop, commands are how update
reaches the outside world, once, and gets an answer. For things that keep happening, see Subscriptions. Step 4 of the tutorial adds a command to a growing app. Dice
Live: this is the program below, running
?
Roll
Roll 50
0
0
0
0
0
0
0
rolls, average
0.0
Press Roll a few times, then Roll 50. The bars count how often each face came up, so the die's odds draw themselves.
examples/src/core/dice.silk
Copy
//! Dice: a command asks the outside world for a random number, and a message brings it back.
//! The program keeps count of what came up, so a few hundred rolls draw the die's odds.
import
core.look { ACCENT
, INK
, LINE
, MUTED
, button, primary, rgb }
import
loom.css
import
loom.css { px, Align
, BorderStyle
, BoxSizing
, FlexWrap
}
import
loom.lib { CommandSet
, Document
, Node
, NoOutput
, Program
, Update
}
import
silk.collections.list { List
}
import
silk.core.option { Option
}
import
silk.mem.allocator { Allocator
, OutOfMemoryError
}
import
silk.num.i64
import
silk.num.u32
import
silk.num.u64
import
silk.num.usize
import
silk.system.random { Random
}
pub
struct
Dice
{
/// The face that is up; zero before the first roll.
pub
face: u32,
pub
rolls: i64,
/// How many rolls were asked for and have not come back yet.
pub
waiting: u32,
/// How often each face came up: `counts[0]` is for the one.
pub
counts: [i64; 6
],
}
pub
union
Message
{
ClickedRoll
,
ClickedRollMany
,
Rolled
{ pub
face: u32 },
}
/// What the program asks to have done.
pub
union
Command
{
Roll
{ pub
sides: u32 },
}
impl
CommandSet
<Message
? &mut
Random
> for
Command
{
/// Does the work of a command and says how it ended. This is the only code of the program
/// that touches the outside world.
effect
fn
execute
(self: Self
) -> Message
! OutOfMemoryError
? &mut
Random
{
match
move
self {
Command
.Roll
{ sides } => {
return
Message
.Rolled
{ face: run
roll
(sides) }
}
}
}
}
/// A face from 1 to `sides`, each as likely as the others. `Random` is the standard library's
/// service for random numbers: the program only says it needs one, and the browser, a native app
/// and a test each provide their own.
effect
fn
roll
(sides: u32) -> u32 ? &mut
Random
{
return
match
run
Random
.below
(u32.toU64
(sides)) {
Option
<u64>.Some
{ value } => u64.toU32
(value) + 1
Option
<u64>.None
=> 0
}
}
type
Next
= Update
<Dice
, Command
, NoOutput
>
/// How many rolls "Roll 50" asks for.
const
MANY
: u32 = 50
impl
Program
<Message
, Command
> for
Dice
{
effect
fn
init
() -> Next
! OutOfMemoryError
? &mut
Allocator
{
return
Next
.of
(Dice
{ face: 0
, rolls: 0
, waiting: 0
, counts: [0
, 0
, 0
, 0
, 0
, 0
] })
}
effect
fn
update
(mut
model: Dice
, message: Message
) -> Next
! OutOfMemoryError
? &mut
Allocator
{
match
move
message {
Message
.ClickedRoll
=> {
model.waiting = model.waiting + 1
return
run
Next
.with
(move
model, Command
.Roll
{ sides: 6
})
}
Message
.ClickedRollMany
=> {
let
mut
commands = run
List
<Command
>.makeWithCapacity
(u32.toUsize
(MANY
))
let
mut
i: u32 = 0
while
i < MANY
{
run
commands.append
(Command
.Roll
{ sides: 6
})
i = i + 1
}
model.waiting = model.waiting + MANY
return
Next
.batch
(move
model, move
commands)
}
Message
.Rolled
{ face } => {
model.face = face
model.rolls = model.rolls + 1
model.waiting = model.waiting - 1
let
at = u32.toUsize
(face - 1
)
model.counts[at] = model.counts[at] + 1
}
}
return
Next
.of
(move
model)
}
fn
view
(model: &Dice
, h: &Document
<Message
>) -> Node
{
return
h.row
(
&[
h.style
(
&[
css.alignItems
(Align
.Center
),
css.columnGap
(px
(24.0
)),
css.rowGap
(px
(16.0
)),
css.flexWrap
(FlexWrap
.Wrap
),
css.padding
(px
(16.0
)),
css.color
(rgb
(INK
)),
],
),
],
&[
h.column
(
&[h.style
(&[css.alignItems
(Align
.Center
), css.rowGap
(px
(12.0
))])],
&[
h.box
(&[h.testId
("face"
), h.label
(FACES
[u32.toUsize
(model.face)])], &[die
(h, model.face, 72.0
)]),
h.row
(
&[h.style
(&[css.columnGap
(px
(8.0
))])],
&[
primary
(h, "Roll"
, Message
.ClickedRoll
),
button
(h, "Roll 50"
, Message
.ClickedRollMany
),
],
),
],
),
h.column
(
&[h.style
(&[css.rowGap
(px
(8.0
)), css.flexGrow
(1.0
), css.minWidth
(px
(220.0
))])],
&[
h.row
(
&[h.style
(&[css.columnGap
(px
(8.0
)), css.alignItems
(Align
.End
), css.height
(px
(BARS
+ 48.0
))])],
&[
bar
(h, model, 1
),
bar
(h, model, 2
),
bar
(h, model, 3
),
bar
(h, model, 4
),
bar
(h, model, 5
),
bar
(h, model, 6
),
],
),
h.row
(
&[h.style
(&[css.columnGap
(px
(4.0
)), css.color
(rgb
(MUTED
)), css.fontSize
(px
(13.0
))])],
&[
h.box
(&[h.testId
("rolls"
)], &[h.number
(model.rolls)]),
h.box
(&[], &[h.text
("rolls, average"
)]),
h.box
(&[], &[average
(h, model)]),
],
),
],
),
],
)
}
}
const
FACES
: [string<'static
>; 7
] = ["Not rolled"
, "One"
, "Two"
, "Three"
, "Four"
, "Five"
, "Six"
]
/// The height of the tallest bar.
const
BARS
: f32 = 72.0
/// The most often any face came up. The bars are drawn against it.
fn
most
(model: &Dice
) -> i64 {
let
mut
most: i64 = 1
let
mut
i: usize = 0
while
i < 6
{
if
model.counts[i] > most {
most = model.counts[i]
}
i = i + 1
}
return
most
}
/// One face's bar: its count, a bar as tall as its share, and a small die under it.
fn
bar
(h: &Document
<Message
>, model: &Dice
, face: u32) -> Node
{
let
count = model.counts[u32.toUsize
(face - 1
)]
let
height = BARS
* i64.toF32
(count) / i64.toF32
(most
(model))
return
h.column
(
&[h.style
(&[css.alignItems
(Align
.Center
), css.rowGap
(px
(4.0
)), css.flexGrow
(1.0
), css.flexBasis
(px
(0.0
))])],
&[
h.box
(&[h.style
(&[css.fontSize
(px
(11.0
)), css.color
(rgb
(MUTED
))])], &[h.number
(count)]),
h.box
(
&[
h.style
(
&[
css.alignSelf
(Align
.Stretch
),
css.height
(px
(height)),
css.borderRadius
(px
(4.0
)),
css.backgroundColor
(
rgb
(
if
face == model.face {
ACCENT
} else
{
0x99D5CF
},
),
),
],
),
h.transition
("height 180ms ease, background-color 180ms ease"
),
],
&[],
),
die
(h, face, 18.0
),
],
)
}
/// The average of every roll so far, to one decimal place.
fn
average
(h: &Document
<Message
>, model: &Dice
) -> Node
{
if
model.rolls == 0
{
return
h.text
("0.0"
)
}
let
mut
sum: i64 = 0
let
mut
i: usize = 0
while
i < 6
{
sum = sum + model.counts[i] * (usize.toI64
(i) + 1
)
i = i + 1
}
let
tenths = (sum * 10
+ model.rolls / 2
) / model.rolls
return
h.row
(&[], &[h.number
(tenths / 10
), h.text
("."
), h.number
(tenths % 10
)])
}
/// Whether a face has a pip in a cell of its three by three grid, counted row by row.
fn
pip
(face: u32, cell: u32) -> bool {
if
cell == 4
{
return
face == 1
|| face == 3
|| face == 5
}
if
cell == 0
|| cell == 8
{
return
face >= 2
}
if
cell == 2
|| cell == 6
{
return
face >= 4
}
if
cell == 3
|| cell == 5
{
return
face == 6
}
return
false
}
/// A die of `size` pixels with `face` up, drawn with pips. Face zero is a die not rolled yet.
fn
die
(h: &Document
<Message
>, face: u32, size: f32) -> Node
{
return
h.column
(
&[
h.style
(
&[
css.width
(px
(size)),
css.height
(px
(size)),
css.boxSizing
(BoxSizing
.BorderBox
),
css.padding
(px
(size * 0.14
)),
css.justifyContent
(Align
.SpaceBetween
),
css.borderWidth
(px
(1.0
)),
css.borderStyle
(BorderStyle
.Solid
),
css.borderColor
(rgb
(LINE
)),
css.borderRadius
(px
(size * 0.2
)),
css.backgroundColor
(rgb
(0xFFFFFF
)),
],
),
],
&[
if
face == 0
{
h.row
(
&[
h.style
(
&[
css.flexGrow
(1.0
),
css.alignItems
(Align
.Center
),
css.justifyContent
(Align
.Center
),
css.fontSize
(px
(size * 0.4
)),
css.color
(rgb
(MUTED
)),
],
),
],
&[h.text
("?"
)],
)
} else
{
h.fragment
(&[pips
(h, face, 0
, size), pips
(h, face, 3
, size), pips
(h, face, 6
, size)])
},
],
)
}
/// One row of a die's grid, starting at cell `from`.
fn
pips
(h: &Document
<Message
>, face: u32, from: u32, size: f32) -> Node
{
return
h.row
(
&[h.style
(&[css.justifyContent
(Align
.SpaceBetween
)])],
&[dot
(h, pip
(face, from), size), dot
(h, pip
(face, from + 1
), size), dot
(h, pip
(face, from + 2
), size)],
)
}
fn
dot
(h: &Document
<Message
>, on: bool, size: f32) -> Node
{
return
h.box
(
&[
h.style
(
&[
css.width
(px
(size * 0.18
)),
css.height
(px
(size * 0.18
)),
css.borderRadius
(px
(size)),
css.backgroundColor
(
rgb
(
if
on {
INK
} else
{
0xFFFFFF
},
),
),
],
),
],
&[],
)
}Asking
examples/src/core/dice.silk
Copy
effect
fn
update
(mut
model: Dice
, message: Message
) -> Next
! OutOfMemoryError
? &mut
Allocator
{
match
move
message {
Message
.ClickedRoll
=> {
model.waiting = model.waiting + 1
return
run
Next
.with
(move
model, Command
.Roll
{ sides: 6
})
}
Message
.ClickedRollMany
=> {
let
mut
commands = run
List
<Command
>.makeWithCapacity
(u32.toUsize
(MANY
))
let
mut
i: u32 = 0
while
i < MANY
{
run
commands.append
(Command
.Roll
{ sides: 6
})
i = i + 1
}
model.waiting = model.waiting + MANY
return
Next
.batch
(move
model, move
commands)
}
Message
.Rolled
{ face } => {
model.face = face
model.rolls = model.rolls + 1
model.waiting = model.waiting - 1
let
at = u32.toUsize
(face - 1
)
model.counts[at] = model.counts[at] + 1
}
}
return
Next
.of
(move
model)
}When Roll is clicked,
update
does not roll anything. It counts one more roll it is waiting for, and returns the model with a command next to it:Silk
Copy
return
run
Next
.with
(move
model, Command
.Roll
{ sides: 6
})A command is plain data, like a message.
update
is still a function you can call with a model and a message and compare the answer.To return
Write
A model and nothing else
Next.of(model)
A model and one command
run Next.with(model, command)
A model and several commands
Next.batch(model, commands)
Roll 50 is the last row: one update returns fifty commands, and fifty
Rolled
messages come back, one at a time. Nothing else in the program changes for it.init
returns the same thing, so a program can start with commands: load the saved state, ask for the first page of data.Doing
examples/src/core/dice.silk
Copy
impl
CommandSet
<Message
? &mut
Random
> for
Command
{
/// Does the work of a command and says how it ended. This is the only code of the program
/// that touches the outside world.
effect
fn
execute
(self: Self
) -> Message
! OutOfMemoryError
? &mut
Random
{
match
move
self {
Command
.Roll
{ sides } => {
return
Message
.Rolled
{ face: run
roll
(sides) }
}
}
}
}execute
is where a command becomes work. It runs after update
returns. It does the work, and it returns the message that says how the work ended. That message goes to update
like any other.This is the only part of a program that reaches outside, and it is small on purpose.
A command always ends in a message, so a command that can fail says so in its message. A program that loads a file has
LoadedFile { text }
and FailedToLoadFile
, and update
handles both.Services
examples/src/core/dice.silk
Copy
/// A face from 1 to `sides`, each as likely as the others. `Random` is the standard library's
/// service for random numbers: the program only says it needs one, and the browser, a native app
/// and a test each provide their own.
effect
fn
roll
(sides: u32) -> u32 ? &mut
Random
{
return
match
run
Random
.below
(u32.toU64
(sides)) {
Option
<u64>.Some
{ value } => u64.toU32
(value) + 1
Option
<u64>.None
=> 0
}
}execute
does not call a random number generator directly. It asks for a service
: Random
, from the standard library's silk.system.random
. The signature of execute
lists what it needs after the ?
:Silk
Copy
effect
fn
execute
(self: Self
) -> Message
! OutOfMemoryError
? &mut
Random
The program says what it needs and not where it comes from. Whoever starts the program provides it, once:
Where the program runs
Who provides
Random
In this page
OsRandom
, which asks the browser's crypto.getRandomValues
In a native app
OsRandom
too, which asks the operating systemIn a test
A struct that always gives the same bytes, so the die lands on 4
That last line is the point. Here is the test for this program. It decides what the die says, then checks what the program made of one roll and of fifty.
tests/src/core.silk
Copy
/// A die that always lands on the same face, and counts how often it was asked. Each read gives
/// the number `byte`, and on six sides 9 lands on 4 (9 is 3 past a multiple of 6, and faces
/// count from 1).
struct
Loaded
{
byte: u8,
asked: u32,
}tests/src/core.silk
Copy
impl
Random
for
Loaded
{
effect
fn
fillBytes
(self: &mut
Self
, output: &mut
[u8]) -> () {
self.asked = self.asked + 1
let
mut
index: usize = 0
while
index < output.length {
output[index] = 0
index = index + 1
}
output[0
] = self.byte
}
}tests/src/core.silk
Copy
effect
fn
diceBody
() -> ()
! AssertionError
<'static
> | TreeError
| OutOfMemoryError
? &mut
Random
| &mut
Allocator
{
let
mut
page = Html
.make
()
let
mut
app = run
program.make<Dice
, DiceMessage
, DiceCommand
>()
run
app.start
(&mut
page, 0.0
)
run
drain
(&mut
app, &mut
page)
app.send
(DiceMessage
.ClickedRoll
)
run
drain
(&mut
app, &mut
page)
run
Testing
.expect
(app.model.value.face == 4
, "the face is the one the die gave"
)
run
Testing
.expect
(app.model.value.rolls == 1
&& app.model.value.waiting == 0
, "after one roll"
)
app.send
(DiceMessage
.ClickedRollMany
)
run
drain
(&mut
app, &mut
page)
run
Testing
.expect
(app.model.value.rolls == 51
, "one update can ask for fifty rolls"
)
run
Testing
.expect
(app.model.value.counts[3
] == 51
, "and every one of them is counted"
)
}tests/src/core.silk
Copy
test
effect
fn
aRollAsksTheDie
() -> ()
! AssertionError
<'static
> | TreeError
| OutOfMemoryError
{
let
mut
allocator = Allocator
.systemAllocatorProvider
()
let
mut
die = Loaded
{ byte: 9
, asked: 0
}
run
diceBody
()
|> Effect
.provideMut<Random
>(&mut
die)
|> Effect
.provideMut<Allocator
>(&mut
allocator)
run
Testing
.expect
(die.asked == 51
, "one command ran for each roll"
)
}Effect.provideMut<Random>(&mut die)
is the line that hands the program its service. In the browser shows the same line with a real die.Work that takes a while
A command runs to its end before the next message is handled, so a command should be quick. For work that takes a while, such as a network request or a long computation, the command
starts
the work and returns. The result arrives later through a port
, which is a kind of subscription.Background work builds a whole program around that.
Recap
•
update
returns a command as a value. The runtime runs it afterward.•
A command always ends in one message, which goes to
update
.•
execute
reaches the world only through services it names. Whoever starts the program provides them.•
A different service in a test is all it takes to control the outside world.
Next: Subscriptions.