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
fc7728aab91236e1cdf3b0e1419d6a629ed9a056
6858cbebface7beec57e60b19621120da5020a48
/7/2/9.rkt
e3ef825a3a8770fa1a013632aee5e6f367d59677
[]
no_license
ponyatov/PLAI
a68b712d9ef85a283e35f9688068b392d3d51cb2
6bb25422c68c4c7717b6f0d3ceb026a520e7a0a2
refs/heads/master
2020-09-17T01:52:52.066085
2017-03-28T07:07:30
2017-03-28T07:07:30
66,084,244
2
0
null
null
null
null
UTF-8
Racket
false
false
31
rkt
9.rkt
((define (f2 y) (+ 5 y)) 4)
false
3e430043ed609cf385f4b1a6b72a348382fbc405
509969fc69c54b18347eb6c8e76cd95ce4503f6a
/interp.pc.rkt
9c39c424429ce6de9bdd0444f9307c792924d016
[]
no_license
AnkitaVikramShetty/Principles-of-Programming-Languages
8e35a5bb6510fc11229f09317cc357f9b198da02
098eda3d1ce41f336da374bc5d3f590a0d073c06
refs/heads/master
2021-01-21T21:42:52.441068
2016-02-25T07:47:13
2016-02-25T07:47:13
52,506,489
3
1
null
null
null
null
UTF-8
Racket
false
false
6,126
rkt
interp.pc.rkt
;#lang racket ;(require "parenthec.rkt") ;; STEP 10 ;; Comment out the lines #lang racket, (require “parentheC.rkt”), ;; and your invocation of main if you added it to your file. ;; And save a copy of this file named interp.pc. ;(print-as-expression #f) ;(require racket/trace) ;; GLOBAL REGISTERS (define-registers k v expression env lhs a y) ;; PROGRAM COUNTER DEFINITION (define-program-counter pc) (define-union expr (const cexp) (var n) (if test conseq alt) (mult nexp1 nexp2) (sub1 nexp) (zero nexp) (capture body) (return kexp vexp) (let exp1 body) (lambda body) (app rator rand)) (define-label value-of-cps (union-case expression expr [(const expression) (begin (set! k k) (set! v expression) (set! pc apply-k) )] [(mult x1 x2) (begin (set! k (cont-expr_outer-k-mult x2 env k)) (set! expression x1) (set! env env) (set! pc value-of-cps))] [(sub1 x) (begin (set! k (cont-expr_constructor-sub1 k)) (set! expression x) (set! env env) (set! pc value-of-cps))] [(zero x) (begin (set! k (cont-expr_constructor-zero k)) (set! expression x) (set! env env) (set! pc value-of-cps))] [(if test conseq alt) (begin (set! k (cont-expr_constructor-if conseq alt env k)) (set! expression test) (set! env env) (set! pc value-of-cps))] [(capture body) (begin (set! env (env-expr_extend-env k env)) (set! expression body) (set! k k) (set! pc value-of-cps))] [(return k-exp v-exp) (begin (set! k (cont-expr_constructor-return v-exp env)) (set! expression k-exp) (set! env env) (set! pc value-of-cps))] [(let e body) (begin (set! k (cont-expr_constructor-let body env k)) (set! expression e) (set! env env) (set! pc value-of-cps))] [(var expression) (begin (set! env env) (set! y expression) (set! k k) (set! pc apply-env) )] [(lambda body) (begin (set! v (closure-expr_closure body env)) (set! k k) (set! pc apply-k) )] [(app rator rand) (begin (set! k (cont-expr_outer-k-app rand env k)) (set! expression rator) (set! env env) (set! pc value-of-cps))])) ;; CLOSURE CONSTRUCTOR #;(define closure (lambda (body env) `(closure ,body ,env))) (define-union closure-expr (closure body^ env^)) (define-label apply-closure (union-case lhs closure-expr [(closure body^ env^) (begin (set! env (env-expr_extend-env a env^)) (set! expression body^) (set! k k) (set! pc value-of-cps))])) ;; ENVIRONMENT CONSTRUCTORS #;(define empty-env (lambda () `(empty-env))) #;(define extend-env (lambda (a^ env^) `(extend-env ,a^ ,env^))) (define-union env-expr (empty-env) (extend-env a^ env^)) (define-label apply-env (union-case env env-expr [(extend-env a^ env^) (if (zero? y) (begin (set! k k) (set! v a^) (set! pc apply-k) ) (begin (set! env env^) (set! k k) (set! y (sub1 y)) (set! pc apply-env) ))] [(empty-env) (error 'value-of-cps "unbound identifier")])) ;; CONTINUATION CONSTRUCTORS #;(define inner-k-mult (lambda (v^ k^) `(inner-k-mult ,v^ ,k^))) #;(define outer-k-mult (lambda (x2^ env^ k^) `(outer-k-mult ,x2^ ,env^ ,k^))) #;(define constructor-sub1 (lambda (k^) `(constructor-sub1 ,k^))) #;(define constructor-zero (lambda (k^) `(constructor-zero ,k^))) #;(define constructor-if (lambda (conseq^ alt^ env^ k^) `(constructor-if ,conseq^ ,alt^ ,env^ ,k^))) #;(define constructor-return (lambda (v-exp^ env^) `(constructor-return ,v-exp^ ,env^))) #;(define inner-k-app (lambda (c^ k^) `(inner-k-app ,c^ ,k^))) #;(define outer-k-app (lambda (rand^ env^ k^) `(outer-k-app ,rand^ ,env^ ,k^))) #;(define constructor-let (lambda (body^ env^ k^) `(constructor-let ,body^ ,env^ ,k^))) #;(define empty-k (lambda () `(empty-k))) (define-union cont-expr (inner-k-mult v^ k^) (outer-k-mult x2^ env^ k^) (constructor-sub1 k^) (constructor-zero k^) (constructor-if conseq^ alt^ env^ k^) (constructor-return v-exp^ env^) (inner-k-app c^ k^) (outer-k-app rand^ env^ k^) (constructor-let body^ env^ k^) (empty-k jumpout)) (define-label apply-k (union-case k cont-expr [(empty-k jumpout) (dismount-trampoline jumpout)] [(inner-k-mult v^ k^) (begin (set! v (* v^ v)) (set! k k^) (set! pc apply-k) )] [(outer-k-mult x2^ env^ k^) (begin (set! k (cont-expr_inner-k-mult v k^)) (set! expression x2^) (set! env env^) (set! pc value-of-cps))] [(constructor-sub1 k^) (begin (set! k k^) (set! v (sub1 v)) (set! pc apply-k) )] [(constructor-zero k^) (begin (set! k k^) (set! v (zero? v)) (set! pc apply-k) )] [(constructor-if conseq^ alt^ env^ k^) (if v (begin (set! expression conseq^) (set! env env^) (set! k k^) (set! pc value-of-cps)) (begin (set! expression alt^) (set! env env^) (set! k k^) (set! pc value-of-cps)))] [(constructor-return v-exp^ env^) (begin (set! expression v-exp^) (set! env env^) (set! k v) (set! pc value-of-cps))] [(inner-k-app c^ k^) (begin (set! lhs c^) (set! a v) (set! k k^) (set! pc apply-closure) )] [(outer-k-app rand^ env^ k^) (begin (set! k (cont-expr_inner-k-app v k^)) (set! expression rand^) (set! env env^) (set! pc value-of-cps))] [(constructor-let body^ env^ k^) (begin (set! env (env-expr_extend-env v env^)) (set! expression body^) (set! k k^) (set! pc value-of-cps))])) ;; MAIN (define-label main (begin (set! expression (expr_let (expr_lambda (expr_lambda (expr_if (expr_zero (expr_var 0)) (expr_const 1) (expr_mult (expr_var 0) (expr_app (expr_app (expr_var 1) (expr_var 1)) (expr_sub1 (expr_var 0))))))) (expr_mult (expr_capture (expr_app (expr_app (expr_var 1) (expr_var 1)) (expr_return (expr_var 0) (expr_app (expr_app (expr_var 1) (expr_var 1)) (expr_const 4))))) (expr_const 5)))) (set! env (env-expr_empty-env)) (set! pc value-of-cps) (mount-trampoline cont-expr_empty-k k pc) (printf "Fact 5: ~s\n" v)))
false
90a7172c879185a9f9ca788481749c4ca44d8eaf
39551ef8b2a615c31885b907ed95d2c49247317a
/S2/Funktionale/demos/demo6a.rkt
acecb6559cff0b8c3a2eaeb5f40f3c3df86e4777
[]
no_license
ariez-xyz/LectureNotes
cfbc07d60a39719971f5073f513f467198059cf2
5cba22f5c3c3554d02897e0aca646f05d3e9882f
refs/heads/master
2023-06-09T20:20:03.147705
2021-07-08T20:52:16
2021-07-08T20:52:16
null
0
0
null
null
null
null
UTF-8
Racket
false
false
4,992
rkt
demo6a.rkt
#lang racket ;helpers;;; (define (square x) (* x x)) (define (smallest-divisor n) (find-divisor n 2)) (define (find-divisor n test-divisor) (cond ((> (square test-divisor) n) n) (( divides? test-divisor n) test-divisor) (else (find-divisor n (+ test-divisor 1))))) (define (divides? a b) (= (remainder b a) 0)) (define (prime? n) (= n (smallest-divisor n))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; stream motivation (define (sum-primes a b) (define (iter count accum) (cond ((> count b) accum) ((prime? count) (iter (+ count 1) (+ count accum))) (else (iter (+ count 1) accum)))) (iter a 0)) (define (sum-primes2 a b [accum 0]) (cond ((> a b) accum) ((prime? a) (sum-primes2 (+ a 1) b (+ a accum))) (else (sum-primes2 (+ a 1) b accum)))) (define (sum-primes-ci a b) (foldr + 0 (filter prime? (range a (+ b 1))))) ;2nd prime number (car (cdr (filter prime? (range 1 10000)))) ;give me the first prime number > 100,000,000 ;(car (filter prime? (range 100000000 ?????))) ;what value should I put here? ;too small: I won't find a prime number: ;(car (filter prime? (range 100000000 100000005))) ;too big: It will take a while: (car (filter prime? (range 100000000 100100000))) ;;;; STREAMS (presented in the lecture) ;;;;; ;(require racket/stream) ;;in older versions ;(define s0 (stream-cons 6 7)) ;(stream-first (stream-cons 1 2)) ;(define sr (stream-rest (stream-cons 1 2))) (define s (stream 1 2 3)) ;(stream-first s) (stream-first s) (stream-first (stream-rest s)) (stream-length s) (stream-ref s 0) (stream-empty? s) ;ref (define (mystream-ref s n) (if (= n 0) (stream-first s) (stream-ref (stream-rest s) (- n 1)))) ;map (define (mystream-map proc s) (if (stream-empty? s) empty-stream (stream-cons (proc (stream-first s)) (mystream-map proc (stream-rest s))))) ;filter (define (mystream-filter p s) (cond ((stream-empty? s) empty-stream) ((p (stream-first s)) (stream-cons (stream-first s) (mystream-filter p (stream-rest s)))) (else (mystream-filter p (stream-rest s))))) ;range (enumerate) (define (mystream-range low high) (if (> low high) empty-stream (stream-cons low (mystream-range (+ low 1) high)))) ;helper-procedure: display ;(define (display-stream s) ; (stream-for-each displayln s)) (define (display-stream s) ;TODO: improve (if (stream-empty? s) "...?" (~a (stream-first s) "," (display-stream (stream-rest s))))) (display-stream (stream-filter even? s)) ;;;;;;; (define do (delay (+ 10 10))) do (force do) ;first try (won't work) (define (s-cons a b) (cons a (delay b))) (s-cons 1 (sleep 2)) ;;;;;;;;;;;;;;;;; ;(define xxx (stream-cons 1 2)) #| ;a define doesn't make sense. we need a special-form using define-syntax-rule (define (mystream-cons a b) (cons a (delay b))) ; TODO...... delay |# (define-syntax-rule (mystream-cons a b) (cons a (delay b))) ; TODO...... delay (define mys (mystream-cons 1 2)) (define (mystream-first s) (car s)) (mystream-first mys) (define (mystream-rest s) (force (cdr s))) ; TODO....... force (mystream-rest mys) ;;;;;;;; streams in action ;;; (in-range 10) (time (stream-first (stream-rest (stream-filter prime? (in-range 10000 1000000))))) ;1,000,000 ;with lists (time (first (rest (filter prime? (range 10000 600000))))) ;note the reduced range ! ;600,000 ;;; Implementation of delay and force #| ;a define doesn't make sense. we need a special-form using define-syntax-rule (define (mydelay exp) (λ() exp)) |# (define-syntax-rule (mydelay exp) (λ() exp)) (define (myforce delayedObject) (delayedObject)) ;;;; see demo6b.rkt for a 100% self-made stream implementation !!!!!!!!! ;;;; infinite streams! ;helper function (define (display-stream-limit s limit) (define (d s lim) (if (or (= lim 0) (stream-empty? s)) "...?" (~a (stream-first s) "," (d (stream-rest s) (- lim 1))))) (d s limit)) (define (integers-starting-from n) (stream-cons n (integers-starting-from (+ n 1)))) (define integers (integers-starting-from 1)) (display-stream-limit (stream-filter even? integers) 20) (define (fibgen a b) (stream-cons a (fibgen b (+ a b)))) (define fibs (fibgen 0 1)) (display-stream-limit fibs 10) (define ones (stream-cons 1 ones)) ;;;;; more examples (define (divisible? x y) (= (remainder x y) 0)) ;stream of integers that are not divisible by 7 (define no-seven (stream-filter (λ(x) (not (divisible? x 7))) integers)) ;very nice example: Sieve of eratosthenes ;;;;;;;bank account (define (stream-withdraw balance amount-stream) (stream-cons balance (stream-withdraw (- balance (stream-first amount-stream)) (stream-rest amount-stream)))) (define sAccount (stream-withdraw 100 (stream 20 30))) (display-stream-limit sAccount 3)
true
df4e21c4c1061093d30351ea733f3243bb3a0928
e92ed378764664fffe617b78aece143cb5209d01
/scribblings/simple-http.scrbl
5fa131403ada824e74c5673e3a96bd0e005fefbd
[ "BSD-3-Clause" ]
permissive
DarrenN/simple-http
93f7ce39785c27394a5bb0c65b4457bf96506394
cf15bfd0c71f3dd3189417dd1a7a34fc6bfad557
refs/heads/master
2021-08-07T06:55:07.486816
2020-06-13T16:54:18
2020-06-13T16:54:18
82,603,699
25
7
BSD-3-Clause
2019-10-09T23:49:19
2017-02-20T21:18:38
Racket
UTF-8
Racket
false
false
11,130
scrbl
simple-http.scrbl
#lang scribble/manual @require[racket scribble/eval simple-http json xml @for-label[simple-http json xml racket]] @(define EVAL (make-base-eval #:lang 'racket '(require simple-http json))) @title{simple-http} @author[(author+email "Darren Newton" "[email protected]")] @defmodule[simple-http] Very small library for making HTTP requests. Attempts to handle the server response and convert into the correct data type based on Content-Type headers. Heavily inspired and influenced by @hyperlink["https://github.com/jackfirth/racket-request"]{racket-request}. The general use case for this is when you want to make repeated requests to an API. You can setup a requester with the relevant auth headers and base URL, then make requests using the available procedures, @racket[get], @racket[put], etc. Responses are parsed into @racket[jsexpr?], @racket[xexpr?], or @racket[string?] depending on which @racket[requester?] is used. @bold{Example JSON request and response:} @#reader scribble/comment-reader (racketblock ; Setup a json-request using SSL and pointed at httpbin.org (define httpbin-org (update-headers (update-ssl (update-host json-requester "httpbin.org") #t) '("Authorization: 8675309"))) ; Query params for the request (define params '((foo . "12") (bar . "hello"))) ; Make a GET to https://httpbin.org/get?foo=12&bar=hello (define response (get httpbin-org "/get" #:params params))) @bold{Response:} @racketblock[ (json-response "HTTP/1.1 200 OK" '#hasheq((X-Powered-By . ("Flask")) (Access-Control-Allow-Credentials . ("true")) (Connection . ("close")) (Content-Type . ("application/json")) (Via . ("1.1 vegur")) (Date . ("Sun, 14 May 2017 00:18:16 GMT")) (X-Processed-Time . ("0.000797033309937")) (Access-Control-Allow-Origin . ("*")) (Server . ("meinheld/0.6.1")) (Content-Length . ("408"))) '#hasheq((url . "https://httpbin.org/get?foo=12&bar=hello") (headers . #hasheq((Authorization . "8675309") (Host . "httpbin.org") (Connection . "close") (Content-Type . "application/json") (Accept . "application/json") (Accept-Encoding . "gzip") (User-Agent . "Racket/6.8 (net/http-client)"))) (origin . "255.255.255.255") (args . #hasheq((bar . "hello") (foo . "12"))))) ] @section{Requesters} Requests are made by creating requesters and using functions to update them with relevant data such as base url, use SSL, etc. @defstruct[ requester ([host string?] [headers hash?] [port integer?] [ssl boolean?] [type symbol?]) #:transparent]{ Stores information about the types of requests to make (headers). You usually don't need to use this directly, pre-loaded requesters are provided for you. } @deftogether[( @defidform[html-requester] @defidform[json-requester] @defidform[text-requester] @defidform[xml-requester] )]{ Pre-made requesters for requesting specific formats. Requests made with these will send the appropriate Accept and Content-Type headers. Responses will also be parsed according to their request type. } @defproc[(update-host [requester requester?] [host string?]) requester?]{ Change the host string in a requester. Returns the updated requester. } @defproc[(update-port [requester requester?] [port integer?]) requester?]{ Change the port in a requester. This overrides the default port, which is 443 for SSL requests or 80 otherwise. Returns the updated requester. } @defproc[(update-ssl [requester requester?] [ssl boolean?]) requester?]{ Change whether the requester should make SSL requests or not. When set to #t requests will be changed to https. Returns the updated requester. } @defproc[(update-headers [requester requester?] [headers (listof string?)]) requester?]{ Merges @racket[headers] into the existing headers in the requester and returns the requester. Any headers passed to the function will overwrite any existing headers in the @racket[requester?] with the same header key. @racket[(update-headers req '("Authorization: 8675309" "x-foo: oof"))] } @defproc[(authenticate-basic [requester requester?] [username string?] [password string?]) requester?]{ Constructs an http-basic header from @racket[username] and @racket[password], and then merges that header into the headers of the @racket[requester] using @racket[update-headers]. @racket[(authenticate-basic req "[email protected]" "opensesame")] } @section{Making requests} Requests are made using requesters to determine how data should be sent and received. Responses are returned as structs with their data encoded based on the requester used. If the server returns an error code a @racket[exn:fail:network:http:error?] will be raised. If the data returned from the server is in a different format than requested or cannot be properly parsed then a @racket[exn:fail:network:http:read?] will be raised. @defproc[(get [requester requester?] [uri string?] [#:params params (listof pair?) '()]) (or/c html-response? json-response? text-response? xml-response?)]{ Makes a @racket[GET] request using the provided @racket[requester]. @racket[#:params] will be combined onto the URL as query parameters. Responses are structs. @racketblock[(get (update-host json-requester "httpbin.org") "/get" #:params '((foo . "12") (bar . "quux")))] } @defproc[(post [requester requester?] [uri string?] [#:data data any/c #f] [#:params params (listof pair?) '()]) (or/c html-response? json-response? text-response? xml-response?)]{ Makes a @racket[POST] request using the provided @racket[requester]. @racket[#:params] will be combined onto the URL as query parameters. @racket[#:data] is sent to the server in the body of the request. Responses are structs. @racketblock[(post (update-host json-requester "httpbin.org") "/post" #:data (jsexpr->string (hasheq 'colossal-squid "drumbones")) #:params '((sort . "asc") (filter . "hits")))] } @defproc[(put [requester requester?] [uri string?] [#:data data any/c #f] [#:params params (listof pair?) '()]) (or/c html-response? json-response? text-response? xml-response?)]{ Makes a @racket[PUT] request using the provided @racket[requester]. @racket[#:params] will be combined onto the URL as query parameters. @racket[#:data] is sent to the server in the body of the request. Responses are structs. @racketblock[(put (update-host json-requester "httpbin.org") "/put" #:data (jsexpr->string (hasheq 'white-zombie "thunderkiss")) #:params '((sort . "asc")))] } @defproc[(patch [requester requester?] [uri string?] [#:data data any/c #f] [#:params params (listof pair?) '()]) (or/c html-response? json-response? text-response? xml-response?)]{ Makes a @racket[PATCH] request using the provided @racket[requester]. @racket[#:params] will be combined onto the URL as query parameters. @racket[#:data] is sent to the server in the body of the request. Responses are structs. @racketblock[(patch (update-host json-requester "httpbin.org") "/patch" #:data (jsexpr->string (hasheq 'white-zombie "thunderkiss")) #:params '((sort . "asc")))] } @defproc[(delete [requester requester?] [uri string?] [#:params params (listof pair?) '()]) (or/c html-response? json-response? text-response? xml-response?)]{ Makes a @racket[DELETE] request using the provided @racket[requester]. @racket[#:params] will be combined onto the URL as query parameters. Responses are structs. @racketblock[(delete (update-host json-requester "httpbin.org") "/delete" #:params '((sort . "asc")))] } @section{Responses} @deftogether[( @defstruct[ html-response ([status string?] [headers hash?] [body xexpr?]) #:transparent] @defstruct[ json-response ([status string?] [headers hash?] [body jsexpr?]) #:transparent] @defstruct[ text-response ([status string?] [headers hash?] [body string?]) #:transparent] @defstruct[ xml-response ([status string?] [headers hash?] [body xexpr?]) #:transparent] )]{ Response bodies are decoded into a form determined by the requester used to make requests. If the response comes back in a form that can't be processed or throws an error duing processing then a @racket[exn:fail:network:http:read?] exception will be raised. @racket[status] is a @racket[string?] such as @racket["HTTP/1.1 200 OK"]. @racket[headers] are a key value representation of the response headers: @racketblock[ #hasheq((Host . "httpbin.org") (Connection . "close") (Content-Type . "application/json") (Accept . "application/json")) ] } @deftogether[( @defproc[(get-status [resp (or/c html-response? json-response? text-response? xml-response?)]) (or/c string? void?)] @defproc[(get-status-code [resp (or/c html-response? json-response? text-response? xml-response?)]) (or/c number? void?)] @defproc[(get-response-type [resp (or/c html-response? json-response? text-response? xml-response?)]) (or/c "html" "json" "text" "xml")] @defproc[(get-headers [resp (or/c html-response? json-response? text-response? xml-response?)]) (hash/c symbol? (listof string?))] )]{ These helper functions extract parts of responses based on their type. } @section{Exceptions} @defstruct[ exn:fail:network:http:read ([message string?] [continuation-marks continuation-mark-set?] [type symbol?]) #:transparent]{ Raised when a response is either the wrong format (ex: HTML returned for a JSON request) or malformed and cannot be parsed by the relevant reader. @racket[type] is a symbol to let you know which requester made the request, such as @racket['json], etc. } @defstruct[ exn:fail:network:http:error ([message string?] [continuation-marks continuation-mark-set?] [code number?] [type symbol?]) #:transparent]{ Raised when the server responds with an error code. @racket[code] is the numeric error code returned by the server. @racket[type] is a @racket[symbol?] letting you know which requester made the request (ex: @racket['json]). }
false
fe11224c8732ccc6a99ff5ce03089327d3700fbc
caf92e9cc39d4b123a1bfd8c2d0bed2f2c209142
/week6/variables.rkt
82bd9720f7334dda22145242028173a381196f47
[]
no_license
sergiovasquez122/Programming-Languages-Coursera-Solutions
e02b28d8c36da429d621c46e9796b77d072c1e79
3aeef4471c66a57e3ac940f4d284d98fc88b86f4
refs/heads/main
2023-04-09T20:08:01.216873
2021-04-26T03:12:53
2021-04-26T03:12:53
326,312,125
0
0
null
null
null
null
UTF-8
Racket
false
false
964
rkt
variables.rkt
#lang racket ; Interpreters so far have been for language without variables ; - no let-expressions, functions-with-arguments, etc. ; An evironment is a mapping from variables to values ; - Only ever put pairs of strings and values in the evironment ; Evaluation takes place in an evironment ; We'll have a list of pairs ; - Evironment passed as argument to interpreter helper function ; - A variable expresssion looks up the variable in the environment ; - Most subexpressions use same environment as outer expressions ; - A let-expresssion evaluates it body in a larger environment ; So now a recursive heper function has all the intersting stuff. ; (define (eval-under-env e env) ;; (cond _ ; case for each kind of expression ; recursive calls must "pass down" correct environment ; The eval-exp just calls eval-under-env with same expressions and the empty environment ; eval-under-env would be helper function one could define locally inside eval-exp
false
f626b4a2bb56802d3dd4f50b15a953041ad26f9e
b08b7e3160ae9947b6046123acad8f59152375c3
/Programming Language Detection/Experiment-2/Dataset/Train/Racket/pattern-matching.rkt
8596084821d45cd9525ca9c328be3a442d6f089c
[]
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
1,248
rkt
pattern-matching.rkt
#lang racket ;; Using short names to make the code line up nicely (struct N (color left value right) #:prefab) (define (balance t) (match t [(N 'B (N 'R (N 'R a x b) y c) z d) (N 'R (N 'B a x b) y (N 'B c z d))] [(N 'B (N 'R a x (N 'R b y c)) z d) (N 'R (N 'B a x b) y (N 'B c z d))] [(N 'B a x (N 'R (N 'R b y c) z d)) (N 'R (N 'B a x b) y (N 'B c z d))] [(N 'B a x (N 'R b y (N 'R c z d))) (N 'R (N 'B a x b) y (N 'B c z d))] [else t])) (define (insert x s) (define (ins t) (match t ['empty (N 'R 'empty x 'empty)] [(N c l v r) (cond [(< x v) (balance (N c (ins l) v r))] [(> x v) (balance (N c l v (ins r)))] [else t])])) (match (ins s) [(N _ l v r) (N 'B l v r)])) (define (visualize t0) (let loop ([t t0] [last? #t] [indent '()]) (define (I mid last) (cond [(eq? t t0) ""] [last? mid] [else last])) (for-each display (reverse indent)) (printf "~a~a[~a]\n" (I "\\-" "+-") (N-value t) (N-color t)) (define subs (filter N? (list (N-left t) (N-right t)))) (for ([s subs] [n (in-range (sub1 (length subs)) -1 -1)]) (loop s (zero? n) (cons (I " " "| ") indent))))) (visualize (for/fold ([t 'empty]) ([i 16]) (insert i t)))
false
229e67a2143ce48b7c50855ac9d5b8a6384c377f
a2382cc68a29984b21ad2bd8a43048b2776472a2
/test/helpers.rkt
cf41c07e799c055734d43a31c6ca963f0e31ca69
[]
no_license
JacobGinsparg/yomi-lang
5d0710554c53d15db25b27db1c02e44a6aa34648
24fd2b282d341ce698f75fdd716c97cb17670868
refs/heads/master
2021-01-25T10:01:01.379800
2018-04-17T03:12:39
2018-04-17T03:12:39
123,335,388
0
0
null
2018-04-17T03:12:40
2018-02-28T19:58:33
null
UTF-8
Racket
false
false
1,356
rkt
helpers.rkt
#lang racket (require (for-syntax syntax/parse rackunit) "../lib/mock-device.rkt" "../lib/yomi-lib.rkt" rackunit) (provide ensure-setup ensure-teardown with-mock-device check-received-inputs check-def-failure check-combo-inputs) ; Safely setup mock device (define (ensure-setup) (when is-set-up (teardown)) (setup)) ; Safely teardown mock device (define (ensure-teardown) (when is-set-up (teardown))) ; Wrap expressions in mock device setup/teardown (define-syntax (with-mock-device stx) (syntax-parse stx [(_ stuff ...) #'(begin (ensure-setup) stuff ... (ensure-teardown))])) ; Perform a move and check that its inputs are correct (define (check-received-inputs expected action) (with-mock-device (perform-move action) (check-equal? received-inputs expected))) ; Expand the macro and assert that it fails with the given message (define-syntax check-def-failure (syntax-parser [(_ def msg) (check-exn (regexp (syntax->datum #'msg)) (lambda () (local-expand #'def 'module-begin null))) #'(void)])) (define (check-combo-inputs expected action) (with-mock-device (perform-combo-for-test action) (check-equal? received-inputs expected)))
true
8958e33a4b0df07cdd5331e06bc17deb53c5dbcc
9e5f7de7265162c38f3e482266b819ede76113ba
/Assignment 3/a3q2.rkt
22f2f0982cfe5f02331f2b8a3d1e306b6662472b
[ "Apache-2.0" ]
permissive
xiaroy/Comp-3007
b34eb4859115415290302a9b4fb46c6bba9d173b
4d65c7692ea69562fd94cd9a2f5ec28e9d1048fb
refs/heads/master
2021-04-27T00:48:42.762857
2018-02-23T19:06:15
2018-02-23T19:06:15
122,661,050
0
2
null
null
null
null
UTF-8
Racket
false
false
973
rkt
a3q2.rkt
;Name:Roy Xia ;Student Number: 101009419 ;Question: 2 ;a (define (special-cons x y) (lambda (m) (m x y))) (define (special-car z) (z (lambda (p q) p))) (define (special-cdr z) (z (lambda (p q) q))) ;b (define (triple x y z) (lambda (m) (m x y z))) (define (first z) (z (lambda (p q r) p))) (define (second z) (z (lambda (p q r) q))) (define (third z) (z (lambda (p q r) r))) ;testing ;a (write "Test a") (newLine) (write "Test 1 car: ( 1 2 )") (newLine) (write "Expected 1") (newLine) (special-car (special-cons 1 2)) (write "Test 2 cdr: ( 1 2 )") (newLine) (write "Expected 2") (newLine) (special-cdr (special-cons 1 2)) ;b (write "Test b") (newLine) (write "Test 1 first: ( 1 2 3 )") (newLine) (write "Expected 1") (newLine) (first (triple 1 2 3)) (write "Test 2 second: ( 1 2 3 )") (newLine) (write "Expected 2") (newLine) (second (triple 1 2 3)) (write "Test 2 third: ( 1 2 3 )") (newLine) (write "Expected 3") (newLine) (third (triple 1 2 3))
false
e3259fcb8d7a687e69ea46135a0d366dd582c5c9
205af7cd452afd60d88319ec5eb7bcee058cae07
/escape.rkt
0caf94e77571648439feb9ac454328336f9f96b6
[]
no_license
d3zd3z/racksure
b992d21dd163e7a3cb8e7aa1d93e08cfce100d4f
04c9782c71ac11eccf665cf8bce7711d98addfb9
refs/heads/master
2020-03-25T00:41:35.713638
2018-08-08T04:37:31
2018-08-08T04:37:31
143,200,177
0
0
null
null
null
null
UTF-8
Racket
false
false
3,000
rkt
escape.rkt
#lang racket (provide (contract-out ;; Return a new bytes that will be a quoted-printable version of ;; the input bytes. (escape [-> bytes? bytes?]) ;; Invert the above escape procedure, producing the original byte string. (unescape [-> bytes? bytes?]))) ;;; File/path names in Posix systems are treated as a plain sequence ;;; of bytes. To make this safe for both filenames and link targets, ;;; we use a simple quoted-printable type of encoding, which is ;;; defined by printable? below. ;;; Decide if the character needs to be escaped. (define (printable? b) (define ch (integer->char b)) (and (char<=? #\! ch #\~) (not (char=? ch #\=)) (not (char=? ch #\[)) (not (char=? ch #\])))) (define (escape text) (define slen (bytes-length text)) (define new-len slen) (for ([ch (in-bytes text)]) (unless (printable? ch) (set! new-len (+ new-len 2)))) (define result (make-bytes new-len)) (let loop ([spos 0] [dpos 0]) (if (= spos slen) result (let ([ch (bytes-ref text spos)]) (cond [(printable? ch) (bytes-set! result dpos ch) (loop (add1 spos) (add1 dpos))] [else (bytes-set! result dpos 61) ; #\= (bytes-set! result (+ dpos 1) (bytes-ref hex-digits (arithmetic-shift ch -4))) (bytes-set! result (+ dpos 2) (bytes-ref hex-digits (bitwise-and ch 15))) (loop (add1 spos) (+ dpos 3))]))))) (define hex-digits #"0123456789abcdef") ;;; Unescape. (define (unescape text) (define text-len (bytes-length text)) (define len (let loop ([pos 0] [len 0]) (cond [(= pos text-len) len] [(> pos text-len) (error "Invalid quote in escaped text" text)] [else (let ([ch (bytes-ref text pos)]) (if (= ch 61) (loop (+ pos 3) (add1 len)) (loop (add1 pos) (add1 len))))]))) (define result (make-bytes len)) (let loop ([src 0] [dest 0]) (cond [(= src text-len) result] [else (let ([ch (bytes-ref text src)]) (if (= ch 61) (let () (define a (unhex-byte (bytes-ref text (add1 src)))) (define b (unhex-byte (bytes-ref text (+ src 2)))) (bytes-set! result dest (bitwise-ior (arithmetic-shift a 4) b)) (loop (+ src 3) (add1 dest))) (begin (bytes-set! result dest ch) (loop (add1 src) (add1 dest)))))]))) (define (unhex-byte a) (cond [(<= 48 a 57) (- a 48)] [(<= 65 a 70) (- a 55)] [(<= 97 a 102) (- a 87)] [else (error "Invalid hex digit" a)]))
false
5731cf1c279082c72d9a1d380e20ad9f3727196c
ac0c749388bc6c01f081538b1cea919b524041b8
/cse507-sources/hw2/uf/uf.rkt
dac7ddec5b622905fe511c2d658bc750703568fe
[]
no_license
cal-poly-csc530-2214/rosette-123-805-kitchen
aa55ba2ad7b6815a2055bf95523734255783d13b
184dc6e7382420006da90e31a0dbf7dc4f6b442e
refs/heads/master
2023-05-03T08:25:04.432973
2021-05-28T16:47:24
2021-05-28T16:47:24
369,000,240
0
1
null
null
null
null
UTF-8
Racket
false
false
1,372
rkt
uf.rkt
#lang rosette (provide (all-defined-out)) ; This module should provide UF-based implementations of ; all procedures that need to be abstracted in order to ; improve the performance of the queries in matrix.rkt. ; If you want to replace a Rosette procedure, such as -, ; with a UF, all you need to do is re-define the procedure ; - in this file. Doing so causes every call to - in ; a module that imports uf.rkt to refer to your custom - ; definition. For example, uncommenting the following definition ; would cause every call to - in matrix.rkt to be refer to this -. ; ; (define (- a b) ; (define-symbolic uf- (~> real? real? real?)) ; (uf- a b)) ; ; So evaluating (- 1 2) would return the symbolic value (app uf- 1 2), ; which represents the application of the uninterpreted function uf- ; to the inputs 1, 2. ; ; Note that many Rosette procedures take a variable number of arguments. ; Your re-defined procedure should provid the same interface, or the code ; that calls it may crash. For example, Rosette's - takes as input 1 or ; more arguments, so the above definition would only work for clients that ; call - with 2 arguments. You might want to read the docs to find out the ; arity of the procedure proc that you want to abstract with a UF. ; ; See https://docs.racket-lang.org/rosette-guide/sec_UF.html for more ; details on Rosette's support for UFs.
false
0c422e262995301a3eb308ec2ecd09ebff24eb6e
f1e530da5c62986635c3a24ee2b7d5c0fc8cff5f
/main.rkt
6d2a36286cf83e98a5737bb73c9f390a0c5a144c
[]
no_license
david-vanderson/warp
3172892fc2d19ae9e2f19fa026e2d7cdf4e59a86
cdc1d0bd942780fb5360dc6a34a2a06cf9518408
refs/heads/master
2021-01-23T09:30:16.887310
2018-09-30T03:52:59
2018-09-30T03:52:59
20,066,539
24
1
null
null
null
null
UTF-8
Racket
false
false
1,597
rkt
main.rkt
#lang racket/base (require racket/cmdline "defs.rkt" "server.rkt" "client.rkt") (define show-help #f) (define port PORT) (define address #f) (define run-server? #f) (define g #f) (define combined? #f) (define name "player") (command-line #:program "warp" #:usage-help "Runs the warp game client (or server with -s)" #:once-each [("-c" "--combined") "Run combined server and client for testing" (set! combined? #t)] [("-a" "--address") a "Specify ip address to use for tcp" (set! address a)] [("-p" "--port") p "Specify port to use for tcp" (set! port p)] [("-g" "--nogui") ng "Run # of headless clients for testing" (set! g (string->number ng))] [("-n" "--name") n "Set client base name for -g" (set! name n)] [("-s" "--server") "Run server" (set! run-server? #t)]) (cond [combined? ; note that start-client immediately changes the server? parameter to #f ; so start the server thread first (need to fix it at some point) (thread (lambda () (start-server))) (start-client port #:ip address)] [run-server? (start-server port)] [g (for ((i g)) (start-client port #:ip address #:name (string-append name "-" (number->string i)) #:gui? #f #:new-eventspace? #t)) (sync never-evt)] [else (start-client port #:ip address)])
false
a9cb92813c3e3ed3fb1524d544ac07ea8da173d0
662e55de9b4213323395102bd50fb22b30eaf957
/dissertation/scrbl/validate-sample/avg/quadU-avg-dist.rktd
48be7103f734c6bc878a0184abbca488bac642d7
[]
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
165
rktd
quadU-avg-dist.rktd
;; This file was generated by the `with-cache` library on 2020-12-18 (((take5 tetris synth quadU quadT)) (3) 0 () 0 () () (h - (equal) (1 . 24) (2 . 726) (3 . 50)))
false
735556b72df9478eed9a974cd77c34c9c7b59724
6858cbebface7beec57e60b19621120da5020a48
/8/1/6/2.rkt
021161f72c050632007bbb3dee83ce91a6764d39
[]
no_license
ponyatov/PLAI
a68b712d9ef85a283e35f9688068b392d3d51cb2
6bb25422c68c4c7717b6f0d3ceb026a520e7a0a2
refs/heads/master
2020-09-17T01:52:52.066085
2017-03-28T07:07:30
2017-03-28T07:07:30
66,084,244
2
0
null
null
null
null
UTF-8
Racket
false
false
123
rkt
2.rkt
(define (lookup [for : symbol] [env : Env]) : Location ...) (define (fetch [loc : Location] [sto : Store]) : Value ...)
false
7dd46621f1eb9df481319a4b719832c77c45d510
f58e5513606af04b35d4093e4b152bda32cdbd6a
/private/model-authors.rkt
eeb9c6c73a02cd54aa493e7199253401ba63ab50
[ "BSD-3-Clause" ]
permissive
DarrenN/nautilus
e5f9e1c14f924b8d30b3a5644ffa1e8dfb49540b
a9d549a0dbbf0eb6e9c7cc0f9b5c08ab313bd2b6
refs/heads/master
2021-03-27T14:07:49.657787
2017-09-12T00:58:41
2017-09-12T00:58:41
95,302,907
4
0
null
2017-09-12T00:58:42
2017-06-24T14:33:37
Racket
UTF-8
Racket
false
false
2,793
rkt
model-authors.rkt
#lang racket/base (require db racket/match racket/dict "db-adapter.rkt" "parameters.rkt" "structs.rkt") (provide insert-and-join-author) #| Table schemas ============= Authors ------- (id integer primary key, name varchar unique not null, first_name varchar, middle_name varchar, last_name varchar) Authorpapers - join table for authors <--> papers ------------------------------------------------- (id integer primary key, author_id integer not null, paper_id integer not null) |# ;; Prepared queries ;; ================ (define/prepared-query db-insert-author "INSERT OR IGNORE INTO authors (name, first_name, middle_name, last_name) VALUES (?, ?, ?, ?)") (define/prepared-query dp-select-author-by-name "SELECT id FROM authors WHERE name = ?") (define/prepared-query db-insert-authorspapers "INSERT INTO authorspapers (paper_id, author_id) VALUES (?, ?)") ; If we didn't get an insert id back from the query, lets go find the record (define (fetch-author-id logger conn author) (with-handlers ([exn:fail:sql? (handle-sql-error logger author)]) (define q (query-rows conn "select id from authors where name = $1" (author-name author))) (if (not (null? q)) (vector-ref (car q) 0) '()))) (define (insert-author-join logger conn author pid aid) (with-handlers ([exn:fail:sql? (handle-sql-error logger author)]) ;; check for existing joins (define join-rows (query-rows conn "SELECT paper_id, author_id FROM authorspapers WHERE paper_id = $1 AND author_id = $2" pid aid)) ;; only insert joins if the join doesn't already exist (define q (if (null? join-rows) (db-insert-authorspapers conn pid aid) join-rows)) (if (simple-result? q) (get-insert-id q) '()))) ;////////////////////////////////////////////////////////////////////////////// ; PUBLIC ;; if insert fails then get author id and make join ;; otherwise make join with returned id (define (insert-and-join-author logger conn author pid) (with-handlers ([exn:fail:sql? (handle-sql-error logger author)]) (define q (db-insert-author conn (author-name author) (author-first_name author) (author-middle_name author) (author-last_name author))) (define insert-id (if (simple-result? q) (get-insert-id q) '())) (define aid (if (null? insert-id) (fetch-author-id logger conn author) insert-id)) (if (not (null? aid)) (insert-author-join logger conn author pid aid) '())))
false
f31907fbec040f43967cc6830989520c9f9fe1b9
b3e61e6f9433fc153f8b17943b08d9ef56b076a1
/examples/prime.rkt
f69daaab9cf990692618c158ca990902350f6492
[ "CC0-1.0" ]
permissive
dyoo/brainfudge
f32ae3748683208732fb3ed84567f5af6b5c491a
cafaa03cf710f13a2ce5f381ba17c6dfd2ef493a
refs/heads/master
2021-06-03T23:38:33.296177
2016-03-18T18:51:45
2016-03-18T18:51:45
1,878,008
26
9
CC0-1.0
2020-05-05T18:32:26
2011-06-10T21:14:18
Racket
UTF-8
Racket
false
false
4,121
rkt
prime.rkt
#lang planet dyoo/bf =================================================================== ======================== OUTPUT STRING ============================ =================================================================== >++++++++[<++++++++>-]<++++++++++++++++.[-] >++++++++++[<++++++++++>-]<++++++++++++++.[-] >++++++++++[<++++++++++>-]<+++++.[-] >++++++++++[<++++++++++>-]<+++++++++.[-] >++++++++++[<++++++++++>-]<+.[-] >++++++++++[<++++++++++>-]<+++++++++++++++.[-] >+++++[<+++++>-]<+++++++.[-] >++++++++++[<++++++++++>-]<+++++++++++++++++.[-] >++++++++++[<++++++++++>-]<++++++++++++.[-] >+++++[<+++++>-]<+++++++.[-] >++++++++++[<++++++++++>-]<++++++++++++++++.[-] >++++++++++[<++++++++++>-]<+++++++++++.[-] >+++++++[<+++++++>-]<+++++++++.[-] >+++++[<+++++>-]<+++++++.[-] =================================================================== ======================== INPUT NUMBER ============================ =================================================================== + cont=1 [ - cont=0 >, ======SUB10====== ---------- [ not 10 <+> cont=1 =====SUB38====== ---------- ---------- ---------- -------- > =====MUL10======= [>+>+<<-]>>[<<+>>-]< dup >>>+++++++++ [ <<< [>+>+<<-]>>[<<+>>-]< dup [<<+>>-] >>- ] <<<[-]< ======RMOVE1====== < [>+<-] ] < ] >>[<<+>>-]<< =================================================================== ======================= PROCESS NUMBER =========================== =================================================================== ==== ==== ==== ==== numd numu teid teiu ==== ==== ==== ==== >+<- [ >+ ======DUP====== [>+>+<<-]>>[<<+>>-]< >+<-- >>>>>>>>+<<<<<<<< isprime=1 [ >+ <- =====DUP3===== <[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<<< =====DUP2===== >[>>+>+<<<-]>>>[<<<+>>>-]<<< < >>> ====DIVIDES======= [>+>+<<-]>>[<<+>>-]< DUP i=div << [ >>>>>+ bool=1 <<< [>+>+<<-]>>[<<+>>-]< DUP [>>[-]<<-] IF i THEN bool=0 >> [ IF i=0 <<<< [>+>+<<-]>>[<<+>>-]< i=div >>> - bool=0 ] <<< - DEC i << - ] +>>[<<[-]>>-]<< >[-]< CLR div =====END DIVIDES==== [>>>>>>[-]<<<<<<-] if divides then isprime=0 << >>[-]>[-]<<< ] >>>>>>>> [ - <<<<<<<[-]<< [>>+>+<<<-]>>>[<<<+>>>-]<<< >> =================================================================== ======================== OUTPUT NUMBER =========================== =================================================================== [>+<-]> [ ======DUP====== [>+>+<<-]>>[<<+>>-]< ======MOD10==== >+++++++++< [ >>>+<< bool= 1 [>+>[-]<<-] bool= ten==0 >[<+>-] ten = tmp >[<<++++++++++>>-] if ten=0 ten=10 <<- dec ten <- dec num ] +++++++++ num=9 >[<->-]< dec num by ten =======RROT====== [>+<-] < [>+<-] < [>+<-] >>>[<<<+>>>-] < =======DIV10======== >+++++++++< [ >>>+<< bool= 1 [>+>[-]<<-] bool= ten==0 >[<+>-] ten = tmp >[<<++++++++++>>>+<-] if ten=0 ten=10 inc div <<- dec ten <- dec num ] >>>>[<<<<+>>>>-]<<<< copy div to num >[-]< clear ten =======INC1========= <+> ] < [ =======MOVER========= [>+<-] =======ADD48======== +++++++[<+++++++>-]<-> =======PUTC======= <.[-]> ======MOVEL2======== >[<<+>>-]< <- ] >++++[<++++++++>-]<.[-] =================================================================== =========================== END FOR =============================== =================================================================== >>>>>>> ] <<<<<<<< >[-]< [-] <<- ] ======LF======== ++++++++++.[-]
false
2b07057b440bb04b5d6e54a909a75e0710a93cfd
b08b7e3160ae9947b6046123acad8f59152375c3
/Programming Language Detection/Experiment-2/Dataset/Train/Racket/draw-a-sphere.rkt
a983114bb4fcbc1be1f75f361e31736c62564cf5
[]
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
89
rkt
draw-a-sphere.rkt
#lang typed/racket (require plot/typed) (plot3d (polar3d (λ (θ ρ) 1)) #:altitude 25)
false
389b6531e680e904017a101ec4be72c99124b312
1ae479672668733f0fb94fc6988ec7bfef697501
/basics.rkt
b170a74919ee5f3664705468feb758167d7f37cf
[]
no_license
bboskin/records
441435ca9d8044ce00b42ead25b5476d891b9337
683678c450934cc7d5e66d8757c4499ff421eed0
refs/heads/master
2022-04-26T19:58:08.307316
2020-03-31T17:56:28
2020-03-31T17:56:28
null
0
0
null
null
null
null
UTF-8
Racket
false
false
408
rkt
basics.rkt
#lang racket (provide (all-defined-out)) ;; struct definitions (struct Record [title artist cost tracks facts]) (struct Store [grid mode taskbar record-bag money owned]) ;; basic list ops (define (front-to-back ls) (if (null? ls) ls (append (cdr ls) (list (car ls))))) (define (back-to-front ls) (if (null? ls) ls (let ((ls (reverse ls))) (cons (car ls) (reverse (cdr ls))))))
false
3fc760d15415ea7f2f5dd77fc16144f197bd76b6
7e15b782f874bcc4192c668a12db901081a9248e
/eopl/ch2/ex-2.5.rkt
fa45c4f84d5c97ab14250714e996d47f16240177
[]
no_license
Javran/Thinking-dumps
5e392fe4a5c0580dc9b0c40ab9e5a09dad381863
bfb0639c81078602e4b57d9dd89abd17fce0491f
refs/heads/master
2021-05-22T11:29:02.579363
2021-04-20T18:04:20
2021-04-20T18:04:20
7,418,999
19
4
null
null
null
null
UTF-8
Racket
false
false
1,100
rkt
ex-2.5.rkt
#lang eopl (require "../common.rkt") ; interfaces: ; ; constructors: ; * (empty-env) ; * (extend-env var v f) ; ; observers: ; * (apply-env f var) ; empty-env: () -> Env (define (empty-env) '()) ; extend-env: Var x SchemeVal x Env -> Env (define (extend-env key val env) (cons (cons key val) env)) ; apply-env: Env x Var -> SchemeVal (define (apply-env env var) (if (null? env) (report-no-binding-found var) ; else, non-empty env (let ((current-k-v (car env))) (cond ((eqv? (car current-k-v) var) (cdr current-k-v)) (else (apply-env (cdr env) var)))))) (define (report-no-binding-found var) (eopl:error 'apply-env "No binding for ~s" var)) (define e (extend-env 'x 1 (extend-env 'y 2 (extend-env 'x 3 (extend-env 'z 4 (empty-env)))))) (out (apply-env e 'x) (apply-env e 'y) (apply-env e 'z)) (require "./ex-2.6-test.rkt") (do-env-test empty-env extend-env apply-env) (provide empty-env) (provide extend-env) (provide apply-env)
false
cc2a75c4a3427b917c2670fd164bccf818c6e586
b64657ac49fff6057c0fe9864e3f37c4b5bfd97e
/ch2/ex-28.rkt
186d95f75d0374cc51c7d8c25fc5d33991495d7f
[]
no_license
johnvtan/sicp
af779e5bf245165bdfbfe6965e290cc419cd1d1f
8250bcc7ee4f4d551c7299643a370b44bc3f7b9d
refs/heads/master
2022-03-09T17:30:30.469397
2022-02-26T20:22:24
2022-02-26T20:22:24
223,498,855
0
0
null
null
null
null
UTF-8
Racket
false
false
837
rkt
ex-28.rkt
#!/usr/bin/racket #lang sicp (define (reverse items) (define (iter acc items) (if (null? items) acc (iter (cons (car items) acc) (cdr items)))) (iter '() items)) ; Given a tree, return a list whose elements are ; all the leaves of the tree arragned in left-to-right ; order (define (fringe tree) (define (iter acc tree) (cond ; end of list -> return acc [(null? tree) acc] ; first elem is itself a list ; call iter on first elem and append to end of acc [(pair? (car tree)) (iter (append acc (iter '() (car tree))) (cdr tree))] ; Otherwise, we can just add the first elem to the end of acc [else (iter (append acc (list (car tree))) (cdr tree))])) (iter '() tree)) (fringe '(1 2 3 4)) (fringe '(1 (2 3) 4)) (fringe '((1 2) (3 4) (5 (6 7))))
false
07761b4463a975b497acc37b3092db62cff5e471
c180d49b9f3785b2d0b75df262339aaae352639d
/Labs/lab4/hello.rkt
68c4ae7f25171f5b315b6bc2f981323b6d3cdb53
[]
no_license
abriggs914/CS2613
4180d304bf8e1fa0b5d675a341204e1ade65889f
aac085b409bb0e9fbd530274347f9f7bbed95694
refs/heads/master
2020-03-29T04:22:42.375054
2018-12-11T16:06:47
2018-12-11T16:06:47
149,317,591
0
0
null
null
null
null
UTF-8
Racket
false
false
461
rkt
hello.rkt
#lang racket (define (hello) (displayln "Hello world!")) (module+ test (require rackunit). (check-equal? (with-output-to-string hello) "Hello world!\n")) (module cake racket (provide print-cake) (define (print-cake n) (show " ~a " n #\.) (show " .-~a-. " n #\|) (show " | ~a | " n #\space) (show "---~a---" n #\-)) (define (show fmt n ch) (printf fmt (make-string n ch)) (newline))) > (require 'cake) > (print-cake 3)
false
8abb71549b277a0bd49030988c19253f0522507b
7ab4846887821aaa6ac2290c686a2ceb51673ec4
/CSC431/mini-compiler/optimize/constant-prop.rkt
d6a4865e532f9daf76f4e58c2e0173fc42ec742a
[]
no_license
baileywickham/college
14d39bf5586a0f3c15f3461eb42ff1114c58a7d5
8f3bb6433ea8555f0ba73cb0db2fabd98c95d8ee
refs/heads/master
2022-08-24T19:20:18.813089
2022-08-11T10:22:41
2022-08-11T10:22:41
150,782,968
1
5
null
2021-03-15T19:56:38
2018-09-28T18:56:44
Java
UTF-8
Racket
false
false
3,941
rkt
constant-prop.rkt
#lang racket (provide constant-prop) (require "common.rkt") (define op-procs (hash 'add + 'mul * 'sub - 'sdiv quotient 'and (λ (a b) (and a b)) 'or (λ (a b) (or a b)) 'eq equal? 'sle <= 'sgt > 'sge >= 'slt < 'xor xor 'ne (negate equal?))) ;; (define+ (constant-prop (LLVM tys decs funs)) (LLVM tys decs (map prop/fun funs))) ;; (define+ (prop/fun (FunLL id params ret-ty body)) (FunLL id params ret-ty (prop/body body))) ;; (define (prop/body blocks) (define vals (initial-vals blocks)) (define worklist (filter identity (hash-map vals (λ (id v) (if (equal? v 'T) #f id))))) (define final-values (update-vals worklist vals (get-uses blocks))) ((subst-vals* vals) blocks)) ;; (define (subst-vals* vals) ;; (define (subst-vals/blocks blocks) (map subst-vals/block blocks)) ;; (define+ (subst-vals/block (Block id stmts)) (Block id (map subst-vals/stmt stmts))) ;; (define (subst-vals/stmt stmt) (match stmt [(AssignLL target src) (AssignLL target (subst-vals/stmt src))] [(BinaryLL op ty op1 op2) (BinaryLL op ty (get-val op1) (get-val op2))] [(CallLL ty fn args var-args?) (CallLL ty fn (map (λ+ ((cons id ty)) (cons (get-val id) ty)) args) var-args?)] [(PhiLL id ty args) (PhiLL id ty (map (λ+ ((cons label (cons id ty))) (cons label (cons (get-val id) ty))) args))] [(StoreLL ty val ptr) (StoreLL ty (get-val val) (get-val ptr))] [(LoadLL ty ptr) (LoadLL ty (get-val ptr))] [(CastLL op ty val ty2) (CastLL op ty (get-val val) ty2)] [(BrCondLL c iftrue iffalse) (BrCondLL (get-val c) iftrue iffalse)] [(ReturnLL ty val) (ReturnLL ty (get-val val))] [_ stmt])) ;; (define (get-val arg) (let ([v (hash-ref vals arg arg)]) (if (const? v) v arg))) subst-vals/blocks) ;; (define (update-vals worklist vals use-graph) (match worklist ['() vals] [(cons r remaining-work) (let ([new-work (update-vals/reg r vals use-graph)]) (update-vals (set-union remaining-work new-work) vals use-graph))])) ;; (define (update-vals/reg r vals use-graph) (define ops (hash-ref use-graph r '())) (filter-map (λ (op) (update-vals/op op vals)) ops)) ;; (define (update-vals/op op vals) (match (stmt-writes op) ['() #f] [(list m) (define m-val (hash-ref vals m)) (cond [(equal? m-val 'L) #f] [else (let ([m-eval (evaluate op vals)]) (hash-set! vals m m-eval) (if (equal? m-eval m-val) #f m))])])) ;; (define (evaluate op vals) (match op [(AssignLL _ src) (evaluate/src src vals)] [(? PhiLL?) 'L])) ;; (define (evaluate/src src vals) (match src [(BinaryLL op _ op1 op2) (let ([val1 (hash-ref vals op1 op1)] [val2 (hash-ref vals op2 op2)]) (if (and (const? val1) (const? val2)) ((get-op op) val1 val2) 'T))] [(? CallLL?) 'L] [(? LoadLL?) 'L] [(CastLL op ty val ty2) (let ([new-val (hash-ref vals val val)]) (if (const? new-val) new-val 'T))] [(? GetEltLL?) 'T])) ;; (define (get-uses blocks) (make-immutable-hash* (get-all uses/stmt blocks))) ;; (define (uses/stmt stmt) (map (λ (var) (cons var stmt)) (filter ssa-reg? (stmt-reads stmt)))) ;; (define (initial-vals blocks) (make-hash (get-all initial-vals/stmt blocks))) ;; (define (initial-vals/stmt stmt) (match stmt [(PhiLL id _ _) (list (cons id (evaluate stmt #hash())))] [(AssignLL id _) (list (cons id (evaluate stmt #hash())))] [_ '()])) ;; (define (make-immutable-hash* assocs) (make-immutable-hash (map make-hash-entry (group-by car assocs)))) ;; (define (make-hash-entry lst) (cons (car (first lst)) (map cdr lst))) ;; (define (get-op op) (hash-ref op-procs op)) ;; (define const? (disjoin integer? boolean?))
false
612c772f05a22b49f4852a93feb8f6131b737245
688feb2eac8bc384583c4f0960cfbc86c3470d91
/racket/class/field.rkt
df89ebac87544ba5e51b469f1523cec12f5990eb
[]
no_license
halida/code_example
7d2873e92707b4bab673046ff3d0c742e1984b4c
5c882a24b93696c2122a78425ef6b3775adc80fa
refs/heads/master
2023-06-08T15:51:23.150728
2022-03-27T09:57:43
2022-03-27T09:57:43
2,458,466
2
1
null
2023-06-06T02:07:28
2011-09-26T06:01:29
Ruby
UTF-8
Racket
false
false
412
rkt
field.rkt
#lang racket (define people% (class object% (super-new) (init-field firstname [lastname ""]) )) (define people (new people% [firstname "James"])) (get-field firstname people) (set-field! firstname people "Bob") (define get-firstname (class-field-accessor people% firstname)) (get-firstname people) (define set-firstname (class-field-mutator people% firstname)) (set-firstname people "Steven")
false
f44943f07a57e15632d882ef33c3dcb5955092c4
ef61a036fd7e4220dc71860053e6625cf1496b1f
/HTDP2e/03-abstraction/ch-16/ex-260.rkt
d601a19528f41a5b28f65429b37434a6981f6a3b
[]
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
964
rkt
ex-260.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-intermediate-reader.ss" "lang")((modname ex-260) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp")) #f))) ; Nelon -> Number ; determines the smallest number on l (define (inf.v2 l) (cond [(empty? (rest l)) (first l)] [else (local ((define smallest-in-rest (inf.v2 (rest l)))) (if (< (first l) smallest-in-rest) (first l) smallest-in-rest))])) (check-expect (inf.v2 (list 25 24 23 22 21 20 19 18 17 16 15 14 12 11 10 9 8 7 6 5 4 3 2 1)) 1) (check-expect (inf.v2 (list 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25)) 1)
false
584e62ee095d9d4ad3a95380bd33ea0971e561f8
d2d01d48d5c59d54c295f8474c45e3b42f605005
/accelerack/private/prim-redefinitions.rkt
ff18bd160cbf576b89d193ccd0e6072af4cbfa81
[]
no_license
iu-parfunc/accelerack
543d73e3a01711ad765f6ee4defef0c9d52447b8
9550ecc1e7494d296f3faac3aef71393c1705827
refs/heads/master
2021-01-21T04:27:28.653604
2016-05-02T14:02:24
2016-05-02T14:02:24
30,226,648
3
6
null
null
null
null
UTF-8
Racket
false
false
354
rkt
prim-redefinitions.rkt
#lang racket (require (except-in racket/base map sqrt round ceiling floor) (prefix-in r: racket/base)) (provide sqrt round ceiling floor) (define (sqrt n) (exact->inexact (r:sqrt n))) (define (round n) (inexact->exact (r:round n))) (define (ceiling n) (inexact->exact (r:ceiling n))) (define (floor n) (inexact->exact (r:floor n)))
false
6af421715368d058fcbf7b9e8c1d81a720a5ae3e
5bbc152058cea0c50b84216be04650fa8837a94b
/data/6.8/take5-v6.8-2017-06-27T16:35:56.rktd
b71375f63701c652397e72584c81056f7398d810
[]
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
7,148
rktd
take5-v6.8-2017-06-27T16:35:56.rktd
;; #(-v 6.8 -i 6 benchmarks/acquire/ benchmarks/dungeon/ benchmarks/forth/ benchmarks/fsm/ benchmarks/fsmoo/ benchmarks/gregor/ benchmarks/lnm/ benchmarks/mbta/ benchmarks/morsecode/ benchmarks/sieve/ benchmarks/snake/ benchmarks/stack benchmarks/suffixtree/ benchmarks/synth/ benchmarks/take5/ benchmarks/tetris/ benchmarks/zombie/ benchmarks/zordoz.6.5/) ;; 6.8 ;; binaries in /home/ben/code/racket/6.8/bin/ ;; base @ <unknown-commit> ;; typed-racket @ 495da1bd ;; 2017-06-12T05:09:58 #( (159 159 159 156 159 159) (177 177 178 175 177 178) (187 185 188 188 187 185) (190 190 186 189 188 186) (187 188 186 186 187 185) (188 188 184 188 187 188) (196 197 193 195 196 197) (198 200 197 196 197 196) (180 181 182 180 180 180) (180 182 182 180 181 181) (191 191 189 190 190 191) (191 190 192 178 191 189) (189 189 190 189 189 190) (191 187 191 189 189 190) (200 197 200 198 199 198) (198 197 200 198 198 199) (194 192 197 193 194 181) (196 194 195 195 195 195) (195 195 195 195 196 193) (197 197 196 194 194 196) (196 195 196 196 193 195) (197 196 198 198 193 198) (181 183 181 179 183 181) (184 182 182 183 183 184) (194 193 194 194 194 195) (192 196 195 196 194 191) (195 194 193 196 195 195) (195 195 196 195 197 196) (196 194 197 199 199 195) (197 197 198 197 198 196) (182 178 182 182 183 182) (182 182 182 181 184 182) (174 175 175 175 176 176) (174 178 166 178 176 178) (189 189 187 189 189 192) (188 187 191 190 190 192) (187 187 186 188 189 188) (189 191 189 189 191 188) (195 197 197 198 197 198) (200 199 198 199 199 185) (179 179 183 181 181 178) (182 184 182 181 183 183) (189 192 192 192 193 192) (192 191 190 192 193 193) (191 188 191 192 192 189) (192 190 189 191 192 192) (198 200 199 199 200 198) (198 197 196 199 198 200) (194 195 196 197 197 196) (196 197 196 184 194 196) (198 194 196 197 196 198) (199 199 196 202 198 198) (195 196 196 199 197 198) (199 200 186 200 200 198) (184 185 185 184 184 184) (183 186 182 185 184 182) (195 196 196 196 195 194) (194 193 196 192 197 196) (196 195 197 197 197 197) (196 196 184 198 197 197) (197 199 198 199 198 186) (186 199 199 199 199 196) (183 184 184 183 184 185) (183 184 183 184 184 183) (180 181 181 179 180 179) (179 182 182 182 181 178) (192 190 192 192 190 190) (191 193 192 193 192 192) (190 188 189 191 188 190) (192 190 190 190 191 191) (198 186 196 200 196 199) (201 201 199 201 197 199) (171 183 179 182 181 179) (181 183 183 182 182 182) (180 191 192 194 193 190) (193 193 193 194 192 192) (193 194 193 192 193 192) (188 192 192 191 191 179) (202 200 201 200 199 200) (200 199 201 200 201 201) (194 195 194 199 195 195) (196 193 195 196 193 196) (197 197 195 196 193 196) (198 198 197 198 198 196) (195 198 197 199 197 198) (200 199 199 200 200 200) (184 182 184 186 183 183) (184 184 185 185 185 182) (196 196 196 194 194 196) (196 196 196 198 196 196) (193 196 195 196 195 198) (197 196 195 198 196 197) (197 198 197 198 195 196) (200 198 198 199 198 198) (181 184 183 182 182 183) (183 185 181 184 171 183) (181 178 182 181 181 180) (180 183 182 183 183 183) (192 191 192 190 193 192) (194 193 193 193 191 194) (191 192 192 191 190 191) (192 190 190 192 193 192) (202 200 199 199 201 197) (201 202 198 202 202 201) (184 184 185 184 183 183) (184 184 183 184 172 185) (195 196 197 193 194 194) (191 197 190 192 192 195) (191 193 194 192 194 192) (193 190 193 193 193 194) (202 189 201 200 203 203) (199 200 200 199 203 200) (198 197 197 197 196 196) (198 196 197 198 198 197) (198 198 199 199 197 195) (198 199 200 197 199 196) (200 200 200 200 200 202) (200 202 201 200 201 201) (185 183 186 186 186 186) (186 186 188 188 186 184) (197 196 197 196 198 196) (199 196 196 199 194 195) (198 198 196 194 198 194) (184 196 196 195 195 183) (199 200 199 198 200 199) (198 197 200 199 200 200) (184 184 187 185 186 185) (183 181 183 183 183 179) (168 173 174 172 171 162) (178 178 178 178 178 179) (188 189 189 189 189 189) (187 188 190 188 189 191) (188 186 188 188 188 176) (189 188 188 188 189 188) (197 196 197 197 198 196) (198 199 196 199 198 198) (181 181 182 179 181 182) (180 182 182 182 182 178) (192 191 192 190 188 191) (194 191 192 192 193 190) (191 190 190 189 191 190) (191 191 191 190 191 190) (198 199 199 198 200 200) (198 198 197 200 200 199) (194 181 194 192 192 194) (192 195 196 194 195 195) (195 195 193 192 192 195) (195 197 198 196 196 195) (197 197 197 195 202 184) (198 194 199 197 196 198) (183 183 184 184 183 183) (183 183 180 180 185 180) (194 195 195 191 194 193) (195 195 194 194 195 193) (192 195 194 194 196 195) (193 195 194 195 196 193) (197 196 197 197 198 195) (197 198 198 197 196 197) (184 183 180 182 183 181) (182 182 183 181 182 184) (176 176 174 177 176 177) (177 179 180 178 178 176) (190 192 191 190 191 192) (192 193 192 188 191 195) (188 188 189 189 188 189) (189 189 191 187 189 190) (200 198 198 200 200 198) (198 199 199 200 199 199) (182 183 184 183 183 184) (185 183 183 184 183 181) (191 195 195 195 196 192) (195 196 191 190 195 193) (192 191 194 192 192 192) (193 192 191 191 192 192) (201 201 201 197 201 202) (200 198 201 201 201 201) (195 195 196 196 196 192) (197 195 197 195 195 194) (197 195 196 197 196 194) (198 197 198 185 197 199) (197 197 198 198 198 198) (200 199 199 199 200 196) (184 183 183 184 184 184) (186 182 183 184 186 185) (196 196 192 195 195 183) (195 196 197 197 196 195) (197 197 196 197 196 197) (193 185 197 198 197 196) (199 199 199 198 197 199) (199 196 200 200 198 199) (184 183 184 184 184 182) (184 184 185 184 184 184) (177 180 180 180 177 181) (182 180 182 179 181 179) (192 194 192 190 192 192) (192 191 192 192 195 192) (190 192 190 189 191 191) (191 192 187 192 191 192) (198 201 200 199 199 200) (198 197 201 201 187 198) (183 180 180 183 182 183) (187 183 185 184 184 184) (196 195 193 196 193 190) (193 194 193 180 190 180) (192 192 192 192 192 193) (192 189 193 192 193 179) (202 202 200 200 201 201) (200 200 200 198 201 201) (195 195 195 196 196 196) (195 183 196 195 196 196) (197 196 194 196 197 195) (197 198 197 194 198 198) (198 199 197 198 199 198) (200 199 198 198 199 200) (183 181 184 184 184 185) (183 186 184 184 187 174) (195 193 195 192 196 192) (196 194 196 196 196 196) (195 196 196 196 196 196) (196 195 194 194 196 196) (195 197 196 196 199 197) (197 198 198 198 195 196) (179 183 183 184 180 182) (181 183 181 183 181 183) (181 182 182 184 182 182) (183 184 181 182 184 183) (193 192 194 195 193 197) (194 194 191 194 196 194) (188 193 192 193 192 195) (189 191 191 193 193 194) (201 198 202 201 200 201) (203 201 202 202 202 202) (184 184 185 186 183 185) (183 184 185 185 186 185) (194 197 197 198 196 196) (194 196 195 197 196 195) (194 194 194 194 195 195) (194 193 194 194 193 194) (189 201 202 203 203 202) (203 203 202 203 204 202) (183 197 197 196 196 196) (195 198 197 197 199 198) (198 198 195 199 199 199) (199 199 199 199 199 200) (200 200 200 200 200 199) (201 201 200 187 202 200) (186 184 187 184 185 186) (186 185 187 187 187 185) (193 196 196 197 196 195) (194 196 199 197 196 197) (194 194 197 198 198 197) (195 195 193 195 196 196) (186 204 199 200 199 196) (199 201 200 200 198 199) (183 184 181 185 183 184) (182 182 183 182 183 182) )
false
51bb839a7508543bf9e775c7357c64dc5a51a282
1397f4aad672004b32508f67066cb7812f8e2a14
/plot-gui-lib/plot/private/gui/plot3d.rkt
368c0431c6d4c598d10314129c32d22754bdd9c5
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
racket/plot
2da8d9f8159f28d0a9f540012e43457d490d36da
b0da52632c0369058887439345eb90cbf8e99dae
refs/heads/master
2023-07-14T07:31:23.099585
2023-07-04T12:53:33
2023-07-04T12:53:33
27,409,837
39
29
NOASSERTION
2023-07-04T12:56:50
2014-12-02T01:50:35
Racket
UTF-8
Racket
false
false
17,813
rkt
plot3d.rkt
#lang typed/racket/base #:no-optimize ;; See note at the top of plot2d.rkt for the use of `#:no-optimize` and ;; `unsafe-provide` (require (only-in typed/mred/mred Snip% Frame%) (only-in racket/gui/base get-display-backing-scale) typed/racket/draw typed/racket/class racket/match racket/list (only-in typed/pict pict pict?) plot/utils plot/private/common/parameter-group plot/private/common/draw plot/private/common/deprecation-warning plot/private/common/type-doc plot/private/common/utils plot/private/plot3d/plot-area plot/private/no-gui/plot3d plot/private/no-gui/plot3d-utils plot/private/no-gui/utils "lazy-snip-typed.rkt" typed/racket/unsafe) (unsafe-provide plot3d-snip plot3d-frame plot3d) (require/typed plot/utils (legend-anchor/c (-> Any Boolean)) (plot-color/c (-> Any Boolean)) (plot-file-format/c (-> Any Boolean))) ;; =================================================================================================== ;; Plot to a snip (:: plot3d-snip (->* [(Treeof (U renderer3d nonrenderer))] [#:x-min (U Real #f) #:x-max (U Real #f) #:y-min (U Real #f) #:y-max (U Real #f) #:z-min (U Real #f) #:z-max (U Real #f) #:width Positive-Integer #:height Positive-Integer #:angle Real #:altitude Real #:title (U String pict #f) #:x-label (U String pict #f) #:y-label (U String pict #f) #:z-label (U String pict #f) #:aspect-ratio (U Nonnegative-Real #f) #:legend-anchor Legend-Anchor] (Instance Plot-Snip%))) (define (plot3d-snip renderer-tree #:x-min [x-min #f] #:x-max [x-max #f] #:y-min [y-min #f] #:y-max [y-max #f] #:z-min [z-min #f] #:z-max [z-max #f] #:width [width (plot-width)] #:height [height (plot-height)] #:angle [angle (plot3d-angle)] #:altitude [altitude (plot3d-altitude)] #:title [title (plot-title)] #:x-label [x-label (plot-x-label)] #:y-label [y-label (plot-y-label)] #:z-label [z-label (plot-z-label)] #:aspect-ratio [aspect-ratio (plot-aspect-ratio)] #:legend-anchor [legend-anchor (plot-legend-anchor)]) (define fail/kw (make-raise-keyword-error 'plot3d-snip)) (cond ;; check arguments, see note at the top of this file [(and x-min (not (rational? x-min))) (fail/kw "#f or rational" '#:x-min x-min)] [(and x-max (not (rational? x-max))) (fail/kw "#f or rational" '#:x-max x-max)] [(and y-min (not (rational? y-min))) (fail/kw "#f or rational" '#:y-min y-min)] [(and y-max (not (rational? y-max))) (fail/kw "#f or rational" '#:y-max y-max)] [(and z-min (not (rational? z-min))) (fail/kw "#f or rational" '#:z-min z-min)] [(and z-max (not (rational? z-max))) (fail/kw "#f or rational" '#:z-max z-max)] [(not (real? angle)) (fail/kw "real" '#:angle angle)] [(not (real? altitude)) (fail/kw "real" '#:altitude altitude)] [(not (and (integer? width) (positive? width))) (fail/kw "positive integer" '#:width width)] [(not (and (integer? height) (positive? height))) (fail/kw "positive integer" '#:height height)] [(and title (not (or (string? title) (pict? title)))) (fail/kw "#f, string or pict" '#:title title)] [(and x-label (not (or (string? x-label) (pict? x-label)))) (fail/kw "#f, string or pict" '#:x-label x-label)] [(and y-label (not (or (string? y-label) (pict? y-label)))) (fail/kw "#f, string or pict" '#:y-label y-label)] [(and z-label (not (or (string? z-label) (pict? z-label)))) (fail/kw "#f, string or pict" '#:y-label z-label)] [(and aspect-ratio (not (and (rational? aspect-ratio) (positive? aspect-ratio)))) (fail/kw "#f or positive real" '#:aspect-ratio aspect-ratio)] [(not (legend-anchor/c legend-anchor)) (fail/kw "legend-anchor/c" '#:legend-anchor legend-anchor)]) (parameterize ([plot-title title] [plot-x-label x-label] [plot-y-label y-label] [plot-z-label z-label] [plot-legend-anchor legend-anchor]) (define saved-plot-parameters (plot-parameters)) (define renderer-list (get-renderer-list renderer-tree)) (define bounds-rect (get-bounds-rect renderer-list x-min x-max y-min y-max z-min z-max)) (define-values (x-ticks x-far-ticks y-ticks y-far-ticks z-ticks z-far-ticks) (get-ticks renderer-list bounds-rect)) (define render-tasks-hash ((inst make-hash Boolean render-tasks))) ;; For 3D legend can be calculated once since we don't change the bounding box (define legend (get-legend-entry-list renderer-list bounds-rect)) (: make-bm (-> Boolean Real Real Positive-Integer Positive-Integer (Values (Instance Bitmap%) (U #f (Instance 3D-Plot-Area%))))) (define (make-bm anim? angle altitude width height) (parameterize/group ([plot-parameters saved-plot-parameters] [plot-animating? (if anim? #t (plot-animating?))] [plot3d-angle angle] [plot3d-altitude altitude]) (define bm (make-bitmap width height #t #:backing-scale (or (get-display-backing-scale) 1.0))) (define dc (make-object bitmap-dc% bm)) (define area (make-object 3d-plot-area% bounds-rect x-ticks x-far-ticks y-ticks y-far-ticks z-ticks z-far-ticks legend dc 0 0 width height aspect-ratio)) (send area start-plot) (cond [(not (hash-ref render-tasks-hash (plot-animating?) #f)) (for ([rend (in-list renderer-list)]) (match-define (renderer3d rend-bounds-rect _bf _tf label-proc render-proc) rend) (when render-proc (send area start-renderer (if rend-bounds-rect (rect-inexact->exact rend-bounds-rect) (unknown-rect 3))) (render-proc area))) (hash-set! render-tasks-hash (plot-animating?) (send area get-render-tasks))] [else (send area set-render-tasks (hash-ref render-tasks-hash (plot-animating?)))]) (send area end-renderers) (send area end-plot) (values bm area))) (define-values (bm area) (make-bm #f angle altitude width height)) (make-3d-plot-snip bm saved-plot-parameters make-bm angle altitude area width height))) ;; =================================================================================================== ;; Plot to a frame (:: plot3d-frame (->* [(Treeof (U renderer3d nonrenderer))] [#:x-min (U Real #f) #:x-max (U Real #f) #:y-min (U Real #f) #:y-max (U Real #f) #:z-min (U Real #f) #:z-max (U Real #f) #:width Positive-Integer #:height Positive-Integer #:angle Real #:altitude Real #:title (U String pict #f) #:x-label (U String pict #f) #:y-label (U String pict #f) #:z-label (U String pict #f) #:aspect-ratio (U Nonnegative-Real #f) #:legend-anchor Legend-Anchor] (Instance Frame%))) (define (plot3d-frame renderer-tree #:x-min [x-min #f] #:x-max [x-max #f] #:y-min [y-min #f] #:y-max [y-max #f] #:z-min [z-min #f] #:z-max [z-max #f] #:width [width (plot-width)] #:height [height (plot-height)] #:angle [angle (plot3d-angle)] #:altitude [altitude (plot3d-altitude)] #:title [title (plot-title)] #:x-label [x-label (plot-x-label)] #:y-label [y-label (plot-y-label)] #:z-label [z-label (plot-z-label)] #:aspect-ratio [aspect-ratio (plot-aspect-ratio)] #:legend-anchor [legend-anchor (plot-legend-anchor)]) (define fail/kw (make-raise-keyword-error 'plot3d-frame)) (cond ;; check arguments, see note at the top of this file [(and x-min (not (rational? x-min))) (fail/kw "#f or rational" '#:x-min x-min)] [(and x-max (not (rational? x-max))) (fail/kw "#f or rational" '#:x-max x-max)] [(and y-min (not (rational? y-min))) (fail/kw "#f or rational" '#:y-min y-min)] [(and y-max (not (rational? y-max))) (fail/kw "#f or rational" '#:y-max y-max)] [(and z-min (not (rational? z-min))) (fail/kw "#f or rational" '#:z-min z-min)] [(and z-max (not (rational? z-max))) (fail/kw "#f or rational" '#:z-max z-max)] [(not (real? angle)) (fail/kw "real" '#:angle angle)] [(not (real? altitude)) (fail/kw "real" '#:altitude altitude)] [(not (and (integer? width) (positive? width))) (fail/kw "positive integer" '#:width width)] [(not (and (integer? height) (positive? height))) (fail/kw "positive integer" '#:height height)] [(and title (not (or (string? title) (pict? title)))) (fail/kw "#f, string or pict" '#:title title)] [(and x-label (not (or (string? x-label) (pict? x-label)))) (fail/kw "#f, string or pict" '#:x-label x-label)] [(and y-label (not (or (string? y-label) (pict? y-label)))) (fail/kw "#f, string or pict" '#:y-label y-label)] [(and z-label (not (or (string? z-label) (pict? z-label)))) (fail/kw "#f, string or pict" '#:y-label z-label)] [(and aspect-ratio (not (and (rational? aspect-ratio) (positive? aspect-ratio)))) (fail/kw "#f or positive real" '#:aspect-ratio aspect-ratio)] [(not (legend-anchor/c legend-anchor)) (fail/kw "legend-anchor/c" '#:legend-anchor legend-anchor)]) ;; make-snip will be called in a separate thread, make sure the ;; parameters have the correct values in that thread as well. (define saved-plot-parameters (plot-parameters)) (: make-snip (-> Positive-Integer Positive-Integer (Instance Snip%))) (define (make-snip width height) (parameterize/group ([plot-parameters saved-plot-parameters]) (plot3d-snip renderer-tree #:x-min x-min #:x-max x-max #:y-min y-min #:y-max y-max #:z-min z-min #:z-max z-max #:width width #:height height #:angle angle #:altitude altitude #:title title #:x-label x-label #:y-label y-label #:z-label z-label #:legend-anchor legend-anchor #:aspect-ratio aspect-ratio))) (make-snip-frame make-snip width height (if title (format "Plot: ~a" title) "Plot"))) ;; =================================================================================================== ;; Plot to a frame or a snip, depending on the value of plot-new-window? (:: plot3d (->* [(Treeof (U renderer3d nonrenderer))] [#:x-min (U Real #f) #:x-max (U Real #f) #:y-min (U Real #f) #:y-max (U Real #f) #:z-min (U Real #f) #:z-max (U Real #f) #:width Positive-Integer #:height Positive-Integer #:angle Real #:altitude Real #:az Real #:alt Real #:title (U String pict #f) #:x-label (U String pict #f) #:y-label (U String pict #f) #:z-label (U String pict #f) #:aspect-ratio (U Nonnegative-Real #f) #:legend-anchor Legend-Anchor #:out-file (U Path-String Output-Port #f) #:out-kind (U 'auto Image-File-Format) #:fgcolor Plot-Color #:bgcolor Plot-Color #:lncolor Plot-Color] (U (Instance Snip%) Void))) (define (plot3d renderer-tree #:x-min [x-min #f] #:x-max [x-max #f] #:y-min [y-min #f] #:y-max [y-max #f] #:z-min [z-min #f] #:z-max [z-max #f] #:width [width (plot-width)] #:height [height (plot-height)] #:angle [angle #f] #:altitude [altitude #f] #:az [az #f] #:alt [alt #f] ; backward-compatible aliases #:title [title (plot-title)] #:x-label [x-label (plot-x-label)] #:y-label [y-label (plot-y-label)] #:z-label [z-label (plot-z-label)] #:aspect-ratio [aspect-ratio (plot-aspect-ratio)] #:legend-anchor [legend-anchor (plot-legend-anchor)] #:out-file [out-file #f] #:out-kind [out-kind 'auto] #:fgcolor [fgcolor #f] #:bgcolor [bgcolor #f] #:lncolor [lncolor #f]) ; unused (when fgcolor (deprecation-warning "the plot3d #:fgcolor keyword argument" "plot-foreground")) (when bgcolor (deprecation-warning "the plot3d #:bgcolor keyword argument" "plot-background")) (when lncolor (deprecation-warning "the plot3d #:lncolor keyword argument")) (when az (deprecation-warning "the plot3d #:az keyword argument" "#:angle")) (when alt (deprecation-warning "the plot3d #:alt keyword argument" "#:altitude")) (define fail/kw (make-raise-keyword-error 'plot3d)) (cond ;; check arguments, see note at the top of this file [(and x-min (not (rational? x-min))) (fail/kw "#f or rational" '#:x-min x-min)] [(and x-max (not (rational? x-max))) (fail/kw "#f or rational" '#:x-max x-max)] [(and y-min (not (rational? y-min))) (fail/kw "#f or rational" '#:y-min y-min)] [(and y-max (not (rational? y-max))) (fail/kw "#f or rational" '#:y-max y-max)] [(and z-min (not (rational? z-min))) (fail/kw "#f or rational" '#:z-min z-min)] [(and z-max (not (rational? z-max))) (fail/kw "#f or rational" '#:z-max z-max)] [(and angle (not (real? angle))) (fail/kw "#f or real" '#:angle angle)] [(and altitude (not (real? altitude))) (fail/kw "#f or real" '#:altitude altitude)] [(and az (not (real? az))) (fail/kw "#f or real" '#:az az)] [(and alt (not (real? alt))) (fail/kw "#f or real" '#:alt alt)] [(not (and (integer? width) (positive? width))) (fail/kw "positive integer" '#:width width)] [(not (and (integer? height) (positive? height))) (fail/kw "positive integer" '#:height height)] [(and title (not (or (string? title) (pict? title)))) (fail/kw "#f, string or pict" '#:title title)] [(and x-label (not (or (string? x-label) (pict? x-label)))) (fail/kw "#f, string or pict" '#:x-label x-label)] [(and y-label (not (or (string? y-label) (pict? y-label)))) (fail/kw "#f, string or pict" '#:y-label y-label)] [(and z-label (not (or (string? z-label) (pict? z-label)))) (fail/kw "#f, string or pict" '#:y-label z-label)] [(and aspect-ratio (not (and (rational? aspect-ratio) (positive? aspect-ratio)))) (fail/kw "#f or positive real" '#:aspect-ratio aspect-ratio)] [(not (legend-anchor/c legend-anchor)) (fail/kw "legend-anchor/c" '#:legend-anchor legend-anchor)] [(and out-kind (not (plot-file-format/c out-kind))) (fail/kw "plot-file-format/c" '#:out-kind out-kind)] [(not (plot-file-format/c out-kind)) (fail/kw "plot-file-format/c" '#:out-kind out-kind)] [(and fgcolor (not (plot-color/c fgcolor))) (fail/kw "plot-color/c" '#:fgcolor fgcolor)] [(and bgcolor (not (plot-color/c bgcolor))) (fail/kw "plot-color/c" '#:bgcolor bgcolor)] ;; NOTE: don't check this one, as it is not used anyway ;; [(and lncolor (not (plot-color/c lncolor))) (fail/kw "plot-color/c" '#:lncolor lncolor)] [(and out-file (not (or (path-string? out-file) (output-port? out-file)))) (fail/kw "#f, path-string or output port" '#:out-file out-file)]) (cond ;; because this function is exported via `unsafe-provide` [(and out-kind (not (plot-file-format/c out-kind))) (fail/kw "plot-file-format/c" '#:out-kind out-kind)] [(and fgcolor (not (plot-color/c fgcolor))) (fail/kw "plot-color/c" '#:fgcolor fgcolor)] [(and bgcolor (not (plot-color/c bgcolor))) (fail/kw "plot-color/c" '#:bgcolor bgcolor)]) (parameterize ([plot-foreground (if fgcolor fgcolor (plot-foreground))] [plot-background (if bgcolor bgcolor (plot-background))]) (when out-file (plot3d-file renderer-tree out-file out-kind #:x-min x-min #:x-max x-max #:y-min y-min #:y-max y-max #:z-min z-min #:z-max z-max #:width width #:height height #:title title #:angle (or angle az (plot3d-angle)) #:altitude (or altitude alt (plot3d-altitude)) #:x-label x-label #:y-label y-label #:z-label z-label #:legend-anchor legend-anchor #:aspect-ratio aspect-ratio)) (cond [(plot-new-window?) (define frame (plot3d-frame renderer-tree #:x-min x-min #:x-max x-max #:y-min y-min #:y-max y-max #:z-min z-min #:z-max z-max #:width width #:height height #:title title #:angle (or angle az (plot3d-angle)) #:altitude (or altitude alt (plot3d-altitude)) #:x-label x-label #:y-label y-label #:z-label z-label #:legend-anchor legend-anchor #:aspect-ratio aspect-ratio)) (send frame show #t) (void)] [else (plot3d-snip renderer-tree #:x-min x-min #:x-max x-max #:y-min y-min #:y-max y-max #:z-min z-min #:z-max z-max #:width width #:height height #:title title #:angle (or angle az (plot3d-angle)) #:altitude (or altitude alt (plot3d-altitude)) #:x-label x-label #:y-label y-label #:z-label z-label #:legend-anchor legend-anchor #:aspect-ratio aspect-ratio)])))
false
7c01f9c58ee81a30e2c0ce74bce27ba1d085de22
5240df931f8ff8f13f1fc042f337e193ed3410ec
/Programming Language/exercises/ex8/stack_choice.rkt
321a30f38a7cb75691e108e52f0eb5243456dc71
[]
no_license
enw860/MyProject
e20ce1e911e32f0fcbfb02db71f169b94d2dfe0f
8152c3dedeef65bd1e0b54d3882ad4ce4fb166ea
refs/heads/master
2021-09-12T09:55:34.418156
2018-04-16T04:09:33
2018-04-16T04:09:33
106,640,241
0
0
null
null
null
null
UTF-8
Racket
false
false
4,732
rkt
stack_choice.rkt
#lang racket #| Choices and backtracking, Version 3 (UPDATED Mon Mar 5) |# #| Racket Notes 1. In the DrRacket menu, go to Language -> Choose Language... Click on Show Details, and make sure "Enforce constant definitions" is *NOT* checked. |# (require racket/control) (provide -< next fail choices generate num-between) ; A constant representing the state of having *no more choices*. (define done 'done) ; The stack of choice points, represented as a list. (define choices null) #| (-< expr ...) expr ... : Any expression. Evaluates and returns the first expression, but creates a "choice point" that can be returned to later with a different expression used. |# (define-syntax -< (syntax-rules () ; Given no options, return done. [(-<) done] ; Given one option, return the value. [(-< <expr1>) <expr1>] ; If there are two or more values, return the first one and ; store the others in a thunk, ; but *also stores the continuation of the -< expression*. [(-< <expr1> <expr2> ...) (let/cc cont ; 1. Store the current continuation and the remaining choices in a thunk. (add-choice! (thunk (cont (-< <expr2> ...)))) ; 2. Evaluate and return the first expression. <expr1>)])) #| (next) Returns the next choice, or `done` if there are no more choices. Sample usage (with -<): > (+ 10 (-< 1 2 3)) 11 > (next) 12 > (next) 13 > (next) 'done > (next) 'done |# (define (next) (if (null? choices) done ; Note the use of `prompt` here, so that calling a saved ; choice continuation returns its value from next to ; wherever next was called. This enables calling `next` ; inside larger expressions, e.g. (+ 10 (next)). (prompt ((get-choice!))))) ; NEW (for Lab 8 and Exercise 8) ; Similar to next, except it doesn't wrap the continuation call in a prompt. ; We use this to represent a continuation call that we explicitly want to ; throw away the current execution context, to resume at some previous choice point. (define (fail) (if (null? choices) done ((get-choice!)))) ;------------------------------------------------------------------------------- ; Stack helpers ;------------------------------------------------------------------------------- ; Wrapper functions around the push! and pop! macros. ; This is necessary for exporting purposes, as Racket doesn't allow ; mutation of module identifiers from outside of the module. ; See https://docs.racket-lang.org/guide/module-set.html. (define (add-choice! c) (push! choices c)) (define (get-choice!) (pop! choices)) (define-syntax push! (syntax-rules () [(push! <id> obj) (set! <id> (cons obj <id>))])) (define-syntax pop! (syntax-rules () [(pop! <id>) (let ([obj (first <id>)]) (set! <id> (rest <id>)) obj)])) ;------------------------------------------------------------------------------- ; Turning the choices into a stream ;------------------------------------------------------------------------------- (require "streams.rkt") ; Download from course website #| (all-choices) Returns a stream containing the currently-stored choices. |# (define (all-choices) (let ([val (next)]) (if (equal? val done) s-null (s-cons val (all-choices))))) #| (generate <expr>) <expr>: an expression using the ambiguous operator -< Evaluates to a stream containing all choices generated by <expr>. Note that this is basically (all-choices), except it captures the original expression as well. Sample usage: > (stream->list (generate (-< 1 2 3))) '(1 2 3) > (stream->list (generate (+ 10 (-< 1 2 3)))) '(11 12 13) > (stream->list (generate ((-< + *) (-< 2 3 4) (-< 100 200)))) '(102 202 103 203 104 204 200 400 300 600 400 800) |# (define-syntax generate (syntax-rules () [(generate <expr>) ; Note the use of prompt here. This ensures that the continuation(s) ; captured in <expr> don't extend beyond the expression itself. (let ([val (prompt <expr>)]) (if (equal? val 'done) s-null (s-cons val (all-choices))))])) ;------------------------------------------------------------------------------- ; Useful library functions. (Not core implementation, but utilities.) ;------------------------------------------------------------------------------- #| (num-between start end) start, end: integers Precondition: start <= end Returns a choice of a number in the range [start .. end], inclusive. |# (define (num-between start end) (if (equal? start end) (-< end) (-< start (num-between (+ 1 start) end))))
true
d76fa8289fb4a4db9c1101760f7fd089c8b865f1
bd528140fc0a7ada47a4cb848f34eae529620c1e
/3-05.rkt
7aaa671d3abb2d260d958395590aeee59ec1cfcd
[]
no_license
michaldarda/sicp
c09c197b35014d66f516f4a0a8d49f33e3c09a37
8ea78f8f0780f786057dfdaae24e44f16abf063b
refs/heads/master
2020-07-15T01:23:51.573237
2020-05-24T19:54:59
2020-05-24T19:54:59
205,447,221
4
0
null
null
null
null
UTF-8
Racket
false
false
1,534
rkt
3-05.rkt
#lang racket ;; lets assume this guy is given to us (define (rand-update x) (modulo (+ (* 214013 x) 2531011) (expt 2 32))) ;; (define random-init 1) (define rand (let ([x random-init]) (lambda () (set! x (rand-update x)) x))) ;; (define (random-in-range low high) (let ([range (- high low)]) (+ low (random range)))) (define (estimate-pi trials) (sqrt (/ 6 (monte-carlo trials cesaro-test)))) (define (cesaro-test) (= (gcd (rand) (rand)) 1)) (define (monte-carlo trials experiment) (define (iter trials-remaining trials-passed) (cond [(= trials-remaining 0) (/ trials-passed trials)] [(experiment) (iter (- trials-remaining 1) (+ trials-passed 1))] [else (iter (- trials-remaining 1) trials-passed)])) (iter trials 0)) (estimate-pi 10) (define (estimate-integral predicate x1 x2 y1 y2 trials) (define (test) (predicate (random-in-range x1 x2) (random-in-range y1 y2))) (let ([area (* (- x2 x1) (- y2 y1))]) (* (monte-carlo trials test) area))) (define (square x) (* x x)) ;; pi r^2 = computed ;; r = 3 ;; computed/(3^2) (define (estimate-pi2 trials) (define P (lambda (x y) (<= (+ (square (- x 5)) (square (- y 7))) (square 3)))) (let ([estimated-integral (exact->inexact (estimate-integral P 2 8 4 10 trials))]) (/ estimated-integral (square 3)))) (estimate-pi2 10000)
false
b0d6c392d9b0bb718611e083f2880887850a2928
398b8a8f19808a963a97111400796940295164ed
/test/grammars/waxeye.rkt
5ecc1766dc174a47da66e1af24b4a96d810210a3
[ "MIT" ]
permissive
mkohlhaas/waxeye
cb5ba8d3899db7f4417778a5d5d59b0db298daf0
81a250a8b7a2859c06a15c429a6c5366e9f0e161
refs/heads/master
2022-08-02T01:49:46.196364
2020-05-27T17:59:08
2020-05-27T17:59:08
267,149,456
0
0
NOASSERTION
2020-05-26T20:51:52
2020-05-26T20:51:50
null
UTF-8
Racket
false
false
1,761
rkt
waxeye.rkt
;; Waxeye Parser Generator ;; www.waxeye.org ;; Copyright (C) 2008-2010 Orlando Hill ;; Licensed under the MIT license. See 'LICENSE' for details. ;; These are tests for the 'Grammar' non-terminal (Grammar ; <- This is the non-terminal's name ;; Following the name are pairs of input string and expected output. The ;; output is either the keyword 'pass', the keyword 'fail' or an AST. The AST ;; specifies the structure of the expected tree, the names of the nodes and ;; the individual characters. If you don't want to specify the whole tree, ;; just use the wild-card symbol '*' for the portion of the tree you want to ;; skip. "" ; <- This is the input (Grammar) ; <- This is the expected output "A <- 'a'" pass ; <- The keyword 'pass' "A" fail ; <- The keyword 'fail' "A <- 'a' B <- 'b'" (Grammar (Definition (Identifier #\A) *) ; <- Here we skip some of (Definition (Identifier #\B) *)) ; Definition's children "A <- 'a'" (Grammar (*)) ; <- Here we specify a child tree of any type "A <- [a-z] *[a-z0-9]" (Grammar (Definition (Identifier #\A) (LeftArrow) (Alternation *))) "A <- 'a'" (Grammar (Definition (Identifier #\A) (LeftArrow) (Alternation (Sequence (Unit (Literal (LChar #\a))))))) ) (Literal "'in'" (Literal (LChar #\i) (LChar #\n)) "''" fail ) (Range "" fail "-" (Range (Char #\-)) "a" (Range (Char #\a)) "a-z" (Range (Char #\a) (Char #\z)) "\\u{0C}" (Range (Hex #\0 #\C)) "\\u{30}-\\u{39}" (Range (Hex #\3 #\0) (Hex #\3 #\9)) "0-\\u{39}" (Range (Char #\0) (Hex #\3 #\9)) "\\u{30}-9" (Range (Hex #\3 #\0) (Char #\9)) "\\u{1F381}-\\u{1F382}" (Range (Hex #\1 #\F #\3 #\8 #\1) (Hex #\1 #\F #\3 #\8 #\2)) ) (Alt "|" pass "| " pass " | " fail )
false
749bcc9eebfacd6022d50c75768b24234e60f9be
2c819623a83d8c53b7282622429e344389ce4030
/test/rv64ui/addw.rkt
9b28d0bc7dfbf5baf2edf6239429c424cafa158b
[]
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,066
rkt
addw.rkt
#lang rosette (require "../riscv/test-macros.rkt") (provide run-riscv-addw-tests) (define (run-riscv-addw-tests) ; See LICENSE for license details. ;***************************************************************************** ; 'addw.S ;----------------------------------------------------------------------------- ; ; Test 'addw instruction. ; ;include "riscv_test.h" ;include "test_macros.h" ;------------------------------------------------------------- ; Arithmetic tests ;------------------------------------------------------------- (TEST_RR_OP 2 'addw #x00000000 #x00000000 #x00000000 ); (TEST_RR_OP 3 'addw #x00000002 #x00000001 #x00000001 ); (TEST_RR_OP 4 'addw #x0000000a #x00000003 #x00000007 ); (TEST_RR_OP 5 'addw #xffffffffffff8000 #x0000000000000000 #xffffffffffff8000 ); (TEST_RR_OP 6 'addw #xffffffff80000000 #xffffffff80000000 #x00000000 ); (TEST_RR_OP 7 'addw #x000000007fff8000 #xffffffff80000000 #xffffffffffff8000 ); (TEST_RR_OP 8 'addw #x0000000000007fff #x0000000000000000 #x0000000000007fff ); (TEST_RR_OP 9 'addw #x000000007fffffff #x000000007fffffff #x0000000000000000 ); (TEST_RR_OP 10 'addw #xffffffff80007ffe #x000000007fffffff #x0000000000007fff ); (TEST_RR_OP 11 'addw #xffffffff80007fff #xffffffff80000000 #x0000000000007fff ); (TEST_RR_OP 12 'addw #x000000007fff7fff #x000000007fffffff #xffffffffffff8000 ); (TEST_RR_OP 13 'addw #xffffffffffffffff #x0000000000000000 #xffffffffffffffff ); (TEST_RR_OP 14 'addw #x0000000000000000 #xffffffffffffffff #x0000000000000001 ); (TEST_RR_OP 15 'addw #xfffffffffffffffe #xffffffffffffffff #xffffffffffffffff ); (TEST_RR_OP 16 'addw #xffffffff80000000 #x0000000000000001 #x000000007fffffff ); ;------------------------------------------------------------- ; Source/Destination tests ;------------------------------------------------------------- (TEST_RR_SRC1_EQ_DEST 17 'addw 24 13 11 ); (TEST_RR_SRC2_EQ_DEST 18 'addw 25 14 11 ); (TEST_RR_SRC12_EQ_DEST 19 'addw 26 13 ); ;------------------------------------------------------------- ; Bypassing tests ;------------------------------------------------------------- (TEST_RR_DEST_BYPASS 20 0 'addw 24 13 11 ); (TEST_RR_DEST_BYPASS 21 1 'addw 25 14 11 ); (TEST_RR_DEST_BYPASS 22 2 'addw 26 15 11 ); (TEST_RR_SRC12_BYPASS 23 0 0 'addw 24 13 11 ); (TEST_RR_SRC12_BYPASS 24 0 1 'addw 25 14 11 ); (TEST_RR_SRC12_BYPASS 25 0 2 'addw 26 15 11 ); (TEST_RR_SRC12_BYPASS 26 1 0 'addw 24 13 11 ); (TEST_RR_SRC12_BYPASS 27 1 1 'addw 25 14 11 ); (TEST_RR_SRC12_BYPASS 28 2 0 'addw 26 15 11 ); (TEST_RR_SRC21_BYPASS 29 0 0 'addw 24 13 11 ); (TEST_RR_SRC21_BYPASS 30 0 1 'addw 25 14 11 ); (TEST_RR_SRC21_BYPASS 31 0 2 'addw 26 15 11 ); (TEST_RR_SRC21_BYPASS 32 1 0 'addw 24 13 11 ); (TEST_RR_SRC21_BYPASS 33 1 1 'addw 25 14 11 ); (TEST_RR_SRC21_BYPASS 34 2 0 'addw 26 15 11 ); (TEST_RR_ZEROSRC1 35 'addw 15 15 ); (TEST_RR_ZEROSRC2 36 'addw 32 32 ); (TEST_RR_ZEROSRC12 37 'addw 0 ); (TEST_RR_ZERODEST 38 'addw 16 30 ); )
false
b01a838bc66cb09181749421629b13f4c1520833
3b2cf17b2d77774a19e9a9540431f1f5a840031e
/src/lang/racket-ffi/db.rkt
7647acb4fb38de58979b43f5b727b230163ca55e
[]
no_license
brownplt/pyret-lang-resugarer
5bfaa09e52665657abad8d9d863e8915e0029a29
49519679aefb7b280a27938bc7bfbaaecc0bd4fc
HEAD
2016-09-06T03:59:24.608789
2014-06-27T03:45:02
2014-06-27T03:45:02
13,936,477
1
1
null
null
null
null
UTF-8
Racket
false
false
1,277
rkt
db.rkt
#lang pyret import dblib as dblib provide { DB: DB, sqlite: sqlite, Connection: Connection, connection: connection, Result: Result, simple_result: simple_result, rows_result: rows_result } end data DB: # | postgres with: # connect(user :: String, database :: String, password :: String): # dblib.postgresql-connect(user, ) # end | sqlite with: connect(_, database :: String): connection(dblib.sqlite3-connect(database)) end end data Connection: | connection(con) with: query(self, sql :: String, args :: List) -> Result: res = dblib.query(self.con, sql, args) if String(res): simple_result else if List(res): rows_result(res) end end, query_(self, sql :: String) -> Result: self.query(sql, []) end, connected(self): dblib.is-connected(self.con) end, disconnect(self): if dblib.is-connected(self.con): dblib.disconnect(self.con) nothing else: nothing end end end data Result: # racket makes it unclear what simple_results will return (and states it will # will change). So for now, just drop results. | simple_result | rows_result(rows :: List<List>) end
false
ac96a3c92f62b6706f5add75e30223946c3b3d08
d0ea449400a715f50fd720c265d2b923c34bc464
/info.rkt
571fe125753173fa9a73bf89346d7bc67495bcca
[]
no_license
wargrey/psd
c3d69b8c7d6577cdac9be433be832e80d2bb32d4
73b16a52e0777250d02e977f7dcbd7c1d98ef772
refs/heads/master
2020-12-02T06:26:02.875227
2018-07-16T11:00:58
2018-07-16T11:00:58
96,830,933
1
1
null
null
null
null
UTF-8
Racket
false
false
392
rkt
info.rkt
#lang info (define collection 'use-pkg-name) (define pkg-desc "PSD: Read and Write Photoshop Documents") (define deps '("base" "typed-racket-lib" "typed-racket-more" "draw-lib")) (define build-deps '("scribble-lib" "racket-doc")) (define version "1.0") (define pkg-authors '(wargrey)) (define test-omit-paths 'all) (define scribblings '(["tamer/psd.scrbl" (main-doc) (parsing-library)]))
false
93c9783907676c605fddb7bc8e9c4da9070f9a11
7759bda0d7e3b45aa77f25657c365b525f22a473
/monadic-eval/monad/monad-cycle.rkt
86501a5c59ec07e81896d336c835a3defac3aae0
[]
no_license
plum-umd/abstracting-definitional-interpreters
89bafe22c8f7d861c43edd2153f7309958b0c398
7a51f429227dd11b371b9a27f83b8aa0f6adb5d3
refs/heads/master
2021-08-19T07:13:31.621906
2017-11-25T04:19:30
2017-11-25T04:19:30
5,044,629
61
2
null
2017-11-25T04:19:31
2012-07-14T04:27:57
TeX
UTF-8
Racket
false
false
992
rkt
monad-cycle.rkt
#lang racket/unit (require racket/set "../signatures.rkt" "../transformers.rkt" "../map.rkt") (import) (export monad^ menv^ mstore^ mcycle^) ;; M ρ σ a := ρ → σ → a × σ (define M (ReaderT (FailT (StateT #f (NondetT (ReaderT ID)))))) (define-monad M) ;; mrun : (M ρ σ Σ a) [→ ρ [→ σ [→ Σ]]] → a × σ (define (mrun m [ρ₀ ∅] [σ₀ ∅] [Σ₀ {set}]) (run-ReaderT Σ₀ (run-StateT σ₀ (run-ReaderT ρ₀ m)))) (define (mret x) x) ;; env^ impl: (define ask-env (bind ask (compose1 return car))) (define (local-env ρ m) (do (cons _ Σ) ← ask (local (cons ρ Σ) m))) ;; store^ impl: (define get-store (with-monad M get)) (define put-store (with-monad M put)) (define (update-store f) (with-monad M (do σ ← get-store (put-store (f σ))))) ;; cycle^ impl: (define ask-cycle (bind ask (compose1 return cdr))) (define (local-cycle Σ m) (do (cons ρ _) ← ask (local (cons ρ Σ) m)))
false
851ffa570764d1f4509646dce30386e9bf0485c3
94e9923b043132127488bf59887a156d976e2207
/ex_2_53.rkt
788138f5ad779c48d63aa8dc37d38c483ee02413
[]
no_license
pbruyninckx/sicp
31b5a76cf9a06a0bb24bd8d7b75353c1eb6358b9
133e2ac911a3345594ae265661d7d15f0c1927c9
refs/heads/master
2020-04-18T18:27:57.961188
2019-10-19T12:14:06
2019-10-19T12:14:06
167,684,388
1
1
null
null
null
null
UTF-8
Racket
false
false
509
rkt
ex_2_53.rkt
#lang racket ; Ex 2.53 (list 'a 'b 'c) ;(a b c) (list (list 'george)) ;((george)) (cdr '((x1 x2) (y1 y2))) ; ((y1 y2)) (cadr '((x1 x2) (y1 y2))) ; (y1 y2) (pair? (car '(a short list))) ; #f (memq 'red '((red shoes) (blue socks))) ; #f (memq 'red '(red shoes blue socks)) ; (red shoes blue socks) ; Ex 2.54 (define (equal? l1 l2) (cond ((not (eq? (pair? l1) (pair? l2))) #f) ((pair? l1) (and (equal? (car l1) (car l2)) (equal? (cdr l1) (cdr l2)))) (else (eq? l1 l2))))
false
5931fdb273af68cbdc480054243b958c3ecd0190
3e9f044c5014959ce0e915fe1177d19f93d238ed
/racket/com-spacetimecat/edit/quick-open.rkt
bf3ad673ac35e2a89072ca3692c284c14288f6b3
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "LicenseRef-scancode-public-domain", "CC0-1.0", "BSD-2-Clause" ]
permissive
edom/work
5e15c311dd49eb55fafbff3455cae505fa51643a
df55868caa436efc631e145a43e833220b8da1d0
refs/heads/master
2022-10-10T22:25:11.652701
2020-02-26T19:42:08
2020-02-26T19:44:58
138,504,284
0
1
NOASSERTION
2022-10-06T01:38:07
2018-06-24T18:03:16
TeX
UTF-8
Racket
false
false
2,303
rkt
quick-open.rkt
#lang s-exp "lang.rkt" (require setup/dirs ) (provide find-paths-for-quick-open ) (define/contract (get-dirs-for-quick-open) (-> (listof path?)) ;(define orig-dir (find-system-path 'orig-dir)) ;(define exec-file (find-system-path 'exec-file)) ;(define main-collects-dir (find-system-path 'collects-dir)) ;; TODO: (current-library-collection-links) before (current-library-collection-paths)? (define racket-src-dir (string->path "/junk/racket-src")) (list-remove-duplicates (list-map path-remove-trailing-slash `( ,(current-directory) ,@(current-library-collection-paths) ,(find-user-pkgs-dir) ,(find-pkgs-dir) ,racket-src-dir )))) (define/contract (find-paths-for-quick-open) (-> (listof path?)) (list-concat-map traverse (get-dirs-for-quick-open))) (define ignored-directory-names (list-map symbol->string '( |.git| ))) (define wanted-file-extensions (list-map (λ s -> (string-append "." (symbol->string s))) '( rkt scrbl scm c cc cxx cpp c++ h hh hxx hpp h++ md txt org rst tex css js ts ))) (define (want-dir? path) (not (list-member path ignored-directory-names))) (define (want-extension? str) (list-member (string-downcase str) wanted-file-extensions)) (define (want-file? path) (define-values (_base name _dir?) (split-path path)) (and (path? name) ;; otherwise name may be 'up or 'same (want-extension? (path-get-extension/utf-8 path #:or "")))) ;; Recursively list the files in dir. ;; If dir is not a directory, this returns an empty list. (define/contract (traverse dir) (-> path? (listof path?)) (let/ec return (unless (directory-exists? dir) (return '())) (define children (directory-list dir #:build? #t)) (define-values (child-dirs child-files) (list-partition directory-exists? children)) (define wanted-dirs (list-filter want-dir? child-dirs)) (define wanted-files (list-filter want-file? child-files)) (list-append wanted-files (list-concat-map traverse wanted-dirs))))
false
6a31107006f16be4704e9fb25cb432a727fc2a07
1f7978b861d63d5048b169ae7eadb94014c9deee
/hw4tests.rkt
9c0f6d7038ab4fd7bbc29a65964129ef393f05f9
[]
no_license
thesourabh/racket-practice
45cf0015b4aa4c04d5c87a55e7b49c7260f63671
096224770a0a21179e40de3a3d16f0634104ee26
refs/heads/master
2021-01-15T21:44:20.054785
2014-02-28T12:20:01
2014-02-28T12:20:01
null
0
0
null
null
null
null
UTF-8
Racket
false
false
3,870
rkt
hw4tests.rkt
#lang racket (require "hw4.rkt") ;; A simple library for displaying a 2x3 grid of pictures: used ;; for fun in the tests below (look for "Tests Start Here"). (require (lib "graphics.rkt" "graphics")) (open-graphics) (define window-name "Programming Languages, Homework 4") (define window-width 700) (define window-height 500) (define border-size 100) (define approx-pic-width 200) (define approx-pic-height 200) (define pic-grid-width 3) (define pic-grid-height 2) (define (open-window) (open-viewport window-name window-width window-height)) (define (grid-posn-to-posn grid-posn) (when (>= grid-posn (* pic-grid-height pic-grid-width)) (error "picture grid does not have that many positions")) (let ([row (quotient grid-posn pic-grid-width)] [col (remainder grid-posn pic-grid-width)]) (make-posn (+ border-size (* approx-pic-width col)) (+ border-size (* approx-pic-height row))))) (define (place-picture window filename grid-posn) (let ([posn (grid-posn-to-posn grid-posn)]) ((clear-solid-rectangle window) posn approx-pic-width approx-pic-height) ((draw-pixmap window) filename posn))) (define (place-repeatedly window pause stream n) (when (> n 0) (let* ([next (stream)] [filename (cdar next)] [grid-posn (caar next)] [stream (cdr next)]) (place-picture window filename grid-posn) (sleep pause) (place-repeatedly window pause stream (- n 1))))) ;; Tests Start Here ; These definitions will work only after you do some of the problems ; so you need to comment them out until you are ready. ; Add more tests as appropriate, of course. (define nums (sequence 0 5 1)) (define files (string-append-map (list "dan" "dog" "curry" "dog2") ".jpg")) (define funny-test (stream-for-n-steps funny-number-stream 16)) ; a zero-argument function: call (one-visual-test) to open the graphics window, etc. (define (one-visual-test) (place-repeatedly (open-window) 0.5 (cycle-lists nums files) 27)) ; similar to previous but uses only two files and one position on the grid (define (visual-zero-only) (place-repeatedly (open-window) 0.5 (stream-add-zero dan-then-dog) 27)) (print "Test 1: ") (equal? (sequence 3 11 2) (list 3 5 7 9 11)) (print "Test 1: ") (equal? (sequence 3 8 3) (list 3 6)) (print "Test 1: ") (equal? (sequence 3 2 1) null) (print "Test 2: ") (equal? (string-append-map (list "foo1" "foo2" "foo3") "bar") (list "foo1bar" "foo2bar" "foo3bar")) (print "Test 3: ") (= 3 (list-nth-mod (list 1 2 3 4 5) 12)) (print "Test 5: ") (equal? (stream-for-n-steps funny-number-stream 10) (list 1 2 3 4 -5 6 7 8 9 -10)) (print "Test 6: ") (equal? (stream-for-n-steps dan-then-dog 10) (list "dan.jpg" "dog.jpg" "dan.jpg" "dog.jpg" "dan.jpg" "dog.jpg" "dan.jpg" "dog.jpg" "dan.jpg" "dog.jpg")) (print "Test 7: ") (equal? (stream-for-n-steps (stream-add-zero funny-number-stream) 10) (list (cons 0 1) (cons 0 2) (cons 0 3) (cons 0 4) (cons 0 -5) (cons 0 6) (cons 0 7) (cons 0 8) (cons 0 9) (cons 0 -10))) (print "Test 8: ") (equal? (stream-for-n-steps (cycle-lists (list 1 2 3) (list "a" "b")) 10) (list (cons 1 "a") (cons 2 "b") (cons 3 "a") (cons 1 "b") (cons 2 "a") (cons 3 "b") (cons 1 "a") (cons 2 "b") (cons 3 "a") (cons 1 "b"))) (print "Test 8: ") (equal? (stream-for-n-steps (cycle-lists (list 1 2 3 4 5) (list "a" "b" "c")) 12) (list (cons 1 "a") (cons 2 "b") (cons 3 "c") (cons 4 "a") (cons 5 "b") (cons 1 "c") (cons 2 "a") (cons 3 "b") (cons 4 "c") (cons 5 "a") (cons 1 "b") (cons 2 "c"))) (print "Test 9: ") (equal? (vector-assoc 5 (vector 1 2 (cons 5 32) 3 (cons 5 33) 4 5 6 7)) (cons 5 32)) (print "Test 10: ") (define myfunc (cached-assoc (list (cons 1 2) (cons 2 4) (cons 3 8) (cons 4 16) (cons 5 32) (cons 6 64)) 3)) (equal? (myfunc 3) (cons 3 8))
false
146ad3af63ec1c4027abcaae0e5d9a7a1f32266f
662e55de9b4213323395102bd50fb22b30eaf957
/dissertation/scrbl/shallow/with-cache/mixed-bestpath.rktd
071eb4eaa56348df52e65c5e2439fe159356a1f0
[]
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
100
rktd
mixed-bestpath.rktd
;; This file was generated by the `with-cache` library on 2020-11-17 ((fsm) (3) 0 () 0 () () 11/10)
false
09c12346c0f477432f46bf6b8baaf6dc75034deb
b64657ac49fff6057c0fe9864e3f37c4b5bfd97e
/ch2/ex-47.rkt
235108419d9d8af99d68bfc3f775f319880c6b5e
[]
no_license
johnvtan/sicp
af779e5bf245165bdfbfe6965e290cc419cd1d1f
8250bcc7ee4f4d551c7299643a370b44bc3f7b9d
refs/heads/master
2022-03-09T17:30:30.469397
2022-02-26T20:22:24
2022-02-26T20:22:24
223,498,855
0
0
null
null
null
null
UTF-8
Racket
false
false
229
rkt
ex-47.rkt
#!/usr/bin/racket #lang sicp (define (make-frame orig e1 e2) (list orig e1 e2)) ; orig -> car ; e1 -> cadr ; e2 -> caddr (define (make-frame2 orig e1 e2) (cons orig (cons e1 e2))) ; orig -> car ; e1 -> cadr ; e2 -> cddr
false
194dd504361a98e20c230f9c1a6b596dbdb6a896
b08b7e3160ae9947b6046123acad8f59152375c3
/Programming Language Detection/Experiment-2/Dataset/Train/Racket/word-wrap-2.rkt
d39d7034dceb6a1fe98c7c6e7c1056d80d00b18d
[]
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
759
rkt
word-wrap-2.rkt
#lang racket (define (wrap words width) (define (maybe-cons xs xss) (if (empty? xs) xss (cons xs xss))) (match/values (for/fold ([lines '()] [line '()] [left width]) ([w words]) (define n (string-length w)) (cond [(> n width) ; word longer than line => line on its own (values (cons (list w) (maybe-cons line lines)) '() width)] [(> n left) ; not enough space left => new line (values (cons line lines) (list w) (- width n 1))] [else (values lines (cons w line) (- left n 1))])) [(lines line _) (apply string-append (for/list ([line (reverse (cons line lines))]) (string-join line #:after-last "\n")))])) ;;; Usage: (wrap (string-split text) 70)
false
71ebdbed5f42620250faf51804155c952932fe21
954cbc297b8e659888639dfc1f153879c4401226
/labs/scheme/3-higher-order-functions/lab-3.rkt
31a6c1f74add604c905485c09bd47b7b268b12b4
[]
no_license
kirilrusev00/fmi-fp
3beb41d8e86d3ddba048e2b853a74bc8eaf24caa
1c6c76e18982b13fcdfb9dc274eb29b73c2f6167
refs/heads/main
2023-03-01T09:23:01.540527
2021-02-06T20:04:03
2021-02-06T20:04:03
309,650,566
1
0
null
null
null
null
UTF-8
Racket
false
false
2,603
rkt
lab-3.rkt
;;Задача 1 (define (constantly c) (lambda (x) c) ) ;;Задача 2 (define (flip f) (lambda (x y) (f y x))) ;;Задача 3 (define (complement p) (lambda (x) (not (p x)))) ;;Задача 4 (define (compose f g) (lambda (x) (f (g x)))) ;;Задача 5 (define (repeat n f) (define (loop i rep) (if (= i n) rep (loop (+ i 1) (compose rep f)))) (loop 0 (lambda (x) x))) ;;Задача 6 (define dx 1/100000) (define (derive f) (lambda (x) (/ (- (f (+ x dx)) (f x)) dx))) ;;Задача 7 (define (derive-n n f) (define (loop i der) (if (= i n) der (loop (+ i 1) (derive der)))) (loop 0 f)) ;------------------------------------------------------ (define (accumulate-p operation transform initial start next shouldStop? ) (define (helper i) (if (shouldStop? i) initial (operation (transform i) (helper (next i))) ) ) (helper start) ) (define (accumulate operation transform initial start next end ) (define (helper i) (if (> i end) initial (operation (transform i) (helper (next i))) ) ) (helper start) ) (define accumulate-r accumulate) (define (accumulate-i operation transform initial start next end ) (define (loop i result) (if (> i end) result (loop (next i) (operation result (transform i)) ) ) ) (loop start initial) ) (define accumulate-l accumulate-r) (define (sum-from-1-to n) (accumulate + id 0 1 ++ n) ) (define (sum-square-from-1-to n) (accumulate + (lambda (x) (* x x)) 0 1 ++ n) ) ;;Задача 8 (define (!! n) (accumulate-i * (lambda (x) x) 1 (if (even? n) 2 1) (lambda (x) (+ x 2)) n ) ) (define (df n) (accumulate-p * (lambda (x) x) 1 n (lambda (x) (- x 2)) (lambda (x) (< x 1)) ) )
false
c15fc46d663c41f685d977437d7a0e680a666442
ed8b2ac4d175b75dbd1a368b1234b4d64ace38b4
/sandboxes.rkt
d09ea9831a6ec7cc520a40b7e83273589a442cfc
[]
no_license
offby1/rudybot
692204f94587be24d4330ebdc597bf7543a27251
69df1f966dea1ceed9616e50535e92d6a90f6171
refs/heads/master
2022-07-17T04:30:13.333880
2022-06-29T17:52:57
2022-06-29T17:52:57
65,196
34
5
null
2016-08-08T03:36:48
2008-10-20T01:29:49
Racket
UTF-8
Racket
false
false
8,903
rkt
sandboxes.rkt
#lang racket ;; if porting this to Python, consider using either https://github.com/google/nsjail or ;; https://github.com/python-discord/snekbox (which is based upon it). (require racket/sandbox net/url) (module+ test (require rackunit rackunit/text-ui)) (struct sandbox (evaluator last-used-time) #:transparent #:mutable) (provide (rename-out [public-make-sandbox make-sandbox])) (define (public-make-sandbox #:lang [lang '(begin (require racket))] #:timeout-seconds [timeout-seconds 10]) (sandbox (parameterize ([sandbox-output 'string] [sandbox-error-output 'string] [sandbox-eval-limits (list timeout-seconds 50)] [sandbox-path-permissions '([exists "/"])]) (call-with-limits 10 #f (lambda () (let ([port (and (string? lang) (regexp-match? #rx"^http://" lang) (get-pure-port (string->url lang)))]) (if port (make-module-evaluator port) (make-evaluator lang)))))) 0)) (define (sandbox-eval sb string) (set-sandbox-last-used-time! sb (current-inexact-milliseconds)) ((sandbox-evaluator sb) string)) ;; returns the sandbox, force/new? can be #t to force a new sandbox, ;; or a box which will be set to #t if it was just created (define (get-sandbox-by-name ht name #:lang [lang '(begin (require scheme))] #:timeout-seconds [timeout-seconds 10] #:force/new? [force/new? #f]) (define sb (hash-ref ht name #f)) (define (make) (let ([sb (public-make-sandbox #:lang lang #:timeout-seconds timeout-seconds)]) (when (box? force/new?) (set-box! force/new? #t)) (add-grabber name sb) (hash-set! ht name sb) sb)) (cond [(not (and sb (evaluator-alive? (sandbox-evaluator sb)))) (when (and (not sb) (>= (hash-count ht) (*max-sandboxes*))) ;; evict the sandbox that has been unused the longest, don't do this ;; if we have a dead sandbox -- since we'll just replace it. (let ([moldiest #f]) (for ([(name sb) (in-hash ht)]) (let ([t (sandbox-last-used-time sb)]) (unless (and moldiest (> t (car moldiest))) (set! moldiest (list t name sb))))) (when (not moldiest) (error "assertion-failure")) (kill-evaluator (sandbox-evaluator (caddr moldiest))) (hash-remove! ht (cadr moldiest)))) ;; (when sb ...inform user about reset...) (make)] [(and force/new? (not (box? force/new?))) (kill-evaluator (sandbox-evaluator sb)) (make)] [else sb])) (define (sandbox-get-stdout s) (get-output (sandbox-evaluator s))) (define (sandbox-get-stderr s) (get-error-output (sandbox-evaluator s))) (define *max-sandboxes* (make-parameter 3)) ;; A subtle point here is memory that is accessible from the sandbox: ;; the value shouldn't be accessible outside the originating sandbox to ;; prevent this from being a security hole (use `give' to avoid being ;; charged for the allocated memory). Solve this by registering the ;; value with a gensym handle in the sending sandbox's namespace, and ;; make the handle accessible in the other sandbox. The handle is ;; available in the receiving sandbox and weakly held in the giving ;; sandbox, so if the receiver dies the handle can be GCed and with it ;; the value. (define given-handles (gensym 'given-values)) (define (sandbox->given-registry sb) (call-in-sandbox-context (sandbox-evaluator sb) (lambda () (namespace-variable-value given-handles #f (lambda () (let ([t (make-weak-hasheq)]) (namespace-set-variable-value! given-handles t) t)))) #t)) (define name->grabber (make-hash)) ;; give : Sandbox String Any -> Void (define (sandbox-give from to val) ;; Evaluate the expression (all the usual things apply: should catch errors, ;; and require a single value too). See above for an explanation for the ;; handle. (define handle (gensym 'given)) (hash-set! (sandbox->given-registry from) handle val) ;; Note: removing registered values depends on the handle being released, so ;; (a) the following should be done only for existing nicks (otherwise ;; error), (b) when a nick leaves it should be removed from this table (hash-set! name->grabber to (lambda () (if (evaluator-alive? (sandbox-evaluator from)) ;; note: this could be replaced with `val' -- but then this ;; closure will keep a reference for the value, making it ;; available from the receiving thread! (hash-ref (sandbox->given-registry from) handle (lambda () (error 'grab "internal error (the value disappeared)"))) (error 'grab "the sending evaluator died"))))) ;; adds the GRAB binding to a given sandbox (define (add-grabber name sb) (call-in-sandbox-context (sandbox-evaluator sb) (lambda () (define (GRAB) ((hash-ref name->grabber name (lambda () void)))) (namespace-set-variable-value! 'GRAB GRAB)))) (print-hash-table #t) (module+ test (define sandboxes-tests (let ([*sandboxes-by-nick* (make-hash)]) (test-suite "sandboxes" (let ([s (get-sandbox-by-name *sandboxes-by-nick*"charlie")]) (check-equal? (sandbox-eval s "(dict-update '((a . 9) (b . 2) (a . 1)) 'a add1 0)") '((a . 10) (b . 2) (a . 1)))) (test-case "simple get" (let ([s (get-sandbox-by-name *sandboxes-by-nick*"charlie")]) (check-pred sandbox? s) (check-equal? (sandbox-eval s "3") 3))) (test-case "command line args inaccessible" (let ([s (get-sandbox-by-name *sandboxes-by-nick* "charlie")]) (check-pred zero? (vector-length (sandbox-eval s "(current-command-line-arguments)"))))) (test-case "output" (let ([s (get-sandbox-by-name *sandboxes-by-nick*"charlie")]) (sandbox-eval s "(display \"You bet!\")") (check-equal? (sandbox-get-stdout s) "You bet!") (sandbox-eval s "(display \"Whatever\")") (check-equal? (sandbox-get-stdout s) "Whatever"))) (test-suite "timeouts" (test-exn "sleeps too long" exn:fail? (lambda () (sandbox-eval (get-sandbox-by-name *sandboxes-by-nick* "sleepy" #:timeout-seconds 1) "(sleep 20)"))) (test-exn "gacks on incomplete input" exn:fail? (lambda () (sandbox-eval (get-sandbox-by-name *sandboxes-by-nick*"oops") "(" )))) (let ([charlies-sandbox #f] [keiths-sandbox #f]) (test-suite "distinct " #:before (lambda () (set! *sandboxes-by-nick* (make-hash)) (set! charlies-sandbox (get-sandbox-by-name *sandboxes-by-nick* "charlie")) (set! keiths-sandbox (get-sandbox-by-name *sandboxes-by-nick* "keith"))) (test-false "keeps sandboxes distinct, by name" (eq? charlies-sandbox keiths-sandbox)) (test-case "remembers state" (sandbox-eval charlies-sandbox "(define x 99)") (let ([this-better-still-be-charlies (get-sandbox-by-name *sandboxes-by-nick*"charlie")]) (check-equal? (sandbox-eval this-better-still-be-charlies "x") 99)) (check-exn exn:fail? (lambda () (sandbox-eval keiths-sandbox "x")) "keith's sandbox didn't gack when I referenced 'x' -- even though we never defined it.")))) ;; I'm not sure what I want to do here. On the one hand, I want ;; all calls to "getenv" to fail in the sandbox; on the other ;; hand, I cannot think of an elegant way to have the sandbox ;; itself ensure that (currently I'm counting on the bot's "main" ;; function to clear the environment). ;;; (test-case ;;; "environment" ;;; (let ([s (get-sandbox-by-name *sandboxes-by-nick* "yow")]) ;;; (check-false (sandbox-eval s "(getenv \"HOME\")")))) (test-case "immediately recycles dead sandbox" (check-exn exn:fail:sandbox-terminated? (lambda () (sandbox-eval (get-sandbox-by-name *sandboxes-by-nick* "yow") "(kill-thread (current-thread))"))) (check-equal? (sandbox-eval (get-sandbox-by-name *sandboxes-by-nick* "yow") "3") 3) ) ))) (run-tests sandboxes-tests)) (provide get-sandbox-by-name sandbox-evaluator sandbox-eval sandbox-get-stderr sandbox-get-stdout sandbox-give)
false
3273f4d044af6e73fa4143ef44748e8b0685dca5
716582f7fafb0d820027ffecf317c8648f883d49
/src/language/coercion.rkt
9c819a187161322dd166549376b6bf2cb4853bb4
[ "MIT" ]
permissive
pnwamk/schml
cc6497661a38d66f9c625102c0cdc2ecaff61c27
3deea57f0e87b9cc63689e4b28b46626a7906d31
refs/heads/master
2021-05-15T16:52:26.416645
2017-10-18T01:06:21
2017-10-18T01:48:26
107,545,644
0
0
null
2017-10-19T12:50:52
2017-10-19T12:50:52
null
UTF-8
Racket
false
false
2,763
rkt
coercion.rkt
#lang typed/racket/base (require "forms.rkt" "primitives.rkt") (provide (all-defined-out) (all-from-out "forms.rkt" "primitives.rkt")) #|-----------------------------------------------------------------------------+ | Language/Coercion created by cast->coercions +------------------------------------------------------------------------------+ | Description: This language represents all casts as equivalent coercions. | Subsequent pass languages may represent cast as coercions or casts but both | are not permitted. The types of various passes cannot enforce this but latter | passes should enforce this constraint dynamically. +-----------------------------------------------------------------------------|# (define-type Coercion-Lang (Prog (List String Natural Schml-Type) Crcn-Expr)) (define-type Crcn-Expr (Rec E (U ;; Non-Terminals ;; replaced (Cast E Schml-Type Schml-Type Label) with next line (Observe E Schml-Type) No-Op (Cast E (Coercion Schml-Coercion)) (Lambda Uid* E) (Letrec Crcn-Bnd* E) (Let Crcn-Bnd* E) (App E (Listof E)) (Op Schml-Primitive (Listof E)) (If E E E) (Switch E (Switch-Case* E) E) (Begin Crcn-Expr* E) (Repeat Uid E E Uid E E) ;; Guarded effects (Gbox E) (Gunbox E) (Gbox-set! E E) (Gvector E E) (Gvector-set! E E E) (Gvector-ref E E) (Gvector-length E) ;; Monotonic references (Mbox E Schml-Type) (Munbox E) ;; fast read (Mbox-set! E E) ;; fast write (MBoxCastedRef E Schml-Type) (MBoxCastedSet! E E Schml-Type) (Mvector E E Schml-Type) (Mvector-ref E E) ;; fast read (Mvector-set! E E E) ;; fast write (MVectCastedRef E E Schml-Type) (MVectCastedSet! E E E Schml-Type) (Mvector-length E) ;; (Create-tuple (Listof E)) (Tuple-proj E Index) ;; Terminals (Var Uid) (Quote Cast-Literal) ;; Dynamic Operations (Dyn-Tuple-Proj E E E) (Dyn-GVector-Len E E) (Dyn-GVector-Set! E E E Schml-Type Blame-Label) (Dyn-GVector-Ref E E Blame-Label) (Dyn-GRef-Set! E E Schml-Type Blame-Label) (Dyn-GRef-Ref E Blame-Label) (Dyn-MVector-Set! E E E Schml-Type Blame-Label) (Dyn-MVector-Ref E E Blame-Label) (Dyn-MRef-Set! E E Schml-Type Blame-Label) (Dyn-MRef-Ref E Blame-Label) (Dyn-Fn-App E Crcn-Expr* Schml-Type* Blame-Label) ))) (define-type Crcn-Expr* (Listof Crcn-Expr)) (define-type Crcn-Bnd (Pairof Uid Crcn-Expr)) (define-type Crcn-Bnd* (Listof Crcn-Bnd))
false
39c5e13b27a624132bb0d435b1bb8c6c29b31a20
a8ed4fd7471b7e03d247ef23174e989b91ee93a3
/translate.rkt
d334db8d775b80caafb1f1fcf7293c7b3f58dedf
[]
no_license
katsuya94/gambit_racket_numerics
326798dafc46a337dcf33b27d008f8c2ea8b9f44
ce71ccb701d1298baf63fc70bb4b5cd71a313530
refs/heads/master
2021-01-17T10:10:55.432217
2016-03-15T06:39:01
2016-03-15T06:39:01
52,853,257
0
1
null
null
null
null
UTF-8
Racket
false
false
1,691
rkt
translate.rkt
#lang racket (require "definitions.rkt" "cheat.rkt" "constants.rkt") (provide to-rktnum from-rktnum rktnum->bignum bignum->rktnum) (define (to-rktnum x) (cond ((fixnum? x) x) ((flonum? x) x) ((bignum? x) (bignum->rktnum x)) ((ratnum? x) (/ (ratnum-numerator x) (ratnum-denominator x))) ((cpxnum? x) (make-rectangular (to-rktnum (cpxnum-real x)) (to-rktnum (cpxnum-imag x)))) (else x))) (define (from-rktnum x) (if (number? x) (if (real? x) (if (exact? x) (if (integer? x) (if (or (> x max-fixnum) (< x min-fixnum)) (rktnum->bignum x) x) (ratnum (from-rktnum (numerator x)) (from-rktnum (denominator x)))) x) (cpxnum (from-rktnum (real-part x)) (from-rktnum (imag-part x)))) x)) (define (rktnum->bignum x) (define adigit-modulus (expt 2 @@bignum.adigit-width)) (define magnitude (abs x)) (define adigits (for/vector ((_ (in-naturals)) #:break (zero? magnitude)) (define adigit (modulo magnitude adigit-modulus)) (set! magnitude (quotient magnitude adigit-modulus)) adigit)) (if (negative? x) (bignum.- (@@fixnum->bignum 0) (bignum adigits)) (bignum adigits))) (define (bignum->rktnum x) (define adigit-modulus (expt 2 @@bignum.adigit-width)) (if (@@bignum.negative? x) (- (bignum->rktnum (bignum.- (@@fixnum->bignum 0) x))) (for/sum ((adigit (in-vector (bignum-adigits x))) (i (in-naturals))) (* adigit (expt adigit-modulus i)))))
false
3f913f599c78b2ed9924a70b24018cad6c5dc061
a8338c4a3d746da01ef64ab427c53cc496bdb701
/drbayes/tests/lyric-tests/tests.rkt
c6c0647203cada3b93c1dc1d3420b351fd5dc0f6
[]
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
8,577
rkt
tests.rkt
#lang typed/racket (require plot/typed math/distributions math/statistics math/flonum "../../main.rkt" "../test-utils.rkt" "../profile.rkt" "../normal-normal.rkt") (printf "starting...~n~n") (error-print-width 1024) (interval-max-splits 5) (define n 1000) #;; Test: Normal-Normal model ;; Preimage should be a banana shape (begin (interval-max-splits 2) ;(interval-min-length (expt 0.5 1.0)) (define/drbayes e (let* ([x (normal 0 1)] [y (normal x 1)]) (list x y))) (define B (set-list reals (real-set 0.9 1.1))) (normal-normal/lw 0 1 '(1.0) '(1.0))) #;; Test: Normal-Normal model with circular condition ;; Preimage should look like a football set up for a field goal (begin (interval-max-splits 0) (define/drbayes (hypot x y) (sqrt (+ (sqr x) (sqr y)))) (define/drbayes e (let* ([x0 (normal 0 1)] [x1 (normal x0 1)]) (list x0 x1 (hypot x0 x1)))) (define B (set-list reals reals (real-set 0.99 1.01)))) #;; Test: thermometer that goes to 100 (begin (interval-max-splits 4) (define e (drbayes (let* ([x (normal 90 10)] [y (normal x 1)]) (list x (if (y . > . 100) 100 y))))) (define B (set-list reals (real-set 99.0 100.0)))) (define ε 0.5) (: interval-near (Flonum -> Set)) (define (interval-near x) (real-set (- x ε) (+ x ε))) #;; Test: Normal-Normal model with more observations ;; Density plot, mean, and stddev should be similar to those produced by `normal-normal/lw' (begin (interval-max-splits 2) ;(interval-min-length (flexpt 0.5 5.0)) (define/drbayes e (let ([x (normal 0 1)]) (list x (normal x 1) (normal x 1) (normal x 1) (normal x 1) (normal x 1) (normal x 1)))) (define B (set-list reals (interval-near 3.3) (interval-near 2.0) (interval-near 1.0) (interval-near 0.2) (interval-near 1.5) (interval-near 2.4))) (normal-normal/lw 0 1 '(3.3 2.0 1.0 0.2 1.5 2.4) '(1.0 1.0 1.0 1.0 1.0 1.0))) ;; =================================================================================================== (define-values (f h idxs) (match-let ([(meaning _ f h k) e]) (values (run/bot* f '()) (run/pre* h '()) (k '())))) (define (empty-set-error) (error 'drbayes-sample "cannot sample from the empty set")) (define refine (if (empty-set? B) (empty-set-error) (preimage-refiner h B))) (define S (let ([S (refine (cons omegas traces))]) (if (empty-set? S) (empty-set-error) S))) (match-define (cons R T) S) (printf "idxs = ~v~n" idxs) (printf "R = ~v~n" R) (printf "T = ~v~n" T) (newline) (struct: domain-sample ([S : Nonempty-Store-Rect] [s : Store] [b : Maybe-Value] [measure : Flonum] [prob : Flonum] [point-prob : Flonum] [weight : Flonum]) #:transparent) (: accept-sample? (domain-sample -> Boolean)) (define (accept-sample? s) (define b (domain-sample-b s)) (and (not (bottom? b)) (set-member? B b))) (: orig-samples (Listof store-rect-sample)) (define orig-samples (time ;profile-expr (refinement-sample* S idxs refine n))) (: all-samples (Listof domain-sample)) (define all-samples (time ;profile-expr (let: loop : (Listof domain-sample) ([orig-samples : (Listof store-rect-sample) orig-samples]) (cond [(empty? orig-samples) empty] [else (define s (first orig-samples)) (match-define (store-rect-sample S m p) s) (define pt (refinement-sample-point S idxs refine)) ;(match-define (cons R T) S) ;(define r (omega-set-sample-point R)) ;(define t (trace-set-sample-point T)) ;(define pt (store-sample (cons r t) m)) (match pt [(store-sample s q) (define b (f (cons s null))) (cons (domain-sample S s b m p q (/ q p)) (loop (rest orig-samples)))] [_ (define r (omega-set-sample-point R)) (define t (trace-set-sample-point T)) (define s (cons r t)) (define b (bottom (delay "refinement-sample-point failed"))) (cons (domain-sample S s b m p m (/ m p)) (loop (rest orig-samples)))])])))) (newline) (define samples (filter accept-sample? all-samples)) (define ws (map domain-sample-weight samples)) (define ps (map domain-sample-prob samples)) (define ms (map domain-sample-measure samples)) (define not-samples (filter (compose not accept-sample?) all-samples)) (define num-all-samples (length all-samples)) (define num-samples (length samples)) (define num-not-samples (length not-samples)) (define accept-prob (fl (/ num-samples num-all-samples))) (printf "search stats:~n") (get-search-stats) (newline) #| (printf "cache stats:~n") (get-cache-stats) (newline) |# (printf "unique numbers of primitive rvs: ~v~n" (sort (remove-duplicates (map (λ: ([d : domain-sample]) (length (omega-set->list (car (domain-sample-S d))))) all-samples)) <)) (newline) (printf "accepted samples: ~v (~v%)~n" (length samples) (* 100.0 accept-prob)) (newline) (define all-alpha (min 1.0 (/ 250.0 (fl num-all-samples)))) (define alpha (min 1.0 (/ 250.0 (fl num-samples)))) (plot-z-ticks no-ticks) (plot3d (list (rectangles3d (append* (map (λ: ([d : domain-sample]) (omega-rect->plot-rects (car (domain-sample-S d)))) not-samples)) #:alpha all-alpha #:color 1 #:line-color 1) (rectangles3d (append* (map (λ: ([d : domain-sample]) (omega-rect->plot-rects (car (domain-sample-S d)))) samples)) #:alpha all-alpha #:color 3 #:line-color 3)) #:x-min 0 #:x-max 1 #:y-min 0 #:y-max 1 #:z-min 0 #:z-max 1) (: domain-sample->omega-point (domain-sample -> (Listof Flonum))) (define (domain-sample->omega-point d) (omega->point (car (domain-sample-s d)))) (plot3d (list (points3d (map domain-sample->omega-point not-samples) #:sym 'dot #:size 12 #:alpha all-alpha #:color 1 #:fill-color 1) (points3d (map domain-sample->omega-point samples) #:sym 'dot #:size 12 #:alpha all-alpha #:color 3 #:fill-color 3)) #:x-min 0 #:x-max 1 #:y-min 0 #:y-max 1 #:z-min 0 #:z-max 1 #:x-label "x1" #:y-label "x2" #:z-label "x3") (plot3d (points3d (sample (discrete-dist (map domain-sample->omega-point samples) ws) num-samples) #:sym 'dot #:size 12 #:alpha alpha) #:x-min 0 #:x-max 1 #:y-min 0 #:y-max 1 #:z-min 0 #:z-max 1 #:x-label "x1" #:y-label "x2" #:z-label "x3") (: xss (Listof (Listof Flonum))) (define xss (map (λ: ([d : domain-sample]) (define lst (value->listof-flonum (cast (domain-sample-b d) Value))) (maybe-pad-list lst 3 random)) samples)) (with-handlers ([exn? (λ (_) (printf "image points scatter plot failed~n"))]) (plot3d (points3d xss #:sym 'dot #:size 12 #:alpha alpha) #:x-label "x1" #:y-label "x2" #:z-label "x3")) (with-handlers ([exn? (λ (_) (printf "resampled image points scatter plot failed~n"))]) (plot3d (points3d (sample (discrete-dist xss ws) num-samples) #:sym 'dot #:size 12 #:alpha alpha) #:x-label "x1" #:y-label "x2" #:z-label "x3")) (define x0s (map (inst first Flonum Flonum) xss)) (with-handlers ([exn? (λ (_) (printf "weight density plot failed~n"))]) (plot (density ws) #:x-label "weight" #:y-label "density")) (with-handlers ([exn? (λ (_) (printf "weight/measure scatter plot failed~n"))]) (plot (points (map (λ: ([w : Flonum] [m : Flonum]) (list w m)) ws ms) #:sym 'dot #:size 12 #:alpha alpha) #:x-label "weight" #:y-label "measure")) (printf "Corr(W,M) = ~v~n" (correlation ws ms)) (with-handlers ([exn? (λ (_) (printf "density plot failed~n"))]) (plot (density (sample (discrete-dist x0s ws) num-samples) 2) #:x-label "x0" #:y-label "density")) (printf "E[x0] = ~v~n" (mean x0s (ann ws (Sequenceof Real)))) (printf "sd[x0] = ~v~n" (stddev x0s (ann ws (Sequenceof Real))))
false
8fb4f992718e088fb9187095727ef75c7f286ae2
e000b691d8248fd1b47140cc24e8ee8356cf062d
/composite.rkt
ca9109b718da28120cd200bd273f910b9a3ad423
[]
no_license
Perfect5th/prototype-inheritance
117f934ed447c4a59d29ea02f0662362a54c9d37
d4a7b1e90f65223313a7106de06ede68d8981e13
refs/heads/master
2020-11-25T03:32:36.380651
2019-12-16T23:25:25
2019-12-16T23:25:25
228,482,557
0
0
null
null
null
null
UTF-8
Racket
false
false
1,601
rkt
composite.rkt
#lang racket ;; Syntax definitions (define-syntax-rule (-> obj msg args ...) ((obj (quote msg)) obj args ...)) (define-syntax-rule (get obj msg) (obj (quote msg))) (define-syntax-rule (new objname [(f v) ...]) (obj objname (list (list (quote f) v) ...))) (define-syntax class (syntax-rules (extends) [(_ name [(f v) ...]) (define name (new Object [(f v) ...]))] [(_ name extends super [(f v) ...]) (define name (new super [(f v) ...]))])) (define Object (λ (msg) (void))) (define (obj superobj fields) (λ (msg) (let ([field (assoc msg fields)]) (if field (second field) (superobj msg))))) ;; Object prototype definitions (class File [(name "") (printName (λ (self depth) (printf "~a~n" (get self name))))]) (class Dir extends File [(children empty) (printName (λ (self depth) (begin (printf "~a/~n" (get self name)) (map (λ (child) (begin (printf "~a" (string-append* (make-list (+ depth 1) " "))) (-> child printName (+ depth 1)))) (get self children)) (void))))]) ;; Concrete object definitions (define file1 (new File ([name "file1"]))) (define file2 (new File ([name "file2"]))) (define file3 (new File ([name "file3"]))) (define dir1 (new Dir ([name "dir1"] [children (list file1 file2)]))) (define dir3 (new Dir ([name "dir3"] [children (list file3)]))) (define dir2 (new Dir ([name "dir2"] [children (list dir1 dir3)]))) (-> dir2 printName 0)
true
d4a7bbfaf2ce14834c0372819421e19c462dd613
6a517ffeb246b6f87e4a2c88b67ceb727205e3b6
/lang/function.rkt
b6205272bee3a3a4cf2f41ed30381f6dfa232b06
[]
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
4,566
rkt
function.rkt
#lang racket/base (require (for-syntax racket/base syntax/parse) racket/class racket/stxparam "../private/environment.rkt" "../private/error.rkt" "../private/function.rkt" "../private/global-object.rkt" "../private/object.rkt" "../private/primitive.rkt" "../private/this.rkt" "../lib/function.rkt" "../convert.rkt" "environment.rkt") (provide return function begin-scope (rename-out [ecma:call call] [ecma:new new] [ecma:this this])) (define-syntax-parameter return-binding #f) (define-syntax return (λ (stx) (unless (syntax-parameter-value #'return-binding) (raise-syntax-error #f "not permitted outside of function body" stx)) (syntax-case stx () [(_) #'(return-binding)] [(_ v) #'(return-binding (get-value v))]))) (define-syntax function (syntax-parser [(_ (~optional name:id) (param:id ...) (~optional (~seq #:vars (var-id:id ...))) (~optional (~seq body:expr ...+))) #`(let ([scope-env (new-declarative-environment lexical-environment)]) (letrec ([f (new Function% [formal-parameters '(param ...)] [proc (λ args (let ([local-env (new-declarative-environment scope-env)]) (send f bind-arguments args local-env) (let/ec escape (syntax-parameterize ([return-binding (make-rename-transformer #'escape)]) (begin-scope local-env #,@(if (attribute var-id) #'(#:vars (var-id ...)) #'()) #,@(or (attribute body) #'(ecma:undefined)))))))])]) #,@(if (attribute name) (with-syntax ([idstr (symbol->string (syntax-e (attribute name)))]) #'((send scope-env create-immutable-binding! idstr) (send scope-env initialize-immutable-binding! idstr f))) #'()) f))])) (define-syntax (begin-scope stx) (syntax-parse stx [(_ new-env (~optional (~seq #:vars (var-id:id ...))) form ...) (with-syntax ([var-ids (or (attribute var-id) '())]) #'(let ([new-scope new-env]) (syntax-parameterize ([variable-environment (make-rename-transformer #'new-scope)] [lexical-environment (make-rename-transformer #'new-scope)]) (reorder-functions () () (create-variables! variable-environment 'var-ids) form ...))))])) (define (create-function! env-rec id fn) (let ([name (symbol->string id)]) (void (send env-rec create-mutable-binding! name #f) (send env-rec set-mutable-binding! name fn #f)))) (define-syntax reorder-functions (syntax-parser #:literals (function) [(_ ([fn-id fn-def] ...) (form ...)) #'(begin (create-function! variable-environment 'fn-id fn-def) ... form ...)] [(_ (fns ...) collected-forms (function fn-id:id . rest) form ...) #'(reorder-functions (fns ... [fn-id (function . rest)]) collected-forms form ...)] [(_ collected-fns (collected-form ...) form rest ...) #'(reorder-functions collected-fns (collected-form ... form) rest ...)])) (define (ecma:call ref . args) (let ([func (get-value ref)]) (unless (Function? func) (raise-native-error 'type "not a function")) (let ([this-value (if (reference? ref) (let ([base (reference-base ref)]) (cond [(Object? base) base] [(is-a? base environment-record%) (send base implicit-this-value)])) ecma:undefined)]) (let ([argvs (map get-value args)]) (send func call (cond [(or (ecma:null? this-value) (ecma:undefined? this-value)) global-object] [(Object? this-value) this-value] [else (to-object this-value)]) argvs))))) (define (ecma:new ref . args) (let ([constructor (get-value ref)]) (unless (Function? constructor) (raise-native-error 'type "not a constructor")) (let ([argvs (map get-value args)]) (send constructor construct argvs))))
true
7a646789d99cd6fc694fd06e6ab968f3ee7a079d
cf47530e1682d103e96b3915bc6f0a5fb755bb19
/racket-react/components/cytoscape.rkt
916b50ee2b855afbbdcb52e688a0129690bb6f5c
[ "Apache-2.0", "MIT" ]
permissive
srfoster/racket-react
3a6dcafd02a6361f1b89fc4bcf3c9869055d8ecb
7bb14cf755a8257bec016004e2ba4f8bce009dd2
refs/heads/main
2023-03-06T03:56:27.598458
2021-02-22T01:49:04
2021-02-22T01:49:04
332,783,467
0
0
null
null
null
null
UTF-8
Racket
false
false
251
rkt
cytoscape.rkt
#lang at-exp racket (provide CytoscapeComponent) (require racket-react/client) (add-import! @js{ import CytoscapeComponent from 'react-cytoscapejs'; }) (add-dependency! "react-cytoscapejs") (define-foreign-component CytoscapeComponent)
false
df4727dd24d35fb7def50f1acc38df2ab8efd8e2
cfdfa191f40601547140a63c31e933b16323cf84
/racket/monadic-eval/units/delta-unit.rkt
0f1a18885b9424cdf05c419a2b6a3248883fdda7
[]
no_license
philnguyen/monadic-eval
6e3415512195d680551ce9203133281790feb7ef
ca1142fd932b17fee7d8e791519eaa8f11d9a9ef
refs/heads/master
2020-05-29T11:43:21.777045
2016-03-02T22:35:01
2016-03-02T22:35:01
53,002,423
0
0
null
2016-03-02T22:49:33
2016-03-02T22:49:32
null
UTF-8
Racket
false
false
3,552
rkt
delta-unit.rkt
#lang racket (require "../signatures.rkt") (provide δ@ abs-δ@ pres-δ@ symbolic-δ@) ;; Concrete δ (define-unit δ@ (import monad^ err^) (export δ^) (define (δ o . vs) (match* (o vs) [('add1 (list n)) (return (add1 n))] [('sub1 (list n)) (return (sub1 n))] [('- (list n)) (return (- n))] [('+ (list n1 n2)) (return (+ n1 n2))] [('- (list n1 n2)) (return (- n1 n2))] [('* (list n1 n2)) (return (* n1 n2))] [('quotient (list n1 n2)) (if (zero? n2) (err) (quotient n1 n2))])) (define (truish? v) (return (zero? v)))) ;; Abstract δ (define-unit abs-δ@ (import monad^ symbolic^ err^) (export δ^) (define (δ o . vs) (match* (o vs) [('add1 (list n)) (return 'N)] [('sub1 (list n)) (return 'N)] [('+ (list n1 n2)) (return 'N)] [('- (list n1 n2)) (return 'N)] [('* (list n1 n2)) (return 'N)] [('quotient (list n1 (? number? n2))) (if (zero? n2) (err) (return 'N))] [('quotient (list n1 n2)) (both (return 'N) (err))])) (define (truish? v) (match v ['N (both (return #t) (return #f))] [_ (return (zero? v))]))) ;; Precision preserving abstract δ (define-unit pres-δ@ (import monad^ symbolic^ err^) (export δ^) (define (δ o . vs) (match* (o vs) [('add1 (list (? number? n))) (return (add1 n))] [('sub1 (list (? number? n))) (return (sub1 n))] [('- (list (? number? n))) (return (- n))] [('+ (list (? number? n1) (? number? n2))) (return (+ n1 n2))] [('- (list (? number? n1) (? number? n2))) (return (- n1 n2))] [('* (list (? number? n1) (? number? n2))) (return (* n1 n2))] [('quotient (list (? number? n1) (? number? n2))) (if (zero? n2) (err) (return (quotient n1 n2)))] [('add1 (list n)) (return 'N)] [('sub1 (list n)) (return 'N)] [('+ (list n1 n2)) (return 'N)] [('* (list n1 n2)) (return 'N)] [('- (list n1 n2)) (return 'N)] [('quotient (list n1 (? number? n2))) (if (zero? n1) (err) (return 'N))] [('quotient (list n1 n2)) (both (err) (return 'N))])) (define (truish? v) (match v ['N (both (return #t) (return #f))] [_ (return (zero? v))]))) (define-unit symbolic-δ@ (import monad^ symbolic^) (export δ^) (define (δ o . vs) (return (match* (o vs) [('add1 (list (? number? n))) (add1 n)] [('add1 (list s)) `(add1 ,s)] [('+ (list (? number? n) (? number? m))) (+ n m)] [('+ (list s t)) `(+ ,s ,t)] [('sub1 (list (? number? n))) (sub1 n)] [('sub1 (list s)) `(sub1 ,s)] [('- (list (? number? n))) (- n)] [('- (list s)) `(- ,s)] [('- (list (? number? n1) (? number? n2))) (- n1 n2)] [('- (list s1 s2)) `(- ,s1 ,s2)] [('* (list (? number? n1) (? number? n2))) (* n1 n2)] [('* (list s1 s2)) `(* ,s1 ,s2)] [('quotient (list (? number? n1) (? number? n2))) (if (zero? n2) 'err (quotient n1 n2))] [('quotient (list s1 (? number? n2))) (if (zero? n2) 'err `(quotient ,s1 ,n2))] [('quotient (list s1 s2)) ;; both err and `(quotient ,s1 ,s2)]))) (define (truish? v) (match v [(? number?) (return (zero? v))] [_ (both (return #t) (return #f))]))) (define (δ-err o vs) (error (format "~a: undefined on ~a" o vs)))
false
3424769807ec4f7b82e563309e1e852faaa81440
bfd875e987a49d8e64f780c296a99ba4c28d7dfa
/blog/allrgb/debug.rkt
5da0c7d4b9b285ed4b248d28f159434e4c4efcb9
[ "BSD-3-Clause" ]
permissive
jpverkamp/small-projects
b794cfc445306c5caea7a96d9dadd3e8d0ed5d28
363dc7294d5b215279eba38f34d02647e9d0a2e4
refs/heads/master
2021-08-05T03:08:25.041519
2021-06-28T16:43:35
2021-06-28T16:43:35
6,299,271
20
3
null
2018-07-10T00:33:16
2012-10-19T18:00:56
Racket
UTF-8
Racket
false
false
1,668
rkt
debug.rkt
#lang racket (provide debug) ; Keep track of starting time for each key (define starting-times (make-hash)) (define last-percents (make-hash)) (define last-print-length 0) ; Format time nicely (define (format-time ms) (let* ([seconds (inexact->exact (floor (/ ms 1000)))] [hours (quotient seconds (* 60 60))] [seconds (- seconds (* hours 60 60))] [minutes (quotient seconds 60)] [seconds (- seconds (* minutes 60))]) (~a hours ":" (~a minutes #:width 2 #:align 'right #:pad-string "0") ":" (~a seconds #:width 2 #:align 'right #:pad-string "0")))) ; Print out a debug indicator and estimated time remaining (define (debug key progress total) ; Set the starting timestamp if this is a new key (define now (current-inexact-milliseconds)) (when (not (hash-has-key? starting-times key)) (hash-set! starting-times key now)) ; Print if the percent complete has changed (define current-percent (quotient (* 100 progress) total)) (when (or (not (hash-has-key? last-percents key)) (not (= (hash-ref last-percents key) current-percent))) (define ms-elapsed (- now (hash-ref starting-times key))) (define ms-total (if (zero? progress) 0 (* total (/ ms-elapsed progress)))) (printf "~a\r" (make-string last-print-length #\space)) (printf "~a ~a% complete, ~a so far, ~a remaining\r" key current-percent (format-time ms-elapsed) (format-time (- ms-total ms-elapsed))) (flush-output) ; Update the last percent to avoid reprinting (hash-set! last-percents key current-percent)))
false
67932816f2bbf02e1fe19d752e5a26be4bbb4267
b996d458a2d96643176465220596c8b747e43b65
/how-to-code-simple-data/problem-bank/how-to-design-data/bike-route.rkt
0117ead6e234560ea07766a3ecbc8235722acf31
[ "MIT" ]
permissive
codingram/courses
99286fb9550e65c6047ebd3e95eea3b5816da2e0
9ed3362f78a226911b71969768ba80fb1be07dea
refs/heads/master
2023-03-21T18:46:43.393303
2021-03-17T13:51:52
2021-03-17T13:51:52
null
0
0
null
null
null
null
UTF-8
Racket
false
false
2,549
rkt
bike-route.rkt
;; The first three lines of this file were inserted by DrRacket. They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-reader.ss" "lang")((modname bike-route) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) ;; ===================================================================== ;; PROBLEM a: ;; ;; Suppose you are developing a route planning tool for bicycling in Vancouver. ;; There are four varieties of designated bike routes: ;; ;; 1) Separated Bikeway ;; 2) Local Street Bikeway ;; 3) Painted Bike Lane ;; 4) Painted Shared-Use Lane ;; ;; Use the HtDD recipe to design a data definition for varieties of bike routes (call it BikeRoute) ;; ===================================================================== ;; Data definitions: ;; BikeRoute is one of: ;; - "Separated Bikeway" ;; - "Local Street Bikeway" ;; - "Painted Bike Lane" ;; - "Painted Shared-Use Lane" ;; interp. represents the four varieties of designated bike routes #; (define (fn-for-bike-route br) (cond [(string=? br "Separated Bikeway") (...)] [(string=? br "Local Street Bikeway") (...)] [(string=? br "Painted Bike Lane") (...)] [(string=? br "Painted Shared-Use Lane") (...)])) ;; Template Rules Used: ;; - one of: 4 cases ;; - atomic distinct: "Separated Bikeway" ;; - atomic distinct: "Local Street Bikeway" ;; - atomic distinct: "Painted Bike Lane" ;; - atomic distinct: "Painted Shared-Use Lane" ;; ===================================================================== ;; PROBLEM b: ;; ;; Separated bikeways and painted bike lanes are exclusively designated for bicycles, while ;; local street bikeways and shared-use lanes must be shared with cars and/or pedestrians. ;; ;; Design a function called 'exclusive?' that takes a bike route and indicates whether it ;; is exclusively designated for bicycles. ;; ===================================================================== ;; BikeRoute -> Boolean ;; produces true if a BikeRoute is exclusively designated for bicycles (check-expect (exclusive? "Separated Bikeway") true) (check-expect (exclusive? "Local Street Bikeway") false) (check-expect (exclusive? "Painted Bike Lane") true) (check-expect (exclusive? "Painted Shared-Use Lane") false) ;; (define (exclusive? br) false) ;stub (define (exclusive? br) (cond [(string=? br "Separated Bikeway") true] [(string=? br "Painted Bike Lane") true] [else false]))
false
0269c5e0a8bb4876bd436270e9f3d46fef496013
b0c1638c5396000a5c6e8c5131169218362511da
/Scheme/seminars/tasks.week3.rkt
d7bf3a9e6192e5707f2f3fe0c13566bae8a40d83
[]
no_license
rostislavts/FP-course-FMI
add89f186ccf144aed57385ee4c349f8dee62b20
8c7f8cb0532111a121147d2c979478758cf74251
refs/heads/master
2022-11-17T18:28:08.279578
2020-07-16T14:19:51
2020-07-16T14:19:51
280,173,623
0
0
null
null
null
null
UTF-8
Racket
false
false
5,419
rkt
tasks.week3.rkt
;;; Task 1 (define (sum-step a b next) (define (help-iter currA result) (if (> currA b) result (help-iter (next currA) (+ result currA) ) ) ) (help-iter a 0) ) (define (sum-term a b term) (define (help-iter currA result) (if (> currA b) result (help-iter (+ 1 currA) (+ result (term currA) ) ))) (help-iter a 0)) (define (sum a b term next) (define (help-iter currA result) (if (> currA b) result (help-iter (next currA) (+ result (term currA) ) ) )) (help-iter a 0)) ; From week2 ================== (define (fact n) (define (for i result) (if (<= i n) (for (+ 1 i) (* result i)) result ) ) (for 1 1)) (define (pow-it x n) (define (iter i result) (if (< i n) (iter (+ i 1) (* result x) ) result) ) (iter 0 1)) (define (fast-pow x n) (if (< n 0) (pow-it (/ 1 x) (- n) ) (pow-it x n)) ) (define (count-digits n) (define (abs x) (if (< x 0) (- x) x) ) (define (iter result currN) (if (> currN 0) (iter (+ 1 result) (quotient currN 10) ) result) ) (if (= n 0) 1 (iter 0 (abs n) ) )) (define (palindrome? n) (define (getDigitAt i) (remainder (quotient n (expt 10 (- (count-digits n) i) ) ) 10 ) ) (define (iter idx) (if (< idx (- (count-digits n) (- idx 1)) ) (if (= (getDigitAt idx) (getDigitAt (- (count-digits n) (- idx 1) ) ) ) (iter (+ idx 1) ) #f) #t) ) (iter 1) ) ;================================ ;;; Task 2 (define (my-exp m) (lambda (x) (sum 0 m (lambda (n) (/ (pow-it x n) (fact n) ) ) (lambda (x) (+ 1 x) ) ) )) (define (my-sin m) (lambda (x) (sum 0 m (lambda (n) (* (pow-it (- 1) n) (/ (pow-it x (+ (* 2 n) 1) ) (fact (+ (* 2 n) 1) ) ) )) (lambda (x) (+ 1 x) ) ) ) ) (define (my-cos m) (lambda (x) (sum 0 m (lambda (n) (* (pow-it (- 1) n) (/ (pow-it x (* 2 n) ) (fact (* 2 n) ) ) )) (lambda (x) (+ 1 x) ) ) ) ) ;;; Task 3 (define (my-exp x m) (define (help-iter i result) (if (> i m ) result (help-iter (+ 1 i) (+ result (/ (pow-it x i) (fact i) ) ) )) ) (help-iter 0 0) ) ;;; Task 4 (define (product a b term next) (define (help-iter currA result) (if (> currA b) result (help-iter (next currA) (* result (term currA) ) ) )) (help-iter a 1)) ;;; Task 5 (define (sprod p) (lambda (x) (accumulate * 1 1 p (lambda (currA) (accumulate + 0 0 currA (lambda (k) (/ (* (pow-it (- 1) k) (pow-it x (+ (* 2 k ) 1) ) ) (fact (+ (* 2 k) 1) ) ) ) (lambda (k) (+ k 1 ) ) )) (lambda (k) (+ 1 k) ) ))) ;;; Task 6 (define (accumulate op nv a b term next) (define (help-iter currA result) (if (> currA b) result (help-iter (next currA) (op result (term currA) ) ) )) (help-iter a nv)) (define (accumulate-rec op nv a b term next) (define (help currA) (if (> currA b) nv (op (term currA) (help (next currA) ) ))) (help a)) ;;; Task 7 (define (fact-acc n) (accumulate * 1 1 n (lambda (i) i) (lambda (x) (+ 1 x)))) (define (pow-acc x n) (accumulate * 1 1 n (lambda (i) x ) (lambda (x) (+ 1 x) ))) ;; Task 8 (define (count-palindromes a b) (define (help i counter) (if (> i b) counter (if (palindrome? i) (help (+ 1 i) (+ 1 counter) ) (help (+ 1 i) counter) ) ) ) (help a 0) ) ;;; Task 9 (define (prime? n) (= (accumulate + 0 2 (- n 1) (lambda (k) (if (= (remainder n k) 0) 1 0) ) (lambda (x) (+ 1 x) ) ) 0 ) ) ;;; Task 10 (define (exists? pred? a b) (> (accumulate + 0 a b (lambda (i) (if (pred? i) 1 0) ) (lambda (x) (+ 1 x) )) 0) ) ;;; Task 11 (define (forall? pred? a b) (= (accumulate + 0 a b (lambda (i) (if (pred? i) 0 1) ) (lambda (i) (+ 1 i) )) 0 ) ) ;;; Task 12 (define (count-pred pred? a b next) (accumulate + 0 a b (lambda (i) (if (pred? i) 1 0) ) next) ) ;;; Task 13 (define (comb n k) (/ (fact-acc n) (* (fact-acc (- n k) ) (fact-acc k) ) ) ) ;;; Task 14 (define (var n k) (/ (fact-acc n) (fact-acc (- n k) ) ) ) ;;; Task 15 (define (flip f) (lambda (a b) (f b a) ) ) ;;; Task 16 (define (twice f x) (f (f x))) (define (compose f g) (f (g x))) (define (repeated f n) (lambda (x) (define (help-iter i result) (if (< i n) (help-iter (+ 1 i) (f result) ) result )) (help-iter 0 x) )) (define (repeated-2 f n) (lambda (x) (define (help-iter i result) (if (< i n) (if (>= (- n i) 2) (help-iter (+ 2 i) (twice f result) ) (help-iter (+ 1 i) (f result) )) result )) (help-iter 0 x) )) ;;; Task 17 (define (derive f dx) (lambda (x) (/ (- (f (+ x dx) ) (f x) ) dx ) )) ;;; Task 18 (define (derive-n f n dx) (lambda (x) (define (help i result) (if (< i n) (help (+ 1 i) (derive result dx) ) (result x) )) (help 0 f) ))
false
f76d6f177e7906fd2511e67302b0d662d2b5f0b0
0640a3c297cd8b53f33a4799b531476e81e76610
/tulip-lib/lang/emitter.rkt
caa66a2d8a7cee5def717bff93410c943c4f5d48
[]
no_license
chrisgd/racket-tulip
e38d63b715a3f6e24a8f96454dd0e7feb4e9e4ed
1613cfd4d7e8dbc8ceb86cf33479375147f42b2f
refs/heads/master
2020-07-28T08:46:55.622752
2016-09-21T21:39:42
2016-09-21T21:39:42
null
0
0
null
null
null
null
UTF-8
Racket
false
false
6,412
rkt
emitter.rkt
#lang racket/base (require racket/list racket/match racket/syntax syntax/parse syntax/strip-context tulip/private/util/srcloc) (provide emit-module emit-interaction) (define (emit-module stx) (syntax-parse stx #:context '|error while parsing module| [((~var expr-or-def (tulip-top-level-form #f)) ...) (strip-context #'(#%module-begin expr-or-def.emitted ...))])) (define (emit-interaction stx) (syntax-parse stx #:context '|error while parsing interaction| [((~var expr-or-def (tulip-top-level-form #t)) ...) (strip-context #'(@%begin expr-or-def.emitted ...))])) (define-splicing-syntax-class (tulip-top-level-form interaction?) #:attributes [emitted] #:description "top level form" [pattern #s(import module-name:tulip-require-spec) #:attr emitted #'(#%require module-name.emitted)] [pattern expr-or-defn:tulip-expr-or-defn #:attr emitted (if (and (not interaction?) (attribute expr-or-defn.defined-id)) #'(@%begin (#%provide expr-or-defn.defined-id) expr-or-defn.emitted) #'expr-or-defn.emitted)]) (define-splicing-syntax-class tulip-expr-or-defn #:attributes [emitted defined-id] #:description #f ; Function definitions next to one another with the same name should be parsed as a single function ; definition with multiple pattern clauses. For example, this: ; is-zero 0 = .t ; is-zero _ = .f ; Should be parsed like this: ; is-zero = [ 0 => .t; _ => .f ] [pattern (~seq {~and def #s(function-definition id:tulip-unnamespaced-id pats expr)} {~and def* #s(function-definition id*:tulip-unnamespaced-id ; require each id* to be the same as id (otherwise, backtrack) (~fail #:unless (free-identifier=? #'id.emitted #'id*.emitted)) pats* expr*)} ...) #:do [(define this-srcloc (let ([matched-syntax #'(def def* ...)]) (join-srclocs (first (syntax->list matched-syntax)) (last (syntax->list matched-syntax)))))] #:with [clause ...] #'[#s(lambda-clause pats expr) #s(lambda-clause pats* expr*) ...] #:with lambda:tulip-expr (datum->syntax #f (syntax-e #'#s(lambda-full [clause ...])) this-srcloc) #:attr emitted #'(@%define-multiple-binders id.emitted [id*.emitted ...] lambda.emitted) #:attr defined-id #'id.emitted] [pattern #s(definition id:tulip-unnamespaced-id expr:tulip-expr) #:attr emitted #'(@%define id.emitted expr.emitted) #:attr defined-id #'id.emitted] [pattern expr:tulip-expr #:attr emitted #'expr.emitted #:attr defined-id #f]) (define-syntax-class tulip-id #:attributes [namespace name] [pattern #s(identifier (~or namespace-stx:id (~and #f namespace-stx)) name:id) #:attr namespace (and (syntax->datum #'namespace-stx) #'namespace-stx)]) (define-syntax-class tulip-unnamespaced-id #:attributes [emitted] #:description "identifier" [pattern id:tulip-id #:fail-when (attribute id.namespace) "expected an unnamespaced identifier, but a namespace was provided" #:attr emitted #'id.name]) (define-syntax-class tulip-expr #:attributes [emitted] [pattern id:tulip-id #:attr emitted (if (attribute id.namespace) (syntax/loc this-syntax (@%namespaced id.namespace id.name)) #'id.name)] [pattern #s(chain-slot) #:attr emitted (syntax/loc this-syntax @%chain-slot)] [pattern #s(tag-word name:id) #:attr emitted (syntax/loc this-syntax (@%tag name))] [pattern #s(flag-word name:id) #:attr emitted (syntax/loc this-syntax (@%flag name))] [pattern #s(flag-pair word:tulip-expr value:tulip-expr) #:attr emitted (syntax/loc this-syntax (@%flag-pair word.emitted value.emitted))] [pattern #s(number value) #:attr emitted #'value] [pattern #s(string value) #:attr emitted #'value] [pattern #s(application fn:tulip-expr arg:tulip-expr) #:attr emitted (datum->syntax #f (list #'fn.emitted #'arg.emitted) this-syntax #'fn.emitted)] [pattern #s(application! fn:tulip-expr) #:attr emitted (datum->syntax #f (list #'fn.emitted) this-syntax #'fn.emitted)] [pattern #s(block [expr:tulip-expr-or-defn ...]) #:attr emitted (syntax/loc this-syntax (@%block expr.emitted ...))] [pattern #s(chain left:tulip-expr right:tulip-expr) #:attr emitted (syntax/loc this-syntax (@%chain left.emitted right.emitted))] [pattern #s(lambda-full [clause:tulip-lambda-clause ...]) #:attr emitted (syntax/loc this-syntax (@%lambda clause.emitted ...))]) (define-syntax-class tulip-require-spec #:attributes [emitted] [pattern #s(string value) #:attr emitted #'value] [pattern id:tulip-id #:attr emitted (if (attribute id.namespace) (format-id #f "~a/~a" #'id.namespace #'id.name #:source (join-srclocs #'id.namespace #'id.name) #:props #'id.name) #'id.name)]) (define-syntax-class tulip-lambda-clause #:attributes [emitted] [pattern #s(lambda-clause (pat:tulip-pattern ...) expr:tulip-expr) #:attr emitted #'[(pat.emitted ...) expr.emitted]]) (define-syntax-class tulip-pattern #:attributes [emitted] [pattern #s(hole) #:attr emitted #'_] [pattern #s(tag-pattern #s(tag-word name:id) [value-pat:tulip-pattern ...]) #:attr emitted #'(@%tag name value-pat.emitted ...)] [pattern other-expr:tulip-expr #:attr emitted #'other-expr.emitted])
true
06adfc6fa3ddcc43d234097f89c42e9a44d4ad1d
e29bd9096fb059b42b6dde5255f39d443f69caee
/metapict/color.rkt
8b6efffb72f3c0258528f8e0e66fb97f4079e5f0
[]
no_license
soegaard/metapict
bfe2ccdea6dbc800a6df042ec00c0c77a4915ed3
d29c45cf32872f8607fca3c58272749c28fb8751
refs/heads/master
2023-02-02T01:57:08.843234
2023-01-25T17:06:46
2023-01-25T17:06:46
16,359,210
52
12
null
2023-01-25T17:06:48
2014-01-29T21:11:46
Racket
UTF-8
Racket
false
false
4,824
rkt
color.rkt
#lang racket/base (provide color ; match-expander for color% objects and color names (strings) make-color* ; fault tolerant make-color that also accepts color names color->list ; return components as a list color+ ; add colors componentwise color* ; scale componentwise color-med ; mediate (interpolate) between colors color-med* ; mediate (interpolate) between colors in a list change-red ; change red component change-green ; change green component change-blue ; change blue component change-alpha ; change transparency ) ; TODO Idea: Consider support for other color systems. ; https://github.com/mbutterick/css-tools/blob/master/colors.rkt ; Idea: Add a user supplied string to color resolver. ; This could be used to make a pallette where "red", "green" etc ; aren't the pure colors. (require "def.rkt" "parameters.rkt" racket/draw racket/match racket/class racket/format racket/math racket/list (for-syntax racket/base syntax/parse)) (module+ test (require rackunit)) ; (color r g b a) matches a color name (as a string) or a color% object. ; The variables r g b a will be bound to the red, gren, blue and alpha component respectively. ; In an expression context (color c p) will be equivalent to (colorize p c) ; In an expression context (color f c p) will be equivalent to (colorize p (color* f c)) (define-match-expander color (λ (stx) (syntax-parse stx [(_ r g b a) #'(or (and (? string?) (app (λ(s) (def c (send the-color-database find-color s)) (list (send c red) (send c green) (send c blue) (send c alpha))) (list r g b a))) (and (? object?) (app (λ(c) (list (send c red) (send c green) (send c blue) (send c alpha))) (list r g b a))))])) (λ (stx) (syntax-parse stx [(_ c p) #'((colorizer) c p)] [(_ f c p) #'((colorizer) (color* f c) p)]))) ; return components as a list (define (color->list c) (defm (color r g b α) c) (list r g b α)) ; (make-color* s) where s is a color name returns the corresponding color% object ; (make-color r g b [α 1.0]) like make-color but accepts out-of-range numbers (define make-color* (case-lambda [(name) (cond [(is-a? name color%) name] [else (def c (send the-color-database find-color name)) (unless c (error 'make-color* (~a "expected color name, got " name))) c])] [(r g b) (make-color* r g b 1.0)] [(r g b α) (def (f x) (min 255 (max 0 (exact-floor x)))) (make-color (f r) (f g) (f b) (max 0.0 (min 1.0 α)))])) (module+ test (check-equal? (color->list (make-color* 1 2 3 .4)) '(1 2 3 .4)) (check-equal? (color->list (make-color* "red")) '(255 0 0 1.))) ; add colors componentwise (define (color+ color1 color2) (defm (color r1 g1 b1 α1) color1) (defm (color r2 g2 b2 α2) color2) (make-color* (+ r1 r2) (+ g1 g2) (+ b1 b2) (min 1.0 (+ α1 α2)))) (module+ test (check-equal? (color->list (color+ "red" "blue")) '(255 0 255 1.)) (check-equal? (color->list (color+ "red" (make-color* 0 0 0 2.))) '(255 0 0 1.))) ; multiply each color component with k, keep transparency (define (color* k c) (defm (color r g b α) c) (make-color* (* k r) (* k g) (* k b) α)) (module+ test (check-equal? (color->list (color* 2 (make-color* 1 2 3 .4))) '(2 4 6 .4))) ; mediate (interpolate) between colors 0<=t<=1 (define (color-med t c1 c2) (color+ (color* (- 1 t) c1) (color* t c2))) (module+ test (check-equal? (color->list (color-med 1/2 "red" "blue")) '(127 0 127 1.))) ; mediate between the colors in the list cs, 0<=t<=1 (define (color-med* t cs) (match cs [(list) (make-color "white")] [(list c1) (color-med t "white" c1)] [(list c1 c2) (color-med t c1 c2)] [(list* c1 cs) (def n (length cs)) (def 1/n (/ 1 n)) (if (<= t 1/n) (color-med (* n t) c1 (first cs)) (color-med* (/ (- (* n t) 1) (- n 1)) cs))])) ; change a single component (define (change-red c r) (defm (color _ g b α) c) (make-color* r g b α)) (define (change-green c g) (defm (color r _ b α) c) (make-color* r g b α)) (define (change-blue c b) (defm (color r g _ α) c) (make-color* r g b α)) (define (change-alpha c α) (defm (color r g b _) c) (make-color* r g b α)) (module+ test (check-equal? (color->list (change-red "black" 7)) '(7 0 0 1.)) (check-equal? (color->list (change-green "black" 7)) '(0 7 0 1.)) (check-equal? (color->list (change-blue "black" 7)) '(0 0 7 1.)) (check-equal? (color->list (change-alpha "black" .7)) '(0 0 0 .7)))
false
3a9b937a1d023e747667526b4951dca9ceb5f9c1
9582df0ff3e357deecda33566db3f9a51c7a1592
/hackett-lib/hackett/data/either.rkt
e6e5a9550984ed47a14a79106cdbce6984739da8
[ "ISC" ]
permissive
Shamrock-Frost/hackett
1f7bcb89cc19b057d825bf994a0621c2179a6e93
e9d457b8ced25f8061869231ab6fe4dacacf0246
refs/heads/master
2021-08-22T09:48:31.968521
2017-11-27T01:18:59
2017-11-29T22:46:19
104,480,231
1
0
null
2017-09-22T13:54:39
2017-09-22T13:54:38
null
UTF-8
Racket
false
false
1,085
rkt
either.rkt
#lang hackett/base (require hackett/private/prim) (provide (data Either) either is-left is-right lefts rights partition-eithers) (defn either : (∀ [a b c] {{a -> c} -> {b -> c} -> (Either a b) -> c}) [[f _ (Left x)] (f x)] [[_ g (Right y)] (g y)]) (defn is-left : (forall [l r] {(Either l r) -> Bool}) [[(Left _)] True] [[(Right _)] False]) (defn is-right : (forall [l r] {(Either l r) -> Bool}) [[(Left _)] False] [[(Right _)] True]) (defn lefts : (forall [l r] {(List (Either l r)) -> (List l)}) [[{e :: es}] (case e [(Left x) {x :: (lefts es)}] [_ (lefts es)])] [[Nil] Nil]) (defn rights : (forall [l r] {(List (Either l r)) -> (List r)}) [[{e :: es}] (case e [(Right x) {x :: (rights es)}] [_ (rights es)])] [[Nil] Nil]) (def partition-eithers : (forall [l r] {(List (Either l r)) -> (Tuple (List l) (List r))}) (foldr (λ* [[(Left x) (Tuple ls rs)] (Tuple {x :: ls} rs)] [[(Right x) (Tuple ls rs)] (Tuple ls {x :: rs})]) (Tuple Nil Nil)))
false
f42463ba4b24a67128b3b96bfa860c75c64589e5
f6bbf5befa45e753077cf8afc8f965db2d214898
/ASTBenchmarks/class-compiler/tests/examples/r1_17.rkt
8837d7cc03a01d479ffed99beb86f5b947862a85
[]
no_license
iu-parfunc/gibbon
4e38f1d2d0526b30476dbebd794f929943f19f12
45f39ad0322cd7a31fe04922ad6bf38e6ac36ad6
refs/heads/main
2023-08-31T11:39:58.367737
2023-08-30T23:44:33
2023-08-30T23:44:38
58,642,617
139
23
null
2023-09-12T20:40:48
2016-05-12T13:10:41
C
UTF-8
Racket
false
false
31
rkt
r1_17.rkt
(let ([x 42]) (let ([y x]) y))
false
db6e5c241235606f12328438185a5923a2415d66
69e94593296c73bdfcfc2e5a50fea1f5c5f35be1
/Tutorials/Tut1/q10.rkt
e2cee8ef5908e29017e4105cb346035436ebfb42
[]
no_license
nirajmahajan/CS152
7e64cf4b8ec24ed9c37ecc72c7731816089e959b
ef75b37715422bf96648554e74aa5ef6e36b9eb3
refs/heads/master
2020-05-29T18:02:08.993097
2019-05-29T20:35:06
2019-05-29T20:35:06
189,293,837
0
0
null
null
null
null
UTF-8
Racket
false
false
182
rkt
q10.rkt
#lang racket (define (can-surv pos n) (cond [(< n 3) #t] [(> pos 3) (can-surv (- pos 3) (- n 1))] [(= pos 3) #f] [else (can-surv (- n (- 3 pos)) (- n 1))]))
false
09495e89770682bb93047614d130dea838214c9a
15adbd534264e8e887f3b06f4089814fccd72f9c
/src/util/urltilities.rkt
0105093c5f24cd503d5046fb6330ea20b6472c94
[ "MIT" ]
permissive
bboston7/racpete
e95ac2c13fc1032c6596f49ca20ffa4a6e5d2644
6bc173261a81aa3dfbfe7b734c12a8d04a001a7e
refs/heads/master
2021-06-25T05:10:15.468701
2016-12-28T05:11:54
2016-12-28T05:11:54
13,463,529
3
1
null
2014-07-26T08:37:23
2013-10-10T06:18:03
Racket
UTF-8
Racket
false
false
3,108
rkt
urltilities.rkt
#lang racket (require html xml net/url) (provide urlregex get-website-title get-website-title-async) #| This module provides utilities for use in processing urls |# #| Number of bytes to read of a page before giving up |# (define READ_BYTES (* 1024 100)) ; 100KB #| This is a regex that matches on urls |# (define urlregex #px"https?://([\\da-zA-Z.]+)\\.([a-zA-Z.]{2,6})[/\\w.a-zA-Z?=&-]*/?") #| Parses the website at the given url and returns the title node's contents Parameters url-string - string? representation of a url. |# (define (get-website-title url-string) (letrec ([retrieved-html (open-input-string (read-string READ_BYTES (with-handlers ([exn:fail? (lambda (e) "")]) (get-pure-port (string->url url-string)))))] [get-title-tag-text (lambda (html-blobs) (cond ; Case 1: We didn't find a title. [(null? html-blobs) ""] ; Case 2: Found title node, return it. [(title? (car html-blobs)) (foldr (lambda (x y) (let* ([symbol->str (lambda (c) (cond [(equal? c 'nbsp) " "] [(equal? c 'raquo) ">>"] [else " "]))] [webdata->string (lambda (x) (cond [(pcdata? x) (pcdata-string x)] [(entity? x) (let ([ent (entity-text x)]) (if (valid-char? ent) (make-string 1 (integer->char ent)) (symbol->str ent)))] [(string? x) x] [else ""]))]) (string-append (webdata->string x) (webdata->string y)))) "" (html-full-content (car html-blobs)))] ; Case 3: No title yet, add DOM nodes to list and recurse. [else (get-title-tag-text (append (cdr html-blobs) (filter html-full? (html-full-content (car html-blobs)))))]))]) (if (equal? retrieved-html "") "" (string-trim (get-title-tag-text (list (read-html retrieved-html))))))) #| Asynchronously gets the title for url-string and calls fn on the result |# (define (get-website-title-async url-string fn) (thread (lambda () (fn (get-website-title url-string)))))
false
77cdddf48ce6cc12b6ddfbafb45db132ad629123
8a316e0c796b3f58816078325bf7dc87801e958f
/private/constraint-example.rkt
32fdf3ceec88aa4a180e0f8cf88dd097effb2dcd
[]
no_license
ezig/shilldb
92f017b8e22f9ca8ad6f55f22330b98e89ac14fd
1bb20f53b762254296a8f5343e11a185a6897eb3
refs/heads/master
2021-09-16T14:02:37.436455
2018-06-21T15:59:12
2018-06-21T15:59:12
72,788,098
1
0
null
null
null
null
UTF-8
Racket
false
false
2,868
rkt
constraint-example.rkt
#lang racket (require "shilldb-macros.rkt") (define (apply-first-and-second-arg-only) (define store (box '())) (struct record-arg/c () #:property prop:contract (build-contract-property #:projection (λ (ctc) (λ (blame) (λ (val) (set-box! store (cons val (unbox store))) val))))) (struct valid-arg/c () #:property prop:contract (build-contract-property #:projection (λ (ctc) (λ (blame) (λ (val) (if (member val (unbox store)) val (raise-blame-error blame val "not one of the expected-arguments"))))))) (values (record-arg/c) (valid-arg/c))) (define example/c (constraint/c ([(X Y) apply-first-and-second-arg-only]) (-> (and/c X number?) (and/c X number?) number? (-> Y Y number?) number?))) (define/contract (f x y z g) example/c (g x y)) (f 2 3 4 +) (define/contract (f-prime x y z g) example/c (g x z)) ;; should fail ;(f-prime 2 3 4 +) (struct dummy ([constraint #:mutable #:auto]) #:auto-value values) (define (apply-first-to-second-arg-only-obj) (define store (box '())) (struct valid-arg/c () #:property prop:contract (build-contract-property #:projection (λ (ctc) (λ (blame) (λ (val) (if (member val (unbox store)) val (raise-blame-error blame val "not one of the expected-arguments"))))))) (struct constraint-args/c () #:property prop:contract (build-contract-property #:projection (λ (ctc) (define redirect-proc (λ (s v) v)) (define new-constraint/c (-> (valid-arg/c) (valid-arg/c) any)) (λ (blame) (define new-constraint ((contract-projection new-constraint/c) blame)) (λ (val) (set-box! store (cons val (unbox store))) (impersonate-struct val dummy-constraint (λ (s v) (compose new-constraint v)) set-dummy-constraint! redirect-proc)))))) (constraint-args/c)) (define (binop d1 d2) (define (real-binop d1 d2) d1) (((compose (dummy-constraint d1) (dummy-constraint d2)) real-binop) d1 d2)) (define example-prime/c (constraint/c ([(X) apply-first-to-second-arg-only-obj]) (-> (and/c X dummy?) (and/c X dummy?) dummy? dummy?))) (define/contract (g x y z) example-prime/c (binop x y)) (g (dummy) (dummy) (dummy)) (define/contract (g-prime x y z) example-prime/c (binop x z)) ;; should fail ;(g-prime (dummy) (dummy) (dummy))
false
b97f48818ad45650951ec859b932b04621184395
97639be9f21da72c59fd1c78cf250dc3db228ea1
/for-acc/for-acc.rkt
ae1f530b57ba2b2d19ef01d5886eb580e412c8c4
[ "Apache-2.0" ]
permissive
deeglaze/nifty-macros
40ff240a5be745b9d2c92e04517723c59eb30cbf
49b120743205d372c7033a534ec7e3faae6a2e5b
refs/heads/master
2020-04-09T09:52:29.022678
2018-09-30T14:19:37
2018-09-30T14:19:37
null
0
0
null
null
null
null
UTF-8
Racket
false
false
22,737
rkt
for-acc.rkt
#lang racket/base ;; ;; Copyright 2018 Dionna Glaze ;; ;; 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. ;; (provide for/acc for*/acc let/for/acc let/for*/acc define/for/acc define/for*/acc define-accumulator) ;; Allow mix and match of accumulation styles, like for/list and for/set ;; for two different accumulators. (require (for-syntax racket/base syntax/parse racket/syntax syntax/for-body syntax/id-table racket/pretty (only-in racket/dict in-dict-keys) (only-in racket/bool implies) racket/match)) (begin-for-syntax (define for/fold-types (make-free-id-table)) ;; suppress/drop is (one-of 'suppress 'drop #f) (struct accumulator (id op-initial suppress/drop binds op-inner op-post) #:prefab) (struct folding-data (accumulators num-exported) #:prefab)) ;; Each "accumulator" may have multiple accumulating bindings. (define-syntax (define-accumulator stx) (syntax-parse stx [(_ name:id [acc:id ;; Helper identifiers won't be in the result of the for. Suppress them. ;; They are not just dropped: they don't count for the number of values the body ;; should return. (~or (~optional (~and #:suppress suppress?)) (~optional (~seq #:initial init:expr)) ;; Give the body's result(s) for this position (a) name(s) to use in inner. (~optional (~seq #:bind (~or (~and bind:id (~bind [(binds 1) (list #'bind)])) (binds:id ...))) #:defaults ([(binds 1) '()])) (~optional (~seq #:inner inner:expr)) ;; Suppressed bindings may post-process for side-effect and bind nothing. (~optional (~seq #:post post:expr))) ...] ...) #:fail-unless (memv (syntax-local-context) '(top-level module)) "Can only define for types at the (module) top-level" #:fail-unless (for/or ([s (in-list (attribute suppress?))]) (not s)) "Cannot suppress all accumulators" #:fail-when (for/or ([s (in-list (attribute suppress?))] [bs (in-list (attribute binds))]) (and s (pair? bs))) "Suppressed bindings are hidden; cannot use #:bind." #:fail-when (for/or ([s (in-list (attribute suppress?))] [i (in-list (attribute init))]) (and s (not i))) "Suppressed bindings must have an initial value." #:do [(define dups (check-duplicate-identifier (attribute acc)))] #:fail-when dups (format "Duplicate accumulator identifiers ~a" dups) (define accumulators (map accumulator (attribute acc) (attribute init) (map syntax? (attribute suppress?)) (attribute binds) (attribute inner) (attribute post))) (define num-exported (for/sum ([s (attribute suppress?)] #:unless s) 1)) (define (syntaxify a) (match-define (accumulator id initial sd binds op-inner op-post) a) (with-syntax ([(b ...) binds]) #`(accumulator #'#,id #'#,(or initial #'(quote #f)) ;; can't define an accumulator with a drop quality. Only suppress. #,(and sd #'(quote suppress)) (list #'b ...) #,(and op-inner #`(syntax #,op-inner)) #,(and op-post #`(syntax #,op-post))))) (with-syntax ([(a ...) (map syntaxify accumulators)]) #`(begin-for-syntax (free-id-table-set! for/fold-types #'name (folding-data (list a ...) #,num-exported))))])) (begin-for-syntax (define-syntax-class (folding orig-stx) #:attributes ((accs 1) introducer) (pattern [(~optional (~describe #:opaque "accumulator name(s)" (~or (~and g-acc:id (~bind [(g-accs 1) (list #'g-acc)])) (g-accs:id ...)))) (~or (~optional (~seq #:type (~describe #:opaque "accumulation type" type:id))) ;; suppressed accumulators cannot be named here, so no interface to it. (~optional (~and #:drop drop)) (~optional (~seq #:initial ;; TODO: kinda sucks syntactically requiring `values` (~describe #:opaque "initial value(s)" (~or ((~literal values) inits:expr ...) (~and g-init:expr (~bind [(inits 1) (list #'g-init)])))))) (~optional (~seq #:named-initial (~describe #:opaque "initial value(s) for given accumulators" ([acc-init:id named-init:expr] ...))))) ... (~optional (~describe #:opaque "initial value" p-init:expr))] #:fail-when (and (not (attribute type)) (not (attribute g-accs))) "Accumulator without an accumulation type requires an identifier to bind" #:fail-when (and (not (attribute type)) (not (or (attribute inits) (attribute p-init)))) "Accumulator without an accumulation type requires an initial value" #:fail-when (and (attribute inits) (attribute p-init)) "Cannot specify initial value positionally and with #:initial." #:do [(define num-g-accs (length (or (attribute g-accs) '())))] #:fail-when (and (attribute p-init) (> num-g-accs 1)) "Cannot give multiple initial values positionally. Must use #:initial (values v ...)" #:fail-when (and (attribute inits) (attribute acc-init)) "Cannot specify initial value(s) positionally and by name." #:do [(define (bad) (raise-syntax-error #f (format "Unknown accumulator type ~a" (syntax-e #'type)) #'type)) (define acc-ids (make-free-id-table)) ;; Create first pass of accumulators used, either named or by #:type. (define-values (accumulators num-exported) (if (attribute type) (match (free-id-table-ref for/fold-types #'type bad) [(folding-data a n) ;; Populate names of accumulators. (for ([acc (in-list a)]) (free-id-table-set! acc-ids (accumulator-id acc) #t)) (values a n)]) (values (for/list ([g (in-list (attribute g-accs))] [i (in-list (or (attribute inits) (list (attribute p-init))))]) (free-id-table-set! acc-ids g #t) (accumulator g i (and (attribute drop) 'drop) (generate-temporaries (list g)) #f #f)) num-g-accs))) (define named-dups (check-duplicate-identifier (or (attribute acc-init) '()))) (define unknown-named-inits (if (attribute acc-init) (for/list ([aid (in-list (attribute acc-init))] #:unless (free-id-table-ref acc-ids aid #f)) aid) '()))] #:fail-when named-dups (format "Duplicate named initial values for accumulators: ~a" named-dups) #:fail-unless (null? unknown-named-inits) (format "Initial value given for unknown accumulators: ~a" unknown-named-inits) #:fail-unless (implies (attribute g-accs) (= num-g-accs num-exported)) (format "Type-exported bindings arity-mismatch in binders. Given ~a, expect ~a" num-g-accs num-exported) #:fail-unless (implies (attribute inits) (= (length (attribute inits)) num-exported)) (format "Type-exported bindings arity-mismatch in inital values. Given ~a, expect ~a" (length (attribute inits)) num-exported) #:do [ ;; Associate initial expressions with accumulator identifier (define acc-init-table (make-free-id-table)) ;; Initial values are given positionally or nominally? (cond [(attribute inits) (for ([acc (in-list accumulators)] [i (in-list (attribute inits))]) (free-id-table-set! acc-init-table (accumulator-id acc) i))] [(attribute acc-init) ;; Nominally (for ([aid (in-list (attribute acc-init))] [i (in-list (attribute named-init))]) (free-id-table-set! acc-init-table aid i))] ;; only initial values are the ones from the type itself. [else (for ([acc (in-list accumulators)]) (free-id-table-set! acc-init-table (accumulator-id acc) (accumulator-op-initial acc)))]) ;; Find if we have filled in all the missing initial values (define undefined-initial-values (for/list ([aid (in-dict-keys acc-ids)] #:unless (free-id-table-ref acc-init-table aid #f)) aid))] #:fail-unless (null? undefined-initial-values) (let* ([plural? (pair? (cdr undefined-initial-values))] [many (if plural? "s" "")]) (format "Accumulator~a ~a unspecified initial value~a" many (if plural? "have" "has") many)) #:do [ ;; If we don't give accumulator ids, we want a fresh accumulator id each time ;; we refer to the accumulation style ;; Example: (for/acc ([#:type list] [#:type list]) ([x 5]) (values x x)) ;; => (values '(0 1 2 3 4) '(0 1 2 3 4)) ;; Without the introducer, we have a duplicated identifier in the clauses. (define intro (make-syntax-introducer)) (define new-accs (or (attribute g-accs) (map (compose intro accumulator-id) accumulators))) ;; We need to reinterpret user-given idents (or freshen idents) as the originals ;; in order for the looked-up syntax to match. (define (interp op-stx binds) (and op-stx (with-syntax ([(na ...) new-accs] [(oa ...) (map accumulator-id accumulators)] [(ob ...) binds] [(nb ...) (map intro binds)]) (quasisyntax/loc orig-stx (let-syntax ([oa (make-rename-transformer #'na)] ... [ob (make-rename-transformer #'nb)] ...) #,op-stx)))))] #:attr (accs 1) ;; Now override defaults with provided forms. (for/list ([acc (in-list accumulators)] [aid (in-list new-accs)]) (match-define (accumulator id initial sd binds op-inner op-post) acc) (accumulator aid initial (or sd (and (attribute drop) 'drop)) (map intro binds) (interp op-inner binds) (interp op-post binds))) #:attr introducer intro))) (define-syntax (for/acc-aux stx) (syntax-parse stx [(_ folder (~optional (~seq #:in-post-context in-post-form:id (in-post:expr ...))) ((~var accss (folding stx)) ...) guards . unsplit-body) (define/with-syntax ((pre-body ...) (post-body ...)) (split-for-body #'stx #'unsplit-body)) ;; Suppressed bindings are hidden values of the iteration. ;; Suppressing/dropping bindings requires a let binding, as does post-processing. ;; Binding order is the order that values must be given in values. (define has-involved-post? (for*/or ([accs (in-list (attribute accss.accs))] [acc (in-list accs)]) (or (accumulator-suppress/drop acc) (accumulator-op-post acc)))) (define has-post? (or (attribute in-post) has-involved-post?)) ;; Only add (let-values ([(x ...) ...]) ...) if there is a need to transform them. (define has-inner? (for*/or ([accs (in-list (attribute accss.accs))] [acc (in-list accs)]) (accumulator-op-inner acc))) (with-syntax ([(expected-ids ...) ;; dropped ids count (reverse (for*/fold ([ids '()]) ([accs (in-list (attribute accss.accs))]) (for/fold ([ids ids]) ([acc (in-list accs)]) (cond [(eq? (accumulator-suppress/drop acc) 'suppress) ids] ;; The binders should all have the introducer applied. [else (append (reverse (accumulator-binds acc)) ids)]))))]) (with-syntax ([(return-values ...) (reverse (for*/fold ([rvs '()]) ([accs (in-list (attribute accss.accs))] [acc (in-list accs)]) ;; If no inner expr given, then ;; if binding suppressed, just use the accumulator identifier, ;; otherwise, use the expected-id. (cond ;; Inner expressions should refer to the renamed binders. [(accumulator-op-inner acc) => (λ (i) (cons i rvs))] [(eq? 'suppress (accumulator-suppress/drop acc)) (cons (accumulator-id acc) rvs)] [else (append (reverse (accumulator-binds acc)) rvs)])))]) (define loop-body (if has-inner? (quasisyntax/loc stx (let-values ([(expected-ids ...) (let () post-body ...)]) (values return-values ...))) #'(let () post-body ...))) (define loop (with-syntax ([(clauses ...) (for*/list ([accs (in-list (attribute accss.accs))] [acc (in-list accs)]) (quasisyntax/loc stx [#,(accumulator-id acc) #,(accumulator-op-initial acc)]))]) (quasisyntax/loc stx (folder #,stx (clauses ...) guards pre-body ... #,loop-body)))) (define (general-post all-of-it) (if (attribute in-post) (quasisyntax/loc stx (in-post-form ([#,(for*/list ([accs (in-list (attribute accss.accs))] [acc (in-list accs)] #:unless (accumulator-suppress/drop acc)) (accumulator-id acc)) #,all-of-it]) in-post ...)) all-of-it)) (if has-post? (with-syntax ([(aids ...) (for*/list ([accs (in-list (attribute accss.accs))] [acc (in-list accs)]) (accumulator-id acc))]) (cond [has-involved-post? (general-post (quasisyntax/loc stx (let-values ([(aids ...) #,loop]) ;; Suppressed bindings get their post-processing run for side-effect. #,@(for*/list ([accs (in-list (attribute accss.accs))] [acc (in-list accs)] #:when (and (accumulator-op-post acc) (eq? 'suppress (accumulator-suppress/drop acc)))) (accumulator-op-post acc)) ;; Finally, only return unsuppressed/dropped accumulators. (values #,@(for*/list ([accs (in-list (attribute accss.accs))] [acc (in-list accs)] #:unless (accumulator-suppress/drop acc)) (or (accumulator-op-post acc) (accumulator-id acc)))))))] [else ;; Easy post. Just bind and go. (quasisyntax/loc stx (in-post-form ([(aids ...) #,loop]) in-post ...))])) ;; No post. Just loop. loop)))])) (define-syntax-rule (for/acc accs guards body1 body ...) (for/acc-aux for/fold/derived accs guards body1 body ...)) (define-syntax-rule (for*/acc accs guards body1 body ...) (for/acc-aux for*/fold/derived accs guards body1 body ...)) (define-syntax-rule (let/for/acc (accs guards body1 body ...) lbody1 lbody ...) (for/acc-aux for/fold/derived #:in-post-context let-values ((let () lbody1 lbody ...)) accs guards body1 body ...)) (define-syntax-rule (let/for*/acc (accs guards body1 body ...) lbody1 lbody ...) (for/acc-aux for*/fold/derived #:in-post-context let-values ((let () lbody1 lbody ...)) accs guards body1 body ...)) (define-syntax-rule (rejigger-post-to-define ([(id ...) e])) (define-values (id ...) e)) (define-syntax-rule (define/for/acc accs guards body1 body ...) (for/acc-aux for/fold/derived #:in-post-context rejigger-post-to-define () accs guards body1 body ...)) (define-syntax-rule (define/for*/acc accs guards body1 body ...) (for/acc-aux for*/fold/derived #:in-post-context rejigger-post-to-define () accs guards body1 body ...)) (define-accumulator list [lst #:initial '() #:bind v #:inner (cons v lst) #:post (reverse lst)]) (require racket/set) (define-accumulator set [st #:initial (set) #:bind v #:inner (set-add st v)]) (define-accumulator sum [sm #:initial 0 #:bind v #:inner (+ v sm)]) (define-accumulator prod [pd #:initial 1 #:bind v #:inner (* v pd)]) ;; One accumulator that expects the body expression to return two values for it (positionally) (define-accumulator hash [h #:initial #hash() #:bind (k v) #:inner (hash-set h k v)]) (module+ test (require rackunit racket/set) #; (define-accumulator list [lst #:initial '() #:bind v #:inner (cons v lst) #:post (reverse lst)]) (check equal? (for/acc ([#:type list]) ([i 10]) i) (for/list ([i 10]) i)) (check equal? (call-with-values (λ () (for/acc ([#:type list] [#:type list] [mumble #:drop 'bork]) ([i 10]) (values i i 'bork))) list) (let ([v (for/list ([i 10]) i)]) (list v v))) ;; Tricky internal-definition-context test (check equal? (let () (define (post x) '(bork bork bork)) (for/acc ([#:type list]) ([x 10]) (define (pre x) (if (even? x) (post x) x)) (begin (define (post y) (pre (add1 y))) (post x)))) (for/list ([i 10]) (if (even? (add1 i)) (+ 2 i) (add1 i)))) ;; Don't define dropped ids? (check equal? (let () (define bad 'already-here) (define/for/acc ([l0 #:type list] [l1 #:type list] [bad #:drop 0]) ([x 10]) (values x x 0)) (list l0 l1)) (let ([v (for/list ([i 10]) i)]) (list v v))) (define-accumulator append [lst #:initial '() #:bind v #:inner (append (reverse v) lst) #:post (reverse lst)]) (define-accumulator union [st #:initial (set) #:bind v #:inner (set-union v st)]) (check equal? (call-with-values (λ () (for/acc ([#:type set] [hh #:type hash]) ([i 5]) (values i i (- i)))) list) (list (set 0 1 2 3 4) (hash 0 0 1 -1 2 -2 3 -3 4 -4))) (check equal? (call-with-values (λ () (for/acc ([#:type sum] [a '()] [#:type prod]) ([i (in-range 1 5)]) (values i (cons i a) i))) list) (list 10 (list 4 3 2 1) 24)) (define b (box #f)) (define-accumulator max [m #:initial -inf.0 #:bind v #:inner (if (> v m) v m)] [find #:initial #f #:inner (= m 8) #:suppress #:post (when find (set-box! b #t))]) (check equal? (let ([max (for/acc ([#:type max]) ([x 6]) (* 2 x))]) (and (unbox b) max)) 10) )
true
4b0a8e9c3c2f249cf4f3deaf385cb3e5ec4e2df5
6858cbebface7beec57e60b19621120da5020a48
/15/1/3.rkt
51c9669e5718f73921e173348d7dbc8ffbc2cec7
[]
no_license
ponyatov/PLAI
a68b712d9ef85a283e35f9688068b392d3d51cb2
6bb25422c68c4c7717b6f0d3ceb026a520e7a0a2
refs/heads/master
2020-09-17T01:52:52.066085
2017-03-28T07:07:30
2017-03-28T07:07:30
66,084,244
2
0
null
null
null
null
UTF-8
Racket
false
false
22
rkt
3.rkt
(define f n (+ n 3))
false
cf769c0bafef5be4b671aefe4eef514df373cc73
82c76c05fc8ca096f2744a7423d411561b25d9bd
/typed-racket-test/test-docs-complete.rkt
5efb86b1220ce2d696f270d41d2f82ccf8c2b9f2
[ "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
548
rkt
test-docs-complete.rkt
#lang racket/base (require rackunit/docs-complete) ;; these are currently undocumented in `racket' as well (define exclude '(make-primitive-class make-custom-set make-mutable-custom-set make-weak-custom-set place-sleep)) (check-docs (quote typed-scheme) #:skip exclude) (check-docs (quote typed/scheme) #:skip exclude) (check-docs (quote typed/scheme/base) #:skip exclude) (check-docs (quote typed/racket) #:skip exclude) (check-docs (quote typed/racket/base) #:skip exclude)
false
666f6ba76ed4042e5af9efb993169497bf5baae7
1da0749eadcf5a39e1890195f96903d1ceb7f0ec
/a-d6/a-d/sorting/external/multiway-merge-sort.rkt
9f95ddfcdb0d00df63018dacce5ce9d0b3479e93
[]
no_license
sebobrien/ALGO1
8ce02fb88b6db9e001d936356205a629b49b884d
50df6423fe45b99db9794ef13920cf03d532d69f
refs/heads/master
2020-04-08T20:08:16.986517
2018-12-03T06:48:07
2018-12-03T06:48:07
159,685,194
0
0
null
null
null
null
UTF-8
Racket
false
false
5,976
rkt
multiway-merge-sort.rkt
#lang r6rs ;-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- ;-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- ;-*-* *-*- ;-*-* Balanced Multiway Merge Sort *-*- ;-*-* *-*- ;-*-* Wolfgang De Meuter *-*- ;-*-* 2010 Software Languages Lab *-*- ;-*-* Vrije Universiteit Brussel *-*- ;-*-* *-*- ;-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- ;-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- (library (multiway-merge-sort) (export sort!) (import (rnrs base) (rnrs control) (rnrs io simple) (rename (a-d sorting internal comparative quicksort-m3-bounded) (sort quicksort)) (prefix (a-d heap standard) heap:) (prefix (a-d disk file-system) fs:) (prefix (a-d disk disk) disk:) (prefix (a-d file sequential input-file) in:) (prefix (a-d file sequential output-file) out:) (prefix (a-d sorting external outputfile-with-counted-runs) ofcr:) (prefix (a-d sorting external inputfile-with-counted-runs) ifcr:) (a-d scheme-tools)) ; import random-integer (define rlen 10) (define irun (make-vector rlen)) (define (read-run! file) (let loop ((indx 0)) (cond ((or (= indx rlen) (not (in:has-more? file))) indx) (else (vector-set! irun indx (in:read file)) (loop (+ indx 1)))))) (define (write-run! ofcr imax) (let loop ((indx 0)) (ofcr:write! ofcr (vector-ref irun indx)) (if (< (+ indx 1) imax) (loop (+ indx 1))))) (define (make-aux-bundle disks) (define p (floor (/ (vector-length disks) 2))) (define in (make-vector p)) (define out (make-vector p)) (define name "aux-") (do ((i 0 (+ i 1))) ((= i p)) (vector-set! out i (ofcr:new (vector-ref disks i) (string-append name (number->string i)) rlen)) (vector-set! in i (ofcr:new (vector-ref disks (+ p i)) (string-append name (number->string (+ p i))) rlen)) (ofcr:reread! (vector-ref in i) rlen)) ; we need input files in "in" (c.f. rewrite! in next phase)! (make-bundle p in out)) (define (delete-aux-bundle! files) (for-each-input files (lambda (file indx) (ifcr:delete! file))) (for-each-output files (lambda (file indx) (ofcr:delete! file)))) (define (make-bundle p in out) (cons p (cons in out))) (define (order files) (car files)) (define (input files indx) (vector-ref (cadr files) indx)) (define (output files indx) (vector-ref (cddr files) indx)) (define (for-each-input files proc) (define nrfs (order files)) (do ((indx 0 (+ indx 1))) ((= indx nrfs)) (proc (input files indx) indx))) (define (for-each-output files proc) (define nrfs (order files)) (do ((indx 0 (+ indx 1))) ((= indx nrfs)) (proc (output files indx) indx))) (define (swap-files!? files) (define (switch-refs) (define tmp input) (set! input output) (set! output tmp)) (define p (order files)) (define old-run-length (ofcr:run-length (output files 0))) (define new-run-length (* p old-run-length)) (for-each-output files (lambda (outp indx) (ofcr:reread! outp old-run-length))) (for-each-input files (lambda (inpt indx) (ifcr:rewrite! inpt new-run-length))) (switch-refs) (ifcr:has-more? (input files 1))) (define (next-file indx p) (mod (+ indx 1) p)) (define (distribute! inpt files <<?) (define p (order files)) (let loop ((indx 0)) (let ((nmbr (read-run! inpt))) (when (not (= nmbr 0)) (quicksort irun nmbr <<?) (write-run! (output files indx) nmbr) (ofcr:new-run! (output files indx)) (loop (next-file indx p))))) (swap-files!? files)) (define (collect! files inpt) (define last (input files 0)) (in:rewrite! inpt) (let loop ((rcrd (ifcr:read last))) (out:write! inpt rcrd) (if (ifcr:run-has-more? last) (loop (ifcr:read last)))) (out:close-write! inpt)) (define (read-from-files? heap files) (for-each-input files (lambda (file indx) (when (ifcr:has-more? file) (ifcr:new-run! file) (heap:insert! heap (cons indx (ifcr:read file)))))) (not (heap:empty? heap))) (define (serve heap files) (define el (heap:delete! heap)) (define indx (car el)) (define rcrd (cdr el)) (if (ifcr:run-has-more? (input files indx)) (heap:insert! heap (cons indx (ifcr:read (input files indx))))) rcrd) (define (merge! files <<?) (define heap (heap:new (order files) (lambda (c1 c2) (<<? (cdr c1) (cdr c2))))) (let merge-files ((out-idx 0)) (cond ((read-from-files? heap files) (let merge-p-runs ((rcrd (serve heap files))) (ofcr:write! (output files out-idx) rcrd) (if (not (heap:empty? heap)) (merge-p-runs (serve heap files)))) (ofcr:new-run! (output files out-idx)) (merge-files (next-file out-idx (order files)))) ((swap-files!? files) (merge-files 0))))) (define (sort! file dsks <<?) (define files (make-aux-bundle dsks)) (distribute! file files <<?) (merge! files <<?) (collect! files file) (delete-aux-bundle! files)))
false
e20c98e51ed5b1004f33e991d05b7994414e594a
ba5171ca08db9e0490db63df59ee02c85a581c70
/exam/2020-11-07/2.rkt
d025d2fddc3cfcef7bd3f837114349cf528149b4
[]
no_license
semerdzhiev/fp-2020-21
030071ed14688751d615b1d1d39fa406c131a285
64fa00c4f940f75a28cc5980275b124ca21244bc
refs/heads/master
2023-03-07T10:17:49.583008
2021-02-17T11:46:08
2021-02-17T11:46:08
302,139,037
31
16
null
2021-01-17T15:22:17
2020-10-07T19:24:33
Racket
UTF-8
Racket
false
false
971
rkt
2.rkt
(define (nset-contains? set elem) (= 1 (remainder (quotient set (expt 2 elem)) 2)) ) (define (nset-add set elem) (if (nset-contains? set elem) set ;elem is already in the set (+ set (expt 2 elem)) ) ) (define (nset-remove set elem) (if (nset-contains? set elem) (- set (expt 2 elem)) set ;elem is not in the set ) ) (define (nset-size set) (cond ((= set 0) 0) ((= 0 (remainder set 2)) (nset-size (quotient set 2))) (else (+ 1 (nset-size (quotient set 2)))) ) ) (define (nset-contains-its-size s) (nset-contains? s (nset-size s)) ) (define (nset-map s f) (define (loop i r result) (cond ((= r 0) ; no more elements result) ((= 0 (remainder r 2)) ; i is not contained in the original set (loop (+ i 1) (quotient r 2) result)) (else ; add f(i) to the result (loop (+ i 1) (quotient r 2) (nset-add result (f i)))) ) ) (loop 0 s 0) )
false
e97b6d0c5077728aefd284795f8e951e3ffe8abc
8ad2bcf76a6bda64f509da5f0844e0285f19d385
/persona/p3p/p3p-db.rktd
d61e2cf47f2e47c3a82508372160550f619847cf
[]
no_license
jeapostrophe/exp
c5efae0ea7068bb5c8f225df6de45e6c4fa566bd
764265be4bcd98686c46ca173d45ee58dcca7f48
refs/heads/master
2021-11-19T00:23:11.973881
2021-08-29T12:56:11
2021-08-29T12:56:11
618,042
39
5
null
null
null
null
UTF-8
Racket
false
false
4,343
rktd
p3p-db.rktd
;91 ("Odin" "Melchizedek" "Shiva" "Asura" "Loki" "Lucifer" "Messiah" "Thor" "Koumokuten" "Skadi" "Alilat") 95 ("Orpheus Telos" "Atavaka" "Norn" "Yurlungur" "Scathach") ("Fool" ("Orpheus" 1 4352) ("Slime" 12 9203) ("Legion" 22 22172) ("Black Frost" 34 49628) ("Ose" 44 67712) ("Decarabia" 50 75947) ("Loki" 58 113747) ("Susano-o" 76 233852) ("Orpheus Telos" 90 479603)) ("Magician" ("Nekomata" 5 3875) ("Jack Frost" 8 6107) ("Pyro Jack" 14 10112) ("Hua Po" 20 17987) ("Sati" 28 32000) ("Orobas" 34 43772) ("Rangda" 40 57488) ("Surt" 52 118427)) ("Priestess" ("Apsaras" 3 3728) ("Unicorn" 11 6800) ("High Pixie" 21 16700) ("Sarasvati" 27 25323) ("Ganga" 35 39632) ("Parvati" 47 70403) ("Kikuri-hime" 53 87683) ("Scathach" 64 170507)) ("Empress" ("Leanan Sidhe" 33 40988) ("Yaksini" 50 75947) ("Laksmi" 57 97052) ("Hariti" 62 113747) ("Gabriel" 69 143267) ("Mother Harlot" 74 189500) ("Skadi" 80 189500) ("Alilat" 84 281075)) ("Emperor" ("Forneus" 7 5468) ("Oberon" 15 12092) ("Take-mikazuchi" 24 23675) ("King Frost" 30 38300) ("Raja Naga" 36 45923) ("Kingu" 46 73148) ("Barong" 52 93875) ("Odin" 57 139388)) ("Hierophant" ("Omoikane" 7 5468) ("Berith" 13 10427) ("Shiisaa" 26 28508) ("Flauros" 33 41675) ("Thoth" 41 59963) ("Hokuto Seikun" 47 75947) ("Daisoujou" 53 111443) ("Kohryu" 66 180608)) ("Lovers" ("Pixie" 2 3452) ("Alp" 6 3875) ("Tam Lin" 13 7292) ("Narcissus" 20 17552) ("Queen Mab" 27 25232) ("Saki Mitama" 39 50387) ("Titania" 48 75947) ("Raphael" 61 124412) ("Cybele" 68 191003)) ("Chariot" ("Ara Mitama" 6 4883) ("Chimera" 9 6800) ("Zouchouten" 14 11075) ("Ares" 19 16700) ("Oumitsunu" 30 35708) ("Nata Taishi" 37 57488) ("Koumokuten" 43 65075) ("Thor" 53 122000)) ("Justice" ("Angel" 4 4187) ("Archangel" 10 6107) ("Principality" 16 11075) ("Power" 25 25232) ("Virtue" 32 41675) ("Dominion" 42 67712) ("Throne" 51 78800) ("Melchizedek" 59 148523)) ("Hermit" ("Yomotsu Shikome" 9 5468) ("Naga" 17 12092) ("Lamia" 25 23675) ("Mothman" 32 49628) ("Taraka" 38 57488) ("Kurama Tengu" 44 73148) ("Nebiros" 50 103568) ("Kumbhanda" 56 110300) ("Arahabaki" 60 152528)) ("Fortune" ("Fortuna" 17 12092) ("Empusa" 23 19328) ("Kusi Mitama" 29 32000) ("Clotho" 38 52700) ("Lachesis" 45 70403) ("Atropos" 54 87683) ("Norn" 62 162083)) ("Strength" ("Valkyrie" 11 7547) ("Rakshasa" 16 12092) ("Titan" 23 23675) ("Jikokuten" 29 33827) ("Hanuman" 37 50387) ("Narasimha" 46 78800) ("Kali" 55 106907) ("Siegfried" 59 148523)) ("Hanged Man" ("Inugami" 10 6107) ("Take-minakata" 21 16700) ("Orthrus" 28 32000) ("Vasuki" 38 52700) ("Ubelluris" 48 78800) ("Hecatoncheires" 54 87683) ("Hell Biker" 60 124412) ("Attis" 67 185027)) ("Death" ("Ghoul" 18 15872) ("Pale Rider" 24 25323) ("Loa" 31 40988) ("Samael" 37 57488) ("Mot" 45 83675) ("Alice" 56 126848) ("Thanatos" 64 170507)) ("Temperance" ("Nigi Mitama" 12 9203) ("Mithra" 22 23168) ("Genbu" 29 36347) ("Seiryuu" 36 52700) ("Okuninushi" 44 77843) ("Suzaku" 51 100283) ("Byakko" 57 131792) ("Yurlungur" 64 159323)) ("Devil" ("Lilim" 8 5267) ("Mokoi" 18 15467) ("Vetala" 24 23675) ("Incubus" 34 47387) ("Succubus" 43 76892) ("Pazuzu" 52 111443) ("Lilith" 61 147200) ("Abaddon" 68 177692) ("Beelzebub" 81 263075)) ("Tower" ("Eligor" 31 48875) ("Cu Chulainn" 40 73148) ("Bishamonten" 60 147200) ("Seiten Taisei" 67 179147) ("Masakado" 73 209507) ("Mara" 77 230528) ("Shiva" 82 259547) ("Chi You" 86 292163)) ("Star" ("Neko Shogun" 19 15068) ("Setanta" 28 30812) ("Nandi" 39 59963) ("Kaiwan" 49 93875) ("Ganesha" 58 126848) ("Garuda" 65 156587) ("Kartikeya" 70 183548) ("Saturnus" 78 228875) ("Helel" 88 305372)) ("Moon" ("Gurr" 15 11408) ("Yamatano-orochi" 26 26843) ("Girimehkala" 42 71312) ("Dionysus" 48 90752) ("Chernobog" 58 126848) ("Seth" 66 160700) ("Baal Zebul" 71 192512) ("Sandalphon" 74 222323)) ("Sun" ("Yatagarasu" 30 35708) ("Quetzalcoatl" 43 76892) ("Jatayu" 55 123203) ("Horus" 63 156587) ("Sparna" 70 194027) ("Vishnu" 78 237200) ("Asura" 85 286592)) ("Judgement" ("Anubis" 59 124412) ("Trumpeter" 65 149852) ("Michael" 72 204800) ("Satan" 79 242267) ("Lucifer" 89 301568) ("Messiah" 90 318875)) ("Aeon" ("Uriel" 63 140675) ("Nidhogg" 69 167675) ("Ananta" 75 197075) ("Atavaka" 80 222323) ("Metatron" 87 299675))
false
6396666ca95c6d8562d2b37c102cb1efd9135a4b
82c76c05fc8ca096f2744a7423d411561b25d9bd
/typed-racket-test/fail/promise-any.rkt
ca8ebc6e86197e627ed49750aff0b42d94132437
[ "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
268
rkt
promise-any.rkt
#; (exn-pred #rx"Attempted to use a higher-order value passed as `Any`") #lang racket (module typed typed/racket (: d Any) (define d (delay (lambda: ([x : Integer]) (+ x 1)))) (provide d)) (require 'typed) ;; this line should raise a ctc error ((force d) 6)
false
f48b8cb471071e9633af9905ef3e76794920a3b3
bfe5286a7948115219be4c38e7b8a4e9f0e86413
/test/slow-contract.rkt
70373ad776c919d2c695cbd2e0a3ba4e96145264
[]
no_license
bennn/racket-minus-contracts
3c6bfeea0ea9dbebe1d81fe01f12b80a30e5d0c8
17feb42d63777afac0ea17b6fba6dcd5ba50baaa
refs/heads/master
2021-06-07T05:41:48.305956
2018-02-19T00:47:46
2018-02-19T00:47:46
42,135,816
2
1
null
2016-01-02T00:51:36
2015-09-08T19:58:35
Racket
UTF-8
Racket
false
false
256
rkt
slow-contract.rkt
#lang racket/base (require racket/contract) (define (slow-predicate x) (sleep 2) #t) (define/contract (f x) (-> slow-predicate slow-predicate) x) (define (main) (printf "Checking contract....\n") (f 42) (printf "Done!\n")) (time (main))
false
8a510a731fa49b78454b105dacf020962098339f
ddcff224727303b32b9d80fa4a2ebc1292eb403d
/3. Modularity, Objects, and State/3.5/3.77.rkt
91ba332444bf9e975784b10bd90c805a8916b8cd
[]
no_license
belamenso/sicp
348808d69af6aff95b0dc5b0f1f3984694700872
b01ea405e8ebf77842ae6a71bb72aef64a7009ad
refs/heads/master
2020-03-22T02:01:55.138878
2018-07-25T13:59:18
2018-07-25T13:59:18
139,345,220
1
0
null
null
null
null
UTF-8
Racket
false
false
360
rkt
3.77.rkt
#lang racket (define (integral delayed-integrand initial-value dt) (stream-cons initial-value (let ([integrand (force delayed-integrand)]) (if (stream-empty? integrand) empty-stream (integral (delay (stream-rest integrand)) (+ (* dt (stream-first integrand)) initial-value) dt)))))
false
6647e937b90766d00fe5be7abdd861a4f2adc508
3041fb9e6364332c43ba758db7979e463a5d1209
/private/combinator.rkt
a24eb3c0a508182e7fb6921fca49e1d95733033e
[ "MIT", "Apache-2.0" ]
permissive
SFurnace/Praser-Combinator
2a5ee56153aa1c58bdbbf5a77766f5740252567b
6e3f3fa143137007581c09eeab450cf2eeda46e1
refs/heads/master
2020-12-21T19:16:59.964864
2020-04-01T19:31:58
2020-04-01T19:35:36
236,532,638
0
0
null
null
null
null
UTF-8
Racket
false
false
7,711
rkt
combinator.rkt
#lang racket/base (require "./parseable.rkt" racket/set racket/contract (for-syntax racket/base syntax/parse)) (provide (all-from-out "./parseable.rkt") silver-parser-debug @ @: @* @*? @+ @+? @? @?? @= @>= @>=? @** @**? @u @U @sepBy @infix-left @infix-right @prefix @postfix) ;; Parser ::= parseable<%> -> Any ;; 若parse不成功,则parseable<%>的pos需要保持不变 ;; parameters (define silver-parser-debug (make-parameter #f)) (define left-recursion-records (make-parameter (set))) ;; parser binder (define-syntax (@ stx) (syntax-parse stx [(_ name:id parser:expr) #'(define (name in) (let ([mark (cons 'name (send-generic in get-pos))]) (when (silver-parser-debug) (displayln mark) (sleep (silver-parser-debug))) (if (set-member? (left-recursion-records) mark) (error 'name "left recursion detected at ~a" mark) (parameterize ([left-recursion-records (set-add (left-recursion-records) mark)]) (parser in)))))])) ;; Sequence Combinators (define-syntax (@: stx) (syntax-parse stx #:datum-literals (! =>) [(_ (~optional (~seq #:msg msg:str) #:defaults ([msg #'"parse failed"])) e0:expr ...+ ! e1:expr ...+ => body:expr ...+) (let* ([names0 (make-temp-names #'(e0 ...))] [len (length (syntax->list names0))] [names1 (make-temp-names #'(e1 ...) len)]) (with-syntax ([(n0 ...) names0] [(n1 ...) names1]) #'(lambda (in) (let/ec k (let* ([pos (send-generic in get-pos)] [fail (λ () (send-generic in set-pos pos) (k parse-failed))] [n0 (let ([r (e0 in)]) (if (parse-failed? r) (fail) r))] ... [n1 (let ([r (e1 in)]) (if (parse-failed? r) (raise-parse-error msg) r))] ...) body ...)))))] [(_ exp:expr ...+ => body:expr ...+) (with-syntax ([(name ...) (make-temp-names #'(exp ...))]) #'(lambda (in) (let/ec k (let* ([pos (send-generic in get-pos)] [fail (λ () (send-generic in set-pos pos) (k parse-failed))] [name (let ([r (exp in)]) (if (parse-failed? r) (fail) r))] ...) body ...))))] [(_ e0:expr ...+ ! e1:expr ...+) #`(@: e0 ... ! e1 ... => (list #,@(make-temp-names #'(e0 ... e1 ...))))] [(_ exp:expr ...+) #`(@: exp ... => (list #,@(make-temp-names #'(exp ...))))])) ;; Repeat Combinators (define (((@repeat m n) parser) in) (define pos (send-generic in get-pos)) (define (fail) (send-generic in set-pos pos) parse-failed) (let loop ([rs '()]) (if (= (length rs) n) (reverse rs) (let ([r (parser in)]) (if (parse-failed? r) (if (<= m (length rs) n) (reverse rs) (fail)) (loop (cons r rs))))))) (define (((@repeat? m n) parser #:successor [s #f]) in) (define succ (if s (@may s) #f)) (define pos (send-generic in get-pos)) (define (fail) (send-generic in set-pos pos) parse-failed) (let loop ([rs '()]) (if (> (length rs) n) (fail) (if (and (<= m (length rs)) (if succ (succ in) #t)) (reverse rs) (let ([r (parser in)]) (if (parse-failed? r) (fail) (loop (cons r rs)))))))) (define @* (@repeat 0 +inf.0)) (define @*? (@repeat? 0 +inf.0)) (define @+ (@repeat 1 +inf.0)) (define @+? (@repeat? 1 +inf.0)) (define @? (@repeat 0 1)) (define @?? (@repeat? 0 1)) (define/contract (@= n) (-> natural-number/c any) (@repeat n n)) (define/contract (@>= n) (-> natural-number/c any) (@repeat n +inf.0)) (define/contract (@>=? n) (-> natural-number/c any) (@repeat? n +inf.0)) (define/contract (@** m n) (-> natural-number/c natural-number/c any) (@repeat m n)) (define/contract (@**? m n) (-> natural-number/c natural-number/c any) (@repeat? m n)) ;; Choice Combinators (define ((@u . parsers) in) (define pos (send-generic in get-pos)) (let loop ([ps parsers]) (if (null? ps) (begin (send-generic in set-pos pos) parse-failed) (let* ([p (car ps)] [r (p in)]) (if (parse-failed? r) (loop (cdr ps)) r))))) (define ((@U . parsers) in) (define pos (send-generic in get-pos)) (define rs (filter (lambda (x) (not (parse-failed? (car x)))) (for/list ([p (in-list parsers)]) (send-generic in set-pos pos) (cons (p in) (send-generic in get-pos))))) (if (null? rs) (begin (send-generic in set-pos pos) parse-failed) (let ([r (car (sort rs > #:key cdr))]) (send-generic in set-pos (cdr r)) (car r)))) ;; Helpers, just use in library (define ((@may p) in) (let ([c (send-generic in get-pos)]) (dynamic-wind (λ () '_) (λ () (if (parse-failed? (p in)) #f #t)) (λ () (send-generic in set-pos c))))) (define ((@try p) in) (let ([c (send-generic in get-pos)] [r (p in)]) (if (parse-failed? r) (begin (send-generic in set-pos c) #f) r))) ;; Other Patterns (define (@sepBy p0 p1) (@* (@: p1 (@try p0) => $0))) (define ((@infix op elem associativity #:constructor [c list] #:strictly [s #f]) in) (define pos0 (send-generic in get-pos)) (define (fail) (send-generic in set-pos pos0) parse-failed) (define (construct lst) (if (= (length lst) 1) (car lst) (let ([lst (if (eq? associativity 'right) lst (reverse lst))]) (let loop ([l (cdr lst)] [e0 (car lst)]) (let* ([op (car l)] [e1 (cadr l)] [l (cddr l)] [exp (if (eq? associativity 'right) (c op e1 e0) (c op e0 e1))]) (if (null? l) exp (loop l exp))))))) (define (loop0 stk pos) (let ([v (elem in)]) (if (parse-failed? v) (if (> (length stk) 3) (begin (send-generic in set-pos pos) (construct (cdr stk))) (fail)) (if (< (length stk) 2) (loop1 (cons v stk) pos) (loop1 (cons v stk) (send-generic in get-pos)))))) (define (loop1 stk pos) (let ([v (op in)]) (if (parse-failed? v) (if (or (>= (length stk) 3) (not s)) (construct stk) (fail)) (loop0 (cons v stk) pos)))) (loop0 '() pos0)) (define (@infix-left op elem #:constructor [c list] #:strictly [s #f]) (@infix op elem 'left #:constructor c #:strictly s)) (define (@infix-right op elem #:constructor [c list] #:strictly [s #f]) (@infix op elem 'right #:constructor c #:strictly s)) (define (@prefix op elem #:constructor [c list]) (@: (@+ op) elem => (foldl c $1 $0))) (define (@postfix op elem #:constructor [c list]) (@: elem (@+ op) => (foldl c $0 $1))) ;; Helper (begin-for-syntax (define (make-temp-names stx [start 0]) (let ([temps (for/list ([n (in-naturals start)] [s (in-list (syntax-e stx))]) (datum->syntax s (string->symbol (format "$~a" n)) s s))]) (datum->syntax #f temps))))
true
ec9c695d33955770d76da17ddb287736d52f2657
6377f02394723c3a02b54f2f863f4da4ac1cef76
/ProgrammingLanguages/bonus.rkt
cde9fd80529d09432e9d449ea16bd9764436cced
[]
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,520
rkt
bonus.rkt
#lang racket (define filter-sps (lambda (pred lst store) (cond [(empty? lst) (values lst store)] [(pred (car lst)) (let-values ([(f1 store) (filter-sps pred (cdr lst) store)]) (values (cons (car lst) f1) store))] [else (let-values ([(f1 store) (filter-sps pred (cdr lst) store)]) (values f1 (cons (car lst) store)))]))) (define filter*-sps (lambda (f ls store) (cond [(null? ls) (values ls store)] [(pair? (car ls)) (let-values ([(f1 store1) (filter*-sps f (car ls) store)]) (let-values([(f2 store2) (filter*-sps f (cdr ls) store)]) (values `(,f1 . ,f2) (append `(,store1 . ,store2) store))))] [(null? (car ls)) (values ls store)] [(f (car ls)) (let-values ([(f1 store) (filter*-sps f (cdr ls) store)]) (values (cons (car ls) f1) store))] [else (let-values ([(f1 store) (filter*-sps f (cdr ls) store)]) (values f1 (cons (car ls) store)))]))) (define fib-sps (λ (n store) (cond [(zero? n) (values 0 '((0 . 0)))] [(zero? (sub1 n)) (let-values ([(fub-sub1 store) (fib-sps (sub1 n) store)]) (values 1 (cons '(1 . 1) store)))] [else (let-values ([(fib-sub1 store1) (fib-sps (sub1 n) store)]) (let-values ([(fib-sub2 store2) (fib-sps (sub1 (sub1 n)) store)]) (values (+ fib-sub1 fib-sub2) (cons `(,n . ,(+ fib-sub1 fib-sub2)) (cons `(,(sub1 n) . ,fib-sub1) store2)))))]))) (define-syntax and* (syntax-rules () [(and*) #t] [(and* a) (and a)] [(and* a b c ...) (and a (and* b c ...))])) (define-syntax list* (syntax-rules () [(list*) (raise-syntax-error "Incorrect argument-count to list*")] [(list* a) a] [(list* a b c ...) (cons a (list* b c ...))])) (define-syntax macro-list (syntax-rules () [(macro-list) '()] [(macro-list a) '(a)] [(macro-list a b ...) (cons a (macro-list b ...))])) (define-syntax mcond (syntax-rules () [(mcond (else res)) res] [(mcond (cond1 res1) (cond2 res2)) (if cond1 res1 (mcond (cond2 res2)))] )) (define-syntax quote-quote (syntax-rules () [(_ e) (quote (quote e))])) (define-syntax copy-code (syntax-rules () [(_ x) `(,x x)])) (define-syntax macro-map (syntax-rules () [(macro-map f '()) '()] [(macro-map f '((a))) (f a)] [(macro-map f '(a b ...)) (cons (f a) (macro-map f '(b ...)))]))
true
644f48e30c4f665b8575dac238a8adfeb1e9cf22
14208b07347b67eefeb7c807a1e02301410558da
/model/config.rkt
0f8aeaebd63d278490ede3963d2aa574f2111fe9
[]
no_license
mflatt/scope-sets
a6444696901fe3da350ddf9803655b9818a46e0f
4d3ae9d8a0f6ff83aa597612d280406cb6d82f5b
refs/heads/master
2021-01-21T13:41:15.662388
2016-05-04T01:56:21
2016-05-04T01:57:48
45,715,601
8
0
null
null
null
null
UTF-8
Racket
false
false
345
rkt
config.rkt
#lang racket/base (provide s s/inline narrow-mode?) (define s (string->number (or (getenv "SCOPE_SETS_TO_PDF") "1.2"))) (define s/inline (string->number (or (getenv "SCOPE_SETS_TO_PDF_INLINE") (number->string s)))) (define narrow-mode? (and (getenv "SCOPE_SETS_TO_PDF") #t))
false
9920489e0a6959a7b9f3f97e15615cf032e7a61e
a70301d352dcc9987daf2bf12919aecd66defbd8
/res+edu+pro/scope.rkt
034666890ffcdf22edb9a35173570676437b6df7
[]
no_license
mflatt/talks
45fbd97b1ca72addecf8f4b92053b85001ed540b
7abfdf9a9397d3d3d5d1b4c107ab6a62d0ac1265
refs/heads/master
2021-01-19T05:18:38.094408
2020-06-04T16:29:25
2020-06-04T16:29:25
87,425,078
2
2
null
null
null
null
UTF-8
Racket
false
false
2,854
rkt
scope.rkt
#lang slideshow (require slideshow/code racket/runtime-path racket/draw (for-syntax racket/base) "util.rkt" "history.rkt" "color.rkt") (provide scope-slides) (define-runtime-path strange-loop-jpg "logos/strange-loop.jpg") (define strange-loop (bitmap strange-loop-jpg)) (define colors (vector "lightcoral" "deepskyblue" "gold" (make-color 0 220 0))) (define-syntax-rule (bg n b ...) (background (code b ...) (vector-ref colors (sub1 n)))) (define (scope-demo) (let-syntax ([let* (make-code-transformer (lambda (stx) (if (identifier? stx) #`(bg 4 let) #f)))]) (code (define #,(bg 1 x) 1) #,(bg 1 code:blank (let ([#,(bg 2 x) x]) #,(bg 2 (λ (#,(bg 3 y)) #,(bg 3 (let* ([#,(bg 4 x) y]) (#,(bg 4 if) #,(bg 4 x) #,(bg 4 x) x)))))))))) (define (tint-box color p label suffix) (let* ([p (inset p (/ gap-size 2))] [p (cc-superimpose (frame (cellophane (colorize (filled-rectangle (pict-width p) (pict-height p)) color) 0.3) #:color color) p)]) (vr-append (let ([lbl (inset (hbl-append (text label `modern (current-font-size)) (text suffix `(bold . modern) (current-font-size))) 5)]) (cc-superimpose (colorize (filled-rectangle (pict-width lbl) (pict-height lbl)) file-tab-color) lbl)) p))) (define (convert-desc) (define c-code (tint-box c-color (blank 300 200) "expander." "c")) (define rkt-code (tint-box racket-color (blank 300 200) "expander." "rkt")) (leftward (ht-append (* 2 gap-size) c-code (hc-append (* 2 gap-size) (colorize (arrow gap-size 0) "forestgreen") rkt-code)))) (define (scope-slides) (define macros-and-scope (ca 2016 "Macros and Scope")) (define name "Macros and Scope") (as-history #:edu 0 (slide #:title macros-and-scope #:name name (scope-demo))) (as-history #:res 0 #:edu 0 (slide #:title macros-and-scope #:name name (convert-desc))) (as-history #:res 0 (slide #:title macros-and-scope #:name name (let ([p (convert-desc)]) (refocus (hb-append p (let ([i (scale strange-loop 0.25)]) (inset i (* -2/3 (pict-width i)) 0 0 0))) p))))) (module+ main (scope-slides))
true
53e6e88a35acd3a1190422d958d56da32bbbcfc5
e553691752e4d43e92c0818e2043234e7a61c01b
/test/base/eval-guarded.rkt
3e0bd70a292ce40158564b233ebe38d65edbe2a0
[ "BSD-2-Clause" ]
permissive
emina/rosette
2b8c1bcf0bf744ba01ac41049a00b21d1d5d929f
5dd348906d8bafacef6354c2e5e75a67be0bec66
refs/heads/master
2023-08-30T20:16:51.221490
2023-08-11T01:38:48
2023-08-11T01:38:48
22,478,354
656
89
NOASSERTION
2023-09-14T02:27:51
2014-07-31T17:29:18
Racket
UTF-8
Racket
false
false
10,189
rkt
eval-guarded.rkt
#lang racket (require rackunit/text-ui rackunit rosette/lib/roseunit "solver.rkt" (only-in "vc.rkt" check-vc-eqv) (only-in "store.rkt" check-store)) (require rosette/base/core/eval rosette/base/core/store rosette/base/core/exn rosette/base/core/result) (require rosette/base/adt/box) (require (only-in rosette unsat?) (only-in rosette/base/form/define define-symbolic) (only-in rosette/base/core/bool @boolean? @true? && || ! => <=> vc clear-vc! with-vc merge-vc! $assume $assert @assume @assert vc-true vc-true? vc-assumes vc-asserts) (only-in rosette/base/core/real @integer? @= @<) (only-in rosette/base/core/merge merge merge*)) (define (vc-eqv? actual assumes asserts) (unsat? (solve (! (&& (<=> (vc-assumes actual) assumes) (<=> (vc-asserts actual) asserts)))))) (define (int-eqv? actual expected) (unsat? (solve (! (@= actual expected))))) (define-syntax-rule (check-normal actual e-val e-store e-assumes e-asserts) (begin (match-define (normal (normal v st) sp) actual) (check-equal? v e-val) (check-store st e-store) (check-true (vc-eqv? sp e-assumes e-asserts)))) (define-syntax-rule (check-failed actual e-exn? e-assumes e-asserts) (begin (match-define (failed ex sp) actual) (check-pred e-exn? ex) (check-true (vc-eqv? sp e-assumes e-asserts)))) (define (check-eval-assuming) (define-symbolic g a b @boolean?) (define x (@box 3)) ;---------------------------; (check-normal (eval-assuming #t (const 1)) 1 null #t #t) (check-normal (eval-assuming g (const 1)) 1 null g #t) (check-normal (eval-assuming g (lambda () (@set-box! x 2))) (void) `((,x 0 2)) g #t) (check-normal (eval-assuming g (lambda () (@set-box! x 4) (@assert a))) (void) `((,x 0 4)) g (=> g a)) (check-normal (eval-assuming g (lambda () (@set-box! x 5) (@assert a) (@assume b))) (void) `((,x 0 5)) (&& g (=> a b)) (=> g a)) ;---------------------------; (check-failed (eval-assuming #f (const 1)) exn:fail:svm:assume:core? #f #t) (check-failed (eval-assuming g (lambda () (@set-box! x 2) (@assume (! g)))) exn:fail:svm:assume:user? #f #t) (check-failed (eval-assuming g (lambda () (@set-box! x 4) ($assume (! g)))) exn:fail:svm:assume:core? #f #t) (check-failed (eval-assuming g (lambda () (@set-box! x 5) (@assert #f))) exn:fail:svm:assert:user? g (! g)) (check-failed (eval-assuming g (lambda () (@set-box! x 6) ($assert #f))) exn:fail:svm:assert:core? g (! g)) (check-failed (eval-assuming g (lambda () (@set-box! x 7) (1))) exn:fail:svm:assert:err? g (! g)) ;---------------------------; (check-equal? (@unbox x) 3) (check-pred vc-true? (vc))) (define-syntax-rule (check-vc-and-cell e-assumes e-asserts cell e-cell-val) (begin (check-vc-eqv e-assumes e-asserts) (check-true (int-eqv? (@unbox cell) e-cell-val)) (clear-vc!) (@set-box! cell 1))) (define (check-eval-guarded-0) (define-symbolic g a b c @boolean?) (define x (@box 1)) ;---------------------------; (check-equal? (eval-guarded! (list #t) (list (thunk 1))) 1) (check-vc-and-cell #t #t x 1) (check-equal? (eval-guarded! (list g) (list (thunk 1))) 1) (check-vc-and-cell #t #t x 1) (eval-guarded! (list g) (list (lambda () (@set-box! x 2)))) (check-vc-and-cell #t #t x 2) (eval-guarded! (list g) (list (lambda () (@set-box! x 4) (@assert a)))) (check-vc-and-cell #t (=> g a) x 4) (eval-guarded! (list g) (list (lambda () (@set-box! x 5) (@assert a) (@assume b)))) (check-vc-and-cell (=> g (=> a b)) (=> g a) x 5) ;---------------------------; (@assume c) (check-exn exn:fail:svm:merge? (thunk (eval-guarded! null null))) (check-vc-and-cell c #t x 1) (@assume c) (check-exn exn:fail:svm:merge? (thunk (eval-guarded! (list #f) (list (const 1))))) (check-vc-and-cell c #t x 1) (check-exn exn:fail:svm:merge? (thunk (eval-guarded! (list g) (list (lambda () (@set-box! x 2) (@assume (! g))))))) (check-vc-and-cell (! g) #t x 1) (check-exn exn:fail:svm:merge? (thunk (eval-guarded! (list g) (list (lambda () (@set-box! x 3) (@assert #f)))))) (check-vc-and-cell #t (! g) x 1) (check-exn exn:fail:svm:merge? (thunk (eval-guarded! (list g) (list (lambda () (@set-box! x 3) (1)))))) (check-vc-and-cell #t (! g) x 1)) (define (check-eval-guarded-1) (define-symbolic g a b c @boolean?) (define-symbolic i @integer?) (define !g (! g)) (define x (@box 1)) (define (λ-set v [r v]) (lambda () (@set-box! x v) r)) (define (λ-set-assume v a [r v]) (lambda () (@set-box! x v) (@assume a) r)) (define (λ-set-assert v a [r v]) (lambda () (@set-box! x v) (@assert a) r)) (define (λ-set-err v) (lambda () (@set-box! x v) (1) v)) ;---------------------------; (check-equal? (eval-guarded! (list #t #f) (list void void)) (void)) (check-vc-and-cell #t #t x 1) (check-equal? (eval-guarded! (list #t #f) (list (const 1) (const 2))) 1) (check-vc-and-cell #t #t x 1) (check-equal? (eval-guarded! (list #f #t) (list (const 1) (const 2))) 2) (check-vc-and-cell #t #t x 1) (check-equal? (eval-guarded! (list #t #f) (list (λ-set 2) (λ-set 3))) 2) (check-vc-and-cell #t #t x 2) (check-equal? (eval-guarded! (list #t #f) (list (λ-set 4) (λ-set-assume 3 #f))) 4) (check-vc-and-cell #t #t x 4) (check-equal? (eval-guarded! (list #t #f) (list (λ-set 4) (λ-set-assert 3 #f))) 4) (check-vc-and-cell #t #t x 4) (check-equal? (eval-guarded! (list #t #f) (list (λ-set 4) (λ-set-err 3))) 4) (check-vc-and-cell #t #t x 4) (check-exn exn:fail:svm:assume:core? ; fails during merge-vc! (thunk (eval-guarded! (list #t #f) (list (λ-set-assume 2 #f) (λ-set 3))))) (check-vc-and-cell #f #t x 1) (check-exn exn:fail:svm:assert:core? ; fails during merge-vc! (thunk (eval-guarded! (list #t #f) (list (λ-set-assert 2 #f) (λ-set 3))))) (check-vc-and-cell #t #f x 1) (check-equal? (eval-guarded! (list #t #f) (list (λ-set-assume 4 g) (λ-set-err 3))) 4) (check-vc-and-cell g #t x 4) (check-equal? (eval-guarded! (list #t #f) (list (λ-set-assert 4 g) (λ-set-err 3))) 4) (check-vc-and-cell #t g x 4) ;---------------------------; (check-equal? (eval-guarded! (list g !g) (list void void)) (void)) (check-vc-and-cell #t #t x 1) (check-equal? (eval-guarded! (list g !g) (list (const 1) (const 2))) (merge g 1 2)) (check-vc-and-cell #t #t x 1) (check-equal? (eval-guarded! (list g !g) (list (λ-set 2 1) (const 2))) (merge g 1 2)) (check-vc-and-cell #t #t x (merge g 2 1)) (check-equal? (eval-guarded! (list g !g) (list (λ-set 2 1) (λ-set 3 2))) (merge g 1 2)) (check-vc-and-cell #t #t x (merge g 2 3)) (check-equal? (eval-guarded! (list g !g) (list (λ-set-assume 2 #f) (λ-set 3 2))) 2) (check-vc-and-cell (! g) #t x 3) (check-equal? (eval-guarded! (list g !g) (list (λ-set-assert 2 #f) (λ-set 3 2))) 2) (check-vc-and-cell #t (! g) x 3) (check-equal? (eval-guarded! (list g !g) (list (λ-set-err 2) (λ-set 3 2))) 2) (check-vc-and-cell #t (! g) x 3) (check-exn exn:fail:svm:assume:core? ; fails during merge-vc! (thunk (eval-guarded! (list g !g) (list (λ-set-assume 2 #f) (λ-set-assume 3 #f))))) (check-vc-and-cell #f #t x 1) (check-exn exn:fail:svm:assert:core? ; fails during merge-vc! (thunk (eval-guarded! (list g !g) (list (λ-set-assert 2 #f) (λ-set-assert 3 #f))))) (check-vc-and-cell #t #f x 1) (check-exn exn:fail:svm:merge? (thunk (eval-guarded! (list g !g) (list (λ-set-assume 2 #f) (λ-set-assert 3 #f))))) (check-vc-and-cell (! g) g x 1) (check-exn exn:fail:svm:merge? (thunk (eval-guarded! (list g !g) (list (λ-set-assert 2 #f) (λ-set-assume 3 #f))))) (check-vc-and-cell g (! g) x 1) ;---------------------------; (define-values (i- i0 i+) (values (@< i 0) (@= i 0) (@< 0 i))) (check-equal? (eval-guarded! (list i- i0 i+) (list (λ-set 2) (λ-set 3) (λ-set 4))) (apply merge* `((,i- . 2) (,i0 . 3) (,i+ . 4)))) (check-vc-and-cell #t #t x (apply merge* `((,i- . 2) (,i0 . 3) (,i+ . 4)))) (check-equal? (eval-guarded! (list i- i0 i+) (list (λ-set 2) (const 3) (λ-set 4))) (apply merge* `((,i- . 2) (,i0 . 3) (,i+ . 4)))) (check-vc-and-cell #t #t x (apply merge* `((,i- . 2) (,i0 . 1) (,i+ . 4)))) (check-equal? (eval-guarded! (list i- i0 i+) (list (λ-set 2) (const 3) (const 4))) (apply merge* `((,i- . 2) (,i0 . 3) (,i+ . 4)))) (check-vc-and-cell #t #t x (apply merge* `((,i- . 2) (,i0 . 1) (,i+ . 1)))) (check-equal? (eval-guarded! (list i- i0 i+) (list (λ-set 2) (λ-set-assume 3 #f) (λ-set 4))) (apply merge* `((,i- . 2) (,i+ . 4)))) (check-vc-and-cell (! (@= 0 i)) #t x (apply merge* `((,i- . 2) (,i+ . 4)))) (check-equal? (eval-guarded! (list i- i0 i+) (list (λ-set 2) (λ-set-assert 3 #f) (λ-set 4))) (apply merge* `((,i- . 2) (,i+ . 4)))) (check-vc-and-cell #t (! (@= 0 i)) x (apply merge* `((,i- . 2) (,i+ . 4)))) (check-equal? (eval-guarded! (list i- i0 i+) (list (λ-set 2) (λ-set-err 3) (λ-set 4))) (apply merge* `((,i- . 2) (,i+ . 4)))) (check-vc-and-cell #t (! (@= 0 i)) x (apply merge* `((,i- . 2) (,i+ . 4)))) (check-equal? (eval-guarded! (list i- i0 i+) (list (λ-set-assume 2 #f) (λ-set-err 3) (λ-set 4))) (apply merge* `((,i+ . 4)))) (check-vc-and-cell (! (@< i 0)) (! (@= 0 i)) x (apply merge* `((,i+ . 4)))) (check-exn exn:fail:svm:merge? (thunk (eval-guarded! (list i- i0 i+) (list (λ-set-assume 2 #f) (λ-set-err 3) (λ-set-assert 4 #f))))) (check-vc-and-cell (! (@< i 0)) (&& (! (@= 0 i)) (! (@< 0 i))) x 1)) (define eval-assuming-tests (test-suite+ "Tests for eval-assuming in rosette/base/core/eval.rkt" (check-eval-assuming))) (define eval-guarded-tests (test-suite+ "Tests for eval-guarded in rosette/base/core/eval.rkt" (check-eval-guarded-0) (check-eval-guarded-1))) (module+ test (time (run-tests eval-assuming-tests)) (time (run-tests eval-guarded-tests)))
true
75d25436af9e01e2b20606b76f5cf35a6484ec5d
716d0a8d8eaeec1127c914dfa984228094d48edd
/lang/reader.rkt
0c3d964046508ddf1de21721401e647c23834ee3
[ "ISC" ]
permissive
jkominek/unlambda
57e93238737cfb2144f0050905abe8c405a3f05c
8675721abc801dce3427517d3fed6611d2105ede
refs/heads/master
2021-01-10T22:07:30.552236
2015-04-29T20:27:50
2015-04-29T20:27:50
32,911,934
3
0
null
null
null
null
UTF-8
Racket
false
false
544
rkt
reader.rkt
#lang s-exp syntax/module-reader unlambda/unlambda #:read unlambda-read #:read-syntax unlambda-read-syntax #:info unlambda-info (require "../parser.rkt" ;; Parses to generate an AST. Identifiers in the AST ;; are represented as syntax objects with source location. ) (define (unlambda-read in) (syntax->datum (read-term #f in))) (define (unlambda-read-syntax src in) (read-term src in)) (define (unlambda-info key default default-filter) (case key [(color-lexer) color-lexer] [else (default-filter key default)]))
false
5e1ac363fd83c08d48c98c5771b38707c1e6a335
25a6efe766d07c52c1994585af7d7f347553bf54
/gui-doc/scribblings/gui/window-intf.scrbl
0a8819458983faf4c4942af05171d600860fb58b
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
racket/gui
520ff8f4ae5704210822204aa7cd4b74dd4f3eef
d01d166149787e2d94176d3046764b35c7c0a876
refs/heads/master
2023-08-25T15:24:17.693905
2023-08-10T16:45:35
2023-08-10T16:45:35
27,413,435
72
96
NOASSERTION
2023-09-14T17:09:52
2014-12-02T03:35:22
Racket
UTF-8
Racket
false
false
19,840
scrbl
window-intf.scrbl
#lang scribble/doc @(require "common.rkt" (for-label (only-in ffi/unsafe cpointer?))) @definterface/title[window<%> (area<%>)]{ A @racket[window<%>] object is an @racket[area<%>] with a graphical representation that can respond to events. All @racket[window<%>] classes accept the following named instantiation arguments: @itemize[ @item{@indexed-racket[enabled] --- default is @racket[#t]; passed to @method[window<%> enable] if @racket[#f]} ] @defmethod*[([(accept-drop-files) boolean?] [(accept-drop-files [accept-files? any/c]) void?])]{ @index["drag-and-drop"]{Enables} or disables drag-and-drop dropping for the window, or gets the enable state. Dropping is initially disabled. See also @method[window<%> on-drop-file]. } @defmethod[(client->screen [x position-integer?] [y position-integer?]) (values position-integer? position-integer?)]{ @index["global coordinates"]{Converts} local window coordinates to screen coordinates. On Mac OS, the screen coordinates start with @math{(0, 0)} at the upper left of the menu bar. In contrast, @xmethod[top-level-window<%> move] considers @math{(0, 0)} to be below the menu bar. See also @racket[get-display-left-top-inset]. } @defmethod[(enable [enable? any/c]) void?]{ Enables or disables a window so that input events are ignored. (Input events include mouse events, keyboard events, and close-box clicks, but not focus or update events.) When a window is disabled, input events to its children are also ignored. @MonitorMethod[@elem{The enable state of a window} @elem{enabling a parent window} @elem{@method[window<%> on-superwindow-enable]} @elem{enable state}] If @racket[enable?] is true, the window is enabled, otherwise it is disabled. } @defmethod[(focus) void?]{ @index['("keyboard focus" "setting")]{Moves} the keyboard focus to the window, relative to its top-level window, if the window ever accepts the keyboard focus. If the focus is in the window's top-level window or if the window's top-level window is visible and floating (i.e., created with the @racket['float] style), then the focus is immediately moved to this window. Otherwise, the focus is not immediately moved, but when the window's top-level window gets the keyboard focus, the focus is delegated to this window. See also @method[window<%> on-focus]. Note that on Unix, keyboard focus can move to the menu bar when the user is selecting a menu item. @MonitorMethod[@elem{The current keyboard focus window} @elem{the user} @elem{@method[window<%> on-focus]} @elem{focus}] } @defmethod[(get-client-handle) cpointer?]{ Returns a handle to the ``inside'' of the window for the current platform's GUI toolbox. The value that the pointer represents depends on the platform: @itemize[ @item{Windows: @tt{HWND}} @item{Mac OS: @tt{NSView}} @item{Unix: @tt{GtkWidget}} ] See also @method[window<%> get-handle].} @defmethod[(get-client-size) (values dimension-integer? dimension-integer?)]{ Gets the interior size of the window in pixels. For a container, the interior size is the size available for placing subwindows (including the border margin). For a canvas, this is the visible drawing area. The client size is returned as two values: width and height (in pixels). See also @method[area-container<%> reflow-container]. } @defmethod[(get-cursor) (or/c (is-a?/c cursor%) #f)]{ Returns the window's cursor, or @racket[#f] if this window's cursor defaults to the parent's cursor. See @method[window<%> set-cursor] for more information. } @defmethod[(get-handle) cpointer?]{ Returns a handle to the ``outside'' of the window for the current platform's GUI toolbox. The value that the pointer represents depends on the platform: @itemize[ @item{Windows: @tt{HWND}} @item{Mac OS: @tt{NSWindow} for a @racket[top-level-window<%>] object, @tt{NSView} for other windows} @item{Unix: @tt{GtkWidget}} ] See also @method[window<%> get-client-handle].} @defmethod[(get-height) dimension-integer?]{ Returns the window's total height (in pixels). See also @method[area-container<%> reflow-container]. } @defmethod[(get-label) (or/c label-string? (is-a?/c bitmap%) (or/c 'app 'caution 'stop) (list/c (is-a?/c bitmap%) label-string? (or/c 'left 'top 'right 'bottom)) #f)]{ Gets a window's label, if any. Control windows generally display their label in some way. Frames and dialogs display their label as a window title. Panels do not display their label, but the label can be used for identification purposes. Messages, buttons, and check boxes can have bitmap labels (only when they are created with bitmap labels), but all other windows have string labels. In addition, a message label can be an icon symbol @racket['app], @racket['caution], or @racket['stop], and a button can have both a bitmap label and a string label (along with a position for the bitmap). A label string may contain @litchar{&}s, which serve as keyboard navigation annotations for controls on Windows and Unix. The ampersands are not part of the displayed label of a control; instead, ampersands are removed in the displayed label (on all platforms), and any character preceding an ampersand is underlined (Windows and Unix) indicating that the character is a mnemonic for the control. Double ampersands are converted into a single ampersand (with no displayed underline). See also @method[top-level-window<%> on-traverse-char]. If the window does not have a label, @racket[#f] is returned. } @defmethod[(get-plain-label) (or/c string? #f)]{ Like @method[window<%> get-label], except that: @itemlist[ @item{If the label includes @litchar{(&}@racket[_c]@litchar{)} for any character @racket[_c], then the sequenece and any surrounding whitespace is removed.} @item{If the label contains @litchar{&}@racket[_c] for any character @racket[_c], the @litchar{&} is removed.} @item{If the label contains a tab character, then the tab character and all following characters are removed.} ] See also @racket[button%]'s handling of labels. If the window has no label or the window's label is not a string, @racket[#f] is returned. } @defmethod[(get-size) (values dimension-integer? dimension-integer?)]{ Gets the current size of the entire window in pixels, not counting horizontal and vertical margins. (On Unix, this size does not include a title bar or borders for a frame/dialog.) See also @method[window<%> get-client-size]. The geometry is returned as two values: width and height (in pixels). See also @method[area-container<%> reflow-container]. } @defmethod[(get-width) dimension-integer?]{ Returns the window's current total width (in pixels). See also @method[area-container<%> reflow-container]. } @defmethod[(get-x) position-integer?]{ Returns the position of the window's left edge in its parent's coordinate system. See also @method[area-container<%> reflow-container]. } @defmethod[(get-y) position-integer?]{ Returns the position of the window's top edge in its parent's coordinate system. See also @method[area-container<%> reflow-container]. } @defmethod[(has-focus?) boolean?]{ Indicates whether the window currently has the keyboard focus. See also @method[window<%> on-focus]. } @defmethod[(is-enabled?) boolean?]{ Indicates whether the window is currently enabled or not. The result is @racket[#t] if this window is enabled when its ancestors are enabled, or @racket[#f] if this window remains disable when its ancestors are enabled. (That is, the result of this method is affected only by calls to @method[window<%> enable] for @this-obj[], not by the enable state of parent windows.)} @defmethod[(is-shown?) boolean?]{ Indicates whether the window is currently shown or not. The result is @racket[#t] if this window is shown when its ancestors are shown, or @racket[#f] if this window remains hidden when its ancestors are shown. (That is, the result of this method is affected only by calls to @method[window<%> show] for @this-obj[], not by the visibility of parent windows.)} @defmethod[(on-drop-file [pathname path?]) void?]{ @index["drag-and-drop"]{Called} when the user drags a file onto the window. (On Unix, drag-and-drop is supported via the XDND protocol.) Drag-and-drop must first be enabled for the window with @method[window<%> accept-drop-files]. On Mac OS, when the application is running and user double-clicks an application-handled file or drags a file onto the application's icon, the main thread's application file handler is called (see @racket[application-file-handler]). The default handler calls the @method[window<%> on-drop-file] method of the most-recently activated frame if drag-and-drop is enabled for that frame, independent of the frame's eventspace (but the method is called in the frame's eventspace's handler thread). When the application is not running, the filenames are provided as command-line arguments. } @defmethod[(on-focus [on? any/c]) void?]{ @methspec{ @index['("keyboard focus" "notification")]{Called} when a window receives or loses the keyboard focus. If the argument is @racket[#t], the keyboard focus was received, otherwise it was lost. Note that on Unix, keyboard focus can move to the menu bar when the user is selecting a menu item. } @methimpl{ Does nothing. }} @defmethod[(on-move [x position-integer?] [y position-integer?]) void?]{ @methspec{ Called when the window is moved. (For windows that are not top-level windows, ``moved'' means moved relative to the parent's top-left corner.) The new position is provided to the method. } @methimpl{ Does nothing. }} @defmethod[(on-size [width dimension-integer?] [height dimension-integer?]) void?]{ @methspec{ Called when the window is resized. The window's new size (in pixels) is provided to the method. The size values are for the entire window, not just the client area. } @methimpl{ Does nothing. }} @defmethod[(on-subwindow-char [receiver (is-a?/c window<%>)] [event (is-a?/c key-event%)]) boolean?]{ @methspec{ Called when this window or a child window receives a keyboard event. The @method[window<%> on-subwindow-char] method of the receiver's top-level window is called first (see @method[area<%> get-top-level-window]); if the return value is @racket[#f], then the @method[window<%> on-subwindow-char] method is called for the next child in the path to the receiver, and so on. Finally, if the receiver's @method[window<%> on-subwindow-char] method returns @racket[#f], the event is passed on to the receiver's normal key-handling mechanism. The @racket[event] argument is the event that was generated for the @racket[receiver] window. The atomicity limitation @method[window<%> on-subwindow-event] applies to @method[window<%> on-subwindow-char] as well. That is, an insufficiently cooperative @method[window<%> on-subwindow-char] method can effectively disable a control's handling of key events, even when it returns @racket[#f] BEWARE: The default @xmethod[frame% on-subwindow-char] and @xmethod[dialog% on-subwindow-char] methods consume certain keyboard events (e.g., arrow keys, Enter) used for navigating within the window. Because the top-level window gets the first chance to handle the keyboard event, some events never reach the ``receiver'' child unless the default frame or dialog method is overridden. } @methimpl{ Returns @racket[#f]. }} @defmethod[(on-subwindow-event [receiver (is-a?/c window<%>)] [event (is-a?/c mouse-event%)]) boolean?]{ @methspec{ Called when this window or a child window receives a mouse event. The @method[window<%> on-subwindow-event] method of the receiver's top-level window is called first (see @method[area<%> get-top-level-window]); if the return value is @racket[#f], the @method[window<%> on-subwindow-event] method is called for the next child in the path to the receiver, and so on. Finally, if the receiver's @method[window<%> on-subwindow-event] method returns @racket[#f], the event is passed on to the receiver's normal mouse-handling mechanism. The @racket[event] argument is the event that was generated for the @racket[receiver] window. If the @method[window<%> on-subwindow-event] method chain does not complete atomically (i.e., without requiring other threads to run) or does not complete fast enough, then the corresponding event may not be delivered to a target control, such as a button. In other words, an insufficiently cooperative @method[window<%> on-subwindow-event] method can effectively disable a control's handling of mouse events, even when it returns @racket[#f]. } @methimpl{ Returns @racket[#f]. }} @defmethod[(on-subwindow-focus [receiver (is-a?/c window<%>)] [on? boolean?]) void?]{ @methspec{ Called when this window or a child window receives or loses the keyboard focus. This method is called after the @method[window<%> on-focus] method of @racket[receiver]. The @method[window<%> on-subwindow-focus] method of the receiver's top-level window is called first (see @method[area<%> get-top-level-window]), then the @method[window<%> on-subwindow-focus] method is called for the next child in the path to the receiver, and so on. } @methimpl{ Does nothing. }} @defmethod[(on-superwindow-activate [active? any/c]) void?]{ @methspec{ Called via the event queue whenever the containing @racket[top-level-window<%>] is either activated or deactivated (see @method[top-level-window<%> on-activate]). } @methimpl{ Does nothing. } @history[#:added "1.54"] } @defmethod[(on-superwindow-enable [enabled? any/c]) void?]{ @methspec{ Called via the event queue whenever the enable state of a window has changed, either through a call to the window's @method[window<%> enable] method, or through the enabling/disabling of one of the window's ancestors. The method's argument indicates whether the window is now enabled or not. This method is not called when the window is initially created; it is called only after a change from the window's initial enable state. Furthermore, if an enable notification event is queued for the window and it reverts its enabled state before the event is dispatched, then the dispatch is canceled. If the enable state of a window's ancestor changes while the window is deleted (e.g., because it was removed with @method[area-container<%> delete-child]), then no enable events are queued for the deleted window. But if the window is later re-activated into an enable state that is different from the window's state when it was de-activated, then an enable event is immediately queued. } @methimpl{ Does nothing. }} @defmethod[(on-superwindow-show [shown? any/c]) void?]{ @methspec{ Called via the event queue whenever the visibility of a window has changed, either through a call to the window's @method[window<%> show], through the showing/hiding of one of the window's ancestors, or through the activating or deactivating of the window or its ancestor in a container (e.g., via @method[area-container<%> delete-child]). The method's argument indicates whether the window is now visible or not. This method is not called when the window is initially created; it is called only after a change from the window's initial visibility. Furthermore, if a show notification event is queued for the window and it reverts its visibility before the event is dispatched, then the dispatch is canceled. } @methimpl{ Does nothing. }} @defmethod[(popup-menu [menu (is-a?/c popup-menu%)] [x position-integer?] [y position-integer?]) void?]{ @popupmenuinfo["window" "window" ""] The @racket[menu] is popped up within the window at position (@racket[x], @racket[y]). } @defmethod[(refresh) void?]{ Enqueues a window-refresh event to repaint the window; see @secref["Event_Types_and_Priorities"] for more information on the event's priority. } @defmethod[(screen->client [x position-integer?] [y position-integer?]) (values position-integer? position-integer?)]{ @index["global coordinates"]{Converts} global coordinates to window local coordinates. See also @method[window<%> client->screen] for information on screen coordinates. } @defmethod[(set-cursor [cursor (or/c (is-a?/c cursor%) #f)]) void?]{ Sets the window's cursor. Providing @racket[#f] instead of a cursor value removes the window's cursor. If a window does not have a cursor, it uses the cursor of its parent. Frames and dialogs start with the standard arrow cursor, and text fields start with an I-beam cursor. All other windows are created without a cursor. } @defmethod[(set-label [l label-string?]) void?]{ Sets a window's label. The window's natural minimum size might be different after the label is changed, but the window's minimum size is not recomputed. If the window was not created with a label, or if the window was created with a non-string label, @racket[l] is ignored. See @method[window<%> get-label] for more information. } @defmethod[(show [show? any/c]) void?]{ Shows or hides a window. @MonitorMethod[@elem{The visibility of a window} @elem{the user clicking the window's close box, for example} @elem{@method[window<%> on-superwindow-show] or @method[top-level-window<%> on-close]} @elem{visibility}] If @racket[show?] is @racket[#f], the window is hidden. Otherwise, the window is shown. } @defmethod[(warp-pointer [x position-integer?] [y position-integer?]) void?]{ Moves the cursor to the given location in the window's local coordinates. } @defmethod*[([(wheel-event-mode) (or/c 'one 'integer 'fraction)] [(wheel-event-mode [mode (or/c 'one 'integer 'fraction)]) void?])]{ Gets or sets the mode for mouse-wheel events in the window. Wheel events are represented as @racket[key-event%] instances where @xmethod[key-event% get-key-code] returns @racket['wheel-up], @racket['wheel-down], @racket['wheel-right], or @racket['wheel-left]. A Window's wheel-event mode determines the handling of variable wheel-sized events reported the underlying platform. Specifically, the wheel-event mode determines the possible values of @xmethod[key-event% get-wheel-steps] for a system-generated event for the window: @itemlist[ @item{@racket['one] --- wheel events are always reported for a single step, where the window accumulates increments until it reaches a full step, and where it generates separate events for multi-step accumulations.} @item{@racket['integer] --- wheel events are always reported as integer-sized steps, where fractional steps are accumulated and preserved as needed to reach integer increments.} @item{@racket['fraction] --- wheel events are reported as positive real values immediately as received from the underlying platform.} ] The default wheel-event mode is @racket['one], except that @racket[editor-canvas%] initializes the wheel-event mode to @racket['integer]. @history[#:added "1.43"]} }
false
69b13368472cd90fff76c810bfe584ac4a8f3f8c
063934d4e0bf344a26d5679a22c1c9e5daa5b237
/old/visualization/application/controls.rkt
c1fec29b59abe2f0c7356bd07830eac520da7c97
[]
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
5,833
rkt
controls.rkt
#lang racket/gui (provide fwpboard% entity-snip%) (define arrow-dark (make-object color% 30 30 30)) (define arrow-light (make-object color% 170 170 170)) (define x-red (make-object color% 255 0 0)) ; Returns a normalized vector (define (vn x y) (let ([d (sqrt (+ (* x x) (* y y)))]) (vector (/ x d) (/ y d)))) ; Draws the edge by looking at the location of the nodes (define (draw-edge dc edge) (letrec ( [n1 (send edge get-from)] [n2 (send edge get-to)] [cx1 (+ (send n1 get-x) 43)] [cy1 (+ (send n1 get-y) 43)] [cx2 (+ (send n2 get-x) 43)] [cy2 (+ (send n2 get-y) 43)] [v1 (vn (- cx2 cx1) (- cy2 cy1))] [arrow-color (if (send edge is-active?) arrow-dark arrow-light)] ) ; Line pen (send dc set-pen arrow-color 3 (if (send edge is-blocked?) 'short-dash 'solid)) (send dc set-smoothing 'aligned) ; Draw the line (send dc draw-line (+ cx1 (* 70 (vector-ref v1 0))) (+ cy1 (* 70 (vector-ref v1 1))) (- cx2 (* 70 (vector-ref v1 0))) (- cy2 (* 70 (vector-ref v1 1)))) ; Set the pen width back (send dc set-pen arrow-color 1 'solid) ; Set brush (send dc set-brush arrow-color 'solid) ; Draw the arrowhead (if (send edge is-active?) (send dc draw-polygon (list (make-object point% (- cx2 (* 60 (vector-ref v1 0))) (- cy2 (* 60 (vector-ref v1 1)))) (make-object point% (+ (- cx2 (* 75 (vector-ref v1 0))) (- 0 (* 7 (vector-ref v1 1)))) (+ (- cy2 (* 75 (vector-ref v1 1))) (* 7 (vector-ref v1 0)))) (make-object point% (- (- cx2 (* 75 (vector-ref v1 0))) (- 0 (* 7 (vector-ref v1 1)))) (- (- cy2 (* 75 (vector-ref v1 1))) (* 7 (vector-ref v1 0))))) ) #f) ; Draw the X (if (send edge is-blocked?) (begin (send dc set-pen x-red 3 'solid) (send dc draw-line (- (/ (+ cx1 cx2) 2) 12) (- (/ (+ cy1 cy2) 2) 12) (+ (/ (+ cx1 cx2) 2) 12) (+ (/ (+ cy1 cy2) 2) 12)) (send dc draw-line (- (/ (+ cx1 cx2) 2) 12) (+ (/ (+ cy1 cy2) 2) 12) (+ (/ (+ cx1 cx2) 2) 12) (- (/ (+ cy1 cy2) 2) 12))) #f) ; Fix things (send dc set-pen "black" 1 'solid) (send dc set-brush "black" 'transparent) (send dc set-smoothing 'unsmoothed) )) ; Subclass of pasteboard, so we can draw the arrows. (define fwpboard% (class pasteboard% (init-field [next_model_fun null]) (define edges empty) (define/override (on-paint before? dc left top right bottom dx dy draw-caret) (if before? (begin (map (lambda (edge) (draw-edge dc edge)) ; Sort them so that the black ones are drawn on top of the gray ones (sort edges (lambda (a b) (send b is-active?)))) (send this invalidate-bitmap-cache left top (- right left) (- bottom top)) ) #f) ) ; If you press space (define/override (on-default-char event) (if (eq? (send event get-key-code) #\space) (begin (send this select-all) (send this clear) (set! edges empty) (next_model_fun) (send this refresh 0 0 1000 800 'no-caret #f) ) #f)) ; Double clicking brings up the subcomponents (define/override (on-double-click snip event) (if (and (is-a? snip entity-snip%) (not (null? (send snip get-subed)))) (if (send this get-snip-location (send snip get-subed)) (send this remove (send snip get-subed)) (begin (send this insert (send snip get-subed) (- (send event get-x) 150) (- (send event get-y) 150)) (send (send snip get-subed) set-flags (list)) (send this set-before (send snip get-subed) #f)) ) #f)) (define/public (set-edges! e) (set! edges e)) (super-new))) ; Subclass of image-snip, so we can have text below the images. (define entity-snip% (class image-snip% (init-field updatef [bitmap null] [kind null] [icons empty] [name ""] [subed null]) ; Draws the box around entities with policy decisions, and draws the icons for those decisions. (define/override (draw dc x y left top right bottom dx dy draw-caret) (let ([w (send bitmap get-width)] [h (send bitmap get-height)]) (if (not (empty? icons)) (begin (if (not (null? subed)) (send dc set-pen arrow-dark 2 'solid) (send dc set-pen arrow-light 1 'solid)) (send dc set-smoothing 'aligned) (send dc draw-rounded-rectangle (- x 20) (- y 10) 130 130 9) (send dc set-smoothing 'unsmoothed) (send dc set-pen "black" 1 'solid)) #f) (super draw dc x y left top right bottom dx dy draw-caret) (send dc draw-text name (- (+ x (/ w 2)) (/ (let-values ([(a b c d) (send dc get-text-extent name)]) a) 2)) (+ y h)) (draw-icons icons dc x y) ; Updates the modelgraph node positions (updatef x y) )) (define/private (draw-icons icons dc x y) (cond [(empty? icons) #f] [else (begin (send dc draw-bitmap (first icons) (- x 16) (- y 23)) (draw-icons (rest icons) dc (+ 34 x) y))])) (define/public (set-subed! ed) (set! subed ed)) (define/public (get-subed) subed) (super-make-object bitmap)))
false
562d07794eaf45efb9d64dea145af5750e0bcc99
565dab8666a65a092143e3c7b57681683bbf9837
/mini-hdl/rca-2-hdl.rkt
331cb034d2319f11ab4c1b0c2ecd6676b45d618f
[]
no_license
rfindler/lambdajam-2015-racket-pl-pl
51cd2159188b9c43a279ecc4fe7607b68597932c
4c9001dca9fb72c885d8cc1bef057ac8f56c24d0
refs/heads/master
2021-01-10T05:10:46.168336
2015-10-29T12:46:59
2015-10-29T17:41:27
45,050,373
6
2
null
2015-10-29T17:43:29
2015-10-27T15:27:24
Racket
UTF-8
Racket
false
false
173
rkt
rca-2-hdl.rkt
#lang mini-hdl inputs a1,a0 = 2; inputs b1,b0 = 1; s0 = a0 ⊕ b0; c0 = a0 ∧ b0; s1 = a1 ⊕ b1 ⊕ c0; c1 = (a1 ∧ b1) ∨ (c0 ∧ (a1 ⊕ b1)); showint(c1,s1,s0);
false
6d61aefead5f742ac240a615a78686f08fd30b5a
13b4b00dde31010c4a0bd6060d586172beea97a5
/turnstile/examples/rosette/query/debug.rkt
7d23e554432ac564d8c665fd5efecff2adc338e6
[]
no_license
michaelballantyne/macrotypes
137691348f15b6e663596dd7296e942c2febe82a
d113663b55d04995b05defb6254ca47594f9ec05
refs/heads/master
2021-07-14T11:06:53.567849
2018-02-08T19:17:07
2018-02-08T19:17:07
106,596,122
0
0
null
2020-10-04T19:18:55
2017-10-11T18:53:33
Racket
UTF-8
Racket
false
false
1,141
rkt
debug.rkt
#lang turnstile (require (prefix-in t/ro: (only-in "../rosette2.rkt" λ ann begin C→ Nothing Bool CSolution)) (prefix-in ro: rosette/query/debug)) (provide define/debug debug) (define-typed-syntax define/debug #:datum-literals (: -> →) [(_ x:id e) ≫ [⊢ [e ≫ e- ⇒ : τ]] #:with y (generate-temporary #'x) -------- [_ ≻ (begin- (define-syntax- x (make-rename-transformer (⊢ y : τ))) (ro:define/debug y e-))]] [(_ (f [x : ty] ... (~or → ->) ty_out) e ...+) ≫ ; [⊢ [e ≫ e- ⇒ : ty_e]] #:with f- (generate-temporary #'f) -------- [_ ≻ (begin- (define-syntax- f (make-rename-transformer (⊢ f- : (t/ro:C→ ty ... ty_out)))) (ro:define/debug f- (t/ro:λ ([x : ty] ...) (t/ro:ann (t/ro:begin e ...) : ty_out))))]]) (define-typed-syntax debug [(_ (solvable-pred ...+) e) ≫ [⊢ solvable-pred ≫ solvable-pred- ⇐ (t/ro:C→ t/ro:Nothing t/ro:Bool)] ... [⊢ [e ≫ e- ⇒ : τ]] -------- [⊢ [_ ≫ (ro:debug (solvable-pred- ...) e-) ⇒ : t/ro:CSolution]]])
true
59e5970ff87aea032741c3844bd9e338b083a6af
5e15f02eb421d6c70a8317873c2c9296a737ce55
/tools/main.rkt
e9763fc186e627ac92d3e6cb5203f3949fc2a220
[]
no_license
thoughtstem/ratchet
79c3fffb84e6728ab698063d2c15f1f77b59276e
6dcd99e9ad43e37feeae41838282ce3b94945ca1
refs/heads/master
2020-04-17T20:12:45.605556
2019-12-09T19:01:21
2019-12-09T19:01:21
166,895,719
1
0
null
2019-12-09T19:01:23
2019-01-21T23:40:33
Racket
UTF-8
Racket
false
false
2,404
rkt
main.rkt
#lang racket (require drracket/tool racket/class racket/gui/base racket/unit mrlib/switchable-button) (provide tool@) (define tool@ (unit (import drracket:tool^) (export drracket:tool-exports^) (define reverse-button-mixin (mixin (drracket:unit:frame<%>) () (super-new) (inherit get-button-panel get-definitions-text) (inherit register-toolbar-button) (let ((btn (new switchable-button% (label "Ratchet") (callback (λ (button) (launch-editor (get-definitions-text)))) (parent (get-button-panel)) (bitmap reverse-content-bitmap)))) (register-toolbar-button btn #:number 11) (send (get-button-panel) change-children (λ (l) (cons btn (remq btn l))))))) (define reverse-content-bitmap (let* ((bmp (make-bitmap 16 16)) (bdc (make-object bitmap-dc% bmp))) (send bdc erase) (send bdc set-smoothing 'smoothed) (send bdc set-pen "black" 1 'transparent) (send bdc set-brush "blue" 'solid) (send bdc draw-ellipse 2 2 8 8) (send bdc set-brush "orange" 'solid) (send bdc draw-ellipse 6 6 8 8) (send bdc set-bitmap #f) bmp)) (define (launch-editor text) (define s (send text get-text)) (define lang-line (string->symbol (string-replace (first (string-split s "\n")) "#lang " ""))) (with-handlers ([exn:fail? (lambda (e) (message-box "Unrecognized" (~a "Make sure you put a ratchet compatable language in your #lang line. And please make sure that language is installed on your computer. Error: " e)) )]) (define editor (dynamic-require `(submod ,lang-line ratchet) 'vis-lang)) (define launch (dynamic-require 'ratchet/launch 'launch)) (launch editor)) ) (define (phase1) (void)) (define (phase2) (void)) (drracket:get/extend:extend-unit-frame reverse-button-mixin) ))
false
d1a7995eee6d664a4af7600434de0dfb81696906
bdb6b8f31f1d35352b61428fa55fac39fb0e2b55
/sicp/ex1.46-skipped.rkt
5d0def870cb69a340c30e5f955fdb23d61ce5ee1
[]
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
30
rkt
ex1.46-skipped.rkt
#lang racket ;ex1.46 skipped
false
e11c2de1c1681428f459d0930822e0cf1cd612fe
c63a06955a246fb0b26485162c6d1bfeedfd95e2
/e-2.2.3-permutations.rkt
35eebea822605bdf5e6f27af873a74329bfc5377
[]
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
543
rkt
e-2.2.3-permutations.rkt
#lang racket (define (accumulate op initial sequence) (if (null? sequence) initial (op (car sequence) (accumulate op initial (cdr sequence))))) (define (flat-map proc seq) (accumulate append '() (map proc seq))) (define (remove item seq) (filter (lambda (x) (not (= x item))) seq)) (define (permutations s) (if (null? s) (list '()) (flat-map (lambda (x) (map (lambda (p) (cons x p)) (permutations (remove x s)))) s))) ;; (permutations (list 1 2 3))
false
385b854bf85be448eef2688e24192fa6d7d1139b
1397f4aad672004b32508f67066cb7812f8e2a14
/plot-lib/plot/private/plot3d/surface.rkt
1aa37991488bda153d80b41016eba366aabba5cd
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
racket/plot
2da8d9f8159f28d0a9f540012e43457d490d36da
b0da52632c0369058887439345eb90cbf8e99dae
refs/heads/master
2023-07-14T07:31:23.099585
2023-07-04T12:53:33
2023-07-04T12:53:33
27,409,837
39
29
NOASSERTION
2023-07-04T12:56:50
2014-12-02T01:50:35
Racket
UTF-8
Racket
false
false
3,597
rkt
surface.rkt
#lang typed/racket/base (require typed/racket/class racket/match racket/list (only-in typed/pict pict) plot/utils "../common/type-doc.rkt" "../common/utils.rkt") (provide (all-defined-out)) ;; =================================================================================================== ;; Surface plots of R R -> R functions (: surface3d-render-proc (-> 2D-Sampler Positive-Integer Plot-Color Plot-Brush-Style Plot-Color Nonnegative-Real Plot-Pen-Style Nonnegative-Real 3D-Render-Proc)) (define ((surface3d-render-proc f samples color style line-color line-width line-style alpha) area) (match-define (vector x-ivl y-ivl z-ivl) (send area get-bounds-rect)) (define num (animated-samples samples)) (define sample (f (vector x-ivl y-ivl) (vector num num))) (send area put-alpha alpha) (send area put-brush color style) (send area put-pen line-color line-width line-style) (for-2d-sample (xa xb ya yb z1 z2 z3 z4) sample (define vs (list (vector xa ya z1) (vector xb ya z2) (vector xb yb z3) (vector xa yb z4))) (send area put-polygon vs)) (void)) (:: surface3d (->* [(-> Real Real Real)] [(U #f Real) (U #f Real) (U #f Real) (U #f Real) #:z-min (U #f Real) #:z-max (U #f Real) #:samples Positive-Integer #:color Plot-Color #:style Plot-Brush-Style #:line-color Plot-Color #:line-width Nonnegative-Real #:line-style Plot-Pen-Style #:alpha Nonnegative-Real #:label (U String pict #f)] renderer3d)) (define (surface3d f [x-min #f] [x-max #f] [y-min #f] [y-max #f] #:z-min [z-min #f] #:z-max [z-max #f] #:samples [samples (plot3d-samples)] #:color [color (surface-color)] #:style [style (surface-style)] #:line-color [line-color (surface-line-color)] #:line-width [line-width (surface-line-width)] #:line-style [line-style (surface-line-style)] #:alpha [alpha (surface-alpha)] #:label [label #f]) (define fail/pos (make-raise-argument-error 'surface3d f x-min x-max y-min y-max)) (define fail/kw (make-raise-keyword-error 'surface3d)) (cond [(and x-min (not (rational? x-min))) (fail/pos "#f or rational" 1)] [(and x-max (not (rational? x-max))) (fail/pos "#f or rational" 2)] [(and y-min (not (rational? y-min))) (fail/pos "#f or rational" 3)] [(and y-max (not (rational? y-max))) (fail/pos "#f or rational" 4)] [(and z-min (not (rational? z-min))) (fail/kw "#f or rational" '#:z-min z-min)] [(and z-max (not (rational? z-max))) (fail/kw "#f or rational" '#:z-max z-max)] [(< samples 2) (fail/kw "integer >= 2" '#:samples samples)] [(or (> alpha 1) (not (rational? alpha))) (fail/kw "real in [0,1]" '#:alpha alpha)] [else (define x-ivl (ivl x-min x-max)) (define y-ivl (ivl y-min y-max)) (define z-ivl (ivl z-min z-max)) (define g (2d-function->sampler f (vector x-ivl y-ivl))) (renderer3d (vector x-ivl y-ivl z-ivl) (surface3d-bounds-fun g samples) default-ticks-fun (and label (λ (_) (rectangle-legend-entry label color style line-color line-width line-style))) (surface3d-render-proc g samples color style line-color line-width line-style alpha))]))
false
944bf6f44b5fa197f2d482548489053b8ae8df2e
7b85a7cefb9bd64e9032276844e12ebac7973a69
/unstable-lib/gui/prefs.rkt
24d179f2130c6d56a20112caec509d5d49503e46
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
racket/unstable
28ac91ca96a0434db99a097a6d4d2f0a1ca26f1e
99149bf1a6a82b2309cc04e363a87ed36972b64b
refs/heads/master
2021-03-12T21:56:07.687374
2019-10-24T01:04:57
2019-10-24T01:04:57
27,411,322
2
5
NOASSERTION
2020-06-25T19:01:26
2014-12-02T02:33:45
Racket
UTF-8
Racket
false
false
182
rkt
prefs.rkt
#lang racket/base ;; Re-exports from `framework/preferences`, for backwards compatibility. (require framework/preferences) (provide (rename-out [preferences:get/set pref:get/set]))
false
0ed9c90b58feb62932f7c3b31c5a7cb8408f6b9f
37858e0ed3bfe331ad7f7db424bd77bf372a7a59
/book/1ed/10_2-arithmetic/examples/why-gen-addero-must-use-alli.rkt
26a2c70aac54dc0f01d50bce29b0920e0a8e2713
[]
no_license
chansey97/the-reasoned-schemer
ecb6f6a128ff0ca078a45e097ddf320cd13e81bf
a6310920dde856c6c98fbecec702be0fbc4414a7
refs/heads/main
2023-05-13T16:23:07.738206
2021-06-02T22:24:51
2021-06-02T22:24:51
364,944,122
0
0
null
null
null
null
UTF-8
Racket
false
false
1,680
rkt
why-gen-addero-must-use-alli.rkt
#lang racket (require "../../libs/trs/mk.rkt") (require "../../07-arithmetic/full-addero.rkt") (require "../../07-arithmetic/poso.rkt") (require "../../07-arithmetic/gt1o.rkt") ;; If gen-addero use all instead of alli, then gen&testo will loop. ;; This proved that o+ will miss values! ;; Therefore it is wrong to use all in gen-addero ; 10.57 (define gen-addero (lambda (d n m r) (fresh (a b c e x y z) (== `(,a . ,x) n) (== `(,b . ,y) m) (poso y) (== `(,c . ,z) r) (poso z) (all (full-addero d a b c e) (addero e x y z))))) ; 7.118.1 (define addero (lambda (d n m r) (condi ((== 0 d) (== '() m) (== n r)) ((== 0 d) (== '() n) (== m r) (poso m)) ((== 1 d) (== '() m) (addero 0 n '(1) r)) ((== 1 d) (== '() n) (poso m) (addero 0 '(1) m r)) ((== '(1) n) (== '(1) m) (fresh (a c) (== `(,a ,c) r) (full-addero d 1 1 a c))) ((== '(1) n) (gen-addero d n m r)) ((== '(1) m) (>1o n) (>1o r) (addero d '(1) n r)) ((>1o n) (gen-addero d n m r)) (else fail)))) ; 7.128 (define +o (lambda (n m k) (addero 0 n m k))) (module+ main (require "../../libs/trs/mkextraforms.rkt") (require "../../libs/test-harness.rkt") (test-divergence "10.58" (run 1 (q) (gen&testo +o '(0 1) '(1 1) '(1 0 1)))) (test-divergence "10.62" (run* (q) (enumerateo +o q '(1 1 1)))) )
false
06c0396141ac7ad067809859ede9d1bd24087390
f05c1f175f69ec97ebeb367e153b211c4f3ca64e
/Racket/a9.rkt
738ceb0ee41c765da07d6a65665fb6a3bbd8004c
[]
no_license
peterbuiltthis/FP
2bea66def72a3e3592b3a57eccdbffdc440920bc
3bfdb457cbe58c1f5502e3ff232bb6ac45f89936
refs/heads/master
2020-12-20T04:20:21.684915
2020-01-24T07:55:26
2020-01-24T07:55:26
235,959,816
0
0
null
null
null
null
UTF-8
Racket
false
false
8,576
rkt
a9.rkt
#lang racket (require "parenthec.rkt") (require "c311/pmatch.rkt") ;; Step 11 -- Everything Works!!! (define-registers num c a k v env expr) (define-program-counter pc) (define-union una (empty-k jumpout^) (if-inner conseq^ alt^ env^ k^) (mult-inner k^ v^) (mult-outer rand2^ env^ k^) (sub-inner k^) (zero-inner k^) (return-inner vexp^ env^) (let-inner body^ env^ k^) (app-inner v^ k^) (app-outer rand^ env^ k^) ) (define-union exp (const n) (var v) (if test conseq alt) (mult rand1 rand2) (sub1 rand) (zero rand) (capture body) (return vexp kexp) (let vexp body) (lambda body) (app rator rand)) (define-label app-k (union-case k una ((empty-k jumpout^) (dismount-trampoline jumpout^)) ((if-inner conseq^ alt^ env^ k^) (if v (begin (set! expr conseq^) (set! env env^) (set! k k^) (set! pc value-of)) (begin (set! expr alt^) (set! env env^) (set! k k^) (set! pc value-of)))) ((mult-inner k^ v^) (begin (set! k k^) (set! v (* v^ v)) (set! pc app-k))) ((mult-outer rand2^ env^ k^) (begin (set! expr rand2^) (set! env env^) (set! k (una_mult-inner k^ v)) (set! pc value-of))) ((sub-inner k^) (begin (set! k k^) (set! v (- v 1)) (set! pc app-k))) ((zero-inner k^) (begin (set! k k^) (set! v (zero? v)) (set! pc app-k))) ((return-inner vexp^ env^) (begin (set! expr vexp^) (set! env env^) (set! k v) (set! pc value-of))) ((let-inner body^ env^ k^) (begin (set! expr body^) (set! env (envr_extend v env^)) (set! k k^) (set! pc value-of))) ((app-inner v^ k^) (begin (set! c v^) (set! a v) (set! k k^) (set! pc apply-closure))) ((app-outer rand^ env^ k^) (begin (set! expr rand^) (set! env env^) (set! k (una_app-inner v k^)) (set! pc value-of))) )) (define-label value-of (union-case expr exp [(const n) (begin (set! v n) (set! pc app-k))] [(var v) (begin (set! num v) (set! pc apply-env))] [(if test conseq alt) (begin (set! expr test) (set! k (una_if-inner conseq alt env k)) (set! pc value-of))] [(mult rand1 rand2) (begin (set! expr rand1) (set! k (una_mult-outer rand2 env k)) (set! pc value-of))] [(sub1 rand) (begin (set! expr rand) (set! k (una_sub-inner k)) (set! pc value-of))] [(zero rand) (begin (set! expr rand) (set! k (una_zero-inner k)) (set! pc value-of))] [(capture body) (begin (set! expr body) (set! env (envr_extend k env)) (set! pc value-of))] [(return vexp kexp) (begin (set! expr kexp) (set! k (una_return-inner vexp env)) (set! pc value-of))] [(let vexp body) (begin (set! expr vexp) (set! k (una_let-inner body env k)) (set! pc value-of))] [(lambda body) (begin (set! v (clos_closure body env)) (set! pc app-k))] [(app rator rand) (begin (set! expr rator) (set! k (una_app-outer rand env k)) (set! pc value-of))])) (define-union envr (empty) (extend arg env^)) (define-label apply-env (union-case env envr [(empty) (error 'env "unbound variable")] [(extend arg env^) (if (zero? num) (begin (set! v arg) (set! pc app-k)) (begin (set! env env^) (set! num (sub1 num)) (set! pc apply-env)))])) (define-union clos (closure code env)) (define-label apply-closure (union-case c clos [(closure code env^) (begin (set! expr code) (set! env (envr_extend a env^)) (set! pc value-of))])) (define-label main (begin (set! env (envr_empty)) (set! expr (exp_app (exp_app (exp_lambda (exp_lambda (exp_var 1))) (exp_const 5)) (exp_const 6))) (set! pc value-of) (mount-trampoline una_empty-k k pc) (pretty-print v) (set! env (envr_empty)) (set! expr (exp_app (exp_lambda (exp_app (exp_app (exp_var 0) (exp_var 0)) (exp_const 5))) (exp_lambda (exp_lambda (exp_if (exp_zero (exp_var 0)) (exp_const 1) (exp_mult (exp_var 0) (exp_app (exp_app (exp_var 1) (exp_var 1)) (exp_sub1 (exp_var 0))))))))) (set! pc value-of) (mount-trampoline una_empty-k k pc) (pretty-print v) (set! env (envr_empty)) (set! expr (exp_mult (exp_const 2) (exp_capture (exp_mult (exp_const 5) (exp_return (exp_mult (exp_const 2) (exp_const 6)) (exp_var 0)))))) (set! pc value-of) (mount-trampoline una_empty-k k pc) (pretty-print v) (set! env (envr_empty)) (set! expr (exp_let (exp_lambda (exp_lambda (exp_if (exp_zero (exp_var 0)) (exp_const 1) (exp_mult (exp_var 0) (exp_app (exp_app (exp_var 1) (exp_var 1)) (exp_sub1 (exp_var 0))))))) (exp_app (exp_app (exp_var 0) (exp_var 0)) (exp_const 5)))) (set! pc value-of) (mount-trampoline una_empty-k k pc) (pretty-print v))) (main)
false
1ab2bbeccc1c979ba76efb032c8c11deb7f595ae
791c282fc32d9b64edb87f566bdae25157adc4c1
/interp-cps.rkt
015f168e0bdbc6b34346a62e6dce1a4183bff878
[]
no_license
tenwz/MyPLZoo
217edec5147e9d807b4c4ab54bf6e36540c43259
60203b7be9dafde04065eadf5a17200fc360cf26
refs/heads/master
2023-03-16T08:25:05.205167
2018-04-19T03:54:49
2018-04-19T03:54:49
null
0
0
null
null
null
null
UTF-8
Racket
false
false
3,333
rkt
interp-cps.rkt
#lang racket (require rackunit) (require "share.rkt") ;; Expressions (struct NumE (n) #:transparent) (struct IdE (id) #:transparent) (struct PlusE (l r) #:transparent) (struct MultE (l r) #:transparent) (struct AppE (fun arg) #:transparent) (struct LamE (arg body) #:transparent) (struct CallccE (k body) #:transparent) ;; Values (struct NumV (n) #:transparent) (struct ClosureV (arg body env) #:transparent) (struct Cont (body)) ;; Environment (struct Binding (name val) #:transparent) (define lookup (make-lookup 'lookup Binding? Binding-name Binding-val)) (define ext-env cons) ;; Parser (define (parse s) (match s [(? number? x) (NumE x)] [(? symbol? x) (IdE x)] [`(+ ,l ,r) (PlusE (parse l) (parse r))] [`(* ,l ,r) (MultE (parse l) (parse r))] [`(λ (,var) ,body) (LamE var (parse body))] [`(call/cc (λ (,k) ,body)) (CallccE k (parse body))] [`(let/cc ,k ,body) (CallccE k (parse body))] [`(,fun ,arg) (AppE (parse fun) (parse arg))] [else (error 'parse "invalid expression")])) ;; Interpreter (define (primop op l r) (match* (l r) [((NumV lv) (NumV rv)) (match op ['+ (NumV (+ lv rv))] ['* (NumV (* lv rv))])] [(_ _) (error 'primop "invalid operator")])) (define (interp-cps exp env k) (match exp [(IdE x) (k (lookup x env))] [(NumE n) (k (NumV n))] [(PlusE l r) (interp-cps l env (λ (lv) (interp-cps r env (λ (rv) (k (primop '+ lv rv))))))] [(MultE l r) (interp-cps l env (λ (lv) (interp-cps r env (λ (rv) (k (primop '* lv rv))))))] [(LamE arg body) (k (ClosureV arg body env))] [(CallccE x body) (interp-cps body (ext-env (Binding x (Cont k)) env) k)] [(AppE fun arg) (interp-cps fun env (λ (funv) (cond [(ClosureV? funv) (interp-cps arg env (λ (argv) (interp-cps (ClosureV-body funv) (ext-env (Binding (ClosureV-arg funv) argv) (ClosureV-env funv)) k)))] [(Cont? funv) (interp-cps arg env (Cont-body funv))] [else (error 'cps "not a function or continuation")])))])) (define mt-env empty) (define mt-k (lambda (v) v)) (define (run prog) (define prog* (parse prog)) (interp-cps prog* mt-env mt-k)) ;; Tests (check-equal? (run '{+ 1 2}) (NumV 3)) (check-equal? (run '{* 2 3}) (NumV 6)) (check-equal? (run '{{λ {x} {+ x x}} 3}) (NumV 6)) (check-equal? (run '{+ 1 {let/cc k1 {+ 2 {+ 3 {let/cc k2 {+ 4 {k1 5}}}}}}}) (NumV 6)) (check-equal? (run '{+ 1 {let/cc k1 {+ 2 {+ 3 {let/cc k2 {+ 4 {k2 5}}}}}}}) (NumV 11)) (check-equal? (run '{+ 1 {call/cc {λ {k1} {+ 2 {+ 3 {k1 4}}}}}}) (NumV 5))
false
6ddca574951fd1fd83f480a86bded3a12b77bbd0
1a328ee76c68df01ce7202c36cfa5b2be8635f19
/private/grid/grid.rkt
73378e2f06b53f16b0d8c83945c2ced91805134c
[ "MIT" ]
permissive
alan-turing-institute/nocell-prototype
588ba4c5d1c75bedbe263d5c41383d2cf2c78ff3
f7cf876611b3bd262c568aff6a5e3401b15fb4a7
refs/heads/master
2023-07-15T17:33:16.912043
2021-09-03T14:37:46
2021-09-03T14:37:46
155,192,911
3
1
MIT
2020-09-15T10:53:44
2018-10-29T10:27:03
Racket
UTF-8
Racket
false
false
6,341
rkt
grid.rkt
#lang racket/base #| A little language for creating sheets. (Uses functions, not syntax.) Example: (sheet #:name "mysheet" (row 10 20 (cell)) ;; the last entry is a blank cell (row (cell 40) (cell 50 "a-cell") (cell `(+ 1 ,(ref "a-cell"))))) TODO - All references are converted to relative cell references and names are removed - Names aren't very consistent. We're using "id" in the context of a reference to mean a reference that should be turned into an A1-style reference, rather than a named reference. - How to name: constructors? converters? parsers? - Doesn't cope with rows of unequal length |# (require racket/contract math/array (only-in racket/list check-duplicates) (prefix-in s: "sheet.rkt")) (provide (contract-out ;; Create a cell. Use within (row ...) [cell (case-> (-> cell-spec/c) ; empty cell (cell-expr? . -> . cell-spec/c) ; cell with content (cell-expr? string? . -> . cell-spec/c))] ; cell with content and a name ;; Create a row of cells. Use within (sheet ..) [row (() (#:meta any/c) #:rest (listof cell-spec/c) . ->* . row-spec?)] ;; Create a sheet with an optional name [sheet ((row-spec?) (#:name string?) #:rest (listof row-spec?) . ->* . s:sheet?)] ;; Specify a reference to a named cell [ref (string? . -> . id-ref?)])) ;; --------------------------------------------------------------------------------------------------- (struct named-cell-spec (contents id) #:transparent) ; result of (cell v name) (struct anon-cell-spec (contents) #:transparent) ; result of (cell v) (struct row-spec (meta cells ids) #:transparent) ; result of (row ...) (struct id-ref (id) #:transparent) (define cell-spec/c (or/c s:atomic-value? named-cell-spec? anon-cell-spec? 'nothing)) (define (cell-expr? x) (cond [(s:atomic-value? x) #t] [(id-ref? x) #t] [(pair? x) (and (symbol? (car x)) (andmap cell-expr? (cdr x))) ] [else #f])) (define cell (case-lambda [() 'nothing] [(v) (anon-cell-spec v)] [(v id) (named-cell-spec v id)])) ;; ref : string? -> id-ref? (define (ref id) (id-ref id)) ;; row : (List-of <cell-spec>) -> <row-spec> ;; Traverse cells, producing a list of unparsed-cells and a list of extracted names with their indexes (define (row #:meta [meta null] . cells) (let-values ([(cols cells ids) (row-iter cells)]) (row-spec meta cells ids))) ;; row-iter : List-of cell -> [values max-index cells names] ;; Turn named cells into unnamed cells and extract the names (define (row-iter cell-specs) (for/fold ([col-index 0] [cells null] [ids null] #:result (values col-index (reverse cells) ids)) ([c cell-specs]) (let-values ([(anon-cell maybe-id) (parse-cell-spec c)]) (values (+ col-index 1) (cons anon-cell cells) (if maybe-id (cons (cons maybe-id col-index) ids) ids))))) ;; parse-cell-spec : <cell-spec> -> values anon-cell-spec? (or/c string? #f) ;; Parse an entry in a row, pulling out the name if there is one (define (parse-cell-spec v) (cond [(s:atomic-value? v) (values (anon-cell-spec v) #f)] [(anon-cell-spec? v) (values v #f)] [(named-cell-spec? v) (values (anon-cell-spec (named-cell-spec-contents v)) (named-cell-spec-id v))])) ;; Two-pass sheet parser. The first pass extracts the names; the second pass makes ;; a sheet? and fills in the cell references ;; There must be at least one row in the call to sheet. (define (sheet #:name [name "unnamed-sheet"] first-row-spec . rest-row-specs) (let-values ([(n-rows rows ids) (sheet-iter (cons first-row-spec rest-row-specs))]) (let ([maybe-dup (duplicated-id ids)]) (if maybe-dup (raise-argument-error 'sheet "Duplicate named reference" maybe-dup) (s:sheet (make-dereferenced-array rows ids) null ;; refs null ;; style-definitions null ;; column-definitions null ;; row-definitions (map row-spec-meta rows) ;; meta name))))) ;; duplicated-id : (list-of (name ref)) -> name (define (duplicated-id ids) (check-duplicates ids #:key car #:default #f)) ;; make-dereferenced-array : (list-of <rowspec>) (list-of (name ref)) -> array-of cell? (define (make-dereferenced-array rows ids) ;; convert all the anon-cells to cells (let ([cells (map (λ (r) (map (anon-cell/ids->cell ids) (row-spec-cells r))) rows)]) (list*->array cells s:cell?))) ;; anon-cell/ids->cell : (list-of (name ref)) -> anon-cell -> cell? ;; Turn something made by (cell ...) into an actual cell, replacing any named references with a ;; reference (define ((anon-cell/ids->cell ids) ac) (s:cell ((expr/ids->cell-expr ids) (anon-cell-spec-contents ac)) null null null)) ;; epxr/ids->cell-expr : -> cell-expr? (define ((expr/ids->cell-expr ids) expr) (cond [(s:atomic-value? expr) (s:cell-value-return expr)] [(id-ref? expr) (reference-to (id-ref-id expr) ids)] [(pair? expr) (s:cell-app (car expr) (map (expr/ids->cell-expr ids) (cdr expr)))])) ;; reference-to : string? (listof string? int int) -> cell-addr? ;; Look up the reference in ids, replace with address found therein (define (reference-to name ids) (unless (assoc name ids) (raise-user-error 'reference-to "Unknown name ~a (have ~a)" name ids)) (let ([index (cdr (assoc name ids))]) (s:cell-addr (car index) (cadr index) #t #t))) ;; sheet-iter : list-of row-spec -> values n-rows (list-of (list-of cell)) ids ;; Collate the names from the rows, adding a row index (define (sheet-iter row-specs) (for/fold ([row-index 0] [rows null] [ids null] #:result (values row-index (reverse rows) ids)) ([r row-specs]) (let ([refs (add-row-index row-index (row-spec-ids r))]) (values (+ row-index 1) (cons r rows) (append refs ids))))) ;; add-row-index : number? (list-of (name . col-index)) (define (add-row-index index ids) (map (λ (col-ref) (cons (car col-ref) (list index (cdr col-ref)))) ids))
false
cc2a2696d42ad1cb7eaf247f8198a1bddfd9394f
8b7986599eedd42030ef3782e4a2a9eba0596f4a
/biber/bibgen.rkt
2cd508d2bf08f38c07f5ea7f75282d580ee30a6c
[]
no_license
lihebi/biber
70ddf33ff98a73ef3fa274fe7265953200814c1c
18de3b5af039f1e95872694bec6d0af0c3ddb9ca
refs/heads/master
2020-05-03T19:33:43.491843
2020-04-25T17:40:00
2020-04-25T17:40:00
178,786,246
2
0
null
null
null
null
UTF-8
Racket
false
false
6,177
rkt
bibgen.rkt
#lang racket (require file/sha1 net/url sxml html-parsing rackunit json "utils.rkt" "acm.rkt" "open-review.rkt") (provide gen-bib arxiv-bib) (define (pmlr-bib volume booktitle year) ;; PMLR http://proceedings.mlr.press/ (define pmlr-prefix "http://proceedings.mlr.press/") (define xexp (url->xexp (string-append pmlr-prefix "v" (number->string volume)))) (string-join (for/list ([p ((sxpath "//div[@class='paper']") xexp)]) (define title (first ((sxpath "//p[@class='title']/text()") p))) (define authors (filter non-empty-string? (map (λ (s) (string-trim (string-replace s #rx"\n|," ""))) ((sxpath "//span[@class='authors']/text()") p)))) (define pdflink (second ((sxpath "//a/@href/text()") p))) (gen-single-bib (paper title authors pdflink booktitle year))) "\n")) (define (gen-icml year) (case year [(2019) (pmlr-bib 97 "ICML" 2019)])) (define (gen-jmlr year) (case year ;; FIXME this is ICML ;; [(2018) (pmlr-bib 80 "JMLR" 2018)] [else (error "not supported")])) (define (gen-aistats year) (case year [(2019) (pmlr-bib 89 "AISTATS" 2019)])) (define (thecvf-bib suffix booktitle year) ;; http://openaccess.thecvf.com/CVPR2019.py (define thecvf-prefix "http://openaccess.thecvf.com/") (define suffix "CVPR2019.py") (define xexp (url->xexp (string-append thecvf-prefix suffix))) (define titles ((sxpath "//dt/a/text()") xexp)) (define dts ((sxpath "//dd") xexp)) (when (not (= (* (length titles) 2) (length dts))) (error (format "Elements not match: ~a titles, ~a dts" (length titles) (length dts)))) (define (get-papers titles dts) (if (empty? titles) '() (let* ([title (first titles)] [authors (map string-trim ((sxpath "//form/a/text()") (first dts)))] [pdflink (string-append thecvf-prefix (first ((sxpath "/a[text()='pdf']/@href/text()") (second dts))))] [p (paper title authors pdflink booktitle year)]) (cons p (get-papers (rest titles) (rest (rest dts))))))) (string-join (map gen-single-bib (get-papers titles dts)) "\n")) (define (gen-cvpr year) (case year [(2019) (thecvf-bib "CVPR2019.py" "CVPR" 2019)])) ;; https://arxiv.org/list/cs.AI/1905 ;; https://arxiv.org/list/cs.AI/1905?show=99999 ;; arXiv ;; I would probably organize the papers by month ;; I'm going to download only papers after 2018 ;; The naming: 2018-arXiv-XXX-YYY ;; The file naming: 2018-01-arXiv.bib (define (arxiv-bib cat year month) (define (arxiv-query-date year month) (string-append (~a (modulo year 100) #:width 2 #:pad-string "0" #:align 'right) (~a month #:width 2 #:pad-string "0" #:align 'right))) (check-equal? (arxiv-query-date 2019 7) "1907") (check-equal? (arxiv-query-date 1995 11) "9511") (check-equal? (arxiv-query-date 2000 2) "0002") (define url (format "https://arxiv.org/list/~a/~a?show=999999" cat (arxiv-query-date year month))) (println url) (define xexp (url->xexp url)) (define IDs (map (λ (s) (last (string-split s "/"))) ((sxpath "//dt/span/a[2]/@href/text()") xexp))) (define titles (map (λ (x) (string-join (filter non-empty-string? (map string-trim ((sxpath "//div/text()") (list '*TOP* x)))) "SHOULD_NOT_BE_HERE")) ((sxpath "//dd/div/div[contains(@class, 'list-title')]") xexp))) (define authors (map (λ (x) ((sxpath "//a/text()") x)) ((sxpath "//dd/div/div[contains(@class, 'list-authors')]") xexp))) (when (not (= (length IDs) (length titles) (length authors))) (error "ID title author numbers do not match")) (displayln (format "Total paper: ~a" (length IDs))) (define papers (for/list ([ID IDs] [title titles] [author authors]) (let ([pdflink (format "https://arxiv.org/pdf/~a.pdf" ID)]) (paper title author pdflink cat year)))) (string-join (map gen-single-bib papers) "\n")) (define (xexp-get-all-text x) (match x [(list '@ child ...) ""] ;; (& mdash) [(list '& child ...) ""] ;; this must be the last list pattern [(list name child ...) (string-join (map xexp-get-all-text child) "")] [s #:when (string? s) s] ;; fallback, probably the default error message is better [a (error "No matching")])) (define (acl-bib conf year) (define acl-prefix "https://aclanthology.info/events/") (define suffix (string-append (string-downcase conf) "-" (number->string year))) (define url (string-append acl-prefix suffix)) (define xexp (url->xexp url)) (define paper-xexps ((sxpath "//div[@id='n19-1']/p") xexp)) (let ([titles (map (λ (x) (string-join (map xexp-get-all-text ((sxpath "//span/strong/a") x)) "")) paper-xexps)] [authors (map (λ (x) ((sxpath "//span[2]/a/text()") x)) paper-xexps)] [pdflinks (map (λ (x) (first ((sxpath "//span[1]/a[1]/@href/text()") x))) paper-xexps)]) (define papers (for/list ([pdflink pdflinks] [title titles] [author authors]) (paper title author pdflink conf year))) (string-join (map gen-single-bib papers) "\n"))) (define (gen-naacl year) (case year [(2019) (acl-bib "NAACL" 2019)])) (define (gen-bib conf year) (or (acm-gen-bib conf year) (open-review-gen-bib conf year) (case conf [(icml) (gen-icml year)] [(jmlr) (gen-jmlr year)] [(aistats) (gen-aistats year)] [(cvpr) (gen-cvpr year)] [(naacl) (gen-naacl year)] [else (error "no gen-bib for the conf")])))
false
057e451cdac2888a82438f100b3aeccd3073d1b3
d4767b1235b6eb8c113fbc11d0a3384637fcccd2
/woodcalc/render.rkt
c2dd0729c9de9d028699b8b410558b02b90d0682
[]
no_license
tealeg/racket-scratch
250b23983d0d4bf4689028bae826a405715082e6
dbc0c6c95f434cd10c47da3c8ffd864ec1bf5bff
refs/heads/master
2023-01-27T17:42:56.113715
2023-01-12T13:28:51
2023-01-12T13:28:51
182,085,476
0
0
null
null
null
null
UTF-8
Racket
false
false
6,047
rkt
render.rkt
#lang racket/base (require racket/class) (require racket/draw) (require "block.rkt") (define (render-block dc x y width height colour) (send dc set-brush colour 'solid) (send dc draw-rectangle x y width height) (send dc set-font (make-font #:size 20)) (send dc draw-text (string-append (number->string x) "," (number->string y)) x y) ) (provide render-block) (struct point (x y z)) (define (iso-translate-point point offset-x offset-y) (values (+ (- (point-x point) (point-y point)) offset-x) (+ (point-z point) (/ (+ (point-x point) (point-y point)) 2.0) offset-y))) (define (render-path-isometric dc offset-x offset-y points) (define b-path (new dc-path%)) (let-values ([(x y) (iso-translate-point (car points) offset-x offset-y)]) (send b-path move-to x y) ) (for ([p (cdr points)]) (let-values ([(x y) (iso-translate-point p offset-x offset-y)]) (send b-path line-to x y) )) (send dc draw-path b-path) ) (define (render-block-isometric dc obj offset-x offset-y) (send dc set-brush (block-colour obj) 'solid) (render-path-isometric dc offset-x offset-y (list (point (block-x obj) (block-y obj) (block-z obj)) (point (+ (block-x obj) (block-width obj)) (block-y obj) (block-z obj)) (point (+ (block-x obj) (block-width obj)) (+ (block-y obj) (block-length obj)) (block-z obj)) (point (block-x obj) (+ (block-y obj) (block-length obj)) (block-z obj)) (point (block-x obj) (block-y obj) (block-z obj)) )) (render-path-isometric dc offset-x offset-y (list (point (block-x obj) (block-y obj) (+ (block-z obj) (block-height obj))) (point (+ (block-x obj) (block-width obj)) (block-y obj) (+ (block-height obj)(block-z obj))) (point (+ (block-x obj) (block-width obj)) (+ (block-y obj) (block-length obj)) (+ (block-height obj)(block-z obj))) (point (block-x obj) (+ (block-y obj) (block-length obj)) (+ (block-height obj) (block-z obj))) (point (block-x obj) (block-y obj) (+ (block-height obj)(block-z obj))) )) (render-path-isometric dc offset-x offset-y (list (point (block-x obj) (block-y obj) (block-z obj)) (point (block-x obj) (block-y obj) (+ (block-z obj) (block-height obj))) (point (block-x obj) (+ (block-y obj) (block-length obj)) (+ (block-z obj) (block-height obj))) (point (block-x obj) (+ (block-y obj) (block-length obj)) (block-z obj)) (point (block-x obj) (block-y obj) (block-z obj)) )) (render-path-isometric dc offset-x offset-y (list (point (block-x obj) (block-y obj) (block-z obj)) (point (block-x obj) (block-y obj) (+ (block-z obj) (block-height obj))) (point (+ (block-x obj) (block-width obj)) (block-y obj) (+ (block-z obj) (block-height obj))) (point (+ (block-x obj) (block-width obj)) (block-y obj) (block-z obj)) (point (block-x obj) (block-y obj) (block-z obj)) )) ) (define (render-top-down width height blocks filename) (define target (make-bitmap width height)) (define dc (new bitmap-dc% [bitmap target])) (for ([obj blocks]) (render-block dc (block-x obj) (block-y obj) (block-width obj) (block-length obj) (block-colour obj))) (send target save-file filename 'png)) (provide render-top-down) (define (render-from-left-side width height blocks filename) (define target (make-bitmap width height)) (define dc (new bitmap-dc% [bitmap target])) (for ([obj blocks]) (render-block dc (block-y obj) (- height (+ (block-z obj) (block-height obj))) (block-length obj) (block-height obj) (block-colour obj))) (send target save-file filename 'png)) (provide render-from-left-side) (define (render-isometric width height blocks filename) (define target (make-bitmap width height)) (define dc (new bitmap-dc% [bitmap target])) (for ([obj blocks]) (render-block-isometric dc obj (/ width 2.0) 0)) (send target save-file filename 'png) ) (provide render-isometric)
false
23a86dc71815172ee56f420d20ccbeddcf2f8188
aa042deec7b25c70ce450191eefb6fd66449e3a5
/anim.rkt
ca7d4c44eb5933091aff9c18c4a27d9954e07916
[ "Apache-2.0" ]
permissive
massung/r-cade
c140478be790707011988fe6fbcb47b417fa100d
0cce22885aad28234d3f6e1d88568cdc16daf3e6
refs/heads/main
2023-07-25T18:56:29.437854
2022-02-21T17:52:30
2022-02-21T17:52:30
236,192,472
283
15
NOASSERTION
2023-07-05T09:30:36
2020-01-25T16:01:49
Racket
UTF-8
Racket
false
false
638
rkt
anim.rkt
#lang racket #| Racket Arcade (r-cade) - a simple game engine Copyright (c) 2020 by Jeffrey Massung All rights reserved. |# (require csfml) ;; ---------------------------------------------------- (provide (all-defined-out)) ;; ---------------------------------------------------- (define (anim-frame sprites time #:fps [fps 8] #:loop [loop #t]) (let ([m (sequence-length sprites)]) (remainder (exact-floor (* time fps)) m))) ;; ---------------------------------------------------- (define (anim-sprite sprites time #:fps [fps 8] #:loop [loop #t]) (sequence-ref sprites (anim-frame sprites time #:fps fps #:loop loop)))
false
28e82564a129fb068fce0e0aaa772c5e836a6f26
799b5de27cebaa6eaa49ff982110d59bbd6c6693
/soft-contract/test/programs/safe/larceny/deriv.rkt
b89053c20533e96772858da320793901bcd8f25d
[ "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,036
rkt
deriv.rkt
#lang racket (define (deriv a) (cond ((not (pair? a)) (if (eq? a 'x) 1 0)) ((eq? (car a) '+) (cons '+ (map deriv (cdr a)))) ((eq? (car a) '-) (cons '- (map deriv (cdr a)))) ((eq? (car a) '*) (list '* a (cons '+ (map (lambda (a) (list '/ (deriv a) a)) (cdr a))))) ((eq? (car a) '/) (list '- (list '/ (deriv (cadr a)) (caddr a)) (list '/ (cadr a) (list '* (caddr a) (caddr a) (deriv (caddr a)))))) (else (add1 "should not reach here")))) (define expr/c (or/c (not/c pair?) (list/c (one-of/c '+ '- '* '/) (recursive-contract expr/c) (recursive-contract expr/c)))) (provide (contract-out [deriv (expr/c . -> . any/c)]))
false
3ad62267b953a06582613dc2a560145a060b18f3
49d98910cccef2fe5125f400fa4177dbdf599598
/advent-of-code-2021/solutions/day11/day11-alt.rkt
a915cc8a649d35809c67b185ed71359c9445d1da
[]
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
3,339
rkt
day11-alt.rkt
#lang racket ;; This versions threads both the number of flashes and the list of ;; octopi through the pipeline. (require threading "../../advent/advent.rkt") (struct octopus (coord energy flashed?)) (struct state (flashes octopi)) (define (part1 s) (flashes (iterate step s 100))) (define (part2 s) (repeat-until #:action (λ (s) (step (clear s))) #:stop? (λ (s) (= (flashes s) 100)) s)) (define (step s) (~> s reset increment-energy flash count-flashes)) (define (reset s) (octopi= s (for/list ([ o (state-octopi s) ]) (if (octopus-flashed? o) (reset-octo o) o)))) (define (increment-energy s) (octopi= s (map increment-octo (state-octopi s)))) (define (flash s) ;; Helper functions ------------------------------------------------------------------------- (define (flash-needed? octo) (and (> (octopus-energy octo) 9) (not (octopus-flashed? octo)))) (define (flash-one-octopus octo s) (define (neighbors-of coord) (map (curry + coord) '(-i 1 +i -1 1-i -1-i 1+i -1+i))) (define (mark-flashed o) (struct-copy octopus o [ flashed? #t ])) (let ([ adjacent (neighbors-of (octopus-coord octo)) ]) (for/list ([ o (state-octopi s) ]) (let ([ coord (octopus-coord o) ]) (cond [ (= coord (octopus-coord octo)) (mark-flashed o) ] [ (member coord adjacent) (increment-octo o) ] [ else o ]))))) ;; ------------------------------------------------------------------------------------------ (let ([ octo (findf flash-needed? (state-octopi s)) ]) (if octo (flash (octopi= s (flash-one-octopus octo s))) s))) (define (parse file-name) (define N 10) (define (->coord x y) (+ x (* y +i))) (let ([ octopi (for/list ([ line (file->lines file-name) ] [ y (range N) ] #:when #t [ c (string->list line) ] [ x (range N) ]) (octopus (->coord x y) (- (char->integer c) 48) #f)) ]) (state 0 octopi))) (define (count-flashes s) (flashes= s (+ (state-flashes s) (count octopus-flashed? (state-octopi s))))) (define (repeat-until #:action fun #:stop? stop? arg) (let loop ([ n 1 ][ arg arg ]) (let ([ new-arg (fun arg) ]) (if (stop? new-arg) n (loop (add1 n) new-arg))))) (define (clear s) (struct-copy state s [ flashes 0 ])) (define (flashes s) (state-flashes s)) (define (increment-octo o) (struct-copy octopus o [ energy (add1 (octopus-energy o)) ])) (define (reset-octo o) (struct-copy octopus o [ flashed? #f ][ energy 0 ])) (define (flashes= s n) (struct-copy state s [ flashes n ])) (define (octopi= s octopi) (struct-copy state s [ octopi octopi ])) ;; Tests -------------------------------------------------------------------------------------- (module+ test (require rackunit) (let ([ input (parse "day11.txt") ]) (check-equal? (part1 input) 1647) (check-equal? (part2 input) 348)))
false
b6a3a9ac08d44d71315690098f2f7ae5d1511997
01f1f5d15fcd3e29fb6086131963cd17fb4669d3
/src/spec/compute-style.rkt
954c57dc644f40268825ebc20db58edeb7a3bec6
[ "MIT" ]
permissive
uwplse/Cassius
1664e8c82c10bcc665901ea92ebf4a48ee28525e
60dad9e9b2b4de3b13451ce54cdc1bd55ca64824
refs/heads/master
2023-02-22T22:27:54.223521
2022-12-24T18:18:25
2022-12-24T18:18:25
29,879,625
88
1
MIT
2021-06-08T00:13:38
2015-01-26T20:18:28
Racket
UTF-8
Racket
false
false
9,620
rkt
compute-style.rkt
#lang racket (require "../common.rkt" "../smt.rkt" "css-properties.rkt" "../encode.rkt" "browser.rkt") (provide style-computation) ;; This file defines the translation from specified to computed ;; styles. The specified style happens after all the cascading and so ;; on occurs, but it differs from the specified style in three weird ;; cases where CSS wants "bad" but legal values not to participate in ;; inheritance. (define (prop-is-positive prop elt) (define type (slower (css-type prop))) `(and (=> (,(sformat "is-~a/px" type) (,(sformat "style.~a" prop) (specified-style ,elt))) (<= 0.0 (,(sformat "~a.px" type) (,(sformat "style.~a" prop) (specified-style ,elt))))) (=> (,(sformat "is-~a/em" type) (,(sformat "style.~a" prop) (specified-style ,elt))) (<= 0.0 (,(sformat "~a.em" type) (,(sformat "style.~a" prop) (specified-style ,elt))))) (=> (,(sformat "is-~a/%" type) (,(sformat "style.~a" prop) (specified-style ,elt))) (<= 0.0 (,(sformat "~a.%" type) (,(sformat "style.~a" prop) (specified-style ,elt))))))) (define simple-computed-properties ;; These are properties whose computed style is just directly their specified style (append '(border-top-style border-right-style border-bottom-style border-left-style) '(border-top-color border-right-color border-bottom-color border-left-color) '(text-align overflow-x overflow-y position color background-color) '(clear display box-sizing font-weight font-style font-family))) (define em-computed-properties ;; These are properties whose computed style must convert em values to pixels (append '(width min-width max-width) '(margin-top margin-right margin-bottom margin-left) '(padding-top padding-right padding-bottom padding-left) '(top bottom left right text-indent))) (define (prop-is-simple prop elt) `(= (,(sformat "style.~a" prop) (computed-style ,elt)) (ite (,(sformat "is-~a/inherit" (slower (css-type prop))) (,(sformat "style.~a" prop) (specified-style ,elt))) (ite (is-elt (pelt ,elt)) (,(sformat "style.~a" prop) (computed-style (pelt ,elt))) ,(dump-value (css-type prop) (css-default prop))) (,(sformat "style.~a" prop) (specified-style ,elt))))) (define (prop-has-em prop elt) `(= (,(sformat "style.~a" prop) (computed-style ,elt)) (ite (,(sformat "is-~a/inherit" (slower (css-type prop))) (,(sformat "style.~a" prop) (specified-style ,elt))) (ite (is-elt (pelt ,elt)) (,(sformat "style.~a" prop) (computed-style (pelt ,elt))) ,(dump-value (css-type prop) (css-default prop))) ,(em-to-px prop elt)))) (define (not-inherited prop elt) `(not (,(sformat "is-~a/inherit" (slower (css-type prop))) (,(sformat "style.~a" prop) (computed-style ,elt))))) (define positive-properties (append '(width min-width max-width height min-height max-height) '(padding-top padding-right padding-bottom padding-left) '(border-top-width border-right-width border-bottom-width border-left-width))) (define (em-to-px prop elt) (define type (slower (css-type prop))) `(ite (,(sformat "is-~a/em" type) (,(sformat "style.~a" prop) (specified-style ,elt))) (,(sformat "~a/px" type) (%of (* 100 (,(sformat "~a.em" type) (,(sformat "style.~a" prop) (specified-style ,elt)))) (font-size.px (style.font-size (computed-style ,elt))))) (,(sformat "style.~a" prop) (specified-style ,elt)))) (define-constraints (style-computation) (define-fun rem2px ((rem Real)) Real (%of rem (browser.fs.serif ,(the-browser)))) (define-fun compute-style ((elt Element)) Bool (and ;,@(map (curryr not-inherited 'elt) (css-properties)) ,@(map (curryr prop-is-simple 'elt) simple-computed-properties) ,@(map (curryr prop-has-em 'elt) em-computed-properties) ,@(map (curryr prop-is-positive 'elt) positive-properties) (is-font-size/px (style.font-size (computed-style elt))) (= (style.font-size (computed-style elt)) ,(smt-let* ([fs (style.font-size (specified-style elt))] [pfs (ite (is-elt (pelt elt)) (font-size.px (style.font-size (computed-style (pelt elt)))) (browser.fs.serif ,(the-browser)))] ;; "monospace" text in particular has a default font size of 12 or 13px! [pfs* (ite (= (style.font-family (specified-style elt)) ,(dump-value 'Font-Family "monospace")) (* pfs (/ (browser.fs.mono ,(the-browser)) (browser.fs.serif ,(the-browser)))) pfs)]) ,(smt-cond [(is-font-size/inherit fs) (font-size/px pfs*)] [(is-font-size/% fs) (font-size/px (%of (font-size.% fs) pfs*))] [(is-font-size/em fs) (font-size/px (%of (* 100 (font-size.em fs)) pfs*))] [else fs]))) (= (style.line-height (computed-style elt)) (ite (is-line-height/inherit (style.line-height (specified-style elt))) (ite (is-elt (pelt elt)) (style.line-height (computed-style (pelt elt))) line-height/normal) (ite (is-line-height/% (style.line-height (specified-style elt))) (line-height/px (%of (line-height.% (style.line-height (specified-style elt))) (font-size.px (style.font-size (computed-style elt))))) ,(em-to-px 'line-height 'elt)))) ;; CSS 2.1 § 10.5: height ;; TODO: Positioning case absent here (= (style.height (computed-style elt)) (let ([h ,(em-to-px 'height 'elt)] [h* (style.height (computed-style (pelt elt)))]) (ite (is-height/inherit h) (ite (is-elt (pelt elt)) h* height/auto) (ite (and (is-height/% h) (is-elt (pelt elt)) (is-height/auto h*) (not (is-position/absolute (style.position (computed-style elt)))) (not (is-position/fixed (style.position (computed-style elt))))) height/auto h)))) (= (style.min-height (computed-style elt)) (let ([mh ,(em-to-px 'min-height 'elt)] [h* (style.height (computed-style (pelt elt)))]) (ite (is-min-height/inherit mh) (ite (is-elt (pelt elt)) (style.min-height (computed-style (pelt elt))) (min-height/px 0)) (ite (and (is-min-height/% mh) (is-elt (pelt elt)) (is-height/auto h*) (not (is-position/absolute (style.position (computed-style elt)))) (not (is-position/fixed (style.position (computed-style elt))))) (min-height/px 0) mh)))) (= (style.max-height (computed-style elt)) (let ([mh ,(em-to-px 'max-height 'elt)] [h* (style.height (computed-style (pelt elt)))]) (ite (is-max-height/inherit mh) (ite (is-elt (pelt elt)) (style.max-height (computed-style (pelt elt))) max-height/none) (ite (and (is-max-height/% mh) (is-elt (pelt elt)) (is-height/auto h*) (not (is-position/absolute (style.position (computed-style elt)))) (not (is-position/fixed (style.position (computed-style elt))))) max-height/none mh)))) ;; CSS 2.1 § 9.7: relationship between `float` and `position` ;; NOTE: The standard is ambiguous / undefined, but this is what Firefox does. (= (style.float (computed-style elt)) (let ([pos (style.position (specified-style elt))]) (ite (or (is-position/absolute pos) (is-position/fixed pos)) float/none (ite (is-float/inherit (style.float (specified-style elt))) (ite (is-elt (pelt elt)) (style.float (computed-style (pelt elt))) float/none) (style.float (specified-style elt)))))) ;; CSS 2.1 § 8.5.3: border-style and border-width ,@(for/list ([dir '(top right bottom left)]) `(= (,(sformat "style.border-~a-width" dir) (computed-style elt)) (ite (or (is-border-style/none (,(sformat "style.border-~a-style" dir) (computed-style elt))) (is-border-style/hidden (,(sformat "style.border-~a-style" dir) (computed-style elt)))) (border/px 0.0) (ite (is-border/inherit (,(sformat "style.border-~a-width" dir) (specified-style elt))) (ite (is-elt (pelt elt)) (,(sformat "style.border-~a-width" dir) (computed-style (pelt elt))) (border/px 0.0)) ,(em-to-px (sformat "border-~a-width" dir) 'elt)))))))) (module+ test (require rackunit) (check equal? (sort (append simple-computed-properties em-computed-properties '(height min-height max-height float border-top-width border-right-width border-bottom-width border-left-width font-size line-height)) string<? #:key symbol->string) (sort (css-properties) string<? #:key symbol->string)))
false
32ab2c9d2e4aea38c30248a7944adfda4d5488cb
6858cbebface7beec57e60b19621120da5020a48
/14/6/2/3.rkt
dddd9cf959dccca18bedb721a603602c70df86f6
[]
no_license
ponyatov/PLAI
a68b712d9ef85a283e35f9688068b392d3d51cb2
6bb25422c68c4c7717b6f0d3ceb026a520e7a0a2
refs/heads/master
2020-09-17T01:52:52.066085
2017-03-28T07:07:30
2017-03-28T07:07:30
66,084,244
2
0
null
null
null
null
UTF-8
Racket
false
false
39
rkt
3.rkt
> (g1 10) 10 > (g1 10) 11 > (g1 0) 12 >
false
857b976fb24e36d81ede5feb07a7a268ea07c2b9
f6bbf5befa45e753077cf8afc8f965db2d214898
/ASTBenchmarks/class-compiler/tests/examples/r1_21.rkt
f6279b4b5afbe35718357418686a4798b28cf26d
[]
no_license
iu-parfunc/gibbon
4e38f1d2d0526b30476dbebd794f929943f19f12
45f39ad0322cd7a31fe04922ad6bf38e6ac36ad6
refs/heads/main
2023-08-31T11:39:58.367737
2023-08-30T23:44:33
2023-08-30T23:44:38
58,642,617
139
23
null
2023-09-12T20:40:48
2016-05-12T13:10:41
C
UTF-8
Racket
false
false
29
rkt
r1_21.rkt
(let ([x 14]) (+ (+ x x) x))
false
ca68bb69092d5c550c3d3949b06d58af09a2fb8e
53543edaeff891dd1c2a1e53fc9a1727bb9c2328
/data/bad-commit-allowlist.rktd
46a729dfe496bc2121bb8f23f953a36cce8ec855
[ "MIT" ]
permissive
bennn/gtp-checkup
b836828c357eb5f9f2b0e39c34b44b46f2e97d22
18c69f980ea0e59eeea2edbba388d6fc7cc66a45
refs/heads/master
2023-05-28T16:26:42.676530
2023-05-25T03:06:49
2023-05-25T03:06:49
107,843,261
2
0
NOASSERTION
2019-04-25T17:12:26
2017-10-22T06:39:33
Racket
UTF-8
Racket
false
false
1,034
rktd
bad-commit-allowlist.rktd
;; bad-commit-allowlist ;; --- ;; This file contains a Racket list of commit hashes for commits to the ;; [racket/racket](https://github.com/racket/racket) repo. ;; ;; Each commit must have 2 properties: ;; 1. the `gtp-checkup` repo must have data that says the commit is ;; _significantly worse_ than a previous commit ;; 2. the issue that caused the _worsening_ must have been fixed by a subsequent ;; commit ;; ;; If a commit NOT in this list represents a problem, ;; then `raco setup gtp-checkup` reports the commit for a human to look at. ( "006ec1bfc993c4b59657882c8a07aae3d896c81d" "36c1f5724d04ed1b765cf7b612f44fe92b3961fd" "4ed5d7d98b8f9f901eb055ef686f8e98a5814a6a" "8d77b8403cbe9bdfa5133a71e10fd372895e52bd" "4e07c20afef9a5c5ba5736232a9a4076bc57b43d" ;; forth, failed on Albany, later commits OK "9effeef7aba1d685d189daf95c219c7fae45ccde" ;; https://github.com/racket/racket/issues/3127 "b7fcf4112ac2188f1305b092b8c9cf8f82b352ad" "d14940d22d2d448e3f54eb3495551af960b546ca" "093c5571bd7b6d3635b3520580da0cb6f6170d17" )
false
85d5947aad38e938bd5e4a22db517ee89bd736ac
0ef2678b48fd4ace9b2b941224a04283a287e7ed
/cover-lib/cover/private/file-utils.rkt
49994a4070d94ba1aa677bb0d398b6fc2020bfdd
[ "MIT" ]
permissive
florence/cover
7cdc72379f6afdf7c9e06a20f6581d19333c24d1
bc17e4e22d47b1da91ddaa5eafefe28f4675e85c
refs/heads/master
2022-05-31T21:40:14.776498
2020-03-10T13:59:25
2020-03-10T13:59:25
24,347,312
42
11
MIT
2022-05-15T12:22:00
2014-09-22T22:04:32
Racket
UTF-8
Racket
false
false
399
rkt
file-utils.rkt
#lang racket/base (provide ->relative ->absolute) (require racket/list racket/path) (define (->relative path) (build-path (find-relative-path (simple-form-path (current-directory)) (simple-form-path path)))) (define (->absolute path) (if (absolute-path? path) (path->string (simple-form-path path)) (path->string (simple-form-path (build-path (current-directory) path)))))
false
25f13cf7ba5a4b426afa7a5b06928bea1320d973
89b6239fa8080c36bc0d255b08292cd6c9048857
/lang/avatar-assets.rkt
6f1bda57d0f466f3db0df32c6b2c77563f375f12
[]
no_license
thoughtstem/game-engine-rpg
b2afe80d737ce844b0027f286f7c795b3552a233
d39160dd5dfc8ed80ca17e60b19035e16142b728
refs/heads/master
2021-07-06T01:26:40.178255
2020-08-10T21:25:20
2020-08-10T21:25:20
149,352,661
4
2
null
2019-08-08T00:36:26
2018-09-18T21:11:10
Racket
UTF-8
Racket
false
false
6,292
rkt
avatar-assets.rkt
#lang racket (provide witch-sprite darkelf-sprite lightelf-sprite madscientist-sprite monk-sprite pirate-sprite wizard-sprite mystery-sprite dragon-sprite caitsith-sprite darkknight-sprite kavi-sprite moderngirl-sprite moogle-sprite pirateboy-sprite pirategirl-sprite steampunkboy-sprite steampunkgirl-sprite firedog-sprite phoenix-sprite prince-sprite princess-sprite seaserpent-sprite forestranger-sprite fast-avatar-box ) (require 2htdp/image game-engine ts-kata-util/assets/main "./assets.rkt" ) ; ==== AVATAR SHEETS ===== ;This will both define and provide all sheets in /avatar-assets/" ;TODO: make this also provide sprites and parse rows and columns from filename (define-assets-from "avatar-assets") #|(define witch-sheet (bitmap "images/witch-sheet.png")) (define darkelf-sheet (bitmap "images/darkelf-sheet.png")) (define lightelf-sheet (bitmap "images/lightelf-sheet.png")) (define madscientist-sheet (bitmap "images/madscientist-sheet.png")) (define monk-sheet (bitmap "images/monk-sheet.png")) (define pirate-sheet (bitmap "images/pirate-sheet.png")) (define wizard-sheet (bitmap "images/wizard-sheet.png")) (define mystery-sheet (bitmap "images/mystery-sheet.png")) (define dragon-sheet (bitmap "images/dragon-sheet.png"))|# ; ==== AVATAR SPRITES ==== ; survival (define witch-sprite (sheet->sprite witch-sheet #:columns 4 #:rows 4 #:row-number 3 #:delay 4)) (define darkelf-sprite (sheet->sprite darkelf-sheet #:columns 4 #:rows 4 #:row-number 3 #:delay 4)) (define lightelf-sprite (sheet->sprite lightelf-sheet #:columns 4 #:rows 4 #:row-number 3 #:delay 4)) (define madscientist-sprite (sheet->sprite madscientist-sheet #:columns 4 #:rows 4 #:row-number 3 #:delay 4)) (define monk-sprite (sheet->sprite monk-sheet #:columns 4 #:rows 4 #:row-number 3 #:delay 4)) (define pirate-sprite (sheet->sprite pirate-sheet #:columns 4 #:rows 4 #:row-number 3 #:delay 4)) (define wizard-sprite (sheet->sprite wizard-sheet #:columns 4 #:rows 4 #:row-number 3 #:delay 4)) (define mystery-sprite (row->sprite mystery-sheet #:columns 4 #:delay 4)) (define dragon-sprite (sheet->sprite dragon-sheet #:columns 4 #:rows 4 #:row-number 3 #:delay 4)) ; battlearena (define caitsith-sprite (sheet->sprite caitsith-sheet #:columns 4 #:rows 4 #:row-number 3 #:delay 2)) (define darkknight-sprite (sheet->sprite darkknight-sheet #:columns 4 #:rows 4 #:row-number 3 #:delay 2)) (define kavi-sprite (sheet->sprite kavi-sheet #:columns 4 #:rows 4 #:row-number 3 #:delay 2)) (define moderngirl-sprite (sheet->sprite moderngirl-sheet #:columns 4 #:rows 4 #:row-number 3 #:delay 2)) (define moogle-sprite (sheet->sprite moogle-sheet #:columns 4 #:rows 4 #:row-number 3 #:delay 2)) (define pirateboy-sprite (sheet->sprite pirateboy-sheet #:columns 4 #:rows 4 #:row-number 3 #:delay 2)) (define pirategirl-sprite (sheet->sprite pirategirl-sheet #:columns 4 #:rows 4 #:row-number 3 #:delay 2)) (define steampunkboy-sprite (sheet->sprite steampunkboy-sheet #:columns 4 #:rows 4 #:row-number 3 #:delay 2)) (define steampunkgirl-sprite (sheet->sprite steampunkgirl-sheet #:columns 4 #:rows 4 #:row-number 3 #:delay 2)) ;adventure (define firedog-sprite (sheet->sprite firedog-sheet #:columns 4 #:rows 4 #:row-number 3 #:delay 5)) (define phoenix-sprite (sheet->sprite phoenix-sheet #:columns 4 #:rows 4 #:row-number 3 #:delay 5)) (define prince-sprite (sheet->sprite prince-sheet #:columns 4 #:rows 4 #:row-number 3 #:delay 5)) (define princess-sprite (sheet->sprite princess-sheet #:columns 4 #:rows 4 #:row-number 3 #:delay 5)) (define seaserpent-sprite (sheet->sprite seaserpent-sheet #:columns 4 #:rows 4 #:row-number 3 #:delay 5)) (define forestranger-sprite (sheet->sprite forestranger-sheet #:columns 4 #:rows 4 #:row-number 3 #:delay 5)) (define (fast-avatar-box e-or-s #:scale [scl 2]) (define avatar-sprite (cond [(entity? e-or-s) (get-component e-or-s animated-sprite?)] [(sprite? e-or-s) e-or-s] [else (error "That wasn't an entity or a sprite!")])) (define cropped-sprite (apply-image-function (compose (curry crop/align 'center 'center 54 54) (curry scale scl)) avatar-sprite)) (precompile! cropped-sprite) (append (list cropped-sprite) (bordered-box-sprite 60 60)))
false
2c93f8f633058172dbb957290323f479e01d6ef8
b6420ec5ea614f040eefc5e9c2205508f33bc666
/parendown-lib/lang/reader.rkt
1f5c72aed6199881f0ea96dc0c42e10f896f7e1d
[ "Apache-2.0" ]
permissive
sorawee/parendown-for-racket
e3a678a802ea4e6f0f170a6d69a7cf57b6a3dd1c
9c846654947f1605df9b318b202202d2ea3c8baf
refs/heads/main
2023-07-11T20:12:34.127346
2021-03-12T03:08:35
2021-03-12T03:08:35
394,690,158
0
0
Apache-2.0
2021-08-10T14:45:02
2021-08-10T14:45:01
null
UTF-8
Racket
false
false
7,830
rkt
reader.rkt
#lang racket/base ; parendown/lang/reader ; ; Parendown's weak opening paren functionality in the form of a ; language extension. ; Copyright 2017-2018 The Lathe 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 (only-in syntax/module-reader make-meta-reader lang-reader-module-paths) (only-in parendown parendown-readtable-handler)) (provide (rename-out [-read read] [-read-syntax read-syntax] [-get-info get-info])) (define (wrap-reader -read) (lambda args (parameterize ([current-readtable ; NOTE: There are many syntaxes we could have used for this, ; but we're using #/ as the syntax right now. We can't really ; use / like Cene does, because although the commented-out ; code implements that, it would cause annoyances whenever ; using Racket's many identifiers with / in their names, such ; as racket/base. ; ; If we do change this, we should also change the place we ; hardcode "#/" in the color lexer below. ; (make-readtable (current-readtable) #\/ 'dispatch-macro ; (make-readtable (current-readtable) #\/ 'terminating-macro parendown-readtable-handler)]) (apply -read args)))) ; Parendown's syntax highlighting recognizes the weak open paren as a ; `'parenthesis` token, and it passes all other processing through to ; the extended language's syntax highlighter. ; (define (wrap-color-lexer -get-info) ; TODO: Should we check for whether `-get-info` is false before ; calling it here? Other languages seem to do that, but the ; documented contract of `make-meta-reader` specifies that it will ; at least be a `procedure?`, not `(or/c #f procedure?)`. ; (define get-info-fallback-color-lexer (-get-info 'color-lexer #f)) (define default-fallback-color-lexer (if (procedure? get-info-fallback-color-lexer) get-info-fallback-color-lexer ; TODO: Why are we using `dynamic-require` here? Other languages ; do it. Is that so they can keep their package dependencies ; small and only depend on DrRacket-related things if the user ; is definitely already using DrRacket? ; ; TODO: Some languages even guard against the possibility that ; the packages they `dynamic-require` don't exist. Should we do ; that here? ; (dynamic-require 'syntax-color/racket-lexer 'racket-lexer))) (define normalized-fallback-color-lexer (if (procedure-arity-includes? default-fallback-color-lexer 3) default-fallback-color-lexer (lambda (in offset mode) (define-values (text sym paren start stop) (default-fallback-color-lexer in)) (define backup-distance 0) (define new-mode mode) (values text sym paren start stop backup-distance new-mode)))) (lambda (in offset mode) (define weak-open-paren "#/") (define weak-open-paren-length (string-length weak-open-paren)) (define peeked (peek-string weak-open-paren-length 0 in)) (if (and (string? peeked) (string=? weak-open-paren peeked)) (let () (define-values (line col pos) (port-next-location in)) (read-string weak-open-paren-length in) (define text weak-open-paren) (define sym 'parenthesis) (define paren #f) ; TODO: The documentation of `start-colorer` says the ; beginning and ending positions should be *relative* to the ; original `port-next-location` of "the input port passed to ; `get-token`" (called `in` here), but it raises an error if ; we use `(define start 0)`. Is that a documentation issue? ; Perhaps it should say "the input port passed to the first ; call to `get-token`." ; (define start pos) (define stop (+ start weak-open-paren-length)) (define backup-distance 0) ; TODO: Does it always make sense to preserve the mode like ; this? Maybe some color lexers would want their mode updated ; in a different way here (not that we can do anything about ; it). ; (define new-mode mode) (values text sym paren start stop backup-distance new-mode)) (normalized-fallback-color-lexer in offset mode)))) (define-values (-read -read-syntax -get-info) (make-meta-reader 'parendown "language path" lang-reader-module-paths wrap-reader wrap-reader (lambda (-get-info) (lambda (key default-value) (define (fallback) (-get-info key default-value)) (case key [(color-lexer) (wrap-color-lexer -get-info)] ; TODO: Consider providing behavior for the following other ; extension points: ; ; drracket:indentation ; - Determining the number of spaces to indent a new ; line by. For Parendown, it would be nice to indent ; however the base language indents, but counting the ; weak opening paren as an opening parenthesis (so ; that the new line ends up indented further than a ; preceding weak opening paren). ; ; drracket:keystrokes ; - Determining actions to take in response to ; keystrokes. For Parendown, it might be nice to make ; it so that when a weak opening paren is typed at the ; beginning of a line (with some amount of ; indentation), the line is reindented to be flush ; with a preceding normal or weak opening paren). ; ; configure-runtime ; - Initializing the Racket runtime for executing a ; Parendown-language module directly or interacting ; with it at a REPL. For Parendown, it might be nice ; to let the weak opening paren be used at the REPL. ; Then again, will that modify the current readtable ; in a way people don't expect when they run a module ; directly? Also, for this to work, we need to have ; Parendown attach a `'module-language` syntax ; property to the module's syntax somewhere. Is it ; possible to do that while also passing through the ; base language's `'module-language` declaration? ; ; drracket:submit-predicate ; - Determining whether a REPL input is complete. For ; Parendown, if we're supporting weak opening parens ; at the REPL, we should just make sure inputs with ; weak opening parens are treated as we expect. We ; might not need to extend this. ; ; module-language ; - Is this the right place to look for this key? It's a ; key to the `#:info` specification for ; `#lang syntax/module-reader`, but maybe that's not ; related. Other places in the documentation that talk ; about `'module-language` are referring to a syntax ; property. [else (fallback)])))))
false
7cfb2db0d5002fc4c6d9bcc2ca2888f98243e31a
b996d458a2d96643176465220596c8b747e43b65
/how-to-code-complex-data/problem-bank/abstraction/parameterization.rkt
190102634dc2b3ab02e4b59ffc9aad51efb814f1
[ "MIT" ]
permissive
codingram/courses
99286fb9550e65c6047ebd3e95eea3b5816da2e0
9ed3362f78a226911b71969768ba80fb1be07dea
refs/heads/master
2023-03-21T18:46:43.393303
2021-03-17T13:51:52
2021-03-17T13:51:52
null
0
0
null
null
null
null
UTF-8
Racket
false
false
4,976
rkt
parameterization.rkt
#lang htdp/isl ;; I wanted to try out lambda which is an alternate way on defining function. ;; The syntax is: (define name (lambda (variable variable ...) expression)) ;; A lambda cannot be used outside of this alternate syntax. (define circle-area (lambda (radius) (* pi (sqr radius)))) (circle-area 4) ; (* pi (sqr 4)) ;area of circle radius 4 (circle-area 6) ; (* pi (sqr 6)) ;area of circle radius 6 ;; ==================== ;; ListOfString -> Boolean ;; produce true if los includes "UBC" (check-expect (contains-ubc? empty) false) (check-expect (contains-ubc? (cons "McGill" empty)) false) (check-expect (contains-ubc? (cons "UBC" empty)) true) (check-expect (contains-ubc? (cons "McGill" (cons "UBC" empty))) true) ;<template from ListOfString> (define (contains-ubc? los) (contains? "UBC" los)) ;; ListOfString -> Boolean ;; produce true if los includes "McGill" (check-expect (contains-mcgill? empty) false) (check-expect (contains-mcgill? (cons "UBC" empty)) false) (check-expect (contains-mcgill? (cons "McGill" empty)) true) (check-expect (contains-mcgill? (cons "UBC" (cons "McGill" empty))) true) ;<template from ListOfString> (define (contains-mcgill? los) (contains? "McGill" los)) ;; String (listof String) -> Boolean ;; Produce true if str is in los (list of string), false otherwise (define (contains? str los) (cond [(empty? los) false] [else (if (string=? (first los) str) true (contains? str (rest los)))])) ;; Tests: (check-expect (contains? "UBC" empty) false) (check-expect (contains? "UBC" '("McGill")) false) (check-expect (contains? "UBC" '("UBC")) true) (check-expect (contains? "McGill" '("McGill" "UBC")) true) (check-expect (contains? "McGill" '("UBC" "McGill")) true) (check-expect (contains? "Random" '("UBC" "McGill")) false) ;; ==================== ;; ListOfNumber -> ListOfNumber ;; produce list of sqr of every number in lon (check-expect (squares empty) empty) (check-expect (squares (list 3 4)) (list 9 16)) ;(define (squares lon) empty) ;stub ;<template from ListOfNumber> (define (squares lon) (map2 sqr lon)) ;; ListOfNumber -> ListOfNumber ;; produce list of sqrt of every number in lon (check-expect (square-roots empty) empty) (check-expect (square-roots (list 9 16)) (list 3 4)) ;(define (square-roots lon) empty) ;stub ;<template from ListOfNumber> (define (square-roots lon) (map2 sqrt lon)) ;; Type parameters: The first argument to map2 is a function and the second argument is a list. ;; Now, we don't know what type of elements are present in the list but as we are going to pass ;; them in the given function, they can be denoted using type parameters. The type of the type ;; parameters is Any by default. What this signature says is whatever the type of elements is in ;; the given list, the same type is for the given function parameter and whatever type of element ;; the given function returns, the same type of elements are present in the return type for the ;; map2 function. ;; (X -> Y) (listof X) -> (listof Y) ;; Given a function 'func' and a list of numbers 'lon', produce a list of elements where each ;; element is the return value when the function 'func' is applied on every element in 'lon' (define (map2 func lon) (cond [(empty? lon) empty] [else (cons (func (first lon)) (map2 func (rest lon)))])) ;; Tests: (check-expect (map2 sqr empty) empty) (check-expect (map2 sqr '(2 3)) '(4 9)) (check-expect (map2 sqrt '(16 25)) '(4 5)) (check-expect (map2 abs '(2 -3)) '(2 3)) (check-expect (map2 string-length '("a" "ab" "abcd")) '(1 2 4)) ;; ==================== ;; ListOfNumber -> ListOfNumber ;; produce list with only positive? elements of lon (check-expect (positive-only empty) empty) (check-expect (positive-only (list 1 -2 3 -4)) (list 1 3)) ;(define (positive-only lon) empty) ;stub ;<template from ListOfNumber> (define (positive-only lon) (filter2 positive? lon)) ;; ListOfNumber -> ListOfNumber ;; produce list with only negative? elements of lon (check-expect (negative-only empty) empty) (check-expect (negative-only (list 1 -2 3 -4)) (list -2 -4)) ;(define (negative-only lon) empty) ;stub ;<template from ListOfNumber> (define (negative-only lon) (filter2 negative? lon)) ;; (X -> Boolean) (listof X) -> (listof X) ;; Given a function 'func' and a list of numbers 'lon', removes all the elements in the given ;; list 'lon' whose return value when passed in the function 'func' is false and produces the ;; list of remaining elements. (define (filter2 func? lon) (cond [(empty? lon) empty] [else (if (func? (first lon)) (cons (first lon) (filter2 func? (rest lon))) (filter2 func? (rest lon)))])) ;; Tests (check-expect (filter2 positive? empty) empty) (check-expect (filter2 positive? '(1 2)) '(1 2)) (check-expect (filter2 positive? '(1 -2 -3)) '(1)) (check-expect (filter2 negative? '(2 -3 -1)) '(-3 -1))
false
802f54be71aac963086566e6cecd11ee361f7b47
8a7023acadbb77f621b48446957cc07b851217b1
/R.rkt
84863ffd58e1841f378896e370dde59b93922455
[ "MIT" ]
permissive
jasonhemann/natlogic
36b0102cade3dbf5b06c75eb470ca8d423719146
2dad647f53b4e6f1052a02cb83208a6e7e0eba21
refs/heads/master
2021-03-12T23:18:32.598804
2015-09-23T23:36:35
2015-09-23T23:36:35
17,519,531
6
0
null
null
null
null
UTF-8
Racket
false
false
17,094
rkt
R.rkt
#lang racket (require "pmatch.rkt") (require cKanren) (require cKanren/tree-unify) (require cKanren/attributes) (require cKanren/neq) (provide (all-defined-out)) (define-syntax test-check (syntax-rules () ((_ title tested-expression expected-result) (begin (printf "Testing ~s\n" title) (let* ((expected expected-result) (produced tested-expression)) (or (equal? expected produced) (error 'test-check "Failed: ~a~%Expected: ~a~%Computed: ~a~%" 'tested-expression expected produced))))))) (define-attribute unary-atomo #:satisfied-when symbol? #:incompatible-attributes (number bin-atomo)) (define-attribute bin-atomo #:satisfied-when string? #:incompatible-attributes (number unary-atomo)) (define symbol-or-string? (lambda (s) (or (symbol? s) (string? s)))) (define-attribute un-literalo #:satisfied-when symbol-or-string? #:incompatible-attributes (number)) (define-constraint-interaction [(un-literalo x) (unary-atomo x)] => [(unary-atomo x)]) (define-constraint-interaction [(un-literalo x) (bin-atomo x)] => [(bin-atomo x)]) (test-check "un-literalo" (run 100 (q) (un-literalo q)) '((_.0 : (un-literalo _.0)))) (define negate-un-literalo (lambda (l o) (conde ((unary-atomo l) (== o `(not ,l))) ((== l `(not ,o)) (unary-atomo o))))) (define bin-literalo (lambda (l) (conde ((bin-atomo l)) ((fresh (a) (bin-atomo a) (== l `(not ,a))))))) (test-check "bin-literalo" (run 100 (q) (bin-literalo q)) '((_.0 : (bin-atomo _.0)) ((not _.0) : (bin-atomo _.0)))) (define negate-bin-literalo (lambda (l o) (conde ((bin-atomo l) (== `(not ,l) o)) ((bin-atomo o) (== l `(not ,o)))))) (test-check "negate-bin-literalo" (run 100 (q) (fresh (a b) (negate-bin-literalo a b) (== `(,a ,b) q))) '(((_.0 (not _.0)) : (bin-atomo _.0)) (((not _.0) _.0) : (bin-atomo _.0)))) (define set-termo (lambda (s) (conde ((un-literalo s)) ((fresh (p r) (conde ((== s `(exists ,p ,r)) (un-literalo p) (bin-literalo r)) ((== s `(forall ,p ,r)) (un-literalo p) (bin-literalo r)))))))) (test-check "set-termo" (run 100 (q) (set-termo q)) '((_.0 : (unary-atomo _.0)) ((not _.0) : (unary-atomo _.0)) ((exists _.0 _.1) : (bin-atomo _.1) (unary-atomo _.0)) ((forall _.0 _.1) : (bin-atomo _.1) (unary-atomo _.0)) ((exists (not _.0) _.1) : (bin-atomo _.1) (unary-atomo _.0)) ((forall (not _.0) _.1) : (bin-atomo _.1) (unary-atomo _.0)) ((exists _.0 (not _.1)) : (bin-atomo _.1) (unary-atomo _.0)) ((forall _.0 (not _.1)) : (bin-atomo _.1) (unary-atomo _.0)) ((exists (not _.0) (not _.1)) : (bin-atomo _.1) (unary-atomo _.0)) ((forall (not _.0) (not _.1)) : (bin-atomo _.1) (unary-atomo _.0)))) (define sentenceo (lambda (s) (conde ((fresh (p c) (== `(exists ,p ,c) s) (un-literalo p) (set-termo c))) ((fresh (p c) (== `(forall ,p ,c) s) (un-literalo p) (set-termo c)))))) (test-check "sentenceo" (run 100 (q) (sentenceo q)) '(((exists _.0 _.1) : (unary-atomo _.0 _.1)) ((forall _.0 _.1) : (unary-atomo _.0 _.1)) ((exists (not _.0) _.1) : (unary-atomo _.0 _.1)) ((forall (not _.0) _.1) : (unary-atomo _.0 _.1)) ((exists _.0 (not _.1)) : (unary-atomo _.0 _.1)) ((forall _.0 (not _.1)) : (unary-atomo _.0 _.1)) ((exists (not _.0) (not _.1)) : (unary-atomo _.0 _.1)) ((forall (not _.0) (not _.1)) : (unary-atomo _.0 _.1)) ((exists _.0 (exists _.1 _.2)) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((forall _.0 (exists _.1 _.2)) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((exists _.0 (forall _.1 _.2)) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((forall _.0 (forall _.1 _.2)) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((exists (not _.0) (exists _.1 _.2)) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((forall (not _.0) (exists _.1 _.2)) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((exists (not _.0) (forall _.1 _.2)) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((forall (not _.0) (forall _.1 _.2)) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((exists _.0 (exists (not _.1) _.2)) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((forall _.0 (exists (not _.1) _.2)) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((exists _.0 (forall (not _.1) _.2)) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((forall _.0 (forall (not _.1) _.2)) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((exists (not _.0) (exists (not _.1) _.2)) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((forall (not _.0) (exists (not _.1) _.2)) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((exists _.0 (exists _.1 (not _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((forall _.0 (exists _.1 (not _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((exists (not _.0) (forall (not _.1) _.2)) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((forall (not _.0) (forall (not _.1) _.2)) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((exists _.0 (forall _.1 (not _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((forall _.0 (forall _.1 (not _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((exists (not _.0) (exists _.1 (not _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((forall (not _.0) (exists _.1 (not _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((exists (not _.0) (forall _.1 (not _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((forall (not _.0) (forall _.1 (not _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((exists _.0 (exists (not _.1) (not _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((forall _.0 (exists (not _.1) (not _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((exists _.0 (forall (not _.1) (not _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((forall _.0 (forall (not _.1) (not _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((exists (not _.0) (exists (not _.1) (not _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((forall (not _.0) (exists (not _.1) (not _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((exists (not _.0) (forall (not _.1) (not _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) ((forall (not _.0) (forall (not _.1) (not _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)))) (define negate-quant (lambda (q q^) (conde ((== q 'forall) (== q^ 'exists)) ((== q 'exists) (== q^ 'forall))))) (test-check "negate-quant" (run 100 (q) (fresh (a b) (negate-quant a b) (== `(,a ,b) q))) '((forall exists) (exists forall))) (define negateo (lambda (s o) (fresh (qf1 p c) (== `(,qf1 ,p ,c) s) (un-literalo p) (conde ((un-literalo c) (fresh (qf1^ c^) (== `(,qf1^ ,p ,c^) c) (negate-quant qf1 qf1^) (negate-un-literalo c c^))) ((fresh (qf2 q r) (== `(,qf2 ,q ,r) c) (un-literalo q) (fresh (qf1^ qf2^ r^) (== `(,qf1^ ,p (,qf2^ ,q ,r^)) o) (negate-quant qf1 qf1^) (negate-quant qf2 qf2^) (negate-bin-literalo r r^)))))))) (test-check "negateo" (run 100 (q) (fresh (a b) (negateo a b) (== `(,a ,b) q))) '((((forall _.0 (forall _.1 _.2)) (exists _.0 (exists _.1 (not _.2)))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((forall (not _.0) (forall _.1 _.2)) (exists (not _.0) (exists _.1 (not _.2)))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((forall _.0 (forall (not _.1) _.2)) (exists _.0 (exists (not _.1) (not _.2)))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((forall (not _.0) (forall (not _.1) _.2)) (exists (not _.0) (exists (not _.1) (not _.2)))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((forall _.0 (forall _.1 (not _.2))) (exists _.0 (exists _.1 _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((forall (not _.0) (forall _.1 (not _.2))) (exists (not _.0) (exists _.1 _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((forall _.0 (forall (not _.1) (not _.2))) (exists _.0 (exists (not _.1) _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((forall (not _.0) (forall (not _.1) (not _.2))) (exists (not _.0) (exists (not _.1) _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((exists _.0 (forall _.1 _.2)) (forall _.0 (exists _.1 (not _.2)))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((exists (not _.0) (forall _.1 _.2)) (forall (not _.0) (exists _.1 (not _.2)))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((exists _.0 (forall (not _.1) _.2)) (forall _.0 (exists (not _.1) (not _.2)))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((exists (not _.0) (forall (not _.1) _.2)) (forall (not _.0) (exists (not _.1) (not _.2)))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((exists _.0 (forall _.1 (not _.2))) (forall _.0 (exists _.1 _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((exists (not _.0) (forall _.1 (not _.2))) (forall (not _.0) (exists _.1 _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((exists _.0 (forall (not _.1) (not _.2))) (forall _.0 (exists (not _.1) _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((exists (not _.0) (forall (not _.1) (not _.2))) (forall (not _.0) (exists (not _.1) _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((forall _.0 (exists _.1 _.2)) (exists _.0 (forall _.1 (not _.2)))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((forall (not _.0) (exists _.1 _.2)) (exists (not _.0) (forall _.1 (not _.2)))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((forall _.0 (exists (not _.1) _.2)) (exists _.0 (forall (not _.1) (not _.2)))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((forall (not _.0) (exists (not _.1) _.2)) (exists (not _.0) (forall (not _.1) (not _.2)))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((exists _.0 (exists _.1 _.2)) (forall _.0 (forall _.1 (not _.2)))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((exists (not _.0) (exists _.1 _.2)) (forall (not _.0) (forall _.1 (not _.2)))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((exists _.0 (exists (not _.1) _.2)) (forall _.0 (forall (not _.1) (not _.2)))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((exists (not _.0) (exists (not _.1) _.2)) (forall (not _.0) (forall (not _.1) (not _.2)))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((forall _.0 (exists _.1 (not _.2))) (exists _.0 (forall _.1 _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((forall (not _.0) (exists _.1 (not _.2))) (exists (not _.0) (forall _.1 _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((exists _.0 (exists _.1 (not _.2))) (forall _.0 (forall _.1 _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((exists (not _.0) (exists _.1 (not _.2))) (forall (not _.0) (forall _.1 _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((forall _.0 (exists (not _.1) (not _.2))) (exists _.0 (forall (not _.1) _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((exists _.0 (exists (not _.1) (not _.2))) (forall _.0 (forall (not _.1) _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((forall (not _.0) (exists (not _.1) (not _.2))) (exists (not _.0) (forall (not _.1) _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)) (((exists (not _.0) (exists (not _.1) (not _.2))) (forall (not _.0) (forall (not _.1) _.2))) : (bin-atomo _.2) (unary-atomo _.0 _.1)))) (define membero (lambda (x ls) (fresh (a d) (== `(,a . ,d) ls) (conde [(== a x)] [(=/= a x) (membero x d)])))) (test-check "membero" (run 8 (q) (fresh (a b) (membero a b) (== `(,a ,b) q))) '((_.0 (_.0 . _.1)) ((_.0 (_.1 _.0 . _.2)) : (=/= ((_.0 . _.1)))) ((_.0 (_.1 _.2 _.0 . _.3)) : (=/= ((_.0 . _.1)) ((_.0 . _.2)))) ((_.0 (_.1 _.2 _.3 _.0 . _.4)) : (=/= ((_.0 . _.1)) ((_.0 . _.2)) ((_.0 . _.3)))) ((_.0 (_.1 _.2 _.3 _.4 _.0 . _.5)) : (=/= ((_.0 . _.1)) ((_.0 . _.2)) ((_.0 . _.3)) ((_.0 . _.4)))) ((_.0 (_.1 _.2 _.3 _.4 _.5 _.0 . _.6)) : (=/= ((_.0 . _.1)) ((_.0 . _.2)) ((_.0 . _.3)) ((_.0 . _.4)) ((_.0 . _.5)))) ((_.0 (_.1 _.2 _.3 _.4 _.5 _.6 _.0 . _.7)) : (=/= ((_.0 . _.1)) ((_.0 . _.2)) ((_.0 . _.3)) ((_.0 . _.4)) ((_.0 . _.5)) ((_.0 . _.6)))) ((_.0 (_.1 _.2 _.3 _.4 _.5 _.6 _.7 _.0 . _.8)) : (=/= ((_.0 . _.1)) ((_.0 . _.2)) ((_.0 . _.3)) ((_.0 . _.4)) ((_.0 . _.5)) ((_.0 . _.6)) ((_.0 . _.7)))))) (define R (lambda (G phi proof) (conde ((membero phi G) (== `(Gamma : ,G => ,phi) proof)) ((fresh (p c) ;; D1 (== `(exists ,p ,c) phi) (unary-atomo p) (set-termo c) (fresh (q r1 r2) (== `((,r1 ,r2) D1=> ,phi) proof) (unary-atomo q) (R G `(exists ,p ,q) r1) (R G `(forall ,q ,c) r2)))) ((fresh (p c) ;; B (== `(forall ,p ,c) phi) (unary-atomo p) (set-termo c) (fresh (q r1 r2) (== `((,r1 ,r2) B=> ,phi) proof) (unary-atomo q) (R G `(forall ,p ,q) r1) (R G `(exists ,p ,c) r2)))) ((fresh (p c) ;; D2 (== `(exists ,p ,c) phi) (unary-atomo p) (set-termo c) (fresh (q r1 r2) (== `((,r1 ,r2) D2=> ,phi) proof) (unary-atomo q) (R G `(forall ,q ,p) r1) (R G `(exists ,q ,c) r2)))) ((fresh (p) ;; T (== `(forall ,p ,p) phi) (== phi proof) (un-literalo p))) ((fresh (p) ;; I (== `(exists ,p ,p) phi) (un-literalo p) (fresh (c r) (set-termo c) (== `((,r) I=> ,phi) proof) (R G `(exists ,p ,c) r)))) ((fresh (p nq) ;; D3 (== `(exists ,p ,nq) phi) (unary-atomo p) (fresh (q c nc r1 r2) (== `((,r1 ,r2) D3=> ,phi) proof) (negateo c nc) (un-literalo q) ;; these two lines could be better specialized. (negate-un-literalo q nq) (R G `(forall ,q ,nc) r1) (R G `(exists ,p ,c) r2)))) ((fresh (p c) ;; A (== `(forall ,p ,c) phi) (un-literalo p) (set-termo c) (fresh (np r) (negate-un-literalo p np) (== `((,r) A=> ,phi) proof) (R G `(forall ,p ,np) r)))) ((fresh (p) ;; II (== `(exists ,p ,p) phi) (unary-atomo p) (fresh (q r t) (unary-atomo q) (bin-literalo t) (== `((,r) II=> ,phi) proof) (R G `(exists ,q (exists ,p ,t)) r)))) ((fresh (p q t) ;; AA (== `(forall ,p (exists ,q ,t)) phi) (unary-atomo p) (unary-atomo q) (bin-literalo t) (fresh (q^ r1 r2) (== `((,r1 ,r2) AA=> ,phi) proof) (unary-atomo q^) (R G `(forall ,p (forall ,q^ ,t)) r1) (R G `(exists ,q ,q^) r2)))) ((fresh (p q t) ;; EE (== `(exists ,p (exists ,q ,t)) phi) (unary-atomo p) (unary-atomo q) (bin-literalo t) (fresh (q^ r1 r2) (== `((,r1 ,r2) EE=> ,phi) proof) (unary-atomo q^) (R G `(exists ,p (exists ,q^ ,t)) r1) (R G `(forall ,q^ ,q) r2)))) ((fresh (p q t) ;; AE (== `(forall ,p (exists ,q ,t)) phi) (unary-atomo p) (unary-atomo q) (bin-literalo t) (fresh (q^ r1 r2) (== `((,r1 ,r2) AE=> ,phi) proof) (unary-atomo q^) (R G `(forall ,p (exists ,q^ ,t)) r1) (R G `(forall ,q^ ,q) r2)))) ((sentenceo phi) ;; RAA (fresh (p np nphi r) (negate-un-literalo p np) (negateo phi nphi) (== `((,r) RAA=> ,phi) proof) (R `(,nphi . ,G) `(exists ,p ,np) r)))))) (run 30 (q) (fresh (b c p1 p2 p3) (R `(,p1 ,p2 ,p3) b c) (=/= b p1) (=/= b p2) (=/= b p3) (== `((,p1 ,p2 ,p3) ,b ,c) q))) ;; Commented out, but uses RAA ;; (define lots-of-ans ;; (run 2000 (q) ;; (fresh (b c p1 p2 p3) ;; (R `(,p1 ,p2 ,p3) b c) ;; (=/= b p1) ;; (=/= b p2) ;; (=/= b p3) ;; (== `((,p1 ,p2 ,p3) ,b ,c) q))))
true