Compare commits

...

92 Commits

Author SHA1 Message Date
Matthew Butterick c90834b77a
Update README.md 3 years ago
Matthew Butterick 990b0b5892 switch from Travis to GH actions 3 years ago
Matthew Butterick 0613eafd85
Update .travis.yml 4 years ago
Matthew Butterick d51509494c
Update README.md 4 years ago
Matthew Butterick 3ce9a7c650 MIT license 4 years ago
Matthew Butterick 2621ec6a75 undebug 5 years ago
Matthew Butterick 2fd6367303 add partition* 5 years ago
Matthew Butterick 0081cdaab8 one more example 5 years ago
Matthew Butterick 3ebda9ac66 typo 5 years ago
Matthew Butterick 297a93767b fix `slicef-after` 5 years ago
Matthew Butterick 73e4b8b0ff
Update .travis.yml 5 years ago
Matthew Butterick 6e226980b7
Until SSL issue is repaired 5 years ago
Matthew Butterick 8bb3201185 error msg 5 years ago
Matthew Butterick dab922be52 Revert "promises"
This reverts commit b22b907663.
5 years ago
Matthew Butterick b22b907663 promises 5 years ago
Matthew Butterick 5fb1d5f633 kw 6 years ago
Matthew Butterick 0036a1b2c4 suppress rounding 6 years ago
Matthew Butterick 865f353e18
Update .travis.yml 6 years ago
Matthew Butterick 9ecad9391c string it 6 years ago
Matthew Butterick f6b3399ba1 punt 6 years ago
Matthew Butterick 68947269ae back out `br` libs 6 years ago
Matthew Butterick 53deef1871 unstablers 6 years ago
Matthew Butterick 942c6d7549 neater 6 years ago
Matthew Butterick a6c0253e65 whoops 6 years ago
Matthew Butterick d362cf9483 fix syntax loc 6 years ago
Matthew Butterick fe9f126074 remove unnecessary predicates 6 years ago
Matthew Butterick f1c7a09a4f stylize 6 years ago
Matthew Butterick f3ba2b714b time-avg 6 years ago
Matthew Butterick 15a86c21a7
Add Rackets 6.11 & 6.12 6 years ago
Matthew Butterick 805ae055c6 add `report/time` and `time-name` 6 years ago
Matthew Butterick 75ac017fee nit 6 years ago
Matthew Butterick 3cd0e1ef4b handle multiple return values in `report` 6 years ago
Matthew Butterick f3441e05cc correct ->path with absolute URLs 6 years ago
Matthew Butterick cae71f0b11 correction 6 years ago
Matthew Butterick f79077aec9 tidier 6 years ago
Matthew Butterick db5bbb9a40 tighten `->complete-path` predicate 7 years ago
Matthew Butterick 803370572d avoid a list operation; fix error messages 7 years ago
Matthew Butterick b7933d769b update sugar/file docs 7 years ago
Matthew Butterick a4d560f7be benign stylistic refactoring 7 years ago
Matthew Butterick fbdde8eeb2 benign stylistic refactoring 7 years ago
Matthew Butterick 569b3d4453 refactor coercions with generics 7 years ago
Matthew Butterick e7126511cf Test Rackets 6.7–6.10 7 years ago
Matthew Butterick fd6c7426c4 correct a source location 7 years ago
Matthew Butterick 1e7d5867a4 + tail recursion 7 years ago
Matthew Butterick a21ba17450 improve error message 7 years ago
Matthew Butterick a8656a88e3 add `shift-left`, `shift-cycle`, `shift-left-cycle` 7 years ago
Matthew Butterick 76783eba0e raise input errors more vigorously in `sugar/list` 8 years ago
Matthew Butterick cfc9ed1408 raise input errors more vigorously in `sugar/file` 8 years ago
Matthew Butterick 3df4526827 test 6.5 and 6.6 8 years ago
Matthew Butterick d77eb3fa68 refactor loops to be less slovenly 8 years ago
Matthew Butterick 78c788ae17 fix handling of hidden files with `remove-ext` 8 years ago
Matthew Butterick 32174aac2e Merge pull request #18 from mbutterick/dev-hidden-files
Make `remove-ext` and `remove-ext*` better handle dot-prefixed paths
8 years ago
Matthew Butterick 63b7f84a89 adjustments 8 years ago
lijunsong bc95ce269e fix #16 remove-ext doesn't work.
The problem was remove-ext (and remove-ext*) function checked the given
path for hidden files. This fix lets remove-ext check file name of the
given path.
8 years ago
Matthew Butterick 5a5c0e3a77 clarifications 8 years ago
Matthew Butterick 71a8d0fca2 correct slight naivete 8 years ago
Matthew Butterick c247a29af7 use `normalize-definition` 8 years ago
Matthew Butterick 6c224835a8 improve tests for `sugar/define` 8 years ago
Matthew Butterick cd1ee2ce21 improve error msgs in macro 8 years ago
Matthew Butterick 5e283216a6 tiny refactoring 8 years ago
Matthew Butterick 4a8385aa96 fix doc dep 8 years ago
Matthew Butterick 5b53ea9653 adjust testing macro 8 years ago
Matthew Butterick 3fab229f40 missing dep 8 years ago
Matthew Butterick 6f4bbeefe6 adjust info.rkt 8 years ago
Matthew Butterick e2112c9ce8 reorg source 8 years ago
Matthew Butterick 70b092a1f3 adjust license 8 years ago
Matthew Butterick 2c59ab3974 simplify 8 years ago
Matthew Butterick 90f7eef3e8 test 6.4 8 years ago
Matthew Butterick 89d53b9d57 fix missing provide 8 years ago
Matthew Butterick d8e538d53e first versioned release 8 years ago
Matthew Butterick e613f0cade remove `when/splice` 8 years ago
Matthew Butterick 00e9fabdb8 asciify error msgs 8 years ago
Matthew Butterick c804976b96 Update travis with 6.3 9 years ago
Matthew Butterick 809b7435b7 untype 9 years ago
Matthew Butterick 37f923be8d uncurl apostrophes 9 years ago
Matthew Butterick 81ebd198a7 Update .travis.yml
Add 6.2.1 and allow failures on HEAD
9 years ago
Matthew Butterick 947d9040d1 Merge pull request #11 from samth/fix-new-expander
This fixes sugar and pollen to work with the new expander. I believe that it will work on 6.2 as well.
9 years ago
Sam Tobin-Hochstadt 351346054c Minor fixes, should now work on 6.2. 9 years ago
Sam Tobin-Hochstadt 07e98cd6a9 Fix for new set output order.
This test really ought to be changed somehow.
9 years ago
Sam Tobin-Hochstadt 0be362e112 Fix for new expander. 9 years ago
Matthew Butterick db17d1860b Merge pull request #10 from AlexKnauth/fix-debug-repl
fix repl for #lang sugar/debug in old expander
9 years ago
AlexKnauth 4c5f408677 fix repl for #lang sugar/debug in old expander 9 years ago
Matthew Butterick 8a121f2006 update test 9 years ago
Matthew Butterick 7fe01da7a5 change debug escape to #R 9 years ago
Matthew Butterick 39800fcc4e Merge pull request #8 from AlexKnauth/patch-1
#lang sugar/debug: use #^ instead of ^
9 years ago
Alex Knauth 091774a1cb update test file 9 years ago
Alex Knauth 76e721f52b #lang sugar/debug: use #^ instead of ^
fixes https://github.com/mbutterick/sugar/issues/7
9 years ago
Matthew Butterick a22c0ad753 nit, picked 9 years ago
Matthew Butterick 0ffe317387 add syntactic shorthand for `report` 9 years ago
Matthew Butterick ecce73cdc3 Merge pull request #6 from AlexKnauth/debug-meta-lang
debug-meta-lang: make (require sugar/debug) unnecessary
9 years ago
AlexKnauth 65467b72b4 debug-meta-lang: make (require sugar/debug) unnecessary
and make it hygienic
9 years ago
Matthew Butterick aa97dea3f8 Update .travis.yml 9 years ago

@ -0,0 +1,43 @@
name: CI
on: [push, pull_request]
jobs:
run:
name: "Build using Racket '${{ matrix.racket-version }}' (${{ matrix.racket-variant }})"
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
racket-version: ["6.6", "6.7", "6.8", "6.9", "6.10.1", "6.11", "6.12", "7.0", "7.1", "7.2", "7.3", "7.4", "7.5", "7.6", "7.7", "7.8", "7.9", "current"]
racket-variant: ["BC", "CS"]
# CS builds are only provided for versions 7.4 and up so avoid
# running the job for prior versions.
exclude:
- {racket-version: "6.6", racket-variant: "CS"}
- {racket-version: "6.7", racket-variant: "CS"}
- {racket-version: "6.8", racket-variant: "CS"}
- {racket-version: "6.9", racket-variant: "CS"}
- {racket-version: "6.10.1", racket-variant: "CS"}
- {racket-version: "6.11", racket-variant: "CS"}
- {racket-version: "6.12", racket-variant: "CS"}
- {racket-version: "7.0", racket-variant: "CS"}
- {racket-version: "7.1", racket-variant: "CS"}
- {racket-version: "7.2", racket-variant: "CS"}
- {racket-version: "7.3", racket-variant: "CS"}
steps:
- name: Checkout
uses: actions/checkout@master
- uses: Bogdanp/setup-racket@v0.11
with:
distribution: 'full'
version: ${{ matrix.racket-version }}
variant: ${{ matrix.racket-variant }}
- name: Install Sugar and its dependencies
run: raco pkg install --auto --batch
- name: Run the tests
run: xvfb-run raco test -j 4 -p sugar

@ -1,33 +0,0 @@
# adapted from
# https://github.com/greghendershott/travis-racket/blob/master/.travis.yml
# Thanks Greg!
language: c
sudo: false
env:
global:
- RACKET_DIR=~/racket
matrix:
- RACKET_VERSION=6.0
- RACKET_VERSION=6.1
- RACKET_VERSION=6.2
- RACKET_VERSION=HEAD
#branches:
# only:
# - master
# - typed
matrix:
fast_finish: true
before_install:
- git clone https://github.com/mbutterick/travis-racket.git
- cat travis-racket/install-racket.sh | bash # pipe to bash not sh!
- export PATH="${RACKET_DIR}/bin:${PATH}" #install-racket.sh can't set for us
script:
- cd .. # Travis did a cd into the dir. Back up, for the next:
- raco pkg install --deps search-auto --link sugar
- raco test -p sugar

@ -1,165 +0,0 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

