Appendix G: Solutions
74 of the book's 205 exercises have a worked solution. Each is a program in the companion examples, beside the chapter's listings, under examples/chNN/solutions/, with its expected output in a .out file next to it. The solutions are not printed here: the listing harness compiles and runs every one of them on every target, exactly as it does the chapters' listings, so the files are the version that is known to work.
A solution is one way to do the exercise, not the only one. Several build on a chapter's own listings or modules and import them, and run from their solutions/ directory. A solution marked blocked depends on a compiler fix that the toolchain this book is checked against does not have yet; its .out file is the result it gives once the fix is in.
| Exercise | Chapter | Task | Solution |
|---|---|---|---|
| 1.1 | Getting Started | Write a program that reports which compiler built it and which version that compiler is. | ch01/solutions/ex01-01.tiko |
| 1.2 | Getting Started | Make a program greet you by name and then exit with status 3, and check the status from your shell (echo $?, or echo %ERRORLEVEL% in cmd). | ch01/solutions/ex01-02.tiko |
| 1.3 | Getting Started | Call a procedure that was never declared, and note the identifier of the diagnostic. | ch01/solutions/ex01-03.tiko |
| 3.1 | A Tour of tiko | Report the longest word in the file as well as the most common ones. | ch03/solutions/ex03-01.tiko |
| 3.2 | A Tour of tiko | List the words that appear exactly once, in alphabetical order. | ch03/solutions/ex03-02.tiko |
| 4.1 | Types, Variables and Constants | Print the largest value each signed integer type can hold, then add one to the int32 maximum and explain what you see. | ch04/solutions/ex04-01.tiko |
| 4.2 | Types, Variables and Constants | Build a table comparing cint, int and fix over 2.4, 2.5, 2.6 and their negatives. | ch04/solutions/ex04-02.tiko |
| 5.1 | Operators and Expressions | Build a permissions value from three named bit positions, then read one back. | ch05/solutions/ex05-01.tiko |
| 5.2 | Operators and Expressions | Write expressions where parentheses change the answer, and one where they only make the existing grouping obvious. | ch05/solutions/ex05-02.tiko |
| 6.1 | Control Flow, Scope and defer | Write FizzBuzz for 1 to 15. | ch06/solutions/ex06-01.tiko |
| 6.2 | Control Flow, Scope and defer | Write a procedure that acquires something inside an if and defers its release, and a second that guards first and defers in the procedure body. | ch06/solutions/ex06-02.tiko |
| 7.1 | Procedures | Write MinMax, which takes three int32 values and reports the smallest and largest through byref parameters. | ch07/solutions/ex07-01.tiko |
| 7.2 | Procedures | Overload Describe for int32, float64 and ustring, then call it with an int16 and an int64. | ch07/solutions/ex07-02.tiko |
| 8.1 | Arrays | Write Reverse, which reverses an array in place and works whatever its bounds — test it on arrays indexed from 1, from 0 and from −2, and on an empty one. | ch08/solutions/ex08-01.tiko |
| 8.2 | Arrays | Transpose a two-dimensional array into a second array whose dimensions are the original's, swapped. | ch08/solutions/ex08-02.tiko |
| 9.1 | Strings and Text | Write TitleCase, which uppercases the first letter of each word and lowercases the rest, then check it against strings.MCase on a sentence, a shouted one, one with double spaces and an empty string. | ch09/solutions/ex09-01.tiko |
| 9.2 | Strings and Text | Parse a block of key = value lines into pairs, skipping blanks and lines with no =. | ch09/solutions/ex09-02.tiko |
| 10.1 | User-Defined Types and Layout | Declare a 16-byte record header — magic, version, flags, length, checksum — that must match a published binary format exactly, and have the program verify every offset against the spec instead of trusting it. | ch10/solutions/ex10-01.tiko |
| 10.2 | User-Defined Types and Layout | Take a type with six fields of mixed sizes declared carelessly, reorder them largest first, and print both sizes and what a million of each would cost. | ch10/solutions/ex10-02.tiko |
| 11.1 | Pointers, References and Memory | Write a growable int32 buffer that doubles its capacity when it fills, using reallocate, and report each growth. | ch11/solutions/ex11-01.tiko |
| 11.2 | Pointers, References and Memory | Reverse a singly linked list in place by changing the links, not the values. | ch11/solutions/ex11-02.tiko |
| 12.1 | Objects | Write an IntStack that keeps its items in memory from reallocate, with a constructor, destructor, copy constructor and operator let. | ch12/solutions/ex12-01.tiko |
| 12.2 | Objects | Write a Temperature that stores kelvin and exposes Celsius and Fahrenheit as read-write properties, with the absolute-zero check in exactly one place. | ch12/solutions/ex12-02.tiko |
| 13.1 | Operator Overloading | Write Money, stored in whole cents, with +, -, multiplication by a count, <, = and a cast to text like $15.30. | ch13/solutions/ex13-01.tiko |
| 13.2 | Operator Overloading | Write a Countdown type that a for loop counts down with, printing liftoff at zero. | ch13/solutions/ex13-02.tiko |
| 14.1 | Inheritance and Polymorphism | Add a Triangle with a base and a height to the shapes program, without changing Shape, Circle or the loop. | ch14/solutions/ex14-01.tiko |
| 14.2 | Inheritance and Polymorphism | Write a Counter plugin whose Apply appends the length of the text and counts its calls, and whose destructor prints the count. | ch14/solutions/ex14-02.tiko |
| 14.6 | Inheritance and Polymorphism | Add a Triangle to ifaceshapes.tiko. | ch14/solutions/ex14-03.tiko |
| 15.1 | Modules and Packages | Write a module temp with public CToF and FToC and a module-private rounding helper, and a program that prints a table from −10 to 30 degrees in steps of 10, converting each value there and back. | ch15/solutions/ex15-01.tiko |
| 15.2 | Modules and Packages | Write a module counter whose top-level code prints that it is initialising and whose destructor sub prints that it is done, with a public shared hits. | ch15/solutions/ex15-02.tiko |
| 16.1 | Namespaces, Headers and the Preprocessor | Write CUBE( x ) so that CUBE( 1 + 1 ) is 8 and 100 \ CUBE( 2 ) is 12. | ch16/solutions/ex16-01.tiko |
| 16.2 | Namespaces, Headers and the Preprocessor | Write a #macro DEFINE_COUNTER( name ) that defines a function Next<name> returning 1, 2, 3 … on successive calls, so that DEFINE_COUNTER( Order ) gives NextOrder( ). | ch16/solutions/ex16-02.tiko |
| 16.3 | Namespaces, Headers and the Preprocessor | Write a program that prints the name of the environment variable that holds the temporary directory: TEMP on Windows, TMPDIR on Linux and macOS. | ch16/solutions/ex16-03.tiko |
| 16.4 | Namespaces, Headers and the Preprocessor | Put a function Area in a namespace Disc (one radius) and another in a namespace Rect (width and height). | ch16/solutions/ex16-04.tiko |
| 17.1 | Generics | Write Queue( of T ) — first in, first out — with Enqueue, Dequeue and a Count property, and use it with two different element types. | ch17/solutions/ex17-01.tiko |
| 17.2 | Generics | Write Swap_( of T )( byref a as T, byref b as T ). | ch17/solutions/ex17-02.tiko |
| 17.3 | Generics | Make a Version_ type with major and minor fields usable as a Map key, so that two separately built values of the same version find the same entry. | ch17/solutions/ex17-03.tiko |
| 18.1 | Errors: Optional, Result and Runtime Checks | Write ToInt( s ) returning an Optional( of int32 ) that accepts digits with an optional leading minus and refuses anything else. | ch18/solutions/ex18-01.tiko |
| 18.2 | Errors: Optional, Result and Runtime Checks | Write Divide and Root, each returning a Result( of float64, ustring ), and a RootOfRatio( a, b ) that stops at the first failure and passes it on. | ch18/solutions/ex18-02.tiko |
| 19.1 | Testing, Debugging and Tooling | Write Clamp( v, lo, hi ) and an fbcunit suite for it with three tests: a value inside the range, values on both edges, and values outside on both sides. | ch19/solutions/ex19-01.tiko |
| 19.2 | Testing, Debugging and Tooling | Add TRACEVAL( x ) to trace.ti's family: it prints the expression as written, =, and its value. | ch19/solutions/ex19-02.tiko |
| 20.1 | Tuples, Iterators and For Each | Write DivMod( a, b ) returning the quotient and remainder as one tuple, and use it both destructured and whole. | ch20/solutions/ex20-01.tiko |
| 20.2 | Tuples, Iterators and For Each | Write a Range type holding from, upTo and stepBy, walkable by for each with a positive or negative step, and empty when the step points away from the limit. | ch20/solutions/ex20-02.tiko |
| 21.1 | Lambdas and Closures | Count the words in a containers.Array( of ustring ) that are at least minLen letters long, with ForEach and one closure. | ch21/solutions/ex21-01.tiko |
| 21.2 | Lambdas and Closures | Sort names by length, and names of equal length alphabetically, with one comparer. | ch21/solutions/ex21-02.tiko |
| 22.1 | Resource Management | Write a ScratchFile type that creates a file in its constructor and deletes it in its destructor, and cannot be copied. | ch22/solutions/ex22-01.tiko |
| 22.2 | Resource Management | Keep a WeakPtr( of Image ) as a cache entry. | ch22/solutions/ex22-02.tiko |
| 23.1 | Concurrency | Sum the integers 1 to 1,000,000 in four goroutines, one quarter each, and combine the partial sums through a channel. | ch23/solutions/ex23-01.tiko |
| 23.2 | Concurrency | Two producers send three numbers each into one channel. | ch23/solutions/ex23-02.tiko |
| 24.1 | Containers and Sorting | Count the words of a text in a Map and print the three most frequent, ties broken alphabetically so the output never varies. | ch24/solutions/ex24-01.tiko |
| 24.2 | Containers and Sorting | Keep the booked appointment times in an OrderedSet. | ch24/solutions/ex24-02.tiko |
| 25.1 | Files, Processes and the Environment | Walk a directory tree and count its files by extension, printing the counts in a stable order. | ch25/solutions/ex25-01.tiko |
| 25.2 | Files, Processes and the Environment | Write Sell( stock, record, n ) for the stock file of records.tiko: it reduces the quantity of record record by n and refuses, returning false, if there are not enough. | ch25/solutions/ex25-02.tiko |
| 26.1 | Dates and Times | Write WorkingDays( first, last ), the number of Monday-to-Friday days from first up to but not including last, and check it on a week, a month and a year. | ch26/solutions/ex26-01.tiko |
| 26.2 | Dates and Times | Read a list of lap times written as ISO 8601 durations, report any that do not parse, and print the total and the mean. | ch26/solutions/ex26-02.tiko |
| 27.1 | Numbers | Put 1000.00 in a savings account at 4% a year, credit and round the interest to cents each year, and print the balance for ten years in Decimal. | ch27/solutions/ex27-01.tiko |
| 27.2 | Numbers | Estimate π by throwing a million random points at a unit square and counting how many land inside the quarter circle. | ch27/solutions/ex27-02.tiko |
| 28.1 | Logging, Terminal UIs, SQLite and Regular Expressions | Store a list of sales in a table, then print each region's total and number of sales, largest first, with one SQL query. | ch28/solutions/ex28-01.tiko |
| 28.2 | Logging, Terminal UIs, SQLite and Regular Expressions | Set a logger's minimum level from a level name given on the command line, falling back to INFO for a name that is not a level. | ch28/solutions/ex28-02.tiko |
| 29.1 | Interfacing with C | Bind C's bsearch and use it to look values up in a sorted array, with a cdecl comparison function. | ch29/solutions/ex29-01.tiko |
| 29.2 | Interfacing with C | Bind strtol, using its end pointer to read every number at the start of a string and report where the numbers stopped. | ch29/solutions/ex29-02.tiko |
| 31.1 | Building and Shipping | Build a static library with Gcd and an Lcm built on it, and use it to find the smallest number that every number from 1 to 20 divides. | ch31/solutions/ex31-01.tiko |
| 31.2 | Building and Shipping | Write a program that reports, from the predefined symbols, whether it was built with error checking, with the thread-safe runtime, and against which C runtime. | ch31/solutions/ex31-02.tiko |
| 32.1 | Classic BASIC and Compatibility | Rewrite gosub.bas without gosub, so that it compiles. | ch32/solutions/ex32-01.bas |
| 32.2 | Classic BASIC and Compatibility | Read a price list from data statements until a sentinel item "END", printing each line and the total. | ch32/solutions/ex32-02.bas |
| 33.1 | Capstone: a CLI Search Tool | Write a program that uses the search module to print how many lines match in each file, as path: count. | ch33/solutions/ex33-01.tiko |
| 33.2 | Capstone: a CLI Search Tool | Add whole-word matching, so that dog matches the lazy dog. and hot-dog but not dogma or underdog. | ch33/solutions/ex33-02.tiko |
| 34.1 | Capstone: a Concurrent Pipeline | Write SameBytes( a, b ), which compares two files byte by byte, and check it on the groups that thash reports for sample/. | ch34/solutions/ex34-01.tiko |
| 34.2 | Capstone: a Concurrent Pipeline | Start two walkers, one for sample/docs and one for sample/photos, both sending to a single channel, and print every file name they find in sorted order. | ch34/solutions/ex34-02.tiko |
| 35.1 | Capstone: a TUI Ledger | Print the spending in each category over the whole ledger, the largest first. | ch35/solutions/ex35-01.tiko |
| 35.2 | Capstone: a TUI Ledger | Accept a quick-entry line, date;payee;category;amount, and check it with ParseTxn. | ch35/solutions/ex35-02.tiko |
| 36.1 | Capstone: a Cross-Platform Notepad | Make the status bar's column count characters, so that U+1F600 counts as one. | ch36/solutions/ex36-01.tiko |
| 36.2 | Capstone: a Cross-Platform Notepad | Make a new document use the line ending of the system it was started on, through a NewDocument function and #if, while a file that was read keeps its own. | ch36/solutions/ex36-02.tiko |
| 36.3 | Capstone: a Cross-Platform Notepad | Add Find Previous (Shift+F3) to textfile and to the Edit menu: the last match that ends at or before the start of the selection, wrapping around to the bottom. | ch36/solutions/ex36-03.tiko |