6.0.1.13
Sugar: readability & convenience library
A collection of small functions to help make Racket code simpler & more readable.
1 Installation & updates
At the command line:
+
After that, you can update the package from the command line:
+
2 Coercion
Functions that coerce the datatype of a value to another type. Racket already has type-specific conversion functions. But if you’re handling values of indeterminate type — as sometimes happens in an untyped language — then handling the possible cases individually gets to be a drag.
2.1 Values
Convert v to an integer in the least surprising way, or raise an error if no conversion is possible.
Numbers are rounded down to the nearest integer.
Stringlike values — paths, symbols, and strings — are converted to numbers and rounded down.
Characters are directly converted to integers.
Lists, vectors, and other multi-value datatypes return their length (using len).
The function will raise an error if no sensible conversion is possible.
+
Example: |
> (->int #t) | Can’t convert #t to integer |
|
Return the most natural string representation of v, or raise an error if none exists.
Same as
->string, but return a symbol rather than a string.
Same as
->string, but return a path (or complete path) rather than a string.
If
v is a listlike data type — a vector, set, stream, sequence, or list — convert it to a list. A hash or dictionary becomes a list using
dict->list. If
v is an atomic value, turn it into a single-member list.
Note that a string is treated as an atomic value rather than decomposed with string->list. This is done so the function handles strings the same way as symbols and paths.
Same as
->list, but returns a vector rather than a list.
Return #t for all v except #f, which remains #f.
Predicates that report whether v can be coerced to the specified type.
2.2 Coercion contracts
If v can be coerced to the specified type, change it to that type, then return it. If not, raise the usual contract error. These contracts can be used with input or output values.
Examples: |
| | ; Input arguments will be coerced to integers, then added | > (add-ints 1.6 3.8) | 4 | | | ; Input arguments will be added, and the result coerced to an integer | > (int-sum 1.6 3.8) | 5 |
|
Please note: this is not an officially sanctioned way to use Racket’s contract system, because contracts aren’t supposed to mutate their values (see make-contract).
But coercion contracts can be useful in two situations:
You want to be liberal about input types, but don’t want to deal with the housekeeping and manual conversions between types.
Your contract involves an expensive operation that you’d rather avoid performing twice.
3 Container
Type-neutral functions for getting elements out of a container, or testing membership.
For a
container that’s a
dict?, retrieve the element associated with the key
which. Raise an error if the key doesn’t exist.
Examples: |
> (get (make-hash '((a . 1) (b . 2) (c . 3))) 'b) | len: can’t calculate length of 2 | > (get (make-hash '((a . 1) (b . 2) (c . 3))) 'z) | get: couldn’t retrieve item z from #hash((b . 2) (a . 1) (c | . 3)) |
|
For other container types — which are all sequence-like — retrieve the element located at which. Or if the optional end_which argument is provided, retrieve the elements from which to (sub1 end_which), inclusive (i.e., make a slice). Raise an error if which or end_which is out of bounds.
Examples: |
> (get '(0 1 2 3 4 5) 2) | 2 | > (get '(0 1 2 3 4 5) 2 4) | '(2 3) | > (get '(0 1 2 3 4 5) 100) | get: couldn’t retrieve item 100 from (0 1 2 3 4 5) | > (get '(0 1 2 3 4 5) 2 100) | get: couldn’t retrieve items 2 through 100 from (0 1 2 3 4 | 5) | > (get (list->vector '(0 1 2 3 4 5)) 2) | 2 | > (get (list->vector '(0 1 2 3 4 5)) 2 4) | '#(2 3) | > (get "purple" 2) | "r" | > (get "purple" 2 4) | "rp" | > (get 'purple 2) | 'r | > (get 'purple 2 4) | 'rp |
|
When container is a path, it’s treated as a list of path elements (created by explode-path), not as a stringlike value.
To slice to the end of container, use (len container) as the value of end_which.
Return #t if item is in container, or #f otherwise.
As with get, when container is a path, it’s treated as a list of exploded path elements, not as a stringlike value.
4 Debug
Debugging utilities.
Print the name and value of
expr to
current-error-port, but also return the evaluated result of
expr as usual. This lets you see the value of an expression or variable at runtime without disrupting any of the surrounding code.
For instance, suppose you wanted to see how first-condition? was being evaluted in this expression:
(if (and (first-condition? x) (second-condition? x)) |
(one-thing) |
(other-thing)) |
You can wrap it in report and find out:
(if (and (report (first-condition? x)) (second-condition? x)) |
(one-thing) |
(other-thing)) |
This code will run the same way as before. But when it reaches first-condition?, you willl see in current-error-port:
(first-condition? x) = #t
You can also add standalone calls to report as a debugging aid at points where the return value will be irrelevant, for instance:
(report x) |
(if (and (report (first-condition? x)) (second-condition? x)) |
(one-thing) |
(other-thing)) |
x = 42
+
(first-condition? x) = #t
But don’t do this, because the result of the if expression will be skipped in favor of the last expression, which will be the value of x:
(if (and (report (first-condition? x)) (second-condition? x)) |
(one-thing) |
(other-thing)) |
(report x) |
5 File
File utilities, mostly in the realm of file extensions. These functions don’t access the filesystem.
Arguments that are pathish? can take either a string or a path. For clarity below, I’ve used strings.
Return the last file extension of file-path as a string, or #f if it has no extension. Omit the intervening . separator.
Examples: |
> (get-ext "foo.txt") | "txt" | > (get-ext "/path/to/foo.txt") | "txt" | > (get-ext "/path/to/foo.txt.bar") | "bar" | > (get-ext "/path/to/file-without-extension") | #f | > (get-ext "/path/to/directory/") | #f |
|
Return #t if the last file extension of file-path is ext, otherwise #f.
Remove the last file extension of file-path, and return the path that remains. If file-path has no extension, you just get the same file-path. Does not use the filesystem.
Like
remove-ext, just more. Remove all file extensions from
file-path, and return the path that remains. If
file-path has no extensions, you just get the same
file-path. Does not use the filesystem.
Return a new
file-path with
ext appended. Note that this does not replace an existing file extension. If that’s what you want, then do
(add-ext (remove-ext file-path) ext).
Return the enclosing directory of
path. Does not consult the filesystem about whether
path is valid. If you reach the
root directory, then
(get-enclosing-dir root) will just return
root again.
6 Len
Calculate the length of x in the least surprising way possible, or if it can’t be done, raise an error. Named in honor of the original discover of the length-reticulation algorithm, Prof. Leonard Spottiswoode.
Perhaps ironically, positive integers do not have a length.
Example: |
> (len 3) | len: can’t calculate length of 3 |
|
7 List
Drop elements from each end of
lst that satisfy
pred. Exactly equivalent to
(dropf-right (dropf lst pred) pred).
Like
string-split, but for lists. Drop elements from anywhere in
lst that satisfy
pred — ends, middle, you name it — and return a list of the sublists that remain.
Count the frequency of each element in lst, and return a hash whose keys are the unique elements of lst, and each value is the frequency of that element within lst.
Return #t if every element in container is unique, otherwise #f.
Same as
members-unique?, but if the members are not unique, raises a descriptive error rather than returning
#f.
A special version of
when that you can use inside
quasiquote to suppress
void values when
test is
#f. As the name suggests, it works in conjunction with the
@ splicing operator.
Convert values to a simple list.
8 String
Return #t if str starts with starter, otherwise #f.
Return #t if str ends with ender, otherwise #f.
Return #t if str starts with a capital letter, otherwise #f.
9 License & source code
This module is licensed under the LGPL.
Source repository at http://github.com/mbutterick/sugar. Suggestions & corrections welcome.