@ -0,0 +1,9 @@
MIT License for `sugar`
© 2014-2019 Matthew Butterick
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@ -1,5 +1,4 @@
Sugar [![Build Status](https://travis-ci.org/mbutterick/sugar.svg?branch=master)](https://travis-ci.org/mbutterick/sugar)
-----
## Sugar ![Build Status](https://github.com/mbutterick/sugar/workflows/CI/badge.svg)
Functions that improve the readability of Racket code in Racket 6.0+.
@ -15,8 +14,13 @@ In safe mode (with contracts):
(require (submod sugar safe))
Or in typed mode:
You can [read the docs here](http://pkg-build.racket-lang.org/doc/sugar).
(require typed/sugar)
You can [read the docs here](http://pkg-build.racket-lang.org/doc/sugar).
## License
MIT
## Project status
Complete. Maintained but no improvements planned. I dont disavow this code, exactly, and I maintain other projects that rely on it. But it arises from a more naive era of personal Racketeering. I would not necessarily recommend taking inspiration from the code herein.

@ -1,7 +1,5 @@
#lang info
(define collection 'multi)
(define deps '("base"
"typed-racket-lib"
"typed-racket-more"
"rackunit-lib"))
(define build-deps '("scribble-lib" "racket-doc" "typed-racket-doc"))
(define version "0.3")
(define deps '("base"))
(define build-deps '("scribble-lib" "racket-doc" "rackunit-lib"))

@ -1,6 +1,17 @@
#lang racket/base
(require sugar/define)
(require-via-wormhole "../typed/sugar/cache.rkt")
(require (for-syntax
racket/base
"private/syntax-utils.rkt")
"define.rkt")
(provide+safe [make-caching-proc (procedure? . -> . procedure?)]
define/caching)
(define+provide+safe (make-caching-proc base-proc)
(procedure? . -> . procedure?)
(let ([cache (make-hash)])
(make-keyword-procedure
(λ (kws kw-args . args)
(hash-ref! cache (list* kws kw-args args) (λ () (keyword-apply base-proc kws kw-args args)))))))
(provide+safe define/caching)
(define-syntax (define/caching stx)
(with-syntax ([(ID LAMBDA-EXPR) (lambdafy stx)])
#'(define ID (make-caching-proc LAMBDA-EXPR))))

@ -1,3 +0,0 @@
#lang racket/base
;; isolate typed requires in a helper file so the untyped versions can be substituted on the untyped side
(require net/url)

@ -1,75 +1,4 @@
#lang racket/base
(require (for-syntax racket/base racket/syntax) sugar/define net/url)
(require-via-wormhole "../typed/sugar/coerce.rkt")
(require "private/syntax-utils.rkt")
(provide+safe [->int (any/c . -> . integer?)]
[->string (any/c . -> . string?)]
[->symbol (any/c . -> . symbol?)]
[->path (any/c . -> . path?)]
[->complete-path (any/c . -> . complete-path?)]
[->url (any/c . -> . url?)]
[->list (any/c . -> . list?)]
[->vector (any/c . -> . vector?)]
[->boolean (any/c . -> . boolean?)])
;; coercion contracts & *ish predicates
;; only make sense in untyped code
;; thus they are here.
(define-syntax-rule (make-blame-handler try-proc expected-sym)
(λ(b)
(λ(x)
(with-handlers ([exn:fail? (λ(e)
(raise-blame-error
b x
'(expected: "~a" given: "~e")
expected-sym x))])
(try-proc x)))))
(provide+safe make-coercion-contract)
(define-syntax (make-coercion-contract stx)
(syntax-case stx ()
[(_ stem coerce-proc)
(with-syntax ([coerce/stem? (format-id stx "coerce/~a?" #'stem)]
[can-be-stem? (format-id stx "can-be-~a?" #'stem)])
#'(make-contract
#:name 'coerce/stem?
#:projection (make-blame-handler coerce-proc 'can-be-stem?)))]
[(_ stem)
(with-syntax ([->stem (format-id stx "->~a" #'stem)])
#'(make-coercion-contract stem ->stem))]))
(define-syntax (define+provide-coercion-contract stx)
(syntax-case stx ()
[(_ stem)
(with-syntax ([coerce/stem? (format-id stx "coerce/~a?" #'stem)])
#'(begin
(provide+safe coerce/stem?)
(define coerce/stem? (make-coercion-contract stem))))]))
(define+provide-coercion-contract int)
(define+provide-coercion-contract string)
(define+provide-coercion-contract symbol)
(define+provide-coercion-contract path)
(define+provide-coercion-contract boolean)
(define+provide-coercion-contract list)
(define-syntax (make-*ish-predicate stx)
(syntax-case stx ()
[(_ stem)
(with-syntax ([stemish? (format-id stx "~aish?" #'stem)]
[->stem (format-id stx "->~a" #'stem)])
#`(begin
(provide+safe stemish?)
(define (stemish? x)
(with-handlers ([exn:fail? (λ(e) #f)]) (and (->stem x) #t)))))]))
(make-*ish-predicate int)
(make-*ish-predicate string)
(make-*ish-predicate symbol)
(make-*ish-predicate url)
(make-*ish-predicate complete-path)
(make-*ish-predicate path)
(make-*ish-predicate list)
(make-*ish-predicate vector)
(require+provide/safe "coerce/base.rkt" "coerce/contract.rkt")

@ -0,0 +1,123 @@
#lang racket/base
(require (for-syntax
racket/base
racket/syntax)
racket/stream
racket/generic
net/url
racket/sequence
"../unstable/len.rkt"
"../define.rkt")
(module+ safe (require racket/contract))
(define-syntax-rule (make-coercion-error-handler func funcish val)
(λ (exn) (raise-argument-error 'func (symbol->string 'funcish) val)))
(define (disjoin . preds) (λ (x) (ormap (λ (pred) (pred x)) preds)))
(define (conjoin . preds) (λ (x) (andmap (λ (pred) (pred x)) preds)))
(define-generics+provide+safe stringish
(any/c . -> . string?)
(->string stringish)
#:fast-defaults
([string? (define ->string values)]
[(disjoin null? void?) (define (->string x) "")]
[symbol? (define ->string symbol->string)]
[number? (define ->string number->string)]
[path? (define ->string path->string)]
[(disjoin char? bytes?) (define (->string x) (format "~a" x))]
[url? (define ->string url->string)]))
(define (real->int x) (inexact->exact (floor x)))
(define (string->int x) (let ([strnum (string->number x)])
(unless (real? strnum)
(raise-argument-error '->int "eligible string" x))
(real->int strnum)))
(define-generics+provide+safe intish
(any/c . -> . integer?)
(->int intish)
#:fast-defaults
([(disjoin integer? real?) (define ->int real->int)]
[complex? (define ->int (compose1 real->int real-part))]
[string? (define ->int string->int)]
[(disjoin symbol? path? bytes?) (define ->int (compose1 string->int ->string))]
[char? (define ->int char->integer)]
[lengthable? (define (->int x)
(with-handlers ([exn:fail? (make-coercion-error-handler ->int intish? x)])
(len x)))]))
(define-generics+provide+safe symbolish
(any/c . -> . symbol?)
(->symbol symbolish)
#:fast-defaults
([symbol? (define ->symbol values)]
[stringish? (define (->symbol x)
(with-handlers ([exn:fail? (make-coercion-error-handler ->symbol symbolish? x)])
(string->symbol (->string x))))]))
(define-generics+provide+safe pathish
(any/c . -> . path?)
(->path pathish)
#:fast-defaults
([path? (define ->path values)]
[stringish? (define (->path x)
(with-handlers ([exn:fail? (make-coercion-error-handler ->path pathish? x)])
(if (url? x)
(url->path x)
(string->path (->string x)))))]))
(define-generics+provide+safe urlish
(any/c . -> . url?)
(->url urlish)
#:fast-defaults
([url? (define ->url values)]
[stringish? (define (->url x)
(with-handlers ([exn:fail? (make-coercion-error-handler ->url urlish? x)])
(string->url (->string x))))]))
(define-generics+provide+safe complete-pathish
(any/c . -> . complete-path?)
(->complete-path complete-pathish)
#:fast-defaults
([(conjoin path? complete-path?)
;; caution: plain `complete-path?` returns #t for path strings,
;; so also check `path?`
(define ->complete-path values)]
[stringish? (define (->complete-path x)
(with-handlers ([exn:fail? (make-coercion-error-handler ->complete-path complete-pathish? x)])
(path->complete-path (->path x))))]))
(define-generics+provide+safe listish
(any/c . -> . list?)
(->list listish)
#:fast-defaults
([list? (define ->list values)]
[string? (define ->list list)]
[vector? (define ->list vector->list)]
[hash? (define ->list hash->list)]
[integer? (define ->list list)]
[sequence? (define ->list sequence->list)]
[stream? (define ->list stream->list)]
[(λ (x) #t) (define ->list list)]))
(define-generics+provide+safe vectorish
(any/c . -> . vector?)
(->vector vectorish)
#:fast-defaults
([vector? (define ->vector values)]
[listish? (define (->vector x)
(with-handlers ([exn:fail? (make-coercion-error-handler ->vector vectorish? x)])
(list->vector (->list x))))]))
(define+provide+safe (->boolean x)
(any/c . -> . boolean?)
(and x #t))

@ -0,0 +1,46 @@
#lang racket/base
(require (for-syntax racket/base racket/syntax) racket/contract "../define.rkt" "base.rkt")
(define-syntax-rule (make-blame-handler PROC EXPECTED)
(λ (b)
(λ (x) (with-handlers ([exn:fail? (λ (exn)
(raise-blame-error b x
'(expected: "~a" given: "~e")
EXPECTED x))])
(PROC x)))))
(provide+safe make-coercion-contract)
(define-syntax (make-coercion-contract stx)
(syntax-case stx ()
[(_ STEM COERCE-PROC)
(with-syntax ([COERCE/STEM? (format-id stx "coerce/~a?" #'STEM)]
[STEMISH? (format-id stx "~aish?" #'STEM)])
#'(make-contract
#:name 'COERCE/STEM?
#:projection (make-blame-handler COERCE-PROC 'STEMISH?)))]
[(MACRO-NAME STEM)
(with-syntax ([->STEM (format-id stx "->~a" #'STEM)])
#'(MACRO-NAME STEM ->STEM))]))
(define-syntax (define+provide-coercion-contract stx)
(syntax-case stx ()
[(_ STEM)
(with-syntax ([COERCE/STEM? (format-id stx "coerce/~a?" #'STEM)])
#'(begin
(provide+safe COERCE/STEM?)
(define COERCE/STEM? (make-coercion-contract STEM))))]))
(define-syntax-rule (define+provide-coercion-contracts STEM ...)
(begin (define+provide-coercion-contract STEM) ...))
(define+provide-coercion-contracts int
string
symbol
path
boolean
list)

@ -1,46 +0,0 @@
#lang racket/base
(require "define.rkt" "coerce.rkt" "len.rkt" racket/list racket/set racket/sequence racket/stream racket/dict)
(define (sliceable-container? x)
(ormap (λ(proc) (proc x)) (list list? string? symbol? vector? path? (λ(i) (and (not (dict? i)) (sequence? i))))))
(define (gettable-container? x)
(ormap (λ(proc) (proc x)) (list sliceable-container? dict?)))
(define+provide+safe (get container start [end #f])
((gettable-container? any/c) ((or/c (and/c integer? positive?) #f)) . ->* . any)
(define result
;; use handler to capture error & print localized error message
(with-handlers ([exn:fail? (λ(exn) (error (format "get: couldnt retrieve ~a from ~a" (if end (format "items ~a through ~a" start end) (format "item ~a" start)) container)))])
(let ([end (if (and (equal? end #f) (sliceable-container? container)) (add1 start) end)])
(cond
[(list? container) (for/list ([i (in-range start end)]) (list-ref container i))]
[(vector? container) (for/vector ([i (in-range start end)]) (vector-ref container i))]
[(string? container) (substring container start end)]
[(symbol? container) (->symbol (get (->string container) start end))]
[(path? container) (get (explode-path container) start end)]
[(dict? container) (dict-ref container start)]
[(sequence? container) (get (->list container) start end)]
[else (error)]))))
;; don't return single-item results inside a list
;; check for integer because integers don't have length
(if (and (not (integer? result)) (= (len result) 1) (sliceable-container? container))
(car (->list result))
result))
(define (listlike-container? container)
(ormap (λ(pred) (pred container)) (list vector? set? sequence?)))
(define+provide+safe (in? item container)
(any/c any/c . -> . boolean?)
(->boolean (cond
[(list? container) (member item container)]
[(dict? container) (dict-has-key? container item)]
[(path? container) (in? (->path item) (explode-path container))]
[(stringish? container) (regexp-match (->string item) (->string container))]
;; location relevant because dicts and strings are also listlike (= sequences)
[(listlike-container? container) (in? item (->list container))]
[else #f])))

@ -1,7 +1,184 @@
#lang racket/base
(require sugar/define)
(require-via-wormhole "../typed/sugar/debug.rkt")
(require racket/string
(for-syntax racket/base)
"define.rkt")
(provide+safe report report/line report/file
(provide+safe report report/time time-name
report/line report/file
report* report*/line report*/file
report-apply repeat time-repeat time-repeat* compare)
report-apply repeat time-repeat time-repeat* time-name time-named time-avg compare)
(define (stringify-results expr-results)
(format (if (= 1 (length expr-results))
"~a"
"(values ~a)") (string-join (for/list ([r (in-list expr-results)])
(format "~v" r)) " ")))
(define-syntax (report stx)
(syntax-case stx ()
[(MACRO EXPR) #'(MACRO EXPR EXPR)]
[(_ EXPR NAME)
#'(let ([expr-results (call-with-values (λ () EXPR) list)])
(eprintf "~a = ~a\n" 'NAME (stringify-results expr-results))
(apply values expr-results))]))
(define-syntax (report/time stx)
(syntax-case stx ()
[(MACRO EXPR) #'(MACRO EXPR EXPR)]
[(_ EXPR NAME)
#'(let* ([op (open-output-string)]
[expr-results (parameterize ([current-output-port op])
(time (call-with-values (λ () EXPR) list)))])
(eprintf "~a = ~a [~a]\n" 'NAME (stringify-results expr-results) (string-trim (get-output-string op)))
(apply values expr-results))]))
(define-syntax (report/line stx)
(syntax-case stx ()
[(MACRO EXPR) #'(MACRO EXPR EXPR)]
[(_ EXPR NAME)
#`(let ([expr-results (call-with-values (λ () EXPR) list)])
(eprintf "~a = ~a on line ~a\n" 'NAME (stringify-results expr-results) #,(syntax-line #'EXPR))
(apply values expr-results))]))
(define-syntax (report/file stx)
(syntax-case stx ()
[(MACRO EXPR) #'(MACRO EXPR EXPR)]
[(_ EXPR NAME)
#`(let ([expr-results (call-with-values (λ () EXPR) list)])
(eprintf "~a = ~a on line ~a in \"~a\"\n" 'NAME (stringify-results expr-results)
#,(syntax-line #'EXPR)
'#,(syntax-source #'EXPR))
(apply values expr-results))]))
(define-syntax-rule (define-multi-version MULTI-NAME NAME)
(define-syntax-rule (MULTI-NAME x (... ...))
(begin (NAME x) (... ...))))
(define-multi-version report* report)
(define-multi-version report*/line report/line)
(define-multi-version report*/file report/file)
(define-syntax (report-apply stx)
(syntax-case stx ()
[(_ PROC EXPR)
#'(let ([lst EXPR])
(report (apply PROC lst) (apply PROC EXPR))
lst)]
[(_ PROC EXPR #:line)
#'(let ([lst EXPR])
(report (apply PROC lst) (apply PROC EXPR) #:line)
lst)]))
(define-syntax-rule (repeat NUM EXPR ...)
(for/last ([i (in-range NUM)])
EXPR ...))
(define-syntax-rule (time-repeat NUM EXPR ...)
(time (repeat NUM EXPR ...)))
(define (parse-time-str str)
(for/list ([num (in-port read (open-input-string str))]
#:when (number? num))
num))
(define-syntax-rule (time-avg NUM EXPR ...)
(let ([n NUM])
(define-values (strs results)
(for/lists (strs results)
([i n])
(let* ([op (open-output-string)]
[expr-results (parameterize ([current-output-port op])
(time (call-with-values (λ () EXPR ...) values)))])
(values (get-output-string op) expr-results))))
(displayln (apply format "~a: cpu time: ~a real time: ~a gc time: ~a (avg of ~a)"
(append
(list (car '(EXPR ...)))
(for/list ([vals (apply map list (map parse-time-str strs))])
(floor (/ (apply + vals) n)))
(list n))))
(car (reverse results))))
(define-syntax (time-repeat* stx)
(syntax-case stx ()
[(_ NUM EXPR ...)
#'(let ([n NUM])
(values (time-repeat n EXPR) ...))]))
(define-syntax (time-name stx)
(syntax-case stx ()
[(_ NAME EXPR ...)
#'(let* ([op (open-output-string)]
[expr-results (parameterize ([current-output-port op])
(time (call-with-values (λ () EXPR ...) values)))])
(display (format "~a: ~a" 'NAME (get-output-string op)))
expr-results)]))
(define-syntax (time-named stx)
(syntax-case stx ()
[(_ EXPR ...)
#'(let* ([op (open-output-string)]
[expr-results (parameterize ([current-output-port op])
(time (call-with-values (λ () EXPR ...) values)))])
(display (format "~a: ~a" (car '(EXPR ...)) (get-output-string op)))
expr-results)]))
(define-syntax (compare stx)
(syntax-case stx ()
[(_ EXPR ID ID-ALT ...)
#'(values EXPR (let ([ID ID-ALT]) EXPR) ...)]))
(module reader racket/base
(require syntax/module-reader racket/syntax version/utils)
(provide (rename-out [debug-read read]
[debug-read-syntax read-syntax]
[debug-get-info get-info]))
(define current-metalang-scope-flipper (make-parameter values))
(define (wrap-reader reader)
(λ args
(parameterize ([current-readtable (make-debug-readtable (current-readtable))]
[current-metalang-scope-flipper (make-syntax-introducer)])
(define stx (apply reader args))
(define proc (if (and (syntax? stx) (version<=? "6.2.900.4" (version)))
(current-metalang-scope-flipper)
values))
(proc stx))))
(define-values (debug-read debug-read-syntax debug-get-info)
(make-meta-reader
'sugar/debug
"language path"
(λ (bstr) ; copy of `lang-reader-module-paths`, only available since 6.7
(let* ([str (bytes->string/latin-1 bstr)]
[sym (string->symbol str)])
(and (module-path? sym)
(vector
;; try submod first:
`(submod ,sym reader)
;; fall back to /lang/reader:
(string->symbol (string-append str "/lang/reader"))))))
wrap-reader
wrap-reader
(λ (proc)
(λ (key defval)
(case key
[else (if proc (proc key defval) defval)])))))
(define report-char #\R)
(define (make-debug-readtable [rt (current-readtable)])
(make-readtable rt report-char 'dispatch-macro report-proc))
(define (another-report-char? ip) (and (char=? (peek-char ip) report-char) (read-char ip)))
(define (report-proc trigger-char ip src ln col pos)
(define flip-metalang-scope (current-metalang-scope-flipper))
(flip-metalang-scope (with-syntax ([REPORT-ID (cond
[(not (another-report-char? ip)) 'report] ; #R...
[(not (another-report-char? ip)) 'report/line] ; #RR...
[else 'report/file])] ; #RRR...
[STX (flip-metalang-scope (read-syntax/recursive src ip))])
#'(let ()
(local-require (only-in sugar/debug REPORT-ID))
(REPORT-ID STX))))))

@ -1,28 +0,0 @@
(module reader racket/base
(require syntax/module-reader
(only-in "../../reader.rkt" make-debug-readtable wrap-reader))
(provide (rename-out [debug-read read]
[debug-read-syntax read-syntax]
[debug-get-info get-info]))
(define-values (debug-read debug-read-syntax debug-get-info)
(make-meta-reader
'sugar/debug/lang
"language path"
(lambda (bstr)
(let* ([str (bytes->string/latin-1 bstr)]
[sym (string->symbol str)])
(and (module-path? sym)
(vector
;; try submod first:
`(submod ,sym reader)
;; fall back to /lang/reader:
(string->symbol (string-append str "/lang/reader"))))))
wrap-reader
wrap-reader
(lambda (proc)
(lambda (key defval)
(define (fallback) (if proc (proc key defval) defval))
(case key
[else (fallback)]))))))

@ -1,30 +0,0 @@
#lang racket/base
(provide make-debug-readtable wrap-reader)
(require racket/syntax)
(define (make-debug-readtable [rt (current-readtable)])
(make-readtable rt
#\^ 'dispatch-macro report-proc
))
(define/with-syntax report (datum->syntax #f 'report))
(define/with-syntax report/line (datum->syntax #f 'report/line))
(define (report-proc c in src ln col pos)
(define c2 (peek-char in))
(cond [(char=? c2 #\^)
(read-char in)
(define stx (read-syntax/recursive src in))
#`(report/line #,stx)]
[else
(define stx (read-syntax/recursive src in))
#`(report #,stx)]))
(define (wrap-reader reader)
(define (rd . args)
(parameterize ([current-readtable (make-debug-readtable (current-readtable))])
(apply reader args)))
rd)

@ -1,96 +1,69 @@
#lang racket/base
(require (for-syntax racket/base))
(require racket/contract)
(provide (all-from-out racket/contract))
;; get gets of typed source file, recompile it without typing in a submodule,
;; then require those identifiers into the current level.
(define-syntax (require-via-wormhole stx)
(syntax-case stx ()
[(_ path-spec)
(let ([mod-name (gensym)])
;; need to use stx as context to get correct require behavior
(datum->syntax stx `(begin
(module mod-name typed/racket/base/no-check
(require sugar/include)
(include-without-lang-line ,(syntax->datum #'path-spec)))
(require (quote mod-name)))))]))
;; each define macro recursively converts any form of define
;; into its lambda form (define name body ...) and then operates on that.
(require (for-syntax racket/base
racket/syntax
syntax/strip-context
"private/syntax-utils.rkt")
racket/contract)
(define-syntax (make-safe-module stx)
(syntax-case stx ()
[(_ name contract)
#'(module+ safe
(require racket/contract)
(provide (contract-out [name contract])))]
[(_ name)
#'(module+ safe
(provide name))]))
[(_ [ID CONTRACT])
;; need to put `racket/contract` inside calling location's context
(with-syntax ([RACKET/CONTRACT (datum->syntax #'ID 'racket/contract)])
#'(module+ safe
(require RACKET/CONTRACT)
(provide (contract-out [ID CONTRACT]))))]
[(_ ID)
#'(module+ safe
(provide ID))]))
(define-syntax (define+provide+safe stx)
(syntax-case stx ()
[(_ (proc arg ... . rest-arg) contract body ...)
#'(define+provide+safe proc contract
(λ(arg ... . rest-arg) body ...))]
[(_ name contract body ...)
#'(begin
(define name body ...)
(provide name)
(make-safe-module name contract))]))
(with-syntax ([(ID CONTRACT LAMBDA-EXP) (lambdafy-with-contract stx)])
#'(begin
(define ID LAMBDA-EXP)
(provide+safe [ID CONTRACT]))))
;; for previously defined identifiers
;; takes args like (provide+safe [ident contract]) or just (provide+safe ident)
;; takes args like (provide+safe [id contract]) or just (provide+safe id)
;; any number of args.
(define-syntax (provide+safe stx)
(syntax-case stx ()
[(_ items ...)
(datum->syntax stx
`(begin
,@(for/list ([item (in-list (syntax->datum #'(items ...)))])
(define-values (name contract) (if (pair? item)
(values (car item) (cadr item))
(values item #f)))
`(begin
(provide ,name)
(make-safe-module ,name ,@(if contract (list contract) null))))))]))
(define-syntax-rule (provide+safe THING ...)
(begin
(provide+safe/once THING) ...))
(define-syntax (define+provide/contract stx)
(syntax-case stx ()
[(_ (proc arg ... . rest-arg) contract body ...)
#'(define+provide/contract proc contract
(λ(arg ... . rest-arg) body ...))]
[(_ name contract body ...)
#'(begin
(provide (contract-out [name contract]))
(define name body ...))]))
;; `provide+safe` might have interleaved ids or [id contract] args so handle them individually.
(define-syntax (provide+safe/once stx)
(with-syntax ([(ID MSM-ARG) (syntax-case stx ()
[(_ [ID contract])
#'(ID [ID contract])]
[(_ id)
#'(id id)])])
#'(begin
(provide ID)
(make-safe-module MSM-ARG))))
(define-syntax (define+provide/contract stx)
(with-syntax* ([(ID CONTRACT LAMBDA-EXP) (lambdafy-with-contract stx)]
[RACKET/CONTRACT (datum->syntax #'ID 'racket/contract)])
#'(begin
(require RACKET/CONTRACT)
(provide (contract-out [ID CONTRACT]))
(define ID LAMBDA-EXP))))
(define-syntax (define/contract+provide stx)
(syntax-case stx ()
[(_ (proc arg ... . rest-arg) contract body ...)
#'(define/contract+provide proc contract
(λ(arg ... . rest-arg) body ...))]
[(_ name contract body ...)
#'(begin
(provide name)
(define/contract name contract body ...))]))
(with-syntax* ([(ID CONTRACT LAMBDA-EXP) (lambdafy-with-contract stx)]
[RACKET/CONTRACT (datum->syntax #'ID 'racket/contract)])
#'(begin
(require RACKET/CONTRACT)
(provide ID)
(define/contract ID CONTRACT LAMBDA-EXP))))
(define-syntax (define+provide stx)
(syntax-case stx ()
[(_ (proc arg ... . rest-arg) body ...)
#'(define+provide proc
(λ(arg ... . rest-arg) body ...))]
[(_ name body ...)
#'(begin
(provide name)
(define name body ...))]))
(with-syntax ([(ID LAMBDA-EXP) (lambdafy stx)])
#'(begin
(provide ID)
(define ID LAMBDA-EXP))))
(provide+safe require-via-wormhole
make-safe-module
(provide+safe make-safe-module
define+provide+safe
provide+safe
define+provide/contract

@ -1,14 +1,100 @@
#lang racket/base
(require sugar/define racket/set sugar/coerce)
(require-via-wormhole "../typed/sugar/file.rkt")
(provide+safe
[get-enclosing-dir (coerce/path? . -> . path?)]
[has-ext? (coerce/path? coerce/string? . -> . coerce/boolean?)]
[get-ext (coerce/path? . -> . (or/c #f string?))]
binary-extensions
[has-binary-ext? (coerce/path? . -> . coerce/boolean?)]
[add-ext (coerce/string? coerce/string? . -> . coerce/path?)]
[remove-ext (coerce/path? . -> . path?)]
[remove-ext* (coerce/path? . -> . path?)])
(require racket/list
racket/match
(except-in racket/path filename-extension)
"define.rkt"
"coerce/base.rkt")
;; this is identical to `filename-extension` in `racket/path`
;; but will not treat hidden files as an extension (which is a bug)
(define (filename-extension name)
(match (file-name-from-path name)
[(? path-for-some-system? filename)
(=> resume)
(match (regexp-match #rx#".[.]([^.]+)$" (path->bytes filename))
[(list _ second) second]
[_ (resume)])]
[_ #false]))
(module+ test
(require rackunit)
(require (prefix-in rp: racket/path))
(check-equal? (rp:filename-extension (string->path ".foo")) #"foo") ; bad behavior
(check-false (filename-extension (string->path ".foo")))) ; good behavior
;; does path have a certain extension, case-insensitively
(define+provide+safe (has-ext? x ext)
(pathish? stringish? . -> . boolean?)
(unless (pathish? x)
(raise-argument-error 'has-ext? "pathish?" x))
(unless (stringish? ext)
(raise-argument-error 'has-ext? "stringish?" ext))
(define ext-of-path (filename-extension (->path x)))
(and ext-of-path (string=? (string-downcase (bytes->string/utf-8 ext-of-path))
(string-downcase (->string ext)))))
;; get file extension as a string, or return #f
;; (consistent with filename-extension behavior)
(define+provide+safe (get-ext x)
(pathish? . -> . (or/c #f string?))
(unless (pathish? x)
(raise-argument-error 'get-ext "pathish?" x))
(cond
[(filename-extension (->path x)) => bytes->string/utf-8]
[else #false]))
;; todo: add extensions
(provide+safe binary-extensions)
(define binary-extensions
(map symbol->string '(gif jpg jpeg mp3 png zip pdf ico tar ai eps exe)))
(define+provide+safe (has-binary-ext? x)
(pathish? . -> . boolean?)
(unless (pathish? x)
(raise-argument-error 'has-binary-ext? "pathish?" x))
(for/or ([ext (in-list binary-extensions)]
#:when (has-ext? (->path x) ext))
#true))
;; put extension on path
;; use local contract here because this function is used within module
(define+provide+safe (add-ext x ext)
(stringish? stringish? . -> . pathish?)
(unless (stringish? x)
(raise-argument-error 'add-ext "stringish?" x))
(unless (stringish? ext)
(raise-argument-error 'add-ext "stringish?" ext))
(->path (string-append (->string x) "." (->string ext))))
(define (starts-with? str starter)
(define pat (regexp (format "^~a" (regexp-quote starter))))
(and (regexp-match pat str) #true))
(define (path-hidden? path)
((->string (file-name-from-path path)) . starts-with? . "."))
(define (change-hide-state new-hide-state path)
(define reversed-path-elements (reverse (explode-path path)))
(apply build-path (append (reverse (cdr reversed-path-elements))
(list (if (eq? new-hide-state 'hide)
(format ".~a" (->string (car reversed-path-elements)))
(regexp-replace #rx"^." (->string (car reversed-path-elements)) ""))))))
;; take one extension off path
(define+provide+safe (remove-ext x)
(pathish? . -> . path?)
;; `path-replace-suffix` incorrectly thinks any leading dot counts as a file extension
;; when it might be a hidden path.
;; so handle hidden paths specially.
;; this is fixed in later Racket versions with `path-replace-extension`
(match (->path x)
[(? path-hidden? path) (change-hide-state 'hide (path-replace-suffix (change-hide-state 'unhide path) ""))]
[path (path-replace-suffix path "")]))
;; take all extensions off path
(define+provide+safe (remove-ext* x)
(pathish? . -> . path?)
(let loop ([path (->path x)])
(match (remove-ext path)
[(== path) path]
[path-reduced (loop path-reduced)])))

@ -1,4 +1,3 @@
#lang info
(define scribblings '(("scribblings/sugar.scrbl" ())))
(define compile-omit-paths '("test"))
(define compile-omit-paths '("test"))

@ -1,5 +0,0 @@
#lang racket/base
(require sugar/define racket/set)
(require-via-wormhole "../typed/sugar/len.rkt")
(provide+safe [len ((or/c list? vector? set? sequence? string? symbol? path? hash?) . -> . integer?)])

@ -1,3 +0,0 @@
#lang racket/base
;; isolate typed requires in a helper file so the untyped versions can be substituted on the untyped side
(require (only-in racket/list dropf dropf-right))

@ -1,40 +1,217 @@
#lang racket/base
(require (for-syntax racket/base)
racket/list racket/set racket/function sugar/define)
(require "len.rkt" "coerce.rkt")
(require-via-wormhole "../typed/sugar/list.rkt")
(define (list-of-lists? xs) (and (list? xs) (andmap list? xs)))
(define (index? x) (and (integer? x) (not (negative? x))))
(define increasing-nonnegative? (λ(xs) (apply < -1 xs)))
(define increasing-nonnegative-list? (and/c list? increasing-nonnegative?))
(define (integers? x) (and (list? x) (andmap integer? x)))
(provide+safe [trimf (list? procedure? . -> . list?)]
[slicef (list? procedure? . -> . list-of-lists?)]
[slicef-at ((list? procedure?) (boolean?) . ->* . list-of-lists?)]
[slicef-after (list? procedure? . -> . list-of-lists?)]
[slice-at ((list? (and/c integer? positive?)) (boolean?) . ->* . list-of-lists?)]
[filter-split (list? predicate/c . -> . list-of-lists?)]
[frequency-hash (list? . -> . hash?)]
[members-unique? ((or/c list? vector? string?) . -> . boolean?)]
[members-unique?/error ((or/c list? vector? string?) . -> . boolean?)]
when/splice
values->list
[sublist (list? index? index? . -> . list?)]
[break-at (list? (and/c coerce/list? (or/c empty? increasing-nonnegative-list?)) . -> . list-of-lists?)]
[shift ((list? integer?) (any/c boolean?) . ->* . list?)]
[shifts ((list? integers?) (any/c boolean?) . ->* . (listof list?))]
[shift/values ((list? (or/c integers? integer?)) (any/c boolean?) . ->* . any)])
;; todo: can this work in typed context? couldn't figure out how to polymorphically `apply values`
;; macro doesn't work either
(define (shift/values xs shift-amount-or-amounts [fill-item #f] [cycle #f])
(require (for-syntax
racket/base)
racket/list
racket/match
racket/function
"define.rkt")
(define (increasing-nonnegative-list? x)
(and (list? x) (or (empty? x) (apply < -1 x))))
(define+provide+safe (trimf xs test-proc)
(list? procedure? . -> . list?)
(unless (list? xs)
(raise-argument-error 'trimf "list?" xs))
(dropf-right (dropf xs test-proc) test-proc))
(define (slicef-and-filter-split-helper xs pred [separate-negated? #f])
(let loop ([xs xs][negating? #f][acc empty][negated-acc empty])
(match xs
[(? empty?) (if separate-negated?
(values (reverse acc) (reverse negated-acc))
(reverse acc))]
[(list* (? (if negating? (negate pred) pred) pred-xs) ... other-xs)
(cond
[(and negating? separate-negated?)
(loop other-xs
(not negating?)
acc
(match pred-xs
[(? empty?) negated-acc]
[_ (cons pred-xs negated-acc)]))]
[else
(loop other-xs
(not negating?)
(match pred-xs
[(? empty?) acc]
[_ (cons pred-xs acc)])
negated-acc)])])))
(define+provide+safe (slicef xs pred)
(list? procedure? . -> . (listof list?))
(unless (list? xs)
(raise-argument-error 'slicef "list?" xs))
(slicef-and-filter-split-helper xs pred))
(define+provide+safe (slicef-at xs pred [force? #f])
((list? procedure?) (boolean?) . ->* . (listof list?))
(unless (list? xs)
(raise-argument-error 'slicef-at "list?" xs))
(unless (procedure? pred)
(raise-argument-error 'slicef-at "procedure?" pred))
(let loop ([xs xs][acc empty])
(match xs
[(== empty) (reverse acc)]
[(list* (? pred pred-x) (? (negate pred) not-pred-xs) ... tail)
(loop tail (cons (cons pred-x not-pred-xs) acc))]
[(list* (? (negate pred) not-pred-xs) ... tail)
(loop tail (if force? acc (cons not-pred-xs acc)))])))
(define+provide+safe (slicef-after xs pred [force? #f])
((list? procedure?) (boolean?) . ->* . (listof list?))
(unless (list? xs)
(raise-argument-error 'slicef-after "list?" xs))
(unless (procedure? pred)
(raise-argument-error 'slicef-after "procedure?" pred))
(let loop ([xs xs][acc empty])
(match xs
[(== empty) (reverse acc)]
[(list* (? (negate pred) not-pred-xs) ... (? pred pred-x) tail)
(loop tail (cons (append not-pred-xs (list pred-x)) acc))]
[tail (loop empty (if force? acc (cons tail acc)))])))
(define+provide+safe (slice-at xs len [force? #f])
((list? exact-nonnegative-integer?) (boolean?) . ->* . (listof list?))
(unless (list? xs)
(raise-argument-error 'slice-at "list?" xs))
(unless (and (integer? len) (positive? len))
(raise-argument-error 'slice-at "positive integer for sublist length" len))
(let loop ([xs xs][slices empty])
(if (< (length xs) len)
(reverse (if (or force? (empty? xs))
slices
(cons xs slices)))
(match/values (split-at xs len)
[(subxs rest) (loop rest (cons subxs slices))]))))
(define+provide+safe (partition* pred xs)
(predicate/c list? . -> . (values list? list?))
(unless (list? xs)
(raise-argument-error 'partition* "list?" xs))
(slicef-and-filter-split-helper xs pred 'drop-negated))
(define+provide+safe (filter-split xs pred)
(list? predicate/c . -> . (listof list?))
(unless (list? xs)
(raise-argument-error 'filter-split "list?" xs))
;; same idea as slicef, but the negated items are dropped
(define-values (negated-pred-xs _) (partition* (negate pred) xs))
negated-pred-xs)
(define+provide+safe (frequency-hash xs)
(list? . -> . hash?)
(unless (list? xs)
(raise-argument-error 'frequency-hash "list?" xs))
(define counter (make-hash))
(for ([item (in-list xs)])
(hash-update! counter item add1 0))
counter)
(define (->list x)
(match x
[(? list? x) x]
[(? vector?) (vector->list x)]
[(? string?) (string->list x)]
[else (raise-argument-error '->list "item that can be converted to list" x)]))
(define+provide+safe (members-unique? x)
((or/c list? vector? string?) . -> . boolean?)
(match (->list x)
[(? list? x) (= (length (remove-duplicates x)) (length x))]
[_ (raise-argument-error 'members-unique? "list, vector, or string" x)]))
(define+provide+safe (members-unique?/error x)
((or/c list? vector? string?) . -> . boolean?)
(match (members-unique? x)
[(== #false)
(define duplicate-keys (filter values (hash-map (frequency-hash (->list x))
(λ (element freq) (and (> freq 1) element)))))
(error (string-append "members-unique? failed because " (if (= (length duplicate-keys) 1)
"item isn't"
"items aren't") " unique:") duplicate-keys)]
[result result]))
(provide+safe values->list)
(define-syntax (values->list stx)
(syntax-case stx ()
[(_ VALUES-EXPR) #'(call-with-values (λ () VALUES-EXPR) list)]))
(define+provide+safe (sublist xs i j)
(list? exact-nonnegative-integer? exact-nonnegative-integer? . -> . list?)
(unless (list? xs)
(raise-argument-error 'sublist "list?" xs))
(cond
[(> j (length xs)) (error 'sublist (format "ending index ~a exceeds length of list" j))]
[(>= j i) (for/list ([(x idx) (in-indexed xs)]
#:when (<= i idx (sub1 j)))
x)]
[else (raise-argument-error 'sublist (format "starting index larger than ending index" (list i j)))]))
(define+provide+safe (break-at xs bps-in)
(list? any/c . -> . (listof list?))
(unless (list? xs)
(raise-argument-error 'break-at "list" xs))
(define bps ((if (list? bps-in) values list) bps-in))
(when (ormap (λ (bp) (<= (length xs) bp)) bps)
(raise-argument-error 'break-at
(format "breakpoints not greater than or equal to input list length = ~a" (length xs)) bps))
(unless (increasing-nonnegative-list? bps)
(raise-argument-error 'break-at "increasing-nonnegative-list" bps))
;; easier to do back to front, because then the list index for each item won't change during the recursion
;; cons a zero onto bps (which may already start with zero) and then use that as the terminating condition
;; because breaking at zero means we've reached the start of the list
(let loop ([xs xs][bps (reverse (cons 0 bps))][acc empty])
(match bps
[(cons (? zero?) _) (cons xs acc)] ; return whatever's left, because no more splits are possible
[_ (match/values (split-at xs (car bps))
[(head tail) (loop head (cdr bps) (cons tail acc))])])))
(define (shift-base xs how-far fill-item cycle caller)
(unless (list? xs)
(raise-argument-error caller "list?" xs))
(define abs-how-far (if cycle
(modulo (abs how-far) (length xs))
(abs how-far)))
(define (make-fill thing) (if cycle thing (make-list abs-how-far fill-item)))
(cond
[(> abs-how-far (length xs))
(raise-argument-error caller
(format "index not larger than list length ~a" (length xs))
(* (if (eq? caller 'shift-left) -1 1) how-far))]
[(zero? how-far) xs]
[(positive? how-far)
(match/values (split-at-right xs abs-how-far)
[(head tail) (append (make-fill tail) head)])]
[else ; how-far is negative
(match/values (split-at xs abs-how-far)
[(head tail) (append tail (make-fill head))])]))
(define+provide+safe (shift xs how-far [fill-item #f] [cycle #f])
((list? integer?) (any/c boolean?) . ->* . list?)
(shift-base xs how-far fill-item cycle 'shift))
(define+provide+safe (shift-left xs how-far [fill-item #f] [cycle #f])
((list? integer?) (any/c boolean?) . ->* . list?)
(shift-base xs (- how-far) fill-item cycle 'shift-left))
(define+provide+safe (shift-cycle xs how-far)
(list? integer? . -> . list?)
(shift-base xs how-far #false #true 'shift-cycle))
(define+provide+safe (shift-left-cycle xs how-far)
(list? integer? . -> . list?)
(shift-base xs (- how-far) #false #true 'shift-left-cycle))
(define+provide+safe (shifts xs how-fars [fill-item #f] [cycle #f])
((list? (listof integer?)) (any/c boolean?) . ->* . (listof list?))
(unless (list? xs)
(raise-argument-error 'shifts "list?" xs))
(map (λ (how-far) (shift xs how-far fill-item cycle)) how-fars))
(define+provide+safe (shift/values xs shift-amount-or-amounts [fill-item #f] [cycle #f])
((list? (or/c (listof integer?) integer?)) (any/c boolean?) . ->* . any)
(apply values ((if (list? shift-amount-or-amounts)
shifts
shift) xs shift-amount-or-amounts fill-item cycle)))
shift) xs shift-amount-or-amounts fill-item cycle)))

@ -1,23 +1,11 @@
#lang racket/base
(require "private/syntax-utils.rkt")
(define-syntax-rule (r+p modname)
(begin
(require modname)
(provide (all-from-out modname))
(module+ safe
(require (submod modname safe))
(provide (all-from-out (submod modname safe))))))
(r+p "cache.rkt")
(r+p "coerce.rkt")
(r+p "container.rkt")
(r+p "debug.rkt")
(r+p "define.rkt")
(r+p "file.rkt")
(r+p "include.rkt")
(r+p "len.rkt")
(r+p "list.rkt")
(r+p "misc.rkt")
(r+p "string.rkt")
(r+p "test.rkt")
(r+p "xml.rkt")
(require+provide/safe "cache.rkt"
"coerce.rkt"
"debug.rkt"
"define.rkt"
"file.rkt"
"list.rkt"
"test.rkt"
"xml.rkt")

@ -1,5 +0,0 @@
#lang racket/base
(require sugar/define racket/set sugar/coerce)
(require-via-wormhole "../typed/sugar/misc.rkt")
(provide+safe [bytecount->string (integer? . -> . string?)])

@ -0,0 +1,42 @@
#lang racket/base
(require (for-syntax racket/base)
syntax/define)
(provide (except-out (all-defined-out) values->list))
(define-syntax-rule (require+provide/safe MODNAME ...)
(begin
(begin
(require MODNAME)
(provide (all-from-out MODNAME))
(module+ safe
(require (submod MODNAME safe))
(provide (all-from-out (submod MODNAME safe))))) ...))
(define-syntax (values->list stx)
(syntax-case stx ()
[(_ values-expr) #'(call-with-values (λ () values-expr) list)]))
;; convert calling pattern to form (id contract body-exp)
;; hoist contract out of lambda-exp entirely
(define (lambdafy-with-contract stx)
(syntax-case stx ()
[(_ ID-EXP CONTRACT LAMBDA-EXP) ; matches exactly three args after `define`
;; `normalize-definition` can't handle the acceptable `define/contract` pattern of id, contract, lambda exp after the `define`.
;; so extract the contract, and then put id & lambda-exp back together, and let `normalize-definition` destructure as usual.
(with-syntax ([(NEW-ID NEW-LAMBDA-EXP)
(values->list (normalize-definition #'(_ ID-EXP LAMBDA-EXP) (datum->syntax stx 'λ) #t #t))])
#'(NEW-ID CONTRACT NEW-LAMBDA-EXP))]
;; matches two or more args (three-arg case handled above)
[(_ ID-EXP . BODY)
(with-syntax ([(NEW-ID (LAMBDA ARGS CONTRACT . NEW-BODY))
(values->list (normalize-definition stx (datum->syntax stx 'λ) #t #t))])
;; because the macro provides the `lambda` below, it takes the local srcloc by default
;; so `syntax/loc` applies the original srcloc (associated with args and body-exp)
#`(NEW-ID CONTRACT #,(syntax/loc #'ID-EXP (LAMBDA ARGS . NEW-BODY))))]
;; matches zero or one arguments
[_ (raise-syntax-error 'define-macro "not enough arguments")]))
(define (lambdafy stx)
(with-syntax ([(ID LAMBDA-EXP)
(values->list (normalize-definition stx (datum->syntax stx 'λ) #true #true))])
#'(ID LAMBDA-EXP)))

@ -6,7 +6,7 @@
@(my-eval `(require sugar))
@title{Cache}
@defmodule[#:multi (sugar/cache (submod sugar/cache safe) typed/sugar/cache)]
@defmodule[#:multi (sugar/cache (submod sugar/cache safe))]
If, like Ricky Bobby and me, you want to go fast, then try using more caches. They're wicked fast.

@ -3,10 +3,10 @@
@(require scribble/eval (for-label racket sugar))
@(define my-eval (make-base-eval))
@(my-eval `(require sugar))
@(my-eval `(require sugar racket/contract))
@title{Coercion}
@defmodule[#:multi (sugar/coerce (submod sugar/coerce safe) typed/sugar/coerce)]
@defmodule[#:multi (sugar/coerce (submod sugar/coerce safe))]
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.
@ -161,7 +161,7 @@ Return @racket[#t] for all @racket[_v] except @racket[#f], which remains @racket
@defproc[(listish? [v any/c]) boolean?]
@defproc[(vectorish? [v any/c]) boolean?]
)]
@bold{Untyped only.} Predicates that report whether @racket[_v] can be coerced to the specified type.
Predicates that report whether @racket[_v] can be coerced to the specified type.
@examples[#:eval my-eval
(map intish? (list 3 3.5 #\A "A" + #t))
@ -185,7 +185,7 @@ Return @racket[#t] for all @racket[_v] except @racket[#f], which remains @racket
@defproc[(coerce/boolean? [v any/c]) boolean?]
@defproc[(coerce/list? [v any/c]) list?]
)]
@bold{Untyped only.} If @racket[_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.
If @racket[_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[#:eval my-eval
(define/contract (add-ints x y)

@ -8,7 +8,7 @@
@title{Container}
@defmodule[#:multi (sugar/container (submod sugar/container safe))]
Type-neutral functions for getting elements out of a container, or testing membership. @bold{This submodule is untyped only.}
Type-neutral functions for getting elements out of a container, or testing membership.
@defproc[

@ -6,7 +6,7 @@
@(my-eval `(require sugar))
@title{Debug}
@defmodule[#:multi (sugar/debug (submod sugar/debug safe) typed/sugar/debug)]
@defmodule[#:multi (sugar/debug (submod sugar/debug safe))]
Debugging utilities.

@ -5,10 +5,10 @@
@(define my-eval (make-base-eval))
@(my-eval `(require sugar))
@title{File}
@defmodule[#:multi (sugar/file (submod sugar/file safe) typed/sugar/file)]
@title{File extensions}
@defmodule[#:multi (sugar/file (submod sugar/file safe))]
File utilities, mostly in the realm of file extensions. These functions don't access the filesystem.
These functions don't access the filesystem. @bold{Warning}: these functions adopt the simplifying assumption that the paths are encoded as ASCII or UTF-8. A fully precise treatment of paths would need to handle them as byte strings. If you need that, see the functions in @racketmodname[racket/path]. This library will remain naive.
Arguments that are @racket[pathish?] can take either a string or a path. For clarity below, I've used strings.
@ -30,10 +30,11 @@ Return the last file extension of @racket[_file-path] as a string, or @racket[#f
[file-path pathish?]
[ext stringish?])
boolean?]
Return @racket[#t] if the last file extension of @racket[_file-path] is @racket[_ext], otherwise @racket[#f].
Return @racket[#t] if the last file extension of @racket[_file-path] is @racket[_ext], otherwise @racket[#f]. Not sensitive to case.
@examples[#:eval my-eval
(has-ext? "foo.txt" "txt")
(has-ext? "foo.txt" "TXT")
(has-ext? "foo.txt" "jpg")
(has-ext? "foo.jpg.txt" "jpg")]
@ -72,18 +73,3 @@ Return a new @racket[_file-path] with @racket[_ext] appended. Note that this doe
(add-ext "foo" "txt")
(add-ext "foo.txt" "jpg")
(add-ext (remove-ext "foo.txt") "jpg")]
@defproc[
(get-enclosing-dir
[path pathish?])
path?]
Return the enclosing directory of @racket[_path]. Does not consult the filesystem about whether @racket[_path] is valid. If you reach the @racket[_root] directory, then @racket[(get-enclosing-dir _root)] will just return @racket[_root] again.
@examples[#:eval my-eval
(define bin (string->path "/usr/bin"))
bin
(get-enclosing-dir bin)
(get-enclosing-dir (get-enclosing-dir bin))
(get-enclosing-dir (get-enclosing-dir (get-enclosing-dir bin)))
]

@ -6,6 +6,4 @@
@defmodule[sugar/include]
@defform[(include-without-lang-line path-spec)]
Inline the syntax in the file designated by @racket[_path-spec], after stripping off the @tt{#lang} line of the file (if it exists, otherwise just @racket[include] the file as usual).
Why? So you can take the code from a working source file and recompile it under a different @tt{#lang}. Why? Well, you could take code from a @tt{#lang typed/racket} source file and recompile as @tt{#lang typed/racket/no-check}. Why? Because then you could make typed and untyped modules from the same code without the mandatory contracts imposed by @racket[require/typed].
Inline the syntax in the file designated by @racket[_path-spec], after stripping off the @tt{#lang} line of the file (if it exists, otherwise just @racket[include] the file as usual).

@ -6,7 +6,7 @@
@(my-eval `(require sugar))
@title{Len}
@defmodule[#:multi (sugar/len (submod sugar/len safe) typed/sugar/len)]
@defmodule[#:multi (sugar/len (submod sugar/len safe))]
@defproc[

@ -1,12 +1,12 @@
#lang scribble/manual
@(require scribble/eval (for-label racket sugar))
@(require scribble/eval (for-label racket sugar racket/function))
@(define my-eval (make-base-eval))
@(my-eval `(require sugar racket/list))
@(my-eval `(require sugar racket/list racket/function))
@title{List}
@defmodule[#:multi (sugar/list (submod sugar/list safe) typed/sugar/list)]
@title{Lists}
@defmodule[#:multi (sugar/list (submod sugar/list safe))]
@ -33,9 +33,20 @@ Like @racket[string-split], but for lists. Drop elements from anywhere in @racke
@examples[#:eval my-eval
(filter-split '(1 a b c 2 d e f 3) integer?)
(filter-split '(1 a b c 2 d e f 3) (compose not integer?))
(filter-split '(a b c 1 2 3 d e f) integer?)
(filter-split '(a b c 1 2 3 d e f) (compose not integer?))]
(filter-split '(1 a b c 2 d e f 3) (negate integer?))]
@defproc[
(partition*
[pred procedure?]
[lst list?])
(values list? list?)]
Like @racket[partition], but contiguous groups of elements matching (or not matching) @racket[_pred] are kept together in sublists.
Same as @racket[(values (filter-split _lst _pred) (filter-split _lst (negate _pred)))], but only traverses the list once.
@examples[#:eval my-eval
(partition* integer? '(1 a b c 2 d e f 3))
(partition* (negate integer?) '(1 a b c 2 d e f 3))]
@defproc[
(slice-at
@ -74,7 +85,9 @@ Divide @racket[_lst] into sublists that are homogeneously @racket[_pred] or not
[pred procedure?]
[force? boolean? #f])
(listof list?)]
Divide @racket[_lst] into sublists starting with elements matching @racket[_pred]. The first element of the first sublist may not match @racket[_pred]. Or, if you really & truly want only the sublists starting with an element matching @racket[_pred], set @racket[_force?] to @racket[#t].
Divide @racket[_lst] into sublists, each starting with an element matching @racket[_pred]. The first element of the first sublist may not match @racket[_pred]. But if you really & truly want only the sublists starting with an element matching @racket[_pred], set @racket[_force?] to @racket[#true].
If none of the elements match @racket[_pred], there is no slice to be made, and the result is the whole input list.
@examples[#:eval my-eval
(slicef-at (range 5) even?)
@ -86,13 +99,17 @@ Divide @racket[_lst] into sublists starting with elements matching @racket[_pred
@defproc[
(slicef-after
[lst list?]
[pred procedure?])
[pred procedure?]
[force? boolean? #f])
(listof list?)]
Divide @racket[_lst] into sublists ending with elements matching @racket[_pred]. (Distinct from @racket[slicef-at], which gives you sublists that @italic{start} with elements matching @racket[_pred].) If none of the elements match @racket[_pred], there is no slice to be made, and the result is the whole input list.
Divide @racket[_lst] into sublists, each ending with an element matching @racket[_pred]. The last element of the last sublist may not match @racket[_pred]. But if you really & truly want only the sublists ending with an element matching @racket[_pred], set @racket[_force?] to @racket[#true].
If none of the elements match @racket[_pred], there is no slice to be made, and the result is the whole input list.
@examples[#:eval my-eval
(slicef-after '(1 2 2 1 2) even?)
(slicef-after (range 5) odd?)
(slicef-after (range 5) odd? #true)
(slicef-after (range 5) string?)]
@ -132,15 +149,6 @@ Same as @racket[members-unique?], but if the members are not unique, raises a de
(members-unique?/error '(a b c d e f a b))
]
@defform[(when/splice test expr)]
A special version of @racket[when] that you can use inside @racket[quasiquote] to suppress @racket[void] values when @racket[_test] is @racket[#f]. As the name suggests, it works in conjunction with the @litchar["@"] splicing operator.
@examples[#:eval my-eval
`(,(when (even? 2) "hooray"))
`(,(when (even? 3) "hooray"))
`(,@(when/splice (even? 2) "hooray"))
`(,@(when/splice (even? 3) "hooray"))
]
@defform[(values->list values)]
Convert @racket[_values] to a simple list.
@ -192,7 +200,7 @@ Break @racket[_lst] into smaller lists at the index positions in @racket[_indexe
[fill-item any/c #f]
[cycle? boolean? #f])
list?]
Move the items in @racket[_lst] to the right (if @racket[_how-far] is positive) or left (if @racket[_how-far] is negative). By default, vacated spaces in the list are filled with @racket[_fill-item]. But if @racket[_cycle?] is true, elements of the list wrap around (and @racket[_fill-item] is ignored). Either way, the result list is always the same length as the input list. (If you don't care about the lengths being the same, you probably want @racket[take] or @racket[drop] instead.) If @racket[_how-far] is 0, return the original list. If @racket[_how-far] is bigger than the length of @racket[_lst], raise an error.
Move the items in @racket[_lst] to the right (if @racket[_how-far] is positive) or left (if @racket[_how-far] is negative). By default, vacated spaces in the list are filled with @racket[_fill-item]. But if @racket[_cycle?] is true, elements of the list wrap around (and @racket[_fill-item] is ignored). Either way, the result list is always the same length as the input list. (If you don't care about the lengths being the same, you probably want @racket[take] or @racket[drop] instead.) If @racket[_how-far] is 0, return the original list. If @racket[_how-far] is bigger than the length of @racket[_lst], and @racket[_cycle] is not true, raise an error.
@examples[#:eval my-eval
(define xs (range 5))
@ -204,6 +212,52 @@ Move the items in @racket[_lst] to the right (if @racket[_how-far] is positive)
(shift xs 42)
]
@defproc[
(shift-left
[lst list?]
[how-far integer?]
[fill-item any/c #f]
[cycle? boolean? #f])
list?]
Like @racket[shift], but the list is shifted left when @racket[_how-far] is positive, and right when it's negative. Otherwise identical.
@examples[#:eval my-eval
(define xs (range 5))
(shift-left xs 2)
(shift-left xs -2 0)
(shift-left xs 2 'boing)
(shift-left xs 2 'boing #t)
(shift-left xs 0)
(shift-left xs 42)
]
@deftogether[(
@defproc[
(shift-cycle
[lst list?]
[how-far integer?])
list?]
@defproc[
(shift-left-cycle
[lst list?]
[how-far integer?])
list?]
)]
Like @racket[shift] and @racket[shift-left], but automatically invokes cycle mode. @racket[_how-far] can be any size.
@examples[#:eval my-eval
(define xs (range 5))
(shift-cycle xs 2)
(shift-cycle xs -2)
(shift-cycle xs 0)
(shift-cycle xs 42)
(shift-left-cycle xs 2)
(shift-left-cycle xs -2)
(shift-left-cycle xs 0)
(shift-left-cycle xs 42)
]
@defproc[
(shifts
[lst list?]
@ -227,7 +281,7 @@ Same as @racket[shift], but @racket[_how-far] is a list of integers rather than
[how-far (or/c integer? (listof integer?))]
[fill-item any/c #f])
any]
@bold{Untyped only.} When @racket[_how-far] is a single integer, same as @racket[shift], but the resulting list is returned as values. When @racket[_how-far] is a list of integers, same as @racket[shifts], but the resulting lists are returned as multiple values rather than as a list of lists.
When @racket[_how-far] is a single integer, same as @racket[shift], but the resulting list is returned as values. When @racket[_how-far] is a list of integers, same as @racket[shifts], but the resulting lists are returned as multiple values rather than as a list of lists.
@examples[#:eval my-eval
(define xs (range 5))

@ -6,7 +6,7 @@
@(my-eval `(require sugar))
@title{String}
@defmodule[#:multi (sugar/string (submod sugar/string safe) typed/sugar/string)]
@defmodule[#:multi (sugar/string (submod sugar/string safe))]
@defproc[

@ -1,6 +1,6 @@
#lang scribble/manual
@(require scribble/eval (for-label racket sugar (only-in typed/racket require/typed)))
@(require scribble/eval (for-label racket sugar))
@(define my-eval (make-base-eval))
@(my-eval `(require sugar))
@ -10,17 +10,12 @@
@author[(author+email "Matthew Butterick" "mb@mbtype.com")]
@defmodule[#:multi (sugar (submod sugar safe) typed/sugar)]
@defmodule[#:multi (sugar (submod sugar safe))]
A collection of small functions to help make Racket code simpler & more readable.
A collection of small functions to help make Racket code simpler & more readable. Well, according to me, anyhow.
Sugar can be invoked three ways: as an untyped library, as an untyped library with contracts (using the @tt{safe} submodule), or as a typed library.
Sugar can be invoked two ways: as an ordinary library, or as a library with contracts (using the @tt{safe} submodule).
A few functions are only available as untyped or typed. These exceptions are noted below.
The typed version of Sugar is implemented ``natively'' in the sense that it is compiled separately with type annotations. It is not a @racket[require/typed] wrapper around the untyped code. This avoids the contract barrier that is otherwise automatically imposed between typed and untyped code.
@margin-note{I explain more about this cross-compiling technique in @link["http://unitscale.com/mb/technique/dual-typed-untyped-library.html"]{Making a dual typed / untyped Racket library}.}
@;local-table-of-contents[]
@ -30,20 +25,12 @@ The typed version of Sugar is implemented ``natively'' in the sense that it is c
@include-section["coerce.scrbl"]
@include-section["container.scrbl"]
@include-section["debug.scrbl"]
@include-section["file.scrbl"]
@include-section["include.scrbl"]
@include-section["len.scrbl"]
@include-section["file-extensions.scrbl"]
@include-section["list.scrbl"]
@include-section["string.scrbl"]
@include-section["xml.scrbl"]
@include-section["license.scrbl"]

@ -9,7 +9,7 @@
@defmodule[#:multi (sugar/xml (submod sugar/xml safe))]
Making it easier to do the simplest kind of round-trip with XML: convert an XML string to X-expressions, manipulate, and then convert these X-expressions back to an XML string. @bold{This submodule is untyped only.}
Making it easier to do the simplest kind of round-trip with XML: convert an XML string to X-expressions, manipulate, and then convert these X-expressions back to an XML string.
@defproc[
(xml-string->xexprs

@ -1,7 +0,0 @@
#lang racket/base
(require sugar/define racket/set sugar/coerce)
(require-via-wormhole "../typed/sugar/string.rkt")
(provide+safe [starts-with? (coerce/string? coerce/string? . -> . coerce/boolean?)]
[ends-with? (coerce/string? coerce/string? . -> . coerce/boolean?)]
[capitalized? (coerce/string? . -> . coerce/boolean?)])

@ -1,39 +1,44 @@
#lang racket/base
(require (for-syntax racket/base racket/syntax))
(require sugar/define)
(provide+safe module-test-external module-test-internal module-test-internal+external)
(require (for-syntax
racket/base
racket/syntax
syntax/strip-context)
"define.rkt")
(provide+safe module-test-external
module-test-internal
module-test-internal+external)
;; tests using module-boundary contracts
(define-syntax (module-test-external stx)
(syntax-case stx ()
[(_ expr ...)
(with-syntax ([mod-name (generate-temporary)])
#'(begin
(module* mod-name racket/base
(require (submod ".."))
(require rackunit)
expr ...)
(module+ test
(require (submod ".." mod-name)))))]))
[(_ EXPR ...)
(replace-context
stx
(with-syntax ([MOD-NAME (syntax-e (generate-temporary))])
#'(begin
(module* MOD-NAME racket/base
(require (submod ".."))
(require rackunit)
EXPR ...)
(module+ test
(require (submod ".." MOD-NAME))))))]))
(define-syntax (module-test-internal stx)
(syntax-case stx ()
[(_ expr ...)
(let ([exprs (syntax->datum #'(expr ...))])
(datum->syntax stx `(begin
(module+ test
(require rackunit)
,@exprs))
;; pass original stx for srcloc
;; which is not precisely accurate but
;; OK for now
stx))]))
[(_ EXPR ...)
(replace-context
stx
#'(begin
(module+ test
(require rackunit)
EXPR ...)))]))
(define-syntax (module-test-internal+external stx)
(syntax-case stx ()
[(_ expr ...)
(let ([exprs (syntax->datum #'(expr ...))])
(datum->syntax stx `(begin
(module-test-internal ,@exprs)
(module-test-external ,@exprs)) stx))]))
[(_ EXPR ...)
(replace-context
stx
#'(begin
(module-test-internal EXPR ...)
(module-test-external EXPR ...)))]))

@ -1,10 +1,15 @@
#lang sugar/debug/lang racket
(require sugar/debug rackunit)
(let ([out (open-output-string)])
#lang sugar/debug racket
(require rackunit)
(let ([out (open-output-string)]
[let "something else"]
[local-require "something else entirely"]
[only-in "completely unexpected!"]
[report "well, not really"])
(parameterize ([current-error-port out])
#^5)
#R5)
(check-equal? (get-output-string out) "5 = 5\n"))
(let ([out (open-output-string)])
(let ([out (open-output-string)]
[report/line "outta the blue!"])
(parameterize ([current-error-port out])
#^^5)
(check-equal? (get-output-string out) "5 = 5 on line 9\n"))
#RR5)
(check-equal? (get-output-string out) "5 = 5 on line 14\n"))

@ -1,38 +1,24 @@
#lang racket
(require (for-syntax racket/syntax))
(require (for-syntax racket/syntax
syntax/strip-context))
(define-syntax (eval-as-untyped stx)
(define-syntax (eval-with-and-without-contracts stx)
(syntax-case stx ()
[(_ exprs ...)
(with-syntax ([sym (generate-temporary)]
[sym2 (generate-temporary)])
#'(begin
(module sym racket
(require rackunit "../main.rkt" net/url)
exprs ...)
(require 'sym)
(module sym2 racket
(require rackunit (submod "../main.rkt" safe) net/url)
exprs ...)
(require 'sym2)))]))
[(_ EXPRS ...)
(with-syntax ([MODULE-WITHOUT-CONTRACTS (generate-temporary)]
[MODULE-WITH-CONTRACTS (generate-temporary)])
(replace-context stx
#'(begin
(module MODULE-WITHOUT-CONTRACTS racket
(require rackunit "../main.rkt" net/url)
EXPRS ...)
(require 'MODULE-WITHOUT-CONTRACTS)
(module MODULE-WITH-CONTRACTS racket
(require rackunit (submod "../main.rkt" safe) net/url)
EXPRS ...)
(require 'MODULE-WITH-CONTRACTS))))]))
(define-syntax (eval-as-typed stx)
(syntax-case stx ()
[(_ exprs ...)
(with-syntax ([sym (generate-temporary)])
#'(begin
(module sym typed/racket
(require typed/rackunit "../../typed/sugar.rkt" typed/net/url)
exprs ...)
(require 'sym)))]))
(define-syntax-rule (eval-as-typed-and-untyped exprs ...)
(begin
(eval-as-untyped exprs ...)
(eval-as-typed exprs ...)))
(eval-as-typed-and-untyped
(eval-with-and-without-contracts
(check-equal? (->int 42) 42)
(check-equal? (->int 42.1) 42)
(check-equal? (->int 42+3i) 42)
@ -43,6 +29,7 @@
(check-equal? (->int (make-list 42 null)) 42)
(check-equal? (->string "foo") "foo")
(check-equal? (->string #"foo") "foo")
(check-equal? (->string '()) "")
(check-equal? (->string (void)) "")
(check-equal? (->string 'foo) "foo")
@ -53,44 +40,90 @@
(check-equal? (->string #\¶) "")
(check-equal? (->path "foo") (string->path "foo"))
(check-equal? (->path #"foo") (string->path "foo"))
(check-equal? (->path 'foo) (string->path "foo"))
(check-equal? (->path 123) (string->path "123"))
(check-equal? (->path (string->url "foo/bar.html")) (string->path "foo/bar.html"))
(check-equal? (->path (string->url "/foo/bar.html")) (string->path "/foo/bar.html"))
(check-equal? (->list '(1 2 3)) '(1 2 3))
(check-equal? (->list (list->vector '(1 2 3))) '(1 2 3))
(check-equal? (->list (set 1 2 3)) '(3 2 1))
(check-not-false (andmap (lambda (e) (member e '(1 2 3))) (->list (set 1 2 3))))
(check-equal? (->list "foo") (list "foo"))
(check-true (->boolean #t))
(check-false (->boolean #f))
(check-true (->boolean "#f"))
(check-true (->boolean "#f"))
(check-true (->boolean "foo"))
(check-true (->boolean '()))
(check-true (->boolean '(1 2 3)))
(check-equal? (len '(1 2 3)) 3)
(check-not-equal? (len '(1 2)) 3) ; len 2
(check-equal? (len "foo") 3)
(check-not-equal? (len "fo") 3) ; len 2
(check-equal? (len 'foo) 3)
(check-not-equal? (len 'fo) 3) ; len 2
(check-equal? (len (list->vector '(1 2 3))) 3)
(check-not-equal? (len (list->vector '(1 2))) 3) ; len 2
(check-equal? (len (set 1 2 3)) 3)
(check-not-equal? (len (set 1 2)) 3) ; len 2
(check-equal? (len (make-hash '((a . 1) (b . 2) (c . 3)))) 3)
(check-not-equal? (len (make-hash '((a . 1) (b . 2)))) 3) ; len 2
(check-true ("foobar" . starts-with? . "foo"))
(check-true ("foobar" . starts-with? . "f"))
(check-true ("foobar" . starts-with? . "foobar"))
(check-false ("foobar" . starts-with? . "bar"))
(check-false ("foobar" . starts-with? . "."))
(check-true ("foobar" . ends-with? . "bar"))
(check-true ("foobar" . ends-with? . "r"))
(check-true ("foobar" . ends-with? . "foobar"))
(check-false ("foobar" . ends-with? . "foo"))
(module dp racket/base
(require "../define.rkt")
(define+provide (dp-f x #:y [y 42] . zs)
(apply + x y zs)))
(require 'dp)
(check-equal? (dp-f 1 #:y 0 2 3) 6)
(module dps racket/base
(require sugar/define)
(define+provide+safe (dps-f x #:y [y 42] . zs)
((integer?) (#:y integer?) #:rest (listof integer?) . ->* . integer?)
(apply + x y zs)))
(require 'dps)
(check-equal? (dps-f 1 #:y 0 2 3) 6)
(require (prefix-in safe: (submod 'dps safe)))
(check-equal? (safe:dps-f 1 #:y 0 2 3) 6)
(check-exn exn:fail? (λ _ (safe:dps-f 'foo)))
(module dpsb racket/base
(require sugar/define)
(define+provide+safe dpsb-f
((integer?) (#:y integer?) #:rest (listof integer?) . ->* . integer?)
(λ(x #:y [y 42] . zs) (apply + x y zs))))
(require 'dpsb)
(check-equal? (dpsb-f 1 #:y 0 2 3) 6)
(require (prefix-in safe: (submod 'dpsb safe)))
(check-equal? (safe:dpsb-f 1 #:y 0 2 3) 6)
(check-exn exn:fail? (λ _ (safe:dpsb-f 'foo)))
(module ps racket/base
(require "../define.rkt")
(provide+safe [ps-f ((integer?) (#:y integer?) #:rest (listof integer?) . ->* . integer?)])
(define (ps-f x #:y [y 42] . zs)
(apply + x y zs)))
(require 'ps)
(check-equal? (ps-f 1 #:y 0 2 3) 6)
(require (prefix-in safe: (submod 'ps safe)))
(check-equal? (safe:ps-f 1 #:y 0 2 3) 6)
(check-exn exn:fail? (λ _ (safe:ps-f 'foo)))
(module dcp racket/base
(require "../define.rkt" rackunit)
(define/contract+provide (dcp-f x #:y [y 42] . zs)
((integer?) (#:y integer?) #:rest (listof integer?) . ->* . integer?)
(apply + x y zs))
(check-exn exn:fail? (λ _ (dcp-f 'foo))))
(require 'dcp)
(check-equal? (dcp-f 1 #:y 0 2 3) 6)
(check-exn exn:fail? (λ _ (dcp-f 'foo)))
(module dpc racket/base
(require "../define.rkt" rackunit)
(define+provide/contract (dpc-f x #:y [y 42] . zs)
((integer?) (#:y integer?) #:rest (listof integer?) . ->* . list?)
(list* x y zs))
(check-equal? (dpc-f 'foo) '(foo 42))) ; locally, no contract triggered
(require 'dpc)
(check-equal? (dpc-f 1) '(1 42))
(check-exn exn:fail? (λ _ (dpc-f 'foo)))
(check-true (members-unique? '(a b c)))
(check-false (members-unique? '(a b c c)))
@ -99,7 +132,9 @@
(check-equal? (trimf (list 4 1 2 3 4) even?) '(1 2 3))
(check-equal? (trimf (list 1 3 2 4 5 6 8 9 13) odd?) '(2 4 5 6 8))
(check-equal? (filter-split '(1 2 3 4 5 6) even?) '((1)(3)(5)))
(check-equal? (filter-split '(1 1 2 3 4 4 5 6) even?) '((1 1)(3)(5)))
(check-equal? (let-values ([(preds not-preds) (partition* even? '(1 1 2 3 4 4 5 6))])
(list preds not-preds)) (list '((2)(4 4)(6)) '((1 1)(3)(5))))
(define foo-path-strings '("foo" "foo.txt" "foo.bar" "foo.bar.txt"))
(match-define (list foo-path foo.txt-path foo.bar-path foo.bar.txt-path) (map ->path foo-path-strings))
@ -107,45 +142,46 @@
(define foo-paths (list foo-path foo.txt-path foo.bar-path foo.bar.txt-path))
(for-each check-equal? (map ->string foo-paths) foo-path-strings)
(check-false (has-ext? foo-path 'txt))
(check-false (has-ext? foo-path 'txt))
(check-true (foo.txt-path . has-ext? . 'txt))
(check-true ((->path "foo.TXT") . has-ext? . 'txt))
(check-true (has-ext? foo.bar.txt-path 'txt))
(check-false (foo.bar.txt-path . has-ext? . 'doc)) ; wrong extension
(check-exn exn:fail:contract? (λ () (has-ext? #f "foo")))
(check-exn exn:fail:contract? (λ () (has-ext? "foo" #f)))
(check-equal? (get-ext (->path "foo.txt")) "txt")
(check-false (get-ext "foo"))
(check-false (get-ext ".foo"))
(check-exn exn:fail:contract? (λ () (get-ext #f)))
(check-equal? (add-ext (string->path "foo") "txt") (string->path "foo.txt"))
(check-exn exn:fail:contract? (λ () (add-ext "foo" #f)))
(check-exn exn:fail:contract? (λ () (add-ext #f "foo" )))
(check-equal? (remove-ext foo-path) foo-path)
(check-equal? (remove-ext (->path ".foo.txt")) (->path ".foo.txt"))
(check-equal? (remove-ext (->path ".foo.txt")) (->path ".foo"))
(check-equal? (remove-ext foo.txt-path) foo-path)
(check-equal? (remove-ext foo.bar.txt-path) foo.bar-path)
(check-not-equal? (remove-ext foo.bar.txt-path) foo-path) ; does not remove all extensions
;; test remove-ext on paths that have "." prefix
(check-equal? (remove-ext (->path "./foo.txt.bar")) (->path "./foo.txt"))
(check-equal? (remove-ext (->path "../foo.txt.bar")) (->path "../foo.txt"))
(check-equal? (remove-ext (->path "/hidden/file/.foo.txt.bar")) (->path "/hidden/file/.foo.txt"))
(check-equal? (remove-ext* foo-path) foo-path)
(check-equal? (remove-ext* foo.txt-path) foo-path)
(check-equal? (remove-ext* (->path ".foo.txt")) (->path ".foo.txt"))
(check-equal? (remove-ext* (->path ".foo.txt")) (->path ".foo"))
(check-not-equal? (remove-ext* foo.bar.txt-path) foo.bar-path) ; removes more than one ext
(check-equal? (remove-ext* foo.bar.txt-path) foo-path)
(check-equal? (get-enclosing-dir "/Users/MB/foo.txt") (->path "/Users/MB/"))
(check-equal? (get-enclosing-dir "/Users/MB/foo/") (->path "/Users/MB/"))
;; test remove-ext* on paths that have "." prefix
(check-equal? (remove-ext* (->path "./foo.txt.bar")) (->path "./foo"))
(check-equal? (remove-ext* (->path "../foo.txt.bar")) (->path "../foo"))
(check-equal? (remove-ext* (->path "/hidden/file/.foo.txt.bar")) (->path "/hidden/file/.foo"))
(check-true (has-binary-ext? "foo.MP3"))
(check-false (has-binary-ext? "foo.py"))
(check-true (starts-with? "foobar" "foo"))
(check-true (starts-with? "foobar" "foobar"))
(check-false (starts-with? "foobar" "zam"))
(check-false (starts-with? "foobar" "foobars"))
(check-true (ends-with? "foobar" "bar"))
(check-false (ends-with? "foobar" "zam"))
(check-true (ends-with? "foobar" "foobar"))
(check-false (ends-with? "foobar" "foobars"))
(check-true (capitalized? "Brennan"))
(check-false (capitalized? "foobar"))
(check-equal? (slice-at (range 5) 1) '((0) (1) (2) (3) (4)))
(check-equal? (slice-at (range 5) 2) '((0 1) (2 3) (4)))
(check-equal? (slice-at (range 5) 2 #t) '((0 1) (2 3)))
@ -164,6 +200,14 @@
(check-equal? (slicef-at '(1 2 2 1 2) even?) '((1) (2) (2 1) (2)))
(check-equal? (slicef-at '(1 2 2 1 2) even? #t) '((2) (2 1) (2)))
(check-equal? (slicef-after (range 5) even?) '((0) (1 2) (3 4)))
(check-equal? (slicef-after (range 5) odd?) '((0 1) (2 3) (4)))
(check-equal? (slicef-after (range 5) odd? #t) '((0 1) (2 3)))
(check-equal? (slicef-after (range 5) procedure?) '((0 1 2 3 4)))
(check-equal? (slicef-after '(2 1 2 2 1) even?) '((2) (1 2) (2) (1)))
(check-equal? (slicef-after '(2 1 2 2 1) even? #t) '((2) (1 2) (2)))
(check-equal? (sublist (range 5) 0 0) '())
(check-equal? (sublist (range 5) 0 1) '(0))
@ -181,12 +225,16 @@
(check-equal? (shifts xs '(-1 0 1) 'boing) `((1 2 3 4 boing) ,xs (boing 0 1 2 3)))
(check-equal? (shifts xs '(-1 0 1) 'boing #t) `((1 2 3 4 0) ,xs (4 0 1 2 3)))
(check-equal? (shift xs 5 0) (make-list 5 0))
(check-exn exn:fail? (λ() (shift xs -10))))
(check-exn exn:fail? (λ() (shift xs -10)))
(check-equal? (map (λ(a b c) (list a b c)) (shift-left xs -1) (shift-left xs 0) (shift-left xs 1)) (map reverse '((1 0 #f) (2 1 0) (3 2 1) (4 3 2) (#f 4 3))))
(eval-as-untyped
(check-equal? (shift-cycle xs 2) '(3 4 0 1 2))
(check-equal? (shift-left-cycle xs 2) '(2 3 4 0 1))
(check-equal? (shift-cycle xs 7) '(3 4 0 1 2))
(check-equal? (shift-left-cycle xs 7) '(2 3 4 0 1))
(check-equal? (shift-cycle xs 107) '(3 4 0 1 2))
(check-equal? (shift-left-cycle xs 107) '(2 3 4 0 1))
(check-true (urlish? (->path "/Users/MB/home.html")))
(check-true (urlish? "/Users/MB/home.html?foo=bar"))
@ -201,74 +249,18 @@
(check-exn exn:fail? (λ _ (slice-at (range 5) 0))) ; needs a positive integer as second arg
(check-exn exn:fail? (λ _ (slicef-at (range 5) 3))) ; needs a procedure as second arg
(check-equal? (get '(0 1 2 3 4 5) 2) 2)
(check-exn exn:fail? (λ() (get '(0 1 2 3 4 5) 100))) ; index too big
(check-equal? (get `(0 1 ,(list 2) 3 4 5) 2) (list 2))
(check-equal? (get '(0 1 2 3 4 5) 0 2) '(0 1))
(check-equal? (get (list->vector '(0 1 2 3 4 5)) 2) 2)
(check-equal? (get (list->vector'(0 1 2 3 4 5)) 0 2) (list->vector '(0 1)))
(check-equal? (get "purple" 2) "r")
(check-equal? (get "purple" 0 2) "pu")
(check-equal? (get 'purple 2) 'r)
(check-equal? (get 'purple 0 2) 'pu)
(check-equal? (get (string->path "/root/foo/bar/file.txt") 2) (string->path "foo"))
(check-equal? (get (string->path "/root/foo/bar/file.txt") 0 2) (list (string->path "/") (string->path "root")))
(check-equal? (get (make-hash `((a . ,(list 1)) (b . ,(list 2)) (c . ,(list 3)))) 'a) (list 1))
(check-exn exn:fail? (λ() (get (make-hash `((a . ,(list 1)) (b . ,(list 2)) (c . ,(list 3)))) 'z))) ; nonexistent key
(check-equal? (get (string->path "/root/foo/bar/file.txt") 1) (string->path "root"))
(check-equal? (get (string->path "/root/foo/bar/file.txt") 0 3)
(map string->path '("/" "root" "foo")))
(check-equal? (get (make-hash '((a . 1) (b . 2) (c . 3))) 'b) 2)
(check-true (2 . in? . '(1 2 3)))
(check-false (4 . in? . '(1 2 3)))
(check-true (2 . in? . (list->vector '(1 2 3))))
(check-false (4 . in? . (list->vector '(1 2 3))))
(check-true ('a . in? . (make-hash '((a . 1) (b . 2) (c . 3)))))
(check-false ('x . in? . (make-hash '((a . 1) (b . 2) (c . 3)))))
(check-true ("o" . in? . "foobar"))
(check-false ("z" . in? . "foobar"))
(check-true ('o . in? . 'foobar))
(check-false ('z . in? . 'foobar))
(check-true ("F" . in? . #\F))
(check-true (in? "foo" (string->path "/root/foo/bar/file.txt")))
(check-false (in? "zam" (string->path "/root/foo/bar/file.txt")))
(define xs (range 5))
(define ys (range 5))
(check-equal? (values->list (shift/values ys -1 'boing)) '(1 2 3 4 boing))
(check-equal? (values->list (shift/values ys '(-1 0 1) 'boing)) `((1 2 3 4 boing) ,xs (boing 0 1 2 3)))
(require xml)
(define str "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>hello world</root>")
(define-values (str-prolog str-doc) (xml-string->xexprs str))
(check-equal? str-prolog (prolog (list (p-i (location 1 0 1) (location 1 38 39) 'xml "version=\"1.0\" encoding=\"utf-8\"")) #f null))
(check-equal? str-doc '(root () "hello world"))
(check-equal? (xexprs->xml-string str-prolog str-doc) str)
(module include-test racket/base
(require sugar/include)
(include-without-lang-line "source.rkt")
(provide included-symbol))
(require 'include-test)
(check-equal? included-symbol 'bar)
(module no-lang-line-include-test racket/base
(require sugar/include)
(include-without-lang-line "no-lang-line-source.txt")
(provide no-lang-symbol))
(require 'no-lang-line-include-test)
(check-equal? no-lang-symbol 'bar))
(check-equal? (values->list (shift/values ys -1 'boing)) '(1 2 3 4 boing))
(check-equal? (values->list (shift/values ys '(-1 0 1) 'boing)) `((1 2 3 4 boing) ,xs (boing 0 1 2 3)))
(check-equal? "42 = 42\n" (let ([os (open-output-string)])
(parameterize ([current-error-port os])
(report 42))
(get-output-string os)))
(check-equal? "(quotient/remainder 10 3) = (values 3 1)\n" (let ([os (open-output-string)])
(parameterize ([current-error-port os])
(report (quotient/remainder 10 3))
(get-output-string os)))))
#|
;; todo: revise `check-typing-fails` to make it compatible with 6.0
(check-typing-fails (slice-at (range 5) 0)) ; needs a positive integer as second arg
(check-typing-fails (slicef-at (range 5) 3)) ; needs a procedure as second arg
|#

@ -1,3 +0,0 @@
#lang typed/racket
(define included-symbol 'bar)

@ -1,13 +1,6 @@
#lang racket/base
(require rackunit)
(module trb typed/racket/base
(require typed/sugar/list typed/rackunit)
(provide (all-defined-out))
;; (trimf odd? '(1 2 3)) ; type error
(define foo (trimf '(1 2 3) odd?))
(check-equal? foo '(2)))
(module rb racket/base
(require (submod sugar/list safe) rackunit)
(provide (all-defined-out))
@ -22,8 +15,7 @@
(define foo (trimf '(1 2 3) odd?))
(check-equal? foo '(2)))
(require (prefix-in trb: 'trb))
(require (prefix-in rb: 'rb))
(require (prefix-in rbu: 'rbu))
(check-true (andmap (λ(val) (equal? val '(2))) (list trb:foo rb:foo rbu:foo)))
(check-true (andmap (λ(val) (equal? val '(2))) (list rb:foo rbu:foo)))

@ -0,0 +1,14 @@
#lang racket/base
(require (for-syntax racket/base racket/syntax))
(provide (all-defined-out))
;; like case but strictly uses `eq?` comparison (as opposed to `equal?`)
(define-syntax caseq (make-rename-transformer #'case))
(define-syntax casev (make-rename-transformer #'case))
(require sugar/debug)
(define-syntax (cond-report stx)
(syntax-case stx ()
[(_ [COND . BODY] ... [else . ELSE-BODY]) #'(cond [(report COND) (report (let () (void) . BODY))] ... [else . ELSE-BODY])]
[(_ [COND . BODY] ... ) #'(cond-report [COND . BODY] ... [else (void)])]))

@ -0,0 +1,95 @@
#lang racket/base
(require (for-syntax racket/base racket/syntax) racket/class)
(provide (all-defined-out))
(define string%
(class* object% (writable<%>)
(super-new)
(init-field [data #f])
(define (get-string)
(with-handlers ([exn:fail:object? (λ (exn) data)])
(send this toString)))
(define/public (custom-write port) (write (get-string) port))
(define/public (custom-display port) (display (get-string) port))))
(define mixin-tester%
(class object%
(super-new)
(define/public (addContent val) (make-object string% val))))
(define-syntax (as-method stx)
(syntax-case stx ()
[(_ ID) (with-syntax ([PRIVATE-ID (generate-temporary #'ID)])
#'(begin
(public [PRIVATE-ID ID])
(define (PRIVATE-ID . args) (apply ID this args))))]))
(define-syntax-rule (as-methods ID ...)
(begin (as-method ID) ...))
(define-syntax (define-instance stx)
(syntax-case stx ()
[(_ ID (MAKER BASE-CLASS . ARGS))
(with-syntax ([ID-CLASS (format-id stx "~a:~a" (syntax->datum #'BASE-CLASS) (syntax->datum #'ID))])
#'(define ID (let ([ID-CLASS (class BASE-CLASS (super-new))])
(MAKER ID-CLASS . ARGS))))]))
(define-syntax (define-class-predicates stx)
(syntax-case stx ()
[(_ ID)
(with-syntax ([+ID (format-id #'ID "+~a" (syntax->datum #'ID))]
[ID? (format-id #'ID "~a?" (syntax->datum #'ID))])
#'(begin (define (ID? x) (is-a? x ID))
(define (+ID . args) (apply make-object ID args))))]))
(define-syntax-rule (define-subclass*/interfaces SUPERCLASS INTERFACES (ID . INIT-ARGS) . BODY)
(begin
(define ID (class* SUPERCLASS INTERFACES (init-field . INIT-ARGS) . BODY))
(define-class-predicates ID)))
(define-syntax-rule (define-subclass/interfaces SUPERCLASS INTERFACES (ID . INIT-ARGS) . BODY)
(define-subclass*/interfaces SUPERCLASS INTERFACES (ID . INIT-ARGS) (super-new) . BODY))
(define-syntax-rule (define-subclass* SUPERCLASS (ID . INIT-ARGS) . BODY)
(define-subclass*/interfaces SUPERCLASS () (ID . INIT-ARGS) . BODY))
(define-syntax-rule (define-subclass SUPERCLASS (ID . INIT-ARGS) . BODY)
(define-subclass* SUPERCLASS (ID . INIT-ARGS) (super-new) . BODY))
(define-syntax-rule (push-field! FIELD O EXPR)
(set-field! FIELD O (cons EXPR (get-field FIELD O))))
(define-syntax-rule (push-end-field! FIELD O EXPR)
(set-field! FIELD O (append (get-field FIELD O) (list EXPR))))
(define-syntax-rule (pop-field! FIELD O)
(let ([xs (get-field FIELD O)])
(set-field! FIELD O (cdr xs))
(car xs)))
(define-syntax (increment-field! stx)
(syntax-case stx ()
[(_ FIELD O) #'(increment-field! FIELD O 1)]
[(_ FIELD O EXPR)
#'(begin (set-field! FIELD O (+ (get-field FIELD O) EXPR)) (get-field FIELD O))]))
(define-syntax (getter-field/override stx)
(syntax-case stx ()
[(_ [ID . EXPRS])
(syntax-property #'(getter-field [ID . EXPRS]) 'override #t)]))
(define-syntax (getter-field stx)
(syntax-case stx ()
[(_ [ID . EXPRS])
(with-syntax ([_ID (format-id #'ID "_~a" (syntax->datum #'ID))])
#`(begin
(field [(ID _ID) . EXPRS])
(public (_ID ID))
(#,(if (syntax-property stx 'override) #'define/override #'define) (_ID) ID)))]))

@ -0,0 +1,86 @@
#lang racket/base
(require "../define.rkt" "../coerce.rkt" "len.rkt" racket/list racket/set racket/sequence racket/stream racket/dict)
(define (sliceable-container? x)
(ormap (λ(proc) (proc x)) (list list? string? symbol? vector? path? (λ(i) (and (not (dict? i)) (sequence? i))))))
(define (gettable-container? x)
(ormap (λ(proc) (proc x)) (list sliceable-container? dict?)))
(define+provide+safe (get container start [end #f])
((gettable-container? any/c) ((or/c (and/c integer? positive?) #f)) . ->* . any)
(define result
;; use handler to capture error & print localized error message
(with-handlers ([exn:fail? (λ(exn) (error (format "get: couldn't retrieve ~a from ~a" (if end (format "items ~a through ~a" start end) (format "item ~a" start)) container)))])
(let ([end (if (and (equal? end #f) (sliceable-container? container)) (add1 start) end)])
(cond
[(list? container) (for/list ([i (in-range start end)]) (list-ref container i))]
[(vector? container) (for/vector ([i (in-range start end)]) (vector-ref container i))]
[(string? container) (substring container start end)]
[(symbol? container) (->symbol (get (->string container) start end))]
[(path? container) (get (explode-path container) start end)]
[(dict? container) (dict-ref container start)]
[(sequence? container) (get (->list container) start end)]
[else (error)]))))
;; don't return single-item results inside a list
;; check for integer because integers don't have length
(if (and (not (integer? result)) (= (len result) 1) (sliceable-container? container))
(car (->list result))
result))
(define (listlike-container? container)
(ormap (λ(pred) (pred container)) (list vector? set? sequence?)))
(define+provide+safe (in? item container)
(any/c any/c . -> . boolean?)
(->boolean (cond
[(list? container) (member item container)]
[(dict? container) (dict-has-key? container item)]
[(path? container) (in? (->path item) (explode-path container))]
[(stringish? container) (regexp-match (->string item) (->string container))]
;; location relevant because dicts and strings are also listlike (= sequences)
[(listlike-container? container) (in? item (->list container))]
[else #f])))
(module+ test
(require rackunit)
(check-equal? (get '(0 1 2 3 4 5) 2) 2)
(check-exn exn:fail? (λ() (get '(0 1 2 3 4 5) 100))) ; index too big
(check-equal? (get `(0 1 ,(list 2) 3 4 5) 2) (list 2))
(check-equal? (get '(0 1 2 3 4 5) 0 2) '(0 1))
(check-equal? (get (list->vector '(0 1 2 3 4 5)) 2) 2)
(check-equal? (get (list->vector'(0 1 2 3 4 5)) 0 2) (list->vector '(0 1)))
(check-equal? (get "purple" 2) "r")
(check-equal? (get "purple" 0 2) "pu")
(check-equal? (get 'purple 2) 'r)
(check-equal? (get 'purple 0 2) 'pu)
(check-equal? (get (string->path "/root/foo/bar/file.txt") 2) (string->path "foo"))
(check-equal? (get (string->path "/root/foo/bar/file.txt") 0 2) (list (string->path "/") (string->path "root")))
(check-equal? (get (make-hash `((a . ,(list 1)) (b . ,(list 2)) (c . ,(list 3)))) 'a) (list 1))
(check-exn exn:fail? (λ() (get (make-hash `((a . ,(list 1)) (b . ,(list 2)) (c . ,(list 3)))) 'z))) ; nonexistent key
(check-equal? (get (string->path "/root/foo/bar/file.txt") 1) (string->path "root"))
(check-equal? (get (string->path "/root/foo/bar/file.txt") 0 3)
(map string->path '("/" "root" "foo")))
(check-equal? (get (make-hash '((a . 1) (b . 2) (c . 3))) 'b) 2)
(check-true (2 . in? . '(1 2 3)))
(check-false (4 . in? . '(1 2 3)))
(check-true (2 . in? . (list->vector '(1 2 3))))
(check-false (4 . in? . (list->vector '(1 2 3))))
(check-true ('a . in? . (make-hash '((a . 1) (b . 2) (c . 3)))))
(check-false ('x . in? . (make-hash '((a . 1) (b . 2) (c . 3)))))
(check-true ("o" . in? . "foobar"))
(check-false ("z" . in? . "foobar"))
(check-true ('o . in? . 'foobar))
(check-false ('z . in? . 'foobar))
(check-true ("F" . in? . #\F))
(check-true (in? "foo" (string->path "/root/foo/bar/file.txt")))
(check-false (in? "zam" (string->path "/root/foo/bar/file.txt"))))

@ -0,0 +1,25 @@
#lang racket/base
(require racket/contract racket/class)
(provide (all-defined-out))
(define (option/c x) (or/c #f x))
(module+ main
(define-syntax-rule (define/public/contract (ID . ARGS) CONTRACT . BODY)
(define/public (ID . ARGS)
(define/contract (ID . ARGS)
CONTRACT . BODY)
(ID . ARGS)))
(define c% (class object%
(super-new)
(define/public/contract (add x y)
(integer? integer? . -> . integer?)
(+ x y))))
(define c (make-object c%))
(send c add 12 21))

@ -0,0 +1,22 @@
#lang racket/base
(require sugar/list)
(provide (all-defined-out))
(define (assoc? x) (and (pair? x) (not (list? x))))
(define (assocs? xs) (and (list? xs) (andmap assoc? xs)))
(define (listify kvs)
(for/list ([slice (in-list (slice-at kvs 2))])
(cons (car slice) (cadr slice))))
(define-syntax-rule (define-hashifier id hasher) (define (id . kvs) (hasher (listify kvs))))
;; like indefinite-arity `hash` but mutable
(define-hashifier mhash make-hash)
(define-hashifier mhasheq make-hasheq)
(define-hashifier mhasheqv make-hasheqv)
(module+ test
(require rackunit)
(check-equal? (mhash 'k "v") (make-hash (list (cons 'k "v")))))
(define (dictify . xs) (listify xs))

@ -1,11 +1,10 @@
#lang racket/base
(require (for-syntax racket/base
syntax/path-spec
racket/private/increader
compiler/cm-accomplice
racket/match racket/function)
sugar/define)
"../define.rkt")
(provide+safe include-without-lang-line)

@ -0,0 +1,95 @@
#lang racket/base
(require racket/class (for-syntax racket/base racket/syntax) racket/dict)
(provide (all-defined-out))
;; js-style `push`, which appends to end of list
(define-syntax-rule (push-end! ID THING)
(set! ID (append ID (list THING))))
(define-syntax (increment! stx)
(syntax-case stx ()
[(_ ID) #'(increment! ID 1)]
[(_ ID EXPR)
#'(begin (set! ID (+ ID EXPR)) ID)]))
(module+ test
(define xs '(1 2 3))
(push-end! xs 4)
(check-equal? xs '(1 2 3 4)))
(define-syntax-rule (+= ID THING) (begin (set! ID (+ ID THING)) ID))
(define-syntax-rule (++ ID) (+= ID 1))
(define-syntax-rule (-- ID) (+= ID -1))
(define-syntax-rule (-= ID THING) (+= ID (- THING)))
;; fancy number->string. bounds are checked, inexact integers are coerced.
(define (number x #:round [round? #true])
(unless (and (number? x) (< -1e21 x 1e21))
(raise-argument-error 'number "valid number" x))
(let ([x (if round? (/ (round (* x 1e6)) 1e6) x)])
(number->string (if (integer? x)
(inexact->exact x)
x))))
(module+ test
(check-equal? (number 4.5) "4.5")
(check-equal? (number 4.0) "4")
(check-equal? (number 4) "4")
(check-equal? (number -4) "-4"))
(define ·-helper
(procedure-rename
(λ (x . refs)
(for/fold ([x x])
([ref (in-list refs)]
#:break (not x))
(cond
;; give `send` precedence (presence of method => wants runtime resolution of value)
[(and (object? x)
(memq ref (interface->method-names (object-interface x)))) (dynamic-send x ref)]
;; dict first, to catch objects that implement gen:dict
[(dict? x) (dict-ref x ref #f)]
[(object? x) (cond
[(memq ref (field-names x)) (dynamic-get-field ref x)]
[else #f])]
[else (raise-argument-error '· "object or dict" (cons x refs))]))) '·))
(define-syntax-rule (· X REF ...) (·-helper X 'REF ...))
#;(module+ test
(define c (class object%
(super-new)
(field [a 42])
(define/public (res) (hash 'res (hash 'b 43)))))
(define co (make-object c))
(define h2 (hash 'a 42 'res co))
(check-equal? (· h2 a) 42)
(check-equal? (· h2 b) 43)
(check-equal? (· co a) 42)
(check-equal? (· co b) 43))
(define-syntax-rule (·map REF XS)
(for/list ([x (in-list XS)]) (· x REF)))
(module+ test
(require rackunit)
(define C
(class object%
(super-new)
(field [foo 'field])
(define/public (bar) 'method)
(define/public (zam) (hasheq 'zoom 'hash))))
(define h (hasheq 'bam (new C) 'foo 'hashlet))
(define o (new C))
(check-equal? (· o foo) 'field)
(check-equal? (· o bar) 'method)
(check-equal? (· o zam zoom) 'hash)
(check-equal? (· h bam foo) 'field)
(check-equal? (· h bam bar) 'method)
(check-equal? (· h bam zam zoom) 'hash)
(check-equal? (·map foo (list o h)) '(field hashlet)))

@ -0,0 +1,48 @@
#lang racket/base
(require (for-syntax
racket/base
racket/syntax)
"../define.rkt"
racket/sequence
racket/generic)
(provide define-generics+provide+safe)
(define-syntax (define-generics+provide+safe stx)
(syntax-case stx ()
[(_ TYPE ID-CONTRACT (ID . ID-ARGS) . ARGS)
(with-syntax ([TYPE? (format-id stx "~a?" #'TYPE)])
#'(begin
(provide TYPE? ID)
(module+ safe
(require racket/contract)
(provide TYPE? (contract-out [ID ID-CONTRACT])))
(define-generics TYPE (ID . ID-ARGS) . ARGS)))]))
(provide len lengthable?)
(define-generics lengthable
(len lengthable)
#:fast-defaults
([list? (define len length)]
[string? (define len string-length)]
[symbol? (define len (compose1 string-length symbol->string))]
[path? (define len (compose1 string-length path->string))]
[vector? (define len vector-length)]
[hash? (define (len x) (length (hash-keys x)))]
[(λ (x) (and (sequence? x) (not (integer? x)))) (define len (compose1 length sequence->list))]))
(module+ test
(require rackunit racket/set)
(check-equal? (len '(1 2 3)) 3)
(check-not-equal? (len '(1 2)) 3) ; len 2
(check-equal? (len "foo") 3)
(check-not-equal? (len "fo") 3) ; len 2
(check-equal? (len 'foo) 3)
(check-not-equal? (len 'fo) 3) ; len 2
(check-equal? (len (list->vector '(1 2 3))) 3)
(check-not-equal? (len (list->vector '(1 2))) 3) ; len 2
(check-equal? (len (set 1 2 3)) 3)
(check-not-equal? (len (set 1 2)) 3) ; len 2
(check-equal? (len (make-hash '((a . 1) (b . 2) (c . 3)))) 3)
(check-not-equal? (len (make-hash '((a . 1) (b . 2)))) 3)) ; len 2

@ -1,8 +1,9 @@
#lang racket/base
(require typed/sugar/define)
(require "../define.rkt" racket/set "../coerce.rkt")
(define/typed+provide (bytecount->string bytecount)
(Nonnegative-Integer -> String)
(define+provide+safe (bytecount->string bytecount)
(integer? . -> . string?)
(define (format-with-threshold threshold suffix)
;; upconvert by factor of 100 to get two digits after decimal
(format "~a ~a" (exact->inexact (/ (round ((* bytecount 100) . / . threshold)) 100)) suffix))
@ -17,6 +18,4 @@
[(bytecount . >= . threshold-gigabyte) (format-with-threshold threshold-gigabyte "GB")]
[(bytecount . >= . threshold-megabyte) (format-with-threshold threshold-megabyte "MB")]
[(bytecount . >= . threshold-kilobyte) (format-with-threshold threshold-kilobyte "KB")]
[else (format "~a bytes" bytecount)]))
[else (format "~a bytes" bytecount)]))

@ -0,0 +1,27 @@
#lang racket/base
(require racket/port)
(provide (all-defined-out) (all-from-out racket/port))
(define (port-position ip [where #f])
(cond
[where (file-position ip where)
ip]
[else (file-position ip)]))
(define (set-port-position! ip where)
(file-position ip where))
(module+ test
(require rackunit)
(define ip (open-input-bytes (bytes 1 2 3 4)))
(port-count-lines! ip)
(check-equal? (port-position ip) 0)
(check-equal? (read-byte ip) 1)
(check-equal? (port-position ip) 1)
(check-equal? (read-byte ip) 2)
(set-port-position! ip 4)
(check-equal? (port-position ip) 4)
(check-equal? (read-byte ip) eof)
(set-port-position! ip 0)
(check-equal? (port-position ip) 0)
(check-equal? (read-byte ip) 1))

@ -0,0 +1,3 @@
#lang racket/base
(define included-symbol 'bar)

@ -0,0 +1,37 @@
#lang racket/base
(require "../define.rkt" "../coerce.rkt")
(define+provide+safe (starts-with? str starter)
(string? string? . -> . coerce/boolean?)
(define pat (regexp (format "^~a" (regexp-quote starter))))
(and (regexp-match pat (->string str)) #t))
(define+provide+safe (ends-with? str ender)
(string? string? . -> . coerce/boolean?)
(define pat (regexp (format "~a$" (regexp-quote ender))))
(and (regexp-match pat (->string str)) #t))
(define+provide+safe (capitalized? str-in)
(string? . -> . coerce/boolean?)
(define str (->string str-in))
(and (positive? (string-length str))
(char-upper-case? (car (string->list (car (regexp-match "." str)))))))
(module+ test
(require rackunit)
(check-true (starts-with? "foobar" "foo"))
(check-true (starts-with? "foobar" "foobar"))
(check-false (starts-with? "foobar" "zam"))
(check-false (starts-with? "foobar" "foobars"))
(check-false (starts-with? "foo" "."))
(check-true (ends-with? "foobar" "bar"))
(check-false (ends-with? "foobar" "zam"))
(check-true (ends-with? "foobar" "foobar"))
(check-false (ends-with? "foobar" "foobars"))
(check-true (capitalized? "Brennan"))
(check-false (capitalized? "foobar")))

@ -0,0 +1,39 @@
#lang racket/base
(require (for-syntax racket/base racket/syntax))
(provide (all-defined-out))
(begin-for-syntax
(require racket/string racket/format)
(define (make-prefix caller-stx)
(string-join (map ~a (list (syntax-source caller-stx) (syntax-line caller-stx))) ":" #:after-last ":")))
(define-syntax (define-stub-stop stx)
(syntax-case stx ()
[(_ ID)
(with-syntax ([ERROR-ID (format-id stx "~a~a:not-implemented" (make-prefix stx) (syntax->datum #'ID))])
#'(define (ID . args)
(error 'ERROR-ID)))]))
(provide (rename-out [define-stub-stop define-stub]))
(define-syntax (define-stub-go stx)
(syntax-case stx ()
[(_ ID)
(with-syntax ([ERROR-ID (format-id stx "~a~a:not-implemented" (make-prefix stx) (syntax->datum #'ID))])
#'(define (ID . args)
(displayln 'ERROR-ID)))]))
(define-syntax (define-unfinished stx)
(syntax-case stx ()
[(_ (ID . ARGS) . BODY)
(with-syntax ([ID-UNFINISHED (format-id stx "~a~a:unfinished" (make-prefix stx) (syntax->datum #'ID))])
#'(define (ID . ARGS)
(begin . BODY)
(error 'ID-UNFINISHED)))]))
(define-syntax (unfinished stx)
(syntax-case stx ()
[(_)
(with-syntax ([ID-UNFINISHED (format-id stx "~a:~a:~a" (path->string (syntax-source stx)) (syntax-line stx) (syntax->datum #'unfinished))])
#'(error 'ID-UNFINISHED))]))

@ -1,12 +1,29 @@
#lang racket/base
(require xml racket/port racket/contract "define.rkt")
(require xml
racket/port
racket/contract
"define.rkt")
(provide (all-defined-out))
(define+provide+safe (xml-string->xexprs str)
(string? . -> . (values xexpr? xexpr?))
(define xml-doc (with-input-from-string str (λ _ (permissive-xexprs #t) (read-xml))))
(values (xml->xexpr (document-prolog xml-doc)) (xml->xexpr (document-element xml-doc))))
(parameterize ([current-input-port (open-input-string str)]
[permissive-xexprs #true])
(define xml-doc (read-xml))
(values (xml->xexpr (document-prolog xml-doc)) (xml->xexpr (document-element xml-doc)))))
(define+provide+safe (xexprs->xml-string prolog-xexpr root-xexpr)
(xexpr? xexpr? . -> . string?)
(with-output-to-string (λ _ (write-xml (document (xexpr->xml prolog-xexpr) (xexpr->xml root-xexpr) null)))))
(with-output-to-string
(λ ()
(parameterize ([permissive-xexprs #true])
(write-xml (document (xexpr->xml prolog-xexpr) (xexpr->xml root-xexpr) null))))))
(module+ test
(require rackunit)
(require xml)
(define str "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>hello world</root>")
(define-values (str-prolog str-doc) (xml-string->xexprs str))
(check-equal? str-prolog (prolog (list (p-i (location 1 0 1) (location 1 38 39) 'xml "version=\"1.0\" encoding=\"utf-8\"")) #f null))
(check-equal? str-doc '(root () "hello world"))
(check-equal? (xexprs->xml-string str-prolog str-doc) str))

@ -1,17 +0,0 @@
#lang typed/racket/base
(define-syntax-rule (r/p name)
(begin
(require name)
(provide (all-from-out name))))
(r/p "sugar/cache.rkt")
(r/p "sugar/coerce.rkt")
(r/p "sugar/debug.rkt")
(r/p "sugar/define.rkt")
(r/p "sugar/file.rkt")
(r/p "sugar/len.rkt")
(r/p "sugar/list.rkt")
(r/p "sugar/misc.rkt")
(r/p "sugar/string.rkt")
(r/p "sugar/test.rkt")

@ -1,16 +0,0 @@
#lang typed/racket/base
(require (for-syntax typed/racket/base) typed/sugar/define)
(define/typed+provide (make-caching-proc base-proc)
(All (A B) (A * -> B) -> (A * -> B))
(let ([cache ((inst make-hash (Listof A) B))])
(λ args
(hash-ref! cache args (λ () (apply base-proc args))))))
(provide define/caching)
(define-syntax (define/caching stx)
(syntax-case stx ()
[(_ (name arg ... . rest-arg) body ...)
#'(define/caching name (λ(arg ... . rest-arg) body ...))]
[(_ name body ...)
#'(define name (make-caching-proc body ...))]))

@ -1,3 +0,0 @@
#lang typed/racket/base
;; isolate typed requires in a helper file so the untyped versions can be substituted on the untyped side
(require typed/net/url)

@ -1,109 +0,0 @@
#lang typed/racket/base
(require (for-syntax typed/racket/base racket/syntax) sugar/include)
(include-without-lang-line "coerce-helper.rkt")
(require typed/sugar/define racket/set racket/sequence "len.rkt") ; want relative path-spec for bilingual conversion
(define-syntax-rule (make-coercion-error-handler target-format x)
(λ(e) (error (string->symbol (format "->~a" target-format)) (format "Cant convert ~s to ~a" x target-format))))
(define-type Intable (U Number String Symbol Char Path Lengthable))
(define/typed+provide (->int x)
(Intable -> Integer)
(with-handlers ([exn:fail? (make-coercion-error-handler 'int x)])
(cond
[(or (integer? x) (real? x)) (assert (inexact->exact (floor x)) integer?)]
[(complex? x) (->int (real-part x))]
[(string? x) (let ([strnum (string->number x)])
(if (real? strnum) (->int strnum) (error 'ineligible-string)))]
[(or (symbol? x) (path? x)) (->int (->string x))]
[(char? x) (char->integer x)]
[else (len x)]))) ; covers Lengthable types
(provide Stringish)
(define-type Stringish (U String Symbol Number Path Char Null Void SugarURL))
(define/typed+provide (->string x)
(Stringish -> String)
(if (string? x)
x ; fast exit for strings
(with-handlers ([exn:fail? (make-coercion-error-handler 'string x)])
(cond
[(or (equal? '() x) (void? x)) ""]
[(symbol? x) (symbol->string x)]
[(number? x) (number->string x)]
[(path? x) (path->string x)]
[(char? x) (format "~a" x)]
[(url? x) (url->string x)]
[else (error 'bad-type)]))))
;; ->symbol, ->path, and ->url are just variants on ->string
;; two advantages: return correct type, and more accurate error
;; no need for "Symbolable" type - same as Stringable
(define/typed+provide (->symbol x)
(Stringish -> Symbol)
(if (symbol? x)
x
(with-handlers ([exn:fail? (make-coercion-error-handler 'symbol x)])
(string->symbol (->string x)))))
(define-type Pathish (U Stringish url))
(provide Pathish)
(define/typed+provide (->path x)
(Pathish -> Path)
(if (path? x)
x
(with-handlers ([exn:fail? (make-coercion-error-handler 'path x)])
(cond
[(url? x) (apply build-path (cast (map path/param-path (url-path x)) (List* Path-String (Listof Path-String))))]
[else (string->path (->string x))]))))
;; Use private name here because 'URL' identifier has been added since 6.0
(define-type SugarURL url)
(define/typed+provide (->url x)
(Stringish -> SugarURL)
(with-handlers ([exn:fail? (make-coercion-error-handler 'url x)])
(string->url (->string x))))
(define/typed+provide (->complete-path x)
(Stringish -> Path)
(with-handlers ([exn:fail? (make-coercion-error-handler 'complete-path x)])
(path->complete-path (->path x))))
(define/typed+provide (->list x)
(Any -> (Listof Any))
(if (list? x)
x
(with-handlers ([exn:fail? (make-coercion-error-handler 'list x)])
(cond
[(string? x) (list x)]
[(vector? x) (for/list ([i (in-vector x)])
i)]
[(set? x) (set->list x)]
;; conditional sequencing relevant because hash also tests true for `sequence?`
[(hash? x) (hash->list x)]
[(integer? x) (list x)] ; because an integer tests #t for sequence?
[(sequence? x) (sequence->list x)]
;[(stream? x) (stream->list x)] ;; no support for streams in TR
[else (list x)]))))
(define/typed+provide (->vector x)
(Any -> VectorTop)
(if (vector? x)
x
(with-handlers ([exn:fail? (make-coercion-error-handler 'vector x)])
(list->vector (->list x)))))
(define/typed+provide (->boolean x)
(Any -> Boolean)
(and x #t))

@ -1,88 +0,0 @@
#lang typed/racket/base
(require (for-syntax racket/base racket/syntax))
(provide (all-defined-out))
(define-syntax (report stx)
(syntax-case stx ()
[(_ expr) #'(report expr expr)]
[(_ expr name)
#'(let ([expr-result expr])
(eprintf "~a = ~v\n" 'name expr-result)
expr-result)]))
(define-syntax (report/line stx)
(syntax-case stx ()
[(_ expr) #'(report/line expr expr)]
[(_ expr name)
(with-syntax ([line (syntax-line #'expr)])
#'(let ([expr-result expr])
(eprintf "~a = ~v on line ~v\n" 'name expr-result line)
expr-result))]))
(define-syntax (report/file stx)
(syntax-case stx ()
[(_ expr) #'(report/file expr expr)]
[(_ expr name)
(with-syntax ([file (syntax-source #'expr)]
[line (syntax-line #'expr)])
#'(let ([expr-result expr])
(eprintf "~a = ~v on line ~v in \"~a\"\n" 'name expr-result line file)
expr-result))]))
(define-syntax-rule (define-multi-version multi-name name)
(define-syntax-rule (multi-name x (... ...))
(begin (name x) (... ...))))
(define-multi-version report* report)
(define-multi-version report*/line report/line)
(define-multi-version report*/file report/file)
(define-syntax report-apply
(syntax-rules ()
[(report-apply proc expr)
(let ([lst expr])
(report (apply proc lst) (apply proc expr))
lst)]
[(report-apply proc expr #:line)
(let ([lst expr])
(report (apply proc lst) (apply proc expr) #:line)
lst)]))
#|
(define-syntax (verbalize stx)
(syntax-case stx ()
[(_ proc args ...)
(with-syntax ([proc-input (format-id stx "args to ~a" #'proc)])
#'(begin
(let () (report (list args ...) proc-input) (void))
(report (proc args ...))))]))
|#
(define-syntax-rule (repeat num expr ...)
(for/last ([i (in-range num)])
expr ...))
(define-syntax-rule (time-repeat num expr ...)
(time (repeat num expr ...)))
(define-syntax (time-repeat* stx)
(syntax-case stx ()
[(_ num expr ...)
#'(let ([n num])
(values (time-repeat n expr) ...))]))
(define-syntax (compare stx)
(syntax-case stx ()
[(_ expr id id-alt ...)
#'(values expr (let ([id id-alt]) expr) ...)]))

@ -1,39 +0,0 @@
#lang typed/racket/base/no-check
;; use of no-check is deliberate here.
;; these helper macros don't do any type checking, just rearranging
;; they can't be combined with the untyped define macros, however
;; because the -> symbol is defined differently here
(require (for-syntax typed/racket/base racket/syntax))
(provide (all-defined-out))
(define-syntax (define/typed stx)
(syntax-case stx ()
[(_ (proc-name arg ... . rest-arg) type-expr body ...)
#'(define/typed proc-name type-expr
(λ(arg ... . rest-arg) body ...))]
[(_ proc-name type-expr body ...)
#'(begin
(: proc-name type-expr)
(define proc-name body ...))]))
(define-syntax (define/typed+provide stx)
(syntax-case stx ()
[(_ (proc-name arg ... . rest-arg) type-expr body ...)
#'(begin
(provide proc-name)
(define/typed proc-name type-expr
(λ(arg ... . rest-arg) body ...)))]
[(_ proc-name type-expr body ...)
#'(begin
(provide proc-name)
(begin
(: proc-name : type-expr)
(define proc-name body ...)))]))
(define-syntax (define-type+predicate stx)
(syntax-case stx ()
[(_ id basetype)
(with-syntax ([id? (format-id stx "~a?" #'id)])
#'(begin
(define-type id basetype)
(define-predicate id? id)))]))

@ -1,59 +0,0 @@
#lang typed/racket/base
(require typed/sugar/define "coerce.rkt" "string.rkt" racket/path)
(define/typed+provide (get-enclosing-dir p)
(Pathish -> Path)
(simplify-path (build-path (->path p) 'up)))
;; does path have a certain extension
(define/typed+provide (has-ext? x ext)
(Pathish Stringish -> Boolean)
(define ext-of-path (filename-extension (->path x)))
(->boolean (and ext-of-path (equal? (string-downcase (bytes->string/utf-8 ext-of-path)) (string-downcase (->string ext))))))
;; get file extension as a string, or return #f
;; (consistent with filename-extension behavior)
(define/typed+provide (get-ext x)
(Pathish -> (Option String))
(let ([fe-result (filename-extension (->path x))])
(and fe-result (bytes->string/utf-8 fe-result))))
;; todo: add extensions
(define/typed+provide binary-extensions
(Listof String)
(map symbol->string '(gif jpg jpeg mp3 png zip pdf ico tar ai eps exe)))
(define/typed+provide (has-binary-ext? x)
(Pathish -> Boolean)
(let ([x (->path x)])
(ormap (λ:([ext : String]) (has-ext? x ext)) binary-extensions)))
;; put extension on path
;; use local contract here because this function is used within module
(define/typed+provide (add-ext x ext)
(Stringish Stringish -> Path)
(->path (string-append (->string x) "." (->string ext))))
;; take one extension off path
(define/typed+provide (remove-ext x)
(Pathish -> Path)
;; pass through hidden files (those starting with a dot)
(let ([x (->path x)])
(if (x . starts-with? . ".")
x
(path-replace-suffix x ""))))
;; take all extensions off path
(define/typed+provide (remove-ext* x)
(Pathish -> Path)
;; pass through hidden files (those starting with a dot)
(let ([x (->path x)])
(if (x . starts-with? . ".")
x
(let ([path-with-removed-ext (remove-ext x)])
(if (equal? x path-with-removed-ext)
x
(remove-ext* path-with-removed-ext))))))

@ -1,19 +0,0 @@
#lang typed/racket/base
(require racket/set racket/sequence)
(require typed/sugar/define)
(provide Lengthable)
(define-type Lengthable (U (Listof Any) String Symbol Path (Vectorof Any) HashTableTop (Setof Any)))
(define/typed+provide (len x)
(Lengthable -> Nonnegative-Integer)
(cond
[(list? x) (length x)]
[(string? x) (string-length x)]
[(symbol? x) (len (symbol->string x))]
[(path? x) (len (path->string x))]
[(vector? x) (vector-length x)]
[(hash? x) (len (hash-keys x))]
[(set? x) (len (set->list x))]
[(and (sequence? x) (not (integer? x))) (len (sequence->list x))]
[else (error "len: cant calculate length of" x)]))

@ -1,4 +0,0 @@
#lang typed/racket/base
;; isolate typed requires in a helper file so the untyped versions can be substituted on the untyped side
(require/typed racket/list [dropf (All (A) (Listof A) (A -> Boolean) -> (Listof A))]
[dropf-right (All (A) (Listof A) (A -> Boolean) -> (Listof A))])

@ -1,183 +0,0 @@
#lang typed/racket/base
(require (for-syntax racket/base racket/syntax) racket/function sugar/include)
(require (except-in racket/list dropf dropf-right) typed/sugar/define "coerce.rkt" "len.rkt")
(include-without-lang-line "list-helper.rkt")
;; use fully-qualified paths in require,
;; so they'll work when this file is included elsewhere
(provide (all-defined-out))
(define/typed+provide (trimf xs test-proc)
(All (A) ((Listof A) (A -> Boolean) -> (Listof A)))
(dropf-right (dropf xs test-proc) test-proc))
(define/typed+provide (slicef xs pred)
(All (A) ((Listof A) (A -> Boolean) -> (Listof (Listof A))))
(define-values (last-list list-of-lists last-negating)
(for/fold: ([current-list : (Listof A) empty]
[list-of-lists : (Listof (Listof A)) empty]
[negating? : Boolean #f])
([x (in-list xs)])
(define current-pred (if negating? (λ: ([x : A]) (not (pred x))) pred))
(if (current-pred x)
(values (cons x current-list) list-of-lists negating?)
(values (cons x null) (if (not (empty? current-list))
(cons (reverse current-list) list-of-lists)
list-of-lists) (not negating?)))))
(reverse (cons (reverse last-list) list-of-lists)))
(define/typed+provide (slicef-at xs pred [force? #f])
;; with polymorphic function, use cased typing to simulate optional position arguments
(All (A) (case-> ((Listof A) (A -> Boolean) -> (Listof (Listof A)))
((Listof A) (A -> Boolean) Boolean -> (Listof (Listof A)))))
(define-values (last-list list-of-lists)
(for/fold:
([current-list : (Listof A) empty][list-of-lists : (Listof (Listof A)) empty])
([x (in-list xs)])
(if (pred x)
(values (cons x null) (if (not (empty? current-list))
(cons (reverse current-list) list-of-lists)
list-of-lists))
(values (cons x current-list) list-of-lists))))
(let ([list-of-lists (reverse (if (empty? last-list)
list-of-lists
(cons (reverse last-list) list-of-lists)))])
(if (and force? (not (empty? list-of-lists)) (not (pred (caar list-of-lists))))
(cdr list-of-lists)
list-of-lists)))
(define/typed+provide (slicef-after xs pred)
(All (A) ((Listof A) (A -> Boolean) -> (Listof (Listof A))))
(define-values (last-list list-of-lists)
(for/fold: ([current-list : (Listof A) empty][list-of-lists : (Listof (Listof A)) empty])
([x (in-list xs)])
(if (pred x)
(values empty (cons (reverse (cons x current-list)) list-of-lists))
(values (cons x current-list) list-of-lists))))
(reverse (if (empty? last-list)
list-of-lists
(cons (reverse last-list) list-of-lists))))
(define/typed+provide (slice-at xs len [force? #f])
;; with polymorphic function, use cased typing to simulate optional position arguments
(All (A) (case-> ((Listof A) Positive-Integer -> (Listof (Listof A)))
((Listof A) Positive-Integer Boolean -> (Listof (Listof A)))))
(define-values (last-list list-of-lists)
(for/fold: ([current-list : (Listof A) empty][list-of-lists : (Listof (Listof A)) empty])
([x (in-list xs)][i (in-naturals)])
(if (= (modulo (add1 i) len) 0)
(values empty (cons (reverse (cons x current-list)) list-of-lists))
(values (cons x current-list) list-of-lists))))
(reverse (if (or (empty? last-list) (and force? (not (= len (length last-list)))))
list-of-lists
(cons (reverse last-list) list-of-lists))))
(define/typed+provide (filter-split xs pred)
(All (A) ((Listof A) (A -> Boolean) -> (Listof (Listof A))))
(define-values (last-list list-of-lists)
(for/fold: ([current-list : (Listof A) empty][list-of-lists : (Listof (Listof A)) empty])
([x (in-list xs)])
(if (pred x)
(values empty (if (not (empty? current-list))
(cons (reverse current-list) list-of-lists)
list-of-lists))
(values (cons x current-list) list-of-lists))))
(reverse (if (not (empty? last-list))
(cons (reverse last-list) list-of-lists)
list-of-lists)))
(define/typed+provide (frequency-hash xs)
(All (A) ((Listof A) -> (HashTable A Integer)))
(define counter ((inst make-hash A Integer)))
(for ([item (in-list xs)])
(hash-update! counter item (λ:([v : Integer]) (add1 v)) (λ _ 0)))
counter)
(define/typed+provide (members-unique? x)
(All (A) ((U (Listof A) (Vectorof A) String) -> Boolean))
(cond
[(list? x) (= (len (remove-duplicates x)) (len x))]
[(vector? x) (members-unique? (->list x))]
[(string? x) (members-unique? (string->list x))]
[else (error (format "members-unique? cannot be determined for ~a" x))]))
(define/typed+provide (members-unique?/error x)
(All (A) ((U (Listof A) (Vectorof A) String) -> Boolean))
(define result (members-unique? x))
(if (not result)
(let* ([duplicate-keys (filter-not empty? (hash-map (frequency-hash (->list x))
(λ:([element : Any] [freq : Integer]) (if (> freq 1) element '()))))])
(error (string-append "members-unique? failed because " (if (= (len duplicate-keys) 1)
"item isnt"
"items arent") " unique:") duplicate-keys))
result))
;; for use inside quasiquote
;; instead of ,(when ...) use ,@(when/splice ...)
;; to avoid voids
(provide when/splice)
(define-syntax (when/splice stx)
(syntax-case stx ()
[(_ test body)
#'(if test (list body) '())]))
(provide values->list)
(define-syntax (values->list stx)
(syntax-case stx ()
[(_ values-expr) #'(call-with-values (λ () values-expr) list)]))
(define/typed+provide (sublist xs i j)
(All (A) ((Listof A) Index Index -> (Listof A)))
(cond
[(> j (length xs)) (error 'sublist (format "ending index ~a exceeds length of list" j))]
[(>= j i) (take (drop xs i) (- j i))]
[else (error 'sublist (format "starting index ~a is larger than ending index ~a" i j))]))
(define/typed+provide (break-at xs bps)
(All (A) ((Listof A) (U Nonnegative-Integer (Listof Nonnegative-Integer)) -> (Listof (Listof A))))
(let ([bps (if (list? bps) bps (list bps))]) ; coerce bps to list
(when (ormap (λ:([bp : Nonnegative-Integer]) (>= bp (length xs))) bps)
(error 'break-at (format "breakpoint in ~v is greater than or equal to input list length = ~a" bps (length xs))))
;; easier to do back to front, because then the list index for each item won't change during the recursion
;; cons a zero onto bps (which may already start with zero) and then use that as the terminating condition
;; because breaking at zero means we've reached the start of the list
(reverse (let loop ([xs xs][bps (reverse (cons 0 bps))])
(if (= (car bps) 0)
(cons xs null) ; return whatever's left, because no more splits are possible
(let-values ([(head tail) (split-at xs (car bps))])
(cons tail (loop head (cdr bps)))))))))
(define/typed+provide (shift xs how-far [fill-item #f] [cycle #f])
(All (A) (case-> ((Listof (Option A)) Integer -> (Listof (Option A)))
((Listof (Option A)) Integer (Option A) -> (Listof (Option A)))
((Listof (Option A)) Integer (Option A) Boolean -> (Listof (Option A)))))
(define abs-how-far (abs how-far))
(cond
[(> abs-how-far (length xs)) (error 'shift "index is too large for list\nindex: ~a\nlist: ~v" how-far xs)]
[(= how-far 0) xs]
[(positive? how-far)
(define filler (if cycle
(take-right xs abs-how-far)
(make-list abs-how-far fill-item)))
(append filler (drop-right xs abs-how-far))]
[else ; how-far is negative
(define filler (if cycle
(take xs abs-how-far)
(make-list abs-how-far fill-item)))
(append (drop xs abs-how-far) filler)]))
(define/typed+provide (shifts xs how-fars [fill-item #f] [cycle #f])
(All (A) (case-> ((Listof (Option A)) (Listof Integer) -> (Listof (Listof (Option A))))
((Listof (Option A)) (Listof Integer) (Option A) -> (Listof (Listof (Option A))))
((Listof (Option A)) (Listof Integer) (Option A) Boolean -> (Listof (Listof (Option A))))))
(map (λ:([how-far : Integer]) (shift xs how-far fill-item cycle)) how-fars))

@ -1,21 +0,0 @@
#lang typed/racket/base
(require typed/sugar/define "coerce.rkt")
(define/typed+provide (starts-with? str starter)
(Stringish Stringish -> Boolean)
(let ([str (->string str)]
[starter (->string starter)])
(and (<= (string-length starter) (string-length str))
(equal? (substring str 0 (string-length starter)) starter))))
(define/typed+provide (ends-with? str ender)
(Stringish Stringish -> Boolean)
(let ([str (->string str)]
[ender (->string ender)])
(and (<= (string-length ender) (string-length str))
(equal? (substring str (- (string-length str) (string-length ender)) (string-length str)) ender))))
(define/typed+provide (capitalized? str)
(Stringish -> Boolean)
(let ([str (->string str)])
(char-upper-case? (car (string->list str)))))

@ -1,22 +0,0 @@
#lang typed/racket/base/no-check
(require (for-syntax typed/racket/base) typed/rackunit)
(provide check-typing-fails check-typing)
(define-syntax (check-typing-base stx)
(syntax-case stx ()
[(_ wants-to-fail? expr)
(let* ([wants-to-fail? (syntax->datum #'wants-to-fail?)]
[λ-arg 'v]
[eval-string (if wants-to-fail? `(cons '#%top-interaction ,λ-arg) λ-arg)]
[check-string (if wants-to-fail? '(curry check-exn exn:fail:syntax?) 'check-not-exn)])
#`(begin
(define-namespace-anchor ns)
(let ([E (λ(#,λ-arg) (eval #,eval-string (namespace-anchor->namespace ns)))])
(apply #,check-string (list (λ _ (call-with-values (λ _ (E 'expr)) (λ vals (car vals)))))))))]))
(define-syntax-rule (check-typing-fails expr)
(check-typing-base #t expr))
(define-syntax-rule (check-typing expr)
(check-typing-base #f expr))

@ -1,45 +0,0 @@
#lang typed/racket/base
(require racket/port)
#;(provide (all-defined-out))
#;(require/typed xml [permissive-xexprs (Parameterof Boolean)]
[#:struct prolog ([misc : (Listof Misc)][dtd : (Option DTD)][misc2 : (Listof Misc)])]
[#:struct document ([prolog : Prolog][element : Element][misc : (Listof Misc)])])
#|
The following grammar describes expressions that create X-expressions:
xexpr = string
| (list symbol (list (list symbol string) ...) xexpr ...)
| (cons symbol (list xexpr ...))
| symbol
| valid-char?
| cdata
| misc
|#
(define-type Cdata String) ;; could be tighter
;; valid-char could be tighter
#|
Returns true if x is an exact-nonnegative-integer whose character interpretation under UTF-8 is from the set ([#x1-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]),
|#
(define-type Valid-Char Char)
(define-type Xexpr (Rec X (U String
(List* Symbol (Listof (List Symbol String)) (Listof X))
(Pairof Symbol (Listof X))
Symbol
Valid-Char
Cdata)))
(define-predicate Xexpr? Xexpr)
#|
(: xml-string->xexprs (String . -> . (values Xexpr Xexpr)))
(define (xml-string->xexprs str)
(define xml-doc (with-input-from-string str (λ _ (permissive-xexprs #t) (read-xml))))
(values (xml->xexpr (document-prolog xml-doc)) (xml->xexpr (document-element xml-doc))))
(define (xexprs->xml-string prolog-xexpr root-xexpr)
(xexpr? xexpr? . -> . string?)
(with-output-to-string (λ _ (write-xml (document (xexpr->xml prolog-xexpr) (xexpr->xml root-xexpr) null)))))
|#
Loading…
Cancel
Save