AtlatestRepositorysigil-doc

sigil-doc / tree / book / practical-sigil01-useful-first-script.sgd

1#lang sigil/doc/book
2@chapter["A Useful First Script" authors: '("David Wilson")]
3
4@section["Begin with a Question" id: "first-script"]
5
6Small programs are where a language earns trust. We will craft a task report
7that reads a plain text file, counts unfinished work, and prints a useful
8summary. It is modest enough to understand in one sitting, but real enough to
9exercise files, strings, lists, functions, and command-line behavior.
11@p {Create a file named @code{tasks.txt}:}
13@code["text"]
14TODO Write the first Practical Sigil chapter
15DONE Sketch the report format
16TODO Share the result
17@end code
19The program starts by turning the file into lines and asking whether each line
20begins 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 code
32This is ordinary Scheme-shaped code, but it is directed at practical work.
33There is no framework to adopt and no object hierarchy to satisfy. Data enters
34as strings and lists, and the small functions say exactly how it changes.
36@section["Craft the Report" id: "craft-the-report"]
38Now give the script a boundary: read the file, split it into lines, and display
39the result.
41@code["sigil"]
42(define lines
43 (string-split (read-file-string "tasks.txt") "\n"))
45(display "Open tasks: ")
46(display (count-tasks "TODO" lines))
47(newline)
48@end code
50Run it and the answer is immediate:
52@code["text"]
53Open tasks: 2
54@end code
56The important result is not the number. It is the shape of the solution. Sigil
57lets a short script stay short while still giving it modules, Unicode strings,
58structured errors, a compiler, and a path toward a distributable program.
60@aside
61Keep the first version direct. Extract an abstraction when it makes the next
62change clearer, not merely because a function could exist.
63@end aside
65@exercise["change-state" "Change the state"] {
66@p {
67Change the report to count @code{DONE} lines. Then make the desired state a
68single named value so the question can change without touching the counting
69function.
73@end section
74@end section
75@end chapter