-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtodo.bl
More file actions
96 lines (81 loc) · 2 KB
/
todo.bl
File metadata and controls
96 lines (81 loc) · 2 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// todo.bl — Structs, enums, traits, error handling
//
// Demonstrates: type (struct/enum), trait, impl, Result,
// List[T], pattern matching
type Status {
Open
Done
}
type Todo {
title: Str
status: Status
}
type TodoError {
NotFound(id: Int)
}
trait Display {
fn display(self) -> Str
}
impl Display for Status {
fn display(self) -> Str {
match self {
Open => "[ ]"
Done => "[x]"
}
}
}
impl Display for Todo {
fn display(self) -> Str {
let s = self.status
"{s.display()} {self.title}"
}
}
/// Add a new todo to the list.
fn add(todos: List[Todo], title: Str) {
let todo = Todo { title: title, status: Status.Open }
todos.push(todo)
}
/// Mark a todo as done by index. Returns the updated title or error.
fn complete(todos: List[Todo], index: Int) -> Result[Str, TodoError] {
let opt = todos.get(index)
if opt.is_none() {
return Err(TodoError.NotFound(index))
}
let todo = opt.unwrap()
let updated = Todo { title: todo.title, status: Status.Done }
todos.set(index, updated)
Ok(todo.title)
}
/// Print all todos.
fn print_todos(todos: List[Todo]) {
for todo in todos {
io.println(todo.display())
}
}
fn main() {
let todos: List[Todo] = []
add(todos, "Write Blink spec")
add(todos, "Build compiler")
add(todos, "Ship v1")
complete(todos, 0).unwrap()
print_todos(todos)
}
test "add creates open todo" {
let todos: List[Todo] = []
add(todos, "Test task")
assert_eq(todos.len(), 1)
assert_eq(todos.get(0).unwrap().title, "Test task")
assert_eq(todos.get(0).unwrap().status, Status.Open)
}
test "complete marks done" {
let todos: List[Todo] = []
add(todos, "Task")
let result = complete(todos, 0)
assert(result.is_ok())
assert_eq(todos.get(0).unwrap().status, Status.Done)
}
test "complete out of bounds" {
let todos: List[Todo] = []
let result = complete(todos, 5)
assert(result.is_err())
}