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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
01385dfd20ec0a7d338537d9811ecc95bc5b0c40 | 821e50b7be0fc55b51f48ea3a153ada94ba01680 | /exp4/tr/typed-racket/typecheck/provide-handling.rkt | 9709474436a31b74f6701ce16600a2573b9abb3f | []
| no_license | LeifAndersen/experimental-methods-in-pl | 85ee95c81c2e712ed80789d416f96d3cfe964588 | cf2aef11b2590c4deffb321d10d31f212afd5f68 | refs/heads/master | 2016-09-06T05:22:43.353721 | 2015-01-12T18:19:18 | 2015-01-12T18:19:18 | 24,478,292 | 1 | 0 | null | 2014-12-06T20:53:40 | 2014-09-25T23:00:59 | Racket | UTF-8 | Racket | false | false | 6,378 | rkt | provide-handling.rkt | #lang racket/base
(require "../utils/utils.rkt"
(only-in srfi/1/list s:member)
syntax/kerncase syntax/boundmap
(env type-name-env type-alias-env)
(only-in (private type-contract) type->contract)
"renamer.rkt"
(rep type-rep)
(utils tc-utils)
(for-syntax syntax/parse racket/base)
racket/contract/private/provide unstable/list
syntax/id-table syntax/location racket/dict
racket/syntax racket/struct-info racket/match
"def-binding.rkt" syntax/parse
(for-template racket/base "def-export.rkt" racket/contract))
(provide remove-provides provide? generate-prov get-alternate)
(define (provide? form)
(syntax-parse form
#:literals (#%provide)
[(#%provide . rest) form]
[_ #f]))
(define (remove-provides forms)
(filter (lambda (e) (not (provide? e))) (syntax->list forms)))
(define (mem? i vd)
(cond [(s:member i vd (lambda (i j) (free-identifier=? i (binding-name j)))) => car]
[else #f]))
(define new-id-introducer (make-syntax-introducer))
(define cnt-id-introducer (make-syntax-introducer))
(define error-id-introducer (make-syntax-introducer))
(define untyped-id-introducer (make-syntax-introducer))
;; generate-contract-defs : dict[id -> def-binding] dict[id -> list[id]] id -> syntax
;; defs: defines in this module
;; provs: provides in this module
;; pos-blame-id: a #%variable-reference for the module
;; internal-id : the id being provided
;; if `internal-id' is defined in this module, we will produce a (begin def ... provide) block
;; and a name to provide instead of internal-id
;; anything already recorded in the mapping is given an empty (begin) and the already-recorded id
;; otherwise, we will map internal-id to the fresh id in `mapping'
(define (generate-prov defs provs pos-blame-id)
;; maps ids defined in this module to an identifier which is the possibly-contracted version of the key
(define mapping (make-free-id-table))
;; mk : id [id] -> (values syntax id aliases)
(define (mk internal-id [new-id (new-id-introducer internal-id)])
(define (mk-untyped-syntax b defn-id internal-id)
(match b
[(def-struct-stx-binding _ (? struct-info? si))
(define type-is-constructor? #t) ;Conservative estimate (provide/contract does the same)
(match-define (list type-desc constr pred (list accs ...) muts super) (extract-struct-info si))
(define-values (defns new-ids aliases)
(map/values 3
(lambda (e) (if (identifier? e)
(mk e)
(values #'(begin) e null)))
(list* type-desc constr pred super accs)))
(define/with-syntax (type-desc* constr* pred* super* accs* ...)
(for/list ([i new-ids]) (if (identifier? i) #`(syntax #,i) i)))
(values
#`(begin
#,@defns
(define-syntax #,defn-id
(let ((info (list type-desc* constr* pred* (list accs* ...) (list #,@(map (lambda x #'#f) accs)) super*)))
#,(if type-is-constructor?
#'(make-struct-info-self-ctor constr* info)
#'info))))
(apply append aliases))]
[_
(values
#`(define-syntax #,defn-id
(lambda (stx)
(tc-error/stx stx "Macro ~a from typed module used in untyped code" (syntax-e #'#,internal-id))))
null)]))
(cond
;; if it's already done, do nothing
[(dict-ref mapping internal-id
;; if it wasn't there, put it in, and skip this case
(λ () (dict-set! mapping internal-id new-id) #f))
=> (λ (mapped-id) (values #'(begin) mapped-id null))]
[(dict-ref defs internal-id #f)
=>
(match-lambda
[(def-binding _ (app (λ (ty) (type->contract ty (λ () #f) #:out #t)) (? values cnt)))
(values
(with-syntax* ([id internal-id]
[cnt-id (cnt-id-introducer #'id)]
[export-id new-id]
[module-source pos-blame-id]
[the-contract (generate-temporary 'generated-contract)])
;; stamourv: backporting changes. no idea whether this code is right
#`(begin
(define the-contract #,cnt)
(define-module-boundary-contract cnt-id
id the-contract
#:pos-source module-source
#:srcloc (vector '#,(syntax-source #'id)
#,(syntax-line #'id)
#,(syntax-column #'id)
#,(syntax-position #'id)
#,(syntax-span #'id)))))
new-id
null)]
[(def-binding id ty)
(values
(with-syntax* ([id internal-id]
[error-id (error-id-introducer #'id)]
[export-id new-id])
#'(begin
(define-syntax (error-id stx)
(tc-error/stx stx "The type of ~a cannot be converted to a contract" (syntax-e #'id)))
(def-export export-id id error-id)))
new-id
null)]
[(and b (def-stx-binding _))
(with-syntax* ([id internal-id]
[export-id new-id]
[untyped-id (untyped-id-introducer #'id)])
(define-values (d aliases)
(mk-untyped-syntax b #'untyped-id internal-id))
(define/with-syntax def d)
(values
#`(begin def (def-export export-id id untyped-id))
new-id
(cons (list #'export-id #'id) aliases)))])]
;; otherwise, not defined in this module, not our problem
[else (values #'(begin) internal-id null)]))
;; Build the final provide with auxilliary definitions
(for/lists (l l*) ([(internal-id external-ids) (in-dict provs)])
(define-values (defs id alias) (mk internal-id))
(define provide-forms
(for/list ([external-id (in-list external-ids)])
#`(rename-out [#,id #,external-id])))
(values #`(begin #,defs (provide #,@provide-forms))
alias)))
| true |
424deaa901407a27a09be37b302ad9514c55cbb5 | 799b5de27cebaa6eaa49ff982110d59bbd6c6693 | /soft-contract/test/gradual-typing-benchmarks/acquire/admin.rkt | 570bff187ee79d195f542d9e49fa382639637b8c | [
"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 | 13,578 | rkt | admin.rkt | #lang racket
;; ---------------------------------------------------------------------------------------------------
;; the Acquire game administrator class: sign up players and manage their play
(provide
administrator%
turn%
)
;; ---------------------------------------------------------------------------------------------------
(require
"../base/untyped.rkt"
"board.rkt"
"state.rkt"
"tree.rkt"
)
(require (only-in racket/sandbox
call-with-limits
exn:fail:resource?
))
(require (only-in "basics.rkt"
ALL-HOTELS
hotel?
shares-available?
shares?
shares-order?
))
;; =============================================================================
;; from sandbox.rkt
(define (in-sandbox producer consumer failure #:time (sec-limit 1) #:memory (mb-limit 30))
((let/ec fail
(let ([a
(with-handlers
((exn:fail:resource?
(lambda (x)
(fail
(lambda () (failure 'R)))));`(R ,(exn-message x)))))))
(exn:fail:out-of-memory?
(lambda (x)
(fail
(lambda () (failure 'R)))));`(R ,(exn-message x)))))))
(exn:fail?
(lambda (x)
(fail
(lambda () (failure 'X)))))) ;`(X ,(exn-message x))))))))
(call-with-limits sec-limit mb-limit producer))])
(lambda () (consumer a))))))
;; -----------------------------------------------------------------------------
(define (log status msg)
(void))
;; (display "[LOG:")
;; (display status)
;; (display "] ")
;; (displayln msg))
(define administrator%
(class object%
(init-field next-tile)
(super-new)
(define *count 10)
(define *named-players '())
;; effect: keep track of players
(define/public (sign-up name player)
(define pre (if (< (random 100) 50) "player" "spieler"))
(set! *count (+ *count 1 (random 10)))
(set! name (format "~a~a:~a" pre (number->string *count) name))
(set! *named-players (cons (list name player) *named-players))
name)
(define/public (show-players)
(for/list
([n+p (in-list *named-players)])
(car n+p)))
(define/public (run turns# #:show (show void))
(define players (player->internals))
(when (empty? players) (error 'run "players failed to sign up properly"))
(define tree0 (generate-tree (setup-all players (apply state0 players))))
;; generative recursion: n to 0, but terminate before if final state is reached
;; accumulator: states is reverese list of states encountered since tile distribution
(let loop
([tree tree0]
[n turns#]
[states (list (tree-state tree0))])
(define state (tree-state tree))
(cond
[(= n 0)
(list DONE (state-score state) (reverse states))]
[(empty? (state-players state))
(list EXHAUSTED (state-score state) (reverse states))]
;; [(not (decision-tree? tree))
[(and (is-a? tree lplaced%)
(send tree nothing-to-place?))
(finish state)
(list SCORE (state-score state) (reverse states))]
[else
(define external (or (player-external (state-current-player state)) (error 'external/fail)))
;; (show n state)
(define turn (new turn% [current-state state]))
(in-sandbox
#:time (* (+ (length (state-players state)) 1) 3)
(lambda ()
(let-values ([(a b c) (send external take-turn turn)])
(list a b c)))
;; success
(lambda (arg)
(define-values (tile hotel-involved buy-shares)
(values (car arg) (cadr arg) (caddr arg)))
(cond
[(boolean? tile)
(finish state)
(list IMPOSSIBLE (state-score state) (reverse (cons state states)))]
[(not hotel-involved)
(error "bad hotel")]
[else
(define merger? (eq? (what-kind-of-spot (state-board state) tile) MERGING))
(cond
;; -------------------------------------------------------------------------------
;; temporal contract:
[(and merger? (not (send turn place-called)))
(loop (generate-tree (state-remove-current-player state)) (- n 1) states)]
;; -------------------------------------------------------------------------------
[else
(define-values (t1 h1 d*)
(if merger? (send turn decisions) (values #f #f '())))
;; assert: if merging?:
(and (equal? tile t1) (equal? hotel-involved h1))
(define eliminate (send turn eliminated))
(cond
[(member (state-current-player state) eliminate)
((failure state states (lambda (s) (loop s (- n 1) states)))
`(S "current player failed on keep"))]
[else
(define tree/eliminate
(if (empty? eliminate)
tree
(generate-tree (state-eliminate state eliminate))))
(exec external tree/eliminate tile hotel-involved d* buy-shares
(lambda (next-tree
state)
(inform-all
next-tree state
(lambda (next-tree
state)
(cond
[(empty? (state-tiles state))
(finish state)
(list EXHAUSTED (state-score state) (reverse states))]
[else
(loop next-tree (- n 1) (cons state states))]))))
;; failure
(failure state states (lambda (s) (loop s (- n 1) states))))])])]))
;; failure:
(failure state states (lambda (s) (loop s (- n 1) states))))
])))
;; (-> State
;; (Listof State)
;; (-> State RunResult)
;; (-> State RunResult))
(define/private ((failure state states continue) status)
;; this should be a logging action
(log status `(turn failure ,(player-name (state-current-player state))))
(define state/eliminate (state-remove-current-player state))
(if (empty? (state-players state/eliminate))
(list EXHAUSTED '(all players failed) (reverse states))
(continue (generate-tree state/eliminate))))
;; [ (cons Tile [Listof Tile]) -> Tile ] -> Tree Tile [Maybe Hotel] Decisions [Listof Hotel]
;; (Any -> Any) -- success continuation
;; (Any -> Any) -- failure continuation
;; -> Tree
(define/private (exec external tree0 placement hotel decisions shares-to-buy succ fail)
(define-values (tile tree)
(tree-next tree0 placement hotel decisions shares-to-buy next-tile))
(unless tile (error 'no-tile))
(in-sandbox
(lambda ()
(send external receive-tile tile))
(lambda (_void)
(succ tree (tree-state tree)))
fail))
;; State (Tree State -> Any) -> Any
(define/private (inform-all tree state k)
(define eliminate
(for/fold
((throw-out '()))
((p (state-players state)))
(in-sandbox
(lambda arg*
;;bg; seems to return Void in original
(let ([pe (or (player-external p) (error 'external-fail))])
(send pe inform state)))
(lambda (_void)
throw-out)
(lambda arg*
(log (car arg*) `(inform ,(player-name p)))
(cons p throw-out)))))
(cond
[(empty? eliminate) (k tree state)]
[else (define state/eliminate (state-eliminate state eliminate))
(k (generate-tree state/eliminate) state/eliminate)]))
;; -> [Listof InternalPlayer]
;; create internal players for each external player
;;bg should these be player objects?
(define/private (player->internals)
(define-values (internals _)
(for/fold
((internals '())
(tile* ALL-TILES))
((name+eplayer *named-players))
(define name (first name+eplayer))
(define tiles (take tile* STARTER-TILES#))
(define player
;;bg; STARTER-TILES# = 6, shows the typechecker which case-> to use
(let ([t1 (first tiles)]
[t2 (second tiles)]
[t3 (third tiles)]
[t4 (fourth tiles)]
[t5 (fifth tiles)]
[t6 (sixth tiles)])
(player0 name t1 t2 t3 t4 t5 t6 (second name+eplayer))))
(values (cons player internals) (drop tile* STARTER-TILES#))))
internals)
;; [Listof Player] State -> State
(define/private (setup-all players state)
(define misbehaving
(for/fold
((misbehaving '()))
((p players))
(in-sandbox
(lambda arg*
(let ([pe (or (player-external p) (error 'external-failed))])
(send pe setup state)))
(lambda (_void)
misbehaving)
(lambda status
(log status `(setup ,(player-name p)))
(cons p misbehaving)))))
(if (empty? misbehaving) state (state-eliminate state misbehaving)))
;; State -> Void
;; score the final state and send the final state and the score board to the players
(define/private (finish state)
(define score (state-score state))
(for ((e (state-players state)))
(in-sandbox
(lambda ()
(send (or (player-external e) (error 'noexternal)) the-end state score))
void
(lambda (status)
(log status `(end game ,(player-name e)))))))))
(define DONE 'done)
(define EXHAUSTED 'exhausted)
(define SCORE 'score)
(define turn%
(class object%
(init-field current-state)
(field
[board (state-board current-state)]
[current (state-current-player current-state)]
[cash (player-money current)]
[tiles (player-tiles current)]
[shares (state-shares current-state)]
[hotels (state-hotels current-state)]
[players (state-players current-state)])
(super-new)
(define/public (reconcile-shares t)
;; in principle:
;; (error 'reconcile-shares "not possible for local game play")
;; but I need to accommodate game testing
t)
(define/public (eliminated)
*eliminated)
(define/public (decisions)
;; (unless (send this place-called) (error "Temporal contract violation"))
(values *tile *hotel *decisions))
(define/public (place-called)
*called)
(define *tile #f)
(define *hotel #f)
(define *decisions '())
(define *eliminated '())
(define *called #f)
;; effect: increments *called, sets *decisions to players' decisions
(define/public (place tile hotel)
;; -------------------------
;; temporal contract
(unless *called
(set! *called #t)
(set! *tile tile)
(set! *hotel hotel)
;; -------------------------
(define-values (acquirers acquired) (merging-which board tile))
(define acquired-hotels (append (remove hotel acquirers) acquired))
;; determine decisions and update *decisions
(let keep-to-all
((players players))
(unless (empty? players)
(define p (first players))
(in-sandbox
(lambda ()
(define ex (player-external p))
(if (boolean? ex)
;; accommodate fake players, and say that they always keep all shares
(map (lambda (_) #t) acquired-hotels)
(send ex keep acquired-hotels)))
(lambda (p-s-decisions)
(set! *decisions
(cons
(list p
(for/list
([h (in-list acquired-hotels)]
[d (in-list p-s-decisions)])
(list h (if d #t #f))))
*decisions))
(keep-to-all (rest players)))
(lambda (status)
(log status `(keep failure ,(player-name p)))
(set! *eliminated (cons p *eliminated))
(keep-to-all (rest players))))))
;; now change state and let the current player know
(define state/eliminated (state-eliminate current-state *eliminated))
(define state/returns (state-return-shares state/eliminated *decisions))
;; interesting question: could a return blow up?
(set! current-state state/returns)
(state-players state/returns)))))
| false |
2ef7ae42fdd62cd732193f0266d58ceb3a382b65 | 6a517ffeb246b6f87e4a2c88b67ceb727205e3b6 | /lang/statement.rkt | c88585a98ee71cd70cfd68fb416ac67da7ecf2c7 | []
| no_license | LiberalArtist/ecmascript | 5fea8352f3152f64801d9433f7574518da2ae4ee | 69fcfa42856ea799ff9d9d63a60eaf1b1783fe50 | refs/heads/master | 2020-07-01T01:12:31.808023 | 2019-02-13T00:42:35 | 2019-02-13T00:42:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 7,027 | rkt | statement.rkt | #lang racket/base
(require (for-syntax racket/base
syntax/parse)
racket/class
racket/provide
racket/stxparam
"../private/environment.rkt"
"../private/object.rkt"
"../private/primitive.rkt"
"../convert.rkt"
(only-in "environment.rkt" lexical-environment)
(only-in "function.rkt" begin-scope)
(prefix-in ecma: "operator.rkt"))
(provide (filtered-out
(λ (name)
(and (regexp-match? #rx"^stmt:" name)
(substring name 5)))
(all-defined-out)))
(struct exn:throw exn (value) #:transparent)
(define-syntax-parameter break-bindings '())
(define-syntax-parameter continue-bindings '())
(define-syntax-parameter return-value #f)
(define-syntax (stmt:break stx)
(let ([breaks (syntax-parameter-value #'break-bindings)])
(when (null? breaks)
(raise-syntax-error #f "invalid outside of loop" stx))
(syntax-case stx ()
[(_) #`(#,(cdar breaks)
return-value)]
[(_ label)
(let ([loop (assv (syntax-e #'label) breaks)])
(unless loop
(raise-syntax-error #f "no such label" stx #'label))
(with-syntax ([break-binding (cdr loop)])
#'(break-binding return-value)))])))
(define-syntax (stmt:continue stx)
(let ([continues (syntax-parameter-value #'continue-bindings)])
(when (null? continues)
(raise-syntax-error #f "invalid outside of loop" stx))
(syntax-case stx ()
[(_) #`(#,(cdar continues)
return-value)]
[(_ label)
(let ([loop (assv (syntax-e #'label) continues)])
(unless loop
(raise-syntax-error #f "no such label" stx #'label))
(with-syntax ([continue-binding (cdr loop)])
#'(continue-binding return-value)))])))
(define-syntax stmt:block
(syntax-rules ()
[(_) (void)]
[(_ stmt ...) (begin stmt ...)]))
(define-syntax-rule (var [var-id init] ...)
(begin
(put-value! (id var-id) (get-value init)) ...))
(define (stmt:empty-statement)
(void))
(define-syntax (stmt:if stx)
(syntax-case stx ()
[(_ test true)
#'(if test true (void))]
[(_ test true false)
#'(if test true false)]))
(define-syntax-rule (stmt:while test body ...)
(stmt:for #:test test
body ...))
(define-syntax (stmt:for stx)
(syntax-parse stx
[(_ (~optional (~seq #:init init))
(~optional (~seq #:test test))
(~optional (~seq #:update update))
body ...)
#`(let/ec escape
#,(or (attribute init) #'(void))
(let loop ([rv (void)])
(loop
(let ([new-rv
(let/ec next
(syntax-parameterize
([break-bindings (cons
(cons '#,(syntax-property stx 'label)
#'escape)
(syntax-parameter-value #'break-bindings))]
[continue-bindings (cons
(cons '#,(syntax-property stx 'label)
#'next)
(syntax-parameter-value #'continue-bindings))]
[return-value (make-rename-transformer #'rv)])
(if #,(if (attribute test)
#'(to-boolean
(get-value test))
#t)
(stmt:block
body ...)
(stmt:break))))])
#,(or (attribute update) #'(void))
new-rv))))]))
(define-syntax-rule (stmt:for-in lhs expr body)
(let ([exper-value (get-value expr)])
(if (or (ecma:null? exper-value)
(ecma:undefined? exper-value))
(void)
(let ([obj (to-object exper-value)])
(for/fold ([v (void)])
([(name prop) (in-hash (get-field properties obj))]
#:when (property-enumerable? prop))
(put-value! lhs (get-property-value obj name))
body)))))
(define-syntax-rule (stmt:with expr body0 body ...)
(begin-scope (new-object-environment (get-value expr) lexical-environment)
body0 body ...))
(define-syntax (stmt:switch stx)
(syntax-case stx ()
[(_ expr clause ...)
#'(let/ec escape
(syntax-parameterize
([break-bindings (cons (cons #f #'escape)
(syntax-parameter-value #'break-bindings))]
[return-value (λ (stx) #'(void))])
(let ([v expr])
(do-switch v first-lbl () () ([else (escape)]) clause ...))))]))
(define-syntax do-switch
(syntax-rules (default)
[(_ _ end (letrec-part ...) (cond-part ...) (default-part ...))
(letrec (letrec-part ... [end void])
(cond cond-part ... default-part ...))]
[(_ v lbl (letrec-part ...) (cond-part ...) (default-part ...) (default stmt ...) clause ...)
(do-switch v next-lbl
(letrec-part ...
[lbl (λ () stmt ... (next-lbl))])
(cond-part ...)
([else (lbl)])
clause ...)]
[(_ v lbl (letrec-part ...) (cond-part ...) (default-part ...) (test stmt ...) clause ...)
(do-switch v next-lbl
(letrec-part ...
[lbl (λ () stmt ... (next-lbl))])
(cond-part ...
[(ecma:=== v test) (lbl)])
(default-part ...)
clause ...)]))
(define-syntax (stmt:label stx)
(syntax-case stx ()
[(_ label stmt)
(unless (identifier? #'label)
(raise-syntax-error #f 'syntax "invalid label" stx #'label))
(syntax-property #'stmt 'label (syntax-e #'label))]))
(define (stmt:throw expr)
(let ([v (get-value expr)])
(raise
(exn:throw (to-string v)
(current-continuation-marks)
v))))
(define-syntax (stmt:try stx)
(syntax-parse stx
[(_ body
(~optional (~seq #:catch cid cbody))
(~optional (~seq #:finally fbody)))
(with-syntax
([handlers
(if (attribute cid)
(with-syntax ([eid (symbol->string (syntax-e (attribute cid)))])
#'([exn:throw?
(λ (e)
(let ([env (new-declarative-environment lexical-environment)])
(send env create-mutable-binding! eid)
(send env set-mutable-binding! eid (exn:throw-value e) #f)
(begin-scope env
cbody)))]))
#'())]
[post
(if (attribute fbody)
#'(λ ()
fbody)
#'void)])
#'(dynamic-wind
void
(λ ()
(with-handlers handlers
body))
post))]))
| true |
27f5d6786646a5ef96401e2cce81f0c75d1b2a74 | d9276fbd73cdec7a5a4920e46af2914f8ec3feb1 | /data/scheme/constraint-structs.rkt | 400968edbfd26b2ab9a0315fce7a4697eecdcd8c | []
| no_license | CameronBoudreau/programming-language-classifier | 5c7ab7d709b270f75269aed1fa187e389151c4f7 | 8f64f02258cbab9e83ced445cef8c1ef7e5c0982 | refs/heads/master | 2022-10-20T23:36:47.918534 | 2016-05-02T01:08:13 | 2016-05-02T01:08:13 | 57,309,188 | 1 | 1 | null | 2022-10-15T03:50:41 | 2016-04-28T14:42:50 | C | UTF-8 | Racket | false | false | 1,679 | rkt | constraint-structs.rkt | #lang racket/base
(require "../utils/utils.rkt" (contract-req))
(require-for-cond-contract (rep type-rep))
;; S, T types
;; represents S <: X <: T (see "Local Type Inference" pg. 12)
(define-struct/cond-contract c ([S Type/c] [T Type/c]) #:transparent)
;; fixed : Listof[c]
;; rest : option[c]
;; a constraint on an index variable
;; the index variable must be instantiated with |fixed| arguments, each meeting the appropriate constraint
;; and further instantions of the index variable must respect the rest constraint, if it exists
(define-struct/cond-contract dcon ([fixed (listof c?)] [rest (or/c c? #f)]) #:transparent)
;; fixed : Listof[c]
;; rest : c
(define-struct/cond-contract dcon-exact ([fixed (listof c?)] [rest c?]) #:transparent)
;; fixed : Listof[c]
;; type : c
;; bound : var
(define-struct/cond-contract dcon-dotted ([fixed (listof c?)] [type c?] [bound symbol?]) #:transparent)
(define-for-cond-contract dcon/c (or/c dcon? dcon-exact? dcon-dotted?))
;; map : hash mapping index variables to dcons
(define-struct/cond-contract dmap ([map (hash/c symbol? dcon/c)]) #:transparent)
;; maps is a list of pairs of
;; - functional maps from vars to c's
;; - dmaps (see dmap.rkt)
;; we need a bunch of mappings for each cset to handle case-lambda
;; because case-lambda can generate multiple possible solutions, and we
;; don't want to rule them out too early
(define-struct/cond-contract cset ([maps (listof (cons/c (hash/c symbol? c? #:immutable #t) dmap?))]) #:transparent)
(provide-for-cond-contract dcon/c)
(provide
(struct-out cset)
(struct-out dmap)
(struct-out dcon)
(struct-out dcon-dotted)
(struct-out dcon-exact)
(struct-out c))
| false |
877d9248bf6163bda1105fd31db86bfc64888372 | 720fa5737ec950f39af1283cf73f00cb5746bb5f | /csc121/S17/week6.rkt | 1f43f94ee04c38076737a82b1ac92492494c639c | []
| no_license | gfbee/R | 7ef3ff2d694b793c5a083165e1e3f4d3687797ce | e7e88ecc8e1dfc8957532acd503ff32445a87723 | refs/heads/master | 2021-03-27T16:02:29.024266 | 2017-11-13T19:48:29 | 2017-11-13T19:48:29 | 110,363,549 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,546 | rkt | week6.rkt | #lang racket
; http://www.cs.toronto.edu/~radford/csc121.S17/week6.pdf
; Plot random walk.
; Support library, and plotting, in racket follows.
;
; random_walk <- function (steps) {
; position <- numeric(steps+1)
; for (i in 1:steps) {
; if (runif(1) < 0.5)
; position[i+1] <- position[i] + 1
; else
; position[i+1] <- position[i] - 1
; }
; position
; }
; plot(random_walk(200))
; plot(random_walk(200))
; plot(random_walk(200))
#| Simple indexed plotting. |#
(require "plot.rkt")
#| Simple time series library. |#
#;(repeat-times f seed times)
; produces list of length ‘times’ with:
#;(list seed (f seed) (f (f seed)) ...)
(module Series racket (provide repeat-times)
(define (repeat-times f seed times)
(if (zero? times)
'()
(list* seed (repeat-times f (f seed) (sub1 times))))))
#| Use the libraries. |#
(require 'Series)
; Plot three random walks:
#;(step n) ; → n ± 1.
(define (step position)
#;(if (zero? (random 2)) (+ position 1) (- position 1))
#;(+ position (if (zero? (random 2)) +1 -1))
#;(if (zero? (random 2)) (add1 position) (sub1 position))
((if (zero? (random 2)) add1 sub1) position))
(plot (repeat-times step 0 200))
(plot (repeat-times step 0 200))
(plot (repeat-times step 0 200))
; csc121 pseudo-random number illustration:
; > nxt <- 1; series <- c()
; > for (i in 1:200) { nxt <- (nxt * 17) %% 31; series <- c(series,nxt) }
; > plot(series)
(define (next n) (remainder (* n 17) 31))
(define series (repeat-times next 1 200))
(plot series)
| false |
b389568854ad8cdf2e26fd3afbead301151bd4ad | 82c76c05fc8ca096f2744a7423d411561b25d9bd | /typed-racket-more/typed/net/cgi.rkt | 321e30bc517671043e2bf36dde436962d66768e6 | [
"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 | 931 | rkt | cgi.rkt | #lang typed/racket/base
(require typed/private/utils)
(require/typed/provide net/cgi
[get-bindings (-> (Listof (cons (U Symbol String) String)))]
[get-bindings/post (-> (Listof (Pair (U Symbol String) String)))]
[get-bindings/get (-> (Listof (Pair (U Symbol String) String)))]
[output-http-headers (-> Void)]
[generate-html-output (case-lambda (String (Listof String) -> Void)
(String (Listof String) String String String String String -> Void))]
[generate-error-output ((Listof String) -> (U))]
[bindings-as-html ((Listof (cons (U Symbol String) String)) -> (Listof String))]
[extract-bindings ((U Symbol String) (Listof (cons (U Symbol String) String)) -> ( Listof String))]
[extract-binding/single ((U Symbol String) (Listof (Pair (U Symbol String) String)) -> String)]
[get-cgi-method (-> (U "GET" "POST"))]
[string->html (String -> String)]
[generate-link-text (String String -> String)])
| false |
a6137102bd0bd1b789950ebe6cf592dd2be5086f | 5f8d781ca6e4c9d3d1c3c38d2c04e18d090589cc | /2/www/acks.scrbl | 3949d27be00bc1edff4dd9adec15a42351c2b6d9 | [
"AFL-3.0",
"AFL-2.1",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | plum-umd/fundamentals | a8458621131b864f0e3389b030c5197ea6bb3f41 | eb01ac528d42855be53649991a17d19c025a97ad | refs/heads/master | 2021-06-20T05:30:57.640422 | 2019-07-26T15:27:50 | 2019-07-26T15:27:50 | 112,412,388 | 12 | 1 | AFL-3.0 | 2018-02-12T15:44:48 | 2017-11-29T01:52:12 | Racket | UTF-8 | Racket | false | false | 197 | scrbl | acks.scrbl | #lang scribble/manual
@(require scribble/core)
@title[#:style 'unnumbered]{Acknowledgments}
Material for this course web page is based on the "Fundamentals II"
course at Northeastern University.
| false |
2e9a114d989db388229d2fd96fbeece62cef5222 | a0c24087e281d33f73306f0399184cfc153ab9d5 | /Q004/Q004.rkt | 4d0e57dd42f214cfd9b4eadfd556bdcb796c6da8 | []
| no_license | creasyw/project_euler | c94215886390cd2606c2c92af79008de4d67146f | b0584fb01ba2a255b2049a8cdc24fba98f46aff0 | refs/heads/master | 2021-11-19T10:39:48.946028 | 2021-10-12T03:59:34 | 2021-10-12T03:59:34 | 4,611,853 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 962 | rkt | Q004.rkt | #lang racket
;; problem 36 has better idea check if a number is palindrome
;; which is just convert num->list then check reverse(list)==list
(define (check-palindrome num)
(define (find-base n base)
(if (= 0 (quotient n base))
(find-base n (/ base 10))
(is-pal n base)))
(define (is-pal n base)
(cond (( = base 1) #t)
((= base 10) (if (= (quotient n base) (modulo n base)) #t #f))
(#t (if (= (quotient n base) (modulo n 10))
(is-pal (quotient (modulo n base) 10) (quotient base 100)) #f))))
(find-base num 100000))
(define (largest-pal limit base)
(define (helper n1 n2 acc)
(letrec ((product (* n1 n2)))
(cond ((< n1 base) acc)
((< product acc) (helper (- n1 1) limit acc))
((check-palindrome product) (helper n1 (- n2 1) product))
((> n2 n1) (helper n1 (- n2 1) acc))
(#t (helper (- n1 1) limit acc)))))
(helper limit limit 0)) | false |
e85b2084727a949e1b0f79e53b5eca674a7631e5 | a39714fb53d26c8829e1e24058f0a0624055b14c | /lang.rkt | f0e3e5daefc3ac0fb8ed080532fe6245c44e2c6a | []
| no_license | rasteric/appy | 4b7e3a684ef57dcd85024961f2b9e7f65bef0f0f | 33ced19692e3a60b1742b96b8ba7ca8d039a9223 | refs/heads/master | 2020-03-30T02:05:55.777440 | 2018-09-27T17:05:58 | 2018-09-27T17:05:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 10,568 | rkt | lang.rkt | #lang racket
;; Lang - localization support
(require racket/path
racket/runtime-path
srfi/13)
(provide tr load-language list-available-languages language-available? current-localization-folder current-translations current-language
define-localizations init-language-system check-translations write-translation-template)
(define current-language (make-parameter 'en_US))
(define current-translations (make-parameter #f))
(define current-localization-folder (make-parameter #f))
;; PUBLIC PART
(define (load-language lang)
(precondition:initialized?)
(cond
((file-exists? (get-path-for lang))
(current-translations (make-hash))
(with-input-from-file (get-path-for lang)
(lambda ()
(call-with-default-reading-parameterization
(lambda ()
(for ([translation (in-port)])
(hash-set! (current-translations) (first translation) (second translation)))))))
(current-language lang))
(else
(displayln
(format "APPY Warning: The localization for language ~s was not found. Translations-folder=~a."
lang (path->string (current-localization-folder)))
(current-error-port))
(unless (equal? lang 'en_US)
(display "Switching to default language 'en_US..."(current-error-port))
(load-language 'en_US)
(displayln "done." (current-error-port))))))
(define (list-available-languages)
(precondition:initialized?)
(map
string->symbol
(sort
(filter
(lambda (spec)
(non-empty-string? (string-trim spec)))
(for/list
([file (in-directory (current-localization-folder)
(lambda (dir)
(and (file-exists? dir)
(path-has-extension? dir #".loc"))))])
(first (string-split (path->string (file-name-from-path file)) "."))))
string<?)))
(define (language-available? lang)
(if (member lang (list-available-languages)) #t #f))
(define *translations* (make-hash))
(define-syntax-rule (defloc key value)
(begin
(define (key . args) (apply tr (cons 'key args)))
(add-key 'key value)))
(define-syntax-rule (define-localizations (key value) ...)
(begin (defloc key value)
...))
(define (tr key . args)
(if (empty? args)
(translate key)
(apply format (cons (translate key) args))))
(define (init-language-system #:application-name [appname "appy"] #:hardcoded-paths [hardcoded-paths '()]
#:write-templates? [write-templates? #f])
(current-localization-folder (build-path (find-system-path 'pref-dir) appname "app-data" "localizations"))
(for ([src (in-list hardcoded-paths)])
(unless (file-exists? (build-path (current-localization-folder) (file-name-from-path src)))
(copy-file src (build-path (current-localization-folder) (file-name-from-path src)))
(when write-templates?
(write-translation-template (string->symbol (first (string-split (path->string (file-name-from-path src)) ".")))))))
(make-directory* (current-localization-folder))
(precondition:valid-translations-folder? (current-localization-folder))
(write-keys)
(load-language 'en_US))
(define (write-translation-template lang)
(define current (current-language))
(load-language 'en_US)
(let ((basis (current-translations))
(target (cond
((file-exists? (get-path-for lang))
(load-language lang)
(current-translations))
(else (make-hash)))))
(with-output-to-file
(get-path-for lang)
(lambda ()
(display ";; This file is a template for language ")
(displayln lang)
(displayln ";; Translate all the strings from the comment above the entries to the value in the key value list below it")
(displayln ";; Leave the key untouched.")
(newline)
(for ([(k v) (in-hash basis)])
(display ";; Translation for: ")
(writeln v)
(if (hash-has-key? target k)
(writeln (list k (hash-ref target k)))
(writeln (list k "")))
(newline)))
#:exists 'replace
#:mode 'text))
(if current
(load-language current)
(current-language current)))
(define (check-translations)
(define languages (list-available-languages))
(define current (current-language))
(load-language 'en_US)
(define en (current-translations))
(for ([language (in-list (filter (lambda (x) (not (equal? x 'en_US))) languages))])
(load-language language)
(check-translation-keys (current-language) en (current-translations)))
(load-language current))
;; PRIVATE PART
(define (translate key)
(hash-ref (current-translations)
key
(lambda () (error 'lang "The localization for key '~s was not found in language '~s." key (current-language)))))
(define (get-path-for lang)
(build-path (current-localization-folder) (string-append (symbol->string lang) ".loc")))
(define (check-translation-keys lang t1 t2)
(for ([(k v) (in-hash t1)])
(unless (hash-has-key? t2 k)
(error 'check-translations "The location for key '~s is missing in language '~s." k lang))
(when (and (non-empty-string? (hash-ref t1 k))
(not (non-empty-string? (hash-ref t2 k))))
(displayln (format "Warning: The string for key '~s in language '~s is empty, but not empty for 'en_US." k lang)
(current-error-port)))
(when (not (= (string-count (hash-ref t1 k) #\~) (string-count (hash-ref t2 k) #\~)))
(displayln (format "Warning: The string for key '~s in language '~s seems to have ~a format arguments whereas in 'en_US it seems to have ~a."
k
lang
(string-count (hash-ref t2 k) #\~)
(string-count (hash-ref t1 k) #\~))
(current-error-port)))))
(define (write-keys)
(with-output-to-file
(get-path-for 'en_US)
(lambda ()
(displayln ";; APPY Language Template for US English")
(displayln ";; This file is auto-generated, do not change its contents! The command (init-language-system appname) overwrites this file.")
(displayln ";; Use define-localizations followed by init-language-system for defining en_US file that serves as a basis.")
(displayln ";; Use (check-translations) before deployment to check the completeness of your translation files.")
(displayln ";; Use (write-translation-template lang) to create a template for language lang, abbreviated by symbols as above.")
(newline)
(for ([(k v) (in-hash *translations*)])
(writeln (list k v))))
#:exists 'replace
#:mode 'text))
(define (add-key key value)
(hash-set! *translations* key value)
(current-translations *translations*)
(current-language 'en_US))
;; Preconditions
(define (precondition:initialized?)
(unless (current-localization-folder)
(error 'lang "Attempt to use the localization system without prior initialization. You need to use (init-language-system) first.")))
(define (precondition:valid-translations-folder? f)
(unless (directory-exists? f)
(error 'lang "The translations directory does not exist, path=~s" f)))
(define (precondition:source-dir-exists? d)
(unless (directory-exists? d)
(error 'lang "The source directory for (generate-template source-dir) does not exist, given path=~s" d)))
(module+ test
(require rackunit)
(define (del p)
(when (file-exists? p) (delete-file p)))
;; set up tests
(define testdir (build-path (find-system-path 'pref-dir) "appy-testing" "app-data" "localizations"))
(make-directory* testdir)
(del (build-path testdir "en_US.loc"))
(del (build-path testdir "de_DE.loc"))
(del (build-path testdir "fr_FR.loc"))
(del (build-path testdir "xx_XX.loc"))
(with-output-to-file (build-path testdir "de_DE.loc")
(lambda ()
(writeln '(test1 "de test 1"))
(writeln '(test2 "de test 2: ~a"))
(writeln '(test3 "de test 3: ~a ~s"))
(writeln '(test4 "de der Mond"))))
(with-output-to-file (build-path testdir "fr_FR.loc")
(lambda ()
(writeln '(test1 "fr test 1"))
(writeln '(test2 "fr test 2: ~a"))
(writeln '(test3 "fr test 3: ~a ~s"))
(writeln '(test4 "fr la lune"))))
;; actual tests
(check-not-exn (lambda () (define-localizations
(test1 "en test 1")
(test2 "en test 2: ~a")
(test3 "en test 3: ~a ~s")
(test4 "en the Moon"))))
(check-not-exn (lambda () (init-language-system #:application-name "appy-testing")))
(check-equal? (list-available-languages) '(de_DE en_US fr_FR))
(check-equal? (tr 'test1) "en test 1")
(check-equal? (tr 'test2 'hello) "en test 2: hello")
(check-equal? (tr 'test3 'hello "world") "en test 3: hello \"world\"")
(check-equal? (tr 'test4) "en the Moon")
(check-not-exn (lambda () (load-language 'de_DE)))
(check-equal? (tr 'test1) "de test 1")
(check-equal? (tr 'test2 'hello) "de test 2: hello")
(check-equal? (tr 'test3 'hello "world") "de test 3: hello \"world\"")
(check-equal? (tr 'test4) "de der Mond")
(check-not-exn (lambda () (load-language 'en_US)))
(check-equal? (tr 'test1) "en test 1")
(check-equal? (tr 'test2 'hello) "en test 2: hello")
(check-equal? (tr 'test3 'hello "world") "en test 3: hello \"world\"")
(check-equal? (tr 'test4) "en the Moon")
(check-not-exn (lambda () (load-language 'fr_FR)))
(check-equal? (tr 'test1) "fr test 1")
(check-equal? (tr 'test2 'hello) "fr test 2: hello")
(check-equal? (tr 'test3 'hello "world") "fr test 3: hello \"world\"")
(check-equal? (tr 'test4) "fr la lune")
(check-not-exn (lambda () (check-translations)))
(check-not-exn (lambda () (write-translation-template 'xx_XX)))
(check-true (file-exists? (build-path testdir "xx_XX.loc")))
(displayln "-------------------------------------------------------------------------" (current-error-port))
(displayln "APPY: The following warnings are intended and part of testing \"lang.rkt\":" (current-error-port))
(check-not-exn (lambda () (check-translations)))
(displayln "-------------------------------------------------------------------------" (current-error-port))
(del (build-path testdir "en_US.loc"))
(del (build-path testdir "de_DE.loc"))
(del (build-path testdir "fr_FR.loc"))
(del (build-path testdir "xx_XX.loc"))
)
| true |
420928807392631236a29ed18b7c94a426ddb8a7 | d5aa82d7071cfbe382ecc4d6621137fb385181e6 | /bug_tasks/spray-can-bug2.rkt | d2822b97b5d73c61d435fee86ebd819361f64e35 | [
"MIT"
]
| permissive | schuster/aps-conformance-checker | ff809d238047fbf327cb9695acb51b91a0f5272f | d9bf0c93af2c308f453d9aaf17a2eed9b6606a89 | refs/heads/master | 2021-01-19T11:41:56.847873 | 2019-03-11T12:56:52 | 2019-03-11T12:56:52 | 87,989,503 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 135 | rkt | spray-can-bug2.rkt | #lang racket
(require
"../check-pair.rkt"
"../examples/spray-can.rkt")
(check-pair (make-manager-program #f #t) http-manager-spec)
| false |
c6f8be8f565f23ae59036de51772fd95f88a5686 | 52a4d282f6ecaf3e68d798798099d2286a9daa4f | /v22/x/xnice.rkt | 76466d50b895d4c76d262277f64de314a35df7a7 | [
"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 | 15,510 | rkt | xnice.rkt | ; xnice.rkt -- Experimenting with making nice syntax for specifying a FARG model
#lang debug at-exp racket
(require racket/hash)
(require (prefix-in g: "graph.rkt") (prefix-in g: "make-graph.rkt"))
(require (for-syntax racket/syntax) racket/syntax)
(require debug/repl describe)
(define empty-set (set))
(define empty-hash (hash))
#;(define-syntax (define/g stx)
(syntax-case stx ()
[(define/g (name g args ...) body0 body ...)
(with-syntax ([name/g (format-id #'name "~a/g" #'name
#:source #'name #:props #'name)])
#'(begin
(define (name g args ...) body0 body ...)
(define (name/g args ...)
(λ (g) (name g args ...)))))]))
;; A function whose first argument is a graph, and that returns one or more
;; values, the first of which is the updated graph.
(struct gfunc* (f) #:property prop:procedure 0)
(define-syntax-rule (gλ args body0 body ...)
(gfunc* (λ args body0 body ...)))
(define-syntax (define/g stx)
(syntax-case stx ()
[(define/g (name g args ... . optargs) body0 body ...)
(with-syntax* ([name (syntax-property #'name 'gfunc? #t #t)]
[name/g (format-id #'name "~a/g" #'name
#:source #'name #:props #'name)])
#`(begin
(define name (gλ (g args ... . optargs) body0 body ...))
(define (name/g args ... . optargs)
(gλ (g) #,@(if (null? (syntax->datum #'optargs))
#'(name g args ...)
#'(apply name g args ... optargs))))))]))
(struct is-a* (parents) #:prefab)
; parents: (Setof Symbol)
(define (is-a . args)
(is-a* (list->set args)))
(struct by-ports* (from-port to-port) #:prefab)
(define by-ports by-ports*)
(struct links-into* (ctx-class by-portss) #:prefab)
;ctx-class : Symbol
;by-portss : (Listof by-ports)
(define (links-into ctx-class . by-portss)
(links-into* ctx-class by-portss))
(struct default-attrs* (attrs))
;attrs: (Hash Any Any)
(struct nodeclass* (name parents default-attrs links-intos applies-tos)
#:prefab)
(define (nodeclass-name x)
(if (nodeclass*? x)
(nodeclass*-name x)
x))
(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 (get-spec g-or-spec)
(cond
[(farg-model-spec*? g-or-spec) g-or-spec]
[(g:graph? g-or-spec) (g:graph-spec g-or-spec)]
[else (raise-arguments-error 'get-spec
@~a{Can't get spec from @|g-or-spec|.})]))
(define (nodeclass-is-a? g-or-spec ancestor child)
(define child-name (nodeclass-name child))
(define ancestor-name (nodeclass-name ancestor))
(if (equal? ancestor-name child-name)
#t
(let ([spec (get-spec g-or-spec)]
[ht (farg-model-spec*-ancestors spec)])
(hash-ref/sk ht child-name
(λ (st) (set-member? st ancestor-name))
#f))))
(define (node-is-a? g ancestor node)
(nodeclass-is-a? g ancestor (g:class-of g node)))
(define (plain-name name)
(cond
[(pair? name) (car name)]
[else name]))
(define (make-nodeclass name . elems)
(for/fold ([parents empty-set]
[default-attrs (hash 'class name)]
[links-intos empty-set]
[applies-tos empty-set]
#:result (nodeclass* name
parents
default-attrs
(set->list links-intos)
(set->list applies-tos)))
([elem elems])
(match elem
[(is-a* parents-)
(values
(set-union parents parents-) default-attrs links-intos applies-tos)]
[(default-attrs* attrs)
(values
parents (hash-union default-attrs attrs) links-intos applies-tos)]
[(links-into* ctx by-portss)
(values parents default-attrs (set-add links-intos elem) applies-tos)]
[(applies-to* _ _)
(values parents default-attrs links-intos (set-add applies-tos elem))])))
(define (make-tagclass name . elems)
(define default-attrs (default-attrs* (hash 'tag? #t
'value name)))
(apply make-nodeclass name (cons default-attrs elems)))
(define-syntax-rule (nodeclass name elems ...)
(make-nodeclass (quote name) elems ...))
(define-syntax-rule (tagclass name elems ...)
(make-tagclass (quote name) elems ...))
;; Single instance
;(define (tag-applies-to? (need source) . nodes)
; (let ([pred (λ (node)
; (no-neighbor-at-port?/g 'source node))])
; (apply pred nodes)))
;
;;; Assuming only one condition for now
;(define (tag-applies-to? g tagclass . nodes)
; (let ([condition?/g (apply (tagclass-condition tagclass) nodes)])
; (condition?/g g)))
;
;(define (tag-applies-to?/g tagclass . nodes)
; (apply (tagclass-condition tagclass) nodes))
;
;(define (tag-applies-to? g tagclass . nodes)
; (let ([condition?/g (tagclass-condition tagclass)])
; (apply condition?/g g nodes)))
;
;(define (tag-applies-to?/g tagclass . nodes)
; (λ (g) (apply tag-applies-to? g tagclass nodes)))
(struct applies-to* (taggees conditions) #:prefab)
; taggees: (List taggee*)
; conditions: (List cfunc)
(struct taggee* (name of-classes by-portss) #:prefab)
; name: Any
; of-classes: (List of-class*)
; by-portss: (List by-ports*)
(struct of-class* (class) #:prefab)
; class: Any
(define of-class of-class*)
(define (make-taggee name . taggee-infos)
(define-values (of-classes by-portss)
(for/fold ([of-classes '()] [by-portss '()])
([taggee-info taggee-infos])
(cond
[(of-class*? taggee-info)
(values (cons (of-class*-class taggee-info) of-classes) by-portss)]
[(by-ports*? taggee-info)
(values of-classes (cons taggee-info by-portss))]
[else (raise-arguments-error 'applies-to
@~a{@taggee-info is neither of-class nor by-ports.})])))
(taggee* name of-classes by-portss))
(define-syntax applies-to
(syntax-rules (condition)
[(applies-to ([taggee taggee-info ...] ...)
(condition condition-expr0 condition-expr ...) ...)
(applies-to* (list (make-taggee 'taggee taggee-info ...) ...)
(list (make-condition-func (taggee ...)
condition-expr0 condition-expr ...) ...))]))
; Makes a function that returns a g-func that returns true if the condition
; applies to the given nodes. TODO: Check preconditions from tag-infos.
(define-syntax make-condition-func
(syntax-rules ()
[(make-condition-func (taggee ...) body0 body ...)
(let ([num-taggees (length (list 'taggee ...))]
[make-pred/g (λ (taggee ...) body0 body ...)])
(λ nodes
(if (not (= num-taggees (length nodes)))
(λ (g) #f) ; tag can't apply if number of nodes is wrong
(apply make-pred/g nodes))))]))
(define (condition-func-passes? g cfunc nodes)
(define cfunc-takes-g (apply cfunc nodes))
(cfunc-takes-g g))
(struct farg-model-spec* (nodeclasses ancestors) #:prefab)
; nodeclasses: (Immutable-HashTable Any nodeclass*)
; ancestors: (Immutable-HashTable Any (Setof Any))
(define (make-ancestors-table ht-nodeclasses)
(define (all-ancestors-of name)
(let recur ([name name] [result (set)] [already-seen (set name)])
(hash-ref/sk ht-nodeclasses name
(λ (nc)
(let* ([parents (set-subtract (nodeclass*-parents nc) already-seen)]
[result (set-union result parents)]
[already-seen (set-union already-seen parents)])
(if (set-empty? parents)
result
(apply set-union (map
(λ (parent)
(recur parent result already-seen))
(set->list parents))))))
result)))
(for/hash ([name (hash-keys ht-nodeclasses)])
(values name (set-add (all-ancestors-of name) name))))
(define (farg-model-spec . nodeclasses)
(define ht (for/hash ([nodeclass nodeclasses])
(values (nodeclass*-name nodeclass) nodeclass)))
(farg-model-spec* ht (make-ancestors-table ht)))
(define (get-nodeclasses x)
(cond
[(farg-model-spec*? x) (farg-model-spec*-nodeclasses x)]
[(g:graph? x) (get-nodeclasses (g:graph-spec x))]
[else (raise-arguments-error 'get-nodeclasses
@~a{Can't get nodeclasses from @|x|.})]))
(define (get-nodeclass* g x)
(cond
[(nodeclass*? x) x]
[else (let ([nodeclasses (get-nodeclasses g)])
(hash-ref nodeclasses x
(λ () (raise-arguments-error 'get-nodeclass*
@~a{Unknown node class: @|x|.}))))]))
(define (nodeclass*-of g node)
(hash-ref (get-nodeclasses g) (g:class-of g node)))
;TODO Appropriate response if unknown class
(define (get-links-into g node ctx)
(define nc (nodeclass*-of g node))
(define ctx-class (g:class-of g ctx))
(filter (λ (li) (nodeclass-is-a? g (links-into*-ctx-class li) ctx-class))
(nodeclass*-links-intos nc)))
(define as-member (by-ports 'members 'member-of))
(define/g (no-neighbor-at-port? g port-label node)
(null? (g:port->neighbors g `(,node ,port-label))))
(define spec
(farg-model-spec
(nodeclass ws
(is-a 'ctx))
(nodeclass number)
(nodeclass brick
(is-a 'number)
(links-into 'ctx (by-ports 'bricks 'source) as-member))
(tagclass (need source)
(is-a 'problem-tag)
(applies-to ([node (of-class 'number) (by-ports 'tagged 'tags)])
(condition (no-neighbor-at-port?/g 'source node))))
))
(define start-graph (struct-copy g:graph g:empty-graph [spec spec]))
;; Returns two values: g nodeid
(define/g (make-node g classname [value (void)])
(define nodeclass (hash-ref (get-nodeclasses g) classname
(λ ()
(raise-arguments-error 'make-node
@~a{Undefined class name: @|classname|.}))))
(define default-attrs (nodeclass*-default-attrs nodeclass))
(cond
[(void? value)
(g:make-node g default-attrs)]
[else
(g:make-node g (hash-set default-attrs 'value value))]))
;; Returns two values: g nodeid
(define/g (make-node/in g ctx . args)
;TODO Raise error if ctx does not exist
(let-values ([(g node) (apply make-node g args)])
(for*/fold ([g g] #:result (values g node))
([links-into (get-links-into g node ctx)]
[by-ports (links-into*-by-portss links-into)])
(match-define (by-ports* from-port to-port) by-ports) ;TODO OAOO
(g:add-edge g `((,ctx ,from-port) (,node ,to-port))))))
(define/g (link-to g by-portss from-node to-node)
(let* ([by-portss (match by-portss
[(struct* taggee* ([by-portss bps])) bps]
[(struct* links-into* ([by-portss bps])) bps]
[else
(raise-arguments-error 'link-to
@~a{Can't extract by-portss from @|by-portss|.})])])
(for/fold ([g g])
([by-ports by-portss])
(match-define (by-ports* from-port to-port) by-ports)
(g:add-edge g `((,from-node ,from-port) (,to-node ,to-port))))))
(define-syntax-rule (first-value expr)
(call-with-values (λ () expr)
(λ (result . ignored) result)))
(define/g (add-node g . args)
(first-value (apply make-node g args)))
(define/g (add-node/in g . args)
(first-value (apply make-node/in g args)))
(define (possible-taggee? g taggee node)
(for/or ([of-class (taggee*-of-classes taggee)])
(node-is-a? g of-class node)))
(define (all-taggees-could-apply? g applies-to nodes)
(define taggees (applies-to*-taggees applies-to))
(if (not (= (length taggees) (length nodes)))
#f
(for/and ([taggee taggees]
[node nodes])
(possible-taggee? g taggee node))))
;; Returns #f or the applies-to*.
(define (applies-to? g applies-to nodes)
(if (and (all-taggees-could-apply? g applies-to nodes)
(any-matching-condition? g applies-to nodes))
applies-to
#f))
(define (any-matching-condition? g applies-to nodes)
(for/or ([cfunc (applies-to*-conditions applies-to)])
(condition-func-passes? g cfunc nodes)))
(define (first-matching-applies-to g tagclass nodes)
(define nodeclass (get-nodeclass* g tagclass))
(define applies-tos (nodeclass*-applies-tos nodeclass))
(for/or ([applies-to applies-tos])
(applies-to? g applies-to nodes)))
;TODO Make the tag a member of the nodes' least common ctx
;TODO Don't make the tag if it's already there
(define/g (make-tag g tagclass . nodes)
(cond
[(first-matching-applies-to g tagclass nodes)
=> (λ (applies-to)
(let*-values ([(g tag) (make-node g tagclass)])
(for/fold ([g g] #:result (values g tag))
([taggee (applies-to*-taggees applies-to)]
[node nodes])
(link-to g taggee tag node))))]
[else (raise 'fizzle)]))
(define/g (add-tag g tagclass . args)
(first-value (apply make-tag g tagclass args)))
(define (set-intersect* set-or-void . sets)
(cond
[(void? set-or-void)
(apply set-intersect* sets)]
[(null? sets)
set-or-void]
[else (apply set-intersect set-or-void sets)]))
(define (linked-from g taggee-info node)
(let/cc break
(for/fold ([froms (void)] #:result (if (void? froms) empty-set froms))
([by-ports (in-list (taggee*-by-portss taggee-info))])
(match-define (by-ports* from-port to-port) by-ports)
(let ([froms (set-intersect* froms
(g:port->port-label->nodes g
`(,node ,to-port)
from-port))])
(if (set-empty? froms)
(break froms)
froms)))))
(define (linked-from-common-node? g taggees nodes)
(let/cc break
(for/fold ([back-nodes (void)] #:result (not (set-empty? back-nodes)))
([taggee taggees] [node nodes])
(let ([back-nodes (set-intersect* back-nodes
(linked-from g taggee node))])
(if (set-empty? back-nodes)
(break #f)
back-nodes)))))
(define (tagged-with? g tagclass . nodes)
(let ([tagclass (get-nodeclass* g tagclass)])
(for/or ([applies-to (nodeclass*-applies-tos tagclass)])
(linked-from-common-node? g (applies-to*-taggees applies-to) nodes))))
(define g (void))
(set! g (g:add-spec g:empty-graph spec))
; A little hack to make it easier to work on graphs in the REPL.
; (gdo makenode 'ws) operates on a variable in the local context called g,
; set!s g to the new graph, and returns the nodeid of the created node.
(define-syntax (gdo stx)
(syntax-case stx ()
[(gdo gfunc args ...)
(with-syntax ([g (format-id #'gdo "g"
#:source #'gdo #:props #'f)])
#'(call-with-values (λ () (gfunc g args ...))
(λ (new-g . results)
(set! g new-g)
(cond
[(null? results) (void)]
[(null? (cdr results)) (car results)]
[else results]))))]))
(gdo make-node 'ws)
(gdo make-node/in 'ws 'brick 7)
(gdo make-tag '(need source) 'brick7)
(tagged-with? g '(need source) 'brick7)
| true |
c19e3a9178abdd33723ce622cc37fefd3477efc3 | fc69a32687681f5664f33d360f4062915e1ac136 | /test/parser.rkt | 8f530d3c76c0e9fc24a4d279c5f54d2d24b1266a | []
| no_license | tov/dssl2 | 3855905061d270a3b5e0105c45c85b0fb5fe325a | e2d03ea0fff61c5e515ecd4bff88608e0439e32a | refs/heads/main | 2023-07-19T22:22:53.869561 | 2023-07-03T15:18:32 | 2023-07-03T15:18:32 | 93,645,003 | 12 | 6 | null | 2021-05-26T16:04:38 | 2017-06-07T14:31:59 | Racket | UTF-8 | Racket | false | false | 5,835 | rkt | parser.rkt | #lang racket/base
(require "../private/parser.rkt")
(module+ test
(require rackunit)
(define (test-parse str result)
(check-equal? (syntax->datum
(parse-dssl2 #false (open-input-string str) #false))
result))
(define-syntax-rule (check-parse? source body ...)
(test-parse source
'(begin body ...)))
; simple expressions
(check-parse? "a" a)
(check-parse? "5" 5)
(check-parse? "-5E-2"
(- 5E-2))
(check-parse? "v[i]"
(vec-ref v i))
(check-parse? "s.f"
(struct-ref s f))
(check-parse? "[0, 1, 2]"
(vec-lit 0 1 2))
(check-parse? "[0, 1, 2,]"
(vec-lit 0 1 2))
(check-parse? "[0; 10]"
(make-vec 10 0))
(check-parse? "posn { x: 3, y: 4 }"
(|posn{}| [x 3] [y 4]))
(check-parse? "a == 4"
(== a 4))
(check-parse? "lambda x, y: x == y"
(lambda (x y) (== x y)))
(check-parse? "λ x, y: x == y"
(lambda (x y) (== x y)))
(check-parse? "f(3, x)"
(f 3 x))
(check-parse? "\na"
a)
; compound expressions
(check-parse? "a + b * c + d"
(+ (+ a (* b c)) d))
(check-parse? "a ** b ** c"
(** a (** b c)))
(check-parse? "a ** b ** c == 5"
(== (** a (** b c)) 5))
(check-parse? "a + -6"
(+ a (- 6)))
(check-parse? "[5, lambda x: x + 1]"
(vec-lit 5 (lambda (x) (+ x 1))))
(check-parse? "a.b.c"
(struct-ref (struct-ref a b) c))
; simple statements
(check-parse? "a = b"
(= a b))
(check-parse? "a = b; c = d.e"
(= a b)
(= c (struct-ref d e)))
(check-parse? "a = b\nc = d\n"
(= a b)
(= c d))
(check-parse? "let x"
(let x))
(check-parse? "struct posn:\n let x\n let y"
(struct posn (let x) (let y)))
(check-parse? "a.b.c = e[f]"
(= (struct-ref (struct-ref a b) c)
(vec-ref e f)))
(check-parse? "assert False, time < 5"
(assert #f (#:timeout 5)))
(check-parse? "assert False"
(assert #f))
(check-parse? "assert a + 1 == 6"
(assert (== (+ a 1) 6)))
; compound statements
(check-parse? "if a: c = d"
(if [a (= c d)] [else (pass)]))
(check-parse? "if a: c = d\nelse: e = f"
(if [a (= c d)] [else (= e f)]))
(check-parse? "if a: c = d\nelif b: e = 3\nelse: f = 4"
(if [a (= c d)]
[elif b (= e 3)]
[else (= f 4)]))
(check-parse? "if a:\n c = d"
(if [a (= c d)]
[else (pass)]))
(check-parse? "if a:\n c = d\n e[0] = 9"
(if [a (= c d)
(= (vec-ref e 0) 9)]
[else (pass)]))
(check-parse? "if a:\n if b:\n 5"
(if [a (if [b 5]
[else (pass)])]
[else (pass)]))
(check-parse? "while True:\n a = 6\n b = 7"
(while #t (= a 6) (= b 7)))
(check-parse? (string-append "def fact(n):\n"
" if n <= 1: return 1\n"
" else: return n * fact(n - 1)")
(def (fact n)
(if [(<= n 1) (return 1)]
[else (return (* n (fact (- n 1))))])))
(check-parse? (string-append "for j in v:\n"
" println(j)")
(for [j v] (println j)))
(check-parse? (string-append "for i, j in v:\n"
" println(i, j)")
(for [(i j) v] (println i j)))
(check-parse? "def f[X](): True"
(def (f #:forall [X]) #t))
(check-parse? "def f(x: y, z): True"
(def (f [x y] z) #t))
; expressions that contain statements!
(check-parse? "let x = if a:\n 0\nelse:\n let y = 6\n y + 1\n"
(let x (if [a 0]
[else (let y 6) (+ y 1)])))
; trailing newlines
(check-parse? "pass"
(pass))
(check-parse? "pass "
(pass))
(check-parse? "pass \n"
(pass))
(check-parse? "pass\n"
(pass))
(check-parse? "pass\n "
(pass))
(check-parse? "pass\n \n"
(pass))
; line continuations
(check-parse? "let x =\\\n y"
(let x y))
(check-parse? "let x =\\\r\n y"
(let x y))
(check-parse? "let x = (\n y\n)"
(let x y))
; string literals
(check-parse? "'abcde'"
"abcde")
(check-parse? "\"abcde\""
"abcde")
(check-parse? "'ab\"cde'"
"ab\"cde")
(check-parse? "\"ab\\\"cde\""
"ab\"cde")
(check-parse? "'ab\\'cde'"
"ab'cde")
(check-parse? "\"ab'cde\""
"ab'cde")
(check-parse? "\"ab\\'cde\""
"ab'cde")
(check-parse? "'ab\\\ncde'"
"abcde")
(check-parse? "'ab\\\r\ncde'"
"abcde")
(check-parse? "'''ab\ncde'''"
"ab\ncde")
(check-parse? "'''ab\r\ncde'''"
"ab\ncde")
(check-parse? "'''ab\\\ncde'''"
"abcde")
(check-parse? "'''ab\\\r\ncde'''"
"abcde")
(check-parse? "'\\t\\\\t'"
"\t\\t")
(check-parse? "'\1010'"
"A0")
(check-parse? "'\41\041\0041'"
"!!\x041")
(check-parse? "'\419'"
"!9")
(check-parse? "'\790'"
"\a90")
(check-parse? "'\x41'"
"A")
(check-parse? "'\x4e\x4E\x4g\x4G\x420'"
"NN\4g\4GB0"))
| true |
09d237284d079400bb93ef4b37ec0dafa40c06a4 | c161c2096ff80424ef06d144dacdb0fc23e25635 | /chapter4/exercise/ex4.44.rkt | 7358960f56086f8da27c7a22de792a807d27c673 | []
| no_license | tangshipoetry/SICP | f674e4be44dfe905da4a8fc938b0f0460e061dc8 | fae33da93746c3f1fc92e4d22ccbc1153cce6ac9 | refs/heads/master | 2020-03-10T06:55:29.711600 | 2018-07-16T00:17:08 | 2018-07-16T00:17:08 | 129,242,982 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 3,276 | rkt | ex4.44.rkt | #lang racket
;网上的
#|
; 本题和 2.42 表示方法一样,用一个list表示一种解法,比如四皇后问题,解法(A B C D)表示,第一个皇后在位置A,第二个皇后在位置B,第三个皇后在位置C,第四个皇后在位置D,用list的位置表示了皇后的次序。
; https://github.com/jiacai2050/sicp/blob/master/exercises/02/2.42_2.43.md#242
(define (check-current-diagonal? current-postion rest distance-to-current)
(if (null? rest)
#f
(or (= (- current-postion distance-to-current) (car rest))
(= (+ current-postion distance-to-current) (car rest))
(check-current-diagonal? current-postion (cdr rest) (+ distance-to-current 1)))))
(define (in-diagonal? positions)
(if (null? positions)
#f
(or (in-diagonal (car positions) (cdr positions) 1)
(in-diagonal? (cdr positions)))))
(define (collide? positions)
(or (not (distinct? positions))
(in-diagonal? positions)))
(define (eight-queen)
(let ((q1 (amb 1 2 3 4 5 6 7 8))
(q2 (amb 1 2 3 4 5 6 7 8))
(q3 (amb 1 2 3 4 5 6 7 8))
(q4 (amb 1 2 3 4 5 6 7 8))
(q5 (amb 1 2 3 4 5 6 7 8))
(q6 (amb 1 2 3 4 5 6 7 8))
(q7 (amb 1 2 3 4 5 6 7 8))
(q8 (amb 1 2 3 4 5 6 7 8)))
(require (not (collide? (list q1 q2 q3 q4 q5 q6 q7 q8))))))
|#
;;
(define (vulnerable? queen1-position queen2-position column-separation)
(let ((row-separation (abs (- queen1-position queen2-position))))
(or (= row-separation 0)
(= row-separation column-separation))))
;; first element of previous-queens is the position of the queen
;; in the column immediately adjacent to next-queen
(define (next-queen-vulnerable? next-queen previous-queens)
(define (iter prev-qs column-separation)
(if (null? prev-qs)
false
(or (vulnerable? next-queen (car prev-qs) column-separation)
(iter (cdr prev-qs) (1+ column-separation)))))
(iter previous-queens 1))
;; use let* even though bindings are independent in order to guarantee efficient nesting with respect to amb.
(define (eight-queens)
(define (nnqv? next-queen previous-queens)
(not (next-queen-vulnerable? next-queen previous-queens)))
(let* ((prev0 '())
(q1 (amb 1 2 3 4 5 6 7 8)))
(require (nnqv? q1 prev0)) ;; trivially never fails
(let* ((prev1 (cons q1 prev0))
(q2 (amb 1 2 3 4 5 6 7 8)))
(require (nnqv? q2 prev1))
(let* ((prev2 (cons q2 prev1))
(q3 (amb 1 2 3 4 5 6 7 8)))
(require (nnqv? q3 prev2))
(let* ((prev3 (cons q3 prev2))
(q4 (amb 1 2 3 4 5 6 7 8)))
(require (nnqv? q4 prev3))
(let* ((prev4 (cons q4 prev3))
(q5 (amb 1 2 3 4 5 6 7 8)))
(require (nnqv? q5 prev4))
(let* ((prev5 (cons q5 prev4))
(q6 (amb 1 2 3 4 5 6 7 8)))
(require (nnqv? q6 prev5))
(let* ((prev6 (cons q6 prev5))
(q7 (amb 1 2 3 4 5 6 7 8)))
(require (nnqv? q7 prev6))
(let* ((prev7 (cons q7 prev6))
(q8 (amb 1 2 3 4 5 6 7 8)))
(require (nnqv? q8 prev7))
(cons q8 prev7))))))))))
| false |
352b165b8a24ea15cbaadc4f00b6431a53c061d8 | 4919215f2fe595838a86d14926c10717f69784e4 | /lessons/onscreen2/worksheets/Design-Recipe-Onscreen.scrbl | 42fb62d235062271d46c1336170735d706e44c8b | []
| 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 | 1,737 | scrbl | Design-Recipe-Onscreen.scrbl | #lang curr/lib
@title{onscreen?}
@worksheet{
@design-recipe-exercise["onscreen?" "Use the Design Recipe to write a function " @code{onscreen?} ", which takes in the target's x-coordinate and checks to see Sam is safe on the left and the right."]
}
@;@worksheet{
@; Use the Design Recipe to write a function onscreen?, which takes in the target's x-coordinate and checks to see Sam is safe on the left and on the right
@; @worksheet-segment{I. Contract + Purpose Statement}
@; Every contract has three parts:
@; @contract-exercise["51" #:name "onscreen?" #:domain "number" #:range "boolean"]
@; ;@fill-in-the-blank[#:id "what does the function do?" #:label "Purpose" #:answer "Takes in the x-coordinate and checks if target is protected on the left and the right"]
@; @worksheet-segment{II. Give Examples}
@; Write two examples of your function in action
@; @example-with-text[#:text1 "use the function here"
@; #:text2 "find another way to get the same result here"
@; "onscreen-1"
@; #:example1 "onscreen? 900"
@; #:example2 "(and (safe-left 900) (safe-right 900))"]
@; @example-with-text[#:text1 "use the function here"
@; #:text2 "find another way to get the same result here"
@; "onscreen-2"
@; #:example1 "onscreen? 355"
@; #:example2 "(and (safe-left 355) (safe-right 355))"]
@; @worksheet-segment{III. Function Header}
@; Write the function Header, giving variable names to all your input values.
@; @function-exercise["onscreen?" #:name "onscreen?" #:args "x" #:body "(and (safe-left x) (safe-right x))"]} | false |
13ee0e91d747def7971429de60c30080b6034a78 | 49bef55e6e2ce9d3e64e55e71496be8f4fc7f4f3 | /rb/sections/morris-lecar.scrbl | 78ceb91581c6be32d497aa36e7d2442b8051f595 | []
| no_license | brittAnderson/compNeuroIntro420 | 13dad04726c1bf3b75a494bc221c0c56f52a060f | ad4211f433c22f647b1bf2e30561106178b777ab | refs/heads/racket-book | 2023-08-10T18:34:48.611363 | 2023-07-28T15:59:50 | 2023-07-28T15:59:50 | 78,282,622 | 26 | 97 | null | 2023-07-22T19:50:59 | 2017-01-07T14:10:01 | JavaScript | UTF-8 | Racket | false | false | 1,018 | scrbl | morris-lecar.scrbl | #lang scribble/book
@(require plot/pict
scribble/base
scribble-math/dollar
scribble/example
scribble/manual
symalg
scriblib/figure
scribble/core
scribble/html-properties
"./../code/refs.rkt")
@(define plot-eval
(let ([eval (make-base-eval)])
(eval '(begin
(require racket/math
racket/match
racket/list
racket/draw
racket/class
plot/pict
plot/utils)))
eval))
@title{Morris Lecar Model}
@section{Work in Progress}
This section is a work in progress.
I want to discuss the benefits of simplifying models as well as show the use of direction plots and phase space diagrams.
At the moment I have working racket code, but I have not written up this section yet. I am adding this section now (Oct 2022) to have a way to make the @hyperlink["./../code/morris-lecar.rkt"]{code} discoverable.
| false |
79bb7d8eeb2f35b5bc50b5986fb980a5396d8937 | 6377f02394723c3a02b54f2f863f4da4ac1cef76 | /ProgrammingLanguages/a13.rkt | 7b4ed6c22c3e84645d767689ab4c6c8ba99adc7c | []
| no_license | curt-is-devine/school | f8a1eafb1a5f599d45c4dab07643df75f63491c4 | a15b0eb064a604b7b856021d5681616241e8df8e | refs/heads/master | 2020-07-18T05:40:24.343580 | 2019-09-03T23:55:06 | 2019-09-03T23:55:06 | 206,188,650 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,968 | rkt | a13.rkt | #lang racket
(require "monads.rkt")
(define return-maybe
(lambda (a)
`(Just ,a)))
(define fail
(lambda ()
'(Nothing)))
(define findf-maybe
(lambda (p l)
(cond
[(null? l) (fail)]
[else (if (p (car l)) (return-maybe (car l))
(findf-maybe p (cdr l)))])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define return-writer
(lambda (a)
`(,a . ())))
(define bind-writer
(lambda (ma f)
(let ((mb (f (car ma))))
`(,(car mb) . ,(append (cdr ma) (cdr mb))))))
(define tell-writer
(lambda (to-writer)
`(_ . (,to-writer))))
(define partition-writer
(lambda (p l)
(cond
[(null? l) (return-writer `())]
[(not (p (car l))) (bind-writer
(partition-writer p (cdr l))
(lambda (d)
(return-writer (cons (car l) d))))]
[else
(bind-writer
(tell-writer (car l))
(lambda (_)
(partition-writer p (cdr l))))])))
(define powerXpartials
(lambda (b e)
(cond
[(zero? e) (return-writer 1)]
[(equal? e 1) (return-writer b)]
[(odd? e) (bind-writer (powerXpartials b (sub1 e))
(lambda (o)
(bind-writer (tell-writer o)
(lambda (_)
(return-writer (* b o))))))]
[(even? e) (bind-writer (powerXpartials b (/ e 2))
(lambda (o)
(bind-writer (tell-writer o)
(lambda (_)
(return-writer (* o o))))))])))
(powerXpartials 2 4)
;I cannot get the order of this right
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define return-state
(lambda (a)
(lambda (s)
`(,a . ,s))))
(define bind-state
(lambda (ma f)
(lambda (s)
(let ([vs^ (ma s)])
(let ([v (car vs^)]
[s^ (cdr vs^)])
((f v) s^))))))
(define get-state
(lambda (s) `(,s . ,s)))
(define put-state
(lambda (new-s)
(lambda (s)
`(__ . ,new-s))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define traverse
(lambda (inj bind f)
(letrec
((trav
(lambda (tree)
(cond
[(pair? tree)
(go-on
(a <- (trav (car tree)))
(d <- (trav (cdr tree)))
(inj (cons a d)))]
[else (f tree)]))))
trav)))
(define reciprocal
(lambda (n)
(cond
[(zero? n) (fail)]
[else (return-maybe (/ 1 n))])))
(define traverse-reciprocal
(traverse return-maybe bind-maybe reciprocal))
;(traverse-reciprocal '((1 . 2) . (3 . (4 . 5))))
;I keep getting the error "a is not a monad" but this code is provided by the web page? | false |
af5e006895044896b3cb249a953ed3af638a34bb | 4a1a0f5977069d1130d4b8cd020f6914bd666885 | /scheme04/scheme4.rkt | 3860793b59bc0e1c56963545a439f7c3485b7f80 | []
| no_license | mutsune/FirstScheme | 01d8432f83e7e6c86d382cd2cd7219ad997bb4a9 | 619c287eb3f26466ccfffb4d438f75c2a90931e0 | refs/heads/master | 2016-09-06T04:01:21.823620 | 2013-01-01T08:43:12 | 2013-01-01T08:43:12 | 7,271,314 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 408 | rkt | scheme4.rkt | ; ex1.1
(define (inc x)
(+ x 1))
; ex1.2
(define (dec x)
(- x 1))
; ex2.1
(define pi (* 4 (atan 1.0)))
; ex2.2
(define g 9.8)
(define (movedis vx t)
(* vx t))
; ex2.3
(define (falltime vy)
(/ vy g))
(define (upcast vy)
(* (falltime vy) 2))
; ex2.4
(define (rad theta)
(* (/ theta 180)
pi))
(define (castdis v theta)
(movedis (* v (cos (rad theta))) (upcast (* v (sin (rad theta))))))
| false |
15cf01bbb18827bcd3f713d2e951d955adbd729b | a23dfa31096fd6bc437bf692b12e3761173772b8 | /assembler.rkt | 64747dcebea6c22d410de1e0312f4de128756eec | [
"MIT"
]
| permissive | akuhlens/assembler | 70ac52418148f4901e8f6f311b21c872e2436216 | 5025fecb321e370deb83e0a4e93edf63dd2b8f88 | refs/heads/master | 2021-01-10T14:23:07.280087 | 2016-03-07T16:13:37 | 2016-03-07T16:13:37 | 53,331,279 | 4 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,911 | rkt | assembler.rkt | #lang racket/base
(require (for-syntax racket/base racket/syntax))
;; We want to generate a fast translation
;; from `(op args ...) to (bytes b0 ... bn)
;; We would like to specify this syntax like so
#;(define-instruction-table x86-64-instruction-table)
#;(add-intruction x86-64-instruction-table
[(ADD AL imm8) (x86-64-opcode 04 ib)]
[(ADD r64 r/m64) (x86-64-opcode REX.W + 03 /r)])
#;(add-instruction x86-64-instruction-table
[(MOV moffs64 RAX) ...]
[(MOV r64 imm64) ...]
[(MOV r64 r/m64) (x86-64-opcode REX.W + 89 /r)])
;; one can immagine that the a single clause works
;; [(MOV moffs64,RAX) ;;arbitrary-code to handle special cases]
;; [(MOV r64, imm64) ;; appropriate code here]
;; [(MOV r64, r/m64) (x86-64-opcode REX.W + 89 /r)])
#;(define (encode-MOV a1 a2)
(cond
[(reg64? a1)
(let ([reg a1])
(cond
[(imm64? a2) #|code for opcode|#]
[(reg64? a2) #|code for opcode|#]
[else (error 'encode-mov "undefined for arg 2 = ~a")]))]
[(moffs64? a1) #|code for arg 2 subcases |# ]
[else (error 'encode-mov "(MOV ~a ~a)" a1 a2)]))
;; One lingering problem is how to efficiently transfer information
;; from the argument types to the opcodes in order to efficiently
;; encode information
;; Instruction-Map Symbol (U Index #f) Proc? -> (Void)
(define (add-instruction-encoder! table name arity encoder)
(unless (and (hash? table)
(symbol? name)
(fixnum? arity)
(procedure? encoder))
(error 'add-instruction-encoder!))
(hash-set! table name (cons arity encoder)))
(define (encode-instruction itable instr)
(when (null? instr)
(error 'encode-instruction "given null"))
(define memn (car instr))
(define a.e? (hash-ref itable memn #f))
(unless (pair? a.e?)
(error 'encode-instruction "memnomic not found ~a" instr))
(define arity (car a.e?))
(define encoder (cdr a.e?))
(unless (procedure? encoder)
(error 'encode-instruction "This shouldn't happen"))
(cond
[(eq? arity 0) (encoder)]
[(eq? arity 1) (static-apply encoder 1 (cdr instr))]
[(eq? arity 2) (static-apply encoder 2 (cdr instr))]
[(eq? arity 3) (static-apply encoder 3 (cdr instr))]
[(not arity) (apply encoder (cdr instr))]
[else (error 'encode-instruction "bad arity ~a" arity)]))
(define-syntax (static-apply s)
(syntax-case s ()
[(_ p n a*) #'(apply p a*)]))
(define-syntax (add-instruction stx)
(syntax-case stx ()
[(_ (name table x a) [(n p ...) e** ...] ...)
(with-syntax ([encode-name
(format-id #'name "encode-~a" (syntax-e #'name))])
#'(begin
(define (encode-name x a)
(match x
[`(,_ p ...) e** ...] ...
[otherwise (error 'encode-name "~a" x)]))
(add-instruction-encoder! table 'name (cons #f encode-name))))]))
| true |
d03190442cda1f9982b62401fc332ef2ba0db89d | 1c2209c90f3a026361465e9e7d7a291394a77fc6 | /sxml/ssax/SXML-tree-trans.rkt | 2fb050a7bd38a39157f4153aef5e2ddc3ef53d62 | []
| no_license | jbclements/sxml | 2c1d1b06cdf40187c2141d47ae472ad2708cd456 | 5d1d65561b7bf5059456934c34a5c5f257de4416 | refs/heads/master | 2023-03-11T23:57:19.065847 | 2023-03-03T05:56:52 | 2023-03-03T05:56:52 | 1,371,026 | 30 | 10 | null | 2023-03-03T05:56:53 | 2011-02-15T20:23:20 | Racket | UTF-8 | Racket | false | false | 10,788 | rkt | SXML-tree-trans.rkt | #lang racket/base
(require "myenv.ss")
(provide post-order
pre-post-order
SRV:send-reply
replace-range)
; XML/HTML processing in Scheme
; SXML expression tree transformers
;
; IMPORT
; A prelude appropriate for your Scheme system
; (myenv-bigloo.scm, myenv-mit.scm, etc.)
;
; EXPORT
; (provide SRV:send-reply
; post-order pre-post-order replace-range)
;
; See vSXML-tree-trans.scm for the validation code, which also
; serves as usage examples.
;
; $Id: SXML-tree-trans.scm,v 1.7 2004/11/09 20:22:26 sperber Exp $
; procedure: SRV:send-reply FRAGMENT ...
;
; Output the 'fragments'
; The fragments are a list of strings, characters,
; numbers, thunks, #f, #t -- and other fragments.
; The function traverses the tree depth-first, writes out
; strings and characters, executes thunks, and ignores
; #f and '().
; The function returns #t if anything was written at all;
; otherwise the result is #f
; If #t occurs among the fragments, it is not written out
; but causes the result of SRV:send-reply to be #t
(define (SRV:send-reply . fragments)
(let loop ((fragments fragments) (result #f))
(cond
((null? fragments) result)
((not (car fragments)) (loop (cdr fragments) result))
((null? (car fragments)) (loop (cdr fragments) result))
((eq? #t (car fragments)) (loop (cdr fragments) #t))
((pair? (car fragments))
(loop (cdr fragments) (loop (car fragments) result)))
((procedure? (car fragments))
((car fragments))
(loop (cdr fragments) #t))
(else
(display (car fragments))
(loop (cdr fragments) #t)))))
; procedure: pre-post-order TREE BINDINGS
;
; Traversal of an SXML tree or a grove:
; a <Node> or a <Nodelist>
;
; A <Node> and a <Nodelist> are mutually-recursive datatypes that
; underlie the SXML tree:
; <Node> ::= (name . <Nodelist>) | "text string"
; An (ordered) set of nodes is just a list of the constituent nodes:
; <Nodelist> ::= (<Node> ...)
; Nodelists, and Nodes other than text strings are both lists. A
; <Nodelist> however is either an empty list, or a list whose head is
; not a symbol (an atom in general). A symbol at the head of a node is
; either an XML name (in which case it's a tag of an XML element), or
; an administrative name such as '@'.
; See SXPath.scm and SSAX.scm for more information on SXML.
;
;
; Pre-Post-order traversal of a tree and creation of a new tree:
; pre-post-order:: <tree> x <bindings> -> <new-tree>
; where
; <bindings> ::= (<binding> ...)
; <binding> ::= (<trigger-symbol> *preorder* . <handler>) |
; (<trigger-symbol> *macro* . <handler>) |
; (<trigger-symbol> <new-bindings> . <handler>) |
; (<trigger-symbol> . <handler>)
; <trigger-symbol> ::= XMLname | *text* | *default*
; <handler> :: <trigger-symbol> x [<tree>] -> <new-tree>
;
; The pre-post-order function visits the nodes and nodelists
; pre-post-order (depth-first). For each <Node> of the form (name
; <Node> ...) it looks up an association with the given 'name' among
; its <bindings>. If failed, pre-post-order tries to locate a
; *default* binding. It's an error if the latter attempt fails as
; well. Having found a binding, the pre-post-order function first
; checks to see if the binding is of the form
; (<trigger-symbol> *preorder* . <handler>)
; If it is, the handler is 'applied' to the current node. Otherwise,
; the pre-post-order function first calls itself recursively for each
; child of the current node, with <new-bindings> prepended to the
; <bindings> in effect. The result of these calls is passed to the
; <handler> (along with the head of the current <Node>). To be more
; precise, the handler is _applied_ to the head of the current node
; and its processed children. The result of the handler, which should
; also be a <tree>, replaces the current <Node>. If the current <Node>
; is a text string or other atom, a special binding with a symbol
; *text* is looked up.
;
; A binding can also be of a form
; (<trigger-symbol> *macro* . <handler>)
; This is equivalent to *preorder* described above. However, the result
; is re-processed again, with the current stylesheet.
;
(define (pre-post-order tree bindings)
(let* ((default-binding (assq '*default* bindings))
(text-binding (or (assq '*text* bindings) default-binding))
(text-handler ; Cache default and text bindings
(and text-binding
(if (procedure? (cdr text-binding))
(cdr text-binding) (cddr text-binding)))))
(let loop ((tree tree))
(cond
((null? tree) '())
((not (pair? tree))
(let ((trigger '*text*))
(if text-handler (text-handler trigger tree)
(myenv:error "Unknown binding for " trigger " and no default"))))
((not (symbol? (car tree))) (map loop tree)) ; tree is a nodelist
(else ; tree is an SXML node
(let* ((trigger (car tree))
(binding (or (assq trigger bindings) default-binding)))
(cond
((not binding)
(myenv:error "Unknown binding for " trigger " and no default"))
((not (pair? (cdr binding))) ; must be a procedure: handler
(apply (cdr binding) trigger (map loop (cdr tree))))
((eq? '*preorder* (cadr binding))
(apply (cddr binding) tree))
((eq? '*macro* (cadr binding))
(loop (apply (cddr binding) tree)))
(else ; (cadr binding) is a local binding
(apply (cddr binding) trigger
(pre-post-order (cdr tree) (append (cadr binding) bindings)))
))))))))
; procedure: post-order TREE BINDINGS
; post-order is a strict subset of pre-post-order without *preorder*
; (let alone *macro*) traversals.
; Now pre-post-order is actually faster than the old post-order.
; The function post-order is deprecated and is aliased below for
; backward compatibility.
(define post-order pre-post-order)
;------------------------------------------------------------------------
; Extended tree fold
; tree = atom | (node-name tree ...)
;
; foldts fdown fup fhere seed (Leaf str) = fhere seed str
; foldts fdown fup fhere seed (Nd kids) =
; fup seed $ foldl (foldts fdown fup fhere) (fdown seed) kids
; procedure fhere: seed -> atom -> seed
; procedure fdown: seed -> node -> seed
; procedure fup: parent-seed -> last-kid-seed -> node -> seed
; foldts returns the final seed
(define (foldts fdown fup fhere seed tree)
(cond
((null? tree) seed)
((not (pair? tree)) ; An atom
(fhere seed tree))
(else
(let loop ((kid-seed (fdown seed tree)) (kids (cdr tree)))
(if (null? kids)
(fup seed kid-seed tree)
(loop (foldts fdown fup fhere kid-seed (car kids))
(cdr kids)))))))
; procedure: replace-range:: BEG-PRED x END-PRED x FOREST -> FOREST
; Traverse a forest depth-first and cut/replace ranges of nodes.
;
; The nodes that define a range don't have to have the same immediate
; parent, don't have to be on the same level, and the end node of a
; range doesn't even have to exist. A replace-range procedure removes
; nodes from the beginning node of the range up to (but not including)
; the end node of the range. In addition, the beginning node of the
; range can be replaced by a node or a list of nodes. The range of
; nodes is cut while depth-first traversing the forest. If all
; branches of the node are cut a node is cut as well. The procedure
; can cut several non-overlapping ranges from a forest.
; replace-range:: BEG-PRED x END-PRED x FOREST -> FOREST
; where
; type FOREST = (NODE ...)
; type NODE = Atom | (Name . FOREST) | FOREST
;
; The range of nodes is specified by two predicates, beg-pred and end-pred.
; beg-pred:: NODE -> #f | FOREST
; end-pred:: NODE -> #f | FOREST
; The beg-pred predicate decides on the beginning of the range. The node
; for which the predicate yields non-#f marks the beginning of the range
; The non-#f value of the predicate replaces the node. The value can be a
; list of nodes. The replace-range procedure then traverses the tree and skips
; all the nodes, until the end-pred yields non-#f. The value of the end-pred
; replaces the end-range node. The new end node and its brothers will be
; re-scanned.
; The predicates are evaluated pre-order. We do not descend into a node that
; is marked as the beginning of the range.
(define (replace-range beg-pred end-pred forest)
; loop forest keep? new-forest
; forest is the forest to traverse
; new-forest accumulates the nodes we will keep, in the reverse
; order
; If keep? is #t, keep the curr node if atomic. If the node is not atomic,
; traverse its children and keep those that are not in the skip range.
; If keep? is #f, skip the current node if atomic. Otherwise,
; traverse its children. If all children are skipped, skip the node
; as well.
(define (loop forest keep? new-forest)
(if (null? forest) (values (reverse new-forest) keep?)
(let ((node (car forest)))
(if keep?
(cond ; accumulate mode
((beg-pred node) => ; see if the node starts the skip range
(lambda (repl-branches) ; if so, skip/replace the node
(loop (cdr forest) #f
(append (reverse repl-branches) new-forest))))
((not (pair? node)) ; it's an atom, keep it
(loop (cdr forest) keep? (cons node new-forest)))
(else
(let ((node?
(symbol? (car node)))) ; or is it a nodelist?
(call-with-values
; traverse its children
(lambda () (loop (if node? (cdr node) node) #t '()))
(lambda (new-kids keep?)
(loop (cdr forest) keep?
(cons
(if node? (cons (car node) new-kids) new-kids)
new-forest)))))))
; skip mode
(cond
((end-pred node) => ; end the skip range
(lambda (repl-branches) ; repl-branches will be re-scanned
(loop (append repl-branches (cdr forest)) #t
new-forest)))
((not (pair? node)) ; it's an atom, skip it
(loop (cdr forest) keep? new-forest))
(else
(let ((node?
(symbol? (car node)))) ; or is it a nodelist?
; traverse its children
(call-with-values
(lambda () (loop (if node? (cdr node) node) #f '()))
(lambda (new-kids keep?)
(loop
(cdr forest) keep?
(if (or keep? (pair? new-kids))
(cons
(if node? (cons (car node) new-kids) new-kids)
new-forest)
new-forest) ; if all kids are skipped
)))))))))) ; skip the node too
(call-with-values
(lambda () (loop forest #t '()))
(lambda (new-forest keep?)
new-forest)))
| false |
ff6418e29f5e7c03c28ce17d810f5a3a4b026566 | d0815b834f03a1fa9b4833b4dcaaa5fab0088fe6 | /app-name-here/config.rkt | 8946e9154a57b1e58d1a9b23a7f70c3d25e075eb | [
"BSD-3-Clause"
]
| permissive | Bogdanp/racket-webapp-template | 4da21c20e77641a86fccbf1ab1353167b069786c | 83bc1b9cb62783d54882f823b7c6a9fe8ad41d3b | refs/heads/master | 2020-04-18T09:34:19.556012 | 2019-06-02T10:35:05 | 2019-06-02T10:35:05 | 167,438,891 | 2 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,238 | rkt | config.rkt | #lang racket/base
(require (for-syntax racket/base
syntax/parse)
racket/string
web-server/http/id-cookie)
(define (symbol->option-name s)
(string-append "APP_NAME_HERE_" (string-replace (string-upcase (symbol->string s)) "-" "_")))
(define-syntax (define-option stx)
(syntax-parse stx
[(_ {name:id}) #'(define-option {name #f})]
[(_ {name:id} e:expr ...+) #'(define-option {name #f} e ...)]
[(_ {name:id default:expr}) #'(define-option {name default} name)]
[(_ {name:id default:expr} e:expr ...+)
#'(begin
(define name
(let ([name (or (getenv (symbol->option-name 'name)) default)])
e ...))
(provide name))]))
(define-option {version "dev"})
(define-option {debug}
(equal? debug "x"))
(define-option {profile #f}
(equal? profile "x"))
(define-option {log-level "info"}
(string->symbol log-level))
(define-option {http-host "127.0.0.1"})
(define-option {http-port "8000"}
(string->number http-port))
(define-option {url-scheme "http"})
(define-option {url-host "127.0.0.1"})
(define-option {url-port "8000"})
(define-option {db-name "app_name_here"})
(define-option {db-username "app_name_here"})
(define-option {db-password "app_name_here"})
(define-option {db-host "127.0.0.1"})
(define-option {db-port "5432"}
(string->number db-port))
(define-option {test-db-name "app_name_here_tests"})
(define-option {test-db-username "app_name_here"})
(define-option {test-db-password "app_name_here"})
(define-option {test-db-host "127.0.0.1"})
(define-option {test-db-port "5432"}
(string->number test-db-port))
(define-option {session-cookie-name "_sid"})
(define-option {session-shelf-life "86400"}
(string->number session-shelf-life))
(define-option {session-secret-key-path "/tmp/app-name-here-secret-key"})
(define-option {session-secret-key #f}
(or session-secret-key (make-secret-salt/file session-secret-key-path)))
(define-option {postmark-token #f})
(define-option {product-name "AppNameHere"})
(define-option {company-name "AppNameHere"})
(define-option {company-address ""})
(define-option {support-name "Bot Botterson"})
(define-option {support-email "[email protected]"})
| true |
f2914042dbdbe33d46be03085eebaa0246bfc6fd | 71d714f2e20fec3a2d1cad13a49c4bebf7250900 | /cene-lib/private/shim.rkt | fa28542c7c1c3b6527b9baa76750b9724498cf01 | [
"Apache-2.0"
]
| permissive | era-platform/cene-for-racket | 050da592797977026c0cf0c6eaf03e633f75198f | b1b9235a3e6d8ae978d2666a7eae0f32c8f5982a | refs/heads/main | 2022-10-28T22:43:15.043355 | 2022-10-10T04:56:38 | 2022-10-10T04:56:38 | 139,305,451 | 8 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,885 | rkt | shim.rkt | #lang parendown/slash racket/base
; shim.rkt
;
; Import lists, debugging constants, and other utilities that are
; useful primarily for this codebase.
; Copyright 2022 The Era 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.
(require /for-syntax /only-in syntax/parse ~optional ~seq this-syntax)
(require /only-in reprovide/reprovide reprovide)
(require /only-in lathe-comforts/own-contract
define-own-contract-policies)
(reprovide cene/private/codebasewide-requires)
(provide
(for-syntax
suppressing-external-contracts?
activating-internal-contracts?)
init-shim)
; Should be `#f` unless we're debugging to determine if contracts are
; a performance bottleneck.
;
(define-for-syntax suppressing-external-contracts? #f)
; Should be `#f` unless we're debugging this library's internal call
; graph.
;
(define-for-syntax activating-internal-contracts? #f)
(define-syntax-parse-rule
(init-shim
{~optional {~seq #:antecedent-land antecedent-land}
#:defaults ([antecedent-land (datum->syntax this-syntax '())])})
#:with result
#`(define-own-contract-policies #:antecedent-land antecedent-land
#:suppressing-external-contracts?
#,(datum->syntax #'() suppressing-external-contracts?)
#:activating-internal-contracts?
#,(datum->syntax #'() activating-internal-contracts?))
result)
| true |
3d746124b3eaaf116e13841ac92f9ea668975f6e | ce8eb376b2604be604ade81763626687faddcf0e | /rewindable-streams.rkt | 96da04b97b65a5cffc4e55bec0f4be1887ff1874 | []
| no_license | david-christiansen/pudding | 7bd9a6ca56020ecb57e7e114a111df7562a1dd6d | ead4e1a2e8e0d77a884211adcc4466edcf65e406 | refs/heads/master | 2020-05-20T06:04:24.558940 | 2017-09-12T20:57:37 | 2017-09-12T20:57:37 | 51,451,910 | 29 | 3 | null | 2016-08-20T17:05:15 | 2016-02-10T15:58:37 | Racket | UTF-8 | Racket | false | false | 2,025 | rkt | rewindable-streams.rkt | #lang racket/base
(require racket/contract)
(provide make-rstream list->rstream rstream-forever
rstream-next
rstream-snapshot rstream-rewind!)
(module+ test
(require rackunit))
(struct rstream (contents))
(define the-streams (box (make-weak-hasheq)))
(define/contract (make-rstream contents)
(-> (-> exact-nonnegative-integer? any/c) rstream?)
(define s (rstream contents))
(hash-set! (unbox the-streams) s 0)
s)
(define (rstream-next s)
(define pos (hash-ref (unbox the-streams) s))
(hash-set! (unbox the-streams) s (add1 pos) )
((rstream-contents s) pos))
(define (rstream-snapshot)
(hash-copy (unbox the-streams)))
(define (rstream-rewind! snapshot)
(for ([(s pos) (in-hash snapshot)])
(hash-set! (unbox the-streams) s pos)))
(define (rstream-forever x)
(make-rstream (lambda (i) x)))
(define (list->rstream xs (default #f))
(define l (length xs))
(make-rstream (lambda (i)
(if (< i l)
(list-ref xs i)
default))))
(module+ test
(define nums (list 1 2 3 4 5))
(define num-stream (list->rstream nums))
(check-equal? (rstream-next num-stream) 1)
(check-equal? (rstream-next num-stream) 2)
(check-equal? (rstream-next num-stream) 3)
(define s (rstream-snapshot))
(check-equal? (rstream-next num-stream) 4)
(check-equal? (rstream-next num-stream) 5)
(check-equal? (rstream-next num-stream) #f)
(check-equal? (rstream-next num-stream) #f)
(check-equal? (rstream-next num-stream) #f)
(rstream-rewind! s)
(check-equal? (rstream-next num-stream) 4)
(check-equal? (rstream-next num-stream) 5)
(check-equal? (rstream-next num-stream) #f)
(check-equal? (rstream-next num-stream) #f)
(check-equal? (rstream-next num-stream) #f)
(rstream-rewind! s)
(check-equal? (rstream-next num-stream) 4)
(check-equal? (rstream-next num-stream) 5)
(check-equal? (rstream-next num-stream) #f)
(check-equal? (rstream-next num-stream) #f)
(check-equal? (rstream-next num-stream) #f))
| false |
cbc1ffe5f43c9837892e84f84b8e00064c2df352 | 6071e11de198415ad1e562e0bf9e3685d078074e | /parser-display.rkt | 248a556d1946126dea5e7534e9cd60533c72d6d0 | []
| no_license | jpverkamp/abc | cb6f6d9b10773ec98ea3cfbb199bd0aa020f9b32 | 7e9936e3cee6dccaf85518de5a9a20c4d32e55c4 | refs/heads/master | 2021-01-23T00:15:53.528088 | 2013-11-12T08:05:31 | 2013-11-12T08:05:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 6,460 | rkt | parser-display.rkt | #lang racket
(require
"tokens.rkt")
(provide
abc-parse
(struct-out song)
(struct-out meter)
(struct-out key)
(struct-out staff)
(struct-out measure)
(struct-out note))
(define (snoc x ls) (append ls (list x)))
; An ABC song
(struct song
(name ; From the T: header
headers ; Any headers not otherwise parsed
staffs ; Each staff in printed or instrument in played
) #:transparent #:mutable)
; A single staff of music, should represent an entire song
(struct staff
(which ; Treble, bass, etc.
measures ; First measure (they form a linked list)
) #:transparent #:mutable)
; A measure is a sequential collection of notes
; Meter and key are originally set by headers but can be reset by inline fields
(struct measure
(meter ; Time sig for measure, #f to use song default
key ; Key sig for measure, #f to use song default
notes ; Ordered list of notes / rests in this measure
next ; Measures form a linked list (can be used to implement repeats)
; - A measure is simple case, list for first/second/third time through
) #:transparent #:mutable)
; Meter / time signature
(struct meter
(beats ; How many notes are in a measure
1-beat ; Which note is a beat (4 = quarter, so 1/n)
) #:transparent #:mutable)
; Key signature
(struct key
(base ; Base note for the key (C-B, ex: G)
type ; Type of key (major, minor, etc)
sharps ; List of notes that are sharp (C-B)
flats ; List of flats
) #:transparent #:mutable)
; A note has information to either print it or play it
(struct note
(pitch ; C-B (starting at middle C), z, or Z (z is a rest)
duration ; Normalized to whole notes, 1 is whole, 1/4 is quarter, etc.
accident ; Printed accidental on this note (^, ^^, _, __, =, #f)
octave ; 0 is middle C up to B, +-n for other octaves
1/2steps ; Half steps on a normal 88 key keyboard
) #:transparent #:mutable)
; Record initial meter / key so we can add them to the measures
; Also other state variables like note length
(define current-meter (make-parameter (meter 4 4)))
(define current-key (make-parameter (key 'C 'Maj 0 0)))
(define current-length (make-parameter 1/8))
; Record the current measure a repeat would go to
(define current-repeat-start (make-parameter #f))
; Parse a lexed series of tokens into an ABC song
(define (abc-parse tokens)
; Start with an empty song
(define new-song
(song #f (make-hash) '()))
; (Re)set parameter defaults
(current-meter (meter 4 4))
(current-key (key 'C 'Maj 0 0))
(current-length 1/8)
(current-repeat-start #f)
; Read initial headers
(set! tokens
(let loop ([tokens tokens])
(match tokens
[(list-rest (header text) tokens)
(match-define (list _ key val)
(regexp-match #px"([A-Z])\\:\\s*([^\n]*)\n?" text))
(define skey (string->symbol key))
(case skey
; Title becomes name
[(T) (set-song-name! new-song val)]
; Set the default note length / meter / key
[(L) (current-length (parse-length-header val))]
[(M) (current-meter (parse-meter val))]
[(K) (current-key (parse-key val))]
; Any other header, just store it in the headers hash
[else (hash-set! (song-headers new-song) key val)])
; Process the next header
(loop (cdr tokens))]
; Not a header, move on to the music
[_
tokens])))
; Parse notes
(define current-measure (make-parameter (make-default-measure)))
(set! tokens
(let loop ([tokens tokens])
(match tokens
; Out of tokens, the song is done
[(list) (void)]
; On a bar, start a new measure
; TODO: Treat double bars seperately. (How?)
[(list-rest (or 'bar
'double-bar
'double-bar-start
'double-bar-end)
tokens)
(define new-measure (make-default-measure))
(set-measure-next! (current-measure) new-measure)
(current-measure new-measure)]
; Repeats set up a
)))
; Return the song
new-song)
; Parse length header information
(define (parse-length-header text)
(string->number text))
; Parse a meter definition
(define (parse-meter text)
(cond
[(equal? text "none") (meter #f #f)]
[(equal? text "C") (meter 4 4)]
[(equal? text "C|") (meter "C|")]
[else
(apply meter (map string->number (string-split text "/")))]))
; Parse a key signature
(define (parse-key text)
(match-define (list note type)
(map
string->symbol
(regexp-match #px"([A-G][#b]?)(|Maj|m|Min|Mix|Dor|Phr|Lyd|Loc)" text)))
(when (eq? type '||) (set! type 'Maj))
(when (eq? type 'm) (set! type 'Min))
(define-values (num-sharps num-flats)
(case (string->symbol (format "~a~a" note type))
[(C#Maj, AMin, G#Mix, D#Dor, E#Phr, F#Lyd, B#Loc) (values 7 0)]
[(F#Maj, DMin, C#Mix, G#Dor, A#Phr, BLyd, E#Loc) (values 6 0)]
[(BMaj, GMin, F#Mix, C#Dor, D#Phr, ELyd, A#Loc) (values 5 0)]
[(EMaj, CMin, BMix, F#Dor, G#Phr, ALyd, D#Loc) (values 4 0)]
[(AMaj, FMin, EMix, BDor, C#Phr, DLyd, G#Loc) (values 3 0)]
[(DMaj, Min, AMix, EDor, F#Phr, GLyd, C#Loc) (values 2 0)]
[(GMaj, Min, DMix, ADor, BPhr, CLyd, F#Loc) (values 1 0)]
[(CMaj, Min, GMix, DDor, EPhr, FLyd, BLoc) (values 0 0)]
[(FMaj, Min, CMix, GDor, APhr, BbLyd, ELoc) (values 0 1)]
[(BbMaj, Min, FMix, CDor, DPhr, EbLyd, ALoc) (values 0 2)]
[(EbMaj, Min, BbMix, FDor, GPhr, AbLyd, DLoc) (values 0 3)]
[(AbMaj, Min, EbMix, BbDor, CPhr, DbLyd, GLoc) (values 0 4)]
[(DbMaj, BMin, AbMix, EbDor, FPhr, GbLyd, CLoc) (values 0 5)]
[(GbMaj, EMin, DbMix, AbDor, BbPhr, CbLyd, FLoc) (values 0 6)]
[(CbMaj, AMin, GbMix, DbDor, EbPhr, FbLyd, BbLoc) (values 0 7)]))
(key note
type
(take '(F C G D A E B) num-sharps)
(take '(B E A D G C F) num-flats)))
; Make a new default meter using the current parameters
(define (make-default-measure)
(meter
(current-meter)
(current-key)
'()
#f))
; TODO: DEBUG
(require "tokenizer.rkt")
(abc-parse
(call-with-input-string "T:test\nEDCD|EEEz|DDDz|EGGz|EDCD|EEEz|EFGF|E4" abc-lex)) | false |
c488eb1e6dff69a64e5f6d0e6bed11954d2a67de | 794ae89fbf7d5cda9dfd9b56c4b2ba15cea787e6 | /cKanren/tests/fd.rkt | 0630e2497e0f8145ffc454a837b88d41508a4d4b | [
"MIT"
]
| permissive | mondano/cKanren | 8325f50598c6ff04a7538f8c8a9148fd6eb85f60 | 8714bdd442ca03dbf5b1d6250904cbc5fd275e68 | refs/heads/master | 2023-08-13T23:14:59.058020 | 2014-10-21T15:53:14 | 2014-10-21T15:53:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 10,751 | rkt | fd.rkt | #lang racket
(require
"../ck.rkt"
"../tree-unify.rkt"
"../unstable/fd.rkt"
"../tester.rkt")
(provide test-fd test-fd-long)
;; (define add-digitso
;; (lambda (augend addend carry-in carry digit)
;; (fresh (partial-sum sum)
;; (infd partial-sum (range 0 18))
;; (infd sum (range 0 19))
;; (plusfd augend addend partial-sum)
;; (plusfd partial-sum carry-in sum)
;; (conde
;; ((<fd 9 sum) (=fd carry 1) (plusfd digit 10 sum))
;; ((<=fd sum 9) (=fd carry 0) (=fd digit sum))))))
;;
;; (define send-more-moneyo
;; (lambda (letters)
;; (fresh (s e n d m o r y carry0 carry1 carry2)
;; (== letters `(,s ,e ,n ,d ,m ,o ,r ,y))
;; (distinctfd letters)
;; (infd s m (range 1 9))
;; (infd e n d o r y (range 0 9))
;; (infd carry0 carry1 carry2 (range 0 1))
;; (add-digitso s m carry2 m o)
;; (add-digitso e o carry1 carry2 n)
;; (add-digitso n r carry0 carry1 e)
;; (add-digitso d e 0 carry0 y))))
;;
;; (define diagonalso
;; (lambda (n l)
;; (let loop ((r l) (s (cdr l)) (i 0) (j 1))
;; (cond
;; ((or (null? r) (null? (cdr r))) succeed)
;; ((null? s) (loop (cdr r) (cddr r) (+ i 1) (+ i 2)))
;; (else
;; (let ((qi (car r)) (qj (car s)))
;; (conj
;; (diago qi qj (- j i) (range 0 (* 2 n)))
;; (loop r (cdr s) i (+ j 1)))))))))
;;
;; (define diago
;; (lambda (qi qj d rng)
;; (fresh (qi+d qj+d)
;; (infd qi+d qj+d rng)
;; (plusfd qi d qi+d)
;; (=/=fd qi+d qj)
;; (plusfd qj d qj+d)
;; (=/=fd qj+d qi))))
;;
;; (define n-queenso
;; (lambda (q* n)
;; (let loop ((i n) (l '()))
;; (cond
;; ((zero? i)
;; (conj
;; (distinctfd l)
;; (diagonalso n l)
;; (== q* l)))
;; (else (fresh (x)
;; (infd x (range 1 n))
;; (loop (- i 1) (cons x l))))))))
;;
;; (define smm-mult
;; (lambda (letters)
;; (fresh (s e n d m o r y send more money)
;; (== letters `(,s ,e ,n ,d ,m ,o ,r ,y))
;; (distinctfd letters)
;; (infd s m (range 1 9))
;; (infd e n d o r y (range 0 9))
;; (infd send more (range 0 9999))
;; (infd money (range 0 99999))
;; (actual-wortho `(,s ,e ,n ,d) send)
;; (actual-wortho `(,m ,o ,r ,e) more)
;; (actual-wortho `(,m ,o ,n ,e ,y) money)
;; (plusfd send more money))))
;;
;; (define actual-wortho
;; (lambda (ls out)
;; (let loop ((ls (reverse ls)) (place 1) (acc 0))
;; (cond
;; ((null? ls)
;; (== acc out))
;; (else
;; (fresh (cur acc^)
;; (infd acc^ (range 0 (max-val place)))
;; (infd cur (range 0 (- (* place 10) 1)))
;; (timesfd (car ls) place cur)
;; (plusfd acc cur acc^)
;; (loop (cdr ls) (* place 10) acc^)))))))
;;
;; (define max-val
;; (lambda (n)
;; (case n
;; ((1) 9)
;; ((10) 99)
;; ((100) 999)
;; ((1000) 9999)
;; ((10000) 99999))))
(define (test-fd)
(test (run* (x) (infd x '(1 2)))
'(1 2))
(test (run* (x) (fresh (y) (infd x y '(1 2))))
'(1 2))
(test
(run* (x)
(fresh (y)
(infd x y '(1 2))
(=fd x y)))
'(1 2))
(test
(run* (x)
(infd x '(1 2))
(=/=fd x 1))
`(2))
(test
(run* (x)
(infd x '(1 2))
(=/=fd 1 x))
`(2))
(test
(run* (q)
(fresh (x)
(infd x q '(1 2))
(=/=fd x 1)
(=fd x q)))
`(2))
(test
(run* (x y z)
(infd x '(1 2 3))
(infd y '(3 4 5))
(=fd x y)
(infd z '(1 3 5 7 8))
(infd z '(5 6))
(=fd z 5))
`((3 3 5)))
(test
(run* (x y z)
(infd x '(1 2 3))
(infd y '(3 4 5))
(=fd x y)
(infd z '(1 3 5 7 8))
(infd z '(5 6))
(=fd z x))
'())
(test
(run* (q)
(fresh (x y z)
(infd x '(1 2))
(infd y '(2 3))
(infd z q '(2 4))
(=fd x y)
(=/=fd x z)
(=fd q z)))
`(4))
(test
(run* (q)
(fresh (x y z)
(=fd x y)
(infd y '(2 3))
(=/=fd x z)
(infd z q '(2 4))
(=fd q z)
(infd x '(1 2))))
`(4))
(test
(run* (x y)
(infd x '(1 2))
(infd y '(2 3))
(=fd x y))
`((2 2)))
(test
(run* (q)
(fresh (x y z)
(infd x y z '(1 2))
(=/=fd x y)
(=/=fd x z)
(=/=fd y z)))
`())
(test
(run* (q)
(fresh (x) (infd x '(1 2)))
(infd q '(5)))
`(5))
(test
(run* (q)
(infd q '(1 2))
(== q #t))
`())
(test
(run* (q)
(== q #t)
(infd q '(1 2)))
`())
(test
(run* (q)
(infd q (range 0 10))
(<=fd q 5))
`(0 1 2 3 4 5))
(test
(run* (q)
(fresh (x)
(infd x q (range 0 10))
(<=fd x 5)
(=fd q x)))
`(0 1 2 3 4 5))
(test
(run* (q)
(fresh (x)
(<=fd x 5)
(infd x q (range 0 10))
(=fd q x)))
`(0 1 2 3 4 5))
(test
(run* (x y)
(infd x '(1 2 3))
(infd y '(0 1 2 3 4))
(<=fd x y))
`((1 1) (1 2) (1 3) (1 4) (2 2) (2 3) (3 3) (2 4) (3 4)))
(test
(run* (x y)
(infd x '(1 2 3))
(infd y '(0 1 2 3 4))
(<fd x y))
`((1 2) (1 3) (1 4) (2 3) (2 4) (3 4)))
(test
(run* (x y)
(infd x '(1 2 3))
(infd y '(0 1 2 3 4))
(<fd x y)
(=/=fd x 1)
(=fd y 3))
`((2 3)))
#;
(test
(run* (x y z)
(infd x y z (range 0 3))
(plusfd x y z))
'error)
#;
(test
(run* (q)
(fresh (x y z)
(infd x y z q (range 0 9))
(=/=fd x y)
(=/=fd y z)
(=/=fd x z)
(=fd x 2)
(=fd q 3)
(plusfd y 3 z)))
`(3))
;; (test
;; (run* (q)
;; (distinctfd `(1 2 3 4 5)))
;; `(_.0))
;;
;; (test
;; (run* (q)
;; (distinctfd `(1 2 3 4 4 5)))
;; `())
;;
;; (test
;; (run* (q)
;; (infd q (range 0 2))
;; (distinctfd `(,q)))
;; `(0 1 2))
;;
;; (test
;; (run* (q)
;; (infd q (range 0 2))
;; (distinctfd `(,q ,q)))
;; `())
;;
;; (test
;; (run* (q)
;; (fresh (x y z)
;; (infd x y z (range 0 2))
;; (distinctfd `(,x ,y ,z))
;; (== q `(,x ,y ,z))))
;; `((0 1 2) (0 2 1) (1 0 2) (2 0 1) (1 2 0) (2 1 0)))
;;
;; (test
;; (run* (q)
;; (fresh (a b c x)
;; (infd a b c (range 1 3))
;; (distinctfd `(,a ,b ,c))
;; (=/=fd c x)
;; (<=fd b 2)
;; (== x 3)
;; (== q `(,a ,b ,c))))
;; '((3 1 2) (3 2 1)))
;;
;; (test
;; (run* (q)
;; (fresh (x y z)
;; (infd x y z '(1 2))
;; (distinctfd `(,x ,y ,z))))
;; '())
;;
;; (test
;; (run* (q)
;; (fresh (x y)
;; (infd x y (range 0 6))
;; (timesfd x y 6)
;; (== q `(,x ,y))))
;; `((1 6) (2 3) (3 2) (6 1)))
;;
;; (test
;; (run* (q)
;; (fresh (x y)
;; (infd x y (range 0 6))
;; (timesfd x 6 y)
;; (== q `(,x ,y))))
;; `((0 0) (1 6)))
;;
;; (test
;; (run* (q)
;; (fresh (x y)
;; (infd x y (range 0 6))
;; (timesfd 6 x y)
;; (== q `(,x ,y))))
;; `((0 0) (1 6)))
;;
;; (test
;; (run* (q)
;; (infd q (range 0 36))
;; (timesfd q q 36))
;; `(6))
;;
;; (test
;; (run* (q)
;; (fresh (x y)
;; (infd x y (range 1 100))
;; (timesfd x y 0)
;; (== q 5)))
;; `())
;;
;; ;;; 34 + 89
;;
;; (test
;; (run* (q)
;; (fresh (digit1 digit2 carry0 carry1)
;; (infd carry0 carry1 (range 0 1))
;; (infd digit1 digit2 (range 0 9))
;; (add-digitso 4 9 0 carry0 digit1)
;; (add-digitso 3 8 carry0 carry1 digit2)
;; (== q `(,carry1 ,digit2 ,digit1))))
;; '((1 2 3)))
;;
;; ;;; ((1 2 3))
;;
;; (display "Send More Money (addition)\n")
;; (display (time (run* (q) (send-more-moneyo q))))
;; (newline)
;;
;; (display "One Solution for Eight Queens\n")
;; (display (time (run 1 (q) (n-queenso q 8))))
;; (newline)
;;
;; (test
;; (run* (q)
;; (actual-wortho `(1 2 3) 123))
;; `(_.0))
;;
;; (test
;; (run* (q)
;; (fresh (x y z)
;; (infd x y z (range 0 9))
;; (== q `(,x ,y ,z))
;; (actual-wortho `(,x ,y ,z) 123)))
;; `((1 2 3)))
;;
;; (test
;; (run* (q)
;; (infd q (range 0 999))
;; (actual-wortho `(1 2 3) q))
;; `(123))
;;
;; (test
;; (run* (q)
;; (infd q (range 0 9))
;; (actual-wortho `(5 ,q 3) 543))
;; `(4))
;;
;; (test
;; (run* (q)
;; (fresh (x)
;; (infd x (range 0 9))
;; (infd q (range 0 999))
;; (actual-wortho `(5 ,x 3) q)))
;; `(503 513 523 533 543 553 563 573 583 593))
)
(define (test-fd-long)
(test-fd)
;; (display "All Solutions for Eight Queens\n")
;; (display (time (length (run* (q) (n-queenso q 8)))))
;; (newline)
;;
;; (display "Send More Money (multiplication)\n")
;; (display (time (run* (q) (smm-mult q))))
;; (newline)
)
(module+ main
(test-fd-long)
)
| false |
f14bbd3c63880ab79b8f4a4d826dee554abd641e | d755de283154ca271ef6b3b130909c6463f3f553 | /htdp-lib/graphics/graphics-posn-less-unit.rkt | 313f0481a16c6cc2d25fb7dfc2b864bde7495550 | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
]
| 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 | 43,365 | rkt | graphics-posn-less-unit.rkt | ; Simple graphics routines for GRacket
; Originally written by Johnathan Franklin
(module graphics-posn-less-unit racket/base
(require racket/unit
mred/mred-sig
mred
mzlib/etc
racket/class
"graphics-sig.rkt")
(provide graphics-posn-less@)
(define-syntax define-do-pixel
(syntax-rules ()
[(_ name do-it v-name make-do-pixel)
(define (name viewport)
(let ([f ((make-do-pixel do-it) viewport)])
;; Give a nicer name to f:
(let ([v-name
(case-lambda
[(posn) (f posn)]
[(posn color) (f posn color)])])
v-name)))]))
(define-syntax define-string
(syntax-rules ()
[(_ name what v-name string-functions)
(define name
(let ([finish (lambda (f)
;; Give a nicer name to f:
(let ([v-name
(case-lambda
[(posn text) (f posn text)]
[(posn text color) (f posn text color)])])
v-name))])
(case-lambda
[(viewport font)
(finish ((string-functions 'what) viewport font))]
[(viewport)
(finish ((string-functions 'what) viewport))])))]))
(define-unit graphics-posn-less@
(import (prefix mred: mred^)
graphics:posn^)
(export graphics^)
(init-depend mred^)
(define send/proc
(lambda (class method . args)
(send-generic class (make-generic mred:dc<%> method) . args)))
(define send/proc2
(lambda (class method . args)
(send-generic class (make-generic sixlib-canvas% method) . args)))
(define-struct viewport (label canvas))
(define-struct sixmouse (x y left? middle? right?))
(define-struct sixkey (value))
(define graphics-flag #f)
(define global-viewport-list '())
(define global-color-vector (make-vector 300 #f))
(define global-pen-vector (make-vector 300 #f))
(define global-brush-vector (make-vector 300 #f))
(define default-font (make-object mred:font% 12 'roman 'normal 'normal #f 'unsmoothed))
(define black-color (make-object mred:color% "BLACK"))
(define sixlib-canvas%
(class mred:canvas%
;; were public
(define viewport (void))
(define height 0)
(define width 0)
(define label 0)
(define current-pen 'uninitialized-pen)
(define current-brush 'uninitialized-brush)
(define bitmap 'uninitalized-bitmap)
(define dc 'uninitialized-dc)
(define buffer-dc 'uninitialized-buffer-dc)
(super-new)
(inherit get-parent
min-client-width min-client-height
stretchable-width stretchable-height)
(define current-mouse-posn (make-posn 0 0))
(define queue%
(class object%
(define queue '())
(define last #f)
(define lock (make-semaphore 1))
(define ready (make-semaphore))
(public*
[flush
(lambda ()
(semaphore-wait lock)
(set! queue '())
(set! last #f)
(set! ready (make-semaphore))
(semaphore-post lock))]
[add
(lambda (v)
(semaphore-wait lock)
(if last
(begin
(set-mcdr! last (mcons v '()))
(set! last (mcdr last)))
(begin
(set! queue (mcons v '()))
(set! last queue)))
(semaphore-post ready)
(semaphore-post lock))]
[remove
(lambda ()
(semaphore-wait lock)
(begin0
(if (null? queue)
#f
(begin0
(mcar queue)
(semaphore-wait ready)
(set! queue (mcdr queue))
(when (null? queue)
(set! last #f))))
(semaphore-post lock)))]
[remove/wait
(lambda ()
(semaphore-wait ready)
(semaphore-post ready)
(remove))])
(super-make-object)))
(define click-queue (make-object queue%))
(define release-queue (make-object queue%))
(define press-queue (make-object queue%))
(private*
[reset-size
(lambda ()
(min-client-width width)
(min-client-height height)
(stretchable-width #f)
(stretchable-height #f)
(set! bitmap (make-object mred:bitmap% width height))
(unless (send bitmap ok?)
(error "cannot allocate viewport"))
(send buffer-dc set-bitmap bitmap)
(send buffer-dc set-brush (send dc get-brush))
(send buffer-dc set-pen (send dc get-pen))
(let ([f (send dc get-font)])
(when f
(send buffer-dc set-font f)))
(send buffer-dc clear)
(send dc clear))])
(public*
[get-viewport (lambda () viewport)]
[set-viewport (lambda (x) (set! viewport x))]
[get-sixlib-height (lambda () height)]
[get-sixlib-width (lambda () width)]
[get-current-pen (lambda () current-pen)]
[get-current-brush (lambda () current-brush)]
[get-bitmap (lambda () bitmap)]
[get-sixlib-dc (lambda () dc)]
[get-buffer-dc (lambda () buffer-dc)]
[remember-pen (lambda (pen) (set! current-pen pen))]
[remember-brush (lambda (brush) (set! current-brush brush))])
(override*
[on-paint
(lambda ()
(when (object? buffer-dc)
(define bm (send buffer-dc get-bitmap))
(when bm
(send dc draw-bitmap bm 0 0))))]
[on-event
(lambda (mouse-event)
;; this does deal with mouse events
;; so let's try and put hooks in here
;; after I know that it is a "good" sixm mouseclick
(let* ([x (send mouse-event get-x)]
[y (send mouse-event get-y)]
[left? (send mouse-event button-down? 'left)]
[middle? (send mouse-event button-down? 'middle)]
[right? (send mouse-event button-down? 'right)]
[sixm (make-sixmouse x y left? middle? right?)])
(set! current-mouse-posn (make-posn x y))
(cond
[(send mouse-event button-down?)
(send click-queue add sixm)]
[(send mouse-event button-up?)
(send release-queue add sixm)]
[else (void)])))]
[on-char
(lambda (key-event)
(let ([the-event (make-sixkey (send key-event get-key-code))])
;; --- timing stuff : MF 4/4/2004
(if (procedure? on-char-proc)
(on-char-proc the-event)
(send press-queue add the-event))))])
;; --- timing stuff : MF 4/4/2004
(define the-world #f)
;; KeyEvent World -> Void
(define on-char-proc #f)
(define the-time
(new timer% [notify-callback (lambda () (timer-callback))]))
(define timer-callback
(lambda ()
(set! the-world
(with-handlers ([exn:break? break-handler]
[exn? exn-handler])
(on-tick-proc the-world)))))
;; World -> World
(define on-tick-proc void)
(define exn-handler
(lambda (e)
(send the-time stop)
(set! on-char-proc #f)
(raise e)))
(define break-handler
(lambda _
(printf "animation stopped")
(send the-time stop)
(set! on-char-proc #f)
the-world))
(public*
[set-on-char-proc
(lambda (f)
(let ([esp (current-eventspace)])
(if (procedure? on-char-proc)
(error 'on-event "the event action has been set already")
(set! on-char-proc
(lambda (e)
(parameterize ([current-eventspace esp])
(queue-callback
(lambda ()
(set! the-world
(with-handlers ([exn:break? break-handler]
[exn? exn-handler])
(f e the-world))))
#t)))))))]
[set-on-tick-proc ;; Number [seconds] (World -> World) -> Void
(lambda (delta f)
(if (eq? on-tick-proc void)
(set! on-tick-proc f)
(error 'on-tick "the timing action has been set already"))
(send the-time start delta))]
[stop-tick
(lambda ()
(send the-time stop)
(set! on-char-proc #f)
the-world)]
[init-world (lambda (w) (set! the-world w))])
;; --- end timing stuff
(public*
[get-click
(lambda ()
(send click-queue remove))]
[get-click-now
(lambda ()
(send click-queue remove/wait))]
[get-release
(lambda ()
(send release-queue remove))]
[get-release-noew
(lambda ()
(send release-queue remove/wait))]
[get-press
(lambda ()
(send press-queue remove))]
[get-press-now
(lambda ()
(send press-queue remove/wait))]
[get-posn (lambda () current-mouse-posn)]
[set-dc (lambda (new-dc) (set! dc new-dc))]
[set-buffer-dc (lambda (new-buffer-dc) (set! buffer-dc
new-buffer-dc))]
[set-geometry
(lambda (new-width new-height)
(set! height new-height)
(set! width new-width)
(reset-size))]
[set-height (lambda (new-height)
(set! height new-height)
(reset-size))]
[set-width (lambda (new-width)
(set! width new-width)
(reset-size))]
[viewport-flush-input
(lambda ()
(send click-queue flush)
(send release-queue flush)
(send press-queue flush))])))
(define open-frames-timer (make-object mred:timer%))
;; --- timing events --- MF
[define the-time---old
(new timer% [notify-callback (lambda () (timer-callback---old))])]
[define timer-callback---old void]
;; --- end timing ---
(define sixlib-frame%
(class mred:frame%
(field [canvas #f])
(define/public (set-canvas x) (set! canvas x))
(define/augment (on-close)
(close-viewport (send canvas get-viewport))
(send canvas stop-tick)
(inner (void) on-close))
(super-instantiate ()
[stretchable-height #f]
[stretchable-width #f]
[style '(no-resize-border)])))
(define repaint
(lambda (viewport)
(send (viewport-canvas viewport) on-paint)))
(define viewport-dc
(lambda (viewport)
(send (viewport-canvas viewport) get-sixlib-dc)))
(define viewport-buffer-dc
(lambda (viewport)
(send (viewport-canvas viewport) get-buffer-dc)))
(define viewport-bitmap
(lambda (viewport)
(send (viewport-canvas viewport) get-bitmap)))
(define viewport-frame
(lambda (viewport)
(send (send (viewport-canvas viewport) get-parent) get-parent)))
(define viewport-height
(lambda (viewport)
(send (viewport-canvas viewport) get-sixlib-height)))
(define viewport-width
(lambda (viewport)
(send (viewport-canvas viewport) get-sixlib-width)))
(define (get-mouse-click viewport)
(send (viewport-canvas viewport) get-click-now))
(define (init-world viewport)
(lambda (w)
(send (viewport-canvas viewport) init-world w)))
(define (set-on-key-event viewport)
(lambda (f)
(send (viewport-canvas viewport) set-on-char-proc f)))
(define (set-on-tick-event viewport)
(lambda (delta f)
(send (viewport-canvas viewport) set-on-tick-proc delta f)))
(define (stop-tick viewport)
(lambda ()
(send (viewport-canvas viewport) stop-tick)))
(define (get-key-press viewport)
(send (viewport-canvas viewport) get-press-now))
(define (ready-mouse-click viewport)
(send (viewport-canvas viewport) get-click))
(define (ready-mouse-release viewport)
(send (viewport-canvas viewport) get-release))
(define (ready-key-press viewport)
(send (viewport-canvas viewport) get-press))
(define mouse-click-posn
(lambda (mouse-event)
(make-posn (sixmouse-x mouse-event) (sixmouse-y mouse-event))))
(define query-mouse-posn
(lambda (viewport) (send (viewport-canvas viewport) get-posn)))
(define viewport-flush-input
(lambda (viewport) (send (viewport-canvas viewport) viewport-flush-input)))
(define left-mouse-click?
(lambda (mouse-event) (sixmouse-left? mouse-event)))
(define middle-mouse-click?
(lambda (mouse-event) (sixmouse-middle? mouse-event)))
(define right-mouse-click?
(lambda (mouse-event) (sixmouse-right? mouse-event)))
(define key-value sixkey-value)
(define clear-viewport
(lambda (viewport)
(let* ([vdc (viewport-dc viewport)]
[vbdc (viewport-buffer-dc viewport)])
(lambda ()
(send vdc clear)
(send vbdc clear)))))
(define draw-viewport
(lambda (viewport)
(let* ([dc (viewport-dc viewport)]
[buffer-dc (viewport-buffer-dc viewport)]
[w (viewport-width viewport)]
[h (viewport-height viewport)])
(rec draw-viewport/color
(case-lambda
[(color)
(let ([new-pen (send mred:the-pen-list find-or-create-pen color 1 'solid)]
[new-brush (send mred:the-brush-list find-or-create-brush color 'solid)]
[old-pen (send dc get-pen)]
[old-brush (send dc get-brush)])
(send dc set-pen new-pen)
(send dc set-brush new-brush)
(send buffer-dc set-pen new-pen)
(send buffer-dc set-brush new-brush)
(send dc draw-rectangle 0 0 w h)
(send buffer-dc draw-rectangle 0 0 w h)
(send dc set-pen old-pen)
(send buffer-dc set-pen old-pen)
(send dc set-brush old-brush)
(send buffer-dc set-brush old-brush))]
[() (draw-viewport/color (make-rgb 0 0 0))])))))
(define flip-viewport
(lambda (viewport)
(let* ([dc (viewport-dc viewport)]
[dc2 (viewport-buffer-dc viewport)]
[w (viewport-width viewport)]
[h (viewport-height viewport)])
(lambda ()
(let ([pen (send dc get-pen)]
[pen2 (send dc2 get-pen)]
[brush (send dc get-brush)]
[brush2 (send dc2 get-brush)])
(send dc set-pen xor-pen)
(send dc2 set-pen xor-pen)
(send dc set-brush xor-brush)
(send dc2 set-brush xor-brush)
(send dc draw-rectangle 0 0 w h)
(send dc2 draw-rectangle 0 0 w h)
(send dc set-pen pen)
(send dc2 set-pen pen2)
(send dc set-brush brush)
(send dc2 set-brush brush2))))))
(define close-viewport
(lambda (viewport)
(set! global-viewport-list
(let loop ([l global-viewport-list])
(cond
[(null? l) '()]
[(eq? (car l) viewport) (cdr l)]
[else (cons (car l) (loop (cdr l)))])))
(send (viewport-frame viewport) show #f)
(send (viewport-canvas viewport) show #f)
(when (null? global-viewport-list)
(send open-frames-timer stop))))
(define open-graphics
(lambda ()
(set! graphics-flag #t)))
(define close-graphics
(lambda ()
(map close-viewport global-viewport-list)
(set! graphics-flag #f)
(set! global-viewport-list '())
(send open-frames-timer stop)))
(define graphics-open? (lambda () graphics-flag))
(define make-rgb
(lambda (red green blue)
(when (or (< red 0.) (< blue 0.) (< green 0.)
(> red 1.) (> blue 1.) (> green 1.))
(error 'make-rgb
"all color indices should be in [0.0, 1.0]; provided ~s"
(list red green blue)))
(let* ([convert (lambda (num) (inexact->exact (round (* 255 num))))]
[nred (convert red)]
[ngreen (convert green)]
[nblue (convert blue)])
(make-object mred:color% nred ngreen nblue))))
(define make-color make-rgb)
(define (rgb-red rgb) (/ (send rgb red) 255))
(define (rgb-blue rgb) (/ (send rgb blue) 255))
(define (rgb-green rgb) (/ (send rgb green) 255))
(define rgb? (lambda (object) (is-a? object mred:color%)))
(define (color? x)
(or (rgb? x)
(not (not (send mred:the-color-database find-color x)))))
(define change-color
(lambda (index color)
(vector-set! global-color-vector index color)
(vector-set! global-pen-vector index (get-pen color))
(vector-set! global-brush-vector index (get-brush color))))
(define (get-color index)
(cond
[(is-a? index mred:color%) index]
[(string? index) (make-object mred:color% index)]
[else (vector-ref global-color-vector index)]))
(define get-pen
(lambda (index)
(cond
[(is-a? index mred:pen%) index]
[(or (string? index) (is-a? index mred:color%))
(send mred:the-pen-list find-or-create-pen index 1 'solid)]
[else (vector-ref global-pen-vector index)])))
(define get-brush
(lambda (index)
(cond
[(is-a? index mred:brush%) index]
[(or (string? index) (is-a? index mred:color%))
(send mred:the-brush-list find-or-create-brush index 'solid)]
[else (vector-ref global-brush-vector index)])))
(define pen? (lambda (object) (is-a? object mred:pen%)))
(define brush? (lambda (object) (is-a? object mred:brush%)))
(define display-color-vector
(lambda ()
(do
([index 0 (+ index 1)])
((eq? index 100))
(display (list (/ (rgb-red (get-color index)) 255)
(/ (rgb-green (get-color index)) 255)
(/ (rgb-blue (get-color index)) 255))))))
(define make-font
(lambda (name)
(cond
[(eq? name 'large-deco)
(make-object mred:font% 40 'decorative 'normal 'normal)]
[(eq? name 'small-roman)
(make-object mred:font% 12 'roman 'normal 'normal)]
[(eq? name 'medium-roman)
(make-object mred:font% 24 'roman 'normal 'normal)]
[(eq? name 'large-roman)
(make-object mred:font% 32 'roman 'normal 'normal)]
[else "no such font ~a; only 'large-deco, 'small-roman, 'medium-roman, and 'large-roman"
name])))
(define custom-roman
(lambda (size)
(make-object mred:font%
size 'roman 'normal 'normal)))
(define custom-deco
(lambda (size)
(make-object mred:font% size 'decorative 'normal 'normal)))
(define set-viewport-pen
(lambda (viewport pen)
(send (viewport-canvas viewport) remember-pen pen)
(let ([pen (get-pen pen)])
(send (viewport-dc viewport) set-pen pen)
(send (viewport-buffer-dc viewport) set-pen pen))))
(define set-viewport-brush
(lambda (viewport brush)
(send (viewport-canvas viewport) remember-brush brush)
(let ([brush (get-brush brush)])
(send (viewport-dc viewport) set-brush brush)
(send (viewport-buffer-dc viewport) set-brush brush))))
(define set-text-foreground
(lambda (viewport color)
(let ([color (get-color color)])
(send (viewport-dc viewport) set-text-foreground color)
(send (viewport-buffer-dc viewport) set-text-foreground color))))
(define set-text-background
(lambda (viewport color)
(let ([color (get-color color)])
(send (viewport-dc viewport) set-text-background color)
(send (viewport-buffer-dc viewport) set-text-background color))))
(define set-viewport-font
(lambda (viewport font)
(send (viewport-dc viewport) set-font font)
(send (viewport-buffer-dc viewport) set-font font)))
(define set-viewport-background
(lambda (viewport color)
(send (viewport-dc viewport) set-background color)
(send (viewport-buffer-dc viewport) set-background color)))
(define set-viewport-logical-function
(lambda (viewport logical-function)
(send (viewport-dc viewport) set-logical-function logical-function)
(send (viewport-buffer-dc viewport) set-logical-function
logical-function)))
(define white (make-rgb 1 1 1))
(define black (make-rgb 0 0 0))
(define red (make-rgb 1 0 0))
(define green (make-rgb 0 1 0))
(define blue (make-rgb 0 0 1))
(define white-pen (get-pen white))
(define black-pen (get-pen black))
(define red-pen (get-pen red))
(define blue-pen (get-pen blue))
(define green-pen (get-pen green))
(define white-brush (get-brush white))
(define black-brush (get-brush black))
(define red-brush (get-brush red))
(define green-brush (get-brush green))
(define blue-brush (get-brush blue))
(define invisi-pen (send mred:the-pen-list find-or-create-pen "WHITE" 0 'transparent))
(define invisi-brush (send mred:the-brush-list find-or-create-brush "WHITE" 'transparent))
(define xor-pen (send mred:the-pen-list find-or-create-pen "BLACK" 1 'xor))
(define xor-brush (send mred:the-brush-list find-or-create-brush "BLACK" 'xor))
(define draw-it (lambda (draw flip clear) (draw)))
(define flip-it (lambda (draw flip clear) (flip)))
(define clear-it (lambda (draw flip clear) (clear)))
(define make-draw-proc
(lambda (get-pen-name set-pen-name
get-current-pen-name set-viewport-pen white-pen)
(lambda (viewport)
(let* ([vdc (viewport-dc viewport)]
[vbdc (viewport-buffer-dc viewport)])
(lambda (color go)
(let ([orig (and color
(begin0
(send/proc2 (viewport-canvas viewport)
get-current-pen-name)
(set-viewport-pen viewport (get-color color))))])
(go (lambda (draw)
(let ([pen (send vdc get-pen)]
[brush (send vdc get-brush)])
(send vdc set-brush xor-brush)
(send vbdc set-brush xor-brush)
(send vdc set-pen xor-pen)
(send vbdc set-pen xor-pen)
(draw)
(send vdc set-brush brush)
(send vbdc set-brush brush)
(send vdc set-pen pen)
(send vbdc set-pen pen)))
(lambda (draw)
(let ([pen (send/proc vdc get-pen-name)])
(send/proc vdc set-pen-name white-pen)
(send/proc vbdc set-pen-name white-pen)
(draw)
(send/proc vdc set-pen-name pen)
(send/proc vbdc set-pen-name pen))))
(when orig
(set-viewport-pen viewport orig))))))))
(define make-do-line
(lambda (go)
(let ([f (make-draw-proc 'get-pen 'set-pen
'get-current-pen set-viewport-pen white-pen)])
(lambda (viewport)
(let ([f (f viewport)])
(letrec ([the-function
(case-lambda
[(posn1 posn2) (the-function posn1 posn2 #f)]
[(posn1 posn2 color)
(f color
(lambda (flip clear)
(let* ([x1 (posn-x posn1)]
[y1 (posn-y posn1)]
[x2 (posn-x posn2)]
[y2 (posn-y posn2)]
[draw (lambda ()
(send (viewport-dc viewport)
draw-line
x1 y1 x2 y2)
(send (viewport-buffer-dc viewport)
draw-line
x1 y1 x2 y2))])
(go draw
(lambda () (flip draw))
(lambda () (clear draw))))))])])
the-function))))))
(define draw-line (make-do-line draw-it))
(define (clear-line viewport)
(let ([f ((make-do-line clear-it) viewport)])
(rec clear-line-viewport
(lambda (p1 p2)
(f p1 p2)))))
(define (flip-line viewport)
(let ([f ((make-do-line flip-it) viewport)])
(rec flip-line-viewport
(lambda (p1 p2)
(f p1 p2)))))
(define (draw/clear/flip ivar)
(lambda (init-dc viewport p width height)
(let ([dc (viewport-dc viewport)]
[buffer-dc (viewport-buffer-dc viewport)])
(init-dc dc)
(init-dc buffer-dc)
(send/proc dc ivar (posn-x p) (posn-y p) width height)
(send/proc buffer-dc ivar (posn-x p) (posn-y p) width height))))
(define draw/clear/flip-rectangle (draw/clear/flip 'draw-rectangle))
(define draw/clear/flip-ellipse (draw/clear/flip 'draw-ellipse))
(define (draw-rectangle viewport)
(check-viewport 'draw-rectangle viewport)
(rec draw-rectangle-viewport
(case-lambda
[(p width height) (draw-rectangle-viewport p width height (make-rgb 0 0 0))]
[(p width height color)
(check 'draw-rectangle
posn? p "posn"
number? width "number"
number? height "number"
(orp color? number?) color "color or index")
(draw/clear/flip-rectangle
(lambda (dc)
(send dc set-pen (send mred:the-pen-list find-or-create-pen (get-color color) 1 'solid))
(send dc set-brush (send mred:the-brush-list find-or-create-brush "BLACK" 'transparent)))
viewport p width height)])))
(define (draw-solid-rectangle viewport)
(check-viewport 'draw-solid-rectangle viewport)
(rec draw-solid-rectangle-viewport
(case-lambda
[(p width height) (draw-solid-rectangle-viewport p width height (make-rgb 0 0 0))]
[(p width height color)
(check 'draw-solid-rectangle
posn? p "posn"
number? width "number"
number? height "number"
(orp color? number?) color "color or index")
(draw/clear/flip-rectangle
(lambda (dc)
(send dc set-pen (send mred:the-pen-list find-or-create-pen (get-color color) 1 'solid))
(send dc set-brush (send mred:the-brush-list find-or-create-brush (get-color color) 'solid)))
viewport p width height)])))
(define (flip-rectangle viewport)
(check-viewport 'flip-rectangle viewport)
(rec flip-rectangle-viewport
(case-lambda
[(p width height) (flip-rectangle-viewport p width height (make-rgb 0 0 0))]
[(p width height color)
(check 'flip-rectangle
posn? p "posn"
number? width "number"
number? height "number"
(orp color? number?) color "color or index")
(draw/clear/flip-rectangle
(lambda (dc)
(send dc set-pen (send mred:the-pen-list find-or-create-pen (get-color color) 1 'xor))
(send dc set-brush (send mred:the-brush-list find-or-create-brush "BLACK" 'transparent)))
viewport p width height)])))
(define (flip-solid-rectangle viewport)
(check-viewport 'flip-solid-rectangle viewport)
(rec flip-solid-rectangle-viewport
(case-lambda
[(p width height) (flip-solid-rectangle-viewport p width height (make-rgb 0 0 0))]
[(p width height color)
(check 'flip-solid-rectangle
posn? p "posn"
number? width "number"
number? height "number"
(orp color? number?) color "color or index")
(draw/clear/flip-rectangle
(lambda (dc)
(send dc set-pen (send mred:the-pen-list find-or-create-pen "BLACK" 1 'transparent))
(send dc set-brush (send mred:the-brush-list find-or-create-brush (get-color color) 'xor)))
viewport p width height)])))
(define (draw-ellipse viewport)
(check-viewport 'draw-ellipse viewport)
(rec draw-ellipse-viewport
(case-lambda
[(p width height) (draw-ellipse-viewport p width height (make-rgb 0 0 0))]
[(p width height color)
(check 'draw-ellipse
posn? p "posn"
number? width "number"
number? height "number"
(orp color? number?) color "color or index")
(draw/clear/flip-ellipse
(lambda (dc)
(send dc set-pen (send mred:the-pen-list find-or-create-pen (get-color color) 1 'solid))
(send dc set-brush (send mred:the-brush-list find-or-create-brush "BLACK" 'transparent)))
viewport p width height)])))
(define (draw-solid-ellipse viewport)
(check-viewport 'draw-solid-ellipse viewport)
(rec draw-solid-ellipse-viewport
(case-lambda
[(p width height) (draw-solid-ellipse-viewport p width height (make-rgb 0 0 0))]
[(p width height color)
(check 'draw-solid-ellipse
posn? p "posn"
number? width "number"
number? height "number"
(orp color? number?) color "color or index")
(draw/clear/flip-ellipse
(lambda (dc)
(send dc set-pen (send mred:the-pen-list find-or-create-pen (get-color color) 1 'solid))
(send dc set-brush (send mred:the-brush-list find-or-create-brush (get-color color) 'solid)))
viewport p width height)])))
(define (flip-ellipse viewport)
(check-viewport 'flip-ellipse viewport)
(rec flip-ellipse-viewport
(case-lambda
[(p width height) (flip-ellipse-viewport p width height (make-rgb 0 0 0))]
[(p width height color)
(check 'flip-ellipse
posn? p "posn"
number? width "number"
number? height "number"
(orp color? number?) color "color or index")
(draw/clear/flip-ellipse
(lambda (dc)
(send dc set-pen (send mred:the-pen-list find-or-create-pen (get-color color) 1 'xor))
(send dc set-brush (send mred:the-brush-list find-or-create-brush "BLACK" 'transparent)))
viewport p width height)])))
(define (flip-solid-ellipse viewport)
(check-viewport 'flip-solid-rectangle viewport)
(rec flip-solid-ellipse-viewport
(case-lambda
[(p width height) (flip-solid-ellipse-viewport p width height (make-rgb 0 0 0))]
[(p width height color)
(check 'flip-solid-ellipse
posn? p "posn"
number? width "number"
number? height "number"
(orp color? number?) color "color or index")
(draw/clear/flip-ellipse
(lambda (dc)
(send dc set-pen (send mred:the-pen-list find-or-create-pen "BLACK" 1 'transparent))
(send dc set-brush (send mred:the-brush-list find-or-create-brush (get-color color) 'xor)))
viewport p width height)])))
(define (clear-rectangle viewport)
(check-viewport 'clear-rectangle viewport)
(rec clear-rectangle-viewport
(lambda (p width height)
(check 'clear-rectangle
posn? p "posn"
number? width "number"
number? height "number")
(draw/clear/flip-rectangle
(lambda (dc)
(send dc set-pen (send mred:the-pen-list find-or-create-pen "WHITE" 1 'solid))
(send dc set-brush (send mred:the-brush-list find-or-create-brush "BLACK" 'transparent)))
viewport p width height))))
(define (clear-solid-rectangle viewport)
(check-viewport 'clear-solid-rectangle viewport)
(rec clear-solid-rectangle-viewport
(lambda (p width height)
(check 'clear-solid-rectangle
posn? p "posn"
number? width "number"
number? height "number")
(draw/clear/flip-rectangle
(lambda (dc)
(send dc set-pen (send mred:the-pen-list find-or-create-pen "WHITE" 1 'solid))
(send dc set-brush (send mred:the-brush-list find-or-create-brush "WHITE" 'solid)))
viewport p width height))))
(define (clear-ellipse viewport)
(check-viewport 'clear-ellipse viewport)
(rec clear-ellipse-viewport
(lambda (p width height)
(check 'clear-ellipse
posn? p "posn"
number? width "number"
number? height "number")
(draw/clear/flip-ellipse
(lambda (dc)
(send dc set-pen (send mred:the-pen-list find-or-create-pen "WHITE" 1 'solid))
(send dc set-brush (send mred:the-brush-list find-or-create-brush "BLACK" 'transparent)))
viewport p width height))))
(define (clear-solid-ellipse viewport)
(check-viewport 'clear-solid-ellipse viewport)
(rec clear-solid-ellipse-viewport
(lambda (p width height)
(check 'clear-solid-ellipse
posn? p "posn"
number? width "number"
number? height "number")
(draw/clear/flip-ellipse
(lambda (dc)
(send dc set-pen (send mred:the-pen-list find-or-create-pen "WHITE" 1 'solid))
(send dc set-brush (send mred:the-brush-list find-or-create-brush "WHITE" 'solid)))
viewport p width height))))
(define make-do-pointlist
(lambda (go name get-pen-name set-pen-name
get-current-pen-name set-viewport-pen white-pen
get-brush-name set-brush-name invisi-brush)
(let ([f (make-draw-proc get-pen-name set-pen-name
get-current-pen-name set-viewport-pen white-pen)])
(lambda (viewport)
(let ([f (f viewport)]
[vdc (viewport-dc viewport)]
[vbdc (viewport-buffer-dc viewport)])
(letrec ([the-function
(case-lambda
[(posns offset) (the-function posns offset #f)]
[(posns offset color)
(f color
(lambda (flip clear)
(let* ([points (map (lambda (p)
(make-object mred:point% (posn-x p) (posn-y p)))
posns)]
[x (posn-x offset)]
[y (posn-y offset)]
[orig (send/proc vdc get-brush-name)]
[draw (lambda ()
(send/proc vdc set-brush-name
invisi-brush)
(send/proc vbdc set-brush-name
invisi-brush)
(send/proc
(viewport-dc viewport) name
points x y)
(send/proc
(viewport-buffer-dc viewport) name
points x y)
(send/proc vdc set-brush-name orig)
(send/proc vbdc set-brush-name
orig))])
(go draw
(lambda () (flip draw))
(lambda () (clear draw))))))])])
the-function))))))
(define make-do-polygon
(lambda (go)
(make-do-pointlist go 'draw-polygon 'get-pen 'set-pen
'get-current-pen set-viewport-pen white-pen
'get-brush 'set-brush invisi-brush)))
(define make-do-solid-polygon
(lambda (go)
(make-do-pointlist go 'draw-polygon 'get-brush 'set-brush
'get-current-brush set-viewport-brush white-brush
'get-pen 'set-pen invisi-pen)))
(define draw-polygon (make-do-polygon draw-it))
(define (clear-polygon viewport)
(let ([f ((make-do-polygon clear-it) viewport)])
(rec clear-polygon-viewport
(lambda (posns offset)
(f posns offset)))))
(define (flip-polygon viewport)
(let ([f ((make-do-polygon flip-it) viewport)])
(rec flip-polygon-viewport
(lambda (posns offset)
(f posns offset)))))
(define draw-solid-polygon (make-do-solid-polygon draw-it))
(define (clear-solid-polygon viewport)
(let ([f ((make-do-solid-polygon clear-it) viewport)])
(rec clear-solid-polygon-viewport
(lambda (posns offset)
(f posns offset)))))
(define (flip-solid-polygon viewport)
(let ([f ((make-do-solid-polygon flip-it) viewport)])
(rec flip-solid-polygon-viewport
(lambda (posns offset)
(f posns offset)))))
(define make-do-pixel
(lambda (go)
(let ([f (make-draw-proc 'get-pen 'set-pen
'get-current-pen set-viewport-pen white-pen)])
(lambda (viewport)
(let ([f (f viewport)])
(letrec ([the-function
(case-lambda
[(posn) (the-function posn #f)]
[(posn color)
(f color
(lambda (flip clear)
(let* ([x (posn-x posn)]
[y (posn-y posn)]
[draw (lambda ()
(send
(viewport-dc viewport) draw-point
x y)
(send
(viewport-buffer-dc viewport)
draw-point
x y))])
(go draw
(lambda () (flip draw))
(lambda () (clear draw))))))])])
the-function))))))
(define-do-pixel draw-pixel draw-it draw-pixel-viewport make-do-pixel)
(define-do-pixel clear-pixel clear-it clear-pixel-viewport make-do-pixel)
(define-do-pixel flip-pixel flip-it flip-pixel-viewport make-do-pixel)
(define string-functions
(lambda (string-op)
(letrec ([outer-function
(case-lambda
[(viewport) (outer-function viewport default-font)]
[(viewport font)
(letrec ([the-function
(case-lambda
[(posn text) (the-function posn text #f)]
[(posn text color)
(let*-values ([(dc) (viewport-dc viewport)]
[(x) (posn-x posn)]
[(w h d a) (send dc get-text-extent "X" font)]
[(y) (- (posn-y posn) (- h d))]
[(buffer) (viewport-buffer-dc viewport)]
[(string-create)
(lambda ()
(send dc draw-text text x y)
(send buffer draw-text text x y))])
(cond
[(eq? string-op 'draw)
(when color
(set-text-foreground viewport color))
(set-viewport-font viewport font)
(send dc draw-text text x y)
(send buffer draw-text text x y)]
[(eq? string-op 'flip)
(when color
(set-text-foreground viewport color))
(set-viewport-font viewport font)
(string-create)]
[(eq? string-op 'clear)
(set-text-foreground viewport white)
(set-viewport-font viewport font)
(string-create)
(set-text-foreground viewport black)]))])])
the-function)])])
outer-function)))
(define-string draw-string draw draw-string-viewport string-functions)
(define-string clear-string clear clear-string-viewport string-functions)
(define-string flip-string flip flip-string-viewport string-functions)
(define get-string-size
(case-lambda
[(viewport) (get-string-size viewport default-font)]
[(viewport font)
(lambda (text)
(let-values ([(w h d a) (send (viewport-dc viewport) get-text-extent text font)])
(list w h)))]))
(define get-color-pixel
(lambda (viewport)
(lambda (posn)
(let ([c (make-object mred:color%)]
[x (posn-x posn)]
[y (posn-y posn)])
(unless (send (viewport-buffer-dc viewport) get-pixel x y c)
(error 'get-color-pixel "specified point is out-of-range"))
c))))
(define get-pixel
(lambda (viewport)
(lambda (posn)
(let ([c (make-object mred:color%)]
[x (posn-x posn)]
[y (posn-y posn)])
(unless (send (viewport-buffer-dc viewport) get-pixel x y c)
(error 'get-pixel "specified point is out-of-range"))
(if (or (< (send c blue) 255)
(< (send c red) 255)
(< (send c green) 255))
1
0)))))
(define (test-pixel viewport)
(lambda (color)
(let ([c (make-object mred:color%)])
(send (viewport-buffer-dc viewport) try-color color c)
c)))
(define draw-pixmap-posn
(opt-lambda (filename [type 'unknown/mask])
(check 'draw-pixmap-posn
(andp path-string? file-exists?) filename "filename"
(lambda (x) (memq x '(gif xbm xpm bmp unknown unknown/mask gif/mask))) type "file type symbol")
(let* ([bitmap (make-object mred:bitmap% filename type)])
(lambda (viewport)
(check 'draw-pixmap-posn
viewport? viewport "viewport")
(opt-lambda (posn [color #f])
(check 'draw-pixmap-posn
posn? posn "posn"
(orp not color?) color (format "color or ~e" #f))
(when color
(set-viewport-pen viewport (get-color color)))
(let ([x (posn-x posn)]
[y (posn-y posn)])
(send (viewport-dc viewport) draw-bitmap bitmap x y 'solid black-color (send bitmap get-loaded-mask))
(send (viewport-buffer-dc viewport) draw-bitmap bitmap x y 'solid black-color (send bitmap get-loaded-mask))))))))
(define draw-pixmap
(lambda (viewport)
(check 'draw-pixmap
viewport? viewport "viewport")
(opt-lambda (filename p [color #f])
(check 'draw-pixmap
(andp path-string? file-exists?) filename "filename"
posn? p "posn"
(orp not color?) color (format "color or ~e" #f))
(((draw-pixmap-posn filename 'unknown) viewport) p color))))
(define copy-viewport
(lambda (source target)
(check 'copy-viewport
viewport? source "viewport"
viewport? target "viewport")
(let* ([source-bitmap (viewport-bitmap source)]
[target-dc (viewport-dc target)]
[target-buffer-dc (viewport-buffer-dc target)])
(send target-dc draw-bitmap source-bitmap 0 0)
(send target-buffer-dc draw-bitmap source-bitmap 0 0))))
(define save-pixmap
(lambda (viewport)
(check 'save-pixmap
viewport? viewport "viewport")
(opt-lambda (filename [kind 'xpm])
(check 'save-pixmap
(andp path-string? (orp relative-path? absolute-path?)) filename "filename"
(lambda (x) (memq x '(xpm xbm bmp))) kind "file type symbol")
(let ([bm (viewport-bitmap viewport)])
(send bm save-file filename kind)))))
(define sixlib-eventspace #f)
(define make-open-viewport
(lambda (name show?)
(unless sixlib-eventspace
(set! sixlib-eventspace
(parameterize ([uncaught-exception-handler
(lambda (x)
((error-display-handler)
(format "internal error in graphics library: ~a"
(if (exn? x)
(exn-message x)
(format "~e" x)))
x)
((error-escape-handler)))])
(mred:make-eventspace))))
(letrec ([open-viewport
(case-lambda
[(label point)
(cond
[(posn? point) (open-viewport label (posn-x point) (posn-y point))]
[(and (list? point) (= (length point) 2))
(open-viewport label (car point) (cadr point))]
[else (error name "bad argument ~s" point)])]
[(label width height)
(cond
[graphics-flag
(let*
([frame
(parameterize ([mred:current-eventspace sixlib-eventspace])
(make-object sixlib-frame% label #f width height))]
[panel (make-object mred:vertical-panel% frame)]
[canvas (make-object sixlib-canvas% panel)]
[_ (begin
(send canvas min-height height)
(send canvas min-width width))]
[dc (send canvas get-dc)]
[buffer-dc (make-object mred:bitmap-dc%)]
[viewport (make-viewport label canvas)])
(send panel set-alignment 'center 'center)
(send frame set-canvas canvas)
(send canvas set-viewport viewport)
(send canvas set-dc dc)
(send canvas set-buffer-dc buffer-dc)
(send canvas set-geometry width height)
(when show?
(send frame show #t)
(send canvas focus))
(set-text-foreground viewport black)
(set-text-background viewport white)
(set-viewport-background viewport white)
(set-viewport-pen viewport black-pen)
(set-viewport-brush viewport black-brush)
((clear-viewport viewport))
(when (null? global-viewport-list)
(send open-frames-timer start 100000000))
(set! global-viewport-list (cons viewport global-viewport-list))
viewport)]
[else (error "graphics not open")])])])
open-viewport)))
(define open-viewport (make-open-viewport 'open-viewport #t))
(define open-pixmap (make-open-viewport 'open-pixmap #f))
(define (default-display-is-color?) (mred:is-color-display?))
(define position-display
(lambda (viewport counter)
(cond
[(equal? counter 0) '()]
[else (begin
(display (query-mouse-posn viewport))
(position-display viewport (- counter 1)))])))
(define create-cmap
(lambda ()
(do ([index 0 (+ 1 index)])
((> index 20))
(let* ([r (* 0.05 index)]
[b (- 1 r)]
[g (- 1 r)])
(change-color index (make-rgb r g b))))))
(define viewport->snip
(lambda (viewport)
(let ([orig-bitmap (send (viewport-canvas viewport) get-bitmap)]
[orig-dc (viewport-buffer-dc viewport)])
(let* ([h (send orig-bitmap get-height)]
[w (send orig-bitmap get-width)]
[new-bitmap (make-object mred:bitmap% w h)]
[tmp-mem-dc (make-object mred:bitmap-dc%)])
(send tmp-mem-dc set-bitmap new-bitmap)
(send tmp-mem-dc draw-bitmap (send orig-dc get-bitmap) 0 0)
(send tmp-mem-dc set-bitmap #f)
(let ([snip (make-object mred:image-snip%)])
(send snip set-bitmap new-bitmap)
snip)))))
(create-cmap)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; ;;;
;;; ERROR CHECKING ;;;
;;; ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; check-viewport : symbol TST -> void
(define (check-viewport f-name obj)
(unless (viewport? obj)
(error f-name "expected viewport as first argument, got ~e" obj)))
;; (define-type arg/pred/name-list (list* (TST -> bool) TST string arg/pred/name-list))
;; check : (symbol arg/pred/name-list *-> void)
(define (check f-name . in-args)
(let loop ([args in-args]
[n 0])
(cond
[(null? args) (void)]
[else (let ([pred? (car args)]
[val (cadr args)]
[name (caddr args)])
(unless (pred? val)
(error f-name "expected ~a as arg ~a, got: ~e, all args: ~a"
name n val
(let loop ([args in-args])
(cond
[(null? args) ""]
[else (string-append (format "~e" (cadr args))
" "
(loop (cdddr args)))]))))
(loop (cdddr args)
(+ n 1)))])))
(define (orp . preds)
(lambda (TST)
(ormap (lambda (p) (p TST)) preds)))
(define (andp . preds)
(lambda (TST)
(andmap (lambda (p) (p TST)) preds)))
)
)
| true |
b986a8e541800596d2bb3403b52484cead4ec557 | 0f18ba0b9797529c81b050d456cc8c65edff8774 | /scheme/quasiquotation.rkt | ae71d3630291d9dd5d750ba8a1070ec0dfd19d06 | []
| no_license | troyp/papers-code | 4469399e41751062926c5fa3896b9ba7583abccd | d8dab6567cf20cfd642bf72df45c6c0c5f9df33e | refs/heads/master | 2022-11-21T04:09:28.737541 | 2020-07-21T13:53:08 | 2020-07-21T13:53:08 | 281,412,267 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 494 | rkt | quasiquotation.rkt | #lang racket
(require srfi/1)
(define expr1
(let ((array-name 'a)
(array-size 20)
(init-val 1))
`(do ((i 0 (+ 1 i)))
((>= i ,array-size))
(vector-set! ,array-name
i
,init-val))))
(define expr2
(let ((var 'a)
(val 'b)
(expr '(list 1 2))
(more-clauses (list '((eq? c #F) #F)
'(else (list 2 3)))))
`(cond ((eq? ,var ',val) ,expr)
. ,more-clauses)))
| false |
b249ffaa4ee65d1b732b63af6e25e235a316925b | c31cdd6e00d3d7cd41bf86e5b4ee78d93c82aab3 | /struct-like-struct-type-property/test/test-quadratic.rkt | 21e3951fc38915138750f504b91052a00a3c42b0 | [
"MIT"
]
| permissive | AlexKnauth/struct-like-struct-type-property | f609b2904b90c19e1ec8cbd2b1669e64f1a7abca | 2e433691136c881c87dd27b7e2c3266cca74ff24 | refs/heads/main | 2022-02-06T16:51:47.604439 | 2022-01-07T14:24:50 | 2022-01-07T14:24:50 | 136,227,849 | 2 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 920 | rkt | test-quadratic.rkt | #lang racket/base
(require racket/match
racket/math
struct-like-struct-type-property)
(module+ test
(require rackunit))
;; -----------------
(define-struct-like-struct-type-property quadratic [a b c]
#:property prop:procedure
(λ (self x)
(match-define (quadratic a b c) self)
(+ (* a (sqr x)) (* b x) c)))
(struct vertex-form [a vertex]
#:property prop:quadratic
(λ (self)
(match-define (vertex-form a (list h k)) self)
(define b (* -2 a h))
(define c (+ (* a (sqr h)) k))
(quadratic a b c)))
;; -----------------
(module+ test
(define f (quadratic 1 -2 -3))
(check-equal? (f 0) -3)
(check-equal? (f 1) -4)
(check-equal? (f 2) -3)
(check-equal? (f 3) 0)
(check-equal? (f 4) 5)
(define g (vertex-form 1 '(1 -4)))
(check-equal? (g 0) -3)
(check-equal? (g 1) -4)
(check-equal? (g 2) -3)
(check-equal? (g 3) 0)
(check-equal? (g 4) 5)
) | false |
68c706ed4e20c92bee27e3bc61c32b528909f121 | 6d2bb778af0f1c9066c374dc73390b7776052aca | /scheme/td1/td1.rkt | 24e310ad37fb8c4fc7622aca76125ee9e07e89d2 | []
| no_license | BorisL/LangagesNonClassiques | 85c05e15f3052a3a650406c45254c66ebbfc846a | 8127d196516507a1242b39f0a37fb69348ed3b54 | refs/heads/master | 2021-01-01T20:27:21.675556 | 2013-06-26T23:43:37 | 2013-06-26T23:43:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 4,371 | rkt | td1.rkt | #lang racket
; TD vendredi 17 mai 2013
(require (lib "defmacro.ss"))
; **** Structures ****
; **** Programmation par contrat ****
; !!! En cours de travail !!!
(define (pre exp)
(unless exp (error "Précondition fausse")))
(define-macro (contract . args)
`(begin ,args ... )
)
; !!! En cours de travail !!!
; **** Trace ****
(define-syntax define-trace
(syntax-rules ()
((define-trace (f . args) body ...)
(define (f . args) (begin (display f) (newline) body ... )))))
(define-trace (test1 x y)
(* x y)
)
; **** Transformation de code ****
(define-syntax while
(syntax-rules ()
((while cond body ...)
(let loop()
(unless(equal? cond #f)
body ...
(loop))))))
(define-syntax or
(syntax-rules ()
((or)
#f)
((or a b ...)
(let ((resultat a))
(if resultat
resultat
(or b ...))))))
(define-syntax and
(syntax-rules ()
((and)
#t)
((and a)
a)
((and a b ...)
(if (equal? a #f)
#f
(and b ...)))))
; **** Manipulation de données ****
; applique l’opérateur binaire operator sur les deux premiers éléments de l,
; puis sur ce résultat et le troisième élément, puis sur ce nouveau résultat et le quatrième élément, etc
(define (slash operator l)
(match-let (
((list n1 n2 t ...) l)
)
(if (empty? t)
(operator n1 n2)
(slash operator (cons (operator n1 n2) t)))))
; renvoie une liste avec les éléments de la liste l pour lesquels test est vrai
(define (filter test list)
(if(empty? list )
'()
(let ((filtered (car list)))
(if (equal? (test filtered) #t)
(cons (car list) (filter test (cdr list)))
(filter test (cdr list))))))
; prend une liste de chaînes en paramètre
; et les affiche les unes après les autres en passant à la ligne entre les différentes chaînes
(define (display-all list)
(for-each (lambda(x) (display x) (newline)) list)
)
; prend une liste de symboles en paramètre et renvoie la même liste dans laquelle les caractères sont inversés
(define (trans list)
(map revsymb list)
)
; inverse l’ordre des caractères d’un symbole
(define (revsymb symb)
(string->symbol (list->string(reverse (string->list (symbol->string symb)))))
)
; **** Échauffement ****
; renvoie la liste des n premiers entiers naturels (de 0 à n-1)
(define (iota n)
(if(= n 0)
'()
(buildRange 0 (- n 1))
))
; collecte les résultats des appels à f pour chaque entier de min à max (bornes comprises)
(define (buildRange min max)
(if (> min max)
'()
(cons min (buildRange(+ min 1) max))
))
(define (map-interval f min max)
(letrec ((mapr (buildRange min max)))
(map f mapr)
))
; déterminant si n est un nombre premier.
(define (multiple? i n) (if(= (modulo n i) 0) #t #f))
(define (prime? n)
(if(<= n 2)
(if (= n 2)
#t
#f
)
(if (= (modulo n 2) 0)
#f
(let loop ((t (round(sqrt n)))
(n n))
(if (>= t n)
#t
(if(= (modulo n t) 0)
#f
(loop (next-odd t) n)
))))))
; renvoie le plus petit nombre impair strictement supérieur à n.
(define (next-odd n)
(if(= (modulo n 2) 0)
(+ n 1)
(+ n 2)))
; fonction de test unitaire
(define (test a b)
(unless (equal? a b ) (error "Bad test result"))
)
(test (next-odd 1) 3)
(test (next-odd 2) 3)
(test (prime? -5) #f)
(test (prime? 0) #f)
(test (prime? 1) #f)
(test (prime? 2) #t)
(test (prime? 3) #t)
(test (prime? 4) #f)
(test (prime? 19) #t)
(test (prime? 21) #f)
(test (prime? 25) #f)
(test (map-interval (lambda (x) (+ 2 x)) 10 13) '(12 13 14 15))
(test (iota 5) '(0 1 2 3 4))
(test (iota 0) '())
(test (iota -1) '())
(test (revsymb 'foobar) 'raboof)
(test (trans '(foo bar)) '(oof rab))
(test (filter (lambda (x) (> x 3)) '(1 10 2 20)) '(10 20))
(test (slash * '(10 20 30)) 6000)
(test (slash string-append '("foo" "bar")) "foobar")
(test (slash + '(1 2 3)) 6)
(test (slash - '(10 2 3)) 5)
(test (slash expt '(2 3 4)) 4096)
(test (slash * (filter prime? (iota 100))) 2305567963945518424753102147331756070)
(test (let ((i 0) (c 0)) (while (< i 5) (set! c (+ c i)) (set! i (+ i 1))) c) 10) | true |
42959421fa3b381da3c540756290f90cb0ed1001 | 8dae34d9f5041debfa9f947d2e3242c3a7a4c2e3 | /racket/stacker-test.rkt | c53a270902bed3c8650ba9e1225b536ed4b3678b | []
| no_license | unililium/programming-exercises | f9a26743f33196b06a0511dd0fdebcfc0fc19347 | ede313182d74888a41e7b65d0055cf1e017983a5 | refs/heads/master | 2022-12-05T21:27:55.583302 | 2020-08-01T19:44:47 | 2020-08-01T19:44:47 | 78,768,918 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 39 | rkt | stacker-test.rkt | #lang reader "stacker.rkt"
foo
bar
zam | false |
12ffe3a86f16062314e3e46cc85c27064c2caa24 | f5da4884c236512f9a945100234e213e51f980d3 | /serval/lib/solver.rkt | 10a576a682dba68842aeacf6e99692fff76c9ab2 | [
"MIT"
]
| permissive | uw-unsat/serval | 87574f5ec62480463ae976468d4ae7a56e06fe9f | 72adc4952a1e62330aea527214a26bd0c09cbd05 | refs/heads/master | 2022-05-12T23:19:48.558114 | 2022-01-20T18:53:26 | 2022-01-20T18:53:26 | 207,051,966 | 45 | 12 | MIT | 2022-03-21T14:05:50 | 2019-09-08T02:40:10 | Racket | UTF-8 | Racket | false | false | 3,333 | rkt | solver.rkt | #lang rosette
(require
rosette/solver/smt/boolector
rosette/solver/smt/cvc4
rosette/solver/smt/z3)
; Utility for controlling solver / solver path
; from environment variables.
#|
Code using this library can obtain a solver in three different modes.
1. get-default-solver / with-default-solver lets the user choose
solver and path with environment variables, choosing Rosette
defualts if not set.
2. get-* / with-* force a specific solver, but still lets the
user control path to solver with environment variables.
3. get-prefer-* / with-prefer-* first check if a specific solver
is available, but fall back to the default solver if they are not.
|#
(provide (all-defined-out))
(define solver-logic (make-parameter #f))
(define-syntax-rule (with-solver solver body ...)
(parameterize ([current-solver solver])
(printf "Using solver ~v\n" (current-solver))
body ...))
(define-syntax-rule (with-z3 body ...) (with-solver (get-z3) body ...))
(define-syntax-rule (with-prefer-z3 body ...) (with-solver (get-prefer-z3) body ...))
(define-syntax-rule (with-boolector body ...) (with-solver (get-boolector) body ...))
(define-syntax-rule (with-prefer-boolector body ...) (with-solver (get-prefer-boolector) body ...))
(define-syntax-rule (with-default-solver body ...) (with-solver (get-default-solver) body ...))
(define (get-default-solver)
(define solver (string-downcase (or (getenv "SOLVER") "z3")))
(cond
[(equal? solver "boolector")
(get-boolector)]
[(equal? solver "cvc4")
(get-cvc4)]
[(equal? solver "z3")
(get-z3)]
[else
(error (format "Unknown solver type: ~v" solver))]))
(define (get-z3 #:logic [logic #f]
#:options [options (hash ':auto-config 'false ':smt.relevancy 0)]
#:required [required #t])
(let ([path (getenv "Z3")])
(cond
[path (z3 #:path path #:logic (if logic logic (solver-logic)) #:options options)]
[else (z3)])))
(define (get-boolector #:logic [logic #f]
#:options [options (hash)]
#:required [required #t])
(let ([path (getenv "BOOLECTOR")])
(cond
[path (boolector #:path path #:logic (if logic logic (solver-logic)) #:options options)]
[(boolector-available?) (boolector #:logic (if logic logic (solver-logic)) #:options options)]
[required (error "boolector not in PATH and BOOLECTOR environment variable not set!")]
[else #f])))
(define (get-cvc4 #:logic [logic #f]
#:options [options (hash)]
#:required [required #t])
(let ([path (getenv "CVC4")])
(cond
[path (cvc4 #:path path #:logic (if logic logic (solver-logic)) #:options options)]
[(cvc4-available?) (cvc4 #:logic (if logic logic (solver-logic)) #:options options)]
[required (error "cvc4 not in PATH and CVC4 environment variable not set!")]
[else #f])))
(define (get-prefer-boolector)
(let ([boolector (get-boolector #:required #f)])
(if boolector boolector (begin (printf "Could not find boolector, falling back to the default solver\n")
(get-default-solver)))))
; Set the global default solver. If test cases don't specify any other solver,
; this is what will be used.
(current-solver (get-default-solver))
| true |
9a550e830f4f87f5e9f14722bba0b5499edaf862 | 55aa99e6a9a23eb7acf8dde24558d77667b30394 | /racket/learnracket.rkt | d2702c312e699ba9042150a3458c17edc5132add | []
| no_license | zzz6519003/7-languages | c46317fddf37b9fce66fb9fe4805fb2a5423ea72 | c6319331fc22710dcd7f72077d42383dae3166e5 | refs/heads/master | 2021-01-09T06:04:30.283498 | 2017-10-01T15:18:11 | 2017-10-01T15:18:11 | 80,894,329 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,513 | rkt | learnracket.rkt | #lang racket
(let ([me "Bob"])
"Alice"
) ; => "Bob"
(let* ([x 1]
[y (+ x 1)])
(* x y))
(letrec ([is-even? (lambda (n)
(or (zero? n)
(is-odd? (sub1 n))))]
[is-odd? (lambda (n) (and (not (zero? n))
(is-even? (sub1 n))))])
(is-odd? 11) (is-odd? 11) (is-odd? 12))
((λ () "Hello World"))
(define-syntax-rule (while condition body ...)
(let loop ()
(when condition
body ...
(loop))))
(let ([i 0])
(while (< i 10)
(displayln i)
(set! i (add1 i))))
(define (hello4 [name "World"])
(string-append "Hello " name))
(define (hello-k #:name [name "World"] #:greeting [g "Hello"] . args)
(format "~a ~a, ~a extra args" g name (length args)))
(define (fizzbuzz? n)
(match (list (remainder n 3) (remainder n 5))
[(list 0 0) 'fizzbuzz]
[(list 0 _) 'fizz]
[(list _ 0) 'buzz]
[_ #f]))
(fizzbuzz? 15)
(fizzbuzz? 37)
;; Looping can be done through (tail-) recursion
(define (loop i)
(when (< i 10)
(printf "i=~a\n" i)
(loop (add1 i))))
(loop 5)
(let loop ((i 0))
(when (< i 10)
(printf "i=~a\n" i)
(loop (add1 i))))
(for ([i (in-list '(l i s t))])
(displayln i))
(for ([i 10] [j '(x y z f)] [k '(1 2 3)]) (printf "~a:~a ~a\n" i j k))
(define (make-accumulator delta)
(lambda (amount)
(set! delta (+ delta amount))
delta))
(define A (make-accumulator 5))
(define B (make-accumulator 5))
(A 10)
(A 10)
(B 10)
| true |
8af33f69dbb5a79df268af92afdbffe4eb0361b5 | 0b00fc2e14c1a4d65fc1613a88f506a5e2c3c7db | /dissertation/figures/importance-sampling.rkt | 721cd12138917b9b820d530c1af4c14df37e5591 | []
| no_license | ntoronto/writing | 6a1539cde2a20777f4798446a00183158bdcd75b | 60b30c94110e3f2a9d39ca104656d382b32d1428 | refs/heads/master | 2021-01-22T04:57:38.369018 | 2015-02-20T17:52:08 | 2015-02-20T17:52:08 | 12,441,945 | 2 | 1 | null | 2015-01-16T01:06:14 | 2013-08-28T18:54:16 | Racket | UTF-8 | Racket | false | false | 1,081 | rkt | importance-sampling.rkt | #lang racket
(require plot
math/distributions)
(define ε 0.01)
(define rx-dist (normal-dist 1 0.5))
(define ry-dist (normal-dist 2 1.0))
(define ((diff dist0 dist1) x)
(/ (real-dist-prob dist0 (- x ε) (+ x ε))
(real-dist-prob dist1 (- x ε) (+ x ε))))
(define (maybe-rand)
(define x-dist (uniform-dist 0 2))
(define x (sample x-dist))
(define y-dist
(cond [(x . > . 1.0) ry-dist #;(uniform-dist 0 4)]
[else (uniform-dist 0 2)]))
(define y (sample y-dist))
(define wxy
(list (* ((diff rx-dist x-dist) x) ((diff ry-dist y-dist) y)) x y))
(match wxy
[(list w x y) (and (y . <= . (* 2 (sqr x))) wxy)]
[_ #f]))
(define wxys (filter values (build-list 20000 (λ _ (maybe-rand)))))
(define re-wxys (sample (discrete-dist (map rest wxys) (map first wxys)) (length wxys)))
(plot (points (map rest wxys) #:alpha 0.0125 #:sym 'fullcircle #:size 12)
#:x-min 0 #:x-max 3
#:y-min -5 #:y-max 5)
(plot (points re-wxys #:alpha 0.0125 #:sym 'fullcircle #:size 12)
#:x-min 0 #:x-max 3
#:y-min -1 #:y-max 5)
| false |
4f645fc73f079a47edb68da250797fcab1e1c64f | 743b9a8c65996a9b9e9f955dafa15f7e764c6206 | /assets/code/ack.rkt | bf0d83db84e758f2fc3ab3421b4505d0f31046ec | []
| no_license | nomah98/21FA-CS4400 | 340407020fa5c696e7167017053b7522ed90a4a0 | d893a77e440c415baedc105c7d60abcab261f8a9 | refs/heads/master | 2023-09-06T04:33:17.767053 | 2021-11-13T14:36:14 | 2021-11-13T14:36:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 4,224 | rkt | ack.rkt | #lang racket
;; The following is a dramatization of the course of events of today's
;; class. Actual events may have slightly differed.
;; We defined plus as follows
;; (define plus
;; (λ (x y)
;; (cond
;; ((zero? y) x)
;; (else (add1 (plus x (sub1 y)))))))
;; We defined times as follows
;; (define times
;; (λ (x y)
;; (cond
;; ((zero? y) 0)
;; (else (plus x (times x (sub1 y)))))))
;; We then defined expo as follows
;; (define expo
;; (λ (x y)
;; (cond
;; ((zero? y) 1)
;; (else (times x (expo x (sub1 y)))))))
;; We noticed some mighty strange similarities. They look almost all
;; look almost like:
;; (define <name>
;; (λ (x y)
;; (cond
;; ((zero? y) <base>)
;; (else (<previous-function> x (<name> x (sub1 y)))))))
;; We abstracted from the operations we built last class, for this operation.
;; (define G
;; (λ (i)
;; (cond
;; [(zero? i) (λ (x y)
;; (cond
;; [(zero? y) x]
;; [else (add1 ((G i) x (sub1 y)))]))]
;; [(zero? (sub1 i)) (λ (x y)
;; (cond
;; [(zero? y) 0]
;; [else ((G (sub1 i)) x ((G i) x (sub1 y)))]))]
;; [else (λ (x y)
;; (cond
;; [(zero? y) 1]
;; [else ((G (sub1 i)) x ((G i) x (sub1 y)))]))])))
;; We "inverse staged" the code, by which we mean that we used a
;; single (λ (x y) ...) around the whole cond, instead of 3 different
;; (λ (x y) ...)s in each cond line.
;; (define G
;; (λ (i)
;; (λ (x y)
;; (cond
;; [(zero? i)
;; (cond
;; [(zero? y) x]
;; [else (add1 ((G i) x (sub1 y)))])]
;; [(zero? (sub1 i))
;; (cond
;; [(zero? y) 0]
;; [else ((G (sub1 i)) x ((G i) x (sub1 y)))])]
;; [else
;; (cond
;; [(zero? y) 1]
;; [else ((G (sub1 i)) x ((G i) x (sub1 y)))])]))))
;; We then realized that we could reverse the order of those
;; tests. Handle all the cases where y is zero at once, and then handle
;; all the cases where y is non-zero.
;; (define G
;; (λ (i)
;; (λ (x y)
;; (cond
;; [(zero? y)
;; (cond
;; [(zero? i) x]
;; [(zero? (sub1 i)) 0]
;; [else 1])]
;; [else
;; (cond
;; [(zero? i) (add1 ((G i) x (sub1 y)))]
;; [(zero? (sub1 i)) ((G (sub1 i)) x ((G i) x (sub1 y)))]
;; [else ((G (sub1 i)) x ((G i) x (sub1 y)))])]))))
;; We found a duplicated line, so we removed it.
;; (define G
;; (λ (i)
;; (λ (x y)
;; (cond
;; [(zero? y)
;; (cond
;; [(zero? i) x]
;; [(zero? (sub1 i)) 0]
;; [else 1])]
;; [else
;; (cond
;; [(zero? i) (add1 ((G i) x (sub1 y)))]
;; [else ((G (sub1 i)) x ((G i) x (sub1 y)))])]))))
;; That [else (cond ...) ...] was a little verbose for our tastes, so we
;; got rid of it.
;; (define G
;; (λ (i)
;; (λ (x y)
;; (cond
;; [(zero? y)
;; (cond
;; [(zero? i) x]
;; [(zero? (sub1 i)) 0]
;; [else 1])]
;; [(zero? i) (add1 ((G i) x (sub1 y)))]
;; [else ((G (sub1 i)) x ((G i) x (sub1 y)))]))))
;; We can get rid of that nested cond by in-lining the (zero? y) test.
;; (define G
;; (λ (i)
;; (λ (x y)
;; (cond
;; [(and (zero? y) (zero? i)) x]
;; [(and (zero? y) (zero? (sub1 i))) 0]
;; [(zero? y) 1]
;; [(zero? i) (add1 ((G i) x (sub1 y)))]
;; [else ((G (sub1 i)) x ((G i) x (sub1 y)))]))))
;; And we really have no need to have nested those function calls, so
;; let's de-nest them.
(define G
(λ (i x y)
(cond
[(and (zero? y) (zero? i)) x]
[(and (zero? y) (zero? (sub1 i))) 0]
[(zero? y) 1]
[(zero? i) (add1 (G i x (sub1 y)))]
[else (G (sub1 i) x (G i x (sub1 y)))])))
| false |
899f8997a7aa6a3ee40a500bbb2c6fb6a5c70c67 | 49d98910cccef2fe5125f400fa4177dbdf599598 | /advent-of-code-2020/day08-py.rkt | 72c88bbeb469cd4e900caf19b7c91c2b0d25e37c | []
| no_license | lojic/LearningRacket | 0767fc1c35a2b4b9db513d1de7486357f0cfac31 | a74c3e5fc1a159eca9b2519954530a172e6f2186 | refs/heads/master | 2023-01-11T02:59:31.414847 | 2023-01-07T01:31:42 | 2023-01-07T01:31:42 | 52,466,000 | 30 | 4 | null | null | null | null | UTF-8 | Racket | false | false | 1,255 | rkt | day08-py.rkt | #lang racket
;; Inspired by a Python solution I saw (Part 2).
(define (run prog)
(let loop ([ pc 0 ][ acc 0 ][ seen (mutable-set) ])
(cond [ (set-member? seen pc) #f ]
[ (>= pc (vector-length prog)) acc ]
[ else
(match-let ([ (vector op arg) (vector-ref prog pc)])
(set-add! seen pc)
(cond [ (string=? "acc" op) (loop (add1 pc) (+ acc arg) seen) ]
[ (string=? "jmp" op) (loop (+ pc arg) acc seen) ]
[ else (loop (add1 pc) acc seen) ]))])))
(module+ main
(define prog (for/vector ([ line (in-list (file->lines "day08.txt")) ])
(let ([ tokens (string-split line) ])
(vector (first tokens) (string->number (second tokens))))))
(let loop ([ i 0 ][ p (vector-copy prog) ])
(match-let* ([ (vector op arg) (vector-ref p i) ])
(if (string=? "acc" op)
(loop (add1 i) p)
(let ([ new-op (if (string=? "nop" op) "jmp" "nop") ])
(vector-set! p i (vector new-op arg))
(let ([ result (run p) ])
(if result
(printf "Accumulator is ~a\n" result)
(loop (add1 i) (vector-copy prog)))))))))
| false |
cd8e63a08e9d21f20bc8ec53704d66932aa4001c | 730c2f6bee9939639bf927f473002ffa620c4672 | /error.rkt | d7911aeb0bb1e02d53eeccc3f3a58f5f565b273e | [
"Apache-2.0",
"MIT"
]
| permissive | sorawee/recursive-language | b933ee3e9268acb8b7239251447870cb0af23b10 | 86be12fe663454922c5b1235b4e3fbb7e8691b2c | refs/heads/master | 2022-09-16T21:19:29.650343 | 2022-09-13T22:19:46 | 2022-09-13T22:19:46 | 121,312,359 | 9 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 731 | rkt | error.rkt | #lang racket/base
(provide raise-with-srcloc)
(require racket/syntax-srcloc
racket/path)
(struct exn:fail:with-srcloc exn:fail:user (loc)
#:property prop:exn:srclocs
(lambda (self) (list (exn:fail:with-srcloc-loc self))))
(define (raise-with-srcloc msg v)
(define sloc
(cond
[(syntax? v) (syntax-srcloc v)]
[else v]))
(define src (srcloc-source sloc))
(raise (exn:fail:with-srcloc
(format "~a:~a:~a: ~a"
(cond
[(path-string? src) (file-name-from-path src)]
[else src])
(srcloc-line sloc)
(srcloc-column sloc)
msg)
(current-continuation-marks)
sloc)))
| false |
a0da59d50e53ae6b63b476c5dc693654433dac4c | ef61a036fd7e4220dc71860053e6625cf1496b1f | /HTDP2e/02-arbitrary-large-data/ch-09-designing-with-self-referential-data/ex-137-comparing-templates.rkt | 0053a24d292c8f9cd2ee787e7e98ce1246389c1f | []
| no_license | lgwarda/racket-stuff | adb934d90858fa05f72d41c29cc66012e275931c | 936811af04e679d7fefddc0ef04c5336578d1c29 | refs/heads/master | 2023-01-28T15:58:04.479919 | 2020-12-09T10:36:02 | 2020-12-09T10:36:02 | 249,515,050 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 844 | rkt | ex-137-comparing-templates.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-abbr-reader.ss" "lang")((modname ex-137-comparing-templates) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
;Exercise 137. Compare the template for contains-flatt? with the one for how-many.
;Ignoring the function name, they are the same. Explain the similarity.
(define (contains-flatt? alon)
(cond
[(empty? alon) ...]
[(cons? alon)
(... (string=? (first alon) "Flatt")
... (cintains-flatt? (rest alon)) ...)]))
(define (fun-for-los alos)
(cond
[(empty? alos) ...]
[else
(... (first alos) ...
... (fun-for-los (rest alos)) ...)]))
| false |
2d6ec4a23bcd5ccbb55a720a837472d256005efb | 4f8e3d5bb35d87afbce203adc55433debbbee954 | /sample-hsm-state.rkt | 2961f7637623a508c8707610d54e9bb7b3c7fe8b | []
| no_license | gallerx/lambda | 6ad37f61d50c43b1fa617b394486ffdead5517c9 | 5397b9de5949d767264ac85261529e9718d59fb0 | refs/heads/master | 2021-01-10T11:14:08.772078 | 2015-11-16T20:53:20 | 2015-11-16T20:53:20 | 46,204,658 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 509 | rkt | sample-hsm-state.rkt | (defnode
#:state S4-1
#:parent S4
#:entry (λ _
(menu! MENU:new-edit)
(with-menu-screen (format "~A Order Menu" (fcdr order-type))))
#:init do-nothing
#:exit do-nothing
#:handler (with-parts (case verb
[(new) (trans this S4-2)] ;back will take you to logout
[(esc) (trans this S2)]
[(edit) (trans this S4-2-7)]
[else #f]))
#:parser px-CG-menu
#:bindings menu)
| false |
37f6f8d71cfacb707c077f908f63db3c08cc8919 | 653bfbbe9572ccbbe986785d4907d66cb1318b54 | /parse-only.rkt | 3bbdae10bc3fe310475c76d88825634862bc1dfa | []
| no_license | sstoltze/logo | f1cc7f56e5cdfb859feace5d2930c926a2cdb458 | 5553ec3a780c2ec33e888c741e5d7511d0d50dbe | refs/heads/master | 2022-03-09T07:49:08.093085 | 2022-02-21T23:41:14 | 2022-02-21T23:41:14 | 179,739,160 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 735 | rkt | parse-only.rkt | #lang racket/base
(module+ reader
(provide read-syntax))
(provide (rename-out [logo-parse-module #%module-begin])
#%app #%datum #%top #%top-interaction
read-syntax)
(require "parser.rkt" "tokenizer.rkt"
(for-syntax syntax/parse
racket/base)
syntax/strip-context)
(define (read-syntax path port)
(define parse-tree (parse path (make-tokenizer port path)))
(strip-context
#`(module logo-parser-mod logo/parse-only
#,parse-tree)))
(define-syntax (logo-parse-module stx)
(syntax-parse stx
[(_ (logo-program statements ...))
#'(#%module-begin
'(parameterize ([current-world (new-world)])
(sleep/yield 1)
statements ...))]))
| true |
8ab3552e337b9029e6e131ab83643b62b7ae9a78 | ded5174b1e1554f106022689d479bb7197d62082 | /Racket/add-two-lists.rkt | 796025841a9b7c173d1b147471c4e2a6c449a9ab | []
| no_license | nadazeini/Programming-Paradigms | e968d8669cde01caf7ec51fa18bbd675eae2324e | cc3cbcb57d6acc93521b032a5bbc4bc19bb47d18 | refs/heads/master | 2020-09-23T10:38:51.526457 | 2019-12-15T00:42:43 | 2019-12-15T00:42:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 466 | rkt | add-two-lists.rkt | #lang racket
(provide add-two-lists)
(define (add-two-lists lst1 lst2)
(cond
[(null? lst1) lst2]
[(null? lst2) lst1]
[else (cons(+ (car lst1) (car lst2)) (add-two-lists (cdr lst1) (cdr lst2)))]
)
)
(add-two-lists '(1000 1) '(90 21 1))
;Correction
;(define (add-two-lists lst1 lst2)
;(cond
;[(empty? lst1) lst2]
; [empty? lst2] lst1)
; [else (cons
;(+ (car lst) (car lst2))
;(add-two-lists (cdr lst1) (cdr lst2)))]
;) | false |
51037f66986347aa030728276cc3dbc6d217fc23 | 98fd12cbf428dda4c673987ff64ace5e558874c4 | /paip/will/faster-miniKanren/test-all.rktl | e3bf0125c866d1edf14622bff37202702e7abcf2 | [
"MIT",
"Unlicense"
]
| permissive | CompSciCabal/SMRTYPRTY | 397645d909ff1c3d1517b44a1bb0173195b0616e | a8e2c5049199635fecce7b7f70a2225cda6558d8 | refs/heads/master | 2021-12-30T04:50:30.599471 | 2021-12-27T23:50:16 | 2021-12-27T23:50:16 | 13,666,108 | 66 | 11 | Unlicense | 2019-05-13T03:45:42 | 2013-10-18T01:26:44 | Racket | UTF-8 | Racket | false | false | 94 | rktl | test-all.rktl | #lang racket/load
(require "main.rkt")
(load "test-all.scm")
(when test-failed
(exit 1))
| false |
67d3f92a06aef25f81cd35ebc0a13ded6bfab45b | 24d1a79102839205087966654e33c603bcc41b37 | /scheme/blueboxes.rktd | ebfab996ab26c19276d7c6b0b51014f8f0fd44c0 | []
| no_license | Racket-zh/docs | 4a091e51701325910b93c2cc5f818487e2bca4be | 741be262485a783e66b8e6d1b8a1114f7799e59e | refs/heads/master | 2020-03-19T12:14:21.965606 | 2018-09-10T01:12:30 | 2018-09-10T01:12:54 | 136,505,509 | 5 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 2,805 | rktd | blueboxes.rktd | 1025
((3) 0 () 5 ((q lib "scheme/foreign.rkt") (q lib "scheme/base.rkt") (q lib "scheme/sandbox.rkt") (q 973 . 17) (q lib "scheme/gui/base.rkt")) () (h ! (equal) ((c def c (c (? . 2) q make-module-evaluator)) c (? . 3)) ((c def c (c (? . 1) q make-base-empty-namespace)) q (0 . 2)) ((c form c (c (? . 0) q unsafe!)) q (163 . 2)) ((c form c (c (? . 0) q provide*)) q (180 . 6)) ((c form c (c (? . 1) q #%module-begin)) q (96 . 2)) ((q def ((lib "scheme/class.rkt") printable<%>)) q (131 . 2)) ((c def c (c (? . 4) q make-gui-namespace)) q (439 . 2)) ((c def c (c (? . 2) q make-evaluator)) c (? . 3)) ((c form c (c (? . 0) q define-unsafer)) q (361 . 2)) ((c def c (c (? . 1) q make-base-namespace)) q (51 . 2)) ((c def c (c (? . 2) q sandbox-namespace-specs)) q (706 . 6)) ((q def ((lib "scheme/pretty.rkt") pretty-print)) q (594 . 4)) ((q def ((lib "scheme/gui/dynamic.rkt") gui-dynamic-require)) q (483 . 3)) ((c def c (c (? . 4) q make-gui-empty-namespace)) q (389 . 2)) ((q form ((lib "scheme/nest.rkt") nest)) q (546 . 2))))
函数
(make-base-empty-namespace) -> namespace?
函数
(make-base-namespace) -> namespace?
语法
(#%module-begin form ...)
值
printable<%> : interface?
语法
(unsafe!)
语法
(provide* provide-star-spec ...)
provide-star-spec = (unsafe id)
| (unsafe (rename-out [id external-id]))
| provide-spec
语法
(define-unsafer id)
函数
(make-gui-empty-namespace) -> namespace?
函数
(make-gui-namespace) -> namespace?
函数
(gui-dynamic-require sym) -> any
sym : symbol?
语法
(nest ([datum ...+] ...) body ...+)
函数
(pretty-print v [port]) -> void?
v : any/c
port : output-port? = (current-output-port)
parameter
(sandbox-namespace-specs) -> (cons/c (-> namespace?)
(listof module-path?))
(sandbox-namespace-specs spec) -> void?
spec : (cons/c (-> namespace?)
(listof module-path?))
函数
(make-evaluator language
input-program ...
#:requires requires
#:allow-read allow) -> (any/c . -> . any)
language : (or/c module-path?
(list/c 'special symbol?)
(cons/c 'begin list?))
input-program : any/c
requires : (listof (or/c module-path? path?))
allow : (listof (or/c module-path? path?))
(make-module-evaluator module-decl
#:language lang
#:allow-read allow) -> (any/c . -> . any)
module-decl : (or/c syntax? pair?)
lang : (or/c #f module-path?)
allow : (listof (or/c module-path? path?))
| false |
efe91422beb553d5a6fc028513316555c534174f | e866ea5d522306eca07841c9eae59d08545ea980 | /errortrace-test/tests/errortrace/phase-0-eval.rkt | 026134dece4ccc12ea4f172e3e5f8f3fcde3935c | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | racket/errortrace | 8d82d4fcbd4c8e915ddbb3cc36a9397a0d59408b | 6fb1bd2a1c2de8af52d2bc85d096347381d17fee | refs/heads/master | 2023-08-17T18:43:36.746471 | 2022-10-03T22:25:09 | 2022-10-03T22:25:09 | 27,431,204 | 9 | 16 | NOASSERTION | 2022-10-02T21:53:05 | 2014-12-02T12:19:08 | Racket | UTF-8 | Racket | false | false | 1,287 | rkt | phase-0-eval.rkt | #lang racket/base
(provide phase-0-eval-tests)
;; A Test case from @florence in issue #14
;;
;; When phase-1-eval is required for-template, the evaluation takes place at phase 0,
;; so errortrace will generate top-level #%requires after annotating '(+ 1 2).
;;
;; we need to use namespace-base-phase (which is 0) for these top-level #%requires
;; instead of syntax-local-phase-level (which is -1), which should be used for #%requires
;; inside phase-1-eval.
(define (phase-0-eval-tests)
;; In 'phase-1-eval, we are evaling in the namespace of racket/base.
;; Therefore we re-load racket/base in a fresh empty namespace
;; to avoid affecting other programs.
(define source-namespace (current-namespace))
(parameterize ([current-namespace (make-empty-namespace)])
(namespace-attach-module source-namespace ''#%builtin)
(namespace-require 'racket/base)
(dynamic-require 'errortrace #f)
(eval '(module phase-1-eval racket/base
(require (for-syntax racket/base))
(begin-for-syntax
(parameterize ([current-namespace (module->namespace 'racket/base)])
(eval '(+ 1 2))))))
(eval '(module template racket/base
(require (for-template 'phase-1-eval))))
(dynamic-require ''template #f)))
| false |
81c17563a2357538325e51af93ac7d956588b11b | a18b561b599c8e85d697ecb421fe98cbb41814d1 | /planet/planet-generation.rkt | 7bd73f0a406046125393eff37894537ceb18b316 | []
| no_license | his1220/earthgen | f501f1c6b91831adc3072e4dc7bbe5b9f7045793 | 0fd1904905fea41a441e7494388d734e298b77bc | refs/heads/master | 2021-01-18T15:14:11.895611 | 2015-03-20T19:50:30 | 2015-03-20T20:35:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 200 | rkt | planet-generation.rkt | #lang typed/racket
(require "require-provide.rkt")
(require/provide "heightmap.rkt"
"terrain-generation/planet-create.rkt"
"climate-generation/climate-create.rkt")
| false |
fc9fa8522d4467ff040aaf99958a6c5d81033f95 | 1869dabbedbb7bb1f4477a31020633b617eef27f | /mmcu/msp430/hints.rkt | 0878e81cef3381cd8a03c029296378256123a8e0 | [
"MIT"
]
| permissive | billzorn/SAT | 0e64e60030162a64026fafb2dc1ab6b40fb09432 | 664f5de7e7f1b5b25e932fc30bb3c10410d0c217 | refs/heads/master | 2021-01-12T03:04:31.815667 | 2017-09-22T00:02:50 | 2017-09-22T00:02:50 | 78,153,696 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 846 | rkt | hints.rkt | #lang racket
(provide (all-defined-out))
(define (bitwidth-hint opname)
(printf "~a\n" opname)
(cond
[(string-prefix? opname "dadd") '(4 4 8 8 8)]
[(string-suffix? opname ".b") 8]
[(string-suffix? opname ".w") 16]
[(string-suffix? opname ".a") 20]
[else (error "not an msp430 op name")]))
(define (strategy-hint opname)
(case opname
[("dadd.b" "dadd.w" "dadd.a") '(n4-up n4-up full full full)]
[else 'full]))
(define (maxlength-hint opname)
(case opname
[("mov.b" "mov.w" "movx.a") '(1 1 1 1 1)]
[("add.b" "add.w" "addx.a") '(1 4 4 4 4)]
[("sub.b" "sub.w" "subx.a") '(1 4 4 4 4)]
[("xor.b" "xor.w" "xorx.a") '(1 4 4 4 4)]
[("and.b" "and.w" "andx.a") '(1 4 4 4 4)]
[("dadd.b" "dadd.w" "daddx.a") '(8 8 8 8 8)]
[else '(4 4 4 4 4)]))
| false |
e14ea3fa000856ca90defdcbb143786f1a1e99ba | e0e034ad413094e2b96d188d900712b56cc54c27 | /mm/tests/collectors/infinite.rkt | 6283a5d55108e1e9b907544abff98aa28f2fe5c3 | []
| no_license | jeapostrophe/mm | 2344c9ea9d69ce513a263887c51ac632698f4413 | 6160ca48a0f45617e98709ff5bd31e91dbdaebca | refs/heads/master | 2022-12-21T11:48:08.313942 | 2022-12-02T20:35:52 | 2022-12-02T20:35:52 | 14,350,936 | 0 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 1,697 | rkt | infinite.rkt | #lang racket/base
(require data/gvector
mm)
(define infinite-heap-collector@
(collector
(define HEAP (make-gvector))
(define (gvector->disp g)
(for/list ([i (in-naturals)]
[e (in-gvector g)])
(cons i e)))
;; Uses
(define (closure-allocate k f fvs)
(define a (gvector-count HEAP))
(gvector-add! HEAP 'closure f)
(for ([fv (in-vector fvs)])
(gvector-add! HEAP fv))
(return k a))
(define (closure? a)
(eq? 'closure (gvector-ref HEAP a)))
(define (closure-code-ptr a)
(gvector-ref HEAP (+ a 1)))
(define (closure-env-ref a i)
(gvector-ref HEAP (+ a 2 i)))
(define (atomic-allocate k x)
(define a (gvector-count HEAP))
(gvector-add! HEAP 'atomic x)
(return k a))
(define (atomic? a)
(eq? 'atomic (gvector-ref HEAP (+ a 0))))
(define (atomic-deref a)
(gvector-ref HEAP (+ a 1)))
(define (cons-allocate k f r)
(define a (gvector-count HEAP))
(gvector-add! HEAP 'cons f r)
(return k a))
(define (cons? a)
(eq? 'cons (gvector-ref HEAP (+ a 0))))
(define (cons-first a)
(gvector-ref HEAP (+ a 1)))
(define (cons-rest a)
(gvector-ref HEAP (+ a 2)))
(define (cons-set-first! a nf)
(gvector-set! HEAP (+ a 1) nf))
(define (cons-set-rest! a nf)
(gvector-set! HEAP (+ a 2) nf))
(define (box-allocate k b)
(define a (gvector-count HEAP))
(gvector-add! HEAP 'box b)
(return k a))
(define (box? a)
(eq? 'box (gvector-ref HEAP (+ a 0))))
(define (box-deref a)
(gvector-ref HEAP (+ a 1)))
(define (box-set! a nb)
(gvector-set! HEAP (+ a 1) nb))))
(provide (all-defined-out))
| false |
6372a1cc7735bfd26881bb2ac8b8d3f621ce96c3 | 821e50b7be0fc55b51f48ea3a153ada94ba01680 | /exp4/guide/scribble/sigplan.rkt | e59d808533c83bdb3ba1ae5dd19c91e41dbb1c3b | []
| no_license | LeifAndersen/experimental-methods-in-pl | 85ee95c81c2e712ed80789d416f96d3cfe964588 | cf2aef11b2590c4deffb321d10d31f212afd5f68 | refs/heads/master | 2016-09-06T05:22:43.353721 | 2015-01-12T18:19:18 | 2015-01-12T18:19:18 | 24,478,292 | 1 | 0 | null | 2014-12-06T20:53:40 | 2014-09-25T23:00:59 | Racket | UTF-8 | Racket | false | false | 4,507 | rkt | sigplan.rkt | #lang scheme/base
(require setup/main-collects
racket/contract/base
scribble/core
scribble/base
scribble/decode
scribble/html-properties
scribble/latex-properties
(for-syntax scheme/base))
(provide/contract
[abstract
(->* () () #:rest (listof pre-content?)
block?)]
[subtitle
(->* () () #:rest (listof pre-content?)
content?)]
[authorinfo
(-> pre-content? pre-content? pre-content?
block?)]
[conferenceinfo
(-> pre-content? pre-content?
block?)]
[copyrightyear
(->* () () #:rest (listof pre-content?)
block?)]
[copyrightdata
(->* () () #:rest (listof pre-content?)
block?)]
[category
(->* (pre-content? pre-content? pre-content?)
((or/c false/c pre-content?))
content?)]
[terms
(->* () () #:rest (listof pre-content?)
content?)]
[keywords
(->* () () #:rest (listof pre-content?)
content?)])
(provide preprint 10pt nocopyright onecolumn noqcourier notimes
include-abstract)
(define-syntax-rule (defopts name ...)
(begin (define-syntax (name stx)
(raise-syntax-error #f
"option must appear on the same line as `#lang scribble/sigplan'"
stx))
...
(provide name ...)))
(defopts preprint 10pt nocopyright onecolumn noqcourier notimes)
(define sigplan-extras
(let ([abs (lambda (s)
(path->main-collects-relative
(collection-file-path s "scribble" "sigplan")))])
(list
(make-css-addition (abs "sigplan.css"))
(make-tex-addition (abs "sigplan.tex")))))
;; ----------------------------------------
;; Abstracts:
(define abstract-style (make-style "abstract" sigplan-extras))
(define (abstract . strs)
(make-nested-flow
abstract-style
(decode-flow strs)))
(define (extract-abstract p)
(unless (part? p)
(error 'include-abstract "doc binding is not a part: ~e" p))
(unless (null? (part-parts p))
(error 'include-abstract "abstract part has sub-parts: ~e" (part-parts p)))
(when (part-title-content p)
(error 'include-abstract "abstract part has title content: ~e" (part-title-content p)))
(part-blocks p))
(define-syntax-rule (include-abstract mp)
(begin
(require (only-in mp [doc abstract-doc]))
(make-nested-flow abstract-style (extract-abstract abstract-doc))))
;; ----------------------------------------
;; Authors and conference info:
(define (authorinfo name affiliation e-mail)
;; The \SAuthor macro in "style.tex" looks specifically
;; for an \SAuthorinfo as its argument, and handles it
;; specially in that case:
(author
(make-multiarg-element
(make-style "SAuthorinfo" sigplan-extras)
(list
(make-element #f (decode-content (list name)))
(make-element (make-style "SAuthorPlace" sigplan-extras)
(decode-content (list affiliation)))
(make-element (make-style "SAuthorEmail" sigplan-extras)
(decode-content (list e-mail)))))))
(define (subtitle . str)
(make-element (make-style "SSubtitle" (append '(aux) sigplan-extras))
(decode-content str)))
(define (conferenceinfo what where)
(make-paragraph
(make-style 'pretitle null)
(make-multiarg-element
(make-style "SConferenceInfo" sigplan-extras)
(list
(make-element #f (decode-content (list what)))
(make-element #f (decode-content (list where)))))))
(define (copyrightyear . when)
(make-paragraph
(make-style 'pretitle null)
(make-element
(make-style "SCopyrightYear" sigplan-extras)
(decode-content when))))
(define (copyrightdata . what)
(make-paragraph
(make-style 'pretitle null)
(make-element
(make-style "SCopyrightData" sigplan-extras)
(decode-content what))))
;; ----------------------------------------
;; Categories, terms, and keywords:
(define (category sec title sub [more #f])
(make-multiarg-element
(make-style (format "SCategory~a" (if more "Plus" "")) sigplan-extras)
(list*
(make-element #f (decode-content (list sec)))
(make-element #f (decode-content (list title)))
(make-element #f (decode-content (list sub)))
(if more
(list (make-element #f (decode-content (list more))))
null))))
(define (terms . str)
(make-element (make-style "STerms" sigplan-extras) (decode-content str)))
(define (keywords . str)
(make-element (make-style "SKeywords" sigplan-extras) (decode-content str)))
| true |
68a5249b7a20cde2eeb1062341fae84917ae9618 | 52ca952ca461cadbed7cfa0867b870106e939804 | /Carleton CS/2017 Fall CS/Functional Programming/Assignments/A2/Ass2/sammy.rkt | 6ef559abe6aaf1704e283059c65c868dc7d22fdd | []
| no_license | flintlovesam/CarletonComputerScience | 055913b9fc82cad06b1115aeb6b13796b6541b9c | 601d6aea84e1835cd5ce0d27db4e7b031d9752aa | refs/heads/master | 2021-04-17T13:17:52.071173 | 2018-06-24T15:44:23 | 2018-06-24T15:44:23 | 249,448,153 | 1 | 0 | null | 2020-03-23T14:07:47 | 2020-03-23T14:07:46 | null | UTF-8 | Racket | false | false | 668 | rkt | sammy.rkt | ; WAY 1
(define (sum term a next b)
(if (> a b)
0
(+ (term a)
(sum term (next a) next b))
))
; way NUMBER 2
(define (inc x) (+ x 1))
(define (identity x) x)
(define (sum-integers a b)
(sum identity a inc b))
(sum-integers 0 10)
(sum identity 0 inc 10)
(sum identity 0 inc 10) ;identity 0 .... 0 && inc 10.....11
; a is not greater than b...so (+ (term a)(sum term (next a) next b))
(sum term a next b)
(+ (identity 0)(sum identity (next a) next b)) ;next a = 1 in this case
(+ (identity 0)(sum identity (next 0) next 10))
(sum-integers 0 2)
| false |
5c957ebc3ada7cb42b6e1511048e1e5c9153f9cd | d61ea677f3667daeb0dfd6c1ead321e6685420f2 | /nanopass_tutorial/tutorial/tutorial-more-pass.rkt | f21ec136b0bfc9f93d8f36507a8262c1cc80f4d1 | []
| no_license | arbipher/misc | 23f863fce7c6a43bbda22d565c7f64b2d3aa9c31 | 5ff1ce56efe9c3878bc78b9856b83f3fe2c7bb35 | refs/heads/master | 2022-11-24T20:18:08.929064 | 2022-11-20T02:05:40 | 2022-11-20T02:05:40 | 43,484,588 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 3,015 | rkt | tutorial-more-pass.rkt | #lang nanopass
(define (foo? x)
(eq? x 'Foo))
(define (bar? x)
(eq? x 'Bar))
(define bv 'Bar)
(define-language FooBar
(terminals
(foo (f))
(bar (b)))
(Expr (e)
(e* ... e)
(F f)
(B b)))
(define-parser parse-FooBar FooBar)
(define-pass removeFoo : FooBar (e) -> FooBar ()
(Expr : Expr (e) -> Expr ()
[(F ,f) `(B ,bv)]))
(removeFoo
(parse-FooBar
'(
(F Foo)
(F Foo))))
(define-pass removeFoo2 : FooBar (e) -> FooBar ()
(Expr : Expr (e) -> Expr ()
[(,[e*] ... ,[e]) `(,e* ... ,e)]
[(F ,f) `(B ,bv)]))
(removeFoo2
(parse-FooBar
'(
(F Foo)
(F Foo))))
(define-pass removeFoo3 : FooBar (e) -> FooBar ()
(Expr : Expr (e) -> Expr ()
[(,e* ... ,e) `(,e* ... ,(Expr e))]
[(F ,f) `(B ,bv)]))
(removeFoo3
(parse-FooBar
'(
(F Foo)
(F Foo))))
(define-pass removeFoo4 : FooBar (e) -> FooBar ()
(Expr : Expr (e) -> Expr ()
[(,e* ... ,e) `(,(Expr e*) ... ,(Expr e))]
[(F ,f) `(B ,bv)]))
;nanopass-record-tag: contract violation
; expected: nanopass-record?
; given: '(#<language:FooBar: (F Foo)>)
#;(removeFoo4
(parse-FooBar
'(
(F Foo)
(F Foo))))
(define-pass removeFoo5 : FooBar (e) -> FooBar ()
(Expr : Expr (e) -> Expr ()
[(,e* ... ,e) `(,(map Expr e*) ... ,(Expr e))]
[(F ,f) `(B ,bv)]))
(removeFoo5
(parse-FooBar
'(
(F Foo)
(F Foo))))
(define-language FooBarEmpty
(terminals
(foo (f))
(bar (b)))
(Expr (e)
(e* ...)
(F f)
(B b)))
(define-parser parse-FooBarEmpty FooBarEmpty)
(define-pass removeFoo6 : FooBarEmpty (e) -> FooBarEmpty ()
(Expr : Expr (e) -> Expr ()
[(,e* ... ) `(,(map Expr e*) ... )]
[(F ,f) `(B ,bv)]))
(removeFoo6
(parse-FooBarEmpty
'(
(F Foo)
(F Foo))))
(define-pass removeFoo7 : FooBar (e) -> FooBar ()
(Expr : Expr (ex) -> Expr ()
[(,e* ... ,e)
(display (list? e*))
(display (list? (append e* (list e))))
`(,(map Expr (append e* (list e))) ...)]
[(F ,f) `(B ,bv)]))
;removeFoo7: expected Expr but received (#<language:FooBar: (B Bar)> #<language:FooBar: (B Bar)>) in field e of (e* ... e) from expression (map Expr (append e* (list e))) /Users/ex/Desktop/workspace/odefa2/nano/nanodefa/tutorial-cata.rkt:106.12
#;(removeFoo7
(parse-FooBar
'(
(F Foo)
(F Foo))))
(define-pass removeFoo8 : FooBarEmpty (e) -> FooBarEmpty ()
(Expr : Expr (e) -> Expr ()
[(,e* ... ) `(,(map Expr (append e* (list `(B ,bv)))) ... )]
[(F ,f) `(B ,bv)]))
(removeFoo8
(parse-FooBarEmpty
'(
(F Foo)
(F Foo))))
(define-pass removeFoo9 : FooBar (e) -> FooBar ()
(Expr : Expr (ex) -> Expr ()
[(,e* ... ,e)
(let* ([es (append e* (list e))]
[nes (map Expr es)])
;(match-define `(,ne* ... ,ne) nes)
;`(,ne* ... ,ne))
`(,(drop-right nes 1) ... ,(last nes)))
]
[(F ,f) `(B ,bv)]))
(removeFoo9
(parse-FooBar
'(
(F Foo)
(F Foo)))) | false |
7aadffe2a9c455cb46562f78c436d20b03cc8412 | 047744359fd42f8a32cc5f62daa909ea0721804d | /automata/queries.rkt | 02420fff2f36a5854cf6f6da37dd38595c69888a | []
| no_license | bboskin/Log-Data-Feature-Gen | 80dd5e9b45796481f326e513f01a957e6406e4c2 | 7fd88a65c5bc950ae80cd9eba7f1c3a41ad0ba35 | refs/heads/master | 2022-11-29T23:08:34.217853 | 2020-07-15T02:12:15 | 2020-07-15T02:12:15 | 274,759,933 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,465 | rkt | queries.rkt | #lang racket
(require "basics.rkt")
(provide find-words accept? random-word take-words)
(define-syntax accept?
(syntax-rules ()
[(_ M w) (accept? M w #f)]
[(_ M w disp?)
(run/fast M
`(,w)
(λ (_) #f)
(λ (e) e)
(λ (a) (null? (car a)))
(list (λ (_1 _2 acc) (cdr acc)))
#f
(λ (a A) #t)
(λ (_ a) (if (null? (car a)) '() (list (caar a))))
disp?)]))
(define-syntax find-words
(syntax-rules ()
[(_ M k) (find-words M k #f)]
[(_ M k disp?)
(run/bfs
M
'(())
(λ (a) (> (length (car a)) k))
(λ (x) #f)
(λ (a) #t)
(list (λ (_ i a) (snoc i a)))
'()
(λ (a A) (set-cons (car a) A))
(λ (Σ _) Σ)
disp?)]))
(define-syntax random-word
(syntax-rules ()
[(_ M k) (random-word M k #f)]
[(_ M k disp?)
(run/fast
M
'(())
(λ (a) #f)
(λ (x) x)
(λ (a) #t)
(list (λ (_ i a) (snoc i a)))
#f
(λ (a A) (if A A (if (<= k (length (car a))) (car a) #f)))
(λ (Σ _) (shuffle Σ))
disp?)]))
(define-syntax take-words
(syntax-rules ()
[(_ M k) (take-words M k #f)]
[(_ M k disp?)
(run/fast
M
'(())
(λ (a) #f)
(λ (A) (>= (length A) k))
(λ (a) #t)
(list (λ (_ i a) (snoc i a)))
'()
(λ (a A) (set-cons (car a) A))
(λ (Σ _) Σ)
disp?)]))
| true |
12078926b3a1e5609fe2a78ca46a5e0d51516ada | ea4a41b03c6d95c956655af36a8e955620714e7e | /interp-Cvar.rkt | 09a212dd43416ca7575ff091de3670a77785476d | [
"MIT"
]
| permissive | IUCompilerCourse/public-student-support-code | 9932dec1499261370c554690cee983d569838597 | 58c425df47b304895725434b441d625d2711131f | refs/heads/master | 2023-08-13T07:29:56.236860 | 2023-06-05T18:05:29 | 2023-06-05T18:05:29 | 145,449,207 | 141 | 70 | MIT | 2023-08-23T01:16:47 | 2018-08-20T17:26:01 | Racket | UTF-8 | Racket | false | false | 986 | rkt | interp-Cvar.rkt | #lang racket
(require racket/fixnum)
(require racket/dict)
(require "utilities.rkt")
(require "interp-Lvar.rkt")
(provide interp-Cvar interp-Cvar-mixin)
(define (interp-Cvar-mixin super-class)
(class super-class
(super-new)
(inherit interp-exp)
(define/public (interp-stmt env)
(lambda (s)
(match s
[(Assign (Var x) e)
(dict-set env x ((interp-exp env) e))]
[else
(error 'interp-stmt "unmatched ~a" s)]
)))
(define/public (interp-tail env)
(lambda (t)
(match t
[(Return e)
((interp-exp env) e)]
[(Seq s t2)
(define new-env ((interp-stmt env) s))
((interp-tail new-env) t2)]
)))
(define/override (interp-program p)
(match p
[(CProgram _ `((start . ,t)))
((interp-tail '()) t)]
))
))
(define (interp-Cvar p)
(send (new (interp-Cvar-mixin interp-Lvar-class)) interp-program p))
| false |
bdeb6e0f6d1aef8f2723005d43eec27ac4c06513 | bdb6b8f31f1d35352b61428fa55fac39fb0e2b55 | /sicp/ex3.33-3.37.rkt | 9484277cfab9d990027c6dc8bfbe093ecf38088d | []
| no_license | jtskiba/lisp | 9915d9e5bf74c3ab918eea4f84b64d7e4e3c430c | f16edb8bb03aea4ab0b4eaa1a740810618bd2327 | refs/heads/main | 2023-02-03T15:32:11.972681 | 2020-12-21T21:07:18 | 2020-12-21T21:07:18 | 323,048,289 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 9,324 | rkt | ex3.33-3.37.rkt | #lang racket
(require racket/mpair)
(require compatibility/mlist)
(define (has-value? connector)
(connector 'has-value?))
(define (get-value connector)
(connector 'value))
(define (set-value! connector
new-value
informant)
((connector 'set-value!)
new-value
informant))
(define (forget-value! connector retractor)
((connector 'forget) retractor))
(define (connect connector new-constraint)
((connector 'connect) new-constraint))
(define (for-each-except exception
procedure
list)
(define (loop items)
(cond ((null? items) 'done)
((eq? (car items) exception)
(loop (cdr items)))
(else (procedure (car items))
(loop (cdr items)))))
(loop list))
(define (make-connector)
(let ((value false)
(informant false)
(constraints '()))
(define (set-my-value newval setter)
(cond ((not (has-value? me))
(set! value newval)
(set! informant setter)
(for-each-except
setter
inform-about-value
constraints))
((not (= value newval))
(error "Contradiction"
(list value newval)))
(else 'ignored)))
(define (forget-my-value retractor)
(if (eq? retractor informant)
(begin (set! informant false)
(for-each-except
retractor
inform-about-no-value
constraints))
'ignored))
(define (connect new-constraint)
(if (not (memq new-constraint
constraints))
(set! constraints
(cons new-constraint
constraints))
'ok)
(if (has-value? me)
(inform-about-value new-constraint)
'ok)
'done)
(define (me request)
(cond ((eq? request 'has-value?)
(if informant true false))
((eq? request 'value) value)
((eq? request 'set-value!)
set-my-value)
((eq? request 'forget)
forget-my-value)
((eq? request 'connect) connect)
(else (error "Unknown operation:
CONNECTOR"
request))))
me))
(define (celsius-fahrenheit-converter c f)
(let ((u (make-connector))
(v (make-connector))
(w (make-connector))
(x (make-connector))
(y (make-connector)))
(multiplier c w u)
(multiplier v x u)
(adder v y f)
(constant 9 w)
(constant 5 x)
(constant 32 y)
'ok))
(define (adder a1 a2 sum)
(define (process-new-value)
(cond ((and (has-value? a1)
(has-value? a2))
(set-value! sum
(+ (get-value a1)
(get-value a2))
me))
((and (has-value? a1)
(has-value? sum))
(set-value! a2
(- (get-value sum)
(get-value a1))
me))
((and (has-value? a2)
(has-value? sum))
(set-value! a1
(- (get-value sum)
(get-value a2))
me))))
(define (process-forget-value)
(forget-value! sum me)
(forget-value! a1 me)
(forget-value! a2 me)
(process-new-value))
(define (me request)
(cond ((eq? request 'I-have-a-value)
(process-new-value))
((eq? request 'I-lost-my-value)
(process-forget-value))
(else (error "Unknown request:
ADDER" request))))
(connect a1 me)
(connect a2 me)
(connect sum me)
me)
(define (multiplier m1 m2 product)
(define (process-new-value)
(cond ((or (and (has-value? m1)
(= (get-value m1) 0))
(and (has-value? m2)
(= (get-value m2) 0)))
(set-value! product 0 me))
((and (has-value? m1)
(has-value? m2))
(set-value! product
(* (get-value m1)
(get-value m2))
me))
((and (has-value? product)
(has-value? m1))
(set-value! m2
(/ (get-value product)
(get-value m1))
me))
((and (has-value? product)
(has-value? m2))
(set-value! m1
(/ (get-value product)
(get-value m2))
me))))
(define (process-forget-value)
(forget-value! product me)
(forget-value! m1 me)
(forget-value! m2 me)
(process-new-value))
(define (me request)
(cond ((eq? request 'I-have-a-value)
(process-new-value))
((eq? request 'I-lost-my-value)
(process-forget-value))
(else
(error "Unknown request:
MULTIPLIER"
request))))
(connect m1 me)
(connect m2 me)
(connect product me)
me)
(define (constant value connector)
(define (me request)
(error "Unknown request: CONSTANT"
request))
(connect connector me)
(set-value! connector value me)
me)
(define (probe name connector)
(define (print-probe value)
(newline) (display "Probe: ")
(display name) (display " = ")
(display value))
(define (process-new-value)
(print-probe (get-value connector)))
(define (process-forget-value)
(print-probe "?"))
(define (me request)
(cond ((eq? request 'I-have-a-value)
(process-new-value))
((eq? request 'I-lost-my-value)
(process-forget-value))
(else (error "Unknown request:
PROBE" request))))
(connect connector me)
me)
(define (inform-about-value constraint)
(constraint 'I-have-a-value))
(define (inform-about-no-value constraint)
(constraint 'I-lost-my-value))
(define C (make-connector))
(define F (make-connector))
(celsius-fahrenheit-converter C F)
(probe "Celsius temp" C)
(probe "Fahrenheit temp" F)
(set-value! C 25 'user)
(forget-value! C 'user)
(set-value! F 212 'user)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
'(Ex3.33)
;Ex 3.33
(define (averager a b c)
(let ((u (make-connector))
(x (make-connector)))
(adder a b u)
(multiplier c x u)
(constant 2 x)
'ok))
(define a (make-connector))
(define b (make-connector))
(define c (make-connector))
(averager a b c)
(probe "Value of a" a)
(probe "Value of b" b)
(probe "Average value" c)
(set-value! a 2 'user)
(set-value! c 4 'user)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
'(Ex3.34)
;Ex 3.34
(define (squarer a1 b1) (multiplier a1 a1 b1))
(define a1 (make-connector))
(define b1 (make-connector))
(squarer a1 b1)
(probe "Value of a1" a1)
(probe "Value of b1" b1)
(set-value! b1 4 'user)
; problem is that our multiplier routine does not have a situation defined whereby both m1 and m2 are the same and without value. We would need to add a conditon to say that
; if it has product and both m1 and m2 have no value then, essentially set both m1 and m2 to the square root of the product.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
'(Ex3.35)
;Ex 3.35
(define (squarer2 a b)
(define (process-new-value)
(if (has-value? b)
(if (< (get-value b) 0)
(error "square less than 0:
SQUARER"
(get-value b))
(set-value! a
(sqrt (get-value b))
me))
(set-value! b
(* (get-value a) (get-value a))
me)))
(define (process-forget-value)
(forget-value! a me)
(forget-value! b me)
(process-new-value))
(define (me request)
(cond ((eq? request 'I-have-a-value)
(process-new-value))
((eq? request 'I-lost-my-value)
(process-forget-value))
(else
(error "Unknown request:
SQUARER2"
request))))
(connect a me)
(connect b me)
me)
(define (my-squarer a2 b2) (squarer2 a2 b2))
(define a2 (make-connector))
(define b2 (make-connector))
(my-squarer a2 b2)
(probe "Value of a2" a2)
(probe "Value of b2" b2)
(set-value! b2 4 'user)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
'(Ex3.36 - skipped, read only for now)
;Ex 3.36
; https://wizardbook.wordpress.com/2010/12/17/exercise-3-36/
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
'(Ex3.37)
;Ex 3.37
(define (c+ x y)
(let ((z (make-connector)))
(adder x y z)
z))
(define (c- x y)
(let ((z1 (make-connector))
(z2 (make-connector)))
(adder x (multiplier (cv -1) y z1) z2)
z2))
(define (c* x y)
(let ((z (make-connector)))
(multiplier x y z)
z))
(define (cv x)
(let ((z (make-connector)))
(constant x z)
z))
(define (c/ x y)
(let ((z (make-connector)))
(multiplier z y x)
z))
(define (celsius-fahrenheit-converter2 x)
(c+ (c* (c/ (cv 9) (cv 5))
x)
(cv 32)))
(define CC (make-connector))
(define FF (celsius-fahrenheit-converter2 CC))
(celsius-fahrenheit-converter2 CC)
(probe "Value of CC" CC)
(probe "Value of FF" FF)
(set-value! CC 30 'user)
| false |
78f95bdb78b2cbade7f47a28d2c7862586f0c4d5 | 0980a84e0f54d2c5eda5bcc76ef7bd21a1646d08 | /provee/diff/display.rkt | ce8ea5e1abadd4527f7ba553cb97e8e4575525e1 | []
| no_license | 198d/provee | 9e43ff630e9c1a8a60426ccdf58040bff32c6a56 | dcbc859b3ab8821365a7f7286571dbea9a6ab635 | refs/heads/master | 2021-01-18T14:32:04.342676 | 2016-09-16T08:10:10 | 2016-09-16T08:10:10 | 68,032,931 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 4,622 | rkt | display.rkt | #lang racket
(provide diff->string)
(require "../diff.rkt")
(define (string-append-safe . strs)
(apply
string-append
(filter string? (flatten strs))))
(define (format-lines prefix diff lines)
(string-join
(for/list ([line (in-list lines)])
(format "~a ~a"
prefix
((diff-value-formatter diff) line)))
"\n"))
(define format-added-lines (curry format-lines ">"))
(define format-removed-lines (curry format-lines "<"))
(define (format-line-range start len)
(if (> len 1)
(format "~a,~a" start
(+ start (- len 1)))
(format "~a" start)))
(define (include-line-numbers? diff)
(list? (member (diff-type diff) (list 'file/contents))))
(define (format-line-numbers left-start left-length right-start
right-length action)
(let ([true-left-start (if (equal? action 'a)
(- left-start 1)
left-start)]
[true-right-start (if (equal? action 'd)
(- right-start 1)
right-start)])
(format "~a~a~a"
(format-line-range true-left-start left-length)
action
(format-line-range true-right-start right-length))))
(define (format-added-section diff left-line-number right-line-number vals)
(string-append-safe
(when (include-line-numbers? diff)
(list
(format-line-numbers left-line-number 1 right-line-number (length vals)
'a)
"\n"))
(format-added-lines diff vals)))
(define (format-removed-section diff left-line-number right-line-number vals)
(string-append-safe
(when (include-line-numbers? diff)
(list
(format-line-numbers left-line-number (length vals) right-line-number 1
'd)
"\n"))
(format-removed-lines diff vals)))
(define (format-changed-section diff left-line-number right-line-number
removed-vals added-vals)
(string-append-safe
(when (include-line-numbers? diff)
(list
(format-line-numbers left-line-number (length removed-vals)
right-line-number (length added-vals) 'c)
"\n"))
(format-removed-lines diff removed-vals)
"\n---\n"
(format-added-lines diff added-vals)))
(define (diff->string diff)
(let ([result (list)])
(let loop ([current-section (void)]
[left-line-number 1]
[right-line-number 1]
[list-diff (diff-result diff)])
(unless (void? current-section)
(set! result (append result (list current-section))))
(cond [(and (pair? list-diff) (difference? (car list-diff)))
(cond [(values-added? (car list-diff))
(loop
(format-added-section diff
left-line-number
right-line-number
(cdar list-diff))
left-line-number
(+ right-line-number (length (cdar list-diff)))
(cdr list-diff))]
[(values-removed? (car list-diff))
(cond [(and (pair? (cdr list-diff))
(values-added? (cadr list-diff)))
(loop
(format-changed-section diff
left-line-number
right-line-number
(cdar list-diff)
(cdadr list-diff))
(+ left-line-number (length (cdar list-diff)))
(+ right-line-number (length (cdadr list-diff)))
(cddr list-diff))]
[else
(loop
(format-removed-section diff
left-line-number
right-line-number
(cdar list-diff))
(+ left-line-number (length (cdar list-diff)))
right-line-number
(cdr list-diff))])])]
[(pair? list-diff)
(loop (void) (+ left-line-number 1) (+ right-line-number 1)
(cdr list-diff))]))
(string-join result "\n")))
| false |
4ad60d692c25f6d9ad5fe779972b7c4c2fa932ff | fd1b682efcec90f7ccfa864b27a6ce5b96f49662 | /tester6.rkt | da18f614fe74bad11b4646759de2e0edbc91ad9d | []
| no_license | lexa/rnlms | 41e45aa527bcd28b3508d4c502057b0f0f43b25b | e9c9c44cb7232262f9de7e085364eb6a6d08cb99 | refs/heads/master | 2021-01-18T16:09:40.338058 | 2011-12-31T17:44:59 | 2011-12-31T17:44:59 | 2,008,422 | 0 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 15,495 | rkt | tester6.rkt | #lang racket
(require ffi/unsafe)
(require ffi/cvector)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;utilites;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (lg num)
(/ (log num) (log 10)))
;; (define (signal-level signal)
;; (* 10 (lg (add1 (/ (foldl + 0 (map sqr signal)) (length signal))))))
;; (define-syntax-rule (add! x y)
;; (set! x (+ x y)))
(define (signal-level signal . optional-args)
(let ([start (if (null? optional-args) 0 (car optional-args))]
[len (if (null? optional-args) (vector-length signal) (cadr optional-args))])
(- (* 10 (lg (add1
(/ (let loop ([i (sub1 len)] [sum 0])
(if (< i 0)
sum
(loop (sub1 i) (+ sum (sqr (vector-ref signal (+ start i)))))))
len))))
; 90.30899870323904 ;; 90.30899870323904 == (signal-level #(32768))
83.11858286715683
)))
;; (define (signal-level signal . optional-args)
;; (- (* 10 (lg (add1
;; (/ (let loop ([i (sub1 (vector-length signal))] [sum 0])
;; (if (< i 0)
;; sum
;; (loop (sub1 i) (+ sum (sqr (vector-ref signal i))))))
;; (vector-length signal)))))
;; 90.30899870323904 ;; 90.30899870323904 == (signal-level #(32768))
;; ))
(define (bytes->int bytes)
(if (= (bytes-length bytes) 2)
(let ([buf (malloc _int16 'raw)])
(ptr-set! buf _uint8 (bytes-ref bytes 0))
(ptr-set! buf _uint8 1 (bytes-ref bytes 1))
(let ([ret-val (ptr-ref buf _int16)])
(free buf)
ret-val)
)
(error 'bytes->float "invalid len of bytes")
))
(define (bytes->float bytes)
(if (= (bytes-length bytes) 2)
(let ([buf (malloc _int16 'raw)])
(ptr-set! buf _uint8 (bytes-ref bytes 0))
(ptr-set! buf _uint8 1 (bytes-ref bytes 1))
(let ([ret-val (real->double-flonum (ptr-ref buf _int16))])
(free buf)
ret-val)
)
(error 'bytes->float "invalid len of bytes")
))
(define (signal->levels signal step window)
(let ([ret (make-vector (- (quotient (- (vector-length signal) window) step) -1))])
(let loop ([start 0] [i 0])
(when (<= (+ start window) (vector-length signal))
(begin
(vector-set! ret i (signal-level signal start window))
(loop (+ start step) (add1 i)))
))
ret
))
(define (vector->mem vector type)
(let ([mem (malloc type (vector-length vector))])
(let loop ([i 0])
(when (< i (vector-length vector))
(begin
(ptr-set! mem type i (vector-ref vector i) )
(loop (add1 i)))))
mem
))
(define (mem->vector mem type len)
(let ([ret (make-vector len)])
(let loop ([i 0])
(if (< i len)
(begin
(vector-set! ret i (ptr-ref mem type i))
(loop (add1 i)))
ret
))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;white noise generator ;;;;;;;;;;;;;;;;;;
(define (read-dat-file filename)
(let ([file (open-input-file filename #:mode 'binary)]
[data (make-vector (/ (file-size filename) 2))])
(let loop ([i 0])
(let ([num (read-bytes 2 file)])
(when (not (eof-object? num))
(begin
(bytes->int num)
(vector-set! data i (bytes->int num))
(loop (add1 i))))))
(close-input-port file)
data
))
(define mi (list
(vector -436 -829 -2797 -4208 -17968 -11215 46150 34480 -10427 9049 -1309 -6320 390 -8191 -1751 -6051 -3796 -4055 -3948 -2557 -3372 -1808 -2259 -1300 -1098 -618 -340 -61 323 419 745 716 946 880 1014 976 1033 1091 1053 1042 794 831 899 716 390 313 304 304 73 -119 -109 -176 -359 -407 -512 -580 -704 -618 -685 -791 -772 -820 -839 -724)))
(define (make-echo-answer signal model echo-delay ERL K)
(define (m i)
(let ([impulse-response (list-ref mi model)])
(if (>= (vector-length impulse-response) i)
(vector-ref impulse-response i)
0)
))
(define (g val)
(* (expt 10 (/ (- ERL) 20)) K val)
;; val
)
(define (generate-impulse-response )
(let* ([impulse-response (list-ref mi model)]
[rez (make-vector (+ (vector-length impulse-response) echo-delay) 0)])
(vector-copy! rez echo-delay (vector-map g impulse-response))
rez
))
(define (filter-out impulse-response signal)
(let ([len (vector-length impulse-response)])
(do ([i 0 (add1 i)]
[sum 0 (+ sum (* (vector-ref impulse-response (- len i 1)) (vector-ref signal i)))]
)
((>= i len) sum)
)))
(define (vector-window vec begin len)
(let ([rez (make-vector len 0)])
(vector-copy! rez 0 vec begin (min (+ begin len) (vector-length vec)))
rez
))
(define (filter signal impulse-response)
(let ([rez (make-vector (vector-length signal))])
(do ([b 0 (add1 b)])
((>= b (vector-length signal)))
(vector-set! rez b (filter-out impulse-response (vector-window signal b (vector-length impulse-response))))
)
rez
)
)
;(print (generate-impulse-response))
(vector-map round (filter signal (generate-impulse-response)))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;test-generic;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; (define test-interface (interface () get-test-data check-test-results))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;test-g165;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; (define test-g165-1% (class* object%
;; (test-interface)
;; (super-new)
;; (init input-level delay-time echo-loss)
;; (define R-in (generate-white-noise input-level))
;; (define S-in (delay-signal (attenuate R-in echo-loss) delay-time))
;; ;;возвращает R_in и S_in
;; (define/public (get-test-data)
;; (values R-in S-in))
;; (define/public (check-test-results R-out S-out)
;; ;;TODO
;; #t
;; )))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;c-rnlms ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define _size_t (make-ctype _ulong #f #f))
(define _num _float)
;(define _audio_in (make-ctype _cvector i _int16 ))
;(define _audio_out (_cvector i _int16 ))
(define lib (ffi-lib "/home/lexa/develop/rnlms/librnlms.so"))
(define c-rnlms-init-struct (get-ffi-obj "rnlms_init" lib (_fun (data alpha betta err-buf-len filter-len) :: (data : _pointer) (alpha : _num) (betta : _num) (err-buf-len : _size_t) (filter-len : _size_t) -> _int)))
(define c-rnlms-process (get-ffi-obj "rnlms_process" lib (_fun (hnd x_arr y_arr err_out size) :: (hnd : _pointer) (x_arr : _pointer) (y_arr : _pointer) (err_out : _pointer) (size : _size_t) -> _int)))
(define c-sizeof-rnlms (get-ffi-obj "sizeof_rnlms" lib (_fun (P filter-len) :: (P : _size_t) (filter-len : _size_t) -> _size_t)))
(define _rnlms_options (_bitmask '(OPT_INHIBIT_ADAPTATION = 1 OPT_DISABLE_NONLINEAR_PROCESSING = 2)))
(define c-rnlms-set-options (get-ffi-obj "rnlms_set_options" lib (_fun (mem options) :: (mem : _pointer) (options : _rnlms_options) -> _int)))
(define c-rnlms-show-debug (get-ffi-obj "rnlms_show_debug" lib (_fun (mem) :: (mem : _pointer) -> _void)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;testing-algo;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define rnlms% (class object%
(init alpha betta P filter-len)
(super-new)
(define filter-mem
(let ([mem (malloc 'raw (c-sizeof-rnlms P filter-len))])
(if (= (c-rnlms-init-struct mem alpha betta P filter-len) 0)
mem
(error "error in init")
)))
(define/public (set-options opts)
(c-rnlms-set-options filter-mem opts)
)
(define/public (process far near)
(when (not (= (vector-length far) (vector-length near)))
(error "length of far and near must be the same"))
(let* ([len (vector-length far)]
[err-out-mem (malloc _int16 len )])
(c-rnlms-process filter-mem (vector->mem far _int16) (vector->mem near _int16) err-out-mem len)
(mem->vector err-out-mem _int16 len))
)
(define/public (debug-info)
(c-rnlms-show-debug filter-mem)
)
))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;g165-1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (make-g165-1 input-level delay-time adaptation-time ERL K filter-params)
(let* ([R-in (read-dat-file (format "g165/filtered_noise_~a.dat" input-level))]
; [S-in (read-dat-file (format "g165/echo_~a_~a.dat" input-level delay-time))]
[S-in (make-echo-answer R-in 0 delay-time ERL K)]
[filter (apply make-object rnlms% filter-params)]
[adaptation-signal (send filter process (vector-take S-in adaptation-time) (vector-take R-in adaptation-time))])
(send filter set-options 'OPT_INHIBIT_ADAPTATION)
(let ([residual-signal (send filter process (vector-drop S-in adaptation-time) (vector-drop R-in adaptation-time))])
(with-output-to-file "test.dat"
#:mode 'text
#:exists 'replace
(lambda ()
; (vector-map displayln adaptation-signal)
; (vector-map displayln residual-signal)
(vector-map displayln S-in)
))
(signal-level residual-signal)
)))
;(displayln "g165 - 1")
;(make-g165-1 10 256 40000 800 10 (list 0.45 0.00000001 300 512))
;; (for/list ([filter-len '(128 512 1024 1024)]
;; [alpha '(0.095 0.45 0.9 0.39)])
;; (for/list ([l '(10 15 20 25 30)])
;; (make-g165-1 l filter-len 40000 (list alpha 0.00000001 300 filter-len))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;g165-2;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (make-g165-2 input-level delay-time filter-params)
(let* ([R-in (read-dat-file (format "g165/filtered_noise_~a.dat" input-level))] ;;near
[S-in (read-dat-file (format "g165/echo_~a_~a.dat" input-level delay-time)) ] ;; far
[len (vector-length R-in)]
[N (read-dat-file "g165/filtered_noise_10.dat")] ;;-10 согласно требованиям теста
[first-sample-len 2000]
[sampling 8000]
[filter (apply make-object rnlms% filter-params)])
(send filter set-options 'OPT_INHIBIT_ADAPTATION)
(send filter process (vector-take (vector-map + S-in N) first-sample-len) (vector-take R-in first-sample-len))
(send filter set-options '())
(send filter process (vector-take (vector-drop S-in first-sample-len) (/ sampling 2)) (vector-take (vector-drop R-in first-sample-len) (/ sampling 2)))
(send filter set-options 'OPT_INHIBIT_ADAPTATION)
(let ([combined-loss
(- (- input-level)
(signal-level
(send filter process (vector-take (vector-drop S-in (+ (/ sampling 2) first-sample-len)) sampling) (vector-take (vector-drop R-in (+ (/ sampling 2) first-sample-len)) sampling))))])
combined-loss
)))
;; g165-2
;; (displayln "g165 - 2")
;; (for/list ([filter-len '(128 512 1024 1024)]
;; [alpha '(0.095 0.45 0.9 0.39)])
;; (for/list ([l '(15 20 25 30)])
;; (make-g165-2 l filter-len (list alpha 0.00000001 300 filter-len))))
(define (vector-range vec start len)
(vector-take (vector-drop vec start) len)
)
(define (make-g165-4 input-level delay-time filter-params)
(let* ([R-in (read-dat-file (format "g165/filtered_noise_~a.dat" input-level))] ;;near
[S-in (read-dat-file (format "g165/echo_~a_~a.dat" input-level delay-time))] ;; far
[len (vector-length R-in)]
[sampling 8000]
[filter (apply make-object rnlms% filter-params)])
(send filter process (vector-range S-in 0 (* 5 sampling)) (vector-range R-in 0 (* 5 sampling))) ;;5 секунд адаптации
(send filter process (make-vector (* sampling 120) 0) (make-vector (* sampling 120) 0)) ;;2 минуты тишины
(send filter set-options 'OPT_INHIBIT_ADAPTATION)
(send filter process (vector-range S-in (* 5 sampling) (* 3 sampling) ) (vector-range R-in (* 5 sampling) (* 3 sampling))) ;;3 секунды подаём сигнал на не адаптирующийся фильтр
;;меряем остаточный уровень
(signal-level
(send filter process (vector-range S-in (* 8 sampling) (* 2 sampling) ) (vector-range R-in (* 8 sampling) (* 2 sampling)))
)))
;(make-g165-3 10 1024 (list 0.9 0.00000001 300 1024))
;;g165-4
;; (displayln "g165 - 4")
;; (for/list ([filter-len '(128 512 1024 1024)]
;; [alpha '(0.095 0.45 0.9 0.39)])
;; (for/list ([l '(10 15 20 25 30)])
;; (make-g165-4 l filter-len (list alpha 0.00000001 300 filter-len))))
;; (make-g165-3 10 128 '(0.095 1e-08 300 128))
;; (make-g165-3 20 128 '(0.095 1e-08 300 128))
;; (make-g165-3 10 512 '(0.45 1e-08 300 512))
;; (make-g165-3 20 512 '(0.45 1e-08 300 512))
;(make-g165-3 10 1024 '(0.4 1e-08 300 1024))
;; (make-g165-3 20 1024 '(0.9 1e-08 300 1024))
(define (make-g165-5 input-level delay-time filter-params)
(let* ([R-in (read-dat-file (format "g165/filtered_noise_~a.dat" input-level))] ;;near
[S-in (read-dat-file (format "g165/echo_~a_~a.dat" input-level delay-time))] ;; far
[len (vector-length R-in)]
[sampling 8000]
[filter (apply make-object rnlms% filter-params)])
(send filter process (vector-range S-in 0 (* 5 sampling)) (vector-range R-in 0 (* 5 sampling))) ;;5 секунд адаптации
(send filter process (make-vector (/ sampling 2) 0) (vector-range R-in (* 5 sampling) (/ sampling 2))) ;;0.5 секунды отключён эхотракт
(send filter set-options 'OPT_INHIBIT_ADAPTATION)
(send filter process (make-vector sampling 0) (vector-range R-in (* 55/10 sampling) sampling)) ;;1 секунды без адаптации, чтоб всё просралось
(signal-level (send filter process (make-vector (* sampling 2) 0) (vector-range R-in (* 65/10 sampling) (* sampling 2)))) ;;2 секунды меряем уровень
))
;;g165-5
;; (displayln "g165 - 5")
;; (for/list ([filter-len '(128 512 1024 1024)]
;; [alpha '(0.095 0.45 0.9 0.39)])
;; (for/list ([l '(10 15 20 25 30)])
;; (make-g165-5 l filter-len (list alpha 0.00000001 300 filter-len))))
(let* ([R-in (read-dat-file "echo-in.dat" )] ;;near
[S-in (read-dat-file "echo-out.dat" )] ;; far
[len (vector-length R-in)]
[filter (apply make-object rnlms% (list 0.4 0.00000001 300 512))]
[err-signal (send filter process (vector-take R-in 80000) (vector-take S-in 80000))])
(with-output-to-file "test.dat"
#:mode 'text
#:exists 'replace
(lambda ()
(vector-map displayln err-signal)
))
(send filter debug-info)
)
| true |
eafe2bd59844510cf47ca28333575ef85f8288aa | 0ad0076e542f597f37c3c793f6e7596c1bda045b | /ts-tactics/tactics/tactic-library/team-memorize.rkt | c2426041389c219910cc4b2a3ead905d7062f7d0 | []
| 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 | 5,827 | rkt | team-memorize.rkt | #lang racket
(provide team-memorize
pass-and-memorize
all-correct-post-mortem)
(require "../lang.rkt")
;TODO: Start on docs. They will help a lot. Plus, much of that can go directly into the handbook.
(define (pass-and-memorize (time 10))
(list
(instruction (owner-of 'the-challenge-card)
(within-seconds time
(memorize
(contents-of
(back-of
'the-challenge-card)))))
(transfer-ownership-of 'the-challenge-card
(owner-of 'the-challenge-card)
(person-right-of you))))
(define (timer-holder-talks-to-scribe)
(list
(instruction (owner-of timer)
(set-timer-for-seconds 30 timer))
(until (timer-beeps timer)
(instruction
(group-add (owner-of timer)
(owner-of whiteboard))
(minding-the-phase-constraints
(communicate))))
(transfer-ownership-of timer
(owner-of timer)
(adjective
"(skipping the whiteboard holder)"
(person-right-of you)))))
(define (all-correct-post-mortem)
(instruction (group-add coach team)
(branching-verb
(is-bug-free?
;Code on?
(contents-of computers))
(announce "We are the winners!")
(discuss "strategy for next time"))))
(define (team-memorize coach
students
computers
challenge-card
timer
whiteboard
markers)
(list
(phase 'Strategy
(instruction coach
(announce "In a moment, you must decide which order you will take turns in. You may also strategize during this phase. Do this wisely. After this phase, you will not be allowed to talk freely."))
(instruction coach
(discuss (front-of challenge-card)))
(instruction students
(configure-for-circle-play-around coach)))
(phase 'Silent
(instruction coach
(announce "The [Silent] phase has begun. Any talking during this phase will result in penalties and possibly an instant-loss. Hand signals are permitted. Looking at the challenge card when you are not the owner is forbidden."))
(transfer-ownership-of challenge-card
coach
starting-player)
(until (rounds-completed 1)
(sub-routine
(pass-and-memorize 10))))
(phase 'One-Talker
(instruction coach
(announce "The [One-Talker] phase has begun. During this phase, you may only speak or gesture if you own the timer. If you own the whiteboard, you may write or gesture (but you may not speak). All other forms of communication from anyone will result in penalties or an instant loss for the whole team."))
(instruction coach
(hide challenge-card))
(transfer-ownership-of whiteboard
coach
starting-player)
;How to specify that the whiteboard holder doesn't get the timer?
(transfer-ownership-of timer
coach
(person-right-of starting-player))
(until (rounds-completed 1)
(sub-routine
(timer-holder-talks-to-scribe))))
(phase 'Testing
(instruction coach
(announce "The [Testing] phase has begun. All communication is forbidden in this phase. However, you may type on your own computer and look at the whiteboard whenever you want. By the end of this phase, the goal is to have the same code on all of the computers. And it must work correctly! Nod your heads if you understand."))
(instruction students (nod))
(instruction coach (announce "You have 5 minutes beginning now."))
(instruction coach (set-timer-for 5 timer))
(until (timer-beeps timer)
(instruction students
(minding-the-phase-constraints
(write-code)))))
(phase 'Meta-Cognition
(instruction coach
(announce "The [Scoring] phase has now begun. If the code on EACH computer is correct, we all win."))
(sub-routine
(all-correct-post-mortem)))))
(module+ test
;TODO: Note that subroutines need to be printed, which means they need to have been called with all of the same inputs as the calling function (otherwise bindings and labelings and context won't match up).
; ... If we need more control, maybe we can implement functions and give people a mnemonic for figuring out the parameter passing -- i.e. using the whiteboard. (Actually, could already do this on top of subroutines...)
(displayln "SUB ROUTINE, pass-and-memorize")
(print-tactic
(pass-and-memorize 10))
(displayln "SUB ROUTINE, timer-holder-talks-to-scribe")
(print-tactic
(timer-holder-talks-to-scribe))
(displayln "SUB ROUTINE, all-correct-post-mortem")
(print-tactic
(all-correct-post-mortem))
(displayln "\n")
(print-tactic
(team-memorize
'Coach
'Team
'Team-Computers
'the-challenge-card
'the-timer
'the-whiteboard
'the-markers)))
| false |
8ca9696b05f1a793a0ce9509dc68b665f0523383 | 6794e895dbcb7b68858776b6d09e5a6e41f77ffa | /syntax/parse/syntax-class-or/scribblings/syntax-class-or.scrbl | e32c700f17eb19c80c9a1da508c598ac55873099 | [
"MIT"
]
| permissive | AlexKnauth/syntax-class-or | 972af85ecea020ac825afa92235706d73ce4fc23 | 948a823026cb462f113400b5deb5276c9bd1846a | refs/heads/main | 2021-07-09T02:02:50.486285 | 2018-08-01T15:43:41 | 2018-08-01T15:43:41 | 143,089,376 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 3,474 | scrbl | syntax-class-or.scrbl | #lang scribble/manual
@(require scribble/example
(for-label racket
syntax/parse
syntax/parse/experimental/reflect
syntax/parse/syntax-class-or))
@(define (make-ev)
(define ev (make-base-eval))
(ev '(require racket
syntax/parse
syntax/parse/experimental/reflect
syntax/parse/syntax-class-or))
ev)
@title{Combining syntax classes together as multiple variants}
@defmodule[syntax/parse/syntax-class-or]
@defform[(define-syntax-class/or* head
#:attributes [attr-arity-decl ...]
reified-classes-expr)
#:grammar
([head name-id
(name-id parameters)]
[parameters (code:line parameter ...)
(code:line parameter ... @#,racketparenfont{.} rest-id)]
[parameter (code:line param-id)
(code:line [param-id default-expr])
(code:line #:keyword param-id)
(code:line #:keyword [param-id default-expr])]
[attr-arity-decl attr-name-id
[attr-name-id depth]])
#:contracts
([reified-classes-expr (listof reified-syntax-class?)])]{
Normally, there needs to be one syntax-class containing
all the variants, in one centralized place. Even when you
divide the the work into helper syntax classes, you're
limited to the variants that were already written that
the parsing can depend on. The number of variants is
limited by the syntax at compile time.
The syntax-parse reflection interface (@racket[~reflect]) allows
you to fill in a syntax class at runtime, which lets you
leave a variant to be filled in from somewhere else.
However, the @racket[~reflect] pattern only allows one syntax
class, and that syntax class must include all the
non-built-in variants, still limiting it to what some
centralized parser can depend on. And still the number of
new variants is limited to fixed number at compile time.
The @racket[define-syntax-class/or*] form allows you to define
a syntax class that combines a list of arbitrarily many
variants into one parser. The list of variants can be
computed at run time (relative to the parser) or can be
passed in as arguments.
@examples[
#:eval (make-ev)
#:escape UNEXAMPLES
(require syntax/parse
syntax/parse/experimental/reflect
syntax/parse/syntax-class-or)
(define-syntax-class addition
#:datum-literals [+]
[pattern [{~and a {~not +}} ... {~seq + {~and b {~not +}} ...} ...+]
#:with op #'+
#:with [sub ...] #'[[a ...] [b ...] ...]])
(define-syntax-class multiplication
#:datum-literals [*]
[pattern [{~and a {~not *}} ... {~seq * {~and b {~not *}} ...} ...+]
#:with op #'*
#:with [sub ...] #'[[a ...] [b ...] ...]])
(define-syntax-class exponentiation
#:datum-literals [^]
[pattern [{~and a {~not ^}} ... ^ b ...]
#:with op #'expt
#:with [sub ...] #'[[a ...] [b ...]]])
(define-syntax-class/or* infix
#:attributes [op [sub 1]]
(list (reify-syntax-class addition)
(reify-syntax-class multiplication)
(reify-syntax-class exponentiation)))
(define (parse stx)
(syntax-parse stx
[e:infix #`(e.op #,@(map parse (attribute e.sub)))]
[[a] #'a]))
(parse #'[x])
(parse #'[a * x ^ 2 + b * x + c])
(parse #'[a ^ b * c + 2 * d + 3])
(parse #'[2 ^ 10 ^ x + -1 * y])
]}
| true |
1dfb8ccf50c532f7d1077cf2fd54e373423ca71e | 3416b95d38c6beafa486132f807782e0ebbdbd8a | /CSC324/A2/A2.rkt | 89114174d3f946dc4a0fba7322b70706cb05ba5f | []
| no_license | stroudgr/UofT | f31956d05b87d20cf7e76c3af5c7eee1b9e055a4 | 137f3d22775827ff3a70d402dacfa8d5cc8935ca | refs/heads/master | 2021-05-01T21:33:27.059333 | 2019-01-11T00:47:23 | 2019-01-11T00:47:23 | 69,030,927 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 7,494 | rkt | A2.rkt | #lang racket #| CSC324 2017 Fall Assignment 2 : Due Wednesday November 29 at 6PM. |#
#| The Maybe Monad.
In this assignment you implement the functional API for computation that propagates false as failure,
and use that to implement the associated Do notation. |#
(provide >> >>=
÷ √ ln
E1 Do E2 E3)
(module+ test (require rackunit)
; Implement ‘>>’, called “then”, that takes two *expressions* and produces an expression that:
; 1. Evaluates the first expression.
; 2. If that produces false then that is the result.
; 3. Otherwise, evaluates the second expression and that is the result.
(check-false (>> (not (zero? 0)) (/ 324 0)))
(check-equal? (>> (not (zero? 324)) (/ 324 324))
1)
(check-false (>> (number? "324") (>> (not (zero? "324")) (/ 324 "324"))))
; Implement functions ÷, √, and ln, that produce false if dividing by zero, taking the square root
; of a negative number, or taking the logarithm of a non-positive number.
; Use ‘>>’ appropriately in the implementations.
; Implement ÷ curried: taking a number, and returning a unary function ready to divide a number.
#;(check-false (√ -1))
#;(check-equal? (√ 324) 18)
#;(check-false ((÷ 1) 0))
#;(check-equal? ((÷ 324) 18) 18)
#;(check-false (ln 0))
#;(check-equal? (ln 324) (log 324))
; Implement *function* ‘>>=’, called “bind”, that takes two arguments and:
; 1. If the first argument is false then that is the result.
; 2. Otherwise, calls the second argument on the first.
; Use ‘>>’ appropriately in the implementation.
#;(check-false (>>= -1 √))
#;(check-false (>>= (>>= -1 √) ln))
#;(check-equal? (>>= (>>= (>>= 324 √) (÷ 1)) ln)
(log (/ (sqrt 324)))))
#;(define >> (λ (a) (cond [(not a) a] [else b])))
(define-syntax >>
(syntax-rules ()
[(>> a b) (cond [(not a) a] [else b])]))
(define ÷ (λ (a) (λ (b) (>> (not (zero? b)) (/ a b)))))
(define √ (λ (a) (>> (not (negative? a)) (sqrt a))))
(define ln (λ (a) (>> (positive? a) (log a))))
(define >>= (λ (a b) (>> a (b a))))
#;(define (÷ a) (λ (b) (>> (not (zero? b)) (/ a b))))
#;(define (√ a) (>> (not (negative? a)) (sqrt a)))
#;(define (ln a) (>> (positive? a) (log a)))
#;(define (>>= a b)
(>> a (b a)))
; Consider this language of arithmetic expressions:
; <numeric-literal>
; - represented by a number
; (√ <ae>)
; - represented by a list with the symbol √ and an arithemtic expression
; (ln <ae>)
; - represented by a list with the symbol ln and an arithemtic expression
; (<ae> ÷ <ae>)
; - represented by a list with an arithmetic expression, symbol ÷, and arithemtic expression
; Implement function ‘E1’ to evaluate such expressions, producing false if any of the computations
; are invalid according to the earlier restrictions for square root, logarithm, and division.
; Use pattern matching appropriately, along with ‘>>’ and ‘>>=’ for propagating false.
; In particular, do not use any other conditionals, nor boolean operations or literals.
; Use quasiquotation as appropriate for the patterns, but nothing else from match's pattern language
; [e.g. don't use ‘?’, nor #:when].
(define E1
(λ (term)
(match term
[`(,a ÷ ,b) (>> (and (E1 a) (E1 b)) ( (÷ (E1 a)) (E1 b)) )]
[`(√ ,a) (>> (E1 a) (√ (E1 a)))]
[`(ln ,a) (>> (E1 a) (ln (E1 a)))]
[_ term])))
(module+ test (require rackunit)
(check-equal? (E1 1) 1)
(check-equal? (E1 '(6 ÷ 3)) 2)
(check-equal? (E1 '(√ 9)) 3)
(check-equal? (E1 '(ln 1)) 0)
(check-equal? (E1 '((6 ÷ 3) ÷ (10 ÷ 5))) 1)
(check-equal? (E1 '((ln 36) ÷ (√ 4))) (log 6))
(check-equal? (E1 '(√ ( ((√ 81) ÷ (√ 1)) ÷ (√ (1 ÷ 16)) ))) 6)
(check-false (E1 '(√ -1)))
(check-false (E1 '(1 ÷ 0)))
(check-false (E1 '(ln (ln 1))))
(check-false (E1 '(√(9 ÷ (√(ln 0))))))
)
; Implement ‘Do’, using ‘>>’ and ‘>>=’ appropriately.
;
; It takes a sequence of clauses to be evaluated in order, short-circuiting to produce false if any
; of the clauses produces false, producing the value of the last clause.
;
; Except for the last clause, a clause can be of the form
#;(identifier ← expression)
; in which case its meaning is: evaluate the expression, and make the identifier refer to the
; value in subsequent clauses.
;
; Don't use any local naming [local, let, match, define, etc] except for λ parameters:
; recall that ‘let’ is just a notation for a particular lambda calculus “design pattern”.
(module+ test
(check-equal? (Do 324)
324)
(check-false (Do #false
(/ 1 0)))
(check-false (Do (r1 ← (√ -1))
(r2 ← (ln (+ 1 r1)))
((÷ r1) r2)))
(check-false (Do (r1 ← (√ -1))
(r2 ← (ln (+ 1 r1)))
((÷ r1) r2))))
#;(define Do (λ args
(cond [(empty? args) args]
[else (>>= first )])))
(define-syntax Do (syntax-rules (←)
[(Do (id ← value) rest ... )
(>>= value (λ (id) (Do rest ... )))]
[(Do value) value]
[(Do first rest ...) (>> first (Do rest ...))]))
; Implement ‘E2’, behaving the same way as ‘E1’, but using ‘Do’ notation instead of ‘>>’ and ‘>>=’.
(define E2
(λ (term)
(match term
#;[`(,a ÷ ,b) (>> (and (E2 a) (E2 b)) ( (÷ (E2 a)) (E2 b)) )]
[`(,a ÷ ,b) (Do (r1 ← (E2 a)) (r2 ← (E2 b)) ((÷ r1) r2)) ]
#;[`(√ ,a) (>> (E2 a) (√ (E2 a)))]
[`(√ ,a) (Do (r1 ← (E2 a)) (√ r1))]
#;[`(ln ,a) (>> (E2 a) (ln (E2 a)))]
[`(ln ,a) (Do (r1 ← (E2 a)) (ln r1))]
[_ term])))
; Implement ‘E3’, behaving the same way as ‘E2’, by expanding each use of ‘Do’ notation in ‘E2’,
; and also replacing ‘E2’ with ‘E3’. The result will be similar to your ‘E1’, but likely a bit
; less elegant.
(define E3
(λ (term)
(match term
#;[`(,a ÷ ,b) (Do (r1 ← (E3 a)) (r2 ← (E3 b)) (÷ r1 r2)) ]
[`(,a ÷ ,b) (>>= (E3 a)
(λ (r1) (>>= (E3 b)
(λ (r2) ((÷ r1) r2)) )))]
#;[`(√ ,a) (Do (r1 ← (E3 a)) (√ r1))]
[`(√ ,a) (>>= (E3 a) (λ (r1) (√ r1)))]
#;[`(ln ,a) (Do (r1 ← (E3 a)) (ln r1))]
[`(ln ,a) (>>= (E3 a) (λ (r1) (ln r1)))]
[_ term])))
(module+ test (require rackunit)
(check-equal? (E2 1) 1)
(check-equal? (E2 '(6 ÷ 3)) 2)
(check-equal? (E2 '(√ 9)) 3)
(check-equal? (E2 '(ln 1)) 0)
(check-equal? (E2 '((6 ÷ 3) ÷ (10 ÷ 5))) 1)
(check-equal? (E2 '((ln 36) ÷ (√ 4))) (log 6))
(check-equal? (E2 '(√ ( ((√ 81) ÷ (√ 1)) ÷ (√ (1 ÷ 16)) ))) 6)
(check-false (E2 '(√ -1)))
(check-false (E2 '(1 ÷ 0)))
(check-false (E2 '(ln (ln 1))))
(check-false (E2 '(√(9 ÷ (√(ln 0))))))
(check-equal? (E3 1) 1)
(check-equal? (E3 '(6 ÷ 3)) 2)
(check-equal? (E3 '(√ 9)) 3)
(check-equal? (E3 '(ln 1)) 0)
(check-equal? (E3 '((6 ÷ 3) ÷ (10 ÷ 5))) 1)
(check-equal? (E3 '((ln 36) ÷ (√ 4))) (log 6))
(check-equal? (E3 '(√ ( ((√ 81) ÷ (√ 1)) ÷ (√ (1 ÷ 16)) ))) 6)
(check-false (E3 '(√ -1)))
(check-false (E3 '(1 ÷ 0)))
(check-false (E3 '(ln (ln 1))))
(check-false (E3 '(√(9 ÷ (√(ln 0))))))
)
| true |
bf19bbf95a20b2adb571709b92bd86f884dcf403 | bb6ddf239800c00988a29263947f9dc2b03b0a22 | /tests/exercise-3.12-test.rkt | ce8bd7d3743bfbecde18503c2a3f739e4981047a | []
| no_license | aboots/EOPL-Exercises | f81b5965f3b17f52557ffe97c0e0a9e40ec7b5b0 | 11667f1e84a1a3e300c2182630b56db3e3d9246a | refs/heads/master | 2022-05-31T21:29:23.752438 | 2018-10-05T06:38:55 | 2018-10-05T06:38:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 303 | rkt | exercise-3.12-test.rkt | #lang racket/base
(require rackunit)
(require "../solutions/exercise-3.x-let-lang.rkt")
(check-equal? (run "cond zero?(1) ==> 2
zero?(3) ==> 4
zero?(0) ==> 5
zero?(6) ==> 7
end")
(num-val 5))
| false |
5dd9f5a387a44d92caec0cb09656b343224a004f | 900611bb401e54e448310314118c55f9a289cd93 | /main.rkt | 0e21d382b105ac842d41d35772d8aa160b349edc | []
| no_license | silver-ag/the-hacker | 8468ec04def6c34f6b54e55633cf6bcd5b49f044 | f2c3a4da60bc1007899f8b962cae0dc8a1c0acd1 | refs/heads/main | 2023-04-17T10:19:04.911252 | 2021-05-08T14:13:30 | 2021-05-08T14:13:30 | 365,531,266 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,181 | rkt | main.rkt | #lang racket
(require "SMOG.rkt")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; manage running the game
;;;;
(define (main-menu [current-level 0] [play-immediately? #f])
(if (equal? current-level (length levels))
(display "YOU HAVE WON\n")
(if play-immediately?
(if (play-level (list-ref levels current-level))
(main-menu (+ current-level 1) #t)
(main-menu current-level))
(let []
(display (format "// THE HACKER\n\n1) play (current level: ~a)\n2) help\n3) SMOG manual\n4) exit\n\n" current-level))
(define (get-choice)
(display "> ")
(let [[in (read-line)]]
(case in
[("1") (if (play-level (list-ref levels current-level))
(main-menu (+ current-level 1) #t)
(main-menu current-level))]
[("2") (display help) (get-choice)]
[("3") (display manual) (get-choice)]
[("4") (exit)]
[else (display "please choose 1-4\n") (get-choice)])))
(get-choice)))))
(define (play-level lvl)
(let/cc cc
(run lvl (hash-set
(hash-set SMOG-standard-functions
"escape" (scriptfun (λ () (display "success!\n\n") (cc #t)) '()))
"give_up" (scriptfun (λ () (cc #f)) '())))
(display "\nerror encountered, restarting level...\n")
(play-level lvl)))
;;;;;;;;;;;;;;;;;;
;; define levels
;;;;
(require "level-0.rkt"
"level-1.rkt"
"level-2.rkt"
"level-3.rkt"
"level-4.rkt")
(define levels (list level-0 level-1 level-2 level-3 level-4))
;;;;;;;;;;;;;;;;;;;;
;; menu text lumps
;;;;
(define help
(format "* in order to pass each level, you'll need to find and exploit some security issue in order to call the function escape()\n~
* you can always say 'quit' or 'give up' in levels to return to the main menu\n~
* SMOG is the language in which levels are written. A manual is available from the menu.\n"))
(define manual
(format "see the accompanying pdf\n"))
;;;;;;;;;;
;; begin
;;;;
(main-menu 0) | false |
4d42be92959713b138a6d9b00a1721391599fd1d | cc01edd31885c9431d33c7f79dc9e63809a35e51 | /Assignment1/math.rkt | 3ee01550051fce24a6a14eb955093892adad6a78 | []
| no_license | abriggs914/CS3613 | 4bba00ed9b74c904a20d24b01745b2e412b4d639 | 496d931fdaa49d60ef83be27c790b5e9dc309b28 | refs/heads/master | 2020-04-15T20:12:03.721710 | 2019-04-27T02:11:01 | 2019-04-27T02:11:01 | 164,982,788 | 0 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 43 | rkt | math.rkt | #lang racket
(define (pow b e)(expt b e)) | false |
ed5afacc1bc1b5f65558bed262d327baeac7d898 | e78f63086748a051a0a79cf9595fd1db769cb584 | /marionette-test/info.rkt | fdf0bcb26eb385c2e62d319e3c8da22824b32ecb | [
"BSD-3-Clause"
]
| permissive | Bogdanp/marionette | d8f56eabd34928666376d4a02501e86405f48aa8 | daac17634775dc516611de6ea1e4c43776d64405 | refs/heads/master | 2023-06-19T12:17:24.451731 | 2023-06-02T09:21:45 | 2023-06-02T09:21:45 | 190,891,830 | 84 | 7 | null | 2023-06-02T09:21:58 | 2019-06-08T13:36:10 | Racket | UTF-8 | Racket | false | false | 236 | rkt | info.rkt | #lang info
(define license 'BSD-3-Clause)
(define collection 'multi)
(define deps '())
(define build-deps '("base"
"marionette-lib"
"rackunit-lib"))
(define update-implies '("marionette-lib"))
| false |
8170e1ee1a3d9b9d5150123f9facf66fb062368f | 2cbc93f55376cdc4a4dc86065c790e9fbc7db10e | /evolution.rkt | 279265568467523f4ae5f5da15809694b3f6c584 | []
| no_license | CheatEx/land-of-lisp-rkt | bdd67c822639e744bb9d3ee20c2cbebcc24acc63 | 10e61b77a5bf10ca1ff010f09f2ac972b99664c0 | refs/heads/master | 2020-04-08T06:44:50.567464 | 2014-02-04T05:50:57 | 2014-02-04T05:50:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 3,796 | rkt | evolution.rkt | #lang racket
(require racket/set)
(define *width* 120)
(define *height* 30)
(define *jungle* '(45 10 10 10))
(define *plant-energy* 60)
(define *reproduction-energy* 200)
(define *plants* (set))
(struct animal (x y energy dir genes) #:transparent #:mutable)
(define *animals* (list
(animal
(truncate (/ *width* 2))
(truncate (/ *height* 2))
150
0
(for/list ([i (in-range 8)])
(add1 (random 10))))))
(define (random-plant! left top width height)
(let ([pos (cons
(+ left (random width))
(+ top (random height)))])
(set! *plants* (set-add *plants* pos))))
(define (add-plants!)
(apply random-plant! *jungle*)
(random-plant! 0 0 *width* *height*))
(define (move! animal)
(let* ([dir (animal-dir animal)]
[x-shift (cond [(and (>= dir 2) (< dir 5)) 1]
[(or (= dir 1) (= dir 5)) 0]
[else -1])]
[y-shift (cond [(and (>= dir 0) (< dir 3)) -1]
[(and (>= dir 4) (< dir 7)) 1]
[else 0])])
(set-animal-x! animal
(remainder (+ (animal-x animal) x-shift *width*)
*width*))
(set-animal-y! animal
(remainder (+ (animal-y animal) y-shift *height*)
*height*))
(set-animal-energy! animal (sub1 (animal-energy animal)))))
(define (angle genes)
(let* ([x (random (apply + genes))]
[xnu (- x (car genes))])
(if (< xnu 0)
0
(add1 (angle (cdr genes))))))
(define (turn! animal)
(set-animal-dir! animal
(remainder (+ (animal-dir animal) (angle (animal-genes animal)))
8)))
(define (eat! animal)
(let ([pos (cons (animal-x animal) (animal-y animal))])
(when (set-member? *plants* pos)
(set-animal-energy! animal (+ (animal-energy animal) *plant-energy*))
(set! *plants* (set-remove *plants* pos)))))
(define (mutate genes mutation)
(if (null? genes)
null
(if (equal? mutation 0)
(cons (max 1 (+ (car genes) (random 3) -1))
(mutate (cdr genes) (sub1 mutation)))
(cons (car genes)
(mutate (cdr genes) (sub1 mutation))))))
(define (reproduce! a)
(let ([e (animal-energy a)])
(when (>= e *reproduction-energy*)
(set-animal-energy! a (truncate (/ e 2)))
(let* ([mutation (random 8)]
[new-animal (struct-copy animal a
[genes (mutate (animal-genes a) mutation)])])
(set! *animals* (cons new-animal *animals*))))))
(define (day!)
(set! *animals*
(filter (lambda (a) (>= (animal-energy a) 0))
*animals*))
(for-each (lambda (a)
(turn! a)
(move! a)
(eat! a)
(reproduce! a))
*animals*)
(add-plants!))
(define (draw-world)
(for* ([y (in-range *height*)]
[x (in-range *width*)])
(when (= x 0)
(display #"|"))
(when (= x (sub1 *width*))
(display #"|") (display #\newline))
(display (cond
[(for/or ([a *animals*]) (and (= (animal-x a) x) (= (animal-y a) y)))
#"M"]
[(set-member? *plants* (cons x y)) #"*"]
[else #\space]))))
(define (evolution)
(draw-world)
(display #\newline)
(let ([str (read-line)])
(cond [(equal? str "quit") null]
[else (let ([turns (string->number str)])
(if turns
(for ([i (in-range (add1 turns))])
(day!))
(day!))
(evolution))])))
| false |
ecbf32f7c230f2d20f10d0f5f7578b891f8e5e60 | c63a06955a246fb0b26485162c6d1bfeedfd95e2 | /p-1.37.a-cont-frac.rkt | 37780036fee787186c3ea86d02b53997cbad5efa | []
| 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 | 285 | rkt | p-1.37.a-cont-frac.rkt | #lang racket
(define (cont-frac n d k)
(define (rec i)
(if (> i k)
0
(/ (n i)
(+ (d i)
(rec (+ i 1))))))
(rec 1))
;;
(define (phi)
(/ 1
(cont-frac (lambda (i) 1.0)
(lambda (i) 1.0)
10000)))
(phi) | false |
ce6fcc8047d775b40a9716ca2ca2336beafd36c2 | 0860413ff69994c6fcf30a607e5125dfb6327f76 | /Chapter3/LET/let-interp.rkt | bcbf9d67d913efa61f5473b4a14706d0fdad4672 | []
| no_license | hcoona/eopl3-answer | e7187b37398e884bfed83bb6bbefc301271f84ef | aba3822303502ed26522ee61b8f8b7954f0b7d77 | refs/heads/master | 2021-01-23T12:22:09.626889 | 2014-08-26T06:51:45 | 2014-08-26T06:51:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,575 | rkt | let-interp.rkt | (module let-interp eopl
(require "let-environment.rkt"
"let-syntax.rkt"
"let-expval.rkt"
"let-parser.rkt")
(provide run
value-of-program
value-of)
;; Page 71
(define (run string)
(value-of-program (scan&parse string)))
(define (value-of-program pgm)
(cases program pgm
[a-program (exp1)
(value-of exp1 (init-env))]))
(define (value-of exp env)
(cases expression exp
[const-exp (num) (num-val num)]
[var-exp (var) (apply-env env var)]
[diff-exp (exp1 exp2)
(let ([val1 (value-of exp1 env)]
[val2 (value-of exp2 env)])
(let ([num1 (expval->num val1)]
[num2 (expval->num val2)])
(num-val (- num1 num2))))]
[zero?-exp (exp1)
(let* ([val1 (value-of exp1 env)]
[num1 (expval->num val1)])
(if (zero? num1)
(bool-val #t)
(bool-val #f)))]
[if-exp (exp1 exp2 exp3)
(let ([val1 (value-of exp1 env)])
(if (expval->bool val1)
(value-of exp2 env)
(value-of exp3 env)))]
[let-exp (var exp1 body)
(let ([val1 (value-of exp1 env)])
(value-of body
(extend-env var val1 env)))]))
#|
(run "let x = 7
in let y = 2
in let y = let x = -(x,1) in -(x,y)
in -(-(x,8),y)")
|#
) | false |
0feeace68c273ba6e43b2411c25aac35e4c16cf6 | b08b7e3160ae9947b6046123acad8f59152375c3 | /Programming Language Detection/Experiment-2/Dataset/Train/Racket/empty-string.rkt | 0a653c7befcec1f5f69bfe8197448564452779fc | []
| 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 | 127 | rkt | empty-string.rkt | #lang racket
(define empty-string "")
(define (string-null? s) (string=? "" s))
(define (string-not-null? s) (string<? "" s))
| false |
99eda52a6f110675740dd5c7fa6c22e4699bc6fe | 4cc0edb99a4c5d945c9c081391ae817b31fc33fd | /paint-by-numbers/all-problems.rkt | eb70e19f7bf3778a9b9327f5c4326059c6045ede | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | racket/games | c8eaa92712405890cd1db19b8ba32b1620d885b8 | eba5c6fa54c524871badb8b0e205fe37640d6c3e | refs/heads/master | 2023-08-19T00:41:23.930448 | 2023-07-24T23:29:05 | 2023-07-24T23:29:05 | 27,138,761 | 54 | 33 | NOASSERTION | 2020-05-04T13:46:50 | 2014-11-25T17:59:40 | Racket | UTF-8 | Racket | false | false | 2,988 | rkt | all-problems.rkt | #lang racket
(require racket/unit
racket/include
"problem.rkt"
(for-syntax racket))
(define-signature paint-by-numbers:all-problems^ (problemss set-names))
(define-signature paint-by-numbers:problem-set^ (problems set-name))
(define-signature paint-by-numbers:problem^ ((struct problem (name rows cols solution) #:omit-constructor)))
(define-syntax (mk-units stx)
(syntax-case stx ()
[(_)
(with-syntax
([(unit-names ...)
(let* ([prob-dir (collection-file-path "problems" "games" "paint-by-numbers")]
[files (call-with-input-file (build-path prob-dir "directory") read)])
(for/list ([file files] #:when (file-exists? (build-path prob-dir file)))
(define path-spec (string-append "problems" "/" file))
path-spec))])
#'(list (include unit-names) ...))]))
(define units (mk-units))
(define empty-unit
(unit
(import paint-by-numbers:problem^)
(export paint-by-numbers:all-problems^)
(define problemss null)
(define set-names null)))
(define (combine-units new-unit sofar)
(compound-unit
(import [p : paint-by-numbers:problem^])
(export combine)
(link [((new : paint-by-numbers:problem-set^)) new-unit p]
[((old : paint-by-numbers:all-problems^)) sofar p]
[((combine : paint-by-numbers:all-problems^))
(unit
(import (prefix old: paint-by-numbers:all-problems^)
(prefix new: paint-by-numbers:problem-set^)
paint-by-numbers:problem^)
(export paint-by-numbers:all-problems^)
(define (expand-problem pbm)
(make-problem (problem-name pbm)
(problem-rows pbm)
(problem-cols pbm)
(expand-solution (problem-solution pbm))))
(define problemss
(if (null? new:problems)
old:problemss
(cons (map expand-problem new:problems) old:problemss)))
(define set-names
(if (null? new:problems)
old:set-names
(cons new:set-name old:set-names)))) new old p])))
;; expand-solution : (union #f (listof string[row])) ->
;; (union #f (vectorof (vectorof (union 'on 'off 'unknown))))
(define (expand-solution sol)
(and sol (apply vector (map expand-row sol))))
;; expand-row : string -> (vectorof (union 'on 'off 'unknown))
(define (expand-row str)
(list->vector (map expand-char (string->list str))))
;; expand-char : char -> (union 'on 'off 'unknown)
(define (expand-char c)
(case c
[(#\x) 'on]
[(#\space) 'off]
[(#\U) 'unknown]))
(provide-signature-elements paint-by-numbers:all-problems^)
(define-values/invoke-unit
(foldr combine-units empty-unit units)
(import paint-by-numbers:problem^)
(export paint-by-numbers:all-problems^))
| true |
a3eb1e5e6c2dd2c1b6cf11d0a899a048da9e8c30 | 5bbc152058cea0c50b84216be04650fa8837a94b | /pre-benchmark/htdp/base/Draft.scrbl | 38395dabf0414768fc5dc1dbebd3a55dd63de409 | []
| no_license | nuprl/gradual-typing-performance | 2abd696cc90b05f19ee0432fb47ca7fab4b65808 | 35442b3221299a9cadba6810573007736b0d65d4 | refs/heads/master | 2021-01-18T15:10:01.739413 | 2018-12-15T18:44:28 | 2018-12-15T18:44:28 | 27,730,565 | 11 | 3 | null | 2018-12-01T13:54:08 | 2014-12-08T19:15:22 | Racket | UTF-8 | Racket | false | false | 8,167 | scrbl | Draft.scrbl | #lang scribble/manual
@(require "../base/Shared/shared.rkt")
@(require racket/date (for-label racket))
@(define (one s) (string-append s ", "))
@(define copyright (with-output-to-string (lambda () (display #\u00A9))))
@(require (only-in racket with-output-to-string))
@margin-note{@copyright 1 August 2014 @link["http://mitpress.mit.edu"]{MIT Press}
This material is copyrighted and provided under the Creative Commons
@link["http://creativecommons.org/licenses/by-nc-nd/2.0/legalcode"]{CC
BY-NC-ND} license [@link["http://creativecommons.org/licenses/by-nc-nd/2.0/"]{interpretation}].}
@title[#:tag "htdp2e" #:style book-style ]{How to Design Programs, Second Edition}
@big-block[150]{
@centerline{
Matthias Felleisen,
Robert Bruce Findler,
Matthew Flatt,
Shriram Krishnamurthi}}
@margin-note{Do you notice the italics? Italicized words refer to technical
terms. Here they refer to books on programming currently in bookstores.}
Bad programming is easy. Even @italic{Dummies} can learn it in @italic{21 days}.
Good programming requires thought, but @bold{everyone} can do it and
@bold{everyone} can experience the extreme satisfaction that comes with
it. The price is worth paying for the sheer joy of the discovery process,
the elegance of the result, and the commercial benefits of a systematic
program design process.
The goal of our book is to introduce readers of all ages and backgrounds to
the craft of designing programs systematically. We assume few
prerequisites: arithmetic, a tiny bit of middle school algebra, and the
willingness to think through issues. We promise that the travails will pay
off not just for future programmers but for anyone who has to follow a
process or create one for others.
@; -----------------------------------------------------------------------------
@(define draft? (or (getenv "DRAFT") (is-draft?)))
@(define draft
@p[@list{This document is the @bold{draft release} of HtDP/2e. It
is updated on a frequent basis. The @link["../index.html"]{@bold{stable
version}} is released in conjunction with the PLT software and is thus more
suitable for teaching than this draft.}]
)
@(define release
@p[@list{This document is the @bold{current, stable release} of HtDP/2e. It is
updated in sync with semester breaks (summer, new years). It is thus
well-suited for courses. In contrast, @link["./Draft/index.html"]{the
@bold{current draft}} changes on a frequent basis; it should be consulted
when people discover problems and/or errors in this document. If such
flaws exist in both documents, please report them to the first author.}]
)
@(if draft? @bold{Draft Release} @bold{Stable Release})
@(if draft? draft release)
@centerline{Released on @(date->string (seconds->date (current-seconds)) draft)}
@;local-table-of-contents[]
@; -----------------------------------------------------------------------------
@;section[#:tag "difference" #:style 'unnumbered]
@bold{How the Second Edition Differs from the First}
This second edition of ``How to Design Programs'' differs from the first
one in several aspects:
@itemlist[#:style 'ordered
@item{The second edition explicitly acknowledges the difference between
designing a program and designing a bunch of functions. In particular,
this edition focuses on two kinds of programs: interactive, reactive
(graphical) programs and so-called batch programs.@margin-note*{Because
graphical interactive programs are more interesting than batch programs,
the book emphasizes the former over the latter.}}
@item{The design of a program proceeds in a top-down planning and a
bottom-up construction fashion. We explicitly show how the interface to
the libraries dictates the shape of certain program elements. In
particular, the very first phase of a program design yields a wish list of
functions. While the concept of a wish list existed in the first edition,
the second edition treats it as an explicit design element.}
@item{The design of each wish on the wish list exploits the design recipe
for functions. As in the first edition, the six parts focus on structural
design, compositional design, generative recursion, and design of both
structural and generative programs with accumulators.}
@item{A key element of structural design is the definition of functions
that compose others. This design-by-composition@margin-note*{We thank
Dr. Kathi Fisler for focusing our attention on this point.} is especially
useful for the world of batch programs. Like generative recursion, it
requires a eureka, specifically a recognition that the creation of
intermediate data by one function and processing the intermediate data by
a second function simplifies the overall design. Again, this kind of
planning also creates a wish list, but formulating these wishes calls for
an insightful development of an intermediate data definition. This edition
of the book weaves in a number of explicit exercises on
design-by-composition.}
@item{While testing has always been a part of the ``How to Design
Programs'' philosophy, the teaching languages and @dr[] started supporting
it properly only in 2002, just after we had released the first
edition. This new edition heavily relies on this testing support now.}
@item{This edition of the book drops the design of imperative programs. The
old chapters remain available on-line. The material will flow into the
second volume of this series, ``How to Design Components.''}
@item{The book's examples and exercises employ new teachpacks. The
preferred style is to link in these libraries via so-called
@racket[require] specifications, but it is still possible to add
teachpacks via a menu in @dr{}.}
@item{Finally, we decided to use a slightly different terminology:
@v-table[
@(map p
@list{
HtDP/1e
contract
union
})
@(map p
@list{
HtDP/2e
signature
itemization
})]
}
]
@; -----------------------------------------------------------------------------
@bold{Acknowledgments}
@; Special thanks
@; colleagues
@; Kathi, Gregor, Norman,
@; teachers
@; Dan (geb), Jack, Kyle, Nadeem
We thank
@one{Ennas Abdussalam}
@one{Saad Bashir}
Steven Belknap,
Stephen Bloch,
@one{Elijah Botkin}
@one{Anthony Carrico}
@one{Rodolfo Carvalho}
Estevo Castro,
Stephen Chang,
@one{Nelson Chiu}
Jack Clay,
@one{Richard Cleis}
John Clements,
@one{Mark Engelberg}
Christopher Felleisen,
Sebastian Felleisen,
Adrian German,
@one{Jack Gitelson}
@one{Kyle Gillette}
@one{Scott Greene}
Ryan Golbeck,
Josh Grams,
Nadeem Abdul Hamid,
@one{Jeremy Hanlon}
@one{Craig Holbrook}
@one{Wayne Iba}
Jordan Johnson,
@one{Blake Johnson}
@one{Erwin Junge}
Gregor Kiczales,
Eugene Kohlbecker,
Jackson Lawler,
Jay McCarthy,
@one{Mike McHugh}
@one{Wade McReynolds}
@one{Elena Machkasova}
@one{David Moses}
Ann E. Moskol,
@one{Scott Newson}
Paul Ojanen,
@one{Prof. Robert Ordóñez}
@one{Laurent Orseau}
Klaus Ostermann,
Sinan Pehlivanoglu,
@one{Eric Parker}
@one{Nick Pleatsikas}
Norman Ramsey,
@one{Krishnan Ravikumar}
@one{Jacob Rubin}
Luis Sanjuán,
@one{Ryan ``Havvy'' Scheel}
@one{Lisa Scheuing}
@one{Willi Schiegel}
@one{Vinit Shah}
@one{Nick Shelley}
@one{Matthew Singer}
Stephen Siegel,
@one{Joe Snikeris}
Marc Smith,
Dave Smylie,
Vincent St-Amour,
@one{Reed Stevens}
@one{Kevin Sullivan}
Éric Tanter,
Sam Tobin-Hochstadt,
@one{Thanos Tsouanas}
@one{Yuwang Yin}
David Van Horn,
@one{Jan Vitek}
Mitchell Wand,
@one{Michael Wijaya}
@one{G. Clifford Williams}
@one{Ewan Whittaker-Walker}
@one{Julia Wlochowski}
Roelof Wobben
and
@one{Mardin Yadegar}
for comments on previous drafts of this second edition.
The HTML layout is due to Matthew Butternick who created these styles for
the Racket documentation.
We are grateful to Ada Brunstein and Marie Lufkin Lee, our editors at MIT
Press, who gave us permission to develop this second edition of "How to
Design Programs" on-line.
@; -----------------------------------------------------------------------------
@table-of-contents[]
@; -----------------------------------------------------------------------------
@include-section["0prologue.scrbl"]
| false |
1313f68cd5361eca00db539dbeebce5f01d5a9fb | 2c819623a83d8c53b7282622429e344389ce4030 | /toy-ebpf-to-toy-riscv/make-compiler.rkt | 9a46c2ddf42da0de1c7d8a0d558433f8de88efd1 | []
| no_license | uw-unsat/jitsynth | 6bc97dd1ede9da42c0b9313a4766095345493adc | 69529e18d4a8d4dace884bfde91aa26b549523fa | refs/heads/master | 2022-05-29T05:38:57.129444 | 2020-05-01T19:35:32 | 2020-05-01T19:35:32 | 260,513,113 | 14 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 3,874 | rkt | make-compiler.rkt | #lang rosette
(require
"stp.rkt"
"../toy-riscv/interpreter.rkt"
"../toy-riscv/machine-instance.rkt"
"../common/case-hex.rkt"
"../common/data-utils.rkt"
"../common/data-structures.rkt"
"../common/options.rkt"
"../ams/machine.rkt")
(require (except-in "../toy-ebpf/interpreter.rkt" interpret))
(require rosette/lib/angelic)
(define stp (make-stp))
(define ebpf-iws (get-iwss (src/tgt-source stp)))
(define riscv-iws (get-iwss (src/tgt-target stp)))
(define dst (symbv 4))
(define src (symbv 4))
(define off (symbv 16))
(define imm (symbv 32))
(define src-insn (ebpf-insn 'addi32 dst src off imm))
; This is an intermediate things synthesized
; I can also make a query for this if needed
(define modif-imm (bvadd imm (bvshl (bvand imm (bv32 #x800)) (bv32 1))))
(define load
(list
(rv-insn
'lui
(bv #b111 5)
(bv 0 5)
(bv 0 5)
(extract 31 12 modif-imm))
(rv-insn
'addiw
(bv #b111 5)
(bv #b111 5)
(bv 0 5)
(extract 11 0 modif-imm))))
(define regmap
(lambda (index)
(case-hex index 4
[(0) (bv 15 5)]
[(1) (bv 10 8)]
[(2) (bv 11 5)]
[(3) (bv 12 5)]
[(4) (bv 13 5)]
[(5) (bv 14 5)]
[(6) (bv 9 5)]
[(7) (bv 18 5)]
[(8) (bv 19 5)]
[(9) (bv 20 5)]
[(10) (bv 21 5)]
[(11) (bv 5 5)])))
#|
(choose* (symbv 5) (regmap dst))
(choose* (symbv 5) (regmap dst))
(choose* (symbv 5) (regmap dst))
(symbv (if (equal? name 'lui) 20 12))))
|#
(define (insn-sketch-helper
name r1 r2 r3 imm12 imm20)
(rv-insn name r1 r2 r3 (if (equal? name 'lui) imm20 imm12)))
(define (opt-insn-sketch)
(let ([names '(lui addiw add slli srli)]
[r1 (choose* (symbv 5) (regmap dst))]
[r2 (choose* (symbv 5) (regmap dst))]
[r3 (choose* (symbv 5) (regmap dst))]
[imm12 (symbv 12)]
[imm20 (symbv 20)])
(apply choose*
(map
(lambda (n)
(insn-sketch-helper
n r1 r2 r3 imm12 imm20))
names))))
(define (basic-insn-sketch immval)
(let* ([names '(lui addiw add slli srli ld sd)]
[r1 (choose* (symbv 5) (regmap dst) (regmap src))]
[r2 (choose* (symbv 5) (regmap dst) (regmap src))]
[r3 (choose* (symbv 5) (regmap dst) (regmap src))]
[symimmval (symbv 20)]
[imm12 (extract 11 0 (choose* symimmval immval))]
[imm20 (choose* symimmval (extract 31 12 immval))])
(apply choose*
(map
(lambda (n)
(insn-sketch-helper
n r1 r2 r3 imm12 imm20))
names))))
(define (opt-sketch)
(append load (build-list 3 (thunk* (opt-insn-sketch)))))
(define (basic-sketch)
(let ([immval (symbv-func-apply 48 32 (concat off imm))])
(build-list 5 (thunk* (basic-insn-sketch immval)))))
(define (mid-sketch)
(let ([immval (symbv-func-apply 48 32 (concat off imm))])
(append load (build-list 3 (thunk* (basic-insn-sketch immval))))))
(define tgt-start-state (machine-default-state (src/tgt-target stp)))
(define src-start-state (t2s-state stp tgt-start-state))
(define (query sketch)
(synthesize
#:forall (list src-insn tgt-start-state)
#:assume (ebpf-iws (list src-insn) src-start-state (bv64 1))
#:guarantee
(let* ([src-state (ebpf-iws (list src-insn) src-start-state (bv64 1))]
[tgt-state (riscv-iws sketch tgt-start-state (bv64 (length sketch)))])
(assert
(bveq
(read-register
(state-regs tgt-state)
(regmap dst))
(read-register
(state-regs src-state)
dst))))))
(define skch (basic-sketch))
; (define skch (opt-sketch))
; (define skch (mid-sketch))
(define mdl
(time
(complete-solution
(query skch)
(remove* (symbolics src-insn) (symbolics skch)))))
(for ([i 5])
(displayln (list-ref (evaluate skch mdl) i)))
| false |
37567202aebec1b9d6f281017e6e67b024dfbeae | b3f7130055945e07cb494cb130faa4d0a537b03b | /gamble/examples/par-pf-airplane-sim.rkt | 489b3ad8e758efe0deb670c8fd233325d1b85da2 | [
"BSD-2-Clause"
]
| permissive | rmculpepper/gamble | 1ba0a0eb494edc33df18f62c40c1d4c1d408c022 | a5231e2eb3dc0721eedc63a77ee6d9333846323e | refs/heads/master | 2022-02-03T11:28:21.943214 | 2016-08-25T18:06:19 | 2016-08-25T18:06:19 | 17,025,132 | 39 | 10 | BSD-2-Clause | 2019-12-18T21:04:16 | 2014-02-20T15:32:20 | Racket | UTF-8 | Racket | false | false | 3,832 | rkt | par-pf-airplane-sim.rkt | ;; Copyright (c) 2014 Ryan Culpepper
;; Released under the terms of the 2-clause BSD license.
;; See the file COPYRIGHT for details.
#lang gamble
(require slideshow/pict
(rename-in racket/match [match-define defmatch])
"par-pf-airplane-model.rkt")
(provide (all-defined-out))
;; The model needs to be in a separate module from the GUI code, else
;; the places try to restart racket/gui (error).
;; ------------------------------------------------------------
;; Simulation & Inference
(define NPARTICLES 100)
(define STEPS 100)
(define terrain terrain3)
(define xtrues (make-vector STEPS))
(vector-set! xtrues 0 (airplane-init #f))
(for ([i (in-range 1 STEPS)])
(vector-set! xtrues i (airplane-after-step (vector-ref xtrues (sub1 i)))))
(define observed-altitudes
(for/vector ([xtrue (in-vector xtrues)])
(observed-altimeter-reading xtrue terrain)))
(define particless (make-vector STEPS))
(for ([i (in-range STEPS)]
[obs (in-vector observed-altitudes)])
(let* ([prev-ps
(cond [(zero? i)
(particles-update (make-parallel-particles NPARTICLES #f)
airplane-init)]
[else
(particles-resample
(vector-ref particless (sub1 i)))])]
[curr-ps (particles-update prev-ps airplane-after-step)]
[curr-ps (particles-score curr-ps (airplane-score terrain obs))])
(vector-set! particless i curr-ps)))
(define (particles-mean ps)
(define-values (ssum wsum)
(for/fold ([ssum 0] [wsum 0])
([wstate (in-vector (particles-weighted-states ps))])
(defmatch (cons s w) wstate)
(values (+ ssum (* s w)) (+ wsum w))))
(/ ssum wsum))
;; ============================================================
;; Visualization
(require racket/class
racket/vector
plot/pict
gamble/viz/multi)
(define (visualize [plotter plot-both])
(define mv (make-multi-viz-frame #:label "Airplane Localization"))
(for ([xtrue xtrues]
[ps particless])
(send mv add-pict (plotter xtrue ps))))
(define (plot-both xtrue ps)
(hc-append 10 (plot-simulation xtrue ps) (plot-likelihood xtrue ps)))
(define (plot-simulation xtrue ps)
(define wstates (particles-weighted-states ps))
(define positions (vector-map car wstates))
(define xest (particles-mean ps))
(plot
(list (function-interval terrain (lambda (p) 0) #:color "green")
(lines (list (vector xest (+ ALTITUDE 100)) (vector xest (- ALTITUDE 100)))
#:label "estimate" #:style 'dot #:color "red")
(points (for/list ([p positions]) (vector p ALTITUDE))
#:label "particles" #:size 2 #:color "red")
(points (list (vector xtrue ALTITUDE))
#:label "true position"
#:size 4
#:sym 'fulldiamond
#:color "blue"))
#:x-label "position"
#:y-label "altitude"
#:x-min 0 #:x-max XMAX
#:y-min 0 #:y-max 6000))
(define (plot-likelihood xtrue ps)
(define wstates (particles-weighted-states ps))
(define positions (vector-map car wstates))
(define weights (vector-map log (vector-map cdr wstates)))
(define xest (particles-mean ps))
(plot
(list (lines (list (vector xtrue 0) (vector xtrue -10))
#:color "blue"
#:style 'long-dash
#:label "target")
(lines (list (vector xest 0) (vector xest -10))
#:color "red"
#:style 'dot
#:label "mean estimate")
(points (vector->list (vector-map vector positions weights))
#:label "log probability"
#:size 8
#:color 'red))
#:x-label "position"
#:y-label "log likelihood"
#:x-min 0 #:x-max XMAX
#:y-min -10 #:y-max 0))
| false |
2ae0422153b5e0b676cb292edd653fb857894450 | cd9a2d11c110b6e02dae1328e23445e2871f0863 | /tests/superc/bdb.rkt | 121937f50b5473e78a9b6d405b16fc2d397635a8 | []
| no_license | julian-becker/superc | f230aba7795e3e13e5ca79883be284b7a94861d9 | 929d3e32db7a5c69fa9e033db7b5707cff329672 | refs/heads/master | 2020-05-24T03:24:10.851047 | 2015-12-19T21:50:03 | 2015-12-19T21:50:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,043 | rkt | bdb.rkt | #lang superc
(define-syntax (maybe-db stx)
(if (not (directory-exists? "/opt/local/include/db48"))
(syntax @c{int main() { return 0; }})
(syntax
(begin
@cflags{-I/opt/local/include/db48}
@ldflags{-L/opt/local/lib/db48 -ldb}
@c{
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <db.h>
#define DATABASE "access.db"
int
main()
{
DB *dbp;
DBT key, data;
int ret, t_ret;
/* Create the database handle and open the underlying database. */
if ((ret = db_create(&dbp, NULL, 0)) != 0) {
fprintf(stderr, "db_create: %s\n", db_strerror(ret));
exit (1);
}
if ((ret = dbp->open(dbp,
NULL, DATABASE, NULL, DB_BTREE, DB_CREATE, 0664)) != 0) {
dbp->err(dbp, ret, "%s", DATABASE);
goto err;
}
/* Initialize key/data structures. */
memset(&key, 0, sizeof(key));
memset(&data, 0, sizeof(data));
key.data = "fruit";
key.size = sizeof("fruit");
data.data = "apple";
data.size = sizeof("apple");
/* Store a key/data pair. */
if ((ret = dbp->put(dbp, NULL, &key, &data, 0)) == 0)
printf("db: %s: key stored.\n", (char *)key.data);
else {
dbp->err(dbp, ret, "DB->put");
goto err;
}
/* Retrieve a key/data pair. */
if ((ret = dbp->get(dbp, NULL, &key, &data, 0)) == 0)
printf("db: %s: key retrieved: data was %s.\n",
(char *)key.data, (char *)data.data);
else {
dbp->err(dbp, ret, "DB->get");
goto err;
}
/* Delete a key/data pair. */
if ((ret = dbp->del(dbp, NULL, &key, 0)) == 0)
printf("db: %s: key was deleted.\n", (char *)key.data);
else {
dbp->err(dbp, ret, "DB->del");
goto err;
}
/* Retrieve a key/data pair. */
if ((ret = dbp->get(dbp, NULL, &key, &data, 0)) == 0)
printf("db: %s: key retrieved: data was %s.\n",
(char *)key.data, (char *)data.data);
else
dbp->err(dbp, ret, "DB->get");
err: if ((t_ret = dbp->close(dbp, 0)) != 0 && ret == 0)
ret = t_ret;
exit(ret);
}
}
))))
(maybe-db)
(define main (get-ffi-obj-from-this 'main (_fun -> _int)))
(printf "The C program returned: ~a~n"
(main))
| true |
36ef716eced88624ba5da9eaf5d46fc3f395018e | 0f6e59eeda27cfb61e0623e5e795c514da53f95f | /macro-debugger/macro-debugger/syntax-browser/embed.rkt | f95756cb894e86f8c46f38f6c8b0e75f07480fb9 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | racket/macro-debugger | 1679a781fe0d601bb0e9c97d224f0d06ee777b24 | 047c36a4d6a0b15a31d0fa7509999b9bf2c5f295 | refs/heads/master | 2023-08-24T04:09:14.428768 | 2023-01-18T02:27:26 | 2023-01-18T02:27:26 | 27,413,285 | 10 | 14 | NOASSERTION | 2021-05-04T22:30:05 | 2014-12-02T03:30:26 | Racket | UTF-8 | Racket | false | false | 332 | rkt | embed.rkt | #lang racket/base
(require macro-debugger/syntax-browser/interfaces
"widget.rkt"
"keymap.rkt"
macro-debugger/syntax-browser/partition)
(provide (all-from-out macro-debugger/syntax-browser/interfaces)
(all-from-out "widget.rkt")
(all-from-out "keymap.rkt")
identifier=-choices)
| false |
8255a41a0f059eb4076a1faa1b526503def6cf12 | d3645e518084e8e16747fc893996c5c114c76d0c | /racketscript-compiler/racketscript/boot/lang/private/interop.rkt | 5c5d87fa21cb51c83793905cc7f7cb4318a7349f | [
"MIT"
]
| permissive | freeduck/racketscript | ba3a1f640ef8f355505f9aa28164804038f9d76f | d7ede990c3faf891aa19a47fa3b3f94bfe832c42 | refs/heads/master | 2020-09-10T14:25:45.676891 | 2019-11-14T14:31:56 | 2019-11-14T14:31:56 | 221,717,581 | 0 | 0 | MIT | 2019-11-14T14:34:00 | 2019-11-14T14:33:59 | null | UTF-8 | Racket | false | false | 2,959 | rkt | interop.rkt | #lang racket/base
(require racket/match
racket/string
racket/syntax
syntax/readerr
(only-in racketscript/compiler/util-untyped
js-identifier?))
(provide (rename-out [x-read read]
[x-read-syntax read-syntax]))
(define (x-read in)
(syntax->datum (x-read-syntax #f in)))
(define (x-read-syntax src in)
(skip-whitespace in)
(read-racketscript src in))
(define (skip-whitespace in)
(regexp-match #px"^\\s*" in))
(define (parts->ffi strs first-id?)
(define result (cond
[first-id? (car strs)]
[(js-identifier? (car strs))
`(#%js-ffi 'var ',(car strs))]
[else (error 'ffi "invalid characters in js identifier")]))
(let loop ([strs (cdr strs)]
[result result])
(match strs
['() (datum->syntax #f result)]
[(cons hd tl)
(loop tl
`(#%js-ffi 'ref ,result ',hd))])))
(define (get-id-parts in)
(map string->symbol (string-split
(symbol->string
(syntax-e
(read-syntax (object-name in) in)))
".")))
(define (read-racketscript src in)
(define-values (line col pos) (port-next-location in))
(define (peek-char=? offset chr)
(char=? (peek-char in offset) chr))
(cond
[(and #;(peek-char=? 0 #\j)
(peek-char=? 0 #\s)
(peek-char=? 1 #\.)
(read-string 2 in))
(parts->ffi (get-id-parts in) #t)]
[(and #;(peek-char=? 0 #\j)
(peek-char=? 0 #\s)
(peek-char=? 1 #\*)
(peek-char=? 2 #\.)
(read-string 2 in))
(parts->ffi (get-id-parts in) #f)]
[(and (peek-char=? 0 #\s)
(peek-char=? 1 #\")
(read-string 1 in))
(datum->syntax #f `(#%js-ffi 'string ,(read-syntax (object-name in) in)))]
[else #f]))
(module+ test
(require rackunit
racketscript/interop)
(define-simple-check (check-reader str first-id? result)
(equal? (syntax->datum
(read-racketscript #f (open-input-string
(string-append
(if first-id? "s." "s*.")
str))))
result))
(check-reader "window" #t 'window)
(check-reader "window" #f '(#%js-ffi 'var 'window))
(check-reader "window.document" #t `(#%js-ffi 'ref window 'document))
(check-reader "window.document.write" #t
`(#%js-ffi 'ref (#%js-ffi 'ref window 'document) 'write))
(check-reader "window.document" #f
`(#%js-ffi 'ref (#%js-ffi 'var 'window) 'document))
(check-reader "window.document.write" #f
`(#%js-ffi 'ref
(#%js-ffi 'ref
(#%js-ffi 'var 'window)
'document)
'write)))
| false |
63ab48126fdee02c7167be9826d2aa5f4b4abb2e | d755de283154ca271ef6b3b130909c6463f3f553 | /htdp-doc/test-engine/test-engine.scrbl | 974ab543e711e7add62e94726a63b6589fff3872 | [
"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 | 12,700 | scrbl | test-engine.scrbl | #lang scribble/doc
@(require (for-label racket/base test-engine/racket-tests test-engine/test-markup))
@(require scribble/manual scribble/eval racket/sandbox)
@(define-syntax-rule (mk-eval defs ...)
;; ==>
(let ([me (make-base-eval)])
(call-in-sandbox-context me (lambda () (error-print-source-location #f)))
(interaction-eval #:eval me defs)
...
me))
@title{Test Support}
@table-of-contents[]
@; ----------------------------------------------------------------------
@section{Using Check Forms}
@defmodule[test-engine/racket-tests]
This module provides test forms for use in Racket programs, as well
as parameters to configure the behavior of test reports.
Each check form may only occur at the top-level; results are collected
and reported by the test function. Note that the check forms only
register checks to be performed. The checks are actually run by the
@racket[test] function.
@defform[(check-expect expr expected-expr)]{
Checks whether the value of the @racket[expr] expression is
@racket[equal?] to the value produced by the @racket[expected-expr].
It is an error for @racket[expr] or @racket[expected-expr] to produce a function
value or an inexact number.}
@defform[(check-random expr expected-expr)]{
Checks whether the value of the @racket[expr] expression is
@racket[equal?] to the value produced by the @racket[expected-expr].
The form supplies the same random-number generator to both parts. If both
parts request @racket[random] numbers from the same interval in the same
order, they receive the same random numbers.
@examples[#:eval (mk-eval (require test-engine/racket-tests))
(check-random (random 10) (random 10))
(check-random
(begin (random 100) (random 200))
(begin (random 100) (random 200)))
(test)
]
If the two parts call @racket[random] for different intervals, they are
likely to fail:
@examples[#:eval (mk-eval (require test-engine/racket-tests))
(check-random
(begin (random 100) (random 200))
(begin (random 200) (random 100)))
(test)
]
It is an error for @racket[expr] or @racket[expected-expr] to produce a function
value or an inexact number.}
@defform[(check-satisfied expr property?)]{
Checks whether the value of the @racket[expr] expression satisfies
the @racket[property?] predicate (which must evaluate to a function of one
argument).
@examples[#:eval (mk-eval (require test-engine/racket-tests))
(check-satisfied 1 odd?)
(check-satisfied 1 even?)
(test)
]
@history[
#:changed
"1.1"
"allow the above examples to run in BSL and BSL+"]
}
@defform[(check-within expr expected-expr delta-expr)
#:contracts ([delta-expr number?])]{
Checks whether the value of the @racket[test] expression is structurally
equal to the value produced by the @racket[expected] expression; every
number in the first expression must be within @racket[delta] of the
corresponding number in the second expression.
It is an error for @racket[expr] or @racket[expected] to produce a function
value.}
@defform*[ [(check-error expr)
(check-error expr msg-expr)]
#:contracts ([msg-expr string?]) ]{
Checks that evaluating @racket[expr] signals an error, where
the error message matches the string (if any).}
@defform[(check-member-of expr expected-expr ...)]{
Checks whether the value of the @racket[expr] expression is @racket[equal?]
to any of the values produced by the @racket[expected-expr]s.
It is an error for @racket[expr] or any of the @racket[expected-expr]s
to produce a function value or an inexact number.}
@defform[(check-range expr min-expr max-expr)
#:contracts ([expr number?]
[min-expr number?]
[max-expr number?])]{
Checks whether value of @racket[expr] is between the values of
@racket[min-expr] and @racket[max-expr] inclusive.}
@defform[(test)]{
Runs all of the tests specified by check forms in the current module
and reports the results. When using the gui module, the results are
provided in a separate window, otherwise the results are printed to
the current output port.}
@defboolparam[test-silence silence?]{
A parameter that stores a boolean, defaults to #f, that can be used to
suppress the printed summary from test.}
@defboolparam[test-execute execute?]{
A parameter that stores a boolean, defaults to #t, that can be used to
suppress evaluation of test expressions.
}
@section{Running Tests and Inspecting Test Results}
@defmodule[test-engine/test-engine]
This module defines language-agnostic procedures for running test code
to execute checks, and recording and inspecting their results.
A @italic{test} is a piece of code run for testing, a @italic{check}
is a single assertion within that code: Typically the tests are first
registered, then they are run, and then their results are inspected.
Both tests and the results of failed checks are recorded in a data
structure called a @italic{test object}. There is always a current
test object associated with the current namespace.
@defstruct*[test-object
((tests (listof (-> any)))
(failed-checks (listof failed-check?))
(signature-violations (listof signature-violation?)))
#:omit-constructor]{
The three components of a @racket[test-object] are all in reverse order:
The first one is the list of tests (each represented by a thunk), the
others are failed checks and signature violations, respectively.
}
@defproc[(empty-test-object) test-object?]{
Creates an empty test object.
}
@defproc[(current-test-object) test-object?]{
Returns the current test object.
}
@defproc[(initialize-test-object!) any]{
Initializes the test object. Note that this is not necessary before
using @racket[current-test-object] and the various other functions
operating on it: These will automatically initialize as necessary.
Use this function to reset the current test object.
}
@defproc[(add-test! [thunk (-> any)]) any]{
Register a test, represented by a thunk. The thunk, when called, is
expected to call @racket[add-failed-check!] and
@racket[add-signature-violation!] as appropriate.
}
@defproc[(add-failed-check! [failed-check failed-check?]) any]{
Record a test failure.
}
@defproc[(add-signature-violation! [violation signature-violation?]) any]{
Record a signature violation.
}
@defproc[(run-tests!) test-object?]{
Run the tests, calling the thunks registered via @racket[add-test!] in
the order they were registered.
}
@defstruct*[failed-check ((reason fail-reason?)
(srcloc? (or/c #f srcloc?)))]{
This is a description of a failed check.
The source location, if present, is from an expression that may have caused the failure,
possibly an exception.}
@defstruct*[fail-reason ((srcloc srcloc?))]{
Common supertype of all objects describing a reason for a failed check.
The @code{srcloc} is the source location of the check.}
@defstruct*[(unexpected-error fail-reason)
((srcloc srcloc?)
(expected any/c)
(exn exn?))]{
An error happened instead of regular termination.
}
@defstruct*[(unexpected-error/markup unexpected-error)
((srcloc srcloc?)
(expected any/c)
(exn exn?)
(error-markup markup?))]{
An error happened instead of regular termination. This also contains markup
describing the error.
}
@defstruct*[(unequal fail-reason)
((srcloc srcloc?)
(actual any/c)
(expected any/c))]{
A value was supposed to be equal to another, but wasn't.
Generated by @racket[check-expect].
}
@defstruct*[(not-within fail-reason)
((srcloc srcloc?)
(actual any/c)
(expected any/c)
(range real?))]{
A value was supposed to be equal to another within a certain range, but wasn't.
Generated by @racket[check-within].
}
@defstruct*[(incorrect-error fail-reason)
((srcloc srcloc?)
(expected any/c)
(exn exn?))]{
An exception was expected, but a different one occurred.
Generated by @racket[check-error].
}
@defstruct*[(incorrect-error/markup incorrect-error)
((srcloc srcloc?)
(expected any/c)
(exn exn?)
(error-markup markup?))]{
An exception was expected, but a different one occurred.
Also includes markup describing the error.
Generated by @racket[check-error].
}
@defstruct*[(expected-error fail-reason)
((srcloc srcloc?)
(message (or/c #f string?))
(value any/c))]{
An error was expected, but a value came out instead.
Generated by @racket[check-error].
}
@defstruct*[(not-mem fail-reason)
((srcloc srcloc?)
(actual any/c)
(set (listof any/c)))]{
The value produced was not part an the expected set.
Generated by @racket[check-member-of].
}
@defstruct*[(not-range fail-reason)
((srcloc srcloc?)
(actual real?)
(min real?)
(max real?))]{
The value produced was not part an the expected range.
Generated by @racket[check-range].
}
@defstruct*[(satisfied-failed fail-reason)
((srcloc srcloc?)
(actual any/c)
(name string?))]{
The value produced did not satisfy a predicate.
The @code{name} field is the name of the predicate.
Generated by @racket[check-satisfied].
}
@defstruct*[(unsatisfied-error fail-reason)
((srcloc srcloc?)
(name string?)
(exn exn?))]{
A value was supposed to satsify a predicate, but an error happened
instead. The @code{name} field is the name of the predicate.
Generated by @racket[check-satisfied].
}
@defstruct*[(unsatisfied-error/markup unsatisfied-error)
((srcloc srcloc?)
(name string?)
(exn exn?)
(error-markup markup?))]{
A value was supposed to satsify a predicate, but an error happened
instead. The @code{name} field is the name of the predicate.
Also includes markup describing the error.
Generated by @racket[check-satisfied].
}
@defstruct*[(violated-signature fail-reason)
((srcloc srcloc?)
(obj any/c)
(signature signature?)
(blame-srcloc (or/c #f srcloc?)))]{
A signature was violated, and this was communicated via an exception.
Note that signature violations should really be (and usually are)
communicated via @racket[add-signature-violation!].
}
@defstruct*[signature-got
((value any/c))]{
The value that violated the signature.
}
@defstruct*[signature-violation
((obj any/c)
(signature signature?)
(message (or/c string? signature-got?))
(srcloc (or/c #f srcloc?))
(blame-srcloc (or/c #f srcloc?)))]{
Signature @code{signature} was violated by object @code{obj}.
The @code{srcloc} field is the location of the signature.
The optional @code{blame-srcloc} points at the source code to blame
for the violation.
}
@defstruct*[(property-fail fail-reason)
((srcloc srcloc?)
(result check-result?))]{
A counterexample for a property was found, described in the @code{result} field.
}
@defstruct*[(property-error fail-reason)
((srcloc srcloc?)
(exn exn?))]{
A property check produced an unexpected exception.
}
@section{Printing Test Results}
This module is responsible for output of test results: Where the
output goes, and some aspects of the formatting can be customized via parameters.
@defmodule[test-engine/test-markup]
@defparam[render-value-parameter render-value-proc (any/c . -> . string?)]{
This parameter determines how @racket[test-object->markup] renders a value
for display in an error message in a language-specific way.
The default is @racket[(lambda (v) (format "~V" v))].
}
@defparam[display-test-results-parameter display-test-proc (markup? . -> . any)]{
This parameter determines how to output the test results.
The default prints to @racket[(current-output-port)].
}
@defproc[(display-test-results! [test-object test-object?]) any]{
This just calls the procedure bound to @racket[display-test-results-parameter].
}
@defparam[get-rewritten-error-message-parameter get-rewritten-error-message-proc (exn? . -> . string?)]{
This parameter determines how to get an error message from an exception,
possibly after reformulation and/or translation.
}
@defproc[(get-rewritten-error-message [exn exn?]) string?]{
This just calls the procedure bound to @racket[get-rewritten-error-message-parameter].
}
@defproc[(test-object->markup [test-object test-object?]) markup?]{
This generates a test report as markup, using
@racket[render-value-parameter] and
@racket[get-rewritten-error-message-parameter].
}
| true |
e95345d5ebafd919c167c20e66ea54e2a9baacde | 799b5de27cebaa6eaa49ff982110d59bbd6c6693 | /soft-contract/test/proofs/correct/quickcheck-paper.rkt | aab29911b9096c860ce6687bc0d4f2f107ad03c7 | [
"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 | 1,981 | rkt | quickcheck-paper.rkt | #lang racket/base
(require racket/contract
racket/match
soft-contract/induction)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Helpers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (append xs ys)
(match xs
['() ys]
[(cons x xs*) (cons x (append xs* ys))]))
(define (reverse xs)
(match xs
['() '()]
[(cons x xs*) (append (reverse xs*) (list x))]))
(define (insert x xs)
(match xs
['() (list x)]
[(cons x* xs*) (cond [(<= x x*) (list* x x* xs*)]
[else (cons x* (insert x xs*))])]))
(define (ordered? xs)
(match xs
['() #t]
[(list _) #t]
[(cons x₁ (and xs* (cons x₂ _))) (and (<= x₁ x₂) (ordered? xs*))]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 2.1 Simple Example
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-theorem thm-rev-unit (∀ (x) (equal? (reverse (list x)) (list x))))
(define-theorem thm-rev-app (∀ ([xs ys list?]) (equal? (reverse (append xs ys)) (append (reverse ys) (reverse xs)))))
(define-theorem thm-rev-rev (∀ ([xs list?]) (equal? (reverse (reverse xs)) xs)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 2.2 Functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; In paper, test needed a monomorphic instance.
;; Verification needs not.
(define ((=== f g) x) (equal? (f x) (g x)))
(define-theorem thm-comp-assoc
(∀/c (α β γ δ)
(∀ ([f (γ . -> . δ)] [g (β . -> . γ)] [h (α . -> . β)] [x α])
((=== (compose1 f (compose1 g h)) (compose (compose1 f g) h)) x))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 2.3 Conditional Laws
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-theorem thm-max-le
(∀ ([x integer?] [y (and/c integer? (>=/c x))])
(equal? (max x y) y)))
(define-theorem thm-insert
(∀ ([x integer?] [xs (and/c (listof integer?) ordered?)])
(ordered? (insert x xs))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 2.5 Inifite Structures (TODO)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
| false |
9acb1653d34e727ed32c8efb2391b8e3c5ab92cf | 21d7d49a0e07472e62ae872cfee6125cbf56f338 | /0005-new.rkt | e91bf807a8aaf8204b8ce7bb35cf796725210090 | []
| no_license | samdphillips/euler | 6a9cf72869f3d72cc8b08c95e25bc1442cebe7d5 | 8de2256efff98d8b7093af2d058eb62eedc98d1f | refs/heads/master | 2021-11-24T07:49:04.982593 | 2021-10-27T04:49:53 | 2021-10-27T04:49:53 | 1,365,307 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 969 | rkt | 0005-new.rkt | #lang racket/base
#|
2520 is the smallest number that can be divided by each of the numbers
from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all
of the numbers from 1 to 20?
The original version I wrote was before the addition of the math/number-theory library.
This is much faster using the speed tuned library.
|#
(require math/number-theory
racket/match)
(define (merge-factors f1* f2*)
(match* {f1* f2*}
[{'() f2*} f2*]
[{f1* '()} f1*]
[{(cons (list f e1) f1*) (cons (list f e2) f2*)}
(cons (list f (max e1 e2))
(merge-factors f1* f2*))]
[{(cons (and p1 (list f1 _)) f1**) (cons (and p2 (list f2 _)) f2**)}
(if (< f1 f2)
(cons p1 (merge-factors f1** f2*))
(cons p2 (merge-factors f1* f2**)))]))
(define (solve n)
(for/fold ([f null] #:result (defactorize f))
([i (in-range 2 (add1 n))])
(merge-factors f (factorize i))))
| false |
0de5575487dca3d19cb5c43190686cc48acb6240 | 18a51a897441d33155dda9b1969c1d4898820530 | /base/modules/builtin-modules.rkt | 2f0b0c8f2543471541f5ddd643aad1a05cf7efbc | [
"Apache-2.0"
]
| permissive | jpolitz/lambda-py | 6fc94e84398363c6bb2e547051da9db6466ab603 | a2d1be7e017380414429a498435fb45975f546dd | refs/heads/master | 2019-04-21T09:36:42.116912 | 2013-04-16T13:30:44 | 2013-04-16T13:30:44 | 7,525,003 | 1 | 0 | null | 2013-01-09T22:32:47 | 2013-01-09T16:54:10 | Racket | UTF-8 | Racket | false | false | 633 | rkt | builtin-modules.rkt | #lang plai-typed/untyped
(require "sys.rkt"
"main-module.rkt"
"../python-core-syntax.rkt"
"../util.rkt")
(define (get-builtin-module-names)
(map (lambda (x)
(Module-name x))
(builtin-modules-list)))
(define (get-builtin-modules)
(map (lambda (x)
(Module-object x))
(builtin-modules-list)))
;; add new built-in modules info here, then all should work fine in
;; python-lib and python-lib-bindings.
(define (builtin-modules-list)
(list
(Module main-module-name main-module)
; make sure to put sys at the last
(Module sys-module-name sys-module)
))
| false |
236806690abb792b6116e6a9c2b868e5b68ef665 | 063934d4e0bf344a26d5679a22c1c9e5daa5b237 | /racket/tests/old/lang-margrave-tests.rkt | fab1e80187e073547d1500a2c02c164a6312cb7e | []
| no_license | tnelson/Margrave | 329b480da58f903722c8f7c439f5f8c60b853f5d | d25e8ac432243d9ecacdbd55f996d283da3655c9 | refs/heads/master | 2020-05-17T18:43:56.187171 | 2014-07-10T03:24:06 | 2014-07-10T03:24:06 | 749,146 | 5 | 2 | null | null | null | null | UTF-8 | Racket | false | false | 10,223 | rkt | lang-margrave-tests.rkt | #lang margrave
// Tests of Margrave commands.
// TODO
// The Margrave script language doesn't allow testing the _results_
// So once inlining in Racket is finished, move these tests inline
// and confirm they return the correct results
// TODO
// invoke Java tests (needs to be from Racket)
// TODO: import the rest of the old SISC tests
// ***************************************
// Initial basic tests for syntax coverage
// ***************************************
info;
//info doesntexist;
// LOAD POLICY (no-path, *MARGRAVE*, relative path. with and without quotes)
load policy "conference1.p";
LOAD POLICY "*MARGRAVE*/tests/conference2.p";
load policy ./emptyconference.p;
// RENAME
rename conferencepolicy1 conf1;
// EXPLORE + UNDER + AND + NOT
explore assigned(s, r) AND NOT assigned(s, r) UNDER conf1;
// more than one UNDER
explore assigned(s, r) AND NOT assigned(s, r)
UNDER conf1, conferencepolicy2;
// IS POSSIBLE? + SHOW ONE + SHOW ALL
// expect: unsat
IS POSSIBLE?;
SHOW ONE;
SHOW ALL;
// IMPLIES
explore conf1:permit(s, a, r) AND
(subject(s) IMPLIES NOT subject(s));
// expect: unsat
IS POSSIBLE?;
// IFF
explore conf1:permit(s, a, r) AND
(subject(s) IFF NOT subject(s));
// expect: unsat
IS POSSIBLE?;
// basic request vector sugar
explore conf1:permit(<conf1:req>);
// publish and vector in publish
explore conf1:permit(<conf1:req>) PUBLISH <conf1:req>;
// last ID, info saved query
info last;
// Result accessor commands with and without explicit ID
IS POSSIBLE? 0;
SHOW ONE 0;
SHOW NEXT 0;
GET ONE 0;
GET NEXT 0;
GET ALL 0;
COUNT 0;
SHOW ONE;
SHOW NEXT;
GET ONE;
GET NEXT;
GET ALL;
COUNT;
// Accessing a policy's rule set
GET RULES IN conf1;
GET QUALIFIED RULES IN conf1;
GET RULES IN conf1 WITH DECISION permit;
GET QUALIFIED RULES IN conf1 WITH DECISION permit;
// TODO: realized (later in doc?)
// TODO: rest of syntax
// ***************************************
// Tests from old SISC suite
// ***************************************
load policy "*MARGRAVE*/tests/extconference.p";
load policy "*MARGRAVE*/tests/conference1.p";
load policy "*MARGRAVE*/tests/hospitaldenypayrollmedrecsfa.p";
rename hospitaldenypayrollmedrecs hospitalfa;
load policy "*MARGRAVE*/tests/hospitaldenypayrollmedrecsdo.p";
rename hospitaldenypayrollmedrecs hospitaldo;
load policy "*MARGRAVE*/tests/awfw.p";
load policy "*MARGRAVE*/tests/bigfw.p";
load policy "*MARGRAVE*/tests/phone1.p";
EXPLORE BigFW:Accept(ipsrc, ipdest, portsrc, portdest);
IS POSSIBLE?;
// expect: true
// Empty policy never permits
EXPLORE EmptyConference:Permit(s, a, r);
IS POSSIBLE?;
// expect: false
// *******************************************************************
// *******************************************************************
// Use the happy router "more" secure side policy for realized testing
load policy "*MARGRAVE*/tests/happyroutermore.p";
// Tests for REALIZED without tupling
// Much slower without tupling
// IMPORTANT: Note below rulex_applies -> rule1_matches, which seems
// nonsensical. But without tupling, realized can be read as populated.
// other packets exist populating rule1_matches...
// DISABLED 10/11/10 by TN
// since we are changing the syntax of SHOW REALIZED w/o tupling
// to match the tupled case
//explore happyroutermore:accept(<happyroutermorex:req>)
//explore happyroutermore:accept(<happyroutermore:req>) AND
// tcp=pro AND ipsrc=webserver and portdest=portsrc and portdest=http
//include happyroutermore:rule1_matches,
// happyroutermore:ruleX_matches,
// happyroutermore:rule1_applies,
// happyroutermore:ruleX_applies;
//SHOW ONE;
//SHOW REALIZED happyroutermore:rule1_matches,
// happyroutermore:ruleX_matches;
//SHOW UNREALIZED happyroutermore:rule1_matches,
// happyroutermore:ruleX_matches;
//SHOW REALIZED happyroutermore:rule1_matches,
// happyroutermore:ruleX_matches
//FOR CASES happyroutermore:rule1_applies,
// happyroutermore:ruleX_applies;
//SHOW UNREALIZED happyroutermore:rule1_matches,
// happyroutermore:ruleX_matches
//FOR CASES happyroutermore:rule1_applies,
// happyroutermore:ruleX_applies;
// *******************************************************************
// Tests for REALIZED with tupling
// TUPLING, INCLUDE, SHOW REALIZED
// Need a policy with q-free IDBs to TUPLE (so can't use the phone policy)
explore ipaddress(ipsrc) and ipaddress(ipdest)
UNDER happyroutermore
include happyroutermore:rule1_matches(<happyroutermore:req>),
happyroutermore:rule2_matches(<happyroutermore:req>),
happyroutermore:rule3_matches(<happyroutermore:req>),
happyroutermore:ruleX_matches(<happyroutermore:req>),
happyroutermore:rule1_applies(<happyroutermore:req>),
happyroutermore:rule2_applies(<happyroutermore:req>),
happyroutermore:rule3_applies(<happyroutermore:req>),
happyroutermore:ruleX_applies(<happyroutermore:req>)
TUPLING;
// Don't enable this: error when user forgets qualifier in INCLUDE
// But check for exn:fail:user, not null ptr
//explore ipaddress(ipsrc) and ipaddress(ipdest)
//UNDER happyroutermore
//include rule1_matches(<happyroutermore:req>),
// rule2_matches(<happyroutermore:req>),
// rule3_matches(<happyroutermore:req>),
// ruleX_matches(<happyroutermore:req>)
//TUPLING;
SHOW REALIZED happyroutermore:rule1_matches(<happyroutermore:req>),
happyroutermore:rule2_matches(<happyroutermore:req>),
happyroutermore:rule3_matches(<happyroutermore:req>),
happyroutermore:ruleX_matches(<happyroutermore:req>);
SHOW UNREALIZED happyroutermore:rule1_matches(<happyroutermore:req>),
happyroutermore:rule2_matches(<happyroutermore:req>),
happyroutermore:rule3_matches(<happyroutermore:req>),
happyroutermore:ruleX_matches(<happyroutermore:req>);
SHOW REALIZED happyroutermore:rule1_matches(<happyroutermore:req>),
happyroutermore:rule2_matches(<happyroutermore:req>),
happyroutermore:rule3_matches(<happyroutermore:req>),
happyroutermore:ruleX_matches(<happyroutermore:req>)
FOR CASES happyroutermore:rule1_applies(<happyroutermore:req>),
happyroutermore:rule2_applies(<happyroutermore:req>),
happyroutermore:rule3_applies(<happyroutermore:req>),
happyroutermore:ruleX_applies(<happyroutermore:req>);
SHOW UNREALIZED happyroutermore:rule1_matches(<happyroutermore:req>),
happyroutermore:rule2_matches(<happyroutermore:req>),
happyroutermore:rule3_matches(<happyroutermore:req>),
happyroutermore:ruleX_matches(<happyroutermore:req>)
FOR CASES happyroutermore:rule1_applies(<happyroutermore:req>),
happyroutermore:rule2_applies(<happyroutermore:req>),
happyroutermore:rule3_applies(<happyroutermore:req>),
happyroutermore:ruleX_applies(<happyroutermore:req>);
// *** TUPLING ONLY
// Test: EDB in tupled INCLUDE ---> forces the EDB to be included if it doesn't appear in the query
EXPLORE happyroutermore:rulex_applies(<happyroutermore:req>) DEBUG 3
INCLUDE happyroutermore:rulex_applies(<happyroutermore:req>), udp(pro)
TUPLING;
SHOW ONE;
// *** TUPLING ONLY
// Test SHOW REALIZED with non-standard variable ordering:
// matches reverse packet when normal pkt is accepted?
// rules 1, 2, 3 apply: dest 10net --> src 10net. only X can match.
// rule X applies: there is still some room available to have 10network(ipdest), so 1,2,3 can all match
explore ipaddress(ipsrc) and ipaddress(ipdest)
UNDER happyroutermore
include happyroutermore:rule1_matches(ipdest, ipsrc, portdest, portsrc, pro),
happyroutermore:rule2_matches(ipdest, ipsrc, portdest, portsrc, pro),
happyroutermore:rule3_matches(ipdest, ipsrc, portdest, portsrc, pro),
happyroutermore:ruleX_matches(ipdest, ipsrc, portdest, portsrc, pro),
happyroutermore:rule1_applies(<happyroutermore:req>),
happyroutermore:rule2_applies(<happyroutermore:req>),
happyroutermore:rule3_applies(<happyroutermore:req>),
happyroutermore:ruleX_applies(<happyroutermore:req>)
TUPLING;
SHOW REALIZED happyroutermore:rule1_matches(ipdest, ipsrc, portdest, portsrc, pro),
happyroutermore:rule2_matches(ipdest, ipsrc, portdest, portsrc, pro),
happyroutermore:rule3_matches(ipdest, ipsrc, portdest, portsrc, pro),
happyroutermore:ruleX_matches(ipdest, ipsrc, portdest, portsrc, pro)
FOR CASES happyroutermore:rule1_applies(<happyroutermore:req>),
happyroutermore:rule2_applies(<happyroutermore:req>),
happyroutermore:rule3_applies(<happyroutermore:req>),
happyroutermore:ruleX_applies(<happyroutermore:req>);
// *******************************************************************
// *******************************************************************
// Test COMPARE keyword
// and comparing >2-decision policies
load policy "*MARGRAVE*/tests/phone2.p";
COMPARE phone1 phone2;
COMPARE phone1 phone2 CEILING 9;
INFO LAST; // should be the compare
IS POSSIBLE?;
EXPLORE last(src, dest) and outofservice(dest) or number(extravar)
PUBLISH src, dest, extravar CEILING 9;
INFO LAST;
IS POSSIBLE?; // true. and should see ceiling 11, not ceiling 9 (extravar and its exchange)
SHOW ONE;
// duplicate what compare does
EXPLORE
(Phone1:TollFree(ncaller, nreceive)
AND NOT Phone2:TollFree(ncaller, nreceive))
OR
(Phone2:TollFree(ncaller, nreceive)
AND NOT Phone1:TollFree(ncaller, nreceive))
OR
(Phone1:Toll(ncaller, nreceive)
AND NOT Phone2:Toll(ncaller, nreceive))
OR
(Phone2:Toll(ncaller, nreceive)
AND NOT Phone1:Toll(ncaller, nreceive))
OR
(Phone1:Refuse(ncaller, nreceive)
AND NOT Phone2:Refuse(ncaller, nreceive))
OR
(Phone2:Refuse(ncaller, nreceive)
AND NOT Phone1:Refuse(ncaller, nreceive)) CEILING 9;
IS POSSIBLE?;
// IOS loading
LOAD IOS "../examples/policies/ios-demo/initial/demo.txt" WITH "" "1";
LOAD IOS "*MARGRAVE*/examples/policies/ios-demo/change1/change1.txt" WITH "" "2";
// identical to demo.txt above, but in the local directory to test lack of path in the filename
LOAD IOS ios-local-file-load.txt WITH "" "3"; | false |
c8f611c11ab63d3d9cac3bd6e872bee9f4a2f061 | 37c451789020e90b642c74dfe19c462c170d9040 | /cap-3/solucao-3.07.rkt | 104dea2bc4b903367f92fe4b75731b5f3419d9fd | []
| no_license | hmuniz/LP-2016.2 | 11face097c3015968feea07c218c662dc015d1cf | 99dc28c6da572701dbfc885f672c2385c92988e7 | refs/heads/master | 2021-01-17T21:26:06.154594 | 2016-12-20T15:22:16 | 2016-12-20T15:22:16 | 71,069,658 | 1 | 0 | null | 2016-10-16T18:41:10 | 2016-10-16T18:41:09 | null | UTF-8 | Racket | false | false | 1,124 | rkt | solucao-3.07.rkt | #lang racket
(define (make-account balance password)
(define (correct-password? some-password password)
(if (pair? password)
(or (eq? some-password (car password))
(eq? some-password (cdr password)))
(eq? some-password password)))
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance
(- balance amount))
balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount))
balance)
(define (acc-joint-password new-p)
(set! password (cons password new-p)))
(define (dispatch some-password m)
(if (correct-password? some-password password)
(cond ((eq? m 'withdraw) withdraw)
((eq? m 'deposit) deposit)
((eq? m 'acc-joint-password) acc-joint-password)
(else (error "Unknown request:
MAKE-ACCOUNT" m)))
(error "Incorrect password")))
dispatch)
(define (make-joint account old-p new-p)
(begin
((account old-p 'acc-joint-password) new-p)
(lambda (some-password m)
(account some-password m))))
| false |
c9392f7a72bdcad209fcf8bf37164ef4841c1ac5 | d5b24cc43f13d84ccfccf7867ffdd90efb45f457 | /data/rooms/g_coal_chute.rkt | 2c2fccda54b21393a8e54cf5ab292686588886b7 | [
"MIT"
]
| permissive | jpverkamp/house-on-the-hill | ae86d46265636cacbc1fcf93e728daf24842da1d | af6dcad52dbeba25c8f376ba6ce2ec24c6f4362f | refs/heads/master | 2021-01-13T01:35:56.049740 | 2014-02-17T23:40:44 | 2014-02-17T23:40:44 | 8,725,181 | 6 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 1,583 | rkt | g_coal_chute.rkt | (define (slide-away! player tile)
(send player say "YOU FALL INTO THE BASEMENT!"))
(define-room
[name "coal chute"]
[description "a chute into the darkness, where could it lead?"]
[floors '(ground)]
[doors '(north)]
[floorplan
'(" \\.../ "
" |~| "
" |~| "
" |~| "
"__ \\ / __"
"~~\\ | /~~"
"~~~-O-~~~"
"__/ \\__"
" ")]
[tiles
(list
(define-tile
[tile "\\"]
[name "coal chute"]
[description "a chute directly into the basement"]
[walkable #t]
[on-walk slide-away!])
(define-tile
[tile "/"]
[name "coal chute"]
[description "a chute directly into the basement"]
[walkable #t]
[on-walk slide-away!])
(define-tile
[tile "~"]
[name "coal chute"]
[description "a chute directly into the basement"]
[walkable #t]
[on-walk slide-away!])
(define-tile
[tile "|"]
[name "coal chute"]
[description "a chute directly into the basement"]
[walkable #t]
[on-walk slide-away!])
(define-tile
[tile "-"]
[name "coal chute"]
[description "a chute directly into the basement"]
[walkable #t]
[on-walk slide-away!])
(define-tile
[tile "_"]
[name "coal chute"]
[description "a chute directly into the basement"]
[walkable #t]
[on-walk slide-away!])
(define-tile
[tile "O"]
[name "coal chute"]
[description "a chute directly into the basement"]
[walkable #t]
[on-walk slide-away!]))]) | false |
7b3dfedce555fbbe1612890615324c32ea5e0149 | bfdea13ca909b25a0a07c044ec456c00124b6053 | /mischief/parse.rkt | b7c1a7d1a91cc323f82e47b2efc6b671990598be | []
| no_license | carl-eastlund/mischief | 7598630e44e83dd477b7539b601d9e732a96ea81 | ce58c3170240f12297e2f98475f53c9514225825 | refs/heads/master | 2018-12-19T07:25:43.768476 | 2018-09-15T16:00:33 | 2018-09-15T16:00:33 | 9,098,458 | 7 | 2 | null | 2015-07-30T20:52:08 | 2013-03-29T13:02:31 | Racket | UTF-8 | Racket | false | false | 9,168 | rkt | parse.rkt | #lang racket/base
(provide
@
$
$!
syntax-matcher
syntax-matches?
syntax-class/c
syntax-parse/c
formals
kw-formals
for-clauses
for-body
block-body
self-quoting
datum-literal
literal
module-path
temp-id
bound-id
static-id
static-binding
struct-binding
struct-binding/known
struct-binding/check
define-literals/ids
require/define-literals/ids)
(require
(for-syntax
racket/base
racket/list
racket/match
racket/require-transform
racket/syntax
syntax/parse)
racket/contract
racket/function
racket/list
racket/bool
racket/syntax
racket/struct-info
syntax/parse
syntax/parse/experimental/specialize
syntax/parse/experimental/template
mischief/list
mischief/boolean
mischief/maybe
mischief/scope
(only-in srfi/1 list-index))
(define-syntax @
(make-rename-transformer #'attribute))
(define-syntax $
(make-rename-transformer #'template))
(define-syntax $!
(make-rename-transformer #'quote-syntax))
(define-syntax (syntax-class/c stx)
(syntax-parse stx
[(_ class:id)
#'(flat-named-contract '(syntax-class/c class)
(lambda (x)
(and (syntax? x)
(syntax-matches? x (~var _ class)))))]))
(define-syntax (syntax-parse/c stx)
(syntax-parse stx
[(_ pat ...)
#'(flat-named-contract '(syntax-parse/c pat ...)
(lambda (x)
(and (syntax? x)
(syntax-matches? x pat ...))))]))
(define-syntax (syntax-matcher stx)
(syntax-parse stx
[(_ pat ...)
#'(syntax-parser [pat #true] ... [_ #false])]))
(define-syntax (syntax-matches? stx)
(syntax-parse stx
[(_ e:expr pat ...)
#'(syntax-parse e [pat #true] ... [_ #false])]))
(define-syntax (define-literals/ids stx)
(syntax-parse stx
[(_ base-name:id opt ... [ref:id ...])
(define/syntax-parse literals-name
(format-id #'base-name "~a-literals" #'base-name))
(define/syntax-parse ids-name
(format-id #'base-name "~a-ids" #'base-name))
#'(begin
(define-literal-set literals-name opt ... [ref ...])
(define ids-name (list (quote-syntax/prune ref) ...)))]))
(define-syntax (require/define-literals/ids stx)
(syntax-parse stx
[(_ base-name:id require-spec)
(define-values [imports sources]
(expand-import #'require-spec))
(define phases
(map import-mode imports))
(define phase
(cond
[(empty? phases) 0]
[(empty? (rest phases)) (first phases)]
[else (let* {[p0 (first phases)]}
(for/first {[p (in-list (rest phases))]
#:unless (eqv? p p0)}
(raise-syntax-error #f
(format "conflicting phases in imports: ~v vs. ~v" p p0)
stx))
p0)]))
(define/syntax-parse [ref ...]
(map import-local-id imports))
#`(begin
(require require-spec)
(define-literals/ids base-name
#:phase #,phase
[ref ...]))]))
(define-syntax-class self-quoting
(pattern (~not (~or _:id _:keyword (_ . _)))))
(define-syntax-class formals
(pattern (arg-id:id ... . (~and rest (~or rest-id?:id ())))
#:attr [rest-id 1]
(cond
[(attribute rest-id?) => list]
[else empty])
#:attr [formal-id 1]
(syntax->list
#'[arg-id ... rest-id ...])
#:attr call
(cond
[(not (attribute rest-id?)) #'#%app]
[else #'apply])))
(define-syntax-class kw-formals
(pattern ((~or
req-id:id
[opt-id:id opt-expr:expr]
(~seq req-kw:keyword req-kw-id:id)
(~seq opt-kw:keyword [opt-kw-id:id opt-kw-expr:expr]))
...
. (~and rest (~or rest-id?:id ())))
#:attr [rest-id 1]
(cond
[(attribute rest-id?) => list]
[else empty])
#:attr [formal-id 1]
(syntax->list
#'[req-id ... req-kw-id ... opt-id ... opt-kw-id ... rest-id ...])
#:attr call
(cond
[(not (attribute rest-id?)) #'#%app]
[(and (empty? (attribute req-kw)) (empty? (attribute opt-kw)) #'apply)]
[else #'keyword-apply])))
(define-syntax-class for-clauses
#:attributes {}
(pattern {clause:for-clause ...}
#:fail-when
(check-duplicate-identifier (append* (@ clause.name)))
"duplicate identifier"))
(define-splicing-syntax-class for-clause
#:attributes {[name 1]}
(pattern [var:id _:expr] #:attr [name 1] (list (@ var)))
(pattern [(name:id ...) _:expr])
(pattern (~seq #:when _:expr) #:attr [name 1] '())
(pattern (~seq #:unless _:expr) #:attr [name 1] '())
(pattern _:break-clause #:attr [name 1] '()))
(define-splicing-syntax-class break-clause
(pattern (~seq #:break _:expr))
(pattern (~seq #:final _:expr)))
(define-syntax-class for-body
(pattern
((~and (~seq head ...)
(~seq (~or _:break-clause _:expr) ...))
tail:expr)))
(define-syntax-class block-body
(pattern (_:expr ...+)))
(define-syntax-class temp-id
#:attributes {temp}
(pattern x #:attr temp (generate-temporary #'x))
(pattern _ #:attr temp (generate-temporary)))
(define-syntax-class (datum-literal datum-pred datum-desc)
#:description datum-desc
#:attributes {value}
(pattern x
#:attr value (syntax->datum #'x)
#:when (datum-pred (attribute value))))
(define-syntax-class/specialize (literal v)
(datum-literal (lambda {x} (equal? x v)) (format "~s" v)))
(define-syntax-class/specialize module-path
(datum-literal module-path? "a module path"))
(define-syntax-class bound-id
#:description "a bound identifier"
#:attributes {}
(pattern x:id
#:fail-unless (identifier-binding #'x)
"expected a bound identifier, but found an unbound identifier"))
(define-syntax-class (static-binding static-pred static-desc)
#:description static-desc
#:attributes {value delta}
(pattern x
#:fail-unless (identifier? (@ x))
(format "expected ~a, but found ~a"
static-desc "a non-identifier")
#:fail-unless (identifier-binding (@ x))
(format "expected ~a, but found ~a"
static-desc "an unbound identifier")
#:do {(define maybe (scope-static-value (@ x) #:success yes #:failure no))}
#:fail-unless (yes? maybe)
(format "expected ~a, but found ~a"
static-desc "an identifier bound as a value")
#:attr value (yes-value maybe)
#:fail-unless (static-pred (attribute value))
(format "expected ~a, but found ~a"
static-desc
(format "an identifier bound as syntax to ~v"
(attribute value)))
#:attr delta
;; do not compute delta until we need it
(let* {[proc #false]
[scope (current-scope)]}
(lambda (stx)
(unless proc
(set! proc
(scope-delta-introducer (@ x)
#:scope scope)))
(proc stx)))))
(define-syntax-class/specialize static-id
(static-binding (const #true) "an identifier bound as syntax"))
(define-syntax-class (struct-binding/check
#:all [all #false]
#:descriptor [known-descriptor? all]
#:constructor [known-constructor? all]
#:predicate [known-predicate? all]
#:fields [known-accessors? all]
#:super [known-super? all]
#:mutable [known-mutators? #false])
#:attributes {value
descriptor-id
constructor-id
predicate-id
[accessor-id 1]
[mutator-id 1]
super-id
known-fields?}
(pattern (~var type (static-binding struct-info? "struct type name"))
#:do {(define info (extract-struct-info (attribute type.value)))}
#:attr value info
#:attr descriptor-id (first info)
#:attr constructor-id (second info)
#:attr predicate-id (third info)
#:attr [accessor-id 1] (reverse (take-while identifier? (fourth info)))
#:attr [mutator-id 1] (reverse (take (fifth info)
(length (attribute accessor-id))))
#:attr super-id (sixth info)
#:attr known-fields? (= (length (fourth info))
(length (attribute accessor-id)))
#:fail-unless (implies known-descriptor? (attribute descriptor-id))
"struct type descriptor name unknown"
#:fail-unless (implies known-constructor? (attribute constructor-id))
"struct constructor name unknown"
#:fail-unless (implies known-predicate? (attribute predicate-id))
"struct predicate name unknown"
#:fail-unless (implies (or known-accessors? known-mutators?)
(attribute known-fields?))
"struct may have unknown fields"
#:fail-unless (implies known-mutators?
(andmap identifier? (attribute mutator-id)))
(format "struct has missing or unknown mutator for field ~s"
(syntax-e
(list-ref (attribute accessor-id)
(list-index false? (attribute mutator-id)))))))
(define-syntax-class/specialize struct-binding
(struct-binding/check #:all #false))
(define-syntax-class/specialize struct-binding/known
(struct-binding/check #:all #true))
| true |
0d790106ff90abb1ee465278d01bed24513db12e | 174072a16ff2cb2cd60a91153376eec6fe98e9d2 | /2-2-4-racket/square-of-four.rkt | 9c7c9b7abc2a77284f1240f929b761f15a3bbd84 | []
| no_license | Wang-Yann/sicp | 0026d506ec192ac240c94a871e28ace7570b5196 | 245e48fc3ac7bfc00e586f4e928dd0d0c6c982ed | refs/heads/master | 2021-01-01T03:50:36.708313 | 2016-10-11T10:46:37 | 2016-10-11T10:46:37 | 57,060,897 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 578 | rkt | square-of-four.rkt | #lang scheme
(require (planet "sicp.ss" ("soegaard" "sicp.plt" 2 1)))
(require "2-2-4.rkt")
(define e einstein)
(define (square-of-four tl tr bl br)
(lambda (p) (let((top (beside (tl p) (tr p))) (bottom (beside (bl p) (br p))))
(below bottom top))))
(define indentity (lambda(x) x))
(define flipped-pairs ( square-of-four indentity flip-vert indentity flip-vert))
(define (square-limit p n) (let ((combine4 (square-of-four flip-horiz indentity rotate180 flip-vert)))
(combine4( corner-split p n))))
(paint (square-limit e 3)) | false |
9e6bda3288b8b8565e3e2e6996214de6b2982f48 | 2990b0841b63f300a722107933c01c7237a7976b | /all_xuef/程序员练级+Never/Fun_Projects/cs173-python/cs173-python-master/design3/cs173-python/python-interp.rkt | b3374dba2f4b1397d6c66055fc4f36cf4464c235 | []
| no_license | xuefengCrown/Files_01_xuef | 8ede04751689e0495e3691fc5d8682da4d382b4d | 677329b0189149cb07e7ba934612ad2b3e38ae35 | refs/heads/master | 2021-05-15T04:34:49.936001 | 2019-01-23T11:50:54 | 2019-01-23T11:50:54 | 118,802,861 | 1 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 17,956 | rkt | python-interp.rkt | #lang plai-typed
(require "python-core-syntax.rkt"
"python-monad.rkt"
"python-lib.rkt"
(typed-in racket/base
[display : (string -> void)]
[andmap : (('a -> boolean) (listof 'a) -> boolean)]))
;;note: interp and primitives need to be mutually recursive -- primops
;;need to lookup and apply underscore members (ie + calls __plus__),
;;and applying a function requires m-interp. Since racket doesn't
;;allow mutually recursive modules, I had to move python-primitives
;;into python-interp.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Primitives
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;note: primitive functions have type (listof CVal) -> (PM CVal)
;;they take in a list of vals because they may take in an arbitrary
;;number of values (think print). At some point, I will add in better
;;argument checking to prim functions, but at the moment, I just
;;assume they are correct
;;helper macro for (define-primf)
(define-syntax prim-bind
(syntax-rules (&)
[(prim-bind val (& (bind pred)) body)
(let ([bind val])
(if (pred bind)
body
(interp-error "primf given wrong argument type")))]
[(prim-bind val (& bind) body)
(let ([bind val])
body)]
[(prim-bind val ((bind pred) binds ...) body)
(let ([val-val val])
(if (empty? val-val)
(interp-error "primf not given enough arguments")
(let ([bind (first val-val)])
(if (pred bind)
(prim-bind (rest val-val) (binds ...) body)
(interp-error "primf given wrong argument type")))))]
[(prim-bind val (bind binds ...) body)
(let ([val-val val])
(if (empty? val-val)
(interp-error "primf not given enough arguments")
(let ([bind (first val-val)])
(prim-bind (rest val-val) (binds ...) body))))]
[(prim-bind val () body)
(if (empty? val)
body
(interp-error "primf given too many arguments"))]))
;;defines the racket version of a primf.
;;syntax: (define-primf (name . args) body)
;;args: (arg ... & rest)
;;arg (including rest): id or (id predicate)
;;notes: & rest is optional, bound to remaining arguments
;;actual racket function's type is ((listof CVal) -> (PM CVal))
;;if predicate is present, define-primf throws an error unless the
;;predicate returns true when applied to its associated arg
(define-syntax define-primf
(syntax-rules ()
[(define-primf (name . args) body)
(define (name (arg : (listof CVal))) : (PM CVal)
(prim-bind arg args body))]))
;;get the class of obj
(define-primf (class obj)
(type-case CVal obj
[VUndefined () (interp-error "local used before being set")]
[VNone () (get-global "none-type")]
[VTrue () (get-global "bool-type")]
[VFalse () (get-global "bool-type")]
[VNum (n) (get-global "num-type")]
[VStr (s) (get-global "str-type")]
[VBox (v) (interp-error "Boxes don't have a class")]
[VObj (dict class) (get-box (list class))]
[VPrimF (id) (get-global "func-type")]
[VPrimMap (m) (interp-error "prim maps don't have a class")]
[VClosure (e a v b) (get-global "func-type")]
[VTuple (l) (get-global "tuple-type")]))
;;get the dict out of obj
(define (dict (obj : CVal)) : (PM CVal)
(type-case CVal obj
[VObj (dict class) (get-box (list dict))]
[else (m-return (VNone))]))
;;get the super class of the class c (c's class must be type)
(define (super (c : CVal)) : (PM CVal)
(m-do ([c-c (class (list c))]
[class-type (get-global "class-type")]
[(if (eq? c-c class-type)
(pm-catch-error
(local-lookup c (VStr "__super__"))
(lambda (error)
(get-global "obj-type")))
(m-do ([c-s (pretty c)]
[(interp-error (string-append "isn't a class:"
c-s))])))])))
;;add a value to a prim dict (return the new dict)
(define (prim-dict-add (c-dict : CVal) (key : CVal) (val : CVal)) : (PM CVal)
(type-case CVal c-dict
[VPrimMap (m)
(m-return (VPrimMap (hash-set m key val)))]
[else (interp-error "prim-dict-add expects a prim-dict")]))
;;lookup a value in a prim dict
(define (prim-dict-lookup (c-dict : CVal) (key : CVal)) : (PM CVal)
(type-case CVal c-dict
[VPrimMap (m)
(type-case (optionof CVal) (hash-ref m key)
[some (v) (m-return v)]
[none () (interp-error
(string-append "key not found: "
(to-string key)))])]
[else (interp-error
(string-append "prim-dict-lookup wants a dict: "
(to-string key)))]))
;;lookup a value in an object (fails if there is no dict)
(define (local-lookup (obj : CVal) (key : CVal)) : (PM CVal)
(m-do ([c-dict (dict obj)]
[(prim-dict-lookup c-dict key)])))
;;takes an object in the first position and a key in the second
;;position, and returns true iff the object's class (or its
;;superclasses) contains key
(define-primf (class-has-member? & args)
(pm-catch-error (m-do ([(class-lookup args)])
(VTrue))
(lambda (x)
(m-return (VFalse)))))
;;takes an object in the first position and a key in the second
;;position, returns the value that the class has for key. Errors if
;;the key is not present in the class or its superclasses. Function
;;return values are curried with the object (so if the class contains
;;(lambda (this) this), the returned function is equivalent to (lamba ()
;;this), where this refers to the object. This sets up obj.method()
;;semantics properly
(define-primf (class-lookup object name)
(m-do
([obj-type (get-global "obj-type")]
[partial (get-global "partial-apply")]
[(local [(define (iter c)
(m-do ([c-dict (dict c)]
[(pm-catch-error
(local-lookup c name)
(lambda (error)
(if (eq? c obj-type)
(pm-error error)
(m-bind (super c)
iter))))])))]
(m-do ([c (class (list object))]
[res (iter c)]
[(if (or (VClosure? res)
(VPrimF? res))
(apply-func partial
(list res object)
(VTuple empty))
(m-return res))])))])))
;;take an object in the first position and a key in the second
;;position. looks the key up in the objects dict first, and in the
;;objects class second (if the key isn't in the dict)
(define-primf (obj-lookup obj name)
(cond
[(equal? name (VStr "__dict__")) (dict obj)]
[(equal? name (VStr "__class__")) (class (list obj))]
[else (pm-catch-error
(local-lookup obj name)
(lambda (error)
(class-lookup (list obj name))))]))
;;will be replaced by a to-string method in classes
(define (pretty arg)
(type-case CVal arg
[VNum (n) (m-return (to-string n))]
[VNone () (m-return "None")]
[VStr (s) (m-return s)]
[VTuple (l) (m-do ([vals (m-map pretty l)]
[rvals (m-return (reverse vals))])
(cond
[(empty? rvals) "()"]
[(empty? (rest rvals))
(string-append "("
(string-append (first rvals)
",)"))]
[else (string-append
"("
(string-append
(foldl (lambda (c t)
(string-append c
(string-append ", "
t)))
(first rvals)
(rest rvals))
")"))]))]
[VObj (c dict)
(m-do ([c (get-box (list c))]
[c-s (pretty c)]
[dict (get-box (list dict))]
[dict-s (pretty dict)])
(string-append "(obj "
(string-append c-s
(string-append " "
(string-append dict-s
")")))))]
[else (m-return (to-string arg))]))
;;gets the global variable dict
(define get-globals
(pm-lookup-store -2))
;;sets the global variable dict
(define (set-globals (v : CVal))
(type-case CVal v
[VPrimMap (m) (pm-add-store -2 v)]
[else (interp-error "globals must be a prim dict")]))
;;gets a particular global from the global varaible dict
(define (get-global (arg : string))
(m-do ([d get-globals]
[(prim-dict-lookup d (VStr arg))])))
;;adds a global variable and its value to the global variable dict
(define (add-global (name : string) (val : CVal))
(m-do ([d get-globals]
[new-d (prim-dict-add d (VStr name) val)]
[(set-globals new-d)])))
;;prints the args, separated by spaces, followed by a newline
(define-primf (print val & rest)
(m-do ([prettied (pretty val)]
[(m-return (display prettied))]
[(if (empty? rest)
(begin (display "\n")
(m-return (VNone)))
(begin (display " ")
(print rest)))])))
;;checks whether the 2 arguments are equal
(define-primf (equal left right)
(if (equal? left
right)
(m-return (VTrue))
(m-return (VFalse))))
;;numeric addition
(define-primf (add left right)
(m-return (VNum
(+ (VNum-n left)
(VNum-n right)))))
;;numeric subtraction
(define-primf (sub left right)
(m-return (VNum
(- (VNum-n left)
(VNum-n right)))))
;;numeric negation
(define-primf (neg arg)
(m-return (VNum (- 0 (VNum-n arg)))))
;;gets a value from a box
(define-primf (get-box (box VBox?))
(pm-lookup-store (VBox-v box)))
;;sets the value inside a box
(define-primf (set-box (box VBox?) val)
(m-do ([(pm-add-store (VBox-v box) val)])
val))
;;appends n tuples
(define-primf (tuple-append & (args (lambda (args) (andmap VTuple? args))))
(m-return
(VTuple
(foldr (lambda (t l)
(append (VTuple-l t)
l))
empty
args))))
;;finds the length of a tuple
(define-primf (tuple-length (t VTuple?))
(m-return (VNum (length (VTuple-l t)))))
;;finds the appropriate racket function for a given VPrimF symbol
(define (python-prim op) : ((listof CVal) -> (PM CVal))
(case op
[(print) print]
[(equal) equal]
[(int-add) add]
[(int-sub) sub]
[(int-neg) neg]
[(get-box) get-box]
[(set-box) set-box]
[(class-has-member?) class-has-member?]
[(class-lookup) class-lookup]
[(tuple-append) tuple-append]
[(tuple-length) tuple-length]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; interp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;returns the first n elements in lst
(define (take n lst)
(cond
[(or (empty? lst)
(= n 0)) empty]
[else (cons (first lst)
(take (- n 1)
(rest lst)))]))
;;returns lst without the first n elements
(define (drop n lst)
(cond [(empty? lst) empty]
[(= n 0) lst]
[else (drop (- n 1) (rest lst))]))
;;applies funct to args and varargs
(define (apply-func (func : CVal) (args : (listof CVal)) (varargs : CVal)) : (PM CVal)
(let ([args (append args
(VTuple-l varargs))])
(type-case CVal func
[VClosure
(c-env off-args off-vararg body)
(let ([named-args (take (length off-args) args)]
[varargs (drop (length off-args) args)])
(if (or (< (length args)
(length off-args))
(and (not (empty? varargs))
(none? off-vararg)))
(interp-error
(string-append "Application failed with arity mismatch\nfunction: "
(string-append (to-string func)
(string-append "\nargs: "
(to-string args)))))
(m-do ([new-env
(m-foldl
(lambda (pair env)
(local [(define-values (name val) pair)]
(m-do ([loc (add-new-loc val)])
(hash-set env name loc))))
(type-case (optionof symbol) off-vararg
[none () (m-return c-env)]
[some (name)
(m-do ([loc (add-new-loc (VTuple varargs))])
(hash-set c-env name loc))])
(map2 (lambda (x y)
(values x y))
off-args named-args))]
[(pm-catch-return (m-do ([(m-interp body
new-env)])
(VNone))
m-return)]))))]
[VPrimF (id) ((python-prim id) args)]
[else (interp-error (string-append "Applied a non-function: "
(to-string func)))])))
(define (m-interp expr env) : (PM CVal)
(type-case CExp expr
[CUndefined () (m-return (VUndefined))]
[CNone () (m-return (VNone))]
[CTrue () (m-return (VTrue))]
[CFalse () (m-return (VFalse))]
[CNum (n) (m-return (VNum n))]
[CStr (s) (m-return (VStr s))]
[CBox (v) (m-do ([val (m-interp v env)]
[loc (add-new-loc val)])
(VBox loc))]
[CObj (d c)
(m-do ([dict (m-interp d env)]
[class (m-interp c env)])
(VObj dict class))]
[CPrimMap (vals)
(m-do ([contents
(m-map (lambda (pair)
(local [(define-values (key val) pair)]
(m-do ([key (m-interp key env)]
[val (m-interp val env)])
(values key val))))
vals)])
(VPrimMap
(hash contents)))]
[CTuple (l)
(m-do ([contents (m-map (lambda (v)
(m-interp v env))
l)])
(VTuple contents))]
[CId (x)
(type-case (optionof Location) (hash-ref env x)
[some (l)
(m-do ([store pm-get-store]
[(let ([v (type-case (optionof CVal) (hash-ref store l)
[some (v) v]
[none () (error 'interp
(string-append
"can't find loc for var: "
(to-string x)))])])
(if (VUndefined? v)
(interp-error (string-append "local used before it was defined: "
(to-string x)))
(m-return v)))]))]
[none () (interp-error (string-append "Unbound identifier: "
(to-string x)))])]
[CSet! (id v)
(m-do ([v (m-interp v env)]
[(type-case (optionof Location) (hash-ref env id)
[some (l) (pm-add-store l v)]
[none () (error 'interp (string-append "variable never bound:"
(to-string id)))])]))]
[CLet (x bind body)
(m-do ([val (m-interp bind env)]
[loc (add-new-loc val)]
[(m-interp body (hash-set env x loc))]))]
[CAddGlobal (id bind)
(m-do ([bind (m-interp bind env)]
[(add-global (symbol->string id) bind)])
bind)]
[CSeq (e1 e2)
(m-do ([(m-interp e1 env)]
[(m-interp e2 env)]))]
[CFunc (args vararg body)
(m-return (VClosure env args vararg body))]
[CApp (func args varargs)
(m-do ([func (m-interp func env)]
[args (m-map (lambda (arg) (m-interp arg env)) args)]
[varargs (m-interp varargs env)]
[(apply-func func args varargs)]))]
[CReturn (v)
(m-do ([v (m-interp v env)]
[(pm-return v)]))]
[CPrimF (id) (m-return (VPrimF id))]
[CIf (test t e)
(m-do ([test-v (m-interp test env)]
[(if (equal? test-v (VFalse))
(m-interp e env)
(m-interp t env))]))]
[CError (val)
(m-bind (m-interp val env) pm-error)]
;;[else (error 'm-interp (string-append "not implemented: "
;; (to-string expr)))]
))
(define (interp expr)
(local [(define-values (store res)
((m-interp expr (hash (list)))
empty-store))]
(type-case (ROption CVal) res
[RValue (v) v]
[RReturn (v) (error 'interp "returned when not in function context")]
[RError (v) (error 'interp (to-string v))])))
| true |
2e50f8e9a11f617ec4489a8814872fa79fb37c62 | 662e55de9b4213323395102bd50fb22b30eaf957 | /dissertation/QA/math-test/advent-2015-06/natural/main.rkt | 47e75ad9f711a548fdd7b623cb65a00fe627e6bb | []
| no_license | bennn/dissertation | 3000f2e6e34cc208ee0a5cb47715c93a645eba11 | 779bfe6f8fee19092849b7e2cfc476df33e9357b | refs/heads/master | 2023-03-01T11:28:29.151909 | 2021-02-11T19:52:37 | 2021-02-11T19:52:37 | 267,969,820 | 7 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 1,825 | rkt | main.rkt | #lang racket
(require math/array)
(module+ test (require rackunit))
(define w 1000)
(define h 1000)
(define (make-grid)
(array->mutable-array
(make-array (vector w h) 0)))
(define (count-lit g)
(for*/sum ((xy (in-array g)))
xy))
(struct command [f x0 y0 x1 y1] #:transparent)
(define (toggle v)
(if (= v 1) 0 1))
(define (off v)
0)
(define (on v)
1)
(define (add2 v)
(+ v 2))
(define (nat-sub1 v)
(if (= v 0) 0 (sub1 v)))
(define (parse-command str [part2? #f])
(match (regexp-match #rx"^(.*) ([0-9]+),([0-9]+) through ([0-9]+),([0-9]+)$" str)
((list _m cmd x0 y0 x1 y1)
(command (str->f cmd part2?) (string->number x0) (string->number y0) (string->number x1) (string->number y1)))
(_
(raise-user-error 'parse-command "command-string?" str))))
(define (str->f str part2?)
(match str
("toggle" (if part2? add2 toggle))
("turn on" (if part2? add1 on))
("turn off" (if part2? nat-sub1 off))
(_ (raise-user-error 'str->f "f-string?" str))))
(define (do-command! g cmd)
(define f (command-f cmd))
(for* ((x (in-range (command-x0 cmd) (+ 1 (command-x1 cmd))))
(y (in-range (command-y0 cmd) (+ 1 (command-y1 cmd)))))
(define v (vector x y))
(array-set! g v (f (array-ref g v)))))
(define (part1 input)
(define g (make-grid))
(with-input-from-file
input
(lambda ()
(for ((ln (in-lines)))
(do-command! g (parse-command ln)))))
(count-lit g))
(define (part2 input)
(define g (make-grid))
(with-input-from-file
input
(lambda ()
(for ((ln (in-lines)))
(do-command! g (parse-command ln #true)))))
(count-lit g))
(define input (map parse-command (file->lines "input")))
(define (main input)
(part1 input)
(part2 input)
(void))
(time
;; 400410
;; 15343601
(main "input"))
| false |
9341d67d6abd618c668002c6668535d0a0e48b0e | a8338c4a3d746da01ef64ab427c53cc496bdb701 | /drbayes/tests/bool-set-tests.rkt | 024d412572ac59574f2564a05359782e673d43e8 | []
| no_license | ntoronto/plt-stuff | 83c9c4c7405a127bb67b468e04c5773d800d8714 | 47713ab4c16199c261da6ddb88b005222ff6a6c7 | refs/heads/master | 2016-09-06T05:40:51.069410 | 2013-10-02T22:48:47 | 2013-10-02T22:48:47 | 1,282,564 | 4 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 541 | rkt | bool-set-tests.rkt | #lang typed/racket
(require "../private/set/bool-set.rkt"
"rackunit-utils.rkt"
"random-bool-set.rkt")
(printf "starting...~n")
(time
(for: ([_ (in-range 100000)])
(check-set-algebra
eq?
bool-set-member?
bool-set-subseteq?
empty-bool-set
bools
bool-set-subtract
bool-set-union
bool-set-intersect
random-bool-set
random-bool)
(check-bounded-lattice
eq?
bool-set-subseteq?
bool-set-union
bool-set-intersect
empty-bool-set
bools
random-bool-set)))
| false |
fda86c3b145683f6372034f6a899ef16a26673c5 | fc78b0f13aede8f52d5d5dd5d8a9005e4b713aaa | /old.rkt | 68fab8f3825c0e45596652fb6b06a2061b64f1fc | [
"MIT"
]
| permissive | bqv/Symmetry | 1f25752c30cb7369cf4ec1d39f49c281eb7d17be | 0cac0bcb0573dc07c05a44100f921114fb726902 | refs/heads/master | 2020-04-10T22:44:57.019863 | 2015-12-21T00:20:48 | 2015-12-21T00:20:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,419 | rkt | old.rkt | #lang racket
(require racket/tcp)
(define-values (in out) (tcp-connect "irc.subluminal.net" 6667))
;(define-values (in out) (tcp-connect "192.168.1.65" 4444))
(define-syntax-rule (debug str ...)
(let ()
(displayln (string-append "-> " str ...))
(displayln (string-append str ...) out)))
(define connected #t)
(define welcome #f)
(define autojoin "#programming")
(define-syntax-rule (put str num)
(let ()
(namespace-set-variable-value! (string->symbol (substring str 1)) num)
num))
(define-syntax-rule (get str)
(with-handlers ([exn:fail:contract:variable?
(lambda (e) (put str 0))])
(namespace-variable-value (string->symbol (substring str 1)))))
(debug "USER symmetry * * *")
(debug "NICK it")
(debug "PASS him/awfulnot:him")
(flush-output out)
(define (weigh-line str)
(for/sum ([i (map (lambda (c)
(if (or (equal? c #\() (equal? c #\[)) +1 (if (or (equal? c #\)) (equal? c #\])) -1 0)))
(string->list str))]) i))
(let loop ()
(when connected
(let ([line (read-line in)])
(when (eof-object? line)
(displayln "Server hungup...")
(set! connected #f))
(displayln line)
(when (not (equal? line ""))
(let ([line (string-split line)])
(when (equal? (car line) "PING")
(debug "PONG " (cadr line)))
(when (not welcome)
(when (equal? (cadr line) "001")
(set! welcome #t)
(debug "JOIN " autojoin)))
(when (equal? (cadr line) "JOIN")
(displayln (get (caddr line))))
(when (equal? (cadr line) "PRIVMSG")
(let ([text (string-downcase (substring (string-join (cdddr line)) 1))])
(displayln (string-append "<- " text ))
(if (regexp-match #rx" *@symmetry *" text)
(debug "PRIVMSG " (caddr line) " :" (number->string (get (caddr line))))
(put (caddr line) (+ (weigh-line (substring (cadddr line) 1)) (get (caddr line)))))
(when (regexp-match #rx" *@rebalance *" text)
(put (caddr line) 0))))
(when (equal? (cadr line) "INVITE")
(let ([text (string-downcase (substring (string-join (cdddr line)) 1))])
(displayln (string-append "[INV] " text ))
(debug "JOIN " text))))
(flush-output out)))
(loop)))
| true |
4db5e0d85e2ecfae4665675a285cba845d46cb76 | b98c135aff9096de1311926c2f4f401be7722ca1 | /sgml/digitama/relaxng/recognizer.rkt | bfa74fee2ec4071b359df446fb25f8008c897753 | []
| no_license | wargrey/w3s | 944d34201c16222abf51a7cf759dfed11b7acc50 | e5622ad2ca6ec675fa324d22dd61b7242767fb53 | refs/heads/master | 2023-08-17T10:26:19.335195 | 2023-08-09T14:17:45 | 2023-08-09T14:17:45 | 75,537,036 | 3 | 1 | null | 2022-02-12T10:59:27 | 2016-12-04T12:49:33 | Racket | UTF-8 | Racket | false | false | 22,203 | rkt | recognizer.rkt | #lang typed/racket
;;; Parser Combinators and Syntax Sugars of parsing the compact syntax of RelaxNG
;;; This is ported from w3s/css by removing unused APIs
(provide (all-defined-out))
(require "../digicore.rkt")
(require "../namespace.rkt")
(require css/digitama/syntax/misc)
(require racket/string)
(require digimon/symbol)
(require (for-syntax syntax/parse))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-syntax (define-rnc-disjoint-filter stx)
(syntax-case stx [:]
[(_ compound-filter #:-> RangeType #:with [[dom : DomType defval ...] ...] atom-filters ...)
(syntax/loc stx (define (compound-filter [dom : DomType defval ...] ...) : (XML:Filter RangeType) (RNC:<+> atom-filters ...)))]
[(_ compound-filter #:-> RangeType atom-filters ...)
(syntax/loc stx (define (compound-filter) : (XML:Filter RangeType) (RNC:<+> atom-filters ...)))]))
(define-syntax (define-rnc-atomic-filter stx)
(syntax-parse stx #:datum-literals [:]
[(_ atom-filter #:-> RangeType #:with [[token : token?] [dom : DomType defval ...] ...]
(~optional (~seq #:on-error make-exn) #:defaults ([make-exn #'#false]))
atom-body ...
#:where [defaux ...])
(syntax/loc stx
(define (atom-filter [dom : DomType defval ...] ...) : (XML:Filter RangeType) defaux ...
(λ [[token : XML-Syntax-Any]] : (XML-Option RangeType)
(cond [(token? token) atom-body ...]
[else (and make-exn (make-exn token))]))))]
[(defilter atom-filter #:-> RangeType #:with [[token : token?] [dom : DomType defval ...] ...] atom-body ...)
(syntax/loc stx (defilter atom-filter #:-> RangeType #:with [[token : token?] [dom : DomType defval ...] ...] atom-body ... #:where []))]))
(define-syntax (RNC<?> stx)
(syntax-parse stx #:datum-literals [else]
[(_) #'values]
[(_ [else <else> ...]) (syntax/loc stx (RNC<&> <else> ...))]
[(_ [<if> <then> ...]) (syntax/loc stx (rnc:if <if> (RNC<&> <then> ...) #false))]
[(_ [<if> <then> ...] [else <else> ...]) (syntax/loc stx (rnc:if <if> (RNC<&> <then> ...) (RNC<&> <else> ...)))]
[(_ [<if> <then> ...] ... [else <else> ...]) (syntax/loc stx (rnc:if (list (cons <if> (RNC<&> <then> ...)) ...) (RNC<&> <else> ...)))]
[(_ [<if> <then> ...] ...) (syntax/loc stx (rnc:if (list (cons <if> (RNC<&> <then> ...)) ...) #false))]))
(define-syntax (RNC:<+> stx)
(syntax-case stx []
[(_ rnc-filter) #'rnc-filter]
[(_ rnc-filter rnc-filters ...) (syntax/loc stx (rnc:disjoin rnc-filter (RNC:<+> rnc-filters ...)))]))
(define-syntax (RNC<+> stx)
(syntax-case stx []
[(_) #'values]
[(_ #:any rnc-parser rnc-parsers ...) (syntax/loc stx (rnc-disjoin (list rnc-parser rnc-parsers ...)))]
[(_ rnc-parser) #'rnc-parser]
[(_ rnc-parser rnc-parsers ...) (syntax/loc stx (rnc-disjoin rnc-parser (RNC<+> rnc-parsers ...)))]))
(define-syntax (RNC<&> stx)
(syntax-case stx []
[(_) #'values]
[(_ #:any rnc-parser rnc-parsers ...) (syntax/loc stx (rnc-juxtapose (list rnc-parser rnc-parsers ...)))]
[(_ rnc-parser) #'rnc-parser]
[(_ rnc-parser rnc-parsers ...) (syntax/loc stx (rnc-juxtapose rnc-parser (RNC<&> rnc-parsers ...)))]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define RNC:<=> : (All (a) (-> (XML:Filter Any) a (XML:Filter a)))
(lambda [rnc-filter const]
(λ [[token : XML-Syntax-Any]]
(define datum : (XML-Option Any) (rnc-filter token))
(if (exn:xml? datum) datum (and datum const)))))
(define RNC:<^> : (All (a) (-> (U (XML:Filter a) (Listof+ (XML:Filter a))) (XML-Parser (Listof a))))
(case-lambda
[(atom-filter)
(if (pair? atom-filter)
(apply RNC:<&> atom-filter)
(RNC:<&> atom-filter))]))
(define RNC:<_> : (All (a) (-> (XML:Filter Any) (XML-Parser a)))
(lambda [atom-filter]
(λ [[data : a] [tokens : (Listof XML-Token)]]
(define-values (head tail) (rnc-car/cdr tokens))
(define datum : (XML-Option Any) (atom-filter head))
(cond [(or (exn:xml? datum) (not datum)) (values datum tokens)]
[else (values data tail)]))))
(define RNC:<~> : (All (a b) (case-> [(XML:Filter a) (-> a b) -> (XML:Filter b)]
[(XML:Filter a) (-> a b) (-> b XML-Syntax-Any (XML-Option True)) -> (XML:Filter b)]))
(case-lambda
[(rnc-filter xml->racket)
(λ [[token : XML-Syntax-Any]]
(define datum : (XML-Option a) (rnc-filter token))
(if (exn:xml? datum) datum (and datum (xml->racket datum))))]
[(rnc-filter xml->racket datum-guard)
(λ [[token : XML-Syntax-Any]]
(define datum : (XML-Option a) (rnc-filter token))
(cond [(or (not datum) (exn:xml? datum)) datum]
[else (let* ([rdatum (xml->racket datum)]
[okay? (datum-guard rdatum token)])
(cond [(or (not okay?) (exn:xml? okay?)) okay?]
[else rdatum]))]))]))
(define RNC:<&> : (All (a) (-> (XML:Filter a) * (XML-Parser (Listof a))))
;;; https://drafts.csswg.org/css-values-4/#component-combinators [juxtaposing components]
(case-lambda
[() values]
[(atom-filter)
(λ [[data : (Listof a)] [tokens : (Listof XML-Token)]]
(define-values (head tail) (rnc-car/cdr tokens))
(define datum : (XML-Option a) (atom-filter head))
(cond [(or (not datum) (exn:xml? datum)) (values datum tokens)]
[else (values (cons datum data) tail)]))]
[atom-filters
(λ [[data : (Listof a)] [tokens : (Listof XML-Token)]]
(let juxtapose ([data++ : (Listof a) data]
[tokens-- : (Listof XML-Token) tokens]
[filters : (Listof (XML:Filter a)) atom-filters])
(cond [(null? filters) (values data++ tokens--)]
[else (let ([rnc-filter (car filters)])
(define-values (token --tokens) (rnc-car/cdr tokens--))
(define datum : (XML-Option a) (rnc-filter token))
(cond [(or (not datum) (exn:xml? datum)) (values datum tokens--)]
[else (juxtapose (cons datum data++) --tokens (cdr filters))]))])))]))
(define RNC:<*> : (All (a) (->* ((XML:Filter a)) ((U (XML-Multiplier Index) '+ '? '*)) (XML-Parser (Listof a))))
;;; https://drafts.csswg.org/css-values/#mult-zero-plus
(lambda [atom-filter [multiplier '*]]
(define-values (least most) (rnc:multiplier-range multiplier 0))
(cond [(zero? most) values]
[else (λ [[data : (Listof a)] [tokens : (Listof XML-Token)]]
(let mult-0+ ([data++ : (Listof a) data]
[tokens-- : (Listof XML-Token) tokens]
[n+1 : Natural 1])
(define-values (token --tokens) (rnc-car/cdr tokens--))
(define datum : (XML-Option a) (atom-filter token))
(cond [(or (not datum) (exn:xml? datum)) (values (if (< least n+1) data++ datum) tokens--)]
[(= n+1 most) (values (cons datum data++) --tokens)] ; (= n +inf.0) also does not make much sense
[else (mult-0+ (cons datum data++) --tokens (add1 n+1))])))])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define RNC<~> : (All (a b) (case-> [(XML-Parser (Listof a)) (-> (Listof a) b) -> (XML-Parser (Listof b))]
[(XML-Parser (Listof a)) (-> (Listof a) b) (-> (Listof b) b (Listof XML-Token) (XML-Option True)) -> (XML-Parser (Listof b))]))
(case-lambda
[(rnc-parser rnc->racket)
(λ [[data : (Listof b)] [tokens : (Listof XML-Token)]]
(define-values (datum --tokens) (rnc-parser null tokens))
(cond [(or (exn:xml? datum) (false? datum)) (values datum --tokens)]
[else (values (cons (rnc->racket (reverse datum)) data) --tokens)]))]
[(rnc-parser rnc->racket data-guard)
(λ [[data : (Listof b)] [tokens : (Listof XML-Token)]]
(define-values (datum --tokens) (rnc-parser null tokens))
(cond [(or (exn:xml? datum) (false? datum)) (values datum --tokens)]
[else (let* ([rdatum (rnc->racket (reverse datum))]
[okay? (data-guard data rdatum (if (eq? tokens --tokens) null (drop-right tokens (length --tokens))))])
(cond [(or (not okay?) (exn:xml? okay?)) (values okay? tokens)]
[else (values (cons rdatum data) --tokens)]))]))]))
(define RNC<_> : (All (a) (-> (XML-Parser (Listof Any)) (XML-Parser a)))
(lambda [rnc-parser]
(λ [[data : a] [tokens : (Listof XML-Token)]]
(define-values (++data --tokens) (rnc-parser null tokens))
(cond [(or (exn:xml? ++data) (not ++data)) (values ++data --tokens)]
[else (values data --tokens)]))))
(define RNC<*> : (All (a) (->* ((XML-Parser a)) ((U (XML-Multiplier Index) '+ '? '*)) (XML-Parser a)))
;;; https://drafts.csswg.org/css-values/#mult-zero-plus
(lambda [rnc-parser [multiplier '*]]
(define-values (least most) (rnc:multiplier-range multiplier 0))
(cond [(zero? most) values]
[else (λ [[data : a] [tokens : (Listof XML-Token)]]
(let mult-0+ ([data++ : a data]
[tokens-- : (Listof XML-Token) tokens]
[n+1 : Natural 1])
(define-values (++data --tokens) (rnc-parser data++ tokens--))
(cond [(or (not ++data) (exn:xml? ++data)) (if (< least n+1) (values data++ tokens--) (values ++data --tokens))]
[(= n+1 most) (values ++data --tokens)] ; (= n +inf.0) also does not make much sense
[else (mult-0+ ++data --tokens (add1 n+1))])))])))
(define RNC<λ> : (All (a b) (case-> [(-> (XML-Parser (Listof a))) -> (XML-Parser (Listof a))]
[(-> b (XML-Parser (Listof a))) b -> (XML-Parser (Listof a))]))
(case-lambda
[(rnc-parser)
(λ [[data : (Listof a)] [tokens : (Listof XML-Token)]]
((rnc-parser) data tokens))]
[(rnc-parser argc)
(λ [[data : (Listof a)] [tokens : (Listof XML-Token)]]
((rnc-parser argc) data tokens))]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define rnc:disjoin : (All (a b c) (case-> [(XML:Filter a) (XML:Filter b) -> (XML:Filter (U a b))]))
(case-lambda
[(rnc-filter1 rnc-filter2)
(λ [[token : XML-Syntax-Any]]
(define datum : (XML-Option a) (rnc-filter1 token))
(cond [(nor (not datum) (exn:xml? datum)) datum]
[else (rnc-filter2 token)]))]))
(define rnc-disjoin : (All (a b) (case-> [(Listof (XML-Parser a)) -> (XML-Parser a)]
[(XML-Parser (Listof a)) (XML-Parser (Listof b)) -> (XML-Parser (Listof (U a b)))]))
;;; https://drafts.csswg.org/css-values/#comb-one
(case-lambda
[(atom-parsers)
(cond [(null? atom-parsers) values]
[(null? (cdr atom-parsers)) (car atom-parsers)]
[else (λ [[data : a] [tokens : (Listof XML-Token)]]
(let combine-one ([head-parser : (XML-Parser a) (car atom-parsers)]
[tail-parsers : (Listof (XML-Parser a)) (cdr atom-parsers)])
(define-values (++data --tokens) (head-parser data tokens))
(cond [(nor (not ++data) (exn:xml? ++data)) (values ++data --tokens)]
[(pair? tail-parsers) (combine-one (car tail-parsers) (cdr tail-parsers))]
[else (values ++data --tokens)])))])]
[(atom-parser1 atom-parser2)
(λ [[data : (Listof (U a b))] [tokens : (Listof XML-Token)]]
(define-values (datum --tokens) (atom-parser1 null tokens))
(cond [(nor (not datum) (exn:xml? datum)) (values (append datum data) --tokens)]
[else (let-values ([(datum --tokens) (atom-parser2 null tokens)])
(cond [(or (not datum) (exn:xml? datum)) (values datum --tokens)]
[else (values (append datum data) --tokens)]))]))]))
(define rnc-juxtapose : (All (a b) (case-> [(Listof (XML-Parser a)) -> (XML-Parser a)]
[(XML-Parser (Listof a)) (XML-Parser (Listof b)) -> (XML-Parser (Listof (U a b)))]))
;;; https://drafts.csswg.org/css-values-4/#component-combinators [juxtaposing components]
(case-lambda
[(atom-parsers)
(λ [[data : a] [tokens : (Listof XML-Token)]]
(let combine-all ([data++ : a data]
[tokens-- : (Listof XML-Token) tokens]
[parsers : (Listof (XML-Parser a)) atom-parsers])
(cond [(null? parsers) (values data++ tokens--)]
[else (let-values ([(++data --tokens) ((car parsers) data++ tokens--)])
(cond [(or (not ++data) (exn:xml? ++data)) (values ++data --tokens)]
[else (combine-all ++data --tokens (cdr parsers))]))])))]
[(atom-parser1 atom-parser2)
(λ [[data : (Listof (U a b))] [tokens : (Listof XML-Token)]]
(define-values (datum1 --tokens) (atom-parser1 null tokens))
(cond [(or (not datum1) (exn:xml? datum1)) (values datum1 --tokens)]
[else (let-values ([(datum2 ----tokens) (atom-parser2 null --tokens)])
(cond [(or (not datum2) (exn:xml? datum2)) (values datum2 ----tokens)]
[else (values (append datum2 datum1 data) ----tokens)]))]))]))
(define rnc:if : (All (a) (case-> [(Listof+ (Pairof (XML:Filter Any) (XML-Parser a))) (Option (XML-Parser a)) -> (XML-Parser a)]
[(XML:Filter Any) (XML-Parser a) (Option (XML-Parser a)) -> (XML-Parser a)]))
(case-lambda
[(cond-parsers else-parser)
(λ [[data : a] [tokens : (Listof XML-Token)]]
(let else-if ([branch (car cond-parsers)]
[branches-- (cdr cond-parsers)])
(define-values (if:filter then-parser) (values (car branch) (cdr branch)))
(define-values (token --tokens) (rnc-car/cdr tokens))
(define if:datum : (XML-Option Any) (if:filter token))
(cond [(nor (not if:datum) (exn:xml? if:datum)) (then-parser data --tokens)]
[(pair? branches--) (else-if (car branches--) (cdr branches--))]
[(not else-parser) (values if:datum --tokens)]
[else (else-parser data tokens)])))]
[(if:filter then-parser else-parser)
(λ [[data : a] [tokens : (Listof XML-Token)]]
(define-values (token --tokens) (rnc-car/cdr tokens))
(define if:datum : (XML-Option Any) (if:filter token))
(cond [(nor (not if:datum) (exn:xml? if:datum)) (then-parser data --tokens)]
[(not else-parser) (values if:datum --tokens)]
[else (else-parser data tokens)]))]))
(define rnc:multiplier-range : (-> (U (XML-Multiplier Index) '+ '? '*) Index (Values Natural (U Natural +inf.0)))
(lambda [multiplier least]
(case multiplier
[(?) (values 0 1)]
[(*) (values 0 +inf.0)]
[(+) (values 1 +inf.0)]
[else (cond [(index? multiplier) (values (max multiplier least) (max multiplier least))]
[else (let ([n (let ([n (car multiplier)]) (if (index? n) (max n least) least))])
(define m : (U Index Symbol Null) (cdr multiplier))
(cond [(index? m) (values n (max n m))]
[(symbol? m) (values n +inf.0)]
[else (values n n)]))])])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-rnc-atomic-filter <rnc:assign> #:-> Char #:with [[token : xml:eq?]] #:on-error make-exn:rnc:missing-delim #\=)
(define #:forall (a) (<:=:>) : (XML-Parser a) ((inst RNC<_> a) (RNC:<^> (<rnc:assign>))))
(define #:forall (a) (<:~:>) : (XML-Parser a) ((inst RNC<_> a) (RNC:<^> (<xml:delim> #\~))))
(define #:forall (a) (<:-:>) : (XML-Parser a) ((inst RNC<_> a) (RNC:<^> (<xml:name> '-))))
(define #:forall (a) (<:*:>) : (XML-Parser a) ((inst RNC<_> a) (RNC:<^> (<xml:delim> #\*))))
(define #:forall (a) (<:>:>) : (XML-Parser a) ((inst RNC<_> a) (RNC:<^> (<xml:delim> #\>))))
(define-rnc-disjoint-filter <rnc:keyword> #:-> Keyword
#:with [[options : (U (-> Keyword Boolean) (Listof Keyword) Keyword)]]
(<xml:pereference> options))
(define-rnc-disjoint-filter <rnc:id> #:-> Symbol
(<xml:name> xml-ncname?)
#;(RNC:<~> (<xml:pereference> null) keyword->symbol))
(define-rnc-disjoint-filter <rnc:cname> #:-> Symbol
(<xml:name> xml-cname?))
(define-rnc-disjoint-filter <rnc:nsname> #:-> Symbol
(<xml:name> xml-nsname?))
(define-rnc-disjoint-filter <rnc:id-or-keyword> #:-> Symbol
(<xml:name> xml-ncname?)
(RNC:<~> (<xml:pereference>) keyword->symbol))
(define-rnc-disjoint-filter <rnc:inherit> #:-> Symbol
(RNC:<=> (<xml:pereference> '#:inherit) 'inherit))
(define-rnc-disjoint-filter <rnc:name> #:-> Symbol
(<xml:name>)
(<rnc:id-or-keyword>))
(define-rnc-disjoint-filter <rnc:literal> #:-> String
#:with [[options : (U (-> String Boolean) (Listof String) String)]]
(<xml:string> options))
(define-rnc-disjoint-filter <rnc:assign-method> #:-> Char
(<rnc:assign>)
(RNC:<=> (<xml:delim> #\&) #\&)
(RNC:<=> (<xml:delim> #\λ #| not a typo |#) #\|))
(define (<:inherit:>) : (XML-Parser (Listof Symbol))
(RNC<&> ((inst RNC<_> (Listof Symbol)) (RNC:<^> (<xml:pereference> '#:inherit)))
((inst <:=:> (Listof Symbol)))
(RNC:<^> (<rnc:id-or-keyword>))))
(define (<:rnc-literal:> [filter : (Option (-> (Listof String) String (Listof XML-Token) (XML-Option True))) #false]) : (XML-Parser (Listof String))
(define <:literal:>
(RNC<&> (RNC:<^> (<xml:string>))
(RNC<*> (RNC<&> ((inst <:~:> (Listof String)))
(RNC:<^> (<xml:string>))) '*)))
(cond [(not filter) (RNC<~> <:literal:> string-append*)]
[else (RNC<~> <:literal:> string-append* filter)]))
(define (<:rnc-ns:literal:>) : (XML-Parser (Listof (U String Symbol)))
(RNC<+> (<:rnc-literal:>)
(RNC:<^> (<rnc:inherit>))))
(define <:rnc-name=value:> : (All (a) (->* ((XML:Filter Symbol) (-> Symbol String a))
((Option (-> (Listof a) a (Listof XML-Token) (XML-Option True))))
(XML-Parser (Listof a))))
(lambda [<name> rnc->racket [datum-guard #false]]
(define (rnc->datum [data : (Listof (U Symbol String))]) : a
(cond [(or (null? data) (null? (cdr data))) (rnc->racket 'dead "code")]
[else (rnc->racket (assert (car data) symbol?) (assert (cadr data) string?))]))
(define <:name=value:>
(RNC<&> (RNC:<^> <name>)
((inst <:=:> (Listof (U String Symbol))))
(<:rnc-literal:>)))
(if (not datum-guard)
(RNC<~> <:name=value:> rnc->datum)
(RNC<~> <:name=value:> rnc->datum datum-guard))))
(define <:rnc-annotation:> : (All (d a b c) (-> (Option (XML-Parser (Listof a))) (XML-Parser (Listof b)) (Option (XML-Parser (Listof c)))
(-> (Option a) b (Listof c) d) (XML-Parser (Listof (U b d)))))
(lambda [<:initial:> <:body:> <:follow:> rnc->racket]
(define <:initial?:> (if (not <:initial:>) values <:initial:>)) ; we won't check the result, so no need using of `RNC<*>`
(define <:follow*:> (and <:follow:> (RNC<*> <:follow:> '*)))
(λ [[data : (Listof (U b d))] [tokens : (Listof XML-Token)]]
(define-values (initial body-tokens) (<:initial?:> null tokens))
(define-values (body follow-tokens) (<:body:> null body-tokens))
(cond [(not (pair? body)) (values body follow-tokens)]
[(not <:follow*:>) (values (cons (if (pair? initial) (rnc->racket (car initial) (car body) null) (car body)) data) follow-tokens)]
[else (let-values ([(follows rest) (<:follow*:> null follow-tokens)])
(values (cons (cond [(not (or (pair? initial) (pair? follows))) (car body)]
[else (rnc->racket (and (pair? initial) (car initial)) (car body) (if (list? follows) follows null))])
data)
rest))]))))
(define <:rnc-bracket:> : (All (a) (->* ((XML-Parser (Listof a))) ((U False (XML-Multiplier Index) '+ '? '*) Char Char) (XML-Parser (Listof a))))
(lambda [<:body:> [multiplier #false] [open #\[] [close #\]]]
(if (not multiplier)
(RNC<&> ((inst RNC:<_> (Listof a)) (<xml:delim> open))
<:body:>
((inst RNC:<_> (Listof a)) (<xml:delim> close)))
(RNC<&> ((inst RNC:<_> (Listof a)) (<xml:delim> open))
(RNC<*> <:body:> multiplier)
((inst RNC:<_> (Listof a)) (<xml:delim> close))))))
(define <:rnc-parenthesis:> : (All (a) (->* ((XML-Parser (Listof a))) ((U False (XML-Multiplier Index) '+ '? '*)) (XML-Parser (Listof a))))
(lambda [<:body:> [multiplier #false]]
(<:rnc-bracket:> <:body:> multiplier #\( #\))))
(define <:rnc-brace:> : (All (a) (->* ((XML-Parser (Listof a))) ((U False (XML-Multiplier Index) '+ '? '*)) (XML-Parser (Listof a))))
(lambda [<:body:> [multiplier #false]]
(<:rnc-bracket:> <:body:> multiplier #\{ #\})))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define rnc-car/cdr : (All (a) (-> (Listof a) (Values (Option a) (Listof a))))
(lambda [dirty]
(let skip-whitespace ([rest dirty])
(cond [(null? rest) (values #false null)]
[else (let-values ([(head tail) (values (car rest) (cdr rest))])
(cond [(not (xml:whitespace? head)) (values head tail)]
[(not (xml:comment? head)) (skip-whitespace tail)]
[(string-prefix? (xml:whitespace-datum head) "#") (values head tail)]
[else (skip-whitespace tail)]))]))))
| true |
0dc847c97597b428a6d488d86333860443920073 | 00cb009baa43cf0c6313b28e74aa2bd99af41cb6 | /tic-tac-toe/utils/case-type/case-type.rkt | c10c40565f28c2b9a78bcee41b34a9438c2e0f1f | [
"MIT"
]
| permissive | AlexKnauth/tic-tac-toe | f9577784227de34412ee3622b4e198add7884f42 | e1cfb9a2a5dba370ddb2f33d47c8531ea220f0fb | refs/heads/master | 2022-01-23T13:53:02.937177 | 2022-01-07T14:59:52 | 2022-01-07T14:59:52 | 35,850,921 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 927 | rkt | case-type.rkt | #lang sweet-exp typed/racket/base
provide case/type
require my-cond/define-syntax-parser
"case-pred.rkt"
for-syntax racket/base
syntax/parse
racket/syntax
define-syntax-parser case/type #:stx stx
[(case/type e:expr (~and clause [:expr :expr ...+]) ...)
#:with x
(generate-temporary #'e)
(syntax/loc stx (case/type e #:id x clause ...))]
[(case/type e:expr #:id x:id
[t:expr body:expr ...+] ...
(~and else-clause [(~literal else) ~! :expr ...+]))
(syntax/loc stx
(case/pred e #:id x
[(make-predicate t) body ...] ...
else-clause))]
[(case/type e:expr #:id x:id (~and clause [:expr :expr ...+]) ...)
#:with covered-id:id
(syntax-parse #'e
[id:id #'id]
[_ #'x])
#:with else-body
#`(typecheck-fail #,stx #:covered-id covered-id)
(syntax/loc stx
(case/type e #:id x clause ... [else else-body]))]
| true |
d00eb4bf4a98c3319ad6ab701eeaab6a68accfdc | 56c17ee2a6d1698ea1fab0e094bbe789a246c54f | /2017/d14/star1.rkt | a05101d552926bfe59d35eb82cfa788f8d40eb11 | [
"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 | 43 | rkt | star1.rkt | #lang reader "main.rkt" ★ ; 8214
hxtvlmkl | false |
1cad4d9d50f17425d0af12b4473b5df3e5fee170 | 1186cb5914d37241eb1441be9995bbce4754407b | /3_3/tramp.rkt | 775e44a1cd45807a8c6fe8dcb955da9fd912b260 | []
| no_license | DonSmalltalk/C311Sp20 | c450a012c5e5eaf4afb4d75a3a5c2fad45b16ac4 | 116fb4f1b7a798eeb45e31d3af173b386e5a5505 | refs/heads/master | 2022-06-28T13:20:27.660408 | 2020-05-07T14:33:16 | 2020-05-07T14:33:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,406 | rkt | tramp.rkt | #lang racket
(require racket/trace)
#|Don't mind this.|#
(define sub2 (compose sub1 sub1))
(define one? (compose zero? sub1))
(define make-k-sub1
(λ (n k)
`(sub1 ,n ,k)))
(define make-k-sub2
(λ (k fib-of-sub1)
`(sub2 ,k ,fib-of-sub1)))
(define make-k-init
(λ (jumpout)
`(init ,jumpout)))
(define make-k-fact
(λ (n k)
`(fact ,n ,k)))
(define fib-cps
(λ (n k)
(λ ()
(cond
[(zero? n) (apply-k k 1)]
[(one? n) (apply-k k 1)]
[else (fib-cps (sub1 n)
(make-k-sub1 n k))]))))
(define fact-cps
(λ (n k)
(λ ()
(cond
[(zero? n) (apply-k k 1)]
[else (fact-cps (sub1 n)
(make-k-fact n k))]))))
(define apply-k
(λ (k v)
(λ ()
(match k
[`(sub1 ,n ,k)
(fib-cps (sub2 n)
(make-k-sub2 k v))]
[`(sub2 ,k ,fib-of-sub1)
(apply-k k (+ fib-of-sub1 v))]
[`(fact ,n ,k) (apply-k k (* n v))]
[`(init ,jumpout) (jumpout v)]))))
(define trampoline
(λ (th)
(trampoline (th))))
(define dt
(λ (th₁ th₂)
(dt th₂ (th₁))))
(define lot
(λ (l)
(let ([a (car l)]
[d (cdr l)])
(lot (append d (list (a)))))))
(let/cc jumpout
(lot
(list
(fact-cps 5 (make-k-init jumpout))
(fib-cps 5 (make-k-init jumpout))
(fact-cps 3 (make-k-init jumpout)))))
| false |
d0a9c197436888113794f7043cd3c8b52ba979ed | 7b04163039ff4cea3ac9b5b6416a134ee49ca1e4 | /thread.rkt | 8218cffa61f442ab27fbc085cda0dbdb9b17d560 | []
| no_license | dstorrs/racket-dstorrs-libs | 4c94219baf3c643a696aa17ed0e81d4a0ab18244 | 7e816d2b5f65a92ab01b29a320cc2c71d7870dbb | refs/heads/master | 2022-08-27T22:31:38.985194 | 2022-08-05T21:35:35 | 2022-08-05T21:35:35 | 68,236,201 | 6 | 1 | null | 2018-10-19T15:37:12 | 2016-09-14T19:24:52 | Racket | UTF-8 | Racket | false | false | 1,455 | rkt | thread.rkt | #lang racket/base
(require racket/contract/base
racket/contract/region
racket/format
racket/function
"utils.rkt")
(provide execute-thunk
threaded)
;;======================================================================
;; Functions for conveniently threading your code.
;;======================================================================
; (define/contract (execute-thunk thnk #:async? [async? #f])
;
; Run a thunk. If you set #:async? #t then it will be run in another
; thread via 'threaded' (see below)
(define/contract (execute-thunk thnk #:async? [async? #f])
(->* ((-> any)) ( #:async? boolean?) any)
(if async?
(threaded thnk)
(thnk)))
;;----------------------------------------------------------------------
; (define/contract (threaded thnk)
;
; Run a thunk in a new thread. The thread will be given a random
; label and all 'say' calls inside the thread will be prefixed with
; this label.
(define/contract (threaded thnk)
(-> (-> any) any)
(define current-prefix (prefix-for-say))
(define thread-label
(cond [(empty-string? current-prefix) (~a (rand-val "thread") ": ")]
[else (~a (rand-val "thread") " / " current-prefix)]))
(say __WHERE:__ "about to start thread with label: " thread-label)
(parameterize ([prefix-for-say thread-label])
(thread (thunk (begin0 (thnk) (sleep 0)))))) ; the sleep 0 suggests other threads should run
| false |
5c40d1947d82d167d6c521bae23004174a4c9f60 | 087c56877811a7737e9ed1ceb261ad2d9d5c65ee | /r7rs-lib/load.rkt | 85b016a0d7bba635b2760d17c80761cc22d71502 | [
"ISC"
]
| permissive | lexi-lambda/racket-r7rs | 2a510e70155c97b3256ec23bbc4de16567f21b70 | 84be3d16aab202e08b13da2f0e7c095e03ff0895 | refs/heads/master | 2023-06-23T10:38:38.675617 | 2022-11-23T08:00:52 | 2023-06-14T16:36:04 | 44,901,769 | 107 | 15 | null | 2022-11-23T08:03:26 | 2015-10-25T08:13:35 | Racket | UTF-8 | Racket | false | false | 235 | rkt | load.rkt | #lang racket/base
(require (prefix-in r: racket/base))
(provide load)
(define load
(case-lambda
[(path)
(r:load path)]
[(path environment)
(parameterize ([current-namespace environment])
(r:load path))]))
| false |
d08f5d06443625fd8f1eec97f7dd9eca670830d5 | cad8a385c15231b2e898aa2e7d37874824cc718f | /hw5_sol2.rkt | 1d59c0fd2bdd19ef3735b3c4102133600a620963 | []
| no_license | drazen41/Racket | 6d14e1ece131b1dd0d2b940ab3ae6ee57a6bc63d | f592e63c191aa78f0ffcaea1e8122ab6c10db6c8 | refs/heads/master | 2021-09-03T14:05:41.273700 | 2018-01-09T16:43:49 | 2018-01-09T16:43:49 | 114,474,939 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 9,306 | rkt | hw5_sol2.rkt | #lang racket
(provide (all-defined-out)) ;; so we can put tests in a second file
;; definition of structures for MUPL programs - Do NOT change
(struct var (string) #:transparent) ;; a variable, e.g., (var "foo")
(struct int (num) #:transparent) ;; a constant number, e.g., (int 17)
(struct add (e1 e2) #:transparent) ;; add two expressions
(struct ifgreater (e1 e2 e3 e4) #:transparent) ;; if e1 > e2 then e3 else e4
(struct fun (nameopt formal body) #:transparent) ;; a recursive(?) 1-argument function
(struct call (funexp actual) #:transparent) ;; function call
(struct mlet (var e body) #:transparent) ;; a local binding (let var = e in body)
(struct apair (e1 e2) #:transparent) ;; make a new pair
(struct fst (e) #:transparent) ;; get first part of a pair
(struct snd (e) #:transparent) ;; get second part of a pair
(struct aunit () #:transparent) ;; unit value -- good for ending a list
(struct isaunit (e) #:transparent) ;; evaluate to 1 if e is unit else 0
;; a closure is not in "source" programs; it is what functions evaluate to
(struct closure (env fun) #:transparent)
;; Problem 1
(define (racketlist->mupllist rlist)
(cond [(null? rlist) (aunit)]
[(null? (cdr rlist)) (apair (car rlist) (aunit))]
[#t (apair (car rlist) (racketlist->mupllist (cdr rlist)))]))
(define (mupllist->racketlist mlist)
(cond [(equal? (aunit) mlist) '()]
[(equal? (apair-e2 mlist) (aunit)) (cons (apair-e1 mlist) null)]
[#t (append (list (apair-e1 mlist)) (mupllist->racketlist (apair-e2 mlist)))]))
;; Problem 2
;; lookup a variable in an environment
;; Do NOT change this function
(define (envlookup env str)
(cond [(null? env) (error "unbound variable during evaluation" str)]
[(equal? (car (car env)) str) (cdr (car env))]
[#t (envlookup (cdr env) str)]))
;; Do NOT change the two cases given to you.
;; DO add more cases for other kinds of MUPL expressions.
;; We will test eval-under-env by calling it directly even though
;; "in real life" it would be a helper function of eval-exp.
(define (eval-under-env e env)
;(displayln (format "e: ~v" e))
;(displayln (format "env: ~v~%" env))
(cond [(var? e)
(envlookup env (var-string e))]
[(add? e)
(let ([v1 (eval-under-env (add-e1 e) env)]
[v2 (eval-under-env (add-e2 e) env)])
(if (and (int? v1)
(int? v2))
(int (+ (int-num v1)
(int-num v2)))
(error "MUPL addition applied to non-number" v1 )))]
; if int return expression
[(int? e) e]
[(aunit? e) e]
; fun (nameopt formal body)
; (list (cons (s1, (f s1 s2 e))), (cons s2, e))
[(fun? e) (closure env
(fun (fun-nameopt e)
(fun-formal e) (fun-body e)))]
; if greater check which is greater by calling eval-under-env for e1 and e2
[(ifgreater? e) (let ([v1 (eval-under-env (ifgreater-e1 e) env)]
[v2 (eval-under-env (ifgreater-e2 e) env)])
(if (> (int-num v1) (int-num v2))
(eval-under-env (ifgreater-e3 e) env)
(eval-under-env (ifgreater-e4 e) env)))]
;An mlet expression evaluates its first expression to a value v. Then it evaluates the second
;expression to a value, in an environment extended to map the name in the mlet expression to v.
; mlet (var e body)
[(mlet? e) (eval-under-env (mlet-body e) (append env (list (cons (mlet-var e) (eval-under-env(mlet-e e) env)))))]
[(closure? e) e]
;A call evaluates its first and second subexpressions to values. If the first is not a closure, it is an
;error. Else, it evaluates the closure’s function’s body in the closure’s environment extended to map
;the function’s name to the closure (unless the name field is #f) and the function’s argument-name8
;(i.e., the parameter name) to the result of the second subexpression.
; call (funexp actual)
; closure (env fun)
[(call? e)
(let ([e1 (eval-under-env (call-funexp e) env)]
[e2 (eval-under-env (call-actual e) env)])
(if (closure? e1)
; evaluate closures functions body
(eval-under-env (fun-body (closure-fun e1))
(if (fun-nameopt(closure-fun e1))
; extended to map the function’s name to the closure
(append (list (cons (fun-nameopt(closure-fun e1)) e1)
; and the function’s argument-name to the result of the second subexpression.
(cons (fun-formal(closure-fun e1)) e2))
;in the closure’s environment
(closure-env e1))
(append (list (cons (fun-formal(closure-fun e1)) e2))
;in the closure’s environment
(closure-env e1))))
(error "Not a closure" e1 )))]
[(apair? e) (apair (eval-under-env(apair-e1 e) env) (if (aunit? (apair-e2 e))
(aunit)
(eval-under-env(apair-e2 e) env)))]
;(apair-e1 e)]
; TODO optimize with let
[(fst? e) (if (apair? (eval-under-env (fst-e e) env)) (apair-e1 (eval-under-env(fst-e e) env)) (error "Not a pair"))]
[(snd? e) (if (apair? (eval-under-env (snd-e e) env)) (apair-e2 (eval-under-env(snd-e e) env)) (error "Not a pair"))]
;An isaunit expression evaluates its subexpression. If the result is an aunit expression, then the
;result for the isaunit expression is the mupl value (int 1), else the result is the mupl value
[(isaunit? e) (if (aunit? (eval-under-env(isaunit-e e) env)) (int 1) (int 0))]
[#t (error (format "bad MUPL expression: ~v" e))]))
;(> (int-num (eval-under-env (ifgreater-e1 e) env)) (int-num (eval-under-env(ifgreater-e2 e) env)))
;return e3 if true
;(ifgreater-e3 e)
;else return e4
;(ifgreater-e4 e)
;; Do NOT change
(define (eval-exp e)
(eval-under-env e null))
;; Problem 3
(define (ifaunit e1 e2 e3)
(ifgreater (isaunit e1) (int 0) e2 e3))
; mlet (var e body)
(define (mlet* lstlst e2)
(if (null? (cdr lstlst))
(mlet (car (car lstlst)) (cdr (car lstlst)) e2)
(mlet (car (car lstlst)) (cdr (car lstlst)) (mlet* (cdr lstlst) e2))))
(define (ifeq e1 e2 e3 e4)
(ifgreater e1 e2 (ifgreater e2 e1 e3 e4) (ifgreater e2 e1 e4 e3)))
;; Problem 4
; Bind to the Racket variable mupl-map a mupl function that acts like map (as we used extensively
; in ML). Your function should be curried: it should take a mupl function and return a mupl
; function that takes a mupl list and applies the function to every element of the list returning a
; new mupl list. Recall a mupl list is aunit or a pair where the second component is a mupl list.
;fun map (f,xs) =
; case xs of
; [] => []
; | x::xs’ => (f x)::(map(f,xs’))
(define mupl-map
; b -> holds mapping function
; c -> holds recursive function (takes in list)
; d -> represents list
(fun #f "b"
(fun "c" "d"
;if list is (aunit)
(ifaunit (var "d")
; return (aunit)
(aunit)
;else call map (b)
(apair (call (var "b")
;on first element of pair
(fst(var "d")))
; and recurively call c
(call (var "c")
; with smaller list
(snd (var "d"))))))))
; Bind to the Racket variable mupl-mapAddN a mupl function that takes an mupl integer i and
; returns a mupl function that takes a mupl list of mupl integers and returns a new mupl list of
; mupl integers that adds i to every element of the list. Use mupl-map (a use of mlet is given to
; you to make this easier).
(define mupl-mapAddN
(mlet "map" mupl-map
(fun #f "b"
(fun "c" "d"
(call (call (var "map") (fun #f "x" (add (var "x") (var "b")))) (var "d"))))))
;; Challenge Problem
(struct fun-challenge (nameopt formal body freevars) #:transparent) ;; a recursive(?) 1-argument function
;; We will test this function directly, so it must do
;; as described in the assignment
(define (compute-free-vars e) "CHANGE")
;; Do NOT share code with eval-under-env because that will make
;; auto-grading and peer assessment more difficult, so
;; copy most of your interpreter here and make minor changes
(define (eval-under-env-c e env) "CHANGE")
;; Do NOT change this
(define (eval-exp-c e)
(eval-under-env-c (compute-free-vars e) null)) | false |
3e411115144d67b1f82babcd1be1bf0fcc016ffa | d081ccc87078307aabb7ffc56ecc51e2e25d653d | /run-tests.rkt | bfc68454b3062d7c0e10d1e303d2edb34475963e | [
"BSD-3-Clause"
]
| permissive | Bogdanp/racket-review | 75501945155a5f75a0684e60ae6934fb2617e655 | bc7b614e3b6ab11a9f569d254aaba7f2d2074354 | refs/heads/master | 2023-08-21T20:16:54.808995 | 2023-07-28T18:28:24 | 2023-07-28T18:28:24 | 191,135,877 | 40 | 3 | BSD-3-Clause | 2022-08-08T08:10:11 | 2019-06-10T09:17:45 | Racket | UTF-8 | Racket | false | false | 1,954 | rkt | run-tests.rkt | #lang racket/base
(require (for-syntax racket/base)
racket/format
racket/match
racket/path
racket/port
racket/runtime-path
racket/string
racket/system)
(define-runtime-path linter-tests
(build-path "tests" "lint"))
(file-stream-buffer-mode (current-output-port) 'none)
(file-stream-buffer-mode (current-error-port) 'none)
(define (indent s)
(~a " " s))
(define (update-output-file! filepath output)
(with-output-to-file filepath
#:exists 'truncate/replace
(lambda ()
(for-each displayln output))))
(define (strip-prefixes line)
(string-replace line (path->string linter-tests) ""))
(for ([filename (directory-list linter-tests)]
#:when (bytes=? (path-get-extension filename) #".rkt"))
(define-values (in out) (make-pipe))
(define input-filepath (build-path linter-tests filename))
(define output-filepath (~a input-filepath ".out"))
(match-define (list _ _ _ _ control)
(process*/ports out #f out (find-executable-path "raco") "review" input-filepath))
(control 'wait)
(close-output-port out)
(define command-output (map strip-prefixes (port->lines in)))
(define expected-output
(cond
[(file-exists? output-filepath)
(call-with-input-file output-filepath port->lines)]
[else
(begin0 command-output
(update-output-file! output-filepath command-output))]))
(unless (equal? command-output expected-output)
(displayln (~a "output differs when linting " output-filepath))
(displayln "expected:")
(for-each (compose1 displayln indent) expected-output)
(displayln "found:")
(for-each (compose1 displayln indent) command-output)
(display "update? ")
(let loop ()
(if (getenv "BATCH")
(exit 1)
(case (read-char)
[(#\y) (update-output-file! output-filepath command-output)]
[(#\n) (exit 1)]
[else (loop)])))))
| false |
0ed3e726731c8f686d288584ac438501e93c715d | 53542701f473a1bf606ae452ed601543d686e514 | /Exam - Quiz 1/submission/160050064/q5.rkt | 66b567977a86fd7cae24c763829597a7472512c5 | [
"MIT"
]
| permissive | vamsi3/IITB-Abstractions-and-Paradigms | f6c187a6d1376ca08dd4c2b18258144627eaed6b | ab80fc33341ba0ba81d1519c92efd7e06127b86b | refs/heads/master | 2022-10-23T23:45:18.907063 | 2020-06-09T15:41:33 | 2020-06-09T15:41:33 | 271,042,673 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 577 | rkt | q5.rkt | #lang racket
(provide flatten)
(struct node (val ltree rtree) #:transparent)
(struct nulltree () #:transparent)
(define (flatten t)
(define (flatten-helper t l)
(cond [(and (nulltree? (node-ltree t)) (nulltree? (node-rtree t))) (cons (node-val t) l)]
[(nulltree? (node-ltree t)) (cons (node-val t) (flatten-helper (node-rtree t) l))]
[(nulltree? (node-rtree t)) (flatten-helper (node-ltree t) (cons (node-val t) l))]
[else (flatten-helper (node-ltree t) (cons (node-val t) (flatten-helper (node-rtree t) l)))]))
(flatten-helper t '())) | false |
a071d90d1672bc5a7fc4fdb011a56f0a456645a7 | b427908ecf798b01f76cb6d1bca1b219f45dac7c | /assemble.rkt | 2a6a9b1b837e42f5dfe908bafc21e9d79f7392a0 | []
| no_license | LeifAndersen/racket-asm | 70e79c337441267c982df4ae07b42e79e702343d | bce977780c4ed0755f42184154bf5a78855f5e93 | refs/heads/master | 2021-01-22T10:19:28.338680 | 2015-12-20T08:40:17 | 2015-12-20T08:40:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,101 | rkt | assemble.rkt | #lang racket
(require
"types.rkt")
(provide
(struct-out object)
assemble
fix-label!
make-forward-label
make-label
plain-assemble
write-instruction)
(struct object (code labels))
(struct assembler
(instructions position emit)
#:mutable)
(define current-assembler
(make-parameter #f))
(define (make-assembler)
(assembler
'()
0
(λ (asm)
(call-with-output-bytes
(λ (out)
(for/fold ([p 0])
([ins (in-list (reverse (assembler-instructions asm)))])
(let ([patch! (instruction-patch! ins)])
(when patch!
(patch! p)))
(define bs (instruction-bytes ins))
(write-bytes bs out)
(+ p (bytes-length bs))))))))
(define-syntax-rule (assemble body ...)
(collect-labels (body ...)))
(define-syntax collect-labels
(syntax-rules ()
[(_ (body ...))
(collect-labels (body ...) ())]
[(_ () (done ...))
(plain-assemble done ...)]
[(_ (#:label id body ...) (done ...))
(collect-labels (body ...)
((define id (make-forward-label))
done ...
(fix-label! id)))]
[(_ (body rest ...) (done ...))
(collect-labels (rest ...) (done ... body))]))
(define-syntax (plain-assemble stx)
(syntax-case stx ()
[(_ body ...)
#'(let ([asm (make-assembler)])
(parameterize ([current-assembler asm])
body ...)
((assembler-emit asm) asm))]))
(define (fix-label! lbl)
(when (label-address lbl)
(error "label already fixed"))
(set-label-address! lbl (assembler-position (current-assembler))))
(define (make-forward-label)
(label #f))
(define (make-label)
(label (assembler-position (current-assembler))))
(define (write-instruction ins)
(let ([asm (current-assembler)])
(unless asm
(error "invalid outside of (assemble ...)"))
(set-assembler-instructions!
asm
(cons ins (assembler-instructions asm)))
(set-assembler-position!
asm
(+ (bytes-length (instruction-bytes ins))
(assembler-position asm)))))
| true |
dd6b02c41cf5f0e8c81820886aaaf7a53628739a | 688b982ef1ae4b822162cee56a6437a3fa3ec9a8 | /asdl/examples/use-arith.rkt | 3425482b09fb82710b17be7f75cfd99bd7c151dd | []
| 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 | 61 | rkt | use-arith.rkt | #lang racket
(require "arith.rkt")
(Num 1)
(Num? (Num 1))
| false |
808fcf974ee7a1cf56a77cd32fbc5dffd88780a9 | 82c76c05fc8ca096f2744a7423d411561b25d9bd | /typed-racket-test/succeed/safe-vector-base.rkt | 699dfcc7059f5cd74362ed4f1a6efd1e3b130053 | [
"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 | 280 | rkt | safe-vector-base.rkt | #lang typed/racket/base
(require typed/racket/unsafe)
(unsafe-require/typed/provide
typed/racket/base
[make-vector
(All (A) (-> ([size : Natural]
[val : A])
(Refine [v : (Vectorof A)]
(= size (vector-length v)))))])
| false |
4c6d0455bb9f71ba580042c5ea7e57a549b460a9 | b3f7130055945e07cb494cb130faa4d0a537b03b | /gamble/private/mh/transitions.rkt | 8ea3e30a285fba22218a5c0d02fc215672b8f7a7 | [
"BSD-2-Clause"
]
| permissive | rmculpepper/gamble | 1ba0a0eb494edc33df18f62c40c1d4c1d408c022 | a5231e2eb3dc0721eedc63a77ee6d9333846323e | refs/heads/master | 2022-02-03T11:28:21.943214 | 2016-08-25T18:06:19 | 2016-08-25T18:06:19 | 17,025,132 | 39 | 10 | BSD-2-Clause | 2019-12-18T21:04:16 | 2014-02-20T15:32:20 | Racket | UTF-8 | Racket | false | false | 7,905 | rkt | transitions.rkt | ;; Copyright (c) 2014 Ryan Culpepper
;; Released under the terms of the 2-clause BSD license.
;; See the file COPYRIGHT for details.
#lang racket/base
(require racket/class
(rename-in racket/match [match-define defmatch])
"db.rkt"
"../interfaces.rkt"
"../dist.rkt"
"../util/prob.rkt"
"../../dist/discrete.rkt"
"base.rkt"
"proposal.rkt")
(provide (all-defined-out))
;; ============================================================
(define perturb-mh-transition-base%
(class mh-transition-base%
(init-field [temperature 1])
(field [last-delta-db #f]) ;; HACK for feedback
(super-new)
;; run* : (-> A) Trace -> (U (list* Real Trace TxInfo) (list* 'fail Any TxInfo))
(define/override (run* thunk last-trace)
(define last-db (trace-db last-trace))
(defmatch (cons delta-db delta-ll-R/F) (perturb last-trace))
(set! last-delta-db delta-db)
(define ctx
(new db-stochastic-ctx%
(last-db last-db)
(delta-db delta-db)
(ll-R/F delta-ll-R/F)))
;; Run program
(define result (with-verbose> (send ctx run thunk)))
(match result
[(cons 'okay sample-value)
(define ll-diff (get-field ll-diff ctx))
(define ll-R/F (get-field ll-R/F ctx))
(define current-trace (send ctx make-trace sample-value))
(define threshold
(accept-threshold last-trace ll-R/F current-trace ll-diff))
(list* threshold current-trace (vector 'delta delta-db))]
[(cons 'fail fail-reason)
(list* 'fail fail-reason (vector 'delta delta-db))]))
;; perturb : Trace -> (cons DB Real)
(abstract perturb)
;; accept-threshold : Trace Real Trace Real Boolean -> Real
;; Computes (log) accept threshold for current trace.
(define/public (accept-threshold last-trace ll-R/F current-trace ll-diff)
(define other-factor (accept-threshold* last-trace current-trace))
(cond [(or (= other-factor -inf.0) (= other-factor +inf.0))
other-factor]
[else
(define ll-diff-obs (traces-obs-diff current-trace last-trace))
(+ ll-R/F (/ (+ ll-diff ll-diff-obs) temperature) other-factor)]))
;; accept-threshold* : Trace Trace -> Real
;; Computes (log) of additional factors of accept threshold.
;; If +/-inf.0, then that is taken as accept factor (to avoid
;; possible NaN from arithmetic).
(define/public (accept-threshold* last-trace current-trace)
0)
(define/override (feedback success?)
(for ([key (in-hash-keys last-delta-db)])
(feedback/key key success?))
(set! last-delta-db #f)
(super feedback success?))
(define/public (feedback/key key success?)
(void))
))
;; ============================================================
(define single-site-mh-transition%
(class perturb-mh-transition-base%
(init-field zone
proposal)
(inherit-field last-delta-db)
(field [proposed 0]
[resampled 0])
(super-new)
(define/override (accinfo)
(Info "== single-site transition"
["Zone" zone]
[include (super accinfo)]
["Proposal perturbs" proposed]
["Fall-through perturbs" resampled]
[nested "Proposal" (send proposal accinfo)]))
;; perturb : Trace -> (cons DB Real)
(define/override (perturb last-trace)
(define last-db (trace-db last-trace))
(define key-to-change
(db-pick-a-key (trace-db last-trace) zone))
(vprintf "key to change = ~s\n" key-to-change)
(define-values (delta-db ll-R/F)
(cond [key-to-change
(match (hash-ref last-db key-to-change)
[(entry zones dist value ll)
(defmatch (cons e ll-R/F)
(perturb-a-key key-to-change dist value zones))
(values (hash key-to-change e) ll-R/F)])]
[else (values '#hash() 0)]))
(set! last-delta-db delta-db)
(cons delta-db ll-R/F))
;; perturb-a-key : Address Dist Value Zones -> (cons Entry Real)
(define/public (perturb-a-key key dist value zones)
(defmatch (cons value* R-F)
(cond [(send proposal propose1 key zones dist value)
=> (lambda (r) (set! proposed (add1 proposed)) r)]
[else
(set! resampled (add1 resampled))
(propose:resample dist value)]))
(vprintf "PROPOSED from ~e to ~e\n" value value*)
(vprintf " R/F = ~s\n" (exp R-F))
(define ll* (dist-pdf dist value* #t))
(unless (logspace-nonzero? ll*)
(eprintf "proposal produced impossible value\n dist: ~e\n value: ~e\n"
dist value*))
(cons (entry zones dist value* ll*) R-F))
(define/override (accept-threshold* last-trace current-trace)
;; Account for backward and forward likelihood of picking
;; the random choice to perturb that we picked.
(define nchoices (db-count (trace-db current-trace) #:zone zone))
(define last-nchoices (db-count (trace-db last-trace) #:zone zone))
(cond [(zero? last-nchoices)
+inf.0]
[else
;; Note: assumes we pick uniformly from all choices.
;; R = (log (/ 1 nchoices)) = (- (log nchoices))
;; F = (log (/ 1 last-nchoices)) = (- (log last-nchoices))
;; convert to inexact so (log 0.0) = -inf.0
(define R (- (log (exact->inexact nchoices))))
(define F (- (log (exact->inexact last-nchoices))))
(- R F)]))
(define/override (feedback/key key success?)
(send proposal feedback key success?))
))
;; ============================================================
(define multi-site-mh-transition%
(class perturb-mh-transition-base%
(init-field zone proposal)
(inherit-field last-delta-db)
(super-new)
(define/override (accinfo)
(Info "== multi-site transition"
["Zone" zone]
[include (super accinfo)]
[nested "Proposal" (send proposal accinfo)]))
;; perturb : Trace -> (cons DB Real)
(define/override (perturb last-trace)
(define last-db (trace-db last-trace))
(define delta-db
(for/hash ([(key e) (in-hash last-db)]
#:when (entry-in-zone? e zone))
(values key proposal)))
(set! last-delta-db delta-db)
(cons delta-db 0))
;; accept-threshold* : Trace Real Trace Real Boolean -> Real
(define/override (accept-threshold* last-trace current-trace)
(cond [(zero? (trace-nchoices last-trace))
+inf.0]
[else ;; FIXME: what if current-nchoices != last-nchoices ???
0]))
(define/override (feedback/key key success?)
(send proposal feedback key success?))
))
;; ============================================================
(define mixture-mh-transition%
(class* object% (mh-transition<%>)
(init transitions weights)
(super-new)
(define tx-dist (make-discrete-dist* transitions weights #:normalize #f))
(define/public (run thunk last-trace)
(define r (send (dist-sample tx-dist) run thunk last-trace))
r)
(define/public (accinfo)
(Info "== mixture transition"
[nested "Alternatives"
(for/list ([tx (discrete-dist-values tx-dist)])
(send tx accinfo))]))
))
;; ============================================================
(define rerun-mh-transition%
(class perturb-mh-transition-base%
(super-new)
(define/override (accinfo)
(Info "== rerun transition"
[include (super accinfo)]))
(define/override (perturb last-trace)
(cons '#hash() +inf.0))
(define/override (accept-threshold . _args)
+inf.0)))
| false |
c0c904227a8be8c763223b426692f088f2e840c9 | 98fd4b7b928b2e03f46de75c8f16ceb324d605f7 | /drracket-test/tests/drracket/syncheck-eval-compile-time.rkt | 0678db10e454f0c3375cc333d421c2682c410d63 | [
"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 | 1,208 | rkt | syncheck-eval-compile-time.rkt | #lang racket/base
(require "private/drracket-test-util.rkt"
racket/class
framework)
(define (main)
(fire-up-drracket-and-run-tests
(λ ()
(let ([drs (wait-for-drracket-frame)])
(set-module-language!)
(do-execute drs)
(queue-callback/res
(λ ()
(preferences:set 'framework:coloring-active #f)
(handler:edit-file (collection-file-path "map.rkt" "racket" "private"))))
(click-check-syntax-and-check-errors drs "syncheck-eval-compile-time.rkt")))))
;; copied from syncheck-test.rkt ....
(define (click-check-syntax-and-check-errors drs test)
(click-check-syntax-button drs)
(wait-for-computation drs)
(when (queue-callback/res (λ () (send (send drs get-definitions-text) in-edit-sequence?)))
(error 'syncheck-test.rkt "still in edit sequence for ~s" test))
(let ([err (queue-callback/res (λ () (send drs syncheck:get-error-report-contents)))])
(when err
(eprintf "FAILED ~s\n error report window is visible:\n ~a\n"
test
err))))
(define (click-check-syntax-button drs)
(test:run-one (lambda () (send (send drs syncheck:get-button) command))))
(main)
| false |
59c3b74348100d54cd6178b64afc1de5a9b102cd | d6b905b841a3c812ff1805879f681111f164e87c | /zenspider/ch02/my-first-program.rkt | 44d71cbf39c060be369485ed0e9de0769d4f418f | [
"MIT"
]
| permissive | SeaRbSg/realm_of_racket | 40398e89ab2d39b7499bb97ee2a6b07bdb79c586 | b4383c6cab68b4cea04f514267c58397e8cc69d0 | refs/heads/master | 2021-03-12T22:50:14.935166 | 2017-11-30T23:40:10 | 2017-11-30T23:51:11 | 12,911,347 | 1 | 2 | null | null | null | null | UTF-8 | Racket | false | false | 583 | rkt | my-first-program.rkt | #lang racket
;; determine or set the upper and lower limits of the player's number
(define lower 1)
(define upper 100)
(define (start n m)
(set! lower (min n m))
(set! upper (max n m))
(guess))
;; guess a number halfway between those two numbers
(define (guess)
(quotient (+ lower upper) 2))
;; if the player says the number is smaller, lower the upper limit
(define (smaller)
(set! upper (max lower (sub1 (guess))))
(guess))
;; if the player says the number is larger, raise the lower limit
(define (larger)
(set! lower (min upper (add1 (guess))))
(guess))
| false |
583b0008589e938ab56ff1c9309dee684a316dc4 | 66c92b955f3caa70ea4b322654079450ab9eff36 | /gm-pepm-2018/main.rkt | bd16a6a7136544422932c60016ec28e84a393bd3 | [
"MIT"
]
| permissive | nuprl/retic_performance | ebc3a5656ce77539ff44c50ac00dacd0a22496ec | da634137b151553c354eafcc549e1650043675f9 | refs/heads/master | 2023-06-22T05:41:16.151571 | 2023-06-12T20:16:13 | 2023-06-12T20:16:13 | 85,637,202 | 3 | 1 | MIT | 2023-06-12T20:16:14 | 2017-03-20T23:23:11 | Racket | UTF-8 | Racket | false | false | 27,549 | rkt | main.rkt | #lang at-exp racket/base
;; Programming environment for the DLS 2017 submission. Includes utilities for:
;; - formatting
;; - processing datasets
;;
;; Basically, extends `scribble/acmart` with project-specific options.
;; (The file `lang/reader.rkt` sets up the actual reader.)
(provide
if-techrpt
DEF-APPROX
(all-from-out
"bib.rkt"
scribble/acmart
scribble/doclang
scriblib/figure
scribble/example
scriblib/autobib)
(except-out (all-from-out scribble/manual) url)
(rename-out
[acmart:#%module-begin #%module-begin]
[render-benchmark-name bm]
;; Usage: `@bm{name}`
;; Given something that uniquely identifies a benchmark, render the
;; benchmark's canonical name.
;; This is essentially `tt`, but it catches typos.
[render-benchmark-names* bm*]
;; Usage: `@bm*{name1 name2 ...}
;; Render multiple benchmark names.
[format-url url]
;; Usage: @url{URL}
;; format a URL, removes the `http://` prefix if given
)
generate-bibliography
bm-desc
appendix
;; Typesets '\appendix{}' before the title of the current part
exact-runtime-category
;; Usage: @category[name bm* make-descr]
;; where `name` is a string, broadly describes the category
;; and `bm*` is a list of benchmark names (e.g. symbols)
;; and `make-descr` is a thunk (-> string? element?)
;; that accepts a string representing the length of `bm*`
;; and produces text that defines and carefully describes the category.
;; Renders a "category describing a group of exact runtime plots"
percent-slower-than-typed
;; Usage: @percent-slower-than-typed{benchmark-name}
;; Extremely specialized function, count the number of configurations
;; that run slower than the typed configuration.
x-axis y-axis
x-axes y-axes
;; Usage: @|x-axis|
;; Renders "x-axis", with or without italics on the `x` (depends what looks better)
*PLOT-HEIGHT*
;; Parameter to fix height of individual overhead plots
*SINGLE-COLUMN?*
;; (Parameterof Boolean)
;; When true, put all plots in 1 column
SNAPL-2015-URL
;; URL to the SNAPL paper by Siek et.al
gnorm
;; Usage: @${@gnorm{x}}
;; where `x` is measurable syntax
definition
;; Usage: @definition[term]{defn ...}
;; where `term` is a term to define and `defn ...` defines the term.
;; Renders a definition
defn
;; Usage: @defn[term]
;; where `term` is previously defined in a `definition`
;; Renders a reference to a technical term.
lib-desc
;; (->* [string?] [#:rest pre-content?] pre-content?)
;; @lib-desc[lib-name]{descr}
;; Render a description of a Python library used by one of the benchmarks
DLS-2014-BENCHMARK-NAMES
POPL-2017-BENCHMARK-NAMES
DLS-2017-BENCHMARK-NAMES
;; (listof symbol?)
MAX-OVERHEAD
EXACT-RUNTIME-XSPACE
benchmark->name
u/p-ratio
t/u-ratio
t/p-ratio
EXHAUSTIVE-BENCHMARKS
VALIDATE-BENCHMARKS
SAMPLE-BENCHMARKS
;; (listof benchmark-info?)
;; Registry of all known benchmarks.
;; To change, edit `script/benchmark-info.rkt`.
NUM-EXHAUSTIVE-BENCHMARKS
;; natural?
;; Same as `(length EXHAUSTIVE-BENCHMARKS)`
NUM-VALIDATE-SAMPLES
;; natural?
;; Number of benchmarks in both the `EXHAUSTIVE-BENCHMARKS` and `SAMPLES-BENCHMARKS` lists
NUM-NEW-SAMPLES
;; natural?
;; Number of benchmarks that are exclusive to the `SAMPLE-BENCHMARKS` list
NUM-ITERATIONS
;; Number of times we ran each configuration for each benchmark.
SAMPLE-RATE
;; Constant, defines sample size.
;; The sample size for a benchmark with N type-able components is
;; `SAMPLE-RATE * N`
NUM-SAMPLE-TRIALS
;; Constant, defines number of sample trials.
;; i.e. how many times we took random samples for each benchmark
NUM-BETTER-WITH-TYPES
;; Number of configurations that run faster than some configuration with
;; fewer typed components. (This is rare, and usually indicates a bug.)
BENCHMARKS-WITH-FIRST-CLASS-FUNCTIONS
;; Number of benchmarks that use first-class function types
;; (ignores object types)
PYTHON
;; "Python 3.4.3",
;; the proper name of the version of python that we used to collect data
$
;; Usage: `@${some math}`
;; where `some math` is LaTeX-formatted math.
;; Wraps its arguments in dollar signs `$ ....$` and sends the result to LaTeX
authors
authors*
;; Usage: `@authors[author-name ...]
;; where `author-name` is a string
;; Renders a sequence of author names
~cite
;; Usage: `@~cite[bib-name]`
;; where `bib-name` is an identifier from `bib.rkt`
;; Renders a short-style citation to `bib-name`.
;; Example:
;; @elem{We love@~cite[matthias]}
;; May render to:
;; "We love [409]."
;; Where 409 is the number assigned to the bib entry that `matthias` refers to
citet
;; Usage: `@citet[bib-name]`
;; where `bib-name` is an identifier from `bib.rkt`
;; Renders a long-style citation to `bib-name`
;; Example:
;; @elem{See work by @citet[matthias]}
;; May render to:
;; "See work by Felleisen 1901"
;; If `matthias` refers to a 1901 article by Felleisen.
cspace
;; Usage: `@cspace{C}`
;; where `C` is a string.
;; Renders a meta-variable that represents a configuration space.
deliverable
;; Usage: `@deliverable[N]`
;; where `N` is a string or positive real number
;; Renders as "N-deliverable"
approximation
;; Usage: `@approximation[r s pct]`
;; where `r`, `s` are variables
;; and `pct` is a percentage.
;; Renders as "pct% r,s-approximation"
sra
;; Usage: @|sra|
etal
;; Usage: `@|etal|`
;; Renders "et al." with proper spacing between the words.
;; Use `citet` instead.
exact
;; Usage: `@exact|{some text}|`
;; or `@exact{some text}`
;; where `some text` is text that should go directly to LaTeX
;; Using `|{ ... }|` instead of `{ ... }` ignores any `@` signs
;; or unmatched `}` in the `...`.
id
;; Usage: `@id[foo]`
;; where `foo` is a Racket identifier.
;; Renders the display-mode form of the value of `foo`
integer->word
Integer->word
;; (->* [integer?] [#:title? any/c] string?)
;; Coverts a small number into a string.
;; Capitalizes the string when `#:title?` is non-#f
note
;; Usage: `@note{some text}`
;; Renders a footnote containing `some text`.
;; The footnote marker will appear where `@note` appears in the source,
;; and the footnote text will appear at the bottom of the current page.
;;
;; Remember! Footnotes always go after any punctuation.
;; (See "Introduction to Notes" here: https://owl.english.purdue.edu/owl/owlprint/717/ )
parag
;; Usage: `@parag{word}`
;; where `word` is a single word or short phrase.
;; Renders a label for an upcoming paragraph.
python
;; Usage: `@python{ code }`
;; where `code` is one-or-more-lines of Python code
;; Renders a codeblock containing Python code.
pythonexternal
;; Usage: `@pythonexternal{path-string}`
;; where `path-string` refers to a file containing Python code
;; Renders the contents of `path-string` in a Python code block
pythoninline
;; Usage: `@pythoninline{code}`
;; where `code` is less than 1 line of Python code
;; Renders some Python code in the current line of text.
;; Useful for formatting identifiers
render-overhead-plot*
;; (-> (listof benchmark-info?) pict?)
;; Render overhead plots for the given benchmarks
render-exact-runtime-plot*
;; (-> (listof benchmark-info?) pict?)
;; Render the exact running times for the given benchmarks.
;; Running times ordered by number of types.
render-static-information
;; (-> (listof benchmark-info?) table?)
;; Build a table of static information about each benchmark
render-ratios-table
;; (-> (or/c table (listof benchmark-info?)) pict?)
;; Build a table of Python/Retic/Typed ratios
render-samples-plot*
;; (-> (listof benchmark-info?) pict?)
;; Plots the random-sample data for the given benchmarks
;; as multiple lines on a single graph.
;; See also `render-validate-samples-plot*`
render-validate-samples-plot*
;; (-> (listof benchmark-info?) pict?)
;; Plots the overhead of each benchmark alongside a confidence interval
;; generated from the benchmark's random samples.
;; See also `render-samples-plot*`
sc
;; Usage `@sc{some text}`
;; Renders `text` in small caps style
sf
;; Usage `@sf{some text}`
;; Renders `some text` in serif style
Section-ref
section-ref
;; Usage: `@section-ref{section-name}`
;; where `section-name` appears in a `@section[#:tag section-name]{...}` form
;; Renders as "section N", where `N` is the number assigned to the section
;; labeled with `section-name`.
;; --------------------------------------------------------------------------
;; hyperlinks
mypy
PEP-483
PEP-484
TPPBS
time.process_time
;; -----------------------------------------------------------------------------
;; performance ratio utils
get-ratios-table
ratios-table-row
ratios-row-retic/python
ratios-row-typed/retic
ratios-row-typed/python
CI?
)
(require
"bib.rkt"
"script/config.rkt"
"script/benchmark-info.rkt"
(prefix-in pi: "script/performance-info.rkt")
"script/render.rkt"
"script/util.rkt"
(only-in "script/plot.rkt"
*CONFIGURATION-X-JITTER*
*OVERHEAD-MAX*)
(only-in racket/class
class new super-new object% define/public)
(only-in racket/list
add-between
partition)
racket/format
racket/string
scribble/acmart
scribble/core
scribble/example
scribble/html-properties
scribble/latex-properties
scriblib/autobib
scriblib/figure
setup/main-collects
(except-in scribble/doclang
#%module-begin)
(only-in scribble/acmart/lang
[#%module-begin acmart:#%module-begin])
(except-in scribble/manual
title author)
(only-in scriblib/footnote
note)
(for-syntax racket/base syntax/parse))
;; =============================================================================
(define-for-syntax TECHRPT #true)
(define-syntax (if-techrpt stx)
(if TECHRPT
(syntax-case stx ()
[(_ x) #'x])
#'(void)))
(define CI? (getenv "CI"))
(define-values [EXHAUSTIVE-BENCHMARKS VALIDATE-BENCHMARKS SAMPLE-BENCHMARKS]
(if CI?
(values '() '() '())
(let ([bm* (all-benchmarks)])
(define e* (filter benchmark->karst-data bm*))
(define n* (map benchmark->name e*))
(define s* (filter (λ (bm) (and (not (memq (benchmark->name bm) '(Evolution take5))) (benchmark->sample-data bm) #t)) bm*))
(define-values [v* r*] (partition (λ (bm) (memq (benchmark->name bm) n*)) s*))
(values e* v* r*))))
(define-values [NUM-EXHAUSTIVE-BENCHMARKS NUM-VALIDATE-SAMPLES NUM-NEW-SAMPLES]
(values (length EXHAUSTIVE-BENCHMARKS)
(length VALIDATE-BENCHMARKS)
(length SAMPLE-BENCHMARKS)))
(define NUM-ITERATIONS
40)
(define NUM-BETTER-WITH-TYPES
;; See unit test for this constant below
;; Maybe better to have count per benchmark?
139975)
(define PYTHON
"Python 3.4.3")
(define SAMPLE-RATE
10)
(define NUM-SAMPLE-TRIALS
10)
(define MAX-OVERHEAD
(*OVERHEAD-MAX*))
(define EXACT-RUNTIME-XSPACE
(*CONFIGURATION-X-JITTER*))
(define SNAPL-2015-URL
"http://drops.dagstuhl.de/opus/volltexte/2015/5031/")
(define BENCHMARKS-WITH-FIRST-CLASS-FUNCTIONS
'(spectralnorm))
;; -----------------------------------------------------------------------------
(define (->benchmark x)
(define key
(cond
[(string? x) (string->symbol x)]
[(symbol? x) x]
[else (raise-argument-error '->benchmark "(or/c string? symbol?)" x)]))
(or
(for/first ([bm (in-list EXHAUSTIVE-BENCHMARKS)]
#:when (eq? key (benchmark->name bm)))
bm)
(for/first ([bm (in-list VALIDATE-BENCHMARKS)]
#:when (eq? key (benchmark->name bm)))
bm)
(for/first ([bm (in-list SAMPLE-BENCHMARKS)]
#:when (eq? key (benchmark->name bm)))
bm)
(if CI?
(format "~a" x)
(raise-argument-error '->benchmark "the name of a benchmark" x))))
(define (render-benchmark-name str)
(if CI?
(format "~a" str)
(let ([bm (if (benchmark-info? str) str (->benchmark str))])
(tt (symbol->string (benchmark->name bm))))))
(define (render-benchmark-names . str*)
(render-benchmark-names* str*))
(define (render-benchmark-names* str*)
(authors* (map render-benchmark-name str*)))
(define (warning msg . arg*)
(display "[WARNING] ")
(apply printf msg arg*)
(newline))
;; -----------------------------------------------------------------------------
(define small-number-style
(let ([autobib-style-extras
(let ([abs (lambda (s)
(path->main-collects-relative
(collection-file-path s "scriblib")))])
(list
(make-css-addition (abs "autobib.css"))
(make-tex-addition (abs "autobib.tex"))))])
(new
(class object%
(define/public (bibliography-table-style)
(make-style "AutoBibliography" autobib-style-extras))
(define/public (entry-style)
(make-style "Autocolbibentry" autobib-style-extras))
(define/public (disambiguate-date?) #f)
(define/public (collapse-for-date?) #f)
(define/public (get-cite-open) "[")
(define/public (get-cite-close) "]")
(define/public (get-group-sep) ", ")
(define/public (get-item-sep) ", ")
(define/public (render-citation date-cite i)
(make-element
(make-style "Thyperref" (list (command-extras (list (make-label i)))))
(list (number->string i))))
(define/public (render-author+dates author dates) dates)
(define (make-label i)
(string-append "autobiblab:" (number->string i)))
(define/public (bibliography-line i e)
(list (make-paragraph plain
(make-element (make-style "Autocolbibnumber"
autobib-style-extras)
(list
(make-element (make-style "label" null)
(make-label i))
"[" (number->string i) "]")))
e))
(super-new)))))
(define-cite ~cite citet generate-bibliography
#:style small-number-style)
(define (authors . a*)
(authors* a*))
(define (authors* a*)
(cond
[(null? a*)
(if CI?
"" ;; TODO remove this check?
(raise-argument-error 'authors "at least one argument" a*))]
[(null? (cdr a*))
(car a*)]
[(null? (cddr a*))
(list (car a*) " and " (cadr a*))]
[else
(add-between a* ", " #:before-last ", and ")]))
(define (sf x)
(elem #:style "sfstyle" x))
(define (sc x #:sup [sup #f])
(exact "\\textsc{\\small " x "}"
(if sup (format "$^~a$" sup) "")))
(define (exact . items)
(make-element (make-style "relax" '(exact-chars))
items))
(define appendix
(make-paragraph (make-style 'pretitle '())
(make-element (make-style "appendix" '(exact-chars)) '())))
(define etal
(exact "et~al."))
(define (id x)
(~a x))
(define ($ . items)
(apply exact (list "$" items "$")))
(define (parag . x)
(apply elem #:style "paragraph" x))
(define (python . x)
(apply exact (append (list "\n\\begin{python}\n") x (list "\n\\end{python}\n"))))
(define (pythoninline . x)
(apply exact (append (list "\\pythoninline{") x (list "}"))))
(define (pythonexternal a)
(exact (format "\\pythonexternal{~a}" a)))
(define (gnorm var)
(format "\\|~a\\|" var))
(define (definition term . defn*)
(make-paragraph plain
(list
(exact "\\vspace{1ex}\n")
(bold "Definition")
(cons (element #f (list " (" (emph term) ") ")) defn*)
(exact "\\vspace{1ex}\n"))))
(define (defn term)
term)
(define (bm-desc title author url lib . descr)
;(void (->benchmark title)) ;; assert that 'title' is the name of a benchmark
(elem
(parag title) (smaller "from " author)
(linebreak)
;ignore `url`
(format-deps lib)
(linebreak)
descr))
(define exact-runtime-category
(if CI?
(λ (name pre-bm* make-descr) "")
(let* ([cat-num (box 0)]
[get-number (λ ()
(set-box! cat-num (+ (unbox cat-num) 1))
(case (unbox cat-num) [(1) "I"] [(2) "II"] [(3) "III"] [(4) "IV"] [else (error 'get-number)]))])
(λ (name pre-bm* make-descr)
(define bm-name* (map render-benchmark-name pre-bm*))
(define perf-type (format "Trend ~a " (get-number)))
(elem (bold perf-type)
~ ~
(emph "(" name ")") ": "
(make-descr (integer->word (length pre-bm*)))
"\n"
(list "Applies to " (authors* bm-name*) "."))))))
(define (format-deps dep*)
(if (null? dep*)
"No dependencies."
(let-values ([(lib* other*) (partition lib? dep*)])
(list "Depends on "
(cond
[(null? lib*)
other*]
[(null? other*)
(format-lib lib*)]
[else
(list (format-lib lib*) ", and " other*)])
"."))))
(define (format-lib lib*)
(define n*
(for/list ([l (in-list lib*)])
(hyperlink (lib-url l) (tt (lib-name l)))))
(define l-str (if (null? (cdr lib*)) "library" "libraries"))
(list "the " (authors* n*) " " l-str))
(struct lib [name url] #:transparent)
;; Names and URLs for standard Python libraries
(define LIB-INDEX*
(list (lib "copy" "https://docs.python.org/3/library/copy.html")
(lib "fnmatch" "https://docs.python.org/3/library/fnmatch.html")
(lib "itertools" "https://docs.python.org/3/library/itertools.html")
(lib "math" "https://docs.python.org/3/library/math.html")
(lib "operator" "https://docs.python.org/3/library/operator.html")
(lib "os" "https://docs.python.org/3/library/os.html")
(lib "os.path" "https://docs.python.org/3/library/os.html#module-os.path")
(lib "random" "https://docs.python.org/3/library/random.html")
(lib "re" "https://docs.python.org/3/library/re.html")
(lib "shlex" "https://docs.python.org/3/library/shlex.html")
(lib "socket" "https://docs.python.org/3/library/socket.html")
(lib "struct" "https://docs.python.org/3/library/struct.html")
(lib "urllib" "https://docs.python.org/3/library/urllib.html")))
(define (lib-desc name . why)
(or (for/first ([l (in-list LIB-INDEX*)]
#:when (string=? name (lib-name l)))
l)
(begin
(warning "no URL for library ~a, please add to `lib-index*` in `main.rkt`" name)
(lib name "https://www.google.com"))))
(define u/p-ratio
"retic/python ratio")
(define t/u-ratio
"typed/retic ratio")
(define t/p-ratio
"typed/python ratio")
(define (deliverable [D "D"])
(define d-str
(cond
[(string? D)
D]
[(and (real? D) (positive? D))
(number->string D)]
[else
(raise-argument-error 'deliverable "(or/c positive-real? string?)" D)]))
(elem ($ d-str) "-deliverable"))
(define (approximation r s [pct #f])
(define pct-elem
(if pct
(elem ($ (~a pct)) "%-")
(elem)))
(define r-elem
(if (real? r) (~a r) r))
(define s-elem
(if (real? s) (~a s) s))
(elem pct-elem ($ r-elem ", " s-elem) "-approximation"))
(define sra
"simple random approximation")
(define (cspace [letter "C"])
(bold letter))
(define (Section-ref s)
(elem "Section" ~ (secref s)))
(define (section-ref s)
(elem "section" ~ (secref s)))
(define (axes q)
(elem (emph q) "-axes"))
(define x-axes
(axes "x"))
(define y-axes
(axes "y"))
(define (axis q)
(elem (emph q) "-axis"))
(define x-axis
(axis "x"))
(define y-axis
(axis "y"))
(define (format-url str)
(hyperlink str
(url
(remove-prefix "www."
(remove-prefix "http[^:]*://" str)))))
(define (remove-prefix rx str)
(define m (regexp-match (string-append "^" rx "(.*)$") str))
(if m (cadr m) str))
(define (percent-slower-than-typed pre-bm)
(define pi (pi:benchmark->performance-info (->benchmark pre-bm)))
(define total (pi:num-configurations pi))
(define num-good ((pi:deliverable (pi:typed/python-ratio pi)) pi))
(round (pct (- total num-good) total)))
(define (Integer->word i)
(integer->word i #:title? #t))
;; =============================================================================
;; Hyperlinks (i.e. non-academic references
(define PEP-483
(hyperlink "https://www.python.org/dev/peps/pep-0483/" (emph "PEP 483: The Theory of Type Hints")))
(define PEP-484
(hyperlink "https://www.python.org/dev/peps/pep-0484/" (emph "PEP 484: Type Hints")))
(define mypy
(hyperlink "http://mypy-lang.org/" (emph "Mypy")))
(define TPPBS
(hyperlink "http://pyperformance.readthedocs.io/" "The Python Performance Benchmark Suite"))
(define time.process_time
(hyperlink "https://docs.python.org/3/library/time.html#time.process_time" (tt "time.process_time()")))
(define DEF-APPROX
@definition[@approximation["r" "s" "95"]]{
Given @${r} samples each containing @${s} configurations chosen uniformly at random,
a @emph{@approximation["r" "s" "95"]} is a @${95\%} confidence interval for
the proportion of @deliverable{D} configurations in each sample.
})
;; =============================================================================
(module+ test
;; Test claims & expectations from the paper
;; aka extra layer of authentication
(require
rackunit
racket/set)
;; ------------------------------------------------------------------
;; TODO make this an error
(define (test-error msg . arg*)
(display "WARNING: ")
(apply printf msg arg*)
(newline))
;; ------------------------------------------------------------------
(unless CI?
(test-case "all-benchmarks"
(check set=?
(map benchmark->name EXHAUSTIVE-BENCHMARKS)
'(futen http2 slowSHA call_method call_simple chaos fannkuch float go meteor nbody nqueens pidigits pystone spectralnorm Espionage PythonFlow take5))
(check set=?
(map benchmark->name (append VALIDATE-BENCHMARKS SAMPLE-BENCHMARKS))
'(futen slowSHA chaos pystone Espionage PythonFlow sample_fsm aespython stats))))
(unless CI?
(test-case "partitioning benchmarks"
(check-equal? NUM-EXHAUSTIVE-BENCHMARKS 18)
(check-equal? NUM-VALIDATE-SAMPLES 6)
(check-equal? NUM-NEW-SAMPLES 3)))
(unless CI?
(test-case "->benchmark"
(check-equal? (car SAMPLE-BENCHMARKS) (->benchmark (benchmark->name (car SAMPLE-BENCHMARKS))))
(check-exn #rx"the name of a benchmark"
(λ () (->benchmark 'zeina)))
(check-exn #rx"string?"
(λ () (->benchmark 8)))))
(test-case "authors"
(unless CI?
(check-exn exn:fail:contract?
(λ () (authors))))
(check-equal? (authors "john doe") "john doe")
(check-equal? (authors "a" "b") (list "a" " and " "b"))
(check-equal? (authors "a" "b" "c") (list "a" ", " "b" ", and " "c")))
(unless CI?
(test-case "percent-slower-than-typed"
(check-equal? (percent-slower-than-typed "spectralnorm") 38)))
(test-case "remove-prefix"
(check-equal?
(remove-prefix "hello" "hello world")
" world")
(check-equal?
(remove-prefix "b" (remove-prefix "a" "abc"))
"c")
(check-equal?
(remove-prefix "a" (remove-prefix "b" "cba"))
"cba"))
)
#;
(module+ test ;; These tests are slow
(require
racket/set
(only-in gm-pepm-2018/script/benchmark-info
benchmark-info->python-info)
(only-in gm-pepm-2018/script/python
python-info->all-types
python-info->num-types)
(only-in gm-pepm-2018/script/performance-info
benchmark->performance-info
untyped/python-ratio
typed/retic-ratio
typed/python-ratio
unzip-karst-data
fold/karst))
(test-case "num-first-class-functions"
(check-equal?
(for/list ([bm (in-list (all-benchmarks))]
#:when (for/or ([t-str (in-set (python-info->all-types (benchmark-info->python-info bm)))])
(and t-str (regexp-match? #rx"^Function" t-str))))
(benchmark->name bm))
BENCHMARKS-WITH-FIRST-CLASS-FUNCTIONS))
;; ------------------------------------------------------------------
(define (count-lines fn)
(with-input-from-file fn
(λ () (for/sum ((ln (in-lines))) 1))))
(define (check-karst-iterations karst-file)
(fold/karst karst-file
#:init #true
#:f (λ (acc cfg num-types t*)
(unless (>= (length t*) NUM-ITERATIONS)
(test-error "configuration ~a has ~a iterations, expected at least ~a iterations (in file ~a)" cfg (length t*) NUM-ITERATIONS karst-file))
acc)))
(define (check-fully-annotated bm)
(let ([t* (python-info->all-types (benchmark-info->python-info bm))])
(when (set-member? t* #f)
(test-error "benchmark ~a is missing some type annotation(s)" (benchmark->name bm)))
(when (for/or ([t (in-set t*)]) (and t (regexp-match? #rx"Dyn" t)))
(test-error "benchmark ~a uses the Dyn type" (benchmark->name bm)))))
;; ------------------------------------------------------------------
(test-case "num-iterations:exhaustive"
(for/and ([bm (in-list EXHAUSTIVE-BENCHMARKS)])
(check-true (check-karst-iterations (unzip-karst-data (benchmark->karst-data bm))))))
(test-case "num-iterations:sample"
(for*/and ([bm (in-list (append VALIDATE-BENCHMARKS SAMPLE-BENCHMARKS))]
[d (in-list (benchmark->sample-data bm))])
(check-true (check-karst-iterations d))))
(test-case "num-iterations:python"
(for/and ([bm (in-list (append EXHAUSTIVE-BENCHMARKS VALIDATE-BENCHMARKS SAMPLE-BENCHMARKS))])
(define t* (benchmark->python-data bm))
(check-true (and t* (>= (length t*) NUM-ITERATIONS)))))
(test-case "sample-rate"
(define (check-sample-rate bm)
(define expected-num-samples (* SAMPLE-RATE (python-info->num-types (benchmark-info->python-info bm))))
(check-true
(for/and ([d (in-list (benchmark->sample-data bm))])
(define nl (count-lines d))
(unless (= nl expected-num-samples)
(test-error "file ~a has ~a lines, expected ~a lines" d nl expected-num-samples))
#true)))
(for-each check-sample-rate (append VALIDATE-BENCHMARKS SAMPLE-BENCHMARKS)))
(test-case "sample-trials"
(define (check-sample-trials bm)
(define st (length (benchmark->sample-data bm)))
(unless (= NUM-SAMPLE-TRIALS st)
(test-error "benchmark ~a has ~a samples, expected ~a samples" (benchmark->name bm) st NUM-SAMPLE-TRIALS))
(void))
(for-each check-sample-trials (append VALIDATE-BENCHMARKS SAMPLE-BENCHMARKS)))
(unless CI?
(test-case "num-better-with-types"
(check-equal?
(pi:count-better-with-types EXHAUSTIVE-BENCHMARKS)
NUM-BETTER-WITH-TYPES))
(test-case "fully-annotated"
(for-each check-fully-annotated (all-benchmarks)))
(test-case "performance-ratios-product"
(define EPS 0.0001)
(for ((bm (in-list (all-benchmarks))))
(define pi (benchmark->performance-info bm))
(check-=
(* (typed/retic-ratio pi)
(untyped/python-ratio pi))
(typed/python-ratio pi)
EPS))))
)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.