AtlatestRepositorysigil-doc
sigil-doc / tree / book / practical-sigil01-useful-first-script.sgd
1
#lang sigil/doc/book2
@chapter["A Useful First Script" authors: '("David Wilson")]4
@section["Begin with a Question" id: "first-script"]6
Small programs are where a language earns trust. We will craft a task report7
that reads a plain text file, counts unfinished work, and prints a useful8
summary. It is modest enough to understand in one sitting, but real enough to9
exercise files, strings, lists, functions, and command-line behavior.11
@p {Create a file named @code{tasks.txt}:}13
@code["text"]14
TODO Write the first Practical Sigil chapter15
DONE Sketch the report format16
TODO Share the result17
@end code19
The program starts by turning the file into lines and asking whether each line20
begins with the state we care about.22
@code["sigil"]23
(import (sigil core) (sigil fs) (sigil string))25
(define (task? state line)26
(string-starts-with? line (string-append state " ")))28
(define (count-tasks state lines)29
(length (filter (lambda (line) (task? state line)) lines)))30
@end code32
This is ordinary Scheme-shaped code, but it is directed at practical work.33
There is no framework to adopt and no object hierarchy to satisfy. Data enters34
as strings and lists, and the small functions say exactly how it changes.36
@section["Craft the Report" id: "craft-the-report"]38
Now give the script a boundary: read the file, split it into lines, and display39
the result.41
@code["sigil"]42
(define lines43
(string-split (read-file-string "tasks.txt") "\n"))45
(display "Open tasks: ")46
(display (count-tasks "TODO" lines))47
(newline)48
@end code50
Run it and the answer is immediate:52
@code["text"]53
Open tasks: 254
@end code56
The important result is not the number. It is the shape of the solution. Sigil57
lets a short script stay short while still giving it modules, Unicode strings,58
structured errors, a compiler, and a path toward a distributable program.60
@aside61
Keep the first version direct. Extract an abstraction when it makes the next62
change clearer, not merely because a function could exist.63
@end aside65
@exercise["change-state" "Change the state"] {66
@p {67
Change the report to count @code{DONE} lines. Then make the desired state a68
single named value so the question can change without touching the counting69
function.70
}71
}73
@end section74
@end section75
@end chapter