-
Notifications
You must be signed in to change notification settings - Fork 1
/
act_test.gleam
49 lines (42 loc) · 1.71 KB
/
act_test.gleam
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//// This is a basic example of how to use `act`. Make sure to look up any
//// functions in the docs that you're unfamiliar with!
import gleam/int
import gleam/io
// The `Action` type and `do` function are imported unqualified since they are
// so common.
import act.{type Action, do}
import act/state
// Our state is simply an integer that we'll increment. In a real program, this
// could be anything used as state—maybe a list or custom type.
type State =
Int
// Here, `increment` is an action that returns Nil. That's because there's no
// real value that makes sense to return from the action. When an action only
// changes state and doesn't return a value, we return Nil. This is similar to
// functions that only do side effects in Gleam, such as `io.println`.
fn increment(by num: Int) -> Action(Nil, State) {
io.println("I'm gonna update the state...")
use <- state.update(int.add(_, num))
io.println("...updated!")
use state <- state.get()
io.println("The state is now " <> int.to_string(state))
act.return(Nil)
}
// `steps` is an action that returns an Int
fn steps() -> Action(Int, State) {
use _ <- do(increment(by: 2))
use _ <- do(increment(by: 3))
use incremented <- state.get()
io.println("Returning & resetting the state to 0...")
use <- state.set(0)
act.return(incremented)
}
pub fn main() {
let initial_state = 4
// Notice how we've called `steps` with two sets of parenthesis. This is on
// purpose! `steps` is a function that *returns* a function (the action), so
// we have to call the returned action too.
let #(final_state, result) = steps()(initial_state)
io.println("The result is " <> int.to_string(result))
io.println("The state is " <> int.to_string(final_state))
}