Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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.

ExerciseChapterTaskSolution
1.1Getting StartedWrite a program that reports which compiler built it and which version that compiler is.ch01/solutions/ex01-01.tiko
1.2Getting StartedMake 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.3Getting StartedCall a procedure that was never declared, and note the identifier of the diagnostic.ch01/solutions/ex01-03.tiko
3.1A Tour of tikoReport the longest word in the file as well as the most common ones.ch03/solutions/ex03-01.tiko
3.2A Tour of tikoList the words that appear exactly once, in alphabetical order.ch03/solutions/ex03-02.tiko
4.1Types, Variables and ConstantsPrint 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.2Types, Variables and ConstantsBuild a table comparing cint, int and fix over 2.4, 2.5, 2.6 and their negatives.ch04/solutions/ex04-02.tiko
5.1Operators and ExpressionsBuild a permissions value from three named bit positions, then read one back.ch05/solutions/ex05-01.tiko
5.2Operators and ExpressionsWrite expressions where parentheses change the answer, and one where they only make the existing grouping obvious.ch05/solutions/ex05-02.tiko
6.1Control Flow, Scope and deferWrite FizzBuzz for 1 to 15.ch06/solutions/ex06-01.tiko
6.2Control Flow, Scope and deferWrite 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.1ProceduresWrite MinMax, which takes three int32 values and reports the smallest and largest through byref parameters.ch07/solutions/ex07-01.tiko
7.2ProceduresOverload Describe for int32, float64 and ustring, then call it with an int16 and an int64.ch07/solutions/ex07-02.tiko
8.1ArraysWrite 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.2ArraysTranspose a two-dimensional array into a second array whose dimensions are the original's, swapped.ch08/solutions/ex08-02.tiko
9.1Strings and TextWrite 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.2Strings and TextParse a block of key = value lines into pairs, skipping blanks and lines with no =.ch09/solutions/ex09-02.tiko
10.1User-Defined Types and LayoutDeclare 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.2User-Defined Types and LayoutTake 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.1Pointers, References and MemoryWrite a growable int32 buffer that doubles its capacity when it fills, using reallocate, and report each growth.ch11/solutions/ex11-01.tiko
11.2Pointers, References and MemoryReverse a singly linked list in place by changing the links, not the values.ch11/solutions/ex11-02.tiko
12.1ObjectsWrite 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.2ObjectsWrite 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.1Operator OverloadingWrite Money, stored in whole cents, with +, -, multiplication by a count, <, = and a cast to text like $15.30.ch13/solutions/ex13-01.tiko
13.2Operator OverloadingWrite a Countdown type that a for loop counts down with, printing liftoff at zero.ch13/solutions/ex13-02.tiko
14.1Inheritance and PolymorphismAdd 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.2Inheritance and PolymorphismWrite 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.6Inheritance and PolymorphismAdd a Triangle to ifaceshapes.tiko.ch14/solutions/ex14-03.tiko
15.1Modules and PackagesWrite 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.2Modules and PackagesWrite 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.1Namespaces, Headers and the PreprocessorWrite CUBE( x ) so that CUBE( 1 + 1 ) is 8 and 100 \ CUBE( 2 ) is 12.ch16/solutions/ex16-01.tiko
16.2Namespaces, Headers and the PreprocessorWrite 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.3Namespaces, Headers and the PreprocessorWrite 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.4Namespaces, Headers and the PreprocessorPut a function Area in a namespace Disc (one radius) and another in a namespace Rect (width and height).ch16/solutions/ex16-04.tiko
17.1GenericsWrite 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.2GenericsWrite Swap_( of T )( byref a as T, byref b as T ).ch17/solutions/ex17-02.tiko
17.3GenericsMake 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.1Errors: Optional, Result and Runtime ChecksWrite 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.2Errors: Optional, Result and Runtime ChecksWrite 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.1Testing, Debugging and ToolingWrite 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.2Testing, Debugging and ToolingAdd TRACEVAL( x ) to trace.ti's family: it prints the expression as written, =, and its value.ch19/solutions/ex19-02.tiko
20.1Tuples, Iterators and For EachWrite DivMod( a, b ) returning the quotient and remainder as one tuple, and use it both destructured and whole.ch20/solutions/ex20-01.tiko
20.2Tuples, Iterators and For EachWrite 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.1Lambdas and ClosuresCount 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.2Lambdas and ClosuresSort names by length, and names of equal length alphabetically, with one comparer.ch21/solutions/ex21-02.tiko
22.1Resource ManagementWrite 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.2Resource ManagementKeep a WeakPtr( of Image ) as a cache entry.ch22/solutions/ex22-02.tiko
23.1ConcurrencySum 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.2ConcurrencyTwo producers send three numbers each into one channel.ch23/solutions/ex23-02.tiko
24.1Containers and SortingCount 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.2Containers and SortingKeep the booked appointment times in an OrderedSet.ch24/solutions/ex24-02.tiko
25.1Files, Processes and the EnvironmentWalk a directory tree and count its files by extension, printing the counts in a stable order.ch25/solutions/ex25-01.tiko
25.2Files, Processes and the EnvironmentWrite 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.1Dates and TimesWrite 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.2Dates and TimesRead 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.1NumbersPut 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.2NumbersEstimate π 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.1Logging, Terminal UIs, SQLite and Regular ExpressionsStore 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.2Logging, Terminal UIs, SQLite and Regular ExpressionsSet 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.1Interfacing with CBind 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.2Interfacing with CBind 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.1Building and ShippingBuild 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.2Building and ShippingWrite 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.1Classic BASIC and CompatibilityRewrite gosub.bas without gosub, so that it compiles.ch32/solutions/ex32-01.bas
32.2Classic BASIC and CompatibilityRead a price list from data statements until a sentinel item "END", printing each line and the total.ch32/solutions/ex32-02.bas
33.1Capstone: a CLI Search ToolWrite 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.2Capstone: a CLI Search ToolAdd whole-word matching, so that dog matches the lazy dog. and hot-dog but not dogma or underdog.ch33/solutions/ex33-02.tiko
34.1Capstone: a Concurrent PipelineWrite 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.2Capstone: a Concurrent PipelineStart 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.1Capstone: a TUI LedgerPrint the spending in each category over the whole ledger, the largest first.ch35/solutions/ex35-01.tiko
35.2Capstone: a TUI LedgerAccept a quick-entry line, date;payee;category;amount, and check it with ParseTxn.ch35/solutions/ex35-02.tiko
36.1Capstone: a Cross-Platform NotepadMake the status bar's column count characters, so that U+1F600 counts as one.ch36/solutions/ex36-01.tiko
36.2Capstone: a Cross-Platform NotepadMake 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.3Capstone: a Cross-Platform NotepadAdd 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