From f5a7133287b954da8e6d1e232b09e0edd552fe40 Mon Sep 17 00:00:00 2001 From: Glenn Jackman Date: Fri, 4 Dec 2026 17:12:37 -0500 Subject: [PATCH 1/3] Add substrings concept docs --- concepts/substrings/.meta/config.json | 7 ++ concepts/substrings/about.md | 142 ++++++++++++++++++++++++++ concepts/substrings/introduction.md | 61 +++++++++++ concepts/substrings/links.json | 6 ++ config.json | 5 + 5 files changed, 221 insertions(+) create mode 100644 concepts/substrings/.meta/config.json create mode 100644 concepts/substrings/about.md create mode 100644 concepts/substrings/introduction.md create mode 100644 concepts/substrings/links.json diff --git a/concepts/substrings/.meta/config.json b/concepts/substrings/.meta/config.json new file mode 100644 index 00000000..006750e5 --- /dev/null +++ b/concepts/substrings/.meta/config.json @@ -0,0 +1,7 @@ +{ + "authors": [ + "glennj" + ], + "contributors": [], + "blurb": "Locate substrings with string first/last, replace ranges with string replace, and insert text with string insert." +} diff --git a/concepts/substrings/about.md b/concepts/substrings/about.md new file mode 100644 index 00000000..3719525a --- /dev/null +++ b/concepts/substrings/about.md @@ -0,0 +1,142 @@ +# Substrings + +Tcl's `string` command includes subcommands for locating exact substrings (`string first`, `string last`), replacing or deleting character ranges (`string replace`), and inserting text at an index (`string insert`). +All of these commands operate on zero-based Unicode codepoint indices and return a new string rather than mutating a variable in place. + +## Searching for Substrings (`string first`, `string last`) + +Both search commands take a `needle` to look for, a `haystack` to search, and an optional bounding index: + +- `string first needle haystack ?startIndex?` searches forward starting at `startIndex` (default `0`) and returns the index of the first character of the earliest match. +- `string last needle haystack ?lastIndex?` searches backward and returns the index of the first character of the latest match whose characters all fall at or before `lastIndex` (default `end`). + +When `needle` does not appear within the search bounds, both commands return `-1`. + +```tcl +set record "usr:alice:admin:active" + +puts [string first ":" $record] +# => 3 + +puts [string first ":" $record 4] +# => 9 + +puts [string last ":" $record] +# => 15 + +puts [string last ":" $record 14] +# => 9 +``` + +### Testing Whether a Substring Exists + +When `needle` matches at the very start of `haystack`, `string first` returns `0`; when it is absent, `string first` returns `-1`. +Never treat that return value directly as a boolean, because Tcl treats `0` as false and `-1` as true. +Instead, compare the result explicitly against `0` or `-1` (in `expr`, `>=` returns `1` for true and `0` for false): + +```tcl +set line "ERROR: disk full" + +puts [expr {[string first "ERROR" $line] >= 0}] +# => 1 +``` + +### Search Edge Cases + +- **Empty `needle`**: Searching for `""` always returns `-1`, even when `haystack` is also `""`. +- **`lastIndex` covers the whole match**: In `string last`, the entire `needle` must fit at or before `lastIndex`, not just its starting character. + For example, `[string last "ab" "xxabxx" 2]` returns `-1` because the `'b'` is at index `3`, whereas `[string last "ab" "xxabxx" 3]` returns `2`. +- **Out-of-bounds indices**: A `startIndex` before `0` is clamped to `0`, and a `startIndex` past `end` returns `-1`. + Similarly, a `lastIndex` past `end` is clamped to `end`, and a `lastIndex` before `0` returns `-1`. + +## Replacing and Deleting Ranges (`string replace`) + +`string replace string first last ?newstring?` returns a copy of `string` with all characters from `first` through `last` (**inclusive**) replaced by `newstring`. +If `newstring` is omitted (or `""`), the specified range is removed: + +```tcl +set tag "build-2026-01-alpha" + +puts [string replace $tag 6 9 "2027"] +# => build-2027-01-alpha + +puts [string replace $tag 13 end] +# => build-2026-01 +``` + +Because strings are immutable, `string replace` does not change `$tag`; assign the return value back with `set` if you want to update the variable. + +### Replacement Edge Cases + +- **Index clamping**: If `first` is less than `0`, it is clamped to `0`. + If `last` is greater than `end`, it is clamped to `end`. +- **No-op ranges**: If `last < first`, `first > end`, or `last < 0`, `string replace` returns `string` unchanged. + +```tcl +puts [string replace "abcdef" -3 1 "X"] +# => Xcdef + +puts [string replace "abcdef" 4 2 "X"] +# => abcdef + +puts [string replace "abcdef" 10 12 "X"] +# => abcdef +``` + +## Inserting Text (`string insert`) + +Introduced in Tcl 9.0, `string insert string index insertString` returns a copy of `string` with `insertString` placed immediately **before** the character at `index`: + +```tcl +set item "report.txt" + +puts [string insert $item 0 "2026-"] +# => 2026-report.txt + +puts [string insert $item 6 "-final"] +# => report-final.txt +``` + +### How `end` Differs in `string insert` + +In `string index`, `string range`, and `string replace`, `end` refers to the last character (`length - 1`). +In `string insert`, `end` refers to the position **after** the last character (`length`), making it natural to append text: + +```tcl +set word "abcd" + +puts [string insert $word 3 "X"] +# => abcXd + +puts [string insert $word end-1 "X"] +# => abcXd + +puts [string insert $word end "X"] +# => abcdX +``` + +### Insertion Edge Cases + +- **Out-of-bounds clamping**: An `index` less than `0` clamps to `0` and prepends `insertString`. + An `index` greater than or equal to the string length clamps to `end` and appends `insertString`. +- **Empty strings**: Inserting into `""` at `0` or `end` returns `insertString`, and inserting `""` returns `string` unchanged. + +## Combining Lookup and Splicing + +`string first` and `string last` pair naturally with `string range`, `string replace`, and `string insert` for structured text edits (using `if`, covered in `conditionals`, to branch on `-1`): + +```tcl +proc swap_extension {filename new_ext} { + set dot [string last "." $filename] + if {$dot == -1} { + return [string insert $filename end ".$new_ext"] + } + return [string replace $filename $dot end ".$new_ext"] +} + +puts [swap_extension "archive.tar.gz" "zip"] +# => archive.tar.zip + +puts [swap_extension "Makefile" "bak"] +# => Makefile.bak +``` diff --git a/concepts/substrings/introduction.md b/concepts/substrings/introduction.md new file mode 100644 index 00000000..d0450a36 --- /dev/null +++ b/concepts/substrings/introduction.md @@ -0,0 +1,61 @@ +# Substrings + +Tcl provides `string` subcommands to locate substrings by codepoint index and to build modified strings by replacing or inserting text at specific positions. +Because Tcl strings are immutable, these commands return a new string without modifying any variable in place. + +## Finding Substrings (`string first`, `string last`) + +`string first` and `string last` search for an exact substring (`needle`) inside another string (`haystack`) and return a zero-based index, or `-1` if `needle` is not found: + +- `string first needle haystack ?startIndex?` searches forward from `startIndex` (default `0`). +- `string last needle haystack ?lastIndex?` searches backward from `lastIndex` (default `end`) and returns the starting index of the last complete match. + +```tcl +set path "/var/log/app/server.log" + +puts [string first "/" $path] +# => 0 + +puts [string first "/" $path 1] +# => 4 + +puts [string last "/" $path] +# => 12 + +puts [string first ".tmp" $path] +# => -1 +``` + +## Replacing Ranges (`string replace`) + +`string replace string first last ?newstring?` returns a new string with the **inclusive** range from `first` through `last` replaced by `newstring`. +If you omit `newstring`, Tcl deletes the characters in that range: + +```tcl +set version "release-v1-beta" + +puts [string replace $version 8 9 "v2"] ;# replaces "v1" +# => release-v2-beta + +puts [string replace $version 10 end] ;# deletes "-beta" +# => release-v1 +``` + +## Inserting Text (`string insert`) + +Introduced in Tcl 9.0, `string insert string index insertString` returns a new string with `insertString` inserted immediately **before** `index`: + +```tcl +set host "example.com" + +puts [string insert $host 0 "api."] +# => api.example.com + +puts [string insert $host end ":8080"] +# => example.com:8080 + +puts [string insert "v10" 2 "."] +# => v1.0 +``` + +Notice that in `string insert`, `end` refers to the position **after** the last character, so `string insert $str end $suffix` appends `$suffix` to the end of `$str`. diff --git a/concepts/substrings/links.json b/concepts/substrings/links.json new file mode 100644 index 00000000..c33198a2 --- /dev/null +++ b/concepts/substrings/links.json @@ -0,0 +1,6 @@ +[ + { + "url": "https://www.tcl-lang.org/man/tcl9.0/TclCmd/string.html", + "description": "Official Tcl 9.0 manual page for the string command, covering string first, string last, string replace, and string insert." + } +] diff --git a/config.json b/config.json index b62297ce..2f379fbd 100644 --- a/config.json +++ b/config.json @@ -1992,6 +1992,11 @@ "uuid": "e84301ef-e4b3-4197-bc3b-ba7839a426cb", "slug": "error-handling", "name": "Error Handling" + }, + { + "uuid": "209a2fbe-be22-4d8c-aeb7-d9c363b56a18", + "slug": "substrings", + "name": "Substrings" } ], "key_features": [ From 238895e2e99cab36cc4c38471526f174bbac7f1a Mon Sep 17 00:00:00 2001 From: Glenn Jackman Date: Fri, 4 Dec 2026 17:18:41 -0500 Subject: [PATCH 2/3] Add uri-inspector concept exercise --- config.json | 12 ++ .../concept/uri-inspector/.docs/hints.md | 35 ++++ .../uri-inspector/.docs/instructions.md | 77 ++++++++ .../uri-inspector/.docs/introduction.md | 63 ++++++ .../uri-inspector/.docs/introduction.md.tpl | 3 + .../concept/uri-inspector/.meta/config.json | 17 ++ .../concept/uri-inspector/.meta/design.md | 30 +++ .../concept/uri-inspector/.meta/exemplar.tcl | 29 +++ .../concept/uri-inspector/testHelpers.tcl | 183 ++++++++++++++++++ .../concept/uri-inspector/uri-inspector.tcl | 44 +++++ .../concept/uri-inspector/uri-inspector.test | 143 ++++++++++++++ 11 files changed, 636 insertions(+) create mode 100644 exercises/concept/uri-inspector/.docs/hints.md create mode 100644 exercises/concept/uri-inspector/.docs/instructions.md create mode 100644 exercises/concept/uri-inspector/.docs/introduction.md create mode 100644 exercises/concept/uri-inspector/.docs/introduction.md.tpl create mode 100644 exercises/concept/uri-inspector/.meta/config.json create mode 100644 exercises/concept/uri-inspector/.meta/design.md create mode 100644 exercises/concept/uri-inspector/.meta/exemplar.tcl create mode 100644 exercises/concept/uri-inspector/testHelpers.tcl create mode 100644 exercises/concept/uri-inspector/uri-inspector.tcl create mode 100644 exercises/concept/uri-inspector/uri-inspector.test diff --git a/config.json b/config.json index 2f379fbd..2d421b57 100644 --- a/config.json +++ b/config.json @@ -202,6 +202,18 @@ "procedures" ], "status": "wip" + }, + { + "slug": "uri-inspector", + "name": "URI Inspector", + "uuid": "c03d337c-5bce-4b0c-b9c3-ac0bf8de6a75", + "concepts": [ + "substrings" + ], + "prerequisites": [ + "strings" + ], + "status": "wip" } ], "practice": [ diff --git a/exercises/concept/uri-inspector/.docs/hints.md b/exercises/concept/uri-inspector/.docs/hints.md new file mode 100644 index 00000000..8834d472 --- /dev/null +++ b/exercises/concept/uri-inspector/.docs/hints.md @@ -0,0 +1,35 @@ +# Hints + +## General + +- All `string` subcommands return a new string without mutating variables in place. +- Remember that `string first` and `string last` return `-1` when the substring is not found, and `0` when it matches at the very start of the string. +- See the [Tcl `string` manual page][tcl-string] for full syntax and edge-case details. + +## 1. Locate the scheme separator + +- Use `string first` with `"://"` as the needle and `$uri` as the haystack. + +## 2. Find a delimiter from a starting offset + +- Pass the starting index as the optional fourth argument to `string first` (`string first needle haystack startIndex`). + +## 3. Find the last slash within a bound + +- Use `string last` with `"/"` as the needle, `$uri` as the haystack, and `$lastIndex` as the upper bound. + +## 4. Replace a span in a URI + +- Pass all four arguments to `string replace` (`string replace str first last newstring`). +- Both `first` and `last` are inclusive, and `end`-relative indices work automatically. + +## 5. Remove a span from a URI + +- Omit the replacement argument when calling `string replace` (`string replace str first last`). + +## 6. Insert a fragment at an offset + +- Use Tcl 9's `string insert` (`string insert str index insertString`). +- In `string insert`, `end` refers to the position after the last character, so passing `end` appends the inserted text. + +[tcl-string]: https://www.tcl-lang.org/man/tcl9.0/TclCmd/string.html diff --git a/exercises/concept/uri-inspector/.docs/instructions.md b/exercises/concept/uri-inspector/.docs/instructions.md new file mode 100644 index 00000000..504017e9 --- /dev/null +++ b/exercises/concept/uri-inspector/.docs/instructions.md @@ -0,0 +1,77 @@ +# Instructions + +You are building a lightweight URI inspection and editing toolkit for an internal proxy service. +Rather than pulling in a full URL parser, the proxy locates delimiters by codepoint index and splices segments directly. + +Implement six procedures to search, replace, remove, and insert URI fragments. + +## 1. Locate the scheme separator + +Implement `schemeSeparatorIndex`, which takes a `uri` string and returns the zero-based index of the `"://"` scheme separator, or `-1` if it is not present. + +```tcl +schemeSeparatorIndex "https://example.com/api" +# => 5 + +schemeSeparatorIndex "/relative/path" +# => -1 +``` + +## 2. Find a delimiter from a starting offset + +Implement `findDelimiterFrom`, which takes `uri`, `delimiter`, and `startIndex`. +It returns the zero-based index of the first occurrence of `delimiter` in `uri` at or after `startIndex`, or `-1` if none is found. + +```tcl +findDelimiterFrom "https://example.com/api/v1" "/" 8 +# => 19 + +findDelimiterFrom "https://example.com/api/v1" "?" 0 +# => -1 +``` + +## 3. Find the last slash within a bound + +Implement `lastSlashAtOrBefore`, which takes `uri` and `lastIndex` (which may be an integer or an `end`-relative index). +It returns the zero-based index of the last `"/"` in `uri` at or before `lastIndex`, or `-1` if no `"/"` appears within that bound. + +```tcl +lastSlashAtOrBefore "https://example.com/api/v1" end +# => 23 + +lastSlashAtOrBefore "https://example.com/api/v1" 22 +# => 19 +``` + +## 4. Replace a span in a URI + +Implement `replaceSpan`, which takes `uri`, `first`, `last`, and `replacement`. +It returns a new string with the inclusive range from `first` through `last` (including `end`-relative indices) replaced by `replacement`. + +```tcl +replaceSpan "https://example.com/v1/users" 20 21 "v2" +# => https://example.com/v2/users +``` + +## 5. Remove a span from a URI + +Implement `deleteSpan`, which takes `uri`, `first`, and `last`. +It returns a new string with the inclusive range from `first` through `last` removed. + +```tcl +deleteSpan "https://example.com/v1/users?debug=1" 28 end +# => https://example.com/v1/users +``` + +## 6. Insert a fragment at an offset + +Implement `insertAt`, which takes `uri`, `index`, and `fragment`. +It returns a new string with `fragment` inserted immediately before `index` (supporting `0` to prepend, `end` to append, and `end-N` or integer offsets). + +```tcl +insertAt "example.com/api" 0 "https://" +# => https://example.com/api + +insertAt "https://example.com/api" end "?v=2" +# => https://example.com/api?v=2 +``` diff --git a/exercises/concept/uri-inspector/.docs/introduction.md b/exercises/concept/uri-inspector/.docs/introduction.md new file mode 100644 index 00000000..f34ec155 --- /dev/null +++ b/exercises/concept/uri-inspector/.docs/introduction.md @@ -0,0 +1,63 @@ +# Introduction + +## Substrings + +Tcl provides `string` subcommands to locate substrings by codepoint index and to build modified strings by replacing or inserting text at specific positions. +Because Tcl strings are immutable, these commands return a new string without modifying any variable in place. + +### Finding Substrings (`string first`, `string last`) + +`string first` and `string last` search for an exact substring (`needle`) inside another string (`haystack`) and return a zero-based index, or `-1` if `needle` is not found: + +- `string first needle haystack ?startIndex?` searches forward from `startIndex` (default `0`). +- `string last needle haystack ?lastIndex?` searches backward from `lastIndex` (default `end`) and returns the starting index of the last complete match. + +```tcl +set path "/var/log/app/server.log" + +puts [string first "/" $path] +# => 0 + +puts [string first "/" $path 1] +# => 4 + +puts [string last "/" $path] +# => 12 + +puts [string first ".tmp" $path] +# => -1 +``` + +### Replacing Ranges (`string replace`) + +`string replace string first last ?newstring?` returns a new string with the **inclusive** range from `first` through `last` replaced by `newstring`. +If you omit `newstring`, Tcl deletes the characters in that range: + +```tcl +set version "release-v1-beta" + +puts [string replace $version 8 9 "v2"] ;# replaces "v1" +# => release-v2-beta + +puts [string replace $version 10 end] ;# deletes "-beta" +# => release-v1 +``` + +### Inserting Text (`string insert`) + +Introduced in Tcl 9.0, `string insert string index insertString` returns a new string with `insertString` inserted immediately **before** `index`: + +```tcl +set host "example.com" + +puts [string insert $host 0 "api."] +# => api.example.com + +puts [string insert $host end ":8080"] +# => example.com:8080 + +puts [string insert "v10" 2 "."] +# => v1.0 +``` + +Notice that in `string insert`, `end` refers to the position **after** the last character, so `string insert $str end $suffix` appends `$suffix` to the end of `$str`. diff --git a/exercises/concept/uri-inspector/.docs/introduction.md.tpl b/exercises/concept/uri-inspector/.docs/introduction.md.tpl new file mode 100644 index 00000000..51f697f7 --- /dev/null +++ b/exercises/concept/uri-inspector/.docs/introduction.md.tpl @@ -0,0 +1,3 @@ +# Introduction + +%{concept:substrings} diff --git a/exercises/concept/uri-inspector/.meta/config.json b/exercises/concept/uri-inspector/.meta/config.json new file mode 100644 index 00000000..9b094e00 --- /dev/null +++ b/exercises/concept/uri-inspector/.meta/config.json @@ -0,0 +1,17 @@ +{ + "authors": [ + "glennj" + ], + "files": { + "solution": [ + "uri-inspector.tcl" + ], + "test": [ + "uri-inspector.test" + ], + "exemplar": [ + ".meta/exemplar.tcl" + ] + }, + "blurb": "Locate URI delimiters with string first and string last, splice segments with string replace, and insert text with string insert." +} diff --git a/exercises/concept/uri-inspector/.meta/design.md b/exercises/concept/uri-inspector/.meta/design.md new file mode 100644 index 00000000..04247417 --- /dev/null +++ b/exercises/concept/uri-inspector/.meta/design.md @@ -0,0 +1,30 @@ +# Design + +## Goal + +The goal of this exercise is to introduce Tcl substring search and index-based editing -- locating delimiters with `string first` and `string last`, replacing or removing character ranges with `string replace`, and inserting text at offsets with Tcl 9's `string insert`. + +## Learning objectives + +- Find the first occurrence of a substring with `string first`, including handling `-1` when not found. +- Resume a forward search from an offset using `string first`'s optional `startIndex` argument. +- Search backward within an upper bound using `string last` and its optional `lastIndex` argument. +- Replace an inclusive character range with `string replace`, including `end`-relative indices. +- Delete an inclusive character range by omitting the replacement argument to `string replace`. +- Insert text before an index -- including `0` to prepend and `end` to append -- using Tcl 9's `string insert`. + +## Out of scope + +- Branching on `-1` with `if` or relational operators (`conditionals`, `booleans`). +- Splitting strings into lists and multi-pair `string map` replacements (`strings-and-lists`). +- Wildcard pattern matching (`glob-matching`) and regular expressions (`regular-expressions`). + +## Concepts + +The Concepts this exercise unlocks are: + +- `substrings` + +## Prerequisites + +- `strings` diff --git a/exercises/concept/uri-inspector/.meta/exemplar.tcl b/exercises/concept/uri-inspector/.meta/exemplar.tcl new file mode 100644 index 00000000..5da3dd6a --- /dev/null +++ b/exercises/concept/uri-inspector/.meta/exemplar.tcl @@ -0,0 +1,29 @@ +# Locate the "://" scheme separator in uri, or -1 if absent. +proc schemeSeparatorIndex {uri} { + string first "://" $uri +} + +# Locate delimiter in uri starting from startIndex, or -1 if absent. +proc findDelimiterFrom {uri delimiter startIndex} { + string first $delimiter $uri $startIndex +} + +# Locate the last "/" in uri at or before lastIndex, or -1 if absent. +proc lastSlashAtOrBefore {uri lastIndex} { + string last "/" $uri $lastIndex +} + +# Replace the inclusive range first..last in uri with replacement. +proc replaceSpan {uri first last replacement} { + string replace $uri $first $last $replacement +} + +# Remove the inclusive range first..last from uri. +proc deleteSpan {uri first last} { + string replace $uri $first $last +} + +# Insert fragment into uri immediately before index. +proc insertAt {uri index fragment} { + string insert $uri $index $fragment +} diff --git a/exercises/concept/uri-inspector/testHelpers.tcl b/exercises/concept/uri-inspector/testHelpers.tcl new file mode 100644 index 00000000..f3dcf0f6 --- /dev/null +++ b/exercises/concept/uri-inspector/testHelpers.tcl @@ -0,0 +1,183 @@ +############################################################# +# Override some tcltest procs with additional functionality + +# Allow an environment variable to override `skip` +proc skip {args} { + if {!( [info exists ::env(RUN_ALL)] && + [string is boolean -strict $::env(RUN_ALL)] && + $::env(RUN_ALL) + )} { + uplevel 1 [list ::tcltest::skip {*}$args] + } +} + +# Exit non-zero if any tests fail. +# The cleanupTests resets the numTests array, so capture it first. +proc cleanupTests {} { + set failed [expr {$::tcltest::numTests(Failed) > 0}] + uplevel 1 ::tcltest::cleanupTests + if {$failed} then {exit 1} +} + +############################################################# +# Some procs that are handy for Tcl test custom matching. +# ref http://www.tcl-lang.org/man/tcl8.6/TclCmd/tcltest.htm#M20 + +# Copy the needed procs into your test file. Use it like this: +# +# customMatch dictionary dictionaryMatch +# test name "description" -body { +# code that returns a dictionary +# } -match dictionary -result {expected dictionary value here} + + +# Compare two dictionaries for the same keys and same values +proc dictionaryMatch {expected actual} { + if {[dict size $expected] != [dict size $actual]} { + return false + } + dict for {key value} $expected { + if {![dict exists $actual $key]} { + return false + } + set actualValue [dict get $actual $key] + + # if this value is a dict then recurse, + # else just check for string equality + if {[string is list -strict $value] && + [llength $value] > 1 && + [llength $value] % 2 == 0 + } { + set procname [lindex [info level 0] 0] + if {![$procname $value $actualValue]} { + return false + } + } elseif {$actualValue ne $value} { + return false + } + } + return true +} +customMatch dictionary dictionaryMatch + + +# Since Tcl boolean values can be more than just 0/1... +# set a yes; set b true +# expr {$a == $b} ;# => 0 +# expr {$a && $b} ;# => 1 +# expr {!!$a == !!$b} ;# => 1 +# set a off; set b no +# expr {$a == $b} ;# => 0 +# expr {$a && $b} ;# => 0 +# expr {!!$a == !!$b} ;# => 1 +# +proc booleanMatch {expected actual} { + return [expr { + [string is boolean -strict $expected] && + [string is boolean -strict $actual] && + !!$expected == !!$actual + }] +} +customMatch boolean booleanMatch + + +# Compare two ordered lists without comparing the lists themselves +# as strings. +# e.g. +# set first { +# a b c +# } +# set second [list a b c] +# expr {$first eq $second} ;# 0 +# expr {$first == $second} ;# 0 +# orderedListsMatch $first $second ;# true +# +proc orderedListsMatch {expected actual} { + if {[llength $expected] != [llength $actual]} { + return false + } + foreach e $expected a $actual { + if {$e != $a} { + return false + } + } + return true +} +customMatch orderedLists orderedListsMatch + + +# two lists have the same elements, in no particular order +proc unorderedListsMatch {expected actual} { + if {[llength $expected] != [llength $actual]} { + return false + } + foreach elem $expected { + if {[lsearch -exact $actual $elem] == -1} { + return false + } + } + return true +} +customMatch unorderedLists unorderedListsMatch + + +# Compare two ordered lists without comparing the lists themselves +# as strings. Calls itself recursively. +proc listOfListsMatch {expected actual} { + set procname [lindex [info level 0] 0] + if {[llength $expected] != [llength $actual]} { + return false + } + foreach e $expected a $actual { + if {[llength $e] > 1 ? (![$procname $e $a]) : ($e != $a)} { + return false + } + } + return true +} +customMatch listOfLists listOfListsMatch + + +# The expected value is one of a list of values. +proc inListMatch {expectedList actual} { + return [expr {$actual in $expectedList}] +} +customMatch inList inListMatch + + +# Compare numbers: for example 5.0 == 5 +proc numberMatch {expected actual} { + return [expr {$expected == $actual}] +} +customMatch numbers numberMatch + + +# Compare floating point numbers +proc floatMatch {expected actual {epsilon 1e-6}} { + return [expr {abs($expected - $actual) <= $epsilon}] +} +customMatch float floatMatch + + +# Compare floating point numbers +proc closeEnough {expected actual {epsilon 1.1}} { + return [expr {abs($expected - $actual) <= $epsilon}] +} +customMatch approxEqual closeEnough + + +# Compare a list of floating point numbers +proc listOfFloatsMatch {expected actual} { + foreach e $expected a $actual { + if {![floatMatch $e $a]} { + return false + } + } + return true +} + +############################################################# +# Convenience function to set the precision of a real number. +proc roundTo {precision number} { + return [format {%.*f} $precision $number] +} diff --git a/exercises/concept/uri-inspector/uri-inspector.tcl b/exercises/concept/uri-inspector/uri-inspector.tcl new file mode 100644 index 00000000..cf76bd76 --- /dev/null +++ b/exercises/concept/uri-inspector/uri-inspector.tcl @@ -0,0 +1,44 @@ +# Implement the procedures for URI Inspector below. +# +# Practice locating delimiters with `string first` and `string last`, +# splicing and removing segments with `string replace`, and inserting +# text at offsets with Tcl 9's `string insert`. + +# 1. schemeSeparatorIndex uri +# Return the zero-based index of "://" in uri, or -1 if it is not present. +proc schemeSeparatorIndex {uri} { + # search forward for "://" +} + +# 2. findDelimiterFrom uri delimiter startIndex +# Return the zero-based index of delimiter in uri starting at startIndex, +# or -1 if delimiter is not found at or after startIndex. +proc findDelimiterFrom {uri delimiter startIndex} { + # search forward from startIndex +} + +# 3. lastSlashAtOrBefore uri lastIndex +# Return the zero-based index of the last "/" in uri at or before +# lastIndex, or -1 if none exists within that bound. +proc lastSlashAtOrBefore {uri lastIndex} { + # search backward up to lastIndex +} + +# 4. replaceSpan uri first last replacement +# Return a copy of uri with the inclusive range first..last replaced by +# replacement. +proc replaceSpan {uri first last replacement} { + # replace the inclusive range with replacement +} + +# 5. deleteSpan uri first last +# Return a copy of uri with the inclusive range first..last removed. +proc deleteSpan {uri first last} { + # remove the inclusive range without supplying a replacement +} + +# 6. insertAt uri index fragment +# Return a copy of uri with fragment inserted immediately before index. +proc insertAt {uri index fragment} { + # insert fragment before index (including 0, end, or end-N) +} diff --git a/exercises/concept/uri-inspector/uri-inspector.test b/exercises/concept/uri-inspector/uri-inspector.test new file mode 100644 index 00000000..363df729 --- /dev/null +++ b/exercises/concept/uri-inspector/uri-inspector.test @@ -0,0 +1,143 @@ +#!/usr/bin/env tclsh +package require tcltest +namespace import ::tcltest::* +source testHelpers.tcl + +# Uncomment next line to view test durations. +#configure -verbose {body error usec} + +############################################################ +source "uri-inspector.tcl" + + +# 1. Locate the scheme separator + +test uri-inspector-1.1 "locate https scheme separator" -body { + schemeSeparatorIndex "https://example.com/api" +} -returnCodes ok -result 5 + +test uri-inspector-1.2 "locate http scheme separator" -body { + schemeSeparatorIndex "http://localhost:8080" +} -returnCodes ok -result 4 + +test uri-inspector-1.3 "scheme separator at start of string returns 0" -body { + schemeSeparatorIndex "://example.com" +} -returnCodes ok -result 0 + +test uri-inspector-1.4 "missing scheme separator returns -1" -body { + schemeSeparatorIndex "/relative/path" +} -returnCodes ok -result -1 + +test uri-inspector-1.5 "empty uri returns -1" -body { + schemeSeparatorIndex "" +} -returnCodes ok -result -1 + + +# 2. Find a delimiter from a starting offset + +test uri-inspector-2.1 "find first path slash after scheme" -body { + findDelimiterFrom "https://example.com/api/v1" "/" 8 +} -returnCodes ok -result 19 + +test uri-inspector-2.2 "match right at startIndex" -body { + findDelimiterFrom "https://example.com/api/v1" "/" 19 +} -returnCodes ok -result 19 + +test uri-inspector-2.3 "delimiter not found after startIndex returns -1" -body { + findDelimiterFrom "https://example.com" "/" 8 +} -returnCodes ok -result -1 + +test uri-inspector-2.4 "missing delimiter from start returns -1" -body { + findDelimiterFrom "https://example.com/api/v1" "?" 0 +} -returnCodes ok -result -1 + +test uri-inspector-2.5 "empty delimiter returns -1" -body { + findDelimiterFrom "https://example.com" "" 0 +} -returnCodes ok -result -1 + +test uri-inspector-2.6 "codepoint index with Unicode path segment" -body { + findDelimiterFrom "https://example.com/café/v1" "/" 20 +} -returnCodes ok -result 24 + + +# 3. Find the last slash within a bound + +test uri-inspector-3.1 "find last slash across entire uri" -body { + lastSlashAtOrBefore "https://example.com/api/v1" end +} -returnCodes ok -result 23 + +test uri-inspector-3.2 "find last slash before an explicit index" -body { + lastSlashAtOrBefore "https://example.com/api/v1" 22 +} -returnCodes ok -result 19 + +test uri-inspector-3.3 "match at exact lastIndex" -body { + lastSlashAtOrBefore "https://example.com/api/v1" 23 +} -returnCodes ok -result 23 + +test uri-inspector-3.4 "no slash before bound returns -1" -body { + lastSlashAtOrBefore "https://example.com/api/v1" 5 +} -returnCodes ok -result -1 + +test uri-inspector-3.5 "relative path with no slash returns -1" -body { + lastSlashAtOrBefore "index.html" end +} -returnCodes ok -result -1 + + +# 4. Replace a span in a URI + +test uri-inspector-4.1 "replace version segment in path" -body { + replaceSpan "https://example.com/v1/users" 20 21 "v2" +} -returnCodes ok -result "https://example.com/v2/users" + +test uri-inspector-4.2 "replace scheme up to end-relative bound" -body { + replaceSpan "http://example.com" 0 3 "https" +} -returnCodes ok -result "https://example.com" + +test uri-inspector-4.3 "replace trailing segment using end" -body { + replaceSpan "https://example.com/api/v1" 24 end "v2-beta" +} -returnCodes ok -result "https://example.com/api/v2-beta" + +test uri-inspector-4.4 "inverted range leaves uri unchanged" -body { + replaceSpan "https://example.com" 10 5 "x" +} -returnCodes ok -result "https://example.com" + + +# 5. Remove a span from a URI + +test uri-inspector-5.1 "remove query string from end" -body { + deleteSpan "https://example.com/v1/users?debug=1" 28 end +} -returnCodes ok -result "https://example.com/v1/users" + +test uri-inspector-5.2 "remove port from authority" -body { + deleteSpan "http://localhost:8080/health" 16 20 +} -returnCodes ok -result "http://localhost/health" + +test uri-inspector-5.3 "remove leading prefix" -body { + deleteSpan "https://example.com" 0 7 +} -returnCodes ok -result "example.com" + + +# 6. Insert a fragment at an offset + +test uri-inspector-6.1 "prepend scheme at index 0" -body { + insertAt "example.com/api" 0 "https://" +} -returnCodes ok -result "https://example.com/api" + +test uri-inspector-6.2 "insert subdomain at offset" -body { + insertAt "https://example.com/api" 8 "api." +} -returnCodes ok -result "https://api.example.com/api" + +test uri-inspector-6.3 "append query string at end" -body { + insertAt "https://example.com/api" end "?v=2" +} -returnCodes ok -result "https://example.com/api?v=2" + +test uri-inspector-6.4 "insert before last character using end-1" -body { + insertAt "https://example.com/v1" end-1 "0." +} -returnCodes ok -result "https://example.com/v0.1" + +test uri-inspector-6.5 "insert into empty uri" -body { + insertAt "" 0 "https://example.com" +} -returnCodes ok -result "https://example.com" + + +cleanupTests From b08807a1c523a8fccce23cce707c0ba7f14b7d9a Mon Sep 17 00:00:00 2001 From: Glenn Jackman Date: Fri, 4 Dec 2026 17:19:12 -0500 Subject: [PATCH 3/3] Mark substrings concept complete in roadmap --- LEARNING_PATH_ROADMAP.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/LEARNING_PATH_ROADMAP.md b/LEARNING_PATH_ROADMAP.md index 8642e0ce..7f3c6b49 100644 --- a/LEARNING_PATH_ROADMAP.md +++ b/LEARNING_PATH_ROADMAP.md @@ -181,7 +181,7 @@ This branch teaches Tcl's value-based collections and functional idioms. - **Teaches**: The `{*}` expansion operator, passing lists as individual arguments, and avoiding `eval` injection/shimmering bugs. - **Concept Exercise Idea**: *Command Dispatcher* (new story) — forward dynamically assembled argument lists safely using `{*}`. -### 15. `dictionaries` +### 15. `dictionaries` ✅ - **Prerequisites**: `lists` - **Teaches**: `dict create`, `get`, `getwithdefault` (Tcl 9), `set`, `unset`, `incr`, `exists`, `keys`, `values`, `for`, `map`, and nested dictionaries. @@ -209,7 +209,7 @@ This branch focuses on formatted text, binary protocols, dates and times, and pa - **Teaches**: `string equal` and `string compare` (`-nocase`, `-length`), string comparison operators in `expr` (`eq`, `ne`, `lt`, `gt`, `le`, `ge`), and `string is` character classes (`alpha`, `digit`, `alnum`, `wordchar`, `space`, `ascii`, `-strict`, `-failindex`). - **Concept Exercise Idea**: *Identifier Validator* (new story) -- validate character classes, check prefixes, and compare normalized identifiers case-insensitively. -### 19. `substrings` +### 19. `substrings` ✅ - **Prerequisites**: `strings` - **Teaches**: Substring lookup (`string first`, `string last`), `string replace`, and Tcl 9 `string insert`.