Compare commits

..

1 Commits

Author SHA1 Message Date
Matthew Butterick 90baf7868d shift some stuff 10 years ago

@ -1,43 +0,0 @@
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

@ -0,0 +1,33 @@
# 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

@ -0,0 +1,165 @@
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.

@ -1,9 +0,0 @@
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,4 +1,5 @@
## Sugar ![Build Status](https://github.com/mbutterick/sugar/workflows/CI/badge.svg)
Sugar [![Build Status](https://travis-ci.org/mbutterick/sugar.svg?branch=master)](https://travis-ci.org/mbutterick/sugar)
-----
Functions that improve the readability of Racket code in Racket 6.0+.
@ -14,13 +15,8 @@ In safe mode (with contracts):
(require (submod sugar safe))
You can [read the docs here](http://pkg-build.racket-lang.org/doc/sugar).
## License
Or in typed mode:
MIT
(require typed/sugar)
## 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.
You can [read the docs here](http://pkg-build.racket-lang.org/doc/sugar).

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

@ -1,17 +1,6 @@
#lang racket/base
(require (for-syntax
racket/base
"private/syntax-utils.rkt")
"define.rkt")
(require sugar/define)
(require-via-wormhole "../typed/sugar/cache.rkt")
(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))))
(provide+safe [make-caching-proc (procedure? . -> . procedure?)]
define/caching)

@ -0,0 +1,3 @@
#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,4 +1,75 @@
#lang racket/base
(require "private/syntax-utils.rkt")
(require (for-syntax racket/base racket/syntax) sugar/define net/url)
(require-via-wormhole "../typed/sugar/coerce.rkt")
(require+provide/safe "coerce/base.rkt" "coerce/contract.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)

@ -1,123 +0,0 @@
#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))

@ -1,46 +0,0 @@
#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)

@ -0,0 +1,46 @@
#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,184 +1,56 @@
#lang racket/base
(require racket/string
(for-syntax racket/base)
"define.rkt")
(require sugar/define)
(require-via-wormhole "../typed/sugar/debug.rkt")
(provide+safe report report/time time-name
report/line report/file
(provide+safe report report/line report/file
report* report*/line report*/file
report-apply repeat time-repeat time-repeat* time-name time-named time-avg compare)
report-apply repeat time-repeat time-repeat* 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))))
(module* reader racket/base
(require syntax/module-reader racket/syntax)
(provide (rename-out [debug-read read]
[debug-read-syntax read-syntax]
[debug-get-info get-info]))
(define-syntax (time-repeat* stx)
(syntax-case stx ()
[(_ NUM EXPR ...)
#'(let ([n NUM])
(values (time-repeat n EXPR) ...))]))
(define (make-debug-readtable [rt (current-readtable)])
(make-readtable rt #\^ 'dispatch-macro report-proc))
(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/with-syntax report (datum->syntax #f 'report))
(define/with-syntax report/line (datum->syntax #f 'report/line))
(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 (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 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 (rd . args)
(parameterize ([current-readtable (make-debug-readtable (current-readtable))])
(apply reader args)))
rd)
(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
(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"))))))
(and (module-path? sym) (vector `(submod ,sym reader)))))
wrap-reader
wrap-reader
(λ (proc)
(λ (key defval)
(lambda (proc)
(lambda (key defval)
(define (fallback) (if proc (proc key defval) 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))))))
[else (fallback)]))))))

@ -1,69 +1,96 @@
#lang racket/base
(require (for-syntax racket/base
racket/syntax
syntax/strip-context
"private/syntax-utils.rkt")
racket/contract)
(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.
(define-syntax (make-safe-module stx)
(syntax-case stx ()
[(_ [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)
[(_ name contract)
#'(module+ safe
(provide ID))]))
(require racket/contract)
(provide (contract-out [name contract])))]
[(_ name)
#'(module+ safe
(provide name))]))
(define-syntax (define+provide+safe stx)
(with-syntax ([(ID CONTRACT LAMBDA-EXP) (lambdafy-with-contract stx)])
#'(begin
(define ID LAMBDA-EXP)
(provide+safe [ID CONTRACT]))))
(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))]))
;; for previously defined identifiers
;; takes args like (provide+safe [id contract]) or just (provide+safe id)
;; takes args like (provide+safe [ident contract]) or just (provide+safe ident)
;; any number of args.
(define-syntax-rule (provide+safe THING ...)
(begin
(provide+safe/once THING) ...))
;; `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 (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 (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))))
(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 ...))]))
(define-syntax (define/contract+provide stx)
(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))))
(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 ...))]))
(define-syntax (define+provide stx)
(with-syntax ([(ID LAMBDA-EXP) (lambdafy stx)])
#'(begin
(provide ID)
(define ID LAMBDA-EXP))))
(syntax-case stx ()
[(_ (proc arg ... . rest-arg) body ...)
#'(define+provide proc
(λ(arg ... . rest-arg) body ...))]
[(_ name body ...)
#'(begin
(provide name)
(define name body ...))]))
(provide+safe make-safe-module
(provide+safe require-via-wormhole
make-safe-module
define+provide+safe
provide+safe
define+provide/contract

@ -1,100 +1,14 @@
#lang racket/base
(require racket/list
racket/match
(except-in racket/path filename-extension)
"define.rkt"
"coerce/base.rkt")
(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?)])
;; 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,10 +1,11 @@
#lang racket/base
(require (for-syntax racket/base
syntax/path-spec
racket/private/increader
compiler/cm-accomplice
racket/match racket/function)
"../define.rkt")
sugar/define)
(provide+safe include-without-lang-line)

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

@ -0,0 +1,5 @@
#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?)])

@ -0,0 +1,3 @@
#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,217 +1,40 @@
#lang racket/base
(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)
(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])
(apply values ((if (list? shift-amount-or-amounts)
shifts
shift) xs shift-amount-or-amounts fill-item cycle)))

@ -1,11 +1,23 @@
#lang racket/base
(require "private/syntax-utils.rkt")
(require+provide/safe "cache.rkt"
"coerce.rkt"
"debug.rkt"
"define.rkt"
"file.rkt"
"list.rkt"
"test.rkt"
"xml.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")

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

@ -1,42 +0,0 @@
#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))]
@defmodule[#:multi (sugar/cache (submod sugar/cache safe) typed/sugar/cache)]
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 racket/contract))
@(my-eval `(require sugar))
@title{Coercion}
@defmodule[#:multi (sugar/coerce (submod sugar/coerce safe))]
@defmodule[#:multi (sugar/coerce (submod sugar/coerce safe) typed/sugar/coerce)]
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?]
)]
Predicates that report whether @racket[_v] can be coerced to the specified type.
@bold{Untyped only.} 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 @@ Predicates that report whether @racket[_v] can be coerced to the specified type.
@defproc[(coerce/boolean? [v any/c]) boolean?]
@defproc[(coerce/list? [v any/c]) list?]
)]
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.
@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.
@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.
Type-neutral functions for getting elements out of a container, or testing membership. @bold{This submodule is untyped only.}
@defproc[

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

@ -5,10 +5,10 @@
@(define my-eval (make-base-eval))
@(my-eval `(require sugar))
@title{File extensions}
@defmodule[#:multi (sugar/file (submod sugar/file safe))]
@title{File}
@defmodule[#:multi (sugar/file (submod sugar/file safe) typed/sugar/file)]
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.
File utilities, mostly in the realm of file extensions. These functions don't access the filesystem.
Arguments that are @racket[pathish?] can take either a string or a path. For clarity below, I've used strings.
@ -30,11 +30,10 @@ 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]. Not sensitive to case.
Return @racket[#t] if the last file extension of @racket[_file-path] is @racket[_ext], otherwise @racket[#f].
@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")]
@ -73,3 +72,18 @@ 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)))
]

@ -7,3 +7,5 @@
@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].

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

@ -1,12 +1,12 @@
#lang scribble/manual
@(require scribble/eval (for-label racket sugar racket/function))
@(require scribble/eval (for-label racket sugar))
@(define my-eval (make-base-eval))
@(my-eval `(require sugar racket/list racket/function))
@(my-eval `(require sugar racket/list))
@title{Lists}
@defmodule[#:multi (sugar/list (submod sugar/list safe))]
@title{List}
@defmodule[#:multi (sugar/list (submod sugar/list safe) typed/sugar/list)]
@ -33,20 +33,9 @@ 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) (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))]
(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?))]
@defproc[
(slice-at
@ -85,9 +74,7 @@ Divide @racket[_lst] into sublists that are homogeneously @racket[_pred] or not
[pred procedure?]
[force? boolean? #f])
(listof list?)]
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.
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].
@examples[#:eval my-eval
(slicef-at (range 5) even?)
@ -99,17 +86,13 @@ If none of the elements match @racket[_pred], there is no slice to be made, and
@defproc[
(slicef-after
[lst list?]
[pred procedure?]
[force? boolean? #f])
[pred procedure?])
(listof 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.
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.
@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?)]
@ -149,6 +132,15 @@ 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.
@ -200,7 +192,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], and @racket[_cycle] is not true, 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], raise an error.
@examples[#:eval my-eval
(define xs (range 5))
@ -212,52 +204,6 @@ 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?]
@ -281,7 +227,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]
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.
@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.
@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))]
@defmodule[#:multi (sugar/string (submod sugar/string safe) typed/sugar/string)]
@defproc[

@ -1,6 +1,6 @@
#lang scribble/manual
@(require scribble/eval (for-label racket sugar))
@(require scribble/eval (for-label racket sugar (only-in typed/racket require/typed)))
@(define my-eval (make-base-eval))
@(my-eval `(require sugar))
@ -10,12 +10,17 @@
@author[(author+email "Matthew Butterick" "mb@mbtype.com")]
@defmodule[#:multi (sugar (submod sugar safe))]
@defmodule[#:multi (sugar (submod sugar safe) typed/sugar)]
A collection of small functions to help make Racket code simpler & more readable. Well, according to me, anyhow.
A collection of small functions to help make Racket code simpler & more readable.
Sugar can be invoked two ways: as an ordinary library, or as a library with contracts (using the @tt{safe} submodule).
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.
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[]
@ -25,12 +30,20 @@ Sugar can be invoked two ways: as an ordinary library, or as a library with cont
@include-section["coerce.scrbl"]
@include-section["container.scrbl"]
@include-section["debug.scrbl"]
@include-section["file-extensions.scrbl"]
@include-section["file.scrbl"]
@include-section["include.scrbl"]
@include-section["len.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.
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.}
@defproc[
(xml-string->xexprs

@ -0,0 +1,7 @@
#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,44 +1,39 @@
#lang racket/base
(require (for-syntax
racket/base
racket/syntax
syntax/strip-context)
"define.rkt")
(provide+safe module-test-external
module-test-internal
module-test-internal+external)
(require (for-syntax racket/base racket/syntax))
(require sugar/define)
(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 ...)
(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))))))]))
[(_ expr ...)
(with-syntax ([mod-name (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 ...)
(replace-context
stx
#'(begin
(module+ test
(require rackunit)
EXPR ...)))]))
[(_ 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))]))
(define-syntax (module-test-internal+external stx)
(syntax-case stx ()
[(_ EXPR ...)
(replace-context
stx
#'(begin
(module-test-internal EXPR ...)
(module-test-external EXPR ...)))]))
[(_ expr ...)
(let ([exprs (syntax->datum #'(expr ...))])
(datum->syntax stx `(begin
(module-test-internal ,@exprs)
(module-test-external ,@exprs)) stx))]))

@ -1,15 +1,10 @@
#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"])
(require sugar/debug rackunit)
(let ([out (open-output-string)])
(parameterize ([current-error-port out])
#R5)
#^5)
(check-equal? (get-output-string out) "5 = 5\n"))
(let ([out (open-output-string)]
[report/line "outta the blue!"])
(let ([out (open-output-string)])
(parameterize ([current-error-port out])
#RR5)
(check-equal? (get-output-string out) "5 = 5 on line 14\n"))
#^^5)
(check-equal? (get-output-string out) "5 = 5 on line 9\n"))

@ -1,24 +1,38 @@
#lang racket
(require (for-syntax racket/syntax
syntax/strip-context))
(require (for-syntax racket/syntax))
(define-syntax (eval-with-and-without-contracts stx)
(define-syntax (eval-as-untyped stx)
(syntax-case stx ()
[(_ 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))))]))
(eval-with-and-without-contracts
[(_ 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)))]))
(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
(check-equal? (->int 42) 42)
(check-equal? (->int 42.1) 42)
(check-equal? (->int 42+3i) 42)
@ -29,7 +43,6 @@
(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")
@ -40,15 +53,13 @@
(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-not-false (andmap (lambda (e) (member e '(1 2 3))) (->list (set 1 2 3))))
(check-equal? (->list (set 1 2 3)) '(3 2 1))
(check-equal? (->list "foo") (list "foo"))
(check-true (->boolean #t))
@ -58,72 +69,28 @@
(check-true (->boolean '()))
(check-true (->boolean '(1 2 3)))
(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-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"))
(check-true (members-unique? '(a b c)))
(check-false (members-unique? '(a b c c)))
@ -132,9 +99,7 @@
(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 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))))
(check-equal? (filter-split '(1 2 3 4 5 6) even?) '((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))
@ -147,41 +112,40 @@
(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"))
(check-equal? (remove-ext (->path ".foo.txt")) (->path ".foo.txt"))
(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"))
(check-equal? (remove-ext* (->path ".foo.txt")) (->path ".foo.txt"))
(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)
;; 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-equal? (get-enclosing-dir "/Users/MB/foo.txt") (->path "/Users/MB/"))
(check-equal? (get-enclosing-dir "/Users/MB/foo/") (->path "/Users/MB/"))
(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)))
@ -201,14 +165,6 @@
(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))
(check-equal? (sublist (range 5) 0 5) '(0 1 2 3 4))
@ -225,16 +181,12 @@
(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))))
(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))
(eval-as-untyped
(check-true (urlish? (->path "/Users/MB/home.html")))
(check-true (urlish? "/Users/MB/home.html?foo=bar"))
@ -249,18 +201,74 @@
(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)))
(check-equal? "42 = 42\n" (let ([os (open-output-string)])
(parameterize ([current-error-port os])
(report 42))
(get-output-string os)))
(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? "(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
|#

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

@ -1,6 +1,13 @@
#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))
@ -15,7 +22,8 @@
(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 rb:foo rbu:foo)))
(check-true (andmap (λ(val) (equal? val '(2))) (list trb:foo rb:foo rbu:foo)))

@ -1,14 +0,0 @@
#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)])]))

@ -1,95 +0,0 @@
#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)))]))

@ -1,86 +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: 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"))))

@ -1,25 +0,0 @@
#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))

@ -1,22 +0,0 @@
#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,95 +0,0 @@
#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)))

@ -1,48 +0,0 @@
#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,27 +0,0 @@
#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))

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

@ -1,37 +0,0 @@
#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")))

@ -1,39 +0,0 @@
#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,29 +1,12 @@
#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?))
(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 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+provide+safe (xexprs->xml-string prolog-xexpr root-xexpr)
(xexpr? xexpr? . -> . string?)
(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))
(with-output-to-string (λ _ (write-xml (document (xexpr->xml prolog-xexpr) (xexpr->xml root-xexpr) null)))))

@ -0,0 +1,17 @@
#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")

@ -0,0 +1,16 @@
#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 ...))]))

@ -0,0 +1,3 @@
#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)

@ -0,0 +1,109 @@
#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))

@ -0,0 +1,88 @@
#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) ...)]))

@ -0,0 +1,39 @@
#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)))]))

@ -0,0 +1,59 @@
#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))))))

@ -0,0 +1,19 @@
#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)]))

@ -0,0 +1,4 @@
#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))])

@ -0,0 +1,183 @@
#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,9 +1,8 @@
#lang racket/base
(require "../define.rkt" racket/set "../coerce.rkt")
(require typed/sugar/define)
(define+provide+safe (bytecount->string bytecount)
(integer? . -> . string?)
(define/typed+provide (bytecount->string bytecount)
(Nonnegative-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))
@ -19,3 +18,5 @@
[(bytecount . >= . threshold-megabyte) (format-with-threshold threshold-megabyte "MB")]
[(bytecount . >= . threshold-kilobyte) (format-with-threshold threshold-kilobyte "KB")]
[else (format "~a bytes" bytecount)]))

@ -0,0 +1,21 @@
#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)))))

@ -0,0 +1,22 @@
#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))

@ -0,0 +1,45 @@
#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