blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
171
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
8
| license_type
stringclasses 2
values | repo_name
stringlengths 6
82
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 13
values | visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 1.59k
594M
⌀ | star_events_count
int64 0
77.1k
| fork_events_count
int64 0
33.7k
| gha_license_id
stringclasses 12
values | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_language
stringclasses 46
values | src_encoding
stringclasses 14
values | language
stringclasses 2
values | is_vendor
bool 2
classes | is_generated
bool 1
class | length_bytes
int64 4
7.87M
| extension
stringclasses 101
values | filename
stringlengths 2
149
| content
stringlengths 4
7.87M
| has_macro_def
bool 2
classes |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6bd4f3358e7ad94bdde7cd7e8b74d9dae2c29305 | 6c60c8d1303f357c2c3d137f15089230cb09479b | /compatibility-lib/net/head-unit.rkt | ea5b6ae5ef320f1415bd60d297772b540c236c27 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | racket/compatibility | 6f96569a3e98909e1e89260eeedf4166b5e26890 | 5b2509e30e3b93ca9d6c9d6d8286af93c662d9a8 | refs/heads/master | 2023-08-23T06:41:14.503854 | 2022-07-08T02:43:36 | 2022-07-14T18:00:20 | 27,431,360 | 6 | 10 | NOASSERTION | 2022-07-14T18:00:21 | 2014-12-02T12:23:20 | Racket | UTF-8 | Racket | false | false | 131 | rkt | head-unit.rkt | #lang racket/base
(require racket/unit
"head-sig.rkt" net/head)
(define-unit-from-context head@ head^)
(provide head@)
| false |
0f6a0d0d53f4a0284fc7dd7ffb1d804e67e3b9d4 | 7ee7cdb18f421a2ae1ffe3fbd7a0629384d4f876 | /Assignment2/example.rkt | 5cfc8d29bdb3f01239a1486f875116594f48c4b1 | []
| no_license | JoeCameron1/CSC324-Principles-of-Programming-Languages-Assignments | 9b346afcfe0872dc9533ba2af77b28aa2256b1e5 | 59c3aad6403a87b3c99f96afea30f0300cb77ffb | refs/heads/master | 2021-01-12T06:04:47.025750 | 2016-12-24T18:27:55 | 2016-12-24T18:27:55 | 77,294,976 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 11,615 | rkt | example.rkt |
#lang racket
(define board '(
(0 0 0 0)
(0 1 0 0)
(0 0 2 0)
(2 0 3 0)))
;this is a board that is unsolved and the function 'ss' will return the solution to this 4x4 sudoku board.
(define (build-list l1 l2 l3)
(append l1 (append l2 l3))
)
;pre: takes 3 lists l1,l2,l3
;post: returns 1 list contianing all items in l1 l2 and l3
;why: this function was made to combine the non-candidates from column row and quadrant that intersect with the current cell we want to change
(define (get-row cell)
(car cell)
)
;pre: takes a list containing row and column e.g. '(3 1) meaning row 3 column 1
;post: returns the car of the list.
;why: to easily get the row that intersects with the cell we wish to change.
(define (get-column cell)
(car (cdr cell))
)
;pre: takes a list containing row and column e.g. '(3 1) meaning row 3 column 1
;post: returns the car of the cdr of the list.
;why: This function is to easily get the column that intersects with the cell we wish to change.
(define (row-ref board cell)
(list-ref board (get-row cell))
)
;pre: takes a board and a cell.
;post: returns the list representation of the row that intersects the cell.
;why: to easily find the non-candidates in that row.
(define (get-quad cell)
(cond
((and (< (get-row cell) 2) (< (get-column cell) 2)) 0)
((and (< (get-row cell) 2) (>= (get-column cell) 2)) 1)
((and (>= (get-row cell) 2) (< (get-column cell) 2)) 2)
(else 3)
)
)
;pre: takes a list containing row and column e.g. '(3 1) meaning row 3 column 1.
;post: returns a number that represents the quadrant the cell is in.
;why: to easily get the quadrant that the cell intersects with.
(define (quad-ref board cell)
(define quad (get-quad cell))
(cond
((= quad 0) (list (list-ref (list-ref board 0) 0)
(list-ref (list-ref board 0) 1)
(list-ref (list-ref board 1) 0)
(list-ref (list-ref board 1) 1)))
((= quad 1) (list (list-ref (list-ref board 0) 2)
(list-ref (list-ref board 0) 3)
(list-ref (list-ref board 1) 2)
(list-ref (list-ref board 1) 3)))
((= quad 2) (list (list-ref (list-ref board 2) 0)
(list-ref (list-ref board 2) 1)
(list-ref (list-ref board 3) 0)
(list-ref (list-ref board 3) 1)))
(else (list (list-ref (list-ref board 2) 2)
(list-ref (list-ref board 2) 3)
(list-ref (list-ref board 3) 2)
(list-ref (list-ref board 3) 3)))
)
)
;pre: it takes two lists that represents a board and a cell
;post: returns a list representation of the quadrant that intersects with the cell
;why: to easily find the non-candidates in that quadrant.
(define (column-ref board cell)
(list (list-ref (list-ref board 0) (get-column cell))
(list-ref (list-ref board 1) (get-column cell))
(list-ref (list-ref board 2) (get-column cell))
(list-ref (list-ref board 3) (get-column cell)))
)
;pre: it takes two lists that represents a board and a cell.
;post: returns the list representation of the column that intersects the cell.
;why: to easily find the non-candidates in that column.
(define (compare-to-numset LON)
(if (empty? LON)
'(1 2 3 4)
(remove (car LON) (compare-to-numset (cdr LON)))
)
)
;pre: it takes a list of non-candidates e.g. '(1 3 4)
;post: returns the list of candidates e.g '(2)
;why: the list of candidates will be used to test each cadidate in a cell.
(define (eliminate-duplicate lst)
(cond
((null? lst) '())
((member (car lst) (cdr lst)) (remove-duplicates (cdr lst)))
(else (cons (car lst) (remove-duplicates (cdr lst))))
)
)
;pre: it takes a list of numbers, lst
;post: returns the a list containing all number of lst with no repetition
;why: because the row, column, and quadrant that intersect with a cell, may have the same numbers. this will end with non candidates that repeat.
(define (clear-zero lst)
(cond
((empty? lst) '())
((= 0 (car lst)) (clear-zero (cdr lst)))
(else (cons (car lst) (clear-zero (cdr lst))))
)
)
;pre: takes a list of numbers, lst
;post: returns a list containing the numbers in lst, excluding zeros
;why: Zero is never a candidate so we do not need to check if it is.
(define (check-column board cell)
(clear-zero (column-ref board cell))
)
;pre: it takes two lists that are a board and a cell
;post: returns the non-candidates of that cell in the row that intersects with the cell
;why: eventually to find candidates by comparing the non-candidates with '(1 2 3 4)
(define (check-row board cell)
(clear-zero (row-ref board cell))
)
;pre: it takes two lists that are a board and a cell
;post: returns the non-candidates of that cell in the column that intersects with the cell
;why: eventually to find candidates by comparing the non-candidates with '(1 2 3 4)
(define (check-quad board cell)
(clear-zero (quad-ref board cell))
)
;pre: it takes two lists that are a board and a cell
;post: returns the non-candidates of that cell in the quadrant that intersects with the cell
;why: eventually to find candidates by comparing the non-candidates with '(1 2 3 4)
(define (get-candidates board cell)
(define LON (build-list (check-column board cell) (check-row board cell) (check-quad board cell)))
(define cleanLON (eliminate-duplicate LON))
(compare-to-numset cleanLON)
)
;pre: it takes two lists that are a board and a cell
;post: returns the possible candidates that can go into that cell
;why: to eventually test the candidates in that cell.
(define (update-board board cell item)
(list-set board (get-row cell)(list-set (list-ref board (get-row cell)) (get-column cell) item))
)
;pre: it takes two lists that are a board and a cell. it also takes a number
;post: returns a copy of the board with the number in the specified cell
;why: this is where we test the candidates. each time we update the board, we insert one of the candidates into the cell and move to the next cell.
(define (next cell)
(if (= (get-column cell) 3)
(list (+ 1 (get-row cell)) 0)
(list (get-row cell) (+ 1 (get-column cell)))
)
)
;pre: it takes a list that represnts cell as input.
;post: returns the next cell we will test. example '(0 0) will be followed with ('0 1) and '(0 3) followed by '(1 0).
;why: to easily move across the board.
(define (test-all candidates board cell);
(cond ((empty? candidates) (list #f board))
((car (ss (update-board board cell (car candidates)) (next cell))) (ss (update-board board cell (car candidates)) (next cell)))
(else (test-all (cdr candidates) board cell))))
;pre: takes a list of candidates, a board and a cell
;post: returns a list containing a boolean and a board e.g. '(#t board)
;if the list of candidates is empty it will return '(#f board)
;if one of the candidates leads to a solved board, then '(#t solved_board)
;why: to test each individual candidate. we recursively go through each candidate and check if that candidate was correct for the position
; if the candidate was correct for the position, then the board will ultimately be solved.
; if the candidate was put there incorrectly, then we simply test the next candidate.
; if we exhaust all candidates, then we simply return (#f board) the funciton that receives that, will test the next avialable candidate
; so on and so forth. until there is a solution.
(define (get-item board cell)
(list-ref (row-ref board cell) (get-column cell))
)
;pre: it takes two lists that represent a board and a cell.
;post: the function returns the number that currently in the cell.
;why? This function is used to help us find the empty cells in the board.
(define (ss board cell)
(cond
((= (get-row cell) 4) (list #t board))
((not (= 0 (get-item board cell))) (ss board (next cell)))
((empty? (get-candidates board cell)) (list #f board))
(else
(test-all (get-candidates board cell) board cell)
)
)
)
(define (solve board)
(cadr (ss board '(0 0)))
)
;precondition: this takes a two lists, the unsolved sudoku board and a cell that represents '(0,0).
;Whereas, the cell '(0,0) represents the beginning of the board.
;postcondition: this will return a list that represents a 4x4 sudoku board
(define (draw-board board)
(display (row-ref board '(0 0)))
(display "\n")
(display (row-ref board '(1 1)))
(display "\n")
(display (row-ref board '(2 2)))
(display "\n")
(display (row-ref board '(3 3)))
(display "\n")
)
(draw-board (cadr(ss board '(0 0))))
;pre: it takes a list within a list that represents the board
;post: it will display the sudoku board representation
;why? I created this function to draw the sudoku board correctly
(define solvedboards '(
(((3 0 0 1)
(1 0 0 0)
(0 0 0 0)
(0 0 2 0))
((3 2 4 1)
(1 4 3 2)
(2 3 1 4)
(4 1 2 3)));1
(((4 0 0 0)
(0 0 4 0)
(0 0 0 3)
(0 2 0 0))
((4 1 3 2)
(2 3 4 1)
(1 4 2 3)
(3 2 1 4)));2
(((0 0 1 0)
(3 0 0 0)
(0 3 0 0)
(0 0 0 4))
((2 4 1 3)
(3 1 4 2)
(4 3 2 1)
(1 2 3 4)));3
(((0 0 4 0)
(1 0 0 0)
(0 2 0 0)
(0 0 0 3))
((2 3 4 1)
(1 4 3 2)
(3 2 1 4)
(4 1 2 3)));4
(((0 0 4 0)
(1 0 0 0)
(0 2 0 0)
(0 0 0 3))
((2 3 4 1)
(1 4 3 2)
(3 2 1 4)
(4 1 2 3)));5
(((2 0 0 0)
(0 0 0 3)
(0 0 0 0)
(0 4 1 0))
((2 3 4 1)
(4 1 2 3)
(1 2 3 4)
(3 4 1 2)));6
(((0 0 1 0)
(0 4 0 0)
(2 0 0 0)
(0 0 0 1))
((3 2 1 4)
(1 4 3 2)
(2 1 4 3)
(4 3 2 1)));7
(((0 0 0 3)
(0 3 0 0)
(4 0 0 0)
(0 0 1 0))
((1 4 2 3)
(2 3 4 1)
(4 1 3 2)
(3 2 1 4)));8
(((0 2 0 0)
(0 0 2 0)
(0 0 0 3)
(4 0 0 0))
((1 2 3 4)
(3 4 2 1)
(2 1 4 3)
(4 3 1 2)));9
(((2 0 0 0)
(0 0 0 3)
(0 2 0 0)
(0 0 1 0))
((2 3 4 1)
(4 1 2 3)
(1 2 3 4)
(3 4 1 2)));10
(((0 4 0 0)
(0 0 0 2)
(0 0 0 0)
(0 0 2 3))
((2 4 3 1)
(1 3 4 2)
(3 2 1 4)
(4 1 2 3)));11
(((0 4 0 0)
(3 0 0 0)
(0 0 1 4)
(0 0 2 0))
((1 4 3 2)
(3 2 4 1)
(2 3 1 4)
(4 1 2 3)));12
(((0 0 0 3)
(0 0 0 4)
(3 0 0 0)
(2 0 0 0))
((4 2 1 3)
(1 3 2 4)
(3 1 4 2)
(2 4 3 1)));13
(((1 0 0 0)
(0 0 0 1)
(0 4 0 0)
(0 0 2 0))
((1 3 4 2)
(4 2 3 1)
(2 4 1 3)
(3 1 2 4)));14
(((0 0 0 0)
(4 3 0 2)
(2 0 0 4)
(0 0 0 0))
((1 2 4 3)
(4 3 1 2)
(2 1 3 4)
(3 4 2 1)));15
(((0 1 0 0)
(0 0 2 0)
(0 0 0 3)
(4 0 0 0))
((2 1 3 4)
(3 4 2 1)
(1 2 4 3)
(4 3 1 2)));16
(((0 2 0 1)
(0 0 2 0)
(4 1 0 0)
(0 0 0 0))
((3 2 4 1)
(1 4 2 3)
(4 1 3 2)
(2 3 1 4)));17
(((0 0 0 3)
(2 0 0 0)
(0 4 0 0)
(0 0 1 0))
((4 1 2 3)
(2 3 4 1)
(1 4 3 2)
(3 2 1 4)));18
(((0 0 2 0)
(1 0 0 0)
(0 4 0 0)
(0 0 0 3))
((4 3 2 1)
(1 2 3 4)
(3 4 1 2)
(2 1 4 3)));19
(((1 4 0 0)
(0 0 0 0)
(0 0 0 0)
(0 0 2 4))
((1 4 3 2)
(2 3 4 1)
(4 2 1 3)
(3 1 2 4)));20
);closing parenthesis
)
(define (test Sboards)
(if (empty? Sboards)
#t
(and (equal? (solve (car (car Sboards))) (car (cdr (car Sboards)))) (test (cdr Sboards)))
)
)
(test solvedboards)
;These are 20 cases that show that the algorithm works correctly. I used the url
;http://www.sudoku-download.net/files/60_Sudokus_4x4_Difficult.pdf to get boards that are solvable
;http://www.sudoku-download.net/files/Solution_60_Sudokus_4x4_Difficult.pdf to get the solutions of the 4x4 sudoku | false |
983ea15bee2c695878b4b65d9ab4df29c1aa4936 | f1e530da5c62986635c3a24ee2b7d5c0fc8cff5f | /utils.rkt | 7e5a8ee24dfecb84a79cc441db76a0ac7ba7bd8c | []
| no_license | david-vanderson/warp | 3172892fc2d19ae9e2f19fa026e2d7cdf4e59a86 | cdc1d0bd942780fb5360dc6a34a2a06cf9518408 | refs/heads/master | 2021-01-23T09:30:16.887310 | 2018-09-30T03:52:59 | 2018-09-30T03:52:59 | 20,066,539 | 24 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 15,463 | rkt | utils.rkt | #lang racket/base
(require racket/math
racket/port
racket/class
racket/list
racket/struct
ffi/unsafe
file/gzip
file/gunzip
racket/draw)
(require "defs.rkt"
"quadtree.rkt")
(provide (all-defined-out))
(define (points-in-region r sep frac)
(define-values (rx ry rw rh) (send r get-bounding-box))
(define sep/2 (/ sep 2.0))
(define ret '())
(for ((y (in-range ry (+ ry rh 1.0) sep/2))
(offset? (in-cycle (in-list '(#f #t)))))
(for ((x (in-range (+ rx (if offset? sep/2 0.0))
(- (+ rx rw 1.0) (if offset? 0.0 sep/2)) sep))
#:when (send r in-region? x y))
(define xd (random-between (* sep (- frac)) (* sep frac)))
(define yd (random-between (* sep (- frac)) (* sep frac)))
(define xx (min (max rx (+ x xd)) (+ rx rw)))
(define yy (min (max ry (+ y yd)) (+ ry rh)))
(set! ret (cons (cons xx yy) ret))))
ret)
(define (nebula-region r)
(for/list ((c (points-in-region r 1000.0 0.1)))
(define dr (* (if ((random) . < . 0.5) -1 1) (random-between 0.01 0.04)))
(define t (inexact->exact (round (random-between 0 100000))))
(make-nebula t (car c) (cdr c) 700.0 dr)))
(define (asteroid-region r f)
(define dd 10.0)
(for/list ((c (points-in-region r 800.0 0.25)))
(define diam (exp (exp (random-between (log (log 25.0)) (log (log 250.0))))))
(define dx (random-between (- dd) dd))
(define dy (random-between (- dd) dd))
(define dr (random-between -0.5 0.5))
(f diam (car c) (cdr c) dx dy dr)))
(define (mine-region r f)
(for/list ((c (points-in-region r 200.0 0.2)))
(f (car c) (cdr c))))
(define IPPROTO_TCP 6)
(define TCP_NODELAY 1)
(define setsockopt_tcp_nodelay
(get-ffi-obj "setsockopt" #f
(_fun (socket enabled?) ::
(socket : _int)
(_int = IPPROTO_TCP)
(_int = TCP_NODELAY)
(enabled-ptr : (_ptr i _int)
= (if enabled? 1 0))
(_int = (compiler-sizeof 'int))
-> (result : _int)
-> (if (zero? result)
(void)
(error 'set-tcp-nodelay! "failed")))))
(define scheme_get_port_socket
(get-ffi-obj "scheme_get_port_socket" #f
(_fun (port) ::
(port : _racket)
(socket : (_ptr o _intptr))
-> (result : _int)
-> (and (positive? result) socket))))
; set-tcp-nodelay! : tcp-port boolean -> void
(define (set-tcp-nodelay! port enabled?)
(let ([socket (scheme_get_port_socket port)])
(setsockopt_tcp_nodelay socket enabled?)))
(define (serialize v)
(define ob (open-output-bytes))
(write v ob)
(define obo (get-output-bytes ob))
(cond
(COMPRESS
(define ib (open-input-bytes obo))
(define ob2 (open-output-bytes))
(deflate ib ob2)
(get-output-bytes ob2))
(else
obo)))
(define (make-in-thread id in-port th)
(define-values (pin pout) (make-pipe))
(thread
(lambda ()
(let loop ()
; read from in-port
(define v
(with-handlers ((exn:fail? (lambda (exn) #f)))
(cond
(COMPRESS
(inflate in-port pout)
(read pin))
(else
(read in-port)))))
(cond
((and v (not (eof-object? v)))
; send to client/server thread
(thread-send th (cons id v))
(loop))
(else
(thread-send th (cons id #f))
;(printf "in-thread ~a stopping\n" id)
(sync never-evt)))))))
(define (make-out-thread id out-port th)
(thread
(lambda ()
(let loop ()
; get next thing from the client/server thread
(define v (thread-receive))
; send it out
(define ret
(with-handlers ((exn:fail? (lambda (exn) #f)))
(cond
((bytes? v)
(write-bytes v out-port))
(else
(write v out-port)))
(flush-output out-port)))
(cond
((void? ret)
(loop))
(else
(thread-send th (cons id #f))
;(printf "out-thread ~a stopping\n" id)
(sync never-evt)))))))
(define-syntax-rule (timeit var e ...)
(begin
(define t (current-milliseconds))
e ...
(set! var (- (current-milliseconds) t))))
(define-syntax-rule (outputtime who time v ...)
(begin
(when (v . > . 1)
(printf "~a : ~a ~a ~a\n" time who 'v v)) ...))
(define (standard-quit-scenario-button [tab? #t] [faction #t])
(make-ann-button 68 76 120 40 "Quit Scenario" "quit-scenario"
#:pos 'topleft #:tab? tab? #:faction faction))
(define-syntax-rule (append! lst e ...)
(set! lst (append lst (flatten (list e ...)))))
(define-syntax-rule (prepend! lst e ...)
(set! lst (append (flatten (list e ...)) lst)))
(define (remove-id id list)
(filter (lambda (o) (not (equal? (ob-id o) id)))
list))
(define (findfid id list)
(findf (lambda (o) (equal? id (ob-id o))) list))
(define (copy s [new-ids? #f])
(cond
((struct? s)
(define ns
(apply make-prefab-struct (prefab-struct-key s) (map copy (struct->list s))))
(when (and new-ids? (ob? ns))
(set-ob-id! ns (next-id)))
ns)
((cons? s)
(cons (copy (car s)) (copy (cdr s))))
((list? s)
(map copy s))
((or (number? s)
(boolean? s)
(string? s)
(symbol? s))
s)
(else
(error "copy unknown datatype:\n" s))))
(define (load-bitmap name)
(read-bitmap (string-append "images/" name ".png")))
(define (obj-age space o)
(- (space-time space) (obj-start-time o)))
; should only be used for things called every TICK
(define (time-for age repeat (offset 0))
(<= (+ 1 offset) (modulo age repeat) (+ offset TICK)))
(define (time-toggle age repeat (div 2.0) (offset 0))
(<= (modulo (+ age offset) repeat) (/ repeat div)))
(define (faction-check my-faction other-faction)
(cond ((equal? my-faction other-faction) 1)
((or (equal? "_neutral" my-faction)
(equal? "_neutral" other-faction)) 0)
(else -1)))
(define (strategy-age space s)
(- (space-time space) (strategy-t s)))
(define (current-strat-age space ship)
(- (space-time space) (ship-ai-strat-time ship)))
; age, life, death are ms since object start time
(define (linear-fade age life death)
(cond ((age . <= . life) 1.0)
((age . > . death) 0.0)
(else (/ (exact->inexact (- death age))
(- death life)))))
(define (clamp zmin zmax z)
(max zmin (min zmax z)))
(define (remain a b)
(define z (/ a b))
(* b (- z (floor z))))
; returns triangle wave from 1-0-1 over cycletime
(define (cycletri age cycletime)
(define a (/ (remain age cycletime) cycletime)) ; goes 0-1,0-1
(abs (* 2.0 (- a 0.5)))) ; goes 1-0-1
; calculates partial sum of geometric series
; a is first term
; r is ratio
; n is number of terms in the sum
(define (geom-sum a r n)
(* a (/ (- 1 (expt r n))
(- 1 r))))
(define (sigmoid x div)
(- (/ 2.0 (+ 1.0 (exp (- (/ x div))))) 1.0))
(define-syntax-rule (define/time (name arg ...) e ...)
(define (name arg ...)
(define start (current-milliseconds))
(define ret (let () e ...))
(printf "~a ~a\n" (object-name name) (- (current-milliseconds) start))
ret))
(define-syntax-rule (with-time name e ...)
(begin
(define start (current-milliseconds))
(define ret (let () e ...))
(printf "~a ~a\n" name (- (current-milliseconds) start))
ret))
(define-syntax-rule (while test e ...)
(let loop ()
(when test
e ...
(loop))))
; returns a list of stacks of all objects from ownspace
; to the object with the given id (found object first)
(define (search space o id (multiple? #f) (subships? #t))
(define search-return '()) ; found stacks
(let/ec esc
(let search-internal ((o o) (stack '()))
(when (and (not (space? o))
(or (and (number? id) (= id (ob-id o)))
(and (procedure? id) (id o))))
(set! search-return (cons (cons o stack) search-return))
(when (not multiple?) (esc)))
(cond
((or (player? o)
(plasma? o)
(explosion? o)
(nebula? o)
(missile? o)
(shield? o)
(effect? o)
(message? o)
(upgrade? o)
(ann? o)
(dmg? o))
(void))
((space? o)
(for ((x (in-list (space-objects o)))
#:when (obj-alive? x))
(search-internal x (cons o stack))))
((ship? o)
(for ((x (in-list (ship-tools o))))
(search-internal x (cons o stack)))
(for ((x (in-list (ship-players space o))))
(search-internal x (cons o stack)))
(for ((x (in-list (ship-cargo o))))
(search-internal x (cons o stack)))
(when (and subships? (ship-hangar o))
(for ((x (in-list (ship-hangar o))))
(search-internal x (cons o stack)))))
((tool? o)
(for ((x (in-list (tool-dmgs o))))
(search-internal x (cons o stack))))
(else
(error 'search-internal "hit ELSE clause for ~v" o)))))
search-return)
(define (find-all space o id)
(map car (search space o id #t)))
(define (find-stack space o id (subships? #t))
(define r (if id (search space o id #f subships?) null))
(if (null? r) #f (car r)))
(define (find-id space o id (subships? #t))
(define r (find-stack space o id subships?))
(if r (car r) #f))
(define (find-top-id space id)
(for/first ((o (in-list (space-objects space))) #:when (= (ob-id o) id)) o))
(define (find-top-containing-id space id)
(for/first ((o (in-list (space-objects space)))
#:when (find-id space o id))
o))
(define (ship-flying? ship)
(obj-posvel ship))
(define (get-ship stack)
(findf ship? stack))
(define (get-ships stack)
(filter ship? stack))
(define (get-topship stack)
(get-ship (reverse stack)))
(define (ship-ships s)
(define h (ship-hangar s))
(if h h '()))
(define (get-space stack)
(car (reverse stack)))
(define (ai-ship? o)
(and (ship? o)
(or (equal? (ship-ai o) 'always)
(and (equal? (ship-ai o) 'empty)
(null? (ship-playerids o))))))
(define (can-launch? stack)
(define ships (get-ships stack))
(and (not (ship-flying? (car ships)))
(not (null? (cdr ships)))
(ship-flying? (cadr ships))))
(define (ship-tool ship sym)
(findf (lambda (t) (equal? sym (tool-name t))) (ship-tools ship)))
(define (player-using-tool? p t)
(findf (lambda (c)
(equal? c (tool-name t)))
(player-commands p)))
(define (tool-count space t ship)
(cond
((not t) 0)
((empty? (ship-playerids ship))
(if (tool-rc t) 1 0))
(else
(define c
(count (lambda (p) (player-using-tool? p t))
(ship-players space ship)))
(if (equal? 'always (ship-ai ship))
(+ c (if (tool-rc t) 1 0))
c))))
(define (tool-online? t (dmgtype "offline"))
(not (findf (lambda (d) (equal? dmgtype (dmg-type d))) (tool-dmgs t))))
(define (will-dock? s1 s2)
(define d (ship-tool s1 'dock))
(and d
(tool-rc d)
((faction-check (ship-faction s2) (ship-faction s1)) . > . 0)
(ship-hangar s2)))
(define (angle-norm r)
(while (r . >= . 2pi) (set! r (- r 2pi)))
(while (r . < . 0) (set! r (+ r 2pi)))
r)
(define (angle-add r theta)
(angle-norm (+ r theta)))
; gives angular distance and direction (-pi to pi)
(define (angle-frto from to)
(define diff (- to from))
(cond (((abs diff) . <= . pi) diff)
((diff . > . pi) (- diff 2pi))
(else (+ 2pi diff))))
(define (random-between a b)
(+ a (* (- b a) (random))))
(define (hit? a b d)
((distance2 a b) . < . (* d d)))
(define (distance2 a b)
(define dx (- (obj-x a) (obj-x b)))
(define dy (- (obj-y a) (obj-y b)))
(+ (* dx dx) (* dy dy)))
(define (distance a b)
(sqrt (distance2 a b)))
(define (dist-polar2 r1 t1 r2 t2)
(+ (* r1 r1) (* r2 r2)
(- (* 2 r1 r2 (cos (- t2 t1))))))
(define (dist-polar r1 t1 r2 t2)
(sqrt (dist-polar2 r1 t1 r2 t2)))
(define (atan0 y x)
(if (= 0.0 x y) 0.0 (atan y x)))
(define (theta from to)
(define dx (- (obj-x to) (obj-x from)))
(define dy (- (obj-y to) (obj-y from)))
;(printf "dx ~a, dy ~a\n" dx dy)
(atan0 dy dx))
(define (dtheta o)
(define dx (posvel-dx (obj-posvel o)))
(define dy (posvel-dy (obj-posvel o)))
(atan0 dy dx))
(define (dmag o)
(define pv (obj-posvel o))
(sqrt (+ (* (posvel-dx pv) (posvel-dx pv))
(* (posvel-dy pv) (posvel-dy pv)))))
(define (hit-distance ship1 ship2)
(+ (ship-radius ship1)
(ship-radius ship2)))
;; ai utils
(define (nearest-enemy qt ownship filterf?)
(define ne #f)
(define ne-dist #f)
(for ((e (in-list (qt-retrieve qt (obj-x ownship) (obj-y ownship) (ship-radar ownship))))
#:when (and (filterf? e)
((faction-check (ship-faction ownship) (ship-faction e)) . < . 0)))
(define d (distance2 ownship e))
(when (or (not ne) (d . < . ne-dist))
(set! ne e)
(set! ne-dist d)))
ne)
(define (ship-behind? qt ship)
(define max-dist 50.0)
(define max-ang pi/2)
(define ns #f)
(for ((o (in-list (qt-retrieve qt (obj-x ship) (obj-y ship) (+ (ship-radius ship) max-dist))))
#:when (and (spaceship? o)
(not (= (ob-id ship) (ob-id o)))))
(define a (angle-frto (angle-add pi (posvel-r (obj-posvel ship))) (theta ship o)))
(when ((abs a) . < . max-ang)
(set! ns o)))
ns)
(define (target-angle source-pos source-vel target-pos target-vel shot-speed shot-life-secs)
; relative velocity
(define vx (- (if target-vel (posvel-dx (obj-posvel target-vel)) 0)
(if source-vel (posvel-dx (obj-posvel source-vel)) 0)))
(define vy (- (if target-vel (posvel-dy (obj-posvel target-vel)) 0)
(if source-vel (posvel-dy (obj-posvel source-vel)) 0)))
(define st-r (theta source-pos target-pos))
(define t #f)
(cond
((= 0 vy vx)
; nobody's moving, so shoot directly at them
(set! t st-r))
(else
; use law of sines
; v-l and shot-speed are the lengths of the sides
(define v-l (sqrt (+ (* vx vx) (* vy vy))))
; this is angle opposite shot-speed
; between side connecting ships and enemy velocity
(define v-r (atan vy vx))
; should be sin(pi - x) but that's equal to sin(x)
(define rel-angle (angle-frto v-r st-r))
(define sin-aim (* (sin rel-angle)
(/ v-l shot-speed)))
(when (<= -1 sin-aim 1)
(define maybe-t (angle-add st-r (- (asin sin-aim))))
; answer could be going backwards in time
(define secs #f)
(define dx (- (* shot-speed (cos maybe-t)) vx))
(cond
((not (= dx 0))
(set! secs (/ (- (obj-x target-pos) (obj-x source-pos)) dx)))
(else
(define dy (- (* shot-speed (sin maybe-t)) vy))
(when (not (= dy 0))
(set! secs (/ (- (obj-y target-pos) (obj-y source-pos)) dy)))))
(when (and secs (< 0 secs shot-life-secs))
(set! t maybe-t)))))
t)
| true |
eade0dbad1bdd57812765d896d06ad3e1a1f18be | 602770a7b429ffdae579329a07a5351bb3858e7a | /data-test/tests/data/enumerate/util.rkt | 3838c98fe38b5ea345918d79b2139acdccf94acf | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | racket/data | 42c9a905dc9ce8716faf39698c5efbc0a95f1fbe | 0b23dd66639ffd1d62cf690c26cbd58b508da609 | refs/heads/master | 2023-08-17T06:57:08.477218 | 2023-06-08T18:09:32 | 2023-06-08T19:34:18 | 27,431,296 | 15 | 23 | NOASSERTION | 2023-06-08T19:34:20 | 2014-12-02T12:21:39 | Racket | UTF-8 | Racket | false | false | 2,380 | rkt | util.rkt | #lang racket/base
(require data/enumerate
rackunit
(for-syntax racket/base)
racket/contract)
(provide check-bijection? check-bijection/just-a-few?
check-contract)
(define (do-check-bijection e confidence)
(for/and ([n (in-range (if (finite-enum? e)
(min (enum-count e) confidence)
confidence))])
(= n (to-nat e (from-nat e n)))))
(define-simple-check (check-bijection? e)
(do-check-bijection e 1000))
(define-simple-check (check-bijection/just-a-few? e)
(do-check-bijection e 100))
(define-syntax (check-contract stx)
(syntax-case stx ()
[(_ e)
(with-syntax ([line (syntax-line stx)])
(syntax/loc stx (check-contract/proc line e 'e)))]))
(define (check-contract/proc line enum enum-code)
(for ([x (in-range (if (finite-enum? enum)
(min (enum-count enum) 100)
100))])
(with-handlers ([exn:fail?
(λ (exn)
(printf "exn exercising when x=~a\n" x)
(raise exn))])
(contract-exercise
(contract (enum-contract enum)
(from-nat enum x)
'ignore-me
'whatever
(format "~s, index ~a" enum-code x)
#f))))
(when (two-way-enum? enum)
(let/ec give-up-completely
(for ([x (in-range 100)])
(with-handlers ([exn:fail?
(λ (exn)
(printf "exn generating when x=~a\n" x)
(raise exn))])
(let/ec give-up-this-attempt
(define value
(contract-random-generate
(enum-contract enum)
2
(λ (no-generator?)
(cond
[no-generator?
(eprintf "no generator for:\n ~s\n ~s\n"
enum-code
(enum-contract enum))
(give-up-completely (void))]
[else
(give-up-this-attempt)]))))
(with-handlers ([exn:fail?
(λ (x)
(eprintf "test/data/enumerate: trying ~s\n" value)
(raise x))])
(to-nat enum value))))))))
| true |
786b7bca4e225f8a46dc213188a2956a5525c702 | 71060ffeffa3469ec44ba661b04118b487fc0602 | /ex_2_45.rkt | e3a567cc4165328cdbe5e051aac3f48ead48b83f | []
| no_license | ackinc/sicp | 18741d3ffc46041ecd08021d57a50702be2e0f92 | 4ee2250f8b7454fb88bc27edb41a1349d7a3016c | refs/heads/master | 2021-09-13T08:55:37.171840 | 2018-04-27T10:02:08 | 2018-04-27T10:02:08 | 114,095,803 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 206 | rkt | ex_2_45.rkt | #lang racket
(define (split tr1 tr2)
(define (helper painter n)
(if (= n 0)
painter
(let ((smaller (helper painter (- n 1))))
(tr1 painter (tr2 smaller smaller)))))
helper) | false |
39c0c53a8b2771d88f955255c72ace247dfcbbce | 82c76c05fc8ca096f2744a7423d411561b25d9bd | /typed-racket-test/succeed/with-asserts.rkt | c6dc9b3210bb9f9ca9574b8a88f2b95dcc3526c7 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | racket/typed-racket | 2cde60da289399d74e945b8f86fbda662520e1ef | f3e42b3aba6ef84b01fc25d0a9ef48cd9d16a554 | refs/heads/master | 2023-09-01T23:26:03.765739 | 2023-08-09T01:22:36 | 2023-08-09T01:22:36 | 27,412,259 | 571 | 131 | NOASSERTION | 2023-08-09T01:22:41 | 2014-12-02T03:00:29 | Racket | UTF-8 | Racket | false | false | 409 | rkt | with-asserts.rkt | #lang typed/racket
(let ([x 1] [y "2"])
(with-asserts ([x integer?] [y string?])
x))
(let ([x 1] [y "2"])
(with-asserts ([x integer?])
x))
(let ([x 1] [y "2"])
(with-asserts ()
x))
(let ([x 1] [y "2"])
(with-asserts ([x])
x))
(: f : (U Integer String) -> Integer)
(define (f x)
(with-asserts ([x integer?])
x))
(f 1)
| false |
6803f8fbe7072cc7c1278c315c78a2932a88a4fb | 3ac344d1cac4caa5eb4842bc0e4d61b1ae7030fb | /parser.rkt | e88662f79be0b3faf63fa455a013ca62c30f466e | [
"ISC"
]
| permissive | vicampo/riposte | 0c2f2a8459a2c6eee43f6f8a83f329eb9741e3fc | 73ae0b0086d3e8a8d38df095533d9f0a8ea6b31b | refs/heads/master | 2021-10-29T11:18:14.745047 | 2021-10-13T10:20:33 | 2021-10-13T10:20:33 | 151,718,283 | 42 | 5 | ISC | 2019-03-26T12:20:23 | 2018-10-05T12:35:49 | Racket | UTF-8 | Racket | false | false | 1,368 | rkt | parser.rkt | #lang racket/base
(provide is-well-formed?
parse-file)
(require racket/contract
syntax/stx
(only-in (file "./tokenizer.rkt")
tokenize)
(only-in (file "./grammar.rkt")
parse))
(define (is-well-formed? path)
(define-values (dir base is-directory?)
(split-path path))
(define (parse-it)
(syntax->datum
(parse path (tokenize (current-input-port)))))
(cond [(file-exists? path)
(with-handlers ([exn:fail? (lambda (e) #f)])
(begin0
(with-input-from-file path parse-it #:mode 'text)
#t))]
[else #f]))
(define/contract (parse-file path)
(path? . -> . list?)
(define-values (dir base is-directory?)
(split-path path))
(when is-directory?
(error (format "Cannot parse directories: ~a" (path->string path))))
(with-input-from-file path
(lambda ()
(syntax->datum
(parse path (tokenize (current-input-port)))))
#:mode 'text))
(module+ main
(require racket/cmdline
racket/pretty)
(define file-to-process
(command-line
#:args (filename)
filename))
(unless (file-exists? file-to-process)
(displayln (format "No such file: ~a" file-to-process)
(current-error-port))
(exit 1))
(pretty-print (parse-file (string->path file-to-process))))
| false |
beadc466a7b58025d0041d62fd585b8a41ee3665 | c54e3384ab0461c7b6552d52676b48159d59628b | /rsh.rkt | 40b6c3f30d191d8c7e57eaf6da804460cda01ffb | []
| no_license | paddymahoney/pracket | 89fcef14b185ad6a2d3c2126d4147ac4fa8d7d97 | 957ac4b765eac3c01ad164e28881129b853d3bcb | refs/heads/master | 2020-12-24T13:44:32.936283 | 2013-02-20T00:28:39 | 2013-02-20T00:28:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 751 | rkt | rsh.rkt | #lang racket
(require racket/file
"user.rkt")
(require (for-syntax syntax/parse))
(provide home-dir cd cwd pwd chdir mkdir make-dir with-cwd with-cwd* create-temp-file
(all-from-out "user.rkt"))
(define create-temp-file make-temporary-file)
(define (home-dir)
(find-system-path 'home-dir))
(define cwd current-directory)
(define pwd current-directory)
(define (chdir path)
(current-directory path))
(define cd chdir)
(define mkdir make-directory)
(define make-dir make-directory)
(define (with-cwd* path thunk)
(parameterize ([current-directory path])
(thunk)))
(define-syntax (with-cwd sntx)
(syntax-parse sntx
[(with-cwd path body ...)
#'(with-cwd* path
(lambda () body ...))]))
| true |
980de78c0e5addbf2d14becbaf374f572bd6d4c9 | af21b2d0c81fbbd228666268b112239d7a022a78 | /experiments/drawable-recompute.rkt | 664ce17e995eaea801624292dcbbb2348bdb2a0b | []
| no_license | GlimmerLabs/gigls | a4e0f528d2a04107031529f323c7768cb3d9e39d | 5116033d8acb30f201d1a0b27ef9fc88cc6fb136 | refs/heads/master | 2016-09-15T04:54:48.047038 | 2015-09-10T02:42:38 | 2015-09-10T02:42:38 | 10,534,146 | 2 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 303 | rkt | drawable-recompute.rkt | #lang racket
; experiments/drawable-recompute.rkt
; An experiment in how drawable-recompute! works. Assumes that
; (1)tThe Gimp DBus server is running ; (2) image 1 with drawable
; 2 is open
(require gigls/tile)
(require gigls/irgb)
(_drawable-recompute! 1 2 (lambda (x y) (irgb-new x 0 y)))
| false |
9319b34033e32dd34520a3318080bdf52ac7452d | 55adde930288ff73186a4d4dbe3f1e746ddcd102 | /mathbook/lang.rkt | 2599d7cb138afdaaec761ad361157a6ae49aa80a | []
| no_license | sorawee/mathbook | dce8a7f290a22bf9211424e738649252b52c9553 | ad9eb1eef96e1ae92ed3e14481100df267fd5435 | refs/heads/master | 2021-01-20T08:20:00.154620 | 2016-05-27T12:41:35 | 2016-05-27T12:41:35 | 59,419,673 | 0 | 0 | null | 2016-05-22T15:31:49 | 2016-05-22T15:31:48 | null | UTF-8 | Racket | false | false | 859 | rkt | lang.rkt | #lang racket/base
;;; This exports of this file define the available constructs in the #lang mathbook language.
(require scribble/base
scribble/doclang
scribble/manual
"mathbook.rkt"
scribble/html-properties
"mathbook-defaults.rkt"
"mathjax.rkt")
(provide (all-from-out scribble/base)
(except-out (all-from-out scribble/doclang) #%module-begin)
(all-from-out "mathbook.rkt" "mathjax.rkt")
; (all-from-out scribble/manual)
(rename-out [module-begin #%module-begin])
mathjax-source
; manual-doc-style
;;; From scribble/manual :
indexed-racket
codeblock codeblock0 code
racket
itemize
)
(define-syntax-rule (module-begin id . body)
(#%module-begin id post-process () #;use-mathjax-cdn . body))
| true |
31f6b3567a044e67c7175591dd6ca7bc109bb6ac | e6f2b3789ab68edc8c36316376af0b61610c2b5e | /kernel-revisited.rkt | efb38f5573ccb770f43055f10a7df7d9089be4b3 | []
| no_license | pedrodelgallego/scarecrow | cfa00f9e07997aa52955c5bfe6eabfb423c631c5 | b8205130b4d05c29a27fc2c54ee21574c1854928 | refs/heads/master | 2016-09-06T09:27:28.169124 | 2011-01-13T00:15:23 | 2011-01-13T00:15:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 6,008 | rkt | kernel-revisited.rkt | #lang racket/base
(require racket/match)
;; ----------------------------------- Evaluator.
(define (eval expr env)
;; (display "evaluating ") (display expr) (newline)
(match expr
[`__environment__ env]
[(? boolean?) (evaluator 'literal expr)]
[(? string?) (evaluator 'literal expr)]
[(? number?) (evaluator 'literal expr)]
[(? symbol?) (evaluator 'symbol env expr)]
[`(set! ,key ,value) (evaluator 'set! key value)]
[`(define (,name . ,bindings) ,function) (evaluator 'define name expr )]
[`(define ,name ,value) (evaluator 'set! name value)]
[`(if ,ec ,et ,ef) (evaluator 'if env ec et ef)]
[`(let ,bindings ,body) (evaluator 'let env bindings body)]
[`(lambda ,bindings ,body) (evaluator 'lambda env expr )]
[`(begin . ,expr) (evaluator 'begin env expr)]
[`(,f . ,args) (evaluator 'apply-proc env
(eval f env)
(map ((evaluator 'evlis) env) args)) ]
[_ error "Unknown expression type -- EVAL" expr] ))
;; ----------------------------------- Evaluation
(define (Evaluator)
(define (evlis env) (lambda (exp) (eval exp env)))
(define (*literal* expr) expr)
(define (*symbol* env expr) ((Env 'look-up) expr env) )
(define (*set!* key value) ((Env 'set!) key value))
(define (*define* name expr) ((Env 'set!) name (list 'closure expr)))
(define (*if* env ec et ef) (if (eval ec env) (eval et env) (eval ef env)))
(define (*lambda* env expr) (list 'closure expr env))
(define (*begin* env expr) (last (map ((evaluator 'evlis) env) expr)))
(define (*let* env bindings body) (eval body ((Env 'extended-env*) env
(map car bindings)
(map ((evaluator 'evlis) env) (map cadr bindings)))))
(define (apply-proc env f values)
(match f
[`(closure (lambda ,vs ,body) ,env)
(eval body ((Env 'extended-env*) env vs values))]
[`(closure (define (,name . ,vs) ,body) )
(eval body ((Env 'extended-env*) env.global vs values))]
[_ (f values)] ))
(lambda (method . args)
(case method
[(literal) (apply *literal* args)]
[(symbol) (apply *symbol* args)]
[(set!) (apply *set!* args)]
[(define) (apply *define* args)]
[(if) (apply *if* args)]
[(lambda) (apply *lambda* args)]
[(begin) (apply *begin* args)]
[(let) (apply *let* args)]
[(evlis) evlis]
[(apply-proc) (apply apply-proc args) ] )))
(define evaluator (Evaluator))
;; ----------------------------------- Environment
(define-struct box ([value #:mutable]))
(define env.global (make-immutable-hash '()))
(define Env
(lambda(method)
(case method
[(set) (lambda (env key value) (hash-set env key value))]
[(set!) (lambda (key value) (set-box-value! (hash-ref env.global key) value))]
[(look-up) (lambda (expr env) (box-value (hash-ref env expr)))]
[(extended-env*) (lambda (env vars values)
(match `(,vars ,values)
[`((,v . ,vars) (,val . ,values))
((Env 'extended-env*) ((Env 'set) env v (make-box val)) vars values)]
[`(() ()) env] ))] )))
;; ----------------------------------- Primitives
(define-syntax definitial
(syntax-rules ()
[(definitial name)
(set! env.global ((Env 'set) env.global name (make-box null))) ]
[(definitial name value)
(set! env.global ((Env 'set) env.global name (make-box value))) ]))
(define-syntax-rule (defprimitive name value arity)
(definitial name
(lambda (values)
(if (= arity (length values))
(apply value values)
(error "Incorrect arity"
(list 'name values))))))
(define-syntax-rule (defpredicate name value arity)
(defprimitive name
(lambda values (or (apply value values) #f))
arity ) )
(define (last lst)
(if (pair? lst)
(if (pair? (cdr lst))
(last (cdr lst))
(car lst))
(error "parameter should be a non empty list")))
;; -----------------------------------
(define (eval-program program)
(evaluate (cons 'begin program)))
(define (evaluate program)
(if (list? program)
(map define->bindings program)
'())
(eval program env.global))
(define (define->bindings definitions)
(match definitions
[`(define (,name . ,bindings ) ,body) (definitial name)]
[`(define ,name ,value) (definitial name)]
[_ '()]))
(definitial #t #t)
(definitial #f #t)
(definitial 'nil '())
(defprimitive 'cons cons 2)
(defprimitive 'car car 1)
(defprimitive 'cdr cdr 1)
(defpredicate 'pair? pair? 1)
(defpredicate 'boolean? boolean? 1)
(defpredicate 'symbol? symbol? 1)
(defpredicate 'procedure? procedure? 1)
(defprimitive 'eq? eq? 2)
(defpredicate 'eq? eq? 2)
(defprimitive '+ + 2)
(defprimitive '- - 2)
(defpredicate '= = 2)
(defpredicate '> > 2)
(defpredicate '< < 2)
(defprimitive '* * 2)
(defpredicate '<= <= 2)
(defpredicate '>= >= 2)
(defprimitive 'remainder remainder 2)
(defprimitive 'display display 1)
;; (module-path-index-resolve (car (identifier-binding #'define-syntax-rule)))
(provide evaluate env.global eval-program) | true |
4cb1a4fb0d9e9e3eddcce673cfe0ca1a86c710c6 | 38bc0fc604c69927021ce4b619e42d8219e1214f | /default-recommendations/miscellaneous-suggestions.rkt | 0f0c1436ab1c19fb12859fae39a013f7658b7528 | [
"Apache-2.0"
]
| permissive | DavidAlphaFox/resyntax | 4f4d18367a98e4b535e5a7b10563368ecbb5309d | 0c957be4eb2cd17601dee90fe4dd4d748de73ef5 | refs/heads/master | 2023-07-01T01:27:18.922334 | 2021-07-02T01:29:10 | 2021-07-02T01:29:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 3,209 | rkt | miscellaneous-suggestions.rkt | #lang racket/base
(require racket/contract/base)
(provide
(contract-out
[miscellaneous-suggestions refactoring-suite?]))
(require (for-syntax racket/base)
racket/match
rebellion/private/static-name
resyntax/refactoring-rule
resyntax/refactoring-suite
resyntax/syntax-replacement
syntax/parse)
;@----------------------------------------------------------------------------------------------------
(define if-begin-to-cond-message
"The cond form supports multiple body expressions in each branch, making begin unnecessary.")
(define-refactoring-rule if-then-begin-to-cond
#:description if-begin-to-cond-message
#:literals (if begin)
[(if condition (begin then-body ...) else-branch)
(cond
NEWLINE [condition (~@ NEWLINE then-body) ...]
NEWLINE [else NEWLINE else-branch])])
(define-refactoring-rule if-else-begin-to-cond
#:description if-begin-to-cond-message
#:literals (if begin)
[(if condition then-branch (begin else-body ...))
(cond
NEWLINE [condition NEWLINE then-branch]
NEWLINE [else (~@ NEWLINE else-body) ...])])
(define-refactoring-rule if-else-cond-to-cond
#:description if-begin-to-cond-message
#:literals (if cond)
[(if condition then-branch (cond clause ...))
(cond
NEWLINE [condition NEWLINE then-branch]
(~@ NEWLINE clause) ...)])
(define-refactoring-rule cond-else-if-to-cond
#:description "The else if branch of this cond expression can be collapsed into the cond\
expression."
#:literals (cond else if)
[(cond clause ... [else (if inner-condition inner-then-branch else-branch)])
(cond
(~@ NEWLINE clause) ...
NEWLINE [inner-condition NEWLINE inner-then-branch]
NEWLINE [else NEWLINE else-branch])])
(define-refactoring-rule cond-begin-to-cond
#:description "The bodies of cond clauses are already implicitly wrapped in begin."
#:literals (cond begin)
[(cond clause-before ...
[condition (begin body ...)]
clause-after ...)
(cond
(~@ NEWLINE clause-before) ...
NEWLINE [condition (~@ NEWLINE body) ...]
(~@ NEWLINE clause-after) ...)])
(define-refactoring-rule or-cond-to-cond
#:description "This or expression can be turned into a clause of the inner cond expression,\
reducing nesting."
#:literals (or cond)
[(or condition (cond clause ...))
(cond
NEWLINE [condition #t]
(~@ NEWLINE clause) ...)])
(define-refactoring-rule and-match-to-match
#:description "This and expression can be turned into a clause of the inner match expression,\
reducing nesting."
#:literals (and match)
[(and and-subject:id (match match-subject:id match-clause ...))
#:when (free-identifier=? #'and-subject #'match-subject)
(match match-subject
NEWLINE [#false #false]
(~@ NEWLINE match-clause) ...)])
(define miscellaneous-suggestions
(refactoring-suite
#:name (name miscellaneous-suggestions)
#:rules (list and-match-to-match
cond-begin-to-cond
cond-else-if-to-cond
if-then-begin-to-cond
if-else-begin-to-cond
if-else-cond-to-cond
or-cond-to-cond)))
| false |
ba775410a225aa8cd7183cd0014d5dc1dda7e164 | 19829daee6f77e93e6628ee48d42a3d2a33b78da | /src/bagpipe/racket/main/network/announcement.rkt | 5f48aaa53d2bdccdf250c2a575ba1268a0c4ddc5 | [
"MIT"
]
| permissive | konne88/bagpipe | 309a1be03412078d14bade4d56e828122dced70e | 9338220fe1fec2e7196e1143c92065ce5d5a7b46 | refs/heads/master | 2020-04-06T06:49:15.911149 | 2016-07-03T23:26:10 | 2016-07-03T23:26:10 | 35,004,324 | 33 | 3 | null | null | null | null | UTF-8 | Racket | false | false | 3,436 | rkt | announcement.rkt | #lang s-exp rosette
(require "../util/util.rkt")
(require "ip.rkt")
(require "prefix.rkt")
(provide default-announcement announcement?
announcement-prefix announcement-prefix-set
announcement-community-test announcement-community-set
announcement-aspath-test announcement-aspath-set
announcement-pref announcement-pref-set
environment environment-merge
count-aspaths count-communities
environment-aspaths environment-communities
symbolic-announcement)
(define (announcement communities prefix aspath pref)
`(Announcement ,communities ,prefix ,aspath ,pref))
(define (announcement? a) (and (pair? a) (eq? (first a) 'Announcement)))
(define (announcement-communities a) (second a))
(define (announcement-prefix a) (third a))
(define (announcement-aspath a) (fourth a))
(define (announcement-pref a) (fifth a))
(define (announcement-aspath-set a p b)
(announcement (announcement-communities a)
(announcement-prefix a)
(subset-set (announcement-aspath a) p b)
(announcement-pref a)))
(define (announcement-aspath-test a p)
(subset-ref (announcement-aspath a) p))
(define (announcement-community-set a c b)
(announcement (subset-set (announcement-communities a) c b)
(announcement-prefix a)
(announcement-aspath a)
(announcement-pref a)))
(define (announcement-community-test a c)
(subset-ref (announcement-communities a) c))
(define (announcement-prefix-set a prefix)
(announcement (announcement-communities a)
prefix
(announcement-aspath a)
(announcement-pref a)))
(define (announcement-pref-set a pref)
(announcement (announcement-communities a)
(announcement-prefix a)
(announcement-aspath a)
pref))
(define (environment communities aspaths) `(Environment ,communities ,aspaths))
(define (environment? c) (and (pair? c) (eq? 'Environment (first c))))
(define (environment-communities c) (second c))
(define (environment-aspaths c) (third c))
(define (count-communities env)
(length (environment-communities env)))
(define (count-aspaths env)
(length (environment-aspaths env)))
(define (environment-merge es)
(environment (remove-duplicates (flatten (map environment-communities es)))
(remove-duplicates (flatten (map environment-aspaths es)))))
; TODO representing communities and aspaths as sets of juniper community/aspaths
; is potentially unsafe. For example, imagine the following communities:
; A = 3
; B = 5
; C = 3 and 5
; dicarding all annoucements with C set, also discards all annoucements with A
; or B set, but we wouldn't know. We could solve this by adding additional
; constraints between an annoucement's boolean variables, e.g. C -> A /\ B.
(define (default-announcement prefix env)
(announcement
(subset (environment-communities env))
prefix
(subset (environment-aspaths env))
200))
(define (symbolic-communities env)
(symbolic-subset (environment-communities env)))
(define (symbolic-aspath env)
(symbolic-subset (environment-aspaths env)))
(define (symbolic-announcement env)
(define prefix (symbolic-prefix))
(define comms (symbolic-communities env))
(define aspath (symbolic-aspath env))
(define-symbolic* pref number?)
(announcement comms prefix aspath pref))
| false |
bdb2a97f964419cb67975ce3ccb6940d3d187f14 | 1a52d279ddc388555020fd8d213e2b3ee5fa97df | /simply-typed/base/expander.rkt | 75b1b293e476f3983171414b0967904fbbce2f8f | [
"MIT"
]
| permissive | GriffinMB/glc | 0323bead1a7e280e69d3f6e4f7562ff243ed72bf | 22fd96aa0a11b092cd8aaaeb049e03bea05764d3 | refs/heads/master | 2022-12-26T11:21:08.761829 | 2020-10-09T00:02:21 | 2020-10-09T00:02:21 | 292,974,113 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 4,262 | rkt | expander.rkt | #lang racket
(require (only-in glc/base/expander normalize-app lambda->number)
(rename-in lazy (lambda lazy:lambda))
(for-syntax racket/syntax syntax/parse racket/list))
(provide (rename-out [glc-simply-typed-module-begin #%module-begin]
[glc-simply-typed-app #%app]
[glc-simply-typed-datum #%datum]
[glc-simply-typed-top #%top]
[glc-simply-typed-lambda lambda]
[glc-simply-typed-lambda λ])
; provide/require
require
; test helpers
module+
; primitives
!
!!
; base
def
lambda->number
:
; module exports
#%top-interaction)
(define-syntax (glc-simply-typed-module-begin stx)
(syntax-parse stx
[(_:id expr ...)
#'(#%module-begin
expr ...)]))
(define-syntax (: stx)
(syntax-parse stx
[(_ id:id type:expr)
(with-syntax ([type-id (format-id stx "glc-type-~a" #'id)])
#'(define-for-syntax type-id 'type))]))
(define-syntax (glc-simply-typed-lambda stx)
(syntax-parse stx
[(_ (~or x:id (x:id)) expr) #'(lazy:lambda (x) expr)]))
(define-syntax (glc-simply-typed-app stx)
(define normalized (datum->syntax stx (normalize-app (cdr (syntax->datum stx)))))
(when (equal? (syntax-local-context) 'module)
(typecheck normalized (make-immutable-hash)))
(syntax-parse normalized
[(x y) #'(#%app x y)]))
(define-syntax (glc-simply-typed-datum stx)
(raise-syntax-error #f "Invalid use of datum literal" stx))
(define-syntax-rule (glc-simply-typed-top . id)
'id)
(define-syntax (def stx)
(syntax-parse stx
[(_ id:id expr:expr)
(with-syntax ([type-id (format-id stx "glc-type-~a" #'id)])
(let*-values ([(type) (eval-syntax #'type-id)]
[(env) (make-immutable-hash)]
[(ctx base) (set-context #'expr type env)]
[(normalized) (datum->syntax base (normalize-app (syntax->datum base)))])
(if (equal? (last type) (typecheck normalized ctx))
#'(define id expr)
(raise (format "~a does not have type ~a" (syntax-e #'id) type)))))]))
(define-for-syntax (set-context stx type-id env)
(let ([type-head (car type-id)]
[type-tail (cdr type-id)])
(if (> (length type-tail) 0)
(syntax-parse stx
; TODO fix error case - i.e. the id won't syntax-match a literal λ or lambda???
[(lam:id (~or id:id (id:id)) expr)
(let* ([lam (syntax-e #'lam)]
[sl (equal? lam 'lambda)]
[ss (equal? lam 'λ)])
(if (or sl ss)
(set-context #'expr type-tail (hash-set env [syntax-e #'id] type-head))
(raise "Lambda expected")))])
(values env stx))))
(define-for-syntax (typecheck stx env)
(syntax-parse stx
[((~or (~literal λ) (~literal lambda)) _ _)
(void)]
[x:id (with-syntax ([type-id (format-id stx "glc-type-~a" #'x)])
(hash-ref env (syntax-e #'x) (lambda () (eval-syntax #'type-id))))]
[(x y) (let* ([x-type (typecheck #'x env)]
[y-type (typecheck #'y env)]
[x1 (car x-type)]
[xrest (cdr x-type)]
[sx1 (format "~a" x1)])
(let ([return-type
(if (match-type? y-type x1)
xrest
(if (equal? sx1 (string-downcase sx1))
(map (lambda (var)
(if (equal? var x1)
y-type
var))
xrest)
(raise (format "Type ~a does not match type ~a" y-type x-type))))])
(if (equal? (length return-type) 1)
(car return-type)
return-type)))]
[x (displayln #'x)]))
(define-for-syntax (match-type? y x [tkn #f])
(cond
; basic type case
[(equal? y x) #t]
; U constructor
[(equal? tkn 'U) (index-of x y)]
[(list? x) (match-type? y (cdr x) (car x))]
; no match or parameterized
[else #f]))
| true |
180d6300f2bd32f67b5f33a90765f377a360a66e | 8218ce91484e3f6bc542a1450b7f4c25bf58f730 | /rnrs-immutable/base-6.rkt | 32860c268803f681a9f3b4870ea8afc02d56e8eb | []
| no_license | samth/r6rs-immutable | b92dd4ad179d24e492f874f4779ccb8365bce3d0 | 3ee044db30cd0efb8b4e0d1ad1df241e0542a2a4 | refs/heads/master | 2020-06-16T11:22:58.436824 | 2015-12-05T21:11:23 | 2015-12-05T21:11:23 | 47,472,883 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 17,744 | rkt | base-6.rkt | #lang scheme/base
(require (for-syntax (rename-in r6rs/private/base-for-syntax
[syntax-rules r6rs:syntax-rules])
scheme/base)
scheme/promise
scheme/splicing
r6rs/private/qq-gen
r6rs/private/exns
r6rs/private/no-set
(for-syntax r6rs/private/reconstruct)
(prefix-in r5rs: r5rs)
(only-in r6rs/private/readtable rx:number)
scheme/bool
(prefix-in racket: racket/base))
(provide
;; 11.2
(rename-out [r6rs:define define]
[r6rs:define-syntax define-syntax])
;; 11.4.1
(rename-out [racket:quote quote])
;; 11.4.2
(rename-out [r6rs:lambda lambda])
;; 11.4.3
(rename-out [r5rs:if if])
;; 11.4.4
(rename-out [r6rs:set! set!])
;; 11.4.5
(rename-out [r5rs:cond cond]
[r5rs:case case])
else =>
and or
;; 11.4.6
let let*
(rename-out [r6rs:letrec letrec]
[r6rs:letrec* letrec*]
[r6rs:let-values let-values]
[r6rs:let*-values let*-values])
;; 11.4.7
begin
;; 11.5
eqv? eq? equal?
;; 11.6
procedure?
;; 11.7.4
number? complex? real? rational? integer?
real-valued? rational-valued? integer-valued?
exact? inexact?
(rename-out [inexact->exact exact]
[exact->inexact inexact])
= < > <= >=
zero? positive? negative? odd?
even? finite? infinite? nan?
min max
+ * -
(rename-out [r6rs:/ /])
abs
div-and-mod div mod
div0-and-mod0 div0 mod0
gcd lcm
numerator denominator
floor ceiling truncate round
rationalize
exp (rename-out [r6rs:log log]) sin cos tan asin acos atan
sqrt (rename-out [integer-sqrt/remainder exact-integer-sqrt])
(rename-out [r6rs:expt expt])
make-rectangular make-polar real-part imag-part magnitude
(rename-out [r6rs:angle angle]
[r6rs:number->string number->string]
[r6rs:string->number string->number])
;; 11.8
not boolean? (rename-out [r6rs:boolean=? boolean=?])
;; 11.9
(rename-out [racket:pair? pair?]
[racket:cons cons]
[racket:car car]
[racket:cdr cdr]
[racket:caar caar]
[racket:cadr cadr]
[racket:cdar cdar]
[racket:cddr cddr]
[racket:caaar caaar]
[racket:caadr caadr]
[racket:cadar cadar]
[racket:caddr caddr]
[racket:cdaar cdaar]
[racket:cdadr cdadr]
[racket:cddar cddar]
[racket:cdddr cdddr]
[racket:caaaar caaaar]
[racket:caaadr caaadr]
[racket:caadar caadar]
[racket:caaddr caaddr]
[racket:cadaar cadaar]
[racket:cadadr cadadr]
[racket:caddar caddar]
[racket:cadddr cadddr]
[racket:cdaaar cdaaar]
[racket:cdaadr cdaadr]
[racket:cdadar cdadar]
[racket:cdaddr cdaddr]
[racket:cddaar cddaar]
[racket:cddadr cddadr]
[racket:cdddar cdddar]
[racket:cddddr cddddr]
[racket:null? null?]
[racket:list? list?]
[racket:list list]
[racket:length length]
[racket:append append]
[racket:reverse reverse]
[racket:list-tail list-tail]
[racket:list-ref list-ref]
[racket:map map]
[racket:for-each for-each])
;; 11.10
symbol? (rename-out [r6rs:symbol=? symbol=?])
string->symbol symbol->string
;; 11.11
char? char=? char<? char>? char<=? char>=?
integer->char char->integer
;; 11.12
string?
make-string string
string-length string-ref
string=? string<? string>? string<=? string>=?
substring string-append
(rename-out [racket:string->list string->list]
[racket:list->string list->string])
string-for-each string-copy
;; 11.13
vector? make-vector vector
vector-length vector-ref vector-set!
(rename-out [racket:vector->list vector->list]
[racket:list->vector list->vector])
vector-fill!
vector-map
vector-for-each
;; 11.14
(rename-out [r6rs:error error])
assertion-violation assert
;; 11.15
(rename-out [racket:apply apply]
[call-with-current-continuation call/cc])
call-with-current-continuation
values call-with-values
dynamic-wind
;; 11.17
(rename-out [r6rs:quasiquote quasiquote])
unquote unquote-splicing
;; 11.18
(rename-out [r6rs:let-syntax let-syntax]
[r6rs:letrec-syntax letrec-syntax])
;; 11.19
(for-syntax (rename-out [r6rs:syntax-rules syntax-rules])
identifier-syntax
...
_)
)
;; ----------------------------------------
(define (real-valued? o)
(or (real? o)
(and (complex? o)
(zero? (imag-part o)))))
(define (rational-valued? o)
(or (rational? o)
(and (complex? o)
(zero? (imag-part o))
(rational? (real-part o)))))
(define (integer-valued? o)
(or (integer? o)
(and (complex? o)
(zero? (imag-part o))
(integer? (real-part o)))))
(define (finite? n)
(if (real? n)
(not (or (eqv? n +inf.0)
(eqv? n -inf.0)
(eqv? n +nan.0)))
(raise-type-error 'infinite? "real" n)))
(define (infinite? n)
(if (real? n)
(or (eqv? n +inf.0)
(eqv? n -inf.0))
(raise-type-error 'infinite? "real" n)))
(define (nan? n)
(if (real? n)
(eqv? n +nan.0)
(raise-type-error 'nan? "real" n)))
;; Someone needs to look more closely at div and mod.
(define (div x y)
(cond
[(rational? y)
(cond
[(x . >= . 0)
(truncate (/ x y))]
[(y . > . 0)
(floor (/ x y))]
[else
(ceiling (/ x y))])]
[(real? y)
;; infinity or nan
(if (equal? y +nan.0)
+nan.0
1.0)]
[else
(raise-type-error 'div "real number" y)]))
(define (mod x y)
(- x (* (div x y) y)))
(define (div-and-mod x y)
(let ([d (div x y)])
(values d (- x (* d y)))))
(define (div0-and-mod0 x y)
(let-values ([(d m) (div-and-mod x y)])
(if (>= m (/ (abs y) 2))
(if (negative? y)
(values (sub1 d) (+ m y))
(values (add1 d) (- m y)))
(values d m))))
(define (div0 x y)
(let-values ([(d m) (div0-and-mod0 x y)])
d))
(define (mod0 x y)
(let-values ([(d m) (div0-and-mod0 x y)])
m))
(define-syntax r6rs:/
;; R6RS says that division with exact zero is treated like
;; division by inexact zero if any of the other arguments are inexact.
;; We use a macro to inline tests in binary mode, since the JIT
;; can inline for flonum arithmetic.
(make-set!-transformer
(lambda (stx)
(if (identifier? stx)
(syntax/loc stx r6rs-/)
(syntax-case stx (r6rs:set!)
[(r6rs:set! . _)
(raise-syntax-error #f
"cannot mutate imported identifier"
stx)]
[(_ expr) #'(/ expr)]
[(_ expr1 expr2)
#'(let ([a expr1]
[b expr2])
(cond
[(and (eq? b 0) (number? a) (inexact? a))
(/ a 0.0)]
[(and (eq? a 0) (number? b) (inexact? b))
(/ 0.0 b)]
[else (/ a b)]))]
[(_ . args)
#'(r6rs-/ . args)])))))
(define r6rs-/
(case-lambda
[(n) (/ n)]
[(a b) (r6rs:/ a b)]
[args (if (ormap (lambda (x) (and (number? x) (inexact? x))) args)
(apply /
(map (lambda (v) (if (eq? v 0)
0.0
v))
args))
(apply / args))]))
(define r6rs:log
(case-lambda
[(n) (log n)]
[(n m) (/ (log n) (log m))]))
(define (r6rs:expt base power)
(cond
[(and (number? base)
(zero? base)
(number? power))
(if (zero? power)
(if (and (eq? base 0)
(exact? power))
1
1.0)
(if (positive? (real-part power))
(if (and (eq? base 0)
(exact? power))
0
0.0)
(expt base power)))]
[(and (eq? base 1)
(number? power)
(inexact? power))
(expt (exact->inexact base) power)]
[else (expt base power)]))
(define (r6rs:angle n)
; because `angle' produces exact 0 for reals:
(if (and (inexact-real? n) (positive? n))
0.0
(angle n)))
(define (r6rs:number->string z [radix 10] [precision #f])
(number->string z radix))
(define (r6rs:string->number s [radix 10])
(let* ([prefix (case radix
[(10) "#d"]
[(16) "#x"]
[(8) "#o"]
[(2) "#b"]
[else (raise-type-error
'string->number
"2, 8, 10, or 16"
radix)])]
[s (if (regexp-match? #rx"#[dDxXoObB]" s)
s
(string-append prefix s))])
(and (regexp-match? (force rx:number) s)
(string->number (regexp-replace* #rx"[|][0-9]+" s "")))))
(define r6rs:symbol=?
(case-lambda
[(a b) (symbol=? a b)]
[(a b . rest) (and (symbol=? a b)
(andmap (lambda (s)
(symbol=? a s))
rest))]))
(define r6rs:boolean=?
(case-lambda
[(a b) (boolean=? a b)]
[(a b . rest) (and (boolean=? a b)
(andmap (lambda (s)
(boolean=? a s))
rest))]))
(define-syntax-rule (make-mapper what for for-each in-val val-length val->list list->result)
(case-lambda
[(proc val) (list->result
(for ([c (in-val val)])
(proc c)))]
[(proc val1 val2)
(if (= (val-length val1)
(val-length val2))
(list->result
(for ([c1 (in-val val1)]
[c2 (in-val val2)])
(proc c1 c2)))
(error 'val-for-each "~as have different lengths: ~e and: ~e"
what
val1 val2))]
[(proc val1 . vals)
(let ([len (val-length val1)])
(for-each (lambda (s)
(unless (= (val-length s) len)
(error 'val-for-each "~a have different lengths: ~e and: ~e"
what
val1 s)))
vals)
(list->result
(apply for-each
proc
(val->list val1)
(map val->list vals))))]))
(define string-for-each
(make-mapper "string" for for-each in-string string-length string->list void))
(define vector-for-each
(make-mapper "vector" for for-each in-vector vector-length vector->list void))
(define vector-map
(make-mapper "vector" for/list map in-vector vector-length vector->list list->vector))
(define (add-irritants msg irritants)
(if (null? irritants)
msg
(apply
string-append
msg
"\n irritants:"
(map (lambda (s)
(format "\n ~e" s))
irritants))))
(define (r6rs:error who msg . irritants)
(raise
(make-exn:fail:r6rs
(add-irritants
(if who
(format "~a: ~a" who msg)
msg)
irritants)
(current-continuation-marks)
msg
who
irritants)))
(define (assertion-violation who msg . irritants)
(raise
(make-exn:fail:contract:r6rs
(add-irritants
(if who
(format "~a: ~a" who msg)
msg)
irritants)
(current-continuation-marks)
msg
who
irritants)))
(define-syntax-rule (assert expr)
(unless expr
(assertion-violation #f "assertion failed")))
;; ----------------------------------------
;; quasiquote generalization
(define-generalized-qq r6rs:quasiquote
racket:quasiquote unquote unquote-splicing values)
;; ----------------------------------------
;; letrec
;; Need bindings like R5RS, but int-def body like Racket
(define-syntax (r6rs:letrec stx)
(syntax-case stx (r6rs:lambda)
[(_ ([id (r6rs:lambda . rest)] ...) . body)
#'(letrec ([id (r6rs:lambda . rest)] ...) (let () (#%stratified-body . body)))]
[(_ bindings . body)
#'(r5rs:letrec bindings (let () (#%stratified-body . body)))]))
(define-syntax-rule (r6rs:letrec* bindings . body)
(letrec bindings (#%stratified-body . body)))
;; ----------------------------------------
;; let[*]-values
(define-syntax (r6rs:let-values stx)
#`(letX-values let-values #,stx))
(define-syntax (r6rs:let*-values stx)
#`(letX-values let*-values #,stx))
(define-syntax (letX-values stx)
(syntax-case stx ()
[(_ dest:let-values orig)
(let ([orig #'orig])
(syntax-case orig ()
[(_ ([formals expr] ...) body0 body ...)
(with-syntax ([bindings
(map (lambda (formals expr)
(if (syntax->list formals)
(list formals expr)
(let ([ids (let loop ([formals formals])
(cond
[(identifier? formals)
(list formals)]
[(and (syntax? formals)
(pair? (syntax-e formals)))
(loop (syntax-e formals))]
[(pair? formals)
(unless (identifier? (car formals))
(raise-syntax-error
#f
"not an identifier for binding"
orig
(car formals)))
(cons (car formals) (loop (cdr formals)))]
[else
(unless (identifier? (car formals))
(raise-syntax-error
#f
"not an identifier for binding"
orig
formals))]))])
#`[#,ids
(call-with-values
(lambda () #,expr)
(r6rs:lambda #,formals
(values . #,ids)))])))
(syntax->list #'(formals ...))
(syntax->list #'(expr ...)))])
#'(dest:let-values bindings (#%stratified-body body0 body ...)))]))]))
;; ----------------------------------------
;; lambda & define
;; Need rest-arg conversion like R5RS, but int-def handlign like Racket
(define-syntax (r6rs:lambda stx)
(syntax-case stx ()
[(_ (id ...) . body)
(andmap identifier? (syntax->list #'(id ...)))
(syntax/loc stx (lambda (id ...) (#%stratified-body . body)))]
[(_ args . body)
(syntax/loc stx (racket:lambda args (let () (#%stratified-body . body))))]))
(define-for-syntax (check-label id orig-stx def)
;; This test shouldn't be needed, and it interferes
;; with macro-introduced bindings:
#;
(when (eq? 'module (syntax-local-context))
(when (identifier-binding id #f)
(raise-syntax-error
#f
"cannot define imported identifier"
orig-stx
id)))
def)
(define-syntax (r6rs:define stx)
(syntax-case stx ()
[(_ id)
(identifier? #'id)
(check-label #'id stx (syntax/loc stx (define id (void))))]
[(_ (name . args) . body)
(check-label #'name
stx
(syntax/loc stx (racket:define (name . args) (let () (#%stratified-body . body)))))]
[(_ . rest) #'(define . rest)]))
;; ----------------------------------------
;; define-syntax: wrap a transformer to
;; ensure that the result of an expansion is
;; a wrapped syntax object.
(define-syntax (r6rs:define-syntax stx)
(syntax-case stx ()
[(_ id expr)
(identifier? #'id)
(check-label #'id
stx
(syntax/loc stx
(define-syntax id (wrap-as-needed expr))))]))
(define-for-syntax (wrap-as-needed v)
(cond
[(and (procedure? v)
(procedure-arity-includes? v 1))
(procedure-reduce-arity
(case-lambda
[(stx) (if (syntax? stx)
(let ([r (v stx)])
(wrap r stx stx #t))
(v stx))]
[args (apply v args)])
(procedure-arity v))]
[(set!-transformer? v)
(make-set!-transformer (wrap-as-needed (set!-transformer-procedure v)))]
[else v]))
;; ----------------------------------------
;; let[rec]-syntax needs to be splicing, and it needs the
;; same transformer wrapper as in `define-syntax'
(define-syntax (r6rs:let-syntax stx)
(syntax-case stx ()
[(_ ([id expr] ...) body ...)
(syntax/loc stx
(splicing-let-syntax ([id (wrap-as-needed expr)] ...) body ...))]))
(define-syntax (r6rs:letrec-syntax stx)
(syntax-case stx ()
[(_ ([id expr] ...) body ...)
(syntax/loc stx
(splicing-letrec-syntax ([id (wrap-as-needed expr)] ...) body ...))]))
| true |
4d8305b51a1c7eab39329610f323611a47b8e776 | 688b982ef1ae4b822162cee56a6437a3fa3ec9a8 | /asdl/grammar.rkt | b433f7de09cd3f246da021e7ae8c3ec94995b32d | []
| no_license | jmillikan/racket-asdl | e6cc16a1f881ba00c837c4ba0005ead42655922a | 341f3b2555560da3d6d8906d02cf13cd2a5dee0d | refs/heads/master | 2020-05-17T08:44:46.062688 | 2013-05-31T00:16:21 | 2013-05-31T00:16:21 | 10,226,058 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 458 | rkt | grammar.rkt | #lang ragg
# Some of these clauses exist to
modules: module*
module: "module" CONSTRUCTORID maybe_version "{" type* "}"
maybe_version: ["version" STRING]
type: TYPEID "=" constructor_list maybe_attributes
constructor_list: constructor ("|" constructor)*
maybe_attributes: ["attributes" properties]
constructor: CONSTRUCTORID [properties]
properties: "(" [property ("," property)*] ")"
property: TYPEID maybe_modifier TYPEID
maybe_modifier: ["?" | "*"]
| false |
227cb5bc890b85f546e40d08c5de269c8b9f3f72 | df0ba5a0dea3929f29358805fe8dcf4f97d89969 | /exercises/computer-science-2/04--lists/solutions/15--list-ref.rkt | 6cc26e4f62b4fa439028880aaea56fcf9bb6690d | [
"MIT"
]
| permissive | triffon/fp-2019-20 | 1c397e4f0bf521bf5397f465bd1cc532011e8cf1 | a74dcde683538be031186cf18367993e70dc1a1c | refs/heads/master | 2021-12-15T00:32:28.583751 | 2021-12-03T13:57:04 | 2021-12-03T13:57:04 | 210,043,805 | 14 | 31 | MIT | 2019-12-23T23:39:09 | 2019-09-21T19:41:41 | Racket | UTF-8 | Racket | false | false | 713 | rkt | 15--list-ref.rkt | #lang racket
(require rackunit rackunit/text-ui)
; ### Задача 15
; Напишете функция `(list-ref L n)`,
; която връща елементът на позиция `n` в списъка `L`. Броенето започва от нула.
(define (list-ref L n)
(cond ((null? L) L)
((= n 0) (car L))
(else (list-ref (cdr L) (- n 1)))))
(run-tests (test-suite "list-ref tests"
(check-equal? (list-ref '(1 2 3 4) 0)
1)
(check-equal? (list-ref '(21 22 23 24) 3)
24)
(check-equal? (list-ref '(1 (2 3 4) (5 6) ((7)) 8) 1)
'(2 3 4)))
'verbose)
| false |
18605470e2bf4dfbd710980f5825018c0980bb93 | b08b7e3160ae9947b6046123acad8f59152375c3 | /Programming Language Detection/Experiment-2/Dataset/Train/Racket/strip-whitespace-from-a-string-top-and-tail.rkt | 893d5a79dbd7aa4cf278983997c3b54e9202d227 | []
| no_license | dlaststark/machine-learning-projects | efb0a28c664419275e87eb612c89054164fe1eb0 | eaa0c96d4d1c15934d63035b837636a6d11736e3 | refs/heads/master | 2022-12-06T08:36:09.867677 | 2022-11-20T13:17:25 | 2022-11-20T13:17:25 | 246,379,103 | 9 | 5 | null | null | null | null | UTF-8 | Racket | false | false | 349 | rkt | strip-whitespace-from-a-string-top-and-tail.rkt | #lang racket
;; Using Racket's `string-trim'
(define str " \n\t foo bar \r\n ")
;; both sides:
(string-trim str) ; -> "foo bar"
;; one side:
(string-trim str #:right? #f) ; -> "foo bar \r\n "
(string-trim str #:left? #f) ; -> " \n\t foo bar"
;; can also normalize spaces:
(string-normalize-spaces (string-trim str)) ; -> "foo bar"
| false |
f5440d973b028f9c3ad487eab845a7db5f3f5b62 | 9dc77b822eb96cd03ec549a3a71e81f640350276 | /collection/multiset.scrbl | a2fbac12bd822f54783e23e512f90238f8b1416a | [
"Apache-2.0"
]
| permissive | jackfirth/rebellion | 42eadaee1d0270ad0007055cad1e0d6f9d14b5d2 | 69dce215e231e62889389bc40be11f5b4387b304 | refs/heads/master | 2023-03-09T19:44:29.168895 | 2023-02-23T05:39:33 | 2023-02-23T05:39:33 | 155,018,201 | 88 | 21 | Apache-2.0 | 2023-09-07T03:44:59 | 2018-10-27T23:18:52 | Racket | UTF-8 | Racket | false | false | 7,757 | scrbl | multiset.scrbl | #lang scribble/manual
@(require (for-label racket/base
racket/contract/base
racket/math
racket/sequence
racket/set
rebellion/collection/multiset
rebellion/streaming/reducer)
(submod rebellion/private/scribble-evaluator-factory doc)
(submod rebellion/private/scribble-cross-document-tech doc)
scribble/example)
@(define make-evaluator
(make-module-sharing-evaluator-factory
#:public (list 'rebellion/collection/multiset
'rebellion/streaming/reducer)
#:private (list 'racket/base)))
@title{Multisets}
@defmodule[rebellion/collection/multiset]
A @deftech{multiset} is an unordered collection, like a @tech/reference{set},
except it can contain duplicate elements. Elements are always compared with
@racket[equal?].
@defproc[(multiset? [v any/c]) boolean?]{
A predicate for @tech{multisets}.}
@defproc[(multiset [v any/c] ...) multiset?]{
Constructs a @tech{multiset} containing the given @racket[v]s.
@(examples
#:eval (make-evaluator) #:once
(multiset 'apple 'orange 'banana)
(multiset 'apple 'orange 'orange 'banana)
(multiset))}
@defthing[empty-multiset multiset? #:value (multiset)]{
The empty @tech{multiset}, which contains no elements.}
@section{Querying Multisets}
@defproc[(multiset-size [set multiset?]) natural?]{
Returns the total number of elements in @racket[set], including duplicates.
@(examples
#:eval (make-evaluator) #:once
(define set (multiset 5 8 8 8))
(multiset-size set))}
@defproc[(multiset-frequency [set multiset?] [v any/c]) natural?]{
Returns the number of times that @racket[set] contains @racket[v].
@(examples
#:eval (make-evaluator) #:once
(define set (multiset 5 8 8 8))
(multiset-frequency set 5)
(multiset-frequency set 8)
(multiset-frequency set 'apple))}
@defproc[(multiset-frequencies [set multiset?])
(immutable-hash/c any/c exact-positive-integer?)]{
Returns a hash mapping the unique elements of @racket[set] to the number of
times they occur in @racket[set].
@(examples
#:eval (make-evaluator) #:once
(multiset-frequencies
(multiset 'red 'red 'red 'blue 'green 'green 'green 'green)))}
@defproc[(multiset-contains? [set multiset?] [v any/c]) boolean?]{
Returns @racket[#t] if @racket[set] contains @racket[v], @racket[#f] otherwise.
@(examples
#:eval (make-evaluator) #:once
(define set (multiset 'apple 'orange 'orange))
(multiset-contains? set 'apple)
(multiset-contains? set 'orange)
(multiset-contains? set 42))}
@defproc[(multiset-unique-elements [set multiset?]) set?]{
Removes all duplicate elements from @racket[set], returning the resulting set.
@(examples
#:eval (make-evaluator) #:once
(multiset-unique-elements (multiset 5 8 8 8 13 13)))}
@section{Persistently Updating Multisets}
Multisets are always immutable. The following update operations return new
multisets and leave the input multiset unchanged. However, multisets are
implemented with an efficient persistent data structure that allows the modified
multisets to share their structure with the input multiset. The precise
performance characteristics of these operations are not specified at this time,
but their running times are all sublinear in the number of distinct elements in
the modified multiset.
@defproc[(multiset-add [set multiset?]
[element any/c]
[#:copies num-copies natural? 1])
multiset?]{
Adds @racket[element] to @racket[set], returning an updated @tech{multiset}. If
@racket[copies] is specified, then @racket[element] is added @racket[
num-copies] times instead of only once.
@(examples
#:eval (make-evaluator) #:once
(multiset-add (multiset 'apple 'orange 'banana) 'grape)
(multiset-add (multiset 'apple 'orange 'banana) 'orange)
(multiset-add (multiset 'apple 'orange 'banana) 'orange #:copies 5))}
@defproc[(multiset-add-all [set multiset?] [seq (sequence/c any/c)]) multiset?]{
Adds @racket[seq] elements into @racket[set], returning an updated
@tech{multiset}. The original @racket[set] is not mutated.
@(examples
#:eval (make-evaluator) #:once
(multiset-add-all (multiset 1 1 2 3) (in-range 0 5))
(multiset-add-all (multiset 1 2 3) (multiset 1 2 3)))}
@defproc[(multiset-remove [set multiset?]
[element any/c]
[#:copies num-copies (or/c natural? +inf.0) 1])
multiset?]{
Removes a single @racket[element] from @racket[set], returning an updated
@tech{multiset}. If @racket[num-copies] is specified then instead that many
copies of @racket[element] are removed from @racket[set], removing all
occurrences if @racket[num-copies] is @racket[+inf.0] or if @racket[set]
contains fewer occurrences of @racket[element] than @racket[num-copies].
@(examples
#:eval (make-evaluator) #:once
(eval:no-prompt
(define set (multiset 'blue 'blue 'red 'red 'red 'green)))
(multiset-remove set 'red)
(multiset-remove set 'red #:copies 2)
(multiset-remove set 'red #:copies 5)
(multiset-remove set 'blue #:copies +inf.0)
(multiset-remove set 'orange))}
@defproc[(multiset-set-frequency [set multiset?]
[element any/c]
[frequency natural?])
multiset?]{
Adds or removes copies of @racket[element] to or from @racket[set] until it
occurs exactly @racket[frequency] times in @racket[set]. If @racket[frequency]
is zero, this is equivalent to removing all copies of @racket[element] from
@racket[set].
@(examples
#:eval (make-evaluator) #:once
(multiset-set-frequency (multiset 'red 'red 'blue 'green) 'blue 4)
(multiset-set-frequency (multiset 'red 'red 'blue 'green) 'blue 0))}
@section{Multiset Iteration and Comprehension}
@defproc[(in-multiset [set multiset?]) sequence?]{
Returns a @tech/reference{sequence} that iterates over the elements of @racket[
set], including duplicates.
@(examples
#:eval (make-evaluator) #:once
(define set (multiset 5 8 8 8 5 3))
(for ([v (in-multiset set)])
(displayln v)))}
@defthing[into-multiset (reducer/c any/c multiset?)]{
A @tech{reducer} that collects elements into a @tech{multiset}.
@(examples
#:eval (make-evaluator) #:once
(reduce-all into-multiset (in-string "happy birthday!")))}
@defform[(for/multiset (for-clause ...) body-or-break ... body)]{
Like @racket[for], but collects the iterated values into a @tech{multiset}.
@(examples
#:eval (make-evaluator) #:once
(for/multiset ([char (in-string "Hello World")])
(cond [(char-whitespace? char) 'whitespace]
[(char-upper-case? char) 'uppercase-letter]
[else 'lowercase-letter])))}
@defform[(for*/multiset (for-clause ...) body-or-break ... body)]{
Like @racket[for*], but collects the iterated values into a @tech{multiset}.
@(examples
#:eval (make-evaluator) #:once
(for*/multiset ([str (in-list (list "the" "quick" "brown" "fox"))]
[char (in-string str)])
char))}
@section{Multiset Conversions}
@defproc[(multiset->list [set multiset?]) list?]{
Returns a list of all the elements of @racket[set]. Duplicate elements are
adjacent in the returned list, but the order of unequal elements is unspecified
and should not be relied upon.
@(examples
#:eval (make-evaluator) #:once
(multiset->list (multiset 'a 'a 'b 'c 'c 'c 'd)))}
@defproc[(sequence->multiset [seq sequence?]) multiset?]{
Returns a @tech{multiset} containing the elements of @racket[seq], including
duplicates.
@(examples
#:eval (make-evaluator) #:once
(sequence->multiset (in-range 5)))}
| false |
c248e2d1f3bdb27487be85fe4052e3254f0226c0 | 320eb8a018f3063eeb2373425fea6144704f4bfc | /neuron-doc/scribblings/reference/data-flow.scrbl | 73da8585c834297e3c962879e6e2334ff2883244 | [
"Apache-2.0"
]
| permissive | dedbox/racket-neuron | 583f458dfa363d652d7e5424ae89e854aeff8508 | a8ecafec0c6398c35423348cb02ec229869c8b15 | refs/heads/master | 2022-06-06T07:54:53.445496 | 2018-04-17T18:33:57 | 2018-04-17T18:33:57 | 115,617,919 | 17 | 3 | Apache-2.0 | 2022-05-16T21:13:56 | 2017-12-28T11:44:22 | Racket | UTF-8 | Racket | false | false | 13,817 | scrbl | data-flow.scrbl | #lang scribble/doc
@(require "../base.rkt")
@title{Data Flow}
@section{Socket}
@(defmodule neuron/socket)
A @deftech{socket} is the local end of a bi-directional serial communications
channel. Each socket holds an @rtech{input port} and an @rtech{output port}.
A socket can be used as a @rtech{synchronizable event}. A socket is
@rtech{ready for synchronization} when the ports it holds have closed. Sockets
do not support half-open connections---when either port closes, the other port
is closed immediately.
@defproc[(socket? [v any/c]) boolean?]{
Returns @racket[#t] if @racket[v] is a @racket[socket], @racket[#f]
otherwise.
}
@defproc[(socket [in-port input-port?] [out-port output-port?]) socket?]{
Returns a @tech{socket}. Serves as @racket[out-port] when used as an
@rtech{output port}, and as @racket[in-port] when used as an @rtech{input
port} or with procedures that take both kinds, such as
@racket[file-position].
}
@defproc[(close-socket [sock socket?]) void?]{
Closes the ports held by @racket[sock]. If the ports are already closed,
@racket[close-socket] has no effect.
}
@defproc[(socket-closed? [sock socket?]) boolean?]{
Returns @racket{#t} if the ports held by @racket[sock] are closed,
@racket[#f] otherwise.
}
@defproc[(null-socket) socket?]{
Returns a @tech{socket} that ignores all input and always outputs
@racket[eof].
}
@deftogether[(
@defproc[(byte-socket [#:in str bytes? #""]
[#:out out? boolean? #f]) socket?]
@defproc[(string-socket [#:in str string? ""]
[#:out out? boolean? #f]) socket?]
)]{
Returns a @tech{socket} that inputs from @racket[str] and, if @racket[out?]
is @racket[#t], accumulates output in a fresh output @rtech{string port}.
@examples[
#:eval neuron-evaluator
#:label "Example:"
(define sock (string-socket #:in "123" #:out #t))
(read sock)
(write 'abc sock)
(get-output-string sock)
]
}
@defproc[(file-socket
[#:in in-path (or/c path-string? #f) #f]
[#:in-mode in-mode-flag (or/c 'binary 'text) 'binary]
[#:out out-path (or/c path-string? #f) #f]
[#:out-mode out-mode-flag (or/c 'binary 'text) 'binary]
[#:exists exists-flag
(or/c 'error 'append 'update 'can-update
'replace 'truncate
'must-truncate 'truncate/replace)]) socket?]{
Returns a @tech{socket} that opens the files specified by @racket[in-path]
and @racket[out-path] for input and output, respectively. If
@racket[in-path] is @racket[#f], then all input is ignored. If
@racket[out-path] is @racket[#f], then only @racket[eof] is output. If both
are @racket[#f], then the @racket[file-socket] call is equivalent to
@racket[(null-socket)].
See @racket[open-input-file] for details on @racket[in-mode-flag], and
@racket[open-output-file] for details on @racket[out-mode-flag] and
@racket[exists-flag].
}
@section{Codec}
@(defmodule neuron/codec)
A @deftech{codec} is a @racket[stream] that uses a @tech{socket} to exchange
serializable values with remote agents. The @racket[sink] is called an
@deftech{encoder}; it uses a @deftech{printer} procedure to serialize values
to a socket. The @racket[source] is called a @deftech{decoder}; it uses a
@deftech{parser} procedure to de-serialize values from a socket.
@defthing[parser/c contract? #:value (-> socket? any/c)]{
Use this @rtech{function contract} to indicate that a function is a
@tech{parser}.
}
@defthing[printer/c contract? #:value (-> any/c socket? any)]{
Use this @rtech{function contract} to indicate that a function is a
@tech{printer}.
}
@defthing[codec/c contract? #:value (-> socket? process?)]{
Use this @rtech{function contract} to indicate that a function makes
@tech{decoders}, @tech{encoders}, or @tech{codecs}.
}
@defproc[(flushed [prn printer/c]) printer/c]{
Returns a @tech{printer} that applies @racket[prn] to a @tech{socket} and
then flushes its @rtech{output port}.
}
@defproc[(decoder [prs parser/c]) codec/c]{
Returns a procedure that makes @tech{decoders} based on @racket[prs]:
Parses and emits values from a @tech{socket}. Stops when @racket[prs]
returns @racket[eof]. Closes the @tech{socket} when it stops. Dies when the
@tech{socket} closes.
Commands:
@itemlist[
@item{@racket['parser] -- returns @racket[prs]}
@item{@racket['socket] -- returns a @tech{socket}}
]
@examples[
#:eval neuron-evaluator
#:label "Example:"
(define dec ((decoder read) (string-socket #:in "123 abc")))
(recv dec)
(recv dec)
(recv dec)
]
}
@defproc[(encoder [prn printer/c]) codec/c]{
Returns a procedure that makes @tech{encoders} based on @racket[prn]:
Takes and prints values to a @tech{socket}. Stops when it takes
@racket[eof]. Closes the @tech{socket} when it stops. Dies when the
@tech{socket} closes.
Commands:
@itemlist[
@item{@racket['printer] -- returns @racket[prn]}
@item{@racket['socket] -- returns a @tech{socket}}
]
@examples[
#:eval neuron-evaluator
#:label "Example:"
(define enc ((encoder writeln) (string-socket #:out #t)))
(for-each (curry give enc) (list 123 'abc eof))
(get-output-string (enc 'socket))
]
}
@defproc[(codec [prs parser/c] [prn printer/c]) codec/c]{
Returns a procedure that makes @tech{codecs} based on @racket[prs] and
@racket[prn]:
Takes and prints values to a @tech{socket}. Reads and emits values from a
@tech{socket}. Stops when given @racket[eof] or @racket[prs] returns
@racket[eof]. Closes the @tech{socket} when it stops. Dies when the
@tech{socket} closes.
Commands:
@itemlist[
@item{@racket['decoder] -- returns a @tech{decoder} based on @racket[prs]}
@item{@racket['encoder] -- returns an @tech{encoder} based on @racket[prn]}
@item{@racket['socket] -- returns a @tech{socket}}
]
@examples[
#:eval neuron-evaluator
#:label "Example:"
(define cdc ((codec read writeln)
(string-socket #:in "123 abc" #:out #t)))
(for-each (curry give cdc) (list 987 'zyx eof))
(recv cdc)
(recv cdc)
(recv cdc)
(get-output-string (cdc 'socket))
]
}
@subsection{Codec Types}
A @deftech{codec type} is a set of uniformly-named procedures for making
codecs and codec parts. A complete codec type named @var[name] is defined by
the following procedures:
@itemlist[
@item{@var[name]@racket[-parser] : @racket[parser/c]}
@item{@var[name]@racket[-printer] : @racket[printer/c]}
@item{@var[name]@racket[-decoder] : @racket[codec/c]}
@item{@var[name]@racket[-encoder] : @racket[codec/c]}
@item{@var[name]@racket[-codec] : @racket[codec/c]}
]
@defproc[(make-codec-type [name symbol?]
[prs parser/c]
[prn printer/c])
(values codec/c
codec/c
codec/c)]{
Creates a new @tech{codec type}. The @racket[name] argument is used as the
type name.
The result of @racket[make-codec-type] is three values:
@itemlist[
@item{a procedure that makes @tech{decoders} based on @racket[prs],}
@item{a procedure that makes @tech{encoders} based on @racket[prn],}
@item{a procedure that makes @tech{codecs} based on @racket[prs] and
@racket[prn].}
]
}
@defform[(define-codec name prs prn)]{
Creates a new @tech{codec type} and binds variables related to the
@tech{codec type}.
A @racket[define-codec] form defines 5 names:
@itemlist[
@item{@racket[name]@racketidfont{-parser}, an alias for @tech{parser}
@racket[prs].}
@item{@racket[name]@racketidfont{-printer}, an alias for @tech{printer}
@racket[prn].}
@item{@racket[name]@racketidfont{-decoder}, a procedure that makes
@tech{decoders} based on @racket[prs].}
@item{@racket[name]@racketidfont{-encoder}, a procedure that makes
@tech{encoders} based on @racket[prn].}
@item{@racket[name]@racketidfont{-codec}, a procedure that makes
@tech{codecs} based on @racket[prs] and @racket[prn].}
]
}
@deftogether[(
@defthing[#:kind "procedure" line-parser parser/c]
@defthing[#:kind "procedure" line-printer printer/c]
@defthing[#:kind "procedure" line-decoder codec/c]
@defthing[#:kind "procedure" line-encoder codec/c]
@defthing[#:kind "procedure" line-codec codec/c]
)]{
Line @tech{codec type}.
@examples[
#:eval neuron-evaluator
#:label "Example:"
(define cdc
(line-codec
(string-socket #:in "123 abc\n" #:out #t)))
(give cdc "987 zyx")
(recv cdc)
(get-output-string (cdc 'socket))
]
}
@deftogether[(
@defthing[#:kind "procedure" sexp-parser parser/c]
@defthing[#:kind "procedure" sexp-printer printer/c]
@defthing[#:kind "procedure" sexp-decoder codec/c]
@defthing[#:kind "procedure" sexp-encoder codec/c]
@defthing[#:kind "procedure" sexp-codec codec/c]
)]{
S-expression @tech{codec type}.
@examples[
#:eval neuron-evaluator
#:label "Example:"
(define cdc
(sexp-codec
(string-socket #:in "(#hasheq((ab . 12)) 34)" #:out #t)))
(give cdc (list 987 'zyx))
(recv cdc)
(get-output-string (cdc 'socket))
]
}
@deftogether[(
@defthing[#:kind "procedure" json-parser parser/c]
@defthing[#:kind "procedure" json-printer printer/c]
@defthing[#:kind "procedure" json-decoder codec/c]
@defthing[#:kind "procedure" json-encoder codec/c]
@defthing[#:kind "procedure" json-codec codec/c]
)]{
@other-doc['(lib "json/json.scrbl")] @tech{codec type}.
To change how null is represented, set the @racket[json-null] parameter in
the @other-doc['(lib "json/json.scrbl")] library.
@examples[
#:eval neuron-evaluator
#:label "Example:"
(require json)
(define cdc
(parameterize ([json-null 'NULL])
(json-codec
(string-socket #:in "[{\"ab\":12},34,null]" #:out #t))))
(give cdc '(98 #hasheq([zy . 76]) NULL))
(recv cdc)
(get-output-string (cdc 'socket))
]
}
@section{Network}
@subsection{TCP}
@(defmodule neuron/network/tcp)
A @deftech{TCP socket} is a @tech{socket} with a TCP address.
@defproc[(tcp-socket? [v any/c]) boolean?]{
Returns @racket[#t] if @racket[v] is a @tech{TCP socket}, @racket[#f]
otherwise.
}
@defproc[(tcp-socket [in-port input-port?]
[out-port output-port?]) tcp-socket?]{
Returns a @tech{TCP socket}.
}
@defproc[(tcp-socket-address [sock tcp-socket?]) (list/c string? port-number?
string? port-number?)]{
Returns the address of @tech{TCP socket} @racket[sock].
}
@defproc[(tcp-client [hostname string?]
[port-no port-number?]
[local-hostname (or/c string? #f) #f]
[local-port-no (or/c port-number? #f) #f]) socket?]{
Establishes a TCP connection to @var[hostname]:@var[port-no]. Returns a
@tech{TCP socket}.
See @racket[tcp-connect] for argument details.
}
@defproc[(tcp-server [port-no listen-port-number?]
[max-allow-wait exact-nonnegative-integer? 4]
[reuse? any/c #f]
[hostname (or/c string? #f) #f]) process?]{
Creates a ``listening'' TCP server on @var[hostname]:@var[port-no]. Returns
a @racket[source] that emits a @tech{TCP socket} for each connection
accepted.
See @racket[tcp-listen] for argument details.
Commands:
@itemlist[
@item{@racket['address] -- returns @racket[(list hostname port-no)]}
]
}
@defproc[(tcp-service [make-codec codec/c]
[srv process?]
[#:on-accept on-accept (-> any/c process? any) void]
[#:on-drop on-drop (-> any/c process? any) void])
process?]{
Returns a @racket[service] keyed by @tech{TCP socket} address. Applies
@racket[make-codec] to each @tech{TCP socket} emitted by @racket[srv] and
adds the resulting @tech{codec} to the service. When given @racket[(list
addr v)], forwards @var[v] to @var[addr]. Emits @racket[(list addr v)] when
@var[addr] emits @var[v]. Applies @racket[on-accept] to the @tech{codecs}
made by @racket[make-codec] and their addresses. Applies @racket[on-drop] to
each address--@tech{codec} pair it drops. Drops each @tech{codec} that dies.
Drops every @tech{codec} when it stops.
Commands:
@itemlist[
@item{@racket['peers] -- returns a list of addresses}
@item{@racket['get] @var[addr] -- returns the @tech{codec} associated with
@var[addr], or @racket[#f] is no such @tech{codec} exists}
@item{@racket['drop] @var[addr] -- disconnects the @tech{TCP socket}
associated with @var[addr]; returns @racket[#t] if @var[addr] was in
use, @racket[#f] otherwise}
]
}
@; @defproc[(udp-datagram-source [sock udp?]) process?]{
@; Emits each datagram received from @racket[sock] as a byte string.
@; }
@; @defproc[(udp-datagram-sink [sock udp?]) process?]{
@; Writes each given byte string to @racket[sock] as a datagram. Bytes strings
@; of length exceeding 65,527 bytes, the maximum size of a UDP datagram
@; payload, are truncated silently.
@; }
@; @defproc[(udp-datagram-stream [sock udp?]) process?]{
@; Returns a @racket[stream] process that combines a
@; @racket[udp-datagram-source] and @racket[udp-datagram-sink].
@; }
@; @defproc[(udp-source [prs parser/c]) process?]{
@; Listens for incoming UDP datagrams. Returns a @racket[source] process that
@; applies @racket[prs] to each UDP datagram received and emits the result.
@; }
@; @defproc[(udp-sink [prn printer/c]) process?]{
@; Applies @racket[prn] to each value received and transmits the result as a
@; UDP datagram.
@; }
@; @defproc[(udp-decoder [make-dec decoder/c]) process?]{
@; }
| false |
aff2d79cfdacf0e00ef2fb0af37fb10210b108c1 | 2bb711eecf3d1844eb209c39e71dea21c9c13f5c | /rosette/base/unbound/dependencies.rkt | 185279df216773ea0947c53178ef5e7de53a83cc | [
"BSD-2-Clause"
]
| permissive | dvvrd/rosette | 861b0c4d1430a02ffe26c6db63fd45c3be4f04ba | 82468bf97d65bde9795d82599e89b516819a648a | refs/heads/master | 2021-01-11T12:26:01.125551 | 2017-01-25T22:24:27 | 2017-01-25T22:24:37 | 76,679,540 | 2 | 0 | null | 2016-12-16T19:23:08 | 2016-12-16T19:23:07 | null | UTF-8 | Racket | false | false | 4,664 | rkt | dependencies.rkt | #lang racket
; This module controls read and write dependencies of functions
; declared via define/unbound. Read dependencies are locations
; accessed with function or by one of its callees for reading.
; Write dependencies are locations updated by function body or
; by one of its callees.
(require
racket/generic
(only-in "../core/term.rkt" constant? define-operator type-of type-applicable? term<?)
(only-in "mutations.rkt" state->mutations symbolization->actual-value state=? source-location=? symbolization-of-head sort/states)
(only-in "utils.rkt" terms->constants)
(only-in "call-graph.rkt" make-associations associate associated? reset-associations-cache fold/reachable))
(provide gen:implicitly-dependent
(rename-out [get-implicit-dependencies implicit-dependencies])
read-dependencies/original read-dependencies/current
write-dependencies write-dependencies-states
set-up-read-dependencies set-up-write-dependencies
read-dependencies-ready? dependent-app associate-id)
; This generics can be implemented to provide implicit dependencies
; for the implementor. Implicit dependencies are the symbolic constants
; that will be used in the final symbolic expression for horn-clauses
; containing the implementor. If such implementor is passed as argument
; then implicit dependencies should not be added into functions's read
; dependencies (cause they are essentially implicit arguments of the funciton).
(define-generics implicitly-dependent
[implicit-dependencies implicitly-dependent instance])
(define (get-implicit-dependencies obj)
(if (implicitly-dependent? (type-of obj))
(implicit-dependencies (type-of obj) obj)
(list)))
(define constants-to-ids (make-hash))
(define read-dependencies-cache (make-associations))
(define write-dependencies-cache (make-associations))
(define (write-dependencies-states f)
(sort/states
(fold/reachable write-dependencies-cache
(constant->id f)
write-dependencies-union)))
(define (write-dependencies f)
(state->mutations (write-dependencies-states f)))
(define (read-dependencies/original f)
(sort
(map (curry symbolization-of-head f)
(fold/reachable read-dependencies-cache (constant->id f) read-dependencies-union))
term<?))
(define (read-dependencies/current f)
(map symbolization->actual-value (read-dependencies/original f)))
(define (associate-id id constant)
(hash-set! constants-to-ids constant id))
(define (constant->id constant)
(hash-ref constants-to-ids constant constant))
(define (set-up-write-dependencies f mutations-state)
(reset-associations-cache write-dependencies-cache)
(associate write-dependencies-cache (constant->id f) mutations-state))
(define (set-up-read-dependencies f body args scope mutations-state)
(reset-associations-cache read-dependencies-cache)
(let* ([args-implicit-dependencies (list->set
(apply append
(map get-implicit-dependencies args)))]
[mutations (state->mutations mutations-state)]
[constants (terms->constants (cons body mutations))]
[global-constants (filter (λ (v) (global-var? v args scope args-implicit-dependencies))
(set->list constants))])
(associate read-dependencies-cache (constant->id f) global-constants)))
(define (read-dependencies-ready? f)
(associated? read-dependencies-cache (constant->id f)))
; Wraps usual @app providing additional specification of state dependencies
; and mutations that @app results.
(define-operator dependent-app
#:identifier 'dependent-app
#:range (λ (expr read-dependencies write-dependencies) (type-of expr))
#:unsafe (λ (expr read-dependencies write-dependencies) expr))
(define (argument? v [args #f])
(and args (member v args)))
(define (local-var? v [scope #f])
(and scope (set-member? scope v)))
(define (implicit-dependence? v [implicit-dependencies #f])
(and implicit-dependencies (set-member? implicit-dependencies v)))
(define (global-var? v [args #f] [scope #f] [implicit-dependencies #f])
(and (constant? v)
(not (or (argument? v args)
(type-applicable? (type-of v))
(local-var? v scope)
(implicit-dependence? v implicit-dependencies)))))
(define (read-dependencies-union d1 d2)
(remove-duplicates (append d1 d2)
(λ (s1 s2) (or (equal? s1 s2)
(source-location=? s1 s2)))))
(define (write-dependencies-union d1 d2)
(remove-duplicates (append d1 d2) state=?))
| false |
6e20e7ce6a3c89747d39230215342811879e30c4 | e7ff3064339bd812c3074fdbee2e98f3b7cfcac0 | /grade-template.rkt | 5da2ab10588a09325fefb8ee7e6fc65a1fbe84e4 | []
| no_license | rebelsky/gradescope-racket | fe3333fe324676d8b275ea014f8d53a1f012885c | 56aacb9caf6d0d233d9e267c6e7a4ba216fde073 | refs/heads/master | 2022-12-19T09:12:07.012137 | 2020-09-27T15:16:21 | 2020-09-27T15:16:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 855 | rkt | grade-template.rkt | #lang racket
(require rackunit) ;; WARNING: Use the test- forms, NOT the check- forms!
(require "lib-grade.rkt")
;; Use as many
;; (define-var <varname> from <filename>)
;; as needed to obtain the variables you want to test.
;; <filename> should be whatever name you asked them to use
;; in their submission. Each <varname> should be a name
;; that you expected them to provide in their assignment.
;; Yes, from is a keyword, it should be there, literally.
(define-var VAR-NAME from FILE-NAME)
;; Now define your tests.
;; The suite name can be anything you want.
;; For the individual tests, use the test-* forms in
;; https://docs.racket-lang.org/rackunit/api.html
(define-test-suite SUITE-NAME
TEST
;; write your tests here
;; using test-* forms.
TEST
…)
;; Naturally, use the same suite name here.
(generate-results SUITE-NAME)
| false |
87a4bbee0daa776e6a097e7534bcce721027f7a9 | 4f38151796c7a569f6b439721db15b27a5862ee1 | /bezier/math.rkt | a76aff78329d396124e50ac293a13b74bdc82c66 | []
| no_license | piotrklibert/bezier | 83fb3867004ef61c4d408128c7921d9a47870c4c | 2db46e1b45396a81c7a42a87054f3a72324ca781 | refs/heads/master | 2021-06-16T16:33:36.836656 | 2013-02-21T22:31:12 | 2013-02-21T22:31:12 | 7,934,340 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 6,393 | rkt | math.rkt | #lang racket
(require
racket/flonum
racket/performance-hint)
(provide
;; not really contracted for performance, don't fix
apply/bez ; (flonum? (vector/c flonum? flonum? flonum? flonum?) . -> . flonum?)
apply/deriv ; (flonum? (vector/c flonum? flonum? flonum? flonum?) . -> . flonum?)
distance ; (flonum? flonum? flonum? flonum? . -> . flonum? )
)
;;================================================================================
;; Everything defined inside a begin-encourage-inline should
;; be inlined, even when called from outside of this module.
(begin-encourage-inline
;; I have no idea why is that, but when I place this function in
;; the bezier-point module (it's used only there) then it's
;; performance drops significantly...
;; TODO: figure out what is happenning.
(define (distance x1 y1 x2 y2)
(let
([x (fl- x1 x2)]
[y (fl- y1 y2)])
(flsqrt (fl+ (fl* x x)
(fl* y y))))))
(begin-encourage-inline
;; Early, non-optimised functions for computing bezier curve points and
;; angles (derivative). They are used in unit tests where their results
;; are compared with newer, optimised ones.
(define-syntax-rule (square n) (* n n))
(define (naive-bezier^2 t a b c)
(let* ([one-minus-t (- 1 t)])
(+ (* (square one-minus-t) a) (* one-minus-t t b 2) (* (square t) c))))
(define (naive-bezier^3 t a b c d)
(+ (* (- 1 t) (naive-bezier^2 t a b c))
(* t (naive-bezier^2 t b c d))))
(define (naive-deriv^2 t a b c)
(+ (* 2 (- 1 t) (- b a))
(* 2 t (- c b))))
(define (naive-deriv^3 t a b c d)
(let
([t-minus-one (- t 1.0)])
(* (- 3) (+ (* a (square t-minus-one)) (* b (+ (* (- 3.0) (square t)) (* 4.0 t) (- 1.0)))
(* t (- (* 3.0 c t) (* 2.0 c) (* d t)))))))
;;================================================================================
;; Optimised functions for bezier curve computations. These are actually used and
;; exported.
(define (bezier^2 t a b c)
(define 1-t (fl- 1.0 t))
(fl+ (fl+ (fl* (fl* 1-t 1-t) a) (fl* (fl* 1-t t) (fl* b 2.0))) (fl* (fl* t t) c)))
(define (bezier^3 t a b c d)
(let*
([1-t (fl- 1.0 t)]
[1-t^2 (fl* 1-t 1-t)]
[t^2 (fl* t t)])
(fl+ (fl* 1-t (fl+ (fl+ (fl* 1-t^2 a) (fl* (fl* 1-t t) (fl* b 2.0))) (fl* t^2 c)))
(fl* t (fl+ (fl+ (fl* 1-t^2 b) (fl* (fl* 1-t t) (fl* c 2.0))) (fl* t^2 d))))))
(define (deriv^3 t a b c d)
(let
([t-minus-1 (fl- t 1.0)])
(fl* -3.0
(fl+ (fl+ (fl* a (fl* t-minus-1 t-minus-1))
(fl* b (fl- (fl+ (fl* -3.0 (fl* t t)) (fl* 4.0 t)) 1.0)))
(fl* t (fl- (fl- (fl* 3.0 (fl* c t)) (fl* 2.0 c)) (fl* d t)))))))
;;================================================================================
;; Wrappers accepting a vector of points instead of points directly,
;; because the points are usually stored in a vector.
(define-syntax-rule (nth vec pos) (vector-ref vec pos))
(define (apply/bez t pts)
(bezier^3 t
(nth pts 0)
(nth pts 1)
(nth pts 2)
(nth pts 3)))
(define (apply/deriv t pts)
(deriv^3 t
(nth pts 0)
(nth pts 1)
(nth pts 2)
(nth pts 3)))
)
(module+ test
(require rackunit)
(test-case
"Test basic mathematical operations"
(check-equal? (square 45) 2025)
;; '(3 4 5) being pythagorean triple
(check-equal? (distance 0.0 0.0 3.0 4.0) 5.0))
(test-case
"bezier^3 degenerate case"
(check-equal? (bezier^2 0.25 0.0 5.0 10.0) 2.5))
(test-case
"bezier^3 degenerate case"
(check-equal? (bezier^3 0.5 0.0 5.0 10.0 15.0) 7.5))
(test-case
"Are bezier^2 results the same as naive-bezier^2?"
(for
([t (in-range 0 1 0.001)])
(let
([t (real->double-flonum t)])
(check-equal? (inexact->exact (bezier^2 t 20.0 30.0 40.0 ))
(inexact->exact (naive-bezier^2 t 20.0 30.0 40.0 ))))))
(test-case
"Are bezier^3 results the same as naive-bezier^3?"
(for
([t (in-range 0 1 0.001)])
(let
([t (real->double-flonum t)])
(check-equal? (inexact->exact (bezier^3 t 20.0 30.0 40.0 120.0))
(inexact->exact (naive-bezier^3 t 20.0 30.0 40.0 120.0))))))
(test-case
"Naive and optimized bezier derivative"
(for
([t (in-range 0 1 0.001)])
(let
([t (real->double-flonum t)])
#;(displayln (format "~a ~a"
(exact->inexact (deriv^3 t 20.0 30.0 40.0 120.0))
(exact->inexact (naive-deriv^3 t 20.0 30.0 40.0 120.0))))
;; TODO: why do they differ by such a tiny value? Are they of different types
;; like flonum vs. single flonum or something?
(check-= (exact->inexact (deriv^3 t 20.0 30.0 40.0 120.0))
(exact->inexact (naive-deriv^3 t 20.0 30.0 40.0 120.0))
0.0001))))
(displayln "Computing bezier^3 10000000 times took:")
(time (for ([_ (in-range 10000000)])
(bezier^3 0.2345 20.0 30.0 40.0 120.0)))
(displayln "Computing naive-bezier^3 1000000 times took:")
(time (for ([_ (in-range 1000000)])
(naive-bezier^3 0.2345 20.0 30.0 40.0 120.0)))
(displayln "Computing deriv^3 10000000 times took:")
(time (for ([_ (in-range 10000000)])
(deriv^3 0.2345 20.0 30.0 40.0 120.0)))
(displayln "Computing naive-deriv^3 10000000 times took:")
(time (for ([_ (in-range 10000000)])
(naive-deriv^3 0.2345 20.0 30.0 40.0 120.0)))
)
#|
Using MATCH is not the best idea and using list instead of vector is similarly bad.
Here's why:
(define l (list 4 5 6 7))
(define v (vector 4 5 6 7))
(define (t1 l)
(match l
[(list a b c d)
(values a b c d)]))
(define (t2 l)
(values (list-ref l 0)
(list-ref l 1)
(list-ref l 2)
(list-ref l 3)))
(define (t3 v)
(values (vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)
(vector-ref v 3)))
(time (for ([_ (in-range 10000000)])
(t1 l)))
(time (for ([_ (in-range 10000000)])
(t2 l)))
(time (for ([_ (in-range 10000000)])
(t3 v)))
|# | true |
9df32f2b78ae817c6b3c2b15ca8651a9bda4c7c4 | 4016b36583cdc169e9b8afced5d83fe98b18bca5 | /pr_peephole-check.rkt | ed1cfb402d06800839094e77ceec4898e64a3565 | [
"MIT"
]
| permissive | mcoram/primrec | 39478e512f147e6e0c5bd299590e9b97c976e1e9 | 1255c7f0b78ade4a3a59bfcf1128d2763f650403 | refs/heads/master | 2021-01-19T14:06:47.787267 | 2013-09-06T20:29:06 | 2013-09-06T20:29:06 | 11,691,853 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,472 | rkt | pr_peephole-check.rkt | #lang racket
(require racket/match)
(provide peephole-check)
(define (peephole-check t)
(match t
[`{C10 P11 ,f} f]
[`{C11 P11 ,f} f]
[`{C11 ,f P11} f]
[`{C21 P21 ,f ,a} f]
[`{C21 P22 ,a ,f} f]
[`{C31 P31 ,f ,a ,b} f]
[`{C31 P32 ,a ,f ,b} f]
[`{C31 P33 ,a ,b ,f} f]
[`{C11 (R0 P21 0) (C11 S ,f)} f] ;decrement the increment of the result of f
[_ null]))
; More candidates.
;[`{C22 P21 ,f ,a} f]
;[`{C22 P22 ,a ,f} f]
;[`{C33 P31 ,f ,a ,b} f]
;[`{C33 P32 ,a ,f ,b} f]
;[`{C33 P33 ,a ,b ,f} f]
; C23 and C32 also?
; C13 P11
; I nearly added this rule, but it's not true unless (f 0)==0. (it'd be true generally if (C10 ,f 0) was in place of the 0, but it's too complex)
; [`{R0 (C12 S (C12 ,f P21)) 0} f]
;(peephole-check '(C11 P11 (C11 P11 (R0 (C12 S (C12 (R0 (R1 (C13 S P32) S) 0) P22)) 0))))
;(peephole-check '(R0 (C12 S (C12 (R0 (R1 (C13 S P32) S) 0) P22)) 0))
;(peephole-check '(R0 (C12 S (C12 (R0 (C12 (R0 (R1 (C13 S P32) S) 0) (C12 S P22)) 0) P21)) 0))
(define (test-peephole-check)
(define fin (open-input-file "misc_peephole_cases.txt"))
(define line null)
(define (loop)
(set! line (read fin))
(when (not (eof-object? line))
(if (null? (peephole-check (third line)))
(printf "no peephole: ~a\n" (third line))
(printf " peephole: ~a\n" (third line)))
(loop)))
(loop))
;(test-peephole-check) ; we catch a lot of the repeats but may be missing quite a few yet.
| false |
4eeb6e667f37aa775427bb326916213a928ea4d9 | f6bbf5befa45e753077cf8afc8f965db2d214898 | /ASTBenchmarks/class-compiler/tests/tests.rkt | f32357e3b1f684719b071b9802deeef79c4bcd18 | []
| no_license | iu-parfunc/gibbon | 4e38f1d2d0526b30476dbebd794f929943f19f12 | 45f39ad0322cd7a31fe04922ad6bf38e6ac36ad6 | refs/heads/main | 2023-08-31T11:39:58.367737 | 2023-08-30T23:44:33 | 2023-08-30T23:44:38 | 58,642,617 | 139 | 23 | null | 2023-09-12T20:40:48 | 2016-05-12T13:10:41 | C | UTF-8 | Racket | false | false | 2,203 | rkt | tests.rkt | #lang racket
(require racket/runtime-path)
(require "test-uniqify.rkt")
(require "test-flatten.rkt")
(require "test-compiler.rkt")
(require "../parse.rkt")
(require "../compiler.gib")
(require "../common.gib")
(require rackunit)
;; TODO: write a parser for R0 so that we can re-use all tests from the class
(define tests
(list uniqify-tests
flatten-tests
compiler-tests))
(define (run-tests)
(let* ([test-results (append-map run-test tests)]
[num-test-results (length test-results)]
[failures (map test-result-test-case-name (filter-not test-success? test-results))])
(inspect-results failures num-test-results "tests")))
;; run examples
(define-runtime-path examples-dir "examples")
;; no support for (read) yet ..
(define ignored-examples
(for/set ([p '("r0_1.rkt" "r0_2.rkt" "r0_3.rkt" "r1_9.rkt" "r1_10.rkt" "r1_19.rkt"
"r1_13.rkt" "r1_15.rkt" "r1a_4.rkt" "r1a_5.rkt" "r1a_6.rkt"
;; actual failure
"r1a_8.rkt")])
(build-path examples-dir p)))
(define (run-example e)
(let* ([parsed (parse e)]
[out-path (path-replace-extension e ".out")]
[expected (if (file-exists? out-path)
(file->value out-path)
42)]
[actual (compile parsed)])
(and (equal? actual expected)
(file-name-from-path e))))
(define (run-examples)
(define test-results
(for/list ([f (in-directory examples-dir)]
#:when (equal? (path-get-extension f) #".rkt")
#:unless (set-member? ignored-examples f))
(run-example f)))
(define num-test-results (length test-results))
(define failures (map path->string (filter-not values test-results)))
(inspect-results failures num-test-results "examples"))
(define (inspect-results xs num-test-results type)
(if (empty? xs)
(printf "All ~a ~a passed.\n" num-test-results type)
(begin (printf "~s/~s ~a failed.\n~a\n"
(length xs)
num-test-results
type
(string-join xs "\n"))
(exit 1))))
(module+ main
(run-tests)
(run-examples))
| false |
5c16b6ff36c922e29c5bd0066f6cc682864fa86c | 804e0b7ef83b4fd12899ba472efc823a286ca52d | /old/gst/gstreamer/gst/GstIterator-ffi.rkt | f3c5dfb7f2c79bd95257be0762b44f52c0fde352 | []
| no_license | cha63506/CRESTaceans | 6ec436d1bcb0256e17499ea9eccd5c034e9158bf | a0d24fd3e93fc39eaf25a0b5df90ce1c4a96ec9b | refs/heads/master | 2017-05-06T16:59:57.189426 | 2013-10-17T15:22:35 | 2013-10-17T15:22:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 4,377 | rkt | GstIterator-ffi.rkt | #lang racket
(require ffi/unsafe)
(require "gst_base.rkt"
"gst-structs-ffi.rkt")
(provide (all-defined-out))
#|typedef enum {
GST_ITERATOR_ITEM_SKIP = 0,
GST_ITERATOR_ITEM_PASS = 1,
GST_ITERATOR_ITEM_END = 2
} GstIteratorItem;|#
(define GST_ITERATOR_ITEM_SKIP 0)
(define GST_ITERATOR_ITEM_PASS 1)
(define GST_ITERATOR_ITEM_END 2)
#|typedef enum {
GST_ITERATOR_DONE = 0,
GST_ITERATOR_OK = 1,
GST_ITERATOR_RESYNC = 2,
GST_ITERATOR_ERROR = 3
} GstIteratorResult;|#
(define GST_ITERATOR_DONE 0)
(define GST_ITERATOR_OK 1)
(define GST_ITERATOR_RESYNC 2)
(define GST_ITERATOR_ERROR 3)
;void (*GstIteratorDisposeFunction) (gpointer owner);
(define GstIteratorDisposeFunction (_cprocedure (list _gpointer) _void))
;GstIteratorResult (*GstIteratorNextFunction) (GstIterator *it, gpointer *result);
(define GstIteratorNextFunction (_cprocedure (list _GstIterator-pointer (_ptr io _gpointer)) _int))
;GstIteratorItem (*GstIteratorItemFunction) (GstIterator *it, gpointer item);
(define GstIteratorItemFunction (_cprocedure (list _GstIterator-pointer _gpointer) _int))
;void (*GstIteratorResyncFunction) (GstIterator *it);
(define GstIteratorResyncFunction (_cprocedure (list _GstIterator-pointer) _void))
;void (*GstIteratorFreeFunction) (GstIterator *it);
(define GstIteratorFreeFunction (_cprocedure (list _GstIterator-pointer) _void))
;gboolean (*GstIteratorFoldFunction) (gpointer item, GValue *ret, gpointer user_data);
(define GstIteratorFoldFunction (_cprocedure (list _gpointer _GValue-pointer _gpointer) _gboolean))
;gpointer (*GstCopyFunction) (gpointer object);
(define GstCopyFunction (_cprocedure (list _gpointer) _gpointer))
#|#define GST_ITERATOR (it)
#define GST_ITERATOR_LOCK (it)
#define GST_ITERATOR_COOKIE (it)
#define GST_ITERATOR_ORIG_COOKIE (it)|#
;GstIterator* gst_iterator_new (guint size, GType type, GMutex *lock, guint32 *master_cookie, GstIteratorNextFunction next, GstIteratorItemFunction item, GstIteratorResyncFunction resync, GstIteratorFreeFunction free);
(define-gstreamer gst_iterator_new (_fun _guint _GType _GMutex-pointer _guint32 GstIteratorNextFunction GstIteratorItemFunction GstIteratorResyncFunction GstIteratorFreeFunction -> _GstIterator-pointer))
;GstIterator* gst_iterator_new_list (GType type, GMutex *lock, guint32 *master_cookie, GList **list, gpointer owner, GstIteratorItemFunction item, GstIteratorDisposeFunction free);
(define-gstreamer gst_iterator_new_list (_fun _GType _GMutex-pointer _guint32 (_ptr io _GList-pointer) _gpointer GstIteratorItemFunction GstIteratorDisposeFunction -> _GstIterator-pointer))
;GstIterator* gst_iterator_new_single (GType type, gpointer object, GstCopyFunction copy, GFreeFunc free);
(define-gstreamer gst_iterator_new_single (_fun _GType _gpointer GstCopyFunction GFreeFunc -> _GstIterator-pointer))
;GstIteratorResult gst_iterator_next (GstIterator *it, gpointer *elem);
(define-gstreamer gst_iterator_next (_fun _GstIterator-pointer (_ptr io _gpointer) -> _int))
;void gst_iterator_push (GstIterator *it, GstIterator *other);
(define-gstreamer gst_iterator_push (_fun _GstIterator-pointer _GstIterator-pointer -> _void))
;GstIterator* gst_iterator_filter (GstIterator *it, GCompareFunc func, gpointer user_data);
(define-gstreamer gst_iterator_filter (_fun _GstIterator-pointer GCompareFunc _gpointer -> _GstIterator-pointer))
;GstIteratorResult gst_iterator_fold (GstIterator *it, GstIteratorFoldFunction func, GValue *ret, gpointer user_data);
(define-gstreamer gst_iterator_fold (_fun _GstIterator-pointer GstIteratorFoldFunction _GValue-pointer _gpointer -> _int))
;GstIteratorResult gst_iterator_foreach (GstIterator *it, GFunc func, gpointer user_data);
(define-gstreamer gst_iterator_foreach (_fun _GstIterator-pointer GFunc _gpointer -> _int))
;gpointer gst_iterator_find_custom (GstIterator *it, GCompareFunc func, gpointer user_data);
(define-gstreamer gst_iterator_find_custom (_fun _GstIterator-pointer GCompareFunc _gpointer -> _gpointer))
| false |
ccb7bea5faa28e433a2a3f7ec6c52cb3dd3cdde6 | 6b8bee118bda956d0e0616cff9ab99c4654f6073 | /doc/htdp/32.2.rkt | bd8dc7f5033cefd7700e3576654319a159ebe36e | []
| no_license | skchoe/2012.Functional-GPU-Programming | b3456a92531a8654ae10cda622a035e65feb762d | 56efdf79842fc465770214ffb399e76a6bbb9d2a | refs/heads/master | 2016-09-05T23:42:36.784524 | 2014-05-26T17:53:34 | 2014-05-26T17:53:34 | 20,194,204 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 7,743 | rkt | 32.2.rkt | #lang racket
(define MC 3)
(define BOAT-CAPACITY 2)
;data represeentation :
; boat is either 's or 'e, other field are all number
(define-struct rc (s-m s-c boat e-m e-c))
(define (echo-rc rc)
(printf (string-append "start-m:~a, c:~a\tboat:~a\tend-m:~a, c:~a\t----------------\n")
(rc-s-m rc) (rc-s-c rc)
(rc-boat rc)
(rc-e-m rc) (rc-e-c rc)))
(define (echo-rc/list lst-rc)
(for-each echo-rc lst-rc))
(define BOAT-LOAD '()) ; list of possible boat load.
(define (make-BOAT-LOAD cap)
(build-list 1 cons))
(define (sub2 x)
(- x 2))
(define (add2 x)
(+ x 2))
;;Exercise 32.2.3.
(define (state->list-successor state)
(local
[(define (new-boat b)
(cond [(symbol=? b 's) 'e]
[(symbol=? b 'e) 's]))
(define (boat-ship-1 m c b)
(cond
[(symbol=? b 's)
(cond
[(and (< 0 m) (< 0 c) (<= m MC) (<= c MC))
(list (make-rc (sub1 m) c (new-boat b) (add1 (- MC m)) (- MC c))
(make-rc m (sub1 c) (new-boat b) (- MC m) (add1 (- MC c))))]
[(and (not (zero? m)) (zero? c)) (list (make-rc (sub1 m) c (new-boat b) (add1 (- MC m)) (- MC c)))]
[(and (zero? m) (not (zero? c))) (list (make-rc m (sub1 c) (new-boat b) (- MC m) (add1 (- MC c))))]
[else '()])]
[(symbol=? b 'e)
(cond
[(and (< 0 m) (< 0 c) (<= m MC) (<= c MC))
(list (make-rc (add1 (- MC m)) (- MC c) (new-boat b) (sub1 m) c)
(make-rc (- MC m) (add1 (- MC c)) (new-boat b) m (sub1 c)))]
[(and (not (zero? m)) (zero? c)) (list (make-rc (add1 (- MC m)) (- MC c) (new-boat b) (sub1 m) c))]
[(and (zero? m) (not (zero? c))) (list (make-rc (- MC m) (add1 (- MC c)) (new-boat b) m (sub1 c)))]
[else (error "err2")])]))
(define (boat-ship-2 m c b)
(cond
[(symbol=? b 's)
(cond
[(and (<= 2 m) (<= 2 c) (<= m MC) (<= c MC))
(list (make-rc (sub2 m) c (new-boat b) (add2 (- MC m)) (- MC c))
(make-rc m (sub2 c) (new-boat b) (- MC m) (add2 (- MC c)))
(make-rc (sub1 m) (sub1 c) (new-boat b) (add1 (- MC m)) (add1 (- MC c))))]
[(and (<= 2 m) (not (<= 2 c)) (and (<= 1 m) (<= 1 c)))
(list (make-rc (sub2 m) c (new-boat b) (add2 (- MC m)) (- MC c))
(make-rc (sub1 m) (sub1 c) (new-boat b) (add1 (- MC m)) (add1 (- MC c))))]
[(and (not (<= 2 m)) (<= 2 c) (and (<= 1 m) (<= 1 c)))
(list (make-rc m (sub2 c) (new-boat b) (- MC m) (add2 (- MC c)))
(make-rc (sub1 m) (sub1 c) (new-boat b) (add1 (- MC m)) (add1 (- MC c))))]
[(and (<= 1 m) (<= 1 c))
(list (make-rc (sub1 m) (sub1 c) (new-boat b) (add1 (- MC m)) (add1 (- MC c))))]
[else (error "err3")])]
[(symbol=? b 'e)
(cond
[(and (<= 2 m) (<= 2 c) (<= m MC) (<= c MC))
(list (make-rc (add2 (- MC m)) (- MC c) (new-boat b) (sub2 m) c)
(make-rc (- MC m) (add2 (- MC c))(new-boat b) m (sub2 c) )
(make-rc (add1 (- MC m)) (add1 (- MC c)) (new-boat b) (sub1 m) (sub1 c)))]
[(and (<= 2 m) (<= 1 m) (<= 1 c))
(list (make-rc (add2 (- MC m)) (- MC c) (new-boat b) (sub2 m) c)
(make-rc (add1 (- MC m)) (add1 (- MC c)) (new-boat b) (sub1 m) (sub1 c)))]
[(and (<= 2 c) (<= 1 m) (<= 1 c))
(list (make-rc (- MC m) (add2 (- MC c)) (new-boat b) m (sub2 c))
(make-rc (add1 (- MC m)) (add1 (- MC c)) (new-boat b) (sub1 m) (sub1 c)))]
[(and (<= 1 m) (<= 1 c))
(list (make-rc (add1 (- MC m)) (add1 (- MC c)) (new-boat b) (sub1 m) (sub1 c)))]
[else '()])]))]
(let* ([s-m (rc-s-m state)]
[s-c (rc-s-c state)]
[boat (rc-boat state)]
[e-m (rc-e-m state)]
[e-c (rc-e-c state)]
[direct-next
(cond
[(symbol=? boat 's)
(append (boat-ship-1 s-m s-c boat) (boat-ship-2 s-m s-c boat))]
[(symbol=? boat 'e)
(append (boat-ship-1 e-m e-c boat) (boat-ship-2 e-m e-c boat))]
[else (error "other boat side?")])])
(filter legal? direct-next))))
;;Exercise 32.2.3.
;; lst-state -> list of lst-state
(define (state->list-successor/list lst-state)
(cond
[(empty? lst-state) '()]
[else
(cons (state->list-successor (first lst-state)) (state->list-successor/list (rest lst-state)))]))
(define (equal? s1 s2)
(if (and (equal? (rc-s-m s1) (rc-s-m s2))
(equal? (rc-s-c s1) (rc-s-c s2))
(symbol=? (rc-boat s1) (rc-boat s2))
(equal? (rc-e-m s1) (rc-e-m s2))
(equal? (rc-e-c s1) (rc-e-c s2)))
#t
#f))
;;Exercise 32.2.4.
(define (legal? state)
(let* ([s-m (rc-s-m state)]
[s-c (rc-s-c state)]
[boat (rc-boat state)]
[e-m (rc-e-m state)]
[e-c (rc-e-c state)])
(cond
[(< MC s-m) #f]
[(< MC s-c) #f]
[(< MC e-m) #f]
[(< MC e-c) #f]
[(< s-m s-c) #f]
[(< e-m e-c) #f]
[else state])))
;Exercise 32.2.5.
(define (final? state)
(let* ([s-m (rc-s-m state)]
[s-c (rc-s-c state)]
[boat (rc-boat state)]
[e-m (rc-e-m state)]
[e-c (rc-e-c state)])
(cond
[(and (equal? MC e-m) (equal? MC e-c)) state]
[else #f])))
;; list of state -> #f or final state
(define (contains-final? lst-state)
(ormap final? lst-state))
;Exercise 32.2.6.
;; state -> #f or
(define (mc-solvable? init-state)
(local [;; output #f or list of state having path to solution
(define (local-solvable?/list lst-state acc)
(cond
[(empty? lst-state) acc]
[else
(let* ([final-state (contains-final? lst-state)])
(cond
[final-state (cons final-state acc)]
[else
(let* ([first-state (first lst-state)]
[lst-succ (state->list-successor first-state)]
[final (local-solvable?/list lst-succ acc)])
(if (empty? final)
(local-solvable?/list (rest lst-state) acc)
(cons first-state final)))]))]))]
(cond
[(final? init-state) (list init-state)]
[else (let* ([result/list (local-solvable?/list (state->list-successor init-state) '())])
(cond
[(empty? result/list) #f]
[else
(cons init-state result/list)]))])))
(define (simple-solvable? init-state max-iter)
(let loop ([state init-state]
[iter 0])
(cond
[(equal? iter max-iter) (error "Not solvable")]
[else
(let* ([lst-next-state (state->list-successor state)])
(printf "iter:~a\t" iter)
(echo-rc/list lst-next-state)
(newline)
(cond
[(empty? lst-next-state) #f]
[(contains-final? lst-next-state) #t]
[else (ormap (λ (x) (boolean=? #t x))
(map loop lst-next-state (build-list (length lst-next-state) (λ (x) (add1 iter)))))]))])))
#;(define init-state (make-rc 0 3 's 3 0))
#;(echo-rc init-state)
(define init-state (make-rc 1 2 'e 2 1))
(echo-rc init-state)
(printf "--------XXXXXXXXXXX--\n")
(simple-solvable? init-state 10000)
#;(for-each echo-rc (mc-solvable? init-state))
;(define lst-succ (state->list-successor init-state))
;(for-each echo-rc lst-succ)
| false |
a2824104f814acf260b62d97faf336dd18225475 | 799b5de27cebaa6eaa49ff982110d59bbd6c6693 | /soft-contract/fake-contract.rkt | 72da463ebaf9a0a58669011a566eddadf0310bc5 | [
"MIT"
]
| permissive | philnguyen/soft-contract | 263efdbc9ca2f35234b03f0d99233a66accda78b | 13e7d99e061509f0a45605508dd1a27a51f4648e | refs/heads/master | 2021-07-11T03:45:31.435966 | 2021-04-07T06:06:25 | 2021-04-07T06:08:24 | 17,326,137 | 33 | 7 | MIT | 2021-02-19T08:15:35 | 2014-03-01T22:48:46 | Racket | UTF-8 | Racket | false | false | 10,671 | rkt | fake-contract.rkt | #lang racket/base
(require (except-in racket/contract
flat-contract
-> ->i case-> and/c or/c any/c none/c list/c listof struct/c ->* provide/contract
one-of/c =/c >/c >=/c </c <=/c between/c not/c cons/c box/c vector/c vectorof hash/c
parameter/c
parametric->/c
recursive-contract
define/contract
contract?)
(except-in racket/set set/c)
(for-syntax racket/base
racket/string
racket/syntax
syntax/parse
racket/pretty
"parse/utils.rkt"
typed-racket/base-env/type-name-error)
racket/contract/private/provide
racket/list
racket/splicing
syntax/parse/define
(prefix-in c: racket/contract/base)
(prefix-in c: (only-in racket/set set/c))
(prefix-in r: racket/base))
(provide (all-from-out racket/contract/base) provide
-> ->* ->i case-> struct/c provide/contract contract-out
parametric->/c
recursive-contract
(rename-out [c:any any])
dynamic-provide/contract
dynamic->i dynamic-case-> dynamic-parametric->/c
dynamic-struct/c
dynamic-recursive-contract
dynamic-struct-out
dynamic-id-struct-out
dynamic-define-opaque
define/contract dynamic-mon
(rename-out [-define define])
--> forall
(rename-out [--> ⇒] [forall ∀]))
(define-syntax (scv:ignore stx)
(syntax-case stx ()
[(_ s) (syntax-property #'s 'scv:ignore #t)]))
(define-syntax (struct/c stx)
(syntax-case stx ()
[(_ name cs ...)
(with-syntax-source stx
#'(begin (dynamic-struct/c name cs ...)
(scv:ignore (c:struct/c name cs ...))))]))
(define-syntax-rule (parametric->/c (x ...) c) (dynamic-parametric->/c (λ (x ...) c)))
(begin-for-syntax
(define-syntax-class dom
#:description "restricted dependent domain"
(pattern _:id+ctc))
(define-syntax-class rng
#:description "restricted dependent range"
(pattern (~literal any))
(pattern _:id+ctc)
(pattern _:un+ctc)
(pattern ((~literal values) _:id+ctc ...))
(pattern ((~literal values) _:un+ctc ...)))
(define-syntax-class id+ctc
#:description "named contract domain"
(pattern (_:id (_:id ...) _:expr))
(pattern (_:id _:expr)))
(define-syntax-class un+ctc
#:description "unnamed contract domain"
(pattern [(~literal _) _:expr])
(pattern [(~literal _) (_:id ...) _:expr])))
(splicing-local
((define-syntax re-export
(syntax-parser
[(_ x ...)
(with-syntax ([(c:x ...)
(for/list ([x (in-list (syntax->list #'(x ...)))])
(format-id x "c:~a" x))])
#'(begin (define x c:x) ...
(provide x ...)))])))
(re-export hash/c set/c contract? flat-contract
listof list/c cons/c box/c vector/c vectorof
any/c none/c and/c or/c one-of/c not/c false/c
=/c </c <=/c >/c >=/c between/c parameter/c))
(define-syntax dom-quote
(let ([gen-name (syntax-parser
[(~literal _) (generate-temporary '_)]
[x #'x])])
(syntax-parser
[(_ (~and stx (name (dep:id ...) ctc:expr)))
(with-syntax ([name* (gen-name #'name)])
(with-syntax-source #'stx
;; not explicitly using `#%plain-app` here results in ambiguous identifier error
;; TODO: find proper fix
#'(#%plain-app list #t 'name* (λ (dep ...) ctc))))]
[(_ (~and stx (name ctc:expr)))
(with-syntax ([name* (gen-name #'name)])
(with-syntax-source #'stx
;; not explicitly using `#%plain-app` here results in ambiguous identifier error
;; TODO: find proper fix
#'(#%plain-app list #f 'name* ctc )))])))
(define-syntax ->i
(syntax-parser
[(~and stx
(_ (c:dom ...)
(~optional (~seq #:rest rest:id+ctc)
#:defaults ([rest #'#f]))
d:rng
(~optional (~seq #:total? total?:boolean)
#:defaults ([total? #'#f]))))
(with-syntax-source #'stx
#`(begin
(dynamic->i (list (dom-quote c) ...)
#,(if (syntax-e #'rest) #'(dom-quote rest) #'#f)
#,(syntax-parse #'d
[(~literal c:any) #'#f]
[((~literal values) d ...) #'(list (dom-quote d) ...)]
[d #'(list (dom-quote d))])
total?)
(scv:ignore (c:->i (c ...) d))))]))
(define-syntaxes (-> ->*)
(let ([gen-dom
(λ (c)
(with-syntax ([x (generate-temporary '_)])
(with-syntax-source c #`(x #,c))))]
[gen-range-dom
(syntax-parser
[(~literal c:any) #'c:any]
[(~and r ((~literal values) d ...))
#`(values #,@(for/list ([dᵢ (in-list (syntax->list #'(d ...)))])
(with-syntax-source dᵢ #`(_ #,dᵢ))))]
[d (with-syntax-source #'d #'(_ d))])])
(values
(syntax-parser
[(~and stx (-> cs:expr ... result-c:expr (~optional (~seq #:total? total?:boolean)
#:defaults ([total? #'#f]))))
(with-syntax ([(dom ...) (map gen-dom (syntax->list #'(cs ...)))]
[rng (gen-range-dom #'result-c)])
(with-syntax-source #'stx
#'(->i (dom ...) rng #:total? total?)))])
(syntax-parser
[(~and stx (->* (cs:expr ...) #:rest rest-c:expr result-c:expr
(~optional (~seq #:total? total?:boolean)
#:defaults ([total? #'#f]))))
(with-syntax ([(dom-init ...) (map gen-dom (syntax->list #'(cs ...)))]
[dom-rest (gen-dom #'rest-c)]
[rng (gen-range-dom #'result-c)])
(with-syntax-source #'stx
#'(->i (dom-init ...) #:rest dom-rest rng #:total? total?)))]))))
(define-syntax case->
(syntax-parser
[(~and stx (_ clauses ...))
(with-syntax-source #'stx
#'(begin
(case->/acc () (clauses ...))
;; TODO can't enable below yet, because hacky expansion replaces `->` and `->*`
#;(scv:ignore (c:case-> clauses ...))))]))
(define-syntax case->/acc
(syntax-rules (c:any)
[(_ (ctcs ...) ())
(dynamic-case-> ctcs ...)]
[(_ (ctcs ...) ((_ init ... #:rest rest c:any) clauses ...))
(case->/acc (ctcs ... (list (list init ...) rest #f))
(clauses ...))]
[(_ (ctcs ...) ((_ init ... #:rest rest range) clauses ...))
(case->/acc (ctcs ... (list (list init ...) rest (list range)))
(clauses ...))]
[(_ (ctcs ...) ((_ init ... c:any) clauses ...))
(case->/acc (ctcs ... (list (list init ...) #f #f))
(clauses ...))]
[(_ (ctcs ...) ((_ init ... range) clauses ...))
(case->/acc (ctcs ... (list (list init ...) #f (list range)))
(clauses ...))]))
(define-syntax-rule (provide/contract [id ctc] ...)
(begin (dynamic-provide/contract (list id ctc) ...)
(scv:ignore (c:provide/contract [id ctc] ...))))
(define-for-syntax (not-macro? id)
(define id-val (syntax-local-value id (λ () #f)))
(or (not id-val) (provide/contract-info? id-val)))
(define-syntax (provide stx)
(syntax-parse stx #:literals (contract-out struct-out)
[(_ (~or i:id
(struct-out so:id)
(contract-out (~or [p/i:id ctc:expr]
;; TODO confirm that ignoring parent declaration makes no difference
[(~datum struct) (~and s* (~or s:id (s:id _:id))) ([ac:id dom:expr] ...)]) ...))
...)
#:with (i* ...) (filter not-macro? (syntax->list #'(i ...)))
(define (ids->str ids)
(string-join (map symbol->string (map syntax-e (syntax->list ids)))))
#;(unless (null? (syntax->list #'(i ...)))
(printf "Warning: ignore verifying: ~a~n" (ids->str #'(i ...))))
#;(unless (null? (syntax->list #'(so ...)))
(printf "Warning: ignore verifying `struct-out` form(s) for: ~a~n" (ids->str #'(so ...))))
#'(begin
;; Real stuff to preserve the program's meaning when run
(scv:ignore
(r:provide i ...
(struct-out so) ...
(contract-out [p/i ctc] ...
[struct s* ([ac dom] ...)] ...)
...))
;; Things to give to SCV for verification.
;; Ignore all non-contracted identifiers because they might be macros even.
;; Verifying against `any/c` doesn't mean much anyways
(dynamic-provide/contract
i* ...
(list p/i ctc) ... ...
(dynamic-id-struct-out 'so) ...
(dynamic-struct-out 's (list 'ac dom) ...) ... ...))]))
(define-syntax define/contract
(syntax-parser
[(_ (f x ...) c e ...)
(with-syntax ([rhs (with-syntax-source #'(f x ...)
#'(dynamic-mon 'f c (λ (x ...) e ...)))])
#'(define f rhs))]
[(_ x c e )
(with-syntax ([rhs (with-syntax-source #'x #'(dynamic-mon 'x c e))])
#'(define x rhs))]))
(define (dynamic-mon x c e) e)
(define-syntax -define
(syntax-parser
[(_ x:id #:opaque)
#'(begin
(scv:ignore (define x (λ () (error 'opaque))))
(dynamic-define-opaque x))]
[(~and stx (_ x ...))
(with-syntax-source #'stx #'(define x ...))]))
;; Phil's clueless hack for `recursive-contract`
(define-syntax-rule (recursive-contract x type ...)
(begin (dynamic-recursive-contract x '(type ...))
(scv:ignore (c:recursive-contract x type ...))))
;; Dummy stuff
(define (dynamic->i . _) (void))
(define (dynamic-struct/c . _) (void))
(define (dynamic-struct-out . _) (void))
(define (dynamic-id-struct-out _) (void))
(define (dynamic-parametric->/c v) v)
(define (dynamic-case-> . _) (void))
(define (dynamic-provide/contract . _) (void))
(define (dynamic-recursive-contract . _) (void))
(define (dynamic-define-opaque x) (void))
;; Syntactic sugar for theorem proving
(define-simple-macro
(--> ([x:id c] ...) d)
(->i ([x c] ...) (res (x ...) (λ _ d)) #:total? #t))
(define-simple-macro
(forall (α:id ...) e)
(c:parametric->/c (α ...) e))
| true |
e388c3546fd3a66d41bcdfe577d8615cef6a4fa4 | 8de3f562d9c8d89d1598c3b9d987c65d72aaa0f7 | /3.70~3.72.rkt | 4c49d28d928d8815680e705c2aae1b0966f42dcc | []
| no_license | tjuqxb/SICP | 17664460ef34cb325c3d5fde000cc989799ca89d | 4fb8400c0d779e3c555cc7a5d490436296cf25e3 | refs/heads/master | 2021-01-24T07:55:41.180817 | 2017-06-20T03:12:26 | 2017-06-20T03:12:26 | 93,363,899 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 3,341 | rkt | 3.70~3.72.rkt | (define (merge-weighted weight s1 s2)
(cond
((stream-null? s1) s2)
((stream-null? s2) s1)
((< (weight (stream-car s1))
(weight (stream-car s2)))
(cons-stream
(stream-car s1)
(merge-weighted weight (stream-cdr s1) s2)))
((< (weight (stream-car s2))
(weight (stream-car s1)))
(cons-stream
(stream-car s2)
(merge-weighted weight s1 (stream-cdr s2))))
((= (weight (stream-car s1))
(weight (stream-car s2)))
(if
(eq-s? (stream-car s1) (stream-car s2))
(cons-stream
(stream-car s1)
(merge-weighted weight (stream-cdr s1) (stream-cdr s2)))
(cons-stream
(stream-car s1)
(cons-stream
(stream-car s2)
(merge-weighted weight (stream-cdr s1) (stream-cdr s2))))))))
(define (eq-s? a b)
(and (= (car a) (car b))
(= (cadr a) (cadr b))))
(define ones
(cons-stream 1
ones))
(define ns
(cons-stream 1
(add-streams
ones
ns)))
(define (interleave s1 s2)
(if (stream-null? s1)
s2
(cons-stream (stream-car s1)
(interleave s2 (stream-cdr s1)))))
(define (ge2 S T)
(cons-stream (list (stream-car S)
(stream-car T))
(interleave
(stream-map
(lambda(x)
(list (stream-car S)
x))
(stream-cdr T))
(ge2 (stream-cdr S) (stream-cdr T)))))
(define int-s
(ge2 ns ns))
(define (weight-f1 m)
(+ (car m) (cadr m)))
(define answer1
(merge-weighted weight-f1 int-s int-s))
(define ff? a
(cond ((=0 (remainder a 2)) #t)
((=0 (remainder a 3)) #t)
((=0 (remainder a 5)) #t)
(else #f)))
(define ss
(stream-filter (lambda(x) ((or (ff? (car x))
(ff? (cadr x))))) int-s))
(define (weight-f2 x)
(+(* 2 (car x))
(* 3 (cadr x))
(* 5 (car x) (cadr x))))
(define answer2
(merge-weighted weight-f2 ss ss))
int-s
(define (weight-f3 x)
(+ (* (car x) (car x) (car x))
(* (cadr x) (cadr x) (cadr x))))
(define as3-pre
(merge-weighted weight-f3 int-s int-s))
(define (get-1 s)
(let ((m0 (stream-ref s 0))
(m1 (stream-ref s 1)))
(if (= (weight-f3 m0)
(weight-f3 m1))
(cons-stream
(weight-f3 m0)
(get-1
(stream-cdr
(stream-cdr s))))
(get-1
(stream-cdr s)))))
(define (simp s)
(let ((m0 (stream-ref s 0))
(m1 (stream-ref s 1))
(if (eq-s? m0 m1)
(simp (stream-cdr s))
(cons-stream
mo
(simp (stream-cdr s)))))))
(define as3
(simp (get-1 as3-pre)))
(define (weight-f4 x)
(+ (* (car x) (car x))
(* (cadr x) (cadr x))))
(define as4-pre
(merge-weighted weight-f4 int-s int-s))
(define (get2 s)
(let ((m0 (stream-ref s 0))
(m1 (stream-ref s 1))
(m2 (stream-ref s 2))
(if (and(= (weight-f4 m0)
(weight-f4 m1))
(= (weight-f4 m1)
(weight-f4 m2)))
(cons-stream
(list (weight-f3 m0) m0 m1 m2)
(get-1
(stream-cdr
(stream-cdr
(stream-cdr s)))))
(get-1
(stream-cdr s))))))
| false |
d7e5f817ca3e6751807b18e87ca1b1024ea810e3 | 52a4d282f6ecaf3e68d798798099d2286a9daa4f | /v22/old/numbo0/wheel.rkt | d27f0107b2a54a4af5bf3d59877d462fdfea70b9 | [
"MIT"
]
| permissive | bkovitz/FARGish | f0d1c05f5caf9901f520c8665d35780502b67dcc | 3dbf99d44a6e43ae4d9bba32272e0d618ee4aa21 | refs/heads/master | 2023-07-10T15:20:57.479172 | 2023-06-25T19:06:33 | 2023-06-25T19:06:33 | 124,162,924 | 5 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 3,049 | rkt | wheel.rkt | ; wheel.rkt -- Wheels to not reinvent
#lang debug at-exp racket
(require (for-syntax racket/syntax) racket/syntax)
(provide (all-defined-out))
(define empty-set (set))
(define empty-hash (hash))
(define (without-voids seq)
(for/list ([x seq] #:when (not (void? x)))
x))
(define (->list x)
(cond
[(pair? x) x]
[(hash? x) (hash->list x)]
[else x]))
(define (sorted xs)
(sort (->list xs) string<? #:key ~a))
(define (sorted-by-cdr ht)
(sort (->list ht) < #:key cdr))
(define-syntax (define-singleton stx)
(syntax-case stx ()
[(define-singleton name)
(with-syntax ([name? (format-id #'name "~a?" #'name
#:source #'name #:props #'name)])
#`(begin
(define name
(let ()
(struct name () #:prefab)
(name)))
(define (name? x)
(eq? name x))))]))
(define-syntax-rule (define-singletons name ...)
(begin
(define-singleton name) ...))
(define (hash-ref/sk ht key sk fk)
(let ([value (hash-ref ht key (void))])
(cond
[(void? value) (if (procedure? fk) (fk) fk)]
[else (sk value)])))
(define (hash-remove* h . keys)
(for/fold ([h h])
([key keys])
(hash-remove h key)))
(define (hash-map-values ht f)
(for/hash ([(k v) ht])
(values k (f v))))
(define (hash-by equiv-class xs)
(for/fold ([ht empty-hash] #:result (hash-map-values ht reverse))
([x xs])
(hash-update ht (equiv-class x) (λ (lst) (cons x lst)) '())))
(define (atom? x)
(and (not (null? x))
(not (pair? x))))
(define (safe-car x)
(match x
[`(,a . ,d) a]
[_ (void)]))
(define (safe-cdr x)
(match x
[`(,_ . ,d) d]
[_ (void)]))
(define (safe-last x)
(cond
[(pair? x) (last x)]
[else (void)]))
(define-syntax-rule (first-value expr)
(call-with-values (λ () expr)
(λ (result . ignored) result)))
(define (exactly-one? pred seq)
(= 1 (for/sum ([item seq])
(if (pred item) 1 0))))
(define (eq?? x)
(λ (x*) (eq? x x*)))
;; "Fills the void": if first argument is void, returns intersection of
;; remaining arguments.
;;
;; This is useful in for/set when you want the intersection of many sets:
;; (for/set ([st (void)]) (set-intersect* st ...)). If you started by setting
;; st to an empty set and calling set-intersect, the result would always be an
;; empty set.
;TODO UT
(define (set-intersect* set-or-void . sets)
(cond
[(void? set-or-void)
(if (null? sets)
set-or-void
(apply set-intersect* sets))]
[(null? sets)
set-or-void]
[else (apply set-intersect set-or-void sets)]))
;;;based on version by soegaard, https://stackoverflow.com/a/45545280/1393162
;(define-match-expander dict
; (λ (stx)
; (syntax-case stx ()
; [(_dict (
;; Doing this right looks very hard. The StackOverflow version doesn't call
;; dict-ref and consequently doesn't work for all values that support gen:dict.
;; It also doesn't match the whole dict analogously to hash-table.
| true |
87bc2e7ea9045b75020cd0c93f935dba0e810a0e | 3cb889e26a8e94782c637aa1126ad897ccc0d7a9 | /SICP/chapter_3/64.rkt | 3dd1091c7c3ee5b56752b304f6a472677adc7343 | []
| no_license | GHScan/DailyProjects | 1d35fd5d69e574758d68980ac25b979ef2dc2b4d | 52e0ca903ee4e89c825a14042ca502bb1b1d2e31 | refs/heads/master | 2021-04-22T06:43:42.374366 | 2020-06-15T17:04:59 | 2020-06-15T17:04:59 | 8,292,627 | 29 | 10 | null | null | null | null | UTF-8 | Racket | false | false | 364 | rkt | 64.rkt | #lang racket
(require "63.rkt")
(define (stream-limit s tolerance)
(let ((x (stream-ref s 0))(y (stream-ref s 1)))
(if (< (abs (- x y)) tolerance)
y
(stream-limit (stream-rest s) tolerance)))
)
(define (sqrt x tolerance)
(stream-limit (sqrt-stream x) tolerance)
)
(sqrt 2.0 0.0001)
(sqrt 3.0 0.0001)
(sqrt 4.0 0.0001)
(sqrt 5.0 0.0001)
| false |
6699a7af0bb4c03f1a8a05fa10e798b0c660d144 | ad2d689356289c7ba80d834b051a233bc437d4f9 | /commands/dr.rkt | 7033c5c517fe2d54adb275e0f6dddd493935c4b5 | []
| no_license | willghatch/dotfileswgh | c141fc256bdb5aa20edb45b1871007bfeebae4f4 | 4614c9d5ef16be411ad9f7cbcafec71060be2a8a | refs/heads/master | 2023-09-01T12:52:01.851093 | 2023-08-29T17:24:04 | 2023-08-29T17:24:04 | 15,466,845 | 5 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 3,857 | rkt | dr.rkt | #!/usr/bin/env racket
#lang racket/base
(require
racket/cmdline
racket/string
racket/file
json
setup/dirs
basedir
net/sendurl
)
(define browser "firefox")
(define same-terminal? #f)
(define search-term
(command-line
#:once-each
[("--browser") b "which browser to use" (set! browser b)]
[("--in-terminal") "launch the browser in the same terminal?"
(set! same-terminal? #t)]
#:args (term)
term
))
(struct sdata
(term url from)
#:transparent)
(define (doc-dir->search-data docdir)
(define path (build-path docdir "search/plt-index.js"))
(define indexf
(if (file-exists? path)
(open-input-file path)
(open-input-string "var plt_search_data = []")))
(void (regexp-match #px"var plt_search_data =" indexf))
;; this array has an entry of four items for each index link:
;; - text is a string holding the indexed text
;; - url holds the link (">" prefix means relative to plt_main_url)
;; - html holds either a string, or [idx, html] where idx is an
;; index into plt_span_classes (note: this is recursive)
;; - from_lib is an array of module names for bound identifiers,
;; or the string "module" for a module entry
(define search-data (read-json indexf))
(close-input-port indexf)
search-data)
(define (doc-dir->matches doc-dir)
(define search-data (doc-dir->search-data doc-dir))
(define search-matches (filter (λ (item) (regexp-match search-term (car item)))
search-data))
(define sorted-matches (sort search-matches <
#:key (λ (item) (string-length (car item)))
#:cache-keys? #t))
;; TODO - multi search term
;; TODO - maybe match approximate results (add things that don't match but are close)
(define (prefixed-url->url u)
(if (string-prefix? u ">")
(string-replace u ">" (string-append (path->string doc-dir) "/") #:all? #f)
u))
(define matches-with-urls
(map (λ (item) (sdata (car item)
(prefixed-url->url (cadr item))
(cadddr item)))
sorted-matches))
matches-with-urls)
(define (format-html matches)
(printf "<h1>matches:</h1>\n")
(map (λ (m) (printf "<p><a href=\"file://~a\">~a</a> from lib: ~a</p>\n"
(sdata-url m) (sdata-term m) (sdata-from m)))
matches))
(define outfile (writable-runtime-file
(string-append "racket-doc-search_"
search-term
"_"
(number->string (current-seconds))
".html")
#:program "racket-docs"))
(make-parent-directory* outfile)
(define outport (open-output-file outfile))
(void
(parameterize ([current-output-port outport])
(format-html (append (doc-dir->matches (find-doc-dir))
(doc-dir->matches (find-user-doc-dir))))))
(close-output-port outport)
(define (schedule-file-deletion)
(define-values (atproc out in err)
(subprocess #f
#f
#f
(find-executable-path "at")
"now" "+" "30" "minutes"))
(fprintf in "rm ~a" outfile))
(define (launch-terminal-browser b)
(define-values (sproc out in err)
(subprocess (current-output-port)
(current-input-port)
(current-error-port)
(find-executable-path b)
outfile))
(subprocess-wait sproc))
(if same-terminal?
(launch-terminal-browser browser)
(let ()
(define browser-setting (cons (string-append browser " ") ""))
(external-browser browser-setting)
(send-url (string-append "file://" (path->string outfile)))
(schedule-file-deletion)))
| false |
86650f6d79229a34aad5231551db3ef99854fe12 | 5dfeeeea0d845413f14fb9422c12395dd6835b17 | /new/threads/count.rkt | a0b89f038a530903085c199b0664f97f6079ab84 | []
| no_license | acieroid/racket-concurrency | 6cd7b0f0f29dcd637ec6407570fc3f93324b2f9d | bd0edeffd46aa15a8233357fb827895c6bd24d5f | refs/heads/master | 2020-05-18T00:15:45.588825 | 2019-05-06T14:16:12 | 2019-05-06T14:16:12 | 184,056,682 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,435 | rkt | count.rkt | #lang racket
(require "../threads.rkt")
(require "../abstract.rkt")
(define (map f l)
(if (pair? l)
(cons (f (car l)) (map f (cdr l)))
(if (null? l)
'()
(error "map applied to a non-list"))))
(define (counter)
(let ((lock (t/new-lock))
(state (t/ref 0)))
(lambda (op)
(if (equal? op 'inc)
(begin
(t/acquire lock)
(t/ref-set state (+ (t/deref state) 1))
(t/release lock))
(if (equal? op 'dec)
(begin
(t/acquire lock)
(t/ref-set state (- (t/deref state) 1))
(t/release lock))
(if (equal? op 'get)
(t/deref state)
(error "unknown operation")))))))
(define (thread cnt ops)
(if (= ops 0)
'done
(let ((op (random 3)))
(if (= op 0)
(cnt 'inc)
(if (= op 1)
(cnt 'dec)
(cnt 'get)))
(thread cnt (- ops 1)))))
(define NOPS (int-top))
(define (create-threads cnt n)
(letrec ((loop (lambda (i acc)
(if (= i n)
acc
(loop (+ i 1) (cons (t/spawn (thread cnt NOPS)) acc))))))
(loop 0 '())))
(define N (int-top))
(define cnt (counter))
(map (lambda (t) (t/join t))
(create-threads cnt N))
(display "result: ")
(display (cnt 'get))
(newline)
(t/display-recorded)
| false |
457dc2d39ba4e89e6aa9f8e2dd3221b1360cf13d | c9406c3155bbe80d9a144592e4e518ec678a3d47 | /play/thread-pool.rkt | 4d307fec856d0bc353894392cb4f00a699127689 | []
| no_license | joshcox/pKanren | 3509db186c0987039eb0d78957804e43ec534778 | d4613ab84c79c6ee9798cbcc54a66342e2221760 | refs/heads/master | 2020-05-05T02:48:45.011419 | 2014-12-14T13:46:44 | 2014-12-14T13:46:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,185 | rkt | thread-pool.rkt | #lang racket
;(require racket/threads)
(define (thread-pool n)
(lambda (proc items)
(define tasks (make-channel))
(define results (make-semaphore))
(define threads #f)
(dynamic-wind
(lambda () (set! threads
(build-list n
(lambda (i)
(thread
(lambda ()
(let f ()
(let ((v (channel-get tasks))) (proc v))
(semaphore-post results)
(f))))))))
(lambda ()
(for-each
(lambda (item)
(channel-put tasks item))
items)
(for-each
(lambda (item)
(semaphore-wait results))
items)
)
(lambda ()
(for-each
(lambda (t)
(kill-thread t)
(thread-wait t))
threads)))))
(define (example)
(define pool-for-each (thread-pool 20))
(pool-for-each
(lambda (i)
;(sleep 1)
(display i) (display "-")
(flush-output))
(build-list 100 (lambda (i) (- 100 i)))))
(provide thread-pool example)
| false |
81b49e157ee6a1b48aa6b2ad5a767b4f8fa4e029 | d755de283154ca271ef6b3b130909c6463f3f553 | /htdp-lib/teachpack/htdp/matrix.rkt | d42b89c16cbc185db414e92e09162b17d0980433 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Apache-2.0"
]
| permissive | racket/htdp | 2953ec7247b5797a4d4653130c26473525dd0d85 | 73ec2b90055f3ab66d30e54dc3463506b25e50b4 | refs/heads/master | 2023-08-19T08:11:32.889577 | 2023-08-12T15:28:33 | 2023-08-12T15:28:33 | 27,381,208 | 100 | 90 | NOASSERTION | 2023-07-08T02:13:49 | 2014-12-01T13:41:48 | Racket | UTF-8 | Racket | false | false | 77 | rkt | matrix.rkt | #lang racket/base
(require htdp/matrix)
(provide (all-from-out htdp/matrix))
| false |
2fc410ce16604aaba1612c4e0d07cb222c42b70b | 1261c45ca4f0b89c2099072839a084e70a6b49a2 | /planet/math/orbit.rkt | a9fb940f47084d034282504643fce873a73115ae | []
| no_license | MightyBOBcnc/earthgen | 8906cadf65b41ae85990f317dcaa633d344d38d0 | 3d5c6de580993c15dbfadabd85b339860a5df3df | refs/heads/master | 2022-04-24T03:06:18.882954 | 2020-04-27T00:47:25 | 2020-04-27T00:47:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 358 | rkt | orbit.rkt | #lang typed/racket
(provide (all-defined-out))
(require vraid/math)
(: solar-equator (Float Float -> Float))
(define (solar-equator axial-tilt time-of-year)
(* axial-tilt
(sin (* time-of-year tau))))
(: solar-irradiance (Float Float -> Float))
(define (solar-irradiance solar-equator latitude)
(max 0.0
(cos (- solar-equator latitude))))
| false |
1e135c7638e7044724143aad3b17216747a889a8 | c63a06955a246fb0b26485162c6d1bfeedfd95e2 | /p-2.6-church-number.rkt | ea5adc4d15a36d39608c4b3bfee765f2a91000cb | []
| no_license | ape-Chang/sicp | 4733fdb300fe1ef8821034447fa3d3710457b4b7 | 9df49b513e721137d889a1f645fddf48fc088684 | refs/heads/master | 2021-09-04T00:36:06.235822 | 2018-01-13T11:39:13 | 2018-01-13T11:39:13 | 113,718,990 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 358 | rkt | p-2.6-church-number.rkt | #lang racket
(define zero (lambda (f) (lambda (x) x)))
(define (add-1 n)
(lambda (f) (lambda (x) (f ((n f) x)))))
(define one
(lambda (f) (lambda (x) (f x))))
(define two
(lambda (f) (lambda (x) (f (f x)))))
(define (plus a b)
(lambda (f) (lambda (x) ((a f) ((b f) x)))))
;;
(cos 4)
((one cos) 4)
(cos (cos 4))
((two cos) 4)
(((plus one one) cos) 4) | false |
6f471ca37a19a897709fc27b051674098231d22a | 592ccef7c8ad9503717b2a6dff714ca233bc7317 | /docs-src/guide-determ.scrbl | 11a86eaceb4d742b7c8084778138e82aab253023 | [
"Apache-2.0"
]
| permissive | Thegaram/reach-lang | 8d68183b02bfdc4af3026139dee25c0a3e856662 | 4fdc83d9b9cfce4002fa47d58d2bcf497783f0ee | refs/heads/master | 2023-02-25T00:10:31.744099 | 2021-01-26T22:41:38 | 2021-01-26T22:41:38 | 333,350,309 | 1 | 0 | Apache-2.0 | 2021-01-27T08:17:28 | 2021-01-27T08:17:27 | null | UTF-8 | Racket | false | false | 3,317 | scrbl | guide-determ.scrbl | #lang scribble/manual
@(require "lib.rkt")
@title[#:version reach-vers #:tag "guide-determ"]{Determinism, simultaneity, and choice in decentralized applications}
The structure of a Reach computation is deterministic, because at each point in a computation, all participants agree on which publication is the next one in the computation.
If this were not the case, then different participants may attempt to pursue different paths through a computation and thereby reach different values at the end.
This deterministic structure, however, does not mean that the participant that provides the publication must be fixed, merely that which publication event is next must be fixed; see for example @reachin{race} expressions and the @seclink["guide-race"]{the guide section on races} for an elaboration of this point.)
Even in the presence of this non-determinism in actors, Reach programs remain deterministic in their structure.
However, many developers think of their application as having a step when two participants act simultaneously.
For example, in a game of @seclink["tut"]{Rock, Paper, Scissors!} in the real world, both players simultaneously choose their hands.
Similarly, a rental agreement gives both the landlord and the tenant the ability to cancel the agreement (subject to some penalty) at any time.
In both of these cases, it is not clear how to understand this interaction as being sequential and deterministic.
At first glance, these situations appear different.
In the first, the participants are doing "the same thing" simultaneously, because both will submit a hand eventually; while in the second, they are doing "something different", because only one of them will actually end the agreement early.
However, both of these situations are actually identical, because in the second case they are both simultaneously deciding whether they will end early.
In the first case, the participants are submitting one of three values (@litchar{Rock}, @litchar{Paper}, or @litchar{Scissors}), while in the second they are submitting one of two (@litchar{Leave} or @litchar{Stay}).
In such situations, in a decentralized application, the program must agree that one participant acts first.
The important thing to realize is that "simultaneity" is not the same thing as "non-determinism".
The pertinent design detail is whether one participant has an advantage for going in any particular order.
If there is no advantage for either place, then the developer can arbitrarily decide to go in one order.
If there is an advantage, then a commitment strategy similar to the @seclink["tut"]{Rock, Paper, Scissors! tutorial} should be used.
For example, in the rental agreement, if we felt there was no advantage for going second, then we could have either the landlord or the tenant go first.
But, is there no advantage?
If both the tenant and the landlord want to exit in the same month, but the landlord goes first, and then the landlord would suffer a loss of their deposit; but, if they fairly shared their choice at the same time, then they could both be refunded in this case.
This is an example of the Pareto improvements that are possible in decentralized applications relative to existing institutions.
@margin-note{See @secref["workshop-rental"] for a discussion of this example in further detail.}
| false |
d8e58a49b8a3ec5d2b9b7340b2dc451a774812e8 | 562a5a338e6d5fe28618abc3a41cb2692f20bab9 | /code/lang-as-lib/simple.rkt | d0f57ea59ff7cb0d55ca78a05b7fd3ecdce31caf | []
| no_license | iafisher/cs399 | 6998ea849755191f90e01642ff24ba5f292f6433 | fe1a4d17984ef84ab8007e8689b6fb989c8ef8ce | refs/heads/master | 2020-04-21T11:05:41.330125 | 2019-04-30T00:43:02 | 2019-04-30T00:43:02 | 169,509,586 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 587 | rkt | simple.rkt | #lang racket
; Fully expands the module and prints out its abstract syntax tree, before running it normally.
(define-syntax (module-begin stx)
(syntax-case stx ()
[(_ forms ...)
(with-syntax ([(_ core-forms ...)
(local-expand #'(#%plain-module-begin forms ...) 'module-begin '())])
#'(#%plain-module-begin (displayln '(core-forms ...)) core-forms ...))]))
; https://docs.racket-lang.org/guide/module-languages.html#%28part._s-exp%29
(provide (except-out (all-from-out racket) #%module-begin)
(rename-out [module-begin #%module-begin]))
| true |
1b54c1846733700313597eda6ca5ea1e6b743444 | 16b6912b521067a9e45da4a69b4f879d6717c7a8 | /taxo-impl.rkt | bb95701da249b1eee2379bea34cef4d05397e785 | []
| no_license | toothbrush/diaracket | fc3f4f3db27413b73514becea05e7e6a66241d75 | a23cb00821fcb6220c75e9047aa76dd75ec5d8f2 | refs/heads/master | 2021-01-21T13:07:30.514795 | 2016-04-19T15:50:43 | 2016-04-19T15:50:43 | 43,831,407 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,206 | rkt | taxo-impl.rkt | ;; in this file we will give the implementations of the
;; taxonomy-defined resources.
;; note that it isn't independently loadable -- it is syntactically
;; spliced into the thermo-impl.rkt file (because of the taxonomy-keyword)
(implement Screen
(lambda (bitmap)
(let ([f (new frame% [label "Bitmap"])])
(new message% [parent f] [label bitmap])
(send f show #t))))
(implement Camera
(lambda ()
(display-line "Returning a predefined image.")
(read-bitmap "./sample.jpg")))
(implement Button
(lambda ()
; placeholder: the button is reactive
#t))
(implement IP
(lambda ()
(with-handlers ([exn:fail? (lambda (exn) (~a "// HTTP airbag! " exn))])
(define-values (status header response)
(http-sendrecv "httpbin.org" "/ip" #:ssl? 'tls))
(let ([js (read-json response)])
(hash-ref js 'origin "oops"))))) ;; return some value from the web
(implement Geo
(lambda ()
; for now we'll act as if this is the constant location:
"Amsterdam, the Netherlands")) | false |
3d1e27acf513f9880747ff488b5cc7ad4184ba8f | 411046d5458a05c0ea35c75cfda3ce8980d9f9e3 | /lenses.rkt | a7f46aef5c7e724c7fc0d213fc852546183be31f | []
| no_license | dys-bigwig/racket-6502 | cac931fec2760c85576c7d1b51c4651fb8f35a75 | 9375bfce0a8b4f8bed241d2cf9581acd8d04bb2e | refs/heads/master | 2020-04-28T22:07:15.764927 | 2019-12-11T23:00:51 | 2019-12-11T23:00:51 | 175,606,606 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 4,661 | rkt | lenses.rkt | #lang racket
(require lens)
(require "utility.rkt")
(require data/collection)
(require data/pvector)
(provide (all-defined-out))
(struct/lens Processor (A X Y Z N PC MEM) #:transparent)
(define A Processor-A-lens)
(define X Processor-X-lens)
(define Y Processor-Y-lens)
(define Z Processor-Z-lens)
(define N Processor-N-lens)
(define PC Processor-PC-lens)
(define MEM Processor-MEM-lens)
(define IMM
(make-lens (λ (processor)
(let ([memory (Processor-MEM processor)]
[program-counter (Processor-PC processor)])
(nth memory (add1 program-counter))))
(λ (processor val)
(let ([memory (Processor-MEM processor)]
[program-counter (Processor-PC processor)])
(lens-set MEM processor (set-nth memory (add1 program-counter) val))))))
(define ZP
(make-lens (λ (processor)
(nth (Processor-MEM processor) (nth (Processor-MEM processor) (add1 (Processor-PC processor)))))
(λ (processor val)
(lens-set MEM processor (nth (lens-view MEM processor) (add1 (lens-view PC processor))) ))))
(define ZPX
(make-lens (λ (processor)
(let ([memory (Processor-MEM processor)]
[program-counter (Processor-PC processor)]
[x (Processor-X processor)])
(nth memory (+ x (nth memory (add1 program-counter))))))
(λ (processor val)
(let ([memory (Processor-MEM processor)]
[program-counter (Processor-PC processor)]
[x (Processor-X processor)])
(lens-set MEM processor (nth memory (add1 program-counter)) )))))
(define ZPY
(make-lens (λ (processor)
(let ([memory (Processor-MEM processor)]
[program-counter (Processor-PC processor)]
[y (Processor-Y processor)])
(nth memory (+ y (nth memory (add1 program-counter))))))
(λ (processor val)
(let ([memory (Processor-MEM processor)]
[program-counter (Processor-PC processor)]
[Y (Processor-Y processor)])
(lens-set MEM processor (nth memory (add1 program-counter)) )))))
(define ABS
(make-lens (λ (processor)
(let ([memory (Processor-MEM processor)]
[program-counter (Processor-PC processor)])
(nth memory (bytes->addr (nth memory (add1 program-counter))
(nth memory (add2 program-counter))))))
(λ (processor val)
(let ([memory (Processor-MEM processor)]
[program-counter (Processor-PC processor)])
(lens-set MEM processor (set-nth memory (bytes->addr (nth memory (add1 program-counter))
(nth memory (add2 program-counter))) val))))))
(define ABSX
(make-lens (λ (processor)
(let ([memory (Processor-MEM processor)]
[program-counter (Processor-PC processor)]
[x (Processor-X processor)])
(nth memory (+ x (bytes->addr (nth memory (add1 program-counter))
(nth memory (add2 program-counter)))))))
(λ (processor val)
(let ([memory (Processor-MEM processor)]
[program-counter (Processor-PC processor)]
[x (Processor-X processor)])
(lens-set MEM processor (set-nth memory (+ x (bytes->addr (nth memory (add1 program-counter))
(nth memory (add2 program-counter)))) val))))))
(define ABSY
(make-lens (λ (processor)
(let ([memory (Processor-MEM processor)]
[program-counter (Processor-PC processor)]
[y (Processor-Y processor)])
(nth memory (+ y (bytes->addr (nth memory (add1 program-counter))
(nth memory (add2 program-counter)))))))
(λ (processor val)
(let ([memory (Processor-MEM processor)]
[program-counter (Processor-PC processor)]
[y (Processor-Y processor)])
(lens-set MEM processor (set-nth memory (+ y (bytes->addr (nth memory (add1 program-counter))
(nth memory (add2 program-counter)))) val))))))
(define INDX
(make-lens (λ (processor)
(let* ([memory (Processor-MEM processor)]
[program-counter (Processor-PC processor)]
[x (Processor-X processor)]
[lo-byte (nth memory (+ x (nth memory (add1 program-counter))))]
[hi-byte (nth memory (+ x (add1 (nth memory (add1 program-counter)))))])
(nth memory (bytes->addr lo-byte hi-byte))))
(λ (processor val)
(let* ([memory (Processor-MEM processor)]
[program-counter (Processor-PC processor)]
[x (Processor-X processor)]
[lo-byte (nth memory (+ x (nth memory (add1 program-counter))))]
[hi-byte (nth memory (+ x (add1 (nth memory (add1 program-counter)))))])
(lens-set MEM processor (set-nth memory (bytes->addr lo-byte hi-byte) val))))))
(define (LDA mode)
(λ (p)
(lens-set A p (lens-view mode p))))
(define (LDX mode p)
(lens-set X p (lens-view mode p)))
(define (LDY mode p)
(lens-set Y p (lens-view mode p)))
| false |
cc59e131274cc123366e0d40a898245a2f905e75 | 394f948952cddcc2c19e81e329f887b1109839b3 | /trace-anf-eg.rkt | 8c21ccb7b6ac829aa8d5ec9c9620e0027dc1c9b2 | []
| no_license | dannypsnl-fork/multi-lang-comp | f51570d71a0790b768de7e8f66151b2d9fe95b12 | 08b65d40b31693b4a65decf529a4c180054eab34 | refs/heads/main | 2023-03-01T13:57:28.729418 | 2021-02-11T02:19:27 | 2021-02-11T02:19:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 310 | rkt | trace-anf-eg.rkt | #lang racket/base
(require
"anf.rkt"
redex/reduction-semantics
redex/gui)
(traces
anf-eval->+
(term (()
(AS (letrec ([fact (λ (n)
(if (eq? n 0)
1
(* n (fact (- n 1)))))])
(fact 5))))))
| false |
983c7e01bf3572dbd88be25a10261e5eda4739aa | e44997c7544a4841478d8c2f5a0fb6e41356be3f | /bsl-tests/blood-test-2list.rkt | e997decc715bd2af36659285354a6deb43543601 | []
| no_license | nadeemabdulhamid/racketui | 76f3195196ed4d6d29cdea2aebed65928ac271c8 | 045e0e647439623397cdf67e8e045ec7aa5e2def | refs/heads/master | 2023-03-22T16:00:15.389937 | 2020-08-12T12:30:35 | 2020-08-12T12:30:35 | 2,000,681 | 2 | 4 | null | 2023-05-13T06:42:47 | 2011-07-05T13:51:55 | Racket | UTF-8 | Racket | false | false | 5,757 | rkt | blood-test-2list.rkt | ;; The first three lines of this file were inserted by DrRacket. They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-reader.ss" "lang")((modname blood-test-2list) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
#|
blood test
given a list of 'normal ranges' and a list of patient readings
produce a list of strings indicating "L" or "H" if patient reading
is below or above corresponding 'normal' range
|#
;;=========================================================================
;; DATA DEFINITIONS/TEMPLATES
; A Range is (make-mrange String Number Number String)
(define-struct mrange (label low high units))
#| TEMPLATE
; range-func : Range ... -> ...
; purpose...
(check-expect (range-func ...) ...)
(define (range-func a-range)
... (range-label a-range) ...
... (range-low a-range) ...
... (range-high a-range) ...
... (range-units a-range) ...
)
|#
; A Reading is a Number
; A ResultCode is one of the strings:
; - "L" (representing a low result)
; - "N" (representing a normal result)
; - "H" (representing a high result)
; A Result is (make-result String ResultCode)
(define-struct result (label code))
; A List-of-ranges is either:
;; ... FILL IN ...
; A List-of-readings is either:
;; ... FILL IN ...
;;=========================================================================
;; EXAMPLES OF DATA
(define READINGS
(list 1.9
136
48
887
33
6.9
0.9))
(define RANGES
(list (make-mrange "ALB" 2.2 3.9 "g/dl")
(make-mrange "ALKP" 23 212 "U/L")
(make-mrange "ALT" 10 100 "U/L")
(make-mrange "AMYL" 500 1500 "U/L")
(make-mrange "BUN" 7 27 "mg/dl")
(make-mrange "Ca" 7.9 12.0 "mg/dl")
(make-mrange "CREA" 0.5 1.8 "mg/dl")))
(define RESULTS
(list (make-result "ALB" "L")
(make-result "ALKP" "N")
(make-result "ALT" "N")
(make-result "AMYL" "N")
(make-result "BUN" "H")
(make-result "Ca" "L")
(make-result "CREA" "N")))
;;=========================================================================
;; FUNCTIONS
; readings->results : List-of-readings List-of-ranges -> List-of-strings
; given a list of ranges and readings, produces a list of ResultCodes
; assumes both lists are the same length
(check-expect (readings->results READINGS RANGES) RESULTS)
(define (readings->results a-lord a-lorg)
(cond
[(empty? a-lorg) empty]
[(cons? a-lorg)
(cons (make-result (mrange-label (first a-lorg)) (compute-code (first a-lorg) (first a-lord)))
(readings->results (rest a-lord) (rest a-lorg)))]))
; compute-code : Range Reading -> ReadingCode
; determine whether the reading was low, normal, or high with respect to the given range
(check-expect (compute-code (make-mrange "ALT" 10 100 "U/L") 67) "N")
(check-expect (compute-code (make-mrange "ALT" 10 100 "U/L") 6) "L")
(check-expect (compute-code (make-mrange "ALT" 10 100 "U/L") 167) "H")
(check-expect (compute-code (make-mrange "ALT" 10 100 "U/L") 100) "N")
(define (compute-code a-range a-reading)
(cond [(< a-reading (mrange-low a-range)) "L"]
[(> a-reading (mrange-high a-range)) "H"]
[else "N"]))
(require 2htdp/image)
(define BAR (add-line (add-line (empty-scene 200 10) 50 0 50 10 "black")
150 0 150 10 "black"))
; result-bars->image : List-of-images -> Image
(define (result-bars->image a-loi)
(cond [(empty? a-loi) (empty-scene 0 0)]
[(cons? a-loi) (above (first a-loi)
(result-bars->image (rest a-loi)))]))
; readings->image :
(define (readings->image a-lorg a-lord)
(result-bars->image (readings->result-bars a-lorg a-lord)))
; readings->result-bars : List-of-ranges List-of-readings -> List-of-images
(define (readings->result-bars a-lorg a-lord)
(cond
[(empty? a-lorg) empty]
[(cons? a-lorg)
(cons (above/align "left"
(text (mrange-label (first a-lorg)) 10 "black")
(indicator-bar (first a-lorg) (first a-lord)))
(readings->result-bars (rest a-lorg) (rest a-lord)))]))
;; indicator-bar : Range Reading -> Image
;; produce a bar representing where the reading falls with respect to the range
(define (indicator-bar a-range a-reading)
(place-image (rectangle 5 10 "solid"
(cond [(string=? "N" (compute-code a-range a-reading)) "blue"]
[(string=? "L" (compute-code a-range a-reading)) "red"]
[(string=? "H" (compute-code a-range a-reading)) "red"]))
(+ 50 (* (- a-reading (mrange-low a-range))
(/ 100 (- (mrange-high a-range) (mrange-low a-range)))))
5
BAR))
(require racketui)
(define/web range/web
(structure make-mrange ["Label" string] ["Low" number] ["High" number] ["Units" string]))
(define/web reading/web
number)
(define/web result/web
(structure make-result
["Label" string]
["Result Code" (oneof ["Low Result" (constant "L")]
["Normal Result" (constant "N")]
["High Result" (constant "H")])]))
#;
(web-launch
"Blood Test Result Analyzer"
(function "Analyzes blood test results"
(readings->results ["List of readings" (listof ["Reading" reading/web])]
["List of ranges" (listof ["Range" range/web])]
-> ["List of results" (listof ["Result" result/web])])))
| false |
454cd1b18f5577518b9acde057c18f797ebbc858 | 7a4634df33a813e5f116ac1a9541742104340a56 | /pollen/test/test-third-tutorial-files.rkt | 83e3ecd71a5506f30a6eb362b15fa8e2266734c9 | [
"MIT"
]
| permissive | mbutterick/pollen | d4c9d44838729ac727972eb64d841b3a5104931b | 99c43e6ad360f7735ebc9c6e70a08dec5829d64a | refs/heads/master | 2023-08-19T06:08:49.719156 | 2022-07-22T22:26:46 | 2022-07-22T22:26:46 | 11,827,835 | 1,089 | 93 | MIT | 2021-11-16T21:00:03 | 2013-08-01T21:14:01 | Racket | UTF-8 | Racket | false | false | 412 | rkt | test-third-tutorial-files.rkt | #lang racket/base
;; because `raco test` will not automatically reach .pm or .pp files
(require (prefix-in burial: "../scribblings/third-tutorial-files/burial.html.pm")
(prefix-in chess: "../scribblings/third-tutorial-files/chess.html.pm")
(prefix-in sermon: "../scribblings/third-tutorial-files/sermon.html.pm")
(prefix-in styles: "../scribblings/third-tutorial-files/styles.css.pp")) | false |
ea29ce408ee8f788d105657f0c24445cbc544e4b | f3e1d44eb1780bd5a3fbe3f61c560f18c2447f48 | /semantics/common.rkt | 656efae212f7c5fc29f8e64f9fe72a2ee1200b4d | []
| no_license | willemneal/decompose-plug | afdda44f0182708dae80610dfd98ce8b13af4f04 | 5bb1acff487d055386c075581b395eb3cfdc12e9 | refs/heads/master | 2020-12-24T06:24:57.820701 | 2011-12-07T00:45:16 | 2011-12-07T00:45:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,054 | rkt | common.rkt | #lang racket/base
(require redex/reduction-semantics
racket/match
"patterns.rkt")
(provide (all-defined-out))
(define-metafunction patterns
append-contexts : C C -> C
[(append-contexts :hole C)
C]
[(append-contexts (:left C_1 t) C_2)
(:left (group/id (append-contexts C_1 C_2)) t)]
[(append-contexts (:right t C_1) C_2)
(:right t (group/id (append-contexts C_1 C_2)))])
(define encode-term
(match-lambda
['() 'mt]
[(cons t u)
`(:cons ,(encode-term t)
,(encode-term u))]
[':hole ':hole]
[(? atom? a) a]))
(define (⊔/proc b1 b2)
(term (⊔ ,b1 ,b2)))
(define-metafunction patterns
⊔ : b b -> b or ⊤
[(⊔ (set) b)
b]
[(⊔ (set (pair x_0 t_0) (pair x_1 t_1) ...) b)
(⊔ (set (pair x_1 t_1) ...) b_1)
(where b_1 (merge-binding x_0 t_0 b))]
[(⊔ b_1 b_2) ; else
⊤])
(define-metafunction patterns
merge-binding : x t b -> b or ⊤
[(merge-binding x t (set))
(set (pair x t))]
[(merge-binding x_0 t_0 (set (pair x_0 t_0) (pair x_1 t_1) ...))
(set (pair x_0 t_0) (pair x_1 t_1) ...)]
[(merge-binding x t (set (pair x_0 t_0) (pair x_1 t_1) ...))
(set-adjoin (pair x_0 t_0) b)
(side-condition (term (neq x x_0)))
(where b (merge-binding x t (set (pair x_1 t_1) ...)))]
[(merge-binding x t b) ; else
⊤])
(define raw-bindings
(match-lambda
[`(set (pair ,xs ,ts) ...)
(map list xs ts)]))
(define-judgment-form patterns
#:mode (nt-has-prod O I I)
#:contract (nt-has-prod p G n)
[(nt-has-prod p_ij (D_0 ... [n_i (p_i0 ... p_ij p_ij+1 ...)] D_i+1 ...) n_i)])
;; definitions to facilitate typesetting
(define-metafunction patterns
[(neq any_1 any_1) #f]
[(neq any_!_1 any_!_1) #t])
(define-term no-bindings (set))
(define-metafunction patterns
[(productions G n)
,(judgment-holds (nt-has-prod p G n) p)])
(define-metafunction patterns
[(: F C) (F C)])
(define-metafunction patterns
[(set-adjoin any_0 (set any_1 ...))
(set any_0 any_1 ...)])
(define-metafunction patterns
[(group/id any) any]) | false |
bd369d114908324285ee78a3d1f3e48386779cb7 | 1d82ffe3722ded66df75b2003a5de9643cd7f964 | /main.rkt | bcf42cd64daefc12eb4efbb073a69b794baf393b | []
| no_license | jeapostrophe/parenlog | a796de4cf69c4218ba0a7fc91ea77f321f2b413b | b02b9960c18b3c238b08a68d334f7ac2641e785c | refs/heads/master | 2020-12-24T14:57:11.243804 | 2017-12-18T21:29:34 | 2017-12-18T21:29:34 | 617,897 | 3 | 3 | null | 2017-12-18T21:29:35 | 2010-04-19T15:00:45 | Racket | UTF-8 | Racket | false | false | 83 | rkt | main.rkt | #lang racket/base
(require "parenlog.rkt")
(provide (all-from-out "parenlog.rkt"))
| false |
b1be0ab0707c8815352f8b34b97633fbb7b07bf4 | a8fd8f18ee59d371858f24283af71b6860d272a3 | /racket/ambient/lang/runtime-config.rkt | 5e0637f263bd78e1781fbca6f98d08ca80f3cc01 | []
| no_license | johankj/shill | b011c5976671c95e44dab23ec162936a21f51b9c | d0391602af9c71fe13971b8b71ec57640e0971ef | refs/heads/master | 2020-03-17T14:06:11.941749 | 2018-02-02T09:08:08 | 2018-06-13T11:03:40 | 133,658,303 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,499 | rkt | runtime-config.rkt | #lang racket/base
(provide configure)
(require shill/ambient/parse)
(require shill/private/repl)
(require (only-in shill/private/filesystem read))
(define out-reader
(thread
(lambda ()
(let ([buffer (make-bytes 0)])
(define (loop)
(sleep 0.05)
(set! buffer (bytes-append buffer (read replout-in)))
(let ([msg (thread-try-receive)])
(when (thread? msg)
(thread-send msg buffer)
(set! buffer (make-bytes 0))))
(loop))
(loop)))))
(define err-reader
(thread
(lambda ()
(let ([buffer (make-bytes 0)])
(define (loop)
(sleep 0.05)
(set! buffer (bytes-append buffer (read replerr-in)))
(let ([msg (thread-try-receive)])
(when (thread? msg)
(thread-send msg buffer)
(set! buffer (make-bytes 0)))
(loop)))
(loop)))))
(define (get-out)
(thread-send out-reader (current-thread))
(thread-receive))
(define (get-err)
(thread-send err-reader (current-thread))
(thread-receive))
(define (configure data)
(let ([old-eval (current-eval)]
[old-print (current-print)]
[first? #t])
(current-eval
(lambda (form)
(when first?
(old-eval
'(#%require (only shill/private/repl
stdout
stderr)))
(set! first? #f))
(old-eval form)))
(current-read-interaction
(lambda (src port)
(if (char-ready? port)
(parameterize ([read-accept-reader #f]
[read-accept-lang #f])
(let* ([result (parse-program src port)]
[new (datum->syntax #f (syntax->datum (car (syntax->list result)))
(list (syntax-source result)
(syntax-line result)
(syntax-column result)
(syntax-position result)
(syntax-span result)))])
new))
eof)))
(current-print
(lambda (val)
(old-print val)
(let ([out (get-out)]
[err (get-err)])
(unless (eq? (bytes-length out) 0)
(printf "stdout:~n~a~n" (bytes->string/utf-8 out)))
(unless (eq? (bytes-length err) 0)
(printf "stderr:~n~a~n" (bytes->string/utf-8 err)))))))) | false |
412c667d078470998a69d8f483042a24d8f3d663 | 3906b8b073a874350da8914107909a90f87f282f | /tamer/csv/reader/unix.rkt | a94f2fce7d7eb8237fd3215d8a931f9e5e34e1f1 | []
| no_license | wargrey/schema | 7d99e4f513b6bac5e35d07d19d1e638972c7aad0 | 860a09a23a01104432be6b990a627afe9d752e66 | refs/heads/master | 2023-07-07T15:39:11.744020 | 2023-06-30T16:33:13 | 2023-06-30T16:33:13 | 76,066,993 | 6 | 2 | null | 2021-04-17T23:30:43 | 2016-12-09T20:14:41 | Racket | UTF-8 | Racket | false | false | 1,142 | rkt | unix.rkt | #lang typed/racket
(require "csv.rkt")
(require racket/logging)
(define unix.csv : Path (#%csv))
csv::unix
(displayln '===================================================================)
(displayln 'read-port)
(parameterize ([port-count-lines-enabled #true])
((inst with-logging-to-port (U (Listof (Listof CSV-Field)) (Listof (Vectorof CSV-Field))))
(current-error-port)
(λ [] (sequence->list (in-csv* unix.csv #false #:dialect csv::unix)))
'debug))
(displayln '===================================================================)
(displayln 'read-line)
(parameterize ([port-count-lines-enabled #false])
((inst with-logging-to-port (U (Listof (Listof CSV-Field)) (Listof (Vectorof CSV-Field))))
(current-error-port)
(λ [] (sequence->list (in-csv* unix.csv #false #:dialect csv::unix)))
'debug))
(displayln '===================================================================)
(displayln 'read-string)
((inst with-logging-to-port (U (Listof (Listof CSV-Field)) (Listof (Vectorof CSV-Field))))
(current-error-port)
(λ [] (sequence->list (in-csv* (file->string unix.csv) #false #:dialect csv::unix)))
'debug)
| false |
2782dcf67c064b963d5a3b8835ebee4d7dc0326a | b232a8795fbc2176ab45eb3393f44a91112702f7 | /test/bv-tests.rkt | 078da95d467343a30fe69e2c21f1e5201b9793b9 | []
| no_license | ilya-klyuchnikov/typed-rosette | 9845b2fcd8b203749bb3469dea4f70f8cf05c368 | d72d4e7aad2c339fdd49c70682d56f83ab3eae3d | refs/heads/master | 2021-09-20T08:25:13.996681 | 2018-08-06T17:58:30 | 2018-08-06T17:58:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,057 | rkt | bv-tests.rkt | #lang typed/bv
(require typed/lib/roseunit)
(check-type current-bvpred : (CParamof CBVPred))
(check-type (current-bvpred) : BVPred -> (bitvector 4))
(check-type (current-bvpred (bitvector 5)) : CUnit -> (void))
(check-type (current-bvpred) : BVPred -> (bitvector 5))
(check-type (current-bvpred (bitvector 4)) : CUnit -> (void))
(check-type (bv 1) : BV)
(check-type ((bitvector 4) (bv 1)) : Bool -> #t)
(check-type ((bitvector 1) (bv 1)) : Bool -> #f)
(check-type (bv 2 (bitvector 3)) : BV)
(check-type ((bitvector 3) (bv 2 (bitvector 3))) : Bool -> #t)
(check-type (bv*) : BV)
(check-type (if 1 (bv 1) (bv 0)) : BV -> (bv 1))
(check-type (if #f (bv 1) (bv 0)) : BV -> (bv 0))
(define-symbolic i integer?)
(define-symbolic b boolean?)
(check-type (if i (bv 1) (bv 0)) : BV -> (bv 1))
(check-type (if b (bv 1) (bv 0)) : BV -> (if b (bv 1) (bv 0)))
(check-type (bvredor (bv 1)) : BV)
(check-type (bvredand (bv 1)) : BV)
(check-type bveq : (→ BV BV BV))
(check-type (bveq (bv 1) (bv 1)) : BV -> (bv 1))
(check-type (bveq (bv 1) (bv 0)) : BV -> (bv 0))
| false |
3a5bf1d7a664446846f6cfc537b69c221538ecdc | 82c76c05fc8ca096f2744a7423d411561b25d9bd | /typed-racket-test/succeed/map1.rkt | 5c4e67a0d7e35cc0b38e9992ac615dd4f3f850fa | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | racket/typed-racket | 2cde60da289399d74e945b8f86fbda662520e1ef | f3e42b3aba6ef84b01fc25d0a9ef48cd9d16a554 | refs/heads/master | 2023-09-01T23:26:03.765739 | 2023-08-09T01:22:36 | 2023-08-09T01:22:36 | 27,412,259 | 571 | 131 | NOASSERTION | 2023-08-09T01:22:41 | 2014-12-02T03:00:29 | Racket | UTF-8 | Racket | false | false | 98 | rkt | map1.rkt | #lang typed-scheme
(: f ((U String Number) -> Void))
(define (f x) (void))
(map f (list 1 2 3))
| false |
9fff35a0401c6a56e4ff22e60d30ef9fe1f5eba4 | 3b2cf17b2d77774a19e9a9540431f1f5a840031e | /src/lang/racket-ffi/math.rkt | 8f12e8bb3ee6dbd82d195d16d60342ddd327ee2f | []
| no_license | brownplt/pyret-lang-resugarer | 5bfaa09e52665657abad8d9d863e8915e0029a29 | 49519679aefb7b280a27938bc7bfbaaecc0bd4fc | HEAD | 2016-09-06T03:59:24.608789 | 2014-06-27T03:45:02 | 2014-06-27T03:45:02 | 13,936,477 | 1 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 407 | rkt | math.rkt | #lang racket/base
(require
"../runtime.rkt"
"../string-map.rkt"
"../ffi-helpers.rkt"
(only-in math uniform-dist sample))
(define math-dict
(make-string-map
(list
(cons "uniform-dist" (ffi-wrap uniform-dist))
(cons "random" (ffi-wrap random))
(cons "sample" (ffi-wrap sample)))))
(define math-obj (p:mk-object math-dict))
(provide (rename-out [math-obj %PYRET-PROVIDE]))
| false |
6d05d658e26cb58dd7bdd167ef8c9e7671d31aa4 | 18c09f49ee1b6670426be9b0d10b6fb24f1475e4 | /Task/Binary-digits/Racket/binary-digits.rkt | ce748521d8f94d0feafe766404063de71b89b1f2 | []
| no_license | hitme/RosettaCodeData | 579f07fe898b6642414281cf8567bac01f6098df | 1f1ad4942732d2b45e67dd9264c3cc8924a72d78 | refs/heads/master | 2021-01-13T04:37:54.198047 | 2013-04-12T23:18:05 | 2013-04-12T23:18:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 63 | rkt | binary-digits.rkt | #lang racket
(for ([i 16])
(displayln (number->string i 2)))
| false |
f2d0c9d235ef0fd96e2f3d8f8a07a080a99eb4fb | 9508c612822d4211e4d3d926bbaed55e21e7bbf3 | /tests/dsls/peg/private/compile.rkt | c67a333657cad79f363e678bc6b64bd20403d384 | [
"MIT",
"Apache-2.0"
]
| permissive | michaelballantyne/syntax-spec | 4cfb17eedba99370edc07904326e3c78ffdb0905 | f3df0c72596fce83591a8061d048ebf470d8d625 | refs/heads/main | 2023-06-20T21:50:27.017126 | 2023-05-15T19:57:55 | 2023-05-15T19:57:55 | 394,331,757 | 13 | 1 | NOASSERTION | 2023-06-19T23:18:13 | 2021-08-09T14:54:47 | Racket | UTF-8 | Racket | false | false | 7,005 | rkt | compile.rkt | #lang racket/base
(provide
(rename-out [compile-peg-top compile-peg])
compile-parse)
(require
racket/stxparam
syntax/id-table
syntax/srcloc
(except-in racket/base => *)
"forms.rkt"
"runtime.rkt"
(for-syntax "compile-alt-str.rkt"
syntax/parse
racket/base
(rename-in syntax/parse [define/syntax-parse def/stx])))
(begin-for-syntax
(define (bound-vars e)
(syntax-parse e
#:literal-sets (peg-literals)
[(bind v rhs)
(list #'v)]
[(seq e1 e2)
(append (bound-vars #'e1) (bound-vars #'e2))]
[(? e) (bound-vars #'e)]
[(* e)
(bound-vars #'e)]
[(src-span v e)
(cons #'v (bound-vars #'e))]
[_ '()])))
(define v-tmps (make-parameter #f))
(define-syntax generate-plain-alt
(syntax-parser
[(_ c1 c2)
#'(let-values ([(in^ res) c1])
(if (failure? in^)
c2
(values in^ res)))]))
#|
you have the PEG and input coming in
you need the result and the updated input out
|#
(define-syntax-rule (compile-peg-top pe in) (let ([in-v in]) (compile-peg pe in-v result in^ (values in^ result) (fail))))
(define-syntax compile-peg
(syntax-parser
; parses `pe` on input stream `in`. If the parse succeeds, binds `result` to the result and `in^` to the updated
; input stream in `on-success`. Otherwise, evaluates to `on-fail`.
; assume `result` is not the same as `in^`
[(_ pe in:id result:id in^:id on-success on-fail)
(syntax-parse #'pe
#:literal-sets (peg-literals)
; start with =>, :, char, seq
[eps #'(let ([result (void)] [in^ in]) on-success)]
[(=> pe e)
#'(compile-peg pe in ignored in^ (let ([result e]) on-success) on-fail)]
[(bind x:id pe)
; assume `x` is not the same as `result`
#'(compile-peg pe in x in^
(if (and (void? x) (not (text-rep? in^)))
(error ': "missing semantic value")
(let ([x (if (not (void? x))
x
(substring (text-rep-str in) (text-rep-ix in) (text-rep-ix in^)))]
[result (void)])
on-success))
on-fail)]
[(seq pe1 pe2)
#'(compile-peg pe1 in ignored in-tmp
(compile-peg pe2 in-tmp result in^ on-success on-fail)
on-fail)]
[(plain-alt pe1 pe2)
; TODO deduplicate on-success?
#'(compile-peg pe1 in result in^ on-success (compile-peg pe2 in result in^ on-success on-fail))]
[(alt pe1 pe2)
#`(let-values ([(in^-tmp result-tmp) #,(optimize+compile-alts this-syntax #'in #'compile-peg-top #'generate-plain-alt)])
(if (failure? in^-tmp)
on-fail
(let ([in^ in^-tmp] [result result-tmp]) on-success)))]
[(? pe)
(def/stx (v* ...) (bound-vars #'pe))
; assume result is not the same as any v*
; assume in^ is not the same as any v*
; TODO could this happen if src-span and ? are used together?
#'(compile-peg pe in result in^
on-success
(let ([v* #f] ... [in^ in] [result (void)]) on-success))]
[(* pe)
(def/stx (v* ...) (bound-vars #'pe))
; bound to the list of values of its corresponding variable
(def/stx (iter-v* ...) (generate-temporaries (attribute v*)))
#'(let ([iter-v* '()] ...)
(let loop ([in in])
(compile-peg pe in ignored in-tmp
(begin (set! iter-v* (cons v* iter-v*)) ...
(loop in-tmp))
; assume result is not the same as any v*
; assume in^ is not the same as any v*
; TODO could this happen if src-span and * are used together?
(let ([v* (reverse iter-v*)]
...
[in^ in]
[result (void)])
on-success))))]
[(src-span v e)
; TODO figure out how to pull some of this back into rt
; trickier now since bindings in e must escape and we do nesting let style
; can't just do a remote set! anymore
#'(if (text-rep? in)
(let ([source (text-rep-source in)]
[init-pos (text-rep-ix in)]
[init-ln (text-rep-ln in)]
[init-col (text-rep-col in)])
(compile-peg e in result in^
(let ([v (srcloc source
init-ln init-col
init-pos (- (text-rep-ix in^) init-pos))])
on-success)
; TODO what is the desired semantics of e failing?
on-fail))
(parameterize ([first-token-srcloc #f]
[last-token-srcloc #f])
(compile-peg e in result in^
(let ([v (build-source-location (first-token-srcloc)
(last-token-srcloc))])
on-success)
on-fail)))]
[(! pe)
#'(compile-peg pe in ignored-result ignored-in^
on-fail
(let ([result (void)] [in^ in]) on-success))]
[(#%nonterm-ref name)
#'(let-values ([(in^-tmp result-tmp) (name in)])
(if (failure? in^-tmp)
on-fail
(let ([in^ in^-tmp] [result result-tmp])
on-success)))]
[(char f)
; TODO this tmp stuff probably isn't necessary
; TODO deduplicate. maybe make runtime cps?
#'(let-values ([(in^-tmp result-tmp) (char-pred-rt f in)])
(if (failure? in^-tmp)
on-fail
(let ([in^ in^-tmp] [result result-tmp]) on-success)))]
[(text s:expr)
#'(let-values ([(in^-tmp result-tmp) (string-rt s in)])
(if (failure? in^-tmp)
on-fail
(let ([in^ in^-tmp] [result result-tmp]) on-success)))]
[(token f) ; TODO probably needs a contract check
#'(let-values ([(in^-tmp result-tmp) (token-pred-rt f in)])
(if (failure? in^-tmp)
on-fail
(let ([in^ in^-tmp] [result result-tmp]) on-success)))]
[_ (raise-syntax-error #f "not a core peg form" this-syntax)])]))
(define-syntax compile-parse
(syntax-parser
[(_ f in-e)
#'(let ([in (wrap-input in-e)])
(let-values ([(in^ res) (f in)])
(if (failure? in^)
(error 'parse "parse failed")
(parse-result in^ res))))]))
| true |
cf0c242bbf29b77799617071df0d7a77cd7d0c18 | f987ad08fe780a03168e72efce172ea86ad5e6c0 | /plai-lib/tests/datatype.rkt | c545434c63b24a26198ec2fd610e086c6a13a587 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Apache-2.0"
]
| permissive | racket/plai | a76573fdd29b648e04f8adabcdc8fb1f6825d036 | ae42bcb581ab02dcb9ddaea98d5ecded589c8d47 | refs/heads/master | 2023-08-18T18:41:24.326877 | 2022-10-03T02:10:02 | 2022-10-03T02:10:14 | 27,412,198 | 11 | 12 | NOASSERTION | 2022-07-08T19:16:11 | 2014-12-02T02:58:30 | Racket | UTF-8 | Racket | false | false | 2,211 | rkt | datatype.rkt | #lang plai
(require (prefix-in eli: tests/eli-tester)
"util.rkt")
(define-type A
[mta]
[a (b B?)])
(define-type B
[mtb]
[b (a A?)])
(define-type T
[i (f number?)])
(define-type T1
[i1 (f (car 1))])
(define-type DefrdSub
[mtSub]
[aSub (value boolean?)])
(define (lookup ds the-name)
(type-case DefrdSub ds
[mtSub () 1]
[aSub (a-name) 2]))
(define-type t (c))
(define-type t1 (c1 (n number?)))
(define-type T-immutable #:immutable
[t-immutable (a number?)])
(define ((ERR f) line#)
(format f (+ line# THIS-LINE#)))
(define ERR1
(ERR "exception \\(make-i #f\\) at line ~a\n expected: <no-expected-value>\nmake-i: contract violation.+"))
(define ERR2
(ERR "exception \\(i-f #f\\) at line ~a\n expected: <no-expected-value>\ni-f: contract violation.+"))
(define ERR3
(ERR
"exception \\(c1 \\(quote not-a-number\\)\\) at line ~a\n expected: <no-expected-value>\nc1: contract violation.+"))
(define (ERR4 line#)
(string-append
(regexp-quote "exception (type-case t (list 1) (c () 1)) at line ")
((ERR "~a") line#)
(regexp-quote "\n expected: <no-expected-value>\n")
(regexp-quote "type-case: expected a value from type t, got: '(1)\n")))
(define THIS-LINE# 55)
(eli:test
(i 4)
(regexp-match (ERR1 4) (with-both-output-to-string (λ () (test/exn (make-i #f) "contract"))))
(regexp-match (ERR2 5) (with-both-output-to-string (λ () (test/exn (i-f #f) "contract"))))
(type-case A (mta) [mta () 1] [a (x) 2])
=>
1
(regexp-match (ERR3 9) (with-both-output-to-string (λ () (test (c1 'not-a-number) (list 5)))))
(regexp-match
(ERR4 (+ 12 1))
(with-both-output-to-string (λ () (test/exn (type-case t (list 1) (c () 1)) "expected"))))
(type-case "foo" "bar") =error> "this must be a type defined with define-type"
(type-case + "bar") =error> "this must be a type defined with define-type"
(type-case #f [x () 1]) =error> "this must be a type defined with define-type"
(type-case A (mta) [mta () (define x 2) x] [else (define x 3) x]) => 2
(type-case A (a (mtb)) [mta () (define x 2) x] [a (b) (define x 3) x]) => 3
(type-case T 1 [i (f)]) =error> "type-case: this case is missing a body expression")
| false |
77c0bc5e51621459222dbf1c80a4c7069413c58b | 65939926c03f939e205a0d0293a774dd970c6903 | /hive/client/commands.rkt | 0f59d3732c5235f5e395689d2a1b36c84abd9364 | [
"MIT"
]
| permissive | Kalimehtar/hive-client | a34033d0b4ca15b9a11076234daf424fea311cbb | 605dd70cdeb4bcc88e9c79d744bcca6fc89c611d | refs/heads/master | 2021-10-29T05:51:55.968148 | 2021-10-17T15:08:13 | 2021-10-17T15:08:13 | 61,033,730 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 4,201 | rkt | commands.rkt | #lang racket/base
(provide connect do-command do-std-command disconnect connection-alive?)
(require racket/match
racket/file
racket/tcp
(prefix-in txt: "string-constants.rkt")
hive/common/read-write
"receiver.rkt"
(prefix-in receivers- "receivers.rkt"))
(struct connection (send-thread close) #:mutable)
(struct exn:bad-password exn:fail:user ())
(define (connect tcp-port
on-event
on-connect
on-fail
[username (get-preference 'username)]
[password (get-preference 'password)]
[result-connection (connection #f #f)])
(define reconnect
(thread (λ ()
(define e (thread-receive))
(custodian-shutdown-all main-custodian)
(sleep 1)
(cond
[(eq? e 'kill) #f]
[(exn:bad-password? e) (on-fail e)]
[else
(on-fail e)
(connect tcp-port on-event on-connect on-fail username password result-connection)
(receivers-resend receivers (connection-send-thread result-connection))]))))
(define main-custodian (make-custodian))
(define-syntax-rule (thread-loop BODY ...)
(thread
(λ ()
(with-handlers ([exn:fail? (λ (e) (thread-send reconnect e))])
(let loop ()
BODY ...
(loop))))))
(define receivers (receivers-init (thread-loop (on-event (thread-receive)))))
(parameterize ([current-custodian main-custodian])
(with-handlers ([exn:fail? (λ (e)
(thread-send reconnect e)
result-connection)])
(define-values (in out) (tcp-connect (get-preference 'server) tcp-port))
(write/flush (list username password) out)
(define auth-result (read/timeout in))
(case auth-result
[(ok) #t]
[(bad-password)
(raise (exn:bad-password (txt:bad-password) (current-continuation-marks)))]
[else
(raise-user-error 'connect "~a" auth-result)])
(define dispatch (thread-loop
(match (thread-receive)
[(list-rest 'data id data)
(receivers-dispatch! receivers id data)]
[(cons 'data _) #f]
[new-receiver (receivers-add! receivers new-receiver)])))
(define next!
(let ([n 0])
(λ ()
(set! n (if (n . > . 10000) 0 (add1 n)))
n)))
(define sender (thread-loop
(sync/timeout 10 (thread-receive-evt))
(match (or (thread-try-receive) 'keepalive)
[(receiver _id return data)
(define id (or _id (next!)))
(thread-send dispatch (receiver id return data) #f)
(write/flush (cons id data) out)]
[data (write/flush data out)])))
(thread-loop
(define data (read/timeout in))
(cond
[(eof-object? data)
(thread-send reconnect #t)]
[else (thread-send dispatch (cons 'data data) #f)]))
(set-connection-send-thread! result-connection sender)
(set-connection-close! result-connection (λ () (custodian-shutdown-all main-custodian)))
(on-connect result-connection)
result-connection)))
(define (talk connection data)
(when connection
(call-in-nested-thread
(λ ()
(with-handlers ([exn:fail? displayln])
(thread-send (connection-send-thread connection) (receiver #f (current-thread) data))
(thread-receive))))))
(define (do-command connection id . args)
(talk connection (list* 'command id args)))
(define (do-std-command connection id . args)
(talk connection (list* 'std-command id args)))
(define (connection-alive? connection)
(and connection
(connection-send-thread connection)
(thread-running? (connection-send-thread connection))))
(define (disconnect connection)
(and connection
(connection-close connection)
((connection-close connection))))
| true |
c89d5f126a1edaff6c28c011c74bbe362228c274 | ea4fc87eafa7b36a43f8f04b9585d73aeed1f036 | /laramie-lib/tokenizer/tests/rawtext.rkt | 581e9e0dc589924965ebe24051baa7ee95586c00 | [
"MIT"
]
| permissive | jthodge/laramie | a58a551727aebc792bdcaa5193dff775fd9848df | 7afc9314ff1f363098efeb68ceb25e2e9c419e6e | refs/heads/master | 2023-06-19T21:19:43.308293 | 2021-07-19T05:20:01 | 2021-07-19T05:20:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 5,220 | rkt | rawtext.rkt | #lang racket/base
(require racket/require
(multi-in ".."
("types.rkt"
"tokenize.rkt"
"tokens.rkt"
"rawtext.rkt"
"parameters.rkt")))
(module+ test
(require rackunit
racket/format
syntax/parse/define))
(module+ test
(define-simple-macro (check-it test-name subject value)
(let ([tokens (parameterize ([current-tag-name (list (character-token (location 1 0 0) (location 1 0 1) #\p))])
(tokenize subject
#:include-dropped? #t
#:include-errors? #t
#:initial-tokenizer RAWTEXT))])
(test-case
(format "~a [value]" test-name)
(check-equal? tokens
value))
(test-case
(format "~a [length]" test-name)
(check-= (length (enumerate-input-characters tokens))
(string-length subject)
0)))))
(module+ test
(check-it
"Empty rawtext"
""
(list))
(check-it
"Orphaned <"
"<"
(list (character-token (location 1 0 1) (location 1 1 2) #\<)))
(check-it
"Null"
(format "~a" #\nul)
(list
(unexpected-null-character (location 1 0 1) #f)
(character-token (location 1 0 1) (location 1 1 2) '(#\nul . #\�))))
(check-it
"Simple string"
"hey"
(list (string-token (location 1 0 1) (location 1 3 4) "hey")))
(check-it
"Simple tag, appropriate"
"</p>"
(list
(end-tag-token
(location 1 0 1)
(location 1 4 5)
(character-token (location 1 0 1) (location 1 1 2) #\<)
(list (character-token (location 1 2 3) (location 1 3 4) #\p))
'()
#f
(character-token (location 1 3 4) (location 1 4 5) #\>)
'()
(character-token (location 1 1 2) (location 1 2 3) #\/))))
(check-it
"Simple tag, inappropriate"
"</q>"
(list
(character-token (location 1 0 1) (location 1 1 2) #\<)
(character-token (location 1 1 2) (location 1 2 3) #\/)
(character-token (location 1 2 3) (location 1 3 4) #\q)
(string-token (location 1 3 4) (location 1 4 5) ">")))
(check-it
"< space"
"< x"
(list
(character-token (location 1 0 1) (location 1 1 2) #\<)
(string-token (location 1 1 2) (location 1 3 4) " x")))
(check-it
"Non-alpha in tag"
"<a1>"
(list
(character-token (location 1 0 1) (location 1 1 2) #\<)
(string-token (location 1 1 2) (location 1 4 5) "a1>")))
(check-it
"EOF on end tag open"
"</"
(list
(character-token (location 1 0 1) (location 1 1 2) #\<)
(character-token (location 1 1 2) (location 1 2 3) #\/)))
(check-it
"Non-tag"
"</1>"
(list
(character-token (location 1 0 1) (location 1 1 2) #\<)
(character-token (location 1 1 2) (location 1 2 3) #\/)
(string-token (location 1 2 3) (location 1 4 5) "1>")))
(check-it
"Whitespace after tag name (appropriate)"
"</p >"
(list
(end-tag-token
(location 1 0 1)
(location 1 5 6)
(character-token (location 1 0 1) (location 1 1 2) #\<)
(list (character-token (location 1 2 3) (location 1 3 4) #\p))
'()
#f
(character-token (location 1 4 5) (location 1 5 6) #\>)
(list (character-token (location 1 3 4) (location 1 4 5) #\space))
(character-token (location 1 1 2) (location 1 2 3) #\/))))
(check-it
"Whitespace after tag name (not appropriate)"
"</q >"
(list
(character-token (location 1 0 1) (location 1 1 2) #\<)
(character-token (location 1 1 2) (location 1 2 3) #\/)
(character-token (location 1 2 3) (location 1 3 4) #\q)
(string-token (location 1 3 4) (location 1 5 6) " >")))
(check-it
"Self-closing end tag (appropriate)"
"</p/>"
(list
(end-tag-token
(location 1 0 1)
(location 1 5 6)
(character-token (location 1 0 1) (location 1 1 2) #\<)
(list (character-token (location 1 2 3) (location 1 3 4) #\p))
'()
(character-token (location 1 3 4) (location 1 4 5) #\/)
(character-token (location 1 4 5) (location 1 5 6) #\>)
'()
(character-token (location 1 1 2) (location 1 2 3) #\/))))
(check-it
"Self-closing end tag (not appropriate)"
"</q/>"
(list
(character-token (location 1 0 1) (location 1 1 2) #\<)
(character-token (location 1 1 2) (location 1 2 3) #\/)
(character-token (location 1 2 3) (location 1 3 4) #\q)
(string-token (location 1 3 4) (location 1 5 6) "/>")))
(check-it
"Uppercase in end tag"
"</P>"
(list
(end-tag-token
(location 1 0 1)
(location 1 4 5)
(character-token (location 1 0 1) (location 1 1 2) #\<)
(list (character-token (location 1 2 3) (location 1 3 4) '(#\P . #\p)))
'()
#f
(character-token (location 1 3 4) (location 1 4 5) #\>)
'()
(character-token (location 1 1 2) (location 1 2 3) #\/))))
(check-it
"Non-alpha in end tag"
"</a1>"
(list
(character-token (location 1 0 1) (location 1 1 2) #\<)
(character-token (location 1 1 2) (location 1 2 3) #\/)
(character-token (location 1 2 3) (location 1 3 4) #\a)
(string-token (location 1 3 4) (location 1 5 6) "1>"))))
| false |
a9b7696214730fa508d25484b36c8141f7fa74f2 | d5c264af20a277a7b7bb34d473f13967bd54f51d | /cronut-lib/private/expressions.rkt | 30404d6fd2dffce58246ad1bd4e376a93a7aab41 | [
"Apache-2.0"
]
| permissive | hermetique/cronut | 6d616815f4915b7bc605c6b0db8045e44e2f836b | a12601900717cad363944d3276c56eb579f3fe5f | refs/heads/main | 2023-08-05T08:30:14.253051 | 2021-09-19T07:30:00 | 2021-09-19T07:30:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 5,102 | rkt | expressions.rkt | #lang racket/base
; cronut/private/expressions.rkt
;
; Interfaces for Cronut expressions.
; Copyright 2021 The Cronut Authors
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing,
; software distributed under the License is distributed on an
; "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
; either express or implied. See the License for the specific
; language governing permissions and limitations under the License.
; TODO: Change the language of this module to
; `cronut/private/implementation`.
;
; TODO: Uncomment this module.
; Some notes about what's going on here:
;
; - Within a `define-interface`, each `method` and each `argument`
; of each `method` is associated with three contracts: The full
; contract that would be used for debugging and documenting this
; codebase, the partial contract that needs to apply when call
; sites beyond this codebase invoke the method, and the partial
; contract that needs to apply when call sites beyond this
; codebase implement the method.
;
; - TODO: Implement a contract for `(expr-substitutable)` instances.
; They should be `(expr)` instances whose
; `map-recursive-occurrences` produce only other
; `(expr-substitutable)` instances satisfying the same constraint.
; To avoid redundant traversals, we should have an
; `expr-substitutable-confirmed` constructor that verifies the
; condition only when it's constructed for the first time. That
; constructor's instances don't themselves need to be instances of
; `(expr)` or `(expr-substitutable)`.
;
; - TODO: It seems like `(expr-substitutable) substitute` should
; require that the value its invoked on satisfy the more complex
; contract above. Perhaps we just won't invoke it through the
; method. Similarly, `(expr-interpretable-as-racket) interpret`
; should impose a condition on its input that's analogous to the
; `(expr-substitutable)` condition but for
; `(expr-interpretable-as-racket)` instead.
;
; - TODO: How should we express that
; `(expr) map-recursive-occurrences` should be invoked only by
; code within this codebase, abstraction-breaking code, and
; error-message-producing code? Ah, perhaps we should designate
; `(expr-substitutable) substitute` as the same kind of method, so
; that most code only invokes it through a contract-imposing
; wrapper function.
;
; - TODO: Oh, we haven't required that the environment arguments to
; `(expr-substitutable) substitute` and
; `(expr-interpretable-as-racket) interpret` bind at least as many
; entries as what the expressions have in their
; `(expr) get-free-variables`. Perhaps we should do that by using
; an `expr-confirmed` constructor that has a precomputed set of
; free variables so that we don't have to traverse the expression
; to find its free variables each time we need to check the
; contract. Perhaps we should also intern that set of free
; variables and have a `cronut-dict-superset-confirmed`
; constructor so that the dictionary doesn't have to be traversed
; every time. Are these contract-confirming wrappers going to
; proliferate all over the place?
; TODO: We depend on some things in this module that we should define
; at some point:
;
; define-interface, method, argument
;
; cronut-any/c
; instance/c
;
; cronut-set/c
; cronut-dict/c
#|
(define-interface expr
(method
(map-recursive-occurrences
(argument env
(cronut-set/c cronut-any/c)
(cronut-set/c cronut-any/c)
any/c)
(argument transform
(->
cronut-any/c
(cronut-set/c cronut-any/c)
(instance/c (expr))
(instance/c (expr)))
(-> any/c any/c any/c (instance/c (expr)))
(->
cronut-any/c
(cronut-set/c cronut-any/c)
(instance/c (expr))
any)))
(instance/c (expr))
any
(instance/c (expr)))
(method (get-free-vars)
(cronut-set/c cronut-any/c)
any
(cronut-set/c cronut-any/c)))
(define-interface expr-substitutable
(method
(substitute
(argument env
(cronut-dict/c cronut-any/c
(and/c
(instance/c (expr))
(instance/c (expr-substitutable))))
(cronut-dict/c cronut-any/c
(and/c
(instance/c (expr))
(instance/c (expr-substitutable))))
any/c))
(and/c
(instance/c (expr))
(instance/c (expr-substitutable)))
any
(and/c
(instance/c (expr))
(instance/c (expr-substitutable)))))
(define-interface expr-interpretable-as-racket
(method
(interpret
(argument env
(cronut-dict/c cronut-any/c any/c)
(cronut-dict/c cronut-any/c any/c)
any/c))
any/c
any
any/c))
|#
| false |
51b6177697a76f507b6eadf7db8c2ef8d8f1a306 | b6a8116250c29cc7056c22992a983863b1f73514 | /minimart/broker/server.rkt | 016a7e60b73b836161a58f8d1f3594bbd06f8148 | []
| no_license | localchart/minimart | 141e0bff882483bd95279e8a600e1ad3239d94fa | a7503d16e4cac0c7da3a184fee637ae0796790a5 | refs/heads/master | 2021-01-16T23:05:14.856133 | 2015-10-09T22:45:30 | 2015-10-09T22:45:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,140 | rkt | server.rkt | #lang racket/base
;; Generic relay for WebSockets/TCP/etc-based participation in a network.
(provide spawn-broker-server)
(require racket/set)
(require racket/match)
(require net/rfc6455)
(require "../main.rkt")
(require "../demand-matcher.rkt")
(require "../drivers/timer.rkt")
(require "../drivers/websocket.rkt")
(require json)
(require "protocol.rkt")
;; Depends on timer driver and websocket driver running at metalevel 1.
(define (spawn-broker-server port [ssl-options #f])
(define server-id (websocket-local-server port ssl-options))
(spawn-demand-matcher (websocket-message (?! (websocket-remote-client ?)) server-id ?)
#:meta-level 1
(lambda (c) (spawn-connection-handler c server-id))))
(define (spawn-connection-handler c server-id)
(actor #:name broker-server
#:state [tunnelled-gestalt (gestalt-empty)]
(send #:meta-level 1 (set-timer c (ping-interval) 'relative))
(subscribe (timer-expired c ?)
#:meta-level 1
(send #:meta-level 1 (set-timer c (ping-interval) 'relative))
(send-event 'ping))
(observe-advertisers (websocket-message c server-id ?)
#:meta-level 1
#:presence peer-connected?
(when (not peer-connected?) (quit)))
(advertise (websocket-message server-id c ?) #:meta-level 1)
(subscribe (websocket-message c server-id ($ data))
#:meta-level 1
#:run-transition (handle-incoming (drop-json-action (string->jsexpr data))))
(define (handle-incoming data)
(match data
[(routing-update g-unfiltered)
(define g (gestalt-transform g-unfiltered
(lambda (ml l p) (if (zero? ml) p '(#f . #f)))))
(begin-transition
#:update [tunnelled-gestalt g]
#:update-routes)]
[(? message? m)
(begin-transition
(when (zero? (message-meta-level m)) m))]
['ping
(begin-transition (send-event 'pong))]
['pong
(begin-transition)]))
(observe-gestalt tunnelled-gestalt
[event ;; routing-update or message, prefiltered by tunnelled-gestalt
(send-event event)])
(define (send-event e)
(send #:meta-level 1
(websocket-message server-id c (jsexpr->string (lift-json-event e)))))))
| false |
e507d73be1a8b76641684308652ceb14751d5753 | 254dab60a34e46710f8c2a3d644a3d7acdadd856 | /chapter1/tests.rkt | 76c23e2586c4dd97e8629b1f4f5409f460309d47 | []
| no_license | justuswilhelm/sicp | c4b3cbab160329084cbac630be5fd011408800f7 | 09b4399971cc07d2c08001c12c227306529f65f5 | refs/heads/master | 2020-06-16T08:45:15.993296 | 2016-11-29T20:44:34 | 2016-11-29T20:44:34 | 75,120,325 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 381 | rkt | tests.rkt | #lang racket
(require "exercises.rkt")
(require "../helpers.rkt")
(require rackunit)
(exercise 1 10)
(check-eq? (g 4) (g-simple 4))
(check-eq? (h 4) (h-simple 4))
(check-eq? (k 4) (k-simple 4))
(exercise 1 11)
(check-eq? (f-recur 4) (f-iter 4))
(exercise 1 12)
(check-eq? (pascal 5 3) 6)
(exercise 1 16)
(check-eq? (fast-expt-recur 2 0) 1)
(check-eq? (fast-expt-recur 2 3) 8)
| false |
d3af0cca88811039a966eee93ef40784534481df | f76720b592ac6498fefb25be830dc89e829555ce | /cycle_functions.rkt | 407fd901a7d4784b3188d8411ee600ee7f743721 | []
| no_license | j0shualarkin/CharacterCreator | 5db155aed5b5a8da568650ccf4eba267d2bdcd01 | 018a22386d2fa2b447fe41a08c9e5083204011ad | refs/heads/master | 2023-02-09T15:02:21.555414 | 2020-12-25T14:24:49 | 2020-12-25T14:24:49 | 324,435,180 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 4,928 | rkt | cycle_functions.rkt | #lang racket
(require "choice_struct.rkt")
(provide (all-defined-out))
(require rackunit)
(require 2htdp/image)
(require 2htdp/universe)
;; cycle-choice : Choice -> [ChoiceValue -> ChoiceValue] -> Choice
(define cycle-choice
(λ (c f)
(match c
((choice type value)
(match (assv type ChoiceMap)
[#f (error 'cycle-choice-right "couldn't find choice ~s in map" c)]
[mpr (update-choice-value c (f mpr) )])))))
(define cycle-choice-*
(λ (*_CYCLE sym)
(λ (c)
(cycle-choice
c
(match-lambda
[(cons name (list left-cycle right-cycle)) (*_CYCLE left-cycle right-cycle)]
[else
(error sym "couldnt match on the mapping for the type in the ChoiceMap: choice was ~s"
c)])
))))
;; cycle-choice-left : Choice -> Choice
(define cycle-choice-left (cycle-choice-* (λ (a b) a) 'cycle-choice-left))
;; cycle-choice-right : Choice -> Choice
(define cycle-choice-right (cycle-choice-* (λ (a b) b) 'cycle-choce-right))
;; cycle-left : World -> World
(define (cycle-left w) (cycle w cycle-choice-left))
;; cycle-right : World -> World
(define (cycle-right w) (cycle w cycle-choice-right))
(define (make-cycle-error index choices idx)
(error 'cycle-inner-loop
"index ~s shouldn't go beyond boundary of choices ~s;\n we expected to find the choice at index ~s"
index
choices
idx))
;; cycle : World [Index -> Choice -> Choice] -> World
(define (cycle w f)
(define loop
(λ (idx index choices)
(cond
[(> index (length choices))
(make-cycle-error index choices idx)]
[(= idx index)
;; apply the update function, don't look any further
(cons (f (car choices)) (cdr choices))]
[else (cons (car choices)
;; leave choice as is, loop
(loop idx (add1 index) (cdr choices)))])))
(match w
((world idx choices phase)
(world idx (loop idx 0 choices) phase))))
;;;
;;; Cycling functions for the Color and Shape ChoiceTypes
;;;
;; macro that makes an inverse function
(define-syntax inverse
(syntax-rules (match-lambda)
((_ (match-lambda [x err]))
(match-lambda [x err]))
((_ (match-lambda [a b] ...))
(match-lambda [b a] ...))))
;; cycle-*type-{left,right} : ChoiceType -> ChoiceType
(define cycle-color-left
(inverse
(match-lambda
["red" "orange"]
["orange" "yellow"]
["yellow" "green"]
["green" "blue"]
["blue" "purple"]
["purple" "white"]
["white" "black"]
["black" "red"]
#|[x (error 'update-color "unknown color: ~s" x)]|#)))
(define cycle-color-right
(match-lambda
["red" "orange"]
["orange" "yellow"]
["yellow" "green"]
["green" "blue"]
["blue" "purple"]
["purple" "white"]
["white" "black"]
["black" "red"]
#|[x (error 'update-color "unknown color: ~s" x)]|#))
(define cycle-shape-left
(match-lambda
["triangle" "circle"]
["circle" "square"]
["square" "triangle"]))
(define cycle-shape-right
(inverse
(match-lambda
["triangle" "circle"]
["circle" "square"]
["square" "triangle"])))
;; ChoiceMap is a [List [Pair ChoiceType [List [ChoiceValue -> ChoiceValue] [ChoiceValue -> ChoiceValue]]]]
(define ChoiceMap
(list (cons "Color" (list cycle-color-left cycle-color-right))
(cons "Shape" (list cycle-shape-left cycle-shape-right))))
(check-equal? (update-choice-value (choice "Color" "red") cycle-color-right)
(choice "Color" "orange"))
(check-equal? (update-choice-value (choice "Color" "red") cycle-color-left)
(choice "Color" "black"))
(check-equal? (cycle-choice-left (choice "Color" "red"))
(choice "Color" "black"))
(check-equal? (cycle-choice-left (choice "Shape" "circle"))
(choice "Shape" "square"))
(check-equal? (cycle-choice-right (choice "Shape" "circle"))
(choice "Shape" "triangle"))
(check-equal? (cycle-choice-right (choice "Color" "red"))
(choice "Color" "orange"))
(check-equal? (cycle (world 0 ex-choices #f) cycle-choice-left)
(world 0
(list (choice ChoiceType-Color "black")
choice2)
#f))
(check-equal? (cycle (world 0 ex-choices #f) cycle-choice-right)
(world 0
(list (choice ChoiceType-Color "orange")
choice2)
#f))
(check-equal? (cycle (world 1 ex-choices #f) cycle-choice-left)
(world 1
(list choice1
(choice ChoiceType-Shape "square"))
#f))
(check-equal? (cycle (world 1 ex-choices #f) cycle-choice-right)
(world 1
(list choice1
(choice ChoiceType-Shape "triangle"))
#f))
| true |
ece5f6e98c57702e99b5902f4647ac158028e764 | 2ed21adcc393425c0793e4042ffec07dcca02e82 | /network/tcp-listener.rkt | 8bf9cf6f8c20427d664450eaea460b77391a6722 | []
| no_license | shargoj/racket-sfml | 5ffa7b57c7d6742303cc7ebf5adbe4338d6b29c5 | 904949fb245a3657100b4fceed6215fe7bd85e55 | refs/heads/master | 2021-01-15T23:40:02.370391 | 2013-05-12T22:04:12 | 2013-05-12T22:04:12 | 9,787,382 | 5 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 633 | rkt | tcp-listener.rkt | #lang racket
(provide (all-defined-out))
(require
ffi/unsafe
"../sfml-util.rkt"
"defnet.rkt"
"socketstatus.rkt"
"types.rkt")
(define-all-types defnet sfTcpListener
([create (_fun -> _sfTcpListener-pointer)]
[destroy (_fun _sfTcpListener-pointer -> _void)]
[setBlocking (_fun _sfTcpListener-pointer _bool -> _void)]
[isBlocking (_fun _sfTcpListener-pointer -> _bool)]
[getLocalPort (_fun _sfTcpListener-pointer -> _ushort)]
[listen (_fun _sfTcpListener-pointer _ushort -> _sfSocketStatus)]
[accept
(_fun
_sfTcpListener-pointer
(_ptr io _sfTcpSocket-pointer)
-> _sfSocketStatus)]))
| false |
6b28dea6579fa5bba5e2642752af0f183876b890 | 1da0749eadcf5a39e1890195f96903d1ceb7f0ec | /a-d6/a-d/sorting/external/polyphase-sort.rkt | 7c226117c0423aa9cfb171b0640e466c887766d6 | []
| no_license | sebobrien/ALGO1 | 8ce02fb88b6db9e001d936356205a629b49b884d | 50df6423fe45b99db9794ef13920cf03d532d69f | refs/heads/master | 2020-04-08T20:08:16.986517 | 2018-12-03T06:48:07 | 2018-12-03T06:48:07 | 159,685,194 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 6,158 | rkt | polyphase-sort.rkt | #lang r6rs
;-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
;-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
;-*-* *-*-
;-*-* Polyphase Sort *-*-
;-*-* *-*-
;-*-* Wolfgang De Meuter *-*-
;-*-* 2010 Software Languages Lab *-*-
;-*-* Vrije Universiteit Brussel *-*-
;-*-* *-*-
;-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
;-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
(library
(polyphase-sort)
(export sort!)
(import (rnrs base)
(rnrs control)
(rnrs io simple)
(rename (a-d sorting internal comparative quicksort-m3-bounded) (sort quicksort))
(prefix (a-d heap standard) heap:)
(prefix (a-d disk file-system) fs:)
(prefix (a-d disk disk) disk:)
(prefix (a-d file sequential input-file) in:)
(prefix (a-d file sequential output-file) out:)
(prefix (a-d sorting external file-with-counted-runs) fwrs:)
(prefix (a-d sorting external outputfile-with-counted-runs) ofcr:)
(prefix (a-d sorting external inputfile-with-counted-runs) ifcr:)
(a-d scheme-tools)) ; import random-integer
(define rlen 10)
(define irun (make-vector rlen))
(define (read-run! file)
(let loop
((indx 0))
(cond ((or (= indx rlen) (not (in:has-more? file)))
indx)
(else
(vector-set! irun indx (in:read file))
(loop (+ indx 1))))))
(define (padded-read-run! file sent)
(define bsiz (read-run! file))
(if (and (not (= bsiz rlen))
(not (in:has-more? file)))
(do ((pad bsiz (+ pad 1)))
((= pad rlen) bsiz)
(vector-set! irun pad sent))
bsiz))
(define (write-run! ofcr imax)
(let loop
((indx 0))
(ofcr:write! ofcr (vector-ref irun indx))
(if (< (+ indx 1) imax)
(loop (+ indx 1)))))
(define (make-aux-bundle disks)
(define files (make-vector 3))
(vector-set! files 0 (ofcr:new (vector-ref disks 0)
"aux-0" rlen))
(vector-set! files 1 (ofcr:new (vector-ref disks 1)
"aux-1" rlen))
(vector-set! files 2 (ofcr:new (vector-ref disks 2)
"aux-2" (+ rlen rlen)))
files)
(define (delete-aux-bundle! files)
(fwrs:delete! (vector-ref files 0))
(fwrs:delete! (vector-ref files 1))
(fwrs:delete! (vector-ref files 2)))
(define (output files)
(vector-ref files 2))
(define (input files i)
(vector-ref files i))
(define (next-phase!? files)
(define irln (ifcr:run-length (input files 0)))
(define orln (ofcr:run-length (output files)))
(define last (vector-ref files 2))
(vector-set! files 2 (vector-ref files 1))
(vector-set! files 1 (vector-ref files 0))
(vector-set! files 0 last)
(ifcr:rewrite! (output files) (+ irln orln))
(ofcr:reread! (input files 0) orln)
(ifcr:has-more? (input files 1)))
(define (distribute! inpt files <<? sent)
(define (swap-input files)
(define temp (vector-ref files 0))
(vector-set! files 0 (vector-ref files 1))
(vector-set! files 1 temp))
(let loop
((fib1 1)
(fib2 0)
(out-ctr 0)
(nmbr (padded-read-run! inpt sent)))
(cond ((< out-ctr fib1)
(cond ((= nmbr 0) ; keep on writing dummy runs
(write-run! (input files 0) rlen)
(ofcr:new-run! (input files 0))
(loop fib1 fib2 (+ out-ctr 1) nmbr))
(else
(quicksort irun nmbr <<?)
(write-run! (input files 0) rlen)
(ofcr:new-run! (input files 0))
(loop fib1 fib2 (+ out-ctr 1) (padded-read-run!
inpt sent)))))
((in:has-more? inpt)
(swap-input files)
(loop (+ fib1 fib2) fib1 fib2 nmbr))))
(ofcr:reread! (input files 0) (ifcr:run-length (input files 0)))
(ofcr:reread! (input files 1) (ifcr:run-length (input files 1))))
(define (collect! files inpt sent)
(define last (input files 0))
(in:rewrite! inpt)
(let loop
((rcrd (ifcr:read last)))
(out:write! inpt rcrd)
(if (ifcr:run-has-more? last)
(let ((rcrd (ifcr:read last)))
(if (not (eq? rcrd sent))
(loop rcrd)))))
(out:close-write! inpt))
(define (read-from-files? heap files)
(define ifcr1 (input files 0))
(define ifcr2 (input files 1))
(ifcr:new-run! (input files 1))
(ifcr:new-run! (input files 0))
(when (ifcr:has-more? ifcr2)
(heap:insert! heap (cons 0 (ifcr:read ifcr1)))
(heap:insert! heap (cons 1 (ifcr:read ifcr2))))
(not (heap:empty? heap)))
(define (serve heap files)
(define el (heap:delete! heap))
(define indx (car el))
(define rcrd (cdr el))
(if (ifcr:run-has-more? (input files indx))
(heap:insert! heap (cons indx (ifcr:read (input files indx)))))
rcrd)
(define (merge! files <<?)
(define heap (heap:new 2
(lambda (c1 c2)
(<<? (cdr c1) (cdr c2)))))
(let merge-files
()
(cond ((read-from-files? heap files)
(let merge-2-runs
((rcrd (serve heap files)))
(ofcr:write! (output files) rcrd)
(if (not (heap:empty? heap))
(merge-2-runs (serve heap files))))
(ofcr:new-run! (output files))
(merge-files))
((next-phase!? files)
(merge-files)))))
(define (sort! file dsks <<? sent)
(define files (make-aux-bundle dsks))
(distribute! file files <<? sent)
(merge! files <<?)
(collect! files file sent)
(delete-aux-bundle! files))) | false |
c2ed09026971cf6ad0df6080b5c635d85188b470 | 20e13aed35dd7382496a568b6b1bf4e095442f60 | /cse1729_scheme_principles-to-programming/problem_sets/ps02/PS2.rkt | 38bcd4e81727b0dbd6908f85c45fd3e20a3bd675 | []
| no_license | ericwangg/cse_coursework | b55ecdc12cc50c75f804c0795b9214173259ae2d | 3aa5401acb580e9a67b1340399134e55a15ec23e | refs/heads/master | 2023-01-22T21:02:01.281640 | 2020-12-06T22:38:45 | 2020-12-06T22:38:45 | 319,145,521 | 0 | 2 | null | null | null | null | UTF-8 | Racket | false | false | 1,294 | rkt | PS2.rkt | "Problem Set 2 - Eric Wang"
"Problem 1A"
(define (number-sum n)
(if (= n 0)
0
(+ n (number-sum (- n 1)))))
(define (odd-sum n)
(if (= n 0)
0
(+ (- (* 2 n) 1) (odd-sum (- n 1)))))
"Problem 1B"
(odd-sum 1)
(odd-sum 2)
(odd-sum 3)
(odd-sum 4)
(odd-sum 5)
(odd-sum 6)
(odd-sum 7)
"It makes sense since adding the odd numbers from the given input, ex.): 5, (9+7+5+3+1) = 25, which gives the square of 5"
"Problem 1C"
(define (sum-from-to a b)
(if (> a b)
0
(+ b (sum-from-to a (- b 1)))))
"Problem 2"
(define (k-product k)
(if (= k 1)
1
(* (- 1 (/ 1 (expt k 2)))
(k-product (- k 1)))))
"Problem 3A"
(define (babylonian x k)
(if (= k 0)
(/ x 2)
(* 0.5 (+ (babylonian x (- k 1)) (/ x (babylonian x (- k 1)))))))
"Problem 3B"
(define (square x)
(* x x))
(define (first-value-k-or-higher x tol k)
(if (< (- (square (babylonian x k)) x) tol)
k
(first-value-k-or-higher x tol (+ k 1))))
(define (terms-needed x tol)
(first-value-k-or-higher x tol 0))
"Problem 4"
(define (factorial n)
(if (= n 0)
1
(* n (factorial (- n 1)))))
(define (new-cos x n)
(if (= n 0)
1
(+ (* (/ (expt x (* 2 n)) (factorial (* 2 n))) (expt -1 n)) (new-cos x (- n 1))))) | false |
2cec180ecaac5dd8d5b42d334d8d1057f080c202 | 40395de4446cbdbf1ffd0d67f9076c1f61d572ad | /cps-conversion/lc-partition.rkt | 4395fbcebd271f1c5fe3f6bf7efb1936310f3542 | []
| no_license | justinethier/nugget | 959757d66f0a8597ab9a25d027eb17603e3e1823 | 0c4e3e9944684ea83191671d58b5c8c342f64343 | refs/heads/master | 2020-12-22T06:36:53.844584 | 2016-07-14T03:30:09 | 2016-07-14T03:30:09 | 3,466,831 | 16 | 4 | null | null | null | null | UTF-8 | Racket | false | false | 1,631 | rkt | lc-partition.rkt | #lang racket
; Input language:
; <expr> ::= (λ (<var>) <expr>)
; | <var>
; | (<expr> <expr>)
; Output language:
; <uexp> ::= (λ (<uvar> <kvar>) <call>)
; | <uvar>
; <kexp> ::= (κ (<uvar>) <call>)
; | <kvar>
; <call> ::= ucall | kcall
; <ucall> ::= (<uexp> <uexp> <kexp>)
; <kcall> ::= (<kexp> <uexp>)
; Generate a continuation variable:
(define (genksym kv)
(gensym (string->symbol (string-append "$$k" (symbol->string kv)))))
; Generate a user variable:
(define (genusym uv)
(gensym (string->symbol (string-append "$$u" (symbol->string uv)))))
; Syntax for continuations:
(define-syntax κ
(syntax-rules ()
[(_ (uvar) call) (λ (uvar) call)]))
; Transform with a meta-continuation:
(define (T-k expr k)
(match expr
[`(λ . ,_) (k (M expr))]
[ (? symbol?) (k (M expr))]
[`(,f ,e)
; =>
(define $rv (genusym '$rv))
(define cont `(κ (,$rv) ,(k $rv)))
(T-k f (λ ($f)
(T-k e (λ ($e)
`(,$f ,$e ,cont)))))]))
; Transform with a syntactic continuation:
(define (T-c expr c)
(match expr
[`(λ . ,_) `(,c ,(M expr))]
[ (? symbol?) `(,c ,(M expr))]
[`(,f ,e)
; =>
(T-k f (λ ($f)
(T-k e (λ ($e)
`(,$f ,$e ,c)))))]))
; Transform an atomic expression:
(define (M expr)
(match expr
[`(λ (,var) ,expr)
; =>
(define $k (genksym '$k))
`(λ (,var ,$k) ,(T-c expr $k))]
[(? symbol?) #;=> expr]))
;; Examples
(M '(λ (x) x))
(T-c '(g a) 'halt)
(T-c '((f x) a) 'halt)
| true |
d5002944f84cb443bf6def6127e849b5a5b32e90 | c47ee5481e2e8a8959fda379943f4fecb89636b1 | /cebir/Teachpacks/bahce-teachpack.rkt | b86d6baaf434f7d92800c42c52a67ba2118c1c2a | []
| no_license | efeatakankaracan/Nesin-Matematik-Koyu-Cebir-Programlama | ae298c85cfc2867d872751c53ab709564af42725 | df52df852a5dfa95a5dd31c8aa35f57a3dcd791c | refs/heads/main | 2023-07-01T17:21:08.858228 | 2021-08-05T14:39:21 | 2021-08-05T14:39:21 | 393,071,079 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 6,686 | rkt | bahce-teachpack.rkt | ;#lang scheme/gui
#lang racket
; make alarm, if kelebek goes out or over well kelebek burns up...
(require lang/prim
lang/posn
"bootstrap-common.rkt"
(except-in htdp/testing test)
(for-syntax scheme/base))
(provide (all-from-out "bootstrap-common.rkt"))
(provide kelebek-imajı-üret kuyu-imajı-üret bahçe-imajı-üret kuyu-x-üret kuyu-y-üret)
(provide-higher-order-primitive start (onscreen? bahçe kuyu kelebek kuyu-x kuyu-y initial-x initial-y))
(define kelebek-list (list
(bitmap "teachpack-images/kelebek-01.png")
(bitmap "teachpack-images/kelebek-02.png")
(bitmap "teachpack-images/kelebek-03.png")
))
(define kuyu-list (list
(bitmap "teachpack-images/kuyu-01.png")
(bitmap "teachpack-images/kuyu-02.png")
(bitmap "teachpack-images/kuyu-03.png")
))
(define bahçe-list (list
(bitmap "teachpack-images/bahçe-01.png")
(bitmap "teachpack-images/bahçe-02.png")
(bitmap "teachpack-images/bahçe-03.png")
(bitmap "teachpack-images/bahçe-04.png")
))
(define (random-list-ref l)
(list-ref l (random (length l))))
(define (random-list-ref-choose l random?)
(cond
(random? (random-list-ref l))
(else (list-ref l 0))))
(define (kelebek-imajı-üret random?)
(random-list-ref-choose kelebek-list random?))
(define (bahçe-imajı-üret random?)
(random-list-ref-choose bahçe-list random?))
(define (kuyu-imajı-üret random?)
(random-list-ref-choose kuyu-list random?))
(define (koord-üret içi dışı)
(+ (random (- dışı içi)) (/ içi 2)))
(define (kuyu-x-üret bahçe kuyu random?)
(cond
(random? (koord-üret (image-width kuyu) (image-width bahçe)))
(else 320)))
(define (kuyu-y-üret bahçe kuyu random?)
(cond
(random? (koord-üret (image-height kuyu) (image-height bahçe)))
(else 200)))
(define flame (list (bitmap "teachpack-images/flame_0.gif")
(bitmap "teachpack-images/flame_1.gif")
(bitmap "teachpack-images/flame_2.gif")
(bitmap "teachpack-images/flame_3.gif")
(bitmap "teachpack-images/flame_4.gif")
(bitmap "teachpack-images/flame_5.gif")
(bitmap "teachpack-images/flame_6.gif")
(bitmap "teachpack-images/flame_7.gif")
))
(define-struct world [bahçe kuyu kelebek kuyu-x kuyu-y x y burn])
(define (change-world w new-x new-y)
(make-world (world-bahçe w)(world-kuyu w)(world-kelebek w)(world-kuyu-x w)(world-kuyu-y w) new-x new-y(world-burn w)))
(define (change-burn w new-burn)
(make-world (world-bahçe w)(world-kuyu w)(world-kelebek w)(world-kuyu-x w)(world-kuyu-y w) (world-x w) (world-y w) new-burn))
;; move: World Number -> Number
;; did the object move?
(define (move w key)
(let ((step 5))
(cond
[(not (string? key)) w]
[(string=? key "left")
(change-world w (- (world-x w) step) (world-y w))]
[(string=? key "right")
(change-world w (+ (world-x w) step) (world-y w))]
[(string=? key "down")
(change-world w (world-x w) (- (world-y w) step))]
[(string=? key "up")
(change-world w (world-x w) (+ (world-y w) step))]
[else w])))
(define (tick w)
(cond
; ((>= (world-burn w) 0) (change-burn w (modulo (add1 (world-burn w)) (length flame)))); REPEAT FLAME
((>= (world-burn w) 0) (change-burn w (min (add1 (world-burn w)) (sub1 (length flame)))))
(else w)))
(define (kelebek-image w)
(cond
((< (world-burn w) 0) (world-kelebek w))
(else (list-ref flame (world-burn w)))))
(define (burn? w)
(let*
((kbx (world-x w))
(kby (world-y w))
(kbw/2 (/ (image-width (world-kelebek w)) 2))
(kbh/2 (/ (image-height (world-kelebek w)) 2))
(kb-sağ (+ kbx kbw/2))
(kb-sol (- kbx kbw/2))
(kb-üst (+ kby kbh/2))
(kb-alt (- kby kbh/2))
(kuyu-w/2 (/ (image-width (world-kuyu w)) 2))
(kuyu-h/2 (/ (image-height (world-kuyu w)) 2))
(kuyu-x (world-kuyu-x w))
(kuyu-y (world-kuyu-y w))
(kuyu-sağ (+ kuyu-x kuyu-w/2))
(kuyu-sol (- kuyu-x kuyu-w/2))
(kuyu-üst (+ kuyu-y kuyu-h/2))
(kuyu-alt (- kuyu-y kuyu-h/2))
(ak-sağ (image-width (world-bahçe w)))
(ak-üst (image-height (world-bahçe w))))
(or
(not
(and (< kb-sağ ak-sağ)
(> kb-sol 0)
(< kb-üst ak-üst)
(> kb-alt 0)))
(not
(or (< kb-sağ kuyu-sol)
(> kb-sol kuyu-sağ)
(< kb-üst kuyu-alt)
(> kb-alt kuyu-üst))))))
(define (check-burn w)
(cond
((and (burn? w) (< (world-burn w) 0)) (change-burn w 0))
(else w)))
;; ----------------------------------------------------------------------------
;; draw-world: World -> Image
;; create an image that represents the world
(define (draw-world w)
(let* ((draw-kelebek
(lambda (w scene)
(place-image (kelebek-image w)
(world-x w)
(- (image-height (world-bahçe w)) (world-y w))
scene)))
(draw-text
(lambda (w scene)
(overlay/align "middle" "top"
(text
(string-append "x koordinat: "
(number->string (world-x w))
" y koordinat: "
(number->string (world-y w)))
14 'black)
scene))))
(draw-kelebek w
(draw-text w (place-image (world-kuyu w)
(world-kuyu-x w)
(- (image-height (world-bahçe w)) (world-kuyu-y w))
(world-bahçe w))))))
(define (start onscreen? bahçe kuyu kelebek kuyu-x kuyu-y initial-x initial-y)
(let*
((onscreen?* (if (= (procedure-arity onscreen?) 2)
onscreen?
(lambda (x y) (onscreen? x))))
(update (lambda (w k)
(if (onscreen?* (world-x (move w k))
(world-y (move w k)))
(check-burn (move w k))
w))))
(big-bang (make-world bahçe kuyu kelebek kuyu-x kuyu-y initial-x initial-y -1)
(on-draw draw-world)
(on-key update)
(on-tick tick 0.12))))
| false |
a8de0344add9124024b8e3cc177619cae3190147 | 1b3782a6d5242fdade7345d3e9157a8af0c4a417 | /tests/state-on-msg.rkt | e0bc58c7bd4fc8efbed370258bfe75d31e62428d | []
| no_license | zcc101/dpc | bb75d383f8ff6129d01d1cf33c89f7559143d24f | 54455932b8494f64f5c9a53d481968b22a15748f | refs/heads/master | 2023-03-15T10:53:55.608180 | 2017-11-29T21:57:42 | 2017-11-29T21:57:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 694 | rkt | state-on-msg.rkt | #lang class/0
;; Tests the use of the state pattern where subsequent server
;; states add an on-msg event handler.
;; See https://github.com/dvanhorn/dpc/issues/21
(require class/universe)
(require 2htdp/image)
(define-class wait%
(define (on-new iw)
(new begin%)))
(define-class begin%
(define (on-msg iw msg)
(make-bundle this (list (make-mail iw msg)) empty)))
(define-class client%
(define (register) LOCALHOST)
(define (on-tick)
(make-package this 'tick!))
(define (on-receive msg)
(error "Got here!"))
(define (to-draw)
(empty-scene 20 20 "yellow")))
(check-error
(launch-many-worlds
(universe (new wait%))
(big-bang (new client%)))
"Got here!") | false |
3d39b8dc5611ee499047833748befc72351a0e8b | 56c17ee2a6d1698ea1fab0e094bbe789a246c54f | /2019/08.rkt | 5220c6e96db7e160122c6a38db5d4096e7ba937a | [
"MIT"
]
| permissive | mbutterick/aoc-racket | 366f071600dfb59134abacbf1e6ca5f400ec8d4e | 14cae851fe7506b8552066fb746fa5589a6cc258 | refs/heads/master | 2022-08-07T10:28:39.784796 | 2022-07-24T01:42:43 | 2022-07-24T01:42:43 | 48,712,425 | 39 | 5 | null | 2017-01-07T07:47:43 | 2015-12-28T21:09:38 | Racket | UTF-8 | Racket | false | false | 1,166 | rkt | 08.rkt | #lang br
(require racket/file rackunit racket/sequence)
(define pixel-data (for/list ([c (in-string (file->string "08.rktd"))])
(string->number (string c))))
(define img-width 25)
(define img-height 6)
(define layers (for/list ([layer (in-slice (* img-width img-height) pixel-data)])
layer))
(define ((digit-count digit) layer)
(for/sum ([x (in-list layer)]
#:when (= x digit))
1))
(define least-zero-layer (argmin (digit-count 0) layers))
;; 1
(check-eq?
(* ((digit-count 1) least-zero-layer) ((digit-count 2) least-zero-layer))
2286)
(define (sum-pixels . ps)
(for/first ([p (in-list ps)]
#:when (< p 2))
p))
(define (layer->string layer)
(string-join (for/list ([row (in-slice img-width layer)])
(string-join (for/list ([digit (in-list row)])
(if (zero? digit) " " "X")) "")) "\n"))
;; 2
(check-equal? (layer->string (apply map sum-pixels layers))
" XX XX XXXX X XXX \nX X X X X X X \nX X X X X X \nX X X X XXX \nX X X X X X X \n XX XX XXXX XXXX X ") | false |
8165e99367490a5bb88ec676fab87e1ef3563500 | b42e412841fb3d63b9f7527341d5b58971f0fd2f | /c++/c++.rkt | bae2724ba67a77b2fe0d8a14ae72759a0aa1f8c5 | []
| no_license | kazzmir/extensible-c-- | 491c2d49ce9994af4be4d5e567d805ac6352e2bf | 658be0a5da98eee03012143d72ed13108812c2fb | refs/heads/master | 2021-01-15T20:29:19.008171 | 2011-05-24T01:02:48 | 2011-05-24T01:02:48 | 1,492,975 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 7,009 | rkt | c++.rkt | #lang racket/base
(require syntax/parse
"debug.rkt"
(only-in "utils.rkt" connect syntax-map)
(for-template "c++-literals.rkt"))
(provide assignment-operator
inside-curlies inside-brackets
binary-operator
operator
input-operator
dotted-identifier)
(define-literal-set operators #:for-template
(+= -= - / << >>))
(define-syntax-class assignment-operator
#:literal-sets (operators)
[pattern (~or += -=)])
(define-syntax-class input-operator
#:literal-sets (operators)
[pattern (~or << >>)])
(define-syntax-class inside-curlies
[pattern x #:when (eq? #\{ (syntax-property #'x 'paren-shape))])
(define-syntax-class inside-brackets
[pattern x #:when (eq? #\[ (syntax-property #'x 'paren-shape))])
(define-syntax-class operator
#:literal-sets (operators)
[pattern (~or - /)])
(define-syntax-class binary-operator
#:literal-sets (operators)
[pattern (~or - /)])
(define-syntax-class dotted-identifier
[pattern x:id #:when (regexp-match #rx"^\\...*" (symbol->string (syntax-e #'x)))])
#;
(define-syntax-class assignment-operator
#:literals (+=)
[pattern +=])
(define raw-identifier syntax-e)
(provide function-argument)
(define-syntax-class function-argument
#:literals (const reference pointer)
[pattern ((~optional (~and const has-const)) type:identifier
(~optional (~and reference has-reference))
(~optional (~and pointer has-pointer))
variable:identifier)
#:with final (string-append
(if (attribute has-const) "const " "")
(symbol->string (raw-identifier #'type))
" "
(if (attribute has-reference) "& " "")
(if (attribute has-pointer) "* " "")
(symbol->string (raw-identifier #'variable)))])
(provide type)
(define-splicing-syntax-class type
#:literals (pointer const signed unsigned)
[pattern (~seq (~optional (~and const has-const)) type:identifier pointer)
#:with final (format "~a~a*"
(if (attribute has-const) "const " "")
(raw-identifier #'type))]
[pattern (~seq (~optional (~and unsigned has-unsigned))
type:identifier)
#:with final (string-append
(if (attribute has-unsigned) "unsigned " "")
(symbol->string (raw-identifier #'type)))])
(define-syntax-class single-expression
[pattern (x:expression) #:with final (attribute x.final)])
(define-splicing-syntax-class (debug-here d)
[pattern (~seq) #:when (begin
(debug "Debug parse I got here ~a\n" d)
#t)])
(define-splicing-syntax-class infix-expression
[pattern (~seq (~var xx (debug-here "infix1"))
stuff ...)
#:attr final
(connect (syntax-map (lambda (x)
(debug "Parse infix '~a'\n" x)
(with-syntax ([check x])
(syntax-parse #'((check))
[(what:operator) (format "~a" (raw-identifier #'what))]
[(any:expression) (attribute any.final)])))
stuff ...)
" ")])
(define-splicing-syntax-class (debug-parse stuff)
[pattern x #:when (begin
(debug "~a\n" stuff)
#t)])
(provide expression)
(define-splicing-syntax-class expression
#:literals (sizeof cast pointer)
[pattern (~and (~seq (~var xx (debug-parse "expression 1")))
(~seq (sizeof arg:expression)))
#:attr final (format "sizeof(~a)" (attribute arg.final))]
[pattern (~seq pointer more:expression)
#:attr final (format "*~a" (syntax-e #'more.final))]
[pattern (~seq (cast stuff ...) more:expression)
#:attr final
(format "(~a) ~a" (connect (syntax-map
(lambda (x)
(symbol->string (raw-identifier x)))
stuff ...)
" ")
(attribute more.final)
)]
[pattern ((name:id (~and is:inside-curlies (index:expression))))
#:attr final
(format "~a[~a]"
(raw-identifier #'name)
(attribute index.final))]
[pattern (~and (~seq structure:inside-brackets) (~seq infix:infix-expression))
#:attr final (attribute infix.final)]
[pattern ((expression:expression flow1:dotted-identifier arg:single-expression ...))
#:attr final
(format "~a~a(~a)"
(attribute expression.final)
(syntax-e #'flow1.x)
(connect (attribute arg) ", "))]
[pattern (name:id) #:attr final (format "~a" (raw-identifier #'name))]
[pattern (constant:str) #:attr final (format "\"~a\"" (raw-identifier #'constant))]
[pattern (constant:number) #:attr final (format "~a" (raw-identifier #'constant))]
[pattern (constant:char) #:attr final
(if (eq? #\0 (raw-identifier #'constant))
"'\\0'"
(format "'~a'" (raw-identifier #'constant)))]
[pattern (~var final (debug-here "just before function call")) #:when #f]
[pattern ((name:expression arg:expression ...))
#:attr final
(format "~a(~a)" (attribute name.final)
(connect (attribute arg.final) ", "))
#;
(begin
(debug "do a function from ~a - ~a\n" expression #'name)
(format "~a(~a)"
(canonical-c++-expression #'(name))
(connect (syntax-map canonical-c++-expression (arg) ...) ", ")))]
[pattern (~var final (debug-here "just after function call")) #:when #f]
[pattern x:infix-expression #:attr final (attribute x.final)
;;else (canonical-c++-infix expression)]
])
(provide class-declaration)
(define-syntax-class class-declaration
#:literals (class)
[pattern (class name:identifier super-class:identifier body ...)
#:attr final
(format "class ~a: public ~a {\n~a\n};\n"
(raw-identifier #'name)
(raw-identifier #'super-class)
""
#;
(connect (syntax-map (lambda (what) (canonical-c++-class #'name what))
body ...)))])
| true |
e1f018226c9df08228107b2bfa9d05dc80f75474 | 7b85a7cefb9bd64e9032276844e12ebac7973a69 | /unstable-lib/gui/pict/align.rkt | 7b8fa6fb807e3855cc2305f15191f575a46a480e | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | racket/unstable | 28ac91ca96a0434db99a097a6d4d2f0a1ca26f1e | 99149bf1a6a82b2309cc04e363a87ed36972b64b | refs/heads/master | 2021-03-12T21:56:07.687374 | 2019-10-24T01:04:57 | 2019-10-24T01:04:57 | 27,411,322 | 2 | 5 | NOASSERTION | 2020-06-25T19:01:26 | 2014-12-02T02:33:45 | Racket | UTF-8 | Racket | false | false | 77 | rkt | align.rkt | #lang racket/base
(require ppict/align)
(provide (all-from-out ppict/align))
| false |
3efad2307d11320f987bde85f247f994dcefeee9 | 4919215f2fe595838a86d14926c10717f69784e4 | /lessons/Prepare-Presentation/worksheets/Extra-Space.scrbl | a78f2848e5803d453ad08fde656c8cb4b37c8abe | []
| no_license | Emmay/curr | 0bae4ab456a06a9d25fbca05a25aedfd5457819b | dce9cede1e471b0d12ae12d3121da900e43a3304 | refs/heads/master | 2021-01-18T08:47:20.267308 | 2013-07-15T12:23:41 | 2013-07-15T12:23:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 137 | scrbl | Extra-Space.scrbl | #lang curr/lib
@title{More Space for your Presentation}
@worksheet{
@free-response[#:id "More Space"]
} | false |
185a4483ff91ff0060b144ce3584f9f0408a1181 | 8620239a442323aee50ab0802bc09ab3eacdb955 | /tests/siek/explicate-control-test.rkt | e1473da148ac3cb6f36ebcae65aa6c06548be048 | []
| no_license | aymanosman/racket-siek-compiler | 45b9cffd93c57857fe94ba742770fc2540574705 | 85bcf2cf4881e7b68bfcd1d14e2c28712ab2e68e | refs/heads/master | 2022-10-20T08:56:49.918822 | 2021-02-02T17:23:37 | 2021-02-03T22:28:06 | 170,332,069 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,338 | rkt | explicate-control-test.rkt | #lang racket
(provide explicate-control-tests
explicate-control-R2-tests)
(require siek
"define-compiler-test-suite.rkt")
(module+ test
(require rackunit/text-ui)
(run-tests explicate-control-tests)
(run-tests explicate-control-R2-tests))
(define-compiler compile-R1
(uniquify-R1
normalize-R1
explicate-control-R1
remove-jumps-R1))
;; (compiler-trace! compile-R1 #t)
(define-compiler-test-suite explicate-control-tests
#:compiler compile-R1
#:signature (R1 -> C0)
2
[(read) <= "1"]
(let ([x 32])
(+ x 10))
(let ([x (let ([x 4])
(+ x 1))])
(+ x 2)))
(define-compiler compile-R2
(typecheck-R2
shrink-R2
uniquify-R2
normalize-R2
explicate-control-R2))
;; (compiler-trace! compile-R2 #t)
(define-extended-compiler-test-suite explicate-control-R2-tests explicate-control-tests
#:compiler compile-R2
#:signature (R2 -> C1)
[(- (read) (read)) <= "13 3"]
(if #t
1
2)
(if #f
1
2)
(- 10 20)
(if (< 1 2)
1
2)
(if (not (< 1 2))
1
2)
(if (if (< 1 2) #t #f)
12
13)
(if (or #f #t)
10
20)
(let ([x (if (< 1 2)
10
20)])
(+ x 100))
[(let ([x (if (< (read) (read))
10
20)])
(+ x 100))
<= "2 3"])
| false |
baeab2efb3fb16f31aeef012783014329bd311c4 | 0ad0076e542f597f37c3c793f6e7596c1bda045b | /ts-tactics/info.rkt | 00d30154804770833ed306b04d1fa36023c6a662 | []
| no_license | thoughtstem/TS-Coach | 0b57afbd52520e84f958f7c7e3e131f2521a8e9f | ceb23c8b58909c0d5f80b6341538c330a3543d4a | refs/heads/master | 2020-09-08T04:27:37.804781 | 2020-02-14T20:09:22 | 2020-02-14T20:09:22 | 221,011,766 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 373 | rkt | info.rkt | #lang info
(define collection "ts-tactics")
(define deps '("base"
"pprint"
"threading"))
(define build-deps '("scribble-lib" "racket-doc" "rackunit-lib"))
(define scribblings '(("scribblings/manual.scrbl" ())))
(define pkg-desc "Description Here")
(define version "0.0")
(define pkg-authors '(thoughtstem))
(define compile-omit-paths '())
| false |
9211b766da0b3056fa5f5d7b31619b3573167bcc | 0d4287c46f85c3668a37bcb1278664d3b9a34a23 | /陈乐天/Week8/homework8-2.rkt | b6aa2cec37bb39d701b4ca5215f25107e84113b0 | []
| no_license | siriusmax/Racket-Helper | 3e55f8a69bf005b56455ab386e2f1ce09611a273 | bf85f38dd8d084db68265bb98d8c38bada6494ec | refs/heads/master | 2021-04-06T02:37:14.261338 | 2017-12-20T04:05:51 | 2017-12-20T04:05:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,832 | rkt | homework8-2.rkt | #lang racket
(define (stream-car stream) (car stream))
(define (stream-cdr stream) (force (cdr stream)))
(define-syntax cons-stream
(syntax-rules ()
[(cons-stream x y) (cons x (delay y))]))
(define the-empty-stream '())
(define (stream-null? stream)
(null? stream))
(define (stream-ref s n) ;取 stream里面第 n 项,n从0开始算
(if (stream-null? s) the-empty-stream
(if (= n 0)
(stream-car s)
(stream-ref (stream-cdr s) (- n 1)))))
(define (stream-map proc s)
(if (stream-null? s)
the-empty-stream
(cons-stream (proc (stream-car s))
(stream-map proc (stream-cdr s)))))
(define (display-stream-n s n)
(if (= n 0)
(void)
(begin (displayln (stream-car s)) (display-stream-n (stream-cdr s) (- n 1)))))
(define (scale-stream stream factor)
(stream-map (lambda (x) (* x factor)) stream))
(define (add-stream lhs rhs)
(cons-stream
(+ (stream-car lhs) (stream-car rhs))
(add-stream (stream-cdr lhs) (stream-cdr rhs))))
(define (integral integrand initial-value dt)
(define int
(cons-stream
initial-value
(add-stream
(scale-stream integrand dt)
int)))
int)
(define (RC R C dt)
(lambda (i u0)
(add-stream (integral (scale-stream i (/ 1 C)) u0 dt) (scale-stream i R))))
(define (integers-from n)
(cons-stream n (integers-from (+ n 1))))
(define integers (integers-from 1))
(define fibs
(cons-stream 0
(cons-stream 1
(add-stream fibs (stream-cdr fibs)))))
(define RC1 (RC 5 1 0.5))
(display-stream-n (RC1 fibs 2) 10)
(displayln "******")
(display-stream-n (RC1 integers 2) 10)
(define RC2 (RC 15 10 0.2))
(displayln "******")
(display-stream-n (RC2 fibs 2) 10)
(displayln "******")
(display-stream-n (RC2 integers 2) 10) | true |
efcfb0c12301a01732ef48bf2ce14ecc32e95914 | 6d26c3f08d49093001f5cc455edb86757cdd319d | /Week 04/structs.rkt | da998596470af6bafdeb06604ec379fe82a09731 | []
| no_license | roachsinai/CSE341 | 3a99503bc551ce5423ed3bd77853c9b1041902d1 | ccca33eda73c347cef486d63d99f38d071f260d5 | refs/heads/master | 2020-06-18T04:16:09.956324 | 2014-05-22T09:14:30 | 2014-05-22T09:14:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,210 | rkt | structs.rkt | ;;
;; CSE 341 -- Racket structs
;;
;; For more information see http://docs.racket-lang.org/guide/define-struct.html
#lang racket
(define-struct point (x y))
;; we now have accessors and tests defined:
(define p (make-point 10 10))
;; try these:
;; (point? p)
;; (point-x p)
;; (point-y p)
;; (point-y p)
(define (dist p1 p2)
(let ((dx (- (point-x p1) (point-x p2)))
(dy (- (point-y p1) (point-y p2))))
(sqrt (+ (* dx dx) (* dy dy)))))
(define a (make-point 0 0))
(define b (make-point 3 4))
;; (dist a b)
;; a struct is different from the other datatypes in Racket:
(define (what-is-it v)
(cond ((number? v) 1)
((procedure? v) 2)
((cons? v) 3)
((string? v) 4)
((symbol? v) 5)
((null? v) 6)
(else 7)))
;; points as defined above are opaque (try printing one)
;; add a keyword transparent to show the fields:
(define-struct tpoint (x y) #:transparent)
;; there are many other options for structs -- another declares
;; that all fields are mutable:
(define-struct mpoint (x y) #:mutable)
(define m (make-mpoint 10 10))
;; mpoints have all of the functions as points, plus setters:
;; (set-mpoint-x! m 100)
;; (set-mpoint-y! m 200)
| false |
1d1c500f80ace84feb4090b454764b49741ad192 | 5ba3d408360006fd9785d995019761e8adc3bc41 | /hawk/main.rkt | 1111eb182704a9767c1bca6ba40db94e6b4312c7 | []
| no_license | sju-senior-projects-2019/jc | 1da50b525a0613f109a9ee717b73700ad88c176d | f422b8917808c3b6ea7f2ef8ff588faa64b52023 | refs/heads/master | 2020-04-22T06:14:42.094825 | 2019-05-03T08:09:05 | 2019-05-03T08:09:05 | 170,183,982 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 276 | rkt | main.rkt | #lang racket/base
(require hawk/expander (for-syntax racket/base syntax/parse))
(module reader syntax/module-reader hawk)
(provide
(all-from-out hawk/expander)
#%datum
#%module-begin
#%app
#%top
#%top-interaction)
| false |
ff28df8b04d1e69a76c461f2cd6ec468b955ac59 | c77e6db98a87c83042c5399a614ea4e0439470eb | /Code/Player/failing-inf-turn.rkt | c46047c31f048faa153d4d487e3d5b67690472bc | []
| no_license | mfelleisen/Santorini | 39f5295ec0dcdbf05605573a178ea0435dbc9d61 | 75beeba0121c97eb1a9c53f9fea78ad8b1a509cf | refs/heads/master | 2020-03-23T15:29:19.267778 | 2018-12-11T19:07:15 | 2018-12-11T19:07:15 | 141,751,685 | 3 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 222 | rkt | failing-inf-turn.rkt | #lang racket
;; provide a player that goes into an infinite loop during the first turn of the first game
(require "failing.rkt")
(define inf-tt (lambda (board) (let loop () (loop))))
(failing-module 1 #:tt-failure inf-tt) | false |
f849078c5faf9db6ac0b29ecaf9bac71ec73a3e1 | aca29d30eeccc279f02c5210f3757e6889e0ba22 | /main.rkt | 9879eeda1e68b3dd9319adfa9f4d130f328aed32 | []
| no_license | victorcalixto/racket2python | d9e8467f84016c90e07f83295db80e54e27a3565 | 515e1dbfab38e7efdca228dca46446c29b44da3b | refs/heads/master | 2021-07-22T07:00:49.575889 | 2017-10-31T19:16:25 | 2017-10-31T19:16:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 191 | rkt | main.rkt | #lang racket/base
(require (only-in "racket2python.rkt"
python python-str python-expression python-statement))
(provide python python-str python-expression python-statement) | false |
f15af86079d4f722b84da24bea52de2fd3b724ad | e553691752e4d43e92c0818e2043234e7a61c01b | /rosette/query/core.rkt | ec0dfd7715fbc7dab8d02dcfce9a4ed6d2971693 | [
"BSD-2-Clause"
]
| permissive | emina/rosette | 2b8c1bcf0bf744ba01ac41049a00b21d1d5d929f | 5dd348906d8bafacef6354c2e5e75a67be0bec66 | refs/heads/master | 2023-08-30T20:16:51.221490 | 2023-08-11T01:38:48 | 2023-08-11T01:38:48 | 22,478,354 | 656 | 89 | NOASSERTION | 2023-09-14T02:27:51 | 2014-07-31T17:29:18 | Racket | UTF-8 | Racket | false | false | 7,926 | rkt | core.rkt | #lang racket
(require
"eval.rkt" "finitize.rkt"
(only-in "../base/core/term.rkt" constant? term-type get-type term? with-terms clear-terms! term<? solvable-default)
(only-in "../base/core/bool.rkt" ! || && => @boolean?)
"../solver/solver.rkt"
(only-in "../solver/solution.rkt" model core sat unsat sat? unsat?)
(only-in "../solver/smt/z3.rkt" z3))
(provide current-solver ∃-solve ∃-solve+ ∃∀-solve)
; Current solver instance that is used for queries and kept alive for performance.
(define current-solver
(make-parameter (z3)
(lambda (s)
(unless (solver? s)
(error 'current-solver "expected a solver?, given ~s" s))
(solver-shutdown (current-solver))
s)))
; Searches for a model, if any, for the conjunction
; of the given formulas, using the provided solver and
; bitwidth. The solver and the bitwidth are, by default,
; current-solver and current-bitwidth. This procedure
; clears the solver's state before and after use.
(define (∃-solve φs
#:minimize [mins '()]
#:maximize [maxs '()]
#:solver [solver (current-solver)]
#:bitwidth [bw (current-bitwidth)])
(solver-clear solver)
(begin0
(with-handlers ([exn? (lambda (e) (solver-shutdown solver) (raise e))])
(cond
[bw
(with-terms
(let ([fmap (finitize (append φs mins maxs) bw)])
(solver-assert solver (for/list ([φ φs]) (hash-ref fmap φ)))
(solver-minimize solver (for/list ([m mins]) (hash-ref fmap m)))
(solver-maximize solver (for/list ([m maxs]) (hash-ref fmap m)))
(unfinitize (solver-check solver) fmap)))]
[else
(solver-assert solver φs)
(solver-minimize solver mins)
(solver-maximize solver maxs)
(solver-check solver)]))
(solver-clear solver)))
; Returns a stateful procedure that uses the solver of the given type, with the given
; bitwidth setting, to incrementally solve a sequence of constraints. The procedure
; consumes a constraint (i.e., a boolean value or term), a positive integer, or
; the symbol 'shutdown.
; If the argument is a constraint, it is pushed onto the current assertion stack and
; a solution for all constraints on the stack is returned.
; If it the argument is a positive integer k, then the top k constraints are popped
; from the stack and the result is the solution to the remaining constraints.
; If the argument is 'shutdown, all resources used by the procedure are released, and any
; subsequent calls to the procedure throw an exception.
(define (∃-solve+ #:solver [solver-type #f] #:bitwidth [bw (current-bitwidth)])
(define cust (make-custodian))
(define solver
(parameterize ([current-custodian cust]
[current-subprocess-custodian-mode 'kill])
(if (false? solver-type) ((solver-constructor (current-solver))) (solver-type))))
(define handler
(lambda (e)
(when (and solver cust)
(solver-shutdown solver)
(custodian-shutdown-all cust)
(set! solver #f)
(set! cust #f))
(raise e)))
(define sols (list (sat)))
(if bw
(let ([fmap (make-hash)])
(lambda (δ)
(with-handlers ([exn? handler])
(cond [(or (boolean? δ) (term? δ))
(finitize (list δ) bw fmap)
(solver-push solver)
(solver-assert solver (list (hash-ref fmap δ)))
(define sol (unfinitize (solver-check solver) fmap))
(set! sols (cons sol sols))
sol]
[(equal? δ 'shutdown)
(solver-shutdown solver)
(custodian-shutdown-all cust)
(set! solver #f)
(set! cust #f)
(clear-terms! ; Purge finitization terms from the cache
(for/list ([(t ft) fmap] #:when (and (term? ft) (not (eq? t ft)))) ft))]
[else
(solver-pop solver δ)
(set! sols (drop sols δ))
(car sols)]))))
(lambda (δ)
(with-handlers ([exn? handler])
(cond [(or (boolean? δ) (term? δ))
(solver-push solver)
(solver-assert solver (list δ))
(define sol (solver-check solver))
(set! sols (cons sol sols))
sol]
[(equal? δ 'shutdown)
(solver-shutdown solver)
(custodian-shutdown-all cust)
(set! solver #f)
(set! cust #f)]
[else
(solver-pop solver δ)
(set! sols (drop sols δ))
(car sols)])))))
; Solves the exists-forall problem for the provided list of inputs, assumptions and assertions.
; That is, if I is the set of all input symbolic constants,
; and H is the set of the remaining (non-input) constants appearing
; in the assumptions and the assertions,
; this procedure solves the following constraint:
; ∃H . ∀I . assumes => asserts.
; Note, however, that the procedure will *not* produce models that satisfy the above
; formula by making assumes evaluate to false.
(define (∃∀-solve inputs assumes asserts #:solver [solver #f] #:bitwidth [bw (current-bitwidth)])
(define solver-type (if (false? solver) (solver-constructor (current-solver)) solver))
(parameterize ([current-custodian (make-custodian)]
[current-subprocess-custodian-mode 'kill])
(with-terms
(with-handlers ([exn? (lambda (e) (custodian-shutdown-all (current-custodian)) (raise e))])
(begin0
(cond
[bw
(define fmap (finitize (append inputs assumes asserts) bw))
(define fsol (cegis (for/list ([i inputs]) (hash-ref fmap i))
(for/list ([φ assumes]) (hash-ref fmap φ))
(for/list ([φ asserts]) (hash-ref fmap φ))
(solver-type) (solver-type)))
(unfinitize fsol fmap)]
[else
(cegis inputs assumes asserts (solver-type) (solver-type))])
(custodian-shutdown-all (current-custodian)))))))
; Uses the given solvers to solve the exists-forall problem
; for the provided list of inputs, assumptions and assertions.
; That is, if I is the set of all input symbolic constants,
; and H is the set of the remaining (non-input) constants appearing
; in the assumptions and the assertions,
; this procedure solves the following constraint:
; ∃H. (∀I. assumes => asserts) ∧ (∃I. assumes).
(define (cegis inputs assumes asserts guesser checker)
(define φ `(,(=> (apply && assumes) (apply && asserts))))
(define ¬φ `(,@assumes ,(apply || (map ! asserts))))
(define (guess ψ)
(solver-assert guesser ψ)
(match (solver-check guesser)
[(model m) (sat (for/hash ([(c v) m] #:unless (member c inputs)) (values c v)))]
[other other]))
(define (check sol)
(solver-clear checker)
(solver-assert checker (evaluate ¬φ sol))
(match (solver-check checker)
[(? sat? m) (sat (for/hash ([i inputs])
(values i (let ([v (m i)])
(if (eq? v i)
(solvable-default (term-type i))
v)))))]
[other other]))
(let loop ([candidate (guess (append assumes asserts))])
(cond
[(unsat? candidate) candidate]
[else
(let ([cex (check candidate)])
(cond
[(unsat? cex) candidate]
[else (loop (guess (evaluate φ cex)))]))])))
| false |
2eefa218783a96cdd2b1f2d92f3d724b4fd7e20d | 453869ca6ccd4c055aa7ba5b09c1b2deccd5fe0c | /tests/basic/list.rkt | bbb34afafc32159d034096b543745990d60db222 | [
"MIT"
]
| permissive | racketscript/racketscript | 52d1b67470aaecfd2606e96910c7dea0d98377c1 | bff853c802b0073d08043f850108a57981d9f826 | refs/heads/master | 2023-09-04T09:14:10.131529 | 2023-09-02T16:33:53 | 2023-09-02T16:33:53 | 52,491,211 | 328 | 16 | MIT | 2023-09-02T16:33:55 | 2016-02-25T02:38:38 | Racket | UTF-8 | Racket | false | false | 842 | rkt | list.rkt | #lang racket/base
(define (list-sq)
(define lst '(1 2 3 4 5))
(map (lambda (x) (* x x)) lst))
(displayln (list-sq))
(displayln (length (list-sq)))
(equal? '(1 2 3) '(1 2 3))
(equal? (list 1 2 3) '(1 2 3))
(eq? '() null)
(null? '())
(list? '())
(list? (cons 1 2))
(list? (cons 1 '()))
(list? (cons 1 (cons 2 '())))
(equal? (cons 1 '()) (list 1))
(pair? '())
(pair? (cons 1 #\x))
(immutable? '())
(displayln (cons 1 #\x))
(writeln (cons 1 #\x))
(println (cons 1 #\x))
(displayln '(1 2 3))
(displayln '())
(writeln '(1 2 3))
(writeln '())
(println '(1 2 3))
(println '(1 2 3) (current-output-port) 1)
(println '())
;; anything larger will blow the stack
(build-list 1000 add1)
(remove 1 '(1 2 3))
(remove 4 '(1 2 3))
(remove 1 '())
(remove 4 '(1 2 3 4) equal?)
(remove 5 '(1 2 3 4) <)
(list->vector '())
(list->vector '(1 2 3 4))
| false |
57553470ec496cf11ab56662c0b0b220580e2ba2 | 2a59d8c57f2b4ad9a64d1c69e84516e1e5d07f42 | /satore/trie.rkt | 3a896f97a66e0f874246c5083ba2f11ba5358078 | [
"Apache-2.0",
"MIT"
]
| permissive | sethuramanio/deepmind-research | c1feb49e52fd16535c6ec0e2342c8d3ebff57ab1 | a6ef8053380d6aa19aaae14b93f013ae9762d057 | refs/heads/master | 2023-08-28T05:51:15.062153 | 2021-10-16T10:29:09 | 2021-10-16T10:29:09 | 408,818,983 | 1 | 0 | Apache-2.0 | 2021-09-21T12:52:44 | 2021-09-21T12:52:43 | null | UTF-8 | Racket | false | false | 10,276 | rkt | trie.rkt | #lang racket/base
;***************************************************************************************;
;**** Trie: Imperfect Discrimination Tree ****;
;***************************************************************************************;
;;; A discrimination tree is like a hashtable where the key is a list of elements.
;;; The keys are organized in a tree structure so that to retrieving an object
;;; takes at most O(A×l) steps, where l is the length of the key and A is the size of
;;; the alphabet. In practice it will be closer to O(l) since a hash table is used
;;; at each node to store the branches.
;;;
;;; A key is a actually tree (a list of lists of ...), which is flattened to a list
;;; where parenthesis are replaced with symbols.
;;; Variables are considered to be unnamed and there is no unification/matching.
;;; The only dependency on first-order logic specifics is `variable?`.
;;;
;;; An imperfect discrimination tree does not differentiate variable names.
;;; Hence p(X Y) is stored in the same node as p(A A). An additional tests
;;; is required to tell them apart.
(require bazaar/cond-else
define2
racket/list
racket/match
satore/misc)
(provide (except-out (all-defined-out) no-value)
(rename-out [no-value trie-no-value]))
;; Default value at the leaves. Should not be visible to the user.
(define no-value (string->uninterned-symbol "no-value"))
; Tokens used in the keys of the tree
(define anyvar (string->uninterned-symbol "¿"))
(define sublist-begin (string->uninterned-symbol "<<"))
(define sublist-end (string->uninterned-symbol ">>"))
;; edges : hasheq(key . node?)
;; value : any/c
(struct trie-node (edges value)
#:transparent
#:mutable)
(define (make-node)
(trie-node (make-hasheq) no-value))
;; Trie structure with variables.
;;
;; root : trie-node?
;; variable? : any/c -> boolean?
(struct trie (root variable?))
;; Trie constructor.
;;
;; constructor : procedure?
;; variable? : any/c -> boolean?
;; other-args : (listof any/c)
;; -> trie?
(define (make-trie #:? [constructor trie]
#:? [variable? (λ (x) #false)]
. other-args)
(apply constructor (make-node) variable? other-args))
;; Updates the value of the node for the given key (or sets one if none exists).
;; If default-val/proc is a procedure of arity 0, then it is applied to produce the
;; default value when requested, otherwise default-val/proc is used itself as the
;; default value.
;;
;; atrie : trie?
;; key : any/c
;; update : any/c -> any/c
;; default-val/proc : (or/c thunk? any/c)
;; -> void?
(define (trie-update! atrie key update default-val/proc)
(match-define (trie root variable?) atrie)
; The key is `list`ed because we need a list, and this allows the given key to not be a list.
(let node-insert! ([nd root] [key (list key)])
(cond/else
[(empty? key)
; Stop here.
(define old-value (trie-node-value nd))
(set-trie-node-value! nd (update (if (eq? old-value no-value)
(if (thunk? default-val/proc)
(default-val/proc)
default-val/proc)
old-value)))]
#:else ; key is a list
(define k (car key))
(define edges (trie-node-edges nd))
#:cond
[(pair? k)
; Linearize the tree structure of the key.
(define key2 (cons sublist-begin (append k (cons sublist-end (cdr key)))))
(node-insert! nd key2)]
#:else ; nil, atom, variable
(let ([k (if (variable? k) anyvar k)])
(define nd2 (hash-ref! edges k make-node))
(node-insert! nd2 (cdr key))))))
;; Keeps a list of values at the leaves.
;; If `trie-insert!` is used, any use of `trie-update!` should be consistent with values being lists.
;;
;; atrie : trie?
;; key : any/c
;; val : any/c
;; -> void?
(define (trie-insert! atrie key val)
(trie-update! atrie key (λ (old) (cons val old)) '()))
;; Replacing the current value (if any) for key with val.
;;
;; atrie : trie?
;; key : any/c
;; val : any/C
(define (trie-set! atrie key val)
(trie-update! atrie key (λ _ val) #false))
;; Applies on-leaf at each node that match with key.
;; The matching keys of the trie are necessarily no less general than the given key.
;; `on-leaf` may be effectful.
;;
;; atrie : trie?
;; key : any/c
;; on-leaf : trie-node? -> any
;; -> void?
(define (trie-find atrie key on-leaf)
(define variable? (trie-variable? atrie))
(let node-ref ([nd (trie-root atrie)] [key (list key)])
(cond/else
[(empty? key)
; Leaf found.
(unless (eq? no-value (trie-node-value nd))
(on-leaf nd))]
#:else
(define k (car key))
(define var-nd (hash-ref (trie-node-edges nd) anyvar #false))
#:cond
[(variable? k)
(when var-nd
; both the key and the node are variables
(node-ref var-nd (cdr key)))]
#:else
(when var-nd
; If a variable matches, consider the two paths.
(node-ref var-nd (cdr key)))
#:cond
[(pair? k)
; Linearize the tree structure of the key.
(define key2 (cons sublist-begin (append k (cons sublist-end (cdr key)))))
(node-ref nd key2)]
#:else
(define nd2 (hash-ref (trie-node-edges nd) k #false))
(when nd2
(node-ref nd2 (cdr key))))))
;; Applies the procedure `on-leaf` to any node for which the key is matched by the given key.
;; The matching keys of the trie are necessarily no more general than the given key.
;; `on-leaf` may be effectful.
;;
;; atrie : trie?
;; key : any/c
;; on-leaf : trie-node -> any/c
;; -> void?
(define (trie-inverse-find atrie key on-leaf)
(define variable? (trie-variable? atrie))
(let node-find ([nd (trie-root atrie)] [key (list key)] [depth 0])
(define edges (trie-node-edges nd))
(cond/else
[(> depth 0)
; If the depth is positive, that means we are currently matching a variable.
; We need to continue through every branch and decrease the depth only if we encounter
; a sublist-end, and increase the counter if we encounter a sublist-begin.
; Note that key can be empty while depth > 0.
(for([(k2 nd2) (in-hash edges)])
(node-find nd2 key
(cond [(eq? k2 sublist-begin) (+ depth 1)]
[(eq? k2 sublist-end) (- depth 1)]
[else depth])))]
[(empty? key)
; Leaf found.
(unless (eq? no-value (trie-node-value nd))
(on-leaf nd))]
#:else
(define k (car key))
#:cond
[(variable? k)
;; Anything matches. For sublist we need to keep track of the depth.
;; Note that variables in the tree can only be matched if k is a variable.
(for ([(k2 nd2) (in-hash edges)])
(node-find nd2 (cdr key) (if (eq? k2 sublist-begin) 1 0)))]
[(pair? k)
; Linearize the tree structure of the key.
(define key2 (cons sublist-begin (append k (cons sublist-end (cdr key)))))
(node-find nd key2 0)]
#:else
(define nd2 (hash-ref edges k #false))
(when nd2
(node-find nd2 (cdr key) 0)))))
;; Both find and inverse-find at the same time.
;; Useful when (full) unification must be performed afterwards.
;; `on-leaf` may be effectful.
;;
;; atrie : trie?
;; key : any/c
;; on-leaf : trie-node? -> any
;; -> void?
(define (trie-both-find atrie key on-leaf)
(define variable? (trie-variable? atrie))
(let node-find ([nd (trie-root atrie)] [key (list key)] [depth 0])
(define edges (trie-node-edges nd))
(cond/else
[(> depth 0)
; If the depth is positive, that means we are currently matching a variable.
; Consume everything until we find a sublist-end at depth 1.
; We need to continue through every branch and decrease the depth only if we encounter
; a sublist-end, and increase the counter if we encounter a sublist-begin.
; Note that key can be empty while depth > 0.
(for([(k2 nd2) (in-hash edges)])
(node-find nd2 key
(cond [(eq? k2 sublist-begin) (+ depth 1)]
[(eq? k2 sublist-end) (- depth 1)]
[else depth])))]
[(empty? key)
; Leaf found.
(unless (eq? no-value (trie-node-value nd))
(on-leaf nd))]
#:else
(define k (car key))
(define var-nd (hash-ref (trie-node-edges nd) anyvar #false))
#:cond
[(variable? k)
;; Anything matches. For sublist we need to keep track of the depth.
;; Note that variables in the tree can only be matched if k is a variable.
(for ([(k2 nd2) (in-hash edges)])
(node-find nd2 (cdr key) (if (eq? k2 sublist-begin) 1 0)))]
#:else
(when var-nd
; The node contains a variable, which thus matches the key.
(node-find var-nd (cdr key) 0))
#:cond
[(pair? k)
; Linearize the tree structure of the key.
(define key2 (cons sublist-begin (append k (cons sublist-end (cdr key)))))
(node-find nd key2 0)]
#:else
(define nd2 (hash-ref edges k #false))
(when nd2
(node-find nd2 (cdr key) 0)))))
;; Helper function
(define ((make-proc-tree-ref proc) atrie key)
(define res '())
(proc atrie
key
(λ (nd) (set! res (cons (trie-node-value nd) res))))
res)
;; Returns a list of values which keys are matched by the given key.
;; The matching keys of the trie are necessarily no more general than the given key.
;; These functions do not have side effects.
;;
;; Each function takes as input:
;; atrie : trie?
;; key : any/c
;; -> list?
(define trie-inverse-ref (make-proc-tree-ref trie-inverse-find))
(define trie-ref (make-proc-tree-ref trie-find))
(define trie-both-ref (make-proc-tree-ref trie-both-find))
;; Returns the list of all values in all nodes.
;;
;; atrie : trie?
;; -> list?
(define (trie-values atrie)
(let loop ([nd (trie-root atrie)] [res '()])
(define edges (trie-node-edges nd))
(define val (trie-node-value nd))
(for/fold ([res (if (eq? val no-value) res (cons val res))])
([(key nd2) (in-hash edges)])
(loop nd2 res))))
| false |
c6f0d120b08b33832fa6401198c3d40929e51863 | b08b7e3160ae9947b6046123acad8f59152375c3 | /Programming Language Detection/Experiment-2/Dataset/Train/Racket/sorting-algorithms-merge-sort-1.rkt | 767a1853351f99fa1ed861016014f3af28a1fe2d | []
| no_license | dlaststark/machine-learning-projects | efb0a28c664419275e87eb612c89054164fe1eb0 | eaa0c96d4d1c15934d63035b837636a6d11736e3 | refs/heads/master | 2022-12-06T08:36:09.867677 | 2022-11-20T13:17:25 | 2022-11-20T13:17:25 | 246,379,103 | 9 | 5 | null | null | null | null | UTF-8 | Racket | false | false | 448 | rkt | sorting-algorithms-merge-sort-1.rkt | #lang racket
(define (merge xs ys)
(cond [(empty? xs) ys]
[(empty? ys) xs]
[(match* (xs ys)
[((list* a as) (list* b bs))
(cond [(<= a b) (cons a (merge as ys))]
[ (cons b (merge xs bs))])])]))
(define (merge-sort xs)
(match xs
[(or (list) (list _)) xs]
[_ (define-values (ys zs) (split-at xs (quotient (length xs) 2)))
(merge (merge-sort ys) (merge-sort zs))]))
| false |
9f181067da0a2eeddc553226fbe48fdfa0876d21 | 1f9cbbfd10c5757d44cc016f59ad230a0babb9a6 | /CS5010-Programming-Design-Paradigm/pdp-singhay-dishasoni-master/set10/toys.bak | 451a38f270c4cf861fcca0e9b7583c4c0b8efff0 | []
| no_license | singhay/ms-courses-code | 95dda6d5902218b4e95bf63a5275de5c405a6a14 | 5f986bd66582909b306c7aabcf1c2cda261c68ba | refs/heads/master | 2021-01-01T18:21:29.043344 | 2018-11-10T21:40:58 | 2018-11-10T21:40:58 | 98,319,843 | 1 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 1,630 | bak | toys.bak | #lang racket
#|
FILENAME : toys.rkt
Program to represent a Toy factory making diffrent toys. The child
interacts with the toy by dragging the target (using smooth drag, as usual)
and by typing characters into the system. Each of the characters listed
below causes a new toy to be created with its center located at the center
of the target. Toys are also moveable using smooth drag.
GOAL : To simulate a toy with multiple attributed functionalities on a canvas.
INSTRUCTIONS:
start the program with (run 0.1 10)
Use the following keyPress to add new toys:
1. "s", a new square-shaped toy pops up.
2. "t", a new throbber appears.
3. "w", a clock appears.
4. "f", a football appears.
|#
(require rackunit)
(require "extras.rkt")
(require "sets.rkt")
(require "WidgetWorks.rkt")
(require 2htdp/universe)
(require 2htdp/image)
(require "interfaces.rkt")
(require "playgroundState.rkt")
(require "square.rkt")
(require "target.rkt")
(require "clock.rkt")
(require "football.rkt")
(require "throbber.rkt")
(require "WidgetWorks.rkt")
(check-location "10" "toys.rkt")
(provide run
Toy<%>
make-world
make-clock
make-throbber
make-football
make-square-toy
PlaygroundState<%>
Target<%>)
;run : PosNum PosInt -> Void
;GIVEN: a frame rate (in seconds/tick) and a square-speed (in pixels/tick),
;creates and runs a world in which square toys travel at the given
;speed. Returns the final state of the world.
(define (run rate square-speed)
(send (make-playground square-speed) initialise-world rate))
| false |
79c10962d2951d12f0f485d9cb638c38d3fb5c8e | 98fd4b7b928b2e03f46de75c8f16ceb324d605f7 | /drracket/gui-debugger/load-sandbox.rkt | a6c9e1e250cb0f4d5ffe0fb6ec9dbd0c9311571e | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | racket/drracket | 213cf54eb12a27739662b5e4d6edeeb0f9342140 | 2657eafdcfb5e4ccef19405492244f679b9234ef | refs/heads/master | 2023-08-31T09:24:52.247155 | 2023-08-14T06:31:49 | 2023-08-14T06:32:14 | 27,413,460 | 518 | 120 | NOASSERTION | 2023-09-11T17:02:44 | 2014-12-02T03:36:22 | Racket | UTF-8 | Racket | false | false | 3,777 | rkt | load-sandbox.rkt | #lang mzscheme
(require syntax/moddep
mzlib/class
racket/private/namespace
mred)
(provide eval/annotations
require/annotations
require/sandbox+annotations
load-module/annotate)
;; Like REQUIRE/ANNOTATIONS but the evaluation happens under the given
;; custodian and the given error display handler.
(define (require/sandbox+annotations custodian err-display-handler initial-module annotate-module? annotator)
(parameterize ([current-custodian custodian]
[current-namespace (make-gui-namespace)]
[error-display-handler err-display-handler])
(require/annotations initial-module annotate-module? annotator)))
;; Like EVAL/ANNOTATION, but loads the required spec INITIAL-MODULE using EVAL.
(define (require/annotations initial-module annotate-module? annotator)
(eval/annotations #`(require #,initial-module) annotate-module? annotator))
;; Evaluates STX. For each module loaded during the evaluation,
;; ANNOTATE-MODULE? is queried, if it returns true, ANNOTATOR is ran on the
;; expanded module being loaded, and the return value is loaded instead.
(define (eval/annotations stx annotate-module? annotator)
(parameterize
([current-load/use-compiled
(let ([ocload/use-compiled (current-load/use-compiled)])
(lambda (fn m)
(cond [(annotate-module? fn m)
(unless (and (pair? m)
(pair? (cdr m))
;; if a submodule request for a module that's
;; already loaded, don't reload
(module-declared? fn #f))
(load-module/annotate annotator fn m))]
[else
(ocload/use-compiled fn m)])))])
(eval-syntax (annotator stx))))
;; Loads the file FN expecting a definition for a module called M. The
;; code read from the file is expanded, then it is annotated using the
;; ANNOTATOR function, then it is evaluated
(define (load-module/annotate annotator fn m)
(let-values ([(base _ __) (split-path fn)]
[(in-port src) (build-input-port fn)])
(dynamic-wind
(lambda () (void))
(lambda ()
(parameterize ([read-accept-compiled #f]
[current-load-relative-directory base])
(unless m (raise 'module-name-not-passed-to-load-module/annotate))
(with-module-reading-parameterization
(lambda ()
(let* ([first (parameterize ([current-namespace (make-base-namespace)])
(expand (read-syntax src in-port)))]
[module-ized-exp (annotator (check-module-form first m fn))]
[second (read in-port)])
(unless (eof-object? second)
(raise-syntax-error
'load-module/annotate
(format "expected only a `module' declaration for `~s', but found an extra expression" m)
second))
(eval module-ized-exp))))))
(lambda () (close-input-port in-port)))))
; taken directly from mred.rkt -- it's not exported...
(define (build-input-port filename)
(let ([p (open-input-file filename)])
(port-count-lines! p)
(let ([p (cond [(regexp-match-peek "^WXME01[0-9][0-9] ## " p)
(let ([t (make-object text%)])
(send t insert-file p 'standard)
(close-input-port p)
(open-input-text-editor t))]
[else p])])
(port-count-lines! p)
(values p filename))))
| false |
568bc42b931c8a83510f6f5d17f544cd24f26039 | 5c58ab6f71ae0637bb701b21f288bc08e815f5e9 | /chapter2/243.rkt | 69d3470bf4870482f7d27b21ff2ab469ea055f99 | [
"MIT"
]
| permissive | zxymike93/SICP | 81949b33d283ac7e7603d5b02a2bd18d0bf3bd9d | a5b90334207dabeae19feaa3b441a3e64a2aee64 | refs/heads/master | 2023-01-09T03:22:13.887151 | 2022-12-28T15:11:54 | 2022-12-28T15:11:54 | 98,005,093 | 19 | 2 | null | null | null | null | UTF-8 | Racket | false | false | 4,702 | rkt | 243.rkt | #lang sicp
(define (utest fname f)
;(display fname)
;f
(newline))
;; int, int -> list
(define (enumerate-interval low high)
(if (> low high)
nil
(cons low
(enumerate-interval (+ low 1) high))))
;; (enumearte-interval 2 7) -> (2 3 4 5 6 7)
(utest "enumerate-interval: " (enumerate-interval 2 7))
(define (accumulate proc init seq)
(if (null? seq)
init
(proc (car seq)
(accumulate proc init (cdr seq)))))
;; (accumulate append nil (list (list 1 2) (list 3 4)))
;; -> (1 2 3 4)
(utest "accumulate: " (accumulate append nil (list (list 1 2) (list 3 4))))
;; proc, list -> list
(define (map proc seq)
(if (null? seq)
nil
(cons (proc (car seq))
(map proc (cdr seq)))))
;; (map - (list 1 2 3)) -> (-1 -2 -3)
(utest "map: " (map - (list 1 2 3)))
;; proc, (list (list) (list) ...) -> (append (proc list) (proc list) ...)
(define (flatmap proc seq)
(accumulate append nil (map proc seq)))
;; (flatmap lambda (list (list 1 2) (list 3 4))) -> (append (lambda (1 2)) (lambda (3 4)))
(utest "flatmap: " (flatmap (lambda (i) (list (car i))) (list (list 1 2) (list 3 4))))
;; proc, list -> (and (proc a1) (proc a2) ....)
(define (andmap proc seq)
(accumulate (lambda [x y] (and x y))
#t
(map proc seq)))
(define (filter predicate seq)
(cond [(null? seq)
nil]
[(predicate (car seq))
(cons (car seq)
(filter predicate (cdr seq)))]
[else
(filter predicate (cdr seq))]))
;; (filter odd? (list 1 2 3)) -> (1 3)
(utest "filter: " (filter odd? (list 1 2 3)))
;; 添加新的 position 到 position 序列中
;; int, int, position -> position
(define (adjoin-position row col positions)
(cons (list row col) positions))
;; (adjoin-position 1 3 (list (list 4 2) (list 6 1)))
;; -> (list (list 1 3) (list 4 2) (list 6 1))
(utest "adjoin-position: " (adjoin-position 1 3 (list (list 4 2) (list 6 1))))
;; (adjoin-position 5 4 (list (list 1 3) (list 4 2) (list 6 1)))
;; -> (list (list 5 4) (list 1 3) (list 4 2) (list 6 1))
(utest "adjoin-position: " (adjoin-position 5 4 (list (list 1 3) (list 4 2) (list 6 1))))
(define empty-board nil)
(define (safe? k positions)
(let ([k-queen (car positions)]
[k-1-queens (cdr positions)])
(and
;; 不同一行
(andmap (lambda [q] (not (= (car q) (car k-queen))))
k-1-queens)
;; 不同一列
(andmap (lambda [q] (not (= (cadr q) (cadr k-queen))))
k-1-queens)
;; 不同一对角线
(andmap (lambda [q] (not (= (- (car q) (cadr q))
(- (car k-queen) (cadr k-queen)))))
k-1-queens)
(andmap (lambda [q] (not (= (+ (car q) (cadr q))
(+ (car k-queen) (cadr k-queen)))))
k-1-queens))))
;; 假设使用这个过程计算八皇后问题,耗时为T
;(define (queens board-size)
; (define (queen-cols k)
; (if (= k 0)
; (list empty-board)
; (filter
; (lambda [positions] (safe? k positions))
; ;; 将 k-1 个子放到前 k-1 列
; (flatmap (lambda [rest-of-queens]
; ;; 第 k 个子放在第 k 列有多少种选择(第几行)
; (map (lambda [new-row]
; (adjoin-position new-row k rest-of-queens))
; (enumerate-interval 1 board-size)))
; (queen-cols (- k 1))))))
; (queen-cols board-size))
;; 如果改为以下过程,耗时多少?
(define (queens board-size)
(define (queen-cols k)
(if (= k 0)
(list empty-board)
(filter
(lambda [positions] (safe? k positions))
(flatmap (lambda [new-row]
(map (lambda [rest-of-queens]
(adjoin-position new-row k rest-of-queens))
(queen-cols (- k 1))))
(enumerate-interval 1 board-size)))))
(queen-cols board-size))
;; Original
(flatmap (map join (1 ... 8)) (q-cols 7))
(flatmap (map join (1 ... 8)) (flatmap (map join (1 ... 8)) (q-cols 6)))
...
(map join 8 (map join 8 (map join 8 (map join 8 (map join 8 (map join 8 (map join 8 (map join 8 (q-cols 0)))))))))
(map join 8 (map join 8 (map join 8 (map join 8 (map join 8 (map join 8 (map join 8 1)))))))
(map join 8 (map join 8 (map join 8 (map join 8 (map join 8 (map join 8 2))))))
...
8*7*6*5*4*3*2*1
;; Louis
(flatmap (map join (q-cols 7)) (1 ... 8))
(flatmap (map join (flatmap (map join (q-cols 6)) (1 ... 8))) (1 ... 8))
...
(map join (map join (map join (map join (map join (map join (map join (map join (q-cols 0) 8) 8) 8) 8) 8) 8) 8) 8)
...
8*8*8*8*8*8*8*8
| false |
2f7c98a39d63a55a17f1303ccfc02cc7d27bb902 | e29bd9096fb059b42b6dde5255f39d443f69caee | /metapict/scribblings/examples2.rkt | ef70e0645708086b08630d512d977ae8bfa34faa | []
| no_license | soegaard/metapict | bfe2ccdea6dbc800a6df042ec00c0c77a4915ed3 | d29c45cf32872f8607fca3c58272749c28fb8751 | refs/heads/master | 2023-02-02T01:57:08.843234 | 2023-01-25T17:06:46 | 2023-01-25T17:06:46 | 16,359,210 | 52 | 12 | null | 2023-01-25T17:06:48 | 2014-01-29T21:11:46 | Racket | UTF-8 | Racket | false | false | 7,648 | rkt | examples2.rkt | #lang scribble/manual
@(require scribble/core scribble/html-properties)
@(require (for-label (except-in racket angle open path? identity ...))
scribble/extract
scribble/eval
scribble/base
scribble/manual
"utils.rkt")
@(define eval (make-metapict-eval))
@interaction-eval[#:eval eval (require metapict)]
@(define math-style tt)
@title[#:tag "examples"]{Examples}
@; ----------------------------------------
@section[#:tag "rotating triangle" #:style svg-picts]{Rotating Triangle}
This example was inspired by Alain Matthes's
@hyperlink["http://www.texample.net/tikz/examples/rotated-triangle/"]{rotated triangle}
TikZ example.
@interaction[#:eval eval
(require metapict)
(def N 18)
(set-curve-pict-size 300 300)
(with-window (window -0.1 1.1 -0.1 1.1)
(defv (A B C) (values (pt 0 0) (pt@d 1 60) (pt 1 0)))
(first-value
(for/fold ([drawing (draw)] [A A] [B B] [C C]) ([n N])
(def triangle (curve A -- B -- C -- cycle))
(def shade (color-med (expt (/ n N) 0.4) "red" "yellow"))
(def filled (color shade (fill triangle)))
(values (draw drawing filled triangle)
(med 0.12 A B) (med 0.12 B C) (med 0.12 C A)))))]
@; ----------------------------------------
@section[#:tag "rooty helix" #:style svg-picts]{Rooty Helix}
The example shows the lengths of @racket[sqrt]@math{(n)} for values of @math{n}
from 1 to 86. The design is from Felix Lindemann's
@hyperlink["http://www.texample.net/tikz/examples/rooty-helix/"]{rooty helix}
TikZ example.
@interaction[#:eval eval
(require metapict)
(def max-r 86)
(def dark-green (make-color* 175 193 36))
(def almost-black (make-color* 50 50 50))
(define (shade r) ; white -> dark-green -> almost-black
(cond
[(<= 0 r 1/2) (color-med (* 2 r) "white" dark-green )]
[(<= r 1) (color-med (* 2 (- r 1/2)) dark-green almost-black )]
[else (error 'shader (~a "got: " r))]))
(define (spiral drawing max-r)
(def (node p r)
(def circ (circle p 1.5))
(def filled (color "white" (fill circ)))
(def label (label-cnt (~a r) p))
(draw filled circ label))
(defv (spiral θ)
(for/fold ([drawing drawing] [θ 0])
([r (in-range 1 max-r)])
(def √r (sqrt r))
(def (rotθ c) (scaled 4 (rotated θ c)))
(defv (A B C) (values (pt 0 0) (rotθ (pt √r 0)) (rotθ (pt √r 1))))
(def triangle (curve A -- B -- C -- cycle))
(def filled (color (shade (/ r 86)) (fill triangle)))
(values (draw drawing filled triangle (node B r))
(+ θ (acos (sqrt (/ r (+ 1 r))))))))
(draw spiral
(node (scaled 4 (pt@ (sqrt max-r) θ)) max-r)))
(set-curve-pict-size 600 600)
(with-window (window -40 40 -40 40)
(penwidth 0
(for/fold ([drawing (draw)]) ([r '(86 38 15)])
(spiral drawing r))))]
@; ----------------------------------------
@section[#:tag "glider" #:style svg-picts]{Glider - Hacker Emblem}
This figure is a glider, a hacker emblem. The inspiration was
Alex Hirzel @hyperlink["http://www.texample.net/tikz/examples/glider/"]{Glider}.
@interaction[#:eval eval
(set-curve-pict-size 100 100)
(with-window (window 0 3 0 3)
(margin 5
(draw (grid (pt 0 0) (pt 3 3) (pt 0 0) #:step 1)
(for/draw ([p (list (pt 0 0) (pt 1 0) (pt 2 0) (pt 2 1) (pt 1 2))])
(color "black" (fill (circle (pt+ p (vec .5 .5)) 0.42)))))))]
@section[#:tag "rainbow-circle" #:style svg-picts]{Rainbow Circle}
@interaction[#:eval eval
(scale 3 (with-window (window -5 5 -5 5)
(def colors (list "yellow" "orange" "red" "purple" "blue" "green" "yellow"))
(penwidth 16
(margin 20
(for*/draw ([θ (in-range 0 2π .01)])
(def f (/ θ 2π))
(def c (color-med* f colors))
(color (change-alpha c (- 1 f))
(draw (pt@ 4 θ))))))))]
@section[#:tag "puzzle-missing-square" #:style svg-picts]{Puzzle: The Missing Square}
The two figures are made from the same colored pieces.
It seems a square is missing from the bottom figure.
Where is it?
@interaction[#:eval eval
(define red (curve (pt 0 0) -- (pt 8 0) -- (pt 8 3) -- cycle))
(define blue (curve (pt 0 0) -- (pt 5 0) -- (pt 5 2) -- cycle))
(define green (curve (pt 0 0) -- (pt 5 0) -- (pt 5 2) -- (pt 2 2) -- (pt 2 1) -- (pt 0 1) -- cycle))
(define yellow (curve (pt 0 0) -- (pt 2 0) -- (pt 2 1) -- (pt 5 1) -- (pt 5 2) -- (pt 0 2) -- cycle))
(define (draw-pieces positions)
(for/draw ([p positions]
[d (list red green yellow blue)]
[c (list "red" "green" "yellow" "blue")])
(def fill-color (change-alpha (color-med 0.2 c "magenta") 0.7))
(def piece (shifted p d))
(draw (color fill-color (fill piece))
piece)))
(set-curve-pict-size 400 (* 13/15 400))
(with-window (window -1 14 -1 12)
(define upper (list (pt 0 0) (pt 8 0) (pt 8 1) (pt 8 3)))
(define lower (list (pt 5 2) (pt 8 0) (pt 5 0) (pt 0 0)))
(margin 2 (draw (color "gray" (draw (grid (pt -1 -1) (pt 14 12) (pt 0 0) #:step 1)))
(draw-pieces (map (shifted (pt 0 6)) upper))
(draw-pieces lower))))]
@section[#:tag "olympic-rings"]{The Olympic Rings}
The inspiration was Paul Gaborit's
@hyperlink["http://www.texample.net/tikz/examples/the-olympic-rings/"]{The Olympic Rings}.
@interaction[#:eval eval
(struct ring (center color))
(define r1 (ring (pt -4 0) (make-color* 0 129 188)))
(define r2 (ring (pt -2 -1.8) (make-color* 252 177 49)))
(define r3 (ring (pt 0 0) (make-color* 35 34 35)))
(define r4 (ring (pt 2 -1.8) (make-color* 0 157 87)))
(define r5 (ring (pt 4 0) (make-color* 238 50 78)))
(define (draw-rings . rings)
(for/draw ([r rings])
(defm (ring p c) r)
(def c1 (circle p 1.9))
(def c2 (circle p 1.5))
(draw (color c (fill c1 (curve-reverse c2)))
(penwidth 4 (color "white" (draw c1 c2))))))
(set-curve-pict-size 200 100)
(with-window (window -6 6 -4 2)
(draw (clipped (rectangle (pt -6 2) (pt 6 -1.0)) (draw-rings r5 r4 r3 r2 r1))
(clipped (rectangle (pt -6 -0.8) (pt 6 -3.8)) (draw-rings r1 r2 r3 r4 r5))))]
@section[#:tag "example-cuboid" #:style svg-picts]{Cuboid}
A cuboid drawn with a two-point vanishing perspective.
The inspiration was Florian Lesaint's
@hyperlink["http://www.texample.net/tikz/examples/cuboid/"]{Cuboid}.
@interaction[#:eval eval
(require metapict)
(def p1 (pt -7 1.5)) ; left vanishing point
(def p2 (pt 8 1.5)) ; right vanishing point
(def a1 (pt 0 0)) ; central top point
(def a2 (pt 0 -2)) ; central bottom point
(def a3 (med .8 p1 a2)) ; left bottom
(def a4 (med .8 p1 a1)) ; left top
(def a7 (med .7 p2 a2)) ; right bottom
(def a8 (med .7 p2 a1)) ; right top
(def a5 (intersection-point (curve a8 -- p1) (curve a4 -- p2)))
(def a6 (intersection-point (curve a7 -- p1) (curve a3 -- p2)))
(def f6 (curve a2 -- a3 -- a6 -- a7 -- cycle))
(def f3 (curve a3 -- a4 -- a5 -- a6 -- cycle))
(def f4 (curve a5 -- a6 -- a7 -- a8 -- cycle))
(def (a i) (vector-ref (vector #f a1 a2 a3 a4 a5 a6 a7 a8) i))
(set-curve-pict-size 300 240)
(with-window (window -2 3 -2.5 1.5)
(draw (for/draw ([f (list f3 f4 f6)]
[c (map (λ (x) (color* x "gray")) '(.9 .7 .6))])
(color c (fill f)))
(penwidth 2
(for/draw ([line '((5 6) (3 6) (7 6) (1 2) (3 4) (7 8)
(1 4) (1 8) (2 3) (2 7) (4 5) (8 5))])
(defm (list i j) line)
(curve (a i) -- (a j))))
(penwidth 8
(color "red" (draw a1 a2 a3 a4 a5 a6 a7 a8)))))]
| false |
63af1b0b7d56679ea5877afd4b0635585084324d | 8620239a442323aee50ab0802bc09ab3eacdb955 | /siek/gensym.rkt | 01c3d4313aa52e2ab6c68e15358355416ca43f8e | []
| no_license | aymanosman/racket-siek-compiler | 45b9cffd93c57857fe94ba742770fc2540574705 | 85bcf2cf4881e7b68bfcd1d14e2c28712ab2e68e | refs/heads/master | 2022-10-20T08:56:49.918822 | 2021-02-02T17:23:37 | 2021-02-03T22:28:06 | 170,332,069 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 316 | rkt | gensym.rkt | #lang racket
(provide fresh
current-gensym
make-gensym)
(define (fresh [x 'tmp])
((current-gensym) x))
(define (make-gensym [n 1])
(lambda ([x 'tmp])
(begin0
(string->symbol (format "~a.~a" x n))
(set! n (add1 n)))))
(define current-gensym (make-parameter (make-gensym)))
| false |
adc5ff0921fb8257fcfe9d393dd67518aa981d46 | c01a4c8a6cee08088b26e2a2545cc0e32aba897b | /contrib/medikanren/pieces-parts/example-synonymize.rkt | 6be34f0700f35597a85c91e66a6c45f61a73d677 | [
"MIT"
]
| permissive | webyrd/mediKanren | c8d25238db8afbaf8c3c06733dd29eb2d7dbf7e7 | b3615c7ed09d176e31ee42595986cc49ab36e54f | refs/heads/master | 2023-08-18T00:37:17.512011 | 2023-08-16T00:53:29 | 2023-08-16T00:53:29 | 111,135,120 | 311 | 48 | MIT | 2023-08-04T14:25:49 | 2017-11-17T18:03:59 | Racket | UTF-8 | Racket | false | false | 2,890 | rkt | example-synonymize.rkt | ;; Find CURIE synonyms (and their descriptive names, for convenience) for the
;; given CURIE.
;; celecoxib
(curie-synonyms/names "CHEBI:41423")
;; This expression will give the same result because it's a synonym.
;; The same should hold for all CURIE synonyms.
;(curie-synonyms/names "UMLS:C0538927")
#|
=>
(("MTHSPL:JCX84Q7J1L" . "Celecoxib")
("CHEMBL.COMPOUND:CHEMBL118" . "CELECOXIB")
("DrugBank:DB00482" . "Celecoxib")
("CUI:C0538927" . "Celecoxib")
("MeSH:C105934" . "Celecoxib")
("CHEMBL:CHEMBL118" . "Celecoxib")
("NDFRT:N0000007233" . "Celecoxib [Chemical/Ingredient]")
("HMDB:HMDB0005014" . "Celecoxib")
("DRUGBANK:DB00482" . "Celecoxib")
("CHEBI:41423" . "celecoxib")
("RXNORM:140587" . "celecoxib")
("PUBCHEM:2662" . "Celecoxib")
("NDFRT:N0000148596" . "Celecoxib")
("UMLS:C0538927" . "celecoxib"))
|#
;; e2f1
(curie-synonyms/names "UMLS:C0812258")
#|
=>
(("UMLS:C0812258" . "E2F1 gene")
("OMIM:189971" . "E2f transcription factor 1")
("NCI:C18379" . "E2F1 gene")
("UniProtKB:Q9BSD8" . "E2F1 gene")
("HGNC:3113" . "E2F1 (human)")
("NCIT:C18379" . "E2F1 Gene")
("NCBIGene:1869" . "E2F transcription factor 1")
("UniProtKB:Q01094" . "E2F-1;")
("ENSEMBL:ENSG00000101412"
.
"E2F transcription factor 1 [Source:HGNC Symbol;Acc:HGNC:3113]")
("CUI:C0812258" . "E2f transcription factor 1")
("NCBIGENE:1869" . "E2F1 gene"))
"query.rkt">
|#
;; rhobtb2
(curie-synonyms/names "UMLS:C1425762")
#|
=>
(("UniProtKB:Q9BYZ6" . "RHOBTB2")
("UniProtKB:E5RI44" . "RHOBTB2")
("UMLS:C1425762" . "RHOBTB2 gene")
("NCBIGene:23221" . "Rho related BTB domain containing 2")
("HGNC:18756" . "RHOBTB2 (human)")
("NCBIGENE:23221" . "RHOBTB2")
("OMIM:607352" . "Rho-related btb domain-containing protein 2")
("ENSEMBL:ENSG00000008853"
.
"Rho related BTB domain containing 2 [Source:HGNC Symbol;Acc:HGNC:18756]")
("CUI:C1425762" . "Rho-related btb domain-containing protein 2"))
"query.rkt">
|#
;; failure to thrive
(curie-synonyms/names "HP:0001508")
#|
=>
(("MEDDRA:10047897" . "Weight gain poor")
("CUI:C0231246" . "Failure to gain weight")
("UMLS:C0231246" . "Failure to gain weight")
("CUI:C2315100" . "Pediatric failure to thrive")
("MEDDRA:10036164" . "Poor weight gain")
("UMLS:C2315100" . "Weight gain poor")
("HP:0001508" . "failure to thrive"))
|#
;; bcr
(curie-synonyms/names "UMLS:C0812385")
#|
=>
(("UniProtKB:H0Y554" . "BCR gene")
("UMLS:C0812385" . "BCR gene")
("NCBIGene:613" . "BCR activator of RhoGEF and GTPase")
("NCI:C18455" . "BCR gene")
("ENSEMBL:ENSG00000186716"
.
"BCR activator of RhoGEF and GTPase [Source:HGNC Symbol;Acc:HGNC:1014]")
("Orphanet:119016" . "BCR activator of RhoGEF and GTPase")
("NCBIGENE:613" . "BCR gene")
("NCIT:C18455" . "BCR Gene")
("UniProtKB:P11274" . "BCR")
("HGNC:1014" . "Bcr")
("OMIM:151410" . "Breakpoint cluster region")
("CUI:C0812385" . "Breakpoint cluster region"))
|#
| false |
7acef33584358ca2014ba3e103471e618ccc2fab | 93b116bdabc5b7281c1f7bec8bbba6372310633c | /plt/tspl/codes/ch2/list-procedures.rkt | 0e5f67262b3f4204a8584d9a184d00a1b6b3fc60 | []
| no_license | bianyali/BookList | ac84aa5931ced43f99269f881e009644ce68bb49 | ef64c71ac5da235bfab98336e2deb049e8c35b67 | refs/heads/master | 2021-01-17T10:13:20.341278 | 2015-12-29T04:45:53 | 2015-12-29T04:45:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 330 | rkt | list-procedures.rkt | #lang racket
(car '(a b c))
(cdr '(a b c))
(car (cdr '(a b c)))
(cdr (cdr '(a b c)))
(car '((a b) (c d)))
(cdr '((a b) (c d)))
(cons 'a '())
(cons 'a '(b c))
(cons 'a (cons 'b (cons 'c '())))
(car (cons 'a '(b c)))
(cdr (cons 'a '(b c)))
(cons (car '(a b c))
(cdr '(d e f)))
(cons (car '(a b c))
(cdr '(a b c)))
| false |
30b09726aab7ba7817432883757fcf6293b31d2f | 9910cb51ccc1b9ca880c6876de6ff1d2094a3c87 | /ents.rkt | bcc37e4913eb0647615ed981f60c2778c1982863 | [
"Apache-2.0"
]
| permissive | nickcollins/zinal | 0b3a2321bd78541a2a55c5784b8ad8db73a126e4 | 7c77e792a8873fbf34bafa12d9926695b140b1ef | refs/heads/master | 2021-01-20T04:29:48.072021 | 2017-06-19T21:23:49 | 2017-06-19T21:23:49 | 89,699,525 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 131,291 | rkt | ents.rkt | ; Copyright 2017 Nick Collins
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
; Similar to "#lang racket"
(module ents racket
(require racket/gui/base)
(require racket/set)
(require (only-in srfi/1 list-index))
(require "misc.rkt")
(require "db.rkt")
(require "db-util.rkt")
(require "ui.rkt")
(require "ui-styles.rkt")
(require "key-bindings.rkt")
(provide zinal:ent:manager%)
(define event-handler%% (interface ()
handle-event!! ; (event)
))
(define fallback-event-handler%% (interface ()
handle-child-event!! ; (event)
))
; TERMINOLOGY AND CONCEPTS
; The db is a rather simple and minimalistic representation of the logic. Displaying it literally
; as a tree would be verbose and ugly. We want a middle layer that parses this "low-level" tree into
; a more concise, sophisticated, "high-level" tree. To do so, we will partition the db into a set of
; "cones". A "cone" is a partial subtree. It is any tree, whose nodes (and edges) are a subset of the
; "embedding" tree, but whose leaves need not be leaves of the embedding tree. Each cone of the
; partitioned db will be implicitly represented by an "ent". Besides storing the root and leaves
; of the corresponding cone, an ent is responsible for building and maintaining a ui cone that
; represents the corresponding db cone. UI cones sum up to form a full ui tree which is used by a
; front-end to display a gui. The displayed gui does not handle events - instead, events are sent to
; the ent-manager (the only part of the ent system that the front-end knows about), which then sends
; the event to the selected ui item, which uses an event handler provided to it by the ent and which
; can be changed or updated by the ent. So ui items store event handlers, but the assignment and
; implementation of those handlers are the responsibility of the ent.
; HELPER FUNCTIONS
(define (standard*? db-racket-handle)
(not (send db-racket-handle get-library))
)
(define (standard-with-name*? db-racket-handle name)
(and (standard*? db-racket-handle) (equal? name (send db-racket-handle get-name)))
)
(define (can-be-public*? define-handle)
(and
(is-one-of? define-handle (list zinal:db:def%% zinal:db:define-class%%))
(is-a? (send define-handle get-parent) zinal:db:module%%)
)
)
(define (public*? define-handle)
(assert "cannot assess \"publicity\" of non-def or non-module-child" (can-be-public*? define-handle))
(findf (curry handles-equal? define-handle) (send (send define-handle get-parent) get-public-defs))
)
(define (get-containing-class* node)
(and node (if (is-a? node zinal:db:class%%) node (get-containing-class* (send node get-parent))))
)
(define (issue-warning title message)
(message-box title message #f '(ok caution))
)
(define (get-zinal-super-class* subclass)
(define super-class-ref (send subclass get-super-class))
(and (is-a? super-class-ref zinal:db:class-ref%%) (send super-class-ref get-define-class))
)
; EVENT HANDLER
; Everything is terrible
(define handle-event-info% (class object%
(define was-handled*? #t)
(define was-db-affected*? #t)
(define/public (was-handled?)
was-handled*?
)
(define/public (was-db-affected?)
(and was-handled*? was-db-affected*?)
)
(define/public (set-wasnt-handled!)
(set! was-handled*? #f)
; for convenience; also terrible
#t
)
(define/public (set-db-wasnt-affected!)
(set! was-db-affected*? #f)
; for convenience; also terrible
#t
)
(super-make-object)
))
(define keyname-event-handler% (class* object% (event-handler%%)
; handler-function&keynames=pairs is a list of pairs, first item is an event handler function
; and second is a list of key names that invoke the function
(init handler-function&keynames=pairs)
(define handler-function&keynames=pairs* handler-function&keynames=pairs)
(define keymap* (make-object keymap%))
(begin
(define seen-keynames (mutable-set))
(for-each
(lambda (handler-function&keynames)
(define handler-function (first handler-function&keynames))
(define keynames (second handler-function&keynames))
(define function-name (string-join (sort keynames string<?) " "))
(send keymap* add-function function-name handler-function)
(for-each
(lambda (keyname)
(assert
(format "keyname ~a already exists" keyname)
(not (set-member? seen-keynames keyname))
)
(set-add! seen-keynames keyname)
(send keymap* map-function keyname function-name)
)
keynames
)
)
handler-function&keynames=pairs
)
)
(define/public (handle-event!! event)
(define info (make-object handle-event-info%))
(define was-handler-found?
(if (is-a? event key-event%)
(send keymap* handle-key-event info event)
(send keymap* handle-mouse-event info event)
)
)
(unless was-handler-found? (send info set-wasnt-handled!))
info
)
(define/public (get-handler-function&keynames=pairs*)
handler-function&keynames=pairs*
)
(super-make-object)
))
(define NOOP (make-object keyname-event-handler% '()))
(define NOOP-FALLBACK-EVENT-HANDLER (make-object (class* object% (fallback-event-handler%%)
(define/public (handle-child-event!! event) (send NOOP handle-event!! event))
(super-make-object)
)))
(define THING->NOOP (const NOOP))
(define (combine-keyname-event-handlers event-handlers)
(make-object keyname-event-handler%
(append* (map (lambda (h) (send h get-handler-function&keynames=pairs*)) event-handlers))
)
)
; SLOTS
(define slot% (class* object% (fallback-event-handler%%)
(init slot->event-handler fallback-event-handler)
(define ent* #f)
(define event-handler* (slot->event-handler this))
(define fallback-event-handler* fallback-event-handler)
; Must be called at least once immediately after creation
(define/public (set-ent! new-ent)
(set! ent* new-ent)
)
(define/public (get-ent)
(assert-valid*)
ent*
)
(define/public (handle-child-event!! event)
(assert-valid*)
(define event-info (send event-handler* handle-event!! event))
(or
(and (send event-info was-handled?) event-info)
(send fallback-event-handler* handle-child-event!! event)
)
)
(define (assert-valid*)
(assert "ent must be initialized before using" ent*)
)
(super-make-object)
))
; INTERACTION GUI
(define choice-dialog%
(class dialog% ; abstract
(init label)
(abstract get-choice-from-ui*)
(define chosen* #f)
(define has-been-chosen* #f)
(define/override (on-subwindow-char receiver key-event)
(case (send key-event get-key-code)
[(#\return)
(set! has-been-chosen* #t)
(close*!)
#t
]
[(#\tab)
(super on-subwindow-char receiver key-event)
#f
]
[else (super on-subwindow-char receiver key-event)]
)
)
(define/override (on-activate activated?)
(super on-activate activated?)
; TODO this is a dirty dirty hack to force the choice% to focus against its will
; TODO see https://groups.google.com/forum/#!msg/racket-users/ph2nfGslyuA/AjAM6wMMAwAJ
(send this on-subwindow-char this (make-object key-event% #\tab))
)
(define (on-close)
(set! chosen*
(if has-been-chosen*
(get-choice-from-ui*)
#f
)
)
)
(augment on-close)
(define/public (get-choice)
chosen*
)
(define (close*!)
(send this on-close)
(send this show #f)
)
(super-make-object label)
)
)
(define auto-complete-dialog%
(class choice-dialog%
; key-equalifier takes two key args and returns whether they're equivalent.
; The first arg will never be #f, but the second one may be
(init title message keys&choices [key-equalifier equal?])
(define this* this)
(define keys&choices* (sort keys&choices (lambda (a b) (string<? (second a) (second b)))))
(define chooser* #f)
(define auto-complete-list-box%
(class list-box%
(define chars '())
(define/override (on-subwindow-char receiver key-event)
(define cur-selection-cur-index (send this get-selection))
(define cur-selection-key (and cur-selection-cur-index (send this get-data cur-selection-cur-index)))
(define num-cur-choices (send this get-number))
(define key-code (send key-event get-key-code))
(case key-code
[(#\tab)
(send this set-selection
(if (= cur-selection-cur-index (sub1 num-cur-choices))
0
(add1 cur-selection-cur-index)
)
)
#t
]
[(#\backspace #\rubout)
(cond
[(pair? chars)
(set! chars (take chars (sub1 (length chars))))
(build-choices*! cur-selection-key)
#t
]
[else #f]
)
]
[else
(cond
[(char? key-code)
(define char (char-downcase key-code))
(set! chars (append chars (list char)))
(build-choices*! cur-selection-key)
#t
]
[else #f]
)
]
)
)
(define (build-choices*! selection-key)
(send this clear)
(define found-exact-match? #f)
(for-each
(lambda (pair)
(define key (car pair))
(define choice (second pair))
(define choice-list (string->list (string-downcase choice)))
(when (subsequence? chars choice-list)
(send this append choice key)
(define cur-index (sub1 (send this get-number)))
(when (equal? chars choice-list)
(set! found-exact-match? #t)
(send this set-selection cur-index)
)
(when (and (not found-exact-match?) selection-key (key-equalifier selection-key key))
(send this set-selection cur-index)
)
)
)
keys&choices*
)
(when (zero? (send this get-number)) (reset-choices*!))
(unless (send this get-selection)
(send this set-selection 0)
)
; TODO very hacky sizing
(send this min-height (+ 60 (* 25 (send this get-number))))
)
(define (subsequence? candidate sequence)
(cond
[(null? candidate)
#t
]
[(null? sequence)
#f
]
[(equal? (car candidate) (car sequence))
(subsequence? (cdr candidate) (cdr sequence))
]
[else
(subsequence? candidate (cdr sequence))
]
)
)
(define (reset-choices*!)
(set! chars '())
(build-choices*! #f)
)
(super-make-object message '() this* (const #f) '(single vertical-label))
(reset-choices*!)
)
)
(define/override (get-choice-from-ui*)
(define cur-index (send chooser* get-selection))
(and cur-index (send chooser* get-data cur-index))
)
(super-make-object title)
(set! chooser* (make-object auto-complete-list-box%))
)
)
(define (auto-complete* title message keys&choices [key-equalifier equal?])
(cond
[(pair? keys&choices)
(define dialog
(make-object auto-complete-dialog% title message keys&choices key-equalifier)
)
(send dialog show #t)
; ugly hack to solve some weird gui focus race condition. See blame for more details.
(sleep .05)
(send dialog get-choice)
]
[else
#f
]
)
)
(define discrete-choice-dialog%
(class choice-dialog%
(init title message choices)
(define this* this)
(define choices* choices)
(define num-choices* (length choices))
(define chooser* #f)
(define keyboard-choice%
(class choice%
(define chars "")
(define/override (on-subwindow-char receiver key-event)
(define current-selection (send this get-selection))
(define key-code (send key-event get-key-code))
(define (reset-chars!) (set! chars ""))
(case key-code
[(#\J)
(reset-chars!)
(unless (= current-selection (sub1 num-choices*))
(send this set-selection (add1 current-selection))
)
#t
]
[(#\K)
(reset-chars!)
(unless (zero? current-selection)
(send this set-selection (sub1 current-selection))
)
#t
]
[else
(cond
[(and (char? key-code) (char-alphabetic? key-code))
(define char (char-downcase key-code))
(set! chars (string-append chars (string char)))
(define candidate (findf (curryr string-prefix? chars) choices*))
(if candidate
(send this set-string-selection candidate)
(reset-chars!)
)
#t
]
[else #f]
)
]
)
)
(super-make-object message choices this* (const #f) '(vertical-label))
)
)
(define/override (get-choice-from-ui*)
(send chooser* get-selection)
)
(super-make-object title)
(set! chooser* (make-object keyboard-choice%))
)
)
(define (get-choice-from-user title message choices)
(cond
[(pair? choices)
(define dialog (make-object discrete-choice-dialog% title message choices))
(send dialog show #t)
; ugly hack to solve some weird gui focus race condition. See blame for more details.
(sleep .05)
(send dialog get-choice)
]
[else
#f
]
)
)
; new-blah-creator is a function of form
; (zinal:db:node%% , list-of zinal:db:referable%%) => (zinal:db:unassigned%% => zinal:db:element%%) OR #f
; parent-handle is the parent of the existing or yet-to-be-created node that will be assigned.
; parent-handle need not be the exact parent, as long as there is no zinal:db:class%% in between parent-handle and the creation location
; visible-referables are handles for all referables that are visible to any newly minted nodes.
; If it returns #f, it means no operation should be performed
; The returned creator is destructive and must succeed
(define (new-list-creator parent-handle visible-referables)
(lambda (unassigned) (send unassigned assign-list!!))
)
(define (new-assert-creator parent-handle visible-referables)
(lambda (unassigned)
(define db-assert-handle (send unassigned assign-assert!!))
(send (send db-assert-handle get-assertion) assign-bool!! #t)
(send (send db-assert-handle get-format-string) assign-string!! "Something went wrong ...")
db-assert-handle
)
)
(define (use-text-from-user title message resultificator [validator (const #t)])
(define result
(get-text-from-user
title
message
#f
""
'(disallow-invalid)
#:validate validator
)
)
(and result (validator result) (resultificator result))
)
(define (new-number-creator parent-handle visible-referables)
(use-text-from-user
"Enter a number"
"I believe in you"
(lambda (result)
(lambda (unassigned) (send unassigned assign-number!! (string->number result)))
)
string->number
)
)
(define (new-character-creator parent-handle visible-referables)
(use-text-from-user
"Enter a character"
"I believe in you"
(lambda (result)
(lambda (unassigned) (send unassigned assign-char!! (string-ref result 0)))
)
(compose1 (curry = 1) string-length)
)
)
(define (new-string-creator parent-handle visible-referables)
(use-text-from-user
"Enter a string"
"I believe in you"
(lambda (result)
(lambda (unassigned) (send unassigned assign-string!! result))
)
)
)
(define (new-symbol-creator parent-handle visible-referables)
(use-text-from-user
"Enter a symbol as a string"
"Don't include the leading '"
(lambda (result)
(lambda (unassigned) (send unassigned assign-symbol!! (string->symbol result)))
)
)
)
(define (new-keyword-creator parent-handle visible-referables)
(use-text-from-user
"Enter a keyword as a string"
"Don't include the leading #:"
(lambda (result)
(lambda (unassigned) (send unassigned assign-keyword!! (string->keyword result)))
)
)
)
(define (new-boolean-creator parent-handle visible-referables)
(define choices '("true" "false"))
(define result (get-choice-from-user "To be or not to be?" "That's the question" choices))
(and result
(lambda (unassigned) (send unassigned assign-bool!! (= result 0)))
)
)
(define (new-define-creator parent-handle visible-referables)
(use-text-from-user
"Enter the new definition's short descriptor"
"A short descriptor, one or a few words, to identify this variable"
(lambda (result)
(lambda (unassigned) (send unassigned assign-def!! result))
)
non-empty-string?
)
)
(define (new-lambda-creator parent-handle visible-referables)
(lambda (unassigned) (send unassigned assign-lambda!!))
)
(define (get-referable-from-user allowed-referables)
(and (pair? allowed-referables)
(auto-complete*
"Select a referable"
"Start typing bits and pieces of the desired referable's short descriptor"
(map (lambda (handle) (list handle (get-short-desc-or handle "<no desc>"))) allowed-referables)
handles-equal?
)
)
)
(define (new-value-read-creator parent-handle visible-referables)
(define chosen-handle (get-referable-from-user visible-referables))
(and chosen-handle
(lambda (unassigned)
(cond
[(is-a? chosen-handle zinal:db:param%%) (send unassigned assign-param-ref!! chosen-handle)]
[(is-a? chosen-handle zinal:db:def%%) (send unassigned assign-def-ref!! chosen-handle)]
[(is-a? chosen-handle zinal:db:define-class%%) (send unassigned assign-class-ref!! chosen-handle)]
[(is-a? chosen-handle zinal:db:interface%%) (send unassigned assign-interface-ref!! chosen-handle)]
[else (error 'new-value-read-creator "Invalid referable")]
)
)
)
)
(define (get-standard-racket-from-user)
(use-text-from-user
"Enter the racket standard library identifier"
"It must be from the standard racket library. Use the non-standard option if you want to use an identifier from a different library"
identity
; TODO we need to add a reflective validator
(conjoin non-empty-string? (negate (curryr member ILLEGAL-STANDARD-RACKETS)))
)
)
(define (get-non-standard-racket-from-user)
(define library
(use-text-from-user
"Enter the racket library name"
"Enter exactly what you would enter as the argument to racket 'require - e.g. 'racket/hash' (without quotes)"
identity
; TODO we need to add a reflective validator
non-empty-string?
)
)
(define name
(and library
(use-text-from-user
"Enter the identifier name"
"The identifier's name, not including its library"
identity
; TODO we need to add a reflective validator
non-empty-string?
)
)
)
(and name (list library name))
)
(define (new-standard-racket-creator parent-handle visible-referables)
(define result (get-standard-racket-from-user))
(and result
(lambda (unassigned) (send unassigned assign-racket!! #f result))
)
)
(define (new-non-standard-racket-creator parent-handle visible-referables)
(define library&name (get-non-standard-racket-from-user))
(and library&name
(lambda (unassigned) (send unassigned assign-racket!! (first library&name) (second library&name)))
)
)
(define (new-unassigned-creator parent-handle visible-referables)
identity
)
(define (get-method-from-user choosable-referables)
(define visible-types (filter (curryr is-a? zinal:db:type%%) choosable-referables))
(define type-with-desired-method
(or
(and (= 1 (length visible-types)) (car visible-types))
(auto-complete*
"Select the type which possesses the method"
"Sorry, zinal isn't smart enough to figure out the appropriate type from context, so please enlighten"
(map (lambda (type-handle) (list type-handle (get-short-desc-or type-handle "<unnamed type>"))) visible-types)
handles-equal?
)
)
)
(and type-with-desired-method
(auto-complete*
"Select a method"
"Start typing bits and pieces of the desired method's short descriptor"
(map (lambda (method-handle) (list method-handle (get-short-desc-or method-handle "<unnamed method>"))) (send type-with-desired-method get-all-methods))
handles-equal?
)
)
)
(define (get-super-method-from-user node-handle)
(define super-class-handle (get-zinal-super-class* (get-containing-class* node-handle)))
(cond
[super-class-handle
(auto-complete*
"Select a super method"
"Start typing bits and pieces of the desired method's short descriptor"
(map
(lambda (method-handle) (list method-handle (get-short-desc-or method-handle "<unnamed method>")))
(filter (lambda (m) (not (send super-class-handle is-method-abstract? m))) (send super-class-handle get-all-methods))
)
handles-equal?
)
]
[else
(issue-warning "Can't invoke zinal super method" "This class's super class is a racket class, so it can't super invoke any zinal methods")
#f
]
)
)
(define (get-method-to-define/override-from-user node-handle)
(define class-handle (get-containing-class* node-handle))
(cond
[class-handle
(auto-complete*
"Select a method to define or override"
"Start typing bits and pieces of the desired method's short descriptor"
(map
(lambda (method-handle) (list method-handle (get-short-desc-or method-handle "<unnamed method>")))
(filter (lambda (m) (not (send class-handle get-direct-definition-of-method m))) (send class-handle get-all-methods))
)
handles-equal?
)
]
[else
(issue-warning "Can't define/override method" "A method definition or override must be the immediate child of a class, nowhere else")
#f
]
)
)
(define (check-in-class? node-handle)
(cond
[(get-containing-class* node-handle)
#t
]
[else
(issue-warning "Cannot create OOP node here" "The type of node you're trying to create can only exist inside a class body")
#f
]
)
)
(define (check-directly-in-class? parent-handle)
(cond
[(is-a? parent-handle zinal:db:class%%)
#t
]
[else
(issue-warning "Cannot create OOP node here" "The type of node you're trying to create can only exist as the direct child of a class")
#f
]
)
)
(define (check-directly-in-define-class? parent-handle)
(cond
[(is-a? parent-handle zinal:db:define-class%%)
#t
]
[else
(issue-warning
"Cannot define new method here"
"A new method can only be defined in a class definition. If you want to override a super class method, choose the 'define/override existing method' option"
)
#f
]
)
)
(define (switch-r/z r/z-title r-title r-result-handler z-handler)
(define zinal/racket '("zinal" "racket"))
(define choice-index (get-choice-from-user r/z-title "The choice is yours, and yours alone" zinal/racket))
(and choice-index
(if (zero? choice-index)
(z-handler)
(use-text-from-user
r-title
"I believe in you ..."
r-result-handler
non-empty-string?
)
)
)
)
(define (new-invoke-method-creator parent-handle visible-referables)
(switch-r/z
"Invoke a racket method or a zinal method?"
"Enter the name of the racket method to invoke"
(lambda (result)
(lambda (unassigned) (send unassigned assign-invoke-racket-method!! result))
)
(thunk
(define method (get-method-from-user visible-referables))
(and method
(lambda (unassigned) (send unassigned assign-invoke-method!! method))
)
)
)
)
(define (new-invoke-this-method-creator parent-handle visible-referables)
(and (check-in-class? parent-handle)
(switch-r/z
"Invoke a racket method or a zinal method?"
"Enter the name of the racket method to invoke"
(lambda (result)
(lambda (unassigned)
(define result-handle (send unassigned assign-invoke-racket-method!! result))
(send (send result-handle get-object) assign-this!!)
result-handle
)
)
(thunk
(define method
(auto-complete*
"Select a method"
"Start typing bits and pieces of the desired method's short descriptor"
(map (lambda (method-handle) (list method-handle (get-short-desc-or method-handle "<unnamed method>"))) (send (get-containing-class* parent-handle) get-all-methods))
handles-equal?
)
)
(and method
(lambda (unassigned)
(define result-handle (send unassigned assign-invoke-method!! method))
(send (send result-handle get-object) assign-this!!)
result-handle
)
)
)
)
)
)
(define (new-invoke-super-method-creator parent-handle visible-referables)
(and (check-in-class? parent-handle)
(switch-r/z
"Invoke a racket super method or a zinal super method?"
"Enter the name of the racket method to invoke"
(lambda (result)
(lambda (unassigned) (send unassigned assign-invoke-racket-super-method!! result))
)
(thunk
(define method (get-super-method-from-user parent-handle))
(and method
(lambda (unassigned) (send unassigned assign-invoke-super-method!! method))
)
)
)
)
)
(define (new-define-new-method-creator parent-handle visible-referables)
(and (check-directly-in-define-class? parent-handle)
(use-text-from-user
"Enter a short description of the new method"
"A short descriptor, one or a few words, to identify the new method"
(lambda (result)
(lambda (unassigned)
(define new-method-handle (send parent-handle add-direct-method!! result))
(send unassigned assign-define-method!! new-method-handle)
)
)
non-empty-string?
)
)
)
(define (new-define-existing-method-creator parent-handle visible-referables)
(and (check-directly-in-class? parent-handle)
(switch-r/z
"Override a racket super method, or define/override a zinal method?"
"Enter the name of the racket method to override"
(lambda (result)
(lambda (unassigned) (send unassigned assign-override-racket-method!! result))
)
(thunk
(define method (get-method-to-define/override-from-user parent-handle))
(and method
(lambda (unassigned) (send unassigned assign-define-method!! method))
)
)
)
)
)
(define (new-super-init-creator parent-handle visible-referables)
(and (check-directly-in-class? parent-handle) (not (findf (curryr is-a? zinal:db:super-init%%) (send parent-handle get-body)))
(lambda (unassigned) (send unassigned assign-super-init!!))
)
)
(define (new-create-object-creator parent-handle visible-referables)
(lambda (unassigned) (send unassigned assign-create-object!!))
)
(define (new-this-creator parent-handle visible-referables)
(and (check-in-class? parent-handle)
(lambda (unassigned) (send unassigned assign-this!!))
)
)
(define (new-define-class-creator parent-handle visible-referables)
(use-text-from-user
"Enter a name for the new class definition"
"A short descriptor, one or a few words, to identify this class"
(lambda (result)
(lambda (unassigned) (send unassigned assign-define-class!! result))
)
non-empty-string?
)
)
(define (new-class-instance-creator parent-handle visible-referables)
(lambda (unassigned) (send unassigned assign-class-instance!!))
)
; GUI CONSTANTS
(define FRIENDLY-TYPE->CREATOR (hash
"number" new-number-creator
"character" new-character-creator
"string" new-string-creator
"boolean" new-boolean-creator
"symbol" new-symbol-creator
"keyword" new-keyword-creator
"list" new-list-creator
"assertion" new-assert-creator
"define" new-define-creator
"lambda" new-lambda-creator
"reference" new-value-read-creator
"racket (standard library)" new-standard-racket-creator
"racket (non-standard library)" new-non-standard-racket-creator
"TODO" new-unassigned-creator
"invoke method" new-invoke-method-creator
"invoke this (⊙) method" new-invoke-this-method-creator
"invoke super (🡡) method" new-invoke-super-method-creator
"create new object (☼)" new-create-object-creator
"initialize super class (🡡☼)" new-super-init-creator
"define new method" new-define-new-method-creator
"define/override existing method" new-define-existing-method-creator
"this (⊙)" new-this-creator
"class (definition)" new-define-class-creator
"class (anonymous instantiation)" new-class-instance-creator
))
; Returns #f to signify no action is to be taken (i.e. the user cancels the dialog)
; Returns a function that takes an unassigned db handle and will assign it to something else, returning the new handle
; The returned creator is not allowed to fail. A failure of this function should return #f instead of a creator
(define (request-new-item-creator parent-handle visible-referables [allowed-types (sort (hash-keys FRIENDLY-TYPE->CREATOR) string<?)])
(define choice (get-choice-from-user "Choose the new node's type:" "Choose the node's type:" allowed-types))
(if choice
((hash-ref FRIENDLY-TYPE->CREATOR (list-ref allowed-types choice)) parent-handle visible-referables)
#f
)
)
; ENT MANAGER
(define zinal:ent:manager% (class object%
(init db)
(super-make-object)
(define db* db)
(define ent-manager* this)
(define selected* #f)
(define selected-highlight-equivalence-handle* #f)
(define global-event-handler* #f)
; TODO We want ui:scalar% to only refresh its text if the db has actually changed somehow, because the db calls required to update the text
; are expensive. There are several major changes that could be made to the framework that might facilitate this, like making db handles
; hashable, or giving every ent% a refresh! method that is invoked when that ent is first created and when it's reparsed. These are good
; options to consider for later, but for now they require large reworkings and rethinkings of things, and aren't worth the time required to
; do them properly. So for now it's sufficient just to keep a count of the modifications that have happened so ui:var-scalar% can compare to
; the global count and refresh if necessary
(define mod-count* 0)
(define/public (get-initial-ui!)
(unless (navigate-to-fresh-module*!)
(get-initial-ui!)
)
(send selected* get-root)
)
(define/public (handle-event!! event)
(assert "Something must always be selected" selected*)
(define global-event-info (handle-global-event*!! event))
(assert "global events currently cannot require reparse" (not (send global-event-info was-db-affected?)))
(unless (send global-event-info was-handled?)
(define event-info (send selected* handle-event!! event))
(when (send event-info was-db-affected?)
(set! mod-count* (add1 mod-count*))
(maybe-reparse*! (get-root-slot*) (reverse (get-backwards-selection-path* selected*)))
(update-selected-highlight-equivalence-handle*)
)
)
(send selected* get-root)
)
(define (select! slot/item)
(set! selected* (slot/ui-item->ui-item slot/item))
(update-selected-highlight-equivalence-handle*)
)
(define (update-selected-highlight-equivalence-handle*)
(set! selected-highlight-equivalence-handle* (send (send selected* get-parent-ent) get-highlight-equivalence-handle selected*))
)
(define (get-root-slot*)
(send (send (send selected* get-root) get-parent-ent) get-slot)
)
(define (get-backwards-selection-path* ui-item)
(cond
[ui-item
(define slot (send (send ui-item get-parent-ent) get-slot))
(define sub-chain (get-backwards-selection-path* (send ui-item get-parent)))
(if (and (pair? sub-chain) (eq? (car sub-chain) slot))
sub-chain
(cons slot sub-chain)
)
]
[else
'()
]
)
)
(define (maybe-reparse*! slot selection-path)
(define current-ent (send slot get-ent))
(define db-handle (send current-ent get-cone-root))
(define ui-parent (send (send current-ent get-root-ui-item) get-parent))
(define cone-leaves (send current-ent get-cone-leaves))
(define was-this-slot-respawned? #f)
(unless (implies ui-parent (is-a? current-ent (parse-entity*! db-handle)))
(spawn-entity*! slot db-handle ui-parent (curryr spawn-or-reassign-entity*! cone-leaves))
; Imperative style, but the functional alternatives are just so damn ugly
(set! was-this-slot-respawned? #t)
)
; TODO This is hacky, but that's ok, cuz it gives us an idea of how we might have a more general purpose reactive/notification/spooky-action-at-a-distance system in the future
(when (and (not was-this-slot-respawned?) (is-a? current-ent ent:define-class%))
(send current-ent reset-abstracts)
)
(define is-current-slot-part-of-selection-path? (and (pair? selection-path) (eq? (car selection-path) slot)))
(define next-selection-path (and is-current-slot-part-of-selection-path? (cdr selection-path)))
(define is-some-child-part-of-selection-path?
(pair? (filter-map (curryr maybe-reparse*! next-selection-path) (send (send slot get-ent) get-cone-leaves)))
)
(when (and was-this-slot-respawned? is-current-slot-part-of-selection-path? (not is-some-child-part-of-selection-path?))
(select! slot)
)
is-current-slot-part-of-selection-path?
)
(define (change-module*! handle-event-info event)
(define module-to-go-to (get-module-from-user))
(when module-to-go-to (spawn-root-entity*! module-to-go-to))
(send handle-event-info set-db-wasnt-affected!)
)
(define (create-new-module*!! handle-event-info event)
(define module-to-go-to (create-module*!!))
(when module-to-go-to (spawn-root-entity*! module-to-go-to))
(send handle-event-info set-db-wasnt-affected!)
)
(define (change-interface*! handle-event-info event)
(define interface-to-go-to (get-interface-from-user (send db* get-all-interfaces)))
(when interface-to-go-to (spawn-root-entity*! interface-to-go-to))
(send handle-event-info set-db-wasnt-affected!)
)
(define (create-new-interface*!! handle-event-info event)
(define interface-to-go-to (create-interface*!!))
(when interface-to-go-to (spawn-root-entity*! interface-to-go-to))
(send handle-event-info set-db-wasnt-affected!)
)
(define (find-prev-todo*! handle-event-info event)
(find-prev*! (curryr is-a? zinal:db:unassigned%%))
(send handle-event-info set-db-wasnt-affected!)
)
(define (find-next-todo*! handle-event-info event)
(find-next*! (curryr is-a? zinal:db:unassigned%%))
(send handle-event-info set-db-wasnt-affected!)
)
(define (handle-global-event*!! event)
(unless global-event-handler*
(set! global-event-handler*
(make-object keyname-event-handler% (list
(list change-module*! zinal:key-bindings:CHANGE-MODULE)
(list create-new-module*!! zinal:key-bindings:CREATE-NEW-MODULE)
(list change-interface*! zinal:key-bindings:CHANGE-INTERFACE)
(list create-new-interface*!! zinal:key-bindings:CREATE-NEW-INTERFACE)
(list find-next-todo*! zinal:key-bindings:GOTO-NEXT-UNASSIGNED)
(list find-prev-todo*! zinal:key-bindings:GOTO-PREV-UNASSIGNED)
))
)
)
(send global-event-handler* handle-event!! event)
)
; ENTS
; Some text-getters that are used by some ents
(define (get-ref-text ref-handle)
(get-short-desc-or (send ref-handle get-referable) "<nameless ref>")
)
(define (get-atom-text atom-handle)
(define raw-value (send atom-handle get-val))
(cond
[(is-a? atom-handle zinal:db:symbol%%)
(format "'~a" raw-value)
]
[(is-a? atom-handle zinal:db:char%%)
(~s raw-value)
]
[else
(~a raw-value)
]
)
)
(define (get-unassigned-text unassigned-handle)
(get-short-desc-or unassigned-handle "<?>")
)
(define ent% (class* object% (fallback-event-handler%%) ; abstract
; Every ent must have an init of the form (init cone-root-handle child-spawner!). This
; base class doesn't actually need the child-spawner! , so its init only takes the root handle.
; But all subclasses should accept the child-spawner! and use it for spawning all initial child
; ents.
(init cone-root-handle)
(abstract get-root-ui-item)
(define cone-root* cone-root-handle)
(define slot* #f)
(define/public (get-cone-root)
cone-root*
)
; If the database doesn't change, then this must return the same result every time for a given child-ui-item
(define/public (get-highlight-equivalence-handle child-ui-item)
#f
)
(define/public (handle-child-event!! event)
(assert "You must call assign-to-slot! before sending any events" slot*)
(send slot* handle-child-event!! event)
)
; Returns a list of slots corresponding to the leaves of this cone and the roots of the child cones
(define/public (get-cone-leaves)
(define (get-cone-leaves* ui-item)
(if (is-a? ui-item zinal:ui:list%%)
(append* (map get-cone-leaves* (send ui-item get-children-with-header-internal)))
(if (is-a? ui-item slot%) (list ui-item) '())
)
)
(get-cone-leaves* (get-root-ui-item))
)
; This must be called before the ent can handle events
(define/public (assign-to-slot! slot ui-parent)
(send slot set-ent! this)
(set! slot* slot)
(send (get-root-ui-item) set-parent! ui-parent)
)
(define/public (get-slot)
slot*
)
(super-make-object)
))
(define ent:short-definition% (class ent% ; abstract
(init cone-root-handle child-spawner!)
(define/public (get-prefix-text)
#f
)
(define/public (get-synopsis-text)
"..."
)
(define/override (get-highlight-equivalence-handle ui-item)
(send this get-cone-root)
)
; Gross. We happen to know that the superclass does not actually need to call get-root-ui-item during
; initialization, so we can resolve a cyclic dependency by calling super-make-object before overriding
; get-root-ui-item
(super-make-object cone-root-handle)
(define this-ent* this)
(define ui-item* (make-object (class ui:possibly-public-def-list%
(define/override (get-prefix-text)
(send this-ent* get-prefix-text)
)
(define/override (get-default-name-text)
"<nameless definition>"
)
(define/override (get-bridge-text)
(format "= ~a" (get-synopsis-text))
)
(define/override (get-event-handler)
(combine-keyname-event-handlers (list
(super get-event-handler)
(create-navigate-to-root-handler* (send this-ent* get-cone-root))
))
)
(super-make-object this-ent* this-ent*)
)))
(define/override (get-root-ui-item)
ui-item*
)
))
(define ent:singleton% (class ent% ; abstract
(init cone-root-handle child-spawner! [bookends #f])
(abstract db-get-single-item)
(abstract get-header)
; Gross. We happen to know that the superclass does not actually need to call get-root-ui-item during
; initialization, so we can resolve a cyclic dependency by calling super-make-object before overriding
; get-root-ui-item
(super-make-object cone-root-handle)
(define this-ent* this)
(define ui-item* (make-object (class ui:slotted-list%
(define/override (get-visible-referables-for-slot slot)
(send (send this-ent* get-cone-root) get-visible-referables-underneath)
)
(super-make-object this-ent* this-ent* (get-header) bookends)
(define item-slot* (make-object slot% (lambda (s) (send this child-slot->event-handler s)) NOOP-FALLBACK-EVENT-HANDLER))
(child-spawner! item-slot* (db-get-single-item) this)
(send this insert! 0 item-slot*)
)))
(define/override (get-root-ui-item)
ui-item*
)
))
(define ent:typical-list% (class ent%
(init cone-root-handle child-spawner!)
(define/public (db-insert!! index)
(send (db-get-list-handle) insert!! index)
)
(define/public (db-can-remove? index)
(is-a? (list-ref (send (db-get-list-handle) get-items) index) zinal:db:unassigned%%)
)
(define/public (db-remove!! index)
(send (db-get-list-handle) remove!! index)
)
(define/public (db-get-items)
(send (db-get-list-handle) get-items)
)
(define/public (db-get-list-handle)
(send this get-cone-root)
)
(define/public (get-pseudo-headers)
'()
)
(define/public (get-header)
#f
)
(define/public (get-separator)
#f
)
(define/public (get-bookends)
(list
(make-object ui:const% this zinal:ui:style:NO-STYLE "(")
(make-object ui:const% this zinal:ui:style:NO-STYLE ")")
)
)
(define/public (horizontal-by-default?)
#f
)
; Gross. We happen to know that the superclass does not actually need to call get-root-ui-item during
; initialization, so we can resolve a cyclic dependency by calling super-make-object before overriding
; get-root-ui-item
(super-make-object cone-root-handle)
(define this-ent* this)
(define ui-list* (make-object (class ui:dynamic-slotted-list%
(define/override (db-insert!! index)
(send this-ent* db-insert!! index)
)
(define/override (db-can-remove? index)
(send this-ent* db-can-remove? index)
)
(define/override (db-remove!! index)
(send this-ent* db-remove!! index)
)
(define/override (db-get-items)
(send this-ent* db-get-items)
)
(define/override (db-get-list-handle)
(send this-ent* db-get-list-handle)
)
(define/override (get-pseudo-headers)
(send this-ent* get-pseudo-headers)
)
(super-make-object this-ent* this-ent* child-spawner! (get-header) (get-separator) (get-bookends))
)))
(when (horizontal-by-default?) (send ui-list* set-horizontal! #t))
(define/override (get-root-ui-item)
ui-list*
)
))
(define ent:typical-has-body% (class ent:typical-list% ; abstract
(init cone-root-handle child-spawner!)
(define/public (get-has-body-handle)
(send this get-cone-root)
)
(define/override (db-insert!! index)
(send (get-has-body-handle) insert-into-body!! index)
)
(define/override (db-can-remove? index)
(is-a? (list-ref (db-get-items) index) zinal:db:unassigned%%)
)
(define/override (db-remove!! index)
(send (get-has-body-handle) remove-from-body!! index)
)
(define/override (db-get-items)
(send (get-has-body-handle) get-body)
)
(define/override (db-get-list-handle)
(get-has-body-handle)
)
(define/override (get-separator)
(make-object ui:const% this zinal:ui:style:NO-STYLE "; ")
)
(define/override (get-bookends)
(list
(make-object ui:const% this zinal:ui:style:NO-STYLE "{")
(make-object ui:const% this zinal:ui:style:NO-STYLE "}")
)
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:typical-has-args% (class ent:typical-list% ; abstract
(init cone-root-handle child-spawner!)
(define/public (get-has-args-handle)
(send this get-cone-root)
)
(define/override (db-insert!! index)
(send (get-has-args-handle) insert-arg!! index)
)
(define/override (db-can-remove? index)
(is-a? (list-ref (db-get-items) index) zinal:db:unassigned%%)
)
(define/override (db-remove!! index)
(send (get-has-args-handle) remove-arg!! index)
)
(define/override (db-get-items)
(send (get-has-args-handle) get-args)
)
(define/override (db-get-list-handle)
(get-has-args-handle)
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:module% (class ent:typical-has-body%
(init cone-root-handle child-spawner!)
(define this-ent* this)
(define event-handler*
(combine-keyname-event-handlers (list
(create-name-change-handler (thunk (send this get-cone-root)))
(create-simple-event-handler zinal:key-bindings:TOGGLE-MAIN
(lambda (handle-event-info event)
(define module-handle (send this get-cone-root))
(cond
[(send module-handle is-main-module?)
(send module-handle set-main-module!! #f)
]
[(send db* get-main-module)
(issue-warning "Cannot make main" "Only one module can be the main module")
]
[else
(send module-handle set-main-module!! #t)
]
)
#t
)
)
(create-simple-event-handler zinal:key-bindings:DELETE/UNASSIGN
(lambda (handle-event-info event)
(define module-handle (send this get-cone-root))
(if (send module-handle can-delete?)
(when (navigate-to-fresh-module*! (get-all-modules* module-handle)) (send module-handle delete!!))
(issue-warning "Cannot delete module" "Either other modules require this module or contain references to defs in this module")
)
#t
)
)
))
)
(define (get-module-text*)
(define prefix
(if (send (send this get-cone-root) is-main-module?)
"Main module"
"Module"
)
)
(format "~a: ~a requires:" prefix (get-short-desc-or (send this get-cone-root) "<nameless module>"))
)
(define/override (get-header)
(make-object (class ui:handle-set-list%
(define/override (db-get-items)
(send (send this-ent* get-cone-root) get-required-modules)
)
(define/override (db-add-item!!)
(define this-module (send this-ent* get-cone-root))
(define module-to-require (get-module-from-user (filter (lambda (m) (send this-module can-require? m)) (get-all-modules*))))
(cond
[module-to-require
(send this-module require!! module-to-require)
module-to-require
]
[else
#f
]
)
)
(define/override (db-can-remove-item? to-remove)
#t
)
(define/override (db-remove-item!! to-remove)
(send (send this-ent* get-cone-root) unrequire!! to-remove)
)
(define/override (get-item-ui-style)
zinal:ui:style:REF-STYLE
)
(define header-header*
(make-object ui:var-scalar% this-ent* zinal:ui:style:MODULE-STYLE get-module-text* (const event-handler*) NOOP-FALLBACK-EVENT-HANDLER)
)
(super-make-object this-ent* NOOP-FALLBACK-EVENT-HANDLER header-header*)
))
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:invokation% (class ent:typical-list% ; abstract
(init cone-root-handle child-spawner!)
(abstract get-header-style)
(define/override (get-highlight-equivalence-handle ui-item)
(define handle (get-func-handle*))
(and (is-a? handle zinal:db:reference%%) (send handle get-referable))
)
(define/override (db-insert!! index)
(super db-insert!! (add1 index))
)
(define/override (db-can-remove? index)
(super db-can-remove? (add1 index))
)
(define/override (db-remove!! index)
(super db-remove!! (add1 index))
)
(define/override (db-get-items)
(cdr (super db-get-items))
)
(define/override (get-header)
(make-object ui:var-scalar% this (get-header-style) get-header-text* header->event-handler* NOOP-FALLBACK-EVENT-HANDLER)
)
(define/override (horizontal-by-default?)
#t
)
(define (get-header-text*)
(define func (get-func-handle*))
(cond
[(is-a? func zinal:db:racket%%)
(racket-handle->string func)
]
[(is-a? func zinal:db:reference%%)
(get-short-desc-or (send func get-referable) "<nameless ref>")
]
[else
(error 'get-header-text* "invalid type")
]
)
)
(define (header->event-handler* header)
(define (interaction-function)
(define list-handle (send this db-get-list-handle))
(request-new-item-creator list-handle (send list-handle get-visible-referables-underneath) '("racket (standard library)" "racket (non-standard library)" "reference"))
)
(define (result-handler new-handle-initializer!!)
(new-handle-initializer!! (send (get-func-handle*) unassign!!))
)
(create-interaction-dependent-event-handler interaction-function result-handler zinal:key-bindings:REPLACE)
)
(define (get-func-handle*)
(car (super db-get-items))
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:racket-invokation% (class ent:invokation%
(init cone-root-handle child-spawner!)
(define/override (get-header-style)
zinal:ui:style:RACKET-STYLE
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:reference-invokation% (class ent:invokation%
(init cone-root-handle child-spawner!)
(define/override (get-header-style)
zinal:ui:style:REF-STYLE
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:list-list% (class ent:typical-list%
(init cone-root-handle child-spawner!)
(define/override (db-insert!! index)
(super db-insert!! (add1 index))
)
(define/override (db-can-remove? index)
(super db-can-remove? (add1 index))
)
(define/override (db-remove!! index)
(super db-remove!! (add1 index))
)
(define/override (db-get-items)
(cdr (super db-get-items))
)
(define/override (get-bookends)
(list
(make-object ui:const% this zinal:ui:style:LIST-STYLE "[")
(make-object ui:const% this zinal:ui:style:LIST-STYLE "]")
)
)
(define/override (horizontal-by-default?)
#t
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:quoted-list% (class ent:typical-list%
(init cone-root-handle child-spawner!)
(define/override (db-get-list-handle)
(second (send (send this get-cone-root) get-items))
)
(define/override (get-bookends)
(list
(make-object ui:const% this zinal:ui:style:LIST-STYLE "'(")
(make-object ui:const% this zinal:ui:style:LIST-STYLE ")")
)
)
(define/override (horizontal-by-default?)
#t
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:lambda-like% (class ent:typical-has-body% ; abstract
(init cone-root-handle child-spawner!)
(abstract get-params-header)
(abstract get-lambda-handle)
(define/override (get-has-body-handle)
(get-lambda-handle)
)
(define child-spawner*! child-spawner!)
(define/override (get-header)
(make-object ui:params-list% this this child-spawner*! (get-lambda-handle) (get-params-header))
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:lambda% (class ent:lambda-like%
(init cone-root-handle child-spawner!)
(define/override (get-params-header)
(make-object ui:const% this zinal:ui:style:NO-STYLE "λ:")
)
(define/override (get-lambda-handle)
(send this get-cone-root)
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:func-def% (class ent:lambda-like%
(init cone-root-handle child-spawner!)
(define this-ent* this)
(define/override (get-highlight-equivalence-handle ui-item)
(and (is-a? ui-item zinal:ui:var-scalar%%)
(send this get-cone-root)
)
)
(define/override (get-params-header)
(make-object (class ui:possibly-public-def-list%
(define/override (get-default-name-text)
"<nameless def>"
)
(define/override (get-bridge-text)
"= λ:"
)
(super-make-object this-ent*)
))
)
(define/override (get-lambda-handle)
(send (send this get-cone-root) get-expr)
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:def% (class ent:singleton%
(init cone-root-handle child-spawner!)
(define/override (db-get-single-item)
(send (send this get-cone-root) get-expr)
)
(define this-ent* this)
(define/override (get-header)
(make-object (class ui:possibly-public-def-list%
(define/override (get-default-name-text)
"<nameless def>"
)
(super-make-object this-ent*)
))
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:short-def% (class ent:short-definition%
(init cone-root-handle child-spawner!)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:short-func-def% (class ent:short-definition%
(init cone-root-handle child-spawner!)
(define/override (get-synopsis-text)
(has-params->short-params-string (send (send this get-cone-root) get-expr))
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:short-method-definition% (class ent% ; abstract
(init cone-root-handle child-spawner!)
(abstract get-prefix-string)
(abstract get-method-name)
(abstract get-name-change-handler)
(define this-ent* this)
; Gross. We happen to know that the superclass does not actually need to call get-root-ui-item during
; initialization, so we can resolve a cyclic dependency by calling super-make-object before overriding
; get-root-ui-item
(super-make-object cone-root-handle)
(define ui-item* (make-object (class ui:list%
(define (get-params-text*)
(format "= ~a" (has-params->short-params-string (send (send this-ent* get-cone-root) get-lambda)))
)
(define/override (get-event-handler)
(combine-keyname-event-handlers (list
(super get-event-handler)
(create-navigate-to-root-handler* (send this-ent* get-cone-root))
))
)
(super-make-object this-ent* this-ent*)
(send this insert! 0 (make-object ui:const% this-ent* zinal:ui:style:NO-STYLE (get-prefix-string)))
(send this insert! 1 (make-object ui:var-scalar% this-ent* zinal:ui:style:DEF-STYLE (thunk (get-method-name)) (thunk* (get-name-change-handler)) NOOP-FALLBACK-EVENT-HANDLER))
; TODO - this and other places will need to change to var-scalar if we ever get to a point of saving ui trees when switching roots
(send this insert! 2 (make-object ui:const% this-ent* zinal:ui:style:NO-STYLE (get-params-text*)))
(send this set-horizontal! #t)
)))
(define/override (get-root-ui-item)
ui-item*
)
))
(define ent:short-define-method% (class ent:short-method-definition%
(init cone-root-handle child-spawner!)
(define/override (get-highlight-equivalence-handle ui-item)
(send (send this get-cone-root) get-method)
)
(define/override (get-prefix-string)
"method"
)
(define/override (get-method-name)
(get-short-desc-or (send (send this get-cone-root) get-method) "<nameless method>")
)
(define/override (get-name-change-handler)
(create-name-change-handler (thunk (send (send this get-cone-root) get-method)))
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:short-override-racket-method% (class ent:short-method-definition%
(init cone-root-handle child-spawner!)
(define/override (get-prefix-string)
"override racket method"
)
(define/override (get-method-name)
(send (send this get-cone-root) get-racket-method-name)
)
(define/override (get-name-change-handler)
(create-racket-method-name-change-handler (thunk (send this get-cone-root)))
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:short-augment-racket-method% (class ent:short-override-racket-method%
(init cone-root-handle child-spawner!)
(define/override (get-prefix-string)
"augment racket method"
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:short-class-instance% (class ent%
(init cone-root-handle child-spawner!)
(define/override (get-highlight-equivalence-handle ui-item)
(and (is-a? ui-item zinal:ui:var-scalar%%)
(send (send this get-cone-root) get-super-class)
)
)
(define this-ent* this)
; Gross. We happen to know that the superclass does not actually need to call get-root-ui-item during
; initialization, so we can resolve a cyclic dependency by calling super-make-object before overriding
; get-root-ui-item
(super-make-object cone-root-handle)
(define ui-item* (make-object (class ui:list%
(define (get-super-text*)
(define super-class-handle (send (send this-ent* get-cone-root) get-super-class))
(if (is-a? super-class-handle zinal:db:racket%%)
(racket-handle->string super-class-handle)
(get-short-desc-or (send super-class-handle get-referable) "<some class>")
)
)
(define/override (get-event-handler)
(combine-keyname-event-handlers (list
(super get-event-handler)
(create-navigate-to-root-handler* (send this-ent* get-cone-root))
))
)
(super-make-object this-ent* this-ent*)
(send this insert! 0 (make-object ui:const% this-ent* zinal:ui:style:NO-STYLE "new anonymous"))
(send this insert! 1 (make-object ui:var-scalar% this-ent* zinal:ui:style:REF-STYLE get-super-text* THING->NOOP NOOP-FALLBACK-EVENT-HANDLER))
(send this set-horizontal! #t)
)))
(define/override (get-root-ui-item)
ui-item*
)
))
(define ent:short-define-class% (class ent:short-definition%
(init cone-root-handle child-spawner!)
(define/override (get-prefix-text)
"class"
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:assert% (class ent%
(init cone-root-handle child-spawner!)
(define this-ent* this)
; Gross. We happen to know that the superclass does not actually need to call get-root-ui-item during
; initialization, so we can resolve a cyclic dependency by calling super-make-object before overriding
; get-root-ui-item
(super-make-object cone-root-handle)
(define header* (make-object (class ui:slotted-list%
(define/override (get-visible-referables-for-slot slot)
(send (send this-ent* get-cone-root) get-visible-referables-underneath)
)
(super-make-object this-ent* NOOP-FALLBACK-EVENT-HANDLER)
(define assertion-slot* (make-object slot% (lambda (s) (send this child-slot->event-handler s)) NOOP-FALLBACK-EVENT-HANDLER))
(child-spawner! assertion-slot* (send (send this-ent* get-cone-root) get-assertion) this)
(define format-string-slot* (make-object slot% (lambda (s) (send this child-slot->event-handler s)) NOOP-FALLBACK-EVENT-HANDLER))
(child-spawner! format-string-slot* (send (send this-ent* get-cone-root) get-format-string) this)
(send this insert! 0 (make-object ui:const% this-ent* zinal:ui:style:ASSERT-STYLE "assert"))
(send this insert! 1 assertion-slot*)
(send this insert! 2 (make-object ui:const% this-ent* zinal:ui:style:ASSERT-STYLE ":"))
(send this insert! 3 format-string-slot*)
)))
(define ui-assert* (make-object (class ui:dynamic-slotted-list%
(define/override (db-insert!! index)
(send (db-get-list-handle) insert-format-arg!! index)
)
(define/override (db-can-remove? index)
(is-a? (list-ref (db-get-items) index) zinal:db:unassigned%%)
)
(define/override (db-remove!! index)
(send (db-get-list-handle) remove-format-arg!! index)
)
(define/override (db-get-items)
(send (db-get-list-handle) get-format-args)
)
(define/override (db-get-list-handle)
(send this-ent* get-cone-root)
)
(super-make-object this-ent* this-ent* child-spawner! header*)
)))
(send ui-assert* set-horizontal! #t)
(define/override (get-root-ui-item)
ui-assert*
)
))
(define ent:atom% (class ent%
(init cone-root-handle child-spawner!)
(define ui-scalar*
(make-object ui:var-scalar% this zinal:ui:style:ATOM-STYLE (thunk (get-atom-text (send this get-cone-root))) THING->NOOP this)
)
(define/override (get-root-ui-item)
ui-scalar*
)
(super-make-object cone-root-handle)
))
(define ent:string% (class ent%
(init cone-root-handle child-spawner!)
(define ui-scalar*
(make-object ui:var-scalar% this zinal:ui:style:STRING-STYLE (thunk (send (send this get-cone-root) get-val)) THING->NOOP this)
)
(define/override (get-root-ui-item)
ui-scalar*
)
(super-make-object cone-root-handle)
))
(define ent:empty-string% (class ent%
(init cone-root-handle child-spawner!)
(define ui-scalar*
(make-object ui:var-scalar% this zinal:ui:style:CONST-VALUE-STYLE (const "ε") THING->NOOP this)
)
(define/override (get-root-ui-item)
ui-scalar*
)
(super-make-object cone-root-handle)
))
(define ent:ref% (class ent%
(init cone-root-handle child-spawner!)
(define/override (get-highlight-equivalence-handle ui-item)
(send (send this get-cone-root) get-referable)
)
(define ui-scalar*
(make-object ui:var-scalar% this zinal:ui:style:REF-STYLE (thunk (get-ref-text (send this get-cone-root))) THING->NOOP this)
)
(define/override (get-root-ui-item)
ui-scalar*
)
(super-make-object cone-root-handle)
))
(define ent:optional-param% (class ent:singleton%
(init cone-root-handle child-spawner!)
(define/override (get-highlight-equivalence-handle ui-item)
(send this get-cone-root)
)
(define/override (db-get-single-item)
(define default (send (send this get-cone-root) get-default))
(assert "optional param has no default" default)
default
)
(define this-ent* this)
(define/override (get-header)
(make-object (class ui:def-list%
(define/override (get-default-name-text)
"<nameless param>"
)
(super-make-object this-ent*)
))
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:required-param% (class ent%
(init cone-root-handle child-spawner!)
(define/override (get-highlight-equivalence-handle ui-item)
(send this get-cone-root)
)
(define (get-text)
(get-short-desc-or (send this get-cone-root) "<nameless param>")
)
(define (name-ui->event-handler* name-ui)
(create-name-change-handler (thunk (send this get-cone-root)))
)
(define ui-scalar*
(make-object ui:var-scalar% this zinal:ui:style:DEF-STYLE get-text name-ui->event-handler* this)
)
(define/override (get-root-ui-item)
ui-scalar*
)
(super-make-object cone-root-handle)
))
(define ent:racket% (class ent%
(init cone-root-handle child-spawner!)
(define (get-text)
(racket-handle->string (send this get-cone-root))
)
(define ui-scalar*
(make-object ui:var-scalar% this zinal:ui:style:RACKET-STYLE get-text THING->NOOP this)
)
(define/override (get-root-ui-item)
ui-scalar*
)
(super-make-object cone-root-handle)
))
(define ent:unassigned% (class ent%
(init cone-root-handle child-spawner!)
(define ui-scalar*
(make-object ui:var-scalar% this zinal:ui:style:UNASSIGNED-STYLE (thunk (get-unassigned-text (send this get-cone-root))) THING->NOOP this)
)
(define/override (get-root-ui-item)
ui-scalar*
)
(super-make-object cone-root-handle)
))
(define ent:class% (class ent:typical-has-body% ; abstract
(init cone-root-handle child-spawner!)
; a list of ui:item% that should be prepended to the header. Other than this list, the header starts with the superclass slot
(abstract get-header-prefix-list)
(define this-ent* this)
(define child-spawner*! child-spawner!)
(define/override (get-header)
(define header-header (make-object (class ui:list%
(super-make-object this-ent* NOOP-FALLBACK-EVENT-HANDLER)
(define super-class-slot* #f)
(define (super-class-slot->event-handler slot)
(define class-handle (send this-ent* get-cone-root))
(define (interaction-function)
(cond
[(send class-handle can-set-super-class?)
(define choice-index
(get-choice-from-user
"Is the super class zinal or racket?"
"Choose whether to refer to a zinal class, standard library racket class, or non-standard library racket class"
'("zinal class" "racket class (standard library)" "racket class (non-standard library)")
)
)
(case choice-index
[(0)
(get-referable-from-user
(filter
(conjoin (negate (curry handles-equal? class-handle)) (curryr is-a? zinal:db:define-class%%))
(send class-handle get-visible-referables-underneath)
)
)
]
[(1)
(get-standard-racket-from-user)
]
[(2)
(get-non-standard-racket-from-user)
]
[else
#f
]
)
]
[else
(issue-warning "Can't change super class" "Changing the super class would orphan a method definition or super invokation")
#f
]
)
)
(define (result-handler result)
(define new-handle
(cond
[(is-a? result zinal:db:define-class%%)
(send class-handle set-super-class!! result)
]
[(string? result)
(send class-handle set-racket-super-class!! #f result)
]
[(and (pair? result) (= 2 (length result)) (andmap string? result))
(send class-handle set-racket-super-class!! (first result) (second result))
]
[else
(error 'super-class-slot->event-handler "Bad super-class choice result:" result)
]
)
)
(spawn-entity*! super-class-slot* new-handle this)
(select! super-class-slot*)
)
(create-interaction-dependent-event-handler interaction-function result-handler zinal:key-bindings:REPLACE)
)
(define header-prefix-list* (get-header-prefix-list))
(define prefix-size* (length header-prefix-list*))
(map-by-index
(lambda (index item) (send this insert! index item))
header-prefix-list*
)
(set! super-class-slot* (make-object slot% super-class-slot->event-handler NOOP-FALLBACK-EVENT-HANDLER))
(child-spawner*! super-class-slot* (send (send this-ent* get-cone-root) get-super-class) this)
(send this insert! prefix-size* super-class-slot*)
(send this insert! (add1 prefix-size*) (make-object ui:const% this-ent* zinal:ui:style:NO-STYLE "implementing:"))
)))
(make-object ui:interface-set-list% this-ent* NOOP-FALLBACK-EVENT-HANDLER header-header)
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:class-instance% (class ent:class%
(init cone-root-handle child-spawner!)
(define/override (get-header-prefix-list)
(list
(make-object ui:const% this zinal:ui:style:NO-STYLE "create anonymous instance of")
)
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:define-class% (class ent:class%
(init cone-root-handle child-spawner!)
(define child-spawner*! child-spawner!)
(define this-ent* this)
(define params-list* #f)
(define abstracts* #f)
(define class-name-ui-item* #f)
(define (name-ui->event-handler* name-ui)
(create-name-change-handler (thunk (send this-ent* get-cone-root)))
)
(define (get-name-text*)
(get-short-desc-or (send this-ent* get-cone-root) "<unnamed class>")
)
(define/override (get-highlight-equivalence-handle ui-item)
(and (is-a? ui-item zinal:ui:var-scalar%%)
(cond
[(eq? ui-item class-name-ui-item*)
(send this get-cone-root)
]
[(eq? abstracts* (send ui-item get-parent))
(send abstracts* get-nth-handle (send abstracts* get-child-index ui-item))
]
[else
#f
]
)
)
)
(define/override (get-header-prefix-list)
(set! class-name-ui-item*
(make-object ui:var-scalar% this-ent* zinal:ui:style:DEF-STYLE get-name-text* name-ui->event-handler* NOOP-FALLBACK-EVENT-HANDLER)
)
(list
(make-object ui:const% this-ent* zinal:ui:style:NO-STYLE "class")
class-name-ui-item*
(make-object ui:const% this-ent* zinal:ui:style:NO-STYLE "subclass of")
)
)
(define/public (reset-abstracts)
(when abstracts* (send abstracts* reset!))
)
(define (get-abstracts*)
(make-object (class ui:handle-set-list%
(define/override (db-get-items)
(define class-handle (send this-ent* get-cone-root))
(filter (lambda (m) (send class-handle is-method-abstract? m)) (send class-handle get-direct-methods))
)
(define/override (db-add-item!!)
(use-text-from-user
"Enter short descriptor for the new method"
"A short descriptor, one or a few words, to identify this method"
(lambda (result)
(send (send this-ent* get-cone-root) add-direct-method!! result)
)
non-empty-string?
)
)
(define/override (db-can-remove-item? to-remove)
(send (send this-ent* get-cone-root) can-remove-direct-method? to-remove)
)
(define/override (db-remove-item!! to-remove)
(send (send this-ent* get-cone-root) remove-direct-method!! to-remove)
)
(define/override (get-item-ui-style)
zinal:ui:style:DEF-STYLE
)
(super-make-object this-ent* NOOP-FALLBACK-EVENT-HANDLER (make-object ui:const% this zinal:ui:style:NO-STYLE "abstract methods:"))
))
)
(define/override (get-pseudo-headers)
(unless params-list*
(set! params-list*
(make-object ui:params-list% this NOOP-FALLBACK-EVENT-HANDLER child-spawner*! (send this get-cone-root) (make-object ui:const% this zinal:ui:style:NO-STYLE "init params:"))
)
(set! abstracts*
(get-abstracts*)
)
)
(list
params-list*
abstracts*
)
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:define-method% (class ent:lambda-like%
(init cone-root-handle child-spawner!)
(define this-ent* this)
(define/override (get-highlight-equivalence-handle ui-item)
(send (send this get-cone-root) get-method)
)
(define/override (get-params-header)
(make-object (class ui:list%
(define (name-ui->event-handler* name-ui)
(combine-keyname-event-handlers (list
(create-name-change-handler get-method*)
(create-search-selected-method-handlers* (get-method*))
))
)
(define (get-name-text*)
(get-short-desc-or (get-method*) "<unnamed method>")
)
(define (get-method*)
(send (send this-ent* get-cone-root) get-method)
)
(super-make-object this-ent* NOOP-FALLBACK-EVENT-HANDLER)
(send this insert! 0 (make-object ui:const% this-ent* zinal:ui:style:NO-STYLE "method"))
(send this insert! 1 (make-object ui:var-scalar% this-ent* zinal:ui:style:DEF-STYLE get-name-text* name-ui->event-handler* NOOP-FALLBACK-EVENT-HANDLER))
(send this insert! 2 (make-object ui:const% this-ent* zinal:ui:style:NO-STYLE "= λ:"))
(send this set-horizontal! #t)
))
)
(define/override (get-lambda-handle)
(send (send this get-cone-root) get-lambda)
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:override-racket-method% (class ent:lambda-like%
(init cone-root-handle child-spawner!)
(define this-ent* this)
(define/override (get-params-header)
(make-object (class ui:list%
(define (name-ui->event-handler* name-ui)
(create-racket-method-name-change-handler (thunk (send this-ent* get-cone-root)))
)
(define (get-name-text*)
(send (send this-ent* get-cone-root) get-racket-method-name)
)
(define (get-prefix-text*)
(define prefix (if (send (send this-ent* get-cone-root) is-augment?) "augment" "override"))
(format "~a racket method" prefix)
)
(define (prefix-ui->event-handler* prefix-ui)
(create-simple-event-handler zinal:key-bindings:TOGGLE-AUGMENT
(lambda (handle-event-info event)
(define override-handle (send this-ent* get-cone-root))
(send override-handle set-is-augment!! (not (send override-handle is-augment?)))
#t
)
)
)
(super-make-object this-ent* NOOP-FALLBACK-EVENT-HANDLER)
(send this insert! 0 (make-object ui:var-scalar% this-ent* zinal:ui:style:NO-STYLE get-prefix-text* prefix-ui->event-handler* NOOP-FALLBACK-EVENT-HANDLER))
(send this insert! 1 (make-object ui:var-scalar% this-ent* zinal:ui:style:DEF-STYLE get-name-text* name-ui->event-handler* NOOP-FALLBACK-EVENT-HANDLER))
(send this insert! 2 (make-object ui:const% this-ent* zinal:ui:style:NO-STYLE "= λ:"))
(send this set-horizontal! #t)
))
)
(define/override (get-lambda-handle)
(send (send this get-cone-root) get-lambda)
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:invoke-method% (class ent:typical-has-args% ; abstract
(init cone-root-handle child-spawner!)
(abstract get-method-name)
(abstract get-method-style)
(abstract get-new-method-from-user)
(abstract set-method!!)
(define/public (get-alternative-object-ui)
#f
)
(define this-ent* this)
(define child-spawner*! child-spawner!)
(define/override (get-header)
(make-object (class ui:slotted-list%
(define/override (get-visible-referables-for-slot slot)
(send (send this-ent* get-cone-root) get-visible-referables-after)
)
(super-make-object this-ent* NOOP-FALLBACK-EVENT-HANDLER)
(define (method-ui->event-handler* method-ui)
(define (interaction-function)
(get-new-method-from-user)
)
(define (result-handler result-from-user)
(set-method!! result-from-user)
)
(define method-change-handler (create-interaction-dependent-event-handler interaction-function result-handler zinal:key-bindings:REPLACE))
(define cone-root-handle (send this-ent* get-cone-root))
(if (is-a? cone-root-handle zinal:db:has-method%%)
(combine-keyname-event-handlers (list
method-change-handler
(create-search-selected-method-handlers* (send cone-root-handle get-method))
))
method-change-handler
)
)
(define method-ui* (make-object ui:var-scalar% this-ent* (get-method-style) (thunk (get-method-name)) method-ui->event-handler* NOOP-FALLBACK-EVENT-HANDLER))
(define alternative-object-ui* (get-alternative-object-ui))
(cond
[alternative-object-ui*
(send this insert! 0 alternative-object-ui*)
(send this insert! 1 method-ui*)
]
[else
(define object-slot* (make-object slot% (lambda (s) (send this child-slot->event-handler s)) NOOP-FALLBACK-EVENT-HANDLER))
(child-spawner*! object-slot* (send (send this-ent* get-cone-root) get-object) this)
(send this insert! 0 object-slot*)
(send this insert! 1 (make-object ui:const% this-ent* zinal:ui:style:NO-STYLE "⇒"))
(send this insert! 2 method-ui*)
]
)
(send this set-horizontal! #t)
))
)
(define/override (horizontal-by-default?)
#t
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:invoke-zinal-method% (class ent:invoke-method%
(init cone-root-handle child-spawner!)
(define/override (get-highlight-equivalence-handle ui-item)
(and (is-a? ui-item zinal:ui:var-scalar%%)
(send (send this get-cone-root) get-method)
)
)
(define/override (get-method-name)
(get-short-desc-or (send (send this get-cone-root) get-method) "<unnamed method>")
)
(define/override (get-method-style)
zinal:ui:style:REF-STYLE
)
(define/override (get-new-method-from-user)
(get-method-from-user (send (send this get-cone-root) get-visible-referables-after))
)
(define/override (set-method!! method-handle)
(send (send this get-cone-root) set-method!! method-handle)
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:invoke-racket-method% (class ent:invoke-method%
(init cone-root-handle child-spawner!)
(define/override (get-method-name)
(send (send this get-cone-root) get-racket-method-name)
)
(define/override (get-method-style)
zinal:ui:style:RACKET-STYLE
)
(define/override (get-new-method-from-user)
(use-text-from-user
"Enter the name of the racket method"
"I believe in you ..."
identity
non-empty-string?
)
)
(define/override (set-method!! name)
(send (send this get-cone-root) set-racket-method-name!! name)
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:this-invoke-zinal-method% (class ent:invoke-zinal-method%
(init cone-root-handle child-spawner!)
(define/override (get-alternative-object-ui)
(make-object ui:const% this zinal:ui:style:CONST-VALUE-STYLE "⊙")
)
(define/override (get-new-method-from-user)
(define class-handle (get-containing-class* (send this get-cone-root)))
(auto-complete*
"Select a method"
"Start typing bits and pieces of the desired method's short descriptor"
(map (lambda (method-handle) (list method-handle (get-short-desc-or method-handle "<unnamed method>"))) (send class-handle get-all-methods))
handles-equal?
)
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:this-invoke-racket-method% (class ent:invoke-racket-method%
(init cone-root-handle child-spawner!)
(define/override (get-alternative-object-ui)
(make-object ui:const% this zinal:ui:style:CONST-VALUE-STYLE "⊙")
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:super-invoke-zinal-method% (class ent:invoke-zinal-method%
(init cone-root-handle child-spawner!)
(define/override (get-alternative-object-ui)
(make-object ui:const% this zinal:ui:style:CONST-VALUE-STYLE "🡡")
)
(define/override (get-new-method-from-user)
(get-super-method-from-user (send this get-cone-root))
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:super-invoke-racket-method% (class ent:invoke-racket-method%
(init cone-root-handle child-spawner!)
(define/override (get-alternative-object-ui)
(make-object ui:const% this zinal:ui:style:CONST-VALUE-STYLE "🡡")
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:this% (class ent%
(init cone-root-handle child-spawner!)
(define ui-item*
(make-object ui:var-scalar% this zinal:ui:style:CONST-VALUE-STYLE (const "⊙") THING->NOOP this)
)
(define/override (get-root-ui-item)
ui-item*
)
(super-make-object cone-root-handle)
))
(define ent:create-object% (class ent:typical-has-args%
(init cone-root-handle child-spawner!)
(define/override (horizontal-by-default?)
#t
)
(define this-ent* this)
(define child-spawner*! child-spawner!)
(define/override (get-header)
(make-object (class ui:slotted-list%
(define/override (get-visible-referables-for-slot slot)
(send (send this-ent* get-cone-root) get-visible-referables-after)
)
(super-make-object this-ent* NOOP-FALLBACK-EVENT-HANDLER)
(send this insert! 0 (make-object ui:const% this-ent* zinal:ui:style:CREATE-SYMBOL-STYLE "☼"))
(define class-slot* (make-object slot% (lambda (s) (send this child-slot->event-handler s)) NOOP-FALLBACK-EVENT-HANDLER))
(child-spawner*! class-slot* (send (send this-ent* get-cone-root) get-class-node) this)
(send this insert! 1 class-slot*)
(send this set-horizontal! #t)
))
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:super-init% (class ent:typical-has-args%
(init cone-root-handle child-spawner!)
(define/override (horizontal-by-default?)
#t
)
(define this-ent* this)
(define/override (get-header)
(make-object ui:const% this-ent* zinal:ui:style:CREATE-SYMBOL-STYLE "🡡☼")
)
(super-make-object cone-root-handle child-spawner!)
))
(define ent:interface% (class ent%
(init cone-root-handle child-spawner!)
(define this-ent* this)
; Gross. We happen to know that the superclass does not actually need to call get-root-ui-item during
; initialization, so we can resolve a cyclic dependency by calling super-make-object before overriding
; get-root-ui-item
(super-make-object cone-root-handle)
(define header-header*
(make-object (class ui:list%
(define (name-ui->event-handler* name-ui)
(create-name-change-handler (thunk (send this-ent* get-cone-root)))
)
(define (get-name-text*)
(get-short-desc-or (send this-ent* get-cone-root) "<unnamed interface>")
)
(super-make-object this-ent* NOOP-FALLBACK-EVENT-HANDLER)
(send this insert! 0 (make-object ui:const% this-ent* zinal:ui:style:NO-STYLE "interface"))
(send this insert! 1 (make-object ui:var-scalar% this-ent* zinal:ui:style:DEF-STYLE get-name-text* name-ui->event-handler* NOOP-FALLBACK-EVENT-HANDLER))
(send this set-horizontal! #t)
))
)
(define header* (make-object ui:interface-set-list% this NOOP-FALLBACK-EVENT-HANDLER header-header*))
(define ui-item*
(make-object (class ui:handle-set-list%
(define/override (get-event-handler)
(combine-keyname-event-handlers (list
(super get-event-handler)
(create-simple-event-handler zinal:key-bindings:DELETE/UNASSIGN
(lambda (handle-event-info event)
(define interface-handle (send this-ent* get-cone-root))
(if (send interface-handle can-delete?)
(when (navigate-to-fresh-module*! (get-all-modules*)) (send interface-handle delete!!))
(issue-warning "Cannot delete interface" "Either this interface is a supertype of something or a reference to it exists")
)
#t
)
)
))
)
(define/override (db-get-items)
(send (send this-ent* get-cone-root) get-direct-methods)
)
(define/override (db-add-item!!)
(use-text-from-user
"Enter a short description of the new method"
"A short descriptor, one or a few words, to identify the new method"
(lambda (result)
(send (send this-ent* get-cone-root) add-direct-method!! result)
)
non-empty-string?
)
)
(define/override (db-can-remove-item? to-remove)
(send (send this-ent* get-cone-root) can-remove-direct-method? to-remove)
)
(define/override (db-remove-item!! to-remove)
(send (send this-ent* get-cone-root) remove-direct-method!! to-remove)
)
(define/override (get-item-ui-style)
zinal:ui:style:DEF-STYLE
)
(super-make-object this-ent* this-ent* header*)
(send this set-horizontal! #f)
))
)
(define/override (get-root-ui-item)
ui-item*
)
))
; UI IMPL
(define ui:item% (class* object% (zinal:ui:item%% event-handler%% fallback-event-handler%%) ; abstract
(init parent-ent fallback-event-handler)
(define parent-ent* parent-ent)
(define parent* #f)
(define (select-nearby-item-or*! items index increment alt)
(define num-items (length items))
(define (get-candidate) (list-ref items index))
(if (or (negative? index) (>= index num-items))
(alt)
(if (is-a? (get-candidate) zinal:ui:const%%)
(select-nearby-item-or*! items (+ index increment) increment alt)
(select! (get-candidate))
)
)
)
(define (select-neighbor-or*! item before? alt)
(define parent (send item get-parent))
(define all-siblings (send parent get-children-with-header-internal))
(define inc (if before? -1 1))
(define this-index
(list-index (compose1 (curry eq? item) slot/ui-item->ui-item) all-siblings)
)
(define neighbor-index (+ this-index inc))
(select-nearby-item-or*! all-siblings neighbor-index inc alt)
)
(define (select-next-sibling*! item)
(define parent (send item get-parent))
(when parent
(select-neighbor-or*! item #f (thunk
(select-next-sibling*! parent)
))
)
)
(define (handle-left*! handle-event-info event)
(cond
[(not parent*)
(void)
]
[(send parent* horizontal?)
(select-neighbor-or*! this #t (thunk
(select! parent*)
))
]
[else
(select! parent*)
]
)
(send handle-event-info set-db-wasnt-affected!)
)
(define (handle-right*! handle-event-info event)
(define (get-all-children)
(send this get-children-with-header-internal)
)
(if (and (is-a? this zinal:ui:list%%) (pair? (get-all-children)))
(select-nearby-item-or*! (get-all-children) 0 +1 (thunk (select-next-sibling*! this)))
(select-next-sibling*! this)
)
(send handle-event-info set-db-wasnt-affected!)
)
(define (get-child-of-first-vertical-ancestor* item)
(define parent (send item get-parent))
(if (and parent (send parent horizontal?))
(get-child-of-first-vertical-ancestor* parent)
item
)
)
(define (handle-down*! handle-event-info event)
(select-next-sibling*! (get-child-of-first-vertical-ancestor* this))
(send handle-event-info set-db-wasnt-affected!)
)
(define (handle-up*! handle-event-info event)
(define vert-child (get-child-of-first-vertical-ancestor* this))
(define vert-parent (send vert-child get-parent))
(if vert-parent
(select-neighbor-or*! vert-child #t (thunk
(select! vert-parent)
))
vert-child
)
(send handle-event-info set-db-wasnt-affected!)
)
(define/public (selected?)
(eq? this selected*)
)
(define/public (accept visitor [data #f])
(send visitor visit-item this data)
)
(define/public (get-root)
(if parent*
(send parent* get-root)
this
)
)
(define/public (get-parent-ent)
parent-ent*
)
(define/public (get-parent)
parent*
)
(define/public (set-parent! new-parent)
(set! parent* new-parent)
)
(define/public (get-event-handler)
(create-movement-handler)
)
(define event-handler* (get-event-handler))
(define fallback-event-handler* fallback-event-handler)
(define/public (handle-event!! event)
(define event-info (send event-handler* handle-event!! event))
(or
(and (send event-info was-handled?) event-info)
(send fallback-event-handler* handle-child-event!! event)
)
)
(define/public (handle-child-event!! event)
(send event-handler* handle-event!! event)
)
(define/public (create-movement-handler)
(combine-keyname-event-handlers (list
(create-left-handler)
(create-right-handler)
(create-up-handler)
(create-down-handler)
))
)
(define/public (create-left-handler)
(create-simple-event-handler zinal:key-bindings:MOVE-LEFT handle-left*!)
)
(define/public (create-right-handler)
(create-simple-event-handler zinal:key-bindings:MOVE-RIGHT handle-right*!)
)
(define/public (create-up-handler)
(create-simple-event-handler zinal:key-bindings:MOVE-UP handle-up*!)
)
(define/public (create-down-handler)
(create-simple-event-handler zinal:key-bindings:MOVE-DOWN handle-down*!)
)
(super-make-object)
))
(define ui:scalar% (class* ui:item% (zinal:ui:scalar%%) ; abstract
(init parent-ent style-delta item->event-handler fallback-event-handler)
(abstract get-text)
(define style-delta* style-delta)
(define event-handler* (item->event-handler this))
(define/override (accept visitor [data #f])
(send visitor visit-scalar this data)
)
(define/override (get-event-handler)
(combine-keyname-event-handlers (list
(super get-event-handler)
event-handler*
))
)
(define/public (get-style-delta)
style-delta*
)
(super-make-object parent-ent fallback-event-handler)
))
(define ui:const% (class* ui:scalar% (zinal:ui:const%%)
(init parent-ent style-delta text)
(define text* text)
(define/override (accept visitor [data #f])
(send visitor visit-const this data)
)
(define/override (get-text)
text*
)
(super-make-object parent-ent style-delta THING->NOOP NOOP-FALLBACK-EVENT-HANDLER)
))
(define ui:var-scalar% (class* ui:scalar% (zinal:ui:var-scalar%%)
(init parent-ent style-delta text-getter item->event-handler fallback-event-handler)
(define text-getter* text-getter)
(define current-text* #f)
(define current-highlight-equivalence-handle* #f)
(define last-seen-mod-count* -1)
(define/override (accept visitor [data #f])
(send visitor visit-var-scalar this data)
)
(define/override (get-text)
(update-cached*)
current-text*
)
(define/public (highlighted?)
(update-cached*)
(and
selected-highlight-equivalence-handle*
current-highlight-equivalence-handle*
(handles-equal? selected-highlight-equivalence-handle* current-highlight-equivalence-handle*)
)
)
(define (update-cached*)
(unless (= last-seen-mod-count* mod-count*)
(set! current-text* (text-getter*))
(set! current-highlight-equivalence-handle* (send (send this get-parent-ent) get-highlight-equivalence-handle this))
(set! last-seen-mod-count* mod-count*)
)
)
(super-make-object parent-ent style-delta item->event-handler fallback-event-handler)
))
(define ui:list% (class* ui:item% (zinal:ui:list%%)
(init parent-ent fallback-event-handler [header #f] [separator #f] [bookends #f])
(assert "header must be an item or #f" (implies header (is-a? header zinal:ui:item%%)))
(assert "separator must be a const or #f" (implies separator (is-a? separator zinal:ui:const%%)))
(assert
"bookends must be a pair of consts or #f"
(implies bookends (and (pair? bookends) (= 2 (length bookends)) (andmap (curryr is-a? zinal:ui:const%%) bookends)))
)
(define header* header)
(when header* (send header* set-parent! this))
(define separator* (or separator (make-object ui:const% parent-ent zinal:ui:style:NO-STYLE " ")))
(send separator* set-parent! this)
(define bookends* bookends)
(when bookends* (for-each (lambda (b) (send b set-parent! this)) bookends*))
(define children* '())
(define horizontal*? #f)
(define/override (accept visitor [data #f])
(send visitor visit-list this data)
)
(define/public (get-children)
(map slot/ui-item->ui-item children*)
)
(define/public (get-header)
header*
)
(define/public (horizontal?)
(define parent (send this get-parent))
(or
horizontal*?
(and parent (send parent horizontal?))
)
)
(define/public (get-horizontal-separator)
separator*
)
(define/public (get-bookends)
bookends*
)
(define/public (create-expand-and-collapse-handler)
(make-object keyname-event-handler% (list
(list collapse*! zinal:key-bindings:EXPAND)
(list expand*! zinal:key-bindings:COLLAPSE)
))
)
(define/public (set-horizontal! new-value)
(set! horizontal*? new-value)
)
(define/public (insert-but-dont-select! index new-child)
(define before (take children* index))
(define after (drop children* index))
(set! children* (append before (cons new-child after)))
(when (is-a? new-child zinal:ui:item%%) (send new-child set-parent! this))
)
(define/public (insert! index new-child)
(insert-but-dont-select! index new-child)
(select! new-child)
)
(define/public (remove! child/index)
(define is-index? (number? child/index))
(define index (if is-index? child/index (get-child-index child/index)))
(define child (if is-index? (list-ref children* child/index) child/index))
(set! children* (remq child children*))
(when (eq? selected* (slot/ui-item->ui-item child))
(define num-children (length children*))
(define selection
(cond
[(< index num-children)
(list-ref children* index)
]
[(> num-children 0)
(last children*)
]
[else
this
]
)
)
(select! selection)
)
)
(define/public (clear!)
(set! children* '())
)
(define/public (get-children-internal)
children*
)
(define/public (get-children-with-header-internal)
(if header* (cons header* children*) children*)
)
(define/public (get-child-index child)
(define index (list-index (curry eq? child) children*))
(assert "no such child" index)
index
)
(define (collapse*! handle-event-info event)
(set-horizontal! #t)
#t
)
(define (expand*! handle-event-info event)
(define (expand* ui-list)
(send ui-list set-horizontal! #f)
(define parent (send ui-list get-parent))
(when parent (expand* parent))
)
(expand* this)
#t
)
(super-make-object parent-ent fallback-event-handler)
))
(define ui:def-list% (class ui:list% ; abstract
(init parent-ent [fallback-event-handler NOOP-FALLBACK-EVENT-HANDLER])
(abstract get-default-name-text)
(define parent-ent* parent-ent)
(define/public (db-get-def-handle)
(send parent-ent* get-cone-root)
)
(define/public (get-bridge-text)
"="
)
(define (name-ui->event-handler* name-ui)
(create-name-change-handler (thunk (db-get-def-handle)))
)
(define (get-name-text*)
(get-short-desc-or (db-get-def-handle) (get-default-name-text))
)
(super-make-object parent-ent fallback-event-handler)
(send this set-horizontal! #t)
(send this insert! 0 (make-object ui:var-scalar% parent-ent zinal:ui:style:DEF-STYLE get-name-text* name-ui->event-handler* NOOP-FALLBACK-EVENT-HANDLER))
(send this insert! 1 (make-object ui:const% parent-ent zinal:ui:style:NO-STYLE (get-bridge-text)))
))
(define ui:possibly-public-def-list% (class ui:def-list% ; abstract
(init parent-ent [fallback-event-handler NOOP-FALLBACK-EVENT-HANDLER])
(define/public (get-prefix-text)
#f
)
(define public* (make-object ui:const% parent-ent zinal:ui:style:PUBLICITY-STYLE "public"))
(define (update-publicity-ui*)
(define db-def-handle (send this db-get-def-handle))
(when (can-be-public*? db-def-handle)
(if (public*? db-def-handle)
(send this insert-but-dont-select! 0 public*)
(when (eq? public* (first (send this get-children))) (send this remove! 0))
)
)
)
(define/override (get-event-handler)
(combine-keyname-event-handlers (list
(super get-event-handler)
(create-modify-publicity-handler* (thunk (send this db-get-def-handle)) update-publicity-ui*)
))
)
(super-make-object parent-ent fallback-event-handler)
(when (get-prefix-text)
(send this insert! 0 (make-object ui:const% parent-ent zinal:ui:style:NO-STYLE (get-prefix-text)))
)
(update-publicity-ui*)
))
(define ui:slotted-list% (class ui:list% ; abstract
(init parent-ent fallback-event-handler [header #f] [separator #f] [bookends #f])
(abstract get-visible-referables-for-slot)
(define/public (child-slot->event-handler slot)
(combine-keyname-event-handlers (list
(create-replace-handler slot)
(create-unassign-handler* slot this)
))
)
(define/public (create-replace-handler slot)
(create-replace-handler* slot this (lambda (s) (get-visible-referables-for-slot s)))
)
(super-make-object parent-ent fallback-event-handler header separator bookends)
))
(define ui:dynamic-slotted-list% (class ui:slotted-list% ; abstract
(init parent-ent fallback-event-handler child-spawner! [header #f] [separator #f] [bookends #f])
(abstract db-insert!!)
(abstract db-can-remove?)
(abstract db-remove!!)
(abstract db-get-items)
(abstract db-get-list-handle)
; items that are not part of the header, but which will be prepended to the list
(define/public (get-pseudo-headers)
'()
)
(define/override (get-event-handler)
(combine-keyname-event-handlers (list
(super get-event-handler)
(send this create-expand-and-collapse-handler)
(create-insert-start-handler)
(create-insert-end-handler)
))
)
(define/override (child-slot->event-handler slot)
(combine-keyname-event-handlers (list
(create-insert-before-handler slot)
(create-insert-after-handler slot)
(create-insert-todo-handler slot)
(send this create-replace-handler slot)
(create-unassign-or-remove-handler slot)
))
)
(define/override (get-visible-referables-for-slot slot)
(get-visible-referables-for-hypothetical-index (get-ui-index* slot))
)
(define/public (remove-slot!! slot)
(db-remove!! (get-db-index* slot))
(send this remove! slot)
)
(define/public (create-insert-start-handler [new-item-creator request-new-item-creator])
(create-typical-insert-slot-handler get-offset* zinal:key-bindings:INSERT-FIRST new-item-creator)
)
(define/public (create-insert-end-handler [new-item-creator request-new-item-creator])
(create-typical-insert-slot-handler (thunk (length (send this get-children-internal))) zinal:key-bindings:INSERT-LAST new-item-creator)
)
(define/public (create-insert-before-handler slot [new-item-creator request-new-item-creator])
(create-typical-insert-slot-handler (thunk (get-ui-index* slot)) zinal:key-bindings:INSERT-BEFORE new-item-creator)
)
(define/public (create-insert-after-handler slot [new-item-creator request-new-item-creator])
(create-typical-insert-slot-handler (thunk (add1 (get-ui-index* slot))) zinal:key-bindings:INSERT-AFTER new-item-creator)
)
(define/public (create-insert-todo-handler slot)
(create-typical-insert-slot-handler (thunk (add1 (get-ui-index* slot))) zinal:key-bindings:INSERT-UNASSIGNED-AFTER new-unassigned-creator)
)
(define/public (create-remove-handler slot)
(create-simple-event-handler zinal:key-bindings:DELETE/UNASSIGN
(lambda (handle-event-info event)
(when (db-can-remove? (get-db-index* slot)) (remove-slot!! slot))
#t
)
)
)
(define/public (create-unassign-or-remove-handler slot)
(create-simple-event-handler zinal:key-bindings:DELETE/UNASSIGN
(lambda (handle-event-info event)
(cond
[(db-can-remove? (get-db-index* slot)) (remove-slot!! slot)]
[(unassignable? (slot->db-handle slot)) (reassign-slot*!! slot this)]
)
#t
)
)
)
(define (get-offset*)
(length (get-pseudo-headers))
)
(define (db-index->ui-index* db-index)
(+ db-index (get-offset*))
)
(define (ui-index->db-index* ui-index)
(- ui-index (get-offset*))
)
(define (get-ui-index* slot)
(send this get-child-index slot)
)
(define (get-db-index* slot)
(ui-index->db-index* (get-ui-index* slot))
)
(define (get-visible-referables-for-hypothetical-index ui-index)
(get-visible-referables-for-hypothetical-index* (db-get-list-handle) (db-get-items) (ui-index->db-index* ui-index))
)
(define (create-insert-slot-handler get-ui-index interaction->new-handle-initializer!! keylist)
(define (result-handler new-handle-initializer!!)
(define ui-index (get-ui-index))
(define intermediate-handle (db-insert!! (ui-index->db-index* ui-index)))
(define new-handle (new-handle-initializer!! intermediate-handle))
(insert-new-slot! ui-index new-handle)
)
(create-interaction-dependent-event-handler
interaction->new-handle-initializer!!
result-handler
keylist
)
)
(define (create-typical-insert-slot-handler get-ui-index keylist [new-item-creator request-new-item-creator])
(define interaction->new-handle-initializer!!
(thunk (new-item-creator (db-get-list-handle) (get-visible-referables-for-hypothetical-index (get-ui-index))))
)
(create-insert-slot-handler get-ui-index interaction->new-handle-initializer!! keylist)
)
(define (insert-new-slot! ui-index slot-handle [child-spawner*! spawn-entity*!])
(define new-slot (make-object slot% child-slot->event-handler* this))
(child-spawner*! new-slot slot-handle this)
(send this insert! ui-index new-slot)
)
(define (child-slot->event-handler* slot)
(child-slot->event-handler slot)
)
(super-make-object parent-ent fallback-event-handler header separator bookends)
(map-by-index
(lambda (ui-index item) (send this insert! ui-index item))
(get-pseudo-headers)
)
(map-by-index
(lambda (db-index db-item) (insert-new-slot! (db-index->ui-index* db-index) db-item child-spawner!))
(db-get-items)
)
))
(define ui:params-list% (class ui:dynamic-slotted-list%
(init parent-ent fallback-event-handler child-spawner! has-params-handle [header #f])
(define has-params-handle* has-params-handle)
(define/override (db-insert!! index)
(define first-opt-index (get-first-opt-index*))
(if (<= index first-opt-index)
(send (db-get-list-handle) insert-required-param!! index)
(send (db-get-list-handle) insert-optional-param!! (- index first-opt-index))
)
)
(define/override (db-can-remove? index)
(define first-opt-index (get-first-opt-index*))
(if (< index first-opt-index)
(send (db-get-list-handle) can-remove-required-param? index)
(send (db-get-list-handle) can-remove-optional-param? (- index first-opt-index))
)
)
(define/override (db-remove!! index)
(define first-opt-index (get-first-opt-index*))
(if (< index first-opt-index)
(send (db-get-list-handle) remove-required-param!! index)
(send (db-get-list-handle) remove-optional-param!! (- index first-opt-index))
)
)
(define/override (db-get-items)
(send (db-get-list-handle) get-all-params)
)
(define/override (db-get-list-handle)
has-params-handle*
)
(define/override (get-event-handler)
(combine-keyname-event-handlers (list
(send this create-movement-handler)
(send this create-insert-start-handler new-param-creator)
(send this create-insert-end-handler new-param-creator)
))
)
(define/override (child-slot->event-handler slot)
(combine-keyname-event-handlers (list
(send this create-insert-before-handler slot new-param-creator)
(send this create-insert-after-handler slot new-param-creator)
(send this create-remove-handler slot)
(create-simple-event-handler zinal:key-bindings:MAKE-REQUIRED
(lambda (handle-event-info event)
(define first-opt-index (get-first-opt-index*))
(define slot-index (send this get-child-index slot))
(when (= slot-index first-opt-index)
(send (db-get-list-handle) make-last-optional-param-required!!)
(select! slot)
)
#t
)
)
(create-simple-event-handler zinal:key-bindings:MAKE-OPTIONAL
(lambda (handle-event-info event)
(define first-opt-index (get-first-opt-index*))
(define slot-index (send this get-child-index slot))
(when (= slot-index (sub1 first-opt-index))
(send (db-get-list-handle) make-last-required-param-optional!!)
(select! slot)
)
#t
)
)
))
)
(define (get-first-opt-index*)
(length (send (db-get-list-handle) get-required-params))
)
(define (new-param-creator parent-handle visible-referables)
(use-text-from-user
"Enter short descriptor for param"
"A short descriptor, one or a few words, to identify this param"
(lambda (result)
(lambda (param) (send param set-short-desc!! result) param)
)
non-empty-string?
)
)
(super-make-object parent-ent fallback-event-handler child-spawner! header (make-object ui:const% parent-ent zinal:ui:style:NO-STYLE ", "))
(send this set-horizontal! #t)
))
; TODO this probably shouldn't extend ui:list% , cuz it's not meant to be modified or used in the ways that lists can be
(define ui:handle-set-list% (class ui:list%
(init parent-ent fallback-event-handler [header #f])
; all items must be zinal:db:describable%% , and they should not be part of the tree
(abstract db-get-items)
(abstract db-add-item!!)
(abstract db-can-remove-item?)
(abstract db-remove-item!!)
(abstract get-item-ui-style)
(define parent-ent* parent-ent)
(define handles* (vector-immutable))
(define/override (get-event-handler)
(combine-keyname-event-handlers (list
(super get-event-handler)
(add-item-event-handler* #f)
))
)
(define/public (get-nth-handle index)
(vector-ref handles* index)
)
(define/public (reset! [handle-to-select #f])
(define selected-index (list-index (curry eq? selected*) (send this get-children)))
(send this clear!)
(define handles (sort (db-get-items) item-handle<?))
(set! handles* (list->vector handles))
(map-by-index
(lambda (i h)
(define to-insert
(make-object ui:var-scalar%
parent-ent*
(get-item-ui-style)
(thunk (get-short-desc-or h "<unnamed>"))
(curry item-handle->event-handler* h)
NOOP-FALLBACK-EVENT-HANDLER
)
)
(if (and handle-to-select (handles-equal? handle-to-select h))
(send this insert! i to-insert)
(send this insert-but-dont-select! i to-insert)
)
)
handles
)
(when (and (not handle-to-select) selected-index)
(define children (send this get-children))
(if (null? children)
(select! this)
(select! (list-ref children (min selected-index (sub1 (length children)))))
)
)
)
(define (item-handle->event-handler* item-handle item-ui)
(combine-keyname-event-handlers (list
(create-name-change-handler (const item-handle))
(add-item-event-handler* #t)
(create-simple-event-handler zinal:key-bindings:DELETE/UNASSIGN
(lambda (handle-event-info event)
(cond
[(db-can-remove-item? item-handle)
(db-remove-item!! item-handle)
(reset!)
]
[else
(issue-warning "Cannot remove item from set" "I don't really know why you can't, you just can't. Bummer, i know")
]
)
#t
)
)
))
)
(define (add-item-event-handler* augmented?)
(create-simple-event-handler
(append
zinal:key-bindings:INSERT-FIRST
zinal:key-bindings:INSERT-LAST
(if augmented?
(append zinal:key-bindings:INSERT-BEFORE zinal:key-bindings:INSERT-AFTER)
'()
)
)
(lambda (handle-event-info event)
(define added-handle (db-add-item!!))
(when added-handle (reset! added-handle))
#t
)
)
)
(define (item-handle<? item-handle-1 item-handle-2)
(define (desc ih) (get-short-desc-or ih ""))
(string<? (desc item-handle-1) (desc item-handle-2))
)
(super-make-object parent-ent fallback-event-handler header (make-object ui:const% parent-ent zinal:ui:style:NO-STYLE ", "))
(send this set-horizontal! #t)
(reset!)
))
(define ui:interface-set-list% (class ui:handle-set-list%
(init parent-ent fallback-event-handler [header #f])
(define parent-ent* parent-ent)
(define/override (db-get-items)
(send (send parent-ent* get-cone-root) get-direct-super-interfaces)
)
(define/override (db-add-item!!)
(define type-handle (send parent-ent* get-cone-root))
(define interface-to-implement (get-interface-from-user (filter (lambda (i) (send type-handle can-add-direct-super-interface? i)) (send db* get-all-interfaces))))
(cond
[interface-to-implement
(send type-handle add-direct-super-interface!! interface-to-implement)
interface-to-implement
]
[else
#f
]
)
)
(define/override (db-can-remove-item? to-remove)
(send (send parent-ent* get-cone-root) can-remove-direct-super-interface? to-remove)
)
(define/override (db-remove-item!! to-remove)
(send (send parent-ent* get-cone-root) remove-direct-super-interface!! to-remove)
)
(define/override (get-item-ui-style)
zinal:ui:style:REF-STYLE
)
(super-make-object parent-ent fallback-event-handler header)
))
; HELPER FUNCTIONS
(define (slot/ui-item->ui-item slot/ui-item)
(if (is-a? slot/ui-item slot%)
(send (send slot/ui-item get-ent) get-root-ui-item)
slot/ui-item
)
)
(define (slot->db-handle slot)
(send (send slot get-ent) get-cone-root)
)
(define (find-prev*! criterion)
(find*! db-search-prev criterion)
)
(define (find-next*! criterion)
(find*! db-search-next criterion)
)
(define (find*! searcher criterion)
(define current-handle (send (send selected* get-parent-ent) get-cone-root))
(define found-handle (searcher criterion current-handle))
(when found-handle
(define current-root-slot (get-root-slot*))
(define found-root-handle (find-first-root-ancestor found-handle))
(assert "found handle has no valid root" found-root-handle)
(define new-root-slot
(if (handles-equal? (slot->db-handle current-root-slot) found-root-handle)
current-root-slot
(spawn-root-entity*! found-root-handle)
)
)
(define new-selection (find-handle-under-slot new-root-slot found-handle))
(assert "could not find the found handle underneath the new root slot" new-selection)
(select! new-selection)
)
)
(define (racket-handle->string racket-handle)
(define library (send racket-handle get-library))
(define name (send racket-handle get-name))
(if library (format "~a→~a" library name) name)
)
(define (has-params->short-params-string has-params-handle)
(define param-names
(map
(lambda (p)
(format (if (send p get-default) "[~a]" "~a") (get-short-desc-or p "<nameless param>"))
)
(send has-params-handle get-all-params)
)
)
(format "λ: ~a" (string-join param-names ", "))
)
(define (create-module*!!)
(use-text-from-user
"Enter the new module's name"
"A short descriptor, one or a few words, to name this module"
(lambda (result)
(send db* create-module!! result)
)
non-empty-string?
)
)
(define (create-interface*!!)
(use-text-from-user
"Enter the new interface's name"
"A short descriptor, one or a few words, to name this interface"
(lambda (result)
(send db* create-interface!! result)
)
non-empty-string?
)
)
(define (get-module-from-user [selectable-modules (get-all-modules*)])
(define handles&choices
(map
(lambda (db-module)
(define name (get-short-desc-or db-module "<unnamed module>"))
(list db-module (if (send db-module is-main-module?) (format "~a (Main)" name) name))
)
selectable-modules
)
)
(auto-complete* "Choose a module" "Start typing bits and pieces of the desired module's name" handles&choices handles-equal?)
)
(define (navigate-to-fresh-module*! [selectable-modules (get-all-modules*)] [default-to-main? #t])
(define main-module (send db* get-main-module))
(define next-module
(or
(and default-to-main? (member main-module selectable-modules handles-equal?) main-module)
(if (pair? selectable-modules)
(get-module-from-user selectable-modules)
(create-module*!!)
)
)
)
(when next-module (spawn-root-entity*! next-module))
next-module
)
(define (get-all-modules* [module-to-exclude #f])
(remove module-to-exclude (send db* get-all-modules) handles-equal?)
)
(define (get-interface-from-user selectable-interfaces)
(define handles&choices
(map
(lambda (interface)
(list interface (get-short-desc-or interface "<unnamed interface>"))
)
selectable-interfaces
)
)
(auto-complete* "Choose an interface" "Start typing bits and pieces of the desired interface's name" handles&choices handles-equal?)
)
(define (unassignable? handle)
(cond
[(send handle can-unassign?)
#t
]
[(send handle get-parent)
(assert "can't unassign a non-referable, non-root handle" (is-a? handle zinal:db:referable%%))
(issue-warning
"Cannot unassign"
(format
"Referable ~a has at least one reference that is not a descendant, so it can't be unassigned"
(send handle get-short-desc)
)
)
#f
]
[else
(issue-warning "Cannot unassign" "You cannot unassign the root node")
#f
]
)
)
; result-handler accepts a result from a user interaction and does something with it. Its return
; value is ignored.
; interaction-function should return a result from the user interaction to be passed to,
; result-handler. To indicate that no action should be taken, interaction-function should return #f.
; Regardless of what happens, the handler always returns #t, indicating that the action has been
; handled
(define (create-interaction-dependent-event-handler interaction-function result-handler keylist)
(define (handler-function handle-event-info event)
(define interaction-result (interaction-function))
(when interaction-result (result-handler interaction-result))
#t
)
(make-object keyname-event-handler% (list (list handler-function keylist)))
)
(define (create-simple-event-handler keylist handler-function)
(make-object keyname-event-handler% (list (list handler-function keylist)))
)
(define (create-racket-method-name-change-handler get-racket-method-handle)
(define (interaction-function)
(use-text-from-user
"Enter the new racket method name"
"The exact name of the racket method you want to change this to"
identity
non-empty-string?
)
)
(define (result-handler new-name)
(send (get-racket-method-handle) set-racket-method-name!! new-name)
)
(create-interaction-dependent-event-handler interaction-function result-handler zinal:key-bindings:REPLACE)
)
(define (create-name-change-handler get-describable-handle)
(define (interaction-function)
(use-text-from-user
"Enter the new name"
"A short descriptor, one or a few words, to name this thing"
identity
non-empty-string?
)
)
(define (result-handler new-name)
(send (get-describable-handle) set-short-desc!! new-name)
)
(create-interaction-dependent-event-handler interaction-function result-handler zinal:key-bindings:REPLACE)
)
(define (create-replace-handler* slot ui-parent get-visible-referables-for-slot)
(define (interaction-function)
(define handle (slot->db-handle slot))
(and
(unassignable? handle)
(request-new-item-creator (send handle get-parent) (get-visible-referables-for-slot slot))
)
)
(create-interaction-dependent-event-handler interaction-function (lambda (nhi) (reassign-slot*!! slot ui-parent nhi)) zinal:key-bindings:REPLACE)
)
(define (create-unassign-handler* slot ui-parent)
(create-simple-event-handler zinal:key-bindings:DELETE/UNASSIGN
(lambda (handle-event-info event)
(when (unassignable? (slot->db-handle slot)) (reassign-slot*!! slot ui-parent))
#t
)
)
)
(define (create-modify-publicity-handler* get-define-handle ui-callback)
(create-simple-event-handler zinal:key-bindings:MODIFY-ACCESS
(lambda (handle-event-info event)
(define define-handle (get-define-handle))
(when (can-be-public*? define-handle)
(send (send define-handle get-parent) set-public!! define-handle (not (public*? define-handle)))
(ui-callback)
)
#t
)
)
)
(define (create-navigate-to-root-handler* root-handle)
(create-simple-event-handler zinal:key-bindings:VIEW-DEFINITION
(lambda (handle-event-info event)
(spawn-root-entity*! root-handle)
(send handle-event-info set-db-wasnt-affected!)
)
)
)
(define (create-search-selected-handlers* criterion)
(define (search-handler finder keylist)
(create-simple-event-handler keylist
(lambda (handle-event-info event)
(finder criterion)
(send handle-event-info set-db-wasnt-affected!)
)
)
)
(combine-keyname-event-handlers (list
(search-handler find-next*! zinal:key-bindings:GOTO-NEXT)
(search-handler find-prev*! zinal:key-bindings:GOTO-PREV)
))
)
(define (create-search-selected-method-handlers* method-handle)
(create-search-selected-handlers* (lambda (node)
(and
(is-a? node zinal:db:has-method%%)
(handles-equal? (send node get-method) method-handle)
)
))
)
(define (reassign-slot*!! slot ui-parent [new-handle-initializer!! identity])
(define intermediate-handle (send (slot->db-handle slot) unassign!!))
(define new-handle (new-handle-initializer!! intermediate-handle))
(spawn-entity*! slot new-handle ui-parent)
(select! slot)
)
(define (get-visible-referables-for-hypothetical-index* list-handle child-handles index)
(if (zero? index)
(send list-handle get-visible-referables-underneath)
(send (list-ref child-handles (sub1 index)) get-visible-referables-after)
)
)
(define (spawn-or-reassign-entity*! slot cone-root-handle ui-parent existing-slots)
(define existing-slot
(findf (compose1 (curry handles-equal? cone-root-handle) slot->db-handle) existing-slots)
)
(define new-ent
(if existing-slot
(send existing-slot get-ent)
(make-object (parse-entity*! cone-root-handle) cone-root-handle spawn-entity*!)
)
)
(send new-ent assign-to-slot! slot ui-parent)
)
(define (spawn-entity*! slot cone-root-handle ui-parent [child-spawner! spawn-entity*!])
(define new-ent (make-object (parse-entity*! cone-root-handle) cone-root-handle child-spawner!))
(send new-ent assign-to-slot! slot ui-parent)
)
(define (root-slot->root-event-handler* root-slot)
(create-simple-event-handler zinal:key-bindings:RETURN-TO-PARENT
(lambda (handle-event-info event)
(define root-handle (slot->db-handle root-slot))
(cond
[(is-one-of? root-handle (list zinal:db:module%% zinal:db:interface%%))
(navigate-to-fresh-module*! (get-all-modules* root-handle) #f)
]
[else
(define first-root-ancestor (find-first-root-ancestor root-handle))
(assert "could not find root ancestor of non-module, non-interface root handle" first-root-ancestor)
(define new-root-slot (spawn-root-entity*! first-root-ancestor))
(define new-root-handle-slot (find-handle-under-slot new-root-slot root-handle))
(assert "could not find the previous root handle underneath the new root handle" new-root-handle-slot)
(select! new-root-handle-slot)
]
)
(send handle-event-info set-db-wasnt-affected!)
)
)
)
(define (spawn-root-entity*! root-handle)
(assert "attempt to spawn a root for a non-root type" (can-be-root*? root-handle))
(define root-slot (make-object slot% root-slot->root-event-handler* NOOP-FALLBACK-EVENT-HANDLER))
(define new-ent (make-object (parse-root-entity*! root-handle) root-handle spawn-entity*!))
(send new-ent assign-to-slot! root-slot #f)
(select! root-slot)
root-slot
)
(define (can-be-root*? handle)
; TODO maybe make some definitions present inline
(is-one-of? handle (list zinal:db:def%% zinal:db:define-method%% zinal:db:override-racket-method%% zinal:db:subtype%% zinal:db:module%%))
)
(define (find-first-root-ancestor h)
(define parent (send h get-parent))
(and parent
(if (can-be-root*? parent) parent (find-first-root-ancestor parent))
)
)
(define (find-handle-under-slot slot handle)
(define slot-children (send (send slot get-ent) get-cone-leaves))
(or
(findf (compose1 (curry handles-equal? handle) slot->db-handle) slot-children)
(ormap (curryr find-handle-under-slot handle) slot-children)
)
)
(define (function-definition*? handle)
(and (is-a? handle zinal:db:def%%) (is-a? (send handle get-expr) zinal:db:lambda%%))
)
(define (parse-root-entity*! root-handle)
(send root-handle accept (make-object (class zinal:db:element-visitor% (super-make-object)
(define/override (visit-element e meh)
(error 'parse-root-entity*! "Cannot parse entity for non-root type")
)
(define/override (visit-define-method root-define-method-handle meh)
ent:define-method%
)
(define/override (visit-override-racket-method root-override-racket-handle meh)
ent:override-racket-method%
)
(define/override (visit-interface root-interface-handle meh)
ent:interface%
)
(define/override (visit-define-class root-define-class-handle meh)
ent:define-class%
)
(define/override (visit-class-instance root-class-instance-handle meh)
ent:class-instance%
)
(define/override (visit-module root-module-handle meh)
ent:module%
)
(define/override (visit-def root-def-handle meh)
(if (function-definition*? root-def-handle)
ent:func-def%
ent:def%
)
)
)))
)
(define (parse-non-nil-list-entity*! db-list-handle)
(define items (send db-list-handle get-items))
(define first-item (first items))
(cond
[(is-a? first-item zinal:db:racket%%)
(cond
[(and (= 2 (length items)) (standard-with-name*? first-item "quote") (is-a? (second items) zinal:db:list%%))
ent:quoted-list%
]
[(standard-with-name*? first-item "list")
ent:list-list%
]
[else
; TODO we should probably have some sort of quote-context to make this an ordinary
; list when underneath something quoted ... or something
ent:racket-invokation%
]
)
]
[(is-a? first-item zinal:db:reference%%)
ent:reference-invokation%
]
[else ent:typical-list%]
)
)
(define (parse-entity*! db-handle)
(send db-handle accept (make-object (class zinal:db:element-visitor% (super-make-object)
(define/override (visit-element e meh)
(error 'parse-entity*! "Cannot parse entity for mysterious db handle")
)
(define/override (visit-invoke-method db-invoke-method-handle meh)
(if (is-a? (send db-invoke-method-handle get-object) zinal:db:this%%)
ent:this-invoke-zinal-method%
ent:invoke-zinal-method%
)
)
(define/override (visit-invoke-racket-method db-invoke-racket-method-handle meh)
(if (is-a? (send db-invoke-racket-method-handle get-object) zinal:db:this%%)
ent:this-invoke-racket-method%
ent:invoke-racket-method%
)
)
(define/override (visit-create-object db-create-object-handle meh)
ent:create-object%
)
(define/override (visit-super-init db-super-init-handle meh)
ent:super-init%
)
(define/override (visit-invoke-super-method db-invoke-super-method-handle meh)
ent:super-invoke-zinal-method%
)
(define/override (visit-invoke-racket-super-method db-invoke-racket-super-method-handle meh)
ent:super-invoke-racket-method%
)
(define/override (visit-define-method db-define-method-handle meh)
ent:short-define-method%
)
(define/override (visit-override-racket-method db-override-racket-handle meh)
(if (send db-override-racket-handle is-augment?)
ent:short-augment-racket-method%
ent:short-override-racket-method%
)
)
(define/override (visit-this db-this-handle meh)
ent:this%
)
(define/override (visit-define-class db-define-class-handle meh)
ent:short-define-class%
)
(define/override (visit-class-instance db-class-instance-handle meh)
ent:short-class-instance%
)
(define/override (visit-reference db-ref-handle meh)
ent:ref%
)
(define/override (visit-assert db-assert-handle meh)
ent:assert%
)
(define/override (visit-atom db-atom-handle meh)
(if (is-a? db-atom-handle zinal:db:string%%)
(if (non-empty-string? (send db-atom-handle get-val))
ent:string%
ent:empty-string%
)
ent:atom%
)
)
(define/override (visit-lambda db-lambda-handle meh)
ent:lambda%
)
(define/override (visit-param db-param-handle meh)
(if (send db-param-handle get-default)
ent:optional-param%
ent:required-param%
)
)
(define/override (visit-list db-list-handle meh)
(if (pair? (send db-list-handle get-items))
(parse-non-nil-list-entity*! db-list-handle)
ent:typical-list%
)
)
(define/override (visit-module db-module-handle meh)
(error 'parse-entity*! "Modules should never be parsed in the ordinary way - all parsing should parse the root with spawn-root-entity*!")
)
(define/override (visit-def db-def-handle meh)
(if (function-definition*? db-def-handle)
ent:short-func-def%
ent:short-def%
)
)
(define/override (visit-racket db-racket-handle meh)
ent:racket%
)
(define/override (visit-unassigned db-unassigned-handle meh)
ent:unassigned%
)
)))
)
))
)
| false |
ae1525a07b01934206cc1d9a6949b9d4611d7e9f | e3cfbb9a978d3ac739d7a623bc8982d3dee1ba64 | /fear-of-macro/robust-macro-syntax-parse.rkt | 24be5e643d8ecec0cfd4c80d6487515eef84a7a8 | []
| no_license | xuchunyang/learn-racket | 7cbeb1545c519705bb8759851c2d104760163203 | 13ca916e5eafa7f4de141034fe65a2f99c2b7f71 | refs/heads/master | 2020-03-22T17:10:47.754872 | 2020-01-17T17:24:08 | 2020-01-17T17:24:08 | 140,378,786 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 433 | rkt | robust-macro-syntax-parse.rkt | #lang racket
;; ---------------------------------------------------------------
;; Robust Function
(define/contract (misuse s)
(string? . -> . string?)
(string-append s " snazzy suffix"))
;; (misuse 123)
(module a typed/racket
(: misuse (String -> String))
(define (misuse s)
(string-append s " snazzy suffix"))
;; (misuse 0)
)
;; ---------------------------------------------------------------
;; syntax-parse
| false |
a63e6a11c13e6389f5b39fae90b4e4a7ae3d778b | 627680558b42ab91471b477467187c3f24b99082 | /defense/overview-slides.rkt | 2fd283c9ed6bfb2af820c03a9216983418c9de01 | []
| no_license | bfetscher/dissertation | 2a579aa919d6173a211560e20630b3920d108412 | 148d7f9bb21ce29b705522f7f4967d63bffc67cd | refs/heads/master | 2021-01-12T12:57:45.507113 | 2016-10-06T06:54:21 | 2016-10-06T06:54:21 | 70,130,350 | 0 | 1 | null | 2016-10-06T14:01:38 | 2016-10-06T06:58:19 | Racket | UTF-8 | Racket | false | false | 1,756 | rkt | overview-slides.rkt | #lang racket/base
(require slideshow
racket/gui/base
racket/runtime-path
"examples.rkt")
(dots? #t)
(define (slide-columns num-columns lst)
(define one-nth-ish (quotient (length lst) num-columns))
(define first-columns
(for/list ([i (in-range (- num-columns 1))])
(take (drop lst (* one-nth-ish i))
one-nth-ish)))
(define columns (append first-columns
(list
(drop lst (apply + (map length first-columns))))))
(slide
(to-bitmap
(scale-to-fit
(apply ht-append
40
(for/list ([column (in-list columns)])
(apply vl-append 4 column)))
client-w client-h))))
(define (to-bitmap pict)
(define bmp (make-bitmap (inexact->exact (ceiling (pict-width pict)))
(inexact->exact (ceiling (pict-height pict)))))
(define bdc (make-object bitmap-dc% bmp))
(draw-pict pict bdc 0 0)
(send bdc set-bitmap #f)
(bitmap bmp))
(define (line->pict line factor)
(define dots (line->dots line 20))
(hc-append
20
dots
(filled-rectangle (* (string-length (format "~s" (list-ref line 0)))
factor)
(/ (pict-height dots) 2))))
(define (sort-em l)
(sort l <
#:cache-keys? #t
#:key (λ (x)
(if (list-ref x 0)
(string-length (format "~s" (list-ref x 0)))
-1))))
(define (grammar-overview)
(slide-columns
10
(for/list ([i (in-list (sort-em grammar-based))])
(line->pict i 8))))
(define (jf-overview)
(slide-columns
10
(for/list ([i (in-list (sort-em jf-based))])
(line->pict i 2))))
(provide grammar-overview jf-overview) | false |
0ed9ff0f5e930fbfb9c5887d46bfc69abff1d7b3 | 9cb7787e057ed26dfba2fd6a837bd24cd51e39ff | /contract.rkt | b09aaf75872bf54f19be5aaa6119ccafdbcf6059 | []
| no_license | gmarceau/racket-utils | b3af14bc2fe05ba2b16ba96eb65867b3c82c726c | d7fdf833f0d7602d1a9c17be516c477a1614cef6 | refs/heads/master | 2021-01-18T23:12:23.500045 | 2016-07-08T03:07:38 | 2016-07-08T03:07:38 | 2,110,575 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,010 | rkt | contract.rkt | #lang racket
(provide (all-defined-out))
(provide list-even-length/c)
(define list-even-length/c (rename-contract (and/c list? (lambda (lst) (even? (length lst))))
'list-even-length/c))
(define (map-pairwise k-fn v-fn lst)
(let loop ([even #f] [lst lst])
(cond [(empty? lst) empty]
[(not even) (cons (k-fn (first lst)) (loop (not even) (rest lst)))]
[else (cons (v-fn (first lst)) (loop (not even) (rest lst)))])))
(define (list-pairwise/c k/c v/c)
(define name (build-compound-type-name 'list-pairwise/c k/c v/c))
(rename-contract
(and/c list-even-length/c
(make-contract #:name name
#:first-order (lambda (lst) (andmap identity (map-pairwise (contract-first-order k/c) (contract-first-order v/c) lst)))
#:projection (lambda (blame) (lambda (lst) (map-pairwise ((contract-projection k/c) blame) ((contract-projection v/c) blame) lst)))))
name)) | false |
bb5d6648c27f698d02721d2a847536dd393bb894 | 5dabad9ed5c2506ae2b850b4f013198f46eb1fba | /minipascal/mini-pascal-lexer.rkt | 4604bf620a885bc49e0aa068ab7bfc3605bce2cd | []
| no_license | soegaard/minipascal | 15847546ed0575227e97ad68bb5a1c0520ba90d3 | 646c1cedefc3d269db43b9d186d892655d4efb78 | refs/heads/master | 2021-09-28T05:56:48.576387 | 2021-09-26T12:46:52 | 2021-09-26T12:46:52 | 7,889,135 | 77 | 13 | null | 2015-07-20T20:42:28 | 2013-01-29T09:28:24 | Pascal | UTF-8 | Racket | false | false | 5,950 | rkt | mini-pascal-lexer.rkt | #lang racket
;;;
;;; LEXER
;;;
; This module defines two lexers for MiniPascal.
(provide lex color-lex)
; The main one, lex, returns tokens to
; be used by the ragg parser.
; The other one, color-lex, returns tokens
; to be used by DrRacket to syntax color
; Pascal programs.
(require ragg/support parser-tools/lex)
; Reserved keywords in Pacal ignore case.
; Thus the "PrOgRaM" and "program" are
; the same keyword. Since the lexer has
; no builtin support for matching mixed case
; strings, we define our own lexer
; transformation, mixed, that turns
; (mixed "foo") into
; (concatenation
; (union #\f #\F) (union #\o #\o) (union #\o #\o))
; Remember to use string-downcase on the
; resulting lexeme.
(require (for-syntax syntax/parse))
(define-lex-trans mixed
(λ (stx)
(syntax-parse stx
[(_ datum)
(define str (string-downcase (syntax->datum #'datum)))
(define STR (string-upcase str))
#`(concatenation
#,@(for/list ([c (in-string str)]
[C (in-string STR)])
#`(union #,c #,C)))])))
; The following lexer transformation turns
; (union-mixed "foo" "bar") into
; (union (mixed "foo") (mixed "bar"))
(define-lex-trans union-mixed
(λ (stx)
(syntax-parse stx
[(_ str ...)
#`(union (mixed str) ...)])))
; Since we want to define two lexers, it is
; convenient to define lexer abbreviations
; that can be used in both lexers.
(define-lex-abbrevs
[letter
(union (char-range #\a #\z) (char-range #\A #\Z))]
[digit
(char-range #\0 #\9)]
[identifier
(concatenation letter
(repetition 0 +inf.0 (union letter digit)))]
[integer ; non-negative
(repetition 1 +inf.0 digit)]
[char-constant
(union (concatenation #\' (char-complement #\') #\') "''''")]
[string-content
(union (char-complement #\') "''")]
[string-constant
(union (concatenation #\' (repetition 0 +inf.0 string-content) #\'))]
[reserved
(union-mixed
"div" "or" "and" "not" "if" "for" "to" "downto"
"then" "else" "of" "while" "do" "begin" "end"
"read" "readln" "write" "writeln"
"var" "const" "array" "type" "bindable"
"procedure" "function" "program")]
[slash-comment
(concatenation "//" (repetition 0 +inf.0 (char-complement #\newline)))]
[curly-comment
(concatenation #\{ (repetition 0 +inf.0 (char-complement #\})) #\})]
[comment
(union slash-comment curly-comment)]
[operators
(union "+" "-" "*" "=" "<>" "<" ">" "<=" ">=" ":=")]
[brackets
(union "(" ")" "[" "]")]
[other-delimiters
(union "." "," ";" ":" "..")]
[delimiters
(union operators brackets other-delimiters)])
(define (string-remove-ends str)
(substring str 1 (sub1 (string-length str))))
;; Lexer for MiniPascal
(define (lex ip)
(port-count-lines! ip)
(define my-lexer
(lexer-src-pos
[(union "integer" "char" "boolean" "true" "false")
(token 'IDENTIFIER (string->symbol lexeme))]
[(union reserved delimiters) ; includes operators
(string-downcase lexeme)]
[identifier
(token 'IDENTIFIER (string->symbol (string-downcase lexeme)))]
[integer
(token 'INTEGER-CONSTANT (string->number lexeme))]
[char-constant
(if (equal? lexeme "''''")
(token 'CHARACTER-CONSTANT #\')
(token 'CHARACTER-CONSTANT (string-ref lexeme 1)))]
[string-constant
(token 'STRING-CONSTANT
(regexp-replace* "''" (string-remove-ends lexeme) "'"))]
[whitespace
(token 'WHITESPACE lexeme #:skip? #t)]
[comment
(token 'COMMENT lexeme #:skip? #t)]
[(eof)
(void)]))
(define (next-token)
(my-lexer ip))
next-token)
;;;
;;; COLOR LEXER
;;;
; This lexer is used by DrRacket to color the Pacal program.
; The color lexer returns 5 values:
; - Either a string containing the matching text or the eof object.
; Block comments and specials currently return an empty string.
; This may change in the future to other string or non-string data.
; - A symbol in '(error comment sexp-comment white-space constant
; string no-color parenthesis other symbol eof).
; - A symbol in '(|(| |)| |[| |]| |{| |}|) or #f.
; - A number representing the starting position of the match (or #f if eof).
; - A number representing the ending position of the match (or #f if eof).
(define (syn-val a b c d e)
(values a ; string with matching text
b ; symbol in '(comment white-space no-color eof)
c ; symbol in '(|(| |)| |[| |]| |{| |}|) or #f.
(position-offset d) ; start pos
(max ; end pos
(position-offset e)
(+ (position-offset d) 1))))
(define color-lex
; REMEMBER to restart DrRacket to test any changes in the
; color-lexer. The lexer is only imported into DrRacket
; at startup.
(lexer
[(eof)
(syn-val lexeme 'eof #f start-pos end-pos)]
[reserved
(syn-val lexeme 'keyword #f start-pos end-pos)]
[brackets
(syn-val lexeme 'parenthesis (string->symbol lexeme) start-pos end-pos)]
[whitespace
(syn-val lexeme 'white-space #f start-pos end-pos)]
[slash-comment
(syn-val lexeme 'comment #f start-pos end-pos)]
[curly-comment
(syn-val lexeme 'sexp-comment #f start-pos end-pos)]
[(union "{" "}")
(syn-val lexeme 'sexp-comment (string->symbol lexeme) start-pos end-pos)]
#;[operators
(syn-val lexeme 'symbol #f start-pos end-pos)]
[string-constant
(syn-val lexeme 'string #f start-pos end-pos)]
[identifier
(syn-val lexeme 'identifier #f start-pos end-pos)]
[(union integer char-constant)
(syn-val lexeme 'constant #f start-pos end-pos)]
[delimiters
(syn-val lexeme 'no-color #f start-pos end-pos)]
[any-char ; anything else is an error (red)
(syn-val lexeme 'error #f start-pos end-pos)]))
| false |
3072dd0e6dd2e3602546c0e9aeac777273039e54 | 86d2db451161507789a93b18c8ee671d99afab8a | /historical/seal-unseal.rkt | 30c783f1f0a229e89e1e2170fbbe8c22293fd3c9 | [
"Apache-2.0"
]
| permissive | spdegabrielle/goblins | 45b0d26a05c5fb2116cc8727ef82bed8835d6385 | b836e11aa820c7ea43100d18ce71cbf53c9e47cd | refs/heads/master | 2022-11-25T18:12:01.975165 | 2020-03-04T20:30:04 | 2020-03-04T20:30:04 | 285,831,618 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 602 | rkt | seal-unseal.rkt | #lang racket/base
(provide new-seal)
;; From http://erights.org/elib/capability/ode/ode-capabilities.html
; Create a new sealer / unsealer pair and sealed? predicate
; sealer-name is optional and just for debugging help
(define (new-seal [sealer-name #f])
(define struct-name
(if sealer-name
(string->symbol (string-append "sealed-by-" (symbol->string sealer-name)))
'sealed))
(define-values (struct:seal seal sealed? seal-ref seal-set!)
(make-struct-type struct-name #f 1 0))
(define unseal
(make-struct-field-accessor seal-ref 0))
(values seal unseal sealed?))
| false |
bbbc394cde0ae66a9bb507cf0e63e9ea60fdcff5 | 1b6b7335f3fabb83294f1ff421421e15fd7d1e73 | /2016/restrict.rkt | 2aaccc7401cab8e8326c1e2e5d3fdb6b66749cf3 | []
| no_license | bor0/misc | 42f1aa55618063b632033d70eaa4efcb9d85431d | 1b92b7af0d598d5231e8efa77ab3755cd4ac0b6a | refs/heads/master | 2023-07-20T01:30:04.558101 | 2023-07-16T20:15:40 | 2023-07-16T20:15:40 | 60,490,071 | 11 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 459 | rkt | restrict.rkt | #lang racket
(define (contains item list)
(cond ((eq? list '()) #f)
((= (car list) item) #t)
(else (contains item (cdr list)))))
; https://en.wikipedia.org/wiki/Restriction_(mathematics)
(define (restrict pairs set)
(filter (lambda (x) (contains (car x) set)) pairs))
(restrict (list (cons 1 2) (cons 3 4) (cons 4 5)) '())
(restrict (list (cons 1 2) (cons 3 4) (cons 4 5)) '(3))
(restrict (list (cons 1 2) (cons 3 4) (cons 4 5)) '(3 4))
| false |
53792b844bef675c4c545cbde0e5a3e773727b49 | a3673e4bb7fa887791beabec6fd193cf278a2f1a | /test/parse.rkt | 141de53309d96d4f3b611e3c4f69c6ec7d78f2a4 | []
| no_license | FDWraith/Racket-Docs | f0be2e0beb92f5d4f8aeeca3386240045a03e336 | 7eabb5355c19a87337f13287fbe3c10e10806ae8 | refs/heads/master | 2021-01-25T10:16:51.207233 | 2018-04-16T22:28:33 | 2018-04-16T22:28:33 | 123,346,280 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 4,149 | rkt | parse.rkt | #lang racket
(require [for-syntax "../lib/racket-docs/struct.rkt"
"../lib/racket-docs/utils.rkt"
syntax/parse
rackunit
racket/list]
"../lib/racket-docs/parse.rkt"
"../lib/racket-docs/types.rkt")
(define-data Foo
[: Any]
[Interpretation: "Anything"]
[Examples:
5
"H" <= "\"H\""
7
'() <= "Empty List"])
(define-data Bar
[: - Int
- String ]
[Interpretation: "An integer or string"]
[Examples:
5
"H" <= "\"H\""])
(define-docs foo
[Signature: Int]
[Purpose: "Something"])
(define foo 1)
(define-docs (foo-cons foo foos)
[Signature: Foo [Listof Foo] -> Foo]
[Purpose: "Prepends @foo onto @foos"]
[Examples:
(foo-cons 1 '()) => '(1)
(foo-cons "Hello" '("World" "!")) => '("Hello" "World" "!")]
[Effects: "No effects"])
(define (foo-cons x y)
(cons x y))
(define-docs append-id
[Syntax: (append-id id:id ...+)]
[Semantics: "Appends the @id@s together."]
[Examples:
(let [(helloworld 5)] (append-id hello world)) => 5
(let [(hello 5)] (append-id hello)) => 5
(let [(abc 10)] (append-id a b c)) => 10])
(define-syntax (append-id stx)
(syntax-parse stx
[(_ id:id ...+)
(datum->syntax stx
(string->symbol
(foldr string-append ""
(map symbol->string
(syntax->datum #'(id ...)))))
stx
stx)]))
(begin-for-syntax
(define expected-docs
(list
(doc-entry
'type
#'Foo
(list
(doc-prop 'type Any)
(doc-prop 'desc "Anything")
(doc-prop
'examples
(list
(plain-data-example #'5)
(interpret-data-example #'"H" "\"H\"")
(plain-data-example #'7)
(interpret-data-example #''() "Empty List")))))
(doc-entry
'type
#'Bar
(list
(doc-prop 'type [Union Int String])
(doc-prop 'desc "An integer or string")
(doc-prop
'examples
(list
(plain-data-example #'5)
(interpret-data-example #'"H" "\"H\"")))))
(doc-entry
'const
#'foo
(list
(doc-prop 'args #false)
(doc-prop 'type Int)
(doc-prop 'desc "Something")))
(doc-entry
'func
#'foo-cons
(list
(doc-prop 'args #'(foo foos))
(doc-prop 'type [-> Foo [Listof Foo] Foo])
(doc-prop 'desc "Prepends @foo onto @foos")
(doc-prop 'examples
(list (eval-example #'(foo-cons 1 '())
#''(1)
#'[(foo-cons 1 '()) => '(1)])
(eval-example #'(foo-cons "Hello" '("World" "!"))
#''("Hello" "World" "!")
#'[(foo-cons "Hello" '("World" "!"))
=>
'("Hello" "World" "!")])))
(doc-prop 'effects "No effects")))
(doc-entry
'macro
#'append-id
(list
(doc-prop 'syntax #'((append-id id:id ...+)))
(doc-prop 'desc "Appends the @id@s together.")
(doc-prop 'examples
(list
(eval-example
#'(let [(helloworld 5)] (append-id hello world))
#'5
#'[(let [(helloworld 5)] (append-id hello world)) => 5])
(eval-example #'(let [(hello 5)] (append-id hello))
#'5
#'[(let [(hello 5)] (append-id hello)) => 5])
(eval-example #'(let [(abc 10)] (append-id a b c))
#'10
#'[(let [(abc 10)] (append-id a b c))
=>
10])))))))
(unless (empty? (get-all-docs))
(displayln "Testing ...")
(check equal-datum?
(get-all-docs)
expected-docs)
(displayln "Tested")))
| true |
5c2e16c602deb1c717c4e7fbc958c326d8ee6fa2 | e4ea5deda6670d4477291be5f6234bb3147ef696 | /PAPR1/bartl/ukol-3/ukol-3.rkt | 10174398e47dcda6822b3b5f20e75493d81b5ace | [
"BSD-3-Clause"
]
| permissive | FrostyX/School | 53e80cf3a4a3a61d8225841658326970c5d31dcb | 1d20ba132be941125a832c5b252d6890932c2419 | refs/heads/master | 2021-11-29T08:31:35.299970 | 2021-11-28T21:39:00 | 2021-11-28T21:39:00 | 6,235,766 | 4 | 10 | null | null | null | null | UTF-8 | Racket | false | false | 104 | rkt | ukol-3.rkt | #!/usr/bin/racket
#lang racket
; 1
(define count
(lambda (seznam)
0))
(count '(3 1 3 2 1 2 3 3 3))
| false |
a151fb6ab81d739518122129bfbe219c0a3b392e | de114750d35ea8adb859a23ab432e554157e4373 | /rackunit-test/tests/rackunit/standalone-test-case-test.rkt | 36540c5ab26d5eb1262af9037a3410b467df42c8 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | racket/rackunit | d1dd569b421a751f5a72c0ba634c89a4746c3bd5 | 8c5f0b42295805d763aea2b09b7ee4eb66912c1b | refs/heads/master | 2023-08-22T14:38:50.816420 | 2023-01-11T02:01:14 | 2023-01-11T02:01:14 | 27,409,555 | 17 | 36 | NOASSERTION | 2023-02-15T20:48:25 | 2014-12-02T01:42:38 | Racket | UTF-8 | Racket | false | false | 680 | rkt | standalone-test-case-test.rkt | ;; Here we check the standalone (not within a test-suite)
;; semantics of checks. These tests are not part of the
;; standard test suite and must be run separately.
#lang racket/base
(require rackunit/private/check
rackunit/private/test-case)
;; Don't run this test automatically:
(module test racket/base
(displayln "run as program for tests"))
;; These tests should succeeds
(test-begin (check-eq? 1 1))
(test-case "succeed" (check-eq? 1 1))
;; These should raise errors
(test-begin (error "First Outta here!"))
(test-case "error" (error "Second Outta here!"))
;; Thesse should raise failures
(test-begin (check-eq? 1 2))
(test-case "failure" (check-eq? 1 2))
| false |
cc63c8b89d93e0c1eeeafc48f729f4c1ef00ac4e | 8d77da9997209a4c3c3ee3b7af5d2a913a6db2a6 | /sql-sourcery/types.rkt | 820741f455862cee3ecd2b6cbb71362e7f3b97f3 | [
"MIT"
]
| permissive | adjkant/sql-sourcery | b7b1bb6c87ecf76929bf626d92696333e2ce9872 | 7636e063fdafa3685ff33f9312980fc3009a326d | refs/heads/master | 2023-03-17T23:34:22.073404 | 2023-03-11T15:07:51 | 2023-03-11T15:07:51 | 123,320,461 | 5 | 2 | MIT | 2023-03-11T15:07:53 | 2018-02-28T17:45:56 | Racket | UTF-8 | Racket | false | false | 1,382 | rkt | types.rkt | #lang racket
(provide TYPES
get-type-info)
;; An SQLData is one of:
;; - String
;; - Number
;; A SQLTypeName is one of:
;; - "STRING"
;; - "INTEGER"
;; - "BOOLEAN"
;; A SupportedStructType is one of:
;; - String
;; - Integer
;; - Boolean
;; A SQLSourceryTypeInfo is a:
;; (list SQLTypeName
;; [Any -> Boolean]
;; [SupportedStructType -> SQLData]
;; [SQLData -> SupportedStructType])
;; Interpretation for list:
;; - SQLTypeName is the name of the data
;; - predicate for the SupportedStructType
;; - translator from SupportedStructType to SQLData
;; - translator from SQLData to SupportedStructType
;; [Listof SQLSourceryTypeInfo]
;; All valid SQLSourcery types
(define TYPES
(list (list "INTEGER"
integer?
identity
identity)
(list "STRING"
string?
(λ (s) (format "'~a'" s))
identity)
(list "BOOLEAN"
boolean?
(λ (b) (if b "'TRUE'" "'FALSE'"))
(λ (b) (if (string=? "TRUE" b) #t #f)))))
;; SQLTypeName -> SQLSourceryTypeInfo
;; Get the type info for a SQLTypeName
(define (get-type-info name)
(let [(type (filter (λ (ti) (string=? (first ti) name)) TYPES))]
(if (= 1 (length type))
(first type)
(error 'sourcery-struct (format "Invalid type: ~a" name)))))
| false |
6eddf8ba51676825b10c8d16fddc5f52e0daa0e4 | 0ac2d343bad7e25df1a2f2be951854d86b3ad173 | /pycket/test/basic.rktl | 659fafd6058f07a6a2bc5949398d91fd63ddffca | [
"MIT"
]
| permissive | pycket/pycket | 8c28888af4967b0f85c54f83f4ccd536fc8ac907 | 05ebd9885efa3a0ae54e77c1a1f07ea441b445c6 | refs/heads/master | 2021-12-01T16:26:09.149864 | 2021-08-08T17:01:12 | 2021-08-08T17:01:12 | 14,119,907 | 158 | 14 | MIT | 2021-08-08T17:01:12 | 2013-11-04T18:39:34 | Python | UTF-8 | Racket | false | false | 105,600 | rktl | basic.rktl |
(load-relative (collection-file-path "loadtest.rktl" "tests/racket"))
(Section 'basic)
(require racket/flonum
racket/function
racket/list
(prefix-in k: '#%kernel))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(test '() 'null null)
(test '() 'null '())
(let ([f (lambda () #&7)])
(test #t eq? (f) (f)))
;; test that all symbol characters are supported.
'(+ - ... !.. $.+ %.- &.! *.: /:. :+. <-. =. >. ?. ~. _. ^.)
(define disjoint-type-functions
(list boolean? char? null? number? pair? procedure? string? bytes? symbol? keyword? vector? void?))
(define type-examples
(list
#t #f #\a '() 9739 '(test) record-error "test" "" #"test" #"" 'test '#:test '#() '#(a b c) (void)))
(define i 1)
(for-each (lambda (x) (display (make-string i #\ ))
(set! i (+ 3 i))
(write x)
(newline))
disjoint-type-functions)
(define type-matrix
(map (lambda (x)
(let ((t (map (lambda (f) (f x)) disjoint-type-functions)))
(write t)
(write x)
(newline)
t))
type-examples))
(define count-in-disjoint-types
(lambda (x)
(apply + (map (lambda (f)
(if (f x) 1 0))
disjoint-type-functions))))
(for-each (lambda (x)
(test 1 count-in-disjoint-types x))
type-examples)
(test #f not #t)
(test #f not 3)
(test #f not (list 3))
(test #t not #f)
(test #f not '())
(test #f not (list))
(test #f not 'nil)
(arity-test not 1 1)
(test #t k:true-object? #t)
(test #f k:true-object? 3)
(test #f k:true-object? (list 3))
(test #f k:true-object? #f)
(test #f k:true-object? '())
(test #f k:true-object? (list))
(test #f k:true-object? 'nil)
(arity-test k:true-object? 1 1)
(test #t boolean? #f)
(test #t boolean? #t)
(test #f boolean? 0)
(test #f boolean? '())
(arity-test boolean? 1 1)
(test #t eqv? 'a 'a)
(test #f eqv? 'a 'b)
(test #t eqv? 2 2)
(test #f eqv? 2 2.0)
(test #t eqv? '() '())
(test #t eqv? '10000 '10000)
(test #t eqv? 10000000000000000000 10000000000000000000)
(test #f eqv? 10000000000000000000 10000000000000000001)
(test #f eqv? 10000000000000000000 20000000000000000000)
(test #f eqv? (cons 1 2) (cons 1 2))
(test #f eqv? (lambda () 1) (lambda () 2))
(test #f eqv? #f 'nil)
(let ((p (lambda (x) x)))
(test #t eqv? p p))
(define gen-counter
(lambda ()
(let ((n 0))
(lambda () (set! n (+ n 1)) n))))
(let ((g (gen-counter))) (test #t eqv? g g))
(test #f eqv? (gen-counter) (gen-counter))
(letrec ((f (lambda () (if (eqv? f g) 'f 'both)))
(g (lambda () (if (eqv? f g) 'g 'both))))
(test #f eqv? f g))
(test #t eq? 'a 'a)
(test #f eq? (list 'a) (list 'a))
(test #t eq? '() '())
(test #t eq? car car)
(let ((x '(a))) (test #t eq? x x))
(let ((x '#())) (test #t eq? x x))
(let ((x (lambda (x) x))) (test #t eq? x x))
(test #t equal? 'a 'a)
(test #t equal? '("a") '("a"))
(test #t equal? '(a) '(a))
(test #t equal? '(a (b) c) '(a (b) c))
(test #t equal? '("a" ("b") "c") '("a" ("b") "c"))
(test #t equal? "abc" "abc")
(test #t equal? 2 2)
(test #t equal? (make-vector 5 'a) (make-vector 5 'a))
(test #t equal? (box "a") (box "a"))
(test #f equal? "" (string #\null))
(test #f equal? 'a "a")
(test #f equal? 'a 'b)
(test #f equal? '(a) '(b))
(test #f equal? '(a (b) d) '(a (b) c))
(test #f equal? '(a (b) c) '(d (b) c))
(test #f equal? '(a (b) c) '(a (d) c))
(test #f equal? "abc" "abcd")
(test #f equal? "abcd" "abc")
(test #f equal? 2 3)
(test #f equal? 2.0 2)
(test #f equal? (make-vector 5 'b) (make-vector 5 'a))
(test #f equal? (box "a") (box "b"))
(test #t equal? #\a #\a)
(test #t equal? (integer->char 1024) (integer->char 1024))
(test #f equal? (integer->char 1024) (integer->char 1025))
(arity-test eq? 2 2)
(arity-test eqv? 2 2)
(arity-test equal? 2 2)
(err/rt-test (set-mcdr! (list 1 2) 4))
(test '(a b c d e) 'dot '(a . (b . (c . (d . (e . ()))))))
(define x (mcons 'a (mcons 'b (mcons 'c null))))
(define y x)
(set-mcdr! x 4)
(test (mcons 'a 4) 'set-mcdr! x)
(set-mcar! x 'z)
(test (mcons 'z 4) 'set-mcar! x)
(test #t eqv? x y)
(test '(a b c . d) 'dot '(a . (b . (c . d))))
(test #f list? y)
(test #f list? (cons 'a 4))
(arity-test list? 1 1)
(test #t pair? '(a . b))
(test #t pair? '(a . 1))
(test #t pair? '(a b c))
(test #f pair? '())
(test #f pair? '#(a b))
(arity-test pair? 1 1)
(test #f k:list-pair? '(a . b))
(test #f k:list-pair? '(a . 1))
(test #t k:list-pair? '(a b c))
(test #f k:list-pair? '())
(test #f k:list-pair? '#(a b))
(arity-test k:list-pair? 1 1)
(test '(a) cons 'a '())
(test '((a) b c d) cons '(a) '(b c d))
(test '("a" b c) cons "a" '(b c))
(test '(a . 3) cons 'a 3)
(test '((a b) . c) cons '(a b) 'c)
(arity-test cons 2 2)
(test 'a car '(a b c))
(test '(a) car '((a) b c d))
(test 1 car '(1 . 2))
(arity-test car 1 1)
(err/rt-test (car 1))
(test '(b c d) cdr '((a) b c d))
(test 2 cdr '(1 . 2))
(arity-test cdr 1 1)
(err/rt-test (cdr 1))
(test '(a 7 c) list 'a (+ 3 4) 'c)
(test '() list)
(test 3 length '(a b c))
(test 3 length '(a (b) (c d e)))
(test 0 length '())
(arity-test length 1 1)
(err/rt-test (length 1))
(err/rt-test (length '(1 . 2)))
(err/rt-test (length "a"))
; (err/rt-test (length (quote #0=(1 . #0#))))
(err/rt-test (let ([p (cons 1 (make-placeholder #f))])
(placeholder-set! (cdr p) p)
(length (make-reader-graph p))))
(define x (cons 4 0))
(err/rt-test (length x))
(arity-test set-mcar! 2 2)
(arity-test set-mcdr! 2 2)
(err/rt-test (set-mcar! 4 4))
(err/rt-test (set-mcdr! 4 4))
(err/rt-test (set-mcar! (cons 1 4) 4))
(err/rt-test (set-mcdr! (cons 1 4) 4))
(define (box-tests box unbox box? set-box! set-box!-name unbox-name 2nd-arg?)
(define b (box 5))
(test 5 unbox b)
(when set-box!
(set-box! b 6)
(test 6 unbox b))
(test #t box? b)
(test #f box? 5)
(arity-test box 1 1)
(arity-test unbox 1 (if 2nd-arg? 2 1))
(arity-test box? 1 1)
(when set-box!
(arity-test set-box! 2 2))
(err/rt-test (unbox 8))
(when set-box!
(err/rt-test (set-box! 8 8))))
(box-tests box unbox box? set-box! 'set-box! 'unbox #f)
(box-tests make-weak-box weak-box-value weak-box? #f #f 'weak-box-value #t)
;; test clearing weak boxes
(unless (eq? 'cgc (system-type 'gc))
(let* ([s (gensym)]
[b (make-weak-box s)])
(test s weak-box-value b)
(test s weak-box-value b 123)
(set! s 'something-else)
(collect-garbage)
(test #f weak-box-value b)
(test 123 weak-box-value b 123)))
(test '(x y) append '(x) '(y))
(test '(a b c d) append '(a) '(b c d))
(test '(a (b) (c)) append '(a (b)) '((c)))
(test '() append)
(test '(a b c . d) append '(a b) '(c . d))
(test 'a append '() 'a)
(test 1 append 1)
(test '(1 . 2) append '(1) 2)
(test '(1 . 2) append '(1) 2)
(err/rt-test (append '(1 2 . 3) 1))
(err/rt-test (append '(1 2 3) 1 '(4 5 6)))
(define l '(1 2))
(define l2 '(3 4 . 7))
(define l3 (append l l2))
(test '(1 2 3 4 . 7) 'append l3)
(test '(c b a) reverse '(a b c))
(test '((e (f)) d (b c) a) reverse '(a (b c) d (e (f))))
(arity-test reverse 1 1)
(err/rt-test (reverse 1))
(err/rt-test (reverse '(1 . 1)))
(test 'c list-ref '(a b c d) 2)
(test 'c list-ref '(a b c . d) 2)
(arity-test list-ref 2 2)
(err/rt-test (list-ref 1 1) exn:application:mismatch?)
(err/rt-test (list-ref '(a b . c) 2) exn:application:mismatch?)
(err/rt-test (list-ref '(1 2 3) 2.0))
(err/rt-test (list-ref '(1) '(1)))
(err/rt-test (list-ref '(1) 1) exn:application:mismatch?)
(err/rt-test (list-ref '() 0) exn:application:mismatch?)
(err/rt-test (list-ref '() 0) exn:application:mismatch?)
(err/rt-test (list-ref '(1) -1))
(err/rt-test (list-ref '(1) 2000000000000) exn:application:mismatch?)
(test '(c d) list-tail '(a b c d) 2)
(test '(a b c d) list-tail '(a b c d) 0)
(test '(b c . d) list-tail '(a b c . d) 1)
(test 1 list-tail 1 0)
(arity-test list-tail 2 2)
(err/rt-test (list-tail 1 1) exn:application:mismatch?)
(err/rt-test (list-tail '(1 2 3) 2.0))
(err/rt-test (list-tail '(1) '(1)))
(err/rt-test (list-tail '(1) -1))
(err/rt-test (list-tail '(1) 2) exn:application:mismatch?)
(err/rt-test (list-tail '(1 2 . 3) 3) exn:application:mismatch?)
(define (test-mem memq memq-name)
(test '(a b c) memq 'a '(a b c))
(test '(b c) memq 'b '(a b c))
(test '(b . c) memq 'b '(a b . c))
(test '#f memq 'a '(b c d))
(if (eq? memq-name 'member)
(arity-test memq 2 3)
(arity-test memq 2 2))
(err/rt-test (memq 'a 1) exn:application:mismatch?)
(err/rt-test (memq 'a '(1 . 2)) exn:application:mismatch?))
(test-mem memq 'memq)
(test-mem memv 'memv)
(test-mem member 'member)
(test '("apple") memq "apple" '("apple")) ; literals are interned
(test '(#"apple") memq #"apple" '(#"apple")) ; literals are interned
(test #f memq (list->string (string->list "apple")) '("apple"))
(test #f memq (list->bytes (bytes->list #"apple")) '(#"apple"))
(test #f memv (list->string (string->list "apple")) '("apple"))
(test '("apple") member "apple" '("apple"))
; (test #f memq 1/2 '(1/2)) ; rationals are immutable and we may want to optimize
(test '(1/2) memv 1/2 '(1/2))
(test '(1/2) member 1/2 '(1/2))
(test '((1 2)) member '(1 2) '(1 2 (1 2)))
;; Additional tests for member with equality check argument
(let ([stxs (list #'a #'b #'c)])
(test stxs member #'a stxs free-identifier=?)
(test (cdr stxs) member #'b stxs free-identifier=?)
(test #f member #'z stxs free-identifier=?))
(test '(2 1 2) member 2 '(1 2 1 2) =)
(test #f member 2 '(3 4 5 6) =)
(test '(#"b" #"c") member #"b" '(#"a" #"b" #"c") bytes=?)
(test #f member #"z" '(#"a" #"b" #"c") bytes=?)
(define (test-ass assq assq-name)
(define e '((a 1) (b 2) (c 3)))
(test '(a 1) assq 'a e)
(test '(b 2) assq 'b e)
(test #f assq 'd e)
(test '(a 1) assq 'a '((x 0) (a 1) b 2))
(test '(a 1) assq 'a '((x 0) (a 1) . 0))
(arity-test assq 2 (if (eq? assq-name 'assoc) 3 2))
(err/rt-test (assq 1 1) exn:application:mismatch?)
(err/rt-test (assq 1 '(1 2)) exn:application:mismatch?)
(err/rt-test (assq 1 '((0) . 2)) exn:application:mismatch?))
(test-ass assq 'assq)
(test-ass assv 'assv)
(test-ass assoc 'assoc)
(test #f assq '(a) '(((a)) ((b)) ((c))))
(test #f assv '(a) '(((a)) ((b)) ((c))))
(test '((b) 1) assoc '(b) '(((a)) ((b) 1) ((c))))
; (test #f assq '1/2 '(((a)) (1/2) ((c)))) ; rationals are immutable and we may want to optimize
(test '(1/2) assv '1/2 '(((a)) (1/2) ((c))))
(test '(1/2) assoc '1/2 '(((a)) (1/2) ((c))))
(test #f immutable? (cons 1 null))
(test #f immutable? (list 1))
(test #f immutable? (list 1 2))
(test #f immutable? (list* 1 null))
(test #f immutable? (list* 1 2 null))
(test #f immutable? 1)
(test #t immutable? #(1 2 3))
(test #f immutable? (vector 1 2 3))
(test #f immutable? (vector))
(test #t immutable? #())
(test #f immutable? (string-copy "hi"))
(test #t immutable? "hi")
(test #t immutable? (string->immutable-string "hi"))
(test #t immutable? (string->immutable-string (string-copy "hi")))
(test #t immutable? (make-immutable-hasheq))
(test #t immutable? (make-immutable-hasheq null))
(test #t immutable? (make-immutable-hasheq '((a . b))))
(test #t immutable? (make-immutable-hash '((a . b))))
(test #f immutable? (make-hasheq))
(test #f immutable? (make-hasheqv))
(test #f immutable? (make-hash))
(test #f immutable? (make-weak-hasheq))
(test #f immutable? (make-weak-hash))
(test #t symbol? 'foo)
(test #t symbol? (car '(a b)))
(test #f symbol? "bar")
(test #t symbol? 'nil)
(test #f symbol? '())
(test #f symbol? #f)
;;; But first, what case are symbols in? Determine the standard case:
#ci(parameterize ([read-case-sensitive #f])
(define char-standard-case char-upcase)
(if (string=? (symbol->string 'A) "a")
(set! char-standard-case char-downcase)
(void))
(test #t 'standard-case
(string=? (symbol->string 'a) (symbol->string 'A)))
(test #t 'standard-case
(or (string=? (symbol->string 'a) "A")
(string=? (symbol->string 'A) "a")))
(let ()
(define (str-copy s)
(let ((v (make-string (string-length s))))
(do ((i (- (string-length v) 1) (- i 1)))
((< i 0) v)
(string-set! v i (string-ref s i)))))
(define (string-standard-case s)
(set! s (str-copy s))
(do ((i 0 (+ 1 i))
(sl (string-length s)))
((>= i sl) s)
(string-set! s i (char-standard-case (string-ref s i)))))
(test (string-standard-case "flying-fish") symbol->string 'flying-fish)
(test (string-standard-case "martin") symbol->string 'Martin)
(test "Malvina" symbol->string (string->symbol "Malvina"))
(test #t 'standard-case (eq? 'a 'A))))
(define x (string #\a #\b))
(define y (string->symbol x))
(string-set! x 0 #\c)
(test "cb" 'string-set! x)
(test "ab" symbol->string y)
(test y string->symbol "ab")
#ci(test #t eq? 'mISSISSIppi 'mississippi)
#ci(test #f 'string->symbol (eq? 'bitBlt (string->symbol "bitBlt")))
#cs(test #t 'string->symbol (eq? 'bitBlt (string->symbol "bitBlt")))
(test 'JollyWog string->symbol (symbol->string 'JollyWog))
#ci(test 'JollyWog string->symbol (symbol->string 'JollyWog))
(test #t symbol<? 'a 'b)
(test #t symbol<? 'a 'b 'c)
(test #f symbol<? 'a 'c 'b)
(test #t symbol<? 'a 'aa)
(test #f symbol<? 'aa 'a)
(arity-test symbol? 1 1)
(test #t keyword? '#:a)
(test #f keyword? 'a)
(test '#:apple string->keyword "apple")
(test "apple" keyword->string '#:apple)
(test #t keyword<? '#:a)
(test #t keyword<? '#:a '#:b)
(test #f keyword<? '#:b '#:b)
(test #t keyword<? '#:b '#:bb)
(test #f keyword<? '#:b '#:)
(test #t keyword<? '#:b '#:c '#:d)
(test #f keyword<? '#:b '#:c '#:c)
(test #t keyword<? (string->keyword "a") (string->keyword "\uA0"))
(test #t keyword<? (string->keyword "a") (string->keyword "\uFF"))
(test #f keyword<? (string->keyword "\uA0") (string->keyword "a"))
(test #f keyword<? (string->keyword "\uFF") (string->keyword "a"))
(test #t keyword<? (string->keyword "\uA0") (string->keyword "\uFF"))
(test #f keyword<? (string->keyword "\uFF") (string->keyword "\uA0"))
(test #f keyword<? (string->keyword "\uA0") (string->keyword "\uA0"))
(arity-test keyword? 1 1)
(arity-test keyword<? 1 -1)
(define (char-tests)
(test #t eqv? '#\ #\Space)
(test #t eqv? #\space '#\Space)
(test #t char? #\a)
(test #t char? #\()
(test #t char? #\ )
(test #t char? '#\newline)
(test #t char? #\u100)
(test #f char? 7)
(test #f char? #t)
(test #f char? 'x)
(arity-test char? 1 1)
(test #t k:interned-char? #\a)
(test #t k:interned-char? #\()
(test #t k:interned-char? #\ )
(test #t k:interned-char? '#\newline)
(test #f k:interned-char? #\u100)
(test #f k:interned-char? 7)
(test #f k:interned-char? #t)
(test #f k:interned-char? #t)
(test #f k:interned-char? 'x)
(arity-test k:interned-char? 1 1)
(test #f char=? #\A #\B)
(test #f char=? #\A #\A #\B)
(test #f char=? #\A #\B #\A)
(test #f char=? #\a #\b)
(test #f char=? #\9 #\0)
(test #t char=? #\A #\A)
(test #t char=? #\A #\A #\A)
(test #t char=? #\370 #\370)
(test #f char=? #\371 #\370)
(test #f char=? #\370 #\371)
(arity-test char=? 1 -1)
(err/rt-test (char=? #\a 1))
(err/rt-test (char=? #\a #\b 1))
(err/rt-test (char=? 1 #\a))
(test #t char<? #\A #\B)
(test #t char<? #\A #\B #\C)
(test #f char<? #\A #\B #\A)
(test #f char<? #\A #\A #\C)
(test #t char<? #\a #\b)
(test #f char<? #\9 #\0)
(test #f char<? #\A #\A)
(test #f char<? #\370 #\370)
(test #f char<? #\371 #\370)
(test #t char<? #\370 #\371)
(arity-test char<? 1 -1)
(err/rt-test (char<? #\a 1))
(err/rt-test (char<? #\a #\a 1))
(err/rt-test (char<? 1 #\a))
(test #f char>? #\A #\B)
(test #t char>? #\B #\A)
(test #f char>? #\A #\B #\C)
(test #f char>? #\B #\A #\C)
(test #t char>? #\C #\B #\A)
(test #f char>? #\a #\b)
(test #t char>? #\9 #\0)
(test #f char>? #\A #\A)
(test #f char>? #\370 #\370)
(test #t char>? #\371 #\370)
(test #f char>? #\370 #\371)
(arity-test char>? 1 -1)
(err/rt-test (char>? #\a 1))
(err/rt-test (char>? #\a #\a 1))
(err/rt-test (char>? 1 #\a))
(test #t char<=? #\A #\B)
(test #t char<=? #\A #\B #\C)
(test #t char<=? #\A #\A #\C)
(test #f char<=? #\A #\B #\A)
(test #f char<=? #\B #\A #\C)
(test #t char<=? #\a #\b)
(test #f char<=? #\9 #\0)
(test #t char<=? #\A #\A)
(test #t char<=? #\370 #\370)
(test #f char<=? #\371 #\370)
(test #t char<=? #\370 #\371)
(arity-test char<=? 1 -1)
(err/rt-test (char<=? #\a 1))
(err/rt-test (char<=? #\b #\a 1))
(err/rt-test (char<=? 1 #\a))
(test #f char>=? #\A #\B)
(test #f char>=? #\a #\b)
(test #t char>=? #\9 #\0)
(test #t char>=? #\A #\A)
(test #t char>=? #\370 #\370)
(test #t char>=? #\371 #\370)
(test #f char>=? #\370 #\371)
(arity-test char>=? 1 -1)
(err/rt-test (char>=? #\a 1))
(err/rt-test (char>=? #\a #\b 1))
(err/rt-test (char>=? 1 #\a))
(test #f char-ci=? #\A #\B)
(test #f char-ci=? #\A #\A #\B)
(test #f char-ci=? #\a #\B)
(test #f char-ci=? #\A #\b)
(test #f char-ci=? #\a #\b)
(test #f char-ci=? #\9 #\0)
(test #t char-ci=? #\A #\A)
(test #t char-ci=? #\A #\a)
(test #t char-ci=? #\A #\a #\A)
(test #t char-ci=? #\370 #\370)
(test #f char-ci=? #\371 #\370)
(test #f char-ci=? #\370 #\371)
(arity-test char-ci=? 1 -1)
(err/rt-test (char-ci=? #\a 1))
(err/rt-test (char-ci=? #\a #\b 1))
(err/rt-test (char-ci=? 1 #\a))
(test #t char-ci<? #\A #\B)
(test #t char-ci<? #\A #\B #\C)
(test #t char-ci<? #\a #\B)
(test #t char-ci<? #\A #\b)
(test #t char-ci<? #\A #\b #\C)
(test #t char-ci<? #\a #\b)
(test #f char-ci<? #\9 #\0)
(test #f char-ci<? #\A #\A)
(test #f char-ci<? #\A #\a)
(test #f char-ci<? #\A #\b #\B)
(test #f char-ci<? #\370 #\370)
(test #f char-ci<? #\371 #\370)
(test #t char-ci<? #\370 #\371)
(arity-test char-ci<? 1 -1)
(err/rt-test (char-ci<? #\a 1))
(err/rt-test (char-ci<? #\b #\a 1))
(err/rt-test (char-ci<? 1 #\a))
(test #f char-ci>? #\A #\B)
(test #f char-ci>? #\B #\A #\C)
(test #t char-ci>? #\C #\B #\A)
(test #f char-ci>? #\a #\B)
(test #f char-ci>? #\A #\b)
(test #f char-ci>? #\a #\b)
(test #t char-ci>? #\C #\b #\A)
(test #t char-ci>? #\9 #\0)
(test #f char-ci>? #\A #\A)
(test #f char-ci>? #\A #\a)
(test #f char-ci>? #\370 #\370)
(test #t char-ci>? #\371 #\370)
(test #f char-ci>? #\370 #\371)
(arity-test char-ci>? 1 -1)
(err/rt-test (char-ci>? #\a 1))
(err/rt-test (char-ci>? #\a #\b 1))
(err/rt-test (char-ci>? 1 #\a))
(test #t char-ci<=? #\A #\B)
(test #t char-ci<=? #\a #\B)
(test #t char-ci<=? #\a #\B #\C)
(test #f char-ci<=? #\a #\b #\A)
(test #t char-ci<=? #\A #\b)
(test #t char-ci<=? #\a #\b)
(test #f char-ci<=? #\9 #\0)
(test #t char-ci<=? #\A #\A)
(test #t char-ci<=? #\A #\a)
(test #t char-ci<=? #\370 #\370)
(test #f char-ci<=? #\371 #\370)
(test #t char-ci<=? #\370 #\371)
(arity-test char-ci<=? 1 -1)
(err/rt-test (char-ci<=? #\a 1))
(err/rt-test (char-ci<=? #\b #\a 1))
(err/rt-test (char-ci<=? 1 #\a))
(test #f char-ci>=? #\A #\B)
(test #f char-ci>=? #\B #\A #\C)
(test #t char-ci>=? #\B #\B #\A)
(test #f char-ci>=? #\a #\B)
(test #f char-ci>=? #\A #\b)
(test #f char-ci>=? #\a #\b)
(test #t char-ci>=? #\9 #\0)
(test #t char-ci>=? #\A #\A)
(test #t char-ci>=? #\A #\a)
(test #t char-ci>=? #\370 #\370)
(test #t char-ci>=? #\371 #\370)
(test #f char-ci>=? #\370 #\371)
(arity-test char-ci>=? 1 -1)
(err/rt-test (char-ci>=? #\a 1))
(err/rt-test (char-ci>=? #\a #\b 1))
(err/rt-test (char-ci>=? 1 #\a)))
(char-tests)
(define (ascii-range start end)
(let ([s (or (and (number? start) start) (char->integer start))]
[e (or (and (number? end) end) (char->integer end))])
(let loop ([n e][l (list (integer->char e))])
(if (= n s)
l
(let ([n (sub1 n)])
(loop n (cons (integer->char n) l)))))))
(define uppers (ascii-range #\A #\Z))
(define lowers (ascii-range #\a #\z))
(define alphas (append uppers lowers))
(define digits (ascii-range #\0 #\9))
(define whites (list #\newline #\return #\space #\page #\tab #\vtab))
(define (test-all is-a? name members)
(let loop ([n 0])
(unless (= n 128)
(let ([c (integer->char n)])
(test (and (memq c members) #t) `(,is-a? (integer->char ,n)) (is-a? c))
(loop (add1 n)))))
(arity-test is-a? 1 1)
(err/rt-test (is-a? 1)))
(test-all char-alphabetic? 'char-alphabetic? alphas)
(test-all char-numeric? 'char-numeric? digits)
(test-all char-whitespace? 'char-whitespace? whites)
(test-all char-upper-case? 'char-upper-case? uppers)
(test-all char-lower-case? 'char-lower-case? lowers)
(let loop ([n 0])
(unless (= n 512)
(test n 'integer->char (char->integer (integer->char n)))
(loop (add1 n))))
(test 0 char->integer #\nul)
(test 10 char->integer #\newline)
(test 13 char->integer #\return)
(test 9 char->integer #\tab)
(test 8 char->integer #\backspace)
(test 12 char->integer #\page)
(test 32 char->integer #\space)
(test 127 char->integer #\rubout)
(test #\null 'null #\nul)
(test #\newline 'linefeed #\linefeed)
(test #\. integer->char (char->integer #\.))
(test #\A integer->char (char->integer #\A))
(test #\a integer->char (char->integer #\a))
(test #\371 integer->char (char->integer #\371))
(test #\U12345 integer->char (char->integer #\U12345))
(arity-test integer->char 1 1)
(arity-test char->integer 1 1)
(err/rt-test (integer->char 5.0))
(err/rt-test (integer->char 'a))
(err/rt-test (integer->char -1))
(err/rt-test (integer->char (expt 2 32)))
(err/rt-test (integer->char 10000000000000000))
(err/rt-test (char->integer 5))
(define (test-up/down case case-name members memassoc)
(let loop ([n 0])
(unless (= n 128)
(let ([c (integer->char n)])
(if (memq c members)
(test (cdr (assq c memassoc)) case c)
(test c case c)))
(loop (add1 n))))
(arity-test case 1 1)
(err/rt-test (case 2)))
(test-up/down char-upcase 'char-upcase lowers (map cons lowers uppers))
(test-up/down char-downcase 'char-downcase uppers (map cons uppers lowers))
(test #t string? "The word \"recursion\\\" has many meanings.")
(test #t string? "")
(arity-test string? 1 1)
(test 3 'make-string (string-length (make-string 3)))
(test "" make-string 0)
(arity-test make-string 1 2)
(err/rt-test (make-string "hello"))
(err/rt-test (make-string 5 "hello"))
(err/rt-test (make-string 5.0 #\b))
(err/rt-test (make-string 5.2 #\a))
(err/rt-test (make-string -5 #\f))
(define 64-bit-machine? (eq? (expt 2 40) (eq-hash-code (expt 2 40))))
(unless 64-bit-machine?
(err/rt-test (make-string 500000000000000 #\f) exn:fail:out-of-memory?)) ;; bignum on 32-bit machines
(err/rt-test (make-string 50000000000000000000 #\f) exn:fail:out-of-memory?) ;; bignum on 64-bit machines
(unless 64-bit-machine?
(err/rt-test (make-vector 1234567890 #\f) exn:fail:out-of-memory?)
(err/rt-test (read (open-input-string "#1234567890(0)")) exn:fail:out-of-memory?))
(test #t vector? (make-vector 0))
(let ([b (vector 1 2 3)])
(vector-copy! b 0 b 1)
(test '#(2 3 3) values b))
(let ([b (vector 2 3 4)])
(vector-copy! b 1 b 0 2)
(test '#(2 2 3) values b))
(define f (make-string 3 #\*))
(test "?**" 'string-set! (begin (string-set! f 0 #\?) f))
(arity-test string-set! 3 3)
(test #t immutable? "hello")
(err/rt-test (string-set! "hello" 0 #\a)) ; immutable string constant
(define hello-string (string-copy "hello"))
(err/rt-test (string-set! hello-string 'a #\a))
(err/rt-test (string-set! 'hello 4 #\a))
(err/rt-test (string-set! hello-string 4 'a))
(err/rt-test (string-set! hello-string 4.0 'a))
(err/rt-test (string-set! hello-string 5 #\a) exn:application:mismatch?)
(err/rt-test (string-set! hello-string -1 #\a))
(err/rt-test (string-set! hello-string (expt 2 100) #\a) exn:application:mismatch?)
(test "abc" string #\a #\b #\c)
(test "" string)
(err/rt-test (string #\a 1))
(err/rt-test (string 1 #\a))
(err/rt-test (string 1))
(test 3 string-length "abc")
(test 0 string-length "")
(arity-test string-length 1 1)
(err/rt-test (string-length 'apple))
(test #\a string-ref "abc" 0)
(test #\c string-ref "abc" 2)
(arity-test string-ref 2 2)
(err/rt-test (string-ref 'apple 4))
(err/rt-test (string-ref "apple" 4.0))
(err/rt-test (string-ref "apple" '(4)))
(err/rt-test (string-ref "apple" 5) exn:application:mismatch?)
(err/rt-test (string-ref "" 0) exn:application:mismatch?)
(err/rt-test (string-ref "" (expt 2 100)) exn:application:mismatch?)
(err/rt-test (string-ref "apple" -1))
(test "" substring "ab" 0 0)
(test "" substring "ab" 1 1)
(test "" substring "ab" 2 2)
(test "a" substring "ab" 0 1)
(test "b" substring "ab" 1 2)
(test "ab" substring "ab" 0 2)
(test "ab" substring "ab" 0)
(test "b" substring "ab" 1)
(test "" substring "ab" 2)
(test (string #\a #\nul #\b) substring (string #\- #\a #\nul #\b #\*) 1 4)
(arity-test substring 2 3)
(err/rt-test (substring 'hello 2 3))
(err/rt-test (substring "hello" "2" 3))
(err/rt-test (substring "hello" 2.0 3))
(err/rt-test (substring "hello" 2 3.0))
(err/rt-test (substring "hello" 2 "3"))
(err/rt-test (substring "hello" 2 7) exn:application:mismatch?)
(err/rt-test (substring "hello" -2 3))
(err/rt-test (substring "hello" 4 3) exn:application:mismatch?)
(err/rt-test (substring "hello" (expt 2 100) 3) exn:application:mismatch?)
(err/rt-test (substring "hello" (expt 2 100) 5) exn:application:mismatch?)
(err/rt-test (substring "hello" 3 (expt 2 100)) exn:application:mismatch?)
(test "foobar" string-append "foo" "bar")
(test "foo" string-append "foo")
(test "foo" string-append "foo" "")
(test "foogoo" string-append "foo" "" "goo")
(test "foo" string-append "" "foo")
(test "" string-append)
(test (string #\a #\nul #\b #\c #\nul #\d)
string-append (string #\a #\nul #\b) (string #\c #\nul #\d))
(err/rt-test (string-append 1))
(err/rt-test (string-append "hello" 1))
(err/rt-test (string-append "hello" 1 "done"))
(test "" make-string 0)
(define s (string-copy "hello"))
(define s2 (string-copy s))
(test "hello" 'string-copy s2)
(string-set! s 2 #\x)
(test "hello" 'string-copy s2)
(test (string #\a #\nul #\b) string-copy (string #\a #\nul #\b))
(string-fill! s #\x)
(test "xxxxx" 'string-fill! s)
(arity-test string-copy 1 1)
(arity-test string-fill! 2 2)
(err/rt-test (string-copy 'blah))
(err/rt-test (string-fill! 'sym #\1))
(err/rt-test (string-fill! "static" #\1))
(err/rt-test (string-fill! (string-copy "oops") 5))
(let ([s (make-string 10 #\x)])
(test (void) string-copy! s 0 "hello")
(test "helloxxxxx" values s)
(test (void) string-copy! s 3 "hello")
(test "helhelloxx" values s)
(err/rt-test (string-copy! s 6 "hello") exn:application:mismatch?)
(test (void) string-copy! s 5 "hello" 3)
(test "helhelooxx" values s)
(test (void) string-copy! s 5 "hello" 3)
(test "helhelooxx" values s)
(test (void) string-copy! s 0 "hello" 3 4)
(test "lelhelooxx" values s)
(test (void) string-copy! s 1 "hello" 3 5)
(test "llohelooxx" values s)
#;(err/rt-test (string-copy! s 1 "hello" 3 6) exn:application:mismatch?))
(arity-test string-copy! 3 5)
(let ([s (string-copy x)])
(err/rt-test (string-copy! "x" 0 "x"))
(err/rt-test (string-copy! s "x" "x"))
(err/rt-test (string-copy! 0 0 "x"))
(err/rt-test (string-copy! s 0 "x" -1))
(err/rt-test (string-copy! s 0 "x" 1 0) exn:application:mismatch?)
(err/rt-test (string-copy! s 2 "x" 0 1) exn:application:mismatch?))
(test "Hello, and how are you?" string->immutable-string "Hello, and how are you?")
(arity-test string->immutable-string 1 1)
(err/rt-test (string->immutable-string 'hello))
(define ax (string #\a #\nul #\370 #\x))
(define abigx (string #\a #\nul #\370 #\X))
(define ax2 (string #\a #\nul #\370 #\x))
(define ay (string #\a #\nul #\371 #\x))
(define (string-tests)
(test #t string=? "")
(test #t string=? "A")
(test #t string=? "" "")
(test #f string<? "" "")
(test #f string>? "" "")
(test #t string<=? "" "")
(test #t string>=? "" "")
(test #t string-ci=? "" "")
(test #f string-ci<? "" "")
(test #f string-ci>? "" "")
(test #t string-ci<=? "" "")
(test #t string-ci>=? "" "")
(test #f string=? "A" "B")
(test #f string=? "a" "b")
(test #f string=? "9" "0")
(test #t string=? "A" "A")
(test #f string=? "A" "AB")
(test #t string=? ax ax2)
(test #f string=? ax abigx)
(test #f string=? ax ay)
(test #f string=? ay ax)
(test #t string<? "A")
(test #t string<? "A" "B")
(test #t string<? "a" "b")
(test #f string<? "9" "0")
(test #f string<? "A" "A")
(test #t string<? "A" "AB")
(test #f string<? "AB" "A")
(test #f string<? ax ax2)
(test #t string<? ax ay)
(test #f string<? ay ax)
(test #t string>? "A")
(test #f string>? "A" "B")
(test #f string>? "a" "b")
(test #t string>? "9" "0")
(test #f string>? "A" "A")
(test #f string>? "A" "AB")
(test #t string>? "AB" "A")
(test #f string>? ax ax2)
(test #f string>? ax ay)
(test #t string>? ay ax)
(test #t string<=? "A")
(test #t string<=? "A" "B")
(test #t string<=? "a" "b")
(test #f string<=? "9" "0")
(test #t string<=? "A" "A")
(test #t string<=? "A" "AB")
(test #f string<=? "AB" "A")
(test #t string<=? ax ax2)
(test #t string<=? ax ay)
(test #f string<=? ay ax)
(test #t string>=? "A")
(test #f string>=? "A" "B")
(test #f string>=? "a" "b")
(test #t string>=? "9" "0")
(test #t string>=? "A" "A")
(test #f string>=? "A" "AB")
(test #t string>=? "AB" "A")
(test #t string>=? ax ax2)
(test #f string>=? ax ay)
(test #t string>=? ay ax)
(test #t string-ci=? "A")
(test #f string-ci=? "A" "B")
(test #f string-ci=? "a" "B")
(test #f string-ci=? "A" "b")
(test #f string-ci=? "a" "b")
(test #f string-ci=? "9" "0")
(test #t string-ci=? "A" "A")
(test #t string-ci=? "A" "a")
(test #f string-ci=? "A" "AB")
(test #t string-ci=? ax ax2)
(test #t string-ci=? ax abigx)
(test #f string-ci=? ax ay)
(test #f string-ci=? ay ax)
(test #f string-ci=? abigx ay)
(test #f string-ci=? ay abigx)
(test #t string-ci<? "A")
(test #t string-ci<? "A" "B")
(test #t string-ci<? "a" "B")
(test #t string-ci<? "A" "b")
(test #t string-ci<? "a" "b")
(test #f string-ci<? "9" "0")
(test #f string-ci<? "A" "A")
(test #f string-ci<? "A" "a")
(test #t string-ci<? "A" "AB")
(test #f string-ci<? "AB" "A")
(test #f string-ci<? ax ax2)
(test #f string-ci<? ax abigx)
(test #t string-ci<? ax ay)
(test #f string-ci<? ay ax)
(test #t string-ci<? abigx ay)
(test #f string-ci<? ay abigx)
(test #t string-ci>? "A")
(test #f string-ci>? "A" "B")
(test #f string-ci>? "a" "B")
(test #f string-ci>? "A" "b")
(test #f string-ci>? "a" "b")
(test #t string-ci>? "9" "0")
(test #f string-ci>? "A" "A")
(test #f string-ci>? "A" "a")
(test #f string-ci>? "A" "AB")
(test #t string-ci>? "AB" "A")
(test #f string-ci>? ax ax2)
(test #f string-ci>? ax abigx)
(test #f string-ci>? ax ay)
(test #t string-ci>? ay ax)
(test #f string-ci>? abigx ay)
(test #t string-ci>? ay abigx)
(test #t string-ci<=? "A")
(test #t string-ci<=? "A" "B")
(test #t string-ci<=? "a" "B")
(test #t string-ci<=? "A" "b")
(test #t string-ci<=? "a" "b")
(test #f string-ci<=? "9" "0")
(test #t string-ci<=? "A" "A")
(test #t string-ci<=? "A" "a")
(test #t string-ci<=? "A" "AB")
(test #f string-ci<=? "AB" "A")
(test #t string-ci<=? ax ax2)
(test #t string-ci<=? ax abigx)
(test #t string-ci<=? ax ay)
(test #f string-ci<=? ay ax)
(test #t string-ci<=? abigx ay)
(test #f string-ci<=? ay abigx)
(test #t string-ci>=? "A")
(test #f string-ci>=? "A" "B")
(test #f string-ci>=? "a" "B")
(test #f string-ci>=? "A" "b")
(test #f string-ci>=? "a" "b")
(test #t string-ci>=? "9" "0")
(test #t string-ci>=? "A" "A")
(test #t string-ci>=? "A" "a")
(test #f string-ci>=? "A" "AB")
(test #t string-ci>=? "AB" "A")
(test #t string-ci>=? ax ax2)
(test #t string-ci>=? ax abigx)
(test #f string-ci>=? ax ay)
(test #t string-ci>=? ay ax)
(test #f string-ci>=? abigx ay)
(test #t string-ci>=? ay abigx))
(string-tests)
(map (lambda (pred)
(arity-test pred 1 -1)
(err/rt-test (pred "a" 1))
(err/rt-test (pred "a" "b" 5))
(err/rt-test (pred 1 "a")))
(list string=?
string>?
string<?
string>=?
string<=?
string-ci=?
string-ci>?
string-ci<?
string-ci>=?
string-ci<=?
string-locale=?
string-locale>?
string-locale<?
string-locale-ci=?
string-locale-ci>?
string-locale-ci<?))
(test #t byte? 10)
(test #t byte? 0)
(test #t byte? 255)
(test #f byte? 256)
(test #f byte? -1)
(test #f byte? (expt 2 40))
(test #f byte? (expt 2 100))
(test #f byte? #\newline)
(test #t bytes? #"The word \"recursion\\\" has many meanings.")
(test #t bytes? #"")
(arity-test bytes? 1 1)
(test 3 'make-bytes (bytes-length (make-bytes 3)))
(test #"" make-bytes 0)
(arity-test make-bytes 1 2)
(err/rt-test (make-bytes #"hello"))
(err/rt-test (make-bytes 5 #"hello"))
(err/rt-test (make-bytes 5.0 98))
(err/rt-test (make-bytes 5.2 97))
(err/rt-test (make-bytes -5 98))
(err/rt-test (make-bytes 50000000000000000000 #\f))
(unless 64-bit-machine?
(err/rt-test (make-bytes 500000000000000 45) exn:fail:out-of-memory?)) ;; bignum on 32-bit machines
(err/rt-test (make-bytes 50000000000000000000 45) exn:fail:out-of-memory?) ;; bignum on 64-bit machines
(define f (make-bytes 3 (char->integer #\*)))
(test #"?**" 'bytes-set! (begin (bytes-set! f 0 (char->integer #\?)) f))
(arity-test bytes-set! 3 3)
(err/rt-test (bytes-set! #"hello" 0 #\a)) ; immutable bytes constant
(define hello-bytes (bytes-copy #"hello"))
(err/rt-test (bytes-set! hello-bytes 'a 97))
(err/rt-test (bytes-set! 'hello 4 97))
(err/rt-test (bytes-set! hello-bytes 4 'a))
(err/rt-test (bytes-set! hello-bytes 4.0 'a))
(err/rt-test (bytes-set! hello-bytes 5 97) exn:application:mismatch?)
(err/rt-test (bytes-set! hello-bytes -1 97))
(err/rt-test (bytes-set! hello-bytes (expt 2 100) 97) exn:application:mismatch?)
(test #"abc" bytes 97 98 99)
(test #"" bytes)
(err/rt-test (bytes #\a 1))
(err/rt-test (bytes 1 #\a))
(err/rt-test (bytes #\1))
(test 3 bytes-length #"abc")
(test 0 bytes-length #"")
(arity-test bytes-length 1 1)
(err/rt-test (bytes-length 'apple))
(test 97 bytes-ref #"abc" 0)
(test 99 bytes-ref #"abc" 2)
(arity-test bytes-ref 2 2)
(err/rt-test (bytes-ref 'apple 4))
(err/rt-test (bytes-ref #"apple" 4.0))
(err/rt-test (bytes-ref #"apple" '(4)))
(err/rt-test (bytes-ref #"apple" 5) exn:application:mismatch?)
(err/rt-test (bytes-ref #"" 0) exn:application:mismatch?)
(err/rt-test (bytes-ref #"" (expt 2 100)) exn:application:mismatch?)
(err/rt-test (bytes-ref #"apple" -1))
(test #"" subbytes #"ab" 0 0)
(test #"" subbytes #"ab" 1 1)
(test #"" subbytes #"ab" 2 2)
(test #"a" subbytes #"ab" 0 1)
(test #"b" subbytes #"ab" 1 2)
(test #"ab" subbytes #"ab" 0 2)
(test #"ab" subbytes #"ab" 0)
(test #"b" subbytes #"ab" 1)
(test #"" subbytes #"ab" 2)
(test (bytes 97 0 98) subbytes (bytes 32 97 0 98 45) 1 4)
(arity-test subbytes 2 3)
(err/rt-test (subbytes 'hello 2 3))
(err/rt-test (subbytes #"hello" #"2" 3))
(err/rt-test (subbytes #"hello" 2.0 3))
(err/rt-test (subbytes #"hello" 2 3.0))
(err/rt-test (subbytes #"hello" 2 #"3"))
(err/rt-test (subbytes #"hello" 2 7) exn:application:mismatch?)
(err/rt-test (subbytes #"hello" -2 3))
(err/rt-test (subbytes #"hello" 4 3) exn:application:mismatch?)
(err/rt-test (subbytes #"hello" (expt 2 100) 3) exn:application:mismatch?)
(err/rt-test (subbytes #"hello" (expt 2 100) 5) exn:application:mismatch?)
(err/rt-test (subbytes #"hello" 3 (expt 2 100)) exn:application:mismatch?)
(test #"foobar" bytes-append #"foo" #"bar")
(test #"foo" bytes-append #"foo")
(test #"foo" bytes-append #"foo" #"")
(test #"foogoo" bytes-append #"foo" #"" #"goo")
(test #"foo" bytes-append #"" #"foo")
(test #"" bytes-append)
(test (bytes 97 0 98 99 0 100)
bytes-append (bytes 97 0 98) (bytes 99 0 100))
(err/rt-test (bytes-append 1))
(err/rt-test (bytes-append #"hello" 1))
(err/rt-test (bytes-append #"hello" 1 #"done"))
(test #"" make-bytes 0)
(define s (bytes-copy #"hello"))
(define s2 (bytes-copy s))
(test #"hello" 'bytes-copy s2)
(bytes-set! s 2 (char->integer #\x))
(test #"hello" 'bytes-copy s2)
(test (bytes 97 0 98) bytes-copy (bytes 97 0 98))
(bytes-fill! s (char->integer #\x))
(test #"xxxxx" 'bytes-fill! s)
(arity-test bytes-copy 1 1)
(arity-test bytes-fill! 2 2)
(err/rt-test (bytes-copy 'blah))
(err/rt-test (bytes-fill! 'sym 1))
(err/rt-test (bytes-fill! #"static" 1))
(err/rt-test (bytes-fill! (bytes-copy #"oops") #\5))
(test #t bytes=? #"a" #"a" #"a")
(test #t bytes=? #"a" #"a")
(test #t bytes=? #"a")
(test #f bytes=? #"a" #"a" #"c")
(test #f bytes=? #"a" #"b" #"c")
(test #f bytes=? #"a" #"b")
(test #f bytes=? #"c" #"a" #"a")
(test #f bytes=? #"c" #"b" #"a")
(test #f bytes=? #"b" #"a")
(err/rt-test (bytes=? 1))
(err/rt-test (bytes=? #"a" 1))
(err/rt-test (bytes=? #"a" #"a" 1))
(err/rt-test (bytes=? #"a" #"b" 1))
(test #f bytes<? #"a" #"a" #"a")
(test #f bytes<? #"a" #"a")
(test #t bytes<? #"a")
(test #f bytes<? #"a" #"a" #"c")
(test #t bytes<? #"a" #"b" #"c")
(test #t bytes<? #"a" #"b")
(test #f bytes<? #"c" #"a" #"a")
(test #f bytes<? #"c" #"b" #"a")
(test #f bytes<? #"b" #"a")
(err/rt-test (bytes<? 1))
(err/rt-test (bytes<? #"a" 1))
(err/rt-test (bytes<? #"a" #"a" 1))
(err/rt-test (bytes<? #"b" #"a" 1))
(test #f bytes>? #"a" #"a" #"a")
(test #f bytes>? #"a" #"a")
(test #t bytes>? #"a")
(test #f bytes>? #"a" #"a" #"c")
(test #f bytes>? #"a" #"b" #"c")
(test #f bytes>? #"a" #"b")
(test #f bytes>? #"c" #"a" #"a")
(test #t bytes>? #"c" #"b" #"a")
(test #t bytes>? #"b" #"a")
(err/rt-test (bytes>? 1))
(err/rt-test (bytes>? #"a" 1))
(err/rt-test (bytes>? #"a" #"a" 1))
(err/rt-test (bytes>? #"a" #"b" 1))
(define r (regexp "(-[0-9]*)+"))
(test '("-12--345" "-345") regexp-match r "a-12--345b")
(test '((1 . 9) (5 . 9)) regexp-match-positions r "a-12--345b")
(test '("--345" "-345") regexp-match r "a-12--345b" 2)
(test '("--34" "-34") regexp-match r "a-12--345b" 2 8)
(test '((4 . 9) (5 . 9)) regexp-match-positions r "a-12--345b" 2)
(test '((4 . 8) (5 . 8)) regexp-match-positions r "a-12--345b" 2 8)
(test '("a-b") regexp-match "a[-c]b" "a-b")
(test '("a-b") regexp-match "a[c-]b" "a-b")
(test #f regexp-match "x+" "12345")
(test "su casa" regexp-replace "mi" "mi casa" "su")
(define r2 (regexp "([Mm])i ([a-zA-Z]*)"))
(define insert "\\1y \\2")
(test "My Casa" regexp-replace r2 "Mi Casa" insert)
(test "my cerveza Mi Mi Mi" regexp-replace r2 "mi cerveza Mi Mi Mi" insert)
(test "my cerveza My Mi Mi" regexp-replace* r2 "mi cerveza Mi Mi Mi" insert)
(test "bbb" regexp-replace* "a" "aaa" "b")
(test '(#"") regexp-match "" (open-input-string "123") 3)
(test '(#"") regexp-match "$" (open-input-string "123") 3)
(test '(#"") regexp-match-peek "" (open-input-string "123") 3)
;; (test "b1b2b3b" regexp-replace* "" "123" "b")
;; (test "1b23" regexp-replace* "(?=2)" "123" "b")
;; (test "xax\u03BBx" regexp-replace* "" "a\u03BB" "x")
;; (test "xax\u03BBxbx" regexp-replace* "" "a\u03BBb" "x")
;; (test #"xax\316x\273xbx" regexp-replace* #"" "a\u03BBb" #"x")
;; (test "==1=2===3==" regexp-replace* "2*" "123" (lambda (s) (string-append "=" s "=")))
;; (test "==1=2===3==4==" regexp-replace* "2*" "1234" (lambda (s) (string-append "=" s "=")))
;; (test "x&b\\ab=cy&w\\aw=z" regexp-replace* #rx"a(.)" "xabcyawz" "\\&\\1\\\\&\\99=")
;; (test "x&cy&z" regexp-replace* #rx"a(.)" "xabcyawz" "\\&")
;; (test "x\\cy\\z" regexp-replace* #rx"a(.)" "xabcyawz" "\\\\")
;; (test "ap0p0le" regexp-replace* #rx"p" "apple" "\\0\\$0")
;; ;; Test sub-matches with procedure replace (second example by synx)
;; (test "myCERVEZA myMI Mi"
;; regexp-replace* "([Mm])i ([a-zA-Z]*)" "mi cerveza Mi Mi Mi"
;; (lambda (all one two)
;; (string-append (string-downcase one) "y"
;; (string-upcase two))))
;; (test #"fox in socks, blue seal. trout in socks, blue fish!"
;; regexp-replace*
;; #rx#"([a-z]+) ([a-z]+)"
;; #"red fox, blue seal. red trout, blue trout!"
;; (lambda (total color what)
;; (cond
;; ((equal? color #"red") (bytes-append what #" in socks"))
;; ((equal? what #"trout") (bytes-append color #" fish"))
;; (else (bytes-append color #" " what)))))
;; (test "foofoo" regexp-replace* #px"(.)?" "a" (lambda args "foo"))
;; (test "xxxxx world" regexp-replace* #px"\\w" "hello world" "x" 0 5)
;; (test "HELLO world" regexp-replace* #px"\\w" "hello world" string-upcase 0 5)
;; (test "hello world" regexp-replace* #px"o" "ohello world" "" 0 3)
;; (test "hell world" regexp-replace* #px"o" "ohello world" "" 0 6)
;; ;; Test weird port offsets:
;; (define (test-weird-offset regexp-match regexp-match-positions)
;; (test #f regexp-match "e" (open-input-string ""))
;; (test #f regexp-match "e" (open-input-string "") (expt 2 100))
;; (test #f regexp-match "e" (open-input-string "") (expt 2 100) (expt 2 101))
;; (test #f regexp-match "e" (open-input-string "") (expt 2 100) (expt 2 101))
;; (test '((3 . 4)) regexp-match-positions "e" (open-input-string "eaae") 2 (expt 2 101))
;; (test #f regexp-match "" (open-input-string "123") 4)
;; (test #f regexp-match-positions "" (open-input-string "123") 4)
;; (test #f regexp-match "" (open-input-string "123") 999)
;; (test #f regexp-match-positions "" (open-input-string "123") 999)
;; (test #f regexp-match "" (open-input-string "123") (expt 2 101)))
;; (test-weird-offset regexp-match regexp-match-positions)
;; (test-weird-offset regexp-match-peek regexp-match-peek-positions)
;; ;; Check greedy and non-greedy operators:
;; (define (do-the-tests prefix suffix start end)
;; (define input (format "~a~a~a" prefix "<tag1 b=5> <tag2 bb=7>" suffix))
;; (define (check-greedy-stuff mk-input regexp-match regexp-match-positions)
;; (define (testre s-answer p-answer pattern)
;; (let ([p-answer (if (and p-answer start)
;; (list (cons (+ start (caar p-answer))
;; (+ start (cdar p-answer))))
;; p-answer)])
;; (cond
;; [end
;; (test s-answer regexp-match pattern (mk-input) start (+ end (string-length input)))
;; (test p-answer regexp-match-positions pattern (mk-input) start (+ end (string-length input)))]
;; [start
;; (test s-answer regexp-match pattern (mk-input) start)
;; (test p-answer regexp-match-positions pattern (mk-input) start)]
;; [else
;; (test s-answer regexp-match pattern (mk-input))
;; (test p-answer regexp-match-positions pattern (mk-input))])))
;; (define strs
;; (if (string? (mk-input))
;; list
;; (lambda l (map string->bytes/utf-8 l))))
;; (testre (strs "<tag1 b=5> <tag2 bb=7>") '((0 . 22)) "<.*>")
;; (testre (strs "<tag1 b=5>") '((0 . 10)) "<.*?>")
;; (testre (strs "<tag1 b=5> <tag2 bb=7>") '((0 . 22)) "<.*?>$")
;; (testre (strs "") '((0 . 0)) "b*")
;; (testre (strs "<tag") '((0 . 4)) "^<[tag]*")
;; (testre (strs "<tag") '((0 . 4)) "<[tag]*")
;; (testre (strs "<tag1") '((0 . 5)) "<[tag]*1")
;; (testre (strs "") '((0 . 0)) "b*?")
;; (testre (strs "<") '((0 . 1)) "<[tag]*?")
;; (testre (strs "<tag1") '((0 . 5)) "<[tag]*?1")
;; (testre (strs "b") '((6 . 7)) "b+?")
;; (testre #f #f "^b+?")
;; (testre (strs "<t") '((0 . 2)) "<[tag]+?")
;; (testre (strs "<tag1") '((0 . 5)) "<[tag]+?1")
;; (testre (strs "") '((0 . 0)) "b??")
;; (testre (strs "") '((0 . 0)) "[tag]??")
;; (testre (strs "g1") '((3 . 5)) "[tag]??1")
;; (testre (strs "ag") '((2 . 4)) "[a-m]+"))
;; (check-greedy-stuff (lambda () input) regexp-match regexp-match-positions)
;; (check-greedy-stuff (lambda () (open-input-string input)) regexp-match regexp-match-positions)
;; (let ([p (open-input-string input)])
;; (check-greedy-stuff (lambda () p) regexp-match-peek regexp-match-peek-positions))
;; (let ([mk (lambda ()
;; (let-values ([(r w) (make-pipe)])
;; (thread (lambda ()
;; (let loop ([s 0])
;; (let ([e (min (+ s 1)
;; (string-length input))])
;; (display (substring input s e) w)
;; (sleep)
;; (unless (= e s)
;; (loop e))))
;; (close-output-port w)))
;; r))])
;; (check-greedy-stuff mk regexp-match regexp-match-positions)
;; (let ([p (mk)])
;; (check-greedy-stuff (lambda () p) regexp-match-peek regexp-match-peek-positions))))
;; (do-the-tests "" "" #f #f)
;; (do-the-tests "" "" 0 #f)
;; (do-the-tests "" "" 0 0)
;; (do-the-tests "ack" "" 3 #f)
;; (do-the-tests "ack" "" 3 0)
;; (do-the-tests "ack" "hmm" 3 -3)
;; (test '((10002 . 10003)) regexp-match-positions "a" (open-input-string (format "~abbac" (make-string 10000 #\x))))
;; ;; Test regexp with null chars:
;; (let* ([s (string #\a #\b #\nul #\c)]
;; [3s (string-append s s s)])
;; (test #f regexp-match (string #\nul) "no nulls")
;; (test (list s) regexp-match s s)
;; (test (list 3s s) regexp-match (format "(~a)*" s) 3s)
;; (test (list (string #\b #\nul #\c)) regexp-match (string #\[ #\nul #\b #\] #\* #\c) s)
;; (test (list (string #\a #\b #\nul)) regexp-match (string #\a #\[ #\b #\nul #\] #\+) s)
;; (test "hihihi" regexp-replace* (string #\nul) (string #\nul #\nul #\nul) "hi"))
;; (test (string #\- #\nul #\+ #\- #\nul #\+ #\- #\nul #\+)
;; regexp-replace* "a" "aaa" (string #\- #\nul #\+))
;; (test "xpple" regexp-replace #rx"a" "apple" "x")
;; (test #"xpple" regexp-replace #rx#"a" "apple" "x")
;; (test #"xpple" regexp-replace #rx"a" #"apple" "x")
;; (test #"xpple" regexp-replace #rx#"a" #"apple" "x")
;; (err/rt-test (regexp-replace #rx"a" "apple" #"x"))
;; (test "pAPple" regexp-replace #rx"a(.)" "apple" (lambda (a b) (string-append b (string-upcase a))))
;; (test #"p.ap.ple" regexp-replace #rx#"a(.)" "apple" (lambda (a b) (bytes-append b #"." a #".")))
;; (test #"p.ap.ple" regexp-replace #rx"a(.)" #"apple" (lambda (a b) (bytes-append b #"." a #".")))
;; (test #"p.ap.ple" regexp-replace #rx#"a(.)" #"apple" (lambda (a b) (bytes-append b #"." a #".")))
;; (err/rt-test (regexp-replace #rx#"a(.)" #"apple" (lambda (a b) "string")))
;; (err/rt-test (regexp-replace #rx#"a(.)" "apple" (lambda (a b) "string")))
;; (err/rt-test (regexp-replace #rx"a(.)" #"apple" (lambda (a b) "string")))
;; (err/rt-test (regexp-replace #rx"a(.)" "apple" (lambda (a b) #"bytes")))
;; Check extremely many subexpressions:
(for-each
(lambda (mx)
(let* ([v (make-vector mx null)]
[open (make-vector mx #t)])
(let loop ([n 0][m 0][s null])
(cond
[(and (= n mx) (zero? m))
(let* ([s (list->string (reverse s))]
[plain (regexp-replace* "[()]" s "")])
(test (cons plain (map list->string (map reverse (vector->list v)))) regexp-match s plain))]
[(or (= n mx) (< (random 10) 3))
(if (and (positive? m)
(< (random 10) 7))
(begin
(let loop ([p 0][m (sub1 m)])
(if (vector-ref open p)
(if (zero? m)
(vector-set! open p #f)
(loop (add1 p) (sub1 m)))
(loop (add1 p) m)))
(loop n (sub1 m) (cons #\) s)))
(let ([c (integer->char (+ (char->integer #\a) (random 26)))])
(let loop ([p 0])
(unless (= p n)
(when (vector-ref open p)
(vector-set! v p (cons c (vector-ref v p))))
(loop (add1 p))))
(loop n m (cons c s))))]
[else
(loop (add1 n) (add1 m) (cons #\( s))]))))
'(1 10 100 500))
(define (test-bad-re-args who)
(err/rt-test (who 'e "hello"))
(err/rt-test (who "e" 'hello))
(err/rt-test (who "e" "hello" -1 5))
(err/rt-test (who "e" "hello" (- (expt 2 100)) 5))
(err/rt-test (who "e" (open-input-string "") (- (expt 2 100)) 5))
(err/rt-test (who "e" "hello" 1 (- (expt 2 100))))
(err/rt-test (who "e" (open-input-string "") 1 (- (expt 2 100))))
(err/rt-test (who "e" "hello" 1 +inf.0))
(err/rt-test (who "e" "" 0 1) exn:application:mismatch?)
(err/rt-test (who "e" "hello" 3 2) exn:application:mismatch?)
(err/rt-test (who "e" "hello" 3 12) exn:application:mismatch?)
(err/rt-test (who "e" "hello" (expt 2 100) 5) exn:application:mismatch?)
(err/rt-test (who "e" (open-input-string "") (expt 2 100) 5) exn:application:mismatch?)
(err/rt-test (who "e" (open-input-string "") (expt 2 100) (sub1 (expt 2 100))) exn:application:mismatch?))
(test-bad-re-args regexp-match)
(test-bad-re-args regexp-match-positions)
;; Test non-capturing parens
(test '("1aaa2" "a") regexp-match #rx"1(a)*2" "01aaa23")
(test '("1aaa2") regexp-match #rx"1(?:a)*2" "01aaa23")
(test '("1akakak2" "ak") regexp-match #rx"1(ak)*2" "01akakak23")
(test '("1akakak2") regexp-match #rx"1(?:ak)*2" "01akakak23")
(test '("1akakkakkkk2" "akkkk") regexp-match #rx"1(ak*)*2" "01akakkakkkk23")
(test '("1akakkakkkk2") regexp-match #rx"1(?:ak*)*2" "01akakkakkkk23")
(test '("01akakkakkkk23" "1akakkakkkk2" "1" "a" "k" "2")
regexp-match #rx"(?:0)(((?:1))(?:(a)(?:(k))*)*((?:2)))(?:3)" "_01akakkakkkk23_")
(test '((1 . 10) (7 . 9)) regexp-match-positions #rx"1(ak*)*2" "01akakkak23")
(test '((1 . 10)) regexp-match-positions #rx"1(?:ak*)*2" "01akakkak23")
;; Regexps that shouldn't work:
(err/rt-test (regexp "[a--b]") exn:fail?)
(err/rt-test (regexp "[a-b-c]") exn:fail?)
;; A good test of unicode-friendly ".":
(test '("load-extension: couldn't open \\\" (%s)\"")
regexp-match
(regexp "^(?:[^\\\"]|\\\\.)*\"") "load-extension: couldn't open \\\" (%s)\"")
;; Test bounded byte consumption on failure:
(let ([is (open-input-string "barfoo")])
(test '(#f #\f) list (regexp-match "^foo" is 0 3) (read-char is)))
(let ([is (open-input-string "barfoo")])
(test '(#f #\f) list (regexp-match "foo" is 0 3) (read-char is)))
;; Check that lazy decoding of strings works right with sending
;; unmatched output to a port:
#;
(for* ([succeed? '(#f #t)]
[char '(#\x #\u3BB)])
(for ([N '(1 100 1000 1023 1024 10000)])
(for ([M (list 0 (quotient N 2))])
(define o (open-output-bytes))
(void (regexp-match-positions #rx"y"
(string-append
(make-string N char)
(if succeed? "y" ""))
M
(+ N (if succeed? 1 0))
o))
(test (- N M) string-length (get-output-string o)))))
(arity-test regexp 1 2)
(arity-test regexp? 1 1)
(arity-test regexp-match 2 6)
(arity-test regexp-match-positions 2 6)
(arity-test regexp-match-peek 2 6)
(arity-test regexp-match-peek-positions 2 6)
(arity-test regexp-replace 3 4)
(arity-test regexp-replace* 3 6)
(test #t procedure? car)
(test #f procedure? 'car)
(test #t procedure? (lambda (x) (* x x)))
(test #f procedure? '(lambda (x) (* x x)))
(test #t call-with-current-continuation procedure?)
(test #t call-with-escape-continuation procedure?)
(test #t procedure? (case-lambda ((x) x) ((x y) (+ x y))))
(arity-test procedure? 1 1)
(test 7 apply + (list 3 4))
(test 7 apply (lambda (a b) (+ a b)) (list 3 4))
(test 17 apply + 10 (list 3 4))
(test '() apply list '())
(define compose (lambda (f g) (lambda args (f (apply g args)))))
(test 30 (compose sqrt *) 12 75)
(err/rt-test (apply) exn:application:arity?)
(err/rt-test (apply (lambda x x)) exn:application:arity?)
(err/rt-test (apply (lambda x x) 1))
(err/rt-test (apply (lambda x x) 1 2))
(err/rt-test (apply (lambda x x) 1 '(2 . 3)))
(test '(b e h) map cadr '((a b) (d e) (g h)))
(test '(5 7 9) map + '(1 2 3) '(4 5 6))
(test '#(0 1 4 9 16) 'for-each
(let ((v (make-vector 5)))
(for-each (lambda (i) (vector-set! v i (* i i)))
'(0 1 2 3 4))
v))
(test '(1 2 3) map (lambda (s #:c [c string->number]) (c s)) '("1" "2" "3"))
(define (map-tests map)
(define ((name-and pred) exn)
(and (pred exn)
(regexp-match? (format "^~a:" name) (exn-message exn))))
(let ([size? (name-and exn:application:mismatch?)]
[non-list? (name-and type?)]
[keywords? (lambda (exn)
(and (exn:fail:contract? exn)
(regexp-match #rx"expects keyword arguments" (exn-message exn))))])
(err/rt-test (map (lambda (x y) (+ x y)) '(1 2) '1))
(err/rt-test (map (lambda (x y) (+ x y)) '2 '(1 2)))
(err/rt-test (map (lambda (x y) (+ x y)) '(1 2) '(1 2 3)) size?)
(err/rt-test (map (lambda (x y) (+ x y)) '(1 2 3) '(1 2)) size?)
(err/rt-test (map (lambda (x) (+ x)) '(1 2 . 3)) non-list?)
(err/rt-test (map (lambda (x y) (+ x y)) '(1 2 . 3) '(1 2)) non-list?)
(err/rt-test (map (lambda (x y) (+ x y)) '(1 2 . 3) '(1 2 3)) non-list?)
(err/rt-test (map (lambda (x y) (+ x y)) '(1 2) '(1 2 . 3)) non-list?)
(err/rt-test (map (lambda (x y) (+ x y)) '(1 2 3) '(1 2 . 3)) non-list?)
;(err/rt-test (map) exn:application:arity?)
;(err/rt-test (map (lambda (x y) (+ x y))) exn:application:arity?)
(err/rt-test (map (lambda () 10) null) exn:application:mismatch?)
(err/rt-test (map (case-lambda [() 9] [(x y) 10]) '(1 2 3)) exn:application:mismatch?)
(err/rt-test (map (lambda (x) 10) '(1 2) '(3 4)) exn:application:mismatch?)
(err/rt-test (map (lambda (x #:y y) 10) '(1 2)) keywords?)
(err/rt-test (map (lambda (x #:y y) 10) '()) keywords?)))
(map-tests map)
(map-tests for-each)
(map-tests andmap)
(map-tests ormap)
;(test-values (list (void)) (lambda () (for-each (lambda (x) (values 1 2)) '(1 2))))
;(err/rt-test (map (lambda (x) (values 1 2)) '(1 2)) arity?)
;; Make sure `values' isn't JIT-inlined in a single-value position:
;; (err/rt-test ((if (zero? (random 1)) (lambda () (+ (values) 3)) #f)) arity?)
;; (err/rt-test ((if (zero? (random 1)) (lambda () (+ (values 1 2) 3)) #f)) arity?)
;; (err/rt-test ((if (zero? (random 1)) (lambda () (+ (values 1 2 4) 3)) #f)) arity?)
(test #t andmap add1 null)
(test #t andmap < null null)
(test #f ormap add1 null)
(test #f ormap < null null)
(test #f andmap positive? '(1 -2 3))
(test #t ormap positive? '(1 -2 3))
(test #f andmap < '(1 -2 3) '(2 2 3))
(test #t ormap < '(1 -2 3) '(0 2 4))
(test #f andmap negative? '(1 -2 3))
(test #t ormap negative? '(1 -2 3))
(test #t andmap < '(1 -2 3) '(2 2 4))
(test #f ormap < '(1 -2 3) '(0 -2 3))
(test 4 andmap add1 '(1 2 3))
(test 2 ormap add1 '(1 2 3))
(test #t andmap < '(1 -2 3) '(2 2 4) '(5 6 7))
(test #t ormap < '(1 -2 3) '(0 -2 4) '(0 0 8))
;; (err/rt-test (ormap (lambda (x) (values 1 2)) '(1 2)) arity?)
;; (err/rt-test (andmap (lambda (x) (values 1 2)) '(1 2)) arity?)
(test-values '(1 2) (lambda () (ormap (lambda (x) (values 1 2)) '(1))))
(test-values '(1 2) (lambda () (andmap (lambda (x) (values 1 2)) '(1))))
(test -3 call-with-current-continuation
(lambda (exit)
(for-each (lambda (x) (if (negative? x) (exit x) (void)))
'(54 0 37 -3 245 19))
#t))
(define list-length
(lambda (obj)
(call-with-current-continuation
(lambda (return)
(letrec ((r (lambda (obj) (cond ((null? obj) 0)
((pair? obj) (+ (r (cdr obj)) 1))
(else (return #f))))))
(r obj))))))
(test 4 list-length '(1 2 3 4))
(test #f list-length '(a b . c))
(test '() map cadr '())
(arity-test map 2 -1)
(arity-test for-each 2 -1)
(arity-test andmap 2 -1)
(arity-test ormap 2 -1)
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; exceptions
(test 10 'exns
(with-handlers ([integer? (lambda (x) 10)])
(raise 12)))
(test '(apple) 'exns
(with-handlers ([void (lambda (x) (list x))])
(with-handlers ([integer? (lambda (x) 10)])
(raise 'apple))))
(test '((20)) 'exns
(with-handlers ([void (lambda (x) (list x))])
(with-handlers ([integer? (lambda (x) (raise (list x)))])
(raise 20))))
#;(test '((30)) 'exns
(let/ec esc
(parameterize ([uncaught-exception-handler (lambda (x) (esc (list x)))])
(with-handlers ([integer? (lambda (x) (raise (list x)))])
(raise 30)))))
#;(test '#((40)) 'exns
(let/ec esc
(with-handlers ([void (lambda (x) (vector x))])
(parameterize ([uncaught-exception-handler (lambda (x) (esc (list x)))])
(with-handlers ([integer? (lambda (x) (raise (list x)))])
(raise 40))))))
(test '(except) 'escape
(let/ec k
(call-with-exception-handler
(lambda (exn)
(k (list exn)))
(lambda () (raise 'except)))))
(test '#&except 'escape
(let/ec k
(call-with-exception-handler
(lambda (exn)
(k (list exn)))
(lambda ()
(call-with-exception-handler
(lambda (exn)
(k (box exn)))
(lambda ()
(raise 'except)))))))
(test '#(except) 'escape
(with-handlers ([void (lambda (x) x)])
(values
(call-with-exception-handler
(lambda (exn)
(vector exn))
(lambda ()
(raise 'except))))))
(test '#((except)) 'escape
(with-handlers ([void (lambda (x) x)])
(values
(call-with-exception-handler
(lambda (exn)
(vector exn))
(lambda ()
;; (Used to replace enclosing, but not any more)
(call-with-exception-handler
(lambda (exn)
(list exn))
(lambda ()
(raise 'except))))))))
(test '#((except)) 'escape
(with-handlers ([void (lambda (x) x)])
(values
(call-with-exception-handler
(lambda (exn)
(vector exn))
(lambda ()
(values
(call-with-exception-handler
(lambda (exn)
(list exn))
(lambda ()
(raise 'except)))))))))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; This tests full conformance of call-with-current-continuation. It
;;; is a separate test because some schemes do not support call/cc
;;; other than escape procedures. I am indebted to
;;; [email protected] (Raja Sooriamurthi) for fixing this
;;; code. The function leaf-eq? compares the leaves of 2 arbitrary
;;; trees constructed of conses.
(define (next-leaf-generator obj eot)
(letrec ((return #f)
(cont (lambda (x)
(recurx obj)
(set! cont (lambda (x) (return eot)))
(cont #f)))
(recurx (lambda (obj)
(if (pair? obj)
(for-each recurx obj)
(call-with-current-continuation
(lambda (c)
(set! cont c)
(return obj)))))))
(lambda () (call-with-current-continuation
(lambda (ret) (set! return ret) (cont #f))))))
(define (leaf-eq? x y)
(let* ((eot (list 'eot))
(xf (next-leaf-generator x eot))
(yf (next-leaf-generator y eot)))
(letrec ((loop (lambda (x y)
(cond ((not (eq? x y)) #f)
((eq? eot x) #t)
(else (loop (xf) (yf)))))))
(loop (xf) (yf)))))
(define (test-cont)
(newline)
(display ";testing continuations; ")
(test #t leaf-eq? '(a (b (c))) '((a) b c))
(test #f leaf-eq? '(a (b (c))) '((a) b c d))
'(report-errs))
(define (test-cc-values test-call/cc)
(test '(a b c)
call-with-values
(lambda ()
(test-call/cc
(lambda (k)
(dynamic-wind
void
(lambda ()
(k 'a 'b 'c))
(lambda ()
(values 1 2))))))
list)
(test 1 dynamic-wind
(lambda () (test-call/cc void))
(lambda () 1)
(lambda () (test-call/cc void)))
; Try devious jumping with pre- and post-thunks:
(test 2 test-call/cc
(lambda (exit)
(dynamic-wind
(lambda () (exit 2))
void
void)))
(test 3 test-call/cc
(lambda (exit)
(dynamic-wind
void
void
(lambda () (exit 3)))))
(let ([rv
(lambda (get-v)
(let ([x 0])
(test-call/cc
(lambda (exit)
(dynamic-wind
void
(lambda () (exit))
(lambda () (set! x (get-v))))))
x))]
[r56
(lambda ()
(let ([x 0]
[y 1]
[c1 #f])
(dynamic-wind
(lambda () (set! x (add1 x)))
(lambda ()
(let/cc k (set! c1 k))
(if (>= x 5)
(set! c1 #f)
(void)))
(lambda () (set! y (add1 y))))
(when c1 (c1))
(list x y)))]
[rx.y
(lambda (get-x get-y)
(let ([c1 #f]
[x 0]
[y 0])
(let ([v
(dynamic-wind
(lambda () (set! y x))
(lambda () (let/cc k (set! c1 k)))
(lambda ()
(set! x (get-x))
(when c1
((begin0
c1
(set! c1 #f))
(get-y)))))])
(cons y v))))]
[rv2
(lambda (get-v)
(let ([c1 #f]
[give-up #f])
(test-call/cc
(lambda (exit)
(dynamic-wind
(lambda () (when give-up (give-up (get-v))))
(lambda () (let/cc k (set! c1 k)))
(lambda () (set! give-up exit) (c1)))))))]
[r10-11-12
(lambda ()
(let ([c2 #f]
[x 10]
[y 11])
(let ([v (dynamic-wind
(lambda () (set! y (add1 y)))
(lambda () (begin0 x (set! x (add1 x))))
(lambda () (let/cc k (set! c2 k))))])
(when c2 ((begin0
c2
(set! c2 #f))))
(list v x y))))]
[r13.14
(lambda ()
(let ([c0 #f]
[x 11]
[y 12])
(dynamic-wind
(lambda () (let/cc k (set! c0 k)))
(lambda () (set! x (add1 x)))
(lambda ()
(set! y (add1 y))
(when c0 ((begin0
c0
(set! c0 #f))))))
(cons x y)))]
[ra-b-a-b
(lambda (get-a get-b)
(let ([l null])
(let ((k-in (test-call/cc (lambda (k1)
(dynamic-wind
(lambda () (set! l (append l (list (get-a)))))
(lambda ()
(call/cc (lambda (k2) (k1 k2))))
(lambda () (set! l (append l (list (get-b))))))))))
(k-in (lambda (v) l)))))])
(test 4 rv (lambda () 4))
(test '(5 6) r56)
(test '(7 . 8) rx.y (lambda () 7) (lambda () 8))
(test 9 rv2 (lambda () 9))
(test '(10 11 12) r10-11-12)
(test '(13 . 14) r13.14)
; !!! fixed in 50:
(test '(enter exit enter exit)
ra-b-a-b (lambda () 'enter) (lambda () 'exit))
(test '((13 . 14) (10 11 12) (13 . 14) (10 11 12))
ra-b-a-b r13.14 r10-11-12)
(test '((10 11 12) (13 . 14) (10 11 12) (13 . 14))
ra-b-a-b r10-11-12 r13.14)
(test 10 call/cc (lambda (k) (k 10)))
(test '((enter exit enter exit)
(exit enter exit enter)
(enter exit enter exit)
(exit enter exit enter))
ra-b-a-b
(lambda () (ra-b-a-b (lambda () 'enter) (lambda () 'exit)))
(lambda () (ra-b-a-b (lambda () 'exit) (lambda () 'enter))))
(test '(enter exit enter exit)
rv (lambda () (ra-b-a-b (lambda () 'enter) (lambda () 'exit))))
(test '(enter exit enter exit)
rv2 (lambda () (ra-b-a-b (lambda () 'enter) (lambda () 'exit))))
(test '(10 11 12) rv r10-11-12)
(test '(10 11 12) rv2 r10-11-12)
(test '(13 . 14) rv r13.14)
(test '(13 . 14) rv2 r13.14)
(test 12 'dw/ec (test-call/cc
(lambda (k0)
(test-call/cc
(lambda (k1)
(test-call/cc
(lambda (k2)
(dynamic-wind
void
(lambda () (k1 6))
(lambda () (k2 12))))))))))
;; !!! fixed in 53 (for call/ec)
(test 13 'dw/ec (test-call/cc
(lambda (k0)
(test-call/cc
(lambda (k1)
(test-call/cc
(lambda (k2)
(dynamic-wind
void
(lambda () (k1 6))
(lambda () (k2 12)))))
(k0 13))))))
;; Interaction with exceptions:
(test 42 test-call/cc (lambda (k)
(call-with-exception-handler k (lambda () (add1 (raise 42))))))
(let ([x 0])
;; Make sure inner `k2' doesn't escape using outer `k':
(let/cc k (+ 1 (dynamic-wind
(lambda () (set! x (add1 x)))
(lambda () (let/cc k (k 2)))
void)))
(test 1 values x))
(printf "got to here 2 ~s\n" test-call/cc)
))
(printf "got to here 0")
(test-cc-values call/cc)
(test-cc-values call/ec)
(printf "got to here 1")
#;
(test 'ok
'ec-cc-exn-combo
(with-handlers ([void (lambda (x) 'ok)])
(define f
(let ([k #f])
(lambda (n)
(case n
[(0) (let/ec r (r (set! k (let/cc k k))))]
[(1) (k)]))))
(f 0)
(f 1)))
(test '(1 2 3 4 1 2 3 4) 'dyn-wind-pre/post-order
(let ([x null]
[go-back #f])
(dynamic-wind
(lambda () (set! x (cons 4 x)))
(lambda () (dynamic-wind
(lambda () (set! x (cons 3 x)))
(lambda () (set! go-back (let/cc k k)))
(lambda () (set! x (cons 2 x)))))
(lambda () (set! x (cons 1 x))))
(if (procedure? go-back)
(go-back 1)
x)))
(test '(5 . 5) 'suspended-cont-escape
(let ([retry #f])
(let ([v (let/ec exit
(dynamic-wind
void
(lambda () (exit 5))
(lambda ()
(let/ec inner-escape
(set! retry (let/cc k k))
(inner-escape 12)
10))))])
(if (procedure? retry)
(retry 10)
(cons v v)))))
(test '(here) 'escape-interrupt-full-jump-up
(let ([b #f]
[v null])
(define (f g)
(dynamic-wind
void
g
(lambda ()
(set! v (cons 'here v))
(b 10))))
(let/ec big
(set! b big)
(let/cc ok
(f (lambda ()
(ok #f)))))
v))
;; Check interaction of map and call/cc
(let ()
(define (try n m)
(let ([retries (make-vector n)]
[copy #f]
[special -1]
[in (let loop ([i n])
(if (= i 0)
null
(cons (- n i) (loop (sub1 i)))))])
(let ([v (apply
map
(lambda (a . rest)
(+ (let/cc k (vector-set! retries a k) 1)
a))
(let loop ([m m])
(if (zero? m)
null
(cons in (loop (sub1 m))))))])
(test (map (lambda (i)
(if (= i special)
(+ i 2)
(add1 i)))
in)
`(map/cc ,n ,m)
v))
(if copy
(when (pair? copy)
(set! special (add1 special))
((begin0 (car copy) (set! copy (cdr copy)))
2))
(begin
(set! copy (vector->list retries))
((vector-ref retries (random n)) 1)))))
(try 3 1)
(try 10 1)
(try 3 2)
(try 10 2)
(try 5 3)
(try 3 5)
(try 10 5))
;; Make sure let doesn't allocate a mutatble cell too early:
(test 2 'let+call/cc
(let ([count 0])
(let ([first-time? #t]
[k (call/cc values)])
(if first-time?
(begin
(set! first-time? #f)
(set! count (+ count 1))
(k values))
(void)))
count))
;; Letrec must allocate early, though:
(test #f 'letrec+call/cc
(letrec ((x (call-with-current-continuation list)))
(if (pair? x)
((car x) (lambda () x))
(pair? (x)))))
;; Check shared escape continuation of nested call/cc:
#;(let ([ch (make-channel)])
(thread
(lambda ()
(channel-put
ch
(call/cc
(lambda (escape)
(call/cc
(lambda (escape1)
(escape1 3))))))))
(sync ch))
(arity-test call/cc 1 2)
(arity-test call/ec 1 1)
(err/rt-test (call/cc 4))
(err/rt-test (call/cc (lambda () 0)))
(err/rt-test (call/ec 4))
(err/rt-test (call/ec (lambda () 0)))
(test #t primitive? car)
(test #f primitive? leaf-eq?)
(arity-test primitive? 1 1)
(test 1 procedure-arity procedure-arity)
(test 2 procedure-arity cons)
(test (make-arity-at-least 1) procedure-arity >)
(test (list 0 1) procedure-arity current-output-port)
(test (list 1 3 (make-arity-at-least 5))
procedure-arity (case-lambda [(x) 0] [(x y z) 1] [(x y z w u . rest) 2]))
(test (make-arity-at-least 0) procedure-arity (lambda x 1))
(test (make-arity-at-least 0) procedure-arity (case-lambda [() 10] [x 1]))
(test (make-arity-at-least 0) procedure-arity (lambda x x))
(arity-test procedure-arity 1 1)
;; Tests for normalize-arity without arity-at-least
(test '() normalize-arity '())
(test 1 normalize-arity 1)
(test 1 normalize-arity '(1))
(test '(1 2) normalize-arity '(1 2))
(test '(1 2) normalize-arity '(2 1))
(test (list 1 2) normalize-arity (list 1 1 2 2))
(test 1 normalize-arity (list 1 1 1))
;; Tests for normalize-arity where everything collapses into arity-at-least
(test (make-arity-at-least 2) normalize-arity (list (make-arity-at-least 2) 3))
(test (make-arity-at-least 1)
normalize-arity (list (make-arity-at-least 2) 1))
(test (make-arity-at-least 1)
normalize-arity (list (make-arity-at-least 2) 1 3))
(test (make-arity-at-least 0)
normalize-arity (list (make-arity-at-least 2) 1 0 3))
(test (make-arity-at-least 0)
normalize-arity (list (make-arity-at-least 2)
(make-arity-at-least 4) 1 0 3))
(test (make-arity-at-least 0)
normalize-arity (list (make-arity-at-least 4)
(make-arity-at-least 2) 1 0 3))
(test (make-arity-at-least 1)
normalize-arity (list (make-arity-at-least 2) 1 1))
(test (make-arity-at-least 1)
normalize-arity
(list (make-arity-at-least 2)
(make-arity-at-least 2) 1 1))
;; Tests for normalize-arity that result in a list with arity-at-least.
(test (list 1 (make-arity-at-least 3))
normalize-arity (list (make-arity-at-least 3) 1))
(test (list 1 (make-arity-at-least 3))
normalize-arity (list (make-arity-at-least 3) 1 4))
(test (list 0 1 (make-arity-at-least 3))
normalize-arity (list (make-arity-at-least 3) 1 0 4))
(test (list 0 1 (make-arity-at-least 3))
normalize-arity (list (make-arity-at-least 3)
(make-arity-at-least 5) 1 0 4))
(test (list 0 1 (make-arity-at-least 3))
normalize-arity (list (make-arity-at-least 5)
(make-arity-at-least 3) 1 0 4))
(test (list 1 (make-arity-at-least 3))
normalize-arity (list (make-arity-at-least 3) 1 1))
(test (list 1 (make-arity-at-least 3))
normalize-arity
(list (make-arity-at-least 3)
(make-arity-at-least 3) 1 1))
(test (list 0 1 (make-arity-at-least 3))
normalize-arity (list 0 1 3 (make-arity-at-least 4)))
(test (list 0 1 (make-arity-at-least 3))
normalize-arity (list (make-arity-at-least 4) 3 1 0))
(test (list 0 1 (make-arity-at-least 3))
normalize-arity (list 0 1 3 (make-arity-at-least 4)
5 (make-arity-at-least 6)))
(let ()
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; randomized testing
;; predicate: normalize-arity produces a normalized arity
;;
(define (normalized-arity=? original normalized)
(and
(normalized-arity? normalized)
(arity=? original normalized)))
(for ((i (in-range 1 2000)))
(define rand-bound (ceiling (/ i 10)))
(define l
(build-list (random rand-bound)
(λ (i) (if (zero? (random 5))
(make-arity-at-least (random rand-bound))
(random rand-bound)))))
(define res (normalize-arity l))
#:final (not (normalized-arity=? l res))
(test #t normalized-arity=? l res)))
(test #t procedure-arity-includes? cons 2)
(test #f procedure-arity-includes? cons 0)
(test #f procedure-arity-includes? cons 3)
(test #t procedure-arity-includes? list 3)
(test #t procedure-arity-includes? list 3000)
(test #t procedure-arity-includes? (lambda () 0) 0)
(test #f procedure-arity-includes? (lambda () 0) 1)
(test #f procedure-arity-includes? cons 10000000000000000000000000000)
(test #t procedure-arity-includes? list 10000000000000000000000000000)
(test #t procedure-arity-includes? (lambda x x) 10000000000000000000000000000)
(err/rt-test (procedure-arity-includes? cons -1))
(err/rt-test (procedure-arity-includes? cons 1.0))
(err/rt-test (procedure-arity-includes? 'cons 1))
(arity-test procedure-arity-includes? 2 3)
(newline)
(display ";testing scheme 4 functions; ")
(test '(#\P #\space #\l) string->list "P l")
(test '() string->list "")
(test "1\\\"" list->string '(#\1 #\\ #\"))
(test "" list->string '())
(arity-test list->string 1 1)
(arity-test string->list 1 1)
(err/rt-test (string->list 'hello))
(err/rt-test (list->string 'hello))
(err/rt-test (list->string '(#\h . #\e)))
(err/rt-test (list->string '(#\h 1 #\e)))
(test '(dah dah didah) vector->list '#(dah dah didah))
(test '() vector->list '#())
(test '#(dididit dah) list->vector '(dididit dah))
(test '#() list->vector '())
(arity-test list->vector 1 1)
(arity-test vector->list 1 1)
(err/rt-test (vector->list 'hello))
(err/rt-test (list->vector 'hello))
(err/rt-test (list->vector '(#\h . #\e)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; errors
(err/rt-test (raise-arity-error 'f 5) exn:fail:contract:arity?)
(err/rt-test (raise-arity-error 'f (make-arity-at-least 5)) exn:fail:contract:arity?)
(err/rt-test (raise-arity-error 'f (list 1 (make-arity-at-least 5))) exn:fail:contract:arity?)
(err/rt-test (raise-arity-error + 5) exn:fail:contract:arity?)
(err/rt-test (raise-arity-error + (make-arity-at-least 5)) exn:fail:contract:arity?)
(err/rt-test (raise-arity-error + (list 1 (make-arity-at-least 5))) exn:fail:contract:arity?)
(err/rt-test (raise-result-arity-error 'f 5 #f) exn:fail:contract:arity?)
(err/rt-test (raise-result-arity-error #f 5 #f) exn:fail:contract:arity?)
(err/rt-test (raise-result-arity-error #f (expt 2 100) #f) exn:fail:contract:arity?)
(err/rt-test (raise-result-arity-error #f (expt 2 100) "\n in: extra") exn:fail:contract:arity?)
(err/rt-test (raise-result-arity-error #f (expt 2 100) "\n in: extra" 1 2 3 4 5) exn:fail:contract:arity?)
(err/rt-test (raise-result-arity-error 'oops 5 "%") exn:fail:contract:arity?)
(define (exn:fail:contract:arity?/#f e) (not (exn:fail:contract:arity? e)))
(err/rt-test (raise-arity-error 'f -5) exn:fail:contract:arity?/#f)
(err/rt-test (raise-arity-error 'f -5) exn:fail:contract?)
(err/rt-test (raise-arity-error 'f (list 1 'x)) exn:fail:contract:arity?/#f)
(err/rt-test (raise-arity-error 'f (list 1 'x)) exn:fail:contract?)
(err/rt-test (raise-arity-error 1 1) exn:fail:contract:arity?/#f)
(err/rt-test (raise-arity-error 1 1) exn:fail:contract?)
(err/rt-test (raise-result-arity-error "f" 7 #f) exn:fail:contract:arity?/#f)
(err/rt-test (raise-result-arity-error 'f -7 #f) exn:fail:contract:arity?/#f)
(err/rt-test (raise-result-arity-error 'f 7 #"oops") exn:fail:contract:arity?/#f)
(err/rt-test (raise-arity-mask-error 'f 4) exn:fail:contract:arity?)
(err/rt-test (raise-arity-mask-error 'f -8) exn:fail:contract:arity?)
(err/rt-test (raise-arity-mask-error 'f 5) exn:fail:contract:arity?)
(err/rt-test (raise-arity-mask-error 'f -5) exn:fail:contract:arity?)
(err/rt-test (raise-arity-mask-error 'f (arity-at-least 7)) exn:fail:contract:arity?/#f)
(err/rt-test (raise-arity-mask-error 'f -5.0) exn:fail:contract?)
(err/rt-test (raise-arity-mask-error 1 1) exn:fail:contract?)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; continuations
(test-cont)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; hash tables
(arity-test make-hash 0 1)
(arity-test make-hasheq 0 1)
(arity-test make-hasheqv 0 1)
(arity-test make-weak-hash 0 1)
(arity-test make-weak-hasheq 0 1)
(arity-test make-weak-hasheqv 0 1)
(define (hash-remove! . arg) (void))
(define (hash-tests make-hash make-hasheq make-hasheqv
make-weak-hash make-weak-hasheq make-weak-hasheqv
hash-ref hash-set! hash-ref! hash-update! hash-has-key?
hash-remove! hash-count
hash-map hash-for-each
hash-iterate-first hash-iterate-next
hash-iterate-value hash-iterate-key
hash-copy
hash-clear! hash-clear
hash-empty?
hash-keys-subset?)
(define-struct ax (b c)) ; opaque
(define-struct a (b c) #:inspector (make-inspector))
(define save
(let ([x null]) (case-lambda [() x] [(a) (set! x (cons a x)) a])))
(define an-ax (make-ax 1 2))
(define (check-hash-tables weak? reorder?)
(let ([h1 (if weak? (make-weak-hasheq) (make-hasheq))]
[l (list 1 2 3)])
(test #t eq? (eq-hash-code l) (eq-hash-code l))
(test #t eq? (eqv-hash-code l) (eqv-hash-code l))
(test #t eq? (equal-hash-code l) (equal-hash-code l))
(test #t eq? (equal-hash-code l) (equal-hash-code (list 1 2 3)))
(hash-set! h1 l 'ok)
(test 'ok hash-ref h1 l)
;(err/rt-test (hash-ref h1 'nonesuch (lambda (x) 'bad-proc)) exn:fail:contract:arity? "hash-ref")
(test #t hash-has-key? h1 l)
(test #f hash-has-key? h1 (cdr l))
(when hash-ref!
(test 'ok hash-ref! h1 l 'blah)
(test 'blah hash-ref! h1 (cdr l) 'blah)
(test #t hash-has-key? h1 (cdr l))
(test 'blah hash-ref h1 (cdr l))
(hash-remove! h1 (cdr l)))
(hash-update! h1 l (curry cons 'more))
(test '(more . ok) hash-ref h1 l)
(hash-update! h1 l cdr)
(test 'nope hash-ref h1 (list 1 2 3) (lambda () 'nope))
(test '(((1 2 3) . ok)) hash-map h1 (lambda (k v) (cons k v)))
(hash-remove! h1 l)
(test 'nope hash-ref h1 l (lambda () 'nope))
;(err/rt-test (hash-update! h1 l add1))
;(hash-update! h1 l add1 0)
(test 1 hash-ref h1 l)
(hash-remove! h1 l))
(let ([h1 (if weak? (make-weak-hasheqv) (make-hasheqv))]
[n (expt 2 500)]
[q (/ 1 2)]
[s (make-string 2 #\q)])
(hash-set! h1 n 'power)
(hash-set! h1 q 'half)
(hash-set! h1 s 'string)
(test 'power hash-ref h1 (expt (read (open-input-string "2")) 500))
(test 'half hash-ref h1 (/ 1 (read (open-input-string "2"))))
(test #f hash-ref h1 (make-string (read (open-input-string "2")) #\q) #f))
(let ([h1 (if weak? (make-weak-hash) (make-hash))]
[l (list 1 2 3)]
[v (vector 5 6 7)]
[a (make-a 1 (make-a 2 3))]
[b (box (list 1 2 3))]
[fl (flvector 1.0 +nan.0 0.0)]
[cyclic-list null #;(read (open-input-string "#2=(#1=(#2#) #2#)"))])
(test 0 hash-count h1)
;; Fill in table. Use `puts1' and `puts2' so we can
;; vary the order of additions.
(let ([puts1 (lambda ()
(hash-set! h1 (save l) 'list)
(hash-set! h1 (save "Hello World!") 'string)
(hash-set! h1 (save 123456789123456789123456789) 'bignum)
(hash-set! h1 (save 3.45) 'flonum)
(hash-set! h1 (save 3/45) 'rational)
(hash-set! h1 (save 3+45i) 'complex)
(hash-set! h1 (save (integer->char 955)) 'char)
(hash-set! h1 (save fl) 'flvector))]
[puts2 (lambda ()
(hash-set! h1 (save (list 5 7)) 'another-list)
(hash-set! h1 (save 3+0.0i) 'izi-complex)
(hash-set! h1 (save v) 'vector)
(hash-set! h1 (save a) 'struct)
(hash-set! h1 (save an-ax) 'structx)
(hash-set! h1 (save b) 'box)
(hash-set! h1 (save cyclic-list) 'cyclic-list))])
(if reorder?
(begin
(puts2)
(test 7 hash-count h1)
(puts1))
(begin
(puts1)
(test 8 hash-count h1)
(puts2))))
(when reorder?
;; Add 1000 things and take them back out in an effort to
;; trigger GCs that somehow affect hashing:
(let loop ([i 0.0])
(unless (= i 1000.0)
(hash-set! h1 i #t)
(loop (add1 i))
(hash-remove! h1 i))))
(test 15 hash-count h1)
(test 'list hash-ref h1 l)
(test 'list hash-ref h1 (list 1 2 3))
(test 'another-list hash-ref h1 (list 5 7))
(test 'string hash-ref h1 "Hello World!")
(test 'bignum hash-ref h1 123456789123456789123456789)
(test 'flonum hash-ref h1 3.45)
(test 'rational hash-ref h1 3/45)
(test 'complex hash-ref h1 3+45i)
(test 'izi-complex hash-ref h1 3+0.0i)
(test 'vector hash-ref h1 v)
(test 'vector hash-ref h1 #(5 6 7))
(test 'struct hash-ref h1 a)
;(test 'struct hash-ref h1 (make-a 1 (make-a 2 3)))
(test 'structx hash-ref h1 an-ax)
(test #f hash-ref h1 (make-ax 1 2) (lambda () #f))
(test 'box hash-ref h1 b)
(test 'box hash-ref h1 #&(1 2 3))
(test 'char hash-ref h1 (integer->char 955))
(test 'flvector hash-ref h1 (flvector 1.0 +nan.0 0.0))
(test 'cyclic-list hash-ref h1 cyclic-list)
(test #t
andmap
(lambda (i)
(and (member i (hash-map h1 (lambda (k v) (cons k v))))
#t))
`(((1 2 3) . list)
((5 7) . another-list)
("Hello World!" . string)
(123456789123456789123456789 . bignum)
(3.45 . flonum)
(3/45 . rational)
(3+45i . complex)
(3+0.0i . izi-complex)
(#(5 6 7) . vector)
(,(make-a 1 (make-a 2 3)) . struct)
(,an-ax . structx)
(#\u3BB . char)
(#&(1 2 3) . box)
(,(flvector 1.0 +nan.0 0.0) . flvector)
(,cyclic-list . cyclic-list)))
(hash-remove! h1 (list 1 2 3))
(test 14 hash-count h1)
(test 'not-there hash-ref h1 l (lambda () 'not-there))
(let ([c 0])
(hash-for-each h1 (lambda (k v) (set! c (add1 c))))
(test 14 'count c))
;; return the hash table:
h1))
(define (check-tables-equal mode t1 t2 weak?)
(test #t equal? t1 t2)
(test #t hash-keys-subset? t1 t2)
(test (equal-hash-code t1) equal-hash-code t2)
(test #t equal? t1 (hash-copy t1))
(let ([again (if weak? (make-weak-hash) (make-hash))])
(let loop ([i (hash-iterate-first t1)])
(when i
(hash-set! again
(hash-iterate-key t1 i)
(hash-iterate-value t1 i))
(loop (hash-iterate-next t1 i))))
(test #t equal? t1 again))
(let ([meta-ht (make-hash)])
(hash-set! meta-ht t1 mode)
(test mode hash-ref meta-ht t2 (lambda () #f)))
(test (hash-count t1) hash-count t2))
(check-tables-equal 'the-norm-table
(check-hash-tables #f #f)
(check-hash-tables #f #t)
#f)
(when make-weak-hash
(check-tables-equal 'the-weak-table
(check-hash-tables #t #f)
(check-hash-tables #t #t)
#t))
;; Make sure copy doesn't share:
(for ([make-hash (list make-hash
make-weak-hash)])
(when make-hash
(define c1 (make-hash))
(hash-set! c1 'the-key1 'the-val1)
(hash-set! c1 'the-key2 'the-val2)
(hash-set! c1 'the-key3 'the-val3)
(hash-set! c1 'the-key4 'the-val4)
(define c2 (hash-copy c1))
(hash-set! c1 'the-key3 'the-val5)
(hash-set! c2 'the-key4 'the-val6)
(hash-remove! c1 'the-key1)
(hash-remove! c2 'the-key2)
(test 'the-val1 hash-ref c2 'the-key1)
(test 'the-val2 hash-ref c1 'the-key2)
(test 'the-val3 hash-ref c2 'the-key3)
(test 'the-val4 hash-ref c1 'the-key4)))
(for ([make-hash (list make-hash
make-weak-hash)])
(when make-hash
(define c1 (make-hash))
(hash-set! c1 'the-key1 'the-val1)
(hash-set! c1 'the-key2 'the-val2)
(hash-set! c1 'the-key3 'the-val3)
(hash-set! c1 'the-key4 'the-val4)
(test #f hash-empty? c1)
(hash-clear! c1)
(test #t hash-empty? c1)))
(save)) ; prevents gcing of the ht-registered values
(hash-tests make-hash make-hasheq make-hasheqv
make-weak-hash make-weak-hasheq make-weak-hasheqv
hash-ref hash-set! hash-ref! hash-update! hash-has-key?
hash-remove! hash-count
hash-map hash-for-each
hash-iterate-first hash-iterate-next
hash-iterate-value hash-iterate-key
hash-copy
hash-clear! hash-clear
hash-empty?
hash-keys-subset?)
#;(let ([ub-wrap (lambda (proc)
(lambda (ht . args)
(apply proc (unbox ht) args)))])
(hash-tests (lambda () (box #hash()))
(lambda () (box #hasheq()))
(lambda () (box #hasheqv()))
#f #f #f
(ub-wrap hash-ref)
(lambda (ht k v) (set-box! ht (hash-set (unbox ht) k v)))
#f
(case-lambda
[(ht k u) (set-box! ht (hash-update (unbox ht) k u))]
[(ht k u def) (set-box! ht (hash-update (unbox ht) k u def))])
(ub-wrap hash-has-key?)
(lambda (ht k) (set-box! ht (hash-remove (unbox ht) k)))
(ub-wrap hash-count)
(ub-wrap hash-map)
(ub-wrap hash-for-each)
(ub-wrap hash-iterate-first)
(ub-wrap hash-iterate-next)
(ub-wrap hash-iterate-value)
(ub-wrap hash-iterate-key)
(lambda (ht) (box (unbox ht)))
(lambda (ht) (set-box! ht (hash-clear (unbox ht))))
#f
(ub-wrap hash-empty?)
(lambda (ht1 ht2)
(hash-keys-subset? (unbox ht1) (unbox ht2)))))
(test #f hash? 5)
(test #t hash? (make-hasheq))
(test #t hash? (make-hasheqv))
(test #t hash-eq? (make-hasheq))
(test #f hash-eq? (make-hash))
(test #f hash-eq? (make-hasheqv))
(test #t hash-eq? (make-weak-hasheq))
(test #f hash-eq? (make-weak-hash))
(test #f hash-eq? (make-weak-hasheqv))
(test #f hash-eqv? (make-hasheq))
(test #f hash-eqv? (make-hash))
(test #t hash-eqv? (make-hasheqv))
(test #f hash-eqv? (make-weak-hasheq))
(test #f hash-eqv? (make-weak-hash))
(test #t hash-eqv? (make-weak-hasheqv))
(test #f hash-weak? (make-hasheq))
(test #f hash-weak? (make-hash))
(test #f hash-weak? (make-hasheqv))
(test #t hash-weak? (make-weak-hasheq))
(test #t hash-weak? (make-weak-hash))
(test #t hash-weak? (make-weak-hasheqv))
(let ([ht (make-hasheqv)]
[l (list #x03B1 #x03B2 #x03B3)]
[l2 '(1 2 3)])
(for-each (lambda (a b)
(hash-set! ht (integer->char a) b))
l l2)
(test '(3 2 1)
map
(lambda (a)
(hash-ref ht (integer->char a) #f))
(reverse l)))
(err/rt-test (hash-eq? 5))
(err/rt-test (hash-eqv? 5))
(err/rt-test (hash-weak? 5))
(let ([a (expt 2 500)]
[b (expt (read (open-input-string "2")) 500)])
(test #t equal? (eqv-hash-code a) (eqv-hash-code b))
(test #t equal? (equal-hash-code a) (equal-hash-code b)))
;; Check for proper clearing of weak hash tables
;; (internally, value should get cleared along with key):
(let ([ht (make-weak-hasheq)])
(let loop ([n 10])
(unless (zero? n)
(hash-set! ht (make-string 10) #f)
(loop (sub1 n))))
(collect-garbage)
(map (lambda (i) (format "~a" i)) (hash-map ht cons)))
;; Double check that table are equal after deletions
(let ([test-del-eq
(lambda (mk)
(let ([ht1 (mk)]
[ht2 (mk)])
(test #t equal? ht1 ht2)
(hash-set! ht1 'apple 1)
(hash-set! ht2 'apple 1)
(test #t equal? ht1 ht2)
(hash-set! ht2 'banana 2)
(test #f equal? ht1 ht2)
(hash-remove! ht2 'banana)
(test #t equal? ht1 ht2)))])
(test-del-eq make-hasheq)
(test-del-eq make-hash)
(test-del-eq make-weak-hasheq)
(test-del-eq make-weak-hash))
(err/rt-test (hash-count 0))
(err/rt-test (hash-set! 1 2 3))
(err/rt-test (hash-ref 1 2))
(err/rt-test (hash-remove! 1 2))
;(err/rt-test (hash-ref (make-hasheq) 2) exn:application:mismatch?)
(let ([mk (lambda (mk)
(let ([ht (mk)])
(hash-set! ht make-hash 2)
ht))])
(test #t equal? (mk make-hash) (mk make-hash))
(test #t equal? (mk make-hasheq) (mk make-hasheq))
(test #t equal? (mk make-hasheqv) (mk make-hasheqv))
(test #f equal? (mk make-hash) (mk make-hasheq))
(test #f equal? (mk make-hash) (mk make-hasheqv))
(test #f equal? (mk make-hasheq) (mk make-hasheqv))
(test #f equal? (mk make-hash) (mk make-weak-hash))
(test #f equal? (mk make-hasheq) (mk make-weak-hasheq))
(test #f equal? (mk make-hasheqv) (mk make-weak-hasheqv)))
(let ([mk (lambda (mk)
(mk `((1 . 2))))])
(test #t equal? (mk make-immutable-hash) (mk make-immutable-hash))
(test #t equal? (mk make-immutable-hasheq) (mk make-immutable-hasheq))
(test #t equal? (mk make-immutable-hasheqv) (mk make-immutable-hasheqv))
(test #f equal? (mk make-immutable-hash) (mk make-immutable-hasheq))
(test #f equal? (mk make-immutable-hash) (mk make-immutable-hasheqv))
(test #f equal? (mk make-immutable-hasheq) (mk make-immutable-hasheqv)))
(let ([check-subset (lambda (mk1 mk2 [v2 2] #:k1 [k1 'a] #:k2 [k2 'a])
(define h1 (mk1 k1 #t 'b v2))
(define h2 (mk2 k2 #t))
(test #t hash-keys-subset? h2 h1)
(test #f hash-keys-subset? h1 h2)
(define h3 (mk2 k2 'something-else))
(test #t hash-keys-subset? h3 h1)
(test #t hash-keys-subset? h3 h2))]
[make-make-hash (lambda (mk)
(lambda args
(define ht (mk))
(let loop ([args args])
(cond
[(null? args) (void)]
[else
(hash-set! ht (car args) (cadr args))
(loop (cddr args))]))
ht))])
(check-subset hasheq hasheq #t)
(check-subset hasheq hasheq)
(check-subset hasheqv hasheqv)
(check-subset hasheqv hasheqv #:k1 (expt 2 70) #:k2 (expt 2 70))
(check-subset hash hash)
(check-subset hash hash #:k1 (cons 1 2) #:k2 (cons 1 2))
(check-subset hasheq (make-make-hash make-hasheq))
(check-subset hasheq (make-make-hash make-weak-hasheq))
(check-subset hasheqv (make-make-hash make-hasheqv))
(check-subset hasheqv (make-make-hash make-weak-hasheqv))
(check-subset hash (make-make-hash make-hash))
(check-subset hash (make-make-hash make-weak-hash))
(check-subset (make-make-hash make-hash) (make-make-hash make-weak-hash))
(check-subset hash (make-make-hash make-hash) #:k1 (expt 2 70) #:k2 (expt 2 70)))
(let ([not-same-comparison? (lambda (x)
(regexp-match? #rx"do not use the same key comparison" (exn-message x)))])
(err/rt-test (hash-keys-subset? #hash() #hasheq()) not-same-comparison?)
(err/rt-test (hash-keys-subset? #hash() #hasheqv()) not-same-comparison?)
(err/rt-test (hash-keys-subset? #hasheq() #hasheqv()) not-same-comparison?)
(err/rt-test (hash-keys-subset? (make-hasheq #hasheqv()) not-same-comparison?))
(err/rt-test (hash-keys-subset? (make-weak-hasheq #hasheqv()) not-same-comparison?)))
(define im-t (make-immutable-hasheq null))
(test #t hash? im-t)
(test #t hash-eq? im-t)
(test null hash-map im-t cons)
(err/rt-test (hash-set! im-t 1 2))
(test #f hash-ref im-t 5 (lambda () #f))
(define im-t (make-immutable-hasheq '((1 . 2))))
(test '((1 . 2)) hash-map im-t cons)
(test 2 hash-ref im-t 1)
(define im-t (make-immutable-hasheq '(("hello" . 2))))
(test 2 hash-ref im-t "hello" (lambda () 'none)) ; literals interned
(test 'none hash-ref im-t (list->string (string->list "hello")) (lambda () 'none))
(define im-t (make-immutable-hash '(("hello" . 2))))
(test 2 hash-ref im-t "hello" (lambda () 'none))
(test #f hash-eq? im-t)
(test #f equal? #hash((x . 0)) #hash((y . 0)))
(test #t equal? #hash((y . 0)) #hash((y . 0)))
(err/rt-test (hash-set! im-t 1 2))
(err/rt-test (hash-remove! im-t 1))
(err/rt-test (make-immutable-hasheq '(1)))
(err/rt-test (make-immutable-hasheq '((1 . 2) . 2)))
(err/rt-test (make-immutable-hasheq '((1 . 2) 3)))
(define cyclic-alist (read (open-input-string "#0=((1 . 2) . #0#)")))
(err/rt-test (make-immutable-hasheq cyclic-alist))
(err/rt-test (make-immutable-hasheq '((1 . 2)) 'weak))
(test 2 hash-ref (hash-copy #hasheq((1 . 2))) 1)
(test (void) hash-set! (hash-copy #hasheq((1 . 2))) 3 4)
(test #f hash-iterate-first (make-hasheq))
(test #f hash-iterate-first (make-weak-hasheq))
(test #f hash-iterate-next (make-hasheq) 0)
(test #f hash-iterate-next (make-weak-hasheq) 0)
(let ([hts (list (make-hash)
(make-hasheq)
(make-hasheqv)
(make-weak-hash)
(make-weak-hasheq)
(make-weak-hasheqv)
(hash)
(hasheq)
(hasheqv))])
(let* ([check-all-bad
(lambda (op)
(err/rt-test (op #f 0))
;(err/rt-test (op (make-hasheq) -1))
;(err/rt-test (op (make-hasheq) (- (expt 2 100))))
#;(err/rt-test (op (make-hasheq) 1.0)))]
[check-all-bad-v
(lambda (op)
(check-all-bad op)
(for ([ht (in-list hts)])
(test 'nope op ht 17 'nope)))]
[check-all-bad-pair
(lambda (op)
(check-all-bad op)
(for ([ht (in-list hts)])
(test '(nope . nope) op ht 17 'nope)))]
[check-all-bad-values
(lambda (op)
(check-all-bad op)
(for ([ht (in-list hts)])
(test-values '(nope nope)
(lambda () (op ht 17 'nope)))))])
(check-all-bad hash-iterate-next)
(check-all-bad-v hash-iterate-key)
(check-all-bad-v hash-iterate-value)
(check-all-bad-pair hash-iterate-pair)
(check-all-bad-values hash-iterate-key+value)))
(test (list 1 2 3) sort (hash-keys #hasheq((1 . a) (2 . b) (3 . c))) <)
(test (list 'a 'b 'c)
sort (hash-values #hasheq((1 . a) (2 . b) (3 . c))) string<? #:key symbol->string)
(test (list (cons 1 'a) (cons 2 'b) (cons 3 'c))
sort (hash->list #hasheq((1 . a) (2 . b) (3 . c))) < #:key car)
(err/rt-test (hash-set*! im-t 1 2) exn:fail?)
(err/rt-test (hash-set* (make-hasheq null) 1 2) exn:fail?)
(err/rt-test (hash-set* im-t 1 2 3) exn:fail?)
(err/rt-test (hash-set*! (make-hasheq null) 1 2 3) exn:fail?)
(test #t equal? (hash-set* (hasheq 1 'a 3 'b)) (hasheq 1 'a 3 'b))
(test #t equal? (hasheq 1 2 3 4)
(hash-set* (hasheq 1 'a 3 'b)
1 (gensym)
1 2
3 (gensym)
3 4))
(test #t equal? (make-hasheq (list (cons 1 'a) (cons 3 'b)))
(let ([ht (make-hasheq (list (cons 1 'a) (cons 3 'b)))])
(hash-set*! ht)
ht))
(test #t equal? (make-hasheq (list (cons 1 2) (cons 3 'b)))
(let ([ht (make-hasheq (list (cons 1 'a) (cons 3 'b)))])
(hash-set*! ht
1 2)
ht))
(test #t equal? (make-hasheq (list (cons 1 2) (cons 3 4)))
(let ([ht (make-hasheq (list (cons 1 'a) (cons 3 'b)))])
(hash-set*! ht
1 (gensym)
1 2
3 (gensym)
3 4)
ht))
(arity-test make-immutable-hash 0 1)
(arity-test make-immutable-hasheq 0 1)
(arity-test make-immutable-hasheqv 0 1)
(arity-test hash-keys 1 1)
(arity-test hash-values 1 1)
(arity-test hash-count 1 1)
(arity-test hash-ref 2 3)
(arity-test hash-set! 3 3)
(arity-test hash-set 3 3)
(arity-test hash-remove! 2 2)
(arity-test hash-remove 2 2)
(arity-test hash-map 2 3)
(arity-test hash-for-each 2 3)
(arity-test hash? 1 1)
(arity-test hash-eq? 1 1)
(arity-test hash-weak? 1 1)
;; Ensure that hash-table hashing is not sensitive to the
;; order of key+value additions
(let ()
(define ht (make-hash))
(define ht2 (make-hash))
(define wht (make-weak-hash))
(define wht2 (make-weak-hash))
(define keys (make-hasheq))
(struct a (x) #:transparent)
(define (shuffle c l)
(if (zero? c)
l
(shuffle
(sub1 c)
(let ([n (quotient (length l) 2)])
(let loop ([a (take l n)][b (drop l n)])
(cond
[(null? a) b]
[(null? b) a]
[(zero? (random 2))
(cons (car a) (loop (cdr a) b))]
[else
(cons (car b) (loop a (cdr b)))]))))))
(define l (for/list ([i (in-range 1000)])
i))
(define l2 (shuffle 7 l))
(define (reg v)
(hash-set! keys v #t)
v)
(for ([i (in-list l)])
(hash-set! ht (a i) (a (a i))))
(for ([i (in-list l2)])
(hash-set! ht2 (a i) (a (a i))))
(for ([i (in-list l)])
(hash-set! wht (reg (a i)) (a (a i))))
(for ([i (in-list l2)])
(hash-set! wht2 (reg (a i)) (a (a i))))
(test (equal-hash-code ht) values (equal-hash-code ht2))
(test (equal-hash-code wht) values (equal-hash-code wht2))
(test (equal-secondary-hash-code ht) values (equal-secondary-hash-code ht2))
(test (equal-secondary-hash-code wht) values (equal-secondary-hash-code wht2))
(let ([ht (for/hash ([i (in-list l)])
(values (a i) (a (a i))))]
[ht2 (for/hash ([i (in-list l2)])
(values (a i) (a (a i))))])
(test (equal-hash-code ht) values (equal-hash-code ht2))
(test (equal-secondary-hash-code ht) values (equal-secondary-hash-code ht2)))
;; make sure `key's is retained until here:
(when (positive? (random 1))
(display keys)))
;; Check that immutable hash trees aren't confused by an
;; "is a list" bit set in a key:
(let ()
(define p (list 1 2 3 4))
(define ht (hasheq p 1 'a 7 'b 10 'c 13))
(test 1 hash-ref ht p #f)
(list? p)
(list? p)
(list? (list* 1 2 p))
(list? (list* 1 2 p))
(list? (list* 1 2 p))
(test 1 hash-ref ht p #f))
;; Check that hash-table cycles don't lead to an
;; explosion in the time to compute a hash code.
(let ()
(define ht (make-hash))
(hash-set! ht 'a ht)
(hash-set! ht 'b ht)
(eq-hash-code ht)
(equal-hash-code ht)
(equal-secondary-hash-code ht))
;; Check that an equal hash code on an
;; mutable, opaque structure does not
;; see mutation.
(let ()
(struct a (x [y #:mutable]))
(define an-a (a 1 2))
(define v (equal-hash-code an-a))
(set-a-y! an-a 8)
(test v equal-hash-code an-a))
;; Check that `equal-hash-code` is consistent for interned symbols:
(let ()
(define v (random))
(define k (equal-hash-code (string->symbol (format "sym:~a" v))))
;(collect-garbage 'minor)
(test k equal-hash-code (string->symbol (format "sym:~a" v))))
;; Try to build a hash table whose indexes don't fit in 32 bits:
#;
(let ()
(struct a (x)
#:property
prop:equal+hash
(list
(lambda (a b eql?) (eql? (a-x a) (a-x b)))
(lambda (a hash) (expt 2 15))
(lambda (b hash) 1)))
(define (same-ish i) (a i))
;; No collisions: min depth 17, tree might be as
;; deep as 1.44 * 17 = 24
(define ht (for/hash ([i (in-range (expt 2 17))])
(values i i)))
;; All collissions: subtree min depth is 11, might
;; be as deep as 1.44*11 = 15
(define ht2 (for/fold ([ht ht]) ([i (in-range (expt 2 11))])
(hash-set ht (same-ish i) i)))
;; `ht2' depth is between 28 and 39
;; If the indexes go bad, this loop fails:
(for ([(k v) (in-hash ht2)])
v))
;; Check remove in the vicinity of a hash collision:
(let ()
(struct a (x y)
#:property prop:equal+hash
(list
(lambda (a b eql?) (and (equal? (a-x a)
(a-x b))
(equal? (a-y a)
(a-y b))))
(lambda (a hc) (a-x a))
(lambda (a hc) 1)))
(define k (+ (arithmetic-shift 1 10) 1))
(define k2 (+ (arithmetic-shift 1 15) 1))
;; The second hash here is intended to provoke a
;; collision in a subtable, and then remove an
;; element that causes the subtable, in which
;; case the collision should be moved up a layer.
(equal? (hash (a 1 'a) 1
(a 1 'b) 2
(a 2 'c) 3)
(hash-remove (hash (a 1 'a) 1
(a 1 'b) 2
(a 2 'c) 3
(a k 'd) 4)
(a k 'd)))
;; The second hash here is meanto to provoke
;; a similar shape as above, but where the
;; nested table is created to distinguish
;; hash keys instead of handle a collision,
;; and so it should not be moved up.
(equal? (hash (a 1 'a) 1
(a k2 'b) 2
(a 2 'c) 3)
(hash-remove (hash (a 1 'a) 1
(a k2 'b) 2
(a 2 'c) 3
(a k 'd) 4)
(a k 'd))))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Misc
(test #t string? (version))
;(test #t string? (banner))
(test #t symbol? (system-type))
(test (system-type) system-type 'os)
(test #t string? (system-type 'machine))
(test #t symbol? (system-type 'link))
(test #t relative-path? (system-library-subpath))
(test #t pair? (memv (system-type 'word) '(32 64)))
(test (fixnum? (expt 2 32)) = (system-type 'word) 64)
(test #t 'cmdline (let ([v (current-command-line-arguments)])
(and (vector? v)
(andmap string? (vector->list v)))))
(err/rt-test (current-command-line-arguments '("a")))
(err/rt-test (current-command-line-arguments #("a" 1)))
(arity-test version 0 0)
(arity-test banner 0 0)
(arity-test system-type 0 1)
(arity-test system-library-subpath 0 1)
(arity-test current-command-line-arguments 0 1)
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; procedure-closure-contents-eq?
(for-each
(lambda (jit?)
(parameterize ([eval-jit-enabled jit?])
(let ([f #f])
(set! f (eval '(lambda (x) (lambda () x))))
((f 'c)) ; forced JIT compilation
(test #t procedure-closure-contents-eq? (f 'a) (f 'a))
(test #f procedure-closure-contents-eq? (f 'a) (f 'b))
(set! f (eval '(case-lambda
[(x) (lambda () 12)]
[(x y) (lambda () (list x y))])))
((f 'c)) ; forces JIT compilation
((f 'c 'd)) ; forces JIT compilation
(test #t procedure-closure-contents-eq? (f 'a) (f 'a))
(test #t procedure-closure-contents-eq? (f 'a 'b) (f 'a 'b))
(test #f procedure-closure-contents-eq? (f 'a 'b) (f 'c 'b)))))
'(#t #f))
(test #t procedure-closure-contents-eq? add1 add1)
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; procedure-reduce-arity
#;
(let ([check-ok
(lambda (proc ar inc not-inc)
(for-each
(lambda (proc)
(let ([a (procedure-reduce-arity proc ar)])
(test #t procedure? a)
(test (normalize-arity ar) procedure-arity a)
(map (lambda (i)
(test #t procedure-arity-includes? a i)
(when (i . < . 100)
(test i apply a (let loop ([i i])
(if (zero? i)
null
(cons 1 (loop (sub1 i))))))))
inc)
(map (lambda (i)
(test #f procedure-arity-includes? a i)
(err/rt-test (procedure-reduce-arity a i))
(err/rt-test (procedure-reduce-arity a (make-arity-at-least i)))
(err/rt-test (procedure-reduce-arity a (list 0 i)))
(err/rt-test (procedure-reduce-arity a (list 0 (make-arity-at-least i))))
(err/rt-test (procedure-reduce-arity a (make-arity-at-least 0)))
(when (i . < . 100)
(err/rt-test (apply a (let loop ([i i])
(if (zero? i)
null
(cons 1 (loop (sub1 i))))))
exn:fail:contract?)))
not-inc)))
(list proc (procedure-reduce-arity proc ar))))]
[representable-arity? (lambda (a)
(a . < . 4096))])
(let ([check-all-but-one
(lambda (+)
(check-ok + 0 '(0) '(1))
(check-ok + 2 '(2) '(0 1 3 4))
(check-ok + 10 '(10) (filter representable-arity? (list 0 11 (expt 2 70))))
(when (representable-arity? (expt 2 70))
(check-ok + (expt 2 70) (list (expt 2 70)) (filter representable-arity? (list 0 10 (add1 (expt 2 70))))))
(check-ok + (make-arity-at-least 2) (filter representable-arity? (list 2 5 (expt 2 70))) (list 0 1))
(check-ok + (list 2 4) '(2 4) '(0 3))
(check-ok + (list 2 4) '(4 2) '(0 3))
(check-ok + (list 0 (make-arity-at-least 2)) (filter representable-arity? (list 0 2 5 (expt 2 70))) (list 1))
(check-ok + (list 4 (make-arity-at-least 2)) '(2 3 4 10) '(0 1))
(check-ok + (list 2 (make-arity-at-least 4)) '(2 4 10) '(0 1 3)))])
(check-all-but-one +)
(check-all-but-one (procedure-rename + 'plus))
(check-all-but-one (lambda args (apply + args)))
(check-all-but-one (procedure-rename (lambda args (apply + args)) 'PLUS))
(check-all-but-one (case-lambda
[() 0]
[(a b . args) (apply + a b args)]))
(check-all-but-one (case-lambda
[(b . args) (apply + b args)]
[() 0]))
(check-all-but-one (case-lambda
[(a b c) (+ a b c)]
[(a b) (+ a b)]
[(a b c d) (+ a b c d)]
[() 0]
[(a b c d . e) (apply + a b c d e)]))
(check-all-but-one (case-lambda
[(a b) (+ a b)]
[(a b c d) (+ a b c d)]
[(a b c) (+ a b c)]
[() 0]
[(a b c d . e) (apply + a b c d e)]))))
;(test '+ object-name (procedure-reduce-arity + 3))
(test 'plus object-name (procedure-rename + 'plus))
(test 'again object-name (procedure-rename (procedure-rename + 'plus) 'again))
;(test 'again object-name (procedure-rename (procedure-reduce-arity + 3) 'again))
;(test 3 procedure-arity (procedure-rename (procedure-reduce-arity + 3) 'again))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(report-errs)
"last item in file"
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.