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
ffd9e127e693290d78ce0620cc74beab8587d2e1
4f70e5516345a4aec6ad7a938f1988b162abad49
/resource-pool-lib/info.rkt
a6e153d5fa3009e831ddde764a75a83822bb4897
[ "BSD-3-Clause" ]
permissive
DavidAlphaFox/racket-resource-pool
f9efcd6ab66159f02b02966a9918c84ae752afd4
60838899b4b1f69165dc1b3f664eb30d90355e47
refs/heads/master
2023-04-13T23:01:41.894737
2021-05-03T12:58:56
2021-05-03T12:58:56
null
0
0
null
null
null
null
UTF-8
Racket
false
false
110
rkt
info.rkt
#lang info (define version "0.1") (define collection "data") (define deps '("base")) (define build-deps '())
false
2433ebba279ed1a879d873d9202613700ee5486f
a79dd3d1cbf0d690d7e81ff7f5915c7428200b07
/scribble.scrbl
1da8e5d52386e1a40e537760a04e61a03aa66eef
[]
no_license
winny-/ieeecs-racket-presentation
926733ce5888772ee19f427ee502ff00adbe947e
534c4070f4de176af3a653c15ff147b8889cacdf
refs/heads/master
2020-03-12T19:00:18.979182
2018-04-24T00:53:51
2018-04-24T00:53:51
130,774,955
1
0
null
null
null
null
UTF-8
Racket
false
false
136
scrbl
scribble.scrbl
#lang scribble/base @title{On the Cookie-Eating Habits of Mice} If you give a mouse a cookie, he's going to ask for a glass of milk.
false
9992daf9dad8786f4beabadf6a208dd0e5c720a8
1fa7d40041a7665b94b141894865b473986c7903
/plumb.rkt
9db759d97c94290c3a287e19b1e2e7215ea752f2
[]
no_license
jadudm/jupiter
95543ff8f57c239aa7ec88f1d2559831a8f8a721
b92447c859402ef2d2aa1d20ef7c10dfaf8c5a1b
refs/heads/master
2020-09-13T10:18:47.344102
2013-06-03T22:01:18
2013-06-03T22:01:18
null
0
0
null
null
null
null
UTF-8
Racket
false
false
16,185
rkt
plumb.rkt
#lang racket (require racket/cmdline net/url net/base64 net/dns json racket/gui mrlib/path-dialog ) (require "response-handling.rkt" "path-handling.rkt" "util.rkt" "debug.rkt" "upload.rkt" "session-management.rkt" "app-type.rkt" "sequential-ops.rkt" ) (define VERSION "1.0.0") (define verbose-mode (make-parameter false)) (define session-id (make-parameter false)) (define timeout (make-parameter 15)) (define first-compilation? (make-parameter true)) (define HOST (make-parameter false)) (define PORT (make-parameter 9000)) (define arduino-ports (make-parameter (list))) (define (json-encode h) (let ([os (open-output-string)]) (write-json h os) (get-output-string os))) (define (add-file file-path) (define result (make-parameter (get-response 'OK))) ;; Check the file exists (try/catch result success-response? (get-response 'ERROR-NO-FILE) (unless (file-exists? file-path) (error))) ;; Read the file (set/catch result success-response? (get-response 'ERROR-CANNOT-READ) (file->string file-path)) (set/catch result string? (get-response 'ERROR) (make-hash `((filename . ,(extract-filename file-path)) (code . ,(result)) (sessionid . ,(session-id)) (action . "add-file")))) (debug 'ADD-FILE "~a~n" (result)) ;; Encode the jsexpr (set/catch result hash? (get-response 'ERROR-JSON-ENCODE) (jsexpr->string (result))) ;; Base64 encode the JSON string (set/catch result string? (get-response 'ERROR-JSON-ENCODE) (base64-encode (string->bytes/utf-8 (result)))) ;; Do an HTTP GET (set/catch result bytes? (get-response 'ERROR-HTTP-GET) (get-pure-port (make-server-url (HOST) (PORT) "add-file" (result)))) ;; Process the result (set/catch result port? (get-response 'ERROR-PROCESS-RESPONSE) (process-response (result))) (result)) (define (compile-code id board main) (debug 'COMPILE "Compiling on HOST ~a PORT ~a~n" (HOST) (PORT)) (let* ([url (make-server-url (HOST) (PORT) "compile" id board (extract-filename main))] [resp-port (get-pure-port url)] [content (make-parameter (process-response resp-port))]) (close-input-port resp-port) (debug 'COMPILE "CONTENT RESPONSE~n*****~n~a~n*****~n" (filter-hash (content) 'hex)) (cond [(or (error-response? (content)) (eof-object? (content))) (content)] [else (hash-ref (content) 'hex)]) )) (define (show-response res) (printf "[~a] ~a~n" (hash-ref res 'code) (hash-ref res 'message))) (define (build board dir main) (parameterize ([current-directory dir]) (define p (new process% [context 'BUILD-BOARD])) (seq p [(initial? 'ERROR-START-SESSION) (start-session HOST PORT)] [(string? 'ERROR-STORE-SESSION-ID) (session-id (send p get)) NO-CHANGE] [(pass 'ERROR-LISTING-FILES) (filter (λ (f) (member (->sym (file-extension f)) '(occ inc module))) (filter file-exists? (directory-list)))] [(list? 'ERROR-ADDING-FILES) (for ([f (send p get)]) (add-file f)) NO-CHANGE] [(list? 'ERROR-COMPILING-CODE) (compile-code (session-id) board main)]) )) (define-syntax-rule (while test body ...) (let loop () (when test body ... (loop)))) (define (retrieve-board-config board) (define p (new process% [context 'RETRIEVE-BOARD-CONFIG])) (seq p [(initial? 'ERROR-GENERATING-URL) (make-server-url (HOST) (PORT) "board" board)] [(url? 'ERROR-CREATING-PORT) (get-pure-port (send p get))] [(port? 'ERROR-PARSING-RESPONSE) (process-response (send p get))] [(hash? 'ERROR-STORING-BOARD-CONFIG) (debug 'BOARD-CONFIG "~a" (filter-hash (send p get) 'hex)) (add-config (config) 'BOARD (send p get)) NO-CHANGE]) (send p get) ) ;tvm-avr-atmega328p-16000000-arduino.hex (define (retrieve-board-firmware board) ;; First, get the board config (retrieve-board-config board) ;; Now, fetch the firmware (let* ([url (make-server-url (HOST) (PORT) "firmware" (hash-ref (get-config 'BOARD) 'firmware))] [resp-port (get-pure-port url)] [content (make-parameter (process-response resp-port))]) (try/catch content hash? (get-response 'ERROR) (debug 'FIRMWARE "~a" (string-length (hash-ref (content) 'hex))) ) (content))) (define plumb (command-line #:program "plumb" #:multi [("-d" "--debug") flag "Enable debug flag." (enable-debug! (->sym flag))] #:once-each [("-v" "--version") "Display current plumb version and exit." (printf "plumb version ~a~n" VERSION) (exit)] [("--verbose") "Set maximum verbosity." (verbose-mode true)] [("--server") host "Set the server address." (HOST host) ] [("--start-session") "Start a session." (session-id (start-session HOST PORT)) (printf "~a~n" (session-id)) (exit)] [("-s" "--session-id") id "The session ID to operate under." (session-id id)] [("-a" "--add-file") filename "Add a single file." (show-response (add-file filename))] [("-c" "--compile") main "Compile <main-file>." (compile-code (session-id) main)] [("-t" "--timeout") sec "Set the timeout in seconds." (timeout (string->number sec))] [("--build") dir board main "Compile project <dir>, for <board>, using <main> as the start." (build dir board main)] [("--board-config") board "Fetch configuration data for a given board." (retrieve-board-config board)] [("--get-firmware") board "Retrieve firmware for board." (retrieve-board-firmware board)] #:args filenames (for-each (λ (f) (show-response (add-file f))) filenames) ;;(plumb-repl) )) (define (options serial.port) (printf "Options ~a~n" (list-intersperse (append (if (serial.port) '(f b r) '()) '(h a d p)) ","))) ;; I need a non-stateless thing. (define (plumb-repl) (define board.config (make-parameter false)) (define serial.port (make-parameter false)) (define code.hex (make-parameter false)) (define firmware.hex (make-parameter false)) (load-config (system-type)) ;; If no host is specified, use localhost ;; Otherwise, pull from the command line (if (equal? (HOST) false) (HOST "127.0.0.1") (add-config (config) 'SERVER-HOST (HOST))) (HOST (dns-get-address (dns-find-nameserver) (get-config 'SERVER-HOST))) (PORT (get-config 'SERVER-PORT)) ;; Needed for firmware (unless (directory-exists? (get-config 'TEMPDIR)) (make-directory (get-config 'TEMPDIR))) (define session-id (make-parameter (start-session HOST PORT))) ;; Check the file exists (try/catch session-id success-response? (get-response 'ERROR-NO-CONNECTION) (begin ;(printf "plumb repl session: ~a~n" (session-id)) (options serial.port) (printf "> ") (let main-loop ([cmd (read)]) ;; Input handler (case (->sym cmd) [(h help) (printf "HELP~n")] [(d debug) (let ([flag (read)]) (printf "Enabling debug flag: ~a~n" flag) (enable-debug! (->sym flag)))] [(a add-file) (printf "session-id: ~a~n" (session-id)) (let ([filename (read)]) (show-response (add-file (->string filename))))] [(b build) (let* ([board (read)] [dir (read)] [main-file (read)] ;; Need to pass the board type here -- fix the server [hex (build (->string board) (->string dir) (->string main-file))] [full-config (retrieve-board-config board)] ) (board.config full-config) (debug 'USER-CODE "Board Config: ~a~n" (filter-hash (board.config) 'hex)) (code.hex hex) (debug 'USER-CODE "LENGTH: ~a" (string-length (code.hex))) (avrdude-code (serial.port) (code.hex)) )] [(f firmware) (let* ([board (read)] [full-config (retrieve-board-firmware (->string board))]) (board.config full-config) (debug 'FIRMWARE "Board Config: ~a~n" (filter-hash (board.config) 'hex)) (firmware.hex (hash-ref (board.config) 'hex)) (avrdude-firmware (serial.port)))] [(p port) (newline) (for ([a (list-arduinos)] [n (length (list-arduinos))]) (printf "[~a] ~a~n" n (build-port a))) (newline) (printf "Select serial port~n[port] ") (let ([port (read)]) (serial.port (build-port (list-ref (list-arduinos) (string->number (->string port))))))] [(q quit) (printf "Exiting...~n") (sleep 1) (exit)]) (options serial.port) (printf "> ") (main-loop (read)) ))) ) (define main-file (make-parameter false)) (define (board-choice->board-type choice) (case choice [("Arduino Duemilanove") "arduino"] [else "arduino"])) (define (do-compilation win) (define board.config (make-parameter false)) (define serial.port (make-parameter (build-port (list-ref (arduino-ports) (send (hash-ref (win) 'serial-port) get-selection))))) (define code.hex (make-parameter false)) (define firmware.hex (make-parameter false)) (load-config (system-type)) (debug 'COMPILE "Serial Port: ~a" (serial.port)) ;; If no host is specified, use localhost ;; Otherwise, pull from the command line (HOST (send (hash-ref (win) 'server) get-value)) (add-config (config) 'SERVER-HOST (HOST)) (HOST (dns-get-address (dns-find-nameserver) (get-config 'SERVER-HOST))) (PORT (get-config 'SERVER-PORT)) ;; If this is the first compilation, upload the firmware (when (first-compilation?) (debug 'FIRMWARE "Uploading firmware on first compilation.") (first-compilation? false) (let* ([board (board-choice->board-type (hash-ref (win) 'board))] [full-config (retrieve-board-firmware (->string board))]) (board.config full-config) (debug 'FIRMWARE "Board Config: ~a~n" (filter-hash (board.config) 'hex)) (firmware.hex (hash-ref (board.config) 'hex)) (avrdude-firmware (serial.port)) )) ;; Needed for firmware (unless (directory-exists? (get-config 'TEMPDIR)) (make-directory (get-config 'TEMPDIR))) (session-id (start-session HOST PORT)) (debug 'COMPILE "Session ID: ~a~n" (session-id)) (debug 'COMPILE "Board: ~a~nDir: ~a~nName: ~a~n" (board-choice->board-type (hash-ref (win) 'board)) (extract-filedir (main-file)) (extract-filename (main-file))) (let* ([board (board-choice->board-type (hash-ref (win) 'board))] ;; Need to pass the board type here -- fix the server [hex (build board (extract-filedir (main-file)) (extract-filename (main-file)) )] [full-config (retrieve-board-config board)] ) (send (hash-ref ((hash-ref (win) 'compiler-response-window)) 'f) show true) (board.config full-config) (debug 'USER-CODE "Board Config: ~a~n" (filter-hash (board.config) 'hex)) (code.hex (hash-ref (board.config) 'hex)) (debug 'USER-CODE "LENGTH: ~a" (string-length (code.hex))) (avrdude-code (serial.port) (code.hex)) )) (define (compiler-response-window) (define win (make-parameter (make-hash))) (define f (new frame% [label "Messages"] [width 300] [height 400])) (define editor-canvas (new editor-canvas% (parent f) (label "Editor Canvas"))) (define text (new text%)) (send text insert "Response from server...") (send editor-canvas set-editor text) (let ([w (make-hash `((f . ,f) (editor-canvas . ,editor-canvas) (text . ,text)))]) (win w) win) ) (define (main-frame) (define win (make-parameter (make-hash))) (define f (new frame% [label "Plumb GUI"] [width 400] [height 200] )) (define server (new text-field% [parent f] [label "Server"] [init-value "ec2-54-226-131-120.compute-1.amazonaws.com"] [stretchable-width true] )) (define serial-port (new choice% [parent f] [label "Arduino Port"] [choices (let () (arduino-ports (map ->string (list-arduinos))) (arduino-ports))])) (define board (new choice% [parent f] [label "Board Type"] [choices (list "Arduino Duemilanove")])) (define hortz (new horizontal-panel% [parent f])) (define choose-file (new button% [parent hortz] [label "Choose Code"] [stretchable-width true] [callback (λ (b e) (let ([d (new path-dialog% [label "occam code chooser"] [message "Choose your main .occ file."] [parent f] [existing? true] [filters (list (list "occam files" "*.occ"))] [dir? false])]) (main-file (send d run))))] )) (define compile (new button% [parent hortz] [label "Compile"] [stretchable-width true] [callback (λ (b e) (do-compilation win))] )) (win (make-hash `((frame . ,f) (server . ,server) (serial-port . ,serial-port) (board . ,board) (choose-file . ,choose-file) (compile . ,compile) (compiler-response-window . ,(compiler-response-window)) ))) win) (when (not GUI) (plumb-repl)) (when GUI (enable-debug! 'ALL) (define window (main-frame)) (send (hash-ref (window) 'frame) show true))
true
204de51b65544ace9177db8553620309ec0477fb
304f4484c4cdf0086ebcb91b9735f0755c37c797
/big-stepper/deriv-parser.rkt
0eecdc7ea15374174e10976ab3d47e684b18f667
[ "BSD-2-Clause" ]
permissive
rmculpepper/prob-pl
22792da22636a40879ad0182aab707ef0439f53c
6c12d61ec0d2104e8e364afd9c4821fe1009e68f
refs/heads/master
2021-01-10T05:14:07.473291
2016-03-17T19:13:54
2016-03-17T19:13:54
50,863,303
0
0
null
null
null
null
UTF-8
Racket
false
false
4,624
rkt
deriv-parser.rkt
;; Copyright (c) 2016 Ryan Culpepper ;; Released under the terms of the 2-clause BSD license. ;; See the file COPYRIGHT for details. #lang racket/base (require (for-syntax racket/base) racket/promise syntax/stx parser-tools/lex macro-debugger/model/yacc-ext macro-debugger/model/yacc-interrupted "deriv.rkt" "deriv-tokens.rkt") (provide parse-derivation trace trace*) (define (deriv-error ok? name value start end) (if ok? (error 'derivation-parser "error on token #~a: <~s, ~s>" start name value) (error 'derivation-parser "bad token #~a" start))) ;; PARSER (define-production-splitter production/I values values) (define-syntax (productions/I stx) (syntax-case stx () [(productions/I def ...) #'(begin (production/I def) ...)])) (define parse-derivation (parser (options (start Start) (src-pos) (tokens basic-tokens) (end EOF) #| (debug "/tmp/DEBUG-PARSER.txt") |# (error deriv-error)) ;; tokens (skipped-token-values next next-group EOF IMPOSSIBLE weight eval-top syntax-error eval-expr return expr:variable expr:quote expr:let* expr:lambda expr:app expr:fix expr:S-sample expr:N-sample expr:observe-sample expr:fail expr:mem expr:if if-true if-false apply-function apply:primop apply:closure apply:fixed apply:memoized memo-miss ) ;; Entry point (productions (Start [(eval-top EE) $2] [(eval-top EE/Interrupted) $2])) (productions/I (EE [(eval-expr (? EE/Inner) return) (node:eval (car $1) (cdr $1) $2 $3 #f)]) (EEs (#:skipped null) [() null] [(next (? EE) (? EEs)) (cons $2 $3)]) (EE/Inner [(expr:variable !) (deriv:variable $2)] [(expr:quote) (deriv:quote)] [(expr:let* (? EEs) next-group (? EE)) (deriv:let* $2 $4)] [(expr:lambda) (deriv:lambda)] [(expr:app (? EE) next-group (? EEs) (? ApplyFunction)) (deriv:app $2 $4 $5)] [(expr:fix (? EE) !) (deriv:fix $2 $3)] [(expr:if (? EE) (? EE)) (deriv:if $2 $3)] [(expr:S-sample (? EE) ! DoSample) (deriv:S-sample $2 $3 $4)] [(expr:N-sample (? EE) ! DoSample) (deriv:N-sample $2 $3 $4)] [(expr:observe-sample (? EE) (? EE) ! weight) (deriv:observe-sample $2 $3 $4 $5)] [(expr:fail !) (deriv:fail $2)] [(expr:mem (? EE) !) (deriv:mem $2 $3)] [(!!) (deriv:error $1)]) (ApplyFunction [(apply-function (? ApplyFunction/Inner) return) (node:apply (car $1) (cdr $1) $2 $3)]) (ApplyFunction/Inner [(apply:primop !) (apply:primop $2)] [(apply:closure ! (? EE)) (apply:closure $2 $3)] [(apply:fixed (? ApplyFunction) (? ApplyFunction)) (apply:fixed $2 $3)] [(apply:memoized) (apply:mem-hit)] [(apply:memoized memo-miss (? ApplyFunction)) (apply:mem-miss $3)] [(!!) (apply:error $1)]) (DoSample [() #f]) ))) ;; ============================================================ ;; trace : Expr (Expr -> Value) -> Deriv (define (trace e eval) (let-values ([(result events derivp) (trace* e eval)]) (force derivp))) ;; trace* : Expr (Expr -> Value) -> Value/Exn (list-of Event) (promise-of Deriv) (define (trace* e eval) (let-values ([(result events) (trace/events e eval)]) (values result events (delay (parse-derivation (events->token-generator events)))))) ;; trace/events : Expr (Expr -> Value) -> Value/Exn (list-of Event) (define (trace/events e eval) (define events null) (define (add! x y) (set! events (cons (cons x y) events))) (parameterize ((current-emit-listener add!)) (let ([result (with-handlers ([(lambda (exn) #t) (lambda (exn) (add! 'syntax-error exn) exn)]) (eval e))]) (add! 'EOF #f) (values result (reverse events))))) ;; events->token-generator : (list-of Event) -> (-> Token) (define (events->token-generator events) (let ([pos 1]) (lambda () (define sig+val (car events)) ;; (eprintf " -- ~s\n" sig+val) (set! events (cdr events)) (let* ([sig (car sig+val)] [val (cdr sig+val)] [t (tokenize sig val pos)]) (when #f; (trace-verbose?) (printf "~s: ~s\n" pos (token-name (position-token-token t)))) (set! pos (add1 pos)) t))))
true
2d2b9b3c617320c4c8808b7a0ef36ff115ec0f39
0145705fe3e355bb32245dd2f81585884ada736a
/reactive/pulser-class.rkt
69c3b0b31b0f3287992eb0a448f8051fc85862cc
[ "MIT" ]
permissive
emina/wallingford
83a47e73385941c3c8b182a39d3ccee8599ec567
2e3d1b26b3eb98b57f7a6d34611678bc701586bd
refs/heads/master
2021-01-18T17:33:39.340949
2016-02-25T17:07:59
2016-02-25T17:07:59
52,309,756
2
0
null
2016-02-22T22:10:24
2016-02-22T22:10:24
null
UTF-8
Racket
false
false
453
rkt
pulser-class.rkt
#lang s-exp rosette ; pulsing circle example (require "reactive.rkt") (provide pulser%) ; define a pulser class as a subclass of reactive-thing% (define pulser% (class reactive-thing% (inherit seconds image) (super-new [init-image (make-circle)]) (always* (equal? (circle-radius (image)) (+ 60 (* 50 (sin (seconds)))))))) ; evaluate these lines to make a new pulser and a viewer on it: ; (wally-clear) ; (make-viewer (new pulser%))
false
4bb957df00e5e556f86e33907ce40a8dc7eb54ac
f5da4884c236512f9a945100234e213e51f980d3
/test/info.rkt
df22f4249c29193ca9e71a69a7ad9a5596763e89
[ "MIT" ]
permissive
uw-unsat/serval
87574f5ec62480463ae976468d4ae7a56e06fe9f
72adc4952a1e62330aea527214a26bd0c09cbd05
refs/heads/master
2022-05-12T23:19:48.558114
2022-01-20T18:53:26
2022-01-20T18:53:26
207,051,966
45
12
MIT
2022-03-21T14:05:50
2019-09-08T02:40:10
Racket
UTF-8
Racket
false
false
45
rkt
info.rkt
#lang info (define compile-omit-paths 'all)
false
177e359e7d0bded43b3d863670697814ce58eb68
3cb889e26a8e94782c637aa1126ad897ccc0d7a9
/SICP/chapter_3/76.rkt
70269c1d1765b24a8400449a74784f7d761f3d7b
[]
no_license
GHScan/DailyProjects
1d35fd5d69e574758d68980ac25b979ef2dc2b4d
52e0ca903ee4e89c825a14042ca502bb1b1d2e31
refs/heads/master
2021-04-22T06:43:42.374366
2020-06-15T17:04:59
2020-06-15T17:04:59
8,292,627
29
10
null
null
null
null
UTF-8
Racket
false
false
529
rkt
76.rkt
#lang racket (require "74.rkt") (define (smooth s last-value) (if (stream-empty? s) empty-stream (stream-cons (/ (+ (stream-first s) last-value) 2) (smooth (stream-rest s) (stream-first s)))) ) (define noise-data (stream 1 2 1.5 1 0.5 -0.1 -2 -3 0.02 -2 -0.5 0.2 3 4)) (define noise-zero-crossing (make-zero-crossings noise-data 0)) (define smoothed-noise-zero-crossing (make-zero-crossings (smooth noise-data 0) 0)) (stream->list noise-zero-crossing) (stream->list smoothed-noise-zero-crossing)
false
b6bf0b026f3d8cfa5997aa18d79b2d5e079f0737
da07a048f76b32381db9a55d9fda52adbc8f5dc7
/Sudoku/Sudoku_testcases.rkt
19b5a7fcc621f6e8e74209b81704b0443ce2308e
[]
no_license
nirajmahajan/SAT-Solver
26390cbae20c77ad6a55fc33a9d5c91c8ff93e58
fcb883cbb24619a3689c7d365ddc180d96a6b192
refs/heads/master
2020-05-29T18:04:47.772024
2019-05-29T20:54:34
2019-05-29T20:54:34
189,295,497
0
1
null
null
null
null
UTF-8
Racket
false
false
1,794
rkt
Sudoku_testcases.rkt
#lang racket (provide test1 test2 test3 test4) (define test1 '#(#(#f #f #f 2 6 #f 7 #f 1) #( 6 8 #f #f 7 #f #f 9 #f) #( 1 9 #f #f #f 4 5 #f #f) #( 8 2 #f 1 #f #f #f 4 #f) #(#f #f 4 6 #f 2 9 #f #f) #(#f 5 #f #f #f 3 #f 2 8) #(#f #f 9 3 #f #f #f 7 4) #(#f 4 #f #f 5 #f #f 3 6) #( 7 #f 3 #f 1 8 #f #f #f))) (define test2 '#(#( 9 #f 6 #f 7 #f 4 #f 3) #(#f #f #f 4 #f #f 2 #f #f) #(#f 7 #f #f 2 3 #f 1 #f) #( 5 #f #f #f #f #f 1 #f #f) #(#f 4 #f 2 #f 8 #f 6 #f) #(#f #f 3 #f #f #f #f #f 5) #(#f 3 #f 7 #f #f #f 5 #f) #(#f #f 7 #f #f 5 #f #f #f) #( 4 #f 5 #f 1 #f 7 #f 8))) (define test3 '#(#(#f 2 #f 5 #f 1 #f 9 #f) #( 8 #f #f 2 #f 3 #f #f 6) #(#f 3 #f #f 6 #f #f 7 #f) #(#f #f 1 #f #f #f 6 #f #f) #( 5 4 #f #f #f #f #f 1 9) #(#f #f 2 #f #f #f 7 #f #f) #(#f 9 #f #f 3 #f #f 8 #f) #( 2 #f #f 8 #f 4 #f #f 7) #(#f 1 #f 9 #f 7 #f 6 #f))) (define test4 '#(#(#f #f #f #f #f #f #f #f #f) #(#f #f #f #f #f #f #f #f #f) #(#f #f #f #f #f #f #f #f #f) #(#f #f #f #f #f #f #f #f #f) #(#f #f #f #f #f #f #f #f #f) #(#f 5 #f #f #f 3 #f 2 8) #(#f #f 9 3 #f #f #f 7 4) #(#f 4 #f #f 5 #f #f 3 6) #( 7 #f 3 #f 1 8 #f #f #f)))
false
8c1495ff09aafe050aab1b971e9c28508ccba859
477efc6ec5e6b4727a1b4f6bfb85ac2323bed818
/components/on-mouse.rkt
2bfa6d91d43bbc03dcb7d90c4bc8bf3f060e90bb
[]
no_license
emg110/game-engine
f4049fa2c3c05b9ff68e1c16849d2fc35aa57160
98c4b9e9b8c071818e564ef7efb55465cff487a8
refs/heads/master
2022-12-06T08:56:56.264781
2020-08-10T21:26:04
2020-08-10T21:26:04
null
0
0
null
null
null
null
UTF-8
Racket
false
false
1,322
rkt
on-mouse.rkt
#lang racket (require "../game-entities.rkt") (provide (except-out (struct-out on-mouse) on-mouse) (rename-out (make-on-mouse on-mouse)) (except-out (struct-out on-mouse-hold) on-mouse-hold) (rename-out (make-on-mouse-hold on-mouse-hold)) (rename-out (on-mouse struct-on-mouse) (on-mouse-rule struct-on-mouse-rule) (on-mouse-f struct-on-mouse-f)) get-on-mouse-button) (component on-mouse (button rule f)) (define (make-on-mouse button #:rule [rule (lambda (g e) #t)] f) (new-on-mouse button rule f)) (define (update-on-mouse g e c) (if (and (mouse-button-change-down? (on-mouse-button c) g) ((on-mouse-rule c) g e)) ((on-mouse-f c) g e) e)) (new-component on-mouse? update-on-mouse) ; ==== on-mouse-hold ==== (component on-mouse-hold (button rule f)) (define (make-on-mouse-hold button #:rule [rule (lambda (g e) #t)] f) (new-on-mouse-hold button rule f)) (define (update-on-mouse-hold g e c) (if (and (mouse-button-down? (on-mouse-hold-button c) g) ((on-mouse-hold-rule c) g e)) ((on-mouse-hold-f c) g e) e)) (new-component on-mouse-hold? update-on-mouse-hold) (define (get-on-mouse-button e) (on-mouse-button (get-component e on-mouse?)))
false
c1527e1e3096b487060cbc37b32ca3eeda7e5908
a70301d352dcc9987daf2bf12919aecd66defbd8
/res+edu+pro/pkg.rkt
f5b309ea1e2cdbe9fb0d948ece42c5099fc3f5ae
[]
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,317
rkt
pkg.rkt
#lang slideshow (require racket/draw racket/class "util.rkt" "logo.rkt") (provide pkg-icon) (define box-base (let ([p (new dc-path%)]) (send p move-to 80 80) (send p line-to 50 100) (send p line-to 20 80) (send p line-to 20 40) (send p line-to 50 60) (send p line-to 80 40) (send p close) p)) (define box-inside (let ([p (new dc-path%)]) (send p move-to 20 40) (send p line-to 50 60) (send p line-to 80 40) (send p line-to 50 25) (send p close) p)) (define box-arms (let ([p (new dc-path%)]) (send p move-to 20 40) (send p line-to 5 55) (send p line-to 35 75) (send p line-to 50 60) (send p close) (send p move-to 80 40) (send p line-to 95 55) (send p line-to 65 75) (send p line-to 50 60) (send p close) (send p move-to 20 40) (send p line-to 5 25) (send p line-to 35 10) (send p line-to 50 25) (send p close) (send p move-to 80 40) (send p line-to 95 25) (send p line-to 65 10) (send p line-to 50 25) (send p close) p)) (define (pkg-icon #:logo-inside? [logo-inside? #f]) (define base-color "peru") (define no-pen (make-pen #:style 'transparent)) (define middle-brush (make-brush #:color base-color)) (define bright-brush (make-brush #:color (scale-color base-color 1.2))) (define dim-brush (make-brush #:color (scale-color base-color 0.8))) (define bright-pen (make-pen #:color (scale-color base-color 1.2) #:width 1)) (define draw-logo (and logo-inside? (make-pict-drawer (scale logo 1/8)))) (dc (lambda (dc x y) (define old-p (send dc get-pen)) (define old-b (send dc get-brush)) (send dc set-pen no-pen) (send dc set-brush dim-brush) (send dc draw-path box-inside x y) (when logo-inside? (draw-logo dc (+ x 25) (+ y 35))) (send dc set-brush middle-brush) (send dc draw-path box-base x y) (send dc set-brush bright-brush) (send dc draw-path box-arms x y) (send dc set-pen bright-pen) (send dc draw-line (+ x 50) (+ y 61) (+ x 50) (+ y 99)) (send dc set-pen old-p) (send dc set-brush old-b)) 100 100)) (module+ main (slide (scale (pkg-icon #:logo-inside? #t) 2)))
false
bf33b37b57a4400dc2f84114e672516d10ca6423
729d656d1d13a02dd81dde6e82805c699aeb2ee9
/test/timestamp-expander-test.rkt
5d7fca1dbb46dfd17784b02eb80a66c175064361
[]
no_license
sreque/r5rs-timestamp-expander
0f70ff35623f6b6e4a583ba5d5a41f7a6b9be36a
3180c894b996bd0fe9a5220131f1f9feebce63bd
refs/heads/master
2016-09-03T07:32:30.872648
2012-05-08T01:19:11
2012-05-08T01:19:11
1,280,314
2
0
null
null
null
null
UTF-8
Racket
false
false
1,825
rkt
timestamp-expander-test.rkt
#lang scheme (require racket rackunit "../timestamp-expander.rkt") (let* ([syntax `(,(ts-syntax 'let 0) ([a 1] [b 2] [c (+ 3 4)]) (+ a b c))] [expected `((,(ts-syntax 'lambda 0) (a b c) (+ a b c)) 1 2 (+ 3 4))]) (check-equal? (rewrite-let-as-lambda syntax) expected)) (let* ([syntax `(,(ts-syntax 'letrec 0) ((even? (lambda (n) (if (zero? n) #t (odd? (- n 1))))) (odd? (lambda (n) (if (zero? n) #f (even? (- n 1)))))) (even? 88))]) (check-not-exn (lambda () (match (rewrite-letrec-as-lambda syntax) [(list (list (ts-syntax 'lambda 0) (list 'even? 'odd?) (list (list (ts-syntax 'lambda 0) (list tmp1 tmp2) (list 'set! 'even? tmp1) (list 'set! 'odd? tmp2) (list 'even? 88)) (list 'lambda (list 'n) (list 'if (list 'zero? 'n) #t (list 'odd? (list '- 'n 1)))) (list 'lambda (list 'n) (list 'if (list 'zero? 'n) #f (list 'even? (list '- 'n '1)))))) #f #f) #t])))) (let ([syntax `(,(ts-syntax 'let* 0) ([x 1] [y (+ x 1)]) (+ x y))]) (check-equal? (rewrite-let*-as-lambda syntax) `((,(ts-syntax 'lambda 0) (x) ((,(ts-syntax 'lambda 0) (y) (begin (+ x y))) (+ x 1))) 1))) (check-equal? (alpha-rename (parser-state 'a (hasheq))) 'a) (check-equal? (macro-expand 'a) 'a) (macro-expand '(or 1 2 3)) (macro-expand '(let ([v #t]) (or #f v))) (macro-expand '(let ([a 1] [b 2] [c 3]) (quote a b c)))
false
9360f95345c4cafd1d755f3fb59a97138d0a3951
c3a325ec6bcacd8665041ea454d2fdf081148446
/CS 330/xinterp/fwae.rkt
79779d75aa9d63169c0aff4ffae595082d24979a
[]
no_license
itcropper/BYUCS330
fd53e91672324c0217c14df94b9daa5e8009af72
9cbb311c3e3c032822014e7432548d8fe9a24f1c
refs/heads/master
2016-09-03T06:52:19.785761
2012-12-03T06:44:02
2012-12-03T06:44:02
6,977,866
0
1
null
null
null
null
UTF-8
Racket
false
false
8,165
rkt
fwae.rkt
#lang plai (require racket/trace) (print-only-errors) (define-type Binding [binding (name symbol?) (named-expr CFWAE?)]) (define-type CFWAE [num (n number?)] [binop (op procedure?) (lhs CFWAE?) (rhs CFWAE?)] [with (lob (listof Binding?)) (body CFWAE?)] [id (name symbol?)] [if0 (c CFWAE?) (t CFWAE?) (e CFWAE?)] [fun (args (listof symbol?)) (body CFWAE?)] [app (f CFWAE?) (args (listof CFWAE?))]) (define-type Env [mtEnv] [anEnv (name symbol?) (value CFWAE-Value?) (env Env?)]) (define-type CFWAE-Value [numV (n number?)] [closureV (params (listof symbol?)) (body CFWAE?) (env Env?)]) ;-------------------------------------------------- (define op-table (list (list '+ +) (list '- -) (list '* *) (list '/ /) ) ) (define other-ops (list (list 'fun fun) (list 'with with) (list 'if0 if0) ) ) (define (find-other-ops op) ;(printf "~e\n" op) (if (assoc op other-ops) (second (assoc op other-ops)) false) ) ;CONTRACT:(lookup-op op) → (or/c procedure? false/c) ; op : symbol? ;PURPOSE:extracts the definition ;of an operator or false ;DEFINITION (define (lookup-op op) (if(assoc op op-table) (second (assoc op op-table)) false) ) ;TESTS ;(test (lookup-op '+) +) ;(test (lookup-op '-) -) ;(test (lookup-op '*) *) ;(test (lookup-op '/) /) ;(test (lookup-op '$) false) ;(test (lookup-op '_) false) ;(test (lookup-op '++) false) ;(test (lookup-op 1) false) ;------------;------------;---------- #;(CFWAE = number | (list '+ CFWAE CFWAE) | (list '- CFWAE CFWAE) | (list '* CFWAE CFWAE) | (list '/ CFWAE CFWAE) | id | (list 'if0 CFWAE CFWAE CFWAE) | (list 'with (list (list id CFWAE) ...) CFWAE) | (list 'fun (list id ...) CFWAE)) ; | (list CWFAE CWFAE ... ;DEFINITION: (define (parse-binding l) (if (list? l) (if (= 2 (length l)) (binding (first l) (parse (second l))) (error "too few arguemnts in binding")) (error "Not a list of bindings") ) ) (define (validSymbol? sym) (not (member sym (list 'with 'if0 '+ '- '/ '* 'fun 'app))) ) (define (isValidIf? in) (if (and (list? in) (= 4 (length in)) (equal? 'if0 (first in))) #t #f ) ) ;[binding (name symbol?) (named-expr CFWAE?)]) (define (is-valid-binding in) (if (and (list? in) (= 2 (length in)) (symbol? (first in)) (validSymbol? (first in))) #t #f ) ) (define (isvalidOp op) (if (procedure? (lookup-op op)) #t #f ) ) ;(test (isvalidOp 'if0) #t) ;[with (lob (listof Binding?)) (body CFWAE?)] (define (isValidWith? in) (and (list? in) (= 3 (length in)) (equal? 'with (first in)) (list? (second in)) (andmap is-valid-binding (second in)) ) ) ;(andmap is-valid-binding '((x 4) (y 5) (with 6))) (define (create-list-of-bindings in) (if (empty? in) empty (cons (binding (first (first in)) (parse (second (first in))) ) (create-list-of-bindings (rest in))) ) ) ;(list 'fun (list id ...) CFWAE)) (define (isfun? wae) (and (list? wae) (= (length wae) 3) (equal? 'fun (first wae)) (list? (second wae)) (andmap symbol? (second wae)) (andmap validSymbol? (second wae)) ) ) ;(list CWFAE CWFAE ... (define (isapp? in) (and (list? in) (> (length in) 0) ) ) (define (parse cfwae) (cond [(number? cfwae) (num cfwae)] [(and (validSymbol? cfwae) (symbol? cfwae)) (id cfwae)] [(and (list? cfwae) ;binop? (= 3(length cfwae)) (isvalidOp (first cfwae))) (binop (lookup-op (first cfwae)) (parse (second cfwae)) (parse (third cfwae)))] ;(list 'if0 CFWAE CFWAE CFWAE) [(isValidIf? cfwae) (if0 (parse (second cfwae)) (parse (third cfwae)) (parse (fourth cfwae)))] [(isValidWith? cfwae) (with (create-list-of-bindings (second cfwae)) (parse (third cfwae)))] ;[fun (args (listof symbol?)) (body CFWAE?)] [(isfun? cfwae) (fun (second cfwae) (parse (third cfwae)))] ;[app (f CFWAE?) (args (listof CFWAE?))]) [(isapp? cfwae) (app (parse (first cfwae)) (map parse (rest cfwae)))] [(error "Invalid Syntax")] ) ) ;TESTS: ;(test/exn (parse '(- 2)) ;"wrong number of arguements") (test (parse '5) (num 5)) (test (parse '$) (id '$)) (test/exn (parse 'if0) "Invalid Syntax") (test/exn (parse 'with) "Invalid Syntax") (test/exn (parse 'fun) "Invalid Syntax") (test/exn (parse 'app) "Invalid Syntax") (test (parse '(* 1 2)) (binop * (num 1) (num 2))) (test/exn (parse '(- 1 2 3)) "Invalid Syntax") (test/exn (parse '(with [x 1] x)) "Invalid Syntax") (test (parse '5) (num 5)) (test/exn (parse '(/ 1 "fish"))"Invalid Syntax") (test/exn (parse +) "Invalid Syntax") (test/exn (parse true) "Invalid Syntax") (test (parse '(+ 1 2)) (binop + (num 1) (num 2))) (test/exn (parse '(+ 1 2 3)) "Invalid Syntax") (test (parse '(* 3 2)) (binop * (num 3) (num 2))) (test/exn (parse true) "Invalid Syntax") (test/exn (parse '(+)) "Invalid Syntax") (test/exn (parse '(-)) "Invalid Syntax") (test/exn (parse '(/)) "Invalid Syntax") (test/exn (parse '(*)) "Invalid Syntax") (test (parse '(+ 5 5)) (binop + (num 5) (num 5))) (test/exn (parse '(+ 5 5 5)) "Invalid Syntax") (test/exn (parse '(+ 5)) "Invalid Syntax") (test/exn (parse '(+ 1 "fish")) "Invalid Syntax") (test/exn (parse '(+ "fish" 1 )) "Invalid Syntax") (test (parse '(- 5 5)) (binop - (num 5) (num 5))) (test/exn (parse '(- 5 5 5)) "Invalid Syntax") (test/exn (parse '(- 5)) "Invalid Syntax") (test/exn (parse '(- 1 "fish")) "Invalid Syntax") (test/exn (parse '(- "fish" 1 )) "Invalid Syntax") (test (parse '(/ 5 5)) (binop / (num 5) (num 5))) (test/exn (parse '(/ 5 5 5)) "Invalid Syntax") (test/exn (parse '(/ 5)) "Invalid Syntax") (test/exn (parse '(/ 1 "fish")) "Invalid Syntax") (test/exn (parse '(/ "fish" 1 )) "Invalid Syntax") (test (parse '(* 5 5)) (binop * (num 5) (num 5))) (test/exn (parse '(* 5 5 5)) "Invalid Syntax") (test/exn (parse '(* 5)) "Invalid Syntax") (test/exn (parse '(* 1 "fish")) "Invalid Syntax") (test/exn (parse '(* "fish" 1 )) "Invalid Syntax") (test (parse '(with ((x 4)) (+ 3 x))) (with (list (binding 'x (num 4))) (binop + (num 3) (id 'x)))) (test (parse '(with () (+ x y))) (with empty (binop + (id 'x) (id 'y)))) (test (parse '(with ((x 4) (y 3) (z 2)) (+ x y))) (with (list (binding 'x (num 4)) (binding 'y (num 3)) (binding 'z (num 2))) (binop + (id 'x) (id 'y)))) (test/exn (parse '(with ({x 5}) ({x 4}) (+ 3 x))) "Invalid Syntax") (test/exn (parse '(with (+ 3 x))) "Invalid Syntax") (test/exn (parse '(with ({x 5}) ({x 4}) (+ 3 x y))) "Invalid Syntax") (test/exn (parse '(with ({if0 5}) (+ 3 x))) "Invalid Syntax") (test/exn (parse '(with ({with 5}) (+ 3 x))) "Invalid Syntax") (test/exn (parse '(with ({app 5}) (+ 3 x))) "Invalid Syntax") (test/exn (parse '(with ({fun 5}) (+ 3 x))) "Invalid Syntax") (test/exn (parse '(with ({x 5} {3 3}) (+ 3 x))) "Invalid Syntax") (test/exn (parse '(with)) "Invalid Syntax") (test (parse '(if0 5 5 5)) (if0 (num 5) (num 5) (num 5))) (test/exn (parse '(if0 "test" 2 3)) "Invalid Syntax") (test/exn (parse '(if0 2 "test" 3)) "Invalid Syntax") (test/exn (parse '(if0 1 2 "test")) "Invalid Syntax") (test (parse '( 5 5 5 5)) (app (num 5) (list (num 5) (num 5) (num 5)))) (test/exn (parse empty) "Invalid Syntax") (test/exn (parse empty) "Invalid Syntax")
false
f60a61028dca76b27459dd552cd73ce45ef9cc29
92bf59450f4308a4dca661bf754b63055a803547
/data.rkt
662a586cbeeff66842f02d5f879ae852d28a0c01
[]
no_license
noelwelsh/bonfire
6789be84f93cef3d68e2ac9d3c020f8872104291
290bfd934ae3f3d11e2de5bd5b0e2dceac108bae
refs/heads/master
2021-01-02T22:57:58.812326
2010-11-25T13:53:08
2010-11-25T13:53:08
1,111,796
0
0
null
null
null
null
UTF-8
Racket
false
false
585
rkt
data.rkt
#lang racket/base (require "sequence.rkt") (define (make-point x y) (vector x y)) (define (point-x p) (vector-ref p 0)) (define (point-y p) (vector-ref p 1)) ;; (sequenceof point) -> (vector point point) (define (bounding-box pts) (define xs (for/list ([p (in-sequence pts)]) (point-x p))) (define ys (for/list ([p (in-sequence pts)]) (point-y p))) (define min-x (apply min xs)) (define max-x (apply max xs)) (define min-y (apply min ys)) (define max-y (apply max ys)) (vector (make-point min-x min-y) (make-point max-x max-y))) (provide (all-defined-out))
false
9fa71c4e5a6d0850abdb03bc031326d6709ac31d
bf3128c6b1cf2a164077bcef1ffa23c26c440a0b
/except-in-quiet/except-in-quiet.rkt
2d4d1e77221ea4d2e76af112769531642aeacddd
[ "MIT" ]
permissive
bennn/syntax-parse-example
9e961fefc50c265991665d5de7ec1047dd445ed7
b1616936eafd97f952af050dc41cab25c50041e2
refs/heads/master
2022-09-21T15:43:20.335490
2022-09-06T00:17:37
2022-09-06T00:17:37
423,293,870
1
1
NOASSERTION
2021-11-01T00:38:01
2021-11-01T00:38:00
null
UTF-8
Racket
false
false
897
rkt
except-in-quiet.rkt
#lang racket/base (provide except-in-quiet) (require (for-syntax racket/base racket/require-transform racket/set syntax/parse)) (define-for-syntax (export-list->phase0-ids phase-dict) (define phase0-id-info* (cdr (or (assoc 0 phase-dict) (cons #f '())))) (map car phase0-id-info*)) (define-syntax except-in-quiet (make-require-transformer (syntax-parser [(_ modname:id exception-names:id ...) (define-values [provided-vals provided-macros] (module->exports (syntax-e #'modname))) (define exceptions (map syntax-e (attribute exception-names))) (define excluded (set-intersect exceptions (set-union (export-list->phase0-ids provided-vals) (export-list->phase0-ids provided-macros)))) (expand-import #`(except-in modname #,@excluded))])))
true
a9fea974ed9db8eace74c2cc5bad212fe666f41f
0d4287c46f85c3668a37bcb1278664d3b9a34a23
/陈乐天/Week2/homework2-06.rkt
a6ab9f85146288f3fab4f3552385b2a99e2fd830
[]
no_license
siriusmax/Racket-Helper
3e55f8a69bf005b56455ab386e2f1ce09611a273
bf85f38dd8d084db68265bb98d8c38bada6494ec
refs/heads/master
2021-04-06T02:37:14.261338
2017-12-20T04:05:51
2017-12-20T04:05:51
null
0
0
null
null
null
null
UTF-8
Racket
false
false
257
rkt
homework2-06.rkt
#lang racket (define (dowork num) (if (null? num) empty (append (dowork (cdr num)) (list (car num))))) (define (myloop) (let ((num (read))) (if (eq? num eof) (void) (begin (displayln (dowork num)) (myloop))))) (myloop)
false
08f895c0ed35fdfe164ca79145d94ecd82f29ccf
7b30caa6e3d6f31f4e180dda8d7f76a7870c9e59
/racket-code/racket/derp-core.rkt
ce7dc363612f2dbc33764a054a4d0ef8083daaa9
[]
no_license
plum-umd/parsing-with-derivatives
a0f40138678c73de8a950d698ca7efc96791a20b
41f1fb46a160d1ad4a21d8172128d7a00ad2b461
refs/heads/master
2021-01-16T18:03:22.792191
2015-02-26T18:22:43
2015-02-26T18:22:43
31,380,781
8
0
null
null
null
null
UTF-8
Racket
false
false
1,784
rkt
derp-core.rkt
(module derp-core racket (require "memoization.rkt") (require "fixed-points.rkt") (require "lazy-structs.rkt") (provide (all-defined-out)) ; Atomic parsers: (define-struct ∅ {}) ; empty set (define-struct ε {tree-set}) ; empty string (define-struct token {value?}) ; token class ; Compound parsers: (define-lazy-struct δ {lang}) (define-lazy-struct ∪ {this that}) (define-lazy-struct ∘ {left right}) (define-lazy-struct ★ {lang}) (define-lazy-struct → {lang reduce}) ; Derivative: (define/memoize (D c p) #:order ([p #:eq] [c #:equal]) (match p [(∅) (∅)] [(ε _) (∅)] [(δ _) (∅)] [(token p?) (cond [(p? c) (ε (set c))] [else (∅)])] [(∪ p1 p2) (∪ (D c p1) (D c p2))] [(★ p1) (∘ (D c p1) p)] [(→ p1 f) (→ (D c p1) f)] [(∘ p1 p2) (∪ (∘ (δ p1) (D c p2)) (∘ (D c p1) p2))])) ; Parsing null: (define/fix (parse-null p) #:bottom (set) (match p [(ε S) S] [(∅) (set)] [(δ p) (parse-null p)] [(token _) (set)] [(★ _) (set '())] [(∪ p1 p2) (set-union (parse-null p1) (parse-null p2))] [(∘ p1 p2) (for*/set ([t1 (parse-null p1)] [t2 (parse-null p2)]) (cons t1 t2))] [(→ p1 f) (for/set ([t (parse-null p1)]) (f t))])) ; Parse a list of tokens: (define (parse w p) (if (null? w) (parse-null p) (parse (cdr w) (D (car w) p)))))
false
ef05abad7640b419ebaa89b484bd0f3ee37ad3bc
2b1821134bb02ec32f71ddbc63980d6e9c169b65
/lisp/racket/HtDP2e/II/10-More on Lists.rkt
dc7389097d1e401ab2b774320f27aa81c1675918
[]
no_license
mdssjc/study
a52f8fd6eb1f97db0ad523131f45d5caf914f01b
2ca51a968e254a01900bffdec76f1ead2acc8912
refs/heads/master
2023-04-04T18:24:06.091047
2023-03-17T00:55:50
2023-03-17T00:55:50
39,316,435
3
1
null
2023-03-04T00:50:33
2015-07-18T23:53:39
Java
UTF-8
Racket
false
false
23,753
rkt
10-More on Lists.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 |10-More on Lists|) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) ;; 10-More on Lists.rkt ;; II - Arbitrarily Large Data ;; 10 - More on Lists (require 2htdp/image) (require 2htdp/universe) (require 2htdp/batch-io) (require racket/string) ;; 10.1 - Functions that Produce Lists ;; Exercise 161 ;; ================= ;; Constants: (define WAGE-COST 14) ;; ================= ;; Functions: ; List-of-numbers -> List-of-numbers ; computes the weekly wages for all given weekly hours (check-expect (wage* '()) '()) (check-expect (wage* (cons 28 '())) (cons (* WAGE-COST 28) '())) (check-expect (wage* (cons 4 (cons 2 '()))) (cons (* WAGE-COST 4) (cons (* WAGE-COST 2) '()))) (define (wage* whrs) (cond [(empty? whrs) '()] [else (cons (wage (first whrs)) (wage* (rest whrs)))])) ; Number -> Number ; computes the wage for h hours of work (define (wage h) (* WAGE-COST h)) ;; Exercise 162 ; List-of-numbers -> List-of-numbers ; computes the weekly wages for all given weekly hours (check-expect (wage*.v2 '()) '()) (check-expect (wage*.v2 (cons 28 '())) (cons (* WAGE-COST 28) '())) (check-expect (wage*.v2 (cons 4 (cons 2 '()))) (cons (* WAGE-COST 4) (cons (* WAGE-COST 2) '()))) (check-error (wage*.v2 (cons 12 (cons 100 '()))) "No employee could possibly work more than 100 hours per week") (define (wage*.v2 whrs) (cond [(empty? whrs) '()] [(>= (first whrs) 100) (error "No employee could possibly work more than 100 hours per week")] [else (cons (wage (first whrs)) (wage*.v2 (rest whrs)))])) ;; Exercise 163 ;; ================= ;; Functions: ; List-of-numbers -> List-of-numbers ; converts a list of measurements in Fahrenheit to a list of Celsius measurements (check-expect (convertFC '()) '()) (check-expect (convertFC (cons 98.6 '())) (cons 37 '())) (check-within (convertFC (cons 98.6 (cons 85 '()))) (cons 37 (cons 29.4 '())) 0.1) (define (convertFC t) (cond [(empty? t) '()] [else (cons (fahrenheit->celsius (first t)) (convertFC (rest t)))])) ; Number -> Number ; converts the temperature Fahrenheit in Celsius (check-expect (fahrenheit->celsius 98.6) 37) (check-expect (fahrenheit->celsius 212) 100) (check-expect (fahrenheit->celsius -40) -40) (define (fahrenheit->celsius f) (* (- f 32) (/ 5 9))) ;; Exercise 164 ;; ================= ;; Constants: (define RATE 0.920) ;; ================= ;; Functions: ; List-of-numbers -> List-of-numbers ; converts a list of US$ amounts into a list of € amounts (check-expect (convert-euro* '()) '()) (check-within (convert-euro* (cons 1 '())) (cons 0.92 '()) 0.1) (check-within (convert-euro* (cons 1 (cons 3.5 '()))) (cons 0.92 (cons 3.22 '())) 0.1) (define (convert-euro* d) (cond [(empty? d) '()] [else (cons (convert-euro (first d)) (convert-euro* (rest d)))])) ; Number -> Number ; converts the US$ in € with the current exchange rate (check-within (convert-euro 1) 0.92 0.1) (check-within (convert-euro 3.5) 3.22 0.1) (define (convert-euro d) (* d RATE)) ;; Exercise 165 ;; ================= ;; Functions: ; List-of-strings -> List-of-strings ; consumes a list of toy descriptions (one-word strings) and ; replaces all occurrences of "robot" with "r2d2" (check-expect (subst-robot '()) '()) (check-expect (subst-robot (cons "robot-1" '())) (cons "r2d2-1" '())) (check-expect (subst-robot (cons "robot-1" (cons ">>robot<<" '()))) (cons "r2d2-1" (cons ">>r2d2<<" '()))) (define (subst-robot los) (substitute "r2d2" "robot" los)) ; String String List-of-strings -> List-of-strings ; replaces all occurrences of new with old in the List-of-strings (define (substitute new old los) (cond [(empty? los) '()] [else (cons (string-replace (first los) old new) (substitute new old (rest los)))])) ;; 10.2 - Structures in Lists ;; Exercise 166 ;; ================= ;; Data definitions: (define-struct work [employee number rate hours]) ; A (piece of) Work is a structure: ; (make-work String Number Number Number) ; interpretation (make-work n num r h) combines the name ; with the number num, pay rate r and the number of hours h (define-struct pay-check (number name amount)) ; A Pay-check is a structure: ; (make-pay-check Number String Number) ; interpretation (make-pay-check num n a) contains ; the employee's number num, name n and an amount a ; A Low (short for list of works) is one of: ; - '() ; - (cons Work Low) ; interpretation an instance of Low represents the ; hours worked for a number of employees ; A Lop is one of: ; - '() ; - (cons Pay-check Lop) ; interpretation an instance of Lop represents the ; employee's name and an amount ;; ================= ;; Functions: ; Low -> Lop ; consumes a list of work records and computes a list of pay checks (check-expect (wage*.v3 '()) '()) (check-expect (wage*.v3 (cons (make-work "Robby" 1 11.95 39) '())) (cons (make-pay-check 1 "Robby" (* 11.95 39)) '())) (check-expect (wage*.v3 (cons (make-work "Matthew" 1 12.95 45) (cons (make-work "Robby" 2 11.95 39) '()))) (cons (make-pay-check 1 "Matthew" (* 12.95 45)) (cons (make-pay-check 2 "Robby" (* 11.95 39)) '()))) (define (wage*.v3 an-low) (cond [(empty? an-low) '()] [(cons? an-low) (cons (create-paycheck (first an-low)) (wage*.v3 (rest an-low)))])) ; Work -> Pay-check ; creates a paycheck for the given work w (define (create-paycheck w) (make-pay-check (work-number w) (work-employee w) (wage.v3 w))) ; Work -> Number ; computes the wage for the given work record w (define (wage.v3 w) (* (work-rate w) (work-hours w))) ;; Exercise 167 ;; ================= ;; Data definitions: ; A Lop is one of: ; - '() ; - (cons Posn Lop) ; interpretation an instance of Lop represents a Posn list ;; ================= ;; Functions: ; Lop -> Number ; consumes a list of Posns and produces the sum of all of its x-coordinates (check-expect (sum '()) 0) (check-expect (sum (cons (make-posn 11 20) '())) 11) (check-expect (sum (cons (make-posn 11 20) (cons (make-posn 48 66) '()))) (+ 11 48)) (define (sum lop) (cond [(empty? lop) 0] [else (+ (posn-x (first lop)) (sum (rest lop)))])) ;; Exercise 168 ;; ================= ;; Functions: ; Lop -> Lop ; produces lists of Posns with (make-posn x (+ y 1)) - known as translation (check-expect (translate '()) '()) (check-expect (translate (cons (make-posn 10 10) '())) (cons (make-posn 10 11) '())) (check-expect (translate (cons (make-posn 10 10) (cons (make-posn 20 20) '()))) (cons (make-posn 10 11) (cons (make-posn 20 21) '()))) (define (translate lop) (cond [(empty? lop) '()] [else (cons (make-posn (posn-x (first lop)) (add1 (posn-y (first lop)))) (translate (rest lop)))])) ;; Exercise 169 ;; ================= ;; Functions: ; Lop -> Lop ; produces lists of Posns whose x-coordinates are between 0 and 100 ; and whose y-coordinates are between 0 and 200 (check-expect (legal '()) '()) (check-expect (legal (cons (make-posn -1 100) '())) '()) (check-expect (legal (cons (make-posn 0 100) '())) (cons (make-posn 0 100) '())) (check-expect (legal (cons (make-posn 50 100) '())) (cons (make-posn 50 100) '())) (check-expect (legal (cons (make-posn 100 100) '())) (cons (make-posn 100 100) '())) (check-expect (legal (cons (make-posn 101 100) '())) '()) (check-expect (legal (cons (make-posn 50 -1) '())) '()) (check-expect (legal (cons (make-posn 50 0) '())) (cons (make-posn 50 0) '())) (check-expect (legal (cons (make-posn 50 100) '())) (cons (make-posn 50 100) '())) (check-expect (legal (cons (make-posn 50 200) '())) (cons (make-posn 50 200) '())) (check-expect (legal (cons (make-posn 50 201) '())) '()) (check-expect (legal (cons (make-posn -1 100) (cons (make-posn 50 100) (cons (make-posn 50 -1) (cons (make-posn 50 100) '()))))) (cons (make-posn 50 100) (cons (make-posn 50 100) '()))) (define (legal lop) (cond [(empty? lop) '()] [(< (posn-x (first lop)) 0) (legal (rest lop))] [(> (posn-x (first lop)) 100) (legal (rest lop))] [(< (posn-y (first lop)) 0) (legal (rest lop))] [(> (posn-y (first lop)) 200) (legal (rest lop))] [else (cons (first lop) (legal (rest lop)))])) ;; Exercise 170 ;; ================= ;; Data definitions: (define-struct phone [area switch four]) ; A Phone is a structure: ; (make-phone Three Three Four) ; A Three is a Number between 100 and 999. ; A Four is a Number between 1000 and 9999. (define P1 (make-phone 713 123 4567)) (define P2 (make-phone 281 123 4567)) (define P3 (make-phone 123 123 4567)) ; A Lop is one of: ; - '() ; - (cons Phone Lop) ; interpretation an instance of Lop represents a Phone list ;; ================= ;; Functions: ; Lop -> Lop ; replaces all occurrence of area code 713 with 281 (check-expect (replace* '()) '()) (check-expect (replace* (cons P1 '())) (cons P2 '())) (check-expect (replace* (cons P1 (cons P3 '()))) (cons P2 (cons P3 '()))) (define (replace* lop) (cond [(empty? lop) '()] [else (cons (replace (first lop)) (replace* (rest lop)))])) ; Phone -> Phone ; replaces the area code 713 with 281 (define (replace p) (cond [(= (phone-area p) 713) (make-phone 281 (phone-switch p) (phone-four p))] [else p])) ;; 10.3 - Lists in Lists, Files ;; Exercise 171 ;; ================= ;; Data definitions: ; A Los is one of: ; - '() ; - (cons String Los) ; interpretation a list of Strings, each is a String (define line0 (cons "hello" (cons "world" '()))) (define line1 '()) (define line2 (cons "the" (cons "car" '()))) (define line3 (cons "an" (cons "apple" '()))) (define line4 (cons "a" (cons "kite" '()))) (define line5 (cons "a" (cons "an" (cons "the" '())))) (define line6 (cons "two" (cons "days" '()))) ; A LLS is one of: ; - '() ; - (cons Los LLS) ; interpretation a list of lines, each is a list of Strings (define lls0 '()) (define lls1 (cons line0 (cons line1 '()))) (define lls2 (cons line0 (cons line1 (cons line0 '())))) (define lls3 (cons line0 (cons line0 (cons line0 '())))) (define lls4 (cons line2 (cons line1 (cons line3 (cons line4 '()))))) ;; Exercise 172 ;; ================= ;; Functions: ; LLS -> String ; converts a list of lines into a String ; the Strings should be separated by blank spaces (" ") ; the lines should be separated with a newline ("\n") (check-expect (collapse lls0) "") (check-expect (collapse lls1) "hello world\n") (check-expect (collapse lls2) "hello world\n\nhello world") (check-expect (collapse lls3) "hello world\nhello world\nhello world") (define (collapse lls) (cond [(empty? lls) ""] [else (string-append (collapse-line (first lls)) (if (empty? (rest lls)) "" "\n") (collapse (rest lls)))])) ; Los -> String ; converts a list of Strings into a String ; the Strings should be separated by blank spaces (" ") (check-expect (collapse-line line0) "hello world") (check-expect (collapse-line line1) "") (define (collapse-line los) (cond [(empty? los) ""] [else (string-append (first los) (if (empty? (rest los)) "" " ") (collapse-line (rest los)))])) ; Test drive (write-file "ttt.dat" (collapse (read-words/line "ttt.txt"))) ;; Exercise 173 ;; ================= ;; Functions: ; String -> String ; consumes the name n of a file, reads the file, removes the articles, ; and writes the result out to a file whose name is the result of ; concatenating "no-articles-" with n (define (remove-articles** n) (write-file (string-append "no-articles-" n) (remove-articles* (read-words/line "ttt.txt")))) ; LLS -> String ; converts a list of lines into a String without articles ; the Strings should be separated by blank spaces (" ") ; the lines should be separated with a newline ("\n") (check-expect (remove-articles* lls0) "") (check-expect (remove-articles* lls4) "car\n\napple\nkite") (define (remove-articles* lls) (cond [(empty? lls) ""] [else (string-append (remove-articles (first lls)) (if (empty? (rest lls)) "" "\n") (remove-articles* (rest lls)))])) ; Los -> String ; converts a list of Strings into a String without articles ; the Strings should be separated by blank spaces (" ") ; an article is one of the following three words: "a", "an", and "the" (check-expect (remove-articles line1) "") (check-expect (remove-articles line2) "car") (check-expect (remove-articles line3) "apple") (check-expect (remove-articles line4) "kite") (check-expect (remove-articles line5) "") (check-expect (remove-articles line6) "two days") (define (remove-articles los) (cond [(empty? los) ""] [else (string-append (cond [(string=? (first los) "a") ""] [(string=? (first los) "an") ""] [(string=? (first los) "the") ""] [else (string-append (first los) (if (empty? (rest los)) "" " "))]) (remove-articles (rest los)))])) ; Test drive (remove-articles** "ttt") ;; Exercise 174 ;; ================= ;; Functions: ; LLS -> LLS ; encodes text files numerically (check-expect (encode '()) '()) (check-expect (encode (cons (cons "a" (cons "b" '())) (cons (cons "1" (cons "2" '())) '()))) (cons (cons "097" (cons "098" '())) (cons (cons "049" (cons "050" '())) '()))) (define (encode lls) (cond [(empty? lls) '()] [else (cons (encode-lines (first lls)) (encode (rest lls)))])) ; Los -> Los ; encodes list of Strings numerically (check-expect (encode-lines '()) '()) (check-expect (encode-lines (cons "z" (cons "a" '()))) (cons "122" (cons "097" '()))) (define (encode-lines los) (cond [(empty? los) '()] [else (cons (encode-letters (explode (first los))) (encode-lines (rest los)))])) ; Los -> String ; encodes String numerically (check-expect (encode-letters '()) "") (check-expect (encode-letters (cons "z" (cons "a" '()))) "122097") (define (encode-letters s) (cond [(empty? s) ""] [else (string-append (encode-letter (first s)) (encode-letters (rest s)))])) ; 1String -> String ; converts the given 1String to a 3-letter numeric String (check-expect (encode-letter "z") (code1 "z")) (check-expect (encode-letter "\t") (string-append "00" (code1 "\t"))) (check-expect (encode-letter "a") (string-append "0" (code1 "a"))) (define (encode-letter s) (cond [(>= (string->int s) 100) (code1 s)] [(< (string->int s) 10) (string-append "00" (code1 s))] [(< (string->int s) 100) (string-append "0" (code1 s))])) ; 1String -> String ; convert the given 1String into a String (check-expect (code1 "z") "122") (define (code1 c) (number->string (string->int c))) ; Test drive (encode (read-words/line "ttt.txt")) ;; Exercise 175 ;; ================= ;; Functions: ; String -> String ; consumes the name of a file and produces a value that consists of three numbers (define (wc filename) (count (read-words/line filename))) ; LLS -> String ; counts the number of 1Strings, words, and lines (check-expect (count lls0) "0 0 0") (check-expect (count lls1) "10 2 2") (define (count lls) (string-append (number->string (count-1Strings lls)) " " (number->string (count-words lls)) " " (number->string (count-lines lls)))) ; LLS -> Number ; counts the number of 1Strings (check-expect (count-1Strings lls0) 0) (check-expect (count-1Strings lls1) 10) (define (count-1Strings lls) (cond [(empty? lls) 0] [else (+ (count-1Strings* (first lls)) (count-1Strings (rest lls)))])) (define (count-1Strings* los) (cond [(empty? los) 0] [else (+ (string-length (first los)) (count-1Strings* (rest los)))])) ; LLS -> String ; counts the number of words (check-expect (count-words lls0) 0) (check-expect (count-words lls1) 2) (define (count-words lls) (cond [(empty? lls) 0] [else (+ (length (first lls)) (count-words (rest lls)))])) ; LLS -> String ; counts the number of lines (check-expect (count-lines lls0) 0) (check-expect (count-lines lls1) 2) (define (count-lines lls) (length lls)) ; Test drive (wc "ttt.txt") ;; Exercise 176 ;; ================= ;; Data definitions: ; A Row is one of: ; - '() ; - (cons Number Row) (define row1 (cons 11 (cons 12 '()))) (define row2 (cons 21 (cons 22 '()))) ; A Matrix is one of: ; - (cons Row '()) ; - (cons Row Matrix) ; constraint all rows in matrix are of the same length (define mat1 (cons row1 (cons row2 '()))) ;; ================= ;; Functions: ; Matrix -> Matrix ; transposes the given matrix along the diagonal (define wor1 (cons 11 (cons 21 '()))) (define wor2 (cons 12 (cons 22 '()))) (define tam1 (cons wor1 (cons wor2 '()))) (check-expect (transpose mat1) tam1) (check-expect (transpose (cons (cons 1 (cons 2 '())) (cons (cons 3 (cons 4 '())) '()))) (cons (cons 1 (cons 3 '())) (cons (cons 2 (cons 4 '())) '()))) (define (transpose lln) (cond [(empty? (first lln)) '()] [else (cons (first* lln) (transpose (rest* lln)))])) ; Matrix -> Row ; consumes a matrix and produces the first column as a list of numbers (check-expect (first* '()) '()) (check-expect (first* mat1) (cons 11 (cons 21 '()))) (define (first* m) (cond [(empty? m) '()] [else (cons (first (first m)) (first* (rest m)))])) ; Matrix -> Matrix ; consumes a matrix and removes the first column (check-expect (rest* '()) '()) (check-expect (rest* mat1) (cons (cons 12 '()) (cons (cons 22 '()) '()))) (define (rest* m) (cond [(empty? m) '()] [else (cons (rest (first m)) (rest* (rest m)))])) ;; 10.4 - A Graphical Editor, Revisited ;; Exercise 177 ;; Exercise 178 ; Because its length is 1 (\t and \b are escape characters), the same as the ; alphanumeric characters for (string-length k). ;; Exercise 179 ;; Exercise 180 ;; ================= ;; Constants: (define HEIGHT 20) ; the height of the editor (define WIDTH 200) ; its width (define FONT-SIZE 16) ; the font size (define FONT-COLOR "black") ; the font color (define MT (empty-scene WIDTH HEIGHT)) (define CURSOR (rectangle 1 HEIGHT "solid" "red")) ;; ================= ;; Data definitions: (define-struct editor [pre post]) ; An Editor is a structure: ; (make-editor Lo1S Lo1S) ; An Lo1S is one of: ; - '() ; - (cons 1String Lo1S) ;; ================= ;; Functions: ; Lo1s -> Lo1s ; produces a reverse version of the given list (check-expect (rev (cons "a" (cons "b" (cons "c" '())))) (cons "c" (cons "b" (cons "a" '())))) (define (rev l) (cond [(empty? l) '()] [else (add-at-end (rev (rest l)) (first l))])) ; Lo1s 1String -> Lo1s ; creates a new list by adding s to the end of l (check-expect (add-at-end (cons "c" (cons "b" '())) "a") (cons "c" (cons "b" (cons "a" '())))) (check-expect (add-at-end '() "s") (cons "s" '())) (define (add-at-end l s) (cond [(empty? l) (cons s '())] [else (cons (first l) (add-at-end (rest l) s))])) ; String String -> Editor ; produces an Editor (check-expect (create-editor "left" "right") (make-editor (rev (explode "left")) (explode "right"))) (define (create-editor s1 s2) (make-editor (rev (explode s1)) (explode s2))) (define e1 (create-editor "" "")) (define e2 (create-editor "left" "right")) (define e3 (create-editor "" "right")) (define e4 (create-editor "left" "")) ; main : String -> Editor ; launches the editor given some initial string (define (main s) (big-bang (create-editor s "") [on-key editor-kh] [to-draw editor-render])) ; Editor -> Image ; renders an editor as an image of the two texts ; separated by the cursor (define (editor-render ed) (place-image/align (beside (editor-text (reverse (editor-pre ed))) CURSOR (editor-text (editor-post ed))) 1 1 "left" "top" MT)) ; Editor KeyEvent -> Editor ; deals with a key event, given some editor (check-expect (editor-kh (create-editor "" "") "e") (create-editor "e" "")) (check-expect (editor-kh (create-editor "cd" "fgh") "e") (create-editor "cde" "fgh")) (define (editor-kh ed k) (cond [(key=? k "left") (editor-lft ed)] [(key=? k "right") (editor-rgt ed)] [(key=? k "\b") (editor-del ed)] [(key=? k "\t") ed] [(key=? k "\r") ed] [(= (string-length k) 1) (editor-ins ed k)] [else ed])) ; Editor String -> Editor ; inserts the 1String k between pre and post (check-expect (editor-ins (make-editor '() '()) "e") (make-editor (cons "e" '()) '())) (check-expect (editor-ins (make-editor (cons "d" '()) (cons "f" (cons "g" '()))) "e") (make-editor (cons "e" (cons "d" '())) (cons "f" (cons "g" '())))) (define (editor-ins ed k) (make-editor (cons k (editor-pre ed)) (editor-post ed))) ; Editor -> Editor ; moves the cursor position one 1String left, ; if possible (check-expect (editor-lft e1) e1) (check-expect (editor-lft e2) (create-editor "lef" "tright")) (check-expect (editor-lft e3) e3) (define (editor-lft ed) (cond [(empty? (editor-pre ed)) ed] [else (make-editor (rest (editor-pre ed)) (cons (first (editor-pre ed)) (editor-post ed)))])) ; Editor -> Editor ; moves the cursor position one 1String right, ; if possible (check-expect (editor-rgt e1) e1) (check-expect (editor-rgt e2) (create-editor "leftr" "ight")) (check-expect (editor-rgt e4) e4) (define (editor-rgt ed) (cond [(empty? (editor-post ed)) ed] [else (make-editor (reverse (add-at-end (reverse (editor-pre ed)) (first (editor-post ed)))) (rest (editor-post ed)))])) ; Editor -> Editor ; deletes a 1String to the left of the cursor ; if possible (check-expect (editor-del e1) e1) (check-expect (editor-del e2) (create-editor "lef" "right")) (check-expect (editor-del e3) e3) (define (editor-del ed) (cond [(empty? (editor-pre ed)) ed] [else (make-editor (rest (editor-pre ed)) (editor-post ed))])) ; Lo1s -> Image ; renders a list of 1Strings as a text image (check-expect (editor-text (cons "p" (cons "o" (cons "s" (cons "t" '()))))) (text "post" FONT-SIZE FONT-COLOR)) (define (editor-text s) (cond [(empty? s) empty-image] [else (beside (text (first s) FONT-SIZE FONT-COLOR) (editor-text (rest s)))]))
false
85d1f428992f8525db5326571a7d7a36c7083299
66c92b955f3caa70ea4b322654079450ab9eff36
/gm-pepm-2018/script/cache-python-info/aespython.rktd
a96ab2bd5cd954e8391350d8a250a94664bdf0b6
[ "MIT" ]
permissive
nuprl/retic_performance
ebc3a5656ce77539ff44c50ac00dacd0a22496ec
da634137b151553c354eafcc549e1650043675f9
refs/heads/master
2023-06-22T05:41:16.151571
2023-06-12T20:16:13
2023-06-12T20:16:13
85,637,202
3
1
MIT
2023-06-12T20:16:14
2017-03-20T23:23:11
Racket
UTF-8
Racket
false
false
5,823
rktd
aespython.rktd
;; This file was generated by the `with-cache` library on 2017-05-09 (((aespython ("aes_cipher.py" "d8836244bd9df6b3fc761ae0766a0371") ("aes_tables.py" "82ea78ffb5ddb45138eccb1dca74652a") ("cbc_mode.py" "46143429807bdf157b515e2dd558d8b3") ("cipher_mode.py" "cdf4ada4377a748af06669f25150fb4f") ("key_expander.py" "162d6033afc0925c227f4151e5dcf68f") ("main.py" "ba8ce2785c8f44dda8ee6a6fef10d014"))) (3) 0 () 0 () () (f python-info aespython (c (f module-info aes_cipher () (c (f class-info AESCipher (c (f field-info _expanded_key (u . "List(int)")) c (f field-info _Nr (u . "int"))) (c (f function-info __init__ (c (f field-info self (u . "AESCiper")) c (f field-info expanded_key (u . "List(Int)"))) (u . "Void")) c (f function-info _sub_bytes (c (f field-info self (u . "AESCipher")) c (f field-info state (u . "List(Int)"))) (u . "Void")) c (f function-info _i_sub_bytes (c (f field-info self (u . "AESCipher")) c (f field-info state (u . "List(Int)"))) (u . "Void")) c (f function-info _shift_row (c (f field-info self (u . "AESCipher")) c (f field-info row (u . "List(Int)")) c (f field-info shift (u . "Int"))) (u . "List(Int)")) c (f function-info _i_shift_row (c (f field-info self (u . "AESCipher")) c (f field-info row (u . "List(Int)")) c (f field-info shift (u . "Int"))) (u . "List(Int)")) c (f function-info _shift_rows (c (f field-info self (u . "AESCipher")) c (f field-info state (u . "List(Int)"))) (u . "Void")) c (f function-info _i_shift_rows (c (f field-info self (u . "AESCipher")) c (f field-info state (u . "List(Int)"))) (u . "Void")) c (f function-info _mix_column (c (f field-info self (u . "AESCipher")) c (f field-info column (u . "List(Int)")) c (f field-info inverse (u . "Bool"))) (u . "List(Int)")) c (f function-info _mix_columns (c (f field-info self (u . "AESCipher")) c (f field-info state (u . "List(Int)")) c (f field-info inverse (u . "Bool"))) (u . "Void")) c (f function-info _add_round_key (c (f field-info self (u . "AESCipher")) c (f field-info state (u . "List(Int)")) c (f field-info round (u . "Int"))) (u . "Void")) c (f function-info cipher_block (c (f field-info self (u . "AESCipher")) c (f field-info state (u . "List(Int)"))) (u . "List(Int)")) c (f function-info decipher_block (c (f field-info self (u . "AESCipher")) c (f field-info state (u . "List(Int)"))) (u . "List(Int)")))))) c (f module-info aes_tables () ()) c (f module-info cbc_mode () (c (f class-info CBCMode (c (f field-info name (u . "str"))) (c (f function-info __init__ (c (f field-info self (u . "CBCMode")) c (f field-info block_cipher (u . "Object(my_block_cipher,{cipher_block : Function([List(Int)],List(int)),decipher_block : Function([List(Int)],List(Int))})")) c (f field-info block_size (u . "Int"))) (u . "Void")) c (f function-info encrypt_block (c (f field-info self (u . "CBCMode")) c (f field-info plaintext (u . "List(Int)"))) (u . "List(Int)")) c (f function-info decrypt_block (c (f field-info self (u . "CBCMode")) c (f field-info ciphertext (u . "List(Int)"))) (u . "List(Int)")))))) c (f module-info cipher_mode () (c (f class-info CipherMode (c (f field-info name (u . "str")) c (f field-info _block_cipher (u . "Object(my_block_cipher,{cipher_block : Function([List(Int)],List(int)),decipher_block : Function([List(Int)],List(Int))})")) c (f field-info _block_size (u . "Int")) c (f field-info _iv (u . "List(Int)"))) (c (f function-info __init__ (c (f field-info self (u . "CipherMode")) c (f field-info block_cipher (u . "Object(my_block_cipher,{cipher_block : Function([List(Int)],List(int)),decipher_block : Function([List(Int)],List(Int))})")) c (f field-info block_size (u . "Int"))) (u . "Void")) c (f function-info set_iv (c (f field-info self (u . "CipherMode")) c (f field-info iv (u . "List(Int)"))) (u . "Void")) c (f function-info encrypt_block (c (f field-info self (u . "CipherMode")) c (f field-info plaintext (u . "List(Int)"))) (u . "List(Int)")) c (f function-info decrypt_block (c (f field-info self (u . "CipherMode")) c (f field-info ciphertext (u . "List(Int)"))) (u . "List(Int)")))))) c (f module-info key_expander () (c (f class-info KeyExpander (c (f field-info _key_length (u . "int")) c (f field-info _n (u . "int")) c (f field-info _expanded_key_length (u . "Dict(int,int)"))) (c (f function-info __init__ (c (f field-info self (u . "KeyExpander")) c (f field-info key_length (u . "Int"))) (u . "Void")) c (f function-info _core (c (f field-info self (u . "KeyExpander")) c (f field-info key_array (u . "List(Int)")) c (f field-info iteration (u . "Int"))) (u . "List(int)")) c (f function-info _xor_list (c (f field-info self (u . "KeyExpander")) c (f field-info list_1 (u . "List(Int)")) c (f field-info list_2 (u . "List(Int)"))) (u . "List(int)")) c (f function-info expand (c (f field-info self (u . "KeyExpander")) c (f field-info key_array (u . "List(Int)"))) (u . "List(int)")))))) c (f module-info main () (c (f class-info AESdemo (c (f field-info _salt (u . "Void")) c (f field-info _iv (u . "List(int)")) c (f field-info _key (u . "List(int)")) c (f field-info _python3 (u . "bool"))) (c (f function-info __init__ (c (f field-info self (u . "AESdemo"))) (u . "Void")) c (f function-info new_salt (c (f field-info self (u . "AESdemo"))) (u . "Void")) c (f function-info set_iv (c (f field-info self (u . "AESdemo")) c (f field-info iv (u . "List(int)"))) (u . "Void")) c (f function-info set_key (c (f field-info self (u . "AESdemo")) c (f field-info key (u . "List(int)"))) (u . "Void")) c (f function-info decrypt_file (c (f field-info self (u . "AESdemo")) c (f field-info in_file_path (u . "str")) c (f field-info out_file_path (u . "str"))) (u . "bool")) c (f function-info encrypt_file (c (f field-info self (u . "AESdemo")) c (f field-info in_file_path (u . "str")) c (f field-info out_file_path (u . "str"))) (u . "bool")))))))))
false
174cb31ededb66ca61293de052ec0bf26bf76a62
65c1f9548ad23d102a42be54ae7ef16f54767dba
/gregor-lib/gregor/private/pattern/ast/day.rkt
c5c64cea63bf8e9d0a4ce230aceadddf217cd8d3
[ "MIT" ]
permissive
97jaz/gregor
ea52754ce7aa057941a5a7080415768687cc4764
2d20192e8795e01a1671869dddaf1984f0cbafee
refs/heads/master
2022-07-20T12:52:15.088073
2022-06-28T09:48:59
2022-07-19T16:01:18
32,499,398
45
11
null
2022-06-28T09:50:43
2015-03-19T03:47:23
Racket
UTF-8
Racket
false
false
1,550
rkt
day.rkt
#lang racket/base (require racket/contract/base racket/match "../../generics.rkt" "../../core/structs.rkt" "../../core/ymd.rkt" "../ast.rkt" "../parse-state.rkt" "../l10n/numbers.rkt") (provide (struct-out Day)) (define (day-fmt ast t loc) (match ast [(Day _ 'month n) (num-fmt loc (->day t) n)] [(Day _ 'year n) (num-fmt loc (->yday t) n)] [(Day _ 'week/month n) (num-fmt loc (add1 (quotient (sub1 (->day t)) 7)) n)] [(Day _ 'jdn n) (num-fmt loc (->jdn t) n)])) (define (day-parse ast next-ast state ci? loc) (match ast [(Day _ 'month n) (num-parse ast loc state (parse-state/ day) #:min n #:max 2 #:ok? (between/c 1 31))] [(Day _ 'year n) (num-parse ast loc state parse-state/ignore #:min n #:max 3 #:ok? (between/c 1 366))] [(Day _ 'week/month n) (num-parse ast loc state parse-state/ignore #:min n #:max 1 #:ok? (between/c 1 5))] [(Day _ 'jdn n) (define (update str fs jdn) (match-define (YMD y m d) (jdn->ymd jdn)) (parse-state str (struct-copy fields (set-fields-year/ext fs y) [month m] [day d]))) (num-parse ast loc state update #:min n #:neg #t)])) (define (day-numeric? ast) #t) (struct Day Ast (kind size) #:transparent #:methods gen:ast [(define ast-fmt-contract date-provider-contract) (define ast-fmt day-fmt) (define ast-parse day-parse) (define ast-numeric? day-numeric?)])
false
7693fcf48cd0f00cbb152026d622a1221eaa4df1
e0ea6503b51c4742398ca00e3ee040671d53059f
/emulator/print-utils.rkt
33813a9b273b9e9c776a7f5b0bc3af421a10d4f6
[]
no_license
andrewtshen/riscv-symbolic-emulator
b25622649f4387dffbd7103ad7fa4c7f4dafc629
c7b02091521a4dc3dcd45f3cef35e1af0a43759a
refs/heads/master
2023-04-30T13:38:41.101292
2021-03-23T20:01:27
2021-03-23T20:01:27
206,185,823
1
0
null
2021-03-23T20:01:27
2019-09-03T22:55:21
Racket
UTF-8
Racket
false
false
4,370
rkt
print-utils.rkt
#lang rosette/safe (require "machine.rkt" "pmp.rkt" "csrs.rkt") (require (only-in racket/base for in-range)) (define (print-pmp m) (printf "pmpcfg0: ~a~n" (machine-csr m PMPCFG0)) (printf "pmpcfg2: ~a~n" (machine-csr m PMPCFG2)) (printf "pmpaddr0: ~a~n" (machine-csr m PMPADDR0)) (printf "pmpaddr1: ~a~n" (machine-csr m PMPADDR1)) (printf "pmpaddr2: ~a~n" (machine-csr m PMPADDR2)) (printf "pmpaddr3: ~a~n" (machine-csr m PMPADDR3)) (printf "pmpaddr4: ~a~n" (machine-csr m PMPADDR4)) (printf "pmpaddr5: ~a~n" (machine-csr m PMPADDR5)) (printf "pmpaddr6: ~a~n" (machine-csr m PMPADDR6)) (printf "pmpaddr7: ~a~n" (machine-csr m PMPADDR7)) (printf "pmpaddr8: ~a~n" (machine-csr m PMPADDR8)) (printf "pmpaddr0 base/range: ~a~n" (pmp-decode-napot (machine-csr m PMPADDR0))) (printf "pmpaddr1 base/range: ~a~n" (pmp-decode-napot (machine-csr m PMPADDR1))) (printf "pmpaddr8 base/range: ~a~n" (pmp-decode-napot (machine-csr m PMPADDR8)))) (provide print-pmp) (define (print-csr m) (printf "pc: ~a~n" (machine-pc m)) (printf "mode: ~a~n" (machine-mode m)) (printf "mtvec: ~a~n" (machine-csr m MTVEC)) (printf "mepc: ~a~n" (machine-csr m MEPC)) (printf "pmpcfg0: ~a~n" (machine-csr m PMPCFG0)) (printf "pmpcfg2: ~a~n" (machine-csr m PMPCFG2)) (printf "pmpaddr0: ~a~n" (machine-csr m PMPADDR0)) (printf "pmpaddr1: ~a~n" (machine-csr m PMPADDR1)) (printf "pmpaddr2: ~a~n" (machine-csr m PMPADDR2)) (printf "pmpaddr3: ~a~n" (machine-csr m PMPADDR3)) (printf "pmpaddr4: ~a~n" (machine-csr m PMPADDR4)) (printf "pmpaddr5: ~a~n" (machine-csr m PMPADDR5)) (printf "pmpaddr6: ~a~n" (machine-csr m PMPADDR6)) (printf "pmpaddr7: ~a~n" (machine-csr m PMPADDR7)) (printf "pmpaddr8: ~a~n" (machine-csr m PMPADDR8))) (provide print-csr) (define (get-readable-csr csr) (cond [(bveq csr USTATUS) 'USTATUS] [(bveq csr UTVEC) 'UTVEC] [(bveq csr UEPC) 'UEPC] [(bveq csr UCAUSE) 'UCAUSE] [(bveq csr UTVAL) 'UTVAL] [(bveq csr FFLAGS) 'FFLAGS] [(bveq csr FRB) 'FRB] [(bveq csr FCSR ) 'FCSR ] [(bveq csr TIME) 'TIME] [(bveq csr SSTATUS) 'SSTATUS] [(bveq csr SEDELEG) 'SEDELEG] [(bveq csr SIDELEG) 'SIDELEG] [(bveq csr SIE) 'SIE] [(bveq csr STVEC) 'STVEC] [(bveq csr SSCRATCH) 'SSCRATCH] [(bveq csr SEPC) 'SEPC] [(bveq csr SCAUSE) 'SCAUSE] [(bveq csr STVAL) 'STVAL] [(bveq csr SIP) 'SIP] [(bveq csr SATP) 'SATP] [(bveq csr SSTATUS_SIE) 'SSTATUS_SIE] [(bveq csr SSTATUS_SPIE ) 'SSTATUS_SPIE ] [(bveq csr SSTATUS_SPP) 'SSTATUS_SPP] [(bveq csr PMPCFG0) 'PMPCFG0] [(bveq csr PMPCFG1) 'PMPCFG1] [(bveq csr PMPCFG2) 'PMPCFG2] [(bveq csr PMPCFG3) 'PMPCFG3] [(bveq csr PMPADDR0) 'PMPADDR0] [(bveq csr PMPADDR1) 'PMPADDR1] [(bveq csr PMPADDR2) 'PMPADDR2] [(bveq csr PMPADDR3) 'PMPADDR3] [(bveq csr PMPADDR4) 'PMPADDR4] [(bveq csr PMPADDR5) 'PMPADDR5] [(bveq csr PMPADDR6) 'PMPADDR6] [(bveq csr PMPADDR7) 'PMPADDR7] [(bveq csr PMPADDR8) 'PMPADDR8] [(bveq csr PMPADDR9) 'PMPADDR9] [(bveq csr PMPADDR10) 'PMPADDR10] [(bveq csr PMPADDR11) 'PMPADDR11] [(bveq csr PMPADDR12) 'PMPADDR12] [(bveq csr PMPADDR13) 'PMPADDR13] [(bveq csr PMPADDR14) 'PMPADDR14] [(bveq csr PMPADDR15) 'PMPADDR15] [(bveq csr SSTATUS_FS) 'SSTATUS_FS] [(bveq csr SSTATUS_XS) 'SSTATUS_XS] [(bveq csr SSTATUS_SUM) 'SSTATUS_SUM] [(bveq csr SSTATUS_MXR) 'SSTATUS_MXR] [(bveq csr SSTATUS_UXL) 'SSTATUS_UXL] [(bveq csr MVENDORID) 'MVENDORID] [(bveq csr MARCHID) 'MARCHID] [(bveq csr MIMPID) 'MIMPID] [(bveq csr MHARTID) 'MHARTID] [(bveq csr MSTATUS) 'MSTATUS] [(bveq csr MISA) 'MISA] [(bveq csr MEDELEG) 'MEDELEG] [(bveq csr MIDELEG) 'MIDELEG] [(bveq csr MIE) 'MIE] [(bveq csr MTVEC) 'MTVEC] [(bveq csr MCOUNTEREN) 'MCOUNTEREN] [(bveq csr MSCRATCH) 'MSCRATCH] [(bveq csr MEPC) 'MEPC] [(bveq csr MCAUSE) 'MCAUSE] [(bveq csr MTVAL) 'MTVAL] [(bveq csr MIP) 'MIP] [(bveq csr PMPCFG0) 'PMPCFG0] [(bveq csr PMPADDR0) 'PMPADDR0] [(bveq csr SSIP_BIT) 'SSIP_BIT] [(bveq csr MSIP_BIT) 'MSIP_BIT] [(bveq csr STIP_BIT) 'STIP_BIT] [(bveq csr MTIP_BIT) 'MTIP_BIT] [(bveq csr SEIP_BIT) 'SEIP_BIT] [(bveq csr MEIP_BIT) 'MEIP_BIT] [else 'UNKNOWN_CSR])) (provide get-readable-csr)
false
ac1dce5da3ed6c3eaf3b98383e876d82ac411368
82c76c05fc8ca096f2744a7423d411561b25d9bd
/typed-racket-test/fail/pr11560.rkt
ed3515dec0d41fac4e2a8ae5597f4f0c84c92eb1
[ "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
51
rkt
pr11560.rkt
#lang typed/racket/base (ann (ann 5 Real) Integer)
false
7d4ad60364b08bfff5ff8e38eafae157842f08c4
4b4cf60c0374260777cc3920d5879f434614660f
/doc-coverage/private/export-count.rkt
8f3cae3eb6c34d9a3ef20ea45b758f22e9b2ed75
[ "Apache-2.0" ]
permissive
jackfirth/doc-coverage
9b8919feacdd5646d8e76c1b5613ddaed3c57093
b1c0e9f3fd3a25e260f8905e6c8211dacf532b25
refs/heads/master
2021-01-17T12:24:45.209211
2020-07-21T00:55:58
2020-07-21T00:55:58
31,117,920
6
4
Apache-2.0
2020-07-21T00:55:59
2015-02-21T06:54:54
Racket
UTF-8
Racket
false
false
567
rkt
export-count.rkt
#lang racket (provide module-num-exports module-num-documented-exports module-num-undocumented-exports module-documentation-ratio) (require "export-lists.rkt") (define module-num-exports (compose length module->all-exported-names)) (define module-num-documented-exports (compose length module->documented-exported-names)) (define module-num-undocumented-exports (compose length module->undocumented-exported-names)) (define (module-documentation-ratio mod) (/ (module-num-documented-exports mod) (module-num-exports mod)))
false
cfbb1cc63a45e6aeebd707026bb145d0e220461c
49d98910cccef2fe5125f400fa4177dbdf599598
/exercism.io/acronym/acronym-test.rkt
fb4a11a83bfd09665df4cdd46e75b17a99424dfc
[ "MIT" ]
permissive
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
878
rkt
acronym-test.rkt
#lang racket (require "acronym.rkt") (module+ test (require rackunit rackunit/text-ui) (define suite (test-suite "Tests for the acronym exercise" (test-case "it produces acronyms from title case" (check-equal? (abbreviate "Portable Network Graphics") "PNG")) (test-case "it produces acronyms from lower case" (check-equal? (abbreviate "Ruby on Rails") "ROR")) (test-case "it produces acronyms from inconsistent case" (check-equal? (abbreviate "HyperText Markup Language") "HTML")) (test-case "it ignores punctuation" (check-equal? (abbreviate "First in, First out") "FIFO")) (test-case "produces acronyms ignoring punctuation and casing" (check-equal? (abbreviate "Complementary Metal-Oxide semiconductor") "CMOS")) )) (run-tests suite))
false
f70532382c447d80a3b965c1a8196311a3979e9b
18434afe1c80686258b26c27020a4ed15f561afd
/lisp/1.31.rkt
808ff8fcdb7571b84f46a5211f93306615c1c461
[]
no_license
ParkinWu/outofwork
cc9a50b5fa23c68dfc38e1915c6746ece19d4ffa
a3d7370182cd62cca50b97d524ea897801e1cec0
refs/heads/master
2020-07-25T00:39:24.290684
2017-01-04T01:46:39
2017-01-04T01:46:39
73,782,894
0
0
null
null
null
null
UTF-8
Racket
false
false
607
rkt
1.31.rkt
#lang racket ;迭代版本 ; (define (product term a next b) ; (define (iter a result) ; (if (> a b) ; result ; (iter (next a) (* (term a) result)))) ; (iter a 1) ; 递归版本 (define (product term a next b) (if (> a b) 1 (* (term a) (product term (next a) next b)))) (define (identity a) a) (define (inc-2 a) (+ a 2)) (define (product2 a b) (product identity a inc-2 b)) (define (square a) (* a a)) (define (num n) (/ (* (product2 2 n) (product2 4 n)) n)) (define (deno n) (square (product2 3 n))) (define (pi n) (* 4 (/ (num n) (deno n))))
false
03ea7a709833a08aba07df6175e9a43e85d9aa52
e553691752e4d43e92c0818e2043234e7a61c01b
/sdsl/synthcl/model/runtime.rkt
79cf0de164d540ab53893c388b2527d6d6b9d88c
[ "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
2,228
rkt
runtime.rkt
#lang rosette (require "memory.rkt" "reals.rkt" "type.rkt" "pointers.rkt") (provide current-memory malloc address-of) ; Models the current state of the execution. ; The current memory parameter holds the memory object ; from which are currently allocating memory. This may ; be the host's memory or the device's global memory. (define current-memory (make-parameter (memory) (lambda (m) (match m [(? memory? m) m] [m (raise-argument-error 'current-memory "memory" m)])))) ; A simplified model of malloc that takes as input the ; number of cells to allocate, and where each scalar type ; has the same size (1). The size argument must be a concrete ; exact non-negative integer. (define (malloc size) (unless (exact-nonnegative-integer? size) (raise-argument-error 'malloc "concrete exact nonnegative integer" size)) (memory-allocate! (current-memory) size)) ; Given an lvalue and the type of that lvalue, returns a ; pointer object through which that value can be accessed ; and mutated. The type must be a real-type?. (define-syntax-rule (address-of lval type) (local-pointer (lambda () ((type) lval)) (lambda (v) (set! lval ((type) v))) #'lval type)) (struct local-pointer (get set! address type) #:methods gen:custom-write [(define (write-proc self port mode) (fprintf port "#~x[~a]" (local-pointer-address self) ((local-pointer-get self))))] #:methods gen:pointer [(define (pointer-address self) (local-pointer-address self)) (define (pointer-size self) (real-type-length (local-pointer-type self))) (define (pointer-cast self t) (define type (local-pointer-type self)) (unless (equal? t type) (raise-argument-error 'pointer-cast (~a (type-name type)) t)) self) (define (pointer-ref self idx) (unless (= idx 0) (raise-argument-error 'pointer-ref "0" idx)) ((local-pointer-get self))) (define (pointer-set! self idx val) (unless (= idx 0) (raise-argument-error 'pointer-set! "0" idx)) ((local-pointer-set! self) val)) (define (pointer->list self) (list ((local-pointer-get self))))])
true
c7783ee2762dccd88949a38ec5aab10aaeb44aff
8de3f562d9c8d89d1598c3b9d987c65d72aaa0f7
/递归函数的lambda表达式.rkt
fffa8fa309f8eaea9b9b3d32241fb9eef55cb76d
[]
no_license
tjuqxb/SICP
17664460ef34cb325c3d5fde000cc989799ca89d
4fb8400c0d779e3c555cc7a5d490436296cf25e3
refs/heads/master
2021-01-24T07:55:41.180817
2017-06-20T03:12:26
2017-06-20T03:12:26
93,363,899
0
0
null
null
null
null
UTF-8
Racket
false
false
2,653
rkt
递归函数的lambda表达式.rkt
Y combinator 如何用LAMBDA匿名函数表达递归 我们理解的一个普通递归表达式为(当(g x)到达某个值时,函数会返回一个我们之前规定的值,然后通过我们之前展开的空间进行还原,我们得到所求的值。 (lambda(x) (f (self (g x)))) 其中self为指向自身的指针,如下方所示。 我们用LAMBDA匿名函数展开这个表达式,发现这是个无限展开的表达式,原因是它采用了self指针。(然而如下这种写法仍然是不合法的,因为这样会陷入无限的loop) (lambda(x) ((lambda(s) (f (s (g x)))) self)) => (lambda(x) ((lambda(s) (f (s (g x)))) (lambda(x) (lambda(s) (f s (g x))) ...... 我们的目标是寻求这样一个匿名函数的不包含self指针的写法(即它们是等价的LAMBDA表达式,我们所求的不包含self指针,所以是有限的。) 令没有 self形式的匿名函数为 (lambda(x) (M x)) 令 m = (lambda(x)(M x)) 由于m是我们之前设定的匿名函数的等价形式,我们可以用m代替原来的自指形式匿名函数self 为了能在最外层代入m,原函数被改写为 ((lambda(s) (lambda(x) (f s (g x))))self) 用m代替SELF代入上方函数 我们发现该匿名函数也是一个不包含self指针的有限形式了,那么此时的匿名函数和m事实上是等价的。 ((lambda (s) (lambda (x) (f (s (g x)))))m)=m .....................1 上式可以看出是一个函数接收了函数m,返回了函数m m = (p m) 我们构造一个k k = (lambda(a) (p (a a))) (k k) = (p (k k)) 那么 m = (k k) 实际上,我们要定义的是(k k),以f为参数,返回一个不带自指的递归函数 (define (rec1 f) ((lambda(a) (lambda(x) (f (a a) x))) (lambda(a) (lambda(x) (f (a a) x))))) 其中f以(f self x) 形式写出,self指代自身,代入rec1之后(a a)替代self能得到递归函数,自身递归下去。 在式1中,k 的形式是 (lambda(a) (lambda(x) (f ((a a) (g x))))) (k k) ((lambda(a) (lambda(x) (f ((a a) (g x))))) (lambda(a) (lambda(x) (f ((a a) (g x)))))) 由于f ;;;test (define (recursion f g) ((lambda(a) (lambda(x) (f ((a a) (g x))))) (lambda(a) (lambda(x) (f ((a a) (g x))))))) (define s1 (lambda(x) (if (= x 1) 1 (* 3 x))));s1这样写是错误的,边界条件涉及递归式实际上是无法取得的。 (define s2 (lambda (x) (- x 1))) ((recursion s1 s2) 4)
false
e769d29709ede1204299b36a7f6c488bb44be4f2
3eb2d1bb2e5716e093dbd0fe502db4ea988ea52e
/drawing.rkt
236d29fd2b5c58a853952059a1ab18f212810199
[]
no_license
2050utopia/racket-blocks
eaa854ad5db612c4208ee64f1932854c794d8a18
d239c98e4f71d2f1acb7bcb2b4914c84b65be3ea
refs/heads/master
2020-04-03T18:19:16.349697
2016-10-09T18:30:20
2016-10-09T18:30:20
null
0
0
null
null
null
null
UTF-8
Racket
false
false
4,966
rkt
drawing.rkt
#lang curly-fn racket (provide tile-size ;; board paint-board board-bg board-width-tiles board-height-tiles paint-row ;; pieces piece piece-color piece-positions-update pieces draw-piece piece-width-tiles piece-height-tiles) (require 2htdp/image lang/posn picturing-programs) (require match-plus curly-fn threading) (require (for-syntax syntax/parse)) (require alexis/util/struct) (define tile-size 24) (define board-width-tiles 10) (define board-height-tiles 25) (define board-bgcolor "dark gray") (define board-grid-color "light gray") (define (make-gray x [a 255]) (make-color x x x a)) ;; draw a rectangle with a gradient (define (gradient-rect w h color) (define (apply-factor x) (* x (quotient 255 w))) (define base-rect (rectangle w h "solid" color)) ;; measurably helps with perf to pre-calculate those (define col-vec (vector->immutable-vector (list->vector (foldl (λ(x l) (cons (make-gray (apply-factor x) 127) l)) '() (range w))))) (overlay (map-image (λ(x y col) (vector-ref col-vec x)) base-rect) base-rect)) ;; I need a macro for this because I want to get rid of the ;; make-posn calls everywhere. I can make a function using map ;; and "apply make-posn" but then instead of "make-posn" I have ;; to write "list" in my expressions so I don't gain much... (define-syntax (make-posns stx) (define-syntax-class posn-pair #:description "posn pair" (pattern (x:expr y:expr))) (syntax-parse stx [(_ (p:posn-pair ...+)) #'(list (make-posn p.x p.y) ...)])) ;; draw a single tile of a piece. (define (block-tile color) (define bright-shade (make-gray 255 140)) (define dark-shade (make-gray 0 140)) (define overlay-width (quotient tile-size 7)) (underlay ;; the background (gradient-rect tile-size tile-size color) ;; the brighter top-left shade (polygon (make-posns ((tile-size 0) (tile-size tile-size) (0 tile-size) (overlay-width (- tile-size overlay-width)) ((- tile-size overlay-width) (- tile-size overlay-width)) ((- tile-size overlay-width) overlay-width))) "solid" dark-shade) ;; the darker bottom-right shade (polygon (make-posns ((0 0) (tile-size 0) ((- tile-size overlay-width) overlay-width) (overlay-width overlay-width) (overlay-width (- tile-size overlay-width)) (0 tile-size))) "solid" bright-shade))) (struct piece (color positions) #:transparent) (define-struct-updaters piece) (define pieces (list (piece "red" '((0 0) (1 0) (2 0) (1 1))) (piece "blue" '((0 0) (1 0) (2 0) (3 0))) (piece "green" '((0 0) (1 0) (1 1) (2 1))) (piece "yellow" '((0 0) (1 0) (0 1) (1 1))) (piece "orange" '((0 0) (1 0) (2 0) (0 1))))) (define (offset-px tile-count) (* tile-count tile-size)) (define/match* (piece-width-tiles (piece _ pos)) (add1 (apply max (map first pos)))) (define/match* (piece-height-tiles (piece _ pos)) (add1 (apply max (map second pos)))) (define (draw-piece piece) (define canvas (rectangle (offset-px (piece-width-tiles piece)) (offset-px (piece-height-tiles piece)) "solid" "transparent")) (define tile (block-tile (piece-color piece))) (foldl (λ(cur-pos c) (place-image/align tile (offset-px (first cur-pos)) (offset-px (second cur-pos)) "left" "top" c)) canvas (piece-positions piece))) ;; draw the board (without any pieces or tiles) (define (draw-board) (define board-width (* tile-size board-width-tiles)) (define board-height (* tile-size board-height-tiles)) (define offsets (stream-map #{* tile-size} (in-naturals))) (define (for-offsets board max-val action) (for/fold ([bg board]) ([val offsets] #:break (> val max-val)) (action bg val))) (~> (gradient-rect board-width board-height board-bgcolor) (for-offsets board-width (λ(board x) (add-line board x 0 x board-height board-grid-color))) (for-offsets board-height (λ(board y) (add-line board 0 y board-width y board-grid-color))))) ;; paint the tiles listed in 'row' at y offset based on 'row-idx' (define (paint-row board row row-idx) (define y (- (image-height board) (* tile-size row-idx))) (for/fold ([cur-board board]) ([cell-value row] [col-idx (in-naturals)]) (cond [(image-color? cell-value) (define x (* tile-size col-idx)) (place-image/align (block-tile cell-value) x y "left" "top" cur-board)] [else cur-board]))) (define board-bg (freeze (draw-board))) ;; paint a board with all the tiles as described by 'board-st' (define (paint-board board-st) (for/fold ([board board-bg]) ([row board-st] [row-idx (in-naturals)]) (paint-row board row (- (length board-st) row-idx))))
true
d1cdc893cf7ba6d2425bac8099f26cc748a48623
fc6465100ab657aa1e31af6a4ab77a3284c28ff0
/results/all/stlc-sub-3-enum.rktd
e2c3ffb941e87ac7e1912bdcf3166683c9ecfdf1
[]
no_license
maxsnew/Redex-Enum-Paper
f5ba64a34904beb6ed9be39ff9a5e1e5413c059b
d77ec860d138cb023628cc41f532dd4eb142f15b
refs/heads/master
2020-05-21T20:07:31.382540
2017-09-04T14:42:13
2017-09-04T14:42:13
17,602,325
0
0
null
null
null
null
UTF-8
Racket
false
false
16,212
rktd
stlc-sub-3-enum.rktd
(start 2015-06-21T19:45:22 (#:model "stlc-sub-3" #:type enum)) (counterexample 2015-06-21T19:57:07 (#:model "stlc-sub-3" #:type enum #:counterexample (λ (ᢝ ((list int) → ((int → int) → ((int → int) → (int → int))))) ((λ (a int) (cons a)) 544)) #:iterations 58080 #:time 704354)) (new-average 2015-06-21T19:57:07 (#:model "stlc-sub-3" #:type enum #:average 704353.0 #:stderr +nan.0)) (counterexample 2015-06-21T20:09:47 (#:model "stlc-sub-3" #:type enum #:counterexample (λ (٭ ((int → ((list int) → (list int))) → ((int → int) → (int → (list int))))) ((λ (a int) (cons a)) 118)) #:iterations 57202 #:time 760057)) (new-average 2015-06-21T20:09:47 (#:model "stlc-sub-3" #:type enum #:average 732205.0 #:stderr 27852.0)) (counterexample 2015-06-21T20:20:37 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (i int) (hd nil)) -389040) #:iterations 49740 #:time 649801)) (new-average 2015-06-21T20:20:37 (#:model "stlc-sub-3" #:type enum #:average 704737.0 #:stderr 31828.744744334483)) (counterexample 2015-06-21T20:24:15 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) 45) #:iterations 15476 #:time 217559)) (new-average 2015-06-21T20:24:15 (#:model "stlc-sub-3" #:type enum #:average 582942.5 #:stderr 123856.50861480797)) (counterexample 2015-06-21T20:52:57 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) -3) #:iterations 126634 #:time 1722169)) (new-average 2015-06-21T20:52:57 (#:model "stlc-sub-3" #:type enum #:average 810787.8 #:stderr 247220.02663182444)) (counterexample 2015-06-21T21:08:54 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) -709) #:iterations 72380 #:time 957660)) (new-average 2015-06-21T21:08:54 (#:model "stlc-sub-3" #:type enum #:average 835266.5 #:stderr 203333.14486063668)) (counterexample 2015-06-21T21:26:28 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) -181) #:iterations 77602 #:time 1054984)) (new-average 2015-06-21T21:26:28 (#:model "stlc-sub-3" #:type enum #:average 866654.7142857143 #:stderr 174690.9021128072)) (counterexample 2015-06-21T21:37:48 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) 44) #:iterations 53940 #:time 679820)) (new-average 2015-06-21T21:37:48 (#:model "stlc-sub-3" #:type enum #:average 843300.375 #:stderr 153078.76607881332)) (counterexample 2015-06-21T21:45:13 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) 56) #:iterations 31107 #:time 445211)) (new-average 2015-06-21T21:45:13 (#:model "stlc-sub-3" #:type enum #:average 799068.2222222222 #:stderr 142064.1914471117)) (counterexample 2015-06-21T21:47:10 (#:model "stlc-sub-3" #:type enum #:counterexample (λ (̴ ((int → ((list int) → (list int))) → ((int → (list int)) → (int → int)))) ((λ (a int) (cons a)) -57)) #:iterations 8125 #:time 116495)) (new-average 2015-06-21T21:47:10 (#:model "stlc-sub-3" #:type enum #:average 730810.9 #:stderr 144238.8631061877)) (counterexample 2015-06-21T22:10:29 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) -2094) #:iterations 102109 #:time 1399514)) (new-average 2015-06-21T22:10:29 (#:model "stlc-sub-3" #:type enum #:average 791602.0909090909 #:stderr 143936.5088834439)) (counterexample 2015-06-21T22:59:46 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) 17) #:iterations 226453 #:time 2958434)) (new-average 2015-06-21T22:59:46 (#:model "stlc-sub-3" #:type enum #:average 972171.4166666667 #:stderr 223316.0247179774)) (counterexample 2015-06-21T23:03:06 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) 425) #:iterations 15821 #:time 199357)) (new-average 2015-06-21T23:03:06 (#:model "stlc-sub-3" #:type enum #:average 912724.1538461539 #:stderr 213849.73473361862)) (counterexample 2015-06-21T23:29:53 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) 91) #:iterations 125724 #:time 1608416)) (new-average 2015-06-21T23:29:53 (#:model "stlc-sub-3" #:type enum #:average 962416.4285714286 #:stderr 204127.23953646433)) (counterexample 2015-06-21T23:37:09 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) 75) #:iterations 36537 #:time 436135)) (new-average 2015-06-21T23:37:09 (#:model "stlc-sub-3" #:type enum #:average 927331.0000000001 #:stderr 193243.8698364865)) (counterexample 2015-06-22T00:05:06 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) ((λ (a int) a) a)) -308) #:iterations 127820 #:time 1678886)) (new-average 2015-06-22T00:05:06 (#:model "stlc-sub-3" #:type enum #:average 974303.1875000001 #:stderr 186766.37940015728)) (counterexample 2015-06-22T00:07:14 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) 73) #:iterations 8794 #:time 128106)) (new-average 2015-06-22T00:07:14 (#:model "stlc-sub-3" #:type enum #:average 924526.8823529413 #:stderr 182361.27306454)) (counterexample 2015-06-22T00:23:43 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) -48) #:iterations 71170 #:time 989315)) (new-average 2015-06-22T00:23:43 (#:model "stlc-sub-3" #:type enum #:average 928126.2222222224 #:stderr 171969.52848210224)) (counterexample 2015-06-22T01:06:25 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) 2828) #:iterations 195258 #:time 2563437)) (new-average 2015-06-22T01:06:25 (#:model "stlc-sub-3" #:type enum #:average 1014195.210526316 #:stderr 184033.65861399192)) (counterexample 2015-06-22T01:08:01 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) ((λ (a int) a) a)) -384) #:iterations 6813 #:time 96452)) (new-average 2015-06-22T01:08:01 (#:model "stlc-sub-3" #:type enum #:average 968308.0500000002 #:stderr 180519.19635798867)) (counterexample 2015-06-22T01:30:44 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) 38) #:iterations 105932 #:time 1363434)) (new-average 2015-06-22T01:30:44 (#:model "stlc-sub-3" #:type enum #:average 987123.5714285716 #:stderr 172735.81887905303)) (counterexample 2015-06-22T02:21:36 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) -60) #:iterations 232811 #:time 3053634)) (new-average 2015-06-22T02:21:36 (#:model "stlc-sub-3" #:type enum #:average 1081055.8636363638 #:stderr 189600.69571019287)) (counterexample 2015-06-22T02:26:00 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) ((λ (a int) a) a)) 148) #:iterations 21205 #:time 264225)) (new-average 2015-06-22T02:26:00 (#:model "stlc-sub-3" #:type enum #:average 1045541.4782608696 #:stderr 184617.83631474245)) (counterexample 2015-06-22T02:43:58 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) -32) #:iterations 79366 #:time 1078178)) (new-average 2015-06-22T02:43:58 (#:model "stlc-sub-3" #:type enum #:average 1046901.3333333334 #:stderr 176763.35187917313)) (counterexample 2015-06-22T02:48:58 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) 30) #:iterations 22280 #:time 300414)) (new-average 2015-06-22T02:48:58 (#:model "stlc-sub-3" #:type enum #:average 1017041.8400000001 #:stderr 172154.72489675944)) (counterexample 2015-06-22T02:58:00 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) -32) #:iterations 39390 #:time 542449)) (new-average 2015-06-22T02:58:00 (#:model "stlc-sub-3" #:type enum #:average 998788.2692307694 #:stderr 166405.08929141797)) (counterexample 2015-06-22T03:24:17 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) -16) #:iterations 128171 #:time 1577514)) (new-average 2015-06-22T03:24:17 (#:model "stlc-sub-3" #:type enum #:average 1020222.5555555557 #:stderr 161551.61044040072)) (counterexample 2015-06-22T03:44:35 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) ((λ (a int) a) a)) 409) #:iterations 86176 #:time 1218460)) (new-average 2015-06-22T03:44:35 (#:model "stlc-sub-3" #:type enum #:average 1027302.4642857144 #:stderr 155835.9367075593)) (counterexample 2015-06-22T03:57:37 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) ((λ (a int) cons) a)) 2610) #:iterations 53800 #:time 781597)) (new-average 2015-06-22T03:57:37 (#:model "stlc-sub-3" #:type enum #:average 1018829.8620689657 #:stderr 150604.80624268227)) (counterexample 2015-06-22T04:06:48 (#:model "stlc-sub-3" #:type enum #:counterexample (λ (̪ ((int → ((list int) → int)) → (list int))) ((λ (a int) (cons a)) 74)) #:iterations 38468 #:time 550920)) (new-average 2015-06-22T04:06:48 (#:model "stlc-sub-3" #:type enum #:average 1003232.8666666668 #:stderr 146331.65555710133)) (counterexample 2015-06-22T04:47:20 (#:model "stlc-sub-3" #:type enum #:counterexample (λ (ɐ ((int → (int → (int → int))) → ((list int) → (list int)))) ((λ (a int) (cons a)) -57)) #:iterations 174021 #:time 2432198)) (new-average 2015-06-22T04:47:20 (#:model "stlc-sub-3" #:type enum #:average 1049328.5161290325 #:stderr 148849.8621153433)) (counterexample 2015-06-22T05:01:42 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) -79) #:iterations 70530 #:time 862588)) (new-average 2015-06-22T05:01:42 (#:model "stlc-sub-3" #:type enum #:average 1043492.8750000002 #:stderr 144241.3552640461)) (counterexample 2015-06-22T05:26:59 (#:model "stlc-sub-3" #:type enum #:counterexample (λ (ȍ ((int → (int → (list int))) → (int → (int → int)))) ((λ (a int) (cons a)) -46)) #:iterations 115387 #:time 1517781)) (new-average 2015-06-22T05:26:59 (#:model "stlc-sub-3" #:type enum #:average 1057865.2424242427 #:stderr 140538.92686435903)) (counterexample 2015-06-22T05:59:01 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) 281) #:iterations 138220 #:time 1922236)) (new-average 2015-06-22T05:59:01 (#:model "stlc-sub-3" #:type enum #:average 1083287.911764706 #:stderr 138692.70844858632)) (counterexample 2015-06-22T06:29:25 (#:model "stlc-sub-3" #:type enum #:counterexample (λ (Ȗ (((int → (list int)) → int) → (((list int) → int) → (int → int)))) ((λ (a int) (cons a)) 52)) #:iterations 136178 #:time 1825284)) (new-average 2015-06-22T06:29:25 (#:model "stlc-sub-3" #:type enum #:average 1104487.8 #:stderr 136330.1934460348)) (counterexample 2015-06-22T06:59:43 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) 28) #:iterations 135810 #:time 1819362)) (new-average 2015-06-22T06:59:43 (#:model "stlc-sub-3" #:type enum #:average 1124345.4166666667 #:stderr 133969.00903646223)) (counterexample 2015-06-22T07:14:28 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) -22) #:iterations 63196 #:time 884934)) (new-average 2015-06-22T07:14:28 (#:model "stlc-sub-3" #:type enum #:average 1117874.8378378379 #:stderr 130458.49177518503)) (counterexample 2015-06-22T07:17:39 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) 15) #:iterations 15884 #:time 190829)) (new-average 2015-06-22T07:17:39 (#:model "stlc-sub-3" #:type enum #:average 1093478.8947368423 #:stderr 129301.2810065094)) (counterexample 2015-06-22T07:25:23 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) -8) #:iterations 32129 #:time 464795)) (new-average 2015-06-22T07:25:23 (#:model "stlc-sub-3" #:type enum #:average 1077358.794871795 #:stderr 126969.69496633318)) (counterexample 2015-06-22T07:49:27 (#:model "stlc-sub-3" #:type enum #:counterexample (λ (ռ (((int → int) → (int → int)) → (((list int) → (list int)) → ((list int) → int)))) ((λ (a int) (cons a)) -69)) #:iterations 99258 #:time 1443139)) (new-average 2015-06-22T07:49:27 (#:model "stlc-sub-3" #:type enum #:average 1086503.3 #:stderr 124092.14415865041)) (counterexample 2015-06-22T07:52:06 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) 42) #:iterations 12946 #:time 158959)) (new-average 2015-06-22T07:52:06 (#:model "stlc-sub-3" #:type enum #:average 1063880.268292683 #:stderr 123123.91275167854)) (counterexample 2015-06-22T07:55:46 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) -84) #:iterations 15367 #:time 220235)) (new-average 2015-06-22T07:55:46 (#:model "stlc-sub-3" #:type enum #:average 1043793.4761904762 #:stderr 121824.03808885325)) (counterexample 2015-06-22T08:14:32 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) -194) #:iterations 82482 #:time 1126108)) (new-average 2015-06-22T08:14:32 (#:model "stlc-sub-3" #:type enum #:average 1045707.7674418605 #:stderr 118972.59020659354)) (counterexample 2015-06-22T08:31:14 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) 80) #:iterations 89634 #:time 1002807)) (new-average 2015-06-22T08:31:14 (#:model "stlc-sub-3" #:type enum #:average 1044732.75 #:stderr 116241.31172382292)) (counterexample 2015-06-22T08:53:25 (#:model "stlc-sub-3" #:type enum #:counterexample (λ (ऊ (((int → int) → (list int)) → (((list int) → (list int)) → (int → (int → int))))) ((λ (a int) (cons a)) -21)) #:iterations 99793 #:time 1331194)) (new-average 2015-06-22T08:53:25 (#:model "stlc-sub-3" #:type enum #:average 1051098.5555555555 #:stderr 113806.98927194673)) (counterexample 2015-06-22T08:58:21 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) -1763) #:iterations 21491 #:time 295741)) (new-average 2015-06-22T08:58:21 (#:model "stlc-sub-3" #:type enum #:average 1034677.7391304347 #:stderr 112510.18729425712)) (counterexample 2015-06-22T09:16:05 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) -108) #:iterations 86750 #:time 1064354)) (new-average 2015-06-22T09:16:05 (#:model "stlc-sub-3" #:type enum #:average 1035309.1489361702 #:stderr 110092.14118730008)) (counterexample 2015-06-22T09:23:45 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (v int) ((λ (a (list int)) cons) nil)) -249229) #:iterations 44042 #:time 460914)) (new-average 2015-06-22T09:23:45 (#:model "stlc-sub-3" #:type enum #:average 1023342.5833333333 #:stderr 108436.46340398862)) (counterexample 2015-06-22T09:25:27 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) -30) #:iterations 9379 #:time 101266)) (new-average 2015-06-22T09:25:27 (#:model "stlc-sub-3" #:type enum #:average 1004524.6938775509 #:stderr 107854.72705018889)) (counterexample 2015-06-22T10:05:42 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (λ (b int) (cons a))) -438199) #:iterations 227690 #:time 2417519)) (new-average 2015-06-22T10:05:42 (#:model "stlc-sub-3" #:type enum #:average 1032784.5799999998 #:stderr 109389.0196721851)) (counterexample 2015-06-22T10:17:59 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) ((λ (a int) a) a)) -394) #:iterations 63696 #:time 737994)) (new-average 2015-06-22T10:17:59 (#:model "stlc-sub-3" #:type enum #:average 1027004.3725490194 #:stderr 107378.37390661212)) (counterexample 2015-06-22T10:26:08 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) -110) #:iterations 39299 #:time 488899)) (new-average 2015-06-22T10:26:08 (#:model "stlc-sub-3" #:type enum #:average 1016656.1923076921 #:stderr 105800.44446298362)) (counterexample 2015-06-22T10:31:03 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) 894) #:iterations 25906 #:time 295525)) (new-average 2015-06-22T10:31:03 (#:model "stlc-sub-3" #:type enum #:average 1003049.9433962263 #:stderr 104673.1054262232)) (counterexample 2015-06-22T10:58:03 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) (cons a)) -61) #:iterations 129645 #:time 1620762)) (new-average 2015-06-22T10:58:03 (#:model "stlc-sub-3" #:type enum #:average 1014489.0555555554 #:stderr 103351.42722188758)) (counterexample 2015-06-22T11:24:31 (#:model "stlc-sub-3" #:type enum #:counterexample ((λ (a int) ((λ (a int) a) a)) -282) #:iterations 128634 #:time 1588872)) (new-average 2015-06-22T11:24:31 (#:model "stlc-sub-3" #:type enum #:average 1024932.3818181816 #:stderr 101990.98859079133)) (finished 2015-06-22T11:24:31 (#:model "stlc-sub-3" #:type enum #:time-ms 56371293 #:attempts 4331751 #:num-counterexamples 55 #:rate-terms/s 76.84320812013306 #:attempts/cexp 78759.10909090909))
false
19cff2ece33d05cb99e0d4c62369b62d9fb50e17
eb48ced56feaf37d1f1439589894353a5d0a50f8
/cKanren/src/constraints.rkt
5f0e5cddf69d341d56755023bdd13638b349c47a
[ "MIT" ]
permissive
ReinoutStevens/cKanren
f40eaad090865f4b326d35e4f90738ff985aefbb
b388b60c5487bce1d0ea84a0149347197e80643a
refs/heads/master
2020-12-27T09:13:45.121481
2013-09-08T22:31:39
2013-09-08T22:31:51
null
0
0
null
null
null
null
UTF-8
Racket
false
false
1,439
rkt
constraints.rkt
#lang racket (require "helpers.rkt" "package.rkt") (provide (all-defined-out)) ;; == CONSTRAINTS ============================================================== (struct constraint (fn) #:property prop:procedure (struct-field-index fn) #:methods gen:custom-write ([define (write-proc goal port mode) ((parse-mode mode) "#<constraint>" port)])) ;; splitting up the package (define-syntax lambdam@/private (syntax-rules (:) [(_ (a) e ...) (constraint (lambda (a) e ...))] [(_ (a : s c q t) e ...) (lambdam@/private (a) (let ([s (a-s a)] [c (a-c a)] [q (a-q a)] [t (a-t a)]) e ...))])) (define-syntax lambdam@ (syntax-rules (:) [(_ (a) e ...) (lambdam@/private (a) e ...)] [(_ (a : s) e ...) (lambdam@/private (a) (let ([s (substitution-s (a-s a))]) e ...))] [(_ (a : s c) e ...) (lambdam@/private (a) (let ([s (substitution-s (a-s a))] [c (constraint-store-c (a-c a))]) e ...))])) ;; the identity constraint (define identitym (lambdam@ (a) a)) ;; the simplest failing constraint (define mzerom (lambdam@ (a) #f)) ;; applies a constraint to a package (define (bindm a fm) (fm a)) ;; composes two constraints together (define (composem . fm*) (lambdam@ (a) (cond [(null? fm*) a] [((car fm*) a) => (apply composem (cdr fm*))] [else #f])))
true
394926437c4cfb0035d2a102f11ae0b44c902b40
14be9e4cde12392ebc202e69ae87bbbedd2fea64
/CSC488/assignments/a2/A2.X2.rkt
bb687f51824f55dba288a4cc8b9870155b893146
[ "LicenseRef-scancode-unknown-license-reference", "GLWTPL" ]
permissive
zijuzhang/Courses
948e9d0288a5f168b0d2dddfdf825b4ef4ef4e1e
71ab333bf34d105a33860fc2857ddd8dfbc8de07
refs/heads/master
2022-01-23T13:31:58.695290
2019-08-07T03:13:09
2019-08-07T03:13:09
null
0
0
null
null
null
null
UTF-8
Racket
false
false
31,143
rkt
A2.X2.rkt
#lang racket #| Compile A2's Language L2 to Language X2 |# #| reference: https://cs.brown.edu/courses/cs033/docs/guides/x64_cheatsheet.pdf |# (provide L2→X2 Mac? heap-size postamble) (require "A2.L1.rkt") (require "A2.L2.rkt") (require "A2.M0.rkt") (module+ test (require rackunit)) ; Whether to emit code for the Mac, that Apple's gcc wrapper for clang handles. |# (define Mac? (make-parameter #true)) ; Size of the heap. (define heap-size (make-parameter (/ (* 4 (expt 2 30)) 8))) ; 4G of 8-byte data. ; Code to append to main. ; ; If you put the resulting assembly code into a file file.s then the following postamble ; prints the execution time and lowest byte of the result to the console if run with: ; gcc -o file file.s ; time ./file ; echo $? ; (define postamble (make-parameter "movq %rcx, %rax")) ; Return result. #| X2 == Language X2 is a subset of 64-bit x86 assembly language, which we'll emit in the AT&T syntax. Details are in the rest of this file. |# #| Machine Model ============= Our current model of execution has a few global variables, which are frequently accessed and updated, and a stack with frequent stack-like operations. Many machine architectures provide the following model, and optimize for this pattern of use. The Model --------- Program: a sequence of statements. Execution: sequential, except after a statement that explicitly sets the current statement address. State: a fixed set of global variables, a stack, a large array, and a current statement address. |# #| Global Variables ================ The global variables in a CPU are called registers. From our point of view the general purpose X2 registers are all interchangeable. We'll use: register : use -------------- a : temporary variable (accumulator) c : expression result (counter) 10 : next location to allocate in heap 11 : current environment In 64-bit x86 with the AT&T syntax we refer to them as %rax, %rcx, %r10, and %r11. The names are not meaningful so let's hide them. |# (define (register name) (~a '% name)) (define temp (register 'rax)) (define result (register 'rcx)) (define next (register 'r10)) (define env (register 'r11)) #| Setting and Accessing Registers =============================== |# (module+ test ; result = temp (check-equal? (movq temp result) "movq %rax, %rcx") ; result += temp (check-equal? (addq temp result) "addq %rax, %rcx")) (define (movq from to) (~a 'movq " " from ", " to)) (define (addq from to) (~a 'addq " " from ", " to)) (define (imulq from to) (~a 'imulq " " from ", " to)) #| Integer Constants ================= Integer constants are prefixed with "$". They can appear as ‘from’ in movq and addq. |# (module+ test ; temp = 488 (check-equal? (movq (constant 488) temp) "movq $488, %rax")) (define (constant i) (~a '$ i)) #| Addresses of Statements ======================= We can refer to the address of a statement by putting a label before the statement, and then use the label. In particular, we can change the execution order by jumping to a statement's address. We wont jump to [as opposed to call] stored locations, only explicit labels. To increase portability and flexibility, without much effort, we'll “mangle” labels by potentially adding an underscore [for the Mac's gcc wrapper around clang], and make them relative to the current instruction pointer [reasons and details aren't important for us] This does make them count as offset dereferences, and the limitation of the previous section applies. |# ; main() ; temp = make_add ; goto main #;(labelled 'main (movq (label-reference 'make_add) temp) (jmp 'main)) (define (mangle name) (~a (if (Mac?) '_ "") name)) (define (labelled name . lines) (list (~a (mangle name) ':) lines)) (define (label-reference name) (~a (mangle name) "@GOTPCREL(%rip)")) (define (jmp-label name) (~a 'jmp " " (mangle name))) #| The Stack ========= We can push a value [constant, or contents of a register], and pop a value into a register. Also, we can “call” a statement address [see “Addresses of Statements” below] that's stored in a register, which: 1. Pushes the address of the statement that follows the call. 2. Jumps to the address that's in the register. Coversely, we can “return”, which pops an address that's stored on the stack and jumps to it. |# (define (pushq from) (~a 'pushq " " from)) (define (popq to) (~a 'popq " " to)) (define (callq from) (~a 'call " *(" from ")")) (define (retq) (~a 'retq)) #| Dereferencing and Pointer Arithmetic ==================================== We'll store 64-bit data in our heap: the nth piece of data at an address is 8×n bytes after it. We can dereference a register containing an address, with an optional offset. Most ‘from’s or ‘to’s in the statements we're using can be a dereference, but not at the same time in a single statement. |# (module+ test ; result = temp[0] (check-equal? (movq (★ temp) result) "movq 0(%rax), %rcx") ; result[488] = temp (check-equal? (movq temp (★ result 488)) "movq %rax, 3904(%rcx)")) (define (⊕ offset) (* 8 offset)) (define (★ register [offset 0]) (~a (⊕ offset) "(" register ")")) #| Conditional Execution ===================== We can jump to an address conditionally, in particular on condition that two values are equal. Comparison sets a CPU flag, that various jump instructions react to. For comparison to a constant, the constant must be the first argument. We wont jump to calculated locations, only explicit labels. |# ; if (temp == result) goto main #;(list (cmpq temp result) (je 'main)) (define (cmpq from-1 from-2) (~a 'cmpq " " from-1 ", " from-2)) (define (je-label name) (~a 'je " " (mangle name))) #| L2 Statement to X2 ================== Implement the seven functions needed to translate an L2 statement to an X2 statement or [possibly nested] list of statements. The nesting of the list structure is irrelevant: L2→X2 will flatten the results. |# #| set_result: movq %rdi, result(%rip) push: movq top(%rip), %rax movq %rdi, (%rax) addq $8, top(%rip) ret |# (module+ test ; set_result (check-equal? (set_result 12) '("movq $12, %rcx")) ; push_result (check-equal? (push_result) '("pushq %rcx")) ; closure (check-equal? (closure 'make_add) '("movq _make_add@GOTPCREL(%rip), %rax" "movq %rax, 0(%r10)" "movq %r11, 8(%r10)" "movq %r10, %rcx" "addq $16, %r10")) ; call (check-equal? (call) '("popq %rax" "pushq %r11" "movq 8(%rax), %r11" "movq %r11, 0(%r10)" "movq %rcx, 8(%r10)" "movq %r10, %r11" "addq $16, %r10" "call *(%rax)" "popq %r11")) ; variable (check-equal? (variable 0) '("movq %r11, %rax" "movq 8(%rax), %rcx")) (check-equal? (variable 3) '("movq %r11, %rax" "movq 0(%rax), %rax" "movq 0(%rax), %rax" "movq 0(%rax), %rax" "movq 8(%rax), %rcx")) ; set (check-equal? (set 0) '("movq %r11, %rax" "movq %rcx, 8(%rax)")) (check-equal? (set 3) '("movq %r11, %rax" "movq 0(%rax), %rax" "movq 0(%rax), %rax" "movq 0(%rax), %rax" "movq %rcx, 8(%rax)")) ; label, jump, jump_false (check-equal? (label 'main) '(("_main:" ()))) (check-equal? (jump 'main) '("jmp _main")) (check-equal? (jump_false 'main) '("cmpq $0, %rcx" "je _main")) ) (define (l2→X2 l2) (match l2 [`(L2: set_result ,<i>) (set_result <i>)] [`(L2: push_result) (push_result)] [`(L2: closure ,<name>) (closure <name>)] [`(L2: call) (call)] [`(L2: variable ,<n>) (variable <n>)] [`(L2: set ,<n>) (set <n>)] [`(L2: label ,<name>) (label <name>)] [`(L2: jump ,<name>) (jump <name>)] [`(L2: jump_false ,<name>) (jump_false <name>)])) ; Set result to integer i. (define (set_result i) `(,(movq (constant i) result))) ; Push result onto the stack. (define (push_result) `(,(pushq result))) ; Put a closure on the heap. ; A closure is a pair of body address and an env. ; The closure is put at the address referred to by next, and then next is adjusted ; to point to the next place to put a pair. (define (closure name) `(,(movq (label-reference name) temp) ,(movq temp (★ next)) ,(movq env (★ next 1)) ,(movq next result) ; save pointer to closure to result, not sure if needed as of now ,(addq (constant 16) next))) ; Call the closure that's on the stack, with the argument that's in result. ; Temporarily stores env on the stack. ; Sets env to a new environment containing the closure's environment and the argument. ; Calls the closure. (define (call) `( ; void** f = pop(); push(env); ,(popq temp) ,(pushq env) ; env = environment(f[1], result); ,(movq (★ temp 1) env) ; env = closure-env ,(movq env (★ next)) ; putting (env, result) on heap ,(movq result (★ next 1)) ,(movq next env) ; env = ptr to newly created env ,(addq (constant 16) next) ; ((void(*)())(f[0]))(); ,(callq temp) ; env = pop(); ,(popq env))) ; Puts the value of the variable n levels up from env, into result. ; To “loop” n times: emits n statements. (define (variable n) (append `(,(movq env temp)) (for/list [(i n)] (movq (★ temp) temp)) `(,(movq (★ temp 1) result)))) ; Sets the variable n levels up from env, to the value of result. ; To “loop” n times: emits n statements. (define (set n) (append `(,(movq env temp)) (for/list [(i n)] (movq (★ temp) temp)) `(,(movq result (★ temp 1))))) ; Names the current statement address. (define (label name) `(,(labelled name))) ; Jumps to a named statement address. (define (jump name) `(,(jmp-label name))) ; Jumps to a named statement address, if result is false. ; False is represented by 0. (define (jump_false name) `(,(cmpq (constant 0) result) ,(je-label name))) #| L2 to X2 ======== |# (define (L2→X2 compiled) (match-define (compiled:L2 code λs) compiled) (map (curryr ~a "\n") ; same as curry, but args collected in opposite direction (flatten (list (~a '.globl " " (mangle 'main)) RTL (map λ→X2 λs) (labelled 'main (movq (label-reference 'heap) next) (map l2→X2 code) (postamble) (retq)) (~a '.comm " " (mangle 'heap) "," (heap-size) "," (if (Mac?) 4 32)))))) ; For a compiled λ from L2: the code for its body, including a return, labelled by the name of the λ. (define (λ→X2 a-λ) (labelled (first a-λ) (map l2→X2 (second a-λ)) (retq))) #| Runtime Library =============== |# ; Addition and Multiplication ; --------------------------- ; Roughly, we've been treating addition as if it's: #;(define + (λ_make_add (variable_1) (λ_add (variable_0) (primitive-addition variable_0 variable_1)))) ; L1→L2 translates ‘+’ to a statement that creates a make_add closure. (module+ test (check-equal? (L1→L2 '(L1: var +)) (compiled:L2 '((L2: closure make_add)) '()))) #| void add() { variable(1); long long temp = (long long)result; variable(0); result = (void*)(temp + (long long)result); } void make_add() { closure(add); } |# ; Put X2 versions of make_add and add in RTL below. ; Similarly, find the 64-bit x86 instruction for multiplication, and add multiplication. (module+ test (check-equal? (flatten add) '("_add:" "movq %r11, %rax" "movq 0(%rax), %rax" "movq 8(%rax), %rcx" "pushq %rcx" "movq %r11, %rax" "movq 8(%rax), %rcx" "popq %rax" "addq %rax, %rcx" "retq")) (check-equal? (flatten make_add) '("_make_add:" "movq _add@GOTPCREL(%rip), %rax" "movq %rax, 0(%r10)" "movq %r11, 8(%r10)" "movq %r10, %rcx" "addq $16, %r10" "retq")) ) (define add (labelled 'add (variable 1) (pushq result) (variable 0) (popq temp) (addq temp result) (retq))) (define make_add (labelled 'make_add (closure 'add) (retq))) (define multiply (labelled 'multiply (variable 1) (pushq result) (variable 0) (popq temp) (imulq temp result) (retq))) (define make_multiply (labelled 'make_multiply (closure 'multiply) (retq))) ; Escape Continuations ; -------------------- ; The continuation of an expression is: ; ; The state of the heap, and the stack and env before the expression begins evaluating, ; and the address of the statement after the expression's statements, with that statement ; waiting to work with the result. ; Write out the compilation of (call/ec f) to convince yourself that the continuation of ; that expression is on the stack. And convince yourself that setting the result to v ; and executing a return with the stack in that state continues as if the value of ; (call/ec f) is v [and any side-effects until then are in the heap and persist]. ; (call/ec f) calls f with an escape continuation k, where (k v) escapes the evaluation ; of (call/ec f) to produce v. Roughly, we treat call/ec as: #;(λ_call_ec (f) (f ((λ_make_ec (saved-stack-pointer) (λ_ec (result) (set! stack-pointer saved-stack-pointer) result)) stack-pointer))) ; The CPU's stack pointer is a register: (define stack-pointer (register 'rsp)) (define ec (labelled 'ec (variable 1) (movq result stack-pointer) (variable 0) (retq))) (define make_ec (labelled 'make_ec (closure 'ec) (retq))) (define call_ec (labelled 'call_ec (variable 0) (push_result) ; stack: [f] (closure 'make_ec) (push_result) ; stack: [f make_ec] (movq stack-pointer result) (call) ; (make_ec stack-pointer) now stack: [f] (call) ; (f result) (retq))) ; A2's L1→L2 translates ‘call/ec’ to a statement that creates a call_ec closure. (module+ test (check-equal? (L1→L2 '(L1: var call/ec)) (compiled:L2 '((L2: closure call_ec)) '()))) ; Put X2 versions of less than. ; Roughly, we've been treating “less than” as if it's: #;(define < (λ_make_less_than (variable_1) (λ_less_than (variable_0) (primitive-less-than variable_1 variable_0)))) ; L1→L2 translates ‘<’ to a statement that creates a make_less_than closure. (module+ test (check-equal? (L1→L2 '(L1: var <)) (compiled:L2 '((L2: closure make_less_than)) '()))) ; The CPU flags set by a comparison can be stored as a byte, which we then “widen” to a 64 bit value. ; if result < temp ; result = 1 ; else ; result = 0 #;(list (cmpq temp result) (setl result-byte) (movzbq result-byte result)) (define (setl to) (~a 'setb " " to)) (define result-byte (register 'cl)) (define (movzbq from-1 from-2) (~a 'movzbq " " from-1 ", " from-2)) ; Put X2 versions of make_less_than and less_than in RTL below. (define less_than (labelled 'less_than (variable 1) (pushq result) (variable 0) (popq temp) ; temp = variable_1 result = variable_0 (cmpq result temp) (setl result-byte) (movzbq result-byte result) (retq))) (define make_less_than (labelled 'make_less_than (closure 'less_than) (retq))) (define RTL `(,add ,make_add ,multiply ,make_multiply ,call_ec ,make_ec ,ec ,less_than ,make_less_than)) ; 200 (define app-testcase '(L1: app (L1: λ 0 (L1: var 0)) (L1: datum 200))) ; 36 (define add-testcase '(L1: app (L1: app (L1: var +) (L1: datum 12)) (L1: datum 24))) #;(+ 1 (call/ec (λ (k) 100))) ; output 101 (define callec-testcase '(L1: app (L1: app (L1: var +) (L1: datum 1)) (L1: app (L1: var call/ec) (L1: λ 0 (L1: datum 100))))) #;(+ 1 (call/ec (λ (k) (k 10)))) ; output 11 (define callec2-testcase '(L1: app (L1: app (L1: var +) (L1: datum 1)) (L1: app (L1: var call/ec) (L1: λ 0 (L1: app (L1: var 0) (L1: datum 10)))))) #;(+ 1 (+ 1 (call/ec (λ (k) (k 10))))) ; output 12 (define callec4-testcase '(L1: app (L1: app (L1: var +) (L1: datum 1)) (L1: app (L1: var call/ec) (L1: λ 0 (L1: app (L1: var 0) (L1: datum 10)))))) #;(+ 15 (call/ec (λ (k) (+ 3 (k 16))))) ; output 30 (define callec3-testcase '(L1: app (L1: app (L1: var +) (L1: datum 14)) (L1: app (L1: var call/ec) (L1: λ 0 (L1: app (L1: app (L1: var +) (L1: datum 3)) (L1: app (L1: var 0) (L1: datum 16))))))) #; (< 10 11) ; 1 (define lessthan1-testcase '(L1: app (L1: app (L1: var <) (L1: datum 10)) (L1: datum 11))) #; (< 10 10) ; 0 (define lessthan2-testcase '(L1: app (L1: app (L1: var <) (L1: datum 10)) (L1: datum 10))) #; (< 10 9) ; 0 (define lessthan3-testcase '(L1: app (L1: app (L1: var <) (L1: datum 10)) (L1: datum 9))) (define fib-testcase '(local [(define (fib n) (cond [(= n 1) 1] [(= n 2) 1] [else (+ (fib (- n 1)) (fib (- n 2)))]))] (fib 13))) (define add2-testcase '(< 10 2)) ; 0 (define out (open-output-file "file.s" #:exists 'replace)) (define assembly (L2→X2 (L1→L2 (L0→L1 (M0→L0 fib-testcase))))) (map (λ (x) (display x out)) assembly) (close-output-port out) (module+ test (check-equal? (L0→L1 (M0→L0 fib-testcase)) '(L1: app (L1: app (L1: app (L1: app (L1: app (L1: app (L1: λ 24 (L1: λ 23 (L1: λ 22 (L1: λ 21 (L1: λ 20 (L1: λ 19 (L1: app (L1: λ 17 (L1: app (L1: λ 14 (L1: app (L1: λ 12 (L1: app (L1: λ 9 (L1: app (L1: λ 6 (L1: app (L1: λ 3 (L1: app (L1: λ 2 (L1: app (L1: λ 0 (L1: app (L1: var 1) (L1: datum 13))) (L1: set! 0 (L1: λ 1 (L1: if 0 (L1: app (L1: app (L1: var 8) (L1: var 0)) (L1: datum 1)) (L1: datum 1) (L1: if 1 (L1: app (L1: app (L1: var 8) (L1: var 0)) (L1: datum 2)) (L1: datum 1) (L1: app (L1: app (L1: var +) (L1: app (L1: var 1) (L1: app (L1: app (L1: var 12) (L1: var 0)) (L1: datum 1)))) (L1: app (L1: var 1) (L1: app (L1: app (L1: var 12) (L1: var 0)) (L1: datum 2)))))))))) (L1: datum 0))) (L1: set! 5 (L1: λ 5 (L1: λ 4 (L1: if 2 (L1: app (L1: app (L1: var 8) (L1: var 1)) (L1: var 0)) (L1: if 3 (L1: app (L1: var 12) (L1: app (L1: app (L1: var 9) (L1: var 1)) (L1: var 0))) (L1: datum 1) (L1: datum 0)) (L1: datum 0))))))) (L1: set! 5 (L1: λ 8 (L1: λ 7 (L1: app (L1: var 11) (L1: app (L1: app (L1: var <) (L1: var 1)) (L1: var 0)))))))) (L1: set! 5 (L1: λ 11 (L1: λ 10 (L1: app (L1: app (L1: var <) (L1: var 0)) (L1: var 1))))))) (L1: set! 5 (L1: λ 13 (L1: app (L1: app (L1: var *) (L1: datum -1)) (L1: var 0)))))) (L1: set! 5 (L1: λ 16 (L1: λ 15 (L1: app (L1: app (L1: var +) (L1: var 1)) (L1: app (L1: var 6) (L1: var 0)))))))) (L1: set! 5 (L1: λ 18 (L1: if 4 (L1: var 0) (L1: datum 0) (L1: datum 1))))))))))) (L1: datum 0)) (L1: datum 0)) (L1: datum 0)) (L1: datum 0)) (L1: datum 0)) (L1: datum 0))) ) #;(provide T:*id* T:*datum* T:set! T:if T:λ T:*app* T:block T:let T:local T:cond T:when T:while T:breakable T:continuable T:returnable T:and T:or Ts ; List of all the transformations, defined after all of them. standard-library M0→L0)
false
b8e0968a12237169514804494c4e079225770dc9
757c8e01cab638a9c3b65166aa128f90a0e4dcc0
/Code/Benchmarks/test.rkt
138a217528ba257910c990f44cc8ae5d8cbe4781
[]
no_license
LuKuangChen/Towards-a-miniKanren-with-fair-search-strategies
d622b3b6f938e7331cd786bb72fe4056807e8a43
c586cb6067e367c4455b92fa3568f63c69c3cdc9
refs/heads/master
2023-07-12T12:50:01.243152
2019-12-13T20:07:01
2019-12-13T20:07:01
162,158,182
0
1
null
null
null
null
UTF-8
Racket
false
false
296
rkt
test.rkt
#lang racket ;(require "./mk-balanced-disj.rkt") (require "./mk-0.rkt") (defrel (nevero) (nevero)) (defrel (alwayso) (conde [succeed] [(alwayso)])) (length (run 10000000 q (conde [(nevero)] [(nevero)] [(nevero)] [(nevero)] [(nevero)] [(alwayso)])))
false
0923fe8374d3f80429f6ad7e30797dd48645e3f2
9986c7576749d6822dab17d156fe44703dac2581
/confit/jam/main.rkt
c45c5dd6e1382775c5ce352aa09fd65033671f94
[]
no_license
cdmistman/jam0001
3a162337f8d5e13bdb4b9a719590963182c1b297
0f5013a5f2d1edccf41ad2d49add2eb76084a5b7
refs/heads/main
2023-07-07T20:28:03.230345
2021-08-21T22:57:12
2021-08-21T22:57:12
398,348,057
0
2
null
2021-08-22T07:23:14
2021-08-20T17:07:07
Racket
UTF-8
Racket
false
false
206
rkt
main.rkt
#lang br/quicklang (require "parse.rkt") (module+ reader (provide read-syntax)) (define (read-syntax path port) (define parse-tree (parse port)) #`(module jam-mod jam/expander #,parse-tree))
false
c9c73b01bd7e253c0785ee37e0f354fa7dcecc8e
89b7353f1ab0aae0fe37b2f199ab4d6572defa62
/scribblings/numerics/functions/elliptic-functions.scrbl
50376cb0ebdc31f7e1f10ac5063f767b90f7aa38
[ "MIT" ]
permissive
elplatt/mechanics
dcc16754ea1b74675e0e9f7e042cf556edfbfc27
f65242d4ad0872de7c321a1c9a8e04d9b17b9259
refs/heads/master
2022-06-26T06:47:56.588459
2020-05-01T20:29:25
2020-05-01T20:30:15
null
0
0
null
null
null
null
UTF-8
Racket
false
false
378
scrbl
elliptic-functions.scrbl
#lang scribble/manual @title{Elliptic Functions} This library exports utilities for working with @link["http://en.wikipedia.org/wiki/Elliptic_function"]{elliptic functions} and their inverses, the @link["http://en.wikipedia.org/wiki/Elliptic_integral"]{elliptic integrals} @local-table-of-contents[] @include-section["elliptic.scrbl"] @include-section["elliptic-flo.scrbl"]
false
2c6951307936caf1894661a2c01296cb75ced48a
5d87c34a13a83ae886332e97eabc2d6b1ae9bcd0
/user.rkt
89b832c028cc84e71aee26b230ff381605d08d2d
[]
no_license
taylskid/mkanren-talk
c228dff6ef38f8f3797ecff94b95518efab58282
6ff60ce8439a9eceb19fdfb0ac855960f8538e4c
refs/heads/master
2020-03-29T07:29:19.157556
2018-09-20T20:26:32
2018-09-20T20:30:36
149,666,796
0
0
null
null
null
null
UTF-8
Racket
false
false
2,152
rkt
user.rkt
#lang racket (require "mkanren.rkt") (provide (all-defined-out)) (define-syntax Zzz (syntax-rules () ((_ g) (lambda (s/c) (lambda () (g s/c)))))) (define-syntax conj+ (syntax-rules () ((_ g) (Zzz g)) ((_ g0 g ...) (conj (Zzz g0) (conj+ g ...))))) (define-syntax disj+ (syntax-rules () ((_ g) (Zzz g)) ((_ g0 g ...) (disj (Zzz g0) (disj+ g ...))))) (define-syntax conde (syntax-rules () ((_ (g0 g ...) ...) (disj+ (conj+ g0 g ...) ...)))) (define-syntax fresh (syntax-rules () ((_ () g0 g ...) (conj+ g0 g ...)) ((_ (x0 x ...) g0 g ...) (call/fresh (lambda (x0) (fresh (x ...) g0 g ...)))))) (define (pull s) (if (procedure? s) (pull (s)) s)) (define (take-all s) (let ((s (pull s))) (if (null? s) '() (cons (car s) (take-all (cdr s)))))) (define (take n s) (if (zero? n) '() (let ((s (pull s))) (cond ((null? s) '()) (else (cons (car s) (take (- n 1) (cdr s)))))))) (define (mK-reify s/c*) (map reify-state/1st-var s/c*)) (define (reify-state/1st-var s/c) (let ((v (walk* (var 0) (car s/c)))) (walk* v (reify-s v '())))) (define (reify-s v s) (let ((v (walk v s))) (cond ((var? v) (let ((n (reify-name (length s)))) (cons `(,v . ,n) s))) ((pair? v) (reify-s (cdr v) (reify-s (car v) s))) (else s)))) (define (reify-name n) (string->symbol (string-append "_" "." (number->string n)))) (define (walk* v s) (let ((v (walk v s))) (cond ((var? v) v) ((pair? v) (cons (walk* (car v) s) (walk* (cdr v) s))) (else v)))) (define (call/empty-state g) (g empty-state)) (define-syntax run (syntax-rules () ((_ n (x ...) g0 g ...) (mK-reify (take n (call/empty-state (fresh (x ...) g0 g ...))))))) (define-syntax run* (syntax-rules () ((_ (x ...) g0 g ...) (mK-reify (take-all (call/empty-state (fresh (x ...) g0 g ...))))))) ;; (define-syntax run* ;; (syntax-rules () ;; ((_ (x ...) g0 g ...) ;; (take-all (call/empty-state ;; (fresh (x ...) g0 g ...))))))
true
53d4a4569cc2e7ffcab905a899332d7984531432
b08b7e3160ae9947b6046123acad8f59152375c3
/Programming Language Detection/Experiment-2/Dataset/Train/Racket/singly-linked-list-element-definition.rkt
17e1a4d99ad5d8ddc89f760368472fe7f9a175c5
[]
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
64
rkt
singly-linked-list-element-definition.rkt
#lang racket (mcons 1 (mcons 2 (mcons 3 '()))) ; a mutable list
false
395043a233589fe15935046c854935ba8e75293b
a18b561b599c8e85d697ecb421fe98cbb41814d1
/interface/tile-renderer.rkt
fb4c5fa2394736a44392264380d153a86ecbf9f3
[]
no_license
his1220/earthgen
f501f1c6b91831adc3072e4dc7bbe5b9f7045793
0fd1904905fea41a441e7494388d734e298b77bc
refs/heads/master
2021-01-18T15:14:11.895611
2015-03-20T19:50:30
2015-03-20T20:35:08
null
0
0
null
null
null
null
UTF-8
Racket
false
false
3,438
rkt
tile-renderer.rkt
#lang racket (provide tile-renderer%) (require vraid/opengl vraid/color "../planet/planet.rkt" racket/flonum ffi/cvector ffi/unsafe) (define tile-renderer% (class object% (super-new) (init-field planet) (define buffer-tile-count 0) (define tile-vertex-buffer (gl-vertex-buffer (generate-gl-buffer-handle) (make-cvector _uint 0))) (define tile-index-buffer (gl-index-buffer (generate-gl-buffer-handle) (make-cvector _uint 0))) (define (resize-buffer?) (not (= buffer-tile-count (tile-count (planet))))) (define/public (resize-buffer) (when (resize-buffer?) (let ([b (make-tile-buffer (planet))]) (set! buffer-tile-count (tile-buffer-tile-count b)) (set! tile-index-buffer (gl-index-buffer (gl-index-buffer-handle tile-index-buffer) (tile-buffer-indices b))) (set! tile-vertex-buffer (gl-vertex-buffer (gl-vertex-buffer-handle tile-vertex-buffer) (tile-buffer-vertices b))) (set-gl-index-buffer! tile-index-buffer)))) (define/public (remake-buffer color-function) (update-vertices! (grid-tile-count (planet)) tile-vertex-buffer (curry color-function (planet))) (set-gl-vertex-buffer! tile-vertex-buffer)) (define/public (set-tile-colors color-function) (remake-buffer color-function)) (define/public (render) (gl-cull-face 'back) (gl-draw tile-vertex-buffer tile-index-buffer)))) (struct tile-buffer (tile-count vertices indices)) (define (->gl-vertex coord color) (make-gl-vertex (flvector-ref coord 0) (flvector-ref coord 1) (flvector-ref coord 2) (flcolor->byte (flcolor-red color)) (flcolor->byte (flcolor-green color)) (flcolor->byte (flcolor-blue color)) (flcolor->byte (flcolor-alpha color)))) (define (make-tile-buffer grid) (let* ([tile-count (grid-tile-count grid)] [vertices (make-cvector _gl-vertex (* 7 tile-count))] [indices (make-cvector _uint (* 18 tile-count))] [color (flcolor3 0.0 0.0 0.0)]) (for ([n tile-count]) (cvector-set! vertices (* n 7) (->gl-vertex ((grid-tile-coordinates grid) n) color)) (for ([i 6]) (cvector-set! vertices (+ 1 i (* n 7)) (->gl-vertex ((grid-corner-coordinates grid) ((grid-tile-corner grid) n i)) color)) (let ([k (+ (* i 3) (* n 18))]) (cvector-set! indices k (* n 7)) (cvector-set! indices (+ 1 k) (+ 1 (modulo i 6) (* n 7))) (cvector-set! indices (+ 2 k) (+ 1 (modulo (+ i 1) 6) (* n 7)))))) (tile-buffer tile-count vertices indices))) (define (set-vertex-color! vertices n color) (let ([v (cvector-ref vertices n)]) (set-gl-vertex-red! v (byte-color-red color)) (set-gl-vertex-green! v (byte-color-green color)) (set-gl-vertex-blue! v (byte-color-blue color)))) (define (update-vertices! count buffer color-function) (let* ([vertices (gl-vertex-buffer-data buffer)]) (for ([n count]) (let ([color (flcolor->byte-color (color-function n))]) (set-vertex-color! vertices (* n 7) color) (for ([i 6]) (set-vertex-color! vertices (+ 1 i (* n 7)) color))))))
false
31c6c4540707065617a2294ae17d0458b06df9c4
1b35cdffa859023c346bed5fcac5a9be21b0a5a6
/polyglot-lib/polyglot/private/server.rkt
73579dfc24427a0b464e77e4145be8ac1e2d9beb
[ "MIT" ]
permissive
zyrolasting/polyglot
dd8644425756c87357c1b425670f596be708104d
d27ca7fe90fd4ba2a6c5bcd921fce89e72d2c408
refs/heads/master
2021-07-03T01:09:33.887986
2021-01-01T16:17:57
2021-01-01T16:17:57
204,181,797
95
6
MIT
2020-05-26T13:44:19
2019-08-24T16:18:07
Racket
UTF-8
Racket
false
false
1,336
rkt
server.rkt
#lang racket (provide start-server) (require racket/runtime-path net/url web-server/web-server web-server/http/response-structs web-server/http/request-structs web-server/dispatchers/filesystem-map web-server/private/util web-server/private/mime-types (prefix-in lifter: web-server/dispatchers/dispatch-lift) (prefix-in sequencer: web-server/dispatchers/dispatch-sequencer) (prefix-in files: web-server/dispatchers/dispatch-files)) (define-runtime-path mime-types-file "./mime.types") (define (show-not-found req) (define message (format "Cannot find ~v" (url->string (request-uri req)))) (response/full 404 #"Not Found" (current-seconds) #"text/html; charset=utf-8" '() (list (string->bytes/utf-8 (format "<html><head><title>~a</title></head><body>~a</body></html>" message message))))) (define (start-server static-files-dir [port 8080]) (serve #:dispatch (sequencer:make (files:make #:url->path (make-url->path static-files-dir) #:path->mime-type (make-path->mime-type mime-types-file)) (lifter:make show-not-found)) #:port port))
false
c912858d4ac9d8001966ad7dbb757ad3382c4c22
d25866631857fcba924e1f432efccaf6859d8897
/scribblings/idl.scrbl
a0cd5e1b00b32146cf0739903546b3b08d057a98
[ "MIT" ]
permissive
johnstonskj/racket-thrift
347bb69c1dc8ce8247d6eb7f094ae797ac9cf5dc
bbed34e6af97167ec5e9327c7c6ad739e331e793
refs/heads/master
2022-05-02T00:14:30.383168
2018-12-05T22:07:43
2018-12-05T22:07:43
160,576,898
2
1
null
null
null
null
UTF-8
Racket
false
false
6,571
scrbl
idl.scrbl
#lang scribble/manual @(require racket/sandbox scribble/core scribble/eval (for-label racket/base racket/contract thrift)) @;{============================================================================} @(define example-eval (make-base-eval '(require racket/string thrift))) @;{============================================================================} @title[]{Thrift IDL Support.} Support for Thrift format definitions @examples[ #:eval example-eval (require thrift thrift/idl/language) (define-thrift-namespace parquet) (define-thrift-enum parquet-type 0 (boolean int32 int64 int96 ; deprecated float double byte-array fixed-len-byte-arrary)) (define-thrift-struct file-metadata ([1 version required type-int32] [2 schema required list-of schema-element] [3 num-rows required type-int64] [4 row-groups required list-of row-group] [5 key-value-metadata optional list-of key-value] [6 created-by optional type-string] [7 column-orders optional list-of column-order])) ] @;{============================================================================} @section[]{Type System} @defmodule[thrift/idl/common] @subsection[]{Core Types} @defproc[(type? [v any/c]) boolean?] @deftogether[(@defthing[type-stop type?] @defthing[type-void type?] @defthing[type-bool type?] @defthing[type-byte type?] @defthing[type-int8 type?] @defthing[type-double type?] @defthing[type-int16 type?] @defthing[type-int32 type?] @defthing[type-int64 type?] @defthing[type-string type?] @defthing[type-binary type?] @defthing[type-utf-7 type?] @defthing[type-struct type?] @defthing[type-map type?] @defthing[type-list type?] @defthing[type-set type?] @defthing[type-utf-8 type?] @defthing[type-utf-16 type?])]{ TBD } @deftogether[(@defproc[(integer->type [n exact-nonnegative-integer?]) type?] @defproc[(type/decode [d decoder?]) type?] @defproc[(type/names) (listof string?)])]{ TBD } @subsection[]{Field Type Information} @defproc[(required-type? [v any/c]) boolean?] @deftogether[(@defthing[required-type-required required-type?] @defthing[required-type-optional required-type?] @defthing[required-type-default required-type?])]{ TBD } @deftogether[(@defproc[(integer->required-type [n exact-nonnegative-integer?]) required-type?] @defproc[(required-type/decode [d decoder?]) required-type?] @defproc[(required-type/names) (listof string?)])]{ TBD } @defproc[(container-type? [v any/c]) boolean?] @deftogether[(@defthing[container-type-list-of container-type?] @defthing[container-type-set-of container-type?] @defthing[container-type-map-of container-type?] @defthing[container-type-none container-type?])]{ TBD } @deftogether[(@defproc[(integer->container-type [n exact-nonnegative-integer?]) container-type?] @defproc[(container-type/decode [d decoder?]) container-type?] @defproc[(container-type/names) (listof string?)])]{ TBD } @defstruct*[thrift-field ([id identifier?] [name string?] [required symbol?] [container symbol?] [major-type symbol?] [minor-type symbol?] [position exact-nonnegative-integer?]) #:mutable]{ TBD } @;{============================================================================} @section[]{IDL Language} @defmodule[thrift/idl/language] @defform[(define-thrift-namespace namespace) #:contracts ([namespace string?])]{ TBD } @defform[(define-thrift-enum id maybe-start value ...) #:grammar [(id string?) (maybe-start (code:line) exact-nonnegative-integer?) (value-expr identifier? [identifier? exact-nonnegative-integer?]) ]]{ TBD } @defform[#:literals (map-of) (define-thrift-struct [id string?] field ...) #:grammar [(field (index name maybe-req maybe-con elem-type) (index name maybe-req map-of elem-type key-type)) (maybe-required (code:line) required-type?) (maybe-container (code:line) container-type?)] #:contracts ([index exact-nonnegative-integer?] [name identifier?] [elem-type identifier?] [key-type identifier?])]{ TBD } @;{============================================================================} @section[]{Code Generator} @defmodule[thrift/idl/generator] @defproc[(process-file [file-path string? "."] [module-prefix string? ""] [over-write? boolean? #f]) void?]{ TBD } @subsection[]{Command-Line Launcher} The @racket[parquet/idl/generator] module is also used to create a launcher, @code{rthrift} that wraps @racket[process-file] to generate bindings for an IDL file from a Racket description. @verbatim|{ rthrift [ <option> ... ] <file-path> where <option> is one of -v, --verbose : Compile with verbose messages -V, --very-verbose : Compile with very verbose messages -o <path>, --output-path <path> : Directory to write the output into -m <module>, --module-prefix <module> : Prefix generated modules with a module path -f, --force-overwrite : Over-write any existing files --help, -h : Show this help -- : Do not treat any remaining argument as a switch (at this level) Multiple single-letter switches can be combined after one `-'; for example: `-h-' is the same as `-h --' }| To generate the files used in the module @racket[parquet], we use the following command. @code{$ rthrift -o parquet/generated -m parquet/generated parquet/format.rkt} This generates the following files, in the @code{parquet/generated} directory. @itemlist[ @item{@code{parquet.rkt} - The core types, expanded, used by the following.} @item{@code{parquet-encode.rkt} - All the encoder functions for the types above.} @item{@code{parquet-decode.rkt} - All the decoder functions for the types above.} @item{@code{parquet.scrbl} - Documentation for the three modules above.} ]
false
5dc244f1566a81db2a2f70f1f068c96d0fc83abc
10d178ff72324af154b9b40638d90d1254c697cb
/2d/info.rkt
46cd1fa15ce79be8fe6f36e51368f1e17c9ce19c
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
racket/2d
6f271d40148efd929eb54335225cff443dc1bb60
4b70b2dc77a9e8d2497a2c7373cacd659a3de23c
refs/heads/master
2023-09-01T01:43:47.882888
2022-02-01T03:35:22
2022-02-01T03:35:22
42,080,217
20
6
null
2017-01-18T03:25:53
2015-09-08T00:09:45
Racket
UTF-8
Racket
false
false
236
rkt
info.rkt
#lang info (define collection 'multi) (define version "1.0") (define deps '("2d-lib" "2d-doc")) (define implies '("2d-lib" "2d-doc")) (define pkg-desc "2d syntax") (define pkg-authors '(robby)) (define license '(Apache-2.0 OR MIT))
false
94601f630d9389bb10fb3c84960852382815048b
b08b7e3160ae9947b6046123acad8f59152375c3
/Programming Language Detection/Experiment-2/Dataset/Train/Racket/singleton-1.rkt
e7d3afa86733571119b0b67403d199c070d16a82
[]
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
121
rkt
singleton-1.rkt
#lang racket (provide instance) (define singleton% (class object% (super-new))) (define instance (new singleton%))
false
0e3922beb43620eb30cf4e80e93af8677905e2ec
062daf81f6afcc68f94a01f10347fe9c79bfadb9
/flmatrix.rkt
7cae34e058c9b37e9d590347c81794254d2adccb
[ "MIT" ]
permissive
Metaxal/flmatrix
7db6f283c839f1f25bd298e19a1e6b29699110ee
4a5282bfed3ecac0acd5fb3f98799440660034dd
refs/heads/master
2020-06-29T23:53:56.357313
2019-08-05T14:28:10
2019-08-05T14:28:10
200,661,289
0
0
null
2019-08-05T13:31:45
2019-08-05T13:31:44
null
UTF-8
Racket
false
false
71,310
rkt
flmatrix.rkt
#lang racket (provide (all-defined-out)) ;;; TODO ;;; * Improve matrix-expt! (avoid allocation) ;;; NOTES ;;; * Contracts will be added before release ;;; ;;; * See tests at bottom for examples. ;;; FEEDBACK ;;; * Where is CBLAS and LAPACK on your platform ;;; (Windows and Linux) ;;; * What are the libraries named? ;;; * Do all tests evaluate to #t on your platform? ;;; * Mail: [email protected] ;;; ;;; PLATFORMS TESTED ;;; * OS X Mountain Lion (Working) ;;; ;;; IDEAS ;;; Potential Improvements ;;; * DONE Unsafe operations ;;; * DONE add lda to the flmatrix structure ;;; * DONE support shared submatrix without allocation ;;; * DONE Improve equal? ;;; * Use dgeequ before dgetrf (in matrix-lu!) ;;; * Use an extra call with lwork=-1 in matrix-inverse! ;;; * support different storage schemes ;;; http://www.netlib.org/lapack/lug/node121.html ;;; Useful routines to consider: ;;; * http://www.math.utah.edu/software/lapack/lapack-d/dlazro.html ;;; * http://www.math.utah.edu/software/lapack/lapack-d/dlaset.html ;;; Constructs diagonal matrices. Use for flmatrix-identity ;;; * http://www.math.utah.edu/software/lapack/lapack-d/dlaswp.html ;;; Row interchanges ;;; * http://www.math.utah.edu/software/lapack/lapack-d/drscl.html ;;; Scale by 1/a with correct rounding (require ffi/vector ffi/unsafe ffi/unsafe/define racket/flonum (for-syntax racket/format racket/string ffi/unsafe)) ;;; ;;; LIBRARIES ;;; ; CBLAS and LAPACK are used. ; The first two are C-based whereas LAPACK is Fortran based. ;; Find placement of libraries. (define-values (cblas-lib lapack-lib) (case (system-type) ; MACOS [(macosx) (define veclib-lib ; OS X: Contains CBLAS both CATLAS. CATLAS is not used here. ; https://developer.apple.com/library/mac/#documentation/Accelerate/ ; Reference/BLAS_Ref/Reference/reference.html (ffi-lib "/System/Library/Frameworks/vecLib.framework/Versions/Current/vecLib")) (define cblas-lib veclib-lib) (define lapack-lib (ffi-lib (string-append "/System/Library/Frameworks/Accelerate.framework/" "Versions/A/Frameworks/vecLib.framework/Versions/A/libLAPACK"))) (values cblas-lib lapack-lib)] ; UNIX [(unix) (define cblas-lib (ffi-lib "libblas" '("3" #f))) ; works on debian (define lapack-lib (ffi-lib "liblapack" '("3" #f))) ; works on debian (values cblas-lib lapack-lib)] [(windows) ; tester needed (error 'tester-needed)])) ;;; Load libraries (define-ffi-definer define-cblas cblas-lib) (define-ffi-definer define-lapack lapack-lib) ;;; ;;; REFERENCES ;;; ; LAPACK Naming scheme: ; http://www.netlib.org/lapack/lug/node24.html ;;; ;;; CONFIGURATION ;;; (define epsilon 1e-13) ; If two flmatrices have the same size and ; the differences between two entries are ; smaller than epsilon, they are considered ; equal? . Furthermore if all entries are ; smaller than epislon flmatrix-zero? ; returns true. (define current-max-flmatrix-print-size (make-parameter 100)) ; For matrices with smaller size, all ; entries are printed. For larger matrices ; only the dimension is printed. ;;; ;;; REPRESENTATION ;;; ; BLAS/LAPACK represents matrices as one-dimensional arrays ; of numbers (S=single, D=double, X=complex or Z=double complex). ; This library uses arrays of doubles. (define _flmatrix (_cpointer 'flmatrix)) ; The array is wrapped in a struct, which besides ; a pointer to the array, holds the number of ; rows and columns. Future extension could be to ; allow different types of numbers, or perhaps ; choose specialized operations for triangular matrices. (define (flmatrix-print A port mode) (define print (if mode write display)) (print (if (< (flmatrix-size A) (current-max-flmatrix-print-size)) ; constructor style printing: (list 'flmatrix: ; (flmatrix-m A) (flmatrix-n A) (flmatrix->lists A)) ; omit actual elements (list 'flmatrix (flmatrix-m A) (flmatrix-n A) "...")) port)) (define (flmatrix= A B [eps #f]) (define-param (m n a lda) A) (define-param (r c b ldb) B) (and (= m r) (= n c) (for*/and ([j (in-range n)] [i (in-range m)]) (define aij (unsafe-ref a lda i j)) (define bij (unsafe-ref b ldb i j)) (if eps (fl<= (fl- aij bij) eps) (fl= aij bij))))) ; m = rows, n = cols, a = mxn array of doubles ; lda = leading dimension of a (see below) (struct flmatrix (m n a lda) #:methods gen:custom-write [(define write-proc flmatrix-print)] #:methods gen:equal+hash [(define equal-proc (λ (A B rec) (and (= (flmatrix-m A) (flmatrix-m B)) (= (flmatrix-n A) (flmatrix-n B)) (or (equal? (flmatrix-a A) (flmatrix-a B)) (flmatrix= A B epsilon))))) (define hash-proc ; TODO: Avoid allocation in hash-proc. (λ (A rec) (define-param (m n) A) (rec (cons m (cons n (flmatrix->vector A)))))) (define hash2-proc (λ (A rec) (define-param (m n) A) (rec (cons n (cons m (flmatrix->vector A))))))]) ; convenient destructuring (define-syntax (define-param stx) (syntax-case stx () [(_ (m n) A) #'(begin (define A1 A) (define m (flmatrix-m A1)) (define n (flmatrix-n A1)))] [(_ (m n a) A) #'(begin (define A1 A) (define m (flmatrix-m A1)) (define n (flmatrix-n A1)) (define a (flmatrix-a A1)))] [(_ (m n a lda) A) #'(begin (define A1 A) (define m (flmatrix-m A1)) (define n (flmatrix-n A1)) (define a (flmatrix-a A1)) (define lda (flmatrix-lda A1)))] [_ (error)])) ;;; ;;; MEMORY LAYOUT ;;; ; The entries are layed out in column major order. ; This means that the entries in a column are ; contigious. LAPACK needs this order. ; a[0] a[0 +lda] a[0 + 2*lda] ... a[0+(n-1)*lda] ; a[1] a[1 +lda] ; a[2] ; ... ... ; a[m-1] a[m-1 +lda] a[m01 + 2*lda] ... a[m-1+(n-1)*lda] ; For most matrices lda=m. ; For a submatrix it is possible that lda is larger than m. ; See http://stackoverflow.com/q/5009513/23567 ; Example: ; If ma=10, na=12, a=<some adress>, lda=10, ; then mb=7, nb=2, b=a+3+4*lda, ldb=10 (=lda) ; represent a 7x2 submatrix whose upper, lefter ; corner in A is (3,4) (indices are 0-based). ; The array index of the (i,j)th entry is: (define-syntax-rule (index lda i j) (+ i (* j lda))) (define (ptr-elm a lda i j) ; address of (i,j)th element (ptr-add a (index lda i j) _double)) (define (shared-submatrix! A i j r s) ; return rxs matrix with upper left corner (i,j) ; entries are shared with A ; TODO: consider garbage collection (define-param (m n a lda) A) (flmatrix r s (ptr-elm a lda i j) lda)) (define (flsubmatrix A m n i j) ; TODO: argument order not consistent with shared-submatrix! ; return a the mxn submatrix of with upper ; left corner in (i,j) (copy-flmatrix (shared-submatrix! A i j m n))) (define (ptr-row a i) ; pointer to beginning of row a (ptr-add a i _double)) (define (ptr-col a lda j) ; address of column j (ptr-add a (* j lda) _double)) ;;; ;;; CHECKS ;;; (define (check-flmatrix who A) (unless (flmatrix? A) (raise-type-error who "expected flmatrix" A))) (define (check-same-dimensions A B who) (unless (flmatrix-same-dimensions? A B) (raise-argument-error who "expected two matrices of the same size" A B))) (define (check-product-dimensions who A B [C #f]) (unless (if (not C) (= (flmatrix-n A) (flmatrix-m B)) (and (= (flmatrix-n A) (flmatrix-m B)) (= (flmatrix-m A) (flmatrix-m C)) (= (flmatrix-n B) (flmatrix-n C)))) (raise-argument-error who (if C "expected three matrices with compatible dimensions" "expected two matrices with compatible dimensions") A B C))) (define (check-matrix-vector-product-dimensions who A X Y) (define-param (ma na) A) (define-param (mx nx) X) (define-param (my ny) Y) (unless (if Y (and (= na mx) (= mx my) (= ny nx 1)) (= na mx)) (raise-argument-error who "expected same number of rows" A X Y))) (define (check-legal-column who j A) (unless (<= j (flmatrix-n A)) (raise-argument-error who "column index too large" j)) (unless (<= 0 j) (raise-argument-error who "column index must be non-negative"))) (define (check-legal-row who i A) (unless (<= i (flmatrix-m A)) (raise-argument-error who "row index too large" i)) (unless (<= 0 i) (raise-argument-error who "row index must be non-negative"))) (define (check-square who A) (define-param (m n) A) (unless (= m n) (raise-argument-error who "square matrix expected" A))) ;;; ;;; SIZE and DIMENSION ;;; (define (flmatrix-size A) (check-flmatrix 'flmatrix-size A ) (define-param (m n) A) (* m n)) (define (flmatrix-dimensions A) (check-flmatrix 'flmatrix-dimensions A) (define-param (m n) A) (values m n)) (define (flmatrix-same-dimensions? A B) (define-param (ma na) A) (define-param (mb nb) B) (and (= ma mb) (= na nb))) (define (flmatrix-row-vector? A) (= 1 (flmatrix-m A))) (define (flmatrix-column-vector? A) (= 1 (flmatrix-n A))) ;;; ;;; ALLOCATIONS and CONSTRUCTORS ;;; (define (alloc-flmatrix m n) (if (or (= m 0) (= n 0)) #f ; ~ NULL (cast (malloc (* m n) _double 'atomic-interior) _pointer _flmatrix))) (define (alloc-same-size-matrix A) (define-param (m n) A) (alloc-flmatrix m n)) (define-syntax (define-cblas* stx) (syntax-case stx () [(def xname _x (c ...) body ...) (let () (define ((xname->name ctx xname) c) (datum->syntax ctx (string->symbol (string-replace (~a xname) "x" (~a c) #:all? #f)))) (define (c->_c c) (unless (symbol? c) (error (format "expected symbol, got: ~a" c))) (case c [(c) _double] ; TODO missing from ffi? [(z) _double] ; TODO [(d) _double] [(s) _float] [else (error "expected one of c, z, d, s")])) (with-syntax ([(name ...) (map (xname->name stx (syntax->datum #'xname)) (syntax->datum #'(c ...)))] [(_c ...) (map c->_c (syntax->datum #'(c ...)))]) #'(begin (define-cblas name (let ([_x _c]) body ...)) ...)))])) (define-cblas* cblas_xcopy _x (s d c z) ; copy n elements from vector X to vector Y (_fun (n : _int) (X : _flmatrix) (incX : _int) (Y : _flmatrix) (incY : _int) -> _void)) #;(define-cblas cblas_dcopy ; copy n elements from vector X to vector Y (_fun (n : _int) (X : _flmatrix) (incX : _int) (Y : _flmatrix) (incY : _int) -> _void)) (define (unsafe-vector-copy! s a lda b) ; copy s elements from A into B ; element 0, lda, 2*lda, ... is copied (cblas_dcopy s a lda b 1)) (define (unsafe-matrix-copy! m n a lda b ldb) ; copy the mxn matrix A into B ; copy has upper left corner in (i,j) ; Note: use (ptr-elm b ldb i j) to ; copy into a submatrix of b. (for ([j (in-range n)]) (unsafe-vector-copy! m (ptr-elm a lda 0 j) 1 (ptr-add b (* j ldb) _double)))) (define (copy-flmatrix A) (define-param (m n a lda) A) (define size (* m n)) (define b (cast (malloc size _double 'atomic) _pointer _flmatrix)) (define ldb m) (cond [(= lda m) ; elements in a are contigious (unsafe-vector-copy! size a 1 b)] [else ; copy each column separately (unsafe-matrix-copy! m n a lda b ldb)]) (flmatrix m n b ldb)) (define (make-flmatrix m n [x 0.0]) (define a (alloc-flmatrix m n)) (define x* (real->double-flonum x)) (if (= x 0.0) (memset a 0 (* m n) _double) (for ([i (* m n)]) (ptr-set! a _double i x*))) (flmatrix m n a m)) (define (list->flmatrix xss) (define m (length xss)) (define n (apply max (map length xss))) (for*/flmatrix m n ([xs (in-list xss)] [x (in-list xs)]) x)) (define (vectors->flmatrix xss) (define m (vector-length xss)) (define n (vector-length (vector-ref xss 0))) (for*/flmatrix m n ([xs (in-vector xss)] [x (in-vector xs)]) x)) (define (flmatrix-identity m) (define A (make-flmatrix m m 0.0)) (for ([i (in-range m)]) (flmatrix-set! A i i 1.0)) A) (define (flmatrix-column A j) ; copy column j (check-legal-column 'flmatrix-column j A) (define-param (m n) A) (copy-flmatrix (shared-submatrix! A 0 j m 1))) (define (flmatrix-row A i) ; copy row i (define-param (m n) A) (check-legal-row 'flmatrix-row i A) (copy-flmatrix (shared-submatrix! A i 0 1 n))) ;;; ;;; CONVERSIONS MATRIX <-> VECTOR ;;; (define (flmatrix->vector A) ; the result vector uses row-major order (define-param (m n a lda) A) (for*/vector #:length (* m n) ([i (in-range 0 m)] [j (in-range 0 n)]) (unsafe-ref a lda i j))) (define (flmatrix->vectors A) ; the result is a vector of rows (define-param (m n a lda) A) (for/vector #:length m ([i (in-range 0 m)]) (for/vector #:length n ([j (in-range 0 n)]) (ptr-ref (ptr-elm a lda i j) _double)))) (define (vector->flmatrix m n v) (unless (= (* m n) (vector-length v)) (raise-argument-error 'vector->flmatrix "expected m*n to be the same as the length of the vector")) (define a (alloc-flmatrix m n)) (define k 0) (for* ([j (in-range n)] [i (in-range m)]) (ptr-set! a _double* k ; (index m i j) (vector-ref v (+ (* i n) j))) (set! k (+ k 1))) (flmatrix m n a m)) ; (: matrix/dim : Integer Integer Number * -> (Matrix Number)) ; construct a mxn flmatrix with elements from the values xs ; the length of xs must be m*n (define (flmatrix/dim m n . xs) (vector->flmatrix m n (list->vector xs))) ;;; ;;; COMPREHENSIONS ;;; ; (for/flmatrix m n (clause ...) . defs+exprs) ; Return an m x n flmatrix with elements from the last expr. ; The first n values produced becomes the first row. ; The next n values becomes the second row and so on. ; The bindings in clauses run in parallel. (define-syntax (for/flmatrix stx) (syntax-case stx () ; elements in column 0 are generated first, then column 1, ... [(_ m-expr n-expr #:column (for:-clause ...) . defs+exprs) (syntax/loc stx (let () (define m m-expr) (define n n-expr) (define m*n (* m n)) (define v (make-vector m*n 0)) (define k 0) (for ([i (in-range m*n)] for:-clause ...) (define x (let () . defs+exprs)) (vector-set! v (+ (* n (remainder k m)) (quotient k m)) x) (set! k (+ k 1))) (vector->flmatrix m n v)))] ; elements in row 0 are generated first, then row 1, ... [(_ m-expr n-expr (clause ...) . defs+exprs) (syntax/loc stx (let ([m m-expr] [n n-expr]) (define flat-vector (for/vector #:length (* m n) (clause ...) . defs+exprs)) ; TODO (efficiency): Skip temporary vector (vector->flmatrix m n flat-vector)))])) ; (for*/flmatrix m n (clause ...) . defs+exprs) ; Return an m x n flmatrix with elements from the last expr. ; The first n values produced becomes the first row. ; The next n values becomes the second row and so on. ; The bindings in clauses run nested. ; (for*/flmatrix m n #:column (clause ...) . defs+exprs) ; Return an m x n flmatrix with elements from the last expr. ; The first m values produced becomes the first column. ; The next m values becomes the second column and so on. ; The bindings in clauses run nested. (define-syntax (for*/flmatrix stx) (syntax-case stx () [(_ m-expr n-expr #:column (clause ...) . defs+exprs) (syntax/loc stx (let* ([m m-expr] [n n-expr] [v (make-vector (* m n) 0)] [w (for*/vector #:length (* m n) (clause ...) . defs+exprs)]) (for* ([i (in-range m)] [j (in-range n)]) (vector-set! v (+ (* i n) j) (vector-ref w (+ (* j m) i)))) (vector->flmatrix m n v)))] [(_ m-expr n-expr (clause ...) . defs+exprs) (syntax/loc stx (let ([m m-expr] [n n-expr]) (vector->flmatrix m n (for*/vector #:length (* m n) (clause ...) . defs+exprs))))])) (define-syntax (for/flmatrix-sum stx) (syntax-case stx () [(_ (for:-clause ...) . defs+exprs) (syntax/loc stx (let () (define sum #f) (for (for:-clause ...) (define a (let () . defs+exprs)) (set! sum (if sum (flmatrix+ sum a) a))) sum))])) ;;; ;;; BINARY MATRIX OPERATIONS ;;; ;;; MATRIX SUM AND DIFFERENCE (define-cblas* cblas_xaxpy _x (s d #;c #;z) ; Y := αX+Y ; X and Y are vectors ; If incX=3 then every 3rd element of X is used. (_fun (n : _int) (alpha : _x) (X : _flmatrix) (incX : _int) (Y : _flmatrix) (incY : _int) -> _void)) #;(define-cblas cblas_daxpy ; Y := αX+Y ; X and Y are vectors ; If incX=3 then every 3rd element of X is used. (_fun (n : _int) (alpha : _double) (X : _flmatrix) (incX : _int) (Y : _flmatrix) (incY : _int) -> _void)) (define (unsafe-vector-clear n a [lda 1]) (cblas_daxpy n -1.0 a lda a lda)) ; TODO: Allow adding row to different matrix! (define (flmatrix-add-scaled-row! A i1 s i2) ; scale row i2 and add to row i1 (check-legal-row 'matrix-add-scaled-row! i1 A) (check-legal-row 'matrix-add-scaled-row! i2 A) (define-param (m n a lda) A) (define rowi1 (ptr-row a i1)) (define rowi2 (ptr-row a i2)) (define s* (real->double-flonum s)) (cblas_daxpy n s* rowi2 lda rowi1 lda) A) (define (flmatrix-add-scaled-row A i1 s i2) (define B (copy-flmatrix A)) (flmatrix-add-scaled-row! B i1 s i2) B) (define (flmatrix-add-scaled-column! A j1 s j2) (check-legal-row 'flmatrix-add-scaled-column! j1 A) (check-legal-row 'flmatrix-add-scaled-column! j2 A) (define-param (m n a lda) A) (define colj1 (ptr-col a lda j1)) (define colj2 (ptr-col a lda j2)) (define s* (real->double-flonum s)) (cblas_daxpy m s* colj1 1 colj2 1) A) (define (flmatrix-add-scaled-column A i1 s i2) (define B (copy-flmatrix A)) (flmatrix-add-scaled-column! B i1 s i2) B) (define (constant*flmatrix+flmatrix! alpha A B) ; B := αA+B (define-param (m n a lda) A) (define-param (r s b ldb) B) (for ([j (in-range n)]) (cblas_daxpy m alpha (ptr-col a lda j) 1 (ptr-col b ldb j) 1)) B) (define (constant*flmatrix+flmatrix alpha A B) ; αA+B (define αA+B (copy-flmatrix B)) (constant*flmatrix+flmatrix! alpha A αA+B) αA+B) (define (flmatrix+! A B) ; B := A + B (check-same-dimensions A B 'flmatrix+!) (constant*flmatrix+flmatrix! 1.0 A B)) (define (flmatrix+ A B) ; A + B (check-same-dimensions A B 'flmatrix+) (constant*flmatrix+flmatrix 1.0 A B)) (define (flmatrix-! A B) ; A := A - B (check-same-dimensions A B 'flmatrix-!) (constant*flmatrix+flmatrix! -1.0 B A)) (define (flmatrix- A [B #f]) (cond [B (check-same-dimensions A B 'flmatrix-) (constant*flmatrix+flmatrix -1.0 B A)] [else (flmatrix-scale -1.0 A)])) ;;; Matrix x Matrix Multiplication (define _CBLAS_ORDER _int) (define CblasRowMajor 101) (define CblasColMajor 102) (define _CBLAS_TRANSPOSE _int) (define CblasNoTrans 111) (define CblasTrans 112) (define CblasConjTrans 113) (define-cblas* cblas_xgemm _x (s d z c) ; C := α(A*B)+βC ; 1. Multiplies A and B. ; 2. Scales result with alpha ; 3. Scales C with beta. ; 4. Stores sum in in C. (_fun (order : _CBLAS_ORDER) (transa : _CBLAS_TRANSPOSE) ; transpose A? (transb : _CBLAS_TRANSPOSE) ; transpose B? (m : _int) ; rows in A and C (n : _int) ; cols in B and C (k : _int) ; cols in A = rows in B (alpha : _x) ; scaling factor for A and B (A : _flmatrix) (lda : _int) ; size of first dim of A (B : _flmatrix) (ldb : _int) ; size of first dim of B (beta : _double) ; scaling for C (C : _flmatrix) (ldc : _int) ; size of first dim of C -> _void)) (define (constant*matrix*matrix+constant*matrix! alpha A B beta C transA transB) ; C := α(A*B)+βC, maybe transpose A and/or B first (check-product-dimensions 'constant*matrix*matrix+constant*matrix! A B C) (define-param (m n a lda) A) (define-param (r s b ldb) B) (define-param (x y c ldc) C) (define alpha* (real->double-flonum alpha)) (define beta* (real->double-flonum beta)) (cblas_dgemm CblasColMajor (if transA CblasTrans CblasNoTrans) (if transB CblasTrans CblasNoTrans) m s n alpha* a lda b ldb beta* c ldc) C) (define (flmatrix*! A B C [alpha 1.0] [beta 1.0] [transpose-A #f] [transpose-B #f]) ; C := α(A*B)+βC, maybe transpose A and/or B first (constant*matrix*matrix+constant*matrix! alpha A B beta C transpose-A transpose-B)) (define (flmatrix* A B [C #f] [alpha 1.0] [beta 1.0] [transpose-A #f] [transpose-B #f]) ; C := α(A*B)+βC, maybe transpose A and/or B first (define C1 (or C (make-flmatrix (flmatrix-m A) (flmatrix-n B)))) (flmatrix*! A B C1 alpha beta transpose-A transpose-B)) ;;; Matrix Power (define (flmatrix-expt a n) (check-flmatrix 'flmatrix-expt a) (check-square 'matrix-expt a) (cond [(= n 0) (flmatrix-identity (flmatrix-m a))] [(= n 1) (copy-flmatrix a)] [(= n 2) (flmatrix* a a)] [(even? n) (let ([a^n/2 (flmatrix-expt a (quotient n 2))]) (flmatrix* a^n/2 a^n/2))] [else (flmatrix* a (flmatrix-expt a (sub1 n)))])) ;;; Matrix x Vector Multiplication ; NOTE: Functions accepting column vectors automatically ; convert (standard) vectors into mx1 matrices. (define-cblas* cblas_xgemv _x (s d c z) ; Double GEneral Matrix Vector multiplication ; Y := α(AX) +(βY) (_fun (order : _CBLAS_ORDER) (transa : _CBLAS_TRANSPOSE) ; transpose A? (m : _int) ; rows in A (n : _int) ; cols in A (alpha : _x) ; scaling factor for A (A : _flmatrix) (lda : _int) (X : _flmatrix) ; vector (ldx : _int) (beta : _x) ; scaling for Y (Y : _flmatrix) ; vector (ldy : _int) -> _void)) (define (constant*matrix*vector+constant*vector! alpha A X beta Y transA) ; unsafe: Y := α(AX) +(βY), maybe transpose A first (define-param (m n a lda) A) (cblas_dgemv CblasColMajor (if transA CblasTrans CblasNoTrans) m n (real->double-flonum alpha) a lda (flmatrix-a X) 1 (real->double-flonum beta) (flmatrix-a Y) 1) Y) (define (flmatrix*vector! A X Y [alpha 1.0] [beta 1.0] [transpose-A #f]) (define X1 (result-flcolumn X)) (define Y1 (result-flcolumn Y)) (check-matrix-vector-product-dimensions 'constant*matrix*vector+constant*vector! A X1 Y1) ; Y := α(AX) +(βY), maybe transpose A first (constant*matrix*vector+constant*vector! alpha A X1 beta Y1 transpose-A)) (define (flmatrix*vector A X [Y #f] [alpha 1.0] [beta 1.0] [transpose-A #f] ) ; Y := α(AX) +(βY), maybe transpose A first (define Y1 (or Y (make-flmatrix (flmatrix-m A) 1 0.0))) (flmatrix*vector! A X Y1 alpha 1.0 transpose-A)) ;;; ;;; ELEMENT WISE OPERATIONS ;;; ;;; Ref (define (unsafe-ref a lda i j) (ptr-ref (ptr-elm a lda i j) _double)) (define (flmatrix-ref A i j) (define-param (m n a lda) A) (unless (< -1 i m) (raise-arguments-error 'matrix-ref (format "expected row index between 0 and ~a, got ~a" m i))) (unless (< -1 j n) (error 'matrix-ref (format "expected column index between 0 and ~a, got ~a" n j))) (unsafe-ref a lda i j)) ;;; Set! (define (unsafe-set! a lda i j x) (ptr-set! (ptr-elm a lda i j) _double x)) (define (flmatrix-set! A i j x) (check-legal-row 'flmatrix-set! i A) (check-legal-column 'flmatrix-set! j A) (define-param (m n a lda) A) (define x* (real->double-flonum x)) (unsafe-set! a lda i j x*) A) ;;; Scaling (define-cblas* cblas_xscal _x (s d c z) ; X := αX vector (_fun (n : _int) (alpha : _x) (X : _flmatrix) (incX : _int) -> _void)) (define (constant*matrix! s A) ; A := s*A (define-param (m n a lda) A) (define s* (real->double-flonum s)) (cond [(= lda m) (cblas_dscal (* m n) s* a 1)] [else (for ([j (in-range n)]) (cblas_dscal m s* (ptr-col a lda j) 1))]) A) (define (flmatrix-scale! s A) ; A := s*A (constant*matrix! s A)) (define (flmatrix-scale s A) ; s*A (define sA (copy-flmatrix A)) (flmatrix-scale! s sA)) (define (shared-column-flmatrix A j) (check-legal-column 'shared-column-flmatrix j A) (define-param (m n) A) (shared-submatrix! A 0 j m 1)) (define (shared-row-flmatrix A i) (check-legal-row 'shared-row-flmatrix i A) (shared-submatrix! A i 0 1 (flmatrix-n A))) (define (flmatrix-scale-column! A j s) ; col_j := s * col_j (constant*matrix! s (shared-column-flmatrix A j)) A) (define (flmatrix-scale-column A j s) (define B (copy-flmatrix A)) (flmatrix-scale-column! B j s) B) (define (flmatrix-scale-row! A i s) ; row_i := s * rwo_i (check-legal-row 'flmatrix-scale-row! i A) (define-values (m n) (flmatrix-dimensions A)) (constant*matrix! s (shared-row-flmatrix A i)) A) (define (flmatrix-scale-row A i s) (define B (copy-flmatrix A)) (flmatrix-scale-row! B i s) B) ;;; Swapping (define-cblas* cblas_xswap _x (s d c z) ; Swaps elements in the vectors x and y (_fun (n : _int) ; length of vector (X : _flmatrix) (incX : _int) (Y : _flmatrix) (incY : _int) -> _void)) (define (flmatrix-swap-rows! A i1 i2) (check-legal-row 'flmatrix-swap-rows! i1 A) (check-legal-row 'flmatrix-swap-rows! i2 A) (unless (= i1 i2) (define-param (m n a lda) A) (define rowi1 (ptr-row a i1)) (define rowi2 (ptr-row a i2)) (cblas_dswap n rowi1 lda rowi2 lda)) A) (define (flmatrix-swap-rows A i1 i2) (define B (copy-flmatrix A)) (flmatrix-swap-rows! B i1 i2) B) (define (flmatrix-swap-columns! A j1 j2) (check-legal-row 'flmatrix-swap-columns! j1 A) (check-legal-row 'flmatrix-swap-columns! j2 A) (unless (= j1 j2) (define-param (m n a lda) A) (define colj1 (ptr-col a lda j1)) (define colj2 (ptr-col a lda j2)) (cblas_dswap m colj1 1 colj2 1)) A) (define (flmatrix-swap-columns A j1 j2) (define B (copy-flmatrix A)) (flmatrix-swap-columns! B j1 j2) B) ;;; Max Absolute Value (define-cblas* cblas_ixamax _x (s d c z) ; Returns the index of the element with the largest ; absolute value in a vector. (_fun (n : _int) (X : _flmatrix) (incX : _int) -> _int)) (define (flmatrix-max-abs-index A) (define-param (m n a lda) A) (cond [(= m lda) (define idx (cblas_idamax (* m n) a lda)) (values (remainder idx m) (quotient idx m))] [(= n 1) (define idx (cblas_idamax m a 1)) (values (- idx 1) 0)] [else (define idx (make-vector n)) (for ([j (in-range n)]) (define i (cblas_idamax m (ptr-col a lda j) 1)) (vector-set! idx j (cons (cons i j) (unsafe-ref a lda i j)))) (define ij (car (vector-argmax cdr idx))) (values (car ij) (cdr ij))])) (define (flmatrix-max-abs-value A) (define-values (i j) (flmatrix-max-abs-index A)) (flmatrix-ref A i j)) (define (flmatrix-zero? A [eps epsilon]) ; set eps=#f to use normal equal? (define val (flmatrix-max-abs-value A)) (if eps (< (abs val) eps) (zero? val))) ;;; ;;; BLOCK LEVEL OPERATIONS ;;; (define (flmatrix-augment C . Cs) ; 1. Check that all have same number of rows. (define-param (mc nc c ldc) C) (define rows (map flmatrix-m (cons C Cs))) (unless (andmap (λ (r) (= mc r)) rows) (raise-arguments-error 'flmatrix-augment "all arguments must have same number of rows")) ; 2. Find size for result matrix and allocate (define m mc) (define n (apply + (map flmatrix-n (cons C Cs)))) (define a (alloc-flmatrix m n)) (define lda m) ; 3. Fill in blocks (define j 0) (for ([B (in-list (cons C Cs))]) (define-param (mb nb b ldb) B) (define aj (ptr-col a lda j)) (unsafe-matrix-copy! mb nb b ldb aj lda) (set! j (+ j nb))) (flmatrix m n a lda)) (define (flmatrix-stack C . Cs) ; 1. Check that all have same number of columns (define-param (mc nc c ldc) C) (define cols (map flmatrix-n (cons C Cs))) (unless (andmap (λ (x) (= x nc)) cols) (raise-arguments-error 'flmatrix-stack "all arguments must have same number of columns")) ; 2. Find size for result matrix and allocate (define rows (map flmatrix-m (cons C Cs))) (define m (apply + rows)) (define n nc) (define a (alloc-flmatrix m n)) (define lda m) ; 3. Fill in blocks (define i 0) (for ([B (in-list (cons C Cs))]) (define-param (mb nb b ldb) B) (define ai (ptr-row a i)) (unsafe-matrix-copy! mb nb b ldb ai lda) (set! i (+ i mb))) (flmatrix m n a lda)) (define (flmatrix-block-diagonal C . Cs) (define rows (map flmatrix-m (cons C Cs))) (define cols (map flmatrix-n (cons C Cs))) ; 2. Find size for result matrix and allocate (define m (apply + rows)) (define n (apply + cols)) (define a (alloc-flmatrix m n)) (define lda m) (unsafe-vector-clear (* m n) a) ; 3. Fill in blocks (define i 0) (define j 0) (for ([B (in-list (cons C Cs))]) (define-param (mb nb b ldb) B) (define aij (ptr-elm a lda i j)) (unsafe-matrix-copy! mb nb b ldb aij lda) (set! i (+ i mb)) (set! j (+ j nb))) (flmatrix m n a lda)) ;;; ;;; NORMS ;;; (define-cblas* cblas_xnrm2 _x (s d) ; L2-norm = (sqrt (sum (sqr X_i))), vector (_fun (n : _int) (X : _flmatrix) (incX : _int) -> _x)) (define (flmatrix-norm A) ; (sqrt (sum (sqr A_ij))) (define-param (m n a lda) A) (cond [(= lda m) (cblas_dnrm2 (* m n) a 1)] [(= n 1) (cblas_dnrm2 m a 1)] [else (sqrt (for/sum ([j (in-range n)]) (expt (cblas_dnrm2 m (ptr-col a lda j) 1) 2)))])) ;;; ;;; UNARY MATRIX OPERATIONS ;;; (define (flmatrix-transpose A) ; TODO: Measure: Is it faster to use ; a loop with unsafe-vector-copy ? (define-param (m n a lda) A) (define AT (make-flmatrix n m)) (define at (flmatrix-a AT)) (for* ([j (in-range n)] [i (in-range m)]) (unsafe-set! at n j i (unsafe-ref a lda i j))) AT) ;;; ;;; MATRIX DECOMPOSITIONS ;;; ;;; Pivots (struct pivots (ps)) ; ps is a u32vector ; ps[i]=j <=> row i and row j-1 is swapped ; Note: Fortran counts from 1 ! (define (unsafe-pivot-ref ps i) ; Fortran indices are 1-based. (- (u32vector-ref ps i) 1)) (define (pivots-ref Ps i) (unsafe-pivot-ref (pivots-ps Ps) i)) (define (pivots-length Ps) (u32vector-length (pivots-ps Ps))) (define (pivots->flmatrix Ps) ; return the permuation matrix (define ps (pivots-ps Ps)) (define k (u32vector-length ps)) (define A (make-flmatrix k k 0.0)) (define-param (m n a lda) A) ; introduce ones on diagonal (for ([i (in-range m)]) (unsafe-set! a lda i i 1.0)) ; perform row permutations (for ([i (in-range (- m 1) -1 -1)]) (define i* (unsafe-pivot-ref ps i)) (unless (= i i*) (flmatrix-swap-rows! A i i*))) A) (define (pivots-sign Ps) ; return the sign of the corresponding permuation (define ps (pivots-ps Ps)) (define n (u32vector-length ps)) (for/product ([i (in-range n)]) (define i* (unsafe-pivot-ref ps i)) (if (= i i*) 1 -1))) ;;; ;;; PLU Factorization ;;; ; A = P L U ; where P is a permutation matrix, ; L is lower triangular ; U is upper triangular. ; Note: U is the result of Gauss elimation. (define-lapack dgetrf_ ; http://www.netlib.org/lapack/double/dgetrf.f ; DGETRF computes an LU factorization of a general M-by-N matrix A ; using partial pivoting with row interchanges. ; The factorization has the form ; A = P * L * U ; where P is a permutation matrix, L is lower triangular with unit ; diagonal elements (lower trapezoidal if m > n), and U is upper ; triangular (upper trapezoidal if m < n). ; Algorithm: Gaussian elimination with partial pivoting (_fun (m : (_ptr i _int)) (n : (_ptr i _int)) (a : _flmatrix) (lda : (_ptr i _int)) (ipiv : (_u32vector o (ptr-ref m _int))) (info : (_ptr o _int)) -> _void -> (values (pivots ipiv) info))) (define (flmatrix-lu! A) (define-param (m n a lda) A) (dgetrf_ m n a lda)) (define (flmatrix-plu A) (define B (copy-flmatrix A)) (define-values (ps info) (flmatrix-lu! B)) (define P (pivots->flmatrix ps)) (define L (flmatrix-extract-lower B)) (define U (flmatrix-extract-upper B)) ; TODO: What to do with info? (values P L U)) (define (flmatrix-extract-upper A) ; extract the upper matrix, ; including the diagonal ; discard below diagonal (define-param (m n) A) (define k (min m n)) (define U (make-flmatrix k k)) ; TODO: use unsafe-ref or unsafe-vector-copy (for* ([j (in-range 0 k)] [i (in-range (min (+ 1 j) k))]) (flmatrix-set! U i j (flmatrix-ref A i j))) U) (define (flmatrix-extract-lower A) ; extract the lower matrix, ; and insert ones on diagonal (define L (copy-flmatrix A)) (define-param (m n) A) ; TODO: use unsafe-ref or unsafe-vector-copy (for* ([j (in-range n)] [i (in-range 0 j)]) (flmatrix-set! L i j 0)) (for* ([j (in-range (min m n))]) (flmatrix-set! L j j 1.0)) L) ;;; SVD - Singular Value Decomposition (define-lapack dgesvd_ ; compute SVD ; A = U * SIGMA * transpose(V) ; SIGMA is an mxm matrix, ; Algorith: QR used (_fun (jobu : (_ptr i _byte)) ; char: a, s, o or n (jobvt : (_ptr i _byte)) ; char (m : (_ptr i _int)) ; rows in A (n : (_ptr i _int)) ; cols in A (a : _flmatrix) ; io (lda : (_ptr i _int)) (s : _flmatrix) ; min(m,n) x 1 (u : _flmatrix) ; mxm if jobu = a (ldu : (_ptr i _int)) (vt : _flmatrix) ; nxn if jobvt = a (ldvt : (_ptr i _int)) ; (work : _flmatrix) ; dim max(1,lwork) (lwork : (_ptr i _int)) ; (info : (_ptr o _int)) -> _void -> info)) (define-lapack dgesdd_ ; compute SVD ; A = U * SIGMA * transpose(V) ; SIGMA is an mxm matrix, ; Algorithm: Divide and conquer with QR used for small ; This is the recommended algorithm, but uses ; more work space. (_fun (jobu : (_ptr i _byte)) ; char: a, s, o or n (jobvt : (_ptr i _byte)) (m : (_ptr i _int)) ; rows in A (n : (_ptr i _int)) ; cols in A (a : _flmatrix) ; io (lda : (_ptr i _int)) (s : _flmatrix) ; min(m,n) x 1 (u : _flmatrix) ; mxm if jobu = a (ldu : (_ptr i _int)) (vt : _flmatrix) ; nxn if jobvt = a (ldvt : (_ptr i _int)) ; (work : _flmatrix) ; dim max(1,lwork) (lwork : (_ptr i _int)) ; (info : (_ptr o _int)) -> _void -> info)) (define (flmatrix-svd! A) ; TODO: Use lwork=-1 to get size of work (define-param (m n a lda) A) (define superb (- (min m n) 1)) (define U (make-flmatrix m m)) (define S (make-flmatrix (min m n) 1)) (define VT (make-flmatrix n n)) (define u (flmatrix-a U)) (define s (flmatrix-a S)) (define vt (flmatrix-a VT)) (define lwork (* 10 (max m n))) ; conservative estimate (define W (make-flmatrix lwork lwork)) (define w (flmatrix-a W)) (define ca (char->integer #\A)) (define info (dgesvd_ ca ca m n a lda s u m vt n w lwork)) ; ? TODO: Best way to return error ? ; (when (> info 0) (displayln "Warning: no convergence")) (values U S VT)) (define (flmatrix-svd A) (flmatrix-svd! (copy-flmatrix A))) ;;; QR Factorization (define-lapack dgeqrfp_ ; Compute A = Q*R ; Use dorgqr to generate matrix from output (_fun (m : (_ptr i _int)) ; rows in A (n : (_ptr i _int)) ; cols in A (a : _flmatrix) ; io (lda : (_ptr i _int)) (tau : _flmatrix) ; min(m,n)x1 (work : _flmatrix) ; dim max(1,lwork) (x1) (lwork : (_ptr i _int)) ; >=max(1,n) best with >=n * blocksize (info : (_ptr o _int)) ; -> _void -> info)) (define-lapack dorgqr_ ; generate matrix from output of dgeqrf (_fun (m : (_ptr i _int)) ; rows in Q (n : (_ptr i _int)) ; cols in Q m>=n>=0 (k : (_ptr i _int)) ; number of reflectors (a : _flmatrix) ; io (lda : (_ptr i _int)) (tau : _flmatrix) ; min(m,n)x1 (work : _flmatrix) ; dim max(1,lwork) (x1) (lwork : (_ptr i _int)) ; >=max(1,n) best with >=n * blocksize (info : (_ptr o _int)) ; -> _void -> info)) (define (flmatrix-qr B) (define A (copy-flmatrix B)) (define-param (m n a lda) A) (define k (min m n)) (define tau (make-flmatrix k k)) (define atau (flmatrix-a tau)) (define lwork (* 64 n)) ; 64 block size guess (define work (make-flmatrix lwork 1)) (define awork (flmatrix-a work)) ; TODO: Use lwork=-1 to get optimal lwork size (define info (dgeqrfp_ m n a lda atau awork lwork)) (define R (flmatrix-extract-upper A)) (define info1 (dorgqr_ m n k a lda atau awork lwork)) ; ? TODO: what to do with info (values A R)) ;;; ;;; INVERSE ;;; (define-lapack dgetri_ ; http://www.netlib.org/lapack/double/dgetri.f ; DGETRI computes the inverse of a matrix using the LU factorization ; computed by DGETRF. ; This method inverts U and then computes inv(A) by solving the system ; inv(A)*L = inv(U) for inv(A). (_fun (n : (_ptr i _int)) (a : _flmatrix) (lda : (_ptr i _int)) (ipiv : _u32vector) (work : (_or-null _flmatrix)) ; output (lwork : (_ptr i _int)) (info : (_ptr o _int)) -> _void -> (values info work))) (define (flmatrix-inverse! A) ; TODO: this works, but call dgetri with lwork=-1 ; to get optimal size of workspace in first ; entry of the work array. (define-param (m n a lda) A) (define work (copy-flmatrix A)) (define-values (ipiv info) (flmatrix-lu! A)) (dgetri_ m a lda (pivots-ps ipiv) (flmatrix-a work) (* m m)) A) (define (flmatrix-inverse A) (flmatrix-inverse! (copy-flmatrix A))) ;;; ;;; INVARIANTS ;;; (define (flmatrix-trace A) (check-square 'matrix-trace A) (for/sum ([i (in-range (flmatrix-m A))]) (flmatrix-ref A i i))) (define (flmatrix-determinant-from-plu LU pivots) ; compute determinant using output from PLU ; factorization (* (pivots-sign pivots) (for/product ([i (in-range (flmatrix-m LU))]) (flmatrix-ref LU i i)))) (define (flmatrix-determinant A) (check-square 'matrix-determinant A) (define LU (copy-flmatrix A)) (define-values (pivots info) (flmatrix-lu! LU)) (flmatrix-determinant-from-plu LU pivots)) (define (count-columns-without-pivot pivots) ; TODO: Does this strategy work? (define ps (pivots-ps pivots)) (define m (u32vector-length ps)) (define with (for/sum ([i (in-range m)]) (define i* (- (u32vector-ref ps i) 1)) (if (= i i*) 0 1))) (- m with)) (define (flmatrix-rank A) ; See answer: http://scicomp.stackexchange.com/questions/1861/understanding-how-numpy-does-svd ; rank = dimension of column space = dimension of row space ; = number of non-zero singular values (define-values (U Σ VT) (flmatrix-svd A)) ; ? TODO: check info from -svd... (for/sum ([i (in-range (flmatrix-m Σ))] ; TODO: Which value for epsilon is correct? #:unless (< (abs (flmatrix-ref Σ i 0)) epsilon)) 1)) (define (flmatrix-nullity A) ; nullity = dimension of null space (define-param (m n) A) (- n (flmatrix-rank A))) ;;; ;;; VECTOR OPERATIONS ;;; ; Column vectors are represented as mx1 matrices. ; All operations working on column vectors accept ; standard vectors as input. Outputs are always ; in the form of a mx1 matrix. (define (vector->flcolumn v) (define m (vector-length v)) (vector->flmatrix m 1 v)) (define (result-flcolumn c) ; convert output to mx1 matrix (if (vector? c) (vector->flcolumn c) c)) (define (flcolumn . xs) ; TODO: skip intermediary vector (vector->flcolumn (list->vector xs))) (define (flcolumn-size v) (if (vector? v) (vector-length v) (flmatrix-m v))) ;;; Dot Product (define-cblas* cblas_xdot _x (s d) ; dot product, vectors (_fun (n : _int) (X : _flmatrix) (incX : _int) (Y : _flmatrix) (incY : _int) -> _x)) (define (unsafe-vector-product n x y) (cblas_ddot n x 1 y 1)) (define (flcolumn-dot X Y) (set! X (result-flcolumn X)) (set! Y (result-flcolumn Y)) (define-param (m _ x ldx) X) (define-param (s __ y ldy) Y) (unless (= m s) (error 'column-dot "expected two mx1 matrices with same number of rows, got ~a and ~a" X Y)) (unsafe-vector-product m x y)) (define fldot flcolumn-dot) (define (flcolumn-norm v) (define-param (m _ a lda) (result-flcolumn v)) (cblas_dnrm2 m a 1)) (define (flcolumn-unit m i) ; return i'th unit vector (define U (make-flmatrix m 1 0.0)) (flmatrix-set! U i 0 1.0) U) (define (flscale-column s A) (define s* (real->double-flonum s)) (cond [(vector? A) (define m (vector-length A)) (vector->flcolumn (for/vector #:length m ([i (in-range m)]) (* s* (vector-ref A i))))] [else (flmatrix-scale s A)])) (define (flcolumn+ v w) (define m (flcolumn-size v)) (define n (flcolumn-size w)) (unless (= m n) (error 'flcolumn+ "expected two column vectors of the same length, got ~a and ~a" v w)) (cond [(and (vector? v) (vector? w)) (vector->flcolumn (for/vector #:length (+ m n) ([i (in-range 0 m)] [x (in-vector v)] [y (in-vector w)]) (+ x y)))] [else (flmatrix+ (result-flcolumn v) (result-flcolumn w))])) (define (flcolumn-projection v w) ; Return the projection og vector v on vector w. (let ([w.w (fldot w w)]) (if (zero? w.w) (error 'flcolumn-projection "projection on the zero vector not defined") (flscale-column (/ (fldot v w) w.w) w)))) (define (flcolumn-projection-on-unit v w) ; Return the projection of vector v on a unit vector w. (flscale-column (flcolumn-dot v w) w)) (define (flcolumn-normalize w) ; Return unit vector with same direction as v. ; If v is the zero vector, the zero vector is returned. (define norm (flcolumn-norm w)) (cond [(zero? norm) w] [else (flscale-column (/ norm) w)])) (define (flzero-column-vector? v [eps #f]) (define val (flmatrix-max-abs-value (result-flcolumn v))) (if eps (< (abs val) eps) (zero? val))) ; (flprojection-on-orthogonal-basis v bs) ; Project the vector v on the orthogonal basis vectors in bs. ; The basis bs must be either the column vectors of a matrix ; or a sequence of column-vectors. (define (flprojection-on-orthogonal-basis v bs) (if (empty? bs) (error 'flprojection-on-orthogonal-basis "received empty list of basis vectors") (for/flmatrix-sum([b (in-list bs)]) (flcolumn-projection v (result-flcolumn b))))) ; Project the vector v on the orthonormal basis vectors in bs. ; The basis bs must be either the column vectors of a matrix ; or a sequence of column-vectors. (define (flprojection-on-orthonormal-basis v bs) (for/flmatrix-sum ([b bs]) (flmatrix-scale (flcolumn-dot v b) b))) ; (flgram-schmidt-orthogonal ws) ; Given a list ws of flcolumn vectors, produce ; an orthogonal basis for the span of the ; vectors in ws. (define (flgram-schmidt-orthogonal ws1) (define ws (map result-flcolumn ws1)) (cond [(null? ws) '()] [(null? (cdr ws)) (list (car ws))] [else (define (loop vs ws) (cond [(null? ws) vs] [else (define w (car ws)) (let ([w-proj (flprojection-on-orthogonal-basis w vs)]) ; Note: We project onto vs (not on the original ws) ; in order to get numerical stability. (let ([w-minus-proj (flmatrix- w w-proj)]) (if (flzero-column-vector? w-minus-proj) (loop vs (cdr ws)) ; w in span{vs} => omit it (loop (cons (flmatrix- w w-proj) vs) (cdr ws)))))])) (reverse (loop (list (car ws)) (cdr ws)))])) ; (flgram-schmidt-orthonormal ws) ; Given a list ws of flcolumn vectors, produce ; an orthonormal basis for the span of the ; vectors in ws. (define (flgram-schmidt-orthonormal ws) (map flcolumn-normalize (flgram-schmidt-orthogonal ws))) ; (flprojection-on-subspace v ws) ; Returns the projection of v on span{w_i}, w_i in ws. (define (flprojection-on-subspace v ws) (flprojection-on-orthogonal-basis v (flgram-schmidt-orthogonal ws))) ;;; ;;; EQUATION SOLVING ;;; (define-lapack dgesv_ ; Double, GEneral, Solve ... ; Compute solution to AX=B, where ; A is nxn and X and B are n x nrhs (_fun (n : (_ptr i _int)) (nrhs : (_ptr i _int)) (a : _flmatrix) ; io (lda : (_ptr i _int)) (ipiv : (_u32vector o (ptr-ref n _int))) (b : _flmatrix) ; io (ldb : (_ptr i _int)) (info : (_ptr o _int)) -> _void -> info)) (define (flmatrix-solve A b) ; A matrix, b flcolumn (define-param (m n a lda) (copy-flmatrix A)) (define bout (copy-flmatrix (result-flcolumn b))) (define info (dgesv_ n 1 a lda (flmatrix-a bout) m)) ; ? TODO Handle info bout) (define (flmatrix-solve-many! A B) ; A matrix, b flcolumn ; A and B are overwritten (define-param (m n a lda) A) (define-param (_ nrhs b ldb) B) (define info (dgesv_ n nrhs a lda b ldb)) ; ? TODO: handle info (values B)) (define (flmatrix-solve-many A bs-or-B) ; A matrix, b flcolumn (define-param (m n) A) (define B (if (list? bs-or-B) (apply flmatrix-augment (map result-flcolumn bs-or-B)) (copy-flmatrix bs-or-B))) (flmatrix-solve-many! (copy-flmatrix A) B)) (define (flmatrix->columns A) (define-param (m n) A) (for/list ([j (in-range n)]) (flmatrix-column A j))) ;;; ;;; SEQUENCES ;;; (define (in-flrow/proc A r) (define-param (m n a lda) A) (make-do-sequence (λ () (define (pos->elm j) (unsafe-ref a lda r j)) (define next-pos add1) (define initial-pos 0) (define (continue? j) (< j n)) (values pos->elm initial-pos continue? #f #f)))) ; (in-flrow M i] ; Returns a sequence of all elements of row i, ; that is xi0, xi1, xi2, ... (define-sequence-syntax in-flrow (λ () #'in-flrow/proc) (λ (stx) (syntax-case stx () [[(x) (_ M-expr r-expr)] #'((x) (:do-in ([(M r m n a lda) (let ([M1 M-expr]) (define-param (rd cd a lda) M1) (values M1 r-expr rd cd a lda))]) (begin (unless (flmatrix? M) (raise-type-error 'in-flrow "expected flmatrix, got ~a" M)) (unless (and (integer? r) (and (<= 0 r ) (< r m))) (raise-type-error 'in-flrow "expected row number" r))) ([j 0]) (< j n) ([(x) (unsafe-ref a lda r j)]) #true #true [(+ j 1)]))] [[(i x) (_ M-expr r-expr)] #'((i x) (:do-in ([(M r m n a lda) (let ([M1 M-expr]) (define-param (rd cd a lda) M1) (values M1 r-expr rd cd a lda))]) (begin (unless (flmatrix? M) (raise-type-error 'in-flrow "expected flmatrix, got ~a" M)) (unless (and (integer? r) (and (<= 0 r ) (< r m))) (raise-type-error 'in-flrow "expected row number" r))) ([j 0]) (< j n) ([(x) (unsafe-ref a lda r j)] [(i) j]) #true #true [(+ j 1)]))] [[_ clause] (raise-syntax-error 'in-flrow "expected (in-flrow <flmatrix> <row>)" #'clause #'clause)]))) ; (in-flcol M j] ; Returns a sequence of all elements of column j, ; that is x0j, x1j, x2j, ... (define (in-flcolumn/proc A s) (define-param (m n a lda) A) (make-do-sequence (λ () (define (pos->elm i) (unsafe-ref a lda i s)) (define next-pos add1) (define initial-pos 0) (define (continue? i) (< i m)) (values pos->elm next-pos initial-pos #f #f)))) (define-sequence-syntax in-flcolumn (λ () #'in-flcolumn/proc) (λ (stx) (syntax-case stx () ; M-expr evaluates to column [[(x) (_ M-expr)] #'((x) (:do-in ([(M n m a) (let ([M1 (result-flcolumn M-expr)]) (define-param (rd cd a) M1) (values M1 rd cd a))]) (unless (flmatrix? M) (raise-type-error 'in-column "expected matrix, got ~a" M)) ([j 0]) (< j n) ([(x) (ptr-ref a _double j)]) #true #true [(+ j 1)]))] ; M-expr evaluates to matrix, s-expr to column index [[(x) (_ M-expr s-expr)] #'((x) (:do-in ([(M s m n a lda) (let ([M1 M-expr]) (define-param (rd cd a lda) M1) (values M1 s-expr rd cd a lda))]) (begin (unless (flmatrix? M) (raise-type-error 'in-flcolumn "expected matrix, got ~a" M)) (unless (integer? s) (raise-type-error 'in-flcolumn "expected column number, got ~a" s)) (unless (and (integer? s) (and (<= 0 s ) (< s n))) (raise-type-error 'in-flcolumn "expected column number, got ~a" s))) ([j 0]) (< j m) ([(x) (unsafe-ref a lda j s)]) #true #true [(+ j 1)]))] [[(i x) (_ M-expr s-expr)] #'((x) (:do-in ([(M s m n a lda) (let ([M1 M-expr]) (define-param (rd cd a lda) M1) (values M1 s-expr rd cd a lda))]) (begin (unless (flmatrix? M) (raise-type-error 'in-column "expected matrix, got ~a" M)) (unless (integer? s) (raise-type-error 'in-column "expected col number, got ~a" s)) (unless (and (integer? s) (and (<= 0 s ) (< s n))) (raise-type-error 'in-column "expected col number, got ~a" s))) ([j 0]) (< j m) ([(x) (unsafe-ref a lda j s)] [(i) j]) #true #true [(+ j 1)]))] [[_ clause] (raise-syntax-error 'in-flcolumn "expected (in-flcolumn <flmatrix> <column>)" #'clause #'clause)]))) (define (flmatrix-vandermonde xs n) ; One row for each element of xs. ; Each row consist of the first 0..n-1 powers of x. (define m (length xs)) (define αs (list->vector xs)) (define α^j (make-vector m 1.0)) (for*/flmatrix m n #:column ([j (in-range 0 n)] [i (in-range 0 m)]) (define αi^j (vector-ref α^j i)) (define αi (vector-ref αs i )) (vector-set! α^j i (* αi^j αi)) αi^j)) ;;; ;;; SYNTAX ;;; (require (for-syntax racket/base syntax/parse)) (define-syntax (flmatrix: stx) (syntax-parse stx [(_ [[x0 xs0 ...] [x xs ...] ...]) (syntax/loc stx (vectors->flmatrix #[#[x0 xs0 ...] #[x xs ...] ...]))] [(_ [xs ... (~and [] r) ys ...]) (raise-syntax-error 'flmatrix: "given empty row" stx #'r)] [(_ (~and [] c)) (raise-syntax-error 'flmatrix: "given empty matrix" stx #'c)] [(_ x) (raise-syntax-error 'flmatrix: "expected two-dimensional data" stx)])) (define-syntax (flrow-matrix stx) (syntax-parse stx [(_ [x xs ...]) (syntax/loc stx (flarray: #[#[x xs ...]]))] [(_ (~and [] r)) (raise-syntax-error 'flrow-matrix "given empty row" stx #'r)])) (define-syntax (flcol-matrix stx) (syntax-parse stx [(_ [x xs ...]) (syntax/loc stx (flarray #[#[x] #[xs] ...]))] [(_ (~and [] c)) (raise-syntax-error 'flrow-matrix "given empty column" stx #'c)])) ; TODO: #;(provide ; DONE matrix* ; DONE matrix-expt ; DONE matrix-ref ; DONE matrix-scale ; DONE matrix-row-vector? ; DONE matrix-column-vector? ; DONE matrix/dim ; construct ; DONE matrix-augment ; horizontally ; DONE matrix-stack ; vertically ; DONE matrix-block-diagonal ; norms ; DONE matrix-norm ; operators ; DONE matrix-transpose ; NO-COMPLEX matrix-conjugate ; NO-COMPLEX matrix-hermitian ; DONE matrix-inverse ; row and column ; DONE matrix-scale-row ; DONE matrix-scale-column ; DONE matrix-swap-rows ; DONE matrix-swap-columns ; DONE matrix-add-scaled-row ; DONE ADDED matrix-add-scaled-column ; reduction matrix-gauss-eliminate ; ? use upper in LU ? matrix-gauss-jordan-eliminate ; ? LU ? matrix-row-echelon-form ; ? LU ? matrix-reduced-row-echelon-form ; ? LU ? ; invariant ; DONE matrix-rank (uses SVD!) ; DONE matrix-nullity ; DONE matrix-determinant ; DONE matrix-trace ; spaces ;matrix-column+null-space ; solvers ; DONE matrix-solve ; DONE matrix-solve-many ; spaces matrix-column-space ; use SVD somehow ; column vectors ; DONE column ; construct ; DONE unit-column ; DONE result-column ; convert to lazy ; DONE column-dimension ; DONE column-dot ; DONE column-norm ; DONE column-projection ; DONE column-normalize ; DONE scale-column ; DONE column+ ; projection ; DONE projection-on-orthogonal-basis ; DONE projection-on-orthonormal-basis ; DONE projection-on-subspace ; DONE gram-schmidt-orthogonal ; DONE gram-schmidt-orthonormal ; factorization ; DONE matrix-lu (renamed to matrix-plu) ; DONE matrix-qr ; comprehensions ; DONE for/matrix: ; DONE for*/matrix: ; DONE for/matrix-sum: ; sequences ; DONE in-row ; DONE in-column ; special matrices ; DONE vandermonde-matrix ) (define (flmatrix->lists A) (map vector->list (vector->list (flmatrix->vectors A)))) (define (lists->flmatrix xss) (vectors->flmatrix (list->vector (map list->vector xss)))) ;;; ;;; TEST ;;; (module+ test (require rackunit) (define (flcheck-equal? a b) (< (abs (- b a)) 0.00001)) (with-check-info (['test-case "flmatrix/dim"]) (check-equal? (flmatrix->vector (flmatrix/dim 2 2 1 2 3 4)) #(1. 2. 3. 4.)) (check-equal? (flmatrix->vector (vector->flmatrix 2 2 #(1 2 3 4))) #(1. 2. 3. 4.)) (check-equal? (flmatrix->vector (flmatrix/dim 2 2 1 2 3 4)) #(1. 2. 3. 4.)) (check-equal? (flmatrix->vectors (flmatrix/dim 2 2 1 2 3 4)) #(#[1. 2.] #[3. 4.])) (let () (define A (flmatrix/dim 2 2 1 2 3 4)) (define B (flmatrix/dim 2 2 5 6 7 8)) (define AB (flmatrix/dim 2 2 19 22 43 50)) (check-equal? (flmatrix->vectors (flmatrix* A B)) (flmatrix->vectors AB))) (let () (define C (flmatrix/dim 2 2 1 2 3 4)) (define D (flmatrix/dim 2 3 5 6 7 8 9 10)) (define CD (flmatrix/dim 2 3 21 24 27 47 54 61)) (check-equal? (flmatrix->vectors (flmatrix* C D)) (flmatrix->vectors CD))) (check-equal? (flmatrix->vectors (flmatrix* (flmatrix/dim 2 3 0 0 1 0 0 0) (flmatrix/dim 3 2 1 2 3 4 5 6))) (flmatrix->vectors (flmatrix/dim 2 2 5 6 0 0)))) (with-check-info (['test-group "matrix-constructors.rkt"]) (with-check-info (['test-case 'flmatrix-identity]) (check-equal? (flmatrix->lists (flmatrix-identity 1)) '[[1.]]) (check-equal? (flmatrix->lists (flmatrix-identity 2)) '[[1. 0.] [0. 1.]]) (check-equal? (flmatrix->lists (flmatrix-identity 3)) '[[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]]) (check-equal? (flmatrix->lists (flmatrix-identity 1)) '[[1.]]) (check-equal? (flmatrix->lists (flmatrix-identity 2)) '[[1. 0.] [0. 1.]]) (check-equal? (flmatrix->lists (flmatrix-identity 3)) '[[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]])) (with-check-info (['test-case 'const-matrix]) (check-equal? (flmatrix->lists (make-flmatrix 2 3 0.)) '((0. 0. 0.) (0. 0. 0.)))) (with-check-info (['test-case 'matrix->list]) (check-equal? (flmatrix->lists (lists->flmatrix '((1. 2.) (3. 4.)))) '((1. 2.) (3. 4.)))) (with-check-info (['test-case 'matrix->vectors]) (check-equal? (flmatrix->vectors (vectors->flmatrix '#(#(1. 2.) #(3. 4.)))) '#(#(1. 2.) #(3. 4.)))) (with-check-info (['test-case 'matrix-row]) (check-equal? (flmatrix-row (flmatrix-identity 3) 0) (list->flmatrix '[[1 0 0]])) (check-equal? (flmatrix-row (flmatrix-identity 3) 1) (list->flmatrix '[[0 1 0]])) (check-equal? (flmatrix-row (flmatrix-identity 3) 2) (list->flmatrix '[[0 0 1]]))) (with-check-info (['test-case 'matrix-col]) (check-equal? (flmatrix-column (flmatrix-identity 3) 0) (list->flmatrix '[[1] [0] [0]])) (check-equal? (flmatrix-column (flmatrix-identity 3) 1) (list->flmatrix '[[0] [1] [0]])) (check-equal? (flmatrix-column (flmatrix-identity 3) 2) (list->flmatrix '[[0] [0] [1]]))) (with-check-info (['test-case 'flsubmatrix]) (check-equal? (flsubmatrix (flmatrix-identity 3) 1 2 0 0) (list->flmatrix '[[1 0]])) (check-equal? (flsubmatrix (flmatrix-identity 3) 2 3 0 0) (list->flmatrix '[[1 0 0] [0 1 0]])))) (with-check-info (['test-group "flmatrix-pointwise.rkt"]) (let () (define A (list->flmatrix '[[1 2] [3 4]])) (define ~A (list->flmatrix '[[-1 -2] [-3 -4]])) (define B (list->flmatrix '[[5 6] [7 8]])) (define A+B (list->flmatrix '[[6 8] [10 12]])) (define A-B (list->flmatrix '[[-4 -4] [-4 -4]])) (with-check-info (['test-case 'flmatrix+]) (check-equal? (flmatrix+ A B) A+B)) (with-check-info (['test-case 'flmatrix-]) (check-equal? (flmatrix- A B) A-B) (check-equal? (flmatrix- A) ~A)))) (with-check-info (['test-group "flmatrix-expt.rkt"]) (define A (list->flmatrix '[[1 2] [3 4]])) (with-check-info (['test-case 'flmatrix-expt]) (check-equal? (flmatrix-expt A 0) (flmatrix-identity 2)) (check-equal? (flmatrix-expt A 1) A) (check-equal? (flmatrix-expt A 2) (list->flmatrix '[[7 10] [15 22]])) (check-equal? (flmatrix-expt A 3) (list->flmatrix '[[37 54] [81 118]])) (check-equal? (flmatrix-expt A 8) (list->flmatrix '[[165751 241570] [362355 528106]])))) (with-check-info (['test-group "flmatrix-operations.rkt"]) (with-check-info (['test-case 'vandermonde-flmatrix]) (check-equal? (flmatrix-vandermonde '(1 2 3) 5) (list->flmatrix '[[1 1 1 1 1] [1 2 4 8 16] [1 3 9 27 81]]))) (with-check-info (['test-case 'in-column]) (check-equal? (for/list ([x (in-flcolumn (flmatrix/dim 2 2 1 2 3 4) 0)]) x) '(1. 3.)) (check-equal? (for/list ([x (in-flcolumn (flmatrix/dim 2 2 1 2 3 4) 1)]) x) '(2. 4.)) (check-equal? (for/list ([x (in-flcolumn (flcolumn 5 2 3))]) x) '(5. 2. 3.))) (with-check-info (['test-case 'in-row]) (check-equal? (for/list ([x (in-flrow (flmatrix/dim 2 2 1 2 3 4) 0)]) x) '(1. 2.)) (check-equal? (for/list ([x (in-flrow (flmatrix/dim 2 2 1 2 3 4) 1)]) x) '(3. 4.))) (with-check-info (['test-case 'for/flmatrix:]) (check-equal? (for/flmatrix 2 4 ([i (in-naturals)]) i) (flmatrix/dim 2 4 0 1 2 3 4 5 6 7)) (check-equal? (for/flmatrix 2 4 #:column ([i (in-naturals)]) i) (flmatrix/dim 2 4 0 2 4 6 1 3 5 7)) (check-equal? (for/flmatrix 3 3 ([i (in-range 10 100)]) i) (flmatrix/dim 3 3 10 11 12 13 14 15 16 17 18))) (with-check-info (['test-case 'for*/flmatrix:]) (check-equal? (for*/flmatrix 3 3 ([i (in-range 3)] [j (in-range 3)]) (+ (* i 10) j)) (flmatrix/dim 3 3 0 1 2 10 11 12 20 21 22))) (with-check-info (['test-case 'flmatrix-block-diagonal]) (check-equal? (flmatrix-block-diagonal (flmatrix/dim 2 2 1 2 3 4) (flmatrix/dim 1 3 5 6 7)) (list->flmatrix '[[1 2 0 0 0] [3 4 0 0 0] [0 0 5 6 7]]))) (with-check-info (['test-case 'flmatrix-augment]) (check-equal? (flmatrix-augment (flcolumn 1 2 3) (flcolumn 4 5 6) (flcolumn 7 8 9)) (flmatrix/dim 3 3 1 4 7 2 5 8 3 6 9))) (with-check-info (['test-case 'flmatrix-stack]) (check-equal? (flmatrix-stack (flcolumn 1 2 3) (flcolumn 4 5 6) (flcolumn 7 8 9)) (flcolumn 1 2 3 4 5 6 7 8 9))) (with-check-info (['test-case 'column-dimension]) (= (flcolumn-size #(1 2 3)) 3) (= (flcolumn-size (vector->flmatrix 1 2 #(1 2))) 1)) (let ([flmatrix: vector->flmatrix]) (with-check-info (['test-case 'column-dot]) (= (flcolumn-dot (flcolumn 1 2) (flcolumn 1 2)) 5) (= (flcolumn-dot (flcolumn 1 2) (flcolumn 3 4)) 11) (= (flcolumn-dot (flcolumn 3 4) (flcolumn 3 4)) 25) (= (flcolumn-dot (flcolumn 1 2 3) (flcolumn 4 5 6)) (+ (* 1 4) (* 2 5) (* 3 6))))) (with-check-info (['test-case 'flmatrix-trace]) (check-equal? (flmatrix-trace (vector->flmatrix 2 2 #(1 2 3 4))) 5.)) (let ([flmatrix: vector->flmatrix]) (with-check-info (['test-case 'column-norm]) (= (flcolumn-norm (flcolumn 2 4)) (sqrt 20)))) (with-check-info (['test-case 'column-projection]) (check-equal? (flcolumn-projection #(1 2 3) #(4 5 6)) (flcolumn 128/77 160/77 192/77)) (check-equal? (flcolumn-projection (flcolumn 1 2 3) (flcolumn 2 4 3)) (flmatrix-scale 19/29 (flcolumn 2 4 3)))) (with-check-info (['test-case 'projection-on-orthogonal-basis]) (check-equal? (flprojection-on-orthogonal-basis #(3 -2 2) (list #(-1 0 2) #( 2 5 1))) (flcolumn -1/3 -1/3 1/3)) (check-equal? (flprojection-on-orthogonal-basis (flcolumn 3 -2 2) (list #(-1 0 2) (flcolumn 2 5 1))) (flcolumn -1/3 -1/3 1/3))) (with-check-info (['test-case 'projection-on-orthonormal-basis]) (check-equal? (flprojection-on-orthonormal-basis #(1 2 3 4) (list (flmatrix-scale 1/2 (flcolumn 1 1 1 1)) (flmatrix-scale 1/2 (flcolumn -1 1 -1 1)) (flmatrix-scale 1/2 (flcolumn 1 -1 -1 1)))) (flcolumn 2 3 2 3))) (with-check-info (['test-case 'flgram-schmidt-orthogonal]) (check-equal? (flgram-schmidt-orthogonal (list #(3 1) #(2 2))) (list (flcolumn 3 1) (flcolumn -2/5 6/5)))) (with-check-info (['test-case 'flvector-normalize]) (check-equal? (flcolumn-normalize #(3 4)) (flcolumn 3/5 4/5))) (with-check-info (['test-case 'flgram-schmidt-orthonormal]) (check-equal? (flgram-schmidt-orthonormal '(#(3 1) #(2 2))) (list (flcolumn-normalize #(3 1)) (flcolumn-normalize #(-2/5 6/5))))) (with-check-info (['test-case 'projection-on-subspace]) (check-equal? (flprojection-on-subspace #(1 2 3) '(#(2 4 3))) (flmatrix-scale 19/29 (flcolumn 2 4 3)))) (with-check-info (['test-case 'unit-vector]) (check-equal? (flcolumn-unit 4 1) (flcolumn 0 1 0 0))) (with-check-info (['test-case 'flmatrix-qr]) (let-values ([(Q R) (flmatrix-qr (flmatrix/dim 3 2 1 1 0 1 1 1))]) (check-equal? (list Q R) (list (flmatrix/dim 3 2 0.7071067811865475 0 0 1 0.7071067811865475 0) (flmatrix/dim 2 2 1.414213562373095 1.414213562373095 0 1))))) (with-check-info (['test-case 'flmatrix-solve]) (let* ([M (list->flmatrix '[[1 5] [2 3]])] [b (list->flmatrix '[[5] [5]])]) (check-equal? (flmatrix* M (flmatrix-solve M b)) b))) (with-check-info (['test-case 'flmatrix-inverse]) (check-equal? (let ([M (list->flmatrix '[[1 2] [3 4]])]) (flmatrix* M (flmatrix-inverse M))) (flmatrix-identity 2)) (check-equal? (let ([M (list->flmatrix '[[1 2] [3 4]])]) (flmatrix* (flmatrix-inverse M) M)) (flmatrix-identity 2))) (with-check-info (['test-case 'flmatrix-determinant]) (check-equal? (flmatrix-determinant (list->flmatrix '[[3]])) 3.) (check-equal? (flmatrix-determinant (list->flmatrix '[[1 2] [3 4]])) (- (* 1. 4.) (* 2. 3.))) (flcheck-equal? (flmatrix-determinant (list->flmatrix '[[1 2 3] [4 5 6] [7 8 9]])) 0.) (flcheck-equal? (flmatrix-determinant (list->flmatrix '[[1 2 3] [4 -5 6] [7 8 9]])) 120.) (flcheck-equal? (flmatrix-determinant (list->flmatrix '[[1 2 3 4] [-5 6 7 8] [9 10 -11 12] [13 14 15 16]])) 5280.)) (with-check-info (['test-case 'flmatrix-scale]) (check-equal? (flmatrix-scale 2 (list->flmatrix '[[1 2] [3 4]])) (list->flmatrix '[[2 4] [6 8]]))) (with-check-info (['test-case 'flmatrix-transpose]) (check-equal? (flmatrix-transpose (list->flmatrix '[[1 2] [3 4]])) (list->flmatrix '[[1 3] [2 4]]))) ; TODO: Just use U from LU factorization #;(let () (: gauss-eliminate : (flmatrix Number) Boolean Boolean -> (flmatrix Number)) (define (gauss-eliminate M u? p?) (let-values ([(M wp) (flmatrix-gauss-eliminate M u? p?)]) M)) (with-check-info (['test-case 'flmatrix-gauss-eliminate]) (check-equal? (let ([M (list->flmatrix '[[1 2] [3 4]])]) (gauss-eliminate M #f #f)) (list->flmatrix '[[1 2] [0 -2]])) (check-equal? (let ([M (list->flmatrixixix '[[2 4] [3 4]])]) (gauss-eliminate M #t #f)) (list->flmatrixixixix '[[1 2] [0 1]])) (check-equal? (let ([M (list->flmatrixix '[[2. 4.] [3. 4.]])]) (gauss-eliminate M #t #t)) (list->flmatrixix '[[1. 1.3333333333333333] [0. 1.]])) (check-equal? (let ([M (list->flmatrix '[[1 4] [2 4]])]) (gauss-eliminate M #t #t)) (list->flmatrix '[[1 2] [0 1]])) (check-equal? (let ([M (list->flmatrix '[[1 2] [2 4]])]) (gauss-eliminate M #f #t)) (list->flmatrix '[[2 4] [0 0]])))) (with-check-info (['test-case 'flmatrix-scale-row]) (check-equal? (flmatrix-scale-row (flmatrix-identity 3) 0 2) (lists->flmatrix '[[2 0 0] [0 1 0] [0 0 1]]))) (with-check-info (['test-case 'flmatrix-swap-rows]) (check-equal? (flmatrix-swap-rows (lists->flmatrix '[[1 2 3] [4 5 6] [7 8 9]]) 0 1) (lists->flmatrix '[[4 5 6] [1 2 3] [7 8 9]]))) (with-check-info (['test-case 'flmatrix-add-scaled-row]) (check-equal? (flmatrix-add-scaled-row (lists->flmatrix '[[1 2 3] [4 5 6] [7 8 9]]) 0 2 1) (lists->flmatrix '[[9 12 15] [4 5 6] [7 8 9]]))) (let () (define M (lists->flmatrix '[[1 1 0 3] [2 1 -1 1] [3 -1 -1 2] [-1 2 3 -1]])) (define-values (P L U) (flmatrix-plu M)) (with-check-info (['test-case 'flmatrix-plu]) (check-equal? (flmatrix* P (flmatrix* L U)) M))) (with-check-info (['test-case 'flmatrix-rank]) (check-equal? (flmatrix-rank (list->flmatrix '[[0 0] [0 0]])) 0) (check-equal? (flmatrix-rank (list->flmatrix '[[1 0] [0 0]])) 1) (check-equal? (flmatrix-rank (list->flmatrix '[[1 0] [0 3]])) 2) (check-equal? (flmatrix-rank (list->flmatrix '[[1 2] [2 4]])) 1) (check-equal? (flmatrix-rank (list->flmatrix '[[1 2] [3 4]])) 2)) (with-check-info (['test-case 'flmatrix-nullity]) (check-equal? (flmatrix-nullity (list->flmatrix '[[0 0] [0 0]])) 2) (check-equal? (flmatrix-nullity (list->flmatrix '[[1 0] [0 0]])) 1) (check-equal? (flmatrix-nullity (list->flmatrix '[[1 0] [0 3]])) 0) (check-equal? (flmatrix-nullity (list->flmatrix '[[1 2] [2 4]])) 1) (check-equal? (flmatrix-nullity (list->flmatrix '[[1 2] [3 4]])) 0)) ; Not implemented yet... #;(let () (define-values (c1 n1) (flmatrix-column+null-space (list->flmatrix '[[0 0] [0 0]]))) (define-values (c2 n2) (flmatrix-column+null-space (list->flmatrix '[[1 2] [2 4]]))) (define-values (c3 n3) (flmatrix-column+null-space (list->flmatrix '[[1 2] [2 5]]))) (with-check-info (['test-case 'flmatrix-column+null-space]) (check-equal? c1 '()) (check-equal? n1 (list (list->flmatrix '[[0] [0]]) (list->flmatrix '[[0] [0]]))) (check-equal? c2 (list (list->flmatrix '[[1] [2]]))) ;(check-equal? n2 '([0 0])) (check-equal? c3 (list (list->flmatrix '[[1] [2]]) (list->flmatrix '[[2] [5]]))) (check-equal? n3 '())))) (with-check-info (['test-group "matrix-multiply.rkt"]) (with-check-info (['test-case 'flmatrix*]) (let () (define-values (A B AB) (values '[[1 2] [3 4]] '[[5 6] [7 8]] '[[19 22] [43 50]])) (check-equal? (flmatrix* (list->flmatrix A) (list->flmatrix B)) (list->flmatrix AB))) (let () (define-values (A B AB) (values '[[1 2] [3 4]] '[[5 6 7] [8 9 10]] '[[21 24 27] [47 54 61]])) (check-equal? (flmatrix* (list->flmatrix A) (list->flmatrix B)) (list->flmatrix AB)))))) (define (build-flmatrix m n f) (for*/flmatrix m n ([i (in-range m)] [j (in-range n)]) (f i j)))
true
44a3b8774a70d5468021cde1d6f533e036e4db19
fa659fbb3ae62b3d16c551a6499776c2ec75e017
/Functional programming basics/labs/03/memo.rkt
1c12d77a765ed67b68049236ac3b39a12344d1ae
[]
no_license
stepanplaunov/bmstu-ics9
fe5683371a7806154c735085b075ba94132afd05
d3b1294626512fa0faf347c14856c65d7fa663d6
refs/heads/master
2023-03-16T03:32:06.492608
2020-09-17T08:54:09
2020-09-17T08:54:09
null
0
0
null
null
null
null
UTF-8
Racket
false
false
413
rkt
memo.rkt
(define tribm (let ((memo '())) (lambda (n) (let ((memorized (assq n memo))) (if memorized (cadr memorized) (let ((new-value (if (<= n 1) 0 (if (= n 2) 1 (+ (tribm (- n 1)) (tribm (- n 2)) (tribm (- n 3))))))) (set! memo (cons (list n new-value) memo)) new-value)))))) (tribm 5) ; 1 1 2 4 7 13
false
a51396366a7ec9951cf43c2cef5d3dc55fcca964
c86d2725ede9f022a4ac9a33ab94f452db32a19b
/models/stlc.rkt
08e49bfa5d8afc6a3f4af03ee7c5b65215afae36
[ "MIT" ]
permissive
rfindler/Grift
e38f0d680e423a6ae9365d674376aa24563dab2d
01061bbf9916e18cba340044e9f0fa8b4379f202
refs/heads/master
2020-03-21T15:06:10.102115
2018-06-26T06:33:17
2018-06-26T06:34:08
138,694,386
0
0
null
2018-06-26T06:30:13
2018-06-26T06:30:13
null
UTF-8
Racket
false
false
18,928
rkt
stlc.rkt
#lang racket (require "helpers.rkt" (for-syntax racket/syntax)) (provide (all-from-out "helpers.rkt")) (provide ;; The syntax of the simply typeded lambda calculus STLC STLC/tc ;; Alpha equivalence ;; (=α t1 t2) : metafunction ;; is t1 alpha equivalent to t2? =α ;; (=α/racket t1 t2) racket function ;; is t1 alpha equivalent to t2? =α/racket ;; (⊢ ((xs Ts) ...) e T) : Judgement (⊢ I I O) ;; from the environment, ((xs Ts) ...), we can infer that expression ;; e is of type T. ⊢ ;; Reduction relation for the calculus -->β ;; Standard reduction relation for the call-by value semantics s->βv ;; (tyop o) what is the type of o. tyop) (define-language STLC ;; Things that should definately not be included in the grammar ;; if produced as a pic or pdf (Γ ::= · (x any Γ)) (x ::= variable-not-otherwise-mentioned) (i ::= integer) (b ::= boolean) (k ::= i b ()) (B ::= Int Bool ()) ;; End things that must not be named (e ::= k x f (letrec ([x : T f]) e) (letrec2 ([x_!_ : T f] [x_!_ : T f]) e) (let ([x : T e]) e) (let2 ([x_!_ : T e] [x_!_ : T e]) e) (o e e) (e e) (if e e e)) (f ::= (lambda ([x : T]) e)) ;; (o ::= + - * =) ;; Types (T ::= B (T -> T)) #:binding-forms (lambda ([x_param : T_param]) e #:refers-to x_param) (let ([x_bnd : T_bnd e_bnd]) e #:refers-to x_bnd) (let2 ([x_1 : T_1 e_1] [x_2 : T_2 e_2]) e #:refers-to (shadow x_1 x_2)) (letrec ([x_bnd : T_bnd e_bnd #:refers-to x_bnd]) e #:refers-to x_bnd) (letrec2 ([x_1 : T_1 e_1 #:refers-to (shadow x_1 x_2)] [x_2 : T_2 e_2 #:refers-to (shadow x_1 x_2)]) e #:refers-to (shadow x_1 x_2))) (module+ test (test-true (alpha-equivalent? STLC (term (lambda ([x : Int]) x)) (term (lambda ([y : Int]) y)))) (test-true (alpha-equivalent? STLC (term (lambda ([x : Int]) (lambda ([y : Int]) y))) (term (lambda ([y : Int]) (lambda ([y : Int]) y))))) (test-false (alpha-equivalent? STLC (term (lambda ([x : Int]) (lambda ([y : Int]) y))) (term (lambda ([x : Int]) (lambda ([y : Int]) x))))) (test-true (alpha-equivalent? STLC (term (let ([x : Int 1]) x)) (term (let ([y : Int 1]) y)))) (test-true (alpha-equivalent? STLC (term (letrec ([x : Int x]) x)) (term (letrec ([y : Int y]) y)))) (test-true (alpha-equivalent? STLC (term (letrec2 ([x : Int y] [y : Int x]) x)) (term (letrec2 ([y : Int x] [x : Int y]) y)))) (test-false (alpha-equivalent? STLC (term (letrec2 ([x : Int y] [y : Int x]) x)) (term (letrec2 ([x : Int y] [y : Int x]) y))))) ;;———————————————————————————————————————————————————–———————————————————–—————— ;; Scope helpers #; (define-metafunction STLC in : any (any ...) -> boolean [(in any_1 (any_n ... any_1 any_m ...)) #t] [(in _ _) #f]) (module+ test ;; Example programs to test fvs, bvs, and =α (define xfree0 (term (lambda ([y : ()]) (lambda ([z : ()]) x)))) (define xfree1 (term ((lambda ([x : ()]) x) x))) (define x!free0 (term (lambda ([x : ()]) x))) (define x!free1 (term (lambda ([x : ()]) (x x)))) (define xbound0 (term (lambda ([x : ()]) (x x)))) (define xbound1 (term ((lambda ([x : ()]) x) x))) (define x!bound0 (term (lambda ([y : ()]) (lambda ([z : ()]) x)))) (define x!bound1 (term ((lambda ([x : ()]) z) x))) (define fst0 (term (lambda ([x : ()]) (lambda ([y : ()]) x)))) (define fst1 (term (lambda ([n : ()]) (lambda ([m : ()]) n)))) (define snd0 (term (lambda ([x : ()]) (lambda ([y : ()]) y)))) (define snd1 (term (lambda ([n : ()]) (lambda ([m : ()]) m)))) (test-true (redex-match? STLC e fst0)) (test-true (redex-match? STLC e fst1)) (test-true (redex-match? STLC e snd0)) (test-true (redex-match? STLC e snd1)) ) ;; fvs : Collect the unique free variables of a gradual expression #; (define-metafunction STLC fvs : any -> (x_!_ ...) [(fvs x) (x)] [(fvs (lambda ([x : _] ...) any)) ,(set-subtract (term (fvs any)) (term (x ...)))] [(fvs (any ...)) ,(foldr set-union (term ()) (term ((fvs any) ...)))]) ;; fv? : Does a variable occur free in a expression? #; (define-metafunction STLC fv? : x any -> boolean [(fv? x any) (in x (fvs any))]) #; (module+ test (test-true (term (fv? x ,xfree0))) (test-true (term (fv? x ,xfree1))) (test-false (term (fv? x ,x!free0))) (test-false (term (fv? x ,x!free1)))) ;; bvs : return the bound variables of an expression #; (define-metafunction STLC bvs : any -> (x_!_ ...) [(bvs x) ()] [(bvs (lambda ([x : _] ...) any)) ,(set-union (set-intersect (term (fvs any)) (term (x ...))) (term (bvs any)))] [(bvs (any ...)) ,(foldr set-union (term ()) (term ((bvs any) ...)))]) ;; bv? : test if a variable occurs bound in an expression #; (define-metafunction STLC bv? : x any -> boolean [(bv? x any) (in x (bvs any))]) #; (module+ test (test-true (term (bv? x ,xbound0))) (test-true (term (bv? x ,xbound1))) (test-false (term (bv? x ,x!bound0))) (test-false (term (bv? x ,x!bound1))) (get-coverage)) ;; =α : are two expression alpha equivalent? (define-metafunction STLC =α : any any -> boolean [(=α any any) #t] [(=α _ _) #f]) (define (=α/racket t1 t2) (term (=α ,t1 ,t2))) (module+ test (test-true (term (=α (lambda ([x : ()]) x) (lambda ([y : ()]) y)))) (test-false (term (=α (lambda ([x : ()]) y) (lambda ([y : ()]) y)))) (test-true (term (=α (lambda ([x : ()]) x) (lambda ([x : ()]) x)))) (test-true (term (=α (lambda ([x : ()]) (lambda ([y : ()]) (x y))) (lambda ([x : ()]) (lambda ([y : ()]) (x y)))))) (test-false (term (=α (y x) (a b))))) ;;———————————————————————————————————————————————————–———————————————————–—————— ;; Typing (define-extended-language STLC/tc STLC (Γ ::= · (x T Γ))) (define-environment-helpers (t-lu t-ex) STLC/tc Γ · x T) (define-judgment-form STLC #:mode (⊢_k I O) #:contract (⊢_k k B) [----------------------- "⊢ₖUnit" (⊢_k () ())] [----------------------- "⊢ₖBool" (⊢_k b Bool)] [----------------------- "⊢ₖInt" (⊢_k i Int)]) (define-judgment-form STLC/tc #:mode (⊢ I I O) #:contract (⊢ Γ e T) [(where (some T) (t-lu Γ x)) ------------------------ "wt-var" (⊢ Γ x T)] [(⊢_k k B) ------------------------ "wt-base" (⊢ Γ k B)] [(where Γ_new (t-ex Γ x T)) (⊢ Γ_new e T_e) ------------------------ "wt-lambda" (⊢ Γ (lambda ([x : T]) e) (T -> T_e))] [(where Γ_new (t-ex Γ x T)) (⊢ Γ_new e_body T_body) (⊢ Γ_new f T) ------------------------ "wt-letrec" (⊢ Γ (letrec ([x : T f]) e_body) T_body)] [(where Γ_new (t-ex (t-ex Γ x_1 T_1) x_2 T_2)) (⊢ Γ_new e_body T_body) (⊢ Γ_new f_1 T_1) (⊢ Γ_new f_2 T_2) ------------------------ "wt-letrec2" (⊢ Γ (letrec2 ([x_1 : T_1 f_1] [x_2 : T_2 f_2]) e_body) T_body)] [(where Γ_new (t-ex Γ x_1 T_1)) (⊢ Γ_new e_body T_body) (⊢ Γ e_1 T_1) ------------------------ "wt-let" (⊢ Γ (let ([x_1 : T_1 e_1]) e_body) T_body)] [(where Γ_new (t-ex (t-ex Γ x_1 T_1) x_2 T_2)) (⊢ Γ_new e_body T_body) (⊢ Γ e_1 T_1) (⊢ Γ e_2 T_2) ------------------------ "wt-let2" (⊢ Γ (let ([x_1 : T_1 e_1][x_2 : T_2 e_2]) e_body) T_body)] [(⊢ Γ e_0 (T_1 -> T_r)) (⊢ Γ e_1 T_1) ------------------------ "wt-app" (⊢ Γ (e_0 e_1) T_r)] [(where (T_1 T_2 -> T_r) (tyop o)) (⊢ Γ e_1 T_1) (⊢ Γ e_2 T_2) ------------------------ "wt-op" (⊢ Γ (o e_1 e_2) T_r)] [(⊢ Γ e_t Bool) (⊢ Γ e_c T) (⊢ Γ e_a T) ------------------------ "wt-if" (⊢ Γ (if e_t e_c e_a) T)]) (define-metafunction STLC tyop : o -> (T T -> T) [(tyop +) (Int Int -> Int)] [(tyop -) (Int Int -> Int)] [(tyop *) (Int Int -> Int)] [(tyop =) (Int Int -> Bool)]) (define (gen-stlc-term-and-type!) (match (generate-term STLC #:satisfying (⊢ · e T) (random 1 5)) [`(⊢ · ,e ,t) (values e t)] [#f (gen-stlc-term-and-type!)])) (define-term good.0 (+ 1 2)) (define-term good.1 (lambda ([c : Int]) (lambda ([a : Int]) (+ a c)))) (define-term good.2 (lambda ([a : ()]) (lambda ([b : Bool]) (lambda ([c : Int]) ((if b (lambda ([a : Int]) (+ a c)) (lambda ([b : Int]) (- b c))) 41))))) (define-term good ((((lambda ([a : ()]) (lambda ([b : Bool]) (lambda ([c : Int]) ((if b (lambda ([a : Int]) (+ a c)) (lambda ([b : Int]) (- b c))) 41)))) ()) #t) 1)) (define-term fact5 (letrec ([fact : (Int -> Int) (lambda ([x : Int]) (if (= x 0) 1 (* x (fact (- x 1)))))]) (fact 5))) (define-term fact3 (letrec ([fact : (Int -> Int) (lambda ([x : Int]) (if (= x 0) 1 (* x (fact (- x 1)))))]) (fact 3))) (define-term odd5 (letrec2 ([even? : (Int -> Bool) (lambda ([n : Int]) (if (= n 0) #t (odd? (- n 1))))] [odd? : (Int -> Bool) (lambda ([n : Int]) (if (= n 0) #t (even? (- n 1)))) ]) (odd? 5))) (module+ test (test-true (redex-match? STLC/tc Γ (term ·))) (test-true (redex-match? STLC/tc (lambda ([x : T]) e) fst0)) (test-true (redex-match? STLC/tc T (term (() -> (() -> ()))))) (test-true (judgment-holds (⊢ (t-ex · x ()) x ()))) (test-true (judgment-holds (⊢ · (lambda ([x : ()]) x) (() -> ())))) (test-true (judgment-holds (⊢ · (lambda ([x : ()]) (lambda ([x : ()]) x)) (() -> (() -> ()))))) (test-true (judgment-holds (⊢ · ,fst0 (() -> (() -> ()))))) (test-true (judgment-holds (⊢ · ,fst1 (() -> (() -> ()))))) (test-true (judgment-holds (⊢ · ,snd0 (() -> (() -> ()))))) (test-true (judgment-holds (⊢ · ,snd1 (() -> (() -> ()))))) (test-true (judgment-holds (⊢ · good.0 Int))) (test-true (judgment-holds (⊢ · good.1 (Int -> (Int -> Int))))) (test-true (judgment-holds (⊢ · good.2 (() -> (Bool -> (Int -> Int)))))) (test-true (judgment-holds (⊢ · good Int))) (test-true (judgment-holds (⊢ · fact5 Int))) (test-true (judgment-holds (⊢ · odd5 Bool)))) ;;--------------------------------------------------------------------- ;; The simply typed lambda calculus (define-extended-language STLC-> STLC (v ::= i b () (lambda ([x : T]) e)) (C ::= hole (e ... C e ...) (o e ... C e ...) (if C e e) (if e C e) (if e e C) (letrec ([x : T C]) e) (letrec ([x : T f]) C) (letrec2 ([x : T C] [x : T f]) e) (letrec2 ([x : T f] [x : T C]) e) (letrec2 ([x : T f] [x : T f]) C) (let ([x : T C]) e) (let ([x : T e]) C) (let2 ([x : T C] [x : T e]) e) (let2 ([x : T e] [x : T C]) e) (let2 ([x : T e] [x : T e]) C) (lambda ([x : T]) C))) (define f0 (term (lambda ([x : ()]) x))) (define ex1 (term (,f0 ()))) (define f1 (term (lambda ([f : (() -> ())]) (lambda ([x : ()]) (f x))))) (define ex2 (term ((,f1 ,f0) ,ex1))) (define ex3 (term ((,f1 (,f1 ,f0)) ,ex1))) (module+ test (test-true (judgment-holds (⊢ · ,ex1 ()))) (test-true (judgment-holds (⊢ · ,f1 ((() -> ()) -> (() -> ()))))) (test-true (judgment-holds (⊢ · ,ex2 ()))) (test-true (judgment-holds (⊢ · ,ex3 ())))) (define-metafunction STLC-> δ : o e ... -> e [(δ + i_1 i_2) ,(+ (term i_1) (term i_2))] [(δ - i_1 i_2) ,(- (term i_1) (term i_2))] [(δ * i_1 i_2) ,(* (term i_1) (term i_2))] [(δ = i_1 i_2) ,(= (term i_1) (term i_2))]) (define -->β (reduction-relation STLC-> (--> (in-hole C ((lambda ([x : _]) e_b) e_p)) (in-hole C (substitute e_b x e_p)) β) ;; Primitive operators are evaluated using the delta metafuntion (--> (in-hole C (o v_1 v_2)) (in-hole C (δ o v_1 v_2)) δ) ;; Letrecs get unrolled by one loop (--> (in-hole C (letrec ([x : T f]) e)) (in-hole C (substitute e x e_knot)) (where e_knot (letrec ([x : T f]) f)) μ) (--> (in-hole C (letrec2 ([x_1 : T_1 f_1][x_2 : T_2 f_2]) e)) (in-hole C (substitute (substitute e x_1 e_knot1) x_2 e_knot2)) (where e_knot1 (letrec2 ([x_1 : T_1 f_1][x_2 : T_2 f_2]) f_1)) (where e_knot2 (letrec2 ([x_1 : T_1 f_1][x_2 : T_2 f_2]) f_2)) μ2) ;; Let get unrolled by one loop (--> (in-hole C (let ([x : T e]) e_body)) (in-hole C (substitute e_body x e)) let) (--> (in-hole C (let2 ([x_1 : T_1 e_1][x_2 : T_2 e_2]) e)) (in-hole C (substitute (substitute e x_1 e_1) x_2 e_2)) let2) ;; Branching conditionals (--> (in-hole C (if #t e_c e_a)) (in-hole C e_c) ift) (--> (in-hole C (if #f e_c e_a)) (in-hole C e_a) iff))) (module+ test (test-->> -->β #:equiv =α/racket ex1 (term ())) (test-->> -->β #:equiv =α/racket ex2 (term ())) (test-->> -->β #:equiv =α/racket ex3 (term ()))) (begin-for-syntax (define-syntax-rule (with-prefixed-ids p (i ...) b ...) (with-syntax ([(i ...) #`(#,(format-id #'p "~a~a" #'p #'i) ...)]) b ...))) ;; ——————- ;; call by value semantics for the simply typed lambda calculus (define-syntax (define-stlc-like-reduction-relation stx) (syntax-case stx () [(_ s->βv lang var unit int bool fun expr type oper) (with-prefixed-ids stlc (e e_f e_b e_k e_k1 e_k2 e_c e_a v v_1 v_2 E o f x x_b x_f x_1 x_2 x_12 x_22 T T_b T_f T_1 T_2 T_12 T_22) #`(begin ))])) (define-extended-language cbv STLC #;(o ::= oper) #;(e ::= expr) #;(f ::= fun) #;(v ::= unit int bool fun) (v ::= () i b f) #;(x ::= var) #;(T ::= type) (E ::= hole (E e) (v E) (o E e) (o v E) (if E e e) (let ([x : T E]) e) (let2 ([x : T E] [x : T e]) e) (let2 ([x : T v] [x : T E]) e))) (define s->βv (reduction-relation cbv ;; Standard Beta for Call by Value (--> (in-hole E ((lambda ([x : T]) e) v)) (in-hole E (substitute e x v)) β) ;; Primitive operators are evaluated using the delta metafuntion (--> (in-hole E (o v_1 v_2)) (in-hole E (δ o v_1 v_2)) δ) ;; Letrecs get unrolled by one loop (--> (in-hole E (letrec ([x_b : T_b (lambda ([x_f : T_f]) e_f)]) e_b)) (in-hole E (substitute e_b x_b e_k)) (where e_k (letrec ([x_b : T_b (lambda ([x_f : T_f]) e_f)]) (lambda ([x_f : T_f]) e_f))) μ) (--> (in-hole E (letrec2 ([x_1 : T_1 (lambda ([x_12 : T_12]) e_1)] [x_2 : T_2 (lambda ([x_22 : T_22]) e_2)]) e_b)) (in-hole E (substitute (substitute e_b x_1 e_k1) x_2 e_k2)) (where e_k1 (letrec2 ([x_1 : T_1 (lambda ([x_12 : T_12]) e_1)] [x_2 : T_2 (lambda ([x_22 : T_22]) e_2)]) (lambda ([x_12 : T_12]) e_1))) (where e_k2 (letrec2 ([x_1 : T_1 (lambda ([x_12 : T_12]) e_1)] [x_2 : T_2 (lambda ([x_22 : T_22]) e_2)]) (lambda ([x_22 : T_22]) e_2))) μ2) ;; Let get unrolled by one loop (--> (in-hole E (let ([x : T v]) e_b)) (in-hole E (substitute e_b x v)) let) (--> (in-hole E (let2 ([x_1 : T_1 v_1][x_2 : T_2 v_2]) e)) (in-hole E (substitute (substitute e x_1 v_1) x_2 v_2)) let2) ;; Branching conditionals (--> (in-hole E (if #t e_c e_a)) (in-hole E e_c) ift) (--> (in-hole E (if #f e_c e_a)) (in-hole E e_a) iff))) #; (define-stlc-like-reduction-relation s->βv STLC v () i b f e T o) (module+ test (add-coverage! s->βv) (test-->> s->βv #:equiv =α/racket (term ()) (term ())) (test-->> s->βv #:equiv =α/racket (term ((lambda ([x : ()]) ()) ())) (term ())) (test-->> s->βv #:equiv =α/racket (term ((lambda ([x : ()]) x) ())) (term ())) (test-->> s->βv #:equiv =α/racket ex1 (term ())) (test-->> s->βv #:equiv =α/racket ex2 (term ())) (test-->> s->βv #:equiv =α/racket ex3 (term ())) (test-->> s->βv #:equiv =α/racket (term fact3) 6) (test-->> s->βv #:equiv =α/racket (term odd5) #t)) (define-judgment-form STLC #:mode (=> I O) #:contract (=> e e) [(where (e_2) ,(apply-reduction-relation s->βv (term e_1))) -------------------- (=> e_1 e_2)]) (define-judgment-form STLC #:mode (progress I) #:contract (progress e) [(where #f ,(judgment-holds (⊢ · e T))) --------------------------------------- "progress e ∉ T " (progress e)] [--------------- "progress e=v" (progress v)] [(=> e_1 e_2) ----------------------------- "progress e->e'" (progress e_1)]) (define-judgment-form STLC #:mode (preservation I) #:contract (preservation e) [(where #f ,(judgment-holds (⊢ · e T))) --------------------------------------- "preservation e ∈ T " (preservation e)] [-------------------- "preservation e -/-> e'" (preservation v)] [(=> e_1 e_2) (⊢ · e_1 T) (⊢ · e_2 T) -------------------- "presevation " (preservation e_1)]) (define-judgment-form STLC #:mode (sound I) #:contract (sound e) [(progress e) (preservation e) -------------------- "" (sound e)]) (module+ test (redex-check STLC #:satisfying (⊢ · e t) (judgment-holds (sound e))))
true
a397385030aa736578bf0dce647bcc45613d254b
063934d4e0bf344a26d5679a22c1c9e5daa5b237
/racket/margrave-ios.rkt
7d405021b667432c4fc38b700bd9f70d2d070b08
[]
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
14,467
rkt
margrave-ios.rkt
; Copyright © 2009-2012 Brown University and Worcester Polytechnic Institute. ; ; This file is part of Margrave. ; Margrave is free software: you can redistribute it and/or modify ; it under the terms of the GNU Lesser General Public License as published by ; the Free Software Foundation, either version 3 of the License, or ; (at your option) any later version. ; ; Margrave is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ; GNU Lesser General Public License for more details. ; ; You should have received a copy of the GNU Lesser General Public License ; along with Margrave. If not, see <http://www.gnu.org/licenses/>. #lang racket (require "margrave.rkt" "IOS-parser/ios-compile.rkt") ; Others provided via provide/contract (provide load-ios-policies vardec-internal ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (provide/contract (parse-and-load-ios-by-filename ([string?] [#:prefix string? #:suffix string? #:syntax syntax?] . ->* . string?))) (define (parse-and-load-ios-by-filename raw-filename #:prefix [prefix ""] #:suffix [suffix ""] #:syntax [src-syntax #f]) ;; *MARGRAVE* --> margrave collection path (define the-filename (resolve-margrave-filename-keyword raw-filename)) (file-exists?/error the-filename src-syntax (format "Could not find IOS configuration file: ~a" the-filename)) (define-values (fn-path fn-filepath must-dir) (split-path the-filename)) (define fn-file (path->string fn-filepath)) (when must-dir (raise-user-error (format "Expected a filename, but given: ~a." the-filename))) ; 'relative for the path if no "path" given ;(printf "~a ~a ~a ~a ~a~n" fn-file fn-path margrave-home-path fn-filepath the-filename) (if (equal? 'relative fn-path) (parse-and-load-ios fn-file (string->path ".") prefix suffix) (parse-and-load-ios fn-file fn-path prefix suffix)) (string-append "Success: loaded IOS configuration at: " the-filename "\n")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; parse-and-load-ios: First parses an IOS config file ; and then calls load-ios-policies on the directory ; containing the sub-policies. (provide/contract (parse-and-load-ios (string? (or/c path? string?) string? string? . -> . void?))) (define (parse-and-load-ios config-file-name dirpath prefix suffix) (printf "Parsing IOS configuration ~a in directory ~a ...~n" config-file-name dirpath) ; May be a #path or a string. IOS parser expects a string. (cond [(string? dirpath) (compile-configurations dirpath (list config-file-name) #f)] [(path? dirpath) (compile-configurations (path->string dirpath) (list config-file-name) #f)] [else (raise-user-error (format "Expected a directory path in the second argument of parse-and-load-ios; given: ~a." dirpath))]) (load-ios-policies dirpath prefix suffix)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; parse-and-load-multi-ios: Same as parse-and-load-ios, but ; allows multiple filenames per config (provide/contract (parse-and-load-multi-ios ([(listof string?) (or/c path? string?)] [#:prefix string? #:suffix string? #:syntax syntax?] . ->* . string?))) (define (parse-and-load-multi-ios config-file-name-list pre-dirpath #:prefix [prefix ""] #:suffix [suffix ""] #:syntax [src-syntax #f]) (define dirpath (resolve-margrave-filename-keyword pre-dirpath)) (printf "Parsing multiple IOS configurations in directory ~a ...~n" dirpath) (for-each (lambda (fn) (file-exists?/error (build-path dirpath fn) src-syntax (format "Could not find IOS configuration file: ~a" (path->string (build-path dirpath fn))))) config-file-name-list) ; !!! todo factor out duplicate code -tn ; May be a #path or a string. IOS parser expects a string. (cond [(string? dirpath) (compile-configurations dirpath config-file-name-list #f)] [(path? dirpath) (compile-configurations (path->string dirpath) config-file-name-list #f)] [else (raise-user-error (format "Expected a directory path in the second argument of parse-and-load-multi-ios; given: ~a." dirpath))]) (load-ios-policies dirpath prefix suffix) (string-append "Success: loaded IOS configurations in: " dirpath "\n")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; 14 variables exposing modification of packet and exit interface, ; hiding internal addresses used between in/out nat, next-hop. (define vardec-internal '([ahostname Hostname] [entry Interface] [sa IPAddress] [da IPAddress] [sp Port] [dp Port] [protocol Protocol-any] [paf PayloadAndFlags] [exit Interface] [sa2 IPAddress] [da2 IPAddress] [sp2 Port] [dp2 Port])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (load-ios-helper filename dirpath prefix suffix) (define pol-id (string-append prefix filename suffix)) (m-load-policy pol-id (build-path dirpath (string-append filename ".p"))) (printf ".")) ; ------------------------------------------------ ; load-ios-policies: Given a directory with post-parse sub-policies, load them all. ; Remember to start the engine before calling this. ; dirpath says where to find the policies ; prefix (and suffix) are prepended (and appended) to the ; policy's name to avoid naming conflicts. (define (load-ios-policies dirpath prefix suffix (verbose #f)) (printf "Loading IOS policies in path: ~a. Adding prefix: ~a and suffix: ~a ~n" dirpath prefix suffix) ; ACLs (load-ios-helper "InboundACL" dirpath prefix suffix) (load-ios-helper "OutboundACL" dirpath prefix suffix) ; NATs (load-ios-helper "InsideNAT" dirpath prefix suffix) (load-ios-helper "OutsideNAT" dirpath prefix suffix) ; Routing and switching (load-ios-helper "StaticRoute" dirpath prefix suffix) (load-ios-helper "PolicyRoute" dirpath prefix suffix) (load-ios-helper "DefaultPolicyRoute" dirpath prefix suffix) (load-ios-helper "LocalSwitching" dirpath prefix suffix) (load-ios-helper "NetworkSwitching" dirpath prefix suffix) ; Encryption (not currently tested) (load-ios-helper "Encryption" dirpath prefix suffix) (printf "~n") ;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Internal-Result ;;;;;;;;;;;;;;;;;;;;;;;;;;; (define inboundacl (string->symbol (string-append prefix "InboundACL" suffix))) (define outboundacl (string->symbol (string-append prefix "OutboundACL" suffix))) (define insidenat (string->symbol (string-append prefix "InsideNAT" suffix))) (define outsidenat (string->symbol (string-append prefix "OutsideNAT" suffix))) (define staticroute (string->symbol (string-append prefix "StaticRoute" suffix))) (define policyroute (string->symbol (string-append prefix "PolicyRoute" suffix))) (define defaultpolicyroute (string->symbol (string-append prefix "DefaultPolicyRoute" suffix))) (define localswitching (string->symbol (string-append prefix "LocalSwitching" suffix))) (define networkswitching (string->symbol (string-append prefix "NetworkSwitching" suffix))) (define encryption (string->symbol (string-append prefix "Encryption" suffix))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ACLs are not involved in internal-result, which is concerned with routing, switching and NAT. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (m-let (string-append prefix "internal-result" suffix) vardec-internal `(exists src-addr_ IPAddress (exists dest-addr_ IPAddress (exists src-port_ Port (exists dest-port_ Port (exists next-hop IPAddress (and ([,outsidenat translate] ahostname entry sa da sp dp protocol src-addr_ dest-addr_ src-port_ dest-port_) ([,insidenat translate] ahostname entry src-addr_ dest-addr_ src-port_ dest-port_ protocol sa2 da2 sp2 dp2) ; NAT translation confirmed. Now see if and how the packet is routed. ; Routing can either go to a gateway (route) or an interface (forward) ; Local routing just checks if the destination is a local interface. ; First option: localswitching sends immediately, because the destination is attached. ; In this case next-hop isn't strictly needed, so we set it equal to destination to avoid confusion. ; Other options use networkswitching and one of the routing policies. ; The routing policies will fix next-hop. ; !!! TN: I am concerned about that places that (= next-hop dest-addr-in) still appears in the ios.ss file. ; If odd behavior occurs with switching, examine that first. (or (and (= next-hop dest-addr_) ([,localswitching forward] ahostname dest-addr_ exit)) (and ([,localswitching pass] ahostname dest-addr_ exit)) (or ([,policyroute forward] ahostname entry src-addr_ dest-addr_ src-port_ dest-port_ protocol next-hop exit) (and ([,policyroute route] ahostname entry src-addr_ dest-addr_ src-port_ dest-port_ protocol next-hop exit) ([,networkswitching forward] ahostname next-hop exit)) (and ([,policyroute pass] ahostname entry src-addr_ dest-addr_ src-port_ dest-port_ protocol next-hop exit) (or ([,staticroute forward] ahostname dest-addr_ next-hop exit) (and ([,staticroute route] ahostname dest-addr_ next-hop exit) ([,networkswitching forward] ahostname next-hop exit)) (and ([,staticroute pass] ahostname dest-addr_ next-hop exit) (or ([,defaultpolicyroute forward] ahostname entry src-addr_ dest-addr_ src-port_ dest-port_ protocol next-hop exit) (and ([,defaultpolicyroute route] ahostname entry src-addr_ dest-addr_ src-port_ dest-port_ protocol next-hop exit) ([,networkswitching forward] ahostname next-hop exit)) ; Final option: Packet is dropped. (and ([,defaultpolicyroute pass] ahostname entry src-addr_ dest-addr_ src-port_ dest-port_ protocol next-hop exit) (= next-hop dest-addr_) (interf-drop exit))))))))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Int-dropped: Just check for NOT interf-drop(exit-interface). ; Need to use an UNDER clause since there are no policies appearing. ; ; Technically there's no reason to have this IDB take more than exit-interface. ; However, for now, we use the standard policy request vector, and so must ; use EACH variable in the query definition. ;;;;;;;;;;;;;;;;;;;;;;;;;;; ; (m-let (string-append prefix "int-dropped" suffix) ; vardec-16 ; `(and (Interf-drop exit-interface) ; ) #:under (list (symbol->string inboundacl))) ;(define xml-response-id (mtext (string-append "EXPLORE interf-drop(exit-interface) AND ; IPAddress(src-addr-in) AND IPAddress(src-addr-out) AND IPAddress(dest-addr-in) AND IPAddress(dest-addr-out) AND ;Port(dest-port-out) AND Port(dest-port-in) AND Port(src-port-out) AND Port(src-port-in) AND IPAddress(next-hop) AND ;ICMPMessage(message) AND Interface(entry-interface) AND Interface(exit-interface) and Length(length) AND ;Protocol-any(protocol) AND Hostname(ahostname) AND TCPFlags(flags) ;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Firewall-Passed ;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Do NOT assert internal-result in this query. Why? Because then it cannot be safely ;; negated to mean the packets the firewall drops (or rejects). It would then also ;; include all the nonsensical scenarios... ; Therefore, this query doesn't have the full arity of internal-result. (No src-addr_ etc.) ;;;;;;;;; ^^^^ REVISE THIS: is this restriction still needed? ; paf contains what were once separate: message, flags, length. ; next-hop is only represented inside internal-result (define aclinvec '(ahostname entry sa da sp dp protocol paf)) (define acloutvec '(ahostname exit sa2 da2 sp2 dp2 protocol paf)) (m-let (string-append prefix "passes-firewall" suffix) vardec-internal `(and (not (interf-drop exit)) ([,inboundacl permit] ,@aclinvec ) ([,outboundacl permit] ,@acloutvec))) ; end )
false
a3b858934efbb84559f2f97d7316d2e98919ca94
f76f39038e00e7e526d9e29f967101142b0186a4
/hw4/hw4.rkt
c4ea43b3569756b840402b8b96fc141b6fa14183
[]
no_license
rickyzhang-cn/cse341
23cd91666d755915555a34487f3baa28523e693c
d4e42cb7d17afa00bbb15ce7790e98792649319f
refs/heads/master
2021-01-19T00:46:49.506262
2016-10-13T08:31:52
2016-10-13T08:31:52
60,955,453
0
2
null
null
null
null
UTF-8
Racket
false
false
3,377
rkt
hw4.rkt
#lang racket (provide (all-defined-out)) ;; so we can put tests in a second file ;; put your code below (define (sequence spacing low high) (if (> low high) null (cons low (sequence spacing (+ low spacing) high)))) (define (string-append-map xs suffix) (map (lambda (i) (string-append i suffix)) xs)) (define (list-nth-mod xs n) (cond [(< n 0) (error "list-nth-mod: negative number")] [(null? xs) (error "list-nth-mod: empty list")] [#t (car (list-tail xs (remainder n (length xs))))])) (define (stream-for-k-steps s k) (if (= k 0) null (cons (car (s)) (stream-for-k-steps (cdr (s)) (- k 1))))) (define funny-number-stream (letrec ([f (lambda (x) (if (= (remainder x 6) 0) (cons (- x) (lambda () (f (+ x 1)))) (cons x (lambda () (f (+ x 1))))))]) (lambda () (f 1)))) (define dan-then-dog (letrec ([f (lambda (x) (if (= x 1) (cons "dan.jpg" (lambda () (f 0))) (cons "dog.jpg" (lambda () (f 1)))))]) (lambda () (f 1)))) (define (stream-add-one s) (letrec ([f (lambda (x) (cons (cons 1 (car (x))) (lambda () (f (cdr (x))))))]) (lambda () (f s)))) (define (cycle-lists xs ys) (letrec ([f (lambda (n) (cons (cons (list-nth-mod xs n) (list-nth-mod ys n)) (lambda () (f (+ n 1)))))]) (lambda () (f 0)))) (define (vector-assoc v vec) (letrec ([len (vector-length vec)] [helper (lambda (i) (if (< i len) (letrec ([p (vector-ref vec i)]) (if (and (pair? p) (equal? v (car p))) p (helper (+ i 1)))) #f))]) (helper 0))) (define (caching-assoc xs n) (letrec ([index 0] [cache (make-vector n #f)] [ret-func (lambda (v) (letrec ([r (vector-assoc v cache)]) (if r (begin (print "found in cache") r) (letrec ([t (vector-assoc v xs)]) (if t (begin (print "found in xs") (vector-set! cache index t) (set! index (remainder (+ index 1) n)) t) #f)))))]) ret-func)) ;(define-syntax while-greater ; (syntax-rules (do) ; [(while-greater e1 do e2) ; (let ([t e1]) ; (if (< t e2) ; (while-greater t do e2) ; #t))])) (define-syntax while-greater (syntax-rules (do) [(while-greater e1 do e2) (letrec ([t e1] [loop (lambda (i) (if (< t i) (loop e2) #t))]) (loop e2))])) (define (cycle-lists-chal xs ys) (letrec ([xlen (length xs)] [ylen (length ys)] [f (lambda (i) (cons (cons (list-ref xs (remainder i xlen)) (list-ref ys (remainder i ylen))) (lambda () (f (+ i 1)))))]) (lambda () (f 0))))
true
7a9c907e131ce8f4dd02c0bd62f8a5bf53406320
2bb711eecf3d1844eb209c39e71dea21c9c13f5c
/test/unbound/mochi/max.rkt
67047e8f6601901d32fed6692e7137692e81d340
[ "BSD-2-Clause" ]
permissive
dvvrd/rosette
861b0c4d1430a02ffe26c6db63fd45c3be4f04ba
82468bf97d65bde9795d82599e89b516819a648a
refs/heads/master
2021-01-11T12:26:01.125551
2017-01-25T22:24:27
2017-01-25T22:24:37
76,679,540
2
0
null
2016-12-16T19:23:08
2016-12-16T19:23:07
null
UTF-8
Racket
false
false
346
rkt
max.rkt
#lang rosette/unbound (dbg-level 0) (define-symbolic x y z integer?) (define/unbound max (max2) (x y z) (~> integer? integer? integer? integer?) (max2 (max2 x y) z)) (define/unbound (f x y) (~> integer? integer? integer?) (if (>= x y) x y)) (time (let ([m (max f x y z)]) ; Expecting unsat (verify/unbound (assert (= (f x m) m)))))
false
1c92ed1118ee98fc62a89f189906beb72165a0f0
23d78f4c06e9d61b7d90d8ebd035eb1958fe2348
/racket/compiler/parser/nfa.rkt
17f21d560fbb45585914e3ba4d11ae1f4d78efb0
[ "Unlicense" ]
permissive
seckcoder/pl_research
e9f5dbce4f56f262081318e12abadd52c79d081d
79bb72a37d3862fb4afcf4e661ada27574db5644
refs/heads/master
2016-09-16T09:40:34.678436
2014-03-22T02:31:08
2014-03-22T02:31:08
null
0
0
null
null
null
null
UTF-8
Racket
false
false
6,405
rkt
nfa.rkt
#lang racket (require "../../base/utils.rkt") (provide make-nfa merge-nfa state? trans-end sigma-trans? hash-add-trans!) ; Regexp ::= String | Char | letter | digit | whitespace | any ; ::= (not Char) | (or {Regexp}!) ; :: = (arbno Regexp) | ({Regexp}!) ; Explanation: ; String, Char means any unit representable in the text editor. ; letter: any character except empty space, ; digit: 0-9 ; whitespace: space, tab, new-line, form-feed ; any: any thing ; NFA ::= (start end (i a j) ...) ; Several assumtions for nfa to simplify the code ; - only sigma trans for multi trans ; - only one end state(If there are multi end states, we'll construct sigma trans for each end state to our ultimate end state) ; - We don't accept sigma. sigma is only introduced during the nfa construction ; Character ::= String | char | letter | digit | whitespace | any ; a ::= Character | (not Character) (define state? number?) (define gen-state (let ([n -1]) (lambda () (set! n (add1 n)) n))) (define nfa-start car) (define nfa-end cadr) (define nfa-trans caddr) (define trans-start car) (define trans-a cadr) (define trans-end caddr) (define (sigma-trans? trans) (eq? (trans-a trans) 'sigma)) (define (sigma-trans start end) `(,start sigma ,end)) (define (concat-two-nfa nfa1 nfa2) (list (nfa-start nfa1) (nfa-end nfa2) (append (nfa-trans nfa1) (nfa-trans nfa2) ; nfa1-end ---> nfa2-start (list (sigma-trans (nfa-end nfa1) (nfa-start nfa2)))))) (define (concat-nfas nfas) (cond [(null? nfas) (error 'concat-nfas "bad nfas")] [(null? (cdr nfas)) (car nfas)] [else (concat-nfas (cons (concat-two-nfa (car nfas) (cadr nfas)) (cddr nfas)))])) ; create nfa from regular expression (define (make-nfa reg) (let ([start (gen-state)] [end (gen-state)] [character? (lambda (v) (or (string? v) (char? v) (memq v '(letter digit whitespace any))))]) (match reg [(? character? c) `(,start ,end ((,start ,c ,end)))] [`(not ,(? character? c)) `(,start ,end ((,start ,reg ,end)))] [`(or ,reg0 ,reg* ...) ; or-comb several automaton (let ([nfas (map make-nfa (cons reg0 reg*))]) (list start end (flatmap (match-lambda [(list a-start a-end a-trans) (append a-trans (list (sigma-trans start a-start) (sigma-trans a-end end)))]) nfas)))] [`(concat ,reg0 ,reg* ...) (let ([nfas (map make-nfa (cons reg0 reg*))]) ; concat several automation (concat-nfas nfas))] [`(arbno ,reg) ; arbno-comb a regular expression (let* ([unit-nfa (make-nfa reg)] [unit-start (nfa-start unit-nfa)] [unit-end (nfa-end unit-nfa)]) (list start end (append (nfa-trans unit-nfa) (list (sigma-trans unit-end start) (sigma-trans unit-end end) (sigma-trans start unit-start) (sigma-trans start end)) )))] [_ (error 'nfa "the format of regular expression:~a is not right" reg)] ))) (define (hash-add-trans! htb trans) (match trans [`(,start ,a ,end) (if (not (hash-has-key? htb start)) (hash-set! htb start (list trans)) (hash-set! htb start (cons trans (hash-ref htb start))))])) ; merge nfa's trans into a hashtable. ; re-arrange the key's numbering from 0 (define (merge-nfa nfa) (let* ([htb (make-hasheq)]) (for-each (lambda (trans) (hash-add-trans! htb trans)) (nfa-trans nfa)) (match (re-hash (nfa-start nfa) (nfa-end nfa) htb) [(list start end htb) (list start end htb)]))) ; create a new hashtable from htb, with start maping to zero, end mapping ; to the max number, all key's numbering is restricted in [zero, max] (define (re-hash start end htb) (let* ([keys (hash-keys htb)] [values (flatmap (lambda (k) (flatmap (lambda (trans) (match trans [`(,start ,a ,end) (list start end)] [_ (error 'test1 "b")] )) (hash-ref htb k))) keys)] [min-k (apply min values)] [max-k (apply max values)] [hash-fun (lambda (k) ; the hash function (cond [(= k start) ; start mapping to zero 0] [(= k end) ; end mapping to the max number(total keys number -1) (- max-k min-k)] [(= k min-k) ; the smallest spot is taken by start, so we have to ; replace the origial number that takes the spot. (- start min-k)] [(= k max-k) (- end min-k)] [else (- k min-k)]))] [new-htb (make-hasheq)]) ;(printf "~a ~a\n" min-k max-k) (for-each (lambda (k) (hash-set! new-htb (hash-fun k) (map (lambda (trans) (match trans [`(,start ,a ,end) `(,(hash-fun start) ,a ,(hash-fun end))] [_ (error 'test "aab")] )) (hash-ref htb k)))) keys) (list (hash-fun start) (hash-fun end) new-htb) )) (module+ test (merge-nfa (make-nfa "a")) (merge-nfa (make-nfa '(arbno (or digit whitespace)))) (merge-nfa (make-nfa '(concat ";" (arbno (not #\newline))))) )
false
f80b67a2883af6ec447217e0e1370adf33f4d5a7
385fba048e72b659ad1a9a80d1a79a44dfa1042e
/summaries.rkt
227331402dbfb271e3c4b1c860fd2e97da588f32
[ "MIT" ]
permissive
rxg/biers
1c9a9065e4f8e2a51f2c6ca4cfa79dec1d24930c
342a9fbc1a1f605a0296e7540f569ea8be110168
refs/heads/master
2022-06-19T20:28:48.083179
2022-06-14T02:56:49
2022-06-14T02:56:49
162,618,664
0
0
null
null
null
null
UTF-8
Racket
false
false
3,759
rkt
summaries.rkt
#lang racket (provide (all-defined-out)) (provide median mean stddev variance) ;; ;; summaries.rkt - some techniques for computing summary statistics ;; (require plot) (require math/base) (require math/statistics) ;; ;; Summary Statistics, computed either from the posterior or from samples ;; ;; Intervals of defined boundaries, based on the grid posterior ;; compute the mass of probability that satisfies pred (define (pr-mass-posterior pred? p-grid posterior) (define relevant-mass (for/list ([p p-grid] [d posterior] #:when (pred? p)) d)) (/ (sum relevant-mass) (sum posterior))) #; (pr-mass-posterior (λ (p) (< p 0.5)) p-grid posterior) ;; Intervals of defined boundaries, based on the samples ;; compute the mass of probability that satisfies pred (define (pr-mass-samples pred samples) (/ (count pred samples) (length samples))) #;(pr-mass-samples (λ (p) (< p 0.5)) samples) #;(pr-mass-samples (λ (p) (< 0.5 p 0.75)) samples) ;; DEPRECATED!: quantile is already defined in math/statistics. ;; produce the UPPER boundary of the lower q percent of probability mass ;; (the LOWER boundary is 0). (define (my-quantile q < samples) (let ([pos (inexact->exact (ceiling (* q (length samples))))]) (list-ref (sort samples <) pos))) ;; lower and upper boundaries of the *middle* q percent of probability mass (define (compatibility-interval samples q) (let* ([split (/ q 2)] [lo (- 1/2 split)] [hi (+ 1/2 split)]) (for/list ([p (list lo hi)]) (quantile p < samples) #;(list p (quantile p < samples))))) ;; Highest Posterior Density (HPD) Interval ;; calculate the minimum interval that contains q percent of probability mass (define (hpdi samples q) ;; WHY WHY use multiple return values?!? (define-values (lo hi) (real-hpd-interval q samples)) (list lo hi)) ;; calculate the loss (wrt loss function loss-fn) for point p-guess against ;; the grid posterior (p-grid,posterior) (define (calculate-loss p-guess p-grid posterior loss-fn) (/ (sum (map (λ (x y) (* (loss-fn p-guess x) y)) p-grid posterior)) (sum posterior))) ;; approximate a point estimate with respect to the given loss-function ;; for the approximate posterior (pgrid,posterior) (define (point-estimate loss-fn p-grid posterior) (argmin (λ (pg) (calculate-loss pg p-grid posterior loss-fn)) p-grid)) ;; Example loss functions ;; absolute loss: corresponds to the mean (expected value) of the posterior (define (absolute-loss pg p) (abs (- pg p))) ;; quadratic loss: corresponds to the median of the posterior (define (quadratic-loss pg p) (sqr (- pg p))) ;; 0-1 loss: corresponds to *a* mode of the posterior (not necessarily unique) (define (0-1-loss pg p) (if (= pg p) 0 1)) ;; ;; Maximum a posterior (for a posterior function) ;; ;; Using nlopt (wrapper for NLopt library) to find map. (module maximize racket (require nlopt) (provide maximize-posterior) (define (maximize-posterior post) (define-values (fst snd) (optimize/args post 1 #:maximize #t #:bounds '((0.0 . 1.0)) #:method 'GN_DIRECT_L)) ;; no idea what the first value is about! snd) ) ; module maximize (require (submod "." maximize)) ;; ;; Sampling to simulate prediction ;; ;; code was very specialized... ;; Custom histogram plotting ('cause the plot density plotter ;; is sometimes weird) (define (mk-hist-coords samples) (let-values ([(x* y*) (count-samples samples)]) (let ([pre-coords (map vector x* y*)]) (sort pre-coords < #:key (λ (v) (vector-ref v 0)))))) (define (plot-simple-hist samples) (plot (discrete-histogram (mk-hist-coords samples))))
false
3e93a45c87d57c62bf90b4d292896379aa5b0cbf
ef61a036fd7e4220dc71860053e6625cf1496b1f
/cs61as/homeworks/hw08/hw08.rkt
41feb6bc5888d11422eeb883b01a05e2c4d43844
[]
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
4,375
rkt
hw08.rkt
#lang racket (require berkeley) (provide (all-defined-out)) ;Exercise 1 ;What are the result of the expressions? Make sure to comment your answer out. ; Exercise 2 Mobile (define (make-mobile left right) (list left right)) (define (make-branch length structure) (list length structure)) ; a. Define left-branch, right-branch, branch-length, and ; branch-structure. (define (left-branch mobile) (list-ref mobile 0)) (define (right-branch mobile) (list-ref mobile 1)) (define (branch-length branch) (list-ref branch 0)) (define (branch-structure branch) (list-ref branch 1)) ; b. Define total-weight. (define (total-weight mobile) (cond [(null? mobile) 0] [else (if (not (pair? mobile)) mobile (+ (total-weight (branch-structure (left-branch mobile))) (total-weight (branch-structure (right-branch mobile)))))])) ; c. Define balanced? (define (balanced? mobile) (if (not (pair? mobile)) true (and (equal? (torque (left-branch mobile)) (torque (right-branch mobile))) (balanced? (branch-structure (left-branch mobile))) (balanced? (branch-structure (right-branch mobile)))))) (define (torque branch) (* (branch-length branch) (total-weight (branch-structure branch)))) ; d. Redefine all the necessary procedures to work with the new ; constructors given below. ; Make sure that only one set of constructors is active at any time ; (otherwise Racket will complain about duplicate defintions). ;; (define (make-mobile left right) ;; (cons left right)) ;; (define (make-branch length structure) ;; (cons length structure)) ;Exercise 3a - Define square-tree (define (square-tree d-l) (map (λ (sub-tree) (if (pair? sub-tree) (square-tree sub-tree) (square sub-tree))) d-l)) ;Exercise 3b - Define tree-map (define (tree-map fn tree) (map (λ (sub-tree) (if (pair? sub-tree) (tree-map fn sub-tree) (fn sub-tree))) tree)) ;Exercise 4 - Complete the definition of accumulate-n (define (accumulate-n op init seqs) (if (null? (car seqs)) '() (cons (accumulate op init (map car seqs)) (accumulate-n op init (map cdr seqs))))) ;Exercise 5 - Complete the definitions of matrix-*-vector, transpose, ; and matrix-*-matrix. (define (dot-product v w) (foldr + 0 (map * v w))) (define (matrix-*-vector m v) (map (λ (col) (dot-product col v)) m)) (define (transpose mat) (accumulate-n cons nil mat)) (define (matrix-*-matrix m n) (let ((cols (transpose n))) (map (λ (x) (map (λ (y) (dot-product x y)) cols)) m))) ;Exercise 6 - Give the property that op should satisfy: #| Your property here |# ;Exercise 7 - Define equal? (define (my-equal? l1 l2) (or (eq? l1 l2) (and (pair? l1) (pair? l2) (equal? (car l1) (car l2)) (equal? (cdr l1) (cdr l2))))) ;Exercise 8 - Complete the definition of subsets (define (subsets s) (if (null? s) (list '()) (let ((rest (subsets (cdr s)))) (append rest (map (λ (x) (cons (car s) x)) rest))))) ;Exercuse 9 - Modify the calc program ;; Racket calculator -- evaluate simple expressions ; The read-eval-print loop: (define (calc) (display "calc: ") (flush-output) (print (calc-eval (read))) (calc)) ; Evaluate an expression: (define (calc-eval exp) (cond ((number? exp) exp) ((list? exp) (calc-apply (car exp) (map calc-eval (cdr exp)))) (else exp))) ; Apply a function to arguments: (define (calc-apply fn args) (cond ((eq? fn '+) (foldr + 0 args)) ((eq? fn '-) (cond ((null? args) (error "Calc: no args to -")) ((= (length args) 1) (- (car args))) (else (- (car args) (foldr + 0 (cdr args)))))) ((eq? fn '*) (foldr * 1 args)) ((eq? fn '/) (cond ((null? args) (error "Calc: no args to /")) ((= (length args) 1) (/ (car args))) (else (/ (car args) (foldr * 1 (cdr args)))))) ((eq? fn 'first) (first (car args))) ((eq? fn 'butfirst) (bf (car args))) ((eq? fn 'bf) (bf (car args))) ((eq? fn 'word) (foldr word "" args)) ((eq? fn 'bl) (bl (car args))) ((eq? fn 'butlast) (bl (car args))) ((eq? fn 'last) (last (car args))) (else (error "Calc: bad operator:" fn))))
false
5c0383b72ee09deeb2e3c0300da1e32f14386c64
4dd19196602623d0db1f5aa2ac44eaeace198b4a
/Chapter2/2.46.rkt
08abe510cd2401bd870744551a7c6bc645759b68
[]
no_license
Dibel/SICP
f7810b2c45aa955b8207e6cb126431d6f0ef48cb
abd27c0ed4bdaaa755eff01e78e5fb2a2ef8ee18
refs/heads/master
2020-06-05T16:38:00.957460
2014-12-02T15:20:40
2014-12-02T15:20:40
null
0
0
null
null
null
null
UTF-8
Racket
false
false
575
rkt
2.46.rkt
#lang racket/load ;(load "drawing.rkt") (define (make-vect x y) (cons x y)) (define (xcor-vect vect) (car vect)) (define (ycor-vect vect) (cdr vect)) (define (add-vect v1 v2) (make-vect (+ (xcor-vect v1) (xcor-vect v2)) (+ (ycor-vect v1) (ycor-vect v2)))) (define (sub-vect v1 v2) (make-vect (- (xcor-vect v1) (xcor-vect v2)) (- (ycor-vect v1) (ycor-vect v2)))) (define (scale-vect s vect) (make-vect (* s (xcor-vect vect)) (* s (ycor-vect vect)))) (define a (make-vect 1.0 2.0)) (scale-vect 2 a) ;(define (start-drawing) ((up-split wave 2) testFrame))
false
c763e9da6b380fe2bc2c6673cbac9c37ee1b03cc
206a85f0d9f644377e8aa24a94081c980ac27b43
/test/test-performance.rkt
bde104e346ff3ace1341fbcba0d25328a7c010e2
[]
no_license
curtdutt/openssl
b3d1dd24bc9da23df564b2d68fecc3af6c2cab9a
c5676894e0e6dd5fb85926e7a5f8d6e147ab4e6a
refs/heads/master
2021-01-18T20:20:19.054857
2011-11-19T21:20:11
2011-11-19T21:20:11
2,334,514
0
0
null
null
null
null
UTF-8
Racket
false
false
2,587
rkt
test-performance.rkt
#lang racket/base (require (planet okcomps/racket-test) "../main.rkt" ;openssl ) #| this test sends 1 byte back and forth between two endpoints if does this 50,000 times. |# (define-performance-test back-and-forth (test-timeout 30000) (define server-context (ssl-make-server-context)) (ssl-load-private-key! server-context "../test.pem") (ssl-load-certificate-chain! server-context "../test.pem") (define client-context (ssl-make-client-context)) (ssl-load-private-key! client-context "../test.pem") (let*-values ([(i1 o1) (make-pipe)] [(i2 o2) (make-pipe)]) (thread (λ () (let-values ([(ssl-i1 ssl-o1) (ports->ssl-ports i1 o2 #:context server-context #:mode 'accept)]) (let loop () (write-byte (read-byte ssl-i1) ssl-o1) (loop))))) (let-values ([(ssl-i2 ssl-o2) (ports->ssl-ports i2 o1 #:context client-context)]) (time-iteration (λ () (let loop ([count 0]) (unless (= count 50000) (write-byte 100 ssl-o2) (read-byte ssl-i2) (loop (add1 count))))))))) #| Defines the amount of time it takes to read (expt 2 26) bytes or 67MB through one way |# (define-performance-test upload-67MB (test-timeout 30000) (define goal-count (expt 2 26)) (define server-context (ssl-make-server-context)) (ssl-load-private-key! server-context "../test.pem") (ssl-load-certificate-chain! server-context "../test.pem") (define client-context (ssl-make-client-context)) (ssl-load-private-key! client-context "../test.pem") (let*-values ([(i1 o1) (make-pipe)] [(i2 o2) (make-pipe)]) (thread (λ () (let-values ([(ssl-i1 ssl-o1) (ports->ssl-ports i1 o2 #:context server-context #:mode 'accept)]) (let ([bytes (make-bytes (* 1024 16))]) (let loop ([count 0]) (if (>= count goal-count) (write 100 ssl-o1) (let ([read-count (read-bytes! bytes ssl-i1)]) (loop (+ count read-count))))))))) (let-values ([(ssl-i2 ssl-o2) (ports->ssl-ports i2 o1 #:context client-context)]) (time-iteration (λ () (let ([bytes (make-bytes (* 1024 16))]) (let loop ([count 0]) (unless (>= count goal-count) (loop (+ count (write-bytes bytes ssl-o2))))) (read-byte ssl-i2)))))))
false
d5b888fd6fe4e394dd70dec26a436f75d38572b0
98fd4b7b928b2e03f46de75c8f16ceb324d605f7
/drracket-test/tests/drracket/info.rkt
52b93e16745a422bf53502344d1431267e4367b4
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
racket/drracket
213cf54eb12a27739662b5e4d6edeeb0f9342140
2657eafdcfb5e4ccef19405492244f679b9234ef
refs/heads/master
2023-08-31T09:24:52.247155
2023-08-14T06:31:49
2023-08-14T06:32:14
27,413,460
518
120
NOASSERTION
2023-09-11T17:02:44
2014-12-02T03:36:22
Racket
UTF-8
Racket
false
false
785
rkt
info.rkt
#lang info (define tools '(("time-keystrokes.rkt"))) (define tool-names '("Time Keystrokes")) (define compile-omit-paths '("snip" "image-and-comment-box.rkt")) (define test-timeouts '(("easter-egg.rkt" 300) ("teaching-lang-sharing-modules.rkt" 600) ("no-write-and-frame-leak.rkt" 300))) (define test-responsibles '(("test-engine-test.rkt" sperber) ("teachpack.rkt" (robby matthias)) ("teaching-lang-save-file.rkt" (robby matthias)) ("teaching-lang-coverage.rkt" (robby matthias)) ("language-test.rkt" (robby matthias)) ("hangman.rkt" (robby matthias)) (all robby)))
false
5d0bad55ae8446822c8b35de1d088a08bf9ea055
2c24d4b6ccb5fa68f71932330266c35cafb19d80
/sham-test/tests/pointers.rkt
6858b5572ba60882b43656fcf256ec9d23148eb0
[ "MIT" ]
permissive
rjnw/sham
3e9ecd9103a6eb6a9b329c94560ab9557fa7b6a2
ac859e46d1c6a1cf34e61550f03ade5e880db2cb
refs/heads/master
2022-06-23T12:32:19.533754
2022-01-29T23:10:06
2022-02-13T16:51:58
72,507,297
71
6
MIT
2022-01-29T23:10:14
2016-11-01T05:41:21
Racket
UTF-8
Racket
false
false
803
rkt
pointers.rkt
#lang racket (require sham) (module+ test (require rackunit) (define test-module (create-empty-sham-module "test-module")) (current-sham-module test-module) (define-sham-function (create-box : i32*) (ret (malloc^ (etype i32)))) (define-sham-function (store-box (x : i32) (box : i32*) : tvoid) (store! x box) (return-void)) (define-sham-function (open-box (box : i32*) : i32) (ret (load box))) (define-sham-function (free-box (x : i32*) : tvoid) (free^ x) (return-void)) (parameterize ([compile-options (list 'pretty 'dump 'mc-jit)]) (compile-sham-module! test-module #:opt-level 3)) (define tbox (sham-app create-box)) (sham-app store-box 42 tbox) (check-eq? (sham-app open-box tbox) 42) (sham-app free-box tbox))
false
eaf166bdd79a9d6c3255d80f5d4002b0a032ad02
a18b561b599c8e85d697ecb421fe98cbb41814d1
/package/vraid/math/common.rkt
53ca533a13c6d288a4017945f986955bf41735ae
[]
no_license
his1220/earthgen
f501f1c6b91831adc3072e4dc7bbe5b9f7045793
0fd1904905fea41a441e7494388d734e298b77bc
refs/heads/master
2021-01-18T15:14:11.895611
2015-03-20T19:50:30
2015-03-20T20:35:08
null
0
0
null
null
null
null
UTF-8
Racket
false
false
1,535
rkt
common.rkt
#lang typed/racket (provide (all-defined-out)) (require "constants.rkt" "../types.rkt") (: negative (case-> (Flonum -> Flonum) (Integer -> Integer) (Number -> Number))) (define (negative a) (- a)) (: divide (case-> (Flonum Flonum -> Flonum) (Number Zero -> Zero) (Integer Integer -> Exact-Rational) (Number Number -> Number))) (define (divide a b) (/ b a)) (: subtract (case-> (Flonum Flonum -> Flonum) (Integer Integer -> Integer) (Number Number -> Number))) (define (subtract a b) (- b a)) (define sum +) (define product *) (define-type maybe-minmax ((maybe Real) -> (Real -> Real))) (: maybe-max maybe-minmax) (define ((maybe-max low) num) (if low (max low num) num)) (: maybe-min maybe-minmax) (define ((maybe-min high) num) (if high (min high num) num)) (: within-interval ((maybe Real) (maybe Real) -> (Real -> Real))) (define ((within-interval low high) num) ((maybe-min high) ((maybe-max low) num))) (: ratio-within (Flonum Flonum -> (Flonum -> Flonum))) (define ((ratio-within low high) num) (define closest ((within-interval low high) num)) (/ (- closest low) high)) (: index-within-range? (Integer Integer -> (Integer -> Boolean))) (define ((index-within-range? low high) i) (and (>= i low) (< i high))) (: angle-distance (Flonum Flonum -> Flonum)) (define (angle-distance a b) (abs (- (abs (- a b)) tau)))
false
8996808ba4a7b49e3c4ce48ea39fb58ee07723e6
7fa7ec85880610be6fa667fb8dd219efbc589738
/1-Diff/diff.rkt
42d6bcc9d257881ad60951b9bbdf98273e7db5c9
[]
no_license
C7C8/CS1102-HW
b8ff8f972142a5b9711d74a1755d48631dc4a6ed
267a70d3ddde804e81f8e3f1886eb0417fbb6199
refs/heads/master
2021-06-07T23:40:09.377789
2016-10-29T20:22:57
2016-10-29T20:22:57
66,744,250
0
0
null
null
null
null
UTF-8
Racket
false
false
11,958
rkt
diff.rkt
#!/usr/bin/racket ;;#lang racket ;; These three lines are required to run the program without DrRacket (require test-engine/racket-tests) ;; ;; File by Michael Krebs and Christopher Myers ;; 2016-9-1 ;; ;; A delete is (make-delete number) (define-struct delete (len)) ;; Template: ; (define (delete-func a-delete) ; ...(delete-len a-delete) ; ) ;; Example: (define delete-ex (make-delete 6)) ;; An insert is (make-insert string) (define-struct insert (str)) ;; Template: ; (define (insert-func an-insert) ; ...(insert-str an-insert) ; ) ;; Example: (define insert-ex (make-insert " lazy")) ;; An operation is either ;; -An insert, or ;; -a delete ;; ;; Template: ; (define (operation-func an-op) ; (cond [(insert? an-op) (insert-func an-op)] ; [(delete? an-op) (delete-func an-op)])) ;; A patch is (make-patch operation number) (define-struct patch (op pos)) ;; Template: ; (define (patch-func a-patch) ; ...(patch-op a-patch)... ; ...(patch-pos a-patch)... ; ) ;; Examples: (define patch-ins-ex (make-patch insert-ex 10)) ;; Patch insert example (define patch-del-ex (make-patch delete-ex 13)) ;; Patch delete example ;; apply-patch: patch string -> string ;; Consumes a patch and a string, returns a patched string (check-expect (apply-patch patch-ins-ex "We are not programmers.") "We are not lazy programmers.") (check-expect (apply-patch patch-del-ex "I don't have other example sentences.") "I don't have example sentences.") (define (apply-patch patch str) (apply-op (patch-op patch) (patch-pos patch) str)) ;; apply-op: operation number string -> string ;; Consumes an operation, a number, and a string. Applies the operation ;; at the given position on string str, returning the results. (check-expect (apply-op delete-ex 4 "The quick brown fox") "The brown fox") (check-expect (apply-op insert-ex 14 "jumps over the dog.") "jumps over the lazy dog.") (define (apply-op op position str) (cond [(delete? op) (str-delete position (delete-len op) str)] [(insert? op) (str-insert position str (insert-str op))])) ;; overlap?: patch patch -> boolean ;; Consumes two patches and returns a boolean whose value depends on whether there's an overlap or not ;; Overlaps are defined as ;; 1. Two insertions that start at the same location, ;; 2. Two deletions whose ranges overlap, ;; 3. An insertion that starts within the range of a deletion (unless they start at the same location. (check-expect (overlap? patch-ins-ex patch-ins-ex) #T) (check-expect (overlap? patch-del-ex patch-del-ex) #T) (check-expect (overlap? patch-del-ex patch-ins-ex) #F) (define (overlap? patch1 patch2) (cond [(and (delete? (patch-op patch1)) (delete? (patch-op patch2))) (delete-overlap? patch1 patch2)] [(and (insert? (patch-op patch1)) (insert? (patch-op patch2))) (insert-overlap? patch1 patch2)] [else (ins-del-overlap? patch1 patch2)])) ;; merge?: patch patch string -> string OR boolean (input dependent) ;; Consumes two patches and a string. Applies them to the string and returns the result, otherwise returns false if ;; the patches overlap. (check-expect (merge (make-patch (make-insert "-2-") 3) (make-patch (make-insert "-0-") 5) "01234567890") "012-2-34-0-567890") (check-expect (merge (make-patch (make-insert "-0-") 5) (make-patch (make-insert "-2-") 3) "01234567890") "012-2-34-0-567890") (check-expect (merge (make-patch (make-delete 3) 3) (make-patch (make-delete 3) 7) "01234567890") "01260") (check-expect (merge (make-patch (make-delete 3) 7) (make-patch (make-delete 3) 3) "01234567890") "01260") (check-expect (merge (make-patch (make-insert "-2-") 7) (make-patch (make-delete 3) 3) "01234567890") "0126789-2-0") (check-expect (merge (make-patch (make-delete 3) 3) (make-patch (make-insert "-2-") 7) "01234567890") "0126789-2-0") (check-expect (merge (make-patch (make-delete 3) 3) (make-patch (make-insert "-2-") 3) "01234567890") "012-2-67890") ;; Insertion starting at a deletion (check-expect (merge (make-patch (make-insert "-2-") 3) (make-patch (make-delete 3) 3) "01234567890") "012-2-67890") ;; <- ditto (check-expect (merge patch-ins-ex patch-ins-ex "This will return false!") #F) (define (merge patch1 patch2 str) (if (overlap? patch1 patch2) #F (cond [(and (delete? (patch-op patch1)) (insert? (patch-op patch2))) ;; Apply deletions FIRST (apply-patch patch2 (apply-patch patch1 str))] [(and (insert? (patch-op patch1)) (delete? (patch-op patch2))) (apply-patch patch1 (apply-patch patch2 str))] [(>= (patch-pos patch1) (patch-pos patch2)) (apply-patch patch2 (apply-patch patch1 str))] [else (apply-patch patch1 (apply-patch patch2 str))]))) ;; modernize: string -> string ;; Consumes a string and applies a series of patches to modernize it. Intended to ;; operate on the sequence from "Hamlet" (check-expect (modernize hamlet-str) hamlet-str-modern) (define (modernize str) (patch-walker modernize-patchlist str)) ;;Data for the modernize function (define hamlet-str "Hamlet: Do you see yonder cloud that's almost in shape of a camel? Polonius: By the mass, and 'tis like a camel, indeed. Hamlet: Methinks it is like a weasel. Polonius: It is backed like a weasel. Hamlet: Or like a whale? Polonius: Very like a whale.\n\n\n") (define hamlet-str-modern "Hamlet: Do you see the cloud over there that's almost the shape of a camel? Polonius: By golly, it is like a camel, indeed. Hamlet: I think it looks like a weasel. Polonius: It is shaped like a weasel. Hamlet: Or like a whale? Polonius: It's totally like a whale.\n\n\n") (define modernize-patchlist (cons (make-patch (make-delete 4) 232) (cons (make-patch (make-insert "It's totally") 232) (cons (make-patch (make-delete 6) 175) (cons (make-patch (make-insert "shaped") 175) (cons (make-patch (make-delete 14) 129) (cons (make-patch (make-insert "I think it looks") 129) (cons (make-patch (make-delete 8) 90) (cons (make-patch (make-insert "it is") 90) (cons (make-patch (make-delete 8) 80) (cons (make-patch (make-insert "golly") 80) (cons (make-patch (make-delete 2) 46) (cons (make-patch (make-insert "the") 46) (cons (make-patch (make-delete 19) 19) (cons (make-patch (make-insert "the cloud over there that's") 19) ;;parens incoming empty))))))))))))))) ;; ================ ;; HELPER FUNCTIONS ;; ================ ;; patch-walker: list of patches, string -> string ;; Takes a list of patches, recursively applies them (check-expect (patch-walker (cons (make-patch (make-delete 1) 8) (cons (make-patch (make-insert "9") 8) empty)) "0123456789") "0123456799") (check-expect (patch-walker (cons (make-patch (make-delete 1) 1) (cons (make-patch (make-insert "2") 1) empty)) "0123456789") "0223456789") (define (patch-walker patchlist str) (cond [(empty? patchlist) str] [else (patch-walker (rest patchlist) (apply-patch (first patchlist) str))])) ;; insert-overlap?: patch patch -> boolean ;; Consumes two patches and returns true if they start at the same location, false otherwise. (check-expect (insert-overlap? (make-patch (make-insert "Hello ") 1) (make-patch (make-insert "world!") 1)) #T) (check-expect (insert-overlap? (make-patch (make-insert "Hello ") 1) (make-patch (make-insert "world!") 9)) #F) (define (insert-overlap? patch1 patch2) (= (patch-pos patch1) (patch-pos patch2))) ;; delete-overlap?: patch patch -> boolean ;; Consumes two deletion patches and returns true if they overlap, false otherwise. (check-expect (delete-overlap? (make-patch (make-delete 3) 1) (make-patch (make-delete 4) 2)) #T) (check-expect (delete-overlap? (make-patch (make-delete 3) 1) (make-patch (make-delete 5) 999)) #F) (define (delete-overlap? patch1 patch2) (not (or ;;original tested for no conflicts, not negates this (< (patch-end patch1) (patch-pos patch2)) ;; patch1-end < patch2-start (> (patch-pos patch1) (patch-end patch2))))) ;; patch1-start > patch2-end ;; ins-del-overlap?: patch(insert) patch(delete) -> boolean ;; Consumes two patches and returns true if the insert start is inside the range of the deletion, false otherwise. ;; Hence, "insert-delete-overlap" (check-expect (ins-del-overlap? (make-patch (make-delete 9) 1) (make-patch (make-insert "Go away test case!") 3)) #T) (check-expect (ins-del-overlap? (make-patch (make-insert "Go away test case!") 3) (make-patch (make-delete 9) 99)) #F) (define (ins-del-overlap? patch1 patch2) (cond [(insert? (patch-op patch1)) (and (> (patch-pos patch1) (patch-pos patch2)) ;; delete-start < insert-start <= delete-end (<= (patch-pos patch1) (patch-end patch2)))] [else (and (> (patch-pos patch2) (patch-pos patch1)) ;; delete-start < insert-start <= delete-end (<= (patch-pos patch2) (patch-end patch1)))])) ;; patch-end patch: -> number ;; Consumes a patch, returns the end point of that patch (check-expect (patch-end (make-patch (make-insert "Hello, world!") 3)) 16) (check-expect (patch-end (make-patch (make-delete 3) 1)) 4) (define (patch-end patch) (+ (patch-pos patch) (cond [(delete? (patch-op patch)) (delete-len (patch-op patch))] [(insert? (patch-op patch)) (string-length (insert-str (patch-op patch)))]))) ;; str-delete: number number string -> string ;; Consumes a starting position, an amount to delete and the string to delete from ;; Produces a string with specified deleted portion via starting position and deleted amount (check-expect (str-delete 2 2 "apples") "apes") (check-expect (str-delete 1 5 "0123456") "06") (define (str-delete position num str) (string-append (substring str 0 position) (substring str (+ position num)))) ;; str-insert: number string string -> string ;; Consumes a position, a string, and a substring. Inserts substr at position in str, returning the result. (check-expect (str-insert 4 "The fox" "quick brown " ) "The quick brown fox") (check-expect (str-insert 14 "jumps over the dog." " lazy") "jumps over the lazy dog.") (define (str-insert position str substr) (string-append (substring str 0 position) substr (substring str position (string-length str)))) ;;(test) ;; Run check-expect tests. Not needed if DrRacket is configured in "Beginning Student" mode. ; 7.The advantages to returning false instead of the original string in the case where ; there is an overlap of two patches is that immediately one can know that the patches overlapped ; and didn't instead have a minor error like an index issue. This saves the coder the ; time of searching through the returned string looking for a patch that failed to be ; performed correctly when none of the patches were performed at all. ; ; 8.(/ (- (* 9 3) (double 'a)) 2) where double is defined as (define (double n) (* n 2)) ; ; =(/ (- (27) (double 'a)) 2) ; ; =(/ (- (27) (* a' 2)) 2) ; ; = Error: double n suspected a number but what given a'. They cannot be multiplied together ; ; ; 9.(or (< 5 2) (and (= 15 (- 18 3)) (> 8 4))) ; ; =(or (false) (and (= 15 (- 18 3)) (> 8 4))) ; ; =(or (false) (and (= 15 (15)) (> 8 4))) ; ; =(or (false) (and (true) (> 8 4))) ; ; =(or (false) (and (true) (true))) ; ; =(or (false) (true)) ; ; = true ; ; ; 10.(and (+ 5 -1) false) ; ; =(and (4) false) ; ; = Error: and returns a boolean and since 4 is neither an and or else the and cannot be evaluated ; ; 11.(apply-patch 'remove "this is a test string") [use your own apply-patch program from this assignment] ; ; = Error: apply-patch requires (patch string) as arguments but was given (symbol string). ; Our program doesn't use symbols to create an operation, only make-insert and make-delete do. ; ; ; 12. Code that produces this error would be anything with an incomplete cond; there's a test but no action after that. ; Example: (cond #T) ; ; 13. A variable-undefined error is generated when a variable used in a function doesn't actually exist. ; Example: (+ x 1) ; ; 14. This error would be generated if you used a number after an open paren, but that number wasn't a function. ; Example: (4)
false
6e34ebe62961bf545d12af586cadc646cd77a2ee
ef61a036fd7e4220dc71860053e6625cf1496b1f
/HTDP2e/03-abstraction/ch-15/ex-250.rkt
1ac2f8b71f067ec12e14992de6478096772bcc30
[]
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
806
rkt
ex-250.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-250) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) ; Number -> [List-of Number] ; tabulates sin between n ; and 0 (incl.) in a list (define (tab-sin n) (tabulete sin n)) ; Number -> [List-of Number] ; tabulates sqrt between n ; and 0 (incl.) in a list (define (tab-sqrt n) (tabulete sqr n)) (define (tabulete fn n) (cond [(= n 0) (list (fn 0))] [else (cons (fn n) (tabulete fn (sub1 n)))])) (tabulete sqr 2) ; produce (list 4 1 0) (tabulete tan 0) ; produce (list 0)
false
3b598a4f7a322da4ccc75ac5205ffc383148e26b
2545a03fd0767c2651dcd9b472e7f34890767fe8
/sketches/tic-tac-toe-demo/urlang-test.rkt
7e4619354ca6a192d2f7dbcdac47046e8fe0db20
[]
no_license
thoughtstem/rstack
f88a0ef0bae480fca926dfebf390547861574f11
02300a6b0c84df7464c0a78ae004f24a4628f1b6
refs/heads/master
2020-07-07T18:19:24.746251
2019-08-23T22:39:18
2019-08-23T22:39:18
203,435,715
0
1
null
null
null
null
UTF-8
Racket
false
false
412
rkt
urlang-test.rkt
#lang racket (require syntax/parse/define) (define-syntax (lit stx) (syntax-parse stx #:datum-literals (unquote) [(_ (unquote thing)) #'thing] [(_ thing) #'`thing])) (define-syntax (js stx) (syntax-parse stx #:datum-literals (unquote) [(_ (unquote expr)) #'expr ] [(_ expr) #''(this is js: expr)])) (js ,(lit (my (thing ,(+ 2 2)))))
true
66a1ad634a481806c5f5c55e6e74ea0e9011b236
82c76c05fc8ca096f2744a7423d411561b25d9bd
/typed-racket-test/succeed/pr14458.rkt
958d820ba1b82b3af653e415667feaa5697c4646
[ "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
283
rkt
pr14458.rkt
#lang typed/racket ;; Test for PR 14458. Make sure that overlap checking on ;; invariant struct types works against simple data types. (struct: (X) S ([z : (Vectorof X)])) (define-type (T X) (U 'Leaf (S X))) (: f (∀ (X) (T X) → Any)) (define (f s) (match s [(S _) 42]))
false
21aa45bd245f0ba109ff248f766bd24e5e0dd3e6
5c58ab6f71ae0637bb701b21f288bc08e815f5e9
/chapter4/414.rkt
dfc6067d6a4b1838e1b6cc541ec7fc18c88d3a6c
[ "MIT" ]
permissive
zxymike93/SICP
81949b33d283ac7e7603d5b02a2bd18d0bf3bd9d
a5b90334207dabeae19feaa3b441a3e64a2aee64
refs/heads/master
2023-01-09T03:22:13.887151
2022-12-28T15:11:54
2022-12-28T15:11:54
98,005,093
19
2
null
null
null
null
UTF-8
Racket
false
false
411
rkt
414.rkt
;; 自定义的 map 通过 define-variable! 被绑定到 global-env 中,当调用如 (map display '(1 2 3)) 的时候,被分派到 application? 下,通过查找变量 map 找到对应的过程来执行。 ;; 如果使用内置的 map,同样会被分派到 application? 下,但无法找到对应的过程(除非用某种方式绑定到环境中,比如在 primitives 里面映射 (list 'map map)。
false
218470dd7c4adc0d2ae01b9dd4018c5abf2522f7
25a6efe766d07c52c1994585af7d7f347553bf54
/gui-lib/mrlib/private/aligned-pasteboard/tests/more-tests-margin-aligned.rkt
04c991b08431ce5d638cba2486c0c395ad7cf858
[ "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
943
rkt
more-tests-margin-aligned.rkt
#lang racket/gui (require "../aligned-editor-container.rkt" "../aligned-pasteboard.rkt") (define pb (new horizontal-pasteboard%)) (send* pb (insert (make-object string-snip% "Call") #f) (insert (new editor-snip% [editor (new text%)]) #f)) (define z (new aligned-editor-snip% [editor pb] [stretchable-height #f] [stretchable-width #f])) (define f (new frame% [label "more-tests-text"] [width 200] [height 200])) (define e (new vertical-pasteboard%)) (define c (new aligned-editor-canvas% [editor e] [parent f])) (send e insert z) (send f show #t) ;;;;;;;;;; ;; exploration (require "../snip-lib.rkt") (define (margin snip) (define left (box 0)) (define top (box 0)) (define right (box 0)) (define bottom (box 0)) (send snip get-margin left top right bottom) (list (cons 'left (unbox left)) (cons 'right (unbox right)) (cons 'top (unbox top)) (cons 'bottom (unbox bottom))))
false
ebe5117a0ca1044b1e54f8254c9f25437c9a6452
890a8d611b8d8e968960cd791705b392baafbd88
/private/class.rkt
f3345d41ecbcaab57aa4763d98451bf310e90cd7
[]
no_license
jeapostrophe/rmc
13070ad6d0e71f3b768b8afdc8a0ff529ff8cff3
e11425287cfecb3940f75a25a29f9b74826c2605
refs/heads/master
2021-05-04T09:37:54.977534
2017-04-25T19:59:37
2017-04-25T19:59:37
58,007,148
8
0
null
null
null
null
UTF-8
Racket
false
false
8,018
rkt
class.rkt
#lang racket/base (require (for-syntax racket/base racket/syntax syntax/parse syntax/srcloc) syntax/location racket/contract/base racket/match racket/stxparam) (define-syntax (define-srcloc-struct stx) (syntax-parse stx [(_ name:id [f:id ctc:expr] ...) (with-syntax* ([_name (format-id #'name "_~a" #'name)] [_name? (format-id #'_name "~a?" #'_name)] [name? (format-id #'name "~a?" #'name)] [(n ...) (for/list ([f (in-list (syntax->list #'(f ...)))]) (generate-temporary))] [(name-f ...) (for/list ([f (in-list (syntax->list #'(f ...)))]) (format-id #'name "~a-~a" #'name f))] [(_name-f ...) (for/list ([f (in-list (syntax->list #'(f ...)))]) (format-id #'_name "~a-~a" #'_name f))]) (syntax/loc stx (begin (struct _name (srcloc f ...)) (define-syntax (name stx) (syntax-parse stx [(_ n ...) (with-syntax* ([pos (syntax-source stx)] [neg (syntax-source #'name)] [the-srcloc #`(quote-srcloc #,stx)]) (syntax/loc stx (let ([srcloc the-srcloc] [f n] ...) (_name srcloc (contract ctc f 'pos 'neg 'f srcloc) ...))))])) (define name-f _name-f) ... (define name? _name?) (provide name (contract-out [_name? (-> any/c boolean?)] [name? (-> any/c boolean?)])))))])) (begin-for-syntax (struct interface-info (stx))) (struct object (interfaces fields)) (define-syntax (define-interface stx) (syntax-parse stx [(_ name:id [m:id ctc:expr] ...) (with-syntax* ([name? (format-id #'name "~a?" #'name)] [inst:name (format-id #'name "inst:~a" #'name)] [_inst:name (format-id #'inst:name "_~a" #'inst:name)] [((_inst:name-m name-m) ...) (for/list ([m (in-list (syntax->list #'(m ...)))]) (list (format-id #'_inst:name "~a-~a" #'_inst:name m) (format-id #'name "~a-~a" #'name m)))]) (syntax/loc stx (begin (define-srcloc-struct inst:name [m (-> object? ctc)] ...) (define-syntax name (interface-info #'(_inst:name ([m _inst:name-m] ...)))) (define (name? x) (and (object? x) (hash-has-key? (object-interfaces x) _inst:name))) (define (name-m x) (hash-ref (hash-ref (object-interfaces x) _inst:name (λ () (error 'name-m "Not an instance of ~v: ~e" 'name x))) _inst:name-m (λ () (error 'name-m "Interface missing method ~v: ~e" 'name-m x)))) ... (provide (contract-out [name? (-> any/c boolean?)] [name-m (-> name? ctc)] ...)))))])) (define-syntax (make-interface-record stx) (syntax-parse stx [(_ iname) #:declare iname (static interface-info? "interface") (with-syntax* ([(_inst:name ([m _inst:name-m] ...)) (interface-info-stx (attribute iname.value))] [(m^ ...) (for/list ([m (in-list (syntax->list #'(m ...)))]) (datum->syntax #'iname (syntax->datum m) #'iname))]) (syntax/loc stx (cons _inst:name (make-immutable-hasheq (list (cons _inst:name-m m^) ...)))))])) (define-syntax-parameter this (λ (stx) (raise-syntax-error 'this "Illegal outside define-class methods"))) (define-syntax (define-class stx) (syntax-parse stx [(_ name:id #:fields [f:id f-ctc:expr] ... (~optional (~seq #:procedure proc:id)) (~seq #:methods iname:id idef:expr ...) ...) (with-syntax* ([(n ...) (generate-temporaries #'(f ...))] [maybe-proc (if (attribute proc) (syntax/loc stx (#:property prop:procedure (λ (me . args) (proc me args)))) #'())] [name? (format-id #'name "~a?" #'name)] [name-object (format-id #f "~a-~a" #'name #'object)] [name-object? (format-id #'name-object "~a?" #'name-object)] [(name-f ...) (for/list ([f (in-list (syntax->list #'(f ...)))]) (format-id #'name "~a-~a" #'name f))] [name-fields (format-id #f "~a-fields" #'name)] [name-fields? (format-id #'name-fields "~a?" #'name-fields)] [_name-fields (format-id #'name-fields "_~a" #'name-fields)] [(_name-fields-f ...) (for/list ([f (in-list (syntax->list #'(f ...)))]) (format-id #'_name-fields "~a-~a" #'_name-fields f))] [singleton-case (if (null? (syntax->list #'(f ...))) (syntax/loc stx [_:id (quasisyntax/loc stx (make-name-object #,(syntax/loc stx (name-fields))))]) (syntax/loc stx [_:id (quasisyntax/loc stx (λ (f ...) (make-name-object #,(syntax/loc stx (name-fields f ...)))))]))]) (syntax/loc stx (begin (define (make-name-object fields) (match-define (_name-fields srcloc f ...) fields) (define the-object (name-object (syntax-parameterize ([this (make-rename-transformer #'the-object)]) (make-immutable-hasheq (list (let () idef ... (make-interface-record iname)) ...))) fields)) the-object) (define-srcloc-struct name-fields [f f-ctc] ...) (struct name-object object () #:reflection-name 'name . maybe-proc) (define-syntax (name stx) (syntax-parse stx [(_ n ...) (quasisyntax/loc stx (make-name-object #,(syntax/loc stx (name-fields n ...))))] singleton-case)) (define (name? x) (name-object? x)) (define (name-f x) (_name-fields-f (object-fields x))) ... (provide name (contract-out [name? (-> any/c boolean?)] [name-f (-> name? any/c)] ...)))))])) (define-syntax (define-class-alias stx) (syntax-parse stx [(_ name:id (real-name:id arg:expr ...) (~optional (~seq #:no-provide (~bind [no-provide? #t])))) (with-syntax ([maybe-provide (if (attribute no-provide?) #'() (syntax/loc stx ((provide name))))]) (syntax/loc stx (begin (define-syntax (name stx) (syntax-parse stx [(_ more-arg:expr (... ...)) (syntax/loc stx (real-name arg ... more-arg (... ...)))] [_:id (syntax/loc stx (real-name arg ...))])) . maybe-provide)))])) (provide define-srcloc-struct define-interface define-class define-class-alias this)
true
d61f716405eebe7019abf2487e5b45261691f308
804e0b7ef83b4fd12899ba472efc823a286ca52d
/doc/scribblings/byte-strings.scrbl
9e04be18dac1c84f7bf86444a5cee0911ab2839f
[]
no_license
cha63506/CRESTaceans
6ec436d1bcb0256e17499ea9eccd5c034e9158bf
a0d24fd3e93fc39eaf25a0b5df90ce1c4a96ec9b
refs/heads/master
2017-05-06T16:59:57.189426
2013-10-17T15:22:35
2013-10-17T15:22:35
null
0
0
null
null
null
null
UTF-8
Racket
false
false
2,056
scrbl
byte-strings.scrbl
#lang scribble/doc @(require scribble/manual) @title[#:tag "byte-strings"]{Byte strings} @defproc[(bytes [b byte?] ...) bytes?]{ Returns a new mutable byte string whose length is the number of provided @racket[b]s, and whose positions are initialized with the given @racket[b]s.} @defproc[(bytes-length [bstr bytes?]) exact-nonnegative-integer?]{ Returns the length of @racket[bstr].} @defproc[(bytes-ref [bstr bytes?] [k exact-nonnegative-integer?]) byte?]{ Returns the character at position @racket[k] in @racket[bstr]. The first position in the bytes cooresponds to @racket[0], so the position @racket[k] must be less than the length of the bytes, otherwise an exception is raised.} @defproc[(subbytes [bstr bytes?] [start exact-nonnegative-integer?] [end exact-nonnegative-integer? (bytes-length str)]) bytes?]{ Returns a new mutable byte string that is @racket[(- end start)] bytes long, and that contains the same bytes as @racket[bstr] from @racket[start] inclusive to @racket[end] exclusive. The @racket[start] and @racket[end] arguments must be less than or equal to the length of @racket[bstr], and @racket[end] must be greater than or equal to @racket[start], otherwise an exception is raised.} @defproc[(bytes=? [bstr1 bytes?] [bstr2 bytes?] ...+) boolean?]{ Returns @racket[#t] if all of the arguments are @racket[eqv?].} @defproc[(bytes<? [bstr1 bytes?] [bstr2 bytes?] ...+) boolean?]{ Returns @racket[#t] if the arguments are lexicographically sorted increasing, where individual bytes are ordered by @racket[<], @racket[#f] otherwise.} @defproc[(bytes>? [bstr1 bytes?] [bstr2 bytes?] ...+) boolean?]{Like @racket[bytes<?], but checks whether the arguments are decreasing} @defproc[(bytes/append [bstr bytes?] ...) bytes?]{ Returns a new mutable byte string that is as long as the sum of the given @racket[bstr]s' lengths, and that contains the concatenated bytes of the given @racket[bstr]s. If no @racket[bstr]s are provided, the result is a zero-length byte string.}
false
023fb8de5935b161acf91d3e630d9f61639d5fac
ddae9f912790ca2fb5eb271ce54a156560ea526e
/cs275/lab1/1.8.rkt
179b30fa097d3bf86ea59ad473caaad6e6b702be
[]
no_license
cmccahil/Classwork
489658e06a4f88ac56297a980494a0ced7613184
1ed775acfd6e0a9d511ad3bb795e76039d2fbb5a
refs/heads/master
2020-07-31T18:22:26.034292
2020-01-27T19:26:21
2020-01-27T19:26:21
210,707,952
0
0
null
null
null
null
UTF-8
Racket
false
false
367
rkt
1.8.rkt
#lang racket (define timeSeen 0) (define rember2 (lambda(a lat) (cond [(null? lat) (set! timeSeen 0) null] [(and(eq? a (car lat))(= 1 timeSeen)) (set! timeSeen (+ 1 timeSeen)) (rember2 a (cdr lat))] [(eq? a (car lat)) (set! timeSeen (+ 1 timeSeen)) (cons (car lat)(rember2 a (cdr lat)))] [else (cons(car lat) (rember2 a (cdr lat)))])))
false
b641e3446fad4b63a4a054139fa6bbd4f5b67c32
faac781d39cae739040b99298e672d96e1724929
/flexpr/main.rkt
bba4a56b74304d445bdfea317337aaa604db2e49
[ "MIT", "BSD-2-Clause" ]
permissive
rbarraud/flexpr
fb6175ff5518da673b11fddd338857f1c9e8fcac
a547ca94094a2090f12b0028b634da0b08d42df8
refs/heads/master
2021-05-31T19:23:54.776437
2016-02-04T01:48:17
2016-02-04T01:48:17
null
0
0
null
null
null
null
UTF-8
Racket
false
false
11,887
rkt
main.rkt
#lang at-exp racket/base (require json racket/contract/base racket/format racket/function racket/list racket/match xml) (provide (all-from-out json xml) flexpr? plural-symbol? singular-symbol/c (contract-out [current-singular-symbol (parameter/c singular-symbol/c)] [default-singular-symbol singular-symbol/c]) flexpr->xexpr write-flexpr-xml/content display-flexpr-xml/content flexpr->jsexpr write-flexpr-json) (module+ test (require rackunit)) ;;; Plural and singular symbols (define singular-symbol/c (-> symbol? (or/c symbol? #f))) (define (default-singular-symbol v) ;singular-symbol/c (and (symbol? v) (let ([s (symbol->string v)]) (and (eq? #\s (string-ref s (sub1 (string-length s)))) (string->symbol (substring s 0 (sub1 (string-length s)))))))) (define current-singular-symbol (make-parameter default-singular-symbol)) (define (plural-symbol? v) ;any -> boolean? (and ((current-singular-symbol) v) #t)) ;;; flexpr? predicate (define (flexpr? v) ;any -> boolean? (match v [(? boolean?) #t] [(? string?) #t] [(? exact-integer?) #t] [(? inexact-real?) #t] [(and (? hash?) (? hash-eq? ht)) (for/and ([(k v) (in-hash ht)]) (match* (k v) [((? plural-symbol?) (list (? flexpr?) ...)) #t] [((? symbol?) (? flexpr?) ) #t] [(_ _ ) #f]))] [_ #f])) (module+ test (define-syntax-rule (check-flexpr? v) (check-true (flexpr? v))) (define-syntax-rule (check-not-flexpr? v) (check-false (flexpr? v))) ;; Things that ARE flexprs (check-flexpr? (hasheq)) (check-flexpr? (hasheq 'a 0)) (check-flexpr? (hasheq 'a 0 'b 1)) (check-flexpr? (hasheq 'a (hasheq 'b 0))) ;; Things that are NOT flexprs (check-not-flexpr? 'symbol) (check-not-flexpr? #"bytes") ;; A list by itself is NOT a flexpr (check-not-flexpr? '(1 2 3)) ;; A list CAN be the value in a hash where its key is plural-symbol? (check-flexpr? (hasheq 'results '(1 2 3))) (check-flexpr? (hasheq 'results '(1 2 3) 'other 0)) (check-not-flexpr? (hasheq 'singular '(1 2 3)))) ;;; Conversion to xexpr / xml ;; Note: A contract with flexpr? would double traverse, don't need. (define (flexpr->xexpr v #:root [root 'Response]) (unless (symbol? root) (raise-argument-error 'flexpr->xexpr "symbol" 1 v root)) (list* root (list) (let f->x ([v v]) (match v [#t (list "true")] [#f (list "false")] [(? string? v) (list v)] [(? exact-integer? v) (list (~a v))] [(? inexact-real? v) (list (~a v))] [(and (? hash?) (? hash-eq? ht)) ;; Important: Output the elements in a order that isn't ;; subject to `in-hash` or `hash-keys` order changing across ;; various versions of Racket. (for/list ([k (in-list (sort (hash-keys ht) symbol<?))]) (define v (hash-ref ht k)) (match* (k v) [((? plural-symbol? plural) (? list? vs)) (define singular ((current-singular-symbol) plural)) (list* plural (list) (for/list ([v (in-list vs)]) (list* singular (list) (f->x v))))] [((? symbol? s) (? list? vs)) (raise-arguments-error 'flexpr->xexpr "hash table key must be plural-symbol?" "expected" (string->symbol (format "~as" s)) "given" s "in" ht)] [((? symbol? k) v) (list* k (list) (f->x v))] [(k _) (raise-argument-error 'flexpr->xexpr "symbol" k)]))] [v (raise-argument-error 'flexpr->xexpr "flexpr" v)])))) (define (symbol<? a b) (string<? (symbol->string a) (symbol->string b))) (module+ test (check-false (flexpr? (hasheq 'item (list 0 1 2)))) (check-exn #px"hash table key must be plural-symbol?" (λ () (flexpr->xexpr (hasheq 'item (list 0 1 2)))))) (define (write-flexpr-xml/content v #:root [root 'Response] [out (current-output-port)]) (void (write-xml/content (xexpr->xml (flexpr->xexpr v #:root root)) out))) (define (display-flexpr-xml/content v #:root [root 'Response] [out (current-output-port)]) (void (display-xml/content (xexpr->xml (flexpr->xexpr v #:root root)) out))) ;;; Conversion to jsexpr / json (define (flexpr->jsexpr v) ;flexpr? -> jsexpr? (unless (flexpr? v) (raise-argument-error 'flexpr->jsexpr "flexpr" 0 v)) v) (define (write-flexpr-json v [out (current-output-port)] #:null [jsnull (json-null)] #:encode [encode 'control]) (void (write-json (flexpr->jsexpr v) out #:null jsnull #:encode encode))) ;;; Test same data, both conversions (module+ test (check-equal? (flexpr->xexpr (hasheq)) '(Response ())) (check-equal? (flexpr->xexpr (hasheq) #:root 'Root) '(Root ())) (check-equal? (flexpr->jsexpr (hasheq)) (hasheq)) ;; Using default-singular-symbol (let ([v (hasheq 'ResponseId 123123 'Students (list (hasheq 'FirstName "John" 'LastName "Doe" 'Age 12 'Active #f 'GPA 3.4) (hasheq 'FirstName "Alyssa" 'LastName "Hacker" 'Age 14 'Active #t 'GPA 4.0)))]) (check-true (flexpr? v)) (check-equal? (flexpr->xexpr v) '(Response () (ResponseId () "123123") (Students () (Student () (Active () "false") (Age () "12") (FirstName () "John") (GPA () "3.4") (LastName () "Doe")) (Student () (Active () "true") (Age () "14") (FirstName () "Alyssa") (GPA () "4.0") (LastName () "Hacker"))))) (let ([out (open-output-string)]) (write-flexpr-xml/content v out #:root 'Root) (check-equal? (get-output-string out) "<Root><ResponseId>123123</ResponseId><Students><Student><Active>false</Active><Age>12</Age><FirstName>John</FirstName><GPA>3.4</GPA><LastName>Doe</LastName></Student><Student><Active>true</Active><Age>14</Age><FirstName>Alyssa</FirstName><GPA>4.0</GPA><LastName>Hacker</LastName></Student></Students></Root>")) (let ([out (open-output-string)]) (display-flexpr-xml/content v out #:root 'Root) (check-equal? (get-output-string out) "\n<Root>\n <ResponseId>\n 123123\n </ResponseId>\n <Students>\n <Student>\n <Active>\n false\n </Active>\n <Age>\n 12\n </Age>\n <FirstName>\n John\n </FirstName>\n <GPA>\n 3.4\n </GPA>\n <LastName>\n Doe\n </LastName>\n </Student>\n <Student>\n <Active>\n true\n </Active>\n <Age>\n 14\n </Age>\n <FirstName>\n Alyssa\n </FirstName>\n <GPA>\n 4.0\n </GPA>\n <LastName>\n Hacker\n </LastName>\n </Student>\n </Students>\n</Root>")) (check-equal? (flexpr->jsexpr v) v) (let ([out (open-output-string)]) (write-flexpr-json v out) (check-equal? (string->jsexpr (get-output-string out)) v))) ;; Using pluralization that needs a custom current-singular-symbol (parameterize ([current-singular-symbol (λ (s) (or (and (eq? s 'Werewolves) 'Werewolf) (default-singular-symbol s)))]) (let ([v (hasheq 'ResponseId 123123 'Werewolves (list (hasheq 'FirstName "John" 'LastName "Doe" 'Age 12 'Active #f 'GPA 3.4) (hasheq 'FirstName "Alyssa" 'LastName "Hacker" 'Age 14 'Active #t 'GPA 4.0)))]) (check-true (flexpr? v)) (check-equal? (flexpr->xexpr v) '(Response () (ResponseId () "123123") (Werewolves () (Werewolf () (Active () "false") (Age () "12") (FirstName () "John") (GPA () "3.4") (LastName () "Doe")) (Werewolf () (Active () "true") (Age () "14") (FirstName () "Alyssa") (GPA () "4.0") (LastName () "Hacker"))))) (let ([out (open-output-string)]) (write-flexpr-xml/content v out #:root 'Root) (check-equal? (get-output-string out) "<Root><ResponseId>123123</ResponseId><Werewolves><Werewolf><Active>false</Active><Age>12</Age><FirstName>John</FirstName><GPA>3.4</GPA><LastName>Doe</LastName></Werewolf><Werewolf><Active>true</Active><Age>14</Age><FirstName>Alyssa</FirstName><GPA>4.0</GPA><LastName>Hacker</LastName></Werewolf></Werewolves></Root>")) (let ([out (open-output-string)]) (display-flexpr-xml/content v out #:root 'Root) (check-equal? (get-output-string out) "\n<Root>\n <ResponseId>\n 123123\n </ResponseId>\n <Werewolves>\n <Werewolf>\n <Active>\n false\n </Active>\n <Age>\n 12\n </Age>\n <FirstName>\n John\n </FirstName>\n <GPA>\n 3.4\n </GPA>\n <LastName>\n Doe\n </LastName>\n </Werewolf>\n <Werewolf>\n <Active>\n true\n </Active>\n <Age>\n 14\n </Age>\n <FirstName>\n Alyssa\n </FirstName>\n <GPA>\n 4.0\n </GPA>\n <LastName>\n Hacker\n </LastName>\n </Werewolf>\n </Werewolves>\n</Root>")) (check-equal? (flexpr->jsexpr v) v) (let ([out (open-output-string)]) (write-flexpr-json v out) (check-equal? (string->jsexpr (get-output-string out)) v)))))
true
7ba304ac39be7c65b032d2e3762dbee24533b2e0
fc90b5a3938850c61bdd83719a1d90270752c0bb
/web-server/info.rkt
647718b594c0ca34c8bdd82189ce9cb047075ff8
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
racket/web-server
cccdf9b26d7b908701d7d05568dc6ed3ae9e705b
e321f8425e539d22412d4f7763532b3f3a65c95e
refs/heads/master
2023-08-21T18:55:50.892735
2023-07-11T02:53:24
2023-07-11T02:53:24
27,431,252
91
42
NOASSERTION
2023-09-02T15:19:40
2014-12-02T12:20:26
Racket
UTF-8
Racket
false
false
284
rkt
info.rkt
#lang info (define collection 'multi) (define deps '("web-server-lib" "web-server-doc")) (define implies '("web-server-lib" "web-server-doc")) (define pkg-desc "An HTTP server") (define pkg-authors '(jay)) (define license '(Apache-2.0 OR MIT))
false
1c3e809d48321125824dfe048b74248a014c3316
400da1df8111d5d506bc02dd2041d980429f7840
/plisqin-lib/private2/sql/frags.helpers.rkt
3a0923ccebb4db4392609971e5b9af5f6eb6902c
[ "MIT" ]
permissive
default-kramer/plisqin
b60856520d03441f88d0e5bf74d5e6dc950cd12e
26421c7c42656c873c4e0a4fc7f48c0a3ed7770f
refs/heads/master
2021-07-07T20:45:59.813501
2020-08-09T18:43:39
2020-08-09T18:43:39
158,136,834
9
0
MIT
2020-08-09T18:43:40
2018-11-18T23:24:20
Racket
UTF-8
Racket
false
false
3,058
rkt
frags.helpers.rkt
#lang racket (provide make tokens parens insert-ands interpose ->Bit ->Bool (for-syntax bind:: matchup)) (require "fragment.rkt" "../_types.rkt" "../_dialect.rkt" racket/stxparam) (module+ test (require rackunit)) ; maybe tighten this up and add it to Morsel (define (parens x) (match x [(list "(" a ")") x] [else (list "(" x ")")])) (module+ test (check-equal? (parens (parens "foo")) (parens "foo"))) (define-for-syntax (bind:: id-stx) (lambda (x) (syntax-case x () [(f stuff ...) (quasisyntax/loc x (#%app #,id-stx stuff ...))] [id (quasisyntax/loc x #,id-stx)]))) (define-syntax-parameter tokens #f) ; `make` is used to construct fragments (define-syntax (make stx) (syntax-case stx () [(_ id kind content) (syntax/loc stx (make id kind content #:reduce-proc identity))] [(_ id kind content #:reduce reduce-body) (syntax/loc stx (make id kind content #:reduce-proc (λ (tokes) (syntax-parameterize ([tokens (bind:: #'tokes)]) reduce-body))))] [(_ :id :kind :content #:reduce-proc :reducer) (syntax/loc stx (new fragment% [id :id] [kind :kind] [content :content] [type #f] [as-name #f] [reducer :reducer]))])) ;;; insert-ands ; If the list of tokens is more than 3, insert " and " to join them. (define (insert-ands id tokens) (match tokens [(list a b) (list a (format " ~a " id) b)] [(list a b rest ...) (list (insert-ands id (list a b)) " and " (insert-ands id (cons b rest)))])) (module+ test (check-equal? (string-join (flatten (insert-ands '<> '("foo" "bar" "baz"))) "") "foo <> bar and bar <> baz")) (define (interpose x lst) (match lst [(list a b rest ...) (cons a (cons x (interpose x (cons b rest))))] [(list a) (list a)] [(list) (list)])) (module+ test (check-equal? (interpose '+ '(1 2 3 4)) '(1 + 2 + 3 + 4))) ; To be used during reduction. ; Converts a Bool to a Bit (only needed for MSSQL) (define (->Bit tokens) (match tokens [(list a) #:when (and (Bool? a) (mssql? (current-dialect))) (list "cast(case when "a" then 1 else 0 end as bit)")] [else tokens])) ; To be used during reduction. ; Converts a Bit to a Bool (needed by all dialects) (define (->Bool tokens) (match tokens [(list a) #:when (Bit? a) (list a" <> 0")] [else tokens])) ; helper that flattens #;([(a b) foo] [(c d) bar]) ; into a list like [a foo] [b foo] [c bar] [d bar] (define-for-syntax (matchup stx) (syntax-case stx () [([(id rest ...) body] more ...) (cons (syntax/loc #'id [id body]) (matchup #'([(rest ...) body] more ...)))] [([() body] more ...) (matchup #'(more ...))] [() (list)] [else (error "assert fail t42j90b")]))
true
87a6329917248140f7bcb668cf488b3da3ad7d7e
0031a2836d69c76773f63a60949c02668adfd602
/chapter4/ex4.11-env.rkt
28f1fc039fa620a0a47e15bc70d128d1e649d9d7
[]
no_license
hitalex/SICP-solutions
3a9be86ade702661e8965b9d730e0514be66cedf
d3c7f34fb513c197d037f99afa0abc88dbaa6a3e
refs/heads/master
2020-06-24T17:36:18.457082
2017-01-08T14:49:40
2017-01-08T14:49:40
74,629,242
0
0
null
null
null
null
UTF-8
Racket
false
false
2,269
rkt
ex4.11-env.rkt
#lang r5rs (#%require "error.rkt") (define (enclosing-environment env) (cdr env)) (define (first-frame env) (car env)) (define the-empty-environment '()) (define (make-binding var val) (cons var val)) (define (get-binding-var binding) (car binding)) (define (get-binding-val binding) (cdr binding)) ;; 将框架表示为变量和值的序对 (define (make-frame vars vals) (define (iter vars vals result) (if (null? vars) result (iter (cdr vars) (cdr vals) (cons (make-binding (car vars) (car vals)) result)))) (iter vars vals '())) (define (extend-environment vars vals base-env) (if (= (length vars) (length vals)) (cons (make-frame vars vals) base-env) (if (< (length vars) (length vals)) (error "Too many arguments supplied." vars vals) (error "Too many parameters supplied." vars vals)))) (define (add-binding-to-frame! var val frame) (cons (make-binding var val) frame)) (define (lookup-variable-value var env) (define (env-loop env) (define (scan frame) (cond ((null? frame) (env-loop (enclosing-environment env))) ((eq? var (get-binding-var (car frame))) (get-binding-val (car frame))) (else (scan (cdr frame))))) (if (eq? env the-empty-environment) (error "Unbound variable" var) (let ((frame (first-frame env))) (scan frame)))) (env-loop env)) (define (define-variable! var val env) (let ((frame (first-frame env))) (define (scan frame) (cond ((null? frame) (add-binding-to-frame! var val frame)) ((eq? var (get-binding-var (car frame))) (set-cdr! (car frame) val)) (else (scan (cdr frame))))) (scan frame))) (define (set-variable-value! var val env) (define (env-loop env) (define (scan frame) (cond ((null? frame) (env-loop (enclosing-environment env))) ((eq? var (get-binding-var (car frame))) (set-cdr! (car frame) val)) (else (scan (cdr frame))))) (if (eq? env the-empty-environment) (error "Unbound varialbe -- SET!" var) (let ((frame (first-frame env))) (scan frame)))) (env-loop env))
false
2243ebe645760eece7fb627b6c8f1e692ed0c4d7
e760fbba826475a182be48e23ac201b0f4417fb7
/engine/modules.rkt
70eccdbd950b7906e3fb80c5d56fa9e0a5561bd2
[ "MIT" ]
permissive
pedropramos/PyonR
2a81e40b7bfe2b331458147fc66becbcb513f337
16edd14f3950fd5a01f8b0237e023536ef48d17b
refs/heads/master
2021-01-18T21:51:38.123471
2016-04-13T08:01:23
2016-04-13T08:01:23
24,341,300
147
16
MIT
2018-03-31T05:45:49
2014-09-22T18:57:33
Racket
UTF-8
Racket
false
false
2,092
rkt
modules.rkt
(module modules racket (provide (all-defined-out)) (require "engine.rkt" "../name-mangling.rkt") (struct module_obj instance_obj (name) #:transparent) (define (py-module-set-entry! mod key value) (dict-set! (instance_obj-attributes mod) key value)) (define (py-module-repr mod) (format "<module '~a'>" (module_obj-name mod))) (define py-module (make-type "module" (vector py-object) (hasheq '__delattr__ #f '__dict__ (make-getset instance_obj-attributes) '__doc__ #f '__getattribute__ py-instance-getattribute '__init__ #f '__new__ #f '__repr__ py-module-repr '__setattr__ py-instance-setattribute))) (define (make-py-module name [contents (make-hash)]) (module_obj py-module contents name)) ;; side effect - initializes module (define (py-module-from-module module-spec #:mangled? [mangled? #f]) (let* ([name (extract-module-name module-spec)] [module-obj (make-py-module name)]) (dynamic-require module-spec #f) (for ([id (collect-exported/no-macros module-spec)]) (let ([name (colon-symbol->string id)]) (unless (and (eq? (string-ref name 0) #\_) (not mangled?)) (py-module-set-entry! module-obj (if mangled? (mangle-name name) name) (dynamic-require module-spec id))))) module-obj)) (require racket/path) (define (extract-module-name module-spec) (match module-spec [(? symbol? sym) (symbol->string sym)] [(list 'file path) (second (regexp-match "^([^.]+)(\\..+)?$" (path->string (file-name-from-path path))))] [(list 'planet (? symbol? sym)) (symbol->string sym)] [(list 'planet (? string? str)) str] [(list 'lib strs ...) (first strs)] [_ "anonymous"])) )
false
d0cf0a7543cf78a17a49856c8fdc738666dc92da
a3c50168cfaaad309cd6cc478290018d39f96084
/tutorial.rkt
a03713a9e4b4c3874b34d98d232a339c3962c50e
[]
no_license
nuno-v-santos/PAVA_2
1fabd6c694d9c9341694c93d51fd8660c693e3e3
f5fc2d243726a07be2ab4770dc9163f5f82fb70c
refs/heads/master
2021-09-14T08:54:16.679292
2018-05-10T19:20:39
2018-05-10T19:20:39
131,510,283
0
0
null
null
null
null
UTF-8
Racket
false
false
1,737
rkt
tutorial.rkt
#lang racket (cadr '(1 2 3)) ; 2 (define x 2) ; x=2 (let ([a 0] [b 1]) (+ a b)) ; 0+1=1 (let* ([a 0] [b a]) (+ a b)) ;0+0=0 ;(define (func_name arg1 arg2 arg3) body) (define (double x) (* 2 x)) (double 1) ;=2 ((lambda (x) (* 2 x)) 1) ;return 2 (map (lambda (x) (* 2 x)) '(1 2 3)) ;return '(2 4 6) (struct document (author title)) (define doc (document "Nuno" "Racket is cool *not*")) (document-author doc) ;get author of struct doc -> returns Nuno ofc ;Readable Regular Expressions ;Printable Regular Expressions ;regexp -> #rx ;pregexp -> #px (regexp "ap*le") ;#rx"ap*le" ;regexp-match & regexp-match* (regexp-match #rx"a|b" "cat") ;result -> '("a") (regexp-match* #rx"a|b" "cata") ;result -> '("a","a") (regexp-match #rx"a(t|b)" "cat") ; result -> '("at","t") (regexp-match-positions #rx"a|b" "cata") ;result -> '((1 2)) (regexp-replace #rx"a|b" "cata" "u") ;result -> "cuta" (regexp-replace #rx"a|b" "cata" string-upcase) ;result -> "cAta" ;Pattern based matching (match '(1 2 3) [(list _ _ a) a]) ;result -> 3 (match "yes" ["no" #f] ["yes" #t]) ;return #t (match '(1 2 3) [(list a b c)(list c b a)]) ;return '(3 2 1) (define (bar f) (f 2)) ;(define-syntax-rule ; pattern ; template (define-syntax-rule (foo (var) body) (bar (lambda (var) body))) (foo (y) (+ 1 y)) ;racket will use the syntax rule and will transform to (bar (lambda (y) (+ 1 y))) ;result -> 3 (define (test-str) (define str #<<end Cache = bache; public class Foo { public static Cache mergeCaches(Cache a, Cache b) { Cache vary = new Cache(); } } end ) (displayln (regexp-match #px"^[[:space:]]+([[:word:]]+)[[:space:]]*=[[:space:]]*([^;]+);" str)))
true
25a39c5475c857129192912b2720fcc523752fe4
f58e5513606af04b35d4093e4b152bda32cdbd6a
/private/model-papers.rkt
28f26469f616184798857b9c9a580ef36658446a
[ "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
1,737
rkt
model-papers.rkt
#lang racket/base (require db racket/match racket/dict "db-adapter.rkt" "parameters.rkt" "structs.rkt") (provide insert-paper) #| Table schemas ============= Papers ------- (id integer primary key, title varchar unique not null, year int, abstract varchar, venue varchar, directory varchar, created varchar, modified varchar) |# ;; Prepared queries ;; ================ (define/prepared-query db-update-link-paper-id "update links set paper_id = ? where id = ? ") (define/prepared-query db-insert-paper "INSERT OR IGNORE INTO papers (title, year, abstract, venue, directory, created, modified) values (?, ?, ?, ?, ?, ?, ?)") (define/prepared-query db-select-paper "select id from papers where title = ?") (define (fetch-paper-id logger conn paper) (with-handlers ([exn:fail:sql? (handle-sql-error logger paper)]) (define q (query-rows conn "select id from papers where title = $1" (paper-title paper))) (if (not (null? q)) (vector-ref (car q) 0) '()))) ;////////////////////////////////////////////////////////////////////////////// ; PUBLIC ;; Insert or Ignore paper, and return paper id based on title select (define (insert-paper logger conn paper) (with-handlers ([exn:fail:sql? (handle-sql-error logger paper)]) (define q1 (db-insert-paper conn (paper-title paper) (paper-year paper) (paper-abstract paper) (paper-venue paper) (paper-directory paper) (paper-created paper) (paper-modified paper))) (fetch-paper-id logger conn paper)))
false
5eb752d5402c6727aa251d604433758fa02cf458
53ac5e17fb40ec1c2b718f083b2a2aba9552b6e0
/plai-typed-racket.rkt
9ace414cf61635d66f663482be2ffcedb08eb82e
[ "ISC" ]
permissive
wolverian/plai
1e6cfafdaaa9075f1ba1d2da1149867f8f254e5f
112419aa381d1ed0563dbcdcee015a6788e4918d
refs/heads/master
2021-03-12T23:51:12.147411
2014-10-09T18:31:05
2014-10-09T18:31:05
null
0
0
null
null
null
null
UTF-8
Racket
false
false
7,329
rkt
plai-typed-racket.rkt
#lang typed/racket (require typed/rackunit) ;; * Common type support ;; Unfortunately there's no `match-type` yet. PLAI has one, which ;; requires you to say `(match TypeName expr cases)`. I'd like to do it ;; without requiring the explicit TypeName mention. (define-syntax-rule (deftype name [cons-name (field-name : field-type) ...] ...) (begin (struct cons-name ([field-name : field-type] ...) #:transparent) ... (define-type name (U cons-name ...)))) ;; * Surface syntax (deftype Expr-S [num-s (n : Number)] [id-s (s : Symbol)] [app-s (fun : Expr-S) (arg : Expr-S)] [plus-s (l : Expr-S) (r : Expr-S)] [mult-s (l : Expr-S) (r : Expr-S)] [lam-s (arg : Symbol) (body : Expr-S)] [let-s (name : Symbol) (val : Expr-S) (body : Expr-S)] [seq-s (b1 : Expr-S) (b2 : Expr-S)]) ;; * Parser (: parse (Sexp -> Expr-S)) (define/match (parse expr) [((? number? n)) (num-s n)] [((? symbol? s)) (id-s s)] [(`(+ ,l ,r)) (plus-s (parse l) (parse r))] [(`(* ,l ,r)) (mult-s (parse l) (parse r))] [(`(lambda (,(? symbol? a)) ,b)) (lam-s a (parse b))] [(`(let ([,(? symbol? name) ,val]) ,b)) (let-s name (parse val) (parse b))] [(`(begin ,a ,b)) (seq-s (parse a) (parse b))] [((list f arg)) (app-s (parse f) (parse arg))]) ;; ** Tests for the parser (check-equal? (parse '42) (num-s 42)) (check-equal? (parse 'x) (id-s 'x)) (check-equal? (parse '(+ 27 12)) (plus-s (num-s 27) (num-s 12))) (check-equal? (parse '(* 1 x)) (mult-s (num-s 1) (id-s 'x))) (check-equal? (parse '(lambda (y) (+ y 42))) (lam-s 'y (plus-s (id-s 'y) (num-s 42)))) (check-equal? (parse '((lambda (y) y) 42)) (app-s (lam-s 'y (id-s 'y)) (num-s 42))) (check-equal? (parse '(let ([x 42]) x)) (let-s 'x (num-s 42) (id-s 'x))) (check-equal? (parse '(let ([f (lambda (g) (+ (g 42) 1))]) (f (lambda (x) (* x 2))))) (let-s 'f (lam-s 'g (plus-s (app-s (id-s 'g) (num-s 42)) (num-s 1))) (app-s (id-s 'f) (lam-s 'x (mult-s (id-s 'x) (num-s 2)))))) ;; * Core syntax (deftype Expr-C [num-c (n : Number)] [id-c (s : Symbol)] [app-c (fun : Expr-C) (arg : Expr-C)] [plus-c (l : Expr-C) (r : Expr-C)] [mult-c (l : Expr-C) (r : Expr-C)] [lam-c (arg : Symbol) (body : Expr-C)] [set-c (var : Symbol) (arg : Expr-C)] [seq-c (b1 : Expr-C) (b2 : Expr-C)]) ;; * Desugarer (: desugar (Expr-S -> Expr-C)) (define/match (desugar expr) [((num-s n)) (num-c n)] [((id-s s)) (id-c s)] [((app-s f a)) (app-c (desugar f) (desugar a))] [((plus-s l r)) (plus-c (desugar l) (desugar r))] [((mult-s l r)) (mult-c (desugar l) (desugar r))] [((lam-s a b)) (lam-c a (desugar b))] [((let-s n v b)) (app-c (lam-c n (desugar b)) (desugar v))] [((seq-s a b)) (seq-c (desugar a) (desugar b))]) ;; ** Tests for desugaring (check-equal? (desugar (num-s 42)) (num-c 42)) (check-equal? (desugar (id-s 'foo)) (id-c 'foo)) (check-equal? (desugar (app-s (id-s 'f) (num-s 42))) (app-c (id-c 'f) (num-c 42))) (check-equal? (desugar (plus-s (num-s 42) (num-s 1))) (plus-c (num-c 42) (num-c 1))) (check-equal? (desugar (lam-s 'x (plus-s (id-s 'x) (num-s 42)))) (lam-c 'x (plus-c (id-c 'x) (num-c 42)))) (check-equal? (desugar (let-s 'x (let-s 'y (num-s 42) (plus-s (id-s 'y) (num-s 1))) (plus-s (id-s 'x) (num-s 2)))) (app-c (lam-c 'x (plus-c (id-c 'x) (num-c 2))) (app-c (lam-c 'y (plus-c (id-c 'y) (num-c 1))) (num-c 42)))) (check-equal? (desugar (seq-s (app-s (id-s 'x) (num-s 1)) (app-s (id-s 'y) (num-s 2)))) (seq-c (app-c (id-c 'x) (num-c 1)) (app-c (id-c 'y) (num-c 2)))) ;; * Interpreter types ;; ** Values (deftype Value [num-v (n : Number)] [clos-v (arg : Symbol) (body : Expr-C) (env : Env)]) ;; ** Environments (define-type Location Number) (deftype Binding [bind (name : Symbol) (val : Location)]) (define-type Env (Listof Binding)) (define mt-env empty) (define extend-env cons) ;; ** Mutable storage (deftype Storage [cell (location : Location) (val : Value)]) (define-type Store (Listof Storage)) (define mt-store empty) (define override-store cons) ;; ** Results (deftype Result [v*s (v : Value) (s : Store)]) ;; * Interpreter (: interp (Expr-C Env Store -> Result)) (define (interp expr env store) (match expr [(num-c n) (v*s (num-v n) store)] [(plus-c l r) (match-let* ([(v*s v-l s-l) (interp l env store)] [(v*s v-r s-r) (interp r env s-l)]) (v*s (num+ v-l v-r) s-r))] [(mult-c l r) (match-let* ([(v*s v-l s-l) (interp l env store)] [(v*s v-r s-r) (interp r env s-l)]) (v*s (num* v-l v-r) s-r))] [(app-c f arg-val) (match-let* ([(v*s (clos-v a b f-e) f-s) (interp f env store)] [(v*s a-v a-s) (interp arg-val env f-s)] [where (new-loc)]) (interp b (extend-env (bind a where) f-e) (override-store (cell where a-v) a-s)))] [(id-c n) (v*s (fetch (lookup n env) store) store)] [(lam-c arg body) (v*s (clos-v arg body env) store)] [(set-c var val) (match-let ([(v*s v-val s-val) (interp val env store)] [where (lookup var env)]) (v*s v-val (override-store (cell where v-val) store)))] [(seq-c a b) (match-let ([(v*s v s) (interp a env store)]) (interp b env s))])) ;; * Interpreter support ;; ** Numerics (: num+ (Value Value -> Value)) (define/match (num+ a b) [((num-v x) (num-v y)) (num-v (+ x y))] [(_ _) (error 'num+ "one argument was not a number")]) (: num* (Value Value -> Value)) (define/match (num* a b) [((num-v x) (num-v y)) (num-v (* x y))] [(_ _) (error 'num* "one argument was not a number")]) ;; ** Mutable values (: new-loc (-> Location)) (define new-loc (let ([n (box 0)]) (lambda () (begin (set-box! n (add1 (unbox n))) (unbox n))))) (: lookup (Symbol Env -> Location)) (define (lookup name env) (let ([binding (findf (match-lambda [(bind n _) (symbol=? n name)]) env)]) (if binding (bind-val binding) (error 'lookup "no such binding")))) (: fetch (Location Store -> Value)) (define (fetch loc store) (let ([c (findf (match-lambda [(cell l _) (= loc l)]) store)]) (if c (cell-val c) (error 'fetch "no such location")))) ;; ** Test support (define-syntax-rule (check-interp? prog expected) (check-equal? (v*s-v (interp (desugar (parse 'prog)) mt-env mt-store)) expected)) (define-syntax over (syntax-rules () [(_ target (s ...)) (target s ...)] [(_ target s) (target s)] [(_ target s ss ...) (begin (over target s) (over target ss ...))])) ;; ** Interpreter tests (check-interp? (+ 1 2) (num-v 3)) (over check-interp? [(+ 1 2) (num-v 3)] [(* 1 2) (num-v 2)] [(let ([x 42]) x) (num-v 42)] [(let ([f (lambda (g) (g 42))]) (f (lambda (x) (+ x 41)))) (num-v 83)] [(let ([x (let ([x 42]) (+ x x))]) x) (num-v 84)] [((lambda (x) (let ([x 42]) x)) 666) (num-v 42)])
true
f76b67055de9fb1396bee5e6e7dfcddcb13c85e3
f07e5e2d974bef9f157e58954e48e4711b29a038
/Ex3.39-3.40.rkt
2261a5b7e819e13d4c3c8f21c3dc96a4b64d79d6
[]
no_license
ayushgoel/SICP-Excercises
92cb99b7ac84aead36b7f4237c84131f49a97367
2214bb28758c3eed14568c97367f1e6ab8c28210
refs/heads/master
2016-09-06T14:38:05.284230
2014-05-22T07:46:16
2014-05-22T07:46:16
null
0
0
null
null
null
null
UTF-8
Racket
false
false
574
rkt
Ex3.39-3.40.rkt
#lang racket (require (planet dyoo/sicp-concurrency:1:2/sicp-concurrency)) (define x 10) (parallel-execute (lambda () (set! x (* x x))) (lambda () (set! x (+ x 1)))) (print x) (define y 10) (define s (make-serializer)) (parallel-execute (s (lambda () (set! y (* y y)))) (s (lambda () (set! y (+ y 1))))) (print y) (define x 10) (define s (make-serializer)) (parallel-execute (lambda () (set! x ((s (lambda () (* x x)))))) (s (lambda () (set! x (+ x 1))))) ;; 3.39 101 121 100 ;; 3.40 100 1000 10000 100000 1000000
false
e55d27366c59895a8dbc16b74d7f81f9b3f1871b
18c09f49ee1b6670426be9b0d10b6fb24f1475e4
/Task/100-doors/Racket/100-doors-3.rkt
bb232f0c33cbf5a420e4151587746530fe65b771
[]
no_license
hitme/RosettaCodeData
579f07fe898b6642414281cf8567bac01f6098df
1f1ad4942732d2b45e67dd9264c3cc8924a72d78
refs/heads/master
2021-01-13T04:37:54.198047
2013-04-12T23:18:05
2013-04-12T23:18:05
null
0
0
null
null
null
null
UTF-8
Racket
false
false
620
rkt
100-doors-3.rkt
#lang slideshow (define-syntax-rule (vector-neg-set! vec pos) (vector-set! vec pos (not (vector-ref vec pos)))) (define (make-doors) (define doors (make-vector 100 #f)) (for ([i (in-range 100)]) (for ([j (in-range i 100 (add1 i))]) (vector-neg-set! doors j))) doors) (displayln (list->string (for/list ([d (make-doors)]) (if d #\o #\-)))) (define (closed-door) (inset (filled-rectangle 4 20) 2)) (define (open-door) (inset (rectangle 4 20) 2)) (for/fold ([doors (rectangle 0 0)]) ([open? (make-doors)]) (hc-append doors (if open? (open-door) (closed-door))))
true
3a4a463ecc886d34b8948d7ea532cf5908504494
d07380a8836587ff70fdc001e939e232ee202c80
/tests/opencl/samples/atiSamples/Template/Template.rkt
d52bb155e8bbc4d915351d690e69668a3669b1f6
[]
no_license
jeapostrophe/opencl
8e21c8fd9a4500bcf9a23a63a17ec6636810f6a0
f984050b0c02beb6df186d1d531c4a92a98df1a1
refs/heads/master
2020-05-17T22:41:00.588267
2015-12-19T21:45:10
2015-12-19T21:45:10
617,896
12
5
null
2015-08-01T10:49:35
2010-04-19T15:00:08
Racket
UTF-8
Racket
false
false
2,979
rkt
Template.rkt
#lang racket (require opencl/c "../atiUtils/utils.rkt" ffi/unsafe ffi/cvector ffi/unsafe/cvector) (define width 0) (define input #f) (define output #f) (define multiplier 0) (define devices #f) (define context #f) (define commandQueue #f) (define program #f) (define inputBuffer #f) (define outputBuffer #f) (define kernel #f) (define (print1DArray arrayName arrayData length) (define numElementsToPrint (if (< 256 length) 256 length)) (printf "~n~a:~n" arrayName) (for ([i (in-range numElementsToPrint)]) (printf "~a " (ptr-ref arrayData _cl_uint i))) (display "\n")) (define (initializeHost) (set! width 256) (set! multiplier 2) ;allocate and initialize memory used by host (define sizeInBytes (* width (ctype-sizeof _cl_uint))) (set! input (malloc sizeInBytes 'raw)) (set! output (malloc sizeInBytes 'raw)) (for ([i (in-range width)]) (ptr-set! input _cl_uint i i)) (print1DArray "Input" input width)) (define (initializeCL) (set!-values (devices context commandQueue program) (init-cl "Template_Kernels.cl" #:deviceType 'CL_DEVICE_TYPE_CPU)) (set! inputBuffer (clCreateBuffer context '(CL_MEM_READ_WRITE CL_MEM_USE_HOST_PTR) (* width (ctype-sizeof _cl_uint)) input)) (set! outputBuffer (clCreateBuffer context '(CL_MEM_READ_WRITE CL_MEM_USE_HOST_PTR) (* width (ctype-sizeof _cl_uint)) output)) (set! kernel (clCreateKernel program #"templateKernel"))) (define (runCLKernels) (define device (cvector-ref devices 0)) (define maxWorkGroupSize (clGetDeviceInfo:generic device 'CL_DEVICE_MAX_WORK_GROUP_SIZE)) (define maxDims (clGetDeviceInfo:generic device 'CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS)) (define maxWorkItemSizes (clGetDeviceInfo:generic device 'CL_DEVICE_MAX_WORK_ITEM_SIZES)) (define globalThreads (vector width)) (define localThreads (vector 1)) (clSetKernelArg:_cl_mem kernel 0 outputBuffer) (clSetKernelArg:_cl_mem kernel 1 inputBuffer) (clSetKernelArg:_cl_uint kernel 2 multiplier) (define event (clEnqueueNDRangeKernel commandQueue kernel 1 globalThreads localThreads (make-vector 0))) (clWaitForEvents (vector event)) (clReleaseEvent event) (set! event (clEnqueueReadBuffer commandQueue outputBuffer 'CL_TRUE 0 (* width (ctype-sizeof _cl_uint)) output (make-vector 0))) (clWaitForEvents (vector event)) (clReleaseEvent event)) (define (cleanupCL) (clReleaseKernel kernel) (clReleaseProgram program) (clReleaseMemObject inputBuffer) (clReleaseMemObject outputBuffer) (clReleaseCommandQueue commandQueue) (clReleaseContext context)) (define (cleanupHost) (free input) (free output)) (define (verify) (define passed #t) (for ([i (in-range width)]) (when (not (= (* (ptr-ref input _cl_uint i) multiplier) (ptr-ref output _cl_uint i))) (set! passed #f))) (printf "~a~n" (if passed "Passed!" "Failed!"))) (initializeHost) (initializeCL) (runCLKernels) (print1DArray "Output" output width) (verify) (cleanupCL) (cleanupHost)
false
1338555fba8ed6d04777b22064cbf979fd3d9e19
804e0b7ef83b4fd12899ba472efc823a286ca52d
/peer/src/net/scurl/peer-validation/scurl.rkt
1de7c483ee22379ae2ef8c3d1711baa031498fa8
[]
no_license
cha63506/CRESTaceans
6ec436d1bcb0256e17499ea9eccd5c034e9158bf
a0d24fd3e93fc39eaf25a0b5df90ce1c4a96ec9b
refs/heads/master
2017-05-06T16:59:57.189426
2013-10-17T15:22:35
2013-10-17T15:22:35
null
0
0
null
null
null
null
UTF-8
Racket
false
false
10,899
rkt
scurl.rkt
#lang racket/base (require racket/contract racket/list) ; Provides the scurl structure and functions for scurl creation and scurl validation. ; As well as functions to generate the host-id for a scurl. (require "depends.rkt" "host-id.rkt") (provide make-host-id-base) ; Create the logger for the scurl module. (define logger (make-logger 'scurl-logger peer-validation-parent-logger)) ; A scurl holds all of the information necessary to validate ; a remote peer. The digest-type, key-type and key are allowed to be ; null because it is still possible to validate a remote peer if all that ; is known is the url and host-id. (struct scurl (url host-id digest-type key-type key) #:transparent) (provide/contract [struct scurl ((url url?) ; url with the string encoded host-id. (host-id bytes?) ; the byte encoded host-id. (digest-type (or/c null? !digest?)) ; the digest used to create the host-id. (key-type (or/c null? !pkey?)) ; the type of pkey that the key object is. (key (or/c null? pkey?)) ; the pkey used to sign/verify the host-id. )]) ; Returns true when the scurl contains a pkey that contains a private ; key component. (define (private-scurl? s) (and (scurl? s) (pkey-private? (scurl-key s)))) (provide/contract [private-scurl? (-> any/c boolean?)]) ; Returns true when the digest-type, key-type or key of the given scurl ; is null. (define (null-scurl? s) (and (scurl? s) (or (null? (scurl-digest-type s)) (null? (scurl-key-type s)) (null? (scurl-key s))))) (provide/contract [null-scurl? (-> any/c boolean?)]) ; Returns true when two scurls are equivalent to each other. ; The comparison is done based upon the string version of the scurl. (define (scurl=? s1 s2) ; Convert both scurls to string and perform a string comparison. (and (scurl? s1) (scurl? s2) (string=? (url->string (scurl-url s1)) (url->string (scurl-url s2))))) (provide/contract [scurl=? (-> any/c any/c boolean?)]) ; Searches for the host-id given a list of path/param objects ; that have been retrieved by parsing a url. If the string ; "scurl" is found as part of the path then the next path value ; will be taken to be the host-id (define (find-host-id path) (cond [(null? path) (debug logger "Failed to find a scurl path element while searching for the host-id in an url.") #f] [else ; If we found the text "scurl" and we have another path element ; then hopefully it is the host-id (if (and (string=? (path/param-path (first path)) "scurl") (> (length (rest path)) 0)) (let ((host-id-text (path/param-path (second path)))) ; If the host-id-text is a valid length to be the host-id in string ; form then let's convert it to byte form, otherwise return false. (if (host-id-string? host-id-text) (host-id-string->host-id-bytes host-id-text) (begin (debug logger "Found a scurl path element, but the following element was not a valid host-id in string form.") #f))) (find-host-id (cdr path)))])) (provide/contract [find-host-id (-> (listof path/param?) (or/c bytes? boolean?))]) ; This function converts a string into a SCURL. If the given string ; can be parsed correctly then the scurl is returned, otherwise a ; boolean value of false is returned. (define (string->scurl text [digest-type null] [key-type null] [key null]) (url->scurl (string->url text) digest-type key-type key)) (provide/contract [string->scurl (->* (string?) (!digest? !pkey? (or/c pkey? bytes?)) (or/c scurl? boolean?))]) ; This function converts an URL into a SCURL. If the ; given URL is formatted correctly then the scurl is ; returned, otherwise a boolean value of false is returned. (define (url->scurl url [digest-type null] [key-type null] [key null]) (let (; Extract a valid key. (valid-key (cond ; Key is already a pkey, pass it along. [(pkey? key) key] ; Key is a byte-string and key-type is not null, ; let's try to turn it into a pkey. [(and (bytes? key) (!pkey? key-type)) (with-handlers ((exn? (lambda (e) (debug logger "Failed to convert the given bytes and pkey type into a pkey." e) null))) (bytes->public-key key-type key))] [else ; Return null, because key could be bytes, ; but not a valid bytes to make a pkey. null]))) ; Find the host-id in the path portion of the url. (let ((host-id (find-host-id (url-path url)))) (if (host-id-bytes? host-id) ; Found a valid host-id, create a scurl. (scurl url host-id digest-type key-type valid-key) ; Couldn't find a host-id, so fail to create a scurl. (begin (debug logger "Failed to find a valid host-id!") #f))))) (provide/contract [url->scurl (->* (url?) (!digest? !pkey? (or/c pkey? bytes?)) (or/c scurl? boolean?))]) ; Returns the string representation of the scurl. (define (scurl->string s) (url->string (scurl-url s))) (provide/contract [scurl->string (-> scurl? string?)]) ; Turns the given scurl into a scurl structure that contains only the ; public-key portion of the pkey. The output of this function is safe ; to give out to the public. (define (scurl->public-scurl s) (scurl (scurl-url s) (scurl-host-id s) (scurl-digest-type s) (scurl-key-type s) (pkey->public-key (scurl-key s)))) (provide/contract [scurl->public-scurl (-> scurl? scurl?)]) ; Takes an url that has no scurl tag or host-id and generates a scurl ; structure that contains the scurl that is associated with the given url ; and key information. (define (generate-scurl text digest-type key-type key) ; Convert the text string into a url. (letrec ((url (if (string? text) ; Convert from string to url. (string->url text) ; Must be an url already. text)) ; Now, generate a new host-id based on the given key. (host-id (make-host-id text digest-type key))) ; Return a valid scurl structure that has the correct information. (scurl ; Inject the host-id as a string into the url. (insert-host-id url (host-id-bytes->host-id-string host-id)) host-id digest-type key-type key))) (provide/contract [generate-scurl (-> (or/c string? url?) !digest? !pkey? pkey? scurl?)]) ; Inserts a host-id that is in string format into the path/param list ; of the given url. (define (insert-host-id url host-id) (let ((path (url-path url)) (scurl-path (list (make-path/param "scurl" empty) (make-path/param host-id empty)))) (let ((full-path (if (empty? path) ; If path/param is empty, we need to add a blank path/param ; to get the '/' at the beginning of the url. (append (list (make-path/param "" empty)) scurl-path) (append scurl-path path)))) (make-url (url-scheme url) (url-user url) (url-host url) (url-port url) (url-path-absolute? url) full-path (url-query url) (url-fragment url))))) (provide/contract [insert-host-id (-> url? host-id-string? url?)]) ; This function computes the host-id of a scurl structure. ; SHA( SHA(location:port:publickey):location:port:publickey) (define (make-host-id url digest-type key) (let ((data (make-host-id-base url key))) ; Produce the host id by doing DIGEST( DIGEST(data):data ) and return the number of bytes needed. (subbytes (digest digest-type (bytes-append (digest digest-type data) data)) ; We only the need a certain number of bytes. 0 (host-id-bytes-length)))) (provide/contract [make-host-id (-> (or/c string? url?) !digest? pkey? host-id-bytes?)]) ; This function creates the byte-string that is used to create the host-id of a scurl. ; ; (or url? string?) pkey? -> byte-string? (define (make-host-id-base url key) (let* (; Convert the location, port and public key into bytes. (url (if (string? url) (string->url url) url)) (location-bytes (string->bytes/utf-8 (url-host url))) ; Default the port value to 8080 if there is none present. (port (if (boolean? (url-port url)) 8080 (url-port url))) (port-bytes (integer->integer-bytes port 2 #f #t)) ; Extract the bytes that represent the public key portion. (key-bytes (public-key->bytes key))) ; Append the location, port and public key into one byte string. (bytes-append location-bytes port-bytes key-bytes))) ; Find the scurl tag and remove it and the following path/param element ; so that the final url contains no scurl or host id. (define (remove-host-id path) (cond ; If null return empty list. [(null? path) '()] ; If the path is a scurl tag try to remove it and the host id. Stop searching after this. [(string=? (path/param-path (car path)) "scurl") (let (; Remove the scurl tag from the list. (path (cdr path))) ; We should have another element, the host-id. (if (> (length path) 0) ; If we do, remove it. (cdr path) ; Don't know how that happened, but let's ; just return the path without the scurl tag. path))] [else (append (car path) (remove-host-id (cdr path)))])) ; Returns a url that represents the given scurl without the scurl and ; host-id path elements. (define (scurl->url-without-host-id scurl) (let ((url (scurl-url scurl))) (make-url (url-scheme url) (url-user url) (url-host url) (url-port url) (url-path-absolute? url) (remove-host-id (url-path url)) (url-query url) (url-fragment url)))) (provide/contract [scurl->url-without-host-id (-> scurl? url?)])
false
7e15093128a1a5f43a82ca5917f36b50b7071f59
14dfd3a2665e39d5120de79d7361c697992bf5c9
/TasksFromTenthSeminarStreams.rkt
4bef5a0d1aa8ede973a1b77742a66bb1b12553c8
[ "MIT" ]
permissive
AlexStoyanova/Functional-Programming-FMI
ae13466dc90ed568e5cd5cba04c2bcfb089af6d1
f984dfb3167b0fd50bcc5064511e629844515729
refs/heads/master
2020-08-12T05:38:33.548020
2019-12-12T19:52:22
2019-12-12T19:52:22
214,698,836
1
0
null
null
null
null
UTF-8
Racket
false
false
2,731
rkt
TasksFromTenthSeminarStreams.rkt
#lang racket (define-syntax cons-stream (syntax-rules () ((cons-stream h t) (cons h (delay t))))) (define the-empty-stream '()) (define head car) (define (tail s) (force (cdr s))) (define empty-stream? null?) ;task1 (define (stream-range a b) (if (> a b) the-empty-stream (cons-stream a (stream-range (+ a 1) b)))) (define someStream (stream-range 1 6)) ;task2 (define (stream-ref s n) (cond ((empty-stream? s) the-empty-stream) ((= n 0) (head s)) (else (stream-ref (tail s) (- n 1))))) ;task3 (define (stream-map s f) (if (empty-stream? s) the-empty-stream (cons-stream (f (head s)) (stream-map (tail s) f)))) ;task4 (define (stream-filter s p) (cond ((empty-stream? s) the-empty-stream) ((p (head s)) (cons-stream (head s) (stream-filter (tail s) p))) (else (stream-filter (tail s) p)))) ;task5 (define (stream-fold s acc f) (if (empty-stream? s) acc (stream-fold (tail s) (f acc (head s)) f))) ;task6 (define (stream->list s) (if (empty-stream? s) '() (cons (head s) (stream->list (tail s))))) ;task7 (define (stream-take s n) (cond ((empty-stream? s) the-empty-stream) ((= n 0) the-empty-stream) (else (cons-stream (head s) (stream-take (tail s) (- n 1)))))) ;task8 (define (stream-drop s n) (cond ((empty-stream? s) the-empty-stream) ((> n 0) (stream-drop (tail s) (- n 1))) (else (cons-stream (head s) (stream-drop (tail s) n))))) ;task9 (define (from n) (cons-stream n (from (+ 1 n)))) (define nat (from 0)) ;task10 (define (prime? n) (define (pr count) (cond ((< n 2) #f) ((or (= n 2)(= count n)) #t) ((= (remainder n count) 0) #f) (else (pr (+ count 1))))) (pr 2)) (define (search-el s p) (cond ((empty-stream? s) #f) ((p (head s)) s) (else (search-el (tail s) p)))) (define (prime42) (define (helper n s) (if (= n 0) (head s) (helper (- n 1) (search-el (tail s) prime?)))) (helper 42 nat)) ;task11 (define (fib) (define (fibonacci a b) (cons-stream a (fibonacci b (+ a b)))) (fibonacci 1 1)) ;task12 (define (stream-append s1 s2) (cond ((empty-stream? s1) s2) ((empty-stream? s2) s1) (else (cons-stream (head s1) (stream-append (tail s1) s2))))) ;task13 (define (stream-join s) (if (empty-stream? s) the-empty-stream (stream-append (head s) (stream-join (tail s))))) ;for testing: (define st11 (stream-range 0 6)) (define st22 (stream-range 7 10)) (define st33 (stream-range 11 15)) (define s44 (cons-stream st11 (cons-stream st22 (cons-stream st33 the-empty-stream)))) (define allSt (stream-join s44)) ;task14 (define (pythagorean-triples) (void))
true
89d6509f5d7d191d5fbe22a259cc1c2071e0f32c
a81c078be33105a42fcfaff6189e7bf078aae9b0
/spaceship-game-demo/v13/spaceship_game.rkt
4a96178338a958ca01e03b05753a5bb3d58adc6d
[]
no_license
thoughtstem/game-engine-demos
3536e6c257dc59009996e0e6faeb64dd03730274
614d1c5fb871f17e4008a26cb42542800457576b
refs/heads/master
2021-06-07T07:41:51.064343
2019-10-04T22:18:55
2019-10-04T22:18:55
123,335,201
1
0
null
2019-07-19T18:17:32
2018-02-28T19:57:02
Racket
UTF-8
Racket
false
false
2,349
rkt
spaceship_game.rkt
#lang racket (require game-engine game-engine-demos-common) (define WIDTH 800) (define HEIGHT 800) (define bg-entity (sprite->entity (space-bg-sprite WIDTH HEIGHT 100) #:name "bg" #:position (posn 0 0) #:components (static))) (define (spaceship-entity) (sprite->entity spaceship-sprite #:name "ship" #:position (posn 100 100) #:components (key-movement 5) (on-collide "ore" (change-speed-by 1)) (on-collide "enemy" die) (on-collide "bullet" die))) (define (ore-entity p) (sprite->entity (ore-sprite (random 10)) #:position p #:name "ore" #:components (on-collide "ship" (randomly-relocate-me 0 WIDTH 0 HEIGHT)))) (define (enemy-entity p) (sprite->entity (spaceship-animator 'left) #:position p #:name "enemy" #:components (every-tick (move-up-and-down #:min 0 #:max HEIGHT #:speed 10)) (do-every 50 (spawn bullet)))) (define bullet (sprite->entity (new-sprite (list (circle 5 "solid" "red") (circle 5 "solid" "orange") (circle 5 "solid" "yellow") (circle 5 "solid" "orange")) 1) #:position (posn -32 0) #:name "bullet" #:components (every-tick (move-left #:speed 10)) (after-time 25 die) (on-collide "ship" die))) (define (lost? g e) (not (get-entity "ship" g))) (define (won? g e) (define speed (get-speed (get-entity "ship" g))) (>= speed 10)) (start-game (instructions WIDTH HEIGHT "Use arrow keys to move") (game-over-screen won? lost?) (spaceship-entity) (ore-entity (posn 400 400)) (enemy-entity (posn 500 300)) (enemy-entity (posn 600 200)) (enemy-entity (posn 700 100)) bg-entity)
false
3a163192f1c440dbbf3435eee894a4b4a202b832
bf3128c6b1cf2a164077bcef1ffa23c26c440a0b
/try-catch-finally/3.scrbl
68d4ea228cd472bff68ea44d1f31bcd91ccf482e
[ "MIT" ]
permissive
bennn/syntax-parse-example
9e961fefc50c265991665d5de7ec1047dd445ed7
b1616936eafd97f952af050dc41cab25c50041e2
refs/heads/master
2022-09-21T15:43:20.335490
2022-09-06T00:17:37
2022-09-06T00:17:37
423,293,870
1
1
NOASSERTION
2021-11-01T00:38:01
2021-11-01T00:38:00
null
UTF-8
Racket
false
false
2,539
scrbl
3.scrbl
#lang syntax-parse-example @require[ (for-label racket/base syntax/parse syntax-parse-example/try-catch-finally/3)] @(define try-catch-finally-eval-3 (make-base-eval '(require racket/port racket/string syntax-parse-example/try-catch-finally/3))) @title{@racket[try], @racket[try-with], @racket[try-with*]} @defmodule[syntax-parse-example/try-catch-finally/3]{} @stxbee2021["eutro" 12] @adapted-from[#:what "package" @tt{try-catch-match} "https://docs.racket-lang.org/try-catch-match/index.html"] @defform[#:literals [catch finally] (try body ...+ catch-clause ... maybe-finally-clause) #:grammar ([catch-clause (catch pat body ...+)] [maybe-finally-clause (code:line) (finally body ...+)])]{ Evaluates the body expressions in a context that matches any exceptions against the @racket[catch] clauses in succession. Evaluates the @racket[finally] clause when leaving the dynamic extent of the try expression's body. The expressiveness of match syntax makes it sufficiently flexible for any case, and grants familiarity to those that are used to it. @examples[#:eval try-catch-finally-eval-3 (try (cons 1) (catch (or (? exn? (app exn-message msg)) (app ~a msg)) (car (string-split msg ";"))) (finally (displayln "finally"))) ] } @defform[(try-with ([id val-expr] ...) expr ...+)]{ The @racket[try-with] macro (and its cousin @racket[try-with*]) generalize resource cleanup in an exception-safe way. These macros are influenced by @tt{with-open} from Clojure and @tt{try-with-resources} from Java. Like @racket[let], bind @racket[id]s to @racket[val]s in @racket[body]. @racket[val]s are evaluated with @racket[current-custodian] set to a new custodian created with @racket[make-custodian]. When the expression returns, the custodian is shutdown with @racket[custodian-shutdown-all] in a @racket[finally] clause. @examples[#:eval try-catch-finally-eval-3 (try-with ([port (open-output-string)]) (displayln "Hello!" port)) ] } @defform[(try-with* ([id val-expr] ...) expr ...+)]{ Like @racket[try-with], but the binding of each @racket[id] is made available in subsequent @racket[val]s, as in @racket[let*]. All @racket[val]s are evaluated with the same custodian. } @deftogether[( @defidform[catch] @defidform[finally])]{ These identifiers may only appear within a @racket[try] form. } Implementation: @racketfile{3.rkt}
false
a958ec89ca10bc2af68c1e89ea0beaffa62bd04d
6ed02f3ebc64478e266db7c07d96a88d4979bed7
/gnal-lambda/define.rkt
41e712d4a9e672b2e5d3565e8045341e7302a1a3
[ "MIT" ]
permissive
AlexKnauth/gnal-lambda
2dd09c8515857fc0d1c1a1a0c5addf47a0013039
366160d5752f338e69e11d99fd1b3e5c09363d31
refs/heads/master
2022-01-22T16:01:26.495995
2022-01-07T14:57:10
2022-01-07T14:57:10
64,271,526
1
0
null
null
null
null
UTF-8
Racket
false
false
176
rkt
define.rkt
#lang racket/base (provide define) (require syntax/parse/define (only-in racket/base [define -define])) (define-simple-macro (define x:id v:expr) (-define x v))
false
265ea6a01ec12dd226d41935d1c9f78b2445bbe5
91c95a080586f754ea860d844f9b1e6f60d69210
/graphics-nm.rkt
941a78b3f800b8d3c82fe61f4feea592b5fc3881
[]
no_license
dn-github/nine-men-morris-game
b4057f025490eb56ab77a465af886adba2a12333
78b1c74689e61695b9bdb99ec46fff0bccbd341e
refs/heads/master
2022-12-17T08:07:29.313352
2020-09-20T09:00:03
2020-09-20T09:00:03
297,037,953
0
0
null
null
null
null
UTF-8
Racket
false
false
88,456
rkt
graphics-nm.rkt
#lang racket (require graphics/graphics) (require racket) (define (new) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;<LIST COMPREHENSION>;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (concat l) (foldr append `() l)) (define-syntax lc (syntax-rules (: <- *) [(lc expr : var <- drawn-from) (map (lambda (var) expr) drawn-from)] [(lc expr : * guard) (if guard (list expr) `())] [(lc expr : * guard qualifier ...) (concat (lc (lc expr : qualifier ...) : guard))] [(lc expr : var <- drawn-from qualifier ...) (concat (lc (lc expr : qualifier ... ) : var <- drawn-from))])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;<VECTOR DEFINITIONS>;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (make-2d-vector r c initial) (build-vector r (lambda (x) (make-vector c initial)))) (define (2d-vector-ref vec r c) (vector-ref (vector-ref vec r) c)) (define (2d-vector-set! vec r c val) (vector-set! (vector-ref vec r) c val)) ;(define (vector-append v1 v2) ; (list->vector (append (vector->list v1) (vector->list v2)))) ; ; ;(define (vector-filter pred v1) ; (list->vector (filter pred (vector->list v1)))) ; ;(define (vector-drop v1 pos) ; (if (> pos (vector-length v1)) `fail ; (if (= pos 0) v1 ; (vector-drop (list->vector (cdr (vector->list v1))) (- pos 1))))) (define human-white-pos (make-vector 9 (cons -1 -1))) ;(vector-set! human-white-pos 0 (cons 0 0)) ;(vector-set! human-white-pos 1 (cons 0 1)) ;(vector-set! human-white-pos 2 (cons 0 3)) ;(vector-set! human-white-pos 3 (cons 0 6)) ;(vector-set! human-white-pos 4 (cons 1 0)) ;(vector-set! human-white-pos 5 (cons 1 2)) ;(vector-set! human-white-pos 6 (cons 1 4)) ;(vector-set! human-white-pos 7 (cons 1 5)) ;(vector-set! human-white-pos 8 (cons 2 7)) ;;Its a 9X1 matrix with a cons element in each position.Cons element will be (cons -1 -1) if the coin has not come onto the board till now. ;;(cons -2 -2) if the coin is dead.(cons x y) x=(0 to 7) y=(0 to 7) (define computer-black-pos (make-vector 9 (cons -1 -1))) ;(vector-set! computer-black-pos 0 (cons 0 2)) ;(vector-set! computer-black-pos 1 (cons 0 4)) ;(vector-set! computer-black-pos 2 (cons 0 5)) ;(vector-set! computer-black-pos 3 (cons 0 7)) ;(vector-set! computer-black-pos 4 (cons 1 1)) ;(vector-set! computer-black-pos 5 (cons 1 3)) ;(vector-set! computer-black-pos 6 (cons 1 6)) ;(vector-set! computer-black-pos 7 (cons 1 7)) ;;(vector-set! computer-black-pos 8 (cons 2 0)) ;;Its a 3X8 matrix with a string element in its each position. String will be "EMPTY" if that positon is empty or ("HW0" to "HW8" and "CB0" to "CB8") (define board-status (make-2d-vector 3 8 "EMPTY")) ;(2d-vector-set! board-status 0 2 "CB0") ;(2d-vector-set! board-status 0 4 "CB1") ;(2d-vector-set! board-status 0 5 "CB2") ;(2d-vector-set! board-status 0 7 "CB3") ;(2d-vector-set! board-status 1 1 "CB4") ;(2d-vector-set! board-status 1 3 "CB5") ;(2d-vector-set! board-status 1 6 "CB6") ;(2d-vector-set! board-status 1 7 "CB7") ;;(2d-vector-set! board-status 2 3 "CB8") ;(2d-vector-set! board-status 0 0 "HW0") ;(2d-vector-set! board-status 0 1 "HW1") ;(2d-vector-set! board-status 0 3 "HW2") ;(2d-vector-set! board-status 0 6 "HW3") ;(2d-vector-set! board-status 1 0 "HW4") ;(2d-vector-set! board-status 1 2 "HW5") ;(2d-vector-set! board-status 1 4 "HW6") ;(2d-vector-set! board-status 1 5 "HW7") ;(2d-vector-set! board-status 2 7 "HW8") (define selected-piece (cons "POS" "COIN-ID")) (define count -1) (define mycount 0) (define reference (build-vector 9 (lambda (x) x))) (vector-set! reference 0 #\0) (vector-set! reference 1 #\1) (vector-set! reference 2 #\2) (vector-set! reference 3 #\3) (vector-set! reference 4 #\4) (vector-set! reference 5 #\5) (vector-set! reference 6 #\6) (vector-set! reference 7 #\7) (vector-set! reference 8 #\8) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define helper-list1 (list (cons 2 5) (cons 0 0) (cons 2 7) (cons 0 1) (cons 0 2) (cons 0 3) (cons 0 4) (cons 0 5) (cons 0 6) (cons 0 7) (cons 1 0) (cons 1 1) (cons 1 2) (cons 1 3) (cons 1 4) (cons 1 5) (cons 1 6) (cons 1 7) (cons 2 0) (cons 2 1) (cons 2 2) (cons 2 3) (cons 2 4) (cons 2 6))) (define helper-list (list (cons (cons 0 0) (list (cons 0 1) (cons 0 7))) (cons (cons 0 1) (list (cons 0 0) (cons 0 2) (cons 1 1))) (cons (cons 0 2) (list (cons 0 1) (cons 0 3))) (cons (cons 0 3) (list (cons 0 2) (cons 0 4) (cons 1 3))) (cons (cons 0 4) (list (cons 0 3) (cons 0 5))) (cons (cons 0 5) (list (cons 0 4) (cons 0 6) (cons 1 5))) (cons (cons 0 6) (list (cons 0 5) (cons 0 7))) (cons (cons 0 7) (list (cons 0 0) (cons 0 6) (cons 1 7))) (cons (cons 1 0) (list (cons 1 1) (cons 1 7))) (cons (cons 1 1) (list (cons 1 0) (cons 1 2) (cons 0 1) (cons 2 1))) (cons (cons 1 2) (list (cons 1 1) (cons 1 3))) (cons (cons 1 3) (list (cons 1 2) (cons 1 4) (cons 0 3) (cons 2 3))) (cons (cons 1 4) (list (cons 1 3) (cons 1 5))) (cons (cons 1 5) (list (cons 1 4) (cons 1 6) (cons 0 5) (cons 2 5))) (cons (cons 1 6) (list (cons 1 5) (cons 1 7))) (cons (cons 1 7) (list (cons 1 0) (cons 1 6) (cons 0 7) (cons 2 7))) (cons (cons 2 0) (list (cons 2 1) (cons 2 7))) (cons (cons 2 1) (list (cons 2 0) (cons 2 2) (cons 1 1))) (cons (cons 2 2) (list (cons 2 1) (cons 2 3))) (cons (cons 2 3) (list (cons 2 2) (cons 2 4) (cons 1 3))) (cons (cons 2 4) (list (cons 2 3) (cons 2 5))) (cons (cons 2 5) (list (cons 2 4) (cons 2 6) (cons 1 5))) (cons (cons 2 6) (list (cons 2 5) (cons 2 7))) (cons (cons 2 7) (list (cons 2 0) (cons 2 6) (cons 1 7))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;<GRAPHICS>;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define vec-pos (make-2d-vector 3 8 (cons -1 -1))) (2d-vector-set! vec-pos 0 0 (cons 0 0)) (2d-vector-set! vec-pos 0 1 (cons 270 0)) (2d-vector-set! vec-pos 0 2 (cons 550 0)) (2d-vector-set! vec-pos 0 3 (cons 550 275)) (2d-vector-set! vec-pos 0 4 (cons 550 540)) (2d-vector-set! vec-pos 0 5 (cons 270 540)) (2d-vector-set! vec-pos 0 6 (cons 0 540)) (2d-vector-set! vec-pos 0 7 (cons 0 275)) (2d-vector-set! vec-pos 1 0 (cons 60 60)) (2d-vector-set! vec-pos 1 1 (cons 270 60)) (2d-vector-set! vec-pos 1 2 (cons 480 60)) (2d-vector-set! vec-pos 1 3 (cons 480 275)) (2d-vector-set! vec-pos 1 4 (cons 480 470)) (2d-vector-set! vec-pos 1 5 (cons 270 470)) (2d-vector-set! vec-pos 1 6 (cons 60 470)) (2d-vector-set! vec-pos 1 7 (cons 60 275)) (2d-vector-set! vec-pos 2 0 (cons 130 130)) (2d-vector-set! vec-pos 2 1 (cons 270 130)) (2d-vector-set! vec-pos 2 2 (cons 410 130)) (2d-vector-set! vec-pos 2 3 (cons 410 275)) (2d-vector-set! vec-pos 2 4 (cons 410 400)) (2d-vector-set! vec-pos 2 5 (cons 270 400)) (2d-vector-set! vec-pos 2 6 (cons 130 400)) (2d-vector-set! vec-pos 2 7 (cons 130 275)) (define (outhelper vec r c) (if (> r 2) "Done" (if (> c 7) (outhelper vec (+ r 1) 0) (cond [(equal? (2d-vector-ref vec r c) "HW") (begin ((draw-pixmap windw) "white-1.gif" (make-posn (car (2d-vector-ref vec-pos r c)) (cdr (2d-vector-ref vec-pos r c)))) (outhelper vec r (+ c 1)))] [(equal? (2d-vector-ref vec r c) "CB") (begin ((draw-pixmap windw) "black-1.gif" (make-posn (car (2d-vector-ref vec-pos r c)) (cdr (2d-vector-ref vec-pos r c)))) (outhelper vec r (+ c 1)))] [(equal? (2d-vector-ref vec r c) "HHW") (begin ((draw-pixmap windw) "highlight-1.gif" (make-posn (car (2d-vector-ref vec-pos r c)) (cdr (2d-vector-ref vec-pos r c)))) (outhelper vec r (+ c 1)))] [else (outhelper vec r (+ c 1))])))) (define (main2 vec i) (define (helper r c) (if (> r 2) "Done" (if (> c 7) (helper (+ r 1) 0) (cond [(equal? (substring (2d-vector-ref vec r c) 0 2) "HW") (begin ((draw-pixmap windw) "white-1.gif" (make-posn (car (2d-vector-ref vec-pos r c)) (cdr (2d-vector-ref vec-pos r c)))) (helper r (+ c 1)))] [(equal? (substring (2d-vector-ref vec r c) 0 2) "CB") (begin ((draw-pixmap windw) "black-1.gif" (make-posn (car (2d-vector-ref vec-pos r c)) (cdr (2d-vector-ref vec-pos r c)))) (helper r (+ c 1)))] [(equal? (substring (2d-vector-ref vec r c) 0 3) "HHW") (begin ((draw-pixmap windw) "highlight-1.gif" (make-posn (car (2d-vector-ref vec-pos r c)) (cdr (2d-vector-ref vec-pos r c)))) (helper r (+ c 1)))] [else (begin ((clear-pixel windw) (make-posn (car (2d-vector-ref vec-pos r c)) (cdr (2d-vector-ref vec-pos r c)))) (helper r (+ c 1)))])))) (define (invalid) (define frame (new frame% [label "Example"] [width 100] [height 40])) (define msg (new message% [parent frame] [label "Invalid Selection"])) (send frame show #t)) (define (coordinates) (define mouse-click-pos 0) (begin (set! mouse-click-pos (mouse-click-posn (get-mouse-click windw))) (cond [(and (< (posn-x mouse-click-pos) 39) (< (posn-y mouse-click-pos) 39)) (cons 0 0)] [(and (< (posn-x mouse-click-pos) 315) (> (posn-x mouse-click-pos) 270) (< (posn-y mouse-click-pos) 45) (> (posn-y mouse-click-pos) 0)) (cons 0 1)] [(and (< (posn-x mouse-click-pos) 600) (> (posn-x mouse-click-pos) 550) (< (posn-y mouse-click-pos) 45) (> (posn-y mouse-click-pos) 0)) (cons 0 2)] [(and (< (posn-x mouse-click-pos) 600) (> (posn-x mouse-click-pos) 550) (< (posn-y mouse-click-pos) 320) (> (posn-y mouse-click-pos) 275)) (cons 0 3)] [(and (< (posn-x mouse-click-pos) 600) (> (posn-x mouse-click-pos) 550) (< (posn-y mouse-click-pos) 600) (> (posn-y mouse-click-pos) 545)) (cons 0 4)] [(and (< (posn-x mouse-click-pos) 315) (> (posn-x mouse-click-pos) 270) (< (posn-y mouse-click-pos) 600) (> (posn-y mouse-click-pos) 545)) (cons 0 5)] [(and (< (posn-x mouse-click-pos) 39) (> (posn-x mouse-click-pos) 0) (< (posn-y mouse-click-pos) 600) (> (posn-y mouse-click-pos) 545)) (cons 0 6)] [(and (< (posn-x mouse-click-pos) 39) (> (posn-x mouse-click-pos) 0) (< (posn-y mouse-click-pos) 320) (> (posn-y mouse-click-pos) 275)) (cons 0 7)] [(and (< (posn-x mouse-click-pos) 105) (> (posn-x mouse-click-pos) 65) (< (posn-y mouse-click-pos) 110) (> (posn-y mouse-click-pos) 65)) (cons 1 0)] [(and (< (posn-x mouse-click-pos) 315) (> (posn-x mouse-click-pos) 270) (< (posn-y mouse-click-pos) 110) (> (posn-y mouse-click-pos) 65)) (cons 1 1)] [(and (< (posn-x mouse-click-pos) 525) (> (posn-x mouse-click-pos) 480) (< (posn-y mouse-click-pos) 110) (> (posn-y mouse-click-pos) 65)) (cons 1 2)] [(and (< (posn-x mouse-click-pos) 525) (> (posn-x mouse-click-pos) 480) (< (posn-y mouse-click-pos) 320) (> (posn-y mouse-click-pos) 275)) (cons 1 3)] [(and (< (posn-x mouse-click-pos) 525) (> (posn-x mouse-click-pos) 480) (< (posn-y mouse-click-pos) 500) (> (posn-y mouse-click-pos) 450)) (cons 1 4)] [(and (< (posn-x mouse-click-pos) 315) (> (posn-x mouse-click-pos) 270) (< (posn-y mouse-click-pos) 500) (> (posn-y mouse-click-pos) 450)) (cons 1 5)] [(and (< (posn-x mouse-click-pos) 110) (> (posn-x mouse-click-pos) 65) (< (posn-y mouse-click-pos) 500) (> (posn-y mouse-click-pos) 450)) (cons 1 6)] [(and (< (posn-x mouse-click-pos) 105) (> (posn-x mouse-click-pos) 65) (< (posn-y mouse-click-pos) 320) (> (posn-y mouse-click-pos) 275)) (cons 1 7)] [(and (< (posn-x mouse-click-pos) 185) (> (posn-x mouse-click-pos) 135) (< (posn-y mouse-click-pos) 185) (> (posn-y mouse-click-pos) 135)) (cons 2 0)] [(and (< (posn-x mouse-click-pos) 315) (> (posn-x mouse-click-pos) 270) (< (posn-y mouse-click-pos) 185) (> (posn-y mouse-click-pos) 135)) (cons 2 1)] [(and (< (posn-x mouse-click-pos) 454) (> (posn-x mouse-click-pos) 410) (< (posn-y mouse-click-pos) 185) (> (posn-y mouse-click-pos) 135)) (cons 2 2)] [(and (< (posn-x mouse-click-pos) 454) (> (posn-x mouse-click-pos) 410) (< (posn-y mouse-click-pos) 320) (> (posn-y mouse-click-pos) 275)) (cons 2 3)] [(and (< (posn-x mouse-click-pos) 454) (> (posn-x mouse-click-pos) 410) (< (posn-y mouse-click-pos) 450) (> (posn-y mouse-click-pos) 405)) (cons 2 4)] [(and (< (posn-x mouse-click-pos) 315) (> (posn-x mouse-click-pos) 270) (< (posn-y mouse-click-pos) 450) (> (posn-y mouse-click-pos) 405)) (cons 2 5)] [(and (< (posn-x mouse-click-pos) 185) (> (posn-x mouse-click-pos) 135) (< (posn-y mouse-click-pos) 450) (> (posn-y mouse-click-pos) 405)) (cons 2 6)] [(and (< (posn-x mouse-click-pos) 185) (> (posn-x mouse-click-pos) 135) (< (posn-y mouse-click-pos) 320) (> (posn-y mouse-click-pos) 275)) (cons 2 7)] [else "Invalid Selection" ] ))) (begin ((draw-pixmap windw) "morris.gif" (make-posn 0 0)) (if (= i 1) (begin (helper 0 0) (coordinates)) (helper 0 0) ))) (define (main1 pair) (begin (2d-vector-set! board-status (car pair) (cdr pair) "HW") (main1 (main2 board-status)))) (define (placing-position-checking circle-id-pair) (if (equal? circle-id-pair "Invalid Selection") (placing-position-checking (main2 board-status 1)) (let ((val-at-circle (2d-vector-ref board-status (car circle-id-pair) (cdr circle-id-pair)))) (cond [(equal? count 8) (selecting-to-move-position-checking circle-id-pair)] [(not (equal? val-at-circle "EMPTY")) (placing-position-checking (main2 board-status 1))] ;;Afterwards include error statement. [else (updating-by-placing circle-id-pair)])))) (define (updating-by-placing final-pos) (begin (set! count (+ count 1)) (set! selected-piece (cons final-pos (string-append "HW" (string (vector-ref reference count))))) (2d-vector-set! board-status (car final-pos) (cdr final-pos) (cdr selected-piece)) (vector-set! human-white-pos (string->number (string (string-ref (cdr selected-piece) 2))) final-pos) (if (not (checking-for-mill final-pos `human board-status)) (begin (main2 board-status 2) (let ((most-imp (best-move-generator))) (if (number? (car most-imp)) (begin (2d-vector-set! board-status (car most-imp) (cdr most-imp) (string-append "CB" (string (vector-ref reference mycount)))) (vector-set! computer-black-pos mycount most-imp) (set! mycount (+ mycount 1))) (begin (2d-vector-set! board-status (caar most-imp) (cdar most-imp) (string-append "CB" (string (vector-ref reference mycount)))) (vector-set! computer-black-pos mycount (car most-imp)) (main2 board-status 2) (vector-set! human-white-pos (string->number (string (string-ref (2d-vector-ref board-status (caadr most-imp) (cdadr most-imp)) 2))) (cons -2 -2)) (2d-vector-set! board-status (caadr most-imp) (cdadr most-imp) "EMPTY") (set! mycount (+ mycount 1))))) (placing-position-checking (main2 board-status 1))) (selecting-to-remove1-position-checking (main2 board-status 1)) ))) (define (checking-for-mill final-pos player board-status) (let ((loop-no (car final-pos)) (circle-no (cdr final-pos))) (cond [(= circle-no 0) (if (or (checking-mill-D-type loop-no player board-status) (checking-mill-A-type loop-no player board-status)) #t #f)] [(= circle-no 2) (if (or (checking-mill-A-type loop-no player board-status) (checking-mill-B-type loop-no player board-status)) #t #f)] [(= circle-no 4) (if (or (checking-mill-B-type loop-no player board-status) (checking-mill-C-type loop-no player board-status)) #t #f)] [(= circle-no 6) (if (or (checking-mill-C-type loop-no player board-status) (checking-mill-D-type loop-no player board-status)) #t #f)] [(= circle-no 1) (if (or (checking-mill-A-type loop-no player board-status) (checking-mill-E-type 1 player board-status)) #t #f)] [(= circle-no 3) (if (or (checking-mill-B-type loop-no player board-status) (checking-mill-E-type 3 player board-status)) #t #f)] [(= circle-no 5) (if (or (checking-mill-C-type loop-no player board-status) (checking-mill-E-type 5 player board-status)) #t #f)] [(= circle-no 7) (if (or (checking-mill-D-type loop-no player board-status) (checking-mill-E-type 7 player board-status)) #t #f)]))) (define (checking-mill-A-type loop-no player board-status) (if (equal? player `human) (and (equal? #\H (string-ref (2d-vector-ref board-status loop-no 0) 0)) (equal? #\H (string-ref (2d-vector-ref board-status loop-no 1) 0)) (equal? #\H (string-ref (2d-vector-ref board-status loop-no 2) 0))) (and (equal? #\C (string-ref (2d-vector-ref board-status loop-no 0) 0)) (equal? #\C (string-ref (2d-vector-ref board-status loop-no 1) 0)) (equal? #\C (string-ref (2d-vector-ref board-status loop-no 2) 0))))) (define (checking-mill-B-type loop-no player board-status) (if (equal? player `human) (and (equal? #\H (string-ref (2d-vector-ref board-status loop-no 2) 0)) (equal? #\H (string-ref (2d-vector-ref board-status loop-no 3) 0)) (equal? #\H (string-ref (2d-vector-ref board-status loop-no 4) 0))) (and (equal? #\C (string-ref (2d-vector-ref board-status loop-no 2) 0)) (equal? #\C (string-ref (2d-vector-ref board-status loop-no 3) 0)) (equal? #\C (string-ref (2d-vector-ref board-status loop-no 4) 0))))) (define (checking-mill-C-type loop-no player board-status) (if (equal? player `human) (and (equal? #\H (string-ref (2d-vector-ref board-status loop-no 4) 0)) (equal? #\H (string-ref (2d-vector-ref board-status loop-no 5) 0)) (equal? #\H (string-ref (2d-vector-ref board-status loop-no 6) 0))) (and (equal? #\C (string-ref (2d-vector-ref board-status loop-no 4) 0)) (equal? #\C (string-ref (2d-vector-ref board-status loop-no 5) 0)) (equal? #\C (string-ref (2d-vector-ref board-status loop-no 6) 0))))) (define (checking-mill-D-type loop-no player board-status) (if (equal? player `human) (and (equal? #\H (string-ref (2d-vector-ref board-status loop-no 6) 0)) (equal? #\H (string-ref (2d-vector-ref board-status loop-no 7) 0)) (equal? #\H (string-ref (2d-vector-ref board-status loop-no 0) 0))) (and (equal? #\C (string-ref (2d-vector-ref board-status loop-no 6) 0)) (equal? #\C (string-ref (2d-vector-ref board-status loop-no 7) 0)) (equal? #\C (string-ref (2d-vector-ref board-status loop-no 0) 0))))) (define (checking-mill-E-type circle-no player board-status) (if (equal? player `human) (and (equal? #\H (string-ref (2d-vector-ref board-status 0 circle-no) 0)) (equal? #\H (string-ref (2d-vector-ref board-status 1 circle-no) 0)) (equal? #\H (string-ref (2d-vector-ref board-status 2 circle-no) 0))) (and (equal? #\C (string-ref (2d-vector-ref board-status 0 circle-no) 0)) (equal? #\C (string-ref (2d-vector-ref board-status 1 circle-no) 0)) (equal? #\C (string-ref (2d-vector-ref board-status 2 circle-no) 0))))) (define (selecting-to-remove1-position-checking circle-id-pair) (if (equal? circle-id-pair "Invalid Selection") (selecting-to-remove1-position-checking (main2 board-status 1)) (let ((val-at-circle (2d-vector-ref board-status (car circle-id-pair) (cdr circle-id-pair)))) (cond [(not (equal? (string-ref val-at-circle 0) #\C)) (selecting-to-remove1-position-checking (main2 board-status 1))];;Include error statement. [else (if (checking-for-mill circle-id-pair `computer board-status) (selecting-to-remove1-position-checking (main2 board-status 1)) (updating-by-removing1 circle-id-pair))])))) (define (updating-by-removing1 circle-id-pair) (let ((loop-no (car circle-id-pair)) (circle-no (cdr circle-id-pair))) (begin (vector-set! computer-black-pos (string->number (string (string-ref (2d-vector-ref board-status loop-no circle-no) 2))) (cons -2 -2)) (2d-vector-set! board-status loop-no circle-no "EMPTY") (begin (main2 board-status 2) (let ((most-imp (best-move-generator))) (if (number? (car most-imp)) (begin (2d-vector-set! board-status (car most-imp) (cdr most-imp) (string-append "CB" (string (vector-ref reference mycount)))) (vector-set! computer-black-pos mycount most-imp) (set! mycount (+ mycount 1))) (begin (2d-vector-set! board-status (caar most-imp) (cdar most-imp) (string-append "CB" (string (vector-ref reference mycount)))) (vector-set! computer-black-pos mycount (car most-imp)) (main2 board-status 2) (vector-set! human-white-pos (string->number (string (string-ref (2d-vector-ref board-status (caadr most-imp) (cdadr most-imp)) 2))) (cons -2 -2)) (2d-vector-set! board-status (caadr most-imp) (cdadr most-imp) "EMPTY") (set! mycount (+ mycount 1))))) (placing-position-checking (main2 board-status 1)))))) (define (selecting-to-move-position-checking circle-id-pair) (if (equal? circle-id-pair "Invalid Selection") (selecting-to-move-position-checking (main2 board-status 1)) (let ((val-at-circle (2d-vector-ref board-status (car circle-id-pair) (cdr circle-id-pair)))) (cond [(not (equal? (string-ref val-at-circle 0) #\H)) (selecting-to-move-position-checking (main2 board-status 1))];;Include error statement [else (updating-by-selecting circle-id-pair)])))) (define (updating-by-selecting circle-id-pair) (let ((loop-no (car circle-id-pair)) (circle-no (cdr circle-id-pair))) (begin (set! selected-piece (cons circle-id-pair (2d-vector-ref board-status loop-no circle-no))) (2d-vector-set! board-status loop-no circle-no (string-append "H" (cdr selected-piece))) (moving-position-checking (main2 board-status 1))))) (define (moving-position-checking circle-id-pair) (if (equal? circle-id-pair "Invalid Selection") (moving-position-checking (main2 board-status 1)) (let ((val-at-circle (2d-vector-ref board-status (car circle-id-pair) (cdr circle-id-pair)))) (cond [(not (equal? val-at-circle "EMPTY")) (begin (2d-vector-set! board-status (car (car selected-piece)) (cdr (car selected-piece)) (cdr selected-piece)) (selecting-to-move-position-checking (main2 board-status 1)))] [else (cond [(not (checking-adjacent-pos circle-id-pair)) (begin (2d-vector-set! board-status (car (car selected-piece)) (cdr (car selected-piece)) (cdr selected-piece)) (selecting-to-move-position-checking (main2 board-status 1)))] [else (updating-by-moving circle-id-pair)])])))) (define (checking-adjacent-pos final-pos) (let* ((init-pos (car selected-piece)) (init-loop-no (car init-pos)) (init-circle-no (cdr init-pos)) (final-loop-no (car final-pos)) (final-circle-no (cdr final-pos))) (cond [(equal? init-loop-no final-loop-no) (if (equal? (abs (- init-circle-no final-circle-no)) 1) #t (if (or (and (= init-circle-no 0) (= final-circle-no 7)) (and (= init-circle-no 7) (= final-circle-no 0))) #t #f))] [(and (equal? (abs (- init-loop-no final-loop-no)) 1) (or (= init-circle-no final-circle-no 1) (= init-circle-no final-circle-no 3) (= init-circle-no final-circle-no 5) (= init-circle-no final-circle-no 7))) #t] [else #f]))) (define (updating-by-moving final-pos) (begin (2d-vector-set! board-status (car final-pos) (cdr final-pos) (cdr selected-piece)) (2d-vector-set! board-status (car (car selected-piece)) (cdr (car selected-piece)) "EMPTY") (vector-set! human-white-pos (string->number (string (string-ref (cdr selected-piece) 2))) final-pos) (if (not (checking-for-mill final-pos `human board-status)) (if (= (cdr (alivepieces)) (cdr (blocked-pieces))) (you-win) (begin (main2 board-status 2) (let ((most-imp (best-move-generator))) (if (number? (car (list-ref most-imp 0))) (begin (2d-vector-set! board-status (car (list-ref most-imp 1)) (cdr (list-ref most-imp 1)) (2d-vector-ref board-status (car (list-ref most-imp 0)) (cdr (list-ref most-imp 0)))) (vector-set! computer-black-pos (string->number (string (string-ref (2d-vector-ref board-status (car (list-ref most-imp 0)) (cdr (list-ref most-imp 0))) 2))) (list-ref most-imp 1)) (2d-vector-set! board-status (car (list-ref most-imp 0)) (cdr (list-ref most-imp 0)) "EMPTY") (if (= (car (alivepieces)) (car (blocked-pieces))) (you-lost) (selecting-to-move-position-checking (main2 board-status 1)))) (begin (2d-vector-set! board-status (car (list-ref (list-ref most-imp 0) 1)) (cdr (list-ref (list-ref most-imp 0) 1)) (2d-vector-ref board-status (car (list-ref (list-ref most-imp 0) 0)) (cdr (list-ref (list-ref most-imp 0) 0)))) (vector-set! computer-black-pos (string->number (string (string-ref (2d-vector-ref board-status (car (list-ref (list-ref most-imp 0) 0)) (cdr (list-ref (list-ref most-imp 0) 0))) 2))) (list-ref (list-ref most-imp 0) 1)) (2d-vector-set! board-status (car (list-ref (list-ref most-imp 0) 0)) (cdr (list-ref (list-ref most-imp 0) 0)) "EMPTY") (main2 board-status 2) (vector-set! human-white-pos (string->number (string (string-ref (2d-vector-ref board-status (car (list-ref most-imp 1)) (cdr (list-ref most-imp 1))) 2))) (cons -2 -2)) (2d-vector-set! board-status (car (list-ref most-imp 1)) (cdr (list-ref most-imp 1)) "EMPTY") (if (or (= (car (alivepieces)) (car (blocked-pieces))) (= 2 (no-of-coins `human))) (you-lost) (selecting-to-move-position-checking (main2 board-status 1)))))))) (if (= 3 (no-of-coins `computer)) (you-win) (selecting-to-remove2-position-checking (main2 board-status 1)))))) (define (alivepieces) (cons (foldr + 0 (map (lambda (x) (if (equal? x (cons -2 -2)) 0 1)) (vector->list human-white-pos))) (foldr + 0 (map (lambda (x) (if (equal? x (cons -2 -2)) 0 1)) (vector->list computer-black-pos))))) ;returns number of free movement any coin can make (define (free-movements coin-id cur-pos) (define extended-board (build-vector 3 (lambda(x) (let ((m (vector-ref board-status x))) (vector-append (vector-drop m 7) m (vector (vector-ref m 0))))))) (define (check-surrounding pair) (if (< (cdr pair) 0) 0 (if (= (remainder (cdr pair) 2) 0) (adjacent-vacant pair) (+ (adjacent-vacant pair) (upar-niche-vacant pair))))) (define (adjacent-vacant pair) ; number of adjacent vacant place (let ([a (substring (2d-vector-ref extended-board (car pair) (cdr pair)) 0 2)] [b (substring (2d-vector-ref extended-board (car pair) (+ 2 (cdr pair))) 0 2)]) (if (and (or (equal? a "HW") (equal? a "CB")) (or (equal? b "HW") (equal? b "CB"))) 0 (if (or (or (equal? a "HW") (equal? a "CB")) (or (equal? b "HW") (equal? b "CB"))) 1 2)))) (define (upar-niche-vacant pair) ; number of upar niche vacant place (let ([a (if (= (car pair) 0) "HW" (substring (2d-vector-ref extended-board (- (car pair) 1) (+ 1 (cdr pair))) 0 2))] [b (if (= (car pair) 2) "HW" (substring (2d-vector-ref extended-board (+ 1 (car pair)) (+ (cdr pair) 1)) 0 2))]) (if (and (or (equal? a "HW") (equal? a "CB")) (or (equal? b "HW") (equal? b "CB"))) 0 (if (or (or (equal? a "HW") (equal? a "CB")) (or (equal? b "HW") (equal? b "CB"))) 1 2)))) (if (not (equal? (or (cons -2 -2) (cons -1 -1)) (vector-ref cur-pos (string->number (string (string-ref coin-id 2)))))) (check-surrounding (vector-ref cur-pos (string->number (string (string-ref coin-id 2))))) 0)) ;this function gives the number of blocked pieces (cons white black) (define (blocked-pieces) (define i 0) (define j 0) (let ((temp1 (reverse (lc (begin (set! i (add1 i)) i) : x <- `("HW0" "HW1" "HW2" "HW3" "HW4" "HW5" "HW6" "HW7" "HW8") * (and (= (free-movements x human-white-pos) 0)(>= (cdr (vector-ref human-white-pos (string->number (string (string-ref x 2))))) 0))))) (temp2 (reverse (lc (begin (set! j (add1 j)) j) : x <- `("CB0" "CB1" "CB2" "CB3" "CB4" "CB5" "CB6" "CB7" "CB8") * (and (= (free-movements x computer-black-pos) 0)(>= (cdr (vector-ref computer-black-pos (string->number (string (string-ref x 2))))) 0)))))) (cons (if (equal? temp1 `()) 0 (car temp1)) (if (equal? temp2 `()) 0 (car temp2))))) (define (selecting-to-remove2-position-checking circle-id-pair) (if (equal? circle-id-pair "Invalid Selection") (selecting-to-remove2-position-checking (main2 board-status 1));;Include Error Statement (let ((val-at-circle (2d-vector-ref board-status (car circle-id-pair) (cdr circle-id-pair)))) (cond [(not (equal? (string-ref val-at-circle 0) #\C)) (selecting-to-remove2-position-checking (main2 board-status 1))];;Include error statement. [else (if (checking-for-mill circle-id-pair `computer board-status) (selecting-to-remove2-position-checking (main2 board-status 1)) (updating-by-removing2 circle-id-pair))])))) (define (updating-by-removing2 circle-id-pair) (let ((loop-no (car circle-id-pair)) (circle-no (cdr circle-id-pair))) (begin (vector-set! computer-black-pos (string->number (string (string-ref (2d-vector-ref board-status loop-no circle-no) 2))) (cons -2 -2)) (2d-vector-set! board-status loop-no circle-no "EMPTY") (if (= (cdr (alivepieces)) (cdr (blocked-pieces))) (you-win) (begin (main2 board-status 2) (let ((most-imp (best-move-generator))) (if (number? (car (list-ref most-imp 0))) (begin (2d-vector-set! board-status (car (list-ref most-imp 1)) (cdr (list-ref most-imp 1)) (2d-vector-ref board-status (car (list-ref most-imp 0)) (cdr (list-ref most-imp 0)))) (vector-set! computer-black-pos (string->number (string (string-ref (2d-vector-ref board-status (car (list-ref most-imp 0)) (cdr (list-ref most-imp 0))) 2))) (list-ref most-imp 1)) (2d-vector-set! board-status (car (list-ref most-imp 0)) (cdr (list-ref most-imp 0)) "EMPTY") (if (= (car (alivepieces)) (car (blocked-pieces))) (you-lost) (selecting-to-move-position-checking (main2 board-status 1)))) (begin (2d-vector-set! board-status (car (list-ref (list-ref most-imp 0) 1)) (cdr (list-ref (list-ref most-imp 0) 1)) (2d-vector-ref board-status (car (list-ref (list-ref most-imp 0) 0)) (cdr (list-ref (list-ref most-imp 0) 0)))) (vector-set! computer-black-pos (string->number (string (string-ref (2d-vector-ref board-status (car (list-ref (list-ref most-imp 0) 0)) (cdr (list-ref (list-ref most-imp 0) 0))) 2))) (list-ref (list-ref most-imp 0) 1)) (2d-vector-set! board-status (car (list-ref (list-ref most-imp 0) 0)) (cdr (list-ref (list-ref most-imp 0) 0)) "EMPTY") (main2 board-status 2) (vector-set! human-white-pos (string->number (string (string-ref (2d-vector-ref board-status (car (list-ref most-imp 1)) (cdr (list-ref most-imp 1))) 2))) (cons -2 -2)) (2d-vector-set! board-status (car (list-ref most-imp 1)) (cdr (list-ref most-imp 1)) "EMPTY") (if (or (= (car (alivepieces)) (car (blocked-pieces))) (= 2 (no-of-coins `human))) (you-lost) (selecting-to-move-position-checking (main2 board-status 1))))))))))) (define (no-of-coins player) (if (equal? player `computer) (counter computer-black-pos 8 9) (counter human-white-pos 8 9))) (define (counter vec index ans) (if (= index 0) (if (equal? (cons -2 -2) (vector-ref vec 0)) (- ans 1) ans) (if (equal? (cons -2 -2) (vector-ref vec index)) (counter vec (- index 1) (- ans 1)) (counter vec (- index 1) ans)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;<END OF GRAPHICS>;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;<BEST MOVE GENERATOR>;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (pos-eval-func-phase1 cur-board-status cur-human-pos cur-comp-pos player closed-morris) ;;extended-vector 3*8 to 3*9 (define board1 (build-vector 3 (lambda(x) (let ((m (vector-ref cur-board-status x))) (vector-append m (vector (vector-ref m 0))))))) ;total number complete mills (cons white black) (define (no-of-mills) (define (all-same-element v) (= (length (filter (lambda(x) (equal? (substring x 0 2) (substring (list-ref (vector->list v) 0) 0 2))) (vector->list v))) (length (vector->list v)))) (define (no-of-mills-in-loop) (define (helper x y i j) (if (and (= i 2) (= j 8)) (cons x y) (if (= j 8) (begin (set! i (+ i 1)) (set! j 0) (helper x y i j)) (let ([r (build-vector 3 (lambda(x) (2d-vector-ref board1 i (+ x j))))]) (if (all-same-element r) (begin (if (equal? (substring (vector-ref r 0) 0 2) "HW") (set! x (+ x 1)) (if (equal? (substring (vector-ref r 0) 0 2) "CB") (set! y (+ y 1)) (set! x (+ x 0)))) (helper x y i (+ j 2))) (helper x y i (+ j 2))))))) (helper 0 0 0 0)) (define (no-of-mills-on-side) (define (helper x y k) (if (= k 9) (cons x y) (let ([r (build-vector 3 (lambda(x) (2d-vector-ref board1 x k)))]) (if (all-same-element r) (begin (if (equal? (substring (vector-ref r 0) 0 2) "HW") (set! x (+ x 1)) (if (equal? (substring (vector-ref r 0) 0 2) "CB") (set! y (+ y 1)) (set! x (+ x 0)))) (helper x y (+ k 2))) (helper x y (+ k 2)))))) (helper 0 0 1)) (let ([a (no-of-mills-on-side)] [b (no-of-mills-in-loop)]) (cons (+ (car a) (car b)) (+ (cdr a) (cdr b))))) ;returns number of corner pieces (cons white black) (define (corner-pieces) (define (helper i) (if (= i 8) (vector) (vector-append (build-vector 3 (lambda(x) (2d-vector-ref cur-board-status x i))) (helper (+ i 2))))) (let ([v (helper 0)]) (cons (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "HW")) v)) (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "CB")) v))))) ;returns number of pieces on intersection (cons white black) (define (intersection-pieces) (let ([v (build-vector 4 (lambda(x) (2d-vector-ref cur-board-status 1 (+ 1 (* 2 x)))))]) (cons (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "HW")) v)) (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "CB")) v))))) ;returns number of pieces on side (cons white black) (define (side-pieces) (let ([v (vector-append (build-vector 4 (lambda(x) (2d-vector-ref cur-board-status 0 (+ 1 (* 2 x))))) (build-vector 4 (lambda(x) (2d-vector-ref cur-board-status 2 (+ 1 (* 2 x))))))]) (cons (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "HW")) v)) (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "CB")) v))))) ;returns number of free movement any coin can make (define (free-movements coin-id cur-pos) (define extended-board (build-vector 3 (lambda(x) (let ((m (vector-ref cur-board-status x))) (vector-append (vector-drop m 7) m (vector (vector-ref m 0))))))) (define (check-surrounding pair) (if (< (cdr pair) 0) 0 (if (= (remainder (cdr pair) 2) 0) (adjacent-vacant pair) (+ (adjacent-vacant pair) (upar-niche-vacant pair))))) (define (adjacent-vacant pair) ; number of adjacent vacant place (let ([a (substring (2d-vector-ref extended-board (car pair) (cdr pair)) 0 2)] [b (substring (2d-vector-ref extended-board (car pair) (+ 2 (cdr pair))) 0 2)]) (if (and (or (equal? a "HW") (equal? a "CB")) (or (equal? b "HW") (equal? b "CB"))) 0 (if (or (or (equal? a "HW") (equal? a "CB")) (or (equal? b "HW") (equal? b "CB"))) 1 2)))) (define (upar-niche-vacant pair) ; number of upar niche vacant place (let ([a (if (= (car pair) 0) "HW" (substring (2d-vector-ref extended-board (- (car pair) 1) (+ 1 (cdr pair))) 0 2))] [b (if (= (car pair) 2) "HW" (substring (2d-vector-ref extended-board (+ 1 (car pair)) (+ (cdr pair) 1)) 0 2))]) (if (and (or (equal? a "HW") (equal? a "CB")) (or (equal? b "HW") (equal? b "CB"))) 0 (if (or (or (equal? a "HW") (equal? a "CB")) (or (equal? b "HW") (equal? b "CB"))) 1 2)))) (if (not (equal? (or (cons -2 -2) (cons -1 -1)) (vector-ref cur-pos (string->number (string (string-ref coin-id 2)))))) (check-surrounding (vector-ref cur-pos (string->number (string (string-ref coin-id 2))))) 0)) ;this function gives the number of blocked pieces (cons white black) (define (blocked-pieces) (define i 0) (define j 0) (let ((temp1 (reverse (lc (begin (set! i (add1 i)) i) : x <- `("HW0" "HW1" "HW2" "HW3" "HW4" "HW5" "HW6" "HW7" "HW8") * (and (= (free-movements x cur-human-pos) 0)(>= (cdr (vector-ref cur-human-pos (string->number (string (string-ref x 2))))) 0))))) (temp2 (reverse (lc (begin (set! j (add1 j)) j) : x <- `("CB0" "CB1" "CB2" "CB3" "CB4" "CB5" "CB6" "CB7" "CB8") * (and (= (free-movements x cur-comp-pos) 0)(>= (cdr (vector-ref cur-comp-pos (string->number (string (string-ref x 2))))) 0)))))) (cons (if (equal? temp1 `()) 0 (car temp1)) (if (equal? temp2 `()) 0 (car temp2))))) ;;no. of coins (cons white black) (define (no-of-coins) (cons (counter cur-human-pos 8 9) (counter cur-comp-pos 8 9))) (define (counter vec index ans) (if (= index 0) (if (equal? (cons -2 -2) (vector-ref vec 0)) (- ans 1) ans) (if (equal? (cons -2 -2) (vector-ref vec index)) (counter vec (- index 1) (- ans 1)) (counter vec (- index 1) ans)))) ;A “2 pieces configuration” refers to having 2 pieces on one line (and the other place empty, so morris possibility).this is an important consideration for starting phase (define (no-of-2-pieces-configuration) (define (2-same-element-1-empty v) (and (equal? (vector-filter (lambda(x) (equal? x "EMPTY")) v) #("EMPTY")) (or (= (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "HW")) v)) 2) (= (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "CB")) v)) 2)))) (define (no-of-2-pieces-configuration-in-loop) (define (helper x y i j) (if (and (= i 2) (= j 8)) (cons x y) (if (= j 8) (begin (set! i (+ i 1)) (set! j 0) (helper x y i j)) (let ([r (build-vector 3 (lambda(x) (2d-vector-ref board1 i (+ x j))))]) (if (2-same-element-1-empty r) (begin (if (equal? (vector-filter (lambda(x) (equal? (substring x 0 2) "CB")) r) #()) (set! x (+ x 1)) (set! y (+ y 1))) (helper x y i (+ j 2))) (helper x y i (+ j 2))))))) (helper 0 0 0 0)) (define (no-of-2-pieces-configuration-on-side) (define (helper x y k) (if (= k 9) (cons x y) (let ([r (build-vector 3 (lambda(x) (2d-vector-ref board1 x k)))]) (if (2-same-element-1-empty r) (begin (if (equal? (vector-filter (lambda(x) (equal? (substring x 0 2) "CB")) r) #()) (set! x (+ x 1)) (set! y (+ y 1))) (helper x y (+ k 2))) (helper x y (+ k 2)))))) (helper 0 0 1)) (let ([a (no-of-2-pieces-configuration-in-loop)] [b (no-of-2-pieces-configuration-on-side)]) (cons (+ (car a) (car b)) (+ (cdr a) (cdr b))))) ;this function gives three piece configuration (define (no-of-3-pieces-configuration) (define (3-pieces-configuration-side-wise) (define (2-same-element-1-empty v) (and (equal? (vector-filter (lambda(x) (equal? x "EMPTY")) v) #("EMPTY")) (or (= (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "HW")) v)) 2) (= (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "CB")) v)) 2)))) (define (helper x y i j) (if (= j 8) (helper x y (+ i 1) 0) (if (= i 3) (cons x y) (let* ([r1 (build-vector 3 (lambda(x) (2d-vector-ref board1 i (modulo (+ x j) 8))))] [r2 (build-vector 3 (lambda(x) (2d-vector-ref board1 i (modulo (+ x 2 j) 8))))] [t (build-vector 5 (lambda(x) (2d-vector-ref board1 i (modulo (+ x j) 8))))] [p1 (2-same-element-1-empty r1)] [p2 (2-same-element-1-empty r2)]) (if (and p1 p2) (if (= (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "HW")) t)) 3) (helper (+ x 1) y i (+ j 2)) (if (= (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "CB")) t)) 3) (helper x (+ y 1) i (+ j 2)) (helper x y i (+ j 2)))) (helper x y i (+ j 2))))))) (helper 0 0 0 0)) (define (3-pieces-configuration-cross-wise) (define (2-same-element-1-empty v) (and (equal? (vector-filter (lambda(x) (equal? x "EMPTY")) v) #("EMPTY")) (or (= (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "HW")) v)) 2) (= (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "CB")) v)) 2)))) (define (helper x y i j) (if (= j 8) (helper x y (+ i 1) 0) (if (= i 3) (cons x y) (let* ([r1 (build-vector 3 (lambda(x) (2d-vector-ref board1 i (modulo (+ x j) 8))))] [r2 (build-vector 3 (lambda(x) (2d-vector-ref board1 x (modulo (+ 1 j) 8))))] [t (vector-append r1 r2)] [p1 (2-same-element-1-empty r1)] [p2 (2-same-element-1-empty r2)]) (if (and p1 p2 (not (equal? (vector-ref r1 1) "EMPTY"))) (if (= (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "HW")) t)) 4) (helper (+ x 1) y i (+ j 2)) (if (= (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "CB")) t)) 4) (helper x (+ y 1) i (+ j 2)) (helper x y i (+ j 2)))) (helper x y i (+ j 2))))))) (helper 0 0 0 0)) (let ([a (3-pieces-configuration-side-wise)] [b (3-pieces-configuration-cross-wise)]) (cons (+ (car a) (car b)) (+ (cdr a) (cdr b))))) (define (seedha pair) (- (car pair) (cdr pair))) (define (ulta pair) (- (cdr pair) (car pair))) ; (begin (display closed-morris) ; (display (no-of-mills)) ;(display (corner-pieces)) ;(display (intersection-pieces)) ;(display (side-pieces)) ;(display (blocked-pieces)) ;(display (no-of-coins)) ;(display (no-of-2-pieces-configuration)) ; (display (no-of-3-pieces-configuration))) (if (equal? player `human) (+ (* closed-morris 18) (* 26 (seedha (no-of-mills))) (* 5 (seedha (intersection-pieces))) (* 2 (seedha (side-pieces))) (seedha (blocked-pieces)) (* 6 (seedha (no-of-coins))) (* 12 (seedha (no-of-2-pieces-configuration))) (* 7 (seedha (no-of-3-pieces-configuration)))) (+ (* closed-morris 18) (* 26 (ulta (no-of-mills))) (* 5 (ulta (intersection-pieces))) (* 2 (ulta (side-pieces))) (ulta (blocked-pieces)) (* 6 (ulta (no-of-coins))) (* 12 (ulta (no-of-2-pieces-configuration))) (* 7 (ulta (no-of-3-pieces-configuration))))) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (pos-eval-func-phase2 cur-board-status cur-human-pos cur-comp-pos player closed-morris) ;;extended-vector 3*8 to 3*9 (define board1 (build-vector 3 (lambda(x) (let ((m (vector-ref cur-board-status x))) (vector-append m (vector (vector-ref m 0))))))) ;total number complete mills (cons white black) (define (no-of-mills) (define (all-same-element v) (= (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) (substring (vector-ref v 0) 0 2))) v)) (vector-length v))) (define (no-of-mills-in-loop) (define (helper x y i j) (if (and (= i 2) (= j 8)) (cons x y) (if (= j 8) (begin (set! i (+ i 1)) (set! j 0) (helper x y i j)) (let ([r (build-vector 3 (lambda(x) (2d-vector-ref board1 i (+ x j))))]) (if (all-same-element r) (begin (if (equal? (substring (vector-ref r 0) 0 2) "HW") (set! x (+ x 1)) (if (equal? (substring (vector-ref r 0) 0 2) "CB") (set! y (+ y 1)) (set! x (+ x 0)))) (helper x y i (+ j 2))) (helper x y i (+ j 2))))))) (helper 0 0 0 0)) (define (no-of-mills-on-side) (define (helper x y k) (if (= k 9) (cons x y) (let ([r (build-vector 3 (lambda(x) (2d-vector-ref board1 x k)))]) (if (all-same-element r) (begin (if (equal? (substring (vector-ref r 0) 0 2) "HW") (set! x (+ x 1)) (if (equal? (substring (vector-ref r 0) 0 2) "CB") (set! y (+ y 1)) (set! x (+ x 0)))) (helper x y (+ k 2))) (helper x y (+ k 2)))))) (helper 0 0 1)) (let ([a (no-of-mills-on-side)] [b (no-of-mills-in-loop)]) (cons (+ (car a) (car b)) (+ (cdr a) (cdr b))))) ;returns number of free movement any coin can make (define (free-movements coin-id cur-pos) (define extended-board (build-vector 3 (lambda(x) (let ((m (vector-ref cur-board-status x))) (vector-append (vector-drop m 7) m (vector (vector-ref m 0))))))) (define (check-surrounding pair) (if (< (cdr pair) 0) 0 (if (= (remainder (cdr pair) 2) 0) (adjacent-vacant pair) (+ (adjacent-vacant pair) (upar-niche-vacant pair))))) (define (adjacent-vacant pair) ; number of adjacent vacant place (let ([a (substring (2d-vector-ref extended-board (car pair) (cdr pair)) 0 2)] [b (substring (2d-vector-ref extended-board (car pair) (+ 2 (cdr pair))) 0 2)]) (if (and (or (equal? a "HW") (equal? a "CB")) (or (equal? b "HW") (equal? b "CB"))) 0 (if (or (or (equal? a "HW") (equal? a "CB")) (or (equal? b "HW") (equal? b "CB"))) 1 2)))) (define (upar-niche-vacant pair) ; number of upar niche vacant place (let ([a (if (= (car pair) 0) "HW" (substring (2d-vector-ref extended-board (- (car pair) 1) (+ 1 (cdr pair))) 0 2))] [b (if (= (car pair) 2) "HW" (substring (2d-vector-ref extended-board (+ 1 (car pair)) (+ (cdr pair) 1)) 0 2))]) (if (and (or (equal? a "HW") (equal? a "CB")) (or (equal? b "HW") (equal? b "CB"))) 0 (if (or (or (equal? a "HW") (equal? a "CB")) (or (equal? b "HW") (equal? b "CB"))) 1 2)))) (if (not (equal? (or (cons -2 -2) (cons -1 -1)) (vector-ref cur-pos (string->number (string (string-ref coin-id 2)))))) (check-surrounding (vector-ref cur-pos (string->number (string (string-ref coin-id 2))))) 0)) ;this function gives the number of blocked pieces (cons white black) (define (blocked-pieces) (define i 0) (define j 0) (let ((temp1 (reverse (lc (begin (set! i (add1 i)) i) : x <- `("HW0" "HW1" "HW2" "HW3" "HW4" "HW5" "HW6" "HW7" "HW8") * (and (= (free-movements x cur-human-pos) 0)(>= (cdr (vector-ref cur-human-pos (string->number (string (string-ref x 2))))) 0))))) (temp2 (reverse (lc (begin (set! j (add1 j)) j) : x <- `("CB0" "CB1" "CB2" "CB3" "CB4" "CB5" "CB6" "CB7" "CB8") * (and (= (free-movements x cur-comp-pos) 0)(>= (cdr (vector-ref cur-comp-pos (string->number (string (string-ref x 2))))) 0)))))) (cons (if (equal? temp1 `()) 0 (car temp1)) (if (equal? temp2 `()) 0 (car temp2))))) ;;no. of coins (cons white black) (define (no-of-coins) (cons (counter cur-human-pos 8 9) (counter cur-comp-pos 8 9))) (define (counter vec index ans) (if (= index 0) (if (equal? (cons -2 -2) (vector-ref vec 0)) (- ans 1) ans) (if (equal? (cons -2 -2) (vector-ref vec index)) (counter vec (- index 1) (- ans 1)) (counter vec (- index 1) ans)))) ;A “2 pieces configuration” refers to having 2 pieces on one line (and the other place empty, so morris possibility).this is an important consideration for starting phase (define (no-of-2-pieces-configuration) (define (2-same-element-1-empty v) (and (equal? (vector-filter (lambda(x) (equal? x "EMPTY")) v) #("EMPTY")) (or (= (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "HW")) v)) 2) (= (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "CB")) v)) 2)))) (define (no-of-2-pieces-configuration-in-loop) (define (helper x y i j) (if (and (= i 2) (= j 8)) (cons x y) (if (= j 8) (begin (set! i (+ i 1)) (set! j 0) (helper x y i j)) (let ([r (build-vector 3 (lambda(x) (2d-vector-ref board1 i (+ x j))))]) (if (2-same-element-1-empty r) (begin (if (equal? (vector-filter (lambda(x) (equal? (substring x 0 2) "CB")) r) #()) (set! x (+ x 1)) (set! y (+ y 1))) (helper x y i (+ j 2))) (helper x y i (+ j 2))))))) (helper 0 0 0 0)) (define (no-of-2-pieces-configuration-on-side) (define (helper x y k) (if (= k 9) (cons x y) (let ([r (build-vector 3 (lambda(x) (2d-vector-ref board1 x k)))]) (if (2-same-element-1-empty r) (begin (if (equal? (vector-filter (lambda(x) (equal? (substring x 0 2) "CB")) r) #()) (set! x (+ x 1)) (set! y (+ y 1))) (helper x y (+ k 2))) (helper x y (+ k 2)))))) (helper 0 0 1)) (let ([a (no-of-2-pieces-configuration-in-loop)] [b (no-of-2-pieces-configuration-on-side)]) (cons (+ (car a) (car b)) (+ (cdr a) (cdr b))))) ;; (define noofcoins (no-of-coins)) (define blockedpieces (blocked-pieces)) ;; (define alivepieces (cons (foldr + 0 (map (lambda (x) (if (equal? x (cons -2 -2)) 0 1)) (vector->list cur-human-pos))) (foldr + 0 (map (lambda (x) (if (equal? x (cons -2 -2)) 0 1)) (vector->list cur-comp-pos))))) ;;Winning Condition (define winning-configuration (- (if (or (= 2 (cdr noofcoins)) (= (cdr alivepieces) (cdr blockedpieces))) 1 0) (if (or (= 2 (car noofcoins)) (= (car alivepieces) (car blockedpieces))) 1 0))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;< >;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;returns the number of double morris (cons white black) (define (double-morris) (define (2-same-element-1-empty v) (and (equal? (vector-filter (lambda(x) (equal? x "EMPTY")) v) #("EMPTY")) (or (= (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "HW")) v)) 2) (= (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "CB")) v)) 2)))) (define (all-same-element v) (= (length (filter (lambda(x) (equal? (substring x 0 2) (substring (list-ref (vector->list v) 0) 0 2))) (vector->list v))) (length (vector->list v)))) (define (double-morris-type1) (define (helper x y i j) (if (= j 8) (cons x y) (if (= i 2) (helper x y 0 (+ j 2)) (let* ([brd board1] [r1 (build-vector 3 (lambda(x) (2d-vector-ref brd i (modulo (+ x j) 8))))] [r2 (build-vector 3 (lambda(x) (2d-vector-ref brd(+ 1 i) (modulo (+ x j) 8))))] [p1 (and (2-same-element-1-empty r1) (equal? (vector-ref r1 1) "EMPTY"))] [p2 (and (2-same-element-1-empty r2) (equal? (vector-ref r2 1) "EMPTY"))] [q1 (all-same-element r1)] [q2 (all-same-element r2)] [t (vector-append r1 r2)]) (if (or (and p1 q2) (and p2 q1)) (if (= (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "HW")) t)) 5) (helper (+ x 1) y (+ 1 i) j) (if (= (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "CB")) t)) 5) (helper x (+ y 1) (+ 1 i) j) (helper x y (+ i 1) j))) (helper x y (+ 1 i) j)))))) (helper 0 0 0 0)) (define (double-morris-type2) (define (helper x y i j) (if (= j 9) (cons x y) (if (= i 3) (helper x y 0 (+ j 2)) (let* ([brd board1] [main-vec (build-vector 3 (lambda(x) (2d-vector-ref brd x j)))] [r1 (build-vector 3 (lambda(x) (2d-vector-ref brd i (modulo (- (- j 1) x) 8))))] [r2 (build-vector 3 (lambda(x) (2d-vector-ref brd i (modulo (+ (+ j 1) x) 8))))] [p (and (2-same-element-1-empty main-vec) (equal? (vector-ref main-vec i) "EMPTY"))] [p1 (and (2-same-element-1-empty r1) (equal? (vector-ref r1 0) "EMPTY"))] [p2 (and (2-same-element-1-empty r2) (equal? (vector-ref r2 0) "EMPTY"))] [q (all-same-element main-vec)] [q1 (all-same-element r1)] [q2 (all-same-element r2)] [t1 (vector-append main-vec r1)] [t2 (vector-append main-vec r2)] [hwt1 (= (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "HW")) t1)) 5)] [cbt1 (= (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "CB")) t1)) 5)] [hwt2 (= (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "HW")) t2)) 5)] [cbt2 (= (vector-length (vector-filter (lambda(x) (equal? (substring x 0 2) "CB")) t2)) 5)]) (if (and (or (and p q1) (and p1 q)) (or (and p q2) (and p2 q))) (cond [(and hwt1 hwt2) (helper (+ x 2) y (+ 1 i) j)] [(or (and cbt1 hwt2) (and hwt1 cbt2)) (helper (+ x 1) (+ y 1) (+ 1 i) j)] [(and cbt1 cbt2) (helper x (+ y 2) (+ 1 i) j)] [(or hwt1 hwt2) (helper (+ x 1) y (+ 1 i) j)] [(or cbt1 cbt2) (helper x (+ 1 y) (+ 1 i) j)] [else (helper x y (+ 1 i) j)]) (if (or (and p q1) (and p1 q)) (cond [hwt1 (helper (+ x 1) y (+ 1 i) j)] [cbt1 (helper x (+ 1 y) (+ 1 i) j)] [else (helper x y (+ 1 i) j)]) (if (or (and p q2) (and p2 q)) (cond [hwt2 (helper (+ x 1) y (+ 1 i) j)] [cbt2 (helper x (+ 1 y) (+ 1 i) j)] [else (helper x y (+ 1 i) j)]) (helper x y (+ 1 i) j)))))))) (helper 0 0 0 1)) (let ([a (double-morris-type1)] [b (double-morris-type2)]) (cons (+ (car a) (car b)) (+ (cdr a) (cdr b))))) (define (seedha pair) (- (car pair) (cdr pair))) (define (ulta pair) (- (cdr pair) (car pair))) ;(begin ; (display closed-morris) ; (display (no-of-mills)) ; (display blockedpieces) ; (display alivepieces) ; (display noofcoins) ; (display (no-of-2-pieces-configuration)) ; (display winning-configuration)) ; (display (double-morris)) (if (equal? player `human) (+ (* closed-morris 14) (* 43 (seedha (no-of-mills))) (* 10 (seedha blockedpieces)) (* 8 (seedha noofcoins)) (* 1086 winning-configuration) (* 6 (seedha (no-of-2-pieces-configuration))) (* 42 (seedha (double-morris)))) (+ (* closed-morris 14) (* 43 (ulta (no-of-mills))) (* 10 (ulta blockedpieces)) (* 8 (ulta noofcoins)) (* 1086 winning-configuration ) (* 6 (ulta (no-of-2-pieces-configuration))) (* 42 (ulta (double-morris))))) ) (define (make-vec vec) (define v (make-2d-vector 3 8 #f)) (define (helper i j) (cond [(= i 3) v] [(= j 7) (begin (2d-vector-set! v i j (2d-vector-ref vec i j)) (helper (+ i 1) 0))] [else (begin (2d-vector-set! v i j (2d-vector-ref vec i j)) (helper i (+ j 1)))])) (helper 0 0)) (define (make-vec1 vec) (define v (make-vector 9 #f)) (define (helper i) (if (= i 9) v (begin (vector-set! v i (vector-ref vec i)) (helper (+ i 1))))) (helper 0)) (define (possible-board-generators1 cur-board-status cur-pos player mycount1) (let ((temp-string (string-append (if (equal? player `computer) "CB" "HW") (string (vector-ref reference mycount1))))) (map (lambda (x) (let ((trial-vec (make-vec cur-board-status)) (trial-vec1 (make-vec1 cur-pos))) (begin (2d-vector-set! trial-vec (car x) (cdr x) temp-string) (vector-set! trial-vec1 mycount1 x) (list trial-vec trial-vec1 (checking-for-mill x player trial-vec) x)))) (lc x : x <- helper-list1 *(equal? "EMPTY" (2d-vector-ref cur-board-status (car x) (cdr x))))))) ;(trace possible-board-generators1) (define (possible-board-removers1 cur-board-status cur-pos player) (filter (lambda (x) (not (equal? x `()))) (map (lambda (x) (if (or (equal? x (cons -2 -2)) (equal? x (cons -1 -1)) (checking-for-mill x player cur-board-status)) `() (let ((trial-vec (make-vec cur-board-status)) (trial-vec1 (make-vec1 cur-pos))) (begin (2d-vector-set! trial-vec (car x) (cdr x) "EMPTY") (vector-set! trial-vec1 (string->number (string (string-ref (2d-vector-ref cur-board-status (car x) (cdr x)) 2))) (cons -2 -2)) (list trial-vec trial-vec1 x))))) (vector->list cur-pos)))) ;(trace possible-board-removers1) (define (possible-moves-generator cur-board-status cur-pos) (concat (lc (lc (append (list (car z)) (list w)) : w <- (cdr z) * (equal? "EMPTY" (2d-vector-ref cur-board-status (car w) (cdr w)))) : z <- (map (lambda (x) (car x)) (lc (lc y : y <- helper-list *(equal? x (car y))) : x <- (vector->list cur-pos) * (not (or (equal? x (cons -1 -1)) (equal? x (cons -2 -2))))))))) (define (possible-board-generators cur-board-status cur-pos lst-pos-moves) (map (lambda (x) (let ((trial-vec (make-vec cur-board-status)) (trial-vec1 (make-vec1 cur-pos))) (begin (2d-vector-set! trial-vec (caar x) (cdar x) "EMPTY") (2d-vector-set! trial-vec (caadr x) (cdadr x) (2d-vector-ref cur-board-status (caar x) (cdar x))) (set! trial-vec1 (list->vector (map (lambda (y) (if (equal? y (car x)) (cadr x) y)) (vector->list cur-pos)))) (list trial-vec trial-vec1 (checking-for-mill (cons (caadr x) (cdadr x)) (if (equal? (string-ref (2d-vector-ref cur-board-status (caar x) (cdar x)) 0) #\C) `computer `human) trial-vec) x)))) lst-pos-moves)) ;(trace possible-board-generators) (define (possible-board-removers cur-board-status cur-pos player) (filter (lambda (x) (not (equal? x `()))) (map (lambda (x) (if (or (equal? x (cons -2 -2)) (equal? x (cons -1 -1)) (checking-for-mill x player cur-board-status)) `() (let ((trial-vec (make-vec cur-board-status)) (trial-vec1 (make-vec1 cur-pos))) (begin (2d-vector-set! trial-vec (car x) (cdr x) "EMPTY") ;(display cur-board-status) ;(display trial-vec) ;(display x) ;(display cur-pos) (vector-set! trial-vec1 (string->number (string (string-ref (2d-vector-ref cur-board-status (car x) (cdr x)) 2))) (cons -2 -2)) ;(display trial-vec1) (list trial-vec trial-vec1 x))))) (vector->list cur-pos)))) ;(trace possible-board-removers) (define (best-move-generator) (define (helper1 cur-board-status cur-human-pos cur-comp-pos player i pred closed-morris mycount1) ;;no. of coins (cons white black) (define (no-of-coins) (cons (counter cur-human-pos 8 9) (counter cur-comp-pos 8 9))) (define (counter vec index ans) (if (= index 0) (if (equal? (cons -2 -2) (vector-ref vec 0)) (- ans 1) ans) (if (equal? (cons -2 -2) (vector-ref vec index)) (counter vec (- index 1) (- ans 1)) (counter vec (- index 1) ans)))) (if (= mycount1 9) (helper2 cur-board-status cur-human-pos cur-comp-pos player 3 pred closed-morris) (if (equal? pred #t) (if (equal? player `computer) (let ((lst (possible-board-removers1 cur-board-status cur-human-pos `human))) (if (equal? `() lst) (helper1 cur-board-status cur-human-pos cur-comp-pos `human (- i 1) #f closed-morris (+ mycount1 1)) (if (= i 2) (min3 (map (lambda (x) (cons (list-ref x 2) (helper1 (list-ref x 0) (list-ref x 1) cur-comp-pos `human (- i 1) #f #t (+ mycount1 1)))) lst)) (if (odd? i) (max2 (map (lambda (x) (helper1 (list-ref x 0) (list-ref x 1) cur-comp-pos `human (- i 1) #f closed-morris (+ mycount1 1))) lst)) (min2 (map (lambda (x) (helper1 (list-ref x 0) (list-ref x 1) cur-comp-pos `human (- i 1) #f closed-morris (+ mycount1 1))) lst)))))) (let ((lst (possible-board-removers1 cur-board-status cur-comp-pos `computer))) (if (equal? `() lst) (helper1 cur-board-status cur-human-pos cur-comp-pos `computer (- i 1) #f closed-morris mycount1) (if (= i 2) (min3 (map (lambda (x) (helper1 (list-ref x 0) cur-human-pos (list-ref x 1) `computer (- i 1) #f #t mycount1)) lst)) (if (odd? i) (max2 (map (lambda (x) (helper1 (list-ref x 0) cur-human-pos (list-ref x 1) `computer (- i 1) #f closed-morris mycount1)) lst)) (min2 (map (lambda (x) (helper1 (list-ref x 0) cur-human-pos (list-ref x 1) `computer (- i 1) #f closed-morris mycount1)) lst))))))) (if (equal? player `computer) (cond [(= i 2) (let* ((lst (possible-board-generators1 cur-board-status cur-comp-pos `computer mycount1)) (tempo (map (lambda (x) (if (list-ref x 2) (helper1 (list-ref x 0) cur-human-pos (list-ref x 1) `computer i #t #t mycount1) (helper1 (list-ref x 0) cur-human-pos (list-ref x 1) `human (- i 1) #f closed-morris (+ mycount1 1)))) lst)) (tempo1 (min4 tempo))) (if (number? (list-ref tempo tempo1)) (list-ref (list-ref lst tempo1) 3) (list (list-ref (list-ref lst tempo1) 3) (car (list-ref tempo tempo1)))))] [(= i 0) (if (equal? closed-morris #t) (pos-eval-func-phase1 cur-board-status cur-human-pos cur-comp-pos `human 1) (pos-eval-func-phase1 cur-board-status cur-human-pos cur-comp-pos `human 0))] [else (let ((lst (possible-board-generators1 cur-board-status cur-comp-pos `computer mycount1))) (if (or (equal? `() lst) (equal? 2 (cdr (no-of-coins)))) (if (odd? i) -1500 1500) (if (odd? i) (max2 (map (lambda (x) (if (list-ref x 2) (helper1 (list-ref x 0) cur-human-pos (list-ref x 1) `computer i #t closed-morris mycount1) (helper1 (list-ref x 0) cur-human-pos (list-ref x 1) `human (- i 1) #f closed-morris (+ mycount1 1)))) lst)) (min2 (map (lambda (x) (if (list-ref x 2) (helper1 (list-ref x 0) cur-human-pos (list-ref x 1) `computer i #t closed-morris mycount1) (helper1 (list-ref x 0) cur-human-pos (list-ref x 1) `human (- i 1) #f closed-morris (+ mycount1 1)))) lst)))))]) (cond [(= i 2) (let* ((lst (possible-board-generators1 cur-board-status cur-human-pos `human mycount1)) (tempo (map (lambda (x) (if (list-ref x 2) (helper1 (list-ref x 0) (list-ref x 1) cur-comp-pos `human i #t #t mycount1) (helper1 (list-ref x 0) (list-ref x 1) cur-comp-pos `computer (- i 1) #f closed-morris mycount1))) lst)) (tempo1 (min4 tempo))) (if (number? (list-ref tempo tempo1)) (list-ref lst tempo1) (cons (car (list-ref tempo tempo1)) (cdr (list-ref lst tempo1)))))] [(= i 0) (if (equal? closed-morris #t) (pos-eval-func-phase1 cur-board-status cur-human-pos cur-comp-pos `computer 1) (pos-eval-func-phase1 cur-board-status cur-human-pos cur-comp-pos `computer 0))] [else (let ((lst (possible-board-generators1 cur-board-status cur-human-pos `human mycount1))) (if (or (equal? `() lst) (equal? 2 (car (no-of-coins)))) (if (odd? i) -1500 1500) (if (odd? i) (max2 (map (lambda (x) (if (list-ref x 2) (helper1 (list-ref x 0) (list-ref x 1) cur-comp-pos `human i #t closed-morris mycount1) (helper1 (list-ref x 0) (list-ref x 1) cur-comp-pos `computer (- i 1) #f closed-morris mycount1))) lst)) (min2 (map (lambda (x) (if (list-ref x 2) (helper1 (list-ref x 0) (list-ref x 1) cur-comp-pos `human i #t closed-morris mycount1) (helper1 (list-ref x 0) (list-ref x 1) cur-comp-pos `computer (- i 1) #f closed-morris mycount1))) lst)))))]))))) (define (helper2 cur-board-status cur-human-pos cur-comp-pos player i pred closed-morris) ;;no. of coins (cons white black) (define (no-of-coins) (cons (counter cur-human-pos 8 9) (counter cur-comp-pos 8 9))) (define (counter vec index ans) (if (= index 0) (if (equal? (cons -2 -2) (vector-ref vec 0)) (- ans 1) ans) (if (equal? (cons -2 -2) (vector-ref vec index)) (counter vec (- index 1) (- ans 1)) (counter vec (- index 1) ans)))) (if (equal? pred #t) (if (equal? player `computer) (let ((lst (possible-board-removers cur-board-status cur-human-pos `human))) (if (equal? `() lst) (helper2 cur-board-status cur-human-pos cur-comp-pos `human (- i 1) #f closed-morris) (if (= i 4) (min3 (map (lambda (x) (cons (list-ref x 2) (helper2 (list-ref x 0) (list-ref x 1) cur-comp-pos `human (- i 1) #f #t))) lst)) (if (odd? i) (max2 (map (lambda (x) (helper2 (list-ref x 0) (list-ref x 1) cur-comp-pos `human (- i 1) #f closed-morris)) lst)) (min2 (map (lambda (x) (helper2 (list-ref x 0) (list-ref x 1) cur-comp-pos `human (- i 1) #f closed-morris)) lst)))))) (let ((lst (possible-board-removers cur-board-status cur-comp-pos `computer))) (if (equal? `() lst) (helper2 cur-board-status cur-human-pos cur-comp-pos `computer (- i 1) #f closed-morris) (if (= i 4) (min3 (map (lambda (x) (helper2 (list-ref x 0) cur-human-pos (list-ref x 1) `computer (- i 1) #f #t)) lst)) (if (odd? i) (max2 (map (lambda (x) (helper2 (list-ref x 0) cur-human-pos (list-ref x 1) `computer (- i 1) #f closed-morris)) lst)) (min2 (map (lambda (x) (helper2 (list-ref x 0) cur-human-pos (list-ref x 1) `computer (- i 1) #f closed-morris)) lst))))))) (if (equal? player `computer) (cond [(= i 4) (let* ((lst (possible-board-generators cur-board-status cur-comp-pos (possible-moves-generator cur-board-status cur-comp-pos))) (tempo (map (lambda (x) (if (list-ref x 2) (helper2 (list-ref x 0) cur-human-pos (list-ref x 1) `computer i #t #t) (helper2 (list-ref x 0) cur-human-pos (list-ref x 1) `human (- i 1) #f closed-morris))) lst)) (tempo1 (min4 tempo))) (if (number? (list-ref tempo tempo1)) (list-ref (list-ref lst tempo1) 3) (list (list-ref (list-ref lst tempo1) 3) (car (list-ref tempo tempo1)))))] [(= i 0) (if (equal? closed-morris #t) (pos-eval-func-phase2 cur-board-status cur-human-pos cur-comp-pos `human 1) (pos-eval-func-phase2 cur-board-status cur-human-pos cur-comp-pos `human 0))] [else (let ((lst (possible-board-generators cur-board-status cur-comp-pos (possible-moves-generator cur-board-status cur-comp-pos)))) (if (or (equal? `() lst) (equal? 2 (cdr (no-of-coins)))) (if (odd? i) -1500 1500) (if (odd? i) (max2 (map (lambda (x) (if (list-ref x 2) (helper2 (list-ref x 0) cur-human-pos (list-ref x 1) `computer i #t closed-morris) (helper2 (list-ref x 0) cur-human-pos (list-ref x 1) `human (- i 1) #f closed-morris))) lst)) (min2 (map (lambda (x) (if (list-ref x 2) (helper2 (list-ref x 0) cur-human-pos (list-ref x 1) `computer i #t closed-morris) (helper2 (list-ref x 0) cur-human-pos (list-ref x 1) `human (- i 1) #f closed-morris))) lst)))))]) (cond [(= i 4) (let* ((lst (possible-board-generators cur-board-status cur-human-pos (possible-moves-generator cur-board-status cur-human-pos))) (tempo (map (lambda (x) (if (list-ref x 2) (helper2 (list-ref x 0) (list-ref x 1) cur-comp-pos `human i #t closed-morris) (helper2 (list-ref x 0) (list-ref x 1) cur-comp-pos `computer (- i 1) #f closed-morris))) lst)) (tempo1 (min4 tempo))) (if (number? (list-ref tempo tempo1)) (list-ref lst tempo1) (cons (car (list-ref tempo tempo1)) (cdr (list-ref lst tempo1)))))] [(= i 0) (if (equal? closed-morris #t) (pos-eval-func-phase2 cur-board-status cur-human-pos cur-comp-pos `computer 1) (pos-eval-func-phase2 cur-board-status cur-human-pos cur-comp-pos `computer 0))] [else (let ((lst (possible-board-generators cur-board-status cur-human-pos (possible-moves-generator cur-board-status cur-human-pos)))) (if (or (equal? `() lst) (equal? 2 (car (no-of-coins)))) (if (odd? i) -1500 1500) (if (odd? i) (max2 (map (lambda (x) (if (list-ref x 2) (helper2 (list-ref x 0) (list-ref x 1) cur-comp-pos `human i #t closed-morris) (helper2 (list-ref x 0) (list-ref x 1) cur-comp-pos `computer (- i 1) #f closed-morris))) lst)) (min2 (map (lambda (x) (if (list-ref x 2) (helper2 (list-ref x 0) (list-ref x 1) cur-comp-pos `human i #t closed-morris) (helper2 (list-ref x 0) (list-ref x 1) cur-comp-pos `computer (- i 1) #f closed-morris))) lst)))))])))) (if (< mycount 9) ;(trace helper1) (helper1 board-status human-white-pos computer-black-pos `computer 2 #f #f mycount) ;(trace helper2) (helper2 board-status human-white-pos computer-black-pos `computer 4 #f #f)) ) (define (max1 lst) (let ((temp (max2 lst))) (max-helper temp lst 0))) (define (min1 lst) (let ((temp (min2 lst))) (max-helper temp lst 0))) (define (max-helper mem lst index) (if (= mem (car lst)) index (max-helper mem (cdr lst) (+ index 1)))) (define (max2 lst) (if (equal? `() (cdr lst)) (car lst) (max (car lst) (max2 (cdr lst))))) (define (min2 lst) (if (equal? `() (cdr lst)) (car lst) (min (car lst) (min2 (cdr lst))))) (define (min3 lst) (let ((temp (map (lambda (x) (cdr x)) lst))) (list-ref lst (min1 temp)))) (define (min4 lst) (let ((temp (map (lambda (x) (if (number? x) x (cdr x))) lst))) (min1 temp))) ;(trace pos-eval-func-phase2) ;(trace max1) ;(trace max2) ; (define (you-lost) ; ; (define windw (open-viewport "LOSER!!" 400 594)) ; ; ((draw-pixmap windw) "lose1.png" (make-posn 0 0)) ; ((draw-pixmap windw) "click.jpg" (make-posn 400 0)) ; ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;< >;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;<END OF BEST MOVE GENERATOR>;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (begin (open-graphics) (define windw (open-viewport "Nine Men's Morris" 600 600)) ((draw-pixmap windw) "morris.gif" (make-posn 0 0)) (outhelper board-status 0 0) (placing-position-checking (main2 board-status 1))) ) (define (you-lost) (open-graphics) (define windw (open-viewport "LOSER!!" 400 768)) ((draw-pixmap windw) "lose-2.png" (make-posn 0 0)) ((draw-pixmap windw) "click.png" (make-posn 0 400)) (define (helper) (define mouse-click-pos 0) (define new-mouse-click-pos 0) (begin (set! mouse-click-pos (mouse-click-posn (get-mouse-click windw))) (if (> (posn-y mouse-click-pos) 400) (begin ((draw-pixmap windw) "lose-1.png" (make-posn 0 0)) ((draw-pixmap windw) "exit2.jpg" (make-posn 0 400)) (set! new-mouse-click-pos (mouse-click-posn (get-mouse-click windw))) (if (> (posn-y mouse-click-pos) 400) (begin (close-viewport windw) (close-graphics) ) (helper))) (you-lost)))) (helper)) (define (you-win) (open-graphics) (define windw (open-viewport "WINNER!" 400 768)) ((draw-pixmap windw) "you-win.jpg" (make-posn 0 0)) ((draw-pixmap windw) "click2.jpg" (make-posn 0 400)) (define (helper) (define mouse-click-pos 0) (define new-mouse-click-pos 0) (begin (set! mouse-click-pos (mouse-click-posn (get-mouse-click windw))) (if (> (posn-y mouse-click-pos) 400) (begin ((draw-pixmap windw) "i-will-be-back.jpg" (make-posn 0 0)) ((draw-pixmap windw) "hasta.jpg" (make-posn 0 300)) (set! new-mouse-click-pos (mouse-click-posn (get-mouse-click windw))) (if (> (posn-y mouse-click-pos) 300) (begin (close-viewport windw) (close-graphics) ) (helper))) (you-win)))) (helper))
true
2928903e3713f337c0cfc7f8d0d7812d7da107cc
95bfc30172b907840a072b8ca62ec69200c9e982
/chapter-4/exercise-4.14.rkt
82682b2cc1b84be8f93ac463af264ecb7d4c61f5
[]
no_license
if1live/sicp-solution
68643f9bb291d4e35dc5683d47d06b7c7220abb6
a03d2b080a7091c071ff750bbf65cbb6815b93e5
refs/heads/master
2020-04-15T05:16:48.597964
2019-02-21T15:45:43
2019-02-21T15:45:43
164,415,380
0
0
null
null
null
null
UTF-8
Racket
false
false
250
rkt
exercise-4.14.rkt
#!/usr/bin/env racket #lang racket (require "./lib-evaluator.rkt") ;; copy-and-paste (define (map proc items) (if (null? items) '() (cons (proc (car items)) (map proc (cdr items))))) (map (lambda (x) (+ x 1)) '(1 2 3))
false
a5a9b89ff71a6a899887148608f08e9b418d4ec6
856a2ad1deb12d2871a8e4e4bc106d354ba1a4db
/chido-parse/private/binding-sequence.rkt
3d8dd2d431405e12645d38d354b3cff435f1c220
[ "Apache-2.0", "MIT" ]
permissive
willghatch/racket-chido-parse
d3b00a2281c9261b2c27275ac53c9cdef274639d
820b2e7e0b47259ca8f30a77fc19fe9eab209ac0
refs/heads/master
2023-03-17T20:56:31.082568
2023-02-24T17:47:52
2023-02-24T17:47:52
176,032,247
9
0
null
null
null
null
UTF-8
Racket
false
false
18,232
rkt
binding-sequence.rkt
#lang racket/base (provide binding-sequence (for-syntax binding-sequence-elem) ) (require "core-use.rkt" "procedural-combinators.rkt" racket/match racket/stxparam (for-syntax racket/base syntax/parse )) (module+ test (require rackunit "test-util-3.rkt" )) (define (do-ignore-and-splice derivations ignores splices) ;; Helper function for binding-sequence (define (result->list r) (cond [(and (syntax? r) (syntax->list r))] [(list? r) r] [else (error 'binding-sequence "result to be spliced is not a list: ~v" r)])) (define (do-splices result n) (if (< n 2) (result->list result) (apply append (map (λ (x) (do-splices x (sub1 n))) (result->list result))))) (cond [(null? derivations) '()] [(car ignores) (do-ignore-and-splice (cdr derivations) (cdr ignores) (cdr splices))] [(and (car splices) (< 0 (car splices))) (let* ([r (parse-derivation-result (car derivations))] [this-list (do-splices r (car splices))]) (append this-list (do-ignore-and-splice (cdr derivations) (cdr ignores) (cdr splices))))] [else (cons (parse-derivation-result (car derivations)) (do-ignore-and-splice (cdr derivations) (cdr ignores) (cdr splices)))])) (define (do-full-sequence-splice val n) (match n [#f val] [0 val] [(and (? number?) (? (λ (x) (< 0 x)))) (match val [(list x) (do-full-sequence-splice x (sub1 n))] [(? syntax?) (do-full-sequence-splice (syntax-e val) n)] [else (error 'binding-sequence "can't do full-sequence splice of something that is not a list of a single element: ~v" val)])])) (begin-for-syntax (define-syntax-class binding-sequence-elem (pattern (~and whole-pattern [(~datum :) (~or (~once parser:expr) (~optional (~seq #:bind name:id)) (~optional (~seq #:ignore ignore-given:expr)) (~optional (~seq #:splice splice-given:expr)) (~optional (~seq #:repeat-min repeat-min-given:expr)) (~optional (~seq #:repeat-max repeat-max-given:expr)) (~optional (~seq #:repeat-greedy? repeat-greedy-given:expr)) ) ...]) #:attr ignore #'(~? ignore-given #f) #:attr splice #'(~? splice-given #f) #:attr repeat-min #'(~? repeat-min-given #f) #:attr repeat-max #'(~? repeat-max-given #f) #:attr repeat-greedy #'(~? repeat-greedy-given #f) ) ;; TODO - I want to make greedy-repeat default to #t, but doing so breaks stuff. I should find out why, and maybe explicitly write-in non-greedy as necessary for things that actually require non-greedy repetition, and otherwise fix any bugs behind it. (pattern parser:expr #:attr name #f #:attr ignore #'#f #:attr splice #'#f #:attr repeat-min #'#f #:attr repeat-max #'#f #:attr repeat-greedy #'#f ))) (define-syntax (hidden-between-propagate-key stx) (raise-syntax-error 'hidden-between-propagate-key "only exists for use as a hidden keyword" stx)) (define-syntax-parameter binding-subsequence-layout #f) (define-syntax (binding-sequence-helper stx) (syntax-parse stx [(_ port derive make-result/bare make-result/stx splice start-point between-propagate ([done-int-names ...] [done-ignores ...] [done-splices ...]) [internal-name:id part:binding-sequence-elem] rest ...) #'(let* ([repeat-min* (~? part.repeat-min #f)] [repeat-max* (~? part.repeat-max #f)] [repeat-greedy? (~? part.repeat-greedy #f)] [repeat (or repeat-min* repeat-max*)] [repeat-min (match repeat-min* [#f 0] [#t 0] [else repeat-min*])] [repeat-max (match repeat-max* [#f +inf.0] [#t +inf.0] [else repeat-max*])] [parser/no-repeat ;; TODO - right now this is making ALL subsequences inherit the between argument. I don't like it. I should have some specific form recognized by binding sequences to signify a subsequence that inherits. (syntax-parameterize ([binding-subsequence-layout #'between-propagate]) part.parser)] [parser/repeat (if repeat (repetition parser/no-repeat #:min repeat-min #:max repeat-max #:between between-propagate #:greedy? repeat-greedy? #:result/bare (not (not make-result/bare)) #:result/stx (not (not make-result/stx))) parser/no-repeat)]) (for/parse ([internal-name (parse* port parser/repeat #:start start-point)]) (~? (define part.name internal-name) (void)) (define current-ignore part.ignore) (define current-splice (or part.splice 0)) (when (not (integer? current-splice)) (error 'binding-sequence "splice argument is not an integer: ~v" current-splice)) (binding-sequence-helper port derive make-result/bare make-result/stx splice internal-name between-propagate ([done-int-names ... internal-name] [done-ignores ... current-ignore] [done-splices ... current-splice]) rest ...)))] [(_ port derive make-result/bare make-result/stx splice start-point between-propagate ([done-int-names ...] [done-ignores ...] [done-splices ...])) #'(let* ([derive-arg derive] [make-result/bare-arg make-result/bare] [make-result/stx-arg make-result/stx] [ignored-spliced-thunk (λ () (do-ignore-and-splice (list done-int-names ...) (list done-ignores ...) (list done-splices ...)))] [make-result-wrap (λ (make-result-func stx?) (λ derivations (make-parse-derivation (λ (src line col pos span ds) (let* ([pre-stx+splice (apply make-result-func (ignored-spliced-thunk))] [pre-stx (do-full-sequence-splice pre-stx+splice splice)]) (if stx? (datum->syntax #f pre-stx (list src line col pos span)) pre-stx))) #:derivations derivations)))] [do-derive (cond [derive-arg derive-arg] [(eq? #t make-result/bare-arg) (make-result-wrap list #f)] [make-result/bare-arg (make-result-wrap make-result/bare-arg #f)] [(eq? #t make-result/stx-arg) (make-result-wrap list #t)] [make-result/stx-arg (make-result-wrap make-result/stx-arg #t)] [else (make-result-wrap list #t)])]) (apply do-derive (list done-int-names ...)))])) (define-syntax (binding-sequence stx) (syntax-parse stx [(_ (~optional (~seq (~literal hidden-between-propagate-key) between-propagate:expr)) part:binding-sequence-elem ...+ (~or (~optional (~seq #:name name:expr)) (~optional (~seq #:derive derive-arg:expr)) (~optional (~seq #:result/bare make-result-bare-arg:expr)) (~optional (~seq #:result/stx make-result-stx-arg:expr)) (~optional (~seq #:splice splice-arg:expr)) (~optional (~seq #:inherit-between inherit-between:boolean)) (~optional (~seq #:between between-arg:expr))) ...) (define (add-betweens between-parser-stx partlist) (if (null? partlist) '() (cons #`[: #,between-parser-stx #:ignore #t] (cons (car partlist) (add-betweens between-parser-stx (cdr partlist)))))) (define subsequence-layout (syntax-parse #'(~? inherit-between #f) [#f #'#f] [#t (or (syntax-parameter-value #'binding-subsequence-layout) #'#f)])) (define/syntax-parse between-arg/use (or (attribute between-arg) subsequence-layout)) (define (basename-maybe pathstr) (if (path-string? pathstr) (path->string (car (reverse (explode-path pathstr)))) pathstr)) (define/syntax-parse name/infer #`(format "binding-sequence-at_~a" '#,(format "~a:~a:~a:~a" (basename-maybe (syntax-source stx)) (syntax-line stx) (syntax-column stx) (syntax-position stx)))) (define/syntax-parse name/use #'(~? name name/infer)) (if (syntax-parse #'between-arg/use [#f #f] [else #t]) #`(let ([between-arg* between-arg/use]) #,(with-syntax ([(parts-with-betweens ...) (cons (car (syntax->list #'(part ...))) (add-betweens #'between-arg* (cdr (syntax->list #'(part ...)))))]) ;; Allowing syntax-time #f or an expr that must evaluate to ;; a parser is a terrible interface. So we will allow a ;; second chance to evaluate to false and get a non-between ;; sequence. #'(syntax-parameterize ([binding-subsequence-layout #f]) (if between-arg* (binding-sequence hidden-between-propagate-key between-arg* parts-with-betweens ... #:name name/use #:derive (~? derive-arg #f) #:result/bare (~? make-result-bare-arg #f) #:result/stx (~? make-result-stx-arg #f)) (binding-sequence part ... #:name name/use #:derive (~? derive-arg #f) #:result/bare (~? make-result-bare-arg #f) #:result/stx (~? make-result-stx-arg #f)))))) (with-syntax ([(internal-name ...) (generate-temporaries #'(part ...))] [sequence-length (datum->syntax #'here (length (syntax->list #'(part ...))))]) #'(let ([between-propagate/use (~? between-propagate #f)] [make-result/bare (~? make-result-bare-arg #f)] [make-result/stx (~? make-result-stx-arg #f)] [splice (~? splice-arg #f)]) (proc-parser #:name name/use ;; TODO - other optional args (λ (port) (binding-sequence-helper port (~? derive-arg #f) make-result/bare make-result/stx splice #f between-propagate/use ([] [] []) [internal-name part] ...))))))])) (module+ test (check-equal? (p*/r "ab" (binding-sequence "a" "b" #:result/bare #t)) '(("a" "b"))) (check-equal? (p*/r "ab" (binding-sequence "a" "b" #:result/bare #t)) '(("a" "b"))) (check se? (p*/r "ab" (binding-sequence "a" "b" #:result/stx list)) (list (datum->syntax #f '("a" "b") (list 'string 1 0 1 2)))) (check se? (p*/r "ab" (binding-sequence "a" "b" #:result/stx #t)) (list (datum->syntax #f '("a" "b") (list 'string 1 0 1 2)))) (check-equal? (p*/r "ab" (binding-sequence [: #:bind a1 "a"] "b" #:result/bare #t)) '(("a" "b"))) (check-equal? (p*/r "ab" (binding-sequence [: #:ignore #t "a"] "b" #:result/bare #t)) '(("b"))) (check-equal? (p*/r "a_b" (binding-sequence [: #:ignore #t "a"] "b" #:between "_" #:result/bare #t)) '(("b"))) (check-equal? (p*/r "aaab" (binding-sequence [: #:splice 1 (kleene-star "a" #:result/bare #t)] "b" #:result/bare #t)) '(("a" "a" "a" "b"))) (check-equal? (p*/r "aaa_b" (binding-sequence [: #:splice 1 (kleene-star "a" #:result/bare #t)] "b" #:between "_" #:result/bare #t)) '(("a" "a" "a" "b"))) (check-equal? (p*/r "a-a-a_b" (binding-sequence [: #:splice 1 (kleene-star "a" #:between "-" #:result/bare #t #:greedy? #t)] "b" #:between "_" #:result/bare #t)) '(("a" "a" "a" "b"))) (define bseq-a-not-a-parser (binding-sequence [: #:bind a1 "a"] (parse-filter (proc-parser (λ (port) (make-parse-derivation (read-string 1 port) #:end (port->pos port)))) (λ (port derivation) (not (equal? (parse-derivation-result a1) (parse-derivation-result derivation))))) #:result/bare #t)) (check-equal? (p*/r "ab" bseq-a-not-a-parser) '(("a" "b"))) (check-equal? (p*/r "aa" bseq-a-not-a-parser) '()) ;; check binding-sequence repeat (check-equal? (p*/r "a_a_a_b" (binding-sequence [: #:splice 1 #:repeat-min 0 "a"] "b" #:between "_" #:result/bare #t)) '(("a" "a" "a" "b"))) ;; check binding-sequence subsequnce inheritance of #:between (check-equal? (p*/r "a_1_2_3_7-8-9_b" (binding-sequence "a" [: #:splice 1 (binding-sequence "1" "2" "3" #:inherit-between #t #:result/bare #t)] [: #:splice 1 (binding-sequence "7" "8" "9" #:inherit-between #t #:between "-" #:result/bare #t)] "b" #:between "_" #:result/bare #t)) '(("a" "1" "2" "3" "7" "8" "9" "b"))) (check-equal? (p*/r "a_1_2_3_1_2_3_b" (binding-sequence "a" [: #:splice 2 #:repeat-min 0 (binding-sequence "1" "2" "3" #:inherit-between #t #:result/bare #t)] "b" #:between "_" #:result/bare #t)) '(("a" "1" "2" "3" "1" "2" "3" "b"))) )
true
de43871c520046a8f053a1eec189ffc874a663b7
82c76c05fc8ca096f2744a7423d411561b25d9bd
/typed-racket-test/fail/plambda-dup-tvar.rkt
9cf2889d1b3e4dd70d1615b1116b37352a0a1cae
[ "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
199
rkt
plambda-dup-tvar.rkt
#; (exn-pred exn:fail:syntax?) #lang typed/racket ;; don't allow duplicate type variable names (plambda: (a a a) ([x : a]) x) (popt-lambda: (a a a) ([x : a]) x) (pcase-lambda: (a a a) ([x : a]) x)
false
366935cdc42649d4805e717948d306d7417266d1
3922167fbcc0655bb6fc8bb4886bf0e65d6a155a
/benchmark/configs.rkt
317e22529350297129bb5607f5dc1c1b3049f8f8
[ "MIT" ]
permissive
Gradual-Typing/Grift
d380b334aa53896d39c60c2e3008bfab73a55590
5fa76f837a0d6189332343d7aa899892b3c49583
refs/heads/master
2021-11-23T07:25:24.221457
2021-11-04T14:35:53
2021-11-04T14:35:53
27,832,586
70
12
MIT
2021-09-30T14:03:22
2014-12-10T18:06:44
C
UTF-8
Racket
false
false
10,758
rkt
configs.rkt
#| Author: Deyaaeldeen Almahallawi ([email protected]) Description: Facilitates a user-friendly interface for Grift configurations. It is used mainly by the benchmarking scripts. |# #lang racket (require racket/runtime-path) (provide configs config->name name-sep name-end (struct-out custom-feature ) *custom-feature* parameterize-*custom-feature*/string) (define configs (make-hash ;; Index Cast-Mechinism ;; Ref-Mechinism ;; Cast-Specialization ;; Hybrid/Pure-Cast Runtime '((1 |Type-Based Casts| Proxied Unspecialized Eager UniformClosure) (2 Coercions Proxied Unspecialized Eager UniformClosure) (3 Hyper-Coercions Proxied Unspecialized Eager UniformClosure) (4 |Type-Based Casts| Monotonic Unspecialized Eager UniformClosure) (5 Coercions Monotonic Unspecialized Eager UniformClosure) (6 Hyper-Coercions Monotonic Unspecialized Eager UniformClosure) (7 |Type-Based Casts| Proxied Specialized Eager UniformClosure) (8 Coercions Proxied Specialized Eager UniformClosure) (9 Hyper-Coercions Proxied Specialized Eager UniformClosure) (10 |Type-Based Casts| Monotonic Specialized Eager UniformClosure) (11 Coercions Monotonic Specialized Eager UniformClosure) (12 Hyper-Coercions Monotonic Specialized Eager UniformClosure) (13 Coercions Proxied Unspecialized Lazy UniformClosure) (14 Hyper-Coercions Proxied Unspecialized Lazy UniformClosure) (15 Coercions Monotonic Unspecialized Lazy UniformClosure) (16 Hyper-Coercions Monotonic Unspecialized Lazy UniformClosure) (17 Coercions Proxied Specialized Lazy UniformClosure) (18 Hyper-Coercions Proxied Specialized Lazy UniformClosure) (19 Coercions Monotonic Specialized Lazy UniformClosure) (20 Hyper-Coercions Monotonic Specialized Lazy UniformClosure) (21 |Type-Based Casts| Proxied Unspecialized Eager NoUniformClosure) (22 Coercions Proxied Unspecialized Eager NoUniformClosure) (23 Hyper-Coercions Proxied Unspecialized Eager NoUniformClosure) (24 |Type-Based Casts| Monotonic Unspecialized Eager NoUniformClosure) (25 Coercions Monotonic Unspecialized Eager NoUniformClosure) (26 Hyper-Coercions Monotonic Unspecialized Eager NoUniformClosure) (27 |Type-Based Casts| Proxied Specialized Eager NoUniformClosure) (28 Coercions Proxied Specialized Eager NoUniformClosure) (29 Hyper-Coercions Proxied Specialized Eager NoUniformClosure) (30 |Type-Based Casts| Monotonic Specialized Eager NoUniformClosure) (31 Coercions Monotonic Specialized Eager NoUniformClosure) (32 Hyper-Coercions Monotonic Specialized Eager NoUniformClosure) (33 Coercions Proxied Unspecialized Lazy NoUniformClosure) (34 Hyper-Coercions Proxied Unspecialized Lazy NoUniformClosure) (35 Coercions Monotonic Unspecialized Lazy NoUniformClosure) (36 Hyper-Coercions Monotonic Unspecialized Lazy NoUniformClosure) (37 Coercions Proxied Specialized Lazy NoUniformClosure) (38 Hyper-Coercions Proxied Specialized Lazy NoUniformClosure) (39 Coercions Monotonic Specialized Lazy NoUniformClosure) (40 Hyper-Coercions Monotonic Specialized Lazy NoUniformClosure)))) ;; Why are we writing this data structure to ;; a file. (define-runtime-path config-file "configs.dat") ;; Read the previous cofiguration state (define (read-configs!) (set! configs (call-with-input-file config-file (lambda (in) (read in))))) ;; Write some conguration state (define (write-configs!) (call-with-output-file config-file #:exists 'replace (lambda (in) (write configs in)))) (define name-sep (make-parameter " ")) (define name-end (make-parameter "")) ;; Defines ordering for elements of the configurations ;; names to be displayed (define (name-element<? e1 e2) (define classes '((Specialized Unspecialized) (Eager Lazy) (Proxied Monotonic) (Hyper-Coercions Coercions |Type-Based Casts|) (UniformClosure NoUniformClosure))) (define (find-class-rank e) (let loop ([cs classes]) (if (set-member? (car cs) e) 0 (+ (loop (cdr cs)) 1)))) (< (find-class-rank e1) (find-class-rank e2))) ;; Given a set of configuration options returns the stylized string ;; representation of that name. (define (set->name s [sep (name-sep)] [end (name-end)]) (list->name (set->list s) sep end)) (define (list->name l [sep (name-sep)] [end (name-end)]) (define sls (sort l name-element<?)) (define ss (map symbol->string sls)) (string-join ss sep #:after-last end)) (struct custom-feature (neg-name neg-config pos-name pos-config)) (define *custom-feature* (make-parameter #f)) (define (string-name-sep-spaces x) (string-normalize-spaces x #px"\\s+" (name-sep))) (define (custom-feature->common-name common-name cf) (string-join `(,(string-name-sep-spaces (custom-feature-neg-name cf)) "v" ,(string-name-sep-spaces (custom-feature-pos-name cf)) ,common-name) (name-sep) #:after-last (name-end))) (define (parameterize-*custom-feature*/string x) (match (read (open-input-string x)) [(list-no-order (list '+ (? symbol? pos-name) (and pos-config-alist (list (list (? symbol?) _) ...))) (list '- (? symbol? neg-name) (and neg-config-alist (list (list (? symbol?) _) ...)))) (define (list->pair x) (cons (first x) (second x))) (define cf (custom-feature (symbol->string neg-name) (map list->pair neg-config-alist) (symbol->string pos-name) (map list->pair pos-config-alist))) (*custom-feature* cf)] [x (raise-argument-error 'parameterize-*custom-feature*/string "positive and negative configuration: ((+ name ((grift-param value) ...)) (- name ((grift-param value) ...))" x)])) (define (config->name c [sep (name-sep)] [end (name-end)]) (cond [(*custom-feature*) => (if (< c 0) custom-feature-neg-name custom-feature-pos-name)] [else (list->name (hash-ref configs c) sep end)])) (define (common-name . rest) (define (s->n x) (cond [(exact-integer? x) x] [(and (string? x) (string->number x)) => values] [else (raise-argument-error 'common-name "expected exact integer string or numbers" x)])) (define ns (map s->n rest)) (define cs (map (lambda (n) (hash-ref configs (abs n))) ns)) (define ss (map list->set cs)) (define common (apply set-intersect ss)) (define name (set->name common)) (cond [(*custom-feature*) => (λ (x) (display (custom-feature->common-name name x)))] [else (display name)])) (module+ main (define (default-main) (void)) (define main-fn (make-parameter default-main)) (command-line #:once-each ["--custom-feature" config "todo" (parameterize-*custom-feature*/string config)] [("--name-sep") sep "Set the seperator for name generation" (name-sep sep)] [("--name-end") end "Set the ending for name generation" (name-end end)] #:once-any [("--all" "-a") "Generate configuration strings for all configurations supported by Grift" (main-fn (lambda () (display (string-join (for/list ([i (in-range 1 (+ 1 (hash-count configs)))]) (set->name (list->set (hash-ref configs i)))) ","))))] [("--generate-configs-file" "-g") "Generate the configurations file" (write-configs!)] [("--update-configs" "-u") "Read configuration from the configurations file" (read-configs!)] [("--names" "-n") "Generate configuration names from indicies" (main-fn (case-lambda ;; The singleton case does not work in the general case because ;; subtracting the set representing the configuration from itself yields ;; the empty set. [(x) (config->name (string->number x) "_")] [rest (define ns (map string->number rest)) (define names (cond [(*custom-feature*) => (lambda (x) (unless (and (= (length ns) 2) (= (abs (first ns)) (abs (second ns)))) (error '--names "invalid input with: expects n -n or -n n: given ~a" rest)) (map (λ (x) (string-name-sep-spaces (config->name x))) ns))] [else (define cs (map (lambda (n) (hash-ref configs n)) ns)) (define ss (map list->set cs)) (define common (apply set-intersect ss)) (define ds (map (lambda (s) (set-subtract s common)) ss)) (map set->name ds)])) (display (string-join names ","))]))] [("--common") "Generate shared features of a set of configurations" (main-fn common-name)] [("--indices" "-i") "Generate configuration indices" (display (string-join (map number->string (range 1 (+ 1 (hash-count configs)))) " "))] [("--compare" "-c") c1 c2 "compare and contrast two configurations" (define n1 (string->number c1)) (define n2 (string->number c2)) (cond [(and n1 n2) (cond [(*custom-feature*) (printf "~a,~a,~a" (config->name n1) (config->name n2) (common-name n1 n2))] [else (define cs configs) (define s1 (list->set (hash-ref cs n1))) (define s2 (list->set (hash-ref cs n2))) (define (f s1 s2) (define s (set-subtract s1 s2)) (cond [(= (set-count s) 1) (symbol->string (set-first s))] [(and (set-member? s '|Type-Based Casts|) (set-member? s 'Strict)) "Strict Type-Based Casts"] [(and (set-member? s 'Coercions) (set-member? s 'Lazy)) "Lazy Coercions"] [else (string-join (map symbol->string (set->list s)) " ")])) (define-values (c1 c2) (let ([c1 (f s1 s2)] [c2 (f s2 s1)]) (cond [(and (equal? "Eager Type-Based Casts" c1) (equal? "Lazy Coercions" c2)) (values "Type-Based Casts" "Coercions")] [(and (equal? "Eager Type-Based Casts" c2) (equal? "Lazy Coercions" c1)) (values "Coercions" "Type-Based Casts")] [else (values c1 c2)]))) (define intersection (string-join (map symbol->string (set->list (set-intersect s1 s2))) "_")) (printf "~a,~a,~a" c1 c2 intersection)])] [else (error 'config_str: "could not parse ~a and ~a as numbers" c1 c2)])] #:args all (apply (main-fn) all)))
false
350c0eef1981d55fba4049f78a744b11d67c2795
0de43c205e56b52e1ed9149571f16de8fd1b8239
/mzscheme-lib/setup/info.rkt
6f09a01e9a0efc67d412ee2d582b548a37b718fa
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "Apache-2.0" ]
permissive
racket/mzscheme
373dd38f97b639b2b86dea77be1ce8baaf03ea47
64d63a78795b4bf3f9ac451ff727ae45183d4cb5
refs/heads/master
2023-08-27T17:33:43.994444
2022-07-08T19:17:00
2022-07-14T14:02:15
27,413,270
14
3
NOASSERTION
2022-07-08T19:18:02
2014-12-02T03:29:52
Racket
UTF-8
Racket
false
false
152
rkt
info.rkt
#lang info (define mzscheme-launcher-libraries '("main.rkt")) (define mzscheme-launcher-names '("Setup PLT")) (define copy-man-pages '("setup-plt.1"))
false
bb12f88d19a4de2e3e7614583e3f61813233297d
ee41ac08f0dc02c720636b239feb9f74868b1367
/redex/cos/test/harness.rkt
cf9ce2bdcd49e5980e80bf415a41717765f657ea
[ "MIT" ]
permissive
florence/esterel-calculus
80535dd393ac39abd474b6057e2d1bbc7ea5a3d9
b4ca80479150933d9c21f2fd463da341cfb4c5f9
refs/heads/master
2022-09-05T00:45:30.664730
2022-06-28T00:11:01
2022-06-28T00:11:01
63,906,736
3
1
null
null
null
null
UTF-8
Racket
false
false
13,600
rkt
harness.rkt
#lang racket (require redex/reduction-semantics racket/random esterel-calculus/redex/cos/model) (provide (all-defined-out)) (require rackunit (prefix-in rackunit: rackunit)) (define (do t [E `()] [data `()]) (judgment-holds (non-det-> ,t ,data ,E pdotdot data_* e k) (pdotdot e k data_*))) (define (do/det t [E `()] [data `()]) (judgment-holds (det-> ,t ,data ,E pdotdot data_* e k) (pdotdot e k data_*))) (define-syntax-rule (do* p data) (judgment-holds (non-det-> p data () pdotdot_* data_* e k) (pdotdot_* data_* e k))) (define-extended-language esterel-check esterel-eval (p-check nothing pause (seq p-check p-check) (par p-check p-check) (trap p-check) (exit nat) (signal S p-check) (suspend p-check S) (present S p-check p-check) (emit S) (shared s := call/check p-check+sset) (var v := call/check p-check+vset)) (p-check+sset p-check (seq p-check+sset p-check+sset) (par p-check+sset p-check+sset) (trap p-check+sset) (exit nat) (signal S p-check+sset) (suspend p-check+sset S) (present S p-check+sset p-check+sset) (var v := call/check p-check+sset+vset) (<= s call/check)) (p-check+vset p-check (seq p-check+vset p-check+vset) (par p-check+vset p-check) (trap p-check+vset) (exit nat) (signal S p-check+vset) (suspend p-check+vset S) (present S p-check+vset p-check+vset) (shared s := call/check p-check+sset+vset) (:= v call/check)) (p-check+sset+vset p-check+vset p-check+sset) (phat-check (hat pause) ;; loops only present here to force loops to be non-instantanious (loop phat-check) (suspend phat-check S) (seq phat-check p-check) (seq p-check phat-check) ;; force a phat for the sake of loop safety (present S phat-check phat-check) (par phat-check phat-check) (trap phat-check) (signal S phat-check) (shared s := call/check phat-check+sset)) (phat-check+sset phat-check (loop phat-check+sset) (suspend phat-check+sset S) (seq phat-check+sset p-check+sset) (seq p-check+sset phat-check+sset) ;; force a phat for the sake of loop safety (present S phat-check+sset phat-check+sset) (par phat-check+sset phat-check+sset) (trap phat-check+sset) (signal S phat-check+sset)) (pbar-check p-check phat-check) (NL () (nat NL)) (call/check (+ call/check call/check ) (+ call/check ) (+) v s natural)) (define-judgment-form esterel-eval ;; constructive ->>, with testing checks #:mode (cc->> I I O O O) #:contract (cc->> M E M (S ...) k) [(where (((machine qbar_r data_r*) (S_r ...) k_r) ...) ,(judgment-holds (c->> (machine pbar data) E (machine qbar data_*) (S ...) k) ((machine qbar data_*) (S ...) k))) (where (M_* (S_* ...)) (eval (machine pbar data) E)) (where (((machine qbar data_*) (S ...) k) any_2 ...) (((machine qbar_r data_r*) (S_r ...) k_r) ...)) (where #t ,(andmap (curry equal? `k) `(k_r ...))) (where #t ,(andmap (lambda (M) (alpha-equivalent? esterel-eval `(machine qbar data_*) M)) `(M_* (machine qbar_r data_r*) ...))) ;(side-condition ,(displayln `(S_* ... S ... (free-emitted-signals pbar)))) ;(side-condition ,(displayln `((∈ S (free-emitted-signals pbar)) ...))) (where (#t ...) ((∈ S_* (free-emitted-signals pbar)) ... (∈ S (free-emitted-signals pbar)) ...)) (where E_2 (Can_S pbar E)) ;(side-condition ,(displayln `((S one) ... E_2))) ;(side-condition ,(displayln `((∈ (S one) E_2) ...))) (where (#t ...) ((∈ (S_* (Succ zero)) E_2) ... (∈ (S (Succ zero)) E_2) ...)) (where #t ,(for*/and ([Sl1 (in-list `((S_* ...) (S_r ...) ...))] [Sl2 (in-list `((S_* ...) (S_r ...) ...))]) (equal? (list->set Sl1) (list->set Sl2)))) (bars-match qbar k) ------- (cc->> (machine pbar data) E (machine qbar data_*) (S ...) k)]) (define-judgment-form esterel-eval #:mode (bars-match I I) #:contract (bars-match pbar k) [------- (bars-match p zero)] [------- (bars-match phat (Succ zero))]) (define-metafunction esterel-eval random-E : (S ...) -> E [(random-E (S ...)) ((random-E_S S) ...)]) (define-metafunction esterel-eval random-E_S : S -> (S k) [(random-E_S S) (S ,(if (> (random) 0.5) `zero `(Succ zero)))]) (define-judgment-form esterel-eval #:mode (->*/final I I O O O) [(→* (machine pdotdot data) E (machine qdotdot data_*) (S ...) k) (where #f ,(judgment-holds (→ qdotdot data E _ _ _ _))) ------------- (->*/final (machine pdotdot data) E (machine qdotdot data_*) (S ...) k)]) (define-judgment-form esterel-check #:mode (traps-okay I I) #:contract (traps-okay pbar NL) [(traps-okay (exit nat_h) NL) ----------- (traps-okay (exit nat_h) (nat_h NL))] [----------- (traps-okay (exit nat_h) (nat_h NL))] [(traps-okay pbar ((Succ (Succ zero)) ())) ---------- (traps-okay (trap pbar) ())] [(traps-okay pbar ((Succ nat) (nat NL))) ---------- (traps-okay (trap pbar) (nat NL))] [(traps-okay pbar NL) --------- (traps-okay (loop pbar) NL)] [--------- (traps-okay nothing any)] [--------- (traps-okay pause any)] [--------- (traps-okay (hat pause) any)] [--------- (traps-okay (emit S) any)] [(traps-okay pbar_l NL) (traps-okay pbar_r NL) --------- (traps-okay (seq pbar_l pbar_r) NL)] [(traps-okay pbar_l NL) (traps-okay pbar_r NL) --------- (traps-okay (present S pbar_l pbar_r) NL)] [(traps-okay pbar_l NL) (traps-okay pbar_r NL) --------- (traps-okay (par pbar_l pbar_r) NL)] [(traps-okay pbar NL) --------- (traps-okay (signal S pbar) NL)] [(traps-okay pbar NL) --------- (traps-okay (suspend pbar S) NL)] [(traps-okay pbar NL) --------- (traps-okay (shared s := call pbar) NL)] [(traps-okay pbar NL) --------- (traps-okay (var v := call pbar) NL)] [--------- (traps-okay (<= s call) NL)] [--------- (traps-okay (:= v call) NL)] [(traps-okay pbar NL) (traps-okay qbar NL) --------- (traps-okay (if v pbar qbar) NL)]) (define-judgment-form esterel-check #:mode (loops-okay I) #:contract (loops-okay pbar) [----------- (loops-okay (exit nat_h))] [----------- (loops-okay (exit nat_h))] [(loops-okay pbar) ---------- (loops-okay (trap pbar))] [--------- (loops-okay nothing)] [--------- (loops-okay pause)] [--------- (loops-okay (hat pause))] [--------- (loops-okay (emit S))] [(loops-okay pbar_l) (loops-okay pbar_r) --------- (loops-okay (seq pbar_l pbar_r))] [(loops-okay pbar_l) (loops-okay pbar_r) --------- (loops-okay (present S pbar_l pbar_r))] [(loops-okay pbar_l) (loops-okay pbar_r) --------- (loops-okay (par pbar_l pbar_r))] [(loops-okay pbar) --------- (loops-okay (signal S pbar))] [(loops-okay pbar) --------- (loops-okay (suspend pbar S))] [(loops-okay pbar) (K_s pbar (k ...)) (where #f (∈ zero (k ...))) --------- (loops-okay (loop pbar))] ) (define-judgment-form esterel-check #:mode (K_s I O) #:contract (K_s pbar (k ...)) [---------- (K_s nothing (zero))] [---------- (K_s pause ((Succ zero)))] [----------;; identical. we're pretending its a p (K_s (hat pause) ((Succ zero)))] [---------- (K_s (exit k) (k))] [(K_s pbar (k_1 ...)) (K_s qbar (k_2 ...)) ---------- (K_s (present S pbar qbar) (U (k_2 ...) (k_2 ...)))] [(K_s pbar (k ...)) ---------- (K_s (suspend S pbar) (k ...))] [(K_s pbar (k_1 ...)) (K_s qbar (k_2 ...)) (where #t (∈ 0 (k_1 ...))) ---------- (K_s (seq pbar qbar) (U (k_2 ...) (without zero (k_1 ...))))] [(K_s pbar (k ...)) (where #f (∈ 0 (k ...))) ---------- (K_s (seq pbar qbar) (k ...))] [(K_s pbar (k ...)) ---------- (K_s (loop pbar) (without zero (k ...)))] [(K_s pbar (k_1 ...)) (K_s qbar (k_2 ...)) ---------- (K_s (seq pbar qbar) (metamax (k_2 ...) (k_1 ...)))] [(K_s pbar (k ...)) ---------- (K_s (trap pbar) (↓ (k ...)))] [(K_s pbar (k ...)) ---------- (K_s (suspend S pbar) (k ...))]) (define-metafunction esterel-eval fix-env : M -> M [(fix-env (machine (exit nat_h) data)) (machine (exit nat_h) data)] [(fix-env (machine pause data)) (machine pause data)] [(fix-env (machine (hat pause) data)) (machine (hat pause) data)] [(fix-env (machine nothing data)) (machine nothing data)] [(fix-env (machine (emit S) data)) (machine (emit S) data)] [(fix-env (machine (trap pbar) data)) (machine (trap pbar_*) data_*) (where (machine pbar_* data_*) (fix-env (machine pbar data)))] [(fix-env (machine (loop pbar) data)) (machine (loop pbar_*) data_*) (where (machine pbar_* data_*) (fix-env (machine pbar data)))] [(fix-env (machine (signal S pbar) data)) (machine (signal S pbar_*) data_*) (where (machine pbar_* data_*) (fix-env (machine pbar data)))] [(fix-env (machine (suspend pbar S) data)) (machine (suspend pbar_* S) data_*) (where (machine pbar_* data_*) (fix-env (machine pbar data)))] [(fix-env (machine (seq pbar qbar) data)) (machine (seq pbar_* qbar_*) (U data_* data_**)) (where (machine pbar_* data_*) (fix-env (machine pbar data))) (where (machine qbar_* data_**) (fix-env (machine qbar data)))] [(fix-env (machine (par pbar qbar) data)) (machine (par pbar_* qbar_*) (U data_* data_**)) (where (machine pbar_* data_*) (fix-env (machine pbar data))) (where (machine qbar_* data_**) (fix-env (machine qbar data)))] [(fix-env (machine (present S pbar qbar) data)) (machine (present S pbar_* qbar_*) (U data_* data_**)) (where (machine pbar_* data_*) (fix-env (machine pbar data))) (where (machine qbar_* data_**) (fix-env (machine qbar data)))] [(fix-env (machine (shared s := call phat) data)) (machine (shared s := call_* phat_*) data_**) (where call_* (delete-bad-var-call s data call)) (where data_* (data<- data s (eval-call call_* data) ready)) (where (machine phat_* data_**) (fix-env (machine phat data_*)))] [(fix-env (machine (shared s := call p) data)) (machine (shared s := call_* p_*) data_**) (where call_* (delete-bad-var-call s data call)) (where data_* (data<- data s (eval-call call_* data) old)) (where (machine p_* data_**) (fix-env (machine p data_*)))] [(fix-env (machine (<= s call) data)) (machine (<= s_* call_*) data) (where s_* (visible-s s data)) (where call_* (delete-bad-var-call s_* data call))] [(fix-env (machine (var v := call pbar) data)) (machine (var v := call_* pbar_*) data_**) (where call_* (delete-bad-var-call ,(gensym) data call)) (where data_* (data<- data v (eval-call call_* data))) (where (machine pbar_* data_**) (fix-env (machine pbar data_*)))] [(fix-env (machine (:= v call) data)) (machine (:= v_* call_*) data) (where v_* (visible-v v data)) (where call_* (delete-bad-var-call ,(gensym) data call))] [(fix-env (machine (if v pbar qbar) data)) (machine (if v_* pbar_* qbar_*) (U data_* data_**)) (where v_* (delete-bad-var-call ,(gensym) data v)) (where (machine pbar_* data_*) (fix-env (machine pbar data))) (where (machine qbar_* data_**) (fix-env (machine qbar data)))]) (define-metafunction esterel-eval visible-s : s data -> s [(visible-s s data) s (where #t (∈ s (get-shared data)))] [(visible-s s data) (get-random-s data)]) (define-metafunction esterel-eval visible-v : v data -> v [(visible-v v data) s (where #t (∈ v (get-shared data)))] [(visible-v v data) (get-random-v data)]) (define-metafunction esterel-eval get-shared : data -> (s ...) [(get-shared ()) ()] [(get-shared ((dshared s any_1 any_2) data-elem ...)) (s s_r ...) (where (s_r ...) (get-shared (data-elem ...)))] [(get-shared ((dvar any_1 any_2) data-elem ...)) (get-shared (data-elem ...))]) (define-metafunction esterel-eval get-random-s : data -> s [(get-random-s data) ,(random-ref `(s ...)) (where (s ...) (get-shared data))]) (define-metafunction esterel-eval get-random-v : data -> s [(get-random-v data) ,(random-ref `(v ...)) (where (v ...) (get-unshared data))]) (define-metafunction esterel-eval get-unshared : data -> (v ...) [(get-unshared ()) ()] [(get-unshared ((dvar v any) data-elem ...)) (v v_r ...) (where (v_r ...) (get-unshared (data-elem ...)))] [(get-unshared (any data-elem ...)) (v_r ...) (where (v_r ...) (get-unshared (data-elem ...)))]) (define-metafunction esterel-eval delete-bad-var-call : s data call -> call [(delete-bad-var-call s data (+ call ...)) (+ (delete-bad-var-call s data call) ...)] [(delete-bad-var-call s data s) 1] [(delete-bad-var-call s_0 data s_1) s_1 (where #t (∈ s_1 (get-shared data)))] [(delete-bad-var-call s_0 data s_1) 1] [(delete-bad-var-call s data datum) datum]) (define-extended-language uniquify-lang esterel-eval #:binding-forms (shared s := call pbar #:refers-to s) (var v := call pbar #:refers-to v)) (define-metafunction uniquify-lang ;uniquify : pbar -> pbar [(uniquify (any ...)) ((uniquify any) ...)] [(uniquify any) any]) (define-judgment-form esterel-check #:mode (okay I) #:contract (okay pbar) [(traps-okay pbar ()) -------- (okay pbar)])
true
951342fa9cf12960c95ae351fd616eddc686b9f2
5bbc152058cea0c50b84216be04650fa8837a94b
/pre-benchmark/ecoop/typed-db/private/generic/interfaces.rkt
3bf4c8d2a5a9faeda632f7d60d78fca8cef6c01a
[]
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
10,297
rkt
interfaces.rkt
#lang racket/base (require racket/class racket/serialize unstable/error) (provide connection<%> dbsystem<%> prepared-statement<%> connection? dbsystem? prepared-statement? (struct-out statement-binding) (struct-out simple-result) (struct-out rows-result) (struct-out cursor-result) init-private log-db-error log-db-warning log-db-info log-db-debug (struct-out exn:fail:sql) raise-sql-error) ;; ---------------------------------------- ;; Interfaces ;; connection<%> (define connection<%> (interface () ;; connected? method must return promptly (eg, without acquiring lock) connected? ;; -> boolean disconnect ;; -> void get-dbsystem ;; -> dbsystem<%> query ;; symbol statement -> QueryResult prepare ;; symbol preparable boolean -> prepared-statement<%> fetch/cursor ;; symbol cursor nat -> #f or (listof vector) get-base ;; -> connection<%> or #f (#f means base isn't fixed) list-tables ;; symbol symbol -> (listof string) ;; in start-tx and end-tx, the final boolean arg indicates whether the ;; transaction is managed manually (#f) or by call-with-tx (#t) start-transaction ;; symbol (U 'serializable ...) any boolean -> void end-transaction ;; symbol (U 'commit 'rollback) boolean -> void transaction-status ;; symbol -> (U boolean 'invalid) free-statement)) ;; prepared-statement<%> boolean -> void ;; dbsystem<%> ;; Represents brand of database system, SQL dialect, etc (define dbsystem<%> (interface () get-short-name ;; -> symbol get-parameter-handlers ;; (listof typeid) -> (listof ParameterHandler) field-dvecs->typeids ;; (listof field-dvec) -> (listof typeid) ;; inspection only get-known-types ;; real -> (listof symbol) describe-params ;; (listof typeid) -> (listof TypeDesc) describe-fields)) ;; (listof field-dvec) -> (listof TypeDesc) ;; ParameterHandler = (fsym index datum -> ???) ;; Each system gets to choose its checked-param representation. ;; Maybe check and convert to string. Maybe just check, do binary conversion later. ;; TypeDesc = (list boolean symbol/#f typeid) ;; prepared-statement<%> (define prepared-statement<%> (interface () get-handle ;; -> Handle (depends on database system) set-handle ;; Handle -> void get-close-on-exec? ;; -> boolean after-exec ;; boolean -> void (for close-on-exec) get-stmt ;; -> string/#f get-stmt-type ;; -> symbol/#f get-param-count ;; -> nat get-param-typeids ;; -> (listof typeid) get-result-dvecs ;; -> (listof field-dvec) get-result-count ;; -> nat get-result-typeids ;; -> (listof typeid) check-owner ;; symbol connection any -> #t (or error) bind ;; symbol (listof param) -> statement-binding ;; inspection only get-param-types ;; -> (listof TypeDesc) get-result-types ;; -> (listof TypeDesc) )) (define (connection? x) (is-a? x connection<%>)) (define (dbsystem? x) (is-a? x dbsystem<%>)) (define (prepared-statement? x) (is-a? x prepared-statement<%>)) ;; ---------------------------------------- ;; Auxiliary structures ;; A statement-binding is: ;; - (statement-binding prepared-statement (listof ???)) (struct statement-binding (pst params)) ;; An query-result is one of: ;; - (simple-result alist) ;; - (rows-result Header data) ;; for user-visible rows-results: headers present, data is (listof vector) (serializable-struct simple-result (info) #:transparent) (serializable-struct rows-result (headers rows) #:transparent) ;; A cursor-result is ;; - (cursor-result Header prepared-statement ???) (struct cursor-result (headers pst extra)) ;; A Header is (listof FieldInfo) ;; A FieldInfo is an alist, contents dbsys-dependent ;; ---------------------------------------- ;; Class utilities ;; Here just because ... (define-syntax-rule (init-private iid ...) (begin (init-private1 iid) ...)) (define-syntax-rule (init-private1 iid) (begin (init ([private-iid iid])) (define iid private-iid))) ;; ---------------------------------------- ;; Logging (define-logger db) ;; ---------------------------------------- ;; Exceptions #| Only errors with an associated SQLSTATE are represented by exn:fail:sql, specifically only errors originating from a database backend or library. Other errors are typically raised using 'error', producing plain old exn:fail. For SQLite, use symbol instead of SQLSTATE string. |# ;; exn:fail:sql ;; Represents an error with an associated SQLSTATE (define-struct (exn:fail:sql exn:fail) (sqlstate info)) ;; raise-sql-error : symbol string string alist -> raises exn (define (raise-sql-error who sqlstate message info) (raise (make-exn:fail:sql (compose-error-message who message "SQLSTATE" sqlstate) (current-continuation-marks) sqlstate info))) ;; ---------------------------------------- ;; Common Errors (provide error/internal error/internal* error/not-connected error/disconnect-in-lock error/no-support error/need-password error/comm error/hopeless error/unsupported-type error/no-convert error/invalid-nested-isolation error/tx-bad-stmt error/unbalanced-tx error/unclosed-tx error/nested-tx-option error/exn-in-rollback error/stmt-arity error/stmt error/want-rows error/want-cursor error/column-count error/row-count error/statement-binding-args) (define (error/internal fsym fmt . args) (error* fsym "internal error" #:continued (apply format fmt args))) (define (error/internal* fsym msg . args) (apply error* fsym "internal error" #:continued msg args)) ;; FIXME; clean up (define (error/comm fsym [when-occurred #f]) (error* fsym "communication failure" "when" when-occurred)) (define (error/no-support fsym feature) (error* fsym "feature not supported" "feature" feature)) (define (error/hopeless fsym) (error fsym "connection is permanently locked due to a terminated thread")) (define (error/not-connected fsym) (error fsym "not connected")) (define (error/disconnect-in-lock fsym) (error fsym "disconnected during operation;\n possibly due to custodian shutdown")) ;; ---- (define (error/invalid-nested-isolation fsym isolation) (error* fsym "invalid isolation level for nested transaction" '("isolation level" value) isolation)) (define (error/unbalanced-tx fsym mode saved-cwt?) (error fsym "~a-transaction without matching start-transaction~a" mode (if saved-cwt? " (within the extent of call-with-transaction)" ""))) (define (error/unclosed-tx fsym mode saved-cwt?) (error fsym "unclosed nested transaction~a" (if saved-cwt? " (within extent of call-with-transaction)" ""))) (define (error/tx-bad-stmt fsym stmt-type-string tx-state) (error* fsym "statement not allowed in current transaction state" "statement type" stmt-type-string "transaction state" tx-state)) (define (error/nested-tx-option fsym option) (error* fsym "option not allowed for nested transaction" '("option" value) option)) (define (error/exn-in-rollback fsym e1 e2) (error* fsym "error during rollback" #:continued "secondary error occurred during rollback triggered by primary error" '("primary" value) (exn-message e1) '("secondary" value) (exn-message e2))) ;; ---- (define (error/stmt-arity fsym expected given) (error* fsym "wrong number of parameters for query" ;; FIXME: add stmt, use error/stmt "expected" expected "given" given)) ;; ---- (define (error/need-password fsym) (error fsym "password needed but not supplied")) ;; ---- (define (error/unsupported-type fsym typeid [type #f]) (error* fsym "unsupported type" "type" type "typeid" typeid)) (define (error/no-convert fsym sys type param [note #f] #:contract [ctc #f]) (error* fsym "cannot convert given value to SQL type" '("given" value) param "type" type "expected" (and ctc (format "~.s" ctc)) "dialect" sys "note" note)) ;; ---- (define (error/stmt fsym stmt message . args) (apply error* fsym message '("statement" value) (or (let loop ([stmt stmt]) (cond [(string? stmt) stmt] [(statement-binding? stmt) (loop (statement-binding-pst stmt))] [(prepared-statement? stmt) (loop (send stmt get-stmt))] [else #f])) stmt) ;; FIXME: include params from statement-binding values? ;; must first change statement-binding to store raw params args)) (define (error/want-rows fsym sql executed?) (error/stmt fsym sql (if executed? "query did not return rows" "query does not return rows"))) (define (error/want-cursor fsym sql) (error/stmt fsym sql "query did not return cursor")) (define (error/column-count fsym sql want-columns got-columns executed?) (error/stmt fsym sql (if executed? "query returned wrong number of columns" "query returns wrong number of columns") "expected" want-columns "got" got-columns)) (define (error/row-count fsym sql want-rows got-rows) (error/stmt fsym sql "query returned wrong number of rows" "expected" want-rows "got" got-rows)) (define (error/statement-binding-args fsym stmt args) (error* fsym "cannot execute statement-binding with additional inline arguments" '("statement" value) stmt '("arguments" value) args))
true
b146fa6f29d97873c1fd977a2e32e48609df9dbd
360dceff10ce0671c4f5177ce1271bb760ff38f1
/mosaic/tests/xml-tests.rkt
45494f91824e47dd89e1c7ea1aee89b6152eb329
[]
no_license
shunsunsun/mosaic-racket
7893f296978a240890d671821ea9c869e7239bd0
0e5adfe634e540f2cf4af42cd9d267e33dfca156
refs/heads/master
2021-08-27T15:15:51.352815
2014-04-10T14:48:07
2014-04-10T16:21:40
null
0
0
null
null
null
null
UTF-8
Racket
false
false
2,890
rkt
xml-tests.rkt
#lang racket (require rackunit math/array generic-bind "../xml.rkt" "../validation.rkt" (prefix-in interface: "../interface.rkt") (prefix-in model: "../model.rkt")) (provide xml-tests) (define xml-test-files '("ala_dipeptide.xml" "water.xml" "3ZQ8.xml")) (define (check-items items) (check-equal? (filter (λ (m) (not (equal? (cdr m) "unknown item type"))) (messages (validate-items (sequence-map cdr items)) '())) '())) (define-simple-check (check-equivalent? item1 item2) (empty? (interface:diffs item1 item2))) (define (wrap-sxml-list sxml-list) (let ([refs (make-hash)]) (for/list ([node sxml-list]) (match-let ([(cons xml-id item) (sxml->mosaic node refs)]) (hash-set! refs xml-id item) item)))) (define xml-tests (test-suite "xml" (test-case "items" (for ([filename xml-test-files]) (check-items (items-from-xml (open-input-file filename))))) (test-case "conversion" (for ([filename xml-test-files]) (let* (; Read XML file and return SXML nodes with Mosaic tags [sxml-items-with-ids (filter (λ (x) (or (interface:universe? (cdr x)) (interface:configuration? (cdr x)))) (call-with-input-file filename (λ (in) (sequence->list (items-from-xml in)))))] ; Create Mosaic model data items from SXML [model-items-with-ids (map (λ (x) (cons (car x) (model:make-data-item (cdr x)))) sxml-items-with-ids)] ; Create Mosaic SXML items from Mosaic model items [test-items (wrap-sxml-list (sequence->list (mosaic-sequence->sxml-sequence model-items-with-ids)))] ; Remove xml-ids [sxml-items (map cdr sxml-items-with-ids)] [model-items (map cdr model-items-with-ids)] ; Create XML string from item sequence [xml-string (let ([out (open-output-string)]) (items-to-xml model-items-with-ids out) (get-output-string out))] ; Create item sequence from XML string [recovered-items (map cdr (sequence->list (items-from-xml (open-input-string xml-string))))]) (for ([sxml sxml-items] [model model-items] [test test-items] [recovered recovered-items]) (check-equivalent? sxml model) (check-equivalent? sxml test) (check-equivalent? sxml recovered) (check-equivalent? model test) (check-equivalent? model recovered) (check-equivalent? test recovered)))))))
false
405544a251f44d4006643ebacc8588c18c3b4148
88a45661d9224fa1ef8b37ad50b8c8c549e824a8
/TodoApp/axio/axio-init.rkt
8f05a1604e1a006286d7c28d8c2152244d81ce0e
[ "MIT" ]
permissive
spdegabrielle/RacketCon2020
8c4be25f2aaeb79e9cc0961e54d5a7d0a727d678
310e0ab01d8c3e1546029720f6bb66e6d1a5fb1e
refs/heads/master
2023-03-04T14:00:58.778104
2021-02-21T15:30:33
2021-02-21T15:30:33
null
0
0
null
null
null
null
UTF-8
Racket
false
false
1,147
rkt
axio-init.rkt
#lang racket/base (require "./axio-database.rkt" "./axio-env.rkt" "./axio-init-structs.rkt" "./axio-logger.rkt") (require db racket/contract) (provide axio-init) ;; -------------------------------------------------------------------------------------------- ;; Public Interface ;; -------------------------------------------------------------------------------------------- (define/contract (axio-init app-env-id #:log-level [ log-level 'warning ]) (->* (symbol?) (#:log-level symbol?) axio-context?) (axio-init-logger log-level) (axio-context app-env-id (axio-init-db (get-app-env app-env-id)))) ;; -------------------------------------------------------------------------------------------- ;; Private Implementation ;; -------------------------------------------------------------------------------------------- ;; (axio-init-db app-env-obj) -> axio-db-context? ;; app-env-obj : app-env? (define (axio-init-db app-env-obj) (virtual-connection (connection-pool (λ () (db-connect app-env-obj)) #:max-connections 30 #:max-idle-connections 4)))
false
2103b217ff984cd29f1d0740b285401596a83529
8080968a7c8faf2ef938f4ab4db3cbe284af16f3
/docs/configuring/groups.scrbl
389f9611dada6393573d774805d30d51612ba06c
[ "Apache-2.0" ]
permissive
mooingcat/concourse
98037129914daea008e618238e9e35074982c878
581eb43430fc6d59699824ce903c0c482262f448
refs/heads/master
2020-12-26T00:35:35.333402
2015-05-20T18:37:05
2015-05-20T18:37:05
36,024,824
0
0
null
2015-05-21T16:37:38
2015-05-21T16:37:38
null
UTF-8
Racket
false
false
1,788
scrbl
groups.scrbl
#lang concourse/docs @(require "../common.rkt") @title[#:style 'toc #:version version #:tag "configuring-groups"]{@code{groups}@aux-elem{: Splitting up your pipeline into sections}} A pipeline may optionally contain a section called @code{groups}. As more resources and jobs are added to a pipeline it can become difficult to navigate. Pipeline groups allow you to group jobs together under a header and have them show on different tabs in the user interface. Groups have no functional effect on your pipeline. A simple grouping for the pipeline above may look like: @codeblock["yaml"]|{ groups: - name: tests jobs: - controller-mysql - controller-postgres - worker - integration - name: deploy jobs: - deploy }| This would display two tabs at the top of the home page: "tests" and "deploy". For a real world example of how groups can be used to simplify navigation and provide logical grouping, see the groups used at the top of the page in the @hyperlink["https://ci.concourse.ci"]{Concourse pipeline}. Each configured group consists of the following attributes: @defthing[name string]{ @emph{Required.} The name of the group. This should be short and simple as it will be used as the tab name for navigation. } @defthing[jobs [string]]{ @emph{Optional.} A list of jobs that should appear in this group. A job may appear in multiple groups. Neighbours of jobs in the current group will also appear on the same page in order to give context of the location of the group in the pipeline. } @defthing[resources [string]]{ @emph{Optional.} A list of resources that should appear in this group. Resources that are inputs or outputs of jobs in the group are automatically added; they do not have to be explicitly listed here. } @inject-analytics[]
false
430bd01999975ed110aff8e4be19fbc887542cfc
8f9ddd0172a8b3f21753feddb79436bfcd3766ee
/languageRefactorings/processing-pretty-pritting.rkt
abe1a6c3873eb9bdecbc0e4aa180e26d8ee03c67
[ "MIT" ]
permissive
RafaelReia/RefactoringToolDevelop
4991975ef88c564f70e87f4d33ae3abd7b296ea5
5c3415a3dd2c68c3f2d8bfce592092aef54e2d60
refs/heads/master
2021-01-19T07:23:08.021609
2016-05-28T17:17:15
2016-05-28T17:17:15
47,615,139
3
0
null
2016-05-28T16:48:16
2015-12-08T10:27:13
Racket
UTF-8
Racket
false
false
2,801
rkt
processing-pretty-pritting.rkt
#lang racket (provide write-processing) (require syntax/parse syntax/to-string) (define (write-processing aux) (define (parse-processing-to-racket aux) ;;;;TO FIX BUGS (syntax-parse aux #:datum-literals (:False :True expr-stmt p-not p-truth p-lt p-le p-gt p-ge p-add let/ec p-block p-if p-lt-eq return p-call p-sub p-function p-eq) [(p-not stuff) #`(! #,@(parse-processing-to-racket #'stuff)) ] [(p-truth arg) #`(#,@(parse-processing-to-racket #'arg)) ] ;;call with arg [(p-lt arg1 arg2) #'(arg1 < arg2)] [(p-le arg1 arg2) #'(arg1 <= arg2)] [(p-gt arg1 arg2) #'(arg1 > arg2)] [(p-eq arg1 arg2) #'(arg1 == arg2)] [(p-ge arg1 arg2) #'(arg1 >= arg2)] [(p-declaration (name stuff)) #`(boolean name = #,@(parse-processing-to-racket #'stuff)) ] ;[(p-ge arg1 arg2) #'(#,@(parse-processing-to-racket #'arg1) >= #,@(parse-processing-to-racket #'arg2))] ;[(p-add expr1 expr2) #`(#,@(parse-processing-to-racket #'expr1) #'+ (parse-processing-to-racket #'expr1))] [(p-function (name arg ...) body) #`(#,(parse-name #'name) (int arg ...) {#,@(parse-processing-to-racket #'body)})] [(let/ec return stuff) (parse-processing-to-racket #'stuff)] [(p-block stuff stuff2 stuff3) #`(#,@(parse-processing-to-racket #'stuff) #,@(parse-processing-to-racket #'stuff2) #,@(parse-processing-to-racket #'stuff3))] [(p-if expr result) #`(if #,(parse-processing-to-racket #'expr) #,@(parse-processing-to-racket #'result))] [(p-lt-eq arg1 arg2) #'(arg1 <= arg2)] [(return (p-add arg1 arg2)) #`(return #,@(parse-processing-to-racket #'(p-add arg1 arg2))";")] [(return arg) #'(return arg";")] [(p-add arg1 arg2) #`(#,@(parse-processing-to-racket #'arg1) + #,@(parse-processing-to-racket #'arg2))] [(p-call #:call name arg) #`(#,(parse-name-call #'name) #,(parse-processing-to-racket #'arg))] [(p-sub arg1 arg2) #'(- arg1 arg2)] [_ (displayln "fail")])) (displayln "in write-processing") (parse-processing-to-racket aux)) (define (parse-name name) (define aux (syntax->string #`(#,name))) (define aux-lst (string-split aux "-")) (define return (case (cadr aux-lst) [("I") (string-append "int " (car aux-lst))])) #`(#,@return)) (define (parse-name-call name) (define aux (syntax->string #`(#,name))) (car (string-split aux "-"))) ;(p-function (fib-I-fn n) (let/ec return ;(p-block (p-if (p-lt-eq n 0) (return 0)) ;(p-if (p-eq n 1) (return 1)) ;(return (p-add (p-call #:call fib-I-fn (p-sub n 1)) ;(p-call #:call fib-I-fn (p-sub n 2))))))) (p-initialize)))>
false
a57066c867b636a07ff4676a2e5da53d246fa719
b4146474529ac47b8e93adabe9d61f401a481d41
/GA/GA-enumerator.rkt
5ad64edfad7a376d7505fd4d35c4ce0f29833725
[ "BSD-2-Clause" ]
permissive
mangpo/greenthumb
a2afd5f914bf19747182832606d47670ed9018db
1158769bd0bea5cabc5c1370a14cb5db23e721dc
refs/heads/master
2022-07-10T14:24:35.747168
2022-06-30T20:44:11
2022-06-30T20:44:11
17,042,314
90
11
null
2017-02-21T08:20:55
2014-02-21T01:52:55
Racket
UTF-8
Racket
false
false
1,132
rkt
GA-enumerator.rkt
#lang racket (require "../inst.rkt" "../enumerator.rkt" "GA-machine.rkt") (require racket/generator) (provide GA-enumerator%) (define GA-enumerator% (class enumerator% (super-new) (inherit-field machine) (define opcodes (get-field opcodes machine)) (define mem-inst (map (lambda (x) (vector-member x opcodes)) '(! !+ !b @ @+ @b))) (define/override (filter-with-pruning-info opcode-pool prune-in prune-out #:try-cmp [try-cmp #f] #:no-args [no-args #f]) (define-syntax-rule (min-list x) (foldl min (car x) (cdr x))) (define-syntax-rule (max-list x) (foldl max (car x) (cdr x))) (cond [(and prune-in prune-out) (cond [(= (add1 prune-in) (min-list prune-out)) (filter (lambda (x) (member x mem-inst)) opcode-pool)] [(< prune-in (min-list prune-out)) (list)] [(> prune-in (max-list prune-out)) (list)] [else opcode-pool] ) ] [else opcode-pool])) (define/override (get-pruning-info state-vec) (get-field index (progstate-comm state-vec))) ))
true
42b9516f5a63e58c7261171afc4fe2c8c7d68a28
b55fb34487215aeb0b6fb37891f1d7e4e588ecf8
/proto-template.rkt
4e60edda4589ad03378702149bae9f6156fde124
[]
no_license
endobson/racket-protobuf
3b55a54c63dfcf2fc42f744632a31e79b154eef1
0876bd17bdb81fb1b62d9c91d03059db36f4e21f
refs/heads/master
2022-02-20T17:30:44.867474
2019-08-27T05:16:22
2019-08-27T05:16:22
103,805,078
2
1
null
null
null
null
UTF-8
Racket
false
false
4,776
rkt
proto-template.rkt
#lang racket/base (require (for-syntax (for-syntax racket/base racket/port) racket/base racket/match racket/hash racket/list racket/syntax protobuf/code-generation protobuf/convert-descriptors protobuf/message-identifiers protobuf/proto-descriptors)) (provide (except-out (all-defined-out) gen-requires go)) (begin-for-syntax (define-syntax (gen-raw-descriptor stx) (call-with-input-file "{DESCRIPTOR}" (lambda (port) #`'#,(port->bytes port)))) (define source-path "{SOURCE_PATH}") (define raw-descriptor (gen-raw-descriptor)) (define file-descriptor-set (parse-file-descriptor-set (open-input-bytes raw-descriptor))) (define file-descriptor (or (findf (lambda (desc) (equal? source-path (file-descriptor-proto-name desc))) (file-descriptor-set-file file-descriptor-set)) (error 'proto-template "No descriptor for ~a." source-path))) (define defined-descriptors (convert-file-descriptor file-descriptor)) (define defined-type-ids (make-type-identifier-dict #'here defined-descriptors))) (module* type-ids #f (provide (for-syntax type-ids)) (define-for-syntax type-ids defined-type-ids)) (define-syntax (gen-requires stx) (syntax-case stx () [(_ imported-ids) (let () (define-values (ids requires) (for/lists (ids requires) ([dependency (in-list (file-descriptor-proto-dependency file-descriptor))]) (define lib-name (string-append "protogen/" (substring dependency 0 (- (string-length dependency) 6)) "-proto")) (define id (generate-temporary 'type-id)) (values id #`(require #,(string->symbol lib-name) (only-in (submod #,(string->symbol lib-name) type-ids) [type-ids #,id]))))) #`(begin #,@requires (define-for-syntax imported-ids (hash-union defined-type-ids #,@ids))))])) (gen-requires imported-ids) (define-syntax (go stx) (define (introduce ids) (match ids [(proto-identifiers message builder) (proto-identifiers (introduce message) (introduce builder))] [(message-identifiers constructor fields parser serializer freezer descriptor) (message-identifiers (syntax-local-introduce constructor) (for/hash ([(k v) (in-hash fields)]) (values k (introduce v))) (syntax-local-introduce parser) (syntax-local-introduce serializer) (syntax-local-introduce freezer) (syntax-local-introduce descriptor))] [(singular-field-identifiers accessor) (singular-field-identifiers (syntax-local-introduce accessor))] [(repeated-field-identifiers accessor) (repeated-field-identifiers (syntax-local-introduce accessor))] [(builder-identifiers constructor fields parser serializer copier) (builder-identifiers (syntax-local-introduce constructor) (for/hash ([(k v) (in-hash fields)]) (values k (introduce v))) (syntax-local-introduce parser) (syntax-local-introduce serializer) #f ;(syntax-local-introduce copier) )] [(builder-singular-field-identifiers accessor mutator available-predicate clearer ) (builder-singular-field-identifiers (syntax-local-introduce accessor) (syntax-local-introduce mutator) #f ;(syntax-local-introduce available-predicate) #f ;(syntax-local-introduce clearer) )] [(builder-repeated-field-identifiers count accessor setter adder list-adder remover clearer index-builder-accessor list-builder-accessor builder-adder) (builder-repeated-field-identifiers #f ;(syntax-local-introduce count) (syntax-local-introduce accessor) #f ;(syntax-local-introduce setter) (syntax-local-introduce adder) #f ;(syntax-local-introduce list-adder) #f ;(syntax-local-introduce remover) #f ;(syntax-local-introduce clearer) #f ;(syntax-local-introduce index-builder-accessor) #f ;(syntax-local-introduce list-builder-accessor) #f ;(syntax-local-introduce builder-adder) )] [(enum-identifiers predicate list enum->number number->enum) (enum-identifiers (syntax-local-introduce predicate) (syntax-local-introduce list) (syntax-local-introduce enum->number) (syntax-local-introduce number->enum))])) (define introduced-ids (for/hash ([(k v) (in-hash imported-ids)]) (values k (introduce v)))) (generate-code introduced-ids defined-descriptors)) (go)
true
c7a443d2e80a6bbeb881e3cf0f899a28e2f622c0
569eb7a16d4cfb02c4fb5d92c7452aa13d22d7b8
/homework/hw01/boids00.rkt
2309df976e1681d48da6d7b20da4de1ea5c4065c
[]
no_license
geofmatthews/csci322
7917acd8ee84588db7c549b38deb721d961d555a
4d2687a1a2161d3b07154631cc5bee01507ada92
refs/heads/master
2021-01-13T13:47:29.722467
2016-03-02T18:45:53
2016-03-02T18:45:53
49,018,195
2
2
null
null
null
null
UTF-8
Racket
false
false
6,800
rkt
boids00.rkt
#lang racket ;; Geoffrey Matthews ;; 2016 ;; A non-threaded boids demo (require racket/gui) ;; Small 2d vector library for the Newtonian physics (define (x v) (vector-ref v 0)) (define (y v) (vector-ref v 1)) (define (x! v value) (vector-set! v 0 value)) (define (y! v value) (vector-set! v 1 value)) (define (v* v value) (vector-map (lambda (x) (* x value)) v)) (define (v*! v value) (vector-map! (lambda (x) (* x value)) v)) (define (v+ v w) (vector-map + v w)) (define (v- v w) (vector-map - v w)) (define (v+! v w) (vector-map! + v w)) (define (v-zero! v) (vector-map! (lambda (x) 0) v)) (define (v-dot v w) (let ((vw (vector-map * v w))) (+ (x vw) (y vw)))) (define (v-mag v) (sqrt (v-dot v v))) (define (perp v) (vector (- (y v)) (x v))) ;; Boid object (define boid% (class object% (public p v calculate-force move draw) (init-field (screen-width 1024) (screen-height 768) (position (vector 0 0 )) (velocity (vector 0 0 )) (force (vector 0 0 )) (separation (vector 0 0)) (alignment (vector 0 0)) (cohesion (vector 0 0))) (define (p) position) (define (v) velocity) ;; Boids, as explained by Reynolds (define (calculate-force list-of-boids) (let ((neighborhood-radius 200.0) (separation-strength 10) (alignment-strength 10) (cohesion-strength 10) (max-force 0.05) ) (v-zero! force) (v-zero! separation) (v-zero! alignment) (v-zero! cohesion) (for-each (lambda (other-boid) (when (not (equal? this other-boid)) (let* ((direction (v- (send other-boid p) position)) (dist (v-mag direction)) ) (when (< dist neighborhood-radius) (v+! separation (v* direction (* (/ -1.0 (max 0.001 dist))))) (v+! alignment (send other-boid v)) (v+! cohesion direction))))) list-of-boids) (v*! separation (/ separation-strength (max 1.0 (v-mag separation)))) (v*! alignment (/ alignment-strength (max 1.0 (v-mag alignment)))) (v*! cohesion (/ cohesion-strength (max 1.0 (v-mag cohesion)))) (v+! force (v+ (v- separation (send this v)) (v+ (v- alignment (send this v)) (v- cohesion (send this v))))) (let ((force-magnitude (v-mag force))) (when (> force-magnitude max-force) (set! force (v* force (/ max-force force-magnitude))))) )) ;; Simple Euler integration of acceleration and velocity (define (move) (vector-map! + velocity force) (when (or (zero? (x velocity)) (zero? (y velocity))) (x! velocity (random)) (y! velocity (random))) (vector-map! + position velocity) ;; Wrap the screen (x! position (modulo (round (x position)) screen-width)) (y! position (modulo (round (y position)) screen-height)) ) ;; Draw a boid (define (draw dc) (send dc set-brush brush) (send dc set-pen pen) (let* ((velocity-mag (v-mag velocity)) (tip-vector (v* velocity (/ arrow-length velocity-mag))) (tip (v+ position tip-vector)) (perp (v* (vector (- (y tip-vector)) (x tip-vector)) 0.25)) (p1 (v+ position perp)) (p2 (v+ position (v* perp -1))) (points (list (cons (x tip) (y tip)) (cons (x p1) (y p1)) (cons (x p2) (y p2))))) (send dc draw-polygon points))) ;; Initialize (x! velocity (* 20 (- 0.5 (random)))) (y! velocity (* 20 (- 0.5 (random)))) (define arrow-length 20) ;(define color ; (let* ((r (random)) ; (b (real->floating-point-bytes r 4))) ; (make-object color% (bytes-ref b 0) (bytes-ref b 1) (bytes-ref b 2) ))) (define color (make-object color% 0 0 128)) (define brush (make-object brush% color)) (define pen (make-object pen% color)) ;; Don't forget the super-new! (super-new) )) ;; Abstract the list-handling for a list of boids (define boid-container% (class object% (public add-boid calculate-force move draw get-boids reset) (init-field (boids '())) (define (get-boids) boids) (define (reset) (set! boids '())) (define (add-boid boid) (set! boids (cons boid boids))) (define (calculate-force) (for ((boid boids)) (send boid calculate-force boids))) (define (move) (for ((boid boids)) (send boid move))) (define (draw dc) (for ((boid boids)) (send boid draw dc))) (super-new) ) ) (define boid-container (new boid-container%)) ;; The GUI (define frame (new frame% (label "boids") (width 1024) (height 768) )) (send frame create-status-line) (send frame show #t) (define h-panel (new horizontal-panel% (parent frame) (stretchable-height #f) (style '(border)) (border 2))) (define run-checkbox (new check-box% (parent h-panel) (label "Run animation") )) (define reset-button (new button% (parent h-panel) (label "Reset") (callback (lambda (b e) (send boid-container reset))))) (define my-canvas% (class canvas% (override on-paint on-event) (define (on-paint) (let ((dc (send this get-dc)) (w (send this get-width)) (h (send this get-height))) (send dc clear) (send boid-container draw dc) )) (define (on-event event) (when (send event button-down?) (let ((x (send event get-x)) (y (send event get-y))) (send frame set-status-text (format "Mouse at ~a ~a" x y)) (send boid-container add-boid (new boid% (screen-width (send this get-width)) (screen-height (send this get-height)) (position (vector x y)))) (send this refresh) )) ) (super-new) (send (send this get-dc) set-background (make-object color% 192 224 255)) )) (define canvas (new my-canvas% (parent frame) (style '(border)))) ;; Busy loop boid animator (let loop () (sleep/yield .025) (when (send run-checkbox get-value) (send boid-container calculate-force) (send boid-container move) (send canvas refresh) ) (loop))
false
5c1e86e93d9f3d515d3453628e62433d48fbe096
e29bd9096fb059b42b6dde5255f39d443f69caee
/metapict/device.rkt
8e6b55fbe5707df4ad634f2602edeb73b93f05b0
[]
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
2,877
rkt
device.rkt
#lang racket/base ;;; ;;; i) Transformation from logical to device coordinates ;;; ii) px, xpx and ypx: compute logical size of a pixels (provide curve-pict-width curve-pict-height curve-pict-window set-curve-pict-size current-curve-transformation stdtrans px xpx ypx devpt) (require "def.rkt" "pict-lite.rkt" "pt-vec.rkt" "structs.rkt" "trans.rkt" "parameters.rkt" (for-syntax syntax/parse racket/base) racket/list racket/math) (def curve-pict-width (make-parameter 100)) (def curve-pict-height (make-parameter 100)) (def curve-pict-window (make-parameter ; (window -1 1 -1 1) (window -1.1 1.1 -1.1 1.1))) (define (set-curve-pict-size . xs) (defm (or (list w h) (and (list (? pict?)) (app (λ(ps) (def p (first ps)) (list (pict-width p) (pict-height p))) (list w h)))) xs) (curve-pict-width w) (curve-pict-height h)) (define (trans-logical-to-device win device-width device-height) ; minx, maxx, miny, and, maxy defines a logical coordinate system ; device-width and device-height is the device size (defm (window minx maxx miny maxy) win) (def lw (- maxx minx)) ; logical width (def lh (- maxy miny)) ; logical height (defv (dw dh) (values device-width device-height)) ; transform xmin..xmax , ymin..ymax to standard device coords ; xnew = xx*x + xy*y + x0 ; ynew = yx*x + yy*y + y0 (def xx (/ dw lw)) ; scale from logical x to device x (def yy (- (/ dh lh))) ; scale from logical y to device y (def x0 (- (* (/ dw lw) minx))) ; additional amount added to the device x (def y0 (* (/ dh lh) maxy)) ; additional amount added to the device y (define (post T) (def P (or (current-device-post-transformation) identity)) (P T)) (post (trans xx 0 0 yy x0 y0))) (define stdtrans trans-logical-to-device) (define (current-curve-transformation) (stdtrans (curve-pict-window) (curve-pict-width) (curve-pict-height))) (define (px a [T #f]) (let ([T (or T (current-curve-transformation))]) (sqrt (+ (sqr (xpx a T)) (sqr (ypx a T)))))) (define (xpx w [T #f]) ; logical width of w pixels (let ([T (or T (current-curve-transformation))]) (/ w (norm (vec- (T (vec 1 0)) (T (vec 0 0))))))) (define (ypx h [T #f]) (let ([T (or T (current-curve-transformation))]) (/ h (norm (vec- (T (vec 1 0)) (T (vec 0 0))))))) ; (devpt expr ...] ; receive x and y device coordinate from the last expr, ; return pt in logical coordinates (define-syntax (devpt stx) (syntax-parse stx [(_ expr ...) #'(let () (defv (x y) expr ...) (def Tinv (inverse (current-curve-transformation))) (Tinv (pt x y)))]))
true
99ace43fec34c9eb8abd71e9f596209b670dafb4
66c92b955f3caa70ea4b322654079450ab9eff36
/gm-pepm-2018/script/performance-info.rkt
d280991924bc0e2e9e15c4341ab75c922047f102
[ "MIT" ]
permissive
nuprl/retic_performance
ebc3a5656ce77539ff44c50ac00dacd0a22496ec
da634137b151553c354eafcc549e1650043675f9
refs/heads/master
2023-06-22T05:41:16.151571
2023-06-12T20:16:13
2023-06-12T20:16:13
85,637,202
3
1
MIT
2023-06-12T20:16:14
2017-03-20T23:23:11
Racket
UTF-8
Racket
false
false
31,473
rkt
performance-info.rkt
#lang racket/base ;; Encapsulates info about a benchmark's performance ;; Command-line usage: ;; raco rp-perf <benchmark-name> ... ;; Prints summary stats for each `<benchmark-name>` (require racket/contract) (provide (contract-out [performance-info? (-> any/c boolean?)] ;; Predicate for instances of the `preformance-info` struct [rename performance-info-name performance-info->name (-> performance-info? symbol?)] [benchmark->performance-info (-> benchmark-info? performance-info?)] ;; Construct a `performance-info` struct from a `benchmark-info` struct [python-runtime (-> performance-info? real?)] ;; Return the runtime of the benchmark's untyped configuration under Python [untyped-runtime (-> performance-info? real?)] ;; Return the runtime of the benchmark's untyped configuration under Reticulated [typed-runtime (-> performance-info? real?)] ;; Return the runtime of the benchmark's fully-typed configuration under Reticulated [num-configurations (-> performance-info? natural?)] ;; Count the number of configurations in a benchmark [num-types (-> performance-info? natural?)] ;; Count the number of annotatable-positions in the benchmark (for our experiment) ;; A benchmark with `F` functions and `C` classes with fields and `M` methods ;; across all the classes has `F + C + M` types. [overhead (case-> (-> performance-info? real? real?) (-> performance-info? (-> real? real?)))] ;; `(overhead p v)` returns the overhead of the running time `v` relative ;; to the Python configuration of `p` [min-overhead (-> performance-info? real?)] ;; Returns the lowest observed overhead of any configuration in `p` [max-overhead (-> performance-info? real?)] ;; Returns the maximum observed overhead of any configuration in `p` [mean-overhead (-> performance-info? real?)] ;; Returns the average overhead across all configurations in `p` [deliverable (-> real? (-> performance-info? natural?))] ;; `((deliverable D) p)` returns the number of configurations in `p` ;; that have overhead at most `D` relative to the Python configuration of `p` [typed/python-ratio (-> performance-info? real?)] ;; Returns the overhead of the fully-typed configuration in `p` ;; relative to the Python configuration [typed/retic-ratio (-> performance-info? real?)] ;; Returns the overhead of the fully-typed configuration in `p` ;; relative to the untyped configuration (aka typed/untyped-ratio) [untyped/python-ratio (-> performance-info? real?)] ;; Returns the overhead of the untyped configuration in `p` ;; relative to the Python configuration [make-D-deliverable? (-> real? performance-info? (-> real? boolean?))] ;; Return a function that decides whether a given running time is ;; D-deliverable. [count-configurations (-> performance-info? (-> real? boolean?) natural?)] ;; Count the number of configurations ;; (encapsulted by the given `performance-info` struct) ;; that satisfy the given predicate. [filter-time* (-> performance-info? (-> real? boolean?) (listof real?))] ;; Return the MEAN RUNNING TIMES for configurations whose mean ;; running time satisfies the given predicate. [performance-info-has-karst-data? (-> performance-info? boolean?)] [performance-info->sample* (-> performance-info? (cons/c natural? (listof path-string?)))] [performance-info%sample (-> performance-info? path-string? performance-info?)] [unzip-karst-data (-> path-string? (or/c #f path-string?))] [count-better-with-types (-> (listof benchmark-info?) natural?)] ;; Count the number of typed configurations that run faster than ;; some configuration with less types, across all the given benchmarks. [find-speedy-types (-> (listof benchmark-info?) (hash/c symbol? (listof (cons/c string? string?)) #:immutable #t #:flat? #t))] ;; Enumerate all pairs of configurations C0 C1 such that: ;; - C0 has fewer typed components than C1 ;; - C0 is SLOWER than C1 ;; Return a hash of all enumerations for all given benchmarks. [in-configurations (-> performance-info? (sequence/c configuration? natural? (listof real?)))] [typed-racket-data->performance-info (-> path-string? performance-info?)] ) performance-info-src line->configuration-string fold/karst ;; (-> (or/c path-string? performance-info?) ;; #:f (-> A configuration? natural? (listof real?) A) ;; #:init A A) ;; Fold (left) function for Karst data. ;; Given function is called with: ;; - the accumulated data so far ;; - the current line's configuration ;; - the number of types in the current configuration ;; - the running times for that configuration ) (require "benchmark-info.rkt" "config.rkt" "util.rkt" (only-in math/statistics mean) (only-in racket/list append* remove-duplicates list-set) (only-in racket/file file->value) (only-in racket/format ~r) (only-in racket/path path-only) (only-in racket/math natural?) (only-in file/gunzip gunzip) (only-in math/statistics mean) (only-in racket/sequence sequence/c) (only-in racket/string string-replace)) ;; ============================================================================= (define HOME (retic-performance-home-dir)) (struct performance-info ( name ;; Symbol, a benchmark name src ;; Path-String, data from Karst num-configs python-runtime untyped-runtime typed-runtime ) #:transparent #:methods gen:custom-write [(define (write-proc v port mode) (fprintf port "#<performance-info:~a>" (performance-info-name v)))]) (define (make-performance-info name #:src k #:num-configurations num-configs #:python-runtime python #:untyped-retic-runtime base-retic #:typed-retic-runtime typed-retic) (performance-info name k num-configs python base-retic typed-retic)) (define (typed-racket-data->performance-info ps) (define bm-name (parse-typed-racket-filename ps)) (define v (file->value ps)) (define nc (vector-length v)) (define rr (mean (vector-ref v 0))) (define tr (mean (vector-ref v (- nc 1)))) (make-performance-info (string->symbol bm-name) #:src ps #:num-configurations nc #:python-runtime rr #:untyped-retic-runtime rr #:typed-retic-runtime tr)) (define (performance-info-for-typed-racket? pi) (define src (performance-info-src pi)) (and src (parse-typed-racket-filename src))) (define (parse-typed-racket-filename ps) (define-values [_base name mbd?] (split-path ps)) (and (path-string? name) (let ([m (regexp-match #rx"^([^-]*)-v.*rktd$" (path-string->string name))]) (and m (cadr m))))) (define (performance-info-has-karst-data? pi) (and (performance-info-src pi) #t)) (define (gunzip/cd ps) (define-values [base name _dir?] (split-path ps)) (parameterize ([current-directory base]) (gunzip name)) (build-path base (file-remove-extension name))) (define (unzip-karst-data kd) (let* ([tab.gz kd] [tab (and tab.gz (gunzip/cd tab.gz))]) tab)) (define (->performance-info pi) (cond [(performance-info? pi) pi] [(benchmark-info? pi) (benchmark->performance-info pi)] [else (benchmark->performance-info (->benchmark-info pi))])) (define (benchmark->performance-info bm) (define name (benchmark->name bm)) (define kd (benchmark->karst-data bm)) (define k (and kd (unzip-karst-data kd))) (define-values [num-configs configs/module* base-retic typed-retic] (if kd (scan-karst-file k) (values (benchmark->num-configurations bm) (benchmark->max-configuration bm) (mean (benchmark->karst-retic-untyped bm)) (mean (benchmark->karst-retic-typed bm))))) (unless (and (= num-configs (benchmark->num-configurations bm)) (equal? configs/module* (benchmark->max-configuration bm))) (raise-user-error 'benchmark->performance-info "fatal error processing ~a" name)) (define python (mean (benchmark->python-data bm))) (make-performance-info name #:src k #:num-configurations num-configs #:python-runtime python #:untyped-retic-runtime base-retic #:typed-retic-runtime typed-retic)) (define (make-configuration-counter) (let ([cm (box #f)]) (values cm (λ (cfg/mod*) (set-box! cm (if (and (unbox cm) (for/and ([v-old (in-list (unbox cm))] [v-new (in-list cfg/mod*)]) (>= v-old v-new))) (unbox cm) cfg/mod*)))))) ;; scan-karst-file : Path-String -> (Values Natural (Listof Natural) Natural Natural) ;; Take a "first glance" pass over a data file ;; Return ;; - the number of configurations ;; - the max. number of types per module (in alphabetical order) (define (scan-karst-file k) (define-values [num-configs num-configs++] (let ([nc (box 0)]) (values nc (λ () (set-box! num-configs (+ 1 (unbox num-configs))))))) (define-values [configs/module* update-configs/module*] (make-configuration-counter)) (define-values [base-retic typed-retic update-base-retic update-typed-retic] (let ([ur (box #f)] [tr (box #f)]) (values ur tr (λ (times-str) (set-box! ur (mean (string->time* times-str)))) (λ (times-str) (when (not (unbox tr)) (set-box! tr (mean (string->time* times-str)))))))) (with-input-from-file k (λ () (for ([ln (in-lines)]) (define-values [cfg-str times-str] (let ([ln-info (parse-line ln)]) (values (car ln-info) (caddr ln-info)))) (num-configs++) (define cfg/mod* (string->configuration cfg-str)) (define prev-cfg* (unbox configs/module*)) (update-configs/module* cfg/mod*) (when (typed-configuration? cfg/mod*) (update-typed-retic times-str)) (unless (equal? prev-cfg* (unbox configs/module*)) (update-base-retic times-str)) (void)))) (values (unbox num-configs) (map add1 (unbox configs/module*)) (unbox base-retic) (unbox typed-retic))) (define (karst-file->max-configuration k) (define-values [configs/module* update-configs/module*] (make-configuration-counter)) (with-input-from-file k (λ () (for ([ln (in-lines)]) (update-configs/module* (string->configuration (line->configuration-string ln))) (void)))) (map add1 (unbox configs/module*))) (define (typed-configuration? cfg/mod*) (andmap zero? cfg/mod*)) (define (line->configuration-string str) (let ([str* (parse-line str)]) (car str*))) (define/contract (parse-line str) (-> string? (list/c string? string? string?)) (tab-split str)) (define/contract (string->num-types t-str) (-> string? natural?) (string->number t-str)) (define/contract (string->time* times-str) (-> string? (non-empty-listof (and/c real? (>=/c 0)))) (let ([sp (open-input-string (string-replace times-str "," ""))]) (begin0 (read sp) (close-input-port sp)))) (define (line->values ln line-number) (with-handlers ([exn:fail:read? (λ (e) (printf "PARSE ERROR on line ~a~n" line-number) (raise e))]) (define str* (parse-line ln)) (define cfg (string->configuration (car str*))) (define nt (string->num-types (cadr str*))) (define t* (string->time* (caddr str*))) (values cfg nt t*))) (define (untyped-runtime pf) (performance-info-untyped-runtime pf)) (define (typed-runtime pf) (performance-info-typed-runtime pf)) (define (python-runtime pf) (performance-info-python-runtime pf)) (define (num-configurations pf) (performance-info-num-configs pf)) (define (num-types pf) (log2 (num-configurations pf))) (define overhead (case-lambda [(pf v) ((overhead pf) v)] [(pf) (let ([baseline (performance-info-python-runtime pf)]) (λ (v) (/ v baseline)))])) (define (min-overhead pf) (overhead pf (fold/mean pf min))) (define (max-overhead pf) (overhead pf (fold/mean pf max))) (define (mean-overhead pf) (define 1/N (/ 1 (num-configurations pf))) (define (avg acc v) (+ acc (* 1/N v))) (overhead pf (fold/mean pf avg #:init (λ (v) (* 1/N v))))) (define (fold/karst pf #:init init #:f f) (define src (cond [(path-string? pf) pf] [(performance-info? pf) (performance-info-src pf)] [else (raise-argument-error 'fold/karst "(or/c path-string? performance-info?)" 0 pf init f)])) (with-input-from-file src (λ () (for/fold ([acc init]) ([ln (in-lines)] [i (in-naturals)]) (define-values [cfg nt t*] (line->values ln i)) (f acc cfg nt t*))))) (define (all-configurations pi) (define (add-config H cfg _nt t*) (hash-set H cfg t*)) (fold/karst pi #:init (make-immutable-hash) #:f add-config)) (define count-karst-lines (let ([lines++ (λ (acc cfg nt t*) (+ acc 1))]) (λ (ps) (fold/karst ps #:f lines++ #:init 0)))) ;; fold/mean : (All (A) performance-info? (-> A Real A) #:init (U #f (-> Real A)) -> A) (define (fold/mean pf f #:init [init-f #f]) (define gen (in-configurations pf)) (define init (for/first ([(_a _b t*) gen]) (mean t*))) (for/fold ([acc (if init-f (init-f init) init)]) ([(_a _b t*) gen]) (f acc (mean t*)))) (define ((deliverable D) pf) (count-configurations pf (make-D-deliverable? D pf))) (define (make-D-deliverable? D pf) (define overhead/pf (overhead pf)) (lambda (t) (<= (overhead/pf t) D))) (define (count-configurations pf good?) (define (add-good? count t) (if (good? t) (+ count 1) count)) (fold/mean pf add-good? #:init (λ (t0) (add-good? 0 t0)))) (define (filter-time* pf keep?) (define (keep-it acc t) (if (keep? t) (cons t acc) acc)) (fold/mean pf keep-it #:init (λ (t) (keep-it '() t)))) (define (typed/python-ratio pf) (/ (performance-info-typed-runtime pf) (performance-info-python-runtime pf))) (define (typed/retic-ratio pf) (/ (performance-info-typed-runtime pf) (performance-info-untyped-runtime pf))) (define (untyped/python-ratio pf) (/ (performance-info-untyped-runtime pf) (performance-info-python-runtime pf))) (define (quick-performance-info bm-name) (define bm (->benchmark-info bm-name)) (define pf (benchmark->performance-info bm)) (define nc (performance-info-num-configs pf)) (printf "~a~n" bm-name) (printf "- num configs : ~a~n" nc) (printf "- Python time : ~a~n" (performance-info-python-runtime pf)) (printf "- untyped time : ~a~n" (performance-info-untyped-runtime pf)) (printf "- typed time : ~a~n" (performance-info-typed-runtime pf)) (printf "- untyped/python : ~a~n" (untyped/python-ratio pf)) (printf "- typed/untyped : ~a~n" (typed/retic-ratio pf)) (printf "- typed/python : ~a~n" (typed/python-ratio pf)) (printf "- min overhead : ~a~n" (min-overhead pf)) (printf "- max overhead : ~a~n" (max-overhead pf)) (printf "- avg overhead : ~a~n" (mean-overhead pf)) (let ([d2 ((deliverable 2) pf)]) (printf "- 2 deliv. : ~a (~a%)~n" d2 (rnd (pct d2 nc)))) (let ([d5 ((deliverable 5) pf)]) (printf "- 5 deliv. : ~a (~a%)~n" d5 (rnd (pct d5 nc)))) (void)) (define (performance-info->sample* pi) (define sample* (karst-dir->sample* (retic-performance-karst-dir HOME) (performance-info-name pi))) (when (null? sample*) (raise-argument-error 'performance-info->sample* "performance-info? with sample data" pi)) (define line* (with-handlers ([exn:fail:read? (λ (e) (printf "ERROR reading samples files '~a'~n" sample*) (raise e))]) (map count-karst-lines sample*))) (define sample-size (car line*)) (for ([s (in-list (cdr sample*))] [l (in-list (cdr line*))]) (unless (= l sample-size) (printf "WARNING: sample file ~a should have ~a lines, but has ~a instead" s sample-size l) #;(raise-user-error 'performance-info->sample* "sample file ~a should have ~a lines, but has ~a instead" s sample-size l))) (cons sample-size sample*)) ;; Doesn't really belong here, oh well (define (fix-num-types sample-file) (printf "fixing types in '~a'...~n" sample-file) (define bm (or (for/or ([possible-benchmark-name (in-list (infer-benchmark-name sample-file))]) (with-handlers ([exn:fail:contract? (λ (e) #f)]) (->benchmark-info possible-benchmark-name))) (raise-user-error 'fix-num-types "failed to infer benchmark name from file '~a'" sample-file))) (define mc (benchmark->max-configuration bm)) (define tmp (path-add-extension sample-file #".tmp")) (with-output-to-file tmp #:exists 'replace (λ () (with-input-from-file sample-file (λ () (for ([ln (in-lines)]) (define str* (parse-line ln)) (define cfg (string->configuration (car str*))) (define new-num-types (count-types cfg mc)) (define old-num-types (string->number (cadr str*))) #;(when (not (= new-num-types old-num-types)) (fprintf (current-error-port) "Configuration ~a : ~a ==> ~a~n" cfg old-num-types new-num-types)) (displayln (tab-join (list (car str*) (number->string new-num-types) (caddr str*)))) (void)))))) (copy-file tmp sample-file #t) (delete-file tmp) (void)) (define (count-types cfg max-cfg) (for/sum ([c (in-list cfg)] [x (in-list max-cfg)]) (if (= 1 x) ;; TODO right place to test this? Checking for files with ZERO type annotations. Really the file should be in the "both" directory 0 (count-zero-bits (natural->bitstring c #:pad (log2 x)))))) (define (infer-benchmark-name sample-file) (define dir (or (path-only sample-file) (current-directory))) (define-values [dir-base dir-name dir-mbd] (split-path dir)) (define-values [file-base file-name file-mbd] (split-path sample-file)) (for/list ([candidate (in-list (list dir-name (path-replace-extension file-name #"")))] #:when (path? candidate)) (path->string candidate))) (define (performance-info%sample pi new-src) (performance-info (performance-info-name pi) new-src (count-karst-lines new-src) (performance-info-python-runtime pi) (performance-info-untyped-runtime pi) (performance-info-typed-runtime pi))) (define (count-better-with-types bm*) (for/sum ([n+c* (in-list (better-with-types bm*))]) (length (cdr n+c*)))) (define (better-with-types bm*) (for/list ([(n cc*) (in-hash (find-speedy-types bm*))]) (cons n (remove-duplicates (map cdr cc*))))) (define (find-speedy-types bm*) (for/hash ([bm (in-list bm*)]) (define name (benchmark->name bm)) (define mc (benchmark->max-configuration bm)) (define pi (benchmark->performance-info bm)) (when (< (expt 2 17) (performance-info-num-configs pi)) (raise-user-error 'find-speedy-types "benchmark '~a' is too large" name)) (define AC (all-configurations pi)) (define speedy-pairs (for*/list ([(c0 t0*) (in-hash AC)] [c1 (in-list (successors c0 mc))] #:when (significantly-faster? (hash-ref AC c1) t0*)) (cons (configuration->string c0) (configuration->string c1)))) (values name speedy-pairs))) (define (significantly-faster? t1* t0*) (define u0 (mean t0*)) (define u1 (mean t1*)) (and (< u1 u0) (let ([c0 (confidence-interval t0*)] [c1 (confidence-interval t1*)]) (and (< (+ u1 c1) u0) (< u1 (- u0 c0)))))) (define (successors cfg max-config) (append* (for/list ([mod-id (in-list cfg)] [mod-num-bits (in-list max-config)] [i (in-naturals)]) (define bits (natural->bitstring mod-id #:pad (log2 mod-num-bits))) (for/list ([c (in-string bits)] [j (in-naturals)] #:when (eq? c #\1)) (list-set cfg i (bitstring->natural (string-set bits j #\0))))))) (define (string-set str index new-char) (define str2 (string-copy str)) (string-set! str2 index new-char) str2) (define (in-configurations pi) (if (performance-info-has-karst-data? pi) (if (performance-info-for-typed-racket? pi) (in-configurations/tr pi) (in-configurations/karst-data pi)) (in-configurations/sample-data pi))) (define (in-configurations/tr pi) (define go (let* ([v (file->value (performance-info-src pi))] [num-configs (vector-length v)] [count-hi-bits (λ (i) (for/sum ([c (in-string (~r i #:base 2))] #:when (eq? c #\1)) 1))] [curr (box 0)]) (λ () (define i (unbox curr)) (cond [(= i num-configs) (values #f #f #f)] [else (set-box! curr (+ i 1)) (define cfg (list i)) (define num-types (count-hi-bits i)) (define t* (vector-ref v i)) (values cfg num-types t*)])))) (in-producer go stop?)) (define (in-configurations/karst-data pi) (define go (let ([p (open-input-file (performance-info-src pi))] [line-number (box 0)]) (λ () (define ln (read-line p)) (cond [(eof-object? ln) (close-input-port p) (values #f #f #f)] [else (set-box! line-number (+ 1 (unbox line-number))) (line->values ln (unbox line-number))])))) (in-producer go stop?)) (define (in-configurations/sample-data pi) (define pi* (for/list ([s (in-list (cdr (performance-info->sample* pi)))]) (performance-info%sample pi s))) (apply in-sequences (map in-configurations/karst-data pi*))) (define (stop? a b c) (and (eq? #f a) (eq? a b) (eq? b c))) ;; ============================================================================= (module+ test (require rackunit racket/runtime-path rackunit-abbrevs) (define-runtime-path karst-example "./test/karst-example_tab.gz") (define CI? (getenv "CI")) (test-case "benchmark->performance-info:example-data" (define karst-example-gunzip (gunzip/cd karst-example)) (define-values [num-configs configs/module* base-retic typed-retic] (scan-karst-file karst-example-gunzip)) (check-equal? num-configs 4) (check-equal? configs/module* '(2 2)) (check-equal? base-retic 10) (check-equal? typed-retic 20) (let ([pf (make-performance-info 'example #:src karst-example-gunzip #:num-configurations num-configs #:python-runtime base-retic #:untyped-retic-runtime base-retic #:typed-retic-runtime typed-retic)]) (check-equal? (num-configurations pf) 4) (check-equal? (min-overhead pf) 1/2) (check-equal? (max-overhead pf) 10) (check-equal? (mean-overhead pf) 27/8) (check-equal? (typed/retic-ratio pf) 2) (check-equal? ((deliverable 2) pf) 3) (check-equal? ((deliverable 10) pf) 4) (let () ;; filter-time* tests (check-equal? (filter-time* pf (λ (t) (= t 100))) (list 100)) (check-equal? (filter-time* pf (λ (t) (= t 5))) (list 5)) (check-equal? (filter-time* pf (λ (t) (< t 20))) (list 10 5)) (void)) (void))) (unless CI? (test-case "benchmark->performance-info:no-data" (check-pred performance-info? (benchmark->performance-info (->benchmark-info 'stats))))) ;; general correctness/sanity for a real program (unless CI? (let* ([bm (->benchmark-info 'Espionage)] [pf (benchmark->performance-info bm)]) (test-case "performance-info:spot-check" (check-true (performance-info? pf)) (check <= (performance-info-python-runtime pf) (performance-info-untyped-runtime pf)) (let* ([lo (min-overhead pf)] [hi (max-overhead pf)] [avg (mean-overhead pf)] [nc (num-configurations pf)] [d2 ((deliverable 2) pf)] [d3 ((deliverable 3) pf)] [dhi ((deliverable hi) pf)]) (check <= lo hi) (check <= lo avg) (check <= avg hi) (check <= d2 nc) (check <= d2 d3) (check-equal? dhi nc) (void))) (test-case "quick-stats:spot-check" (define quick-stats-str (let ([sp (open-output-string)]) (parameterize ([current-output-port sp]) (quick-performance-info 'Espionage)) (begin0 (get-output-string sp) (close-output-port sp)))) (define m (regexp-match #rx"avg overhead : ([.0-9]+)\n" quick-stats-str)) (check-true (pair? m)) (check-equal? (string->number (cadr m)) (mean-overhead pf)) (void)) )) (test-case "typed-configuration?" (check-true (typed-configuration? '(0 0 0))) (check-true (typed-configuration? '())) (check-false (typed-configuration? '(1 0))) (check-false (typed-configuration? '(9 8 7 7 9)))) (test-case "parse-line" (check-equal? (parse-line "0-0 4 [1, 2, 2, 3]") (list "0-0" "4" "[1, 2, 2, 3]")) (check-exn exn:fail:contract? (λ () (parse-line "")))) (test-case "string->num-types" (check-equal? (string->num-types "8") 8) (check-exn exn:fail:contract? (λ () (string->num-types "0.3"))) (check-exn exn:fail:contract? (λ () (string->num-types "#f")))) (test-case "string->time*" (check-equal? (string->time* "[1, 2, 3]") '(1 2 3)) (check-equal? (string->time* "[1.23, 4.554]") '(1.23 4.554)) (check-exn exn:fail:contract? (λ () (string->time* "[]"))) (check-exn exn:fail:contract? (λ () (string->time* "[1, -2]")))) (unless CI? (test-case "samples" (define (check-sample* bm-name) (define pi (benchmark->performance-info (->benchmark-info bm-name))) (define n+s* (performance-info->sample* pi)) (define num-configs (car n+s*)) (define s* (cdr n+s*)) (check-true (< 0 (length s*)) "positive number of sample files") (define count* (map count-karst-lines s*)) (check-true (apply = num-configs count*)) (void)) (check-sample* 'Espionage))) (test-case "count-types" (check-apply* count-types ['(0) '(2) ==> 1] ['(1) '(2) ==> 0] ['(0 9) '(128 32) ==> 10] ['(2 16) '(128 32) ==> 10] ['(5 9) '(128 32) ==> 8] ['(0) '(1) ==> 0] ['(6 18) '(128 32) ==> 8] ['(13 18) '(128 32) ==> 7] ['(14 17 30 2) '(16 64 32 4) ==> 7] ['(15 55 31 3) '(16 64 32 4) ==> 1] ['(3 12 21 0) '(16 64 32 4) ==> 10] ['(0 6 24 1) '(16 64 32 4) ==> 12] ['(0 6 8 1) '(16 64 32 4) ==> 13] ['(0 6 8 0) '(16 64 32 4) ==> 14])) (test-case "successors" (check-apply* successors ['(1) '(32) ==> '((0))] ['(2) '(32) ==> '((0))] ['(16) '(32) ==> '((0))] ['(3) '(32) ==> '((1) (2))])) (test-case "string-set" (check-apply* string-set ["hello" 0 #\H ==> "Hello"] ["hello" 4 #\H ==> "hellH"])) (unless CI? (define futen (->benchmark-info 'futen)) (define spectralnorm (->benchmark-info 'spectralnorm)) (define call_method (->benchmark-info 'call_method)) (define fannkuch (->benchmark-info 'fannkuch)) (test-case "better-with-types" (check-apply* count-better-with-types [(list fannkuch) ==> 0] [(list spectralnorm) ==> 13] [(list call_method) ==> 66] [(list futen spectralnorm fannkuch) ==> 23496])) (test-case "find-speedy-types" (check-equal? (find-speedy-types (list fannkuch)) (make-immutable-hash '((fannkuch . ())))) (let* ([x (find-speedy-types (list fannkuch spectralnorm))] [lex< (lambda (a b) (or (string<? (car a) (car b)) (and (string=? (car a) (car b)) (string<? (cdr a) (cdr b)))))] [lex-sort (lambda (x*) (sort x* lex<))]) (check-equal? (hash-count x) 2) (check-equal? (hash-ref x 'fannkuch) '()) (check-equal? (lex-sort (hash-ref x 'spectralnorm)) (lex-sort '(("10" . "2") ("23" . "21") ("26" . "10") ("26" . "18") ("28" . "12") ("28" . "20") ("30" . "14") ("30" . "22") ("24" . "8") ("24" . "16") ("16" . "0") ("18" . "2") ("20" . "4") ("12" . "4") ("8" . "0") ("14" . "6") ("22" . "6"))))))) (unless CI? (test-case "has-karst-data" (check-true (performance-info-has-karst-data? (->performance-info 'call_method))) (check-false (performance-info-has-karst-data? (->performance-info 'Evolution))))) (unless CI? (test-case "ratio-for-samples" (define (check-t/p-ratio bm-name) (define pi (->performance-info bm-name)) (void ;; assert that `pi` has ONLY sample data (when (performance-info-has-karst-data? pi) (raise-user-error 'check-t/p-ratio "benchmark '~a' has more than just sample data" bm-name)) (performance-info->sample* pi)) (check-pred typed/python-ratio pi) (void)) (check-t/p-ratio 'Evolution))) (unless CI? (test-case "in-configurations/karst" (define pi (->performance-info 'fannkuch)) (define x (for/list ([(a b c) (in-configurations pi)]) (list a b c))) (check-equal? (length x) 2) (check-equal? (caar x) '(0)) (check-equal? (caadr x) '(1)))) (unless CI? (test-case "in-configurations/sample-data" (define pi (->performance-info 'sample_fsm)) (define x (for/list ([(a b c) (in-configurations pi)]) (list a b c))) (check-equal? (length x) 1900) (check-equal? (caar x) '(13 0 2 7 7)))) (test-case "parse-typed-racket-filename" (check-equal? (parse-typed-racket-filename "nepls-2017/src/tr-data/mbta-v6.4-2016-07-25T06:46:31.rktd") "mbta")) ) ;; ----------------------------------------------------------------------------- (module+ main (require racket/cmdline) (define *fix-num-types?* (make-parameter #f)) (command-line #:program "perf-info" #:once-each [("--fix-num-types") "Reset the type counts in the given files" (*fix-num-types?* #t)] #:args benchmark-name* (cond [(null? benchmark-name*) (printf "usage: rp:perf-info <benchmark-name> ...~n")] [(*fix-num-types?*) (void (map fix-num-types benchmark-name*))] [(null? (cdr benchmark-name*)) (quick-performance-info (car benchmark-name*))] [else (for ([n (in-list benchmark-name*)]) (with-handlers ([exn:fail:contract? (λ (e) (printf "WARNING: failure processing '~a'~n" n))]) (quick-performance-info n)))])))
false
8756b1f5c4e12dff164555e0eee2d4966ca56456
23d78f4c06e9d61b7d90d8ebd035eb1958fe2348
/racket/types/infer-parser1.rkt
f35513e97ed3e81e7e52d3fccf99331eded0eae1
[ "Unlicense" ]
permissive
seckcoder/pl_research
e9f5dbce4f56f262081318e12abadd52c79d081d
79bb72a37d3862fb4afcf4e661ada27574db5644
refs/heads/master
2016-09-16T09:40:34.678436
2014-03-22T02:31:08
2014-03-22T02:31:08
null
0
0
null
null
null
null
UTF-8
Racket
false
false
1,656
rkt
infer-parser1.rkt
#lang racket (require eopl/datatype "../base/utils.rkt" "../cps/builtin.rkt") (provide (all-defined-out)) (define-datatype expression expression? (const-exp (cst const?)) (var-exp (var symbol?)) (quote-exp (sexp sexp?)) (op-exp (op op?) (rands (list-of expression?))) (call-exp (rator expression?) (rands (list-of expression?))) (if-exp (test expression?) (then expression?) (else expression?)) (lambda-exp (vars (list-of symbol?)) (body expression?)) (let-exp (var symbol?) (val-exp expression?) (body expression?)) (letrec-exp (p-names (list-of symbol?)) (procs (list-of expression?)) (body expression?)) ) (define (single-or-compound exps) (if (null? (cdr exps)) (car exps) `(begin ,@exps))) (define (parse sexp) (match sexp [(? const? x) (const-exp x)] [(? symbol? x) (var-exp x)] ; symbol [`(quote ,x) (quote-exp x)] ; builtin ops [(list (? op? op) params ...) (op-exp op (map parse params))] ; if [`(if ,test ,then ,else) (if-exp (parse test) (parse then) (parse else))] ; lambda [`(lambda (,params ...) ,body) (lambda-exp params (parse body))] [`(let ((,var ,val)) ,body) (let-exp var (parse val) (parse body))] [`(letrec ((,names ,procs) ...) ,body) (letrec-exp names (map parse procs) (parse body))] ; procedure call [(list rator rands ...) (call-exp (parse rator) (map parse rands))] ))
false
4707f3f1b854978a50a565486e6325c3504ea859
5bbc152058cea0c50b84216be04650fa8837a94b
/experimental/micro/suffixtree/typed/structs-node-up-split.rkt
5e3b9100b414bdeda8fd67ba94b2b19c36970e95
[]
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
1,243
rkt
structs-node-up-split.rkt
#lang typed/racket/base (provide node-up-split!) ;; ----------------------------------------------------------------------------- (require "data-node-adapted.rkt" "data-label-adapted.rkt" benchmark-util) (require/typed/check "label-sublabel.rkt" [sublabel (case-> (-> label Index label) (-> label Index Index label))]) (require/typed/check "structs-node-remove-child.rkt" [node-remove-child!(-> Node Node Void)]) (require/typed/check "structs-node-add-child.rkt" [node-add-child!(-> Node Node Void)]) ;; ============================================================================= ;; node-up-split!: node number -> node ;; Introduces a new node that goes between this node and its parent. (: node-up-split! (-> Node Index Node)) (define (node-up-split! nd offset) (let* ((label (node-up-label nd)) (pre-label (sublabel label 0 offset)) (post-label (sublabel label offset)) (parent (node-parent nd)) (new-node (node pre-label parent (list nd) #f))) (set-node-up-label! nd post-label) (unless parent (error "node-up-split!")) (node-remove-child! parent nd) (set-node-parent! nd new-node) (node-add-child! parent new-node) new-node))
false
7a643325ef067ddc337c5477f158dd5f865e9671
425f519523e5b040a1db8e4eaca7d0320ac55313
/src/for-traces/sumloop.rkt
5225b8da5ef0597540bcd78690001a284932d65e
[]
no_license
cderici/pycket-performance
f30390f7ec66ec61135eefd0e863e9f51131ca7b
8cac7d69b55381c07a90e919c4c25eb397b99442
refs/heads/master
2020-03-27T05:04:50.495274
2019-02-13T02:00:46
2019-02-13T02:00:53
145,992,592
2
0
null
null
null
null
UTF-8
Racket
false
false
680
rkt
sumloop.rkt
;;; SUMLOOP -- One of the Kernighan and Van Wyk benchmarks. #lang racket/base #;(require "both.rkt" "conf.rkt") (require "conf.rkt") (define outer 10) ;20) ;(define sumloop-iters 1) ;40) (define sum 0) (define (tail-rec-aux i n) (if (< i n) (begin (set! sum (+ sum 1)) (tail-rec-aux (+ i 1) n)) sum)) (define (tail-rec-loop n) (set! sum 0) (tail-rec-aux 0 n) sum) (define (do-loop n) (set! sum 0) (do ((i 0 (+ i 1))) ((>= i n) sum) (set! sum (+ sum 1)))) (define (main) (do ([i 1 (add1 i)]) ((> i outer) (void)) (time (do ([i 1 (add1 i)]) ((> i sumloop-iters) (void)) (do-loop 100000000))))) (main)
false
b55fd5490d925a9f0ae4c1c2c3ef0fe0c0c537d5
8755c03b48f6c26be60da0d41bd040ba52225edd
/recursive-types.rkt
330baddec5872e883e6e43ca88e8ddfd70a80beb
[ "MIT" ]
permissive
Gradual-Typing/toys
87bdbfc4bee0b4fca261928aea3b933fe7762c5b
82f08dd5437b0e983d8e27d3c7080beaf7351c27
refs/heads/master
2020-03-06T18:14:25.812850
2018-03-27T15:07:38
2018-03-27T15:07:38
127,003,362
1
0
null
null
null
null
UTF-8
Racket
false
false
34,169
rkt
recursive-types.rkt
#lang racket (module+ test (require rackunit)) ;; Interpreter for the GTLC + nats,tuples,recursive types (define base-types '(() Nat Bool)) (define (base-type? x) (set-member? base-types x)) (define type-keywords `(? μ -> . ,base-types)) (define (type-keyword? x) (set-member? type-keywords x)) (define (type-variable? x) (and (symbol? x) (not (type-keyword? x)))) (struct μ ([ref #:mutable]) #:transparent) (define-syntax-rule (-μ x t/c) (let ([x (μ (void))]) (set-μ-ref! x t/c) x)) ;; Type Syntax (define (type? x [valid (set)] [pending (set)] [seen (set)]) (define (rec/pending x v s) (type? x valid (set-add pending v) (set-add seen s))) (define (rec/valid x) (type? x (set-union valid pending) (set) seen)) (match x [`(μ ,(? type-variable? x0) ,x1) (rec/pending x1 x0 x)] [(? type-variable? x) (set-member? valid x)] ['Nat #t] [(or (? base-type?) '? `#(,(? rec/valid) ,(? rec/valid)) `(,(? rec/valid) -> ,(? rec/valid))) #t] [(μ x0) (or (set-member? seen x) ;; Here we clear the other two sets to "enforce" ;; once we are using refs you can't use type-variables (type? x0 (set) (set) (set-add x)))])) (define (type->cyclic-type t) (let c ([t t] [env (hash)]) (match t [(or (? base-type?) '?) t] [`#(,t0 ,t1) `#(,(c t0 env) ,(c t1 env))] [`(,t0 -> ,t1) `(,(c t0 env) -> ,(c t1 env))] [(? type-variable? X) (hash-ref env X)] [`(μ ,X ,t0) (-μ x (c t0 (hash-set env X x)))]))) ;; substitute type s for variable x in type t (define (type-subst t x s) (let rec ([t t]) (match t [(? type-variable? v) #:when (eq? v x) s] [(vector t0 t1) (vector (rec t0) (rec t1))] [`(,t0 -> ,t1) `(,(rec t0) -> ,(rec t1))] [`(μ ,v ,t0) #:when (not (eq? v x)) `(μ ,v ,(rec t0))] [_ t]))) (define (unfold t) (match t [`(μ ,x ,t0) (type-subst t0 x t)] [(μ t0) (error 'unfold "can't be used on cyclic types")] [_ (error 'fold "can only be used on recursive-types")])) (module+ test (define-syntax-rule (t-type? t) (test-pred (~a 't) type? t)) (t-type? 'Nat) (define natXnat #(Nat Nat)) (t-type? natXnat) (define nat->nat '(Nat -> Nat)) (t-type? nat->nat) (define Hungry-Type '(μ H (Nat -> H))) (t-type? Hungry-Type) (define Stream-Type '(μ S #(Nat (() -> S)))) (t-type? Stream-Type) (define Other-Stream-Type '(μ S2 (() -> #(Nat S2)))) (t-type? Other-Stream-Type) (define Dyn-Other-Stream-Type '(μ S2 (() -> #(? S2)))) (t-type? Dyn-Other-Stream-Type)) (define (subtype-aux subtype?) ;; Defined this way to easily override the behavior (lambda (Γ A S T) ;; Γ (Gamma) is a lexical substitution of mu bindings ;; A is a cache of previous subtyping queries ;; subtype-aux returns a substitution if S is a subtype of T ;; otherwise it returns #f (match* (S T) ;; If A is fails then we have already failed [(_ _) #:when (not A) #f] ;; If A contains the pair then we have already checked that ;; S is a subtype of T [(_ _) #:when (set-member? A (cons S T)) A] [(T T) A] [((? symbol? X) _) (=> continue) (define v? (hash-ref Γ X)) (cond [v? (subtype? Γ A v? T)] [else (continue)])] [(_ (? symbol? X)) (=> continue) (define v? (hash-ref Γ X)) (cond [v? (subtype? Γ A S v?)] [else (continue)])] [((vector S1 S2) (vector T1 T2)) ;; Covarient for tuples (define A0 (subtype? Γ A S1 T1)) (subtype? Γ A0 S2 T2)] [(`(,S1 -> ,S2) `(,T1 -> ,T2)) ;; Contravarient for functions (define A0 (subtype? Γ A T1 S1)) (subtype? Γ A0 S2 T2)] [(_ _) (define A0 (set-add A (cons S T))) (match* (S T) [(`(μ ,X ,S1) T) (subtype? (hash-set Γ X S) A0 S1 T)] [(S `(μ ,X ,T1)) (subtype? (hash-set Γ X T) A0 S T1)] [((μ S0) T) (subtype? Γ A0 S0 T)] [(S (μ T0)) (subtype? Γ A0 S T0)] [(_ _) #f])]))) (define (subtype? S T) (define (st? Γ A S T) ((subtype-aux st?) Γ A S T)) (st? (hash) (set) S T)) (define (consistent-subtype? S T) (define (st? Γ A S T) (match* (S T) [('? _) A] [(_ '?) A] [(_ _) ((subtype-aux st?) Γ A S T)])) (st? (hash) (set) S T)) (module+ test (define-syntax-rule (t-st S T) (let ([s S] [t T]) (unless (type? s) (error 'todo)) (unless (type? t) (error 'todo)) (test-not-false (~a '(subtype? S T)) (subtype? s t)))) (define-syntax-rule (t-cst S T) (let ([s S] [t T]) (unless (type? s) (error 'todo)) (unless (type? t) (error 'todo)) (test-not-false (~a '(consistent-subtype? S T)) (consistent-subtype? s t)))) (t-st 'Nat 'Nat) (t-cst 'Nat 'Nat) (t-st '(μ X #(Nat X)) '(μ Y #(Nat Y))) (t-cst '(μ X #(? X)) '(μ Y #(Nat Y))) (t-cst Other-Stream-Type Dyn-Other-Stream-Type) (t-cst Dyn-Other-Stream-Type Other-Stream-Type)) (define-syntax-rule (match? e p ...) (match e [p #t] ... [_ #f])) (define (keyword? x) (set-member? keywords x)) (define (variable? x) (and (symbol? x) (not (keyword? x)))) ;; Syntax (define (expr? x) (match? x '() `(λ (,(? variable?) : ,(? type?)) : ,(? type?) ,(? expr?)) `(let ([,(? variable?) ,(? expr?)]) ,(? expr?)) (? variable?) `(,(? expr?) ,(? expr?)) (? exact-nonnegative-integer?) `(+ ,(? expr?) ,(? expr?)) `(- ,(? expr?) ,(? expr?)) `(= ,(? expr?) ,(? expr?)) `(? boolean?) `(if ,(? expr?) ,(? expr?) ,(? expr?)) (? vector? (app vector-length 2)) `(,(? expr?) . ,(or 0 1)) `(ann ,(? expr?) ,(? type?)))) ;; A program is a series of definitions followed by an expression (define (prgm? x) (match? x `((define ,(? variable?) : ,(? type?) ,(? expr?)) ... ,(? expr?)))) (define-syntax-rule (invalid expect got) (error 'invalid-syntax "expected ~a got ~a" expect got)) (define (assert-prgm! x) (define (assert-variable! x) (unless (variable? x) (invalid 'symbol x))) (define (assert-type! x) (unless (type? x) (invalid 'type x))) (define (assert-expr! x) (match x ['() (void)] [`(λ (,x : ,t0) : ,t1 ,e) (assert-variable! x) (assert-type! t0) (assert-type! t1) (assert-expr! e)] [`(λ (,x : ,t0) ,e) (assert-variable! x) (assert-type! t0) (assert-expr! e)] [`(let ([,x ,e0]) ,e1) (assert-variable! x) (assert-expr! e0) (assert-expr! e1)] [(? variable?) (void)] [`(,e0 ,e1) (assert-expr! e0) (assert-expr! e1)] [(? exact-nonnegative-integer?) (void)] [`(,(? binop?) ,e0 ,e1) (assert-expr! e0) (assert-expr! e1)] [`(? boolean?) (void)] [`(if ,e0 ,e1 ,e2) (assert-expr! e0) (assert-expr! e1) (assert-expr! e2)] [`#(,e0 ,e1) (assert-expr! e0) (assert-expr! e1)] [`(,e . ,(or 0 1)) (assert-expr! e)] [`(ann ,e ,t) (assert-expr! e) (assert-type! t)] [_ (invalid 'expression x)])) (define (assert-define! x) (match x [`(define ,s : ,t ,e) (unless (symbol? s) (invalid 'symbol s)) (unless (type? t) (invalid 'type t)) (assert-expr! e)] [_ (invalid 'define x)])) (match x [`(,d* ... ,e) (for ([d d*]) (assert-define! d)) (unless (expr? e) (invalid 'expression e))] [_ (invalid 'program x)])) (module+ test (define e0 `(+ 40 (+ 1 1))) (test-pred "expression 0" expr? e0) (define e0.5 `(+ x 1)) (test-pred "expression 0.5" expr? e0.5) (define e1 `(λ (x : Nat) : Nat ,e0.5)) (test-pred "expression 1" expr? e1) (define add1-41 '(add1 41)) (test-pred "add1 to 41" expr? add1-41) (define p0 `(,e0)) (test-pred "program 0" prgm? p0) (define p1 `((define add1 : ,nat->nat ,e1) ,add1-41)) (test-pred "program 1" prgm? p1) (define fst-ones '((ones ()) . 0)) (test-pred "first of ones" expr? fst-ones) (define oneXones #(1 ones)) (test-pred "1 and ones" expr? oneXones) (define ones-lambda `(λ (_ : ()) : (μ S #(Nat (() -> S))) #(1 ones))) (test-pred "ones lambda" expr? ones-lambda) (define p2 `((define ones : ,Other-Stream-Type ,ones-lambda) ,fst-ones)) (test-pred "program 2" prgm? p2) (define stream-ref-base `((s ()) . 0)) (test-pred "sr base" expr? stream-ref-base) (define stream-ref-ind `((stream-ref ((s ()) . 1)) (- x 1))) (test-pred "sr ind" expr? stream-ref-ind) (define stream-ref-cond `(= x 0)) (test-pred "sr cond" expr? stream-ref-cond) (define stream-ref-if `(if (= x 0) ((s ()) . 0) ((stream-ref ((s ()) . 1)) (- x 1)))) (test-pred "sr if" expr? stream-ref-if) (define stream-ref-body `(λ (x : Nat) : ? ,stream-ref-if)) (test-pred "sr body" expr? stream-ref-body) (define stream-ref-lam `(λ (s : ,Dyn-Other-Stream-Type) : (Nat -> ?) ,stream-ref-body)) (test-pred "expression stream-ref" expr? stream-ref-lam) (define p3-main `(+ ((stream-ref dones) 4) 41)) (test-pred "p3 main" expr? p3-main) (define p3 `((define ones : (μ S2 (() -> #(Nat S2))) (λ (_ : ()) : (μ S #(Nat (() -> S))) #(1 ones))) (define dones : (μ S2 (() -> #(? S2))) ones) (define stream-ref : ((μ S2 (() -> #(? S2))) -> (Nat -> ?)) (λ (s : (μ S2 (() -> #(? S2)))) : (Nat -> ?) (λ (x : Nat) : ? (if (= x 0) ((s ()) . 0) ((stream-ref ((s ()) . 1)) (- x 1)))))) (+ ((stream-ref dones) 4) 41))) (test-pred "program 3" prgm? p3)) (define (unique? xs) (not (check-duplicates xs))) (define ((error-th x)) (error 'type-check "unbound variable: ~a" x)) (define-syntax (raise-not-consistent-subtype stx) (syntax-case stx () [(_ e s t) #'(error 'type-check "~a : ~a ¬⊆ ~a" e s t)] [(_ s t) #'(error 'type-check "~a ¬⊂ ~a" s t)])) (define (insert-cast e t1 t2) (if (equal? t1 t2) e `(cast ,e ,t1 ,t2))) (define (sub n m) (define p (- n m)) (if (< p 0) 0 p)) (define binops (make-immutable-hash `((+ (Nat Nat -> Nat) ,+) (- (Nat Nat -> Nat) ,sub) (= (Nat Nat -> Bool) ,=) (% (Nat Nat -> Nat) ,modulo)))) (define keywords '(λ let . (hash-keys binops))) (define (truthy? x) (not (not x))) (define (binop? x) (truthy? (hash-ref binops x #f))) (define (binop-type x) (define entry? (hash-ref binops x)) (unless entry? (error 'binop-type "~a not found" x)) (list-ref entry? 0)) (define (binop->racket x) (define entry? (hash-ref binops x)) (unless entry? (error 'binop->racket "~a not found" x)) (list-ref entry? 1)) (define (assert-consistent-subtype! e t1 t2) (unless (consistent-subtype? t1 t2) (raise-not-consistent-subtype e t1 t2))) (define (join S T [env (hash)]) (match* (S T) [(t t) t] [('? t) t] [(t '?) t] ;; Don't Unfold Recursive types if you don't have to [(`(μ ,X ,S0) `(μ ,Y ,T0)) `(μ ,X ,(join S0 T0 (hash-set env X Y)))] [((? type-variable? X) (? type-variable? Y)) (unless (eq? X (hash-ref env Y)) (raise-not-consistent-subtype X Y)) X] [(`(μ ,_ ,_) _) (join (unfold S) T)] [(_ `(μ ,_ ,_)) (join S (unfold T))] [(`(,S0 -> ,S1) `(,T0 -> ,T1)) `(,(join S0 T0) -> ,(join S1 T1))] [(`#(,S0 ,S1) `#(,T0 ,T1)) `#(,(join S0 T0) ,(join S1 T1))] [(_ _) (raise-not-consistent-subtype S T)])) ;; type-synthesis : env, expr -> cc-expr, type (define (synth Γ e) (let rec ([e e]) (match e [(? variable? x) (define tₓ (hash-ref Γ x (error-th x))) (values x tₓ)] [`(λ (,x : ,tₓ) : ,tₘ ,m) (define m0 (check (hash-set Γ x tₓ) tₘ m)) (values `(λ (,x : ,tₓ) : ,tₘ ,m0) `(,tₓ -> ,tₘ))] [`(λ (,x : ,tₓ) ,m) (define-values (m0 tₘ) (synth (hash-set Γ x tₓ) m)) (values `(λ (,x : ,tₓ) : ,tₘ ,m0) `(,tₓ -> ,tₘ))] [`(let ([,x ,eₓ]) ,m) (define-values (eₑ tₓ) (synth Γ eₓ)) (define-values (eₘ tₘ) (synth (hash-set Γ x tₓ) m)) (values `(let ([,x ,eₑ]) ,eₘ) tₘ)] [`(,p ,a) (define-values (p0 tₚ) (rec p)) (assert-consistent-subtype! p tₚ '(? -> ?)) (match-define `(,tₐ -> ,tᵣ) (let loop ([tₚ tₚ]) (match tₚ [`(,_ -> ,_) tₚ] ['? `(? -> ?)] [`(μ ,x ,t) (loop (unfold tₚ))]))) (define p1 (insert-cast p0 tₚ `(,tₐ -> ,tᵣ))) (define a0 (check Γ tₐ a)) (values `(,p1 ,a0) tᵣ)] [(? exact-nonnegative-integer? n) (values n 'Nat)] [(list (? binop? op) a b) (match-define `(,A ,B -> ,C) (binop-type op)) (define a0 (check Γ A a)) (define b0 (check Γ B b)) (values `(+ ,a0 ,b0) C)] [(? boolean? b) (values b 'Bool)] [`(if ,(app (curry check Γ 'Bool) c) ,(app rec e0 t0) ,(app rec e1 t1)) (define t2 (join t0 t1)) (define e2 (insert-cast e0 t0 t2)) (define e3 (insert-cast e1 t1 t2)) (values `(if ,c ,e2 ,e3) t2)] [`#(,(app rec e0 t0) ,(app rec e1 t1)) (values `#(,e0 ,e1) `#(,t0 ,t1))] [(cons m (and i (or 0 1))) (define-values (m0 tₘ) (rec m)) (assert-consistent-subtype! m tₘ #(? ?)) (match-define tᵥ (let loop ([tₘ tₘ]) (match tₘ [`#(,_ ,_) tₘ] ['? #(? ?)] [`(μ ,x ,t) (loop (unfold x t))]))) (define tᵢ (vector-ref tᵥ i)) (define m1 (insert-cast m0 tₘ tᵥ)) (values `(,m1 . ,i) tᵢ)] ['() (values '() '())] [`(ann ,e ,t) (values (check Γ t e) t)]))) ;; type-check : env, expr, type -> expr (define (check Γ t e) (define-values (e0 tₑ) (synth Γ e)) (assert-consistent-subtype! e tₑ t) (insert-cast e0 tₑ t)) (define (type-check prgm) (assert-prgm! prgm) (match prgm [`((define ,s* : ,t* ,e*) ... ,e) (unless (unique? s*) (error 'type-check-prgm "duplicate binding ~a" (check-duplicates s*))) (for ([t t*]) (type? t)) (define rec-env (make-immutable-hash (map cons s* t*))) (define d*0 (for/list ([s s*] [t t*] [e e*]) `(define ,s : ,t ,(check rec-env t e)))) (define-values (e0 _) (synth rec-env e)) (append d*0 `(,e0))])) (module+ test (check-not-exn (lambda () (type-check p1))) (check-not-exn (lambda () (type-check p2))) (check-not-exn (lambda () (type-check p3)))) (define ((env-lookup tl-env) env x) ;; Monadic use of or (or (hash-ref env x #f) (hash-ref tl-env x #f) (error 'undefined "~a" x))) (define (cast v s t) (match* (s t) [(t t) v] [('? t) (cast (car v) (cdr v) t)] [(s '?) (cons v s)] [(`(μ ,_ ,_) t) (cast v (unfold s) t)] [(s `(μ ,_ ,_)) (cast v s (unfold t))] [((μ s0) t) (cast v s0 t)] [(s (μ t0)) (cast v s t0)] [(`(,s1 -> ,s2) `(,t1 -> ,t2)) (lambda (x) (cast (v (cast x t1 s1)) s2 t2))] [(`#(,s1 ,s2) `#(,t1 ,t2)) (match-define `#(,v1 ,v2) v) `#(,(cast v1 s1 t1) ,(cast v2 s2 t2))])) (define ((eval cast coerce) e tl-env) (define lookup (env-lookup tl-env)) (let eval ([e e] [env (hash)]) (match e [(? variable? x) (lookup env x)] [(and v (or (? boolean?) (? number?) '())) v] [`(λ (,x : ,_) : ,_ ,m) (λ (a) (eval m (hash-set env x a)))] [`(let ([,x ,eₓ]) ,m) (let ([v (eval eₓ env)]) (eval m (hash-set env x v)))] [`(,p ,a) ((eval p env) (eval a env))] [(list (? binop? op) a b) ((binop->racket op) (eval a env) (eval b env))] [`(if ,c ,e0 ,e1) (if (eval c env) (eval e0 env) (eval e1 env))] [`#(,e0 ,e1) (vector (eval e0 env) (eval e1 env))] [(cons m (and i (or 0 1))) (vector-ref (eval m env) i)] [`(cast ,e ,t1 ,t2) (cast (eval e env) t1 t2)] [`(coerce ,e ,c) (coerce (eval e env) c)]))) (define ((evaluate type-check compile eval) prgm) (match (compile (type-check prgm)) [`((define ,v* : ,_ ,e*) ... ,e) (define tl-env (make-hash '())) (for ([v v*] [e e*]) (hash-set! tl-env v (eval e tl-env))) (eval e tl-env)] [`(,d ... ,e) (for/list ([d d]) (unless (match? d `(define ,v : ,_ ,e)) (error 'internal-error "~a produced by type-checker" d)))])) (define ((unexpected x) . a) (error 'unexpected "~a" `(,x . ,a))) (define ((fold-expr f-expr) expr) (let m ([e expr]) (match e [(and v (or (? variable?) (? boolean?) (? number?) '())) (f-expr v)] [`(λ (,x : ,t0) : ,t1 ,e0) (f-expr `(λ (,x : ,t0) : ,t1 ,(m e0)))] [`(,e0 ,e1) (f-expr `(,(m e0) ,(m e1)))] [`(,(? binop? op) ,e0 ,e1) (f-expr `(,op ,(m e0) ,(m e1)))] [`(if ,e0 ,e1 ,e2) (f-expr `(if ,(m e0) ,(m e1) ,(m e2)))] [`#(,e0 ,e1) (f-expr `#(,(m e0) ,(m e1)))] [(cons e0 (and i (or 0 1))) (cons (m e0) i)] [`(cast ,e0 ,t0 ,t1) (f-expr `(cast ,(m e0) ,t0 ,t1))]))) (define ((map-prgm f-expr f-type) prgm) (match-define `((define ,s* : ,t* ,e*) ... ,e) prgm) (append (for/list ([s s*] [t t*] [e e*]) `(define ,s : ,(f-type t) ,(f-expr e))) (list (f-expr e)))) (define prgm-identity values) (define (compile-expr-types f-type) (fold-expr (lambda (e) (match e [`(cast ,e0 ,t0 ,t1) `(cast ,e0 ,(f-type t0) ,(f-type t1))] [`(λ (,x : ,t0) : ,t1 ,e0) `(λ (,x : ,(f-type t0)) : ,(f-type t1) ,e0)] [e e])))) (define (compile-prgm-types f-type) (map-prgm (compile-expr-types f-type) f-type)) (module+ test (define types->etypes (compile-prgm-types type->cyclic-type)) (define evaluate/cast (evaluate type-check prgm-identity (eval cast (unexpected 'coerce)))) (define evaluate/ecast (evaluate type-check types->etypes (eval cast (unexpected 'coerce)))) (test-not-exn "eval p3 cast" (thunk (evaluate/cast p3))) (test-not-exn "eval p3 ecast" (thunk (evaluate/ecast p3)))) ;; <(μ X #(Int X) => (μ Y #(Dyn X))> = (μ X #(Int! X)) ;; <(μ X #(Int X)) => #(Dyn (μ X #(Int X)))> = unfold ; #(Int! id) ;; (μ X #(Int X)):#(Int (μ X #(Int X)))|#(Int (μ X #(Int X))) #(Dyn (μ X #(Int X))) ;; <#(Dyn (μ X #(Int X))) => (μ X #(Int X))> = #(Int? id); fold ;; <(μ X (μ Y #(X Y))) => (μ X (μ Y #(? Y)))> = ... ;; (μ X (μ Y #((μ X (μ Y #(? Y)))? Y) ;; (define (make-coercion s t) (define-values (c _) (let mc ([s s] [t t] [env (hash)]) ;; This should be possible to only perform at ;; variable nodes once we go to graphs (define p (cons s t)) (define ref? (hash-ref env p #f)) (match ref? [(box _) (unless (unbox ref?) (set-box! ref? (gensym))) (values (unbox ref?) #t)] [(μ _) (set-μ-ref! ref? #t) (values ref? #t)] [_ (match* (s t) [(t t) (values `id #t)] [('? t) (values `(Seq (? ,t) id) #f)] [(t '?) (values `(Seq id (! ,t)) #f)] [(`(μ ,X ,s0) t) (define ref (box #f)) (define env0 (hash-set env p ref)) (define s1 (unfold s)) (define-values (r id?) (mc s1 t env0)) (define used-sym? (unbox ref)) (cond [id? (values 'id #t)] [used-sym? (values `(μ ,used-sym? ,r) #f)] [else (values r #f)])] [(s `(μ ,Y ,t0)) (define ref (box #f)) (define env0 (hash-set env p ref)) (define t1 (unfold t)) (define-values (r id?) (mc s t1 env0)) (define used-sym? (unbox ref)) (cond [id? (values 'id #t)] [used-sym? (values `(μ ,used-sym? ,r) #f)] [else (values r #f)])] [((μ s0) t) (define var/mu (μ #f)) (define env0 (hash-set env p var/mu)) (define-values (r id?) (mc s0 t env0)) (define used? (μ-ref var/mu)) (cond [id? (values 'id #t)] [used? (set-μ-ref! var/mu r) (values var/mu #f)] [else (values r #f)])] [(s (μ t0)) (define var/mu (μ #f)) (define env0 (hash-set env p var/mu)) (define-values (r id?) (mc s t0 env0)) (define used? (μ-ref var/mu)) (cond [id? (values 'id #t)] [used? (set-μ-ref! var/mu r) (values var/mu #f)] [else (values r #f)])] [(`(,s0 -> ,s1) `(,t0 -> ,t1)) (define-values (r0 i0?) (mc t0 s0 env)) (define-values (r1 i1?) (mc s1 t1 env)) (values (match* (r0 r1) [('id 'id) 'id] [(_ _) `(,r0 -> ,r1)]) (and i0? i1?))] [(`#(,s0 ,s1) `#(,t0 ,t1)) (define-values (r0 i0?) (mc s0 t0 env)) (define-values (r1 i1?) (mc s1 t1 env)) (values (match* (r0 r1) [('id 'id) 'id] [(_ _) `#(,r0 ,r1)]) (and i0? i1?))] [(other wise) (printf "fail:\n~a\n~a\n~a\n" s t env) (values 'fail #f)])]))) c) (define (coercion-α=? x y) (let rec ([x x] [y y] [ex (hash)] [ey (hash)]) (match* (x y) [(x x) #t] [(`(μ ,x ,x0) `(μ ,y ,x1)) (define g (gensym)) (rec x0 x1 (hash-set ex x g) (hash-set ey y g))] [(`(,x0 -> ,x1) `(,y0 -> ,y1)) (and (rec x0 y0 ex ey) (rec x1 y1 ex ey))] [(`#(,x0 ,x1) `#(,y0 ,y1)) (and (rec x0 y0 ex ey) (rec x1 y1 ex ey))] [(`(Seq ,x0 ,x1) `(Seq ,y0 ,y1)) (and (rec x0 y0 ex ey) (rec x1 y1 ex ey))] [(x y) (define x? (hash-ref ex x #f)) (define y? (hash-ref ey y #f)) (and x? y? (eq? x? y?))]))) (define ((check-α=? x) y) (coercion-α=? x y)) (module+ test (test-true "sc 1" (coercion-α=? 'Nat 'Nat)) (test-true "sc 2" (coercion-α=? '(μ x x) '(μ y y))) (test-true "sc 3" (coercion-α=? '(μ x #((? Int) x)) '(μ y #((? Int) y)))) (define sc4 (let ([x (μ (void))]) (set-μ-ref! x x))) (define sc5 (let ([x (μ (void))]) (set-μ-ref! x x))) (test-true "sc 4 5" (coercion-α=? sc4 sc5))) (module+ test (test-equal? "make-crcn sanity" (make-coercion 'Nat 'Nat) 'id) (test-pred "make-crcn mu" (check-α=? '(μ X #((Seq (? Int) id) X))) (make-coercion '(μ X #(? X)) '(μ Y #(Int Y)))) (test-pred "make-crcn mu cyclic" (check-α=? (-μ X `#((Seq (? Int) id) ,X))) (make-coercion (-μ X `#(? ,X)) (-μ Y `#(Int ,Y)))) (test-pred "make-crcn fold" (check-α=? 'id) (make-coercion `#(Int ,(-μ X `#(Int ,X))) (-μ Y `#(Int ,Y)))) (test-pred "make-crcn unfold" (check-α=? 'id) (make-coercion (-μ Y `#(Int ,Y)) `#(Int ,(-μ X `#(Int ,X))))) (test-pred "make-crcn project fold" (check-α=? '#((Seq (? Int) id) id)) (make-coercion '#(? (μ X #(Int X))) '(μ Y #(Int Y)))) (test-pred "make-crcn inject unfold" (check-α=? '#((Seq id (! Int)) id)) (make-coercion '(μ Y #(Int Y)) '#(? (μ X #(Int X))))) (test-pred "make-crcn project unfold stream" (check-α=? '#((Seq (? Int) id) id)) (make-coercion '(μ Y #(? (() -> Y))) '#(Int (() -> (μ X #(? (() -> X))))))) (test-pred "make-crcn project unfold stream" (check-α=? '#(id (id -> (μ Y #((Seq (? Int) id) (id -> Y)))))) (make-coercion '(μ Y #(? (() -> Y))) '#(? (() -> (μ X #(Int (() -> X)))))))) (define ((cast->coercion compile-type) prgm) (define (c->c e) (match e [(and v (or (? variable?) (? boolean?) (? number?) '())) v] [`(λ (,x : ,t0) : ,t1 ,m) `(λ (,x : ,(compile-type t0)) : ,(compile-type t1) ,(c->c m))] [`(,p ,a) `(,(c->c p) ,(c->c a))] [`(,(? binop? op) ,a ,b) `(,op ,(c->c a) ,(c->c b))] [`(if ,c ,e0 ,e1) `(if ,(c->c c) ,(c->c e0) ,(c->c e1))] [`#(,e0 ,e1) `#(,(c->c e0) ,(c->c e1))] [(cons m (and i (or 0 1))) (cons (c->c m) i)] [`(cast ,e ,t1 ,t2) `(coerce ,(c->c e) ,(make-coercion (compile-type t1) (compile-type t2)))])) (match-define `((define ,s* : ,t* ,e*) ... ,e) prgm) (append (for/list ([s s*] [t t*] [e e*]) `(define ,s : ,(compile-type t) ,(c->c e))) (list (c->c e)))) ;; Approaches ignore coercions in casts an (define (coercion? x) (match? x `id `(? ,(? type?)) `(! ,(? type?)) `#(,(? coercion?) ,(? coercion?)) `(,(? coercion?) -> ,(? coercion?)))) (struct hybrid-proxy (closure coercion) #:transparent #:property prop:procedure (lambda (p a) (define f (hybrid-proxy-closure p)) (match-define `(,c0 -> ,c1) (hybrid-proxy-coercion p)) (apply-coercion (f (apply-coercion a c0)) c1))) (define (apply-coercion v c) (define ac apply-coercion) (define mc make-coercion) (define cc compose-coercions) (match c [`id v] [`(Seq ,c0 ,c1) (ac (ac v c0) c1)] [`(? ,t1) (match-define `(,v0 : ,t0) v) (ac v0 (mc t0 t1))] [`(! ,t0) `(,v : ,t0)] [`#(,c0 ,c1) (match-define `#(,v0 ,v1) v) `#(,(ac v0 c0) ,(ac v1 c1))] [`(,_ -> ,_) (cond [(hybrid-proxy? v) (define v0 (hybrid-proxy-closure v)) (define c0 (hybrid-proxy-coercion v)) (define c1 (cc c0 c)) (ac v0 c1)] [else (hybrid-proxy v c)])] [`(μ ,X ,c0) (ac v (unfold c))] [(μ c0) (ac v c0)])) (define (compose-coercions c d) (define mc make-coercion) ;; id? variables means "does the computational content ;; a variable so far amount to the id coercion?" ;; Precondition: d-id? <-> d == id ;; Postcondition: ret-id? -> ret == id (define-values (ret ret-id?) (let cc ([c c] [d d] [d-id? (eq? d 'id)] [e (hash)]) (define p (cons c d)) (define ref? (hash-ref e p #f)) (match ref? [(μ _) (set-μ-ref! ref? #t) (values ref? #t)] [(box _) (unless (unbox ref?) (set-box! ref? (gensym))) (values (unbox ref?) #t)] [_ (match* (c d) [(`(Seq ,g (! ,t0)) `(Seq (? ,t1) ,i)) (define i0 (mc t0 t1)) (define-values (c0 c0-id?) (cc i0 i (eq? i 'id) e)) ;; Need to reason through all the T => G => T compositions ;; to figure out if adding the simple rule ;; (cc id id) => id ;; is the same as maintaining d-id? through (define-values (c1 c1-id?) (cc g c0 c0-id? e)) (values c1 c1-id?)] [(`(Seq (? ,t1) ,i) d) (define-values (c1 _) (cc i d d-id? e)) (values `(Seq (? ,t1) ,c1) #f)] ;; The next case 'g' has to come after this case ;; to rule out it actually being a 'c' [(g `fail) (values `fail #f)] [(g0 `(Seq ,g1 (! ,t0))) (define-values (c1 _) (cc g0 g1 `(eq? g1 'id) e)) (values `(Seq ,c1 (! ,t0)) #f)] [(`fail c) (values `fail #f)] [(`id d) ;; The d-id? has been maintained so that if this ;; case is reached we already know if d can be id? (values d d-id?)] [(`(,c0 -> ,c1) `(,d0 -> ,d1)) (define-values (c2 i1) (cc d0 c0 (eq? c0 'id) e)) (define-values (c3 i2) (cc c1 d1 (eq? d1 'id) e)) (match* (c2 c3) [('id 'id) (values 'id #t)] [(c2 c3) (values `(,c2 -> ,c3) (and i1 i2))])] [(`#(,c0 ,c1) `#(,d0 ,d1)) (define-values (c2 i1) (cc c0 d0 (eq? d0 'id) e)) (define-values (c3 i2) (cc c1 d1 (eq? d1 'id) e)) (match* (c2 c3) [('id 'id) (values 'id #t)] [(c2 c3) (values `#(,c2 ,c3) (and i1 i2))])] [(`(μ ,x ,_) d) (define used? (box #f)) (define e0 (hash-set e p used?)) (define c0 (unfold c)) (define-values (c1 id?) (cc c0 d d-id? e0)) (define used-sym? (unbox used?)) (cond [id? (values 'id #t)] [used-sym? (values `(μ ,used-sym? ,c1) #f)] [else (values c1 #f)])] [(c `(μ ,y ,_)) (define used? (box #f)) (define e0 (hash-set e p used?)) (define d0 (unfold d)) ;; if d-id? then d had computational content and ;; therefore d0 has computational content (define-values (d1 id?) (cc c d0 d-id? e0)) (define used-sym? (unbox used?)) (cond [id? (values 'id #t)] [used-sym? (values `(μ ,used-sym? ,d1) #f)] [else (values d1 #f)])] [((μ c0) d) (define var/mu (μ #f)) (define e0 (hash-set e p var/mu)) (define-values (c1 id?) (cc c0 d d-id? e0)) (define used? (μ-ref var/mu)) (cond [id? (values 'id #t)] [used? (set-μ-ref! var/mu c1) (values var/mu #f)] [else (values c1 #f)])] [(c (μ d0)) (define var/mu (μ #f)) (define e0 (hash-set e p var/mu)) (define-values (d1 id?) (cc c d0 #f e0)) (define used? (μ-ref var/mu)) (cond [id? (values 'id #t)] [used? (set-μ-ref! var/mu d1) (values var/mu #f)] [else (values d1 #f)])] [(_ _) (values 'fail #f)])]))) ret) (module+ test (test-pred "compose sanity" (check-α=? 'id) (compose-coercions 'id 'id)) (test-pred "compose sanity" (check-α=? 'id) (compose-coercions '(Seq id (! Nat)) '(Seq (? Nat) id))) (test-pred "compose bigger 2" (check-α=? #((Seq (? Int) id) id)) (compose-coercions '#(id (μ x #((Seq id (! Int)) x))) '(μ x #((Seq (? Int) id) x)))) #; (test-pred "compose bigger" (check-α=? #((Seq (? Nat) id) (μ x #((Seq (? Nat) id) x)))) (compose-coercions #(id (μ x #((Seq (? Nat) (Seq id (! Nat))) x))) '(μ x #((Seq (? Int) id) x)))) (test-pred "compose bigger 1" (check-α=? 'id) (compose-coercions '(μ x #((Seq id (! Int)) x)) '(μ x #((Seq (? Int) id) x))))) (module+ test (define type-identity values) (define cast->crcn (cast->coercion type-identity)) (define cast->ecrcn (cast->coercion type->cyclic-type)) (define evaluate/crcn (evaluate type-check cast->crcn (eval (unexpected 'cast) apply-coercion))) (define evaluate/ecrcn (evaluate type-check cast->ecrcn (eval (unexpected 'cast) apply-coercion))) (test-not-exn "eval p3 crcn" (thunk (evaluate/crcn p3))) (test-not-exn "eval p3 ecrcn" (thunk (evaluate/ecrcn p3))) ;; Build a value that we never use (define f (lambda (a) (error 'undefined))) (define c1 (make-coercion (-μ x `(() -> #(Int ,x))) (-μ y `(() -> #(? ,y))))) (define g (apply-coercion f c1)) (define c2 (make-coercion (-μ y `(() -> #(? ,y))) (-μ x `(() -> #(Int ,x))))) (define h (apply-coercion g c2)) (define c3 (make-coercion (-μ y `(() -> #(? ,y))) (-μ x `(? -> #(Int ,x))))) (define h0 (apply-coercion g c3)) (evaluate/ecast '((define ones : (μ S2 (() -> #(Nat S2))) (λ (_ : ()) : (μ S #(Nat (() -> S))) #(1 ones))) (define dones : (μ S2 (() -> #(? S2))) ones) (define stream-ref : ((μ S2 (() -> #(? S2))) -> (Nat -> ?)) (λ (s : (μ S2 (() -> #(? S2)))) : (Nat -> ?) (λ (x : Nat) : ? (if (= x 0) ((s ()) . 0) ((stream-ref ((s ()) . 1)) (- x 1)))))) (+ ((stream-ref dones) 100) 41))) (evaluate/ecast '((define from : (Nat -> (μ S2 (() -> #(Nat S2)))) (λ (n : Nat) (λ (_ : ()) #(n (from (+ n 1)))))) (define base : (μ S2 (() -> #(? S2))) (from 2)) (define cleanly-divisible? : (Nat -> (Nat -> Bool)) (λ (n : Nat) (λ (m : Nat) (= (% n m) 0)))) (define filter : (Nat -> ((μ S2 (() -> #(? S2))) -> (μ S2 (() -> #(? S2))))) (λ (n : Nat) (λ (s : (μ S2 (() -> #(? S2)))) (λ (_ : ()) (let ([x (s ())]) (if ((cleanly-divisible? (x . 0)) n) ((x . 1) ()) #((x . 0) ((filter n) (x . 1))))))))) (define prime-sieve : ((μ S2 (() -> #(? S2))) -> (μ S2 (() -> #(? S2)))) (λ (s : (μ S2 (() -> #(? S2)))) (λ (_ : ()) (let ([x (s ())]) #((x . 0) (prime-sieve ((filter (x . 0)) (x . 1)))))))) (define primes : (μ S2 (() -> #(? S2))) (prime-sieve (from 2))) (define stream-ref : ((μ S2 (() -> #(? S2))) -> (Nat -> ?)) (λ (s : (μ S2 (() -> #(? S2)))) (λ (x : Nat) (if (= x 0) ((s ()) . 0) ((stream-ref ((s ()) . 1)) (- x 1)))))) (ann ((stream-ref primes) 100) Nat)))) ;; Local Variables: ;; eval: (put (quote match\?) (quote racket-indent-function) 1) ;; eval: (activate-input-method "TeX") ;; End:
true