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
a052de7a982c97b329bd2bbd5a39a2083461062c
5d8f5baee689450c9a18ca1715f88d3b2678e411
/pdp-2/set07/obstacles.rkt
8eca095afbf6619f5446dfe0944e39efcdfa13fc
[]
no_license
dingkple/racket
c6dca248708fb7119208b182b29fecf7b74c94d2
e11dd4dccc2633d8c86a30c1ef100fce9a065589
refs/heads/master
2021-04-29T03:48:30.260116
2017-01-04T18:19:44
2017-01-04T18:19:44
78,037,659
0
0
null
null
null
null
UTF-8
Racket
false
false
10,168
rkt
obstacles.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-lambda-reader.ss" "lang")((modname obstacles) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ()))) ;; FILE NAME: obstacles.rkt ;; How this program works: ;; In order to realize function position-set-equal?, if two position sets are ;; subset to each other, then the two sets are equal to each other. ;; In order to realize function obstacle?, we have to convert this problem ;; into a graph problem. We will use positon to replace node and use adjacent ;; relationship to replace edges. Then, what we have to do is to use graph alg ;; to help us to determine whether a graph is connected graph. If it is, return ;; true; else, return false. ;; In order to realize function blocks-to-obstacles, we also have to convert ;; this problem into graph problem. The problem is how to use an alg to ;; traversal a graph to get every connected sub graph in the original one. ;; Here, we will starting searching from a given set and then get all its ;; successers. After that, we will compare the result set with the original ;; set. If they are the same, we are done. If not, we will continue handling ;; the successor of the rest set which equals to the original set minus the set ;; which we have already handled. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (require "sets.rkt") (require "extras.rkt") (require rackunit) (provide position-set-equal? obstacle? blocks-to-obstacles) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; A Position is a (list PosInt PosInt) ;; Interp: (x y) represents the position x, y ;; TEMPLATE ;; p-fn: Position -> ?? ;; (define (p-fn p) ;; (... (first p) ;; (second p))) ;; EXAMPLES ;; (list 1 2) ;; A ListOfPosition is either ;; -- empty ;; -- (cons Position ListOfPosition) ;; WHERE: the ListOfPosition is a list of positions without duplication ;; TEMPLATE ;; lop-fn : ListOfPosition -> ?? ;; (define (lop-fn lop) ;; (cond ;; [(empty? lop) ...] ;; [else (... (p-fn (first lop)) ;; (lop-fn (rest lop)))])) ;; A PositionSet is a ListOfPosition ;; EXAMPLES ;; (list (list 1 2) (list 1 3)) ;; A ListOfPositionSet is either ;; -- empty ;; -- (cons PositionSet ListOfPositionSet) ;; WHERE: the ListOfPositionSet is a list of PositionSets without duplication ;; TEMPLATE ;; lops-fn : ListOfPositionSet -> ?? ;; (define (lops-fn lops) ;; [(empty? pss) ...] ;; [else (... (lop-fn (first lops)) ;; (lops-fn (rest lops)))]) ;; A PositionSetSet is a ListOfPositionSet ;; EXAMPLES ;; (list (list (list 1 2) (list 1 3)) ;; (list (list 2 3) (list 3 4))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Examples for testing (define blocks (list (list 1 2) (list 1 3) (list 2 3) (list 3 2) (list 3 4) (list 4 1) (list 4 4))) (define obstacles (list (list (list 4 1) (list 3 4) (list 3 2) (list 2 3) (list 1 2)) (list (list 1 3)) (list (list 4 4)))) (define obstacle (list (list 4 1) (list 3 4) (list 3 2) (list 2 3) (list 1 2))) (define set (list (list 1 2) (list 1 3) (list 2 3) (list 3 2) (list 3 4) (list 4 1) (list 4 3))) (define result (list (list 4 1) (list 4 3) (list 3 2) (list 3 4) (list 2 3) (list 1 2))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; position-set-equal? : PositionSet PositionSet -> Boolean ;; GIVEN: two PositionSets ;; RETURNS: true iff they denote the same set of positions ;; EXAMPLES: see tests below ;; STRATEGY: function composition (define (position-set-equal? ps1 ps2) (set-equal? ps1 ps2)) ;; obstacle? : PositionSet -> Boolean ;; GIVEN: a PositionSet ;; WHERE: every position in the given position set is all occupied ;; RETURNS: true iff the set of positions would be an obstacle ;; EXAMPLES: see tests below ;; STRATEGY: structural decomposition on posset : PositoinSet (define (obstacle? posset) (cond [(empty? posset) false] [else (position-set-equal? (reachalbes (list (first posset)) posset) posset)])) ;; adjacent? : Position Position -> Boolean ;; GIVEN: two Positions p1 and p2 ;; RETURNS: true iff two positions are adjacent to each other ;; EXAMPLES: (position-adjacent? (list 1 2) (list 2 3)) => true ;; STRATEGY: structural decomposition on Position (define (adjacent? p1 p2) (and (= (abs (- (first p1) (first p2))) 1) (= (abs (- (second p1) (second p2))) 1))) ;; adjacent-positions : Position PositionSet -> PositionSet ;; GIVEN: a Position pos and a PositionSet posset ;; RETURNS: a PositionSet which contains the positions that are adjacent to ;; the given position ;; EXAMPLES: (adjacent-positions (list 1 2) set) => (list (list 2 3)) ;; STRATEGY: HOFC (define (adjacent-positions pos posset) (filter ;; Position -> Boolean ;; GIVEN: a Position p ;; RETURNS: true iff the position is adjacent to the given position (lambda (p) (adjacent? p pos)) posset)) ;; all-adjacent-positions : PositionSet PositionSet -> PositionSet ;; GIVEN: a PositionSet ps and another PositionSet posset ;; RETURNS: a PositionSet which contains a list of positions that are ;; adjacent positions of the given list of positions ;; EXAMPLES: (all-adjacent-positions (list (list 1 2)) set) ;; => (list (list 2 3)) ;; STRATEGY: HOFC (define (all-adjacent-positions ps posset) (foldr ;; Position PositionSet -> PositionSet ;; GIVEN: a Position p and a PositionSet set-til-now ;; RETURNS: a PositionSet which contains a list of positions that are ;; adjacent positions of the given list of positions (lambda (p set-til-now) (set-union (adjacent-positions p posset) set-til-now)) empty ps)) ;; reachalbes : PositionSet PositionSet -> PositionSet ;; GIVEN: a PositionSet ps and a PositionSet posset ;; RETURNS: a set of positions which are reachalbe from the given position set ;; EXAMPLES: (reachalbes (list (list 1 2)) set) => result ;; STRATEGY: general recursion ;; HALTING MEASURE: the set of positions NOT in 'ps' ;; TERMINATION ARGUMENT: At the recursive call, 'candidates' contains at ;; least one element that is not in 'PS' (otherwise the subset? test ;; would have returned true). Hence the result of the set-union is at ;; least one element bigger than 'ps'. So the halting measure decreases. (define (reachalbes ps posset) (local ((define candidates (all-adjacent-positions ps posset))) (cond [(subset? candidates ps) ps] [else (reachalbes (set-union candidates ps) posset)]))) ;; blocks-to-obstacles : PositionSet -> PositionSetSet ;; GIVEN: the set of occupied positions on a chessboard ;; RETURNS: the set of obstacles on that chessboard ;; EXAMPLES: see tests below ;; STRATEGY: function composition (define (blocks-to-obstacles posset) (if (empty? (set-diff posset (blocks-to-one-obstacle posset))) (list posset) (cons (blocks-to-one-obstacle posset) (blocks-to-obstacles (set-diff posset (blocks-to-one-obstacle posset)))))) ;; blocks-to-one-obstacle : PositionSet -> PositionSet ;; GIVEN: a PositionSet posset ;; RETURNS: a PositionSet which is an obstacle ;; EXAMPLES: (blocks-to-one-obstacle blocks) => obstacle ;; STRATEGY: function composition (define (blocks-to-one-obstacle posset) (blocks-to-one-obstacle-inner posset empty)) ;; blocks-to-one-obstacle-inner : PositionSet PositionSet -> PositionSet ;; GIVEN: a subset posset of original PositionSet and another PositionSet ;; newset ;; WHERE: newset is an obstacle converted from a subset of original position ;; set which is above the given posset ;; RETURNS: a PositionSet which is an obstacle ;; EXAMPELS: (block-to-one-obstacle-inner blocks) => obstacle ;; STRATEGY: structural decomposition on posset : PositionSet (define (blocks-to-one-obstacle-inner posset newset) (cond [(empty? posset) newset] [else (if (obstacle? (set-cons (first posset) newset)) (blocks-to-one-obstacle-inner (rest posset) (set-cons (first posset) newset)) (blocks-to-one-obstacle-inner (rest posset) newset))])) ;; set-diff : PositionSet PositionSet -> PositionSet ;; GIVEN: two PositionSets set1 and set2 ;; RETURNS: a new position set which contains the positions that only belongs ;; to the first set ;; EXAMPLES: (set-diff (list (list 1 2)) (list (list 1 2))) => empty ;; STRATEGY: HOFC (define (set-diff ps1 ps2) (filter ;; Positoin -> Boolean ;; GIVEN: a position p ;; RETURNS: true iff the given position p is not in the ps2 (lambda (p) (not (my-member? p ps2))) ps1)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TESTS (begin-for-test (check-equal? (position-set-equal? (list (list 1 2) (list 1 3)) (list (list 1 3))) false "the two position sets should be different, but they are NOT") (check-equal? (position-set-equal? (list (list 1 2) (list 1 3)) (list (list 1 3) (list 1 2))) true "the two position sets should be same, but they are NOT") (check-equal? (obstacle? empty) false "the emtpy set is not an obstacle, but it DOES") (check-equal? (obstacle? (list (list 4 1) (list 3 2))) true "this position set is an obstacle, but it does NOT") (check-equal? (obstacle? blocks) false "evety position in this position set should be adjacent to each other, but it does NOT") (check-equal? (blocks-to-obstacles blocks) obstacles "the blocks should be changed to obstacles, but it does NOT"))
false
2dd1cc9d6065838c738c19e6d4ece1ceb3d8f83e
5fc2439218bb27a9aa0e6eb20b0384592b2d422e
/parse-ftl.rkt
e8bb87e7bf78d23b55e4176b3f6a6b4d14ba65f6
[]
no_license
eric93/incremental
49b223abb6f104f1d131706a09943ddf6f19428c
b3ad6cff28af214ddb322529bd0e4aa59ab40d57
refs/heads/master
2021-05-16T02:02:04.361209
2019-05-21T18:30:21
2019-05-21T18:30:21
37,098,018
2
1
null
null
null
null
UTF-8
Racket
false
false
12,907
rkt
parse-ftl.rkt
#lang racket (require parser-tools/lex) (require (prefix-in : parser-tools/lex-sre)) (require parser-tools/yacc) (require racket/match) (provide parse-ftl serialize-ftl (struct-out iface) (struct-out body) (struct-out trait) (struct-out asgn) (struct-out attr) (struct-out children) (struct-out class)) (define-empty-tokens e-tkns (INTERFACE RBRACE LBRACE VAR INPUT TRAIT CLASS CHILDREN ATTRIBUTES ACTIONS LOOP ASSIGN FOLD FOLD-SEP END-STMT COND COLON PLUS MINUS AND OR DIV MUL LPAREN RPAREN LBRACKET RBRACKET COMMA DOT GE LE GEQ LEQ EQ NEQ NOT EOF)) (define-tokens tkns (IDENT NUMERIC BOOL INDEX)) (define-lex-trans int (syntax-rules () ((_) (:+ (char-range "0" "9"))))) (define-lex-trans exponent (syntax-rules () ((_) (:seq (:or "e" "E") (:? (:or "+" "-")) (:+ (char-range "0" "9")))))) (define-lex-trans float (syntax-rules () ((_) (:or (:seq (:+ (char-range "0" "9")) "." (:* (char-range "0" "9")) (:? (exponent)) (:? "f")) (:seq "." (:+ (char-range "0" "9")) (:? (exponent))) (:seq (:+ (char-range "0" "9")) (exponent)))))) (define-lex-trans number (syntax-rules () ((_) (:or (int) (float))))) (define-lex-trans ident (syntax-rules () ((_) (:seq (:or (char-range "a" "z") (char-range "A" "Z") "_" "&") (:* (:or (char-range "a" "z") (char-range "A" "Z") (char-range "0" "9") "_" "-")))))) (define-lex-trans comment (syntax-rules () ((_) (:or (:seq "//" (:* (char-complement (:or "\r" "\n"))) (:? "\r") "\n") (:seq "/*" (:* any-char) "*/"))))) (define ftl-lex (lexer [(comment) (ftl-lex input-port)] ["true" (token-BOOL #t)] ["false" (token-BOOL #f)] ["interface" (token-INTERFACE)] ["}" (token-RBRACE)] ["{" (token-LBRACE)] ["var" (token-VAR)] ["input" (token-INPUT)] ["trait" (token-TRAIT)] ["class" (token-CLASS)] ["children" (token-CHILDREN)] ["attributes" (token-ATTRIBUTES)] ["actions" (token-ACTIONS)] ["loop" (token-LOOP)] [":=" (token-ASSIGN)] ["fold" (token-FOLD)] [".." (token-FOLD-SEP)] [";" (token-END-STMT)] ["?" (token-COND)] [":" (token-COLON)] ["+" (token-PLUS)] ["-" (token-MINUS)] ["&&" (token-AND)] ["||" (token-OR)] ["/" (token-DIV)] ["*" (token-MUL)] ["(" (token-LPAREN)] [")" (token-RPAREN)] ["[" (token-LBRACKET)] ["]" (token-RBRACKET)] ["," (token-COMMA)] ["." (token-DOT)] [">" (token-GE)] ["<" (token-LE)] [">=" (token-GEQ)] ["<=" (token-LEQ)] ["==" (token-EQ)] ["!=" (token-NEQ)] ["!" (token-NOT)] [(:seq "$" (:or "-" "i" "0" "$")) (token-INDEX lexeme)] [(eof) (token-EOF)] [(number) (token-NUMERIC (string->number lexeme))] [(ident) (token-IDENT lexeme)] [whitespace (ftl-lex input-port)])) (struct iface (name fields)) (struct body (children attributes actions)) (struct trait (name body)) (struct asgn (lhs rhs) #:transparent) (struct attr (loc index name) #:transparent) (struct children (name type)) (struct class (name traits interface body)) (define (merge-body elem prev-body) (body (append (car elem) (body-children prev-body)) (append (cadr elem) (body-attributes prev-body)) (append (caddr elem) (body-actions prev-body)))) (define ftl-parse (parser (start decl-list) (tokens tkns e-tkns) (end EOF) (error (print "ERROR!")) (grammar (decl-list ((decl) (list $1)) ((decl decl-list) (cons $1 $2))) (decl ((iface-decl) $1) ((trait-decl) $1) ((class-decl) $1)) (class-decl ((CLASS IDENT COLON IDENT LBRACE class-body RBRACE) (class $2 '() $4 $6)) ((CLASS IDENT LPAREN trait-list RPAREN COLON IDENT LBRACE class-body RBRACE) (class $2 $4 $7 $9))) (trait-list ((IDENT COMMA trait-list) (cons $1 $3)) ((IDENT) (list $1))) (iface-decl ((INTERFACE IDENT LBRACE attr-list RBRACE) (iface $2 $4))) (attr-list ((attr-def IDENT COLON IDENT END-STMT attr-list) (cons (list $1 $2 $4) $6)) ((attr-def IDENT COLON IDENT END-STMT) (list (list $1 $2 $4)))) (attr-def ((VAR) "var") ((INPUT) "input")) (trait-decl ((TRAIT IDENT LBRACE class-body RBRACE) (trait $2 $4))) (class-body ((body-elem class-body) (merge-body $1 $2)) ((body-elem) (body (car $1) (cadr $1) (caddr $1)))) (body-elem ((ACTIONS LBRACE asgn-list RBRACE) `(() () ,$3)) ((CHILDREN LBRACE child-list RBRACE) `(,$3 () ())) ((ATTRIBUTES LBRACE attr-list RBRACE) `(() ,$3 ()))) (asgn ((LOOP IDENT LBRACE asgn-list RBRACE) `(loop ,$2 ,$4)) ((attr-ref ASSIGN expr END-STMT) (asgn $1 $3))) (asgn-list ((asgn asgn-list) (cons $1 $2)) ((asgn) (list $1))) (attr-ref ((IDENT) (attr "self" "" $1)) ((IDENT DOT IDENT) (attr $1 "" $3)) ((INDEX DOT IDENT) (attr "self" $1 $3)) ((IDENT INDEX DOT IDENT) (attr $1 $2 $4))) (child-list ((IDENT COLON child-type END-STMT child-list) (append (children $1 $3) $5)) ((IDENT COLON child-type END-STMT) (list (children $1 $3)))) (child-type ((IDENT) $1) ((LBRACKET IDENT RBRACKET) (string-append "[" $2 "]"))) (expr ((cond-expr) $1) ((FOLD cond-expr FOLD-SEP cond-expr) `(fold ,$2 ,$4))) (cond-expr ((and-expr) $1) ((and-expr COND and-expr COLON and-expr) `(ite ,$1 ,$3 ,$5))) (and-expr ((or-expr) $1) ((or-expr AND and-expr) `(and ,$1 ,$3))) (or-expr ((comparison) $1) ((comparison OR or-expr) `(or ,$1 ,$3))) (comparison ((term) $1) ((NOT term) `(not ,$2)) ((term GE term) `(> ,$1 ,$3)) ((term LE term) `(< ,$1 ,$3)) ((term GEQ term) `(>= ,$1 ,$3)) ((term LEQ term) `(<= ,$1 ,$3)) ((term EQ term) `(= ,$1 ,$3)) ((term EQ term) `(!= ,$1 ,$3))) (term ((factor) $1) ((factor PLUS term) `(+ ,$1 ,$3)) ((factor MINUS term) `(- ,$1 ,$3))) (factor ((prim-expr) $1) ((prim-expr MUL factor) `(* ,$1 ,$3)) ((prim-expr DIV factor) `(/ ,$1 ,$3))) (prim-expr ((MINUS prim-expr) `(- ,$2)) ((attr-ref) `(ref ,$1)) ((NUMERIC) `(num ,$1)) ((BOOL) `(bool ,$1)) ((IDENT LPAREN arg-list RPAREN) `(call ,$1 ,$3)) ((IDENT LPAREN RPAREN) `(call ,$1 ())) ((LPAREN expr RPAREN) $2)) (arg-list ((expr) (list $1)) ((expr COMMA arg-list) (cons $1 $3)))))) (define (serialize-ftl root) (define (m decl) (cond [(iface? decl) (serialize-iface decl)] [(trait? decl) (serialize-trait decl)] [(class? decl) (serialize-class decl)])) (string-join (map m root) "\n")) (define (serialize-iface iface) (define header (string-append "interface " (iface-name iface) " {\n")) (define body (string-join (map serialize-attr-def (iface-fields iface)) "\n")) (define footer "\n}\n") (string-append header body footer)) (define (serialize-attr-def attr-def) (string-append " " (car attr-def) " " (cadr attr-def) " : " (caddr attr-def) ";")) (define (serialize-trait trait) (define header (string-append "trait " (trait-name trait) " {\n")) (define body (serialize-body (trait-body trait))) (define footer "\n}\n") (string-append header body footer)) (define (serialize-class class) (define header (string-append "class " (class-name class) (if (equal? (class-traits class) '()) "" (string-append "(" (string-join (class-traits class) ",") ")")) " : " (class-interface class) " {\n")) (define body (serialize-body (class-body class))) (define footer "\n}\n") (string-append header body footer)) (define (serialize-body body) (define children (string-append " children {\n" (serialize-children (body-children body)) "\n }\n")) (define attributes (string-append " attributes {\n" (string-join (map serialize-attr-def (body-attributes body)) "\n") "\n }\n")) (define actions (string-append " actions {\n" (serialize-assignments (body-actions body) 8) "\n }\n")) (string-append children attributes actions)) (define (serialize-children children) (define (serialize-child child) (string-append " " (children-name child) " : " (children-type child) ";\n")) (string-join (map serialize-child children) "")) (define (spaces depth) (if (equal? depth 0) "" (string-append (spaces (- depth 1)) " "))) (define (serialize-assignments asgns depth) (define (serialize-assignment asgn d) (string-append (spaces d) (serialize-ref (asgn-lhs asgn)) " := " (serialize-expr (asgn-rhs asgn)) " ;\n")) (define (serialize-loop loop d) (string-append (spaces d) "loop " (cadr loop) " {\n" (serialize-assignments (caddr loop) (+ d 4)) (spaces d) "}\n")) (string-join (map (lambda (x) (if (asgn? x) (serialize-assignment x depth) (serialize-loop x depth))) asgns) "\n")) (define (serialize-ref attr-ref) (define loc (if (equal? (attr-loc attr-ref) "self") "" (attr-loc attr-ref))) (define index (attr-index attr-ref)) (define dot (if (and (equal? loc "") (equal? index "")) "" ".")) (string-append loc index dot (attr-name attr-ref))) (define (serialize-expr expr) ;(displayln expr) (match expr [`(fold ,init ,step) (string-append "fold (" (serialize-expr init) ") .. (" (serialize-expr step) ")")] [`(ite ,if ,then ,else) (string-append "(" (serialize-expr if) ") ? (" (serialize-expr then) ") : (" (serialize-expr else) ")")] [`(and ,e1 ,e2) (string-append "(" (serialize-expr e1) ") && (" (serialize-expr e2) ")")] [`(or ,e1 ,e2) (string-append "(" (serialize-expr e1) ") || (" (serialize-expr e2) ")")] [`(not ,e) (string-append "! (" (serialize-expr e) ")")] [`(> ,e1 ,e2) (string-append "(" (serialize-expr e1) ") > (" (serialize-expr e2) ")")] [`(< ,e1 ,e2) (string-append "(" (serialize-expr e1) ") < (" (serialize-expr e2) ")")] [`(>= ,e1 ,e2) (string-append "(" (serialize-expr e1) ") >= (" (serialize-expr e2) ")")] [`(<= ,e1 ,e2) (string-append "(" (serialize-expr e1) ") <= (" (serialize-expr e2) ")")] [`(= ,e1 ,e2) (string-append "(" (serialize-expr e1) ") == (" (serialize-expr e2) ")")] [`(!= ,e1 ,e2) (string-append "(" (serialize-expr e1) ") != (" (serialize-expr e2) ")")] [`(+ ,e1 ,e2) (string-append "(" (serialize-expr e1) ") + (" (serialize-expr e2) ")")] [`(- ,e1 ,e2) (string-append "(" (serialize-expr e1) ") - (" (serialize-expr e2) ")")] [`(* ,e1 ,e2) (string-append "(" (serialize-expr e1) ") * (" (serialize-expr e2) ")")] [`(/ ,e1 ,e2) (string-append "(" (serialize-expr e1) ") / (" (serialize-expr e2) ")")] [`(- ,e) (string-append "- (" (serialize-expr e) ")")] [`(ref ,r) (serialize-ref r)] [`(num ,n) (number->string n)] [`(bool ,b) (if b "true" "false")] [`(call ,name ()) (string-append name "()")] [`(call ,name ,args) (string-append name "(" (string-join (map serialize-expr args) ",") ")")])) (define (parse-ftl input) (ftl-parse (lambda () (ftl-lex input)))) (define (test) (define test-file (open-input-file "test.ftl")) (define (next-token) (define ret (ftl-lex test-file)) (displayln ret) ret) (define test-file-lexed next-token) (ftl-parse test-file-lexed)) (define (test-lex) (define (test-lex-helper inp) (define out (inp)) (displayln out) (if (equal? out (token-EOF)) (displayln "Done") (test-lex-helper inp))) (define x (open-input-file "test.ftl")) (test-lex-helper (lambda () (ftl-lex x)))) (define (test-serialize x) (define out (open-output-file "test-result.ftl" #:exists 'replace)) (display (serialize-ftl x) out) (close-output-port out))
false
56e417fbc69c8c1f14ce735a12ca31baad866a9c
ad1fd30f4e205fa1cf162f1a37a642fe4909aef2
/tests/unparse-pda.rkt
e56a9033a6136700b4c01d667064c7db474b3161
[]
no_license
danking/pda-to-pda-risc
6151803a61acc53f251504d2767dd3eb043d0f78
4aab39bad0a03cc4d545403fcf2cf43366a8a92e
refs/heads/master
2016-09-06T05:44:17.966418
2014-08-01T21:01:02
2014-08-01T21:01:02
2,149,992
2
0
null
null
null
null
UTF-8
Racket
false
false
5,996
rkt
unparse-pda.rkt
#lang racket (require "../pda-data.rkt" rackunit "../unparse-pda.rkt") (check-equal? (unparse-pda (make-pda '(A B $eos) '$eos 's1 (list (make-state 's1 '(()) (list (make-shift '(A) 's2)) (list) (list (make-goto 'start 's6))) (make-state 's2 '((A s1) (A s2)) (list (make-shift '(A) 's2) (make-shift '(B) 's3)) (list) (list (make-goto 'start 's4))) (make-state 's3 '((B s2 A s1) (B s2 A s2)) (list (make-reduce '() 'r2)) (list) (list)) (make-state 's4 '((start s4 A s1) (start s4 A s2)) (list (make-shift '(B) 's5)) (list) (list)) (make-state 's5 '((B s5 start s4 A s1) (B s5 start s4 A s2)) (list (make-reduce '() 'r1)) (list) (list)) (make-state 's6 '((start s1)) (list) (list (make-accept '($eos))) (list))) (list (make-rule 'r1 '((B s5 start s4 A s2)) 'start '(#f v2 #f) '(+ 2 v2)) (make-rule 'r2 '((B s2 A s2)) 'start '(#f #f) '2)))) '((TOKENS A B $eos) (EOS $eos) (START s1) (RULE r1 ((B s5 start s4 A s2)) start (#f v2 #f) (+ 2 v2)) (RULE r2 ((B s2 A s2)) start (#f #f) 2) (STATE s1 (()) (SHIFT (A) s2) (GOTO start s6)) (STATE s2 ((A s1) (A s2)) (SHIFT (A) s2) (SHIFT (B) s3) (GOTO start s4)) (STATE s3 ((B s2 A s1) (B s2 A s2)) (REDUCE () r2)) (STATE s4 ((start s4 A s1) (start s4 A s2)) (SHIFT (B) s5)) (STATE s5 ((B s5 start s4 A s1) (B s5 start s4 A s2)) (REDUCE () r1)) (STATE s6 ((start s1)) (ACCEPT ($eos))))) (check-equal? (unparse-pda (make-pda '(NUM L-PAREN R-PAREN SEMICOLON TIMES DIVIDE PLUS MINUS *EOF*) '*EOF* 's0 (list (make-state 's0 '(()) (list (make-reduce '() 'r5)) (list) (list (make-goto 'program 's1) (make-goto 's-list 's2))) (make-state 's1 '(()) (list) (list (make-accept '(*EOF*))) (list)) (make-state 's2 '(()) (list (make-shift '(NUM) 's5) (make-shift '(L-PAREN) 's6) (make-shift '(*ERROR*) 's7)) (list (make-reduce '(*EOF*) 'r2)) (list (make-goto 'statement 's3) (make-goto 'exp 's4))) (make-state 's3 '(()) (list (make-reduce '() 'r6)) (list) (list)) (make-state 's4 '(()) (list (make-shift '(SEMICOLON) 's19) (make-shift '(TIMES) 's11) (make-shift '(DIVIDE) 's12) (make-shift '(PLUS) 's13) (make-shift '(MINUS) 's14)) (list (make-reduce '(*EOF*) 'r3)) (list))) (list (make-rule 'r4 '(()) 'program '(s-list #f) '(cons (if #f #f) s-list)) (make-rule 'r5 '(()) 's-list '() ''()) (make-rule 'r9 '(()) 'exp '(NUM) 'NUM) (make-rule 'r13 '(()) 'exp '(expA #f exp) '(quotient expA exp)) (make-rule 'r14 '(()) 'exp '(#f exp #f) 'exp)))) '((TOKENS NUM L-PAREN R-PAREN SEMICOLON TIMES DIVIDE PLUS MINUS *EOF*) (EOS *EOF*) (START s0) (RULE r4 (()) program (s-list #f) (cons (if #f #f) s-list)) (RULE r5 (()) s-list () '()) (RULE r9 (()) exp (NUM) NUM) (RULE r13 (()) exp (expA #f exp) (quotient expA exp)) (RULE r14 (()) exp (#f exp #f) exp) (STATE s0 (()) (REDUCE () r5) (GOTO program s1) (GOTO s-list s2)) (STATE s1 (()) (ACCEPT (*EOF*))) (STATE s2 (()) (SHIFT (NUM) s5) (SHIFT (L-PAREN) s6) (SHIFT (*ERROR*) s7) (REDUCE (*EOF*) r2) (GOTO statement s3) (GOTO exp s4)) (STATE s3 (()) (REDUCE () r6)) (STATE s4 (()) (SHIFT (SEMICOLON) s19) (SHIFT (TIMES) s11) (SHIFT (DIVIDE) s12) (SHIFT (PLUS) s13) (SHIFT (MINUS) s14) (REDUCE (*EOF*) r3))))
false
8664fcf245a9a7ed6f3a69fe165f4baaab8d97f8
7b8ebebffd08d2a7b536560a21d62cb05d47be52
/private/types/type-checking.rkt
037b76829d6c283ea9c2d20835435f952bf05234
[]
no_license
samth/formica
2055045a3b36911d58f49553d39e441a9411c5aa
b4410b4b6da63ecb15b4c25080951a7ba4d90d2c
refs/heads/master
2022-06-05T09:41:20.344352
2013-02-18T23:44:00
2013-02-18T23:44:00
107,824,463
0
0
null
2017-10-21T23:52:59
2017-10-21T23:52:58
null
UTF-8
Racket
false
false
2,055
rkt
type-checking.rkt
#lang racket/base ;;______________________________________________________________ ;; ______ ;; ( // _____ ____ . __ __ ;; ~//~ ((_)// // / / // ((_ ((_/_ ;; (_// ;;.............................................................. ;; Provides contract based type system. ;;============================================================== (require racket/contract (for-syntax racket/base)) (provide is check-result check-argument check-type) (define-for-syntax (parse-infix-contract stx) (syntax-case stx (.->.) [(x ... .->. y) #`(.->. #,@(parse-infix-contract #'(x ...)) #,(parse-infix-contract #'y))] [(x y ...) #`(#,(parse-infix-contract #'x) #,@(parse-infix-contract #'(y ...)))] [x #'x])) ;;;================================================================= ;;; Safe type checking ;;;================================================================= (define-syntax is (make-set!-transformer (lambda (stx) (syntax-case stx () [(is x type) (with-syntax ([c (parse-infix-contract #'type)]) (syntax-protect #'(cond [(contract? c) (with-handlers ([exn:fail? (lambda (exn) #f)]) (contract-first-order-passes? c x))] [else (raise-type-error 'is "predicate" 1 x type)])))] [is (syntax-protect #'(λ (x t) (is x t)))])))) (define check-type (make-parameter #t)) (define-syntax-rule (check-result id type expr text ...) (let ([res expr]) (if (or (not (check-type)) (is res type)) res (raise-arguments-error id (format "the result should have type ~a" (build-compound-type-name type)) "received" res text ...)))) (define-syntax-rule (check-argument id type x text ...) (unless (or (not (check-type)) (is x type)) (raise-arguments-error id (format "the argument should have type ~a" (build-compound-type-name type)) "given" x text ...)))
true
d2f102ed834d1c8928b5b32a18884038d7188559
8a19fd7478bb2969bfcd4f7944f4e0c99b9eddf0
/util.rkt
2f8cfd718a63f8c53f908df3ffafd16237d56ff7
[ "MIT", "Apache-2.0" ]
permissive
kurinoku/racquel
0a00bb2eb755d4f7466549c58a129aac16b108da
f2dc534a7523540ff96f7a952b49add6de42c185
refs/heads/master
2022-12-07T02:10:19.835110
2020-08-24T04:14:51
2020-08-24T04:14:51
289,794,795
0
0
null
2020-08-24T01:02:23
2020-08-24T01:02:22
null
UTF-8
Racket
false
false
4,579
rkt
util.rkt
#lang racket ;;;; ;;;; util - Racquel utilities. (require db "metadata.rkt" "schema.rkt" (for-syntax racket/syntax syntax/parse)) (provide (all-defined-out)) ;;; Database system type. (define (dbsystem-type con) (let ([dbsys-type (dbsystem-name (connection-dbsystem con))]) (if (equal? dbsys-type 'odbc) *odbc-dbsystem-type* dbsys-type))) ;;; ODBC database system type. Values are: 'sqlserver, 'oracle, or 'db2. (define *odbc-dbsystem-type* 'sqlserver) ;;; Set the ODBC database system type. (define (set-odbc-dbsystem-type! odbc-dbsys-type) (set! *odbc-dbsystem-type* odbc-dbsys-type)) ;;; Create a multi-dimensional hash table. (define (make-multi-hash #:weak? (wk? #f)) (if wk? (make-weak-hash) (make-hash))) ;;; Set a value given a sequence of keys. (define (multi-hash-set! hash-tbl value . keys) (if (null? (cdr keys)) (hash-set! hash-tbl (car keys) value) (if (hash-has-key? hash-tbl (car keys)) (multi-hash-set! (hash-ref hash-tbl (car keys)) value (cdr keys)) (let ([h (make-multi-hash #:weak? (hash-weak? hash-tbl))]) (hash-set! hash-tbl (car keys) h) (multi-hash-set! h value (cdr keys)))))) ;;; Retrieve a value given a sequence of keys. (define (multi-hash-ref hash-tbl . keys) (if (null? (cdr keys)) (if (hash-has-key? hash-tbl (car keys)) (hash-ref hash-tbl (car keys)) #f) (if (hash-has-key? hash-tbl (car keys)) (multi-hash-ref (hash-ref hash-tbl (car keys)) (cdr keys)) #f))) ;;; Test if the hash contains the given sequence of keys. (define (multi-hash-has-key? hash-tbl . keys) (if (null? (cdr keys)) (hash-has-key? hash-tbl (car keys)) (if (hash-has-key? hash-tbl (car keys)) (multi-hash-ref (hash-ref hash-tbl (car keys)) (cdr keys)) #f))) ;;; Define a global hash table holding data class schema. (define *data-class-schema* (make-multi-hash)) ;;; Define type checker for a data class. (define (data-class? cls) (implementation? cls data-class<%>)) ;;; Define type checker for a data object. (define (data-object? obj) (is-a? obj data-class<%>)) ;;; Define an empty interface used to identify a data class. (define data-class<%> (interface ())) ;;; Class of an object (define (object-class obj) (let-values ([(cls x) (object-info obj)]) cls)) ;;; Get a prepared SQL statement. (define-syntax (make-select-statement stx) (syntax-parse stx [(_ con:id cls:id (~optional (~seq #:print? prnt)) (~optional (~seq #:prepare? prep)) where-clause:expr) (with-syntax ([prnt? (or (attribute prnt) #'#f)] [prep? (not (or (attribute prep) #'#f))]) #`(let* ([dbsys-type (dbsystem-type con)] [tbl-nm (sql-escape (get-class-metadata table-name cls) dbsys-type)] [col-nms (sort (map (λ (n) (sql-escape n dbsys-type)) (get-column-names cls)) string<?)] [sql (string-append "select " (string-join (map (lambda (c) (string-append tbl-nm "." c)) col-nms) ", ") " from " tbl-nm " " (sql-placeholder where-clause (dbsystem-type con)))] [pst (if (or prnt? (not prep?)) sql (virtual-statement con sql))]) pst))])) ;;; SQL schema by database system type. (define (load-schema con schema-nm tbl-nm #:reverse-join? (rev-jn? #f) #:db-system-type dbsys-type) (unless (multi-hash-has-key? *data-class-schema* con schema-nm tbl-nm) (multi-hash-set! *data-class-schema* (cond [(eq? dbsys-type 'db2) (load-db2-schema con schema-nm tbl-nm rev-jn?)] [(eq? dbsys-type 'mysql) (load-mysql-schema con schema-nm tbl-nm rev-jn?)] [(eq? dbsys-type 'oracle) (load-oracle-schema con schema-nm tbl-nm rev-jn?)] [(eq? dbsys-type 'postgresql) (load-postgresql-schema con schema-nm tbl-nm rev-jn?)] [(eq? dbsys-type 'sqlite3) (load-sqlite3-schema con schema-nm tbl-nm rev-jn?)] [(eq? dbsys-type 'sqlserver) (load-sqlserver-schema con schema-nm tbl-nm rev-jn?)]) con schema-nm tbl-nm)) (multi-hash-ref *data-class-schema* con schema-nm tbl-nm))
true
fd3faf812e8568c49f482c8b7af089043747f846
82c76c05fc8ca096f2744a7423d411561b25d9bd
/typed-racket-test/succeed/issue-807.rkt
f7385bccd6ce59fb6eae5945dbf21bb13e0f5e6c
[ "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
470
rkt
issue-807.rkt
#lang typed/racket ;; https://github.com/racket/typed-racket/issues/807 (random-seed 1234) (define r (current-pseudo-random-generator)) (define (run-trials [trials : Natural]) (for ([i (in-range trials)]) (define a (assert (random r) positive?)) (define b (assert (random r) positive?)) (define c (assert (random r) positive?)) (if (and (< (abs (- a b)) c) (< c (sqrt (+ (* a a) (* b b))))) 1 0))) (run-trials (expt 2 20))
false
1fa69139fe7ccddec653c9850d5e2770f0e137d3
76df16d6c3760cb415f1294caee997cc4736e09b
/rosette-benchmarks-4/nonograms/puzzle/src/learn/solve.rkt
e9e56c2bc1c116a5df874e70c7b60640bc82a245
[ "MIT" ]
permissive
uw-unsat/leanette-popl22-artifact
70409d9cbd8921d794d27b7992bf1d9a4087e9fe
80fea2519e61b45a283fbf7903acdf6d5528dbe7
refs/heads/master
2023-04-15T21:00:49.670873
2021-11-16T04:37:11
2021-11-16T04:37:11
414,331,908
6
1
null
null
null
null
UTF-8
Racket
false
false
10,249
rkt
solve.rkt
#lang racket (provide find-maximal-transition-with-rules build-transition-solution-graph board-solvable-with-rules? rollout-board-solution run-board-solution-rollouts) (require "../core/core.rkt" "../nonograms/debug.rkt" "../nonograms/nonograms.rkt") ; two environments! one flipped so we can apply rules in reverse (struct environment-group (forwards backwards)) (define (environment-group-line envgrp) (environment-line (environment-group-forwards envgrp))) (define (create-environment-group ctx) (environment-group (create-environment ctx) (create-environment (flip-line ctx)))) (define (possible-actions-of-rule-single-env env prog) (or (interpret/deterministic prog env) empty)) ; environment-group?, Program? -> (listof fill-action?) (define (possible-actions-of-rule envgrp prog) (append (possible-actions-of-rule-single-env (environment-group-forwards envgrp) prog) (map (curry flip-action (line-length (environment-group-line envgrp))) (possible-actions-of-rule-single-env (environment-group-backwards envgrp) prog)))) ; (listof Program?), environment-group?, (boxof boolean?) -> line? ; apply all possible rules to line-info, returning the new line-info. ; if anything changed, the box are-actions? is set to true (otherwise left alone) (define (maximally-solve all-rules envgrp #:are-actions? are-actions? #:used-rules [used-rules #f]) (define (test-rule r state) ; always apply rules to the original context, but apply actions to the ongoing context (foldl (λ (a s) (define s2 (apply-action a s)) (unless (equal? s s2) (set-box! are-actions? #t) (when used-rules (set-add! used-rules r))) s2) state (possible-actions-of-rule envgrp r))) (foldl test-rule (environment-group-line envgrp) all-rules)) ; (listof Program?), (pairof environment? board-line?), (boxof boolean?) -> board-line? ; apply all possible rules to line-info, returning the new line-info. ; if anything changed, the box are-actions? is set to true (otherwise left alone) (define (maximally-solve* all-rules are-actions? line-info) (match-define (cons env bl) line-info) ; HACK this ruins the cost savings of passing in environment?, need to finish refactoring later (define envgrp (create-environment-group (environment-line env))) (struct-copy board-line bl [line (maximally-solve all-rules envgrp #:are-actions? are-actions?)])) ; (listof rule?), line? -> line-transition? (define (find-maximal-transition-with-rules all-rules start-state #:used-rules-box [used-rules-box (box #f)] #:intermediate-states-box [intermediate-states-box (box #f)]) (define used-rules (mutable-seteq)) (set-box! intermediate-states-box empty) (define end-state (let loop ([ctx start-state]) (set-box! intermediate-states-box (cons ctx (unbox intermediate-states-box))) (define progress? (box #f)) ; first, apply every rule to the base context. (define ctx* (maximally-solve all-rules (create-environment-group ctx) #:are-actions? progress? #:used-rules used-rules)) ; stop at fixed point (cond [(unbox progress?) ; then find (using the oracle) all potential subcontexts. (define sms (find-subspace-mappings ctx*)) ; apply all possible rules to this subcontext until fixed point (define subs (map (λ (sm) (loop (apply-subspace-mapping sm ctx*))) sms)) (define final (foldl (λ (sm sub acc) (reverse-subspace-mapping sm acc sub)) ctx* sms subs)) (loop final)] [else ctx]))) ;(printf "number of used actions: ~a\n" (set-count used-rules)) (set-box! used-rules-box (set->list used-rules)) (line-transition start-state (line-cells end-state))) ; (listof Program?), line-transition? -> digraph? ; builds a graph of all possible solutions for this transition, with edges labeled with the rules needed for those transitions (define (build-transition-solution-graph rules main-tctx) (define grph (make-digraph identity)) ;(printf "rules? ~a\ntctx: ~a\n" (andmap Program? rules) main-tctx) ; a dummy sink node that can never be satisfied. ; this is used because the cover algorithm uses sinks as implicit goals, and having a dummy sink is an easy way to force ; non-goal nodes to be intermediate nodes. (define bad-sink (dg-add-node! grph 'unreachable)) (define (add-internal-node! val) (define n (dg-add-node! grph val)) (dg-add-edge! n bad-sink empty) n) ;(printf "new loop: ~a\n" main-tctx) (let loop ([tctx main-tctx] [starting-node (add-internal-node! 'source)] [prev-mapping (identity-subspace-mapping (line-transition-start main-tctx))]) ; get every destination state for every program, broken into individual cells (define start-state (line-transition-start tctx)) (define envgrp (create-environment-group start-state)) (define env (environment-group-forwards envgrp)) (define components (remove-duplicates (for/list ([idx (length rules)] [p rules] #:when #t [a (possible-actions-of-rule envgrp p)] #:when #t [offset (in-range (- (fill-action-end a) (fill-action-start a)))]) (define start (+ offset (fill-action-start a))) (cons idx (fill-action (fill-action-value a) start (add1 start)))))) ; partition by these cell actions, but discard anything that is ineffective (define classes (filter (λ (cls) (define key (cdar cls)) (action-compatible-with-and-impactful-for-transition? key tctx)) (partition-by-key cdr components))) ; create a mapping from action as (cons val start) to program indices (define mapping (make-hash (for/list ([cls classes]) (cons (cdar cls) (map car cls))))) (define end-state (foldl apply-action (environment-line env) (hash-keys mapping))) (define expected-end (line-transition-end tctx)) ;(printf "checking:\n\t~a ->\n\t~a\n" (pretty-format-line start-state) (pretty-format-line end-state)) (cond [(equal? end-state expected-end) ;(printf "reached end!\n" ) (void)] [else ;(printf "more to go: ~a -> ~a\n" end-state expected-end) (unless (line-weaker? end-state expected-end) (printf "bad transition: ~a -> ~a\n" end-state expected-end) (error "something wrong! applied an invalid rule!")) (define sms (find-subspace-mappings end-state)) ; don't generate the chain unless we're going to use it (unless (empty? sms) ;(printf "subspaces: ~a\n" sms) ; create a chain (to form a conjuction) as a prereq for these subproblems (define end-node (let rec ([prev starting-node] [remaining (hash->list mapping)]) (match remaining ['() prev] [(cons (cons key val) tail) (define next (add-internal-node! `(chain ,tctx ,key))) (dg-add-edge! prev next val) (rec next tail)]))) (for ([sm sms]) ; TODO need some kind of function to reverse the mapping for node names (define sub-tctx (apply-subspace-mapping-t sm (struct-copy line-transition tctx [start end-state]))) (define full-mapping (compose-subspace-mappings prev-mapping sm)) (loop sub-tctx end-node full-mapping)) (void))]) ; make a node for each transition arrived at, with an edge containing the required rules (for ([(key val) (in-hash mapping)]) ; name of the node should be whatever it would be in the root space, so reverse transform the action by the full mapping (define n (dg-add-node! grph (reverse-subspace-mapping-a prev-mapping key))) (dg-add-edge! starting-node n val)) (void)) ;(printf "grph order: ~a, size: ~a, avg edge len: ~a, tctx: ~a\n" (dg-order grph) (dg-size grph) (/ (apply + (map length (dg-edge-values grph))) (dg-size grph)) main-tctx) grph) (define (board-solvable-with-rules? rule-set brd) (define (try-solve typ changed?) (define bls (board-lines-of-type typ brd)) (define envbls (map (λ (bl) (cons (create-environment (board-line-line bl)) bl)) bls)) (define new-bls (map (curry maximally-solve* rule-set changed?) envbls)) (for-each (curry board-set-line! brd) new-bls)) ; alternate between applying all rules to rows and all rules to columns (let loop () (define changed? (box #f)) (try-solve 'row changed?) (try-solve 'col changed?) (cond ; if solved, we're done [(board-solved? brd) #t] ; if nothing changed, we're stuck [(not (unbox changed?)) #f] ; otherwise keep going [else (loop)]))) ; using oracle, solves this board one line at a time, choosing actions randomly. ; returns a list (perhaps with duplicates) of transitions used during the solution process. ; SOME IMPLEMENTATION NOTES ; - looks at all rows, finds their maximal transitions (if they exist). ; - chooses one transition uniformly randomly, and applies the entire thing (define (rollout-board-solution orig-brd) (define brd (copy-board orig-brd)) (define (transition-for bl) (define tctx (strongest-deduction-of (board-line-line bl))) (and tctx (not (equal? (line-transition-start tctx) (line-transition-end tctx))) (cons bl tctx))) (let loop ([acc empty]) (cond [(board-solved? brd) (reverse acc)] [else (define all-infos (board-line-infos brd)) (define all-tctxs (filter-map transition-for all-infos)) (cond [(empty? all-tctxs) #f] [else ; choose a transition randomly, apply it, and loop until board is solved (match-define (cons bl tctx) (choose-random all-tctxs)) (board-set-line! brd (struct-copy board-line bl [line (line-transition-end tctx)])) (loop (cons tctx acc))])]))) (define (run-board-solution-rollouts boards rollouts-per-board) (define items (append-map (λ (b) (make-list rollouts-per-board b)) boards)) (define r (parallel-map/place #:map (λ (_ item) (rollout-board-solution item)) #:list items)) (printf "len: ~a\nitems: ~a\n" (length r) (map length r)) (apply append r))
false
333517536964b6b505ebc1e5b3f86e313572b8d4
d9db2b78867a172cf1cc6c0a346066a7b8f233e7
/private/syntax.rkt
b461670d9149be53457bbd10fa8e7182cef0e5a5
[]
no_license
sabjohnso/abstraction
5a720e2db5b629bf5cb7760bf167f60afbfe4559
ea712cdfab64483ca31633e4ecdbb851f5b2fe73
refs/heads/master
2020-03-26T02:48:18.478699
2018-08-11T23:46:54
2018-08-11T23:46:54
144,425,093
0
0
null
null
null
null
UTF-8
Racket
false
false
2,167
rkt
syntax.rkt
#lang racket/base (provide (all-defined-out) (all-from-out "environment.rkt")) (require (only-in yutes lambda-curried call-with cut) "environment.rkt") (define-syntax begin-m (syntax-rules (- ~) [(_ e) e] [(_ - e1 e2 es ...) (bind e1 (lambda (_) (begin-m e2 es ...)))] [(_ ~ e1 e2 es ...) (bind (pure e1) (lambda (_) (begin-m e2 es ...)))] [(_ e1 e2 es ...) (bind (pure e1) (lambda (_) (begin-m e2 es ...)))])) (define-syntax let-m (syntax-rules (<~ <- <=) [(_ ([x <- mx]) e es ...) (bind mx (lambda (x) (begin-m e es ...)))] [(_ ([x <~ mx]) e es ...) (bind (pure mx) (lambda (x) (begin-m e es ...)))] [(_ ([x mx]) e es ...) (bind (pure mx) (lambda (x) (begin-m e es ...)))] [(_ ([x <= y]) e es ...) (bind (return y) (lambda (x) (begin-m e es ...)))] [(_ ([x <- mx] binding bindings ...) e es ...) (bind mx (lambda (x) (let-m (binding bindings ...) e es ...)))] [(_ ([x <~ mx] binding bindings ...) e es ...) (bind (pure mx) (lambda (x) (let-m (binding bindings ...) e es ...)))] [(_ ([x mx] binding bindings ...) e es ...) (bind (pure mx) (lambda (x) (let-m (binding bindings ...) e es ...)))] [(_ ([x <= y] binding bindings ...) e es ...) (bind (return y) (lambda (x) (let-m (binding bindings ...) e es ...)))])) (define-syntax let-w (syntax-rules () [(_ ([x wx]) e) (extend (pure wx) (lambda (arg) (lambda (w) (let ([x (call-with w (extract arg))]) e))))] [(_ ([x wx] [y wy] [zs wzs] ...) e) (extend (zapp* (trans (lambda-curried (x y zs ...) (list x y zs ...)) (pure wx)) (pure wy) (pure wzs) ...) (lambda (arg) (lambda (w) (let-values ([(x y zs ...) (apply values (call-with w (extract arg)))]) e))))] #; [(_ ([x wx] [y wy] [zs wzs] ...) e) ; (trans ; (compose (lambda (x y zs ...) e) ; (lambda (arg) (apply values arg))) ; (zapp* (trans (lambda-curried (x y zs ...) (list x y zs ...)) (pure wx)) ; (pure wy) ; (pure wzs) ...))]))
true
b28d351f0f9a904ee13ac9a3c53775da92657ec6
560f77c4f107debbe3274823972057ac49073979
/logic.rkt
5ca76377d2b63dac26d76cf5d3c5aa2e8f787c9f
[]
no_license
evolic/earthgen
52fe964146b9c42dce02664ea6b2ef64e33ad516
cd760771c01b8eb35691e3913b1fdaf32d3b1225
refs/heads/master
2021-01-21T12:35:38.139852
2014-07-16T21:11:33
2014-07-16T21:11:33
null
0
0
null
null
null
null
UTF-8
Racket
false
false
744
rkt
logic.rkt
#lang racket (require racket/stream) (provide true? false? all any one none both neither either one-or-both one-or-neither) (define (true? a) (eq? true a)) (define false? not) (define all stream-andmap) (define any stream-ormap) (define ((true-count n) f ls) (= n (stream-count f ls))) (define one (true-count 1)) (define (none f ls) (not (any f ls))) (define (both f a b) (and (f a) (f b))) (define (neither f a b) (not (one-or-both f a b))) (define (either f a b) (not (or (both f a b) (neither f a b)))) (define (one-or-both f a b) (or (f a) (f b))) (define (one-or-neither f a b) (not (both f a b)))
false
2f675c090b59d7756bb51fb8ecfa9bdc4d6041cc
063934d4e0bf344a26d5679a22c1c9e5daa5b237
/margrave-examples-internal/cornell/filter/filter.rkt
c51b997e0ade18fe6adaeea12d01ff9c17f66958
[]
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
2,076
rkt
filter.rkt
#lang margrave LOAD POLICY filter = "filter.p"; /////////////////////////////////////////////////// // Basic query: What WWW traffic is passed by the filter? let q1[sa: IPAddress, da: IPAddress, sp: Port, dp: Port] be filter:permit(sa, sp, da, dp) and dp=$port80; // Get a scenario show q1; // Revise q1 to eliminate cases in which sa=da let q1v2[sa: IPAddress, da: IPAddress, sp: Port, dp: Port] be filter:permit(sa, sp, da, dp) and dp=$port80 and not sa = da; // ignore silly examples // Can see WHY permitted: show q1v2 include filter:rule2_applies(sa, sp, da, dp), filter:rule4_applies(sa, sp, da, dp); /////////////////////////////////////////////////// // Is any of that traffic allowed by an unexpected rule? // (That is: a rule other than the two permit rules.) let q2[sa: IPAddress, da: IPAddress, sp: Port, dp: Port] be q1(sa, da, sp, dp) and not ( filter:rule2_applies(sa, sp, da, dp) or filter:rule4_applies(sa, sp, da, dp)); poss? q2; /////////////////////////////////////////////////// // What rules NEVER fire? (Indicate bugs, bad design, or good engineering!) // careful to not limit to just permit: create a new query that's always true let q3[sa: IPAddress, da: IPAddress, sp: Port, dp: Port] be true under filter; // gives context when no policy references in body show unrealized q3 filter:rule1_applies(sa, sp, da, dp), filter:rule2_applies(sa, sp, da, dp), filter:rule3_applies(sa, sp, da, dp), filter:rule4_applies(sa, sp, da, dp), filter:rule5_applies(sa, sp, da, dp); /////////////////////////////////////////////////// // Why does this rule never fire? // (that is, what rules contribute to it being overshadowed?) let q4[sa: IPAddress, da: IPAddress, sp: Port, dp: Port] be filter:rule4_matches(sa, sp, da, dp); show realized q4 filter:rule1_applies(sa, sp, da, dp), filter:rule2_applies(sa, sp, da, dp), filter:rule3_applies(sa, sp, da, dp), filter:rule5_applies(sa, sp, da, dp);
false
4d941becf83a416234417a467739c8d22abc18ad
d0ec582c3a6233b8063a542332b7d7b99517ffac
/cu/profiles/data-example-example.rkt
237335ceba0b3d0849f716580576324738dc35e8
[]
no_license
lordxist/positive-fragment
2b6a0beb19bbfda7a8313e650f9b1e55344fb586
794d924b144197047101c614b3eef379babd96b9
refs/heads/master
2021-05-02T00:32:05.070725
2018-03-26T09:08:40
2018-03-26T09:08:40
120,945,470
0
0
null
null
null
null
UTF-8
Racket
false
false
1,826
rkt
data-example-example.rkt
#lang s-exp "data-example.rkt" (require "data-sugar.rkt") ;(primitive-pair (mu #s(shift-nat) (((p-shiftnat #s(shift-nat) () () ((p-varn #s(nat) () () ()))) ; (cmd (nvar #s(nat) 0 () ()) ; (zero #s(nat) () () ()))) ; (cmdn daemon #s(impossible) ()))) ; (mu #s(shift-nat) (((p-shiftnat #s(shift-nat) () () ((p-varn #s(nat) () () ()))) ; (cmd (nvar #s(nat) 0 () ()) ; (zero #s(nat) () () ()))) ; (cmdn daemon #s(impossible) ())))) ;(primitive-apply (lambda #s(nat-to-nat) (((p-nattonat #s(nat-to-nat) ; ((p-var #s(nat) () () ())) ; ((p-var #s(nat) () () ())) ()) ; (cmdn (mu #s(shift-nat) ; (((p-shiftnat #s(shift-nat) () () ((p-varn #s(nat) () () ()))) ; (cmd (nvar #s(nat) 0 () ()) ; (zero #s(nat) () () ()))) ; (cmdn daemon #s(impossible) ()))) ; (shiftnat #s(shift-nat) () () ((nvar #s(nat) 0 () ()))))) ; (cmd daemon #s(impossible) ()))) ; (primitive-const (zero #s(nat) () () ()))) (primitive-print #s(nat) (primitive-apply (primitive-fun #s(nat) #s(nat) (((p-var #s(nat) () () ()) (primitive-const (var #s(nat) 0 () ()))))) (primitive-const (zero #s(nat) () () ()))))
false
84edbf82789461300af47f374e2398233ffc942f
3922167fbcc0655bb6fc8bb4886bf0e65d6a155a
/src/form-generics.rkt
50a5f395f2d5cd4d6e8e154804b545ea5b0f4e63
[ "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
1,016
rkt
form-generics.rkt
#lang racket (require racket/generic) (provide form-map form-map-forward form-map-backward form->sexp language-form?) (define-generics language-form #:fast-defaults ([null? (define (form-map f p) '()) (define (form-map-forward f p) '()) (define (form-map-backward f p) '()) (define (form->sexp f) '())] [pair? (define/generic fmap form-map) (define/generic fsexp form->sexp) (define (form-map f p) (cons (fmap (car f) p) (fmap (cdr f) p))) (define (form->sexp f) (cons (fsexp (car f)) (fsexp (cdr f))))]) ;; The generic interface form mapping over language forms [form-map language-form procs] [form-map-forward language-form procs] [form-map-backward language-form procs] [form->sexp language-form]) (define (sexp->form x) (match x [(list (? symbol? ctr) xs ...) ((hash-ref ctr (thunk (error 'sexp->form "unregistered ~a" ctr))) xs)] [(list) '()]))
false
bf8304814ca22086cde741e4784d7afd4b7fe6c4
97c44dbe2be47daf756ef4c5f57960b2dd30b715
/lang/worker.rkt
07260dfb4e5908c621ed6cdf24c77a1d54647abe
[ "ISC" ]
permissive
theia-ide/racket-language-server
a9f11c728229a221fe50778249f38f00afae44c4
e397a130676504fc8b053e6b1f48d49b77b9ad98
refs/heads/master
2021-07-23T13:18:56.720048
2020-04-10T03:23:22
2020-04-10T14:55:23
132,362,355
51
9
null
2020-04-10T14:55:25
2018-05-06T17:48:18
Racket
UTF-8
Racket
false
false
1,251
rkt
worker.rkt
#lang racket/base (require racket/async-channel racket/match) (struct worker (thrd ch)) (define (make-worker work) (define return-to (make-async-channel)) (define (do-work) (define msg (empty-queue thread-try-receive (thread-receive))) (define res (work msg)) (async-channel-put return-to res) (do-work)) (worker (thread do-work) return-to)) (define (worker-receive w last-msg) (define ((try-receive ch)) (async-channel-try-get ch)) (match-define (worker _ ch) w) (define msg (if last-msg last-msg (async-channel-get ch))) (empty-queue (try-receive ch) msg)) (define (worker-send w msg) (match-define (worker thrd _) w) (thread-send thrd msg)) (define (kill-worker w) (match-define (worker thrd _) w) (kill-thread thrd)) (define (empty-queue try-receive last-msg) (define msg (try-receive)) (if msg (empty-queue try-receive msg) last-msg)) (provide make-worker worker-receive worker-send kill-worker) (module+ test (require rackunit) (define (work msg) (add1 msg)) (define wrk (make-worker work)) (worker-send wrk 2) (check-equal? (worker-receive wrk #f) 3) (worker-send wrk 8) (worker-send wrk 4) (worker-send wrk 10) (check-equal? (worker-receive wrk #f) 11))
false
257b0d2fcf2696dc06a498949c09e16b3eb2d98e
1869dabbedbb7bb1f4477a31020633b617eef27f
/synth/synthesize.rkt
fde659dea1c8201e0e070da9bde7c1526c83bbcf
[ "MIT" ]
permissive
billzorn/SAT
0e64e60030162a64026fafb2dc1ab6b40fb09432
664f5de7e7f1b5b25e932fc30bb3c10410d0c217
refs/heads/master
2021-01-12T03:04:31.815667
2017-09-22T00:02:50
2017-09-22T00:02:50
78,153,696
0
0
null
null
null
null
UTF-8
Racket
false
false
5,419
rkt
synthesize.rkt
#lang racket (require "../mmcu/msp430/hints.rkt" "../lib/racket-utils.rkt") (provide run) (struct synthesis (iotab sp stdout stderr fallback strategy) #:transparent) (define racket62 (make-parameter (void))) (define data-prefix (make-parameter (void))) (define out-file (make-parameter (void))) (define op-list (make-parameter (void))) (define (data-file file) (build-path (data-prefix) "io/" file)) (define (begin-synthesis iotab #:width [width 8] #:arity [arity 3] #:index [index 0] #:maxlength [maxlength 4] #:threads [threads 4] #:strategy [strategy 'full] #:fallback [fallback "#f"]) (let*-values ([(sp sp-stdout sp-stdin sp-stderr) (subprocess #f #f #f (racket62) "synapse/cpumodel/synthesize.rkt" "--width" (sprintf "~a" width) "--arity" (sprintf "~a" arity) "--index" (sprintf "~a" index) "--threads" (number->string threads) "--strategy" (sprintf "~a" strategy) "--maxlength" (sprintf "~a" maxlength) (data-file iotab))]) (close-output-port sp-stdin) (synthesis iotab sp sp-stdout sp-stderr fallback (if (list? strategy) (first strategy) strategy)))) (define (condition-result r) (string-replace r "carry-in" "(sr-carry sr)")) (define (end-synthesis synth) (subprocess-wait (synthesis-sp synth)) (let ([stdout-data (port->string (synthesis-stdout synth))] [stderr-data (port->string (synthesis-stderr synth))]) (close-input-port (synthesis-stdout synth)) (close-input-port (synthesis-stderr synth)) (unless (equal? stderr-data "") (fprintf (current-error-port) "Synthesis internal error: ~a\n" stderr-data)) (if (equal? stdout-data "") (synthesis-fallback synth) (let ([results (sread stdout-data)]) ;(printf "[~a]\n" results) (map (λ (result fallback) (if (equal? result "#f") fallback (condition-result result))) results (synthesis-fallback synth)))))) (define (begin-operation-synthesis iotab #:width [width 8] #:maxlengths [maxlengths (list 4 4 4 4 4)] #:strategy [strategy "full"]) (begin-synthesis iotab #:width width #:strategy strategy #:arity '(3 4 4 4 4) #:index '(0 0 1 2 3) #:maxlength maxlengths #:fallback '("(bv 0 20)" "(sr-carry sr)" "(sr-zero sr)" "(sr-negative sr)" "(sr-overflow sr)"))) (define (end-operation-synthesis synth-handle) (define ops (end-synthesis synth-handle)) (define iotab (synthesis-iotab synth-handle)) (define strategy (synthesis-strategy synth-handle)) (case strategy [(full) (fprintf (out-file) #<<END (define (msp-~a sr op1 op2) ~a) (define (msp-sr-~a sr op1 op2 dst) (concat ~a ~a ~a (bv 0 5) ~a)) END iotab (first ops) iotab (second ops) (third ops) (fourth ops) (fifth ops))] [(n4-up) (fprintf (out-file) #<<END (define (msp-~a sr op1 op2) (n4-up.~a (lambda (sr op1 op2) ~a) (lambda (sr op1 op2 dst) ~a))) (define (msp-sr-~a sr op1 op2 dst) (concat (n4-up.~a/c (lambda (sr op1 op2) ~a) (lambda (sr op1 op2 dst) ~a)) ~a ~a (bv 0 5) ~a)) END iotab (second (string-split iotab ".")) (first ops) (second ops) iotab (second (string-split iotab ".")) (first ops) (second ops) (third ops) (fourth ops) (fifth ops))] [else (error "Invalid synthesis strategy ~a" strategy)])) (define (synthesize-operation op) (end-operation-synthesis (begin-operation-synthesis op #:width (bitwidth-hint op) #:maxlengths (maxlength-hint op) #:strategy (strategy-hint op)))) (define (quote->string q) (let ([o (open-output-string)]) (display q o) (get-output-string o))) (define (synthesize-operations ops) (let ([handles (for/list ([op (in-list (map quote->string ops))]) (begin-operation-synthesis op #:width (bitwidth-hint op) #:maxlengths (maxlength-hint op) #:strategy (strategy-hint op)))]) (for ([handle (in-list handles)]) (end-operation-synthesis handle)))) (define (widthshim tab) (fprintf (out-file) "(define (msp-~a bw sr op1 op2) (case bw [(8) msp-~a.b sr op1 op2] [(16) msp-~a.w sr op1 op2] [else (bv 0 20)]))\n" tab tab tab) (fprintf (out-file) "(define (msp-sr-~a bw sr op1 op2 dst) (case bw [(8) msp-sr-~a.b sr op1 op2 dst] [(16) msp-sr-~a.w sr op1 op2 dst] [else (bv 0 20)]))\n" tab tab tab)) (define (run #:racket62 racketpath #:op-list oplist #:data-prefix [datapath "data/"] #:out-file [outfile (current-output-port)]) (parameterize ([racket62 racketpath] [data-prefix datapath] [out-file outfile] [op-list oplist]) (fprintf (out-file) "#lang rosette\n") (fprintf (out-file) "(require \"../../lib/bv-operations.rkt\")\n") (fprintf (out-file) "(provide (all-defined-out))\n\n") (for ([op (in-list (op-list))]) (synthesize-operations (list op))) (close-output-port (out-file))))
false
ace762185348136818cf3b8b6c17997b68b90393
bfdea13ca909b25a0a07c044ec456c00124b6053
/mischief/string.rkt
998e160968b93252154c6716832d08bfa923442f
[]
no_license
carl-eastlund/mischief
7598630e44e83dd477b7539b601d9e732a96ea81
ce58c3170240f12297e2f98475f53c9514225825
refs/heads/master
2018-12-19T07:25:43.768476
2018-09-15T16:00:33
2018-09-15T16:00:33
9,098,458
7
2
null
2015-07-30T20:52:08
2013-03-29T13:02:31
Racket
UTF-8
Racket
false
false
135
rkt
string.rkt
#lang racket/base (provide string-lines) (define (string-lines str) (regexp-split #px"\n" (regexp-replace #px"\n$" str "")))
false
cfb3fcd272d2ab1bd372f0547f7ad07d9e89f2b0
259c841b8a205ecaf9a5980923904452a85c5ee5
/NBE/error.rkt
55ad9db239ef5039c8be2354fb107676dfd562df
[]
no_license
Kraks/the-little-typer
ca7df88c76e4ffc5b8e36ed910bcaa851fadf467
81d69d74aba2d63f9634055ce9f2c313b8bbff3e
refs/heads/master
2020-04-12T00:10:30.654397
2019-03-05T02:09:32
2019-03-05T02:09:32
162,191,489
0
0
null
null
null
null
UTF-8
Racket
false
false
794
rkt
error.rkt
#lang racket (require (for-syntax syntax/parse)) (provide go stop go-on) #| Error handling |# (struct go (result) #:transparent) (struct stop (expr message) #:transparent) (define-syntax (go-on stx) (syntax-parse stx [(go-on () result) (syntax/loc stx result)] [(go-on ([pat0 e0] [pat e] ...) result) (syntax/loc stx (match e0 [(go pat0) (go-on ([pat e] ...) result)] [(go v) (error 'go-on "Pattern did not match value ~v" v)] [(stop expr msg) (stop expr msg)]))])) (define (bigger-than-two n) (if (> n 2) (go n) (stop n "Not greater than two"))) (go-on ([x (bigger-than-two 4)] [y (bigger-than-two 5)]) (go (+ x y))) (go-on ([x (bigger-than-two 1)] [y (bigger-than-two 5)]) (go (+ x y)))
true
197937996ce7648008fa22527462d516362affa0
d755de283154ca271ef6b3b130909c6463f3f553
/htdp-lib/2htdp/private/universe-image.rkt
d2b0263bf2554d7db39359430da4c0409c9b6e1b
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
racket/htdp
2953ec7247b5797a4d4653130c26473525dd0d85
73ec2b90055f3ab66d30e54dc3463506b25e50b4
refs/heads/master
2023-08-19T08:11:32.889577
2023-08-12T15:28:33
2023-08-12T15:28:33
27,381,208
100
90
NOASSERTION
2023-07-08T02:13:49
2014-12-01T13:41:48
Racket
UTF-8
Racket
false
false
2,212
rkt
universe-image.rkt
#lang racket/base (require (prefix-in 2: 2htdp/image) (prefix-in 2-core: mrlib/image-core) (prefix-in 1: htdp/image) racket/class htdp/error) (provide image? scene? image-width image-height text 2:image? check-image check-scene check-scene-result check-scene-dimensions disable-cache) (define (disable-cache x) (if (is-a? x 2-core:image%) (2-core:un/cache-image x #f) x)) (define (scene? x) ;; be sure to check 2:image? first so that ;; bitmaps are always okay (more specifically, ;; so that we don't reject a 2htdp/image universe ;; program that uses a bitmap (bitmap pinholes ;; are not at (0,0).)). (or (2:image? x) (1:scene? x))) (define (image? x) (or (1:image? x) (2:image? x))) (define (text a b c) (2:text a b c)) (define (image-width x) (check-arg 'image-width (image? x) 'image 1 x) (if (2:image? x) (2:image-width x) (1:image-width x))) (define (image-height x) (check-arg 'image-height (image? x) 'image 1 x) (if (2:image? x) (2:image-height x) (1:image-height x))) ;; Symbol Any String String *-> Void (define (check-image tag i rank . other-message) (if (and (pair? other-message) (string? (car other-message))) (check-arg tag (image? i) (car other-message) rank i) (check-arg tag (image? i) "image" rank i))) (define (check-scene tag i rank) (define error "image with pinhole at (~s,~s)") (if (2:image? i) i (if (1:image? i) (check-arg tag (1:scene? i) "scene" rank (image-pins i)) (check-arg tag #f "scene" rank i)))) (define (check-scene-result tname i) (if (2:image? i) i (if (1:image? i) (check-result tname 1:scene? "scene" i (image-pins i)) (check-result tname (lambda _ #f) "scene" i)))) (define (check-scene-dimensions name width height) (unless(and (<= 0 width 2000) (<= 0 height 2000)) (define basics "cannot render images larger than 2000 x 2000 pixels") (error 'big-bang "~a; the dimension demanded by ~a are ~a by ~a" basics name width height))) (define (image-pins i) (format "image with pinhole at (~s,~s)" (1:pinhole-x i) (1:pinhole-y i)))
false
c33c066066ee411e8c13e6c840a2e0c1cf5109c6
82f508288c1bfc3edfe3c101d49697ca57172a5f
/racket-700langs/more-slides.rkt
59c1a5147976663200ab3d8f1fddb83da97c14d0
[]
no_license
ericssmith/presentations
d3eaa11967ceecdf6a16e8fd1b23b87092e2e49e
24c30de7f42b254b2a183cdbccdf4d8a44a8ac22
refs/heads/master
2021-01-24T02:34:18.862041
2017-09-22T20:52:07
2017-09-22T20:52:07
6,692,263
3
2
null
null
null
null
UTF-8
Racket
false
false
10,529
rkt
more-slides.rkt
(slide #:title "Conditional expressions, recursion,functional arguments" #:layout 'tall (para "symbolic differentiation -> recursive functions, maplist -> functional arguments (apparently trouble defining maplist (AIM-001, AIM-002) lead him to lambda (or maybe lead him again to lambda).") ) (slide #:title "The Revised Revised Report on Scheme" #:layout 'tall (t "One Thing to name them all") (t "One Thing to define them") (t "One Thing to place them in environments") (t "and bind them")) (slide #:title "Revised Report on the Algorithmic Language Algol 60" #:layout 'tall (para "By J.W. Backus, F.L. Bauer, J.Green, C. Katz, J. McCarthy, P. Naur, A.J. Perlis, H. Rutishauser, K. Samuelson, B. Vauquois, J.H. Wegstein, A. van Wijngaarden, M. Woodger, Edited by Peter Naur") 'next (t "Revised(3) Report on the Algorithmic Language Scheme") (t "Dedicated to the Memory of ALGOL 60") 'next (colorize (t "♥") "red") ) (slide #:title "Algol60" #:layout 'tall (vl-append (current-code-line-sep) (tt "#lang algol60") (tt "begin") (tt " integer procedure SIGMA(x, i, n);") (tt " value n;") (tt " integer x, i, n;") (tt " begin") (tt " integer sum;") (tt " sum := 0;") (tt " for i := 1 step 1 until n do") (tt " sum := sum + x;") (tt " SIGMA := sum;") (tt " end;") (tt " integer q;") (tt " printnln(SIGMA(q*2-1, q, 7));") (tt "end")) (colorize (hline (* 3/4 client-w) gap-size) "green") (tt "49")) (slide #:title "???" #:layout 'tall (para "The purpose of the algorithmic language is to describe computational processes. The basic concept used for the description of calculating rules is the well known arithmetic expression containing as constituents numbers, variables, and functions. From such expressions are compounded, by applying rules of arithmetic composition, self-contained units of the language -- explicit formulae -- called assignment statements.")) (slide #:title "Higher order Function aka Funargs" #:layout 'tall (vl-append (current-code-line-sep) (tt "procedure euler(fct,sum,eps,tim);") (tt " value eps,tim; integer tim;") (tt " real procedure fct;") (tt " real sum,eps;") (para " comment euler computes the sum of fct(i) for i from zero up to infinity by means of a suitably refined euler transformation.;")) ) (slide #:title "Lexical Scope" #:layout 'tall (t "Paraphrasing Wikipedia:") (para "ALGOL was the first language implementing nested function definitions with lexical scope.") (para "ALGOL is generally considered the first higher order programming language.")) (slide #:title "Lexical Scope" #:layout 'tall 'alts (list (list (t "The Funarg Problem Explained, by Joseph Weizenbaum:")) (list (t "x*x + y*y")) (list (t "g(y) = x*x + y*y")) (list (t "f(x) = g where g(y) = x*x + y*y")) (list (t "f(x) = g where g(y) = x*x + y*y") (t "p = f(3)")) (list (t "f(x) = g where g(y) = x*x + y*y") (t "p = f(3)") (t "what is p(4)?")) (list (code (+ (* x x) (* y y)))) (list (code (define (g y) (+ (* x x) (* y y))))) (list (code (define (f x) (define (g y) (+ (* x x) (* y y))) g))) (list (code (define (f x) (define (g y) (+ (* x x) (* y y))) g) (define p (f 3)))) (list (code (define (f x) (define (g y) (+ (* x x) (* y y))) g) (define p (f 3)) (p 4))) (list (code (define (f x) (define (g y) (+ (* x x) (* y y))) g) (define p (f 3)) (p 4) (let ((x 10)) (p 4)))))) (slide #:title "Closure" #:layout 'tall (para "show a representation (maybe from the Racket manual of the closure p from the example") ) (slide #:title "NOTE: Scheme supports multiple parameters" #:layout 'tall (code (define (f x y) (+ (* x x) (* y y))) (f 3 4)) (para "but the point in lexical scope was to show nested functions.") ) (slide #:title "forshadowing:" #:layout 'tall (code (define (f x) (define (g y) (+ (* x x) (* y y))) g) (code:comment "terse:") (define ((f x) y) (+ (* x x) (* y y))) (code:comment "verbose:") (define f (lambda (x) (lambda (y) (+ (* x x) (* y y))))))) (slide #:title "call by value" #:layout 'tall (item "Steele: call by name -> call by value") ) (slide #:title "Objects and Actors" #:layout 'tall (t "Inspired in part by SIMULA and Smalltalk, Carl Hewitt developed a model of computation around “actors”") (item "Every agent of computation is an actor") (item "Every datum or data structure is an actor") (item "An actor may have “acquaintances” (other actors it knows)") (item "Actors react to messages sent from other actors") (item "An actor can send messages only to acquaintances and to actors received in messages") (para "“You don’t add 3 and 2 to get 5; instead, you send 3 a message asking it to add 2 to itself”") (t "JAOO-SchemeHistory-2006public.pdf")) (slide #:title "from actors to tail calls" #:layout 'tall (t "Hewitt: actors") (t "reference") (t "Steele & Sussman: actors?") (t "JAOO-SchemeHistory-2006public.pdf") (t "Goal: understanding by implementation.") (item "http://neopythonic.blogspot.com/2009/04/tail-recursion-elimination.html") (item "http://jeapostrophe.github.com/2013-07-08-stack-post.html") (para "In a tail-recursive, lexically scoped language, if your primitives operators are functions, you will tend to write programs in a functional style. If your primitive operators are actors, you will tend to write programs in an actor style.")) (slide #:title "metaprogramming aka macros / the story of hygiene" #:layout 'tall (para "lisp.ps: this feature probably accounts for LISP's success in competition with these languages, especially when large programs have to be written. The advantage is like that of binary computers over decimal - but larger.") (para "a new generation of programmers appeared who preferred internal notation to any FORTRAN-like or ALGOL-like notation that could be devised.") (item "A lisp (small core + metaprogramming aka macros)") (code (let ((x 2)) (+ 1 x))) (t "versus") (code ((lambda (x) (+ x 1)) 2))) (slide #:title "tail call" #:layout 'tall (bitmap "functions.png") (para "An expression expr1 is in tail position with respect to an enclosing expression expr2 if, whenever expr1 becomes a redex, its continuation is the same as was the enclosing expr2’s continuation. (racket manual)")) (slide #:title "modules" #:layout 'tall (t "remember this?") (t "g(y) = x*x + y*y") ) (slide #:title "languages" #:layout 'tall ) (slide #:title "A History of Good Ideas" #:layout 'tall (item "lexical scope") (item "tail recursion") (item "macros") (item "modules") (item "languages") (item "continuations ?") (item "multi-return function call ?") (item "reactive programming") (item "samth's extensible match") (item "constraint programming") (item "the list goes on and on...") ) (slide (para "AIM-452 aka R1RS: We discovered (the hard way) that the straightforward implementation of EVALUATE (destroys referential transparency.") ) (slide #:title "0, nil, false" (para "lisp: Besides encouraging pornographic programming, giving a special interpretation to the address 0 has caused difficulties in all subsequent implementations.")) (slide #:title "λ the ultimate" 'alts (list (list (para "The λ-calculus can be seen as a universal glue by which compound constructs can be built inductively from simpler ones and a set of primitives. In particular, if our primitives are functions,then our constructs are functions; if our primitives are relations,then our constructs are relations; if our primitives are actors, then our constructs are actors. The essence of the matter is that the λ-calculus provides a way of abstracting entities of any particular type and then combining such abstractions with other entities to make new entities of that same type, which are instances of the abstractions.")) (list (para "This became apparent to us in, for example, the development of constraint languages. A λ-expression (or its “value”) may be a function (if its application yields a value), but it is more general and more fruitful to regard it as an abstraction. Similarly, a combination is not always a “function call”; it is more general simply to speak of instantiating an abstraction. Given the right primitives,the λ-calculus can serve as a foundation for the abstraction and instantiation of virtually any kind of complex conceptual structure.")))) (slide #:title "property lists on atoms, see lisp:, lead to bad module systems. also closure meta, eq? tables, etc.") (slide #:title "scribble, slideshow, Redex" (t "Docs with indexs?") (t "Slides with unit tests?") (t "Papers with test suites?") (para "McCarthy recalls (22): ... this EVAL was written and published in the paper and Steve Russell said, look, why don't I program this EVAL and you remember the interpreter, and I said to him, ho, ho, you're confusing theory with practice, this EVAL is intended for reading not for computing. But he went ahead and did it. That is, he compiled the EVAL in my paper into 704 machine code fixing bugs and then advertised this as a LISP interpreter which it certainly was, so at that point LISP had essentially the form that it has today, the S-expression form ...") ) (slide #:title "concepts left out" (t "quotation, John McCarthy figured this out early on.") (t "label, for recursive function definition") (t "apply first in terms of substitutions finally to bindings") (t "garbage collection.") ) (slide #:title "What did I learn" (t "Lambda is pure abstraction.") (t "Your primitives determine what you abstract over.") (t "functions, actors, relations, whatever")) (slide (t "fin")) (slide #:title "main points" #:layout 'tall (item (para "Lambda is abstraction. Primitive make it functional, actor, oop, relational,, or xxxxxx style.")) (item (para "Understand xxxxxx Style in terms of abstraction over primitives before adding sugar.")) (item (para "Worse may be better in the short term, but pay attention to the communities that cultivate best practices over the long term.")) (item (para "The turtle keeps going long after the hare is dead, decomposed, and forgotten.")) )
false
a5d98bb74fce3e7fcaa8e04b808aaf084f6b9f5c
dea90bc467e1247e901b0212f2f63a6fbf815899
/rune2/util.rkt
1d92e82f661c32d295cdef6e7bb7dfc728cf6cb3
[]
no_license
jeapostrophe/rune
f76481890cc0467f98d4d9958ae4e359359c111e
c1fe743fb7c137736308899a4e785fc17ae5c286
refs/heads/master
2022-12-12T12:30:18.613498
2019-07-13T00:09:49
2019-07-13T00:09:49
10,560,002
4
0
null
null
null
null
UTF-8
Racket
false
false
441
rkt
util.rkt
#lang racket/base (require racket/async-channel) (define (writeln v [out (current-output-port)]) (write v out) (newline out) (flush-output out)) (define (read-evt ip) (define read-ch (make-async-channel)) (define read-t (thread (λ () (let loop () (define v (read ip)) (async-channel-put read-ch v) (unless (eof-object? v) (loop)))))) read-ch) (provide (all-defined-out))
false
44f8a278a042e50c567503e1a6c858a61cb2eb25
d081ccc87078307aabb7ffc56ecc51e2e25d653d
/tests/lint/no-lang.rkt
359adc932d1c5788920d461f837b4cce8e8847f4
[ "BSD-3-Clause" ]
permissive
Bogdanp/racket-review
75501945155a5f75a0684e60ae6934fb2617e655
bc7b614e3b6ab11a9f569d254aaba7f2d2074354
refs/heads/master
2023-08-21T20:16:54.808995
2023-07-28T18:28:24
2023-07-28T18:28:24
191,135,877
40
3
BSD-3-Clause
2022-08-08T08:10:11
2019-06-10T09:17:45
Racket
UTF-8
Racket
false
false
20
rkt
no-lang.rkt
(displayln "hello")
false
26b4204eedef55052ac5633b2f61d9af42d01d76
ad2d689356289c7ba80d834b051a233bc437d4f9
/commands/racket-scripts-compile.rkt
a4b61165d9c07236b10d033158c4077fdf726c20
[]
no_license
willghatch/dotfileswgh
c141fc256bdb5aa20edb45b1871007bfeebae4f4
4614c9d5ef16be411ad9f7cbcafec71060be2a8a
refs/heads/master
2023-09-01T12:52:01.851093
2023-08-29T17:24:04
2023-08-29T17:24:04
15,466,845
5
1
null
null
null
null
UTF-8
Racket
false
false
648
rkt
racket-scripts-compile.rkt
#!/usr/bin/env racket #lang rash (require racket/string racket/list) (define (racket-script? f) (and (file-exists? f) #{head -n 1 $f |>> string-contains? _ "racket"})) (define user #{whoami}) (define path-dirs (remove-duplicates (string-split (getenv "PATH") ":"))) (for ([d path-dirs] #:when (and (directory-exists? d) (equal? user #{stat -L --format=%U $d}))) (define scripts (filter racket-script? (map (λ (f) (build-path d f)) (directory-list d)))) (when (not (null? scripts)) { echo raco make $scripts raco make $scripts }))
false
fb3a5038fd96f5ac49c67b8a2515f848aaaa1002
3ff658af1c58e6009d60aba7f7a0192590c828ce
/pd2af/server/libs/odysseus_modules/pd2af/translate.rkt
0034d64b92842e133de31c35e946f36e8eae908b
[]
no_license
acanalpay/pd2af-converter
ab994f52deacd96bc423365b1719bc734cae7b08
b4c812172d747d32ae286db7b2efcdcf10fb7409
refs/heads/master
2023-06-06T08:10:42.247438
2021-06-30T07:38:35
2021-06-30T07:38:35
381,607,483
0
0
null
null
null
null
UTF-8
Racket
false
false
1,870
rkt
translate.rkt
#lang racket (require "xml2pd.rkt" "pd2pd.rkt" "pd2af.rkt" "af2af.rkt" "xml2xml.rkt") (require "../../odysseus/lib/_all.rkt") (require "../../odysseus_modules/sbgn/common.rkt") (require "../../odysseus_modules/sbgn/types.rkt") (require "../../odysseus_modules/sbgn/context.rkt") (require "../../odysseus_modules/sbgn/sexp.rkt") (require "../../odysseus_modules/sbgn/geometry.rkt") (require "../../odysseus_modules/sbgn/sexp2ctx.rkt") (require "../../odysseus_modules/sbgn/ctx2xml.rkt") (require compatibility/defmacro) (provide (all-defined-out)) (define (sort-by-names a b) (cond ; if no compartment (compatment = #f): ((or (not (first a)) (not (first b))) (string<? (second a) (second b))) ; if the same compartment: ((string=? (first a) (first b)) (string<? (second a) (second b))) ; order by compartments otherwise: (else (string<? (first a) (first b))))) (define (pd-str->pd pd-str) (let* ((pd-form (read (open-input-string pd-str))) (pd-context (sexp->context pd-form)) (pd-sexp (context->sexp pd-context)) (pd (HG pd-context pd-sexp))) pd)) (define-catch (get-af-context af-str) (sexp->context (read (open-input-string af-str)))) (define-catch (translate-pd pd) (let* ((af-context (pd2af (HG-sexp pd) (HG-context pd)))) (->> remove-self-loops strip-off-state-prefix-if-no-duplication af-context))) (define-macro (sbgn-ml->af-xml sbgn_ml) `(let* ( ; clean incoming XML from <annotation> tag and similar things (sbgn_ml (clean-sbgn-ml ,sbgn_ml)) ; parse SBGN ML into context and sexp (pd (parse-pd-sbgn-ml sbgn_ml)) ; translate SBGN PD and get result in the form of AF context (af-context (translate-pd pd)) ; generate XML from the AF context (af-xml (context->xml af-context #:map-type "activity flow"))) af-xml))
false
d97d5f8df1695a1bb19e98a313ea4c5d7fa2471e
ece0cff46980dd817abc5af494783a839786e523
/lib/test-vm.rkt
f159708bf1d76bf930f9983ce1b2883433ae1372
[ "MIT" ]
permissive
tiagosr/nanopassista
768ecd9e16f21b69aa48606f9514f58779f58a79
4950e9d44479fea7f404a777ce1166db2031833b
refs/heads/master
2021-01-01T17:21:58.809755
2015-04-11T22:17:37
2015-04-11T22:17:37
32,051,289
2
0
null
null
null
null
UTF-8
Racket
false
false
7,195
rkt
test-vm.rkt
#lang racket (require "util.rkt") #| | Tiny virtual machine for testing |# (define (*vm* a ;; accumulator x ;; current code "word" pointer f ;; frame pointer c ;; current closure s ;; argument stack pc ;; program counter ) (define (list-args s n) (let loop ([n (- n 1)] [a '()]) (if (< n 0) a (loop (- n 1) (cons (index s n) a))))) (define (list-args2 s x n) (let loop ([n (- n 1)] [x (- x 1)] [a '()]) (if (< n 0) a (loop (- n 1) (- x 1) (cons (index s x) a))))) (define (shift-args n m s) (let nextarg ([i (- n 1)]) (unless (< i 0) (index-set! s (+ i m) (index s i)) (nextarg (- i 1)))) (- s m)) (let ([key (nth 0 x)]) (case key ; stops the virtual machine returning the accumulator register ['halt a] ; dereferences a variable from the locals stack ['lref (*vm* (index f (nth 1 x)) (cddr x) f c s (+ 1 pc))] ; dereferences a variable from the current frame ['fref (*vm* (index-closure c (nth 1 x)) (cddr x) f c s (+ 1 pc))] ; dereferences a variable from the globals vector ['gref (*vm* (index-global (nth 1 x)) (cddr x) f c s (+ 1 pc))] ; unboxes the current accumulator value ['unbox (*vm* (unbox a) (cdr x) f c s (+ 1 pc))] ; dereferences a value from the constant pool ['const (*vm* (nth 1 x) (cddr x) f c s (+ 1 pc))] ; pushes a value to the argument stack ['push (*vm* a (cdr x) f c (push a s) (+ 1 pc))] ; pushes a frame to the argument stack ['frame (*vm* a (cddr x) f c (push (ncdr (+ 2 (nth 1 x)) x) (push f (push c s))) (+ 1 pc))] ; returns from a scheme subroutine ['return (let ([s (- s (nth 1 x))]) (*vm* a (index s 0) (index s 1) (index s 2) (- s 3) (+ 1 pc)))] ; calls a subroutine or primitive procedure ['call (if (procedure? a) (*vm* (let loop ([i (- (nth 1 x) 1)] [lst '()]) (if (< i 0) (apply a lst) (loop (- i 1) (cons (index s i) lst)))) (ncdr 2 x) f c s (+ 1 pc)) (let ([type (closure-type a)]) (case type ['close1 (let ([diff (- (nth 1 x) 1)]) (index-set! s diff (list-args s (nth 1 x))) (*vm* a (closure-body a) (- s diff) a (- s diff) (+ 1 pc)))] ['close2 (let ([diff (- (nth 1 x) (closure-argnum a))]) (index-set! s (- (nth 1 x) 1) (list-args2 s (nth 1 x) (+ diff 1))) (let ([st (shift-args (- (closure-argnum a) 1) diff s)]) (*vm* a (closure-body a) s a s (+ 1 pc))))] ['close0 (*vm* a (closure-body a) s a s (+ 1 pc))])))] ; tests a value for truth ['test (*vm* a (if a (ncdr 2 x) (ncdr (+ 2 (nth 1 x)) x)) f c s (+ 1 pc))] ; jumps straight to a given position in code ['jump (*vm* a (ncdr (+ 2 (nth 1 x)) x) f c s (+ 1 pc))] ['shift (*vm* a (ncdr 3 x) f c (shift-args (nth 1 x) (nth 2 x) s) (+ 1 pc))] ;; make closure: type args# body n s ['close0 (*vm* (closure 'close0 (nth 2 x) (ncdr 4 x) (nth 1 x) s) (ncdr (+ 4 (nth 3 x)) x) f c (- s (nth 1 x)) (+ 1 pc))] ['close1 (*vm* (closure 'close1 (nth 2 x) (ncdr 4 x) (nth 1 x) s) (ncdr (+ 4 (nth 3 x)) x) f c (- s (nth 1 x)) (+ 1 pc))] ['close2 (*vm* (closure 'close2 (nth 2 x) (ncdr 4 x) (nth 1 x) s) (ncdr (+ 4 (nth 3 x)) x) f c (- s (nth 1 x)) (+ 1 pc))] ; boxes a variable ['box (index-set! s (nth 1 x) (box (index s (nth 1 x)))) (*vm* a (ncdr 2 x) f c s (+ 1 pc))] ; sets a local variable ['lset (set-box! (index f (nth 1 x)) a) (*vm* a (ncdr 2 x) f c s (+ 1 pc))] ; sets a global variable ['gset (*vm* (assign-global! (nth 1 x) a) (ncdr 2 x) f c s (+ 1 pc))] ; sets up a continuation ['conti (*vm* (continuation s) (ncdr 1 x) f c s (+ 1 pc))] ; runs a continuation ['nuate (*vm* a (ncdr 2 x) f c (restore-stack (nth 1 x)) (+ 1 pc))] ['fset (set-box! (index-closure c (nth 1 x)) a) (*vm* a (ncdr 2 x) f c s (+ 1 pc))] ))) (define stack (make-vector 2000)) (define (push x s) (vector-set! stack s x) (+ s 1)) (define (index s i) (vector-ref stack (- s i 1))) (define (index-set! s i v) (vector-set! stack (- s i 1) v)) (define (closure type argnum body n s) (let ([v (make-vector (+ n 3))]) (vector-set! v 0 type) (vector-set! v 1 argnum) (vector-set! v 2 body) (let f ([i 0]) (unless (= i n) (vector-set! v (+ i 3) (index s i)) (f (+ i 1)))) v)) (define (closure-body c) (vector-ref c 2)) (define (closure-type c) (vector-ref c 0)) (define (closure-argnum c) (vector-ref c 1)) (define (index-closure c n) (vector-ref c (+ n 3))) (define *heap-ref* 99900) (define *heap* (make-vector 150000)) (define *heap-pnt* *heap-ref*) (define (box x) (vector-set! *heap* (- *heap-pnt* *heap-ref*) x) (set! *heap-pnt* (+ 1 *heap-pnt*)) (- *heap-pnt* 1)) (define (unbox i) (vector-ref *heap* (- i *heap-ref*))) (define (set-box! p x) (vector-set! *heap* (- p *heap-ref*) x)) (define (continuation s) (define (save-stack s) (let ([v (make-vector s)]) (let copy ([i 0]) (unless (= i s) (vector-set! v i (vector-ref stack i)) (copy (+ i 1)))) v)) (closure 'close0 -1 (list 'lref 0 'nuate (save-stack s) 'return 0) 0 0)) (define (restore-stack v) (let ([s (vector-length v)]) (let copy ([i 0]) (unless (= i s) (vector-set! stack i (vector-ref v i)) (copy (+ i 1)))) s)) (define *globals-v* (make-vector 200)) (define (assign-global! i x) (vector-set! *globals-v* i x)) (define (index-global i) (vector-ref *globals-v* i)) (define (show-globals) (trace #t "~% [g] --- ~A~%" *globals-v*)) ; debugging (define *debug-flag* #f) (define *output-globals* #f) (define *debug-out-port* #t) (define *show-stack* #t) (define *show-reg-c* #t) (define (show-reg a x f c s pc) (trace #t "~% [a] | ~A~% [x] | ~A~% [pc] | ~A~% [f] | ~A~% [c] | ~A~% [s]" a x pc f (if *show-reg-c* c "")) (if *show-stack* (ins-st s) #f)) (define (ins-st p) (trace #t "=> ~3@A [ ]~%" p) (let loop ([i p]) (unless (or (< i 1) (< (+ i 1) p)) (trace #t " ~A [ ~10@A ]~%" (- i 1) (index p (- p i))) (loop (- i 1))))) (define (trace opt frmt . args) (if *debug-flag* (apply format *debug-out-port* frmt args) (void))) (provide (rename-out [*vm* test:vm]))
false
0a9541c881a5dc3029f3bebaa0dba30840efa3d9
4e0a501ebb8e58e360cd21156957aa79f15c5a47
/promotion.rkt
58d82e0ff7230073332271687c8177eba582c382
[]
no_license
anjali227/Mutiplayer-chess
e8a73768128b6f908dc4340311d19d4608a56e15
7b9a0b9b7bfe5f5296c233f72e56fbc971ee9c00
refs/heads/main
2023-06-28T22:27:08.347631
2021-07-23T08:26:16
2021-07-23T08:26:16
388,729,641
0
0
null
null
null
null
UTF-8
Racket
false
false
940
rkt
promotion.rkt
#lang racket (require racket/gui) (require (rename-in 2htdp/image (make-pen 2htdp:make-pen) (make-color 2htdp:make-color))) (provide (all-defined-out)) (define promotion-frame (new frame% [label "Promotion"] [width 340] [height 120] [style '(no-resize-border)])) (send promotion-frame show #t) (define prom-canvas% (class canvas% (define/override (on-event event) (prom-click event)) (super-new))) (define prom-canvas (new prom-canvas% [parent promotion-frame] [paint-callback (lambda (canvas dc) (promotion dc))])) (define (promotion dc) (overlay (text "Congratulations, your pawn has been promoted!" 24 "olive") (empty-scene 340 120))) (define (prom-click event) (cond [(eq? (send event get-event-type) 'left-down) (display (cons (send event get-x) (send event get-y))) (newline)]))
false
14da12b75d4dd2f8f74fe18808e03404726c6e7e
b08b7e3160ae9947b6046123acad8f59152375c3
/Programming Language Detection/Experiment-2/Dataset/Train/Racket/voronoi-diagram-3.rkt
bd4b9119829b5c27238eac66a4c1d78757630d71
[]
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
867
rkt
voronoi-diagram-3.rkt
;; Plots the Voronoi diagram as a contour plot of ;; the classification function built for a set of points (define (plot-Voronoi-diagram2 point-list) (define n (length point-list)) (define F (classification-function point-list)) (plot (list (contour-intervals (compose F vector) 0 1 0 1 #:samples 300 #:levels n #:colors (range n) #:contour-styles '(solid) #:alphas '(1)) (points point-list #:sym 'fullcircle3)))) ;; For a set of centroids returns a function ;; which finds the index of the centroid nearest ;; to a given point (define (classification-function centroids) (define tbl (for/hash ([p (in-list centroids)] [i (in-naturals)]) (values p i))) (λ (x) (hash-ref tbl (argmin (curry (metric) x) centroids))))
false
99b3b67f700797248748573eee5d2047bae9a0ef
b6a5637b6d3fc8ad1b7996c62ec73b6d895c5e95
/ch1/1.2/ex-1.11.rkt
d94b181bbd774a5fabfa21e390215661e9e5956f
[ "MIT" ]
permissive
abelkov/sicp-musings
8911b5215b42fc21c15699b11cdb68727852d399
49373974eb3df8e12ad086ddfabda14b95f139ba
refs/heads/master
2021-06-12T03:55:16.842917
2017-01-31T19:02:45
2017-01-31T19:02:45
null
0
0
null
null
null
null
UTF-8
Racket
false
false
475
rkt
ex-1.11.rkt
#lang racket (define (f-recursive n) (if (< n 3) n (+ (f-recursive (- n 1)) (* 2 (f-recursive (- n 2))) (* 3 (f-recursive (- n 3)))))) (define (f-iterative n) (define (iter a b c count) (cond [(= count 0) a] [(= count 1) b] [(= count 2) c] [else (iter b c (+ c (* 2 b) (* 3 a)) (- count 1))])) (iter 0 1 2 n)) (= (f-recursive 10) (f-iterative 10))
false
cd7088bd87b719b28ba4d639a92f4810472fc9cf
924ba7f58142338d2e50d19d83d5eaa2b03491c8
/musicxml/measure.rkt
f29ccf122ecbb70e5df341c408827c39cda63b83
[ "MIT" ]
permissive
AlexKnauth/musicxml
d793ca90402ae468f8389623fdf216893031a617
60018ccd9fc1867d6feebdcfa698ddb5c07cd524
refs/heads/master
2022-07-01T17:00:09.123436
2022-05-28T17:47:30
2022-05-28T17:47:30
135,214,350
0
0
null
null
null
null
UTF-8
Racket
false
false
1,714
rkt
measure.rkt
#lang racket/base (provide (except-out (all-defined-out) attributes/w-div?)) (require racket/contract/base racket/match (submod txexpr safe) "str-number.rkt" "music-data.rkt" "attributes.rkt" "util/tag.rkt" "util/stxparse.rkt") ;; --------------------------------------------------------- (define-tag measure (attrs-must/c 'number str-integer?) (listof music-data/c)) ;; --------------------------------------------------------- (define-syntax-class measureₑ #:attributes [measure-number] #:datum-literals [number width] [pattern {~measure ({~alt {~once [number N:str-int]} {~optional [width w:str-num]}} ...) (:%music-data ...)} #:attr measure-number (@ N.number)]) ;; --------------------------------------------------------- ;; Measure -> Integer ;; Returns the value in the number attribute, which is ;; probably one-indexed. (define (measure-number m) (match m [(measure _ _) (string->number (attr-ref m 'number))])) ;; --------------------------------------------------------- ;; private ;; Any -> Boolean (define (attributes/w-div? v) (match v [(attributes _ _) (attributes-has-divisions? v)] [_ #false])) ;; Measure -> Boolean (define (measure-has-divisions? m) (match m [(measure _ elements) (ormap attributes/w-div? elements)])) ;; Measure -> PositiveInteger (define (measure-divisions m) (match m [(measure _ elements) (for/first ([e (in-list elements)] #:when (attributes/w-div? e)) (attributes-divisions e))])) ;; ---------------------------------------------------------
true
0f1a800ea9db83251e4b9794e183d2b3b8af602b
2a255c3d95f1336a8e10ab1ce784acabc152e71b
/images-test/images/tests/effects-tests.rkt
9a83d63b8b846dea60be05e8881dc3387f9f92bd
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "Apache-2.0" ]
permissive
racket/images
1faf9dcfaf49d71e1941a7a5913a2f492dbb7c27
b3d032087d9544a0561b61fedc09adc2c63ed29d
refs/heads/master
2023-08-18T18:42:35.521975
2021-10-09T12:38:30
2021-10-09T13:05:26
27,413,308
6
5
NOASSERTION
2020-06-25T19:05:22
2014-12-02T03:31:12
Racket
UTF-8
Racket
false
false
1,671
rkt
effects-tests.rkt
#lang racket/gui (require racket/math images/gui images/flomap images/logos) (module test racket/base) (define frame-delay 1/30) (define size 256) (define blur 8) (define frame-num 10) (define end-frame-quality 90) (define mid-frame-quality 35) (define background-fm (make-flomap* size size #(1 1 1 1))) (define (flomap-shadowed fm σ color) (flomap-cc-superimpose (flomap-shadow fm σ color) fm)) (define plt-fm (flomap-shadowed (flomap-inset (plt-flomap #:height (- size (* 4 blur))) (* 2 blur)) blur #(1/2 0 0 1/8))) (define racket-fm (flomap-shadowed (flomap-inset (racket-flomap #:height (- size (* 4 blur))) (* 2 blur)) blur #(1/2 1/8 0 0))) (define logo-flomap* (flomap-whirl-morph plt-fm racket-fm)) (define (logo-flomap t) (flomap-cc-superimpose background-fm (logo-flomap* t))) (define logo-frames (time (append (list (time (flomap->bitmap (logo-flomap 0)))) (time (for/list ([t (in-range 1 frame-num)]) (flomap->bitmap (logo-flomap (/ t frame-num))))) (list (time (flomap->bitmap (logo-flomap 1))))))) (define frame (new frame% [label "Whirl Morph Logo"] [width 256] [height 256])) (define canvas (make-object bitmap-canvas% frame (first logo-frames))) (send frame show #t) (for ([_ (in-range 5)]) (for ([frame (in-list logo-frames)]) (send canvas set-bitmap frame) (send canvas refresh) (sleep/yield frame-delay)) (sleep 1) (for ([frame (in-list (reverse logo-frames))]) (send canvas set-bitmap frame) (send canvas refresh) (sleep/yield frame-delay)) (sleep 1)) (send frame show #f)
false
713243ace57b67a9b8023951f09b2877d3954684
4858557025c3294a2291ba4f4fef8ac3ceff2886
/Emulator/Examples/toy/reduce.rkt
679d8e8567be11a8b061b2ba01fe61a196b46755
[]
no_license
prg-titech/Kani-CUDA
75e5b5bacd3edae5ee7f618e6d0760f57a54d288
e97c4bede43a5fc4031a7d2cfc32d71b01ac26c4
refs/heads/master
2021-01-20T00:21:21.151980
2019-03-26T02:42:02
2019-03-26T02:42:02
70,029,514
10
1
null
null
null
null
UTF-8
Racket
false
false
485
rkt
reduce.rkt
#lang rosette (require "lang.rkt") (define (reduce arr len) (:= int s (quotient/LS len 2)) (while (>/LS s 0) (if- (</LS (tid) s) (= [arr (tid)] (+/LS [arr (tid)] [arr (+/LS (tid) s)]))) (= s (quotient/LS s 2)) (barrier))) (define xs (make-array (for/vector ([i (in-range 32)]) (make-element 1)))) (invoke-kernel reduce 1 16 xs 32) (for ([i (in-range 32)]) (printf "~a " (element-content (vector-ref (array-contents xs) i)))) (newline)
false
1ae460e06391dc082fcc143800642fed94d34323
8cc8751912b82afd139c664bf358b253117bc8c1
/2/solution.rkt
0d4920425e9fab7484d6988adb278b6ca4194462
[]
no_license
putterson/adventofcode
f9503f09e687716c1907991b927834ce9b02d015
79768c36584b02baa79eb50e6215c04b4cdee216
refs/heads/master
2021-01-10T04:44:17.156116
2015-12-12T19:28:50
2015-12-12T19:28:50
47,430,015
0
0
null
null
null
null
UTF-8
Racket
false
false
1,226
rkt
solution.rkt
#lang racket (define-struct box (l w h)) (define (read-in-box str) (let ([ns (cdr (regexp-match #px"(\\d+)x(\\d+)x(\\d+)" str))]) (define (read-iter lst partial-box) (match lst ['() (partial-box)] [_ (read-iter (cdr lst) (curry partial-box (string->number (car lst))))]) ) (read-iter ns box))) (define (wrapping-paper l w h) (let ([lw (* l w)] [lh (* l h)] [wh (* w h)]) (let ([m (min lw lh wh)]) (+ (* 2 lw) (* 2 lh) (* 2 wh) m) ))) (define (ribbon l w h) (let ([plw (+ (* 2 l) (* 2 w))] [plh (+ (* 2 l) (* 2 h))] [phw (+ (* 2 h) (* 2 w))]) (let ([m (min plw plh phw)]) (+ m (* l w h)) ))) (define (calculate formula) (call-with-input-file "input" (λ (in) (foldl + 0 (sequence->list (sequence-map (λ (line) (let ([b (read-in-box line)]) (let ([l (box-l b)] [w (box-w b)] [h (box-h b)]) (formula l w h)))) (in-lines in))))))) (calculate wrapping-paper) (calculate ribbon)
false
c6d9cbe305a69e230e5d23f6058cd0b2b56a0055
bf5681f7efdee8ca75622731e2d5e3a775504c56
/R.scrbl
d4707fb66497aa0e8b3ec80103759c05312c7881
[]
no_license
joskoot/restricted-permutations
9fb937a9ff2f8d2ef342e03a776156a47c1973cd
a2a40df430f4e1f702d676de6099c9b1bb7835b7
refs/heads/master
2023-07-21T05:26:24.065941
2023-07-08T13:08:56
2023-07-08T13:08:56
64,937,248
6
0
null
null
null
null
UTF-8
Racket
false
false
100,226
scrbl
R.scrbl
#lang scribble/manual @(require scribble/core scribble/eval racket "R.rkt" (for-label "R.rkt" racket (only-in typed/racket Setof Natural Sequenceof Index)) (for-syntax racket)) @(newline) @(display " ┌────────────────────────────────────┐\n") @(display " │ This may take some minutes and may │\n") @(display " │ require up to 1.5 Gbyte of memory. │\n") @(display " └────────────────────────────────────┘\n") @(newline) @(flush-output) @(collect-garbage) @(require scribble/core scribble/eval racket "R.rkt" (for-label "R.rkt" racket (only-in typed/racket Setof Natural Sequenceof Index)) (for-syntax racket)) @(define lb linebreak) @(define (↑lb) (list (↑ (hspace 1)) (lb))) @(define nb nonbreaking) @; ignore is a syntax such as to prevent arguments to be evaluated. @(define-syntax-rule (ignore x ...) (void)) @; Below syntaxes are used such as to allow keyword arguments @; without explicitly mentioning them in the definitions. @(define-syntax-rule (nbsl x ...) (nb (seclink x ...))) @(define-syntax-rule (nbsr x ...) (nb (secref x ...))) @(define-syntax-rule (nbhl x ...) (nb (hyperlink x ...))) @(define-syntax-rule (nber x ...) (nb (elemref x ...))) @(define-syntax-rule (nbrl x ...) (nb (racketlink x ...))) @(define-syntax-rule (nbr x ...) (nb (racket x ...))) @(define (make-color-style color) (define prop:color (color-property color)) (define color-style (style #f (list prop:color))) (lambda (elem) (element 'roman (element color-style elem)))) @(define (make-small-color-style color) (define prop:color (color-property color)) (define color-style (style #f (list prop:color))) (lambda (elem) (element 'roman (element (list color-style smaller) elem)))) @(define red (make-color-style "red")) @(define green (make-color-style "green")) @(define black (make-color-style "black")) @(define example-ns (make-base-namespace)) @(parameterize ((current-namespace example-ns)) (namespace-require 'racket) (namespace-require '"R.rkt")) @(define-syntax-rule (eval-example expr) (begin (random-seed 1) (nb (element 'tt (begin (random-seed 1) (~s (eval 'expr example-ns))))))) @(define-syntax (example stx) (syntax-case stx () ((_ a) #'(begin (nbr a) (hspace 1) "→" (hspace 1) (eval-example a) (lb))))) @(define-syntax (color-example stx) (syntax-case stx () ((_ color a) #'(begin (nbr a) (hspace 1) "→" (hspace 1) (elem #:style 'tt (color (eval-example a))) (lb))))) @(define-syntax (example/n stx) (syntax-case stx () ((_ a) #'(begin (nbr a) (hspace 1) "→" (lb) (eval-example a))))) @(define-syntax-rule (Tabular ((e ...) ...) . rest) (tabular (list (list e ...) ...) . rest)) @(define-syntax-rule (example-table x ...) (Tabular ((@nbr[x] "→" (eval-example x)) ...) #:sep (hspace 1))) @(define(minus) (element 'tt "-")) @(define(-?) (element "roman" ?-)) @(define (note . x) (inset (apply smaller x))) @(define (inset . x) (apply nested #:style 'inset x)) @(define (expt-1) @↑{@(minus)1}) @(define ↑ superscript) @(define ↓ subscript) @(define constr-style (nbhl "https://docs.racket-lang.org/drracket/output-syntax.html" "constructor style")) @title[#:version ""]{Restricted Permutations} @author{Jacob J. A. Koot} @(defmodule restricted-permutations/R #:packages ()) @;@(defmodule "R.rkt" #:packages ()) Module @nbhl["../../R.rkt" "R.rkt"] imports the following modules and exports all its imports@(lb) with exception of a minor modification related to @nbsl["Cleanup" "cleanup"]. @inset{@Tabular[ (("Module" "Documentation in section") (@nbhl["../../N.rkt" "N.rkt"] @(nbsr "N")) (@nbhl["../../C.rkt" "C.rkt"] @(nbsr "C")) (@nbhl["../../P.rkt" "P.rkt"] @(nbsr "P")) (@nbhl["../../H.rkt" "H.rkt"] @(nbsr "H")) (@nbhl["../../G.rkt" "G.rkt"] @(nbsl "G" "Finite groups of restricted permutations"))) #:sep (hspace 3) #:row-properties '(top-border top-border () () () bottom-border)]} @section{Introduction} In this document the word `permutation' is used in mathematical sense, id est,@(lb) such as to mean a bijection of a set onto the same set. @elemtag["rearrangement" ""] @note{The word `permutation' often is used for rearrangements. For example, two lists like @nb{(1 2 0)} and @nb{(0 1 2)} often are called permutations of each other. In this document they are called rearrange@(-?)ments of each other, the word `permutation' being reserved for bijections of a set onto the same set. Rearrangements can represent permutations, though. If there is no danger of confusion, @nb{a representing} object can be written or talked about as though it were the object it represents, @nb{but this} is avoided in this document. However, no formal distinction will be made between @nbsl["numbers" #:doc '(lib "scribblings/guide/guide.scrbl") "exact integer numbers of Racket"] and the abstract integer numbers they represent. @nb{See section} @nbsl["N" "Natural/integer numbers"].} @elemtag["R" ""] Let @bold{N} be the set of all natural numbers, 0 included. Define a restricted permutation, @nb{say p}, as a permutation of @bold{N} with a restriction as follows: @inset{@nb{∃m∈@bold{N}: ∀k∈@bold{N}: k≥m ⇒ p(k) = k}} Let's call the smallest m∈@bold{N} for which this holds, @nb{@italic{the} restriction} @nb{of p.} @nb{`R' is shorthand for `restricted permutation'.} @nb{Let @bold{R} be the set of all Rs.} @nb{@elemtag["composition"]Define the composition:} @inset{@nb{p,q∈@bold{R} → pq∈@bold{R}}} as usual for functions p and q with compatible domain of p and co-domain of q: @inset{@nb{pq: k∈@bold{N} → p@larger{(}q(k)@larger{)}∈@bold{N}}} In this document @bold{R} always will be associated with this composition, thus forming @nb{a @nber["group"]{group}}, in particular a denumerable infinite group. As required, the composition is associative. For some groups the composition is commutative. For @bold{R} it is not, although it is commutative for many subgroups of @bold{R}, but certainly not for all of them. For every finite group there is an isomorphic subgroup of @bold{R}. @note{In fact exactly one such subgroup consisting of the @nber["id"]{identity of @bold{R}} only if the order @nb{(= cardinality)} of the group is 1 and an infinite number of them if the order is greater than 1.} @elemtag["group"] @note{The present document is not an introduction to group theory. It frequently refers to mathematical concepts without their definitions and mentions theorems without their proofs. @nb{For a simple} introduction see chapter 1 of @hyperlink[ "../../Hamermesh-GroupTheory.pdf" "Group Theory and its Application to Physical Problems by Morton Hamermesh"]. @nb{If you} know nothing about quantum mechanics, you'd better skip the intro@(-?)duction. Quantum mechanics plays no role in chapter 1. @nb{As an} alter@(-?)native see @nbhl["../../finite-groups.pdf" "finite-groups.pdf"].} @ignore{Nevertheless a brief summary:@(lb) @bold{Definition:} a group is a system @nb{(@bold{X}, φ)} where:@(↑lb) @(hspace 3)@bold{X} is a non-empty set and@(↑lb) @(hspace 3)φ a composition x,y∈@bold{X} → φ(x,y)∈@bold{X}@(lb) such that:@(↑lb) @(hspace 3)∃e∈@bold{X} : ∀x∈@bold{X} : (φ(e,y) = x) @bold{and} (∃x@↑{@(minus)1}∈@bold{X} : φ(x@↑{@(minus)1},x) = e) and@(↑lb) @(hspace 3)∀x,y,z∈@bold{X} : φ(φ(x,y),z) = φ(x,φ(y,z)) (associativity of the composition).@(lb) e is called identity. x@↑{@(minus)1} is called inverse of x. We write @nb{xy ≡ φ(x,y)}. Because the composition is associative, parentheses can be omitted: @nb{xyz ≡ x(yz) = (xy)z}. If it is obvious or irrelevant which composition a group has, the latter can be identified by its set only. The definition implies all of the following:@(lb) @(hspace 3)∀x∈@bold{X} : ex = x = xe,@(↑lb) @(hspace 3)∀x∈@bold{X} : x@↑{@(minus)1}x = e = xx@↑{@(minus)1},@(↑lb) @(hspace 3)∀x,y∈@bold{X} : ∃|z∈@bold{X} : zx = y, in particular z=yx@↑{@(minus)1} and@(↑lb) @(hspace 3)∀x,y∈@bold{X} : ∃|z∈@bold{X} : xz = y, in particular z=x@↑{@(minus)1}y.@(↑lb) This implies that @bold{X} has one identity only and that every element of @bold{X} has one inverse only:@(↑lb) @(hspace 3)∀x,y∈@bold{X} : xy=y ⇒ x=e,@(↑lb) @(hspace 3)∀x,y∈@bold{X} : xy=x ⇒ y=e,@(↑lb) @(hspace 3)∀x,y∈@bold{X} : xy=e ⇒ x=y@↑{@(minus)1} and@(↑lb) @(hspace 3)∀x,y∈@bold{X} : xy=e ⇒ y=x@↑{@(minus)1}.@(↑lb) Two groups @bold{X} and @bold{Y} are isomorphic to each other if there is a bijection@(↑lb) @(hspace 3)@nb{ξ : x∈@bold{X} → y∈@bold{Y}} such that:@(↑lb) @(hspace 3)∀p,q∈@bold{X} : ξ(pq) = ξ(p)ξ(q).@(↓ (hspace 1))@(lb) We have:@(↑lb) @(hspace 3)∀r,s∈@bold{Y} : ξ@↑{@(minus)1}(rs) = ξ@↑{@(minus)1}(r)ξ@↑{@(minus)1}(s). @(↓ (hspace 1))@(↑lb) Isomorphism is an equivalence relation. Every group @bold{X} is isomorphic to a subgroup of the symmetric group of all permutations of the set of @bold{X}. In particular the following two sets of maps:@(lb) @(hspace 2) {(y∈@bold{X} → xy∈@bold{X}) : x∈@bold{X}} and@(↑lb) @(hspace 2) {(y∈@bold{X} → yx∈@bold{X}) : x∈@bold{X}}@(↓ (hspace 1))@(↑lb) are sets of permutations of the set of @bold{X}. With composition as usual for permutations, they form two groups isomorphic to each other and to group @bold{X}. The two sets are the same if and only if group @bold{X} is abelean. @nb{For every x∈@bold{X}:}@(lb) @(hspace 3)the permutations y∈@bold{X} → x@↑{@(minus)1}y∈@bold{X} and y∈@bold{X} → xy∈@bold{X} are inverses of each other;@(↑lb) @(hspace 3)the permutations y∈@bold{X} → yx@↑{@(minus)1}∈@bold{X} and y∈@bold{X} → yx∈@bold{X} are inverses of each other.} @elemtag["id" "The identity"] of @bold{R} is: @inset{@nb{∀k∈@bold{N}: k → k}} This is the only R with restriction 0 and order 1. For every other R the restriction and order are greater than 1, but always finite. They are not necessarily the same. Inverses of each other have the same order and the same restriction. There are n! Rs with restriction less than or equal to natural @nb{number n}. These form a finite subgroup of @bold{R} isomorphic to the symmetric group S@↓{n}. @note{In every group the identity is the only element of order 1 and inverses of each other have the same order. Do not confuse the order of an element with the order of a group. The latter is the cardinality of a group, but usually it is called its @italic{order}. The word `order' also is used for the consecution of elements in a list or vector. In most cases it is clear with which meaning the word is used. Where appropriate, the present document uses a phrase that avoids confusion.} Let p and q be two Rs with restrictions r@↓{p} and r@↓{q} and let r@↓{pq} be the restriction of pq.@(lb) We have: @nb{0 ≤ r@↓{pq} ≤ max(r@↓{p}@bold{,}r@↓{q}).} The restriction of pq not necessarily equals that of qp.@(lb) See the @nber["P-example"]{example} in the description of procedure @nbr[P]. There is no R with restriction 1.@(lb) If p is a permutation of @bold{N} with @nb{∀k∈@bold{N}: k≥1 ⇒ p(k) = k},@(lb) then necessarily @nb{p(0) = 0} and hence @nb{∀k∈@bold{N}: p(k) = k},@(lb) which means that p is the identity with @nb{restriction 0.} Let @nb{a(m)} be the number of Rs with restriction m.@(lb) We have: @nb{a(0)=1} and @nb{∀m∈@bold{N}: a(m+1) = (m+1)!@(minus)m! = mm!}.@(lb) This implies: @nb{a(1) = 0.} Furthermore: @nb{∀n∈@bold{N}: @larger{Σ}@↓{(m=0@bold{..}n)}a(m) = n!},@(lb) where m runs from 0 up to and including n. An R is an abstract mathematical concept.@(lb) The following @nber["representations" "representations"] in terms of Racket objects are used: @inset{@tabular[#:sep (list (hspace 1) ":" (hspace 1)) (list (list "C" @seclink["C"]{Cycle-representation of Rs}) (list "P" @seclink["P"]{Function-representation of Rs}) (list "H" @seclink["H"]{Hash-representation of Rs}) (list "G" @seclink["G"]{Representation of finite subgroups of @bold{R}}))]} H is for internal use behind the screen. @red{Advice}: avoid explicit use of H. @note{@elemtag["representations"]{ In this document the word `representation' refers to the way abstract mathematical concepts are expressed in terms of Racket objects. In group theory the word has quite another meaning (group of coordinate transformations in a linear space). In this document the word is not used with the group theoretical meaning.}} Notice that: @inset{ @racketblock0[ (lambda ([k : Natural]) (code:comment #,(red "This is not an R.")) ((if (even? k) add1 sub1) k))]} can represent a permutation of @bold{N} but does not represent an R because it does not satisfy the above @nber["R" "restriction"]. @section[#:tag "N"]{Natural/integer numbers} The @nbsl[ "numbers" #:doc '(lib "scribblings/guide/guide.scrbl") "exact integer numbers of Racket"] represent their abstract mathematical counter@(-?)parts exactly. Although the representation is not complete because of memory limits, no distinction will be made between abstract integer numbers and the exact integer numbers of Racket by which they are represented nor between @racketlink[exact-nonnegative-integer? "exact non-negative integers of Racket"] and the corresponding abstract natural numbers. @inset{@Tabular[ ((@bold{N} "is the set of all natural numbers.") (@bold{N@↑{+}} "is the set of all positive natural numbers.") (@bold{Z} "is the set of all integer numbers.")) #:sep (hspace 1)]} @deftogether[ (@defproc[#:kind "predicate" (N? (x any/c)) boolean?] @defproc[#:kind "predicate" (N+? (x any/c)) boolean?] @defproc[#:kind "predicate" (Z? (x any/c)) boolean?])]{ @Tabular[ (("Predicate" (list "Synonym in the sense of " @nbr[free-identifier=?] " of")) (@nbr[N?] @nbr[exact-nonnegative-integer?]) (@nbr[N+?] @nbr[exact-positive-integer?]) (@nbr[Z?] @nbr[exact-integer?])) #:sep (hspace 3) #:row-properties (list '(top-border bottom-border) '() '() 'bottom-border)]} The synonyms are provided by module @nbhl["../../N.rkt" "N.rkt"]. They are used as shorthands in the description of the procedures shown in this document, particularly in their specifications of data types. @note{In this document @bold{R} is the group of @nber["R"]{restricted permutations}@(lb) and has nothing to do with the set of real numbers.} @section[#:tag "C"]{Cycle notation} All objects described in this section are defined in module @nbhl["../../C.rkt" "C.rkt"]. `C' is shorthand for `cycle notation'. A C represents an @nber["R" "R"] and is one of the following: @itemlist[#:style 'ordered (list @item{ A single C, which is a list of distinct @nbsl["N"]{natural numbers}. It represents the @nber["R" "R"] that maps each element of the list onto the next one, the last element onto the first one and every @nbsl["N"]{natural number} that is not part of the single C, onto itself. The empty list and all single Cs of one element represent the @nber["id"]{identity} of @nber["R"]{@bold{R}}, which has order 1. A non-empty single C of n elements represents an @nber["R" "R"] of order n. The @racket[reverse] of a single C represents the inverse of the @nber["R" "R"] represented by the original single C.} @item{ A list of Cs. Represents the @nber["composition" "composition"] of the @nber["R" "Rs"] represented by its elements. @nb{An element} of a list of Cs can be a list of Cs, but superfluous pairs of parentheses can be ignored, because the @nber["composition" "composition"] is associative. The order in which the single Cs appear in the list can be relevant, because the represented @nber["R" "Rs"] are not required to commute with each other.})] @elemtag["normalized-C"]{A normalized C is one of the following:} @itemlist[#:style 'ordered (list @item{ The empty list. It is the one and only normalized C representing the @nber["id"]{identity of @bold{R}}.} @item{ A single C of at least two elements and the first element being the smallest one. @nb{A circular} shift of a single C represents the same @nber["R" "R"] as the original single C. Therefore, @nb{a non-normalized} single C of at least two elements can be normalized by shifting it circularly until its smallest element is in front.} @item{ A list of two or more disjunct non-empty normalized single Cs sorted in increasing order of their lengths and among normalized single Cs of the same length in increasing order of the first element. Sorting is possible because @nber["R" "Rs"] represented by disjunct single Cs commute with each other. The order of the represented @nber["R" "R"] is the smallest common multiple of the lengths of the single Cs.})] Every @nber["R" "R"] can be represented by a C (in fact by many of them and ignoring memory limits). For every C there is exactly one (in the sense of @nbr[equal?]) normalized C representing the same @nber["R" "R"]. For every @nber["R" "R"] there is exactly one representing @nb{normalized C} (in the sense of @nbr[equal?] and ignoring memory limits). @deftogether[ (@defproc[#:kind "predicate" (C? (x any/c)) boolean?] @defproc[#:kind "predicate" (C-normalized? (x any/c)) boolean?])]{ Predicate @nbr[C?] does not discriminate between normalized and non-normalized Cs.@(lb) Predicate @nbr[C-normalized?] returns @nbr[#t] for normalized Cs only.} @defproc[(C-normalize (c C?)) C-normalized?]{ Returns the normalized form of its argument. Examples:} @example-table[ (C-normalize '(1 0)) (C-normalize '(1 2 0)) (C-normalize '((1 2) (0 3))) (C-normalize '((0 2) (0 1))) (C-normalize '((0 1) (0 2))) (C-normalize '((0 1 2) (0 1))) (C-normalize '((0 1 2) (0 2))) (C-normalize '((0 1 2) (1 2))) (C-normalize '((0 1) (0 1 2) (0 1))) (C-normalize '((0 1) (1 2) (2 3))) (C-normalize '(((0 1) (1 2)) (2 3))) (C-normalize '((0 1) ((1 2) (2 3)))) (C-normalize '((() () ()))) (C-normalize '(((99999999)))) (C-normalize '((1) (2) (3))) (C-normalize '((0 1) (0 1)))] The Cs shown below represent the same @nber["R" "R"]. Therefore procedure @nbr[C-normalize] returns the same normalized C for them @nb{(in the sense of @nbr[equal?])}: @example-table[ (C-normalize '((0 1) (1 2))) (C-normalize '((0 2) (0 1))) (C-normalize '((1 2) (0 2))) (C-normalize '(0 1 2)) (C-normalize '(1 2 0)) (C-normalize '(2 0 1))] @defproc[#:kind "predicate" (C-identity? (x any/c)) boolean?]{ Same as @nbr[(and (C? x) (null? (C-normalize x)))].} @defproc[(C-transpositions (c C?)) C?]{ Returns a list of normalized transpositions representing the same @nber["R" "R"] as the argument.@(lb) A transposition is a single C of two elements. For every C there is a list of transpositions representing the same @nber["R" "R"]. In many cases not all of the @nber["R" "R"]s represented by the transpositions commute with each other. Hence, the order in which the transpositions appear in the list, usually is relevant. The list of transpositions is not uniquely defined. Procedure @nbr[C-transpositions] returns one only, but always the same one (in the sense of @nbr[equal?]) for Cs representing the same @nber["R" "R"] and with no more transpositions than necessary. Examples: @example-table[ (C-transpositions '()) (C-transpositions '(0 1)) (C-transpositions '(0 1 2)) (C-transpositions '(2 1 0)) (C-transpositions '(0 1 2 3)) (C-transpositions '(2 3 4 0 1)) (C-transpositions '((0 1) (2 3))) (C-transpositions '((0 1) (0 1))) (C-transpositions '((0 1 2) (3 4 5))) (C-transpositions '((3 4 5) (0 1 2)))] The Cs shown in the example below represent the same @nber["R" "R"]. Therefore procedure @nbr[C-transpositions] produces the same list of transpositions for them @nb{(in the sense of @nbr[equal?]):} @example-table[ (C-transpositions '((0 1) (1 2))) (C-transpositions '((0 2) (0 1))) (C-transpositions '((1 2) (0 2))) (C-transpositions '(0 1 2)) (C-transpositions '(1 2 0)) (C-transpositions '(2 0 1))]} Because every @nber["R" "R"] represented by a transposition equals its inverse, reversal of the list of transpositions produces a C representing the inverse. Example: @interaction[ (require racket "R.rkt") (for/and ((p (in-G (G-symmetric 4)))) (define c (P->C p)) (define transpositions (C-transpositions c)) (C-identity? (list (reverse transpositions) transpositions)))] @defproc[(C-even? (c C?)) boolean?]{ Same as @nbr[(even? (length (C-transpositions c)))] but faster, because procedure @nbr[C-even?] does not form the intermediate list of transpositions nor does it normalize the argument.} @note{For every C there is a list of transpositions representing the same @nber["R" "R"]. A C that can be written as a list of an even number of transpositions cannot be written as a list of an odd number of transpositions and vice versa. Hence, every C, and consequently every @nber["R" "R"], has well defined parity. Composition of two @nber["R" "Rs"] with the same parity yields an even @nber["R" "R"]. Composition of two @nber["R" "Rs"] with opposit parity yields an odd @nber["R" "R"]. The @nber["id"]{identity of @bold{R}} has even parity. @nb{A finite group} containing at least one odd element has as many odd ones as even ones. Combined with the same composition, the subset of all even elements of a finite group forms an @nbrl[G-invariant-subg? "invariant subgroup"]. Inverses of each other have the same parity. The same holds for conjugate elements.} Examples: @interaction[ (require racket "R.rkt") (for/and ((p (in-G (G-symmetric 4)))) (define c (P->C p)) (define c-inverse (P->C (P-inverse p))) (eq? (C-even? c) (C-even? c-inverse))) (for/and ((n (in-range 5))) (define g (G-symmetric n)) (G-invariant-subg? (G-even-subg g) g))] @defproc[(H->C (h pseudo-H?)) C-normalized?]{ Returns a normalized C representing the same @nber["R" "R"] as @nbr[h].@(lb) You probably never need this procedure.@(lb)@nb{@red{Advice: avoid it}.}} @defproc[(C->H (c C?)) H?]{ Returns an @nbsl["H" "H"] representing the same @nber["R" "R"] as @nbr[c].@(lb) You probably never need this procedure.@(lb)@nb{@red{Advice: avoid it}.}} @section[#:tag "P"]{Function representation} All objects described in this section are defined in module @nbhl["../../P.rkt" "P.rkt"]. A P is a procedure @nbr[(-> N? N?)] representing an @nber["R" "R"]. Given the same argument, a P returns the same @seclink["N"]{@nb{natural number}} as the represented @nber["R" "R"], of course. For every @nber["R" "R"] there is a representing P (ignoring memory limits). In fact Ps are @nbsl["structures" #:doc '(lib "scribblings/reference/reference.scrbl") "structures"] with @racketlink[prop:procedure "procedure property"]. Nevertheless, Ps representing the same @nber["R" "R"] are the same in the sense of @nbr[eq?]. @red{Warning}: this may not remain true after @nbsl["Cleanup" "cleanup"]. A P contains its @nbsl["H" "H-representation"]. It memorizes its normalized @nbsl["C" "C-representation"], its @nbrl[P-even? #:style #f]{parity}, its @nbrl[P-order #:style #f]{order}, its @nbrl[P-period #:style #f]{period} and its @nbrl[P-inverse #:style #f]{inverse}, but only after they have been needed for the first time. @nb{A P} is written, printed or displayed in @constr-style as: @inset{@nbr[(P '#,(italic (tt "c")))]} where @italic{@tt{c}} is the normalized @nbsl["C" "C-representation"]. @defproc[(P (p (or/c P? C?)) ...) (and/c (-> N? N?) P?)]{ Returns the P representing the @nber["R" "R"] formed by @nber["composition" "composition"] of the @nber["R" "Rs"] represented by the arguments. If no argument is given, the @nbr[P-identity] is returned. If only one argument is given, the returned P represents the same @nber["R" "R"] as the argument. Examples:} @interaction[ (require racket "R.rkt") (define p (P '(2 3) '(4 5 6))) (for ((k (in-range 10))) (printf "p(~s) = ~s~n" k (p k)))] @example-table[ (P) (P '()) (P '(0 1) '(0 1)) (P '(((0 2) (0 1)))) (P '(0 1)) (P '(1 0)) (P '(0 1) '(2 3 4)) (P '(3 0 1 2)) (P '(0 1) '(1 2) '(2 3)) (P '(2 3) '(1 2) '(0 1))] Let's do a check that two Ps representing the same @nber["R" "R"] are the same in the sense of @nbr[eq?] (provided no disturbing @nbsl["Cleanup" "cleanup"] is made) @interaction[ (require racket "R.rkt") (define a (P '(3 4) '(4 5))) (define b (P '(4 5 3))) (code:comment #,(list "a and b represent the same " (elemref "R" "R") ":")) (define m (max (P-restriction a) (P-restriction b))) (code:line (for/and ((k (in-range m))) (= (a k) (b k))) (code:comment #,(green "true"))) (code:comment "Hence:") (code:line (eq? a b) (code:comment #,(green "true")))] Another example: @interaction[ (require racket "R.rkt") (define p (P '((0 2) (3 4 5)))) (define q (P-inverse p)) q (code:comment "Because p and q are the inverses of each other, we have:") (and (code:comment #,(green "true")) (eq? (P-inverse p) q) (eq? (P-inverse q) p) (eq? (P p q) P-identity) (eq? (P q p) P-identity))] @nbr[P] is associative, of course. For example: @interaction[ (require racket "R.rkt") (define in-S4 (in-G (G-symmetric 4))) (for*/and ((a in-S4) (b in-S4) (c in-S4)) (code:comment #,(green "true")) (define x (P a (P b c))) (define y (P (P a b) c)) (define z (P a b c)) (and (eq? x z) (eq? y z) (eq? x y)))] Some checks on the properties of @nber["composition" "compositions"] of @nber["R" "Rs"]: @interaction[ (require racket "R.rkt") (define S4 (G-symmetric 4)) (define in-S4 (in-G S4)) (for*/and ((p in-S4) (q in-S4)) (code:comment #,(green "true")) (define pq (P p q)) (define qp (P q p)) (define max-restriction (max (P-restriction p) (P-restriction q))) (and (G-member? pq S4) (G-member? qp S4) (= (P-order pq) (P-order qp)) (eq? (P-even? pq) (P-even? qp)) (<= 0 (P-restriction pq) max-restriction) (<= 0 (P-restriction qp) max-restriction)))] @elemtag["P-example"]{ The @nber["R" "restriction"] of pq not necessarily equals that of qp:} @interaction[ (require racket "R.rkt") (define p (P '((1 2) (3 4)))) (define q (P '( 1 2 3 4))) (define pq (P p q)) (define qp (P q p)) (define-syntax-rule (print-restrictions x ...) (begin (printf "~s = ~s with restriction ~s~n" 'x x (P-restriction x)) ...)) (print-restrictions pq qp)] When composing two or more Ps with Racket's procedure @nbr[compose], the result is a procedure that yields the same answers as when made with procedure @nbr[P], but the result is not a P. Example: @interaction[ (require racket "R.rkt") (define a (P '(0 1 2))) (define b (P '(1 2 3))) (define c (P '(2 3 4))) (define abc (compose a b c)) (define Pabc (P a b c)) (for/and ((k (in-range 10))) (= (abc k) (Pabc k))) (code:comment "But:") (code:line (P? abc) (code:comment #,(red "alas:"))) (code:comment "whereas:") (code:line (P? Pabc) (code:comment #,(green "true:"))) (code:comment #,(list "Racket's procedure " (nbr compose) " does not return " (nbr equal?) " results")) (code:comment #,(list "when called with two or more " (nbr eq?) " arguments.")) (code:line (equal? (compose a b c) (compose a b c)) (code:comment #,(red "alas:"))) (code:comment #,(list "Procedure " (nbr P) " does, even " (nbr eq?) ",")) (code:comment #,(list "when the result represents the same " (elemref "R" "R"))) (code:comment #,(list "(and no disturbing " (nbsl "Cleanup" "cleanup") " interferes)")) (eq? (code:comment #,(green "true")) (P (P a b) c) (P a (P b c))) (code:comment "also:") (eq? (code:comment #,(green "true")) (P-inverse (P a b c)) (P (P-inverse c) (P-inverse b) (P-inverse a)))] @note{Notice that (abc)@(expt-1) = c@(expt-1)b@(expt-1)a@(expt-1), writing x@(expt-1) for the inverse of x.} @defproc[#:kind "predicate" (P? (x any/c)) boolean?] @defidform[#:kind "constant" P-identity]{ The P representing the @nber["id" "identity"] of @nber["R"]{@bold{R}.} A P representing the identity always is the same as @nbr[P-identity] in the sense of equivalence relation @nbr[eq?], even after @nbsl["Cleanup" "cleanup"].} @defproc[#:kind "predicate" (P-identity? (x any/c)) boolean?]{ Same as @nbr[(eq? x P-identity)]. The predicate remains valid after @nbsl["Cleanup" "cleanup"].} @deftogether[(@defproc[(P-name (p P?)) any/c] @defproc[(set-P-name! (p P?) (name any/c)) P?])]{ A P can be given a @nbr[name]. This does not alter the identity of the P. @interaction[ (require "R.rkt") (define a (P '(1 2 3))) (define b (P '(1 2 3))) (set-P-name! a 'a-name) (P-name b) (eq? a b)]} @defproc[(P-commute? (p (or/c P? C?)) (q (or/c P? C?))) boolean?]{ Same as @nbr[(eq? (P p q) (P q p))]. Not disturbed by @nbsl["Cleanup" "cleanup"].} @defproc[(P->C (p P?)) C-normalized?]{ Returns the normalized @nbsl["C" "C-representation"] of @nbr[p].} Examples: @example-table[ (P->C P-identity) (P->C (P)) (P->C (P '(0 1) '(0 1))) (P->C (P '(1 0))) (P->C (P '(2 3 4) '(0 1))) (P->C (P '(2 3 0 1))) (P->C (P '(0 1) '(1 2) '(2 3))) (P->C (P '(2 3) '(1 2) '(0 1)))] @defproc[(P-order (p (or/c P? C?))) N+?]{ For every argument @nbr[p] there is a smallest @nbsl["N"]{positive natural number} @nbr[k] such that @nb{@nbr[(P-expt p k)] → @nbr[P-identity].} @nbr[k] is called the order of the @nber["R" "R"] represented by @nbr[p].@(lb) The @nber["id" "identity"] of @nber["R"]{@bold{R}} is the only @nber["R" "R"] of order 1. For every other @nber["R" "R"] the order is greater than 1.} @note{ The order of an element of a finite group always is a divisor of the order of the group.@(lb) Do not confuse the order of a group element with the order of a group.} Examples: @interaction[ (require racket "R.rkt") (define a (P '(0 1))) (define b (P '(2 3 4))) (define c (P '(5 6 7 8 9))) (define e P-identity) (define (show p) (printf "~a has order ~a~n" (~s #:min-width 27 #:align 'right (P->C p)) (~s #:min-width 2 #:align 'right (P-order p)))) (for-each show (list e a b c (P a b) (P a c) (P b c) (P a b c)))] @defproc*[(((P-period (p P?)) (vector-immutableof P?)) ((P-period (c C?)) (vector-immutableof P?)))]{ If the argument is a @nbsl["C" "C"] it is first converted to a @nbsl["P" "P"]. @nbr[(P-period c)] is treated as @nbr[(P-period (P c))]. Procedure @nbr[P-period] returns an immutable vector of length @nbr[(P-order p)] containing the powers of @nbr[p]. Element with index @nbr[i] contains @nbr[(P-expt p i)]. The period and the order of @nbr[p] are memorized in @nbr[p]. They are not computed again when already available. The first element @nb{(index 0)} of the vector always is @nbr[P-identity]. If @nbr[p] is not the @nbr[P-identity], the second element @nb{(index 1)} is @nbr[p] itself. The last element always is the @nbrl[P-inverse "inverse"] of @nbr[p]. In fact, when omitting the first element (index 0, id est, the @nbr[P-identity]), the elements taken from right to left are the @nbrl[P-inverse "inverses"] of the elements taken from left to right.} Examples: @example-table[ (P-period P-identity) (P-period (P '(0 1))) (P-period (P '(3 5 7)))] @interaction[ (require "R.rkt") (for/and ((p (in-G (G-symmetric 4)))) (code:comment #,(green "true")) (define period (P-period p)) (define order (P-order p)) (and (P-identity? (vector-ref period 0)) (for/and ((k (in-range 1 order))) (eq? (vector-ref period (- order k)) (P-inverse (vector-ref period k))))))] @defproc*[(((P-expt (p P?) (k Z?)) P?) ((P-expt (c C?) (k Z?)) P?))]{ @nbr[(P-expt c k)] is treated as @nbr[(P-expt (P c) k)]. Procedure @nbr[P-expt] computes @nbr[p]@(↑ (nbr k)).@(lb) In fact @nbr[P-expt] collects the power from the @nbr[P-period] as in: @(inset @nbr[(vector-ref (P-period p) (modulo k (P-order p)))]) The period and the order are memorized in @nbr[p]. If the period and order already are available, they are recollected from @nbr[p] without computing them again.} @note{Let x be a group element of finite order m. Then @nb{∀k∈@bold{Z}: x@↑{k} = x@↑{k @bold{modulo} m}}.} Large exponents do no harm. The power is computed almost as fast as for small exponents. The computation of the modulus of an exponent with great absolute value may be somewhat slower, though. @(collect-garbage) @interaction[ (require "R.rkt" racket) (code:line (define big (* 6 (expt 10 1000000))) (code:comment "= #e6e1000000")) (define exponents (range -10 11)) (define big-exponents (map (curry + big) exponents)) (define -big-exponents (map - big-exponents)) (define p (P '(0 1 2) '(3 4))) (code:line (P-period p) (code:comment "Computes the order and all powers and memorizes them.")) (define (P-expt-p k) (P-expt p k)) (define-syntax-rule (timer exponents) (begin (collect-garbage) (time (for-each P-expt-p exponents)))) (begin (timer exponents) (timer big-exponents) (timer -big-exponents))] For every group @bold{X} we have: @inset{ ∀x∈@bold{X}: ∀k,m∈@bold{Z}: (x@↑{k})@↑{m} = x@↑{km}@(hspace 3)and@(lb) ∀x∈@bold{X}: ∀k,m∈@bold{Z}: x@↑{k}x@↑{m} = x@↑{k+m}} This applies to @nber["R" (bold "R")] too, of course. For example: @interaction[ (require "R.rkt") (define p (P '(0 1) '(3 4 5))) (P-order p) (define in-exponents (in-range -10 10)) (for*/and ((k in-exponents) (m in-exponents)) (and (eq? (P-expt (P-expt p k) m) (P-expt p (* k m))) (eq? (P (P-expt p k) (P-expt p m)) (P-expt p (+ k m)))))] @defproc*[(((P-inverse (p P?)) P?) ((P-inverse (c C?)) P?))]{ If the argument is a @nbsl["C" "C"] it is first converted to a @nbsl["P" "P"]. @nbr[(P-inverse c)] is treated as @nbr[(P-inverse (P c))]. Procedure @nbr[P-inverse] returns the P representing the inverse of the @nber["R" "R"] represented by the argument. The inverse is memorized in @nbr[p]. When already available, it is recollected immediately from @nbr[p]. The @nbrl[P-order #:style #f]{order}, @nber["R" "restriction"], @nbrl[P-even? #:style #f]{parity} and @nbrl[P-non-fixed-points #:style #f]{non-fixed points} of the inverse are the same as those of argument @nbr[p].} Examples: @example-table[ (P-inverse P-identity) (P-inverse (P '(0 1))) (P-inverse (P '(6 5))) (eq? (P-inverse (P '(6 5))) (P '(6 5))) (P-inverse (P '(0 1 2))) (P-inverse (P '(0 1 2) '(3 4)))] @interaction[ (require racket "R.rkt") (define S4 (G-symmetric 4)) (G-order S4) (for/and ((p (in-G S4))) (code:comment #,(green "true")) (define q (P-inverse p)) (and (P-identity? (P q p)) (P-identity? (P p q)) (equal? (P-non-fixed-points p) (P-non-fixed-points q)) (= (P-order p) (P-order q)) (= (P-restriction p) (P-restriction q)) (eq? (P-even? p) (P-even? q))))] For every group @bold{X} we have: @inset{@nb{∀a,b∈@bold{X}: (ab)@(expt-1) = b@(expt-1)a@(expt-1)}} This applies to @nber["R" @bold{R}] too: @interaction[ (require racket "R.rkt") (define in-S4 (in-G (G-symmetric 4))) (for*/and ((a in-S4) (b in-S4)) (code:comment #,(green "true")) (eq? (P-inverse (P a b)) (P (P-inverse b) (P-inverse a))))] @defproc[(P-even? (p (or/c P? C?))) boolean?]{ Returns @nbr[#t] if the @nber["R" "R"] represented by the argument is even.@(lb) Returns @nbr[#f] if the @nber["R" "R"] represented by the argument is odd.@(lb) See procedure @nbr[C-even?].} Examples: @example-table[ (P-even? P-identity) (not (P-even? (P '(0 1)))) (P-even? (P '(0 1) '(2 3))) (P-even? (P '(0 1) '(1 2))) (not (P-even? (P '(0 1) '(1 2) '(1 0)))) (P-even? (P '(0 1 2))) (eq? (P '(0 1 2)) (P '(0 2) '(0 1))) (not (P-even? (P '(0 2 4 6)))) (eq? (P '(0 2 4 6)) (P '(0 6) '(0 4) '(0 2)))] @interaction[ (require "R.rkt") (define S3-list (G->list (G-symmetric 3))) (filter P-even? S3-list) (filter (compose not P-even?) S3-list)] Let's check that a @nbsl["G" "G"] with at least one odd element has as many odd elements as even ones. @interaction[ (require "R.rkt" racket/set) (code:comment "Procedure check returns \"all even\" if g has no odd elements or") (code:comment "\"as many odd elements as even ones\" if g has as many odd elements as even ones.") (code:comment "Else raises an error, which should never happen.") (define (check g) (define in-g (in-G g)) (define odd-set (for/seteq ((p in-g) #:unless (P-even? p)) p)) (define even-set (for/seteq ((p in-g) #:when (P-even? p)) p)) (cond ((zero? (set-count odd-set)) "all even") ((and (= (set-count odd-set) (set-count even-set) (/ (G-order g) 2)) (for/and ((odd-p (in-set odd-set))) (equal? (for/seteq ((even-p (in-set even-set))) (P odd-p even-p)) odd-set))) "as many odd elements as even ones") (else (error 'check "this should never happen: ~s" g)))) (code:comment "A symmetric group of order greater than 1") (code:comment "has as many odd elements as even ones.") (for/and ((n (in-range 2 6))) (equal? (check (G-symmetric n)) "as many odd elements as even ones")) (code:comment "The statement holds for all groups containing at least one odd element.") (code:comment "Two checks on non-symmetric groups:") (define g (G '((0 1) (2 3)) '((4 5) (6 7)) '(8 9))) (G-order g) (check g) (code:comment "") (define h (G '((0 1) (2 3)) '((4 5) (6 7)) '(0 1))) (G-order h) (check h) (code:comment "") (code:comment "Checks on groups without odd elements.") (check G-identity) (check (G '(0 1 2))) (check (G '((0 1 2 3) (2 3 4 5)))) (check (G '(0 1 2) '(1 2 3)))] @defproc[(P<? (p0 (or/c P? C?)) (p1 (or/c P? C?))) boolean?]{ Defines a sorting order among @nber["R" "Rs"]. The first sorting key is the order of the @nber["R" "Rs"]. The second sorting key is the @nbrl[P-even? #:style #f "parity"], even @nber["R" "Rs"] preceding odd @nber["R" "Rs"]. The third sorting key is @nbr[(p k)] for the smallest argument @nbr[k] for which the two @nber["R" "Rs"] represented by the two arguments yield different values. @nbr[P<?] remains comparing correctly after @nbsl["Cleanup" "cleanup"].@(lb) (@nb{See @nbr[P-sort]} for an example.)} @defproc[(P-sort (ps (listof (or/c P? C?)))) (listof P?)]{ Like @nbr[(sort (map P ps) P<?)], id est, @(nbsl "C" "Cs") are converted to Ps before sorting. Procedure @nbr[P-sort] returns a sorted list of Ps using @nbr[P<?]. It continues sorting correctly after @nbsl["Cleanup" "cleanup"].} Example: @(define comment1 (list (nbr P-equal?) " is not disturbed by " (nbr R-clear-hashes) ".")) @(define comment2 (list "In both lists the first element is the identity, hence " (nbr eq?) ".")) @(define comment3a (list "Because of the cleanup none of the other")) @(define comment3b (list "corresponding elements are " (nbr equal?) ", let alone " (nbr eq?) ".")) @(random-seed 1) @interaction[ (require racket "R.rkt") (random-seed 1) (code:line (define S3-list0 (G->list (G-symmetric 3))) (code:comment "S3-list0 is sorted.")) (code:line (R-clear-hashes) (code:comment #,(list "Does not disturb procedure " (nbr P-sort)))) (code:line (define S3-list1 (G->list (G-symmetric 3))) (code:comment "S3-list1 is sorted.")) (code:comment "") (map P->C S3-list0) (code:comment "") (code:line (define in-rearrangements in-permutations) (code:comment #,(list "See " (elemref "note" "note below")"."))) (code:comment "") (for/and ((rearranged-S3-list1 (in-rearrangements S3-list1))) (code:comment #,(green "true")) (define sorted-rearranged-S3-list1 (P-sort rearranged-S3-list1)) (and (code:comment #,comment1) (andmap P-equal? S3-list0 sorted-rearranged-S3-list1) (code:comment #,comment2) (eq? (car S3-list0) (car sorted-rearranged-S3-list1)) (code:comment #,comment3a) (code:comment #,comment3b) (not (ormap equal? (cdr S3-list0) (cdr sorted-rearranged-S3-list1)))))] @elemtag["note"] @note{According to the @nber["rearrangement" "terminology"] used in this document, Racket's procedure @nbr[in-permutations] produces a sequence of rearrangements rather than a sequence of permutations.} @defproc[(P-restriction (p P?)) N?]{ Returns the @nber["R" "restriction"] of the @nber["R" "R"] represented by @nbr[p].} Examples: @example-table[ (P-restriction P-identity) (P-restriction (P '(0 1))) (P-restriction (P '(0 1 2))) (P-restriction (P '(99))) (P-restriction (P '(0 99))) (P-restriction (P '(98 99)))] Notice that @example[(P '(99))] and @example[(C-normalize '(99))] @defproc[(P-non-fixed-points (p P?)) (listof N?)]{ Returns a sorted list of all @nbsl["N"]{natural numbers} that are not a fixed point of @nbr[p]. If @nbr[k] is a non-fixed-point of @nbr[p], then @nbr[(p k)] is a non-fixed-point of @nbr[p] too. The @nbrl[P-inverse "inverse"] of @nbr[p] has the same non-fixed-points as @nbr[p].} Examples: @example[(P-non-fixed-points P-identity)] @example[(P-non-fixed-points (P '(5 6) '(0 1 2)))] @interaction[ (require racket "R.rkt") (define in-S4 (in-G (G-symmetric 4))) (for/and ((p in-S4)) (code:comment #,(green "true")) (define nfps (P-non-fixed-points p)) (and (equal? nfps (sort (map p nfps) <)) (equal? nfps (P-non-fixed-points (P-inverse p)))))] @defproc[(P-fixed-point? (p P?) (k N?)) boolean?]{ Same as @nbr[(= (p k) k)]. The @nber["R" "restriction"] implies that every P has an infinite number of fixed points including every @nbsl["N"]{natural number} equal to or greater than the @nber["R" "restriction"]. One may want the fixed points less than some positive natural number n, especially where n is the maximal @nber["R" "restriction"] of the @nber["R" "Rs"] of some @nbsl["G"]{finite subgroup of @bold{R}}. This can be done as follows:} @interaction[ (require racket "R.rkt") (define (fixed-points p n) (for/list ((k (in-range n)) #:when (P-fixed-point? p k)) k)) (fixed-points (P '(0 1) '(5 6 7)) 10) (define (pad x k) (~s #:width k x)) (for ((n (in-range 1 4))) (printf "~n ~nS~s~n" n) (for ((p (in-G (G-symmetric n)))) (printf "~a has fixed points ~a and every k≥~s~n" (pad p 12) (pad (fixed-points p n) 7) n)) (newline))] @defproc[(P->H (p P?)) H?]{ You probably never need this procedure. @red{Advice: avoid it}.} @defproc[(H->P (h pseudo-H?)) P?]{ You probably never need this procedure. @red{Advice: avoid it.} Nevertheless, procedure @nbr[H->P] can sometimes be useful. See the @elemref["H->P-example" "example"] in section @nbsl["C3v"]{Group C@↓{3v}}.} @(define sequenceref (nbhl "https://docs.racket-lang.org/reference/sequences.html" "sequence")) @section[#:tag "G"]{Finite subgroups of @nber["R" (bold "R")]} All objects described in this section are defined in module @nbhl["../../G.rkt" "G.rkt"]. A G represents a finite subgroup of @nber["R" (bold "R")] and is written, displayed or printed in @constr-style as: @inset{@nbr[(G (P '()) (P '#,(italic (tt "c"))) ...)]} showing in @nbrl[P-sort]{sorted} order the written forms of all @nbsl["P" "Ps"] representing the elements of the G. @nb{Gs produced} by the procedures of this section and representing the same subgroup of @nber["R" (bold "R")] are the same in the sense of @nbr[eq?]. @red{Warning}: this may not remain true after a @nbsl["Cleanup" "cleanup"]. @nb{For every} finite group there is an isomorphic G (ignoring memory limits). @defproc[(G (p (or/c P? C?)) ...) G?]{ Returns the G representing the smallest group containing all @nber["R" "Rs"] represented by the arguments. Duplicate arguments representing the same @nber["R" "R"] do no harm. If no argument is given, the @nbr[G-identity] is returned.} @note{By definition a group, say @bold{X}, recursively includes the composition of every pair of its elements,@(lb) the composition of every element with itself included, id est,: @nb{∀x,y∈@bold{X}: xy∈@bold{X}}.} Examples: @(example/n (G)) @(example/n (G '())) @(example/n (G P-identity)) @(example/n (G '(0 1))) @(example/n (G '(0 1 2) '(1 2 0) '(2 0 1))) @(example/n (G '(0 1) '(2 3))) @(example/n (G '(0 1) '(1 2))) @(example/n (G '(0 1) '(0 1 2))) @interaction[ (require racket "R.rkt") (define X (G '(0 3) '(0 1 2))) (G-order X) (define in-X (in-G X)) (for*/and ((p in-X) (q in-X)) (G-member? (P p q) X))] @nbr[(G '(0 1) '(1 2))] yields the same as @nbr[(G '(0 1) '(0 1 2))].@(lb) Hence: @(example (eq? (G '(0 1) '(1 2)) (G '(0 1) '(0 1 2)))) @red{Warning:} We have:@(lb) @(color-example green (eq? (P '((0 1) (1 2))) (P '(0 1) '(1 2)))) @red{but:}@(lb) @(color-example red (eq? (G '((0 1) (1 2))) (G '(0 1) '(1 2)))) In particular:@(lb) @(example/n (G '((0 1) (1 2)))) @(lb)and@(lb) @(example/n (G '(0 1) '(1 2))) @defidform[#:kind "constant" G-identity]{ The @(nbsl "G" "G") consisting of the @nbr[P-identity] only.} @defproc[#:kind "predicate"(G-identity? (x any/c)) boolean?]{ Same as @nbr[(eq? x G-identity)]. This predicate remains valid after @nbsl["Cleanup" "cleanup"].} @defproc[#:kind "predicate"(G? (x any/c)) boolean?] @defproc[(in-G (g G?)) (Sequenceof P?)]{ Returns an eagerly @nbrl[P-sort "sorted"] @sequenceref of the elements of @nbr[g].} @defproc[(G-member? (p (or/c P? C?)) (g G?)) boolean?]{ Returns @nbr[#t] if the @nber["R" "R"] represented by @nbr[p] is an element of the @nbsl["G" "G"] represented by @nbr[g],@(lb) else returns @nbr[#f].} Examples: @interaction[ (require racket "R.rkt") (define g (G '(0 1) '(0 2))) (define in-g (in-G g)) (code:comment "By definition, for every pair of elements of g") (code:comment "the composition is an element of g too.") (for*/and ((p in-g) (q in-g)) (G-member? (P p q) g))] @color-example[green (G-member? P-identity G-identity)] @color-example[red (G-member? '(2 3) G-identity)] @red{Warning}: procedure @nbr[G-member?] can be confused by a @nbsl["Cleanup" "cleanup"]: @interaction[ (require racket "R.rkt") (define c '(0 1)) (define g (G c)) (code:line (G-member? c g) (code:comment #,(green "true"))) (code:line (R-clear-hashes) (code:comment #,(red "caution"))) (code:line (G-member? c g) (code:comment #,(red "alas")))] @defproc[(G-print-table (g G?) (output-port output-port? (current-output-port))) void?]{ The @nber["composition" "composition"] table of @nbr[g] is printed in normalized @nbsl["C" "cycle-notation"] on the @nbr[output-port]. Every element is the @nber["composition" "composition"] pq of element p in the left column and element q in the top row. The left column and top row are @nbrl[P-sort "sorted"] and start with the @nbrl[P-identity "identity"]. The columns are aligned (assuming a fixed width font).} @note{For every group @bold{X} with identity e we have: @nb{∀x∈@bold{X}: ex = x = xe}. Hence, with the identity as the first label for both columns and rows, the first row and first column of the table proper are the same as the labels. Therefore we can omit the labels.} Example: @interaction[ (require racket "R.rkt") (define C3v (G '(0 1) '(0 1 2))) (G-print-table C3v)] See section @nbsl["C3v"]{Group C@↓{3v}} for a more elaborated discussion of this group. @defproc[(G-table (g G?)) (vector-immutableof (vector-immutableof P?))]{ Returns the @nber["composition" "composition"] table of @nbr[g] as an immutable vector of immutable vectors of @nbsl["P" "Ps"]. The first row, id est, @nbr[(vector-ref (G-table g) 0)] and the first column, id est, @nbr[(for/vector ((row (in-vector (G-table g))) (vector-ref row 0)))] are @nbrl[P-sort "sorted"].} @interaction0[ (require racket "R.rkt") (define C3v (G '(0 1) '(0 1 2))) (define table (G-table C3v)) table (code:comment "Check that every element pq of the table is the composition of") (code:comment "element p in the left column and element q in the top row.") (define indices (in-range (G-order C3v))) (code:comment "(table-ref i j) = element in row i and column j.") (define (table-ref i j) (vector-ref (vector-ref table i) j)) (for*/and ((i indices) (j indices)) (define p (table-ref i 0)) (define q (table-ref 0 j)) (define pq (table-ref i j)) (eq? pq (P p q)))] @defproc*[(((G-symmetric (n N?) (offset N? 0)) G?) ((G-symmetric (lst (listof N?))) G?))]{ The first form returns the @nbhl["https://en.wikipedia.org/wiki/Symmetric_group"]{symmetric group} of all @nbr[n]! @nbsl["P" "Ps"] corresponding to the rearrangements of the @nbsl["N"]{natural numbers} from @nbr[offset] up to but not including @nbr[(+ offset n)]. All @nbsl["N"]{natural numbers} outside this range are @nbrl[P-fixed-point?]{fixed points} of all elements of the group. @nbr[(G-symmetric 0 offset)] and @nbr[(G-symmetric 1 offset)] both evaluate to the @nbr[G-identity]. Obviously @nbr[G-symmetric] yields isomorphic groups when called with the same value for @nbr[n]. The order of the returned G is @nbr[n]!. The second form returns the @nbhl["https://en.wikipedia.org/wiki/Symmetric_group"]{symmetric group} corresponding to all rearrangements of @nbr[lst]. Duplicate elements are ignored. All @nbsl["N"]{natural numbers} not in the @nbr[lst] are @nbrl[P-fixed-point?]{fixed points} of all elements of the group. If the @nbr[lst] has less than two distinct elements, the @nbr[G-identity] is returned. The order of the returned G is n! where n is the number of distinct elements of @nbr[lst]. @note{@red{Warning}: @nbr[G-symmetric] is not lazy. Because @nb{15! = 1,307,674,368,000},@(lb) @nbr[(> n 15)] and @nbr[(> (length (remove-duplicates lst =)) 15)] almost certainly cause memory problems, thrashing on virtual memory and slowing down the processor to a few per cent of its capacity, eventually aborting because of lack of memory.}} Example: @interaction[ (require "R.rkt" racket) (define g0 (G-symmetric 3)) (define g1 (G-symmetric 3 1)) (define g2 (G-symmetric 3 2)) (define g3 (G-symmetric '(0 3 6))) g0 g1 g2 g3 (and (G-isomorphism g0 g1) (G-isomorphism g0 g2) (G-isomorphism g0 g3) #t) (code:comment "") (and (eq? (G-symmetric '()) G-identity) (eq? (G-symmetric '(0 1 2)) (G-symmetric 3)) (eq? (G-symmetric '(4 5 6)) (G-symmetric 3 4)))] @deftogether[(@defproc[#:kind "predicate" (G-abelean? (g G?)) boolean?] @defproc[#:kind "predicate" (G-commutative? (g G?)) boolean?])]{ @nbr[G-commutative?] is a synonym of @nbr[G-abelean?] in the sense of @nbr[free-identifier=?]. @note{By definition, a group is abelean if and only if all its elements commute with each other. @(lb)Sufficient is that all elements of a @nbrl[G-base]{base} commute with each other.} Examples:} @color-example[green (G-abelean? (G '(0 1 2) '(3 4)))] because: @color-example[ green (eq? (P '(0 1 2) '(3 4)) (P '(3 4) '(0 1 2)))] But: @color-example[red (G-abelean? (G '(0 1 2) '(0 1)))] because: @color-example[red (eq? (P '(0 1 2) '(0 1)) (P '(0 1) '(0 1 2)))] In particular:@(lb) @example[(P '(0 1 2) '(0 1))] @example[(P '(0 1) '(0 1 2))] @defproc[(G-base (g G?)) (Setof P?)]{ Returns a @nbr[seteq] with a minimal base for @nbr[g]. @(nbsl "G" "G")s of order greater than 2 have more than one minimal base. @nbr[G-base] returns one of them only. See @nbr[G-bases].} Example: @(random-seed 1) @interaction[ (require racket "R.rkt") (random-seed 1) (define g (G '(4 5) '(0 1) '(2 3))) (define g-base (G-base g)) (code:comment #,(list "The returned base not necessarily is the " (elemref "simplest base" "simplest one") ":")) g-base (code:comment "Nevertheless it is a correct base:") (eq? (apply G (set->list g-base)) g)] The @nbrl[G-symmetric "symmetric groups"] S@↓{1} and S@↓{2} both have one minimal base of one element. Every symmetric group S@↓{n} with n≥3 has at least one minimal base of two elements, @nb{for example:} @interaction[ (require racket "R.rkt") (G-base (G-symmetric 0)) (G-base (G-symmetric 1)) (G-base (G-symmetric 2)) (for/and ((n (in-range 3 8))) (define n-1 (sub1 n)) (define Sn (G-symmetric n)) (and (= (set-count (G-base Sn)) 2) (code:comment "As an example take base {(0 n-1), (0 .. n-2)},") (code:comment "where (0 n-1) is a transposition and") (code:comment "where (0 .. n-2) is the cycle of the natural") (code:comment "numbers from 0 up to and including n-2.") (eq? Sn (G (list 0 n-1) (range 0 n-1)))))] The following example is not a proof, but shows how to prove that every symmetric group S@↓{n} with n≥3 has at least one minimal base of two elements. @interaction[ (require racket "R.rkt") (code:comment "") (if (for/and ((n (in-range 2 8))) (printf " ~nn = ~s~n ~n" n) (define n-1 (sub1 n)) (code:comment "transposition and cycle form a minimal base.") (define transposition (P (list 0 n-1))) (define cycle (P (range 0 n-1))) (code:comment "base-of-transposition is not minimal for n>3.") (define base-of-transpositions (for/list ((k (in-range n-1))) (P (P-expt cycle k) transposition (P-expt cycle (- k))))) (for-each (curry printf "~s~n") base-of-transpositions) (eq? (apply G base-of-transpositions) (G-symmetric n))) (printf "~n ~netc.~n") (error 'example "failed! (This should never happen)"))] For n>2 the set of @nbrl[C-transpositions]{transpositions} @nb{{(k n@(minus)1): 0 ≤ k < n@(minus)1}} forms a (non-minimal) base @nb{for S@↓{n}}, because every element of S@↓{n} can be written as a composition of transpositions and every relevant transposition @nb{(i j)} not in the list of transpositions can be obtained by composing three transpositions of the list as follows: @nb{((i n@(minus)1) (j n@(minus)1) (i n@(minus)1)) = (i j)}, where i, j and @nb{n@(minus)1} are three distinct natural numbers. @defproc[(G-bases (g G?)) (listof (Setof P?))]{ Returns a list of all minimal bases of @nbr[g].} Examples: @interaction[ (require "R.rkt" racket) (define (G-order+bases g) (define bases (G-bases g)) (values (format "order: ~s" (G-order g)) (format "nr of minimal bases ~s" (length bases)) bases)) (code:comment " ") (G-order+bases (G)) (code:comment " ") (G-order+bases (G '(0 1))) (code:comment " ") (G-order+bases (G '(0 1 2))) (code:comment " ") (G-order+bases (G '(0 1) '(2 3))) (code:comment " ") (G-order+bases (G '(0 1) '(0 1 2))) (code:comment " ") (G-order+bases (G '((0 1 2 3) (4 5 6 7)) '((0 4 2 6) (1 7 3 5)))) (code:comment " ") (define g (G '(0 1) '(0 1 2))) (for/and ((base (in-list (G-bases g)))) (eq? (apply G (set->list base)) g))] @elemtag["simplest base"]{To find one of the simplest bases:} @interaction[ (require "R.rkt" racket) (code:comment "") (define (find-simple-base g) (define bases (G-bases g)) (for/fold ((base (car bases)) (n (string-length (~s (car bases)))) #:result base) ((b (in-list (cdr bases)))) (define m (string-length (~s b))) (if (< m n) (values b m) (values base n)))) (code:comment "") (find-simple-base (G '(0 1) '((0 1) (2 3)) '((2 3) (4 5)))) (find-simple-base (G '(0 1) '(0 1 2))) (find-simple-base (G-symmetric 3)) (find-simple-base (G-symmetric 4)) (find-simple-base (G-symmetric 5))] @defproc[(G-order (g G?)) N+?]{ Returns the order of @nbr[g], id est, its number of elements. @note{Do not confuse the order of a G with the order of a @nbsl["P" "P"] (See @nbr[P-order]). The order of every @nbsl["P" "P"] of a G is a divisor of the order of that G. This is a consequence of the more general theorem of group theory that the order of an element of a finite group always is a divisor of the order of that group. This theorem holds for all finite groups, Gs included.}} @defproc[(G-subg? (g0 G?) (g1 G?)) boolean?]{ @nbr[#t] if @nbr[g0] is a subgroup of @nbr[g1].@(lb) @red{Warning}: procedure @nbr[G-subg?] can be confused by a @nbsl["Cleanup" "cleanup"]:} @interaction[ (require racket "R.rkt") (define g0a (G '(0 1))) (define g1 (G '(0 1) '(0 2))) (code:line (G-subg? g0a g1) (code:comment #,(green "true"))) (code:line (R-clear-hashes) (code:comment #,(red "caution"))) (code:line (G-subg? g0a g1) (code:comment #,(green "true"))) (define g0b (G '(0 1))) (code:line (G-equal? g0a g0b) (code:comment #,(green "true"))) (code:line ( equal? g0a g0b) (code:comment #,(red "alas"))) (code:line ( G-subg? g0b g1) (code:comment #,(red "alas")))] @defproc[(G-proper-subg? (g0 G?) (g1 G?)) boolean?]{ @nbr[g0] is a proper subgroup of @nbr[g1] if and only if it is a @nbr[G-subg?] of @nbr[g1] but not the @nbr[G-identity] and not the same as @nbr[g1]. @red{Warning}: procedure @nbr[G-proper-subg?] can be confused by a @nbsl["Cleanup" "cleanup"].} @defproc[(G-even-subg (g G?)) G?]{ Returns the G representing the invariant subgroup of all even Ps of @nbr[g]. Same, but faster, as: @inset{@nbr[(list->G (filter P-even? (G->list g)))]} Example:} @interaction[ (require "R.rkt") (define g (G '(0 1) '(0 1 2))) (define h (G-even-subg g)) g h (code:line (for/and ((p (in-G g))) (P-even? p)) (code:comment #,(red "False."))) (code:line (for/and ((p (in-G h))) (P-even? p)) (code:comment #,(green "True.")))] @defproc[(G-subgroups (g G?)) (listof G?)]{ Returns a list of all subgroups of @nbr[g]. Example: @interaction[ (require racket "R.rkt") (define g (G '(0 1 2) '(0 1))) (code:comment #,(list "Print subgroups in " (nbsl "C" "C-notation."))) (define (proper? subg) (if ( G-proper-subg? subg g) 'yes 'no)) (define (invariant? subg) (if (G-invariant-subg? subg g) 'yes 'no)) (define line "─────────────────────────────────────────────────────────────~n") (begin (printf line) (printf "Proper? Invariant? Order Subgroup (in C-notation)~n") (printf line) (for ((subg (in-list (sort (G-subgroups g) (lambda (x y) (< (G-order x) (G-order y))))))) (printf "~a ~a ~a" (~a #:min-width 7 #:align 'center (proper? subg)) (~a #:min-width 9 #:align 'center (invariant? subg)) (~a #:min-width 5 #:align 'center (G-order subg))) (for ((p (in-G subg))) (printf " ~s" (P->C p))) (newline)) (printf line))] @note{The order of a subgroup of a finite group always is a divisor of the order of the latter.}} @defproc[#:kind "predicate" (G-simple? (g G?)) boolean?]{ A group is simple if none of its non-trivial subgroups is invariant.} Examples: @example-table[ (G-simple? G-identity) (G-simple? (G '(0 1))) (G-simple? (G '(0 1 2))) (G-simple? (G '(0 1 2 3))) (G-simple? (G '(0 1) '(1 2))) (G-simple? (G '((0 1) (1 2)))) (G-simple? (G '(0 1) '(2 3)))] @defproc[(G-class (p P?) (g G?)) (Setof P?)]{ Returns the conjugation class of @nbr[g] containing element @nbr[p].@(lb) If @nbr[p]∉@nbr[g], @nbr[G-class] returns an empty set. @note{ Two elements a and b of a group @bold{X} are conjugates of each other if and only if: @nb{∃c∈@bold{X}: ac = cb}. @nb{This is} an equivalence relation, which defines conjugation classes in @bold{X}. Two elements belong to the same class if and only if they are conjugates of each other. All elements of a conjugation class of a finite group have the same order and the same normalized cycle structure. The number of elements in a conjugation class of a finite group always is a divisor of the order of the group. @nb{A conjugation} class of element @nb{x∈@bold{X}} consists of x only if and only if it commutes with all elements of @bold{X}. This implies that the identity always is lonesome in its class; it is a conjugate of itself only. @nb{It also} implies that the class of every element of an abelean group consists of this element only.}} Examples: @interaction[ (require racket "R.rkt") (define g (G '(0 1) '(0 2))) (G-class P-identity g) (G-class (P '(0 1)) g) (G-class (P '(0 1 2)) g) (code:comment "Empty set if p∉g:") (G-class (P '(0 3)) g)] @defproc[(G-classes (g G?)) (listof (Setof P?))]{ Returns a list of all conjugation classes of @nbr[g]. Example: @interaction[ (require "R.rkt" racket) (define (print-G-classes g) (for ((class (in-list (G-classes g))) (n (in-naturals 1))) (printf "Class ~s: " n) (for ((p (in-set class))) (printf "~s " (P->C p))) (newline))) (code:comment "All elements of a conjugation class") (code:comment "have the same normalized cycle structure:") (print-G-classes (G '(0 1) '(0 2))) (code:comment "There may be more than one class with.") (code:comment "the same normalized cycle structure.") (code:comment "Below the two classes:") (code:comment "#<seteq: (P '((0 1) (2 3))) (P '((0 3) (1 2)))> and") (code:comment "#<seteq: (P '((0 2) (1 3)))>") (print-G-classes (G '(1 3) '(0 1 2 3))) (print-G-classes (G '((0 1 2 3) (4 5 6 7)) '((0 4 2 6) (1 7 3 5)))) (code:comment " ") (code:comment #,(black "In a symmetric group two elements belong to the same conjugation")) (code:comment #,(black "class if and only if they have the same normalized cycle structure:")) (code:comment " ") (print-G-classes (G-symmetric 4))]} @defproc[(G-invariant-subg? (g0 G?) (g1 G?)) boolean?]{ @nbr[g0] is an invariant subgroup of @nbr[g1] if it is a subgroup of @nbr[g1] and@(lb) @nb{∀p∈@nbr[g1]: {pq: q∈@nbr[g0]} = {qp: q∈@nbr[g0]}}.@(lb) The two sets (indicated by curly braces) are called `cosets'. @note{ Another way to state that @nbr[g0] is an invariant subgroup of @nbr[g1] is that @nbr[g0] is a subgroup consisting of the conjunction of complete conjugation classes of @nbr[g1]. See @nbr[G-classes].}} Examples: @color-example[red (G-invariant-subg? (G '(0 1 )) (G '(0 1) '(0 2)))] @color-example[green (G-invariant-subg? (G '(0 1 2)) (G '(0 1) '(0 2)))] The subset of all even elements of a G is an invariant subgroup. For example: @interaction[ (require racket "R.rkt") (define g (G-symmetric 4)) (define h (G-even-subg g)) (G-order g) (G-order h) (G-invariant-subg? h g)] @defproc[(G-isomorphism (g0 G?) (g1 G?) (name0 symbol? 'no-name) (name1 symbol? 'no-name)) (or/c #f (list/c (-> P? P?) (-> P? P?)))]{ If @nbr[g0] and @nbr[g1] are isomorphic, a list of two isomorphisms is returned, the car mapping the @nbsl["P" "P"]s of @nbr[g0] onto those of @nbr[g1] the cadr being the inverse of the car. The two isomorphisms are functions and @nbr[name0] and @nbr[name1] their names. If @nbr[g0] and @nbr[g1] are not isomorphic, @nbr[#f] is returned. Two isomorphic Gs may have more than one isomorphism. Procedure @nbr[G-isomorphism] returns one only plus its inverse. @note{@elemtag["iso"]{Two groups @bold{X} and @bold{Y} are isomorphic to each other if and only if there is a bijection @nb{ξ: @bold{X} ↔ @bold{Y}} such that: @nb{∀p,q∈@bold{X}: ξ(pq) = ξ(p)ξ(q).} Because ξ is a bijection, we also have:@(↑ (hspace 1)) @nb{∀a,b∈@bold{Y}: ξ@(expt-1)(ab) = ξ@(expt-1)(a)ξ@(expt-1)(b).} Isomorphism is an @nbhl["https://en.wikipedia.org/wiki/Equivalence_relation" "equivalence relation."]}}} Examples: @interaction[ (require racket "R.rkt") (code:comment "Abelean group of 4 elements, called the `four group' or `V'.") (code:comment "Every element of V is its own inverse.") (define V (G '(0 1) '(2 3))) (G-order V) (G-abelean? V) (for/and ((p (in-G V))) (eq? (P-inverse p) p)) (code:comment "There are two isomorphically distinct groups of order 4.") (code:comment "An example of the other one is:") (define C4 (G '(0 1 2 3))) (G-order C4) (G-abelean? C4) (code:comment "C4 is not isomorphic to V") (code:line (G-isomorphism V C4) (code:comment #,(red "false"))) (code:comment "In particular (P '(0 1 2 3)) not equals its own inverse:") (code:line (let ((p (P '(0 1 2 3)))) (eq? (P-inverse p) p)) (code:comment #,(red "false")))] @interaction[ (require racket "R.rkt") (define g0 (G '(0 1) '(2 3))) (define g1 (G '((1 2) (7 8)) '((5 6) (3 4)))) (define-values (p0->p1 p1->p0) (apply values (G-isomorphism g0 g1 'p0->p1 'p1->p0))) (eq? (list->G (map p0->p1 (G->list g0))) g1) (eq? (list->G (map p1->p0 (G->list g1))) g0) (code:comment "If the two Gs are not isomorphic, G-isomorphism returns #f.") (code:line (G-isomorphism (G '(0 1) '(2 3)) (G '(0 1 2 3))) (code:comment #,(red "false"))) (code:comment "An error is reported if the argument") (code:comment "is not in the domain of the isomorphism.") (code:line (p1->p0 (P '(0 1))) (code:comment #,(red "error")))] @red{Warning}: after @nbsl["Cleanup" "cleaning up"] isomorphisms made before do not recognize newly constructed @nbsl["P" "P"]s: @interaction[ (require "R.rkt" racket) (define iso (G-isomorphism (G '(0 1 2)) (G '(1 2 3)) '012->123 '123->012)) (define p (P '(0 1 2))) (code:line ((car iso) p) (code:comment #,(green "true"))) (code:line ((cadr iso) p) (code:comment #,(red "error"))) (code:line (R-clear-hashes) (code:comment #,(red "Caution"))) (code:comment "Because of the cleanup the following raises an exception:") (code:line ((car iso) (P '(0 1 2))) (code:comment #,(red "error"))) (code:comment "because after cleanup:") (define q (P '(0 1 2))) (code:line (equal? p q) (code:comment #,(red "alas"))) (code:comment "although:") (code:line (P-equal? p q) (code:comment #,(green "true")))] @defproc[(G->list (g G?)) (listof P?)]{ Returns a sorted list of all elements of @nbr[g] using @nbr[P-sort].} @defproc[(list->G (p-list (listof P?))) G?]{ If the @nbsl["P" "Ps"] of the argument form a group the corresponding G is returned, else an exception is raised. Duplicate arguments representing the same @nber["R" "R"] do no harm. Examples:} @interaction[ (require "R.rkt") (list->G (list P-identity (P '(0 1 2)) (P '(0 2 1)))) (code:comment "duplicates do no harm:") (list->G (list P-identity P-identity (P '(0 1)) (P '(0 1)))) (code:comment "Error when the list does not form a group:") (code:comment #,(list "In the following example " @nbr[(P '((0 1) (2 3)))] " is missing.")) (code:line (list->G (list P-identity (P '(0 1)) (P '(2 3)))) (code:comment #,(red "alas")))] @section[#:tag "Cleanup"]{Cleanup} @defproc*[ (((R-hashes-count) N+?) ((R-clear-hashes) void?))]{ Modules @nbhl["../../P.rkt" "P.rkt"] and @nbhl["../../G.rkt" "G.rkt"] use hashes in order to avoid repeated identical computations and to guarantee that @nbsl["P" "P"]s and @nbsl["G" "G"]s that represent the same @nber["R" "R"]s and groups of @nber["R" "R"]s are the same in the sense of @nbr[eq?]. The two procedures shown above allow inspection of the total number of keys in the hashes and to clear the hashes. However, the @nbr[P-identity] and the @nbr[G-identity] are not removed. @red{Warning}: after clearing the hashes, newly constructed @nbsl["P" "P"]s and @nbsl["G" "G"]s no longer will be the same (not even in the sense of @nbr[equal?]) as equivalent @nbsl["P" "P"]s and @nbsl["G" "G"]s that were constructed before cleaning up. @nbrl[G-isomorphism "Isomorphisms"] will not recognize newly constructed @nbsl["P" "P"]s. Therefore @nbr[R-clear-hashes] should not be used preceding code that refers to @nbsl["P" "P"]s or @nbsl["G" "G"]s made before cleanup. Procedures @nbr[P-equal?], @nbr[G-equal?], @nbr[P<?] and @nbr[P-sort] remain comparing correctly after cleanup.} @deftogether[ (@defproc[#:kind "equivalence relation" (P-equal? (p0 P?) (p1 P?)) boolean?] @defproc[#:kind "equivalence relation" (G-equal? (g0 G?) (g1 G?)) boolean?])]{Example:} @interaction[ (require "R.rkt") (define p (P '(0 1 2))) (define g (G '(0 1 2) '(0 1))) (eq? p (P '(1 2 0))) (eq? g (G '(0 1) '(0 2))) (R-clear-hashes) (code:line (equal? p (P '(0 1 2))) (code:comment #,(red "alas:"))) (code:line (equal? g (G '(0 1 2) '(0 1))) (code:comment #,(red "alas:"))) (code:line (P-equal? p (P '(2 0 1))) (code:comment #,(green "true"))) (code:line (G-equal? g (G '(0 1) '(1 2))) (code:comment #,(green "true")))] @section[#:tag "Distinct-instances"]{Distinct instances of @nbhl["../../R.rkt" "R.rkt"]} Two distinct instances of module @nbhl["../../R.rkt" "R.rkt"] do not recognize each others @nbsl["P" "Ps"] or @nbsl["G" "Gs"], not even their @nbrl[P-identity "P-identities"] and @nbrl[G-identity "G-identities"]: @interaction[ (require racket "R.rkt") (define other-eval (let ((namespace (make-base-namespace))) (parameterize ((current-namespace namespace)) (namespace-require 'racket) (namespace-require '"R.rkt")) (lambda (expr) (eval expr namespace)))) (define other-P-identity (other-eval 'P-identity)) (define other-G-identity (other-eval 'G-identity)) (define other-P-identity? (other-eval 'P-identity?)) (define other-G-identity? (other-eval 'G-identity?)) (code:line (other-P-identity? other-P-identity) (code:comment #,(green "true"))) (code:line (other-G-identity? other-G-identity) (code:comment #,(green "true"))) (code:line (equal? P-identity other-P-identity) (code:comment #,(red "alas:"))) (code:line (equal? G-identity other-G-identity) (code:comment #,(red "alas:"))) (code:line (P-identity? other-P-identity) (code:comment #,(red "alas:"))) (code:line (G-identity? other-G-identity) (code:comment #,(red "alas:"))) (code:line (other-P-identity? P-identity) (code:comment #,(red "alas:"))) (code:line (other-G-identity? G-identity) (code:comment #,(red "alas:"))) (code:comment "") (code:comment #,(list "Even " (nbr P-equal?) " and " (nbr G-equal?) " can go wrong:")) (code:comment "(with an error message that may be obscure, although it does") (code:comment " indicate the mixing of different structures of the same name)") (P-equal? P-identity other-P-identity) (G-equal? G-identity other-G-identity)] @section[#:tag "H"]{Hash representation} All objects described in this section are defined in module @nbhl["../../H.rkt" "H.rkt"]. The H-representation is used internally for operations like application, @nber["composition" "composition"] and @nbrl[P-inverse "inversion"]. @red{Advice}: avoid explicit use of the H-representation. Use the @nbsl["P" "P-representation"]. It represents @nber["R" "Rs"] by functions and avoids multiple copies in memory of Hs, @nbsl["C" "Cs"] and @nbsl["P" "Ps"] representing the same @nber["R" "R"]: @nbsl["P" "Ps"] representing the same @nber["R" "R"] are the same in the sense of @nbr[eq?]. @red{Warning}: this may not remain true after @nbsl["Cleanup" "cleanup"]. @note{@elemtag["inversion"]{ In this document the word `@italic{inversion}' applies to bijections. The same word often is used for a special kind of symmetry-operation: reflection in the origin of a linear space. In order to avoid confusion, for the latter the word `@italic{inversion-symmetry}' will be used.}} @elemtag["H-definition" ""] An H is an immutable @nbr[hasheqv] representing an @nber["R" "R"]. Its keys and values are @seclink["N"]{natural numbers}. The represented @nber["R" "R"] maps each key onto its value and every @seclink["N"]{natural number} not present as a key onto itself. In order to represent a bijection, every key must appear as a value and every value as a key. A key is not supposed to be mapped onto itself. If there is such key=value pair, the hash is called a pseudo H. @deftogether[ (@defproc[#:kind "predicate" (H? (x any/c)) boolean?] @defproc[#:kind "predicate" (pseudo-H? (x any/c)) boolean?])]{ See the @nber["H-definition" "definitions above"].} @defproc[(H-normalize (h pseudo-H?)) H?]{ Removes key/value pairs with key=value.} @defproc[(H-apply (h pseudo-H?) (k N?)) N?]{ Returns the image of @nbr[k] under the @nber["R" "R"] represented by @nbr[h].@(lb) Same as: @nbr[(hash-ref h k k)].} @defproc[(H-compose (h pseudo-H?) ...) H?]{ Returns an H representing the @nber["R" "R"] formed by @nber["composition" "composition"] of the @nber["R" "R"]s represented by the arguments. When called without argument @nbr[H-compose] returns the @nbr[H-identity]. When called with one argument, the normalized from of the argument is returned.} @defproc[(H-inverse (h pseudo-H?)) H?]{ Returns the H representing the inverse of the @nber["R" "R"] represented by @nbr[h]. Same as @nbr[(for/hasheqv (((k v) (in-hash (H-normalize h)))) (values v k))]} @defidform[#:kind "constant" H-identity]{ Empty @nbsl["H" "hash"] representing the @nber["id"]{identity of @bold{R}}.} @defproc[#:kind "predicate" (H-identity? (x any/c)) boolean?]{ Same as @nbr[(and (pseudo-H? x) (equal? (H-normalize x) H-identity))]} @defproc[(H-restriction (h pseudo-H?)) N?]{ Returns the @nber["R" "restriction"] of the @nber["R" "R"] represented by @nbr[h].} @section{Elaborated examples} @subsection{Symmetries of a square} Number the vertices of a square anticlockwise starting left below with 0, 1, 2 and 3. Name the symmetries as follows: @Tabular[(("name" "description") ("E" "identity") ("R" "clockwise rotation about 90°") ("R2" "clockwise rotation about 180°") ("R2" "clockwise rotation about 270°") ("Sv" "reflection in vertical center line") ("Sh" "reflection in horizontal center line") ("Sd1" "reflection in diagional 0-2") ("Sd2" "reflection in diagional 1-3")) #:sep (hspace 2)] @interaction[ (require "R.rkt" fmt/fmt) (code:line (define E P-identity) (set-P-name! E 'E)) (code:line (define R (P '(0 1 2 3))) (set-P-name! R 'R)) (code:line (define R2 (P R R)) (set-P-name! R2 'R2)) (code:line (define R3 (P R R2)) (set-P-name! R3 'R3)) (code:line (define Sv (P '((0 1) (2 3)))) (set-P-name! Sv 'Sv)) (code:line (define Sh (P R2 Sv)) (set-P-name! Sh 'Sh)) (code:line (define Sd1 (P R Sh)) (set-P-name! Sd1 'Sd1)) (code:line (define Sd2 (P R2 Sd1)) (set-P-name! Sd2 'Sd2)) (define g-list (list E R R2 R3 Sv Sd1 Sh Sd2)) (define names '(E R R2 R3 Sv Sd1 Sh Sd2)) (eq? (apply G g-list) (G R Sv)) (define (print-aligned lst-of-lst) ((fmt "L5U#(U#W/)" 'cur) lst-of-lst)) (print-aligned (for/list ((p (in-list g-list))) (for/list ((q (in-list g-list))) (P-name (P p q))))) ] @subsection{Symmetries of a cube} Number the vertices of a cube as shown in the following figure: @nested[#:style 'inset (image "cube.gif")] All symmetries of the cube can be found with a @nbrl[G-bases "minimal base"] of two elements. Below a base is used consisting of a rotation about 90° around the vertical axis through the center of the cube, in particular @nbr[(P '((0 1 2 3) (4 5 6 7)))], and reflection in the diagonal plane containing the vertices 2, 3, 4 and 5, id est, @nbr[(P '((0 7) (1 6)))]. @interaction[ (require racket "R.rkt") (define rotation (P '((0 1 2 3) (4 5 6 7)))) (define reflection (P '((0 7) (1 6)))) (define cube-symmetries (G rotation reflection)) (code:comment "") (code:comment "The following table associates one member of each") (code:comment #,(list (nbrl G-class "conjugation class") " with a name later to be associated")) (code:comment "with the whole conjugation class of this member.") (code:comment "") (define classocs (list (cons (P '((0 1 2 3) (4 5 6 7))) "Rotation 90° or 270°, axis // to an edge.") (cons (P '((0 2) (1 3) (4 6) (5 7))) "Rotation 180°, axis // to an edge.") (cons (P '((0 1) (2 3) (4 5) (6 7))) "Reflection, plane // to a side.") (cons (P '((0 7) (1 6))) "Reflection, diagonal plane.") (cons (P '((0 2 5) (3 6 4))) "Rotation 120° or 240°, axis a diagonal.") (cons (P '((0 7 2 5) (1 4 3 6))) "Rotation 90° or 270°, axis // to an edge, * inversion-symmetry.") (cons (P '((0 1) (2 4) (3 5) (6 7))) (string-append "Rotation 90° or 270° * rotation 180°,\n" "axes // to an edge and perpendicular to each other.")) (cons (P '((1 7) (0 4 5 6 2 3))) "Rotation 120° or 240°, axis a diagonal, * inversion-symmetry.") (cons P-identity "Identity") (cons (P '((0 6) (1 7) (2 4) (3 5))) "Inversion-symmetry."))) (code:comment "") (define class-names (map cdr classocs)) (define (get-class classoc) (G-class (car classoc) cube-symmetries)) (define conj-classes (map get-class classocs)) (code:comment "") (code:comment "Check that all classocs refer to distinct conjugation") (code:comment "classes and that all conjugation classes are present.") (code:comment "") (code:line (set=? conj-classes (G-classes cube-symmetries)) (code:comment #,(green "true"))) (code:comment "") (code:comment "The following table maps each conjugation class to its name.") (code:comment "") (define conj-name-table (make-hash (map cons conj-classes class-names))) (code:comment "") (define (get-class-name conj-class) (hash-ref conj-name-table conj-class)) (code:comment "") (code:comment "Procedure print-group-info prints some information about group g.") (code:comment "It does some tests too.") (code:comment "") (define (print-group-info g name print-classes?) (define conj-classes (sort (G-classes g) conj-class<?)) (define g-order (G-order g)) (define in-g (in-G g)) (printf " ~nInfo about group: ~a~n ~n" name) (printf "Order of the group: ~s~n" g-order) (printf "Number of conjugation classes: ~s~n" (length conj-classes)) (printf "Check: order of each element divisor of the order of the group? ~s~n" (for/and ((p in-g)) (divisor? (P-order p) g-order))) (printf "Check: size of each conjugation class divisor of order of the group? ~s~n" (for/and ((conj-class (in-list conj-classes))) (divisor? (set-count conj-class) g-order))) (when print-classes? (printf " ~nThe conjugation classes are:~n") (for ((conj-class (in-list conj-classes))) (printf " ~n~a~n" (get-class-name conj-class)) (printf "Order: ~s, class-size: ~s~n" (P-order (set-first conj-class)) (set-count conj-class)) (for ((p (in-list (P-sort (set->list conj-class))))) (printf "~s~n" (P->C p))))) (printf " ~n")) (code:comment "") (define (conj-class<? x y) (and (not (eq? x y)) (or (eq? (set-first x) P-identity) (< (set-count x) (set-count y)) (and (= (set-count x) (set-count y)) (< (P-order (set-first x)) (P-order (set-first y))))))) (code:comment "") (define (divisor? divisor multiple) (zero? (modulo multiple divisor))) (code:comment "") (print-group-info cube-symmetries "cube-symmetries" #t) (code:comment "Subgroup consisting of rotations only.") (code:comment "rotation and other-rotation are rotations about 90°") (code:comment "with intersecting axes perpendicular to each other.") (code:comment "") (define other-rotation '((0 1 5 4) (3 2 6 7))) (define rotations-only (G rotation other-rotation)) (define rotation-classes (G-classes rotations-only)) (print-group-info rotations-only "rotations-only" #f) (code:comment "rotations-only is an invariant subgroup of all cube-symmetries.") (G-invariant-subg? rotations-only cube-symmetries) (code:comment "Each conjugation class of the group of rotations-only") (code:comment "also is a conjugation class of the group of all cube-symmetries") (proper-subset? rotation-classes conj-classes)] The group of all cube-symmetries has ten conjugation classes, of which five coincide with the conjugation classes of subgroup @tt{rotations-only}. Elements of the same class have the same normalized cycle structure, but distinct classes can have the same normalized cycle structure. @note{In a @nbrl[G-symmetric]{symmetric} group every class has distinct normalized cycle structure. In other words, in a symmetric group two elements are conjugates of each other if and only if they have the same normalized cycle structure.} In group @tt{cube-symmetries} the inversion-symmetry, rotations about 180° and reflections in the planes containing the center of the cube and parallel to a side of the cube have the same normalized cycle structure, but form distinct conjugation classes. The @nbr[P-identity] always is the only member of its class. The inversion-symmetry @nbr[(P '((0 6) (1 7) (2 4) (3 5)))], which does not occur in subgroup @element['tt "rotations-only"], is lonesome too. This implies that it commutes with all elements. It maps each vertex to the one in opposit position with respect to the center of the cube. Possibly you did not expect three-fold rotation axes as symmetries of a cube, but they are there. In particular, @nber["composition" "composition"] of two rotations about 90° with intersecting axes orthogonal to each other produces a rotation about 120°, for example: @example/n[(P '((0 1 2 3) (4 5 6 7)) '((0 3 7 4) (1 2 6 5)))] This is a rotation about 120° around axis 0-6. Composition of this rotation with the inversion-symmetry, which is not part of subgroup @element['tt "rotations-only"], produces: @example/n[(P (P '((1 3 4) (2 7 5))) (P '((0 6) (1 7) (2 4) (3 5))))] This is a symmetry of order 6. Let's check that the inversion-symmetry commutes with all symmetries of the cube: @interaction[ (require racket "R.rkt") (define rotation (P '((0 1 2 3) (4 5 6 7)))) (define reflection (P '((0 7) (1 6)))) (define cube-symmetries (G rotation reflection)) (define inversion-symmetry (P '((0 6) (1 7) (2 4) (3 5)))) (for/and ((p (in-G cube-symmetries))) (P-commute? inversion-symmetry p))] There are @nb{9×24 = 216} distinct minimal bases for the symmetries of the cube. They can be grouped in 9 collections of symmetrically equivalent minimal bases, each collection containing 24 bases. Two minimal bases @nb{{a ...}} and @nb{{b ...}} are symmetrically equivalent if the group contains @nb{a symmetry} x such that @nb{{ax ...} = {xb ...}}. This is an equality of two sets: @nb{the consecution} of @nb{the elements} between the curly brackets is irrelevant. Symmetrically equivalent minimal bases have the same normalized cycle structure. The number of collections of symmetrically equivalent minimal bases of the group of @tt{cube-symmetries} is one less than the number of conjugation classes. This is no coincidence, because both the identity and the inversion-symmetry leave every minimal base as it is and are the only ones that commute with all symmetries. @elemtag["seq" ""] The number of minimal bases in a collection of symmetrically equivalent minimal bases of group @tt{cube-symmetries} equals the order of group @tt{rotations-only}. Indeed, for every pair of symmetrically equivalent minimal bases there is a @tt{rotations-only}-symmetry showing the equivalence. In addition, given a minimal base, every @tt{rotations-only}-symmetry produces a dictinct symmetrically equivalent minimal base. The following example shows the details: @interaction[ (require racket "R.rkt") (define rotation (P '((0 1 2 3) (4 5 6 7)))) (define reflection (P '((0 7) (1 6)))) (define cube-symmetries (G rotation reflection)) (define bases (G-bases cube-symmetries)) (code:comment "") (define ((make-base-eqv g) a b) (for/or ((p (in-G g))) (equal? a (for/seteq ((c (in-set b))) (P (P-inverse p) c p))))) (code:comment "") (define (eqv-classes lst eq) (group-by values lst eq)) (code:comment "") (define base-collections (eqv-classes bases (make-base-eqv cube-symmetries))) (code:comment "") (define collection-size (/ (length bases) (length base-collections))) (code:comment "") (define (pad3 datum) (~s #:align 'right #:min-width 3 datum)) (begin (printf " ~n") (printf "nr of bases ~a~n" (pad3 (length bases))) (printf "nr of base-collections ~a~n" (pad3 (length base-collections))) (printf "all base-collections same size? ~a~n" (pad3 (apply = collection-size (map length base-collections)))) (printf "size of each base-collection ~a~n" (pad3 collection-size))) (code:comment "") (code:comment #,(list "Print one base of each collection in " (nbsl "C" "C-notation") ".")) (code:comment "") (for ((base-collection (in-list base-collections)) (i (in-naturals 1))) (define-values (x y) (apply values (map P->C (set->list (car base-collection))))) (apply printf "~s: ~s and ~s~n" i (if (= (string-length (~s x)) 21) (list x y) (list y x)))) (code:comment "") (code:comment "Using the rotations only we find the same collections of bases:") (code:comment "") (define other-rotation '((0 1 5 4) (3 2 6 7))) (define rotations-only (G rotation other-rotation)) (equal? (apply set (map set base-collections)) (apply set (map set (eqv-classes bases (make-base-eqv rotations-only))))) (code:comment "") (code:comment "This is consistent with the fact that adding the inversion-symmetry to") (code:comment "a base of group rotations-only yields the group of all cube-symmetries.") (code:comment "") (define inversion-symmetry (P '((0 6) (1 7) (2 4) (3 5)))) (eq? cube-symmetries (G rotation other-rotation inversion-symmetry)) (code:comment "") (code:comment "In fact adding an arbitrary rotation-reflection will do.") (code:comment "A rotation-reflection is a reflection or") (code:comment "the composition of a rotation with a reflection.") (code:comment "The inversion-symmetry is a rotation-reflection too,") (code:comment "for example: reflection in the horizontal plane") (code:comment "followed by 180° rotation around the vertical axis,") (code:comment "both containing the center of the cube.") (code:comment "") (eq? (P '((0 2) (1 3) (4 6) (5 7)) (code:comment "rotation 180°") '((0 4) (1 5) (2 6) (3 7))) (code:comment "reflection") inversion-symmetry) (code:comment "") (define rotation-reflections (remove* (G->list rotations-only) (G->list cube-symmetries))) (code:comment "") (for/and ((p (in-list rotation-reflections))) (eq? cube-symmetries (G rotation other-rotation p)))] In the group of all cube-symmetries, all collections of symmetrically equivalent minimal bases have the same size. This is not true for all groups. For example, group @tt{rotations-only} has 108 distinct minimal bases in five collections of symmetrically equivalent bases, one collection of 12 bases and four collections of 24 bases. A simple modification of part of the above example can do the computation. Try it! The group of symmetries of the cube has 91 subgroups of which 30 contain rotations only. @interaction[ (require racket "R.rkt") (define rotation (P '((0 1 2 3) (4 5 6 7)))) (define reflection (P '((0 7) (1 6)))) (define other-rotation '((0 1 5 4) (3 2 6 7))) (define cube-symmetries (G rotation reflection)) (define rotations (G rotation other-rotation)) (define all-subgs (G-subgroups cube-symmetries)) (define rotation-subgs (apply set (G-subgroups rotations))) (define order-hash (for/fold ((h (hash))) ((subg (in-list all-subgs))) (define rotations? (set-member? rotation-subgs subg)) (define order (G-order subg)) (define invariant? (G-invariant-subg? subg cube-symmetries)) (define key (list order rotations? invariant?)) (hash-set h key (add1 (hash-ref h key 0))))) (define (sort-entries entries) (sort entries entry<?)) (define (entry<? x y) (define-values (x-order x-rotations? x-invariant?) (apply values (car x))) (define-values (y-order y-rotations? y-invariant?) (apply values (car y))) (or (< x-order y-order) (and (= x-order y-order) (or (and x-rotations? (not y-rotations?)) (and (eq? x-rotations? y-rotations?) x-invariant? (not y-invariant?)))))) (define header "order rotations-only? invariant? nr-of-subgroups~n") (define line "────────────────────────────────────────────────~n") (define (~b x) (if x "yes" "no")) (begin (printf line) (printf "~s subgroups of which ~s with rotations only.~n" (length all-subgs) (set-count rotation-subgs)) (printf line) (printf header) (printf line) (for ((entry (in-list (sort-entries (hash->list order-hash))))) (define-values (n order rotations-only? invariant?) (apply values (cdr entry) (car entry))) (printf "~a ~a ~a ~a~n" (~s #:min-width 5 #:align 'right order) (~a #:min-width 15 #:align 'right (~b rotations-only?)) (~a #:min-width 10 #:align 'right (~b invariant?)) (~s #:min-width 15 #:align 'right n))) (printf line))] @subsection{The quaternion group} @(define Q-comment (list "Q is (a group isomorphic to) the " (nbhl "https://en.wikipedia.org/wiki/Quaternion_group" "quaternion group") ".")) @interaction[ (require "R.rkt" racket) (define i (P '((0 1 2 3) (4 5 6 7)))) (define j (P '((0 4 2 6) (1 7 3 5)))) (code:comment #,Q-comment) (define Q (G i j)) (G-order Q) (for ((p (in-G Q))) (printf "order = ~s, p = ~s~n" (P-order p) p)) (G-classes Q)] In the quaternion group, make the following identifications: @(let () (define | i| (P '((0 1 2 3) (4 5 6 7)))) (define | j| (P '((0 4 2 6) (1 7 3 5)))) (define | k| (P | i| | j|)) (define |-1| (P | i| | i|)) (define | 1| (P |-1| |-1|)) (define |-i| (P |-1| | i|)) (define |-j| (P |-1| | j|)) (define |-k| (P |-1| | k|)) (define Ps (list | 1| |-1| | i| |-i| | j| |-j| | k| |-k|)) (define names (list " 1" "-1" " i" "-i" " j" "-j" " k" "-k")) (define P->name-table (make-hash (map cons Ps names))) (define (P->name p) (hash-ref P->name-table p)) (define op (open-output-string)) (parameterize ((current-output-port op)) (for ((p (in-list Ps))) (for ((q (in-list Ps))) (printf "~a " (P->name (P p q)))) (unless (eq? p |-k|) (newline)))) (define table (get-output-string op)) (define-syntax-rule (ttt x) (element 'tt x)) @nested{@nested[#:style 'inset]{@tabular[ #:sep (hspace 1) #:column-properties '(left right left left right left) #:row-properties '(bottom bottom bottom bottom bottom) #:cell-properties '((() () () () () ()) (() () () () () ()) (() () () () () ()) (() () () () () ()) (bottom bottom bottom bottom bottom bottom)) (list (list "Identify" @tt["i"] "with" (hspace 1) (hspace 1) (ttt (~s | i|))) (list "Identify" @tt["j"] "with" (hspace 1) (hspace 1) (ttt (~s | j|))) (list "Identify" @tt["k"] "with" (tt "ij") "=" (ttt (~s (P | i| | j|)))) (list "Identify" @tt["-1"] "with" (tt "i"@↑{@smaller{2}}) "=" (ttt (~s (P | i| | i|)))) (list "Identify" @tt["1"] "with" @tt{(-1)@↑{@smaller{2}}} "=" (ttt (~s (P |-1| |-1|)))))]} We have @tt["ii=jj=kk=-1"], @tt["ij=k"], @tt["jk=i"] and @tt["ki=j"].@(lb) With these @nber["composition" "compositions"] all others are defined as shown in the following table: @nested[#:style 'inset (verbatim table)]}) @note{This table has been @italic{computed} in module @nbhl["R.scrbl" "R.scrbl"]. It has @italic{not} been typed @italic{manually}.} Because @element['tt "1"] is the identity, it commutes with all elements. @element['tt "-1"] commutes with all elements too, which is verified by the fact that the second row of the table equals the second column. Notice that @nb[@element['tt "ji=(-ii)ji=-i(ij)i=-iki=-ij=-k"]].@(lb) Likewise @nb[@element['tt "kj=-i"]] and @nb[@element['tt "ik=-j"]]. The @nbrl[G-classes "conjugation classes"] are: @nested[#:style 'inset]{@verbatim|{ {1 } { -1} {i, -i} {j, -j} {k, -k}}|} We can verify this as follows: @interaction[ (require racket "R.rkt") (define i (P '((0 1 2 3) (4 5 6 7)))) (define j (P '((0 4 2 6) (1 7 3 5)))) (define Q (G i j)) (define |-1| (P i i)) (for/and ((g-class (in-list (G-classes Q)))) (case (set-count g-class) ((1) (define x (set-first g-class)) (or (P-identity? x) (eq? x |-1|))) ((2) (define-values (p q) (apply values (set->list g-class))) (eq? (P |-1| p) q)) (else #f)))] Every subgroup of the quaternion group is @nbrl[G-invariant-subg? "invariant"]: @interaction[ (require racket "R.rkt") (define i (P '((0 1 2 3) (4 5 6 7)))) (define j (P '((0 4 2 6) (1 7 3 5)))) (define Q (G i j)) (not (G-abelean? Q)) (for/and ((subg (in-list (G-subgroups Q)))) (G-invariant-subg? subg Q))] @subsection[#:tag "C3v"]{Group C@↓{3v}} C@↓{3v} is the group of symmetries of an equilateral triangle, with subscript `3' indicating that it has a three-fold axis of rotation and subscript `v' indicating it has a vertical plane of reflection containing the axis of rotation and one of the vertices, in fact three such reflections and assuming the triangle to be located in a horizontal plane. Naming the vertices 0, 1 and 2 we can map the symmetries isomorphically onto @nber["R" "Rs"]: @interaction[ (require racket "R.rkt") (define C3v (G '(0 1) '(0 1 2))) (G-print-table C3v) (code:comment #,(list "C" (↓ "3v") " is isomorphic to S" (↓ "3") ". In this case we even have:")) (eq? C3v (G-symmetric 3))] The represented symmetries are: @elemtag["C3v-table" ""] @inset{@Tabular[ (("label" (nbsl "C" "C") "symmetry") ("0" @nbr[()] "the identity") ("1" @nbr[(1 2)] "reflection in perpendicular from vertex 0") ("2" @nbr[(0 1)] "reflection in perpendicular from vertex 2") ("3" @nbr[(0 2)] "reflection in perpendicular from vertex 1") ("4" @nbr[(0 1 2)] "rotation about 120°") ("5" @nbr[(0 2 1)] "rotation about 120° in reversed direction")) #:row-properties '((bottom-border top-border) () () () () () bottom-border) #:sep (hspace 2)]} According to @nbhl["https://en.wikipedia.org/wiki/Cayley%27s_theorem" "Cayley's theorem"] every group of finite order m is isomorphic to a subgroup of the symmetric group S@↓{m}. Every row of the table of @nber["composition" "composition"]s of a group is a distinct @nber["rearrangement" "rearrangement"] of the elements. Likewise every column is a distinct @nber["rearrangement" "rearrangement"]. There@(-?)fore every element of a group @bold{X} can be associated with one or two permutations of set @bold{X}: @inset{ ∀x∈@bold{X}: (y∈@bold{X}: → xy) is a permutation of set @bold{X} (column of x)@(lb) ∀x∈@bold{X}: (y∈@bold{X}: → yx) is a permutation of set @bold{X} (row of x)} If the group is abelean, the @nber["rearrangement" "rearrangements"] in the rows are the same as those in the columns. Hence, if the group is abelean, every element corresponds to one permutation only, else some elements correspond to two distinct permutations of @bold{X}. Because C@↓{3v} is not abelean, the set of @nber["rearrangement" "rearrangements"] in the rows is not the same as that in the columns: the table is not invariant under transposition, id est, reflection in the diagonal from the upper left corner to the lower right corner. Labeling the elements of C@↓{3v} as shown in the @nber["C3v-table" "table"] above, the @nber["rearrangement" "rearrangements"] in columns and those in rows can be expressed as @nbsl["C" "Cs"]. Both sets of @nbsl["C" "Cs"] form groups isomorphic to C@↓{3v}. Let's check this: @(define C3v-comment1 "procedure correspondence computes a list of Ps corresponding to the") @(define C3v-comment2 (list @nber["rearrangement" "rearrangements"] " of g in the rows/columns of its composition table.")) @(define C3v-comment3 @(elemtag "H->P-example" (list "Use of " @nbr[H->P] " is " (red "discouraged") ", " (green "but here it is useful") "."))) @interaction[ (require racket "R.rkt") (define (pad7-P->C p) (~s #:width 7 (P->C p))) (define C3v (G '(0 1) '(0 1 2))) (define in-C3v (in-G C3v)) (code:comment "-------------------------------------------------------------------") (code:comment "(correspondence g) ->") (code:comment "(values (hasheq P? N? ... ...) (listof P?) (listof P?))") (code:comment "g : G?") (code:comment #,C3v-comment1) (code:comment #,C3v-comment2) (define (correspondence g) (define in-g (in-G g)) (code:comment #,(list "h maps the Ps of g onto the " @nbsl["N"]{natural numbers})) (code:comment "0 up to but not including the order of g.") (code:comment #,C3v-comment3) (define h (for/hasheq ((p in-g) (k (in-naturals))) (values p k))) (define (correspondence compose-for-row-or-column) (for/list ((p in-g)) (H->P (for/hasheqv ((q in-g)) (values (hash-ref h q) (hash-ref h (compose-for-row-or-column p q))))))) (define rows (correspondence (lambda (p q) (P p q)))) (define columns (correspondence (lambda (p q) (P q p)))) (values h rows columns)) (code:comment "") (define-values (h rows columns) (correspondence C3v)) (code:comment "-------------------------------------------------------------------") (code:comment "Let's print map h:") (code:comment "") (for ((p in-C3v)) (printf "~a is mapped onto ~s.~n" (pad7-P->C p) (hash-ref h p))) (code:comment "") (code:comment "Using this map, the composition table can be simplified by representing") (code:comment #,(list "the elements of C" (↓ "3v") " by the natural numbers they are mapped onto.")) (code:comment "") (for ((p in-C3v)) (for ((q in-C3v)) (printf " ~s" (hash-ref h (P p q)))) (newline)) (code:comment "") (code:comment #,(list "Let's show the correspondence of the elements of C"(↓ "3v"))) (code:comment #,(list "to permutations of the set of C"(↓ "3v")",")) (code:comment #,(list "representing them by the " @nber["C3v-table" "labels shown above"] ".")) (code:comment "") (for ((p in-C3v) (row (in-list rows))) (printf " row of ~a corresponds to ~s~n" (pad7-P->C p) (P->C row))) (code:comment "") (for ((p in-C3v) (column (in-list columns))) (printf "column of ~a corresponds to ~s~n" (pad7-P->C p) (P->C column))) (code:comment "") (code:comment "Let's check that we have isomorphic groups here.") (code:comment "") (define row-group (list->G rows)) (define column-group (list->G columns)) (and (G-isomorphism C3v row-group) (G-isomorphism C3v column-group) #t)] @subsection[#:tag "C3h"]{Group C@↓{3h}} Group C@↓{3h} has a three-fold axis of rotation and a plane of reflection perpendicular to the axis of rotation. The subscript `h' indicates that with vertical axis of rotation, the plane of reflection is horizontal. A minimal base of C@↓{3h} consists of one element only. This implies that C@↓{3h} is circular and abelean. There are two minimal bases (consisting of inverses of each other) C@↓{3h} is isomorphic to the group of the natural numbers from 0 up to 6 (excluded), 0 as identity and addition modulo 6 as @nber["composition" "composition"]. @interaction[ (require racket "R.rkt") (define rotation (P '(0 1 2) '(3 4 5))) (define reflection (P '(0 3) '(1 4) '(2 5))) (eq? (P rotation reflection) (P reflection rotation)) (define C3h-base (P rotation reflection)) (define C3h (G C3h-base)) (G-order C3h) (G-abelean? C3h) (G-bases C3h) (define period (P-period C3h-base)) (define h (make-immutable-hasheq (for/list ((p (in-vector period)) (k (in-naturals))) (printf "~s : ~s~n" k p) (cons p k)))) (for ((p (in-vector period))) (for ((q (in-vector period))) (printf "~s " (hash-ref h (P p q)))) (newline)) (define C6 (G (range 6))) (and (G-isomorphism C3h C6) #t) (define other-C3h (G '(0 1 2) '(3 4))) (and (G-isomorphism C3h other-C3h) #t)] @bold{@larger{@larger{@larger{The end}}}} @(collect-garbage)
true
8543285659c6ad4ad7f9331e7fee7f6e0b05a8e6
5c2ddadff2ad66c4d982131ef5c5f9375b03496d
/hw4/hw4.rkt
c7d7e0f714b34b818457423b54d93f9787d84595
[]
no_license
ernestas-poskus/functional-programming
043b7a3c3da5d8a6a839c961b9ae05cf4865a3b0
b28f49c2b45563f0380e81c97b15a4dbc5af852f
refs/heads/master
2021-01-15T18:46:26.798103
2013-12-15T13:40:56
2013-12-15T13:40:56
13,345,317
2
1
null
null
null
null
UTF-8
Racket
false
false
108
rkt
hw4.rkt
#lang racket (provide (all-defined-out)) ;; so we can put tests in a second file ;; put your code below
false
b76f8898ced15e3a171c48db9c9e54d2e6b8c109
28df383ef3d0cf36d4dd40c478b4c26f0d22bad6
/3.26.rkt
a6244c5d20b8a56fbbf6cbb0243e76774f7abe22
[]
no_license
stefanruijsenaars/sicp-exercises
2df9dc6f62b6701842490da7155da0d5c0230d02
7c6cf3f8ec38f6bd32a9bf120b23de0315ae6193
refs/heads/master
2021-01-21T22:15:06.088385
2017-10-11T17:48:37
2017-10-11T17:48:37
102,140,021
1
0
null
null
null
null
UTF-8
Racket
false
false
2,124
rkt
3.26.rkt
#lang sicp (define (entry tree) (car tree)) (define (left-branch tree) (cadr tree)) (define (right-branch tree) (caddr tree)) ; every entry has a key and a value (define (entry-key entry) (car entry)) (define (entry-value entry) (cdr entry)) (define (set-value! entry value) (set-cdr! entry value)) (define (make-entry key value) (cons key value)) (define (make-tree entry left right) (list entry left right)) ; sorted by (numeric) key (define (adjoin-set key value set) (cond ((null? set) (make-tree (make-entry key value) '() '())) ((= key (entry-key (entry set))) (begin (set-value! (entry set) value) set)) ((< key (entry-key (entry set))) (make-tree (entry set) (adjoin-set key value (left-branch set)) (right-branch set))) ((> key (entry-key (entry set))) (make-tree (entry set) (left-branch set) (adjoin-set key value (right-branch set)))))) (define (lookup given-key set-of-records) (cond ((null? set-of-records) false) ((= given-key (entry-key (entry set-of-records))) (entry set-of-records)) ((< given-key (entry-key (entry set-of-records))) (lookup given-key (left-branch set-of-records))) (else (lookup given-key (right-branch set-of-records))))) (define (make-table) (let ((local-table (list '*table*))) (define (lookup-in-table key) (lookup key (cdr local-table))) (define (insert! key value) (set-cdr! local-table (adjoin-set key value (cdr local-table)))) (define (dispatch m) (cond ((eq? m 'lookup-proc) lookup-in-table) ((eq? m 'insert-proc!) insert!) (else (error "invalid")))) dispatch)) (define t (make-table)) ; insert time: O(log n) ((t 'insert-proc!) 1 8) ((t 'insert-proc!) 4 9) ((t 'insert-proc!) 2 10) ((t 'insert-proc!) 5 11) ((t 'insert-proc!) 3 12) ; lookup time: O(log n) ((t 'lookup-proc) 1) ((t 'lookup-proc) 4) ((t 'lookup-proc) 2) ((t 'lookup-proc) 5) ((t 'lookup-proc) 3)
false
a8d225575b145c6c9a53921bb6c5d6354a3816ee
537789710941e25231118476eb2c56ae0b745307
/ssh/digitama/assignment/connection.rkt
98d28c461970de55d113add3b93e8d4f95484ae9
[]
no_license
wargrey/lambda-shell
33d6df40baecdbbd32050d51c0b4d718e96094a9
ce1feb24abb102dc74f98154ec2a92a3cd02a17e
refs/heads/master
2023-08-16T22:44:29.151325
2023-08-11T05:34:08
2023-08-11T05:34:08
138,468,042
0
1
null
null
null
null
UTF-8
Racket
false
false
1,006
rkt
connection.rkt
#lang typed/racket/base (provide (all-defined-out)) (require "../assignment.rkt") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-ssh-symbols SSH-Channel-Failure-Reason #:as Index ;; https://tools.ietf.org/html/rfc4250#section-4.3 ; Symbols in [0xFE000000, 0xFEFFFFFF] are used for conjunction with locally assigned channels; ; Symbols in [0xFE000000, 0xFFFFFFFF] are left for private use. ([SSH_OPEN_ADMINISTRATIVELY_PROHIBITED 1] [SSH_OPEN_CONNECT_FAILED 2] [SSH_OPEN_UNKNOWN_CHANNEL_TYPE 3] [SSH_OPEN_RESOURCE_SHORTAGE 4]) #:fallback SSH-OPEN-CONNECT-FAILED) (define-ssh-symbols SSH-Channel-Data-Type #:as Index ;; https://tools.ietf.org/html/rfc4250#section-4.4 ; Symbols in [0xFE000000, 0xFFFFFFFF] are left for private use. ([SSH_EXTENDED_DATA_STDERR 1]) #:fallback SSH_EXTENDED_DATA_STDERR)
false
aff900d8d864dde7b0e5022c7110d7cd2b054a9e
9dc77b822eb96cd03ec549a3a71e81f640350276
/collection/multiset.rkt
5d275fd13e6eca16b1a8f81a0b09b10e224732b6
[ "Apache-2.0" ]
permissive
jackfirth/rebellion
42eadaee1d0270ad0007055cad1e0d6f9d14b5d2
69dce215e231e62889389bc40be11f5b4387b304
refs/heads/master
2023-03-09T19:44:29.168895
2023-02-23T05:39:33
2023-02-23T05:39:33
155,018,201
88
21
Apache-2.0
2023-09-07T03:44:59
2018-10-27T23:18:52
Racket
UTF-8
Racket
false
false
10,370
rkt
multiset.rkt
#lang racket/base (require racket/contract/base) (provide for/multiset for*/multiset (contract-out [multiset (-> any/c ... multiset?)] [multiset? (-> any/c boolean?)] [multiset-add (->* (multiset? any/c) (#:copies natural?) multiset?)] [multiset-add-all (-> multiset? multiset-coercible-sequence/c multiset?)] [multiset-remove (->* (multiset? any/c) (#:copies (or/c natural? +inf.0)) multiset?)] [multiset-set-frequency (-> multiset? any/c natural? multiset?)] [multiset-contains? (-> multiset? any/c boolean?)] [multiset-frequency (-> multiset? any/c natural?)] [multiset-frequencies (-> multiset? (immutable-hash/c any/c exact-positive-integer?))] [multiset-size (-> multiset? natural?)] [multiset-unique-elements (-> multiset? set?)] [multiset->list (-> multiset? list?)] [sequence->multiset (-> multiset-coercible-sequence/c multiset?)] [empty-multiset multiset?] [in-multiset (-> multiset? sequence?)] [into-multiset (reducer/c any/c multiset?)])) (require (for-syntax racket/base) racket/hash racket/math racket/set racket/sequence racket/stream racket/struct rebellion/private/guarded-block rebellion/streaming/reducer rebellion/type/record) (module+ test (require (submod "..") rackunit)) ;@------------------------------------------------------------------------------ (define (immutable-hash/c key-contract value-contract) (define both-flat? (and (flat-contract? key-contract) (flat-contract? value-contract))) (hash/c key-contract value-contract #:immutable #t #:flat? both-flat?)) ;@------------------------------------------------------------------------------ (define (in-multiset set) (for*/stream ([(v count) (in-immutable-hash (multiset-frequencies set))] [_ (in-range count)]) v)) (define (make-multiset-props descriptor) (define name (record-type-name (record-descriptor-type descriptor))) (define equal+hash (default-record-equal+hash descriptor)) (define custom-write (make-constructor-style-printer (λ (_) name) (λ (this) (in-multiset this)))) (list (cons prop:equal+hash equal+hash) (cons prop:custom-write custom-write) (cons prop:sequence in-multiset))) (define-record-type multiset (size frequencies unique-elements) #:property-maker make-multiset-props #:omit-root-binding) (define empty-hash (hash)) (define empty-set (set)) (define (multiset . vs) (for/multiset ([v (in-list vs)]) v)) (define empty-multiset (constructor:multiset #:size 0 #:frequencies empty-hash #:unique-elements empty-set)) (define (multiset-set-frequency set element frequency) (define old-frequency (multiset-frequency set element)) (define old-unique-elements (multiset-unique-elements set)) (define frequencies (if (zero? frequency) (hash-remove (multiset-frequencies set) element) (hash-set (multiset-frequencies set) element frequency))) (define unique-elements (cond [(and (zero? old-frequency) (not (zero? frequency))) (set-add old-unique-elements element)] [(and (not (zero? old-frequency)) (zero? frequency)) (set-remove old-unique-elements element)] [else old-unique-elements])) (constructor:multiset #:size (+ (multiset-size set) frequency (- old-frequency)) #:frequencies frequencies #:unique-elements unique-elements)) (define (multiset-add set element #:copies [copies 1]) (define frequency (+ (multiset-frequency set element) copies)) (multiset-set-frequency set element frequency)) (define/guard (multiset-remove set element #:copies [copies 1]) (guard (multiset-contains? set element) else set) (guard (equal? copies +inf.0) then (multiset-set-frequency set element 0)) (define frequency (max (- (multiset-frequency set element) copies) 0)) (multiset-set-frequency set element frequency)) (module+ test (test-case "multiset-add" (test-case "not-already-present" (define set (multiset 'a 'a 'b)) (check-equal? (multiset-add set 'c) (multiset 'a 'a 'b 'c)) (check-equal? (multiset-add set 'c #:copies 3) (multiset 'a 'a 'b 'c 'c 'c))) (test-case "already-present" (define set (multiset 'a 'a 'b)) (check-equal? (multiset-add set 'a) (multiset 'a 'a 'a 'b)) (check-equal? (multiset-add set 'b) (multiset 'a 'a 'b 'b)) (check-equal? (multiset-add set 'b #:copies 3) (multiset 'a 'a 'b 'b 'b 'b))) (test-case "zero-copies" (define set (multiset 'a 'b 'b 'c)) (check-equal? (multiset-add set 'a #:copies 0) set) (check-equal? (multiset-add set 'd #:copies 0) set))) (test-case "add-all" (check-equal? (multiset-add-all (multiset 1 1 2 3) (in-range 0 5)) (multiset 0 1 1 1 2 2 3 3 4)) (check-equal? (multiset-add-all (multiset 1 2 3) (multiset 1 2 3)) (multiset 1 1 2 2 3 3))) (test-case "multiset-set-frequency" (test-case "clearing-already-empty" (define set (multiset-set-frequency empty-multiset 'a 0)) (check-equal? (multiset-size set) 0)) (test-case "setting-empty-to-one" (define set (multiset-set-frequency empty-multiset 'a 1)) (check-equal? (multiset-size set) 1)) (test-case "setting-empty-to-many" (define set (multiset-set-frequency empty-multiset 'a 5)) (check-equal? (multiset-size set) 5)) (test-case "one-unique-element" (define set (multiset 'a 'a 'a)) (check-equal? (multiset-size (multiset-set-frequency set 'a 0)) 0) (check-equal? (multiset-size (multiset-set-frequency set 'a 1)) 1) (check-equal? (multiset-size (multiset-set-frequency set 'a 3)) 3) (check-equal? (multiset-size (multiset-set-frequency set 'a 5)) 5)) (test-case "setting-to-zero" (define set (multiset 'a 'a 'b 'b 'b 'c)) (define (set-to-zero element) (multiset-set-frequency set element 0)) (check-equal? (multiset-size set) 6) (check-equal? (multiset-size (set-to-zero 'a)) 4) (check-equal? (multiset-size (set-to-zero 'b)) 3) (check-equal? (multiset-size (set-to-zero 'c)) 5) (check-equal? (multiset-size (set-to-zero 'd)) 6)) (test-case "equality" (define set (multiset 'a 'b 'c)) (check-equal? (multiset-size (multiset-set-frequency set 'a 3)) 5) (check-equal? (multiset-set-frequency set 'a 3) (multiset 'a 'a 'a 'b 'c)) (check-equal? (multiset-set-frequency set 'a 1) set) (check-equal? (multiset-set-frequency set 'a 0) (multiset 'b 'c)) (check-equal? (multiset-set-frequency set 'd 2) (multiset 'a 'b 'c 'd 'd)) (check-equal? (multiset-set-frequency set 'd 0) set))) (test-case "multiset-remove" (test-case "single-copy" (define set (multiset 'a 'b 'b 'c)) (check-equal? (multiset-remove set 'a) (multiset 'b 'b 'c)) (check-equal? (multiset-remove set 'b) (multiset 'a 'b 'c)) (check-equal? (multiset-remove set 'd) set)) (test-case "multiple-copies" (define set (multiset 'a 'a 'b 'b 'b 'c)) (check-equal? (multiset-remove set 'a #:copies 2) (multiset 'b 'b 'b 'c)) (check-equal? (multiset-remove set 'b #:copies 2) (multiset 'a 'a 'b 'c)) (check-equal? (multiset-remove set 'c #:copies 2) (multiset 'a 'a 'b 'b 'b)) (check-equal? (multiset-remove set 'b #:copies 3) (multiset 'a 'a 'c)) (check-equal? (multiset-remove set 'd #:copies 5) set)) (test-case "zero-copies" (define set (multiset 'a 'b 'b 'c)) (check-equal? (multiset-remove set 'a #:copies 0) set) (check-equal? (multiset-remove set 'b #:copies 0) set) (check-equal? (multiset-remove set 'd #:copies 0) set)) (test-case "all-copies" (define set (multiset 'a 'b 'b 'c)) (check-equal? (multiset-remove set 'a #:copies +inf.0) (multiset 'b 'b 'c)) (check-equal? (multiset-remove set 'b #:copies +inf.0) (multiset 'a 'c)) (check-equal? (multiset-remove set 'd #:copies +inf.0) set)))) (define (multiset-union a b) (constructor:multiset #:size (+ (multiset-size a) (multiset-size b)) #:frequencies (hash-union (multiset-frequencies a) (multiset-frequencies b) #:combine +) #:unique-elements (set-union (multiset-unique-elements a) (multiset-unique-elements b)))) (define (multiset-add-all set seq) (multiset-union set (if (multiset? seq) seq (sequence->multiset seq)))) (define into-multiset (make-fold-reducer multiset-add empty-multiset #:name 'into-multiset)) (define-syntaxes (for/multiset for*/multiset) (make-reducer-based-for-comprehensions #'into-multiset)) (define (multiset-frequency set elem) (hash-ref (multiset-frequencies set) elem 0)) (define (multiset->list set) (frequency-hash->list (multiset-frequencies set))) (define multiset-coercible-sequence/c (or/c multiset? (sequence/c any/c))) (define (sequence->multiset seq) (if (multiset? seq) seq (reduce-all into-multiset seq))) (define (multiset-contains? set v) (hash-has-key? (multiset-frequencies set) v)) (define (frequency-hash->list frequencies) (for*/list ([(elem freq) (in-hash frequencies)] [_ (in-range freq)]) elem)) (module+ test (define letters (multiset 'a 'b 'b 'b 'c 'c 'd)) (test-case "queries" (check-equal? (multiset-frequencies letters) (hash 'a 1 'b 3 'c 2 'd 1)) (check-equal? (multiset-frequency letters 'b) 3) (check-equal? (multiset-frequency letters 'foo) 0) (check-equal? (multiset-size letters) 7) (check-equal? (multiset-unique-elements letters) (set 'a 'b 'c 'd)) (check-true (multiset-contains? letters 'a)) (check-true (multiset-contains? letters 'b)) (check-false (multiset-contains? letters 'foo))) (test-case "conversion" (check-equal? (sequence->multiset "hello") (multiset #\h #\e #\l #\l #\o))) (test-case "iteration" (check-equal? (for/multiset ([char (in-string "hello")]) char) (multiset #\h #\e #\l #\l #\o)) (check-equal? (for/set ([letter (in-multiset letters)]) letter) (set 'a 'b 'c 'd))))
true
cd43c4585e08b6b373f91f7f0ca6c8cc56935f30
310fec8271b09a726e9b4e5e3c0d7de0e63b620d
/bot.rkt
d868ef1a6ba12337576f2bdef31ef9166f518f78
[ "Apache-2.0", "MIT" ]
permissive
thoughtstem/badge-bot
b649f845cdc4bf62ca6bd838f57353f8e508f1ae
e535eefac26f15061c412fd0eb5b7adee158a0bf
refs/heads/master
2022-12-14T21:55:00.173686
2020-09-21T19:54:15
2020-09-21T19:54:15
265,321,144
0
0
null
null
null
null
UTF-8
Racket
false
false
13,704
rkt
bot.rkt
#lang racket (provide (rename-out [b badge-bot])) (require discord-bot discourse-bot mc-discord-config net/uri-codec "badges-lang.rkt" "rosters.rkt" ; "questions/lang.rkt" ) (define (describe-badge b) (define left (incoming-badges-img b)) (define right (outgoing-badges-img b)) (define h (max (image-height left) (image-height right))) (list (show-badge-text b) (badge-img-with-id b) (beside/align 'top left (rectangle 5 h 'solid 'transparent) (rectangle 2 h 'solid 'white) (rectangle 5 h 'solid 'transparent) right))) (define (describe-badge-command badge-id) (define b (id->badge badge-id)) (if (not b) (~a "I couldn't find a badge with id " badge-id ". Please check your spelling and capitalization. Details matter in coding. Bots (like me) are not always smart!") (describe-badge b))) (define (badge-command badge-id verb) (define sub-command (match verb ["desc" (thunk* (describe-badge-command badge-id))])) (sub-command)) (define (graph-badges-command . args) (local-require "full-graph/main.rkt") (if (empty? args) (generate-graph) ;Full badge network (match (first args) [x #:when (string? x) (generate-graph (filter-graph-by-user (current-network) x))] [else (~a "I don't understand that `! badges graph ` subcommand")])) (list "I've rendered the badge network to this html file. Please download it and open in your browser." "FILE:../../full-graph/out/index.html")) (define (submit-command . args) (~a "Thanks for your submission! I've alerted <@&" mc-badge-checker-role-id "> to take a look at your badge submission!")) (define (snooze-command badge-id quanity-s (user #f)) (when user (ensure-messaging-user-has-role-on-server! mc-badge-checker-role-id mc-server-id #:failure-message (~a "Sorry, you don't have the right role (<@&" mc-badge-checker-role-id ">) for that command."))) (define quantity (string->number quanity-s)) (cond [(zero? quantity) (begin (unsnooze-badge! (string->symbol badge-id) (or user (id->mention (messaging-user-id)))) (~a "Okay, I unsnoozed that badge."))] [(> quantity 52) (~a "You can't snooze a badge for more than a year.")] [else (begin (snooze-badge! (string->symbol badge-id) quantity (or user (id->mention (messaging-user-id)))) (~a "Okay, I snoozed that badge so you won't get it for " quantity " weeks. If you change your mind, run `! snooze " badge-id " 0`"))])) (define (badges-command . args) (define sub-command-name (first args)) (define sub-command (match sub-command-name ["list" list-badges-command] ["graph" graph-badges-command] ["count" count-badges-command] #; ;Lifted to a top-level command ["award" award-badges-command])) (apply sub-command (rest args))) (define (list-badges-command sub-command-name [page 0]) (define sub-command (match sub-command-name ["images" (thunk (list-badge-images-command (string->number page)))] ["names" (thunk (list-badge-names-command (string->number page)))] [x #:when (string? x) (thunk (list-badges-by-user-name-command x))] [else (thunk* "What?")])) (sub-command)) (define (show-badge-img b) (badge-img-with-id b)) (define (show-badge-text b) (list (~a (badge-id b) " " (badge-name b) ": " (badge-url b)))) (define (list-badges-by-user-name-command user) (define badge-list (badges-for-user user)) (~a "http://18.213.15.93:6969/badge-reports?user=" (uri-encode user))) (define (get-page p bs) (define (safe-string->number n) (if (string? n) (string->number n) n)) (define (safe-take l n) (with-handlers ([exn:fail? (thunk* l)]) (take l (safe-string->number n)))) (define (safe-drop l n) (with-handlers ([exn:fail? (thunk* '())]) (drop l (safe-string->number n)))) (safe-take (safe-drop bs (* 10 p)) 10)) (define (list-badge-images-command page) (map show-badge-img (get-page page (all-badges)))) (define (list-badge-names-command page) (map show-badge-text (get-page page (all-badges)))) (define (create-users-command . users) (ensure-messaging-user-has-role-on-server! mc-badge-checker-role-id mc-server-id #:failure-message (~a "Sorry, you don't have the right role (<@&" mc-badge-checker-role-id">) for that command.")) (define err "") (define created (filter identity (map (lambda (user) (with-handlers ([exn:fail? (λ(e) (set! err (~a err (exn-message e) " ")) #f)]) (create-user! user))) users))) (~a err "You've created " (length created) " users!")) (define (remove-users-command . users) (ensure-messaging-user-has-role-on-server! mc-core-staff-role-id mc-server-id #:failure-message (~a "Sorry, you don't have the right role (<@&" mc-core-staff-role-id">) for that command.")) (define err "") (define removed (filter identity (map (lambda (user) (with-handlers ([exn:fail? (λ(e) (set! err (~a err (exn-message e) " ")) #f)]) (remove-user! user))) users))) (~a err "You've removed " (length removed) " users!")) (define (award-badges-command badge-id . users) (ensure-messaging-user-has-role-on-server! mc-badge-checker-role-id mc-server-id #:failure-message (~a "Sorry, you don't have the right role (<@&" mc-badge-checker-role-id">) for that command.")) (define err "") (define awarded (filter identity (map (lambda (user) (with-handlers ([exn:fail? (λ(e) (set! err (~a err (exn-message e) " ")) #f)]) (award-badge! (string->symbol badge-id) user))) users))) (~a err "You've awarded " badge-id " to " (length awarded) " users!")) (define (count-badges-command . users) #;(ensure-messaging-user-has-role-on-server! mc-badge-checker-role-id mc-server-id #:failure-message (~a "Sorry, you don't have the right role (<@&" mc-badge-checker-role-id">) for that command.")) (define msg "\n=== BADGES EARNED ===\n") (define counts (filter identity (map (lambda (user) (with-handlers ([exn:fail? (λ(e) (set! msg (~a msg (exn-message e) "\n")) #f)]) (let ([count (count-badges user)]) (begin (set! msg (~a msg user ": " count "\n")) count)))) users))) (if (> (length counts) 1) (~a msg "\n" "Group Total: " (apply + counts)) msg)) #;(define (count-badges-for-role role) (ensure-messaging-user-has-role-on-server! mc-core-staff-role-id mc-server-id #:failure-message (~a "Sorry, you don't have the right role (<@&" mc-core-staff-role-id">) for that command.")) (define err "") (define awarded (filter identity (map (lambda (user) (with-handlers ([exn:fail? (λ(e) (set! err (~a err (exn-message e) " ")) #f)]) (award-badge! (string->symbol badge-id) user))) users))) (~a err "You've awarded " badge-id " to " (length awarded) " users!")) (define (check-badges-command badge-id . users) (ensure-messaging-user-has-role-on-server! mc-badge-checker-role-id mc-server-id #:failure-message (~a "Sorry, you don't have the right role (<@&" mc-badge-checker-role-id">) for that command.")) (define msg "\n") (define checks (filter identity (map (lambda (user) (with-handlers ([exn:fail? (λ(e) (set! msg (~a msg (exn-message e) "\n")) #f)]) (let ([check (check-badge! (string->symbol badge-id) user)]) (begin (if check (set! msg (~a msg user " has already earned badge " badge-id "!\n")) (set! msg (~a msg user " has not earned badge " badge-id "!\n"))) check)))) users))) msg) (define (remove-badges-command badge-id user) (ensure-messaging-user-has-role-on-server! mc-badge-checker-role-id mc-server-id #:failure-message (~a "Sorry, you don't have the right role (<@&" mc-badge-checker-role-id">) for that command.")) (remove-badge! (string->symbol badge-id) user) (~a "You've removed " badge-id " from " user "!")) (define (award-multi-badges-command . badges-and-user) (ensure-messaging-user-has-role-on-server! mc-badge-checker-role-id mc-server-id #:failure-message (~a "Sorry, you don't have the right role (<@&" mc-badge-checker-role-id">) for that command.")) (define user (last badges-and-user)) (define badges (take badges-and-user (sub1 (length badges-and-user)))) (define err "") (define awarded (filter identity (map (lambda (b) (with-handlers ([exn:fail? (λ(e) (set! err (~a err (exn-message e) " ")) #f)]) (award-badge! (string->symbol b) user))) badges))) (~a err "You've awarded " (length awarded) " badges to " user "!")) (define (multi-award badges user) (ensure-messaging-user-has-role-on-server! mc-badge-checker-role-id mc-server-id #:failure-message (~a "Sorry, you don't have the right role (<@&" mc-badge-checker-role-id">) for that command.")) (define awarded (filter identity (map (lambda (b) (with-handlers ([exn:fail? (lambda (e) #f)]) (award-badge! (badge-id b) user))) badges))) (~a "You've awarded " (length awarded) " badges to " user "!")) (define (award-all-badges-command user) (multi-award (all-badges) user)) (define (award-all-interest-badges-command user) (multi-award (filter is-interest-badge? (all-badges)) user)) (define (horizon-command . users) ;TODO: Need to return HTML or text file to work around Discord message length limit (define h (map show-badge-text (horizon-for-users users)) ) (if (empty? h) (~a "Empty horizon") h)) (define (display-roster h) (map (lambda (k) (~a (badge-id k) ": " (string-join (hash-ref h k) ", "))) (hash-keys h))) (define (roster-command #:not (not-these-users '()) . users) (define h (roster-for-users (filter-not (curryr member not-these-users) users))) (if (empty? (hash-keys h)) (~a "Empty roster... Did you forget to assign interest badges? Or have these users earned all possible badges?") (display-roster h))) (define (rosterize-station-command voice-channel-id . not-these-users) (apply (curry roster-command #:not not-these-users) (map id->mention (get-users-from-channel voice-channel-id)))) (define (get-available-coaches [coach-voice-channel-id mc-coach-space-station-voice-channel-id]) (get-users-from-channel coach-voice-channel-id )) (define (beam-up-gif) (~a "https://tenor.com/view/beam-me-up-scotty-gif-11313969")) (define (crew-manifest-station-command student-voice-channel-id coach-voice-channel-id . not-these-users) (define coaches-hash (users->earned-badges-hash (filter-not (curryr member not-these-users) (get-available-coaches coach-voice-channel-id)))) (define roster (parameterize ([available-badges (flatten (hash-values coaches-hash))]) (roster-for-users (filter-not (curryr member not-these-users) (get-users-from-channel student-voice-channel-id))))) (define manifests (map (lambda (m) (list (~a "The following mission will be launching shortly:") (badge-url (first m)) (second m) (beam-up-gif))) (crew-manifests roster #:ship-capacity 5 #:coaches coaches-hash))) (if (empty? manifests) "I couldn't construct a manifest for those users" (serve+link manifests))) (define (serve+link discord-repliable) (define file-name (~a "served-reply-" (random 1000) "-" (current-milliseconds))) (with-output-to-file (build-path "public" file-name) (thunk* (displayln (->discord-reply discord-repliable)))) (~a "http://18.213.15.93:6969/" file-name)) (define b (bot ["help" (help-link "https://forum.metacoders.org/t/documentation-badge-bot/137")] ["badges" badges-command] ["badge" badge-command] ;Students do these ["submit" submit-command] ["snooze" snooze-command] ;Coaches can do this, if htey pass in a user as the third param ;Coaches / Badge Checkers do these ["create-user" create-users-command] ["create-users" create-users-command] ["remove-user" remove-users-command] ["remove-users" remove-users-command] ["check" check-badges-command] ["remove" remove-badges-command] ["award" award-badges-command] ["award-multi" award-multi-badges-command] ["award-all" award-all-badges-command] ["award-all-interest" award-all-interest-badges-command] ["horizon" horizon-command] ["roster" roster-command] ["rosterize-station" rosterize-station-command] ["crew-manifest-station" crew-manifest-station-command] ["cms" crew-manifest-station-command] ;Question bot ; ["q" ask-me-a-question] ; ["a" here-is-my-answer] [else void])) (launch-bot b #:persist #t)
false
4537ae99adc8eafa04ce76252326a2061d587e20
38eb03f9e22c9e602ed12ff7db1185ebd7cefbf7
/console-rep.rkt
1525ae5d031ffe4a961498131d95a2d1e53a29e4
[]
no_license
mwatts15/Constraints
7bacfa62a8bf3b88f63c6d6c5b3c6415ad50ac90
d3c1f23973a3b73cbfea37b2a92a3e98ac7b7f5a
refs/heads/master
2020-05-26T23:10:44.578227
2014-01-15T05:00:57
2014-01-15T05:00:57
null
0
0
null
null
null
null
UTF-8
Racket
false
false
877
rkt
console-rep.rkt
#lang racket (require "connector.rkt") (require "traversable.rkt") (provide ConsoleRep) (define ConsoleRep (class* object% (writable<%> ConnectorObserver Traverseable) (super-new) (init-field c) (connect c this) (define (attach p con) (set! c con)) (define (reevaluate) (resolve)) (define (disconnect port) (error "nope")) (define (resolve) (and (send c hasValue?) (display `(,(send c getName) = ,(send c getValue))) (newline))) (define (custom-write out) (display 'ConsoleRep out)) (define (custom-display out) (send this custom-write out)) (define (getName) "ConsoleRep") (define (connectorNames) '()) (define (neighbors) (list c)) (public custom-write custom-display) (public neighbors) (public connectorNames getName resolve reevaluate attach disconnect)))
false
4f29fc99e695c1e636d2fdae61235a1cca8adb30
2256d27c221511a1221257e9318e449d52d0bf47
/racket/matrix.rkt
f4b9f0f8027504457c9c3c243195de1ec200b241
[]
no_license
madewael/Indexes
ee4dd17c38ab46c7322a3cd22bbf6ff76f5651f3
0a53c6c0a1d123bfaf702457c5f7ec8d86dcc213
refs/heads/master
2016-09-05T22:43:45.435144
2014-06-18T08:59:37
2014-06-18T08:59:37
null
0
0
null
null
null
null
UTF-8
Racket
false
false
2,201
rkt
matrix.rkt
#lang racket (require "orders.rkt") (provide make-matrix build-matrix matrix-size matrix-cols matrix-rows matrix-get matrix-set! matrix-map! matrix-vector matrix-change-layout! matrix->string) (struct matrix ((coord->idx #:mutable) rows cols vector)) (define (make-matrix rows cols v) (matrix (row-major-order rows cols) rows cols (make-vector (* rows cols)))) (define (build-matrix rows cols proc) (let ((m (make-matrix rows cols #f))) (for* ((r (in-range rows)) (c (in-range cols))) (matrix-set! m r c (proc r c))) m)) (define (matrix-size m) (* (matrix-rows m) (matrix-cols m))) (define (matrix-get m r c) (let ((i ((matrix-coord->idx m) r c)) (vector (matrix-vector m))) (vector-ref vector i))) (define (matrix-set! m r c v) (let ((i ((matrix-coord->idx m) r c)) (vector (matrix-vector m))) (vector-set! vector i v))) (define (matrix-map! m proc) (vector-map! proc (matrix-vector m)) (void)) (define (matrix->string m) (apply string-append(for/list ((r (in-range (matrix-rows m)))) (string-append (apply string-append (for/list ((c (in-range (matrix-cols m)))) (format "~a\t" (matrix-get m r c)))) "\n")))) (define (matrix-change-layout! m order) (let ((old-vector (for/vector ((e (matrix-vector m))) e)) (new-vector (matrix-vector m)) (old-coord->idx (matrix-coord->idx m)) (new-coord->idx (order (matrix-rows m)(matrix-cols m)))) (for* ((r (in-range (matrix-rows m))) (c (in-range (matrix-cols m)))) (let ((old-i (old-coord->idx r c)) (new-i (new-coord->idx r c))) (vector-set! new-vector new-i (vector-ref old-vector old-i)))) (set-matrix-coord->idx! m new-coord->idx)) (void)) #| (define m (build-matrix 10 10 (λ (r c)(+ (* 10 r) c)))) (display (matrix->string m)) (matrix-map! m (curry * -1)) (display (matrix->string m)) (matrix-map! m (curry * -1)) (matrix-change-layout! m /-order) (display (matrix->string m)) |#
false
4ab51cc1304383f7b13ee9b12f2d8544081fca3f
e12d461e9e5a6268d9ecfa0a208a2d78e167d527
/binaryio/scribblings/bitvector.scrbl
fc84be12495fb3bd47f4d37d01ccb20e1f57db75
[ "Apache-2.0", "MIT" ]
permissive
rmculpepper/binaryio
e7c23fe37be6a3abdf5abbf03efae42a1e339b2a
34ad07e9e33cf835670c4697572e93e8a0af5f02
refs/heads/master
2023-02-02T20:10:54.879562
2023-01-25T09:48:48
2023-01-25T15:01:05
92,235,699
6
2
null
2023-01-25T15:01:06
2017-05-24T01:13:55
Racket
UTF-8
Racket
false
false
8,579
scrbl
bitvector.scrbl
#lang scribble/manual @(require scribble/example (for-label racket/base racket/contract binaryio/bitvector)) @(begin (define the-eval (make-base-eval)) (the-eval '(require binaryio/bitvector))) @; ---------------------------------------- @title[#:tag "sbv"]{Short Bitvectors} @defmodule[binaryio/bitvector] @history[#:added "1.2"] A @deftech{short bitvector} is an immutable bitvector represented as a Racket exact nonnegative integer. The bitvector @racket[[_b_0 _b_1 _b_2 ... _b_L-1]] is represented as the integer @racketblock[ (+ _L (* _b_0 (arithmetic-shift 1 (+ 0 SBV-LENGTH-BITS))) (* _b_1 (arithmetic-shift 1 (+ 1 SBV-LENGTH-BITS))) (* _b_2 (arithmetic-shift 1 (+ 2 SBV-LENGTH-BITS))) ... (* _b_L-1 (arithmetic-shift 1 (+ _L-1 SBV-LENGTH-BITS)))) ] where @racket[SBV-LENGTH-BITS] is currently @racket[16]. That is, a bitvector is represented as a length field plus a shifted, nonnegative integer encoding of its contents. Note that the first bit of the bitvector corresponds to the @emph{least} significant bit of the ``payload'' integer. This is roughly analogous to the relationship between an integer and its encoding using @emph{little-endian} byte order. (See also @tech{least significant first} bit order.) Consequently, bitvectors up to about 46 bits are represented using fixnums (on 64-bit versions of Racket), and only bitvectors up to @racket[(sub1 (expt 2 SBV-LENGTH-BITS))] bits are representable. @defthing[SBV-LENGTH-BITS exact-nonnegative-integer? #:value 16]{ Number of bits used to represent the length of a bitvector. } @defthing[SBV-LENGTH-BOUND exact-nonnegative-integer? #:value @#,(racketvalfont (number->string (expt 2 16)))]{ Bound for representable bitvector lengths. Specifically, a bitvector's length must be strictly less than @racket[SBV-LENGTH-BOUND] to be representable. } @defproc[(sbv? [v any/c]) boolean?]{ Returns @racket[#t] if @racket[v] represents a @tech{short bitvector}, @racket[#f] otherwise. Equivalent to @racket[exact-nonnegative-integer?]. See also @racket[canonical-sbv?]. } @defproc[(canonical-sbv? [v any/c]) boolean?]{ Returns @racket[#t] if @racket[v] is a canonical representation of a @tech{short bitvector}, @racket[#f] otherwise. For example, @racket[(make-sbv @#,(racketvalfont "#b1011") 2)] is not canonical because it has a bit set after the first two bits. @bold{Warning: } In general, the functions in this library may produce bad results if given non-canonical bitvector values. } @defproc[(make-sbv [le-bits exact-nonnegative-integer?] [bitlength exact-nonnegative-integer?]) sbv?]{ Returns a @tech{short bitvector} whose length is @racket[bitlength] and whose elements are the bits representing the integer @racket[le-bits], starting with the @emph{least} significant bit. If @racket[le-bits] has a bit set after the first @racket[bitlength] bits, then the result is non-canonical (see @racket[canonical-sbv?]). If @racket[bitlength] is not less then @racket[SBV-LENGTH-BOUND], an error is raised. @examples[#:eval the-eval (sbv->string (make-sbv 6 3)) ]} @defproc[(make-be-sbv [be-bits exact-nonnegative-integer?] [bitlength exact-nonnegative-integer?]) sbv?]{ Like @racket[make-sbv], but the elements of the bitvector are the bits representing the integer @racket[be-bits] starting with the @emph{most} significant bit (as a @racket[bitlength]-bit number). This is roughly analogous to the relationship between an integer and its encoding using @emph{big-endian} byte order, thus the name @racket[make-be-sbv]. Equivalent to @racket[(sbv-reverse (make-sbv be-bits bitlength))]. @examples[#:eval the-eval (sbv->string (make-be-sbv 6 3)) ]} @defthing[empty-sbv sbv? #:value (make-sbv 0 0)]{ The empty bitvector. } @defproc[(sbv-empty? [sbv sbv?]) boolean?]{ Returns @racket[#t] if @racket[v] is the empty bitvector, @racket[#f] otherwise. } @defproc[(sbv-length [sbv sbv?]) exact-nonnegative-integer?]{ Returns the length of the bitvector. } @defproc[(sbv-bits [sbv sbv?]) exact-nonnegative-integer?]{ Returns the bitvector's contents, encoded as a nonnegative integer. The first element of the bitvector corresponds to the integer's @emph{least} significant bit. @examples[#:eval the-eval (sbv-bits (string->sbv "1011")) ]} @defproc[(sbv-bit-field [sbv sbv?] [start exact-nonnegative-integer?] [end exact-nonnegative-integer?]) exact-nonnegative-integer?]{ Returns the bitvector's contents from @racket[start] (inclusive) to @racket[end] (exclusive), encoded as a nonnegative integer. The element of @racket[sbv] at index @racket[start] corresponds to the integer's @emph{least} significant bit. If @racket[end] is greater than @racket[(sbv-length sbv)], then the ``out of range'' bits are set to zero. @examples[#:eval the-eval (sbv-bit-field (string->sbv "11100") 1 4) (sbv-bit-field (string->sbv "11100") 1 10) ]} @defproc[(sbv-slice [sbv sbv?] [start exact-nonnegative-integer?] [end exact-nonnegative-integer?]) sbv?]{ Returns the bitvector containing the subsequence of bits from @racket[sbv] from indexes @racket[start] (inclusive) to @racket[end] (exclusive). If @racket[end] is greater than @racket[(sbv-length sbv)], then the ``out of range'' bits are set to zero. @examples[#:eval the-eval (sbv->string (sbv-slice (string->sbv "11100") 1 4)) (sbv->string (sbv-slice (string->sbv "11100") 1 10)) ]} @defproc[(sbv-shift [sbv sbv?] [lshift exact-integer?]) sbv?]{ If @racket[lshift] is positive, adds @racket[lshift] zero bits to the beginning of the bitvector. If @racket[lshift] is negative, removes @racket[(- lshift)] bits from the beginning of the bitvector. @examples[#:eval the-eval (sbv->string (sbv-shift (string->sbv "11100") 3)) (sbv->string (sbv-shift (string->sbv "11100") -2)) ]} @defproc[(sbv-bit-set? [sbv sbv?] [index exact-nonnegative-integer?]) boolean?]{ Returns @racket[#t] if the bit at index @racket[index] of @racket[sbv] is set (@racket[1]), @racket[#f] if it is unset (@racket[0]). If @racket[index] is not less than @racket[(sbv-length sbv)], and @racket[sbv] is canonical, then @racket[#f] is returned. @examples[#:eval the-eval (sbv-bit-set? (string->sbv "1101") 0) (sbv-bit-set? (string->sbv "1101") 1) (sbv-bit-set? (string->sbv "1101") 2) ]} @defproc[(sbv-ref [sbv sbv?] [index exact-nonnegative-integer?]) (or/c 0 1)]{ Like @racket[sbv-bit-set?], but returns the bit at the given index. @examples[#:eval the-eval (sbv-ref (string->sbv "1101") 0) (sbv-ref (string->sbv "1101") 1) (sbv-ref (string->sbv "1101") 2) ]} @deftogether[[ @defproc[(sbv-car [sbv sbv?]) (or/c 0 1)] @defproc[(sbv-cdr [sbv sbv?]) sbv?] ]]{ Returns the first bit of the bitvector and the rest of the bitvector, respectively. Equivalent to @racket[(sbv-ref sbv 0)] and @racket[(sbv-shift sbv -1)]. @examples[#:eval the-eval (sbv-car (string->sbv "110")) (sbv->string (sbv-cdr (string->sbv "110"))) ]} @defproc[(sbv-append [sbv sbv?] ...) sbv?]{ Returns the concatenation of the given bitvectors. @examples[#:eval the-eval (sbv->string (sbv-append (string->sbv "1011") (string->sbv "00"))) ]} @defproc[(sbv-cons [bit (or/c 0 1)] [sbv sbv?]) sbv?]{ Adds a bit to the beginning of the bitvector. Equivalent to @racket[(sbv-append (make-sbv bit 1) sbv)]. } @defproc[(sbv-reverse [sbv sbv?]) sbv?]{ Reverses the bits of the bitvector. @examples[#:eval the-eval (sbv->string (sbv-reverse (string->sbv "1101"))) ]} @defproc[(sbv-prefix? [sbv1 sbv?] [sbv2 sbv?]) boolean?]{ Returns @racket[#t] if @racket[sbv1] is a prefix of @racket[sbv2]. @examples[#:eval the-eval (sbv-prefix? (string->sbv "110") (string->sbv "110")) (sbv-prefix? (string->sbv "110") (string->sbv "1100")) (sbv-prefix? (string->sbv "110") (string->sbv "100110")) (sbv-prefix? (string->sbv "110") (string->sbv "11")) ]} @defproc[(sbv->string [sbv sbv?]) string?]{ Returns a string of @litchar{0} and @litchar{1} characters representing the bits of @racket[sbv]. @examples[#:eval the-eval (sbv->string (sbv-append (make-sbv 1 1) (make-sbv 1 1) (make-sbv 0 1))) ] If @racket[sbv] is canonical, then @racket[sbv] is equal to @racketblock[ (make-be-sbv (string->number (sbv->string sbv) 2) (sbv-length sbv)) ]} @defproc[(string->sbv [s (and/c string? #rx"^[01]*$")]) sbv?]{ Parses @racket[s], which should consist of @litchar{0} and @litchar{1} characters, and returns the corresponding bitvector. } @(close-eval the-eval)
false
5b24cefbcd6028ef0b43ef19a1f31101fae88815
f3e1d44eb1780bd5a3fbe3f61c560f18c2447f48
/aplas2011/wfigure.rkt
ecde114e53ecf24050244662cbabf836f23f4881
[]
no_license
willemneal/decompose-plug
afdda44f0182708dae80610dfd98ce8b13af4f04
5bb1acff487d055386c075581b395eb3cfdc12e9
refs/heads/master
2020-12-24T06:24:57.820701
2011-12-07T00:45:16
2011-12-07T00:45:16
null
0
0
null
null
null
null
UTF-8
Racket
false
false
1,381
rkt
wfigure.rkt
#lang racket/base (require (for-syntax racket/base) scribble/core scribble/latex-properties scribble/decode scriblib/figure setup/main-collects) (provide wfigure figure-ref Figure-ref) (define-syntax (wfigure stx) (syntax-case stx () [(_ #:size s tag caption . args) #'(wfigure/proc tag caption s (list . args))] [(_ tag caption . args) #'(wfigure #:size 2 tag caption . args)])) ;; abstraction breaking ... (define figure-style-extras (let ([abs (lambda (s) (path->main-collects-relative (collection-file-path s "scriblib")))]) (list (make-tex-addition (abs "figure.tex"))))) (define (wfigure/proc tag caption size args) (define rendered-size (cond [(equal? size 1.7) "OS"] [(equal? size 1.8) "OE"] [(equal? size 2) "T"] [(equal? size 2.5) "TF"] [(equal? size 2.2) "TT"] [(equal? size 3) "TH"] [else (error 'wfigure "unknown size: ~s" size)])) (define f (decode-flow args)) (nested-flow (style (format "Wfigure~a" rendered-size) (list (make-tex-addition "wfigure.tex"))) (append f (list (make-paragraph plain (list (make-element (make-style "WLegend" figure-style-extras) (list (Figure-target tag) ": " caption))))))))
true
ff82ccd6651156a9952c779c753e00040e362837
898dceae75025bb8eebb83f6139fa16e3590eb70
/pl1/asg2/osx-dist/lib/plt/assignment2-osx/collects/syntax/parse/experimental/private/substitute.rkt
b05447c6b384f6ed90e4b438556b067c1c24eaf7
[]
no_license
atamis/prog-hw
7616271bd4e595fe864edb9b8c87c17315b311b8
3defb8211a5f28030f32d6bb3334763b2a14fec2
refs/heads/master
2020-05-30T22:17:28.245217
2013-01-14T18:42:20
2013-01-14T18:42:20
2,291,884
0
0
null
null
null
null
UTF-8
Racket
false
false
13,126
rkt
substitute.rkt
#lang racket/base (require syntax/parse/private/minimatch racket/private/stx) ;; syntax/stx (provide translate error/not-stx) #| ;; Doesn't seem to make much difference. (require (rename-in racket/unsafe/ops [unsafe-vector-ref vector-ref] [unsafe-vector-set! vector-set!] [unsafe-car car] [unsafe-cdr cdr])) |# ;; ============================================================ #| A Guide (G) is one of: - '_ - positive-exact-integer ;; represents depth=0 pvar ref or metafun ref - negative-exact-integer ;; represents depth>0 pvar ref (within ellipsis) - (cons G G) - (vector 'vector G) - (vector 'struct G) - (vector 'box G) - (vector 'dots HG (listof (vector-of integer)) nat (listof nat) G) - (vector 'app HG G) - (vector 'escaped G) - (vector 'orelse G (vector-of integer) G) - (vector 'metafun integer G) A HeadGuide (HG) is one of: - G - (vector 'app-opt H (vector-of integer)) - (vector 'orelse-h H (vector-of integer) H) - (vector 'splice G) |# (define (head-guide? x) (match x [(vector 'app-opt g vars) #t] [(vector 'splice g) #t] [(vector 'orelse-h g1 vars g2) #t] [_ #f])) ;; ============================================================ ;; A translated-template is (vector loop-env -> syntax) ;; A loop-env is either a vector of values or a single value, ;; depending on lenv-mode of enclosing ellipsis ('dots) form. (define (translate stx g env-length) (let ([f (translate-g stx stx g env-length 0)]) (lambda (env lenv) (unless (>= (vector-length env) env-length) (error 'template "internal error: environment too short")) (f env lenv)))) ;; lenv-mode is one of ;; - 'one ;; lenv is single value; address as -1 ;; - nat ;; lenv is vector; address as (- -1 index); 0 means no loop env (define (translate-g stx0 stx g env-length lenv-mode) (define (loop stx g) (translate-g stx0 stx g env-length lenv-mode)) (define (loop-h stx hg) (translate-hg stx0 stx hg env-length lenv-mode)) (define (get index env lenv) (get-var index env lenv lenv-mode)) (match g ['_ (lambda (env lenv) stx)] [(? exact-integer? index) (check-var index env-length lenv-mode) (lambda (env lenv) (check-stx stx (get index env lenv)))] [(cons g1 g2) (let ([f1 (loop (stx-car stx) g1)] [f2 (loop (stx-cdr stx) g2)]) (cond [(syntax? stx) (lambda (env lenv) (restx stx (cons (f1 env lenv) (f2 env lenv))))] [(eq? g1 '_) (let ([c1 (stx-car stx)]) (lambda (env lenv) (cons c1 (f2 env lenv))))] [(eq? g2 '_) (let ([c2 (stx-cdr stx)]) (lambda (env lenv) (cons (f1 env lenv) c2)))] [else (lambda (env lenv) (cons (f1 env lenv) (f2 env lenv)))]))] [(vector 'dots ghead henv nesting uptos gtail) ;; At each nesting depth, indexes [0,upto) of lenv* vary; the rest are fixed. ;; An alternative would be to have a list of henvs, but that would inhibit ;; the nice simple vector reuse via vector-car/cdr!. (let* ([lenv*-len (vector-length henv)] [ghead-is-hg? (head-guide? ghead)] [ftail (loop (stx-drop (add1 nesting) stx) gtail)]) (for ([var (in-vector henv)]) (check-var var env-length lenv-mode)) (unless (= nesting (length uptos)) (error 'template "internal error: wrong number of uptos")) (let ([last-upto (for/fold ([last 1]) ([upto (in-list uptos)]) (unless (<= upto lenv*-len) (error 'template "internal error: upto is to big")) (unless (>= upto last) (error 'template "internal error: uptos decreased: ~e" uptos)) upto)]) (unless (= lenv*-len last-upto) (error 'template "internal error: last upto was not full env"))) (cond [(and (= lenv*-len 1) (= nesting 1) (not ghead-is-hg?) (equal? ghead '-1)) ;; template was just (pvar ... . T) (let ([fhead (translate-g stx0 (stx-car stx) ghead env-length 'one)]) (lambda (env lenv) (let ([lenv* (get (vector-ref henv 0) env lenv)]) (restx stx (append lenv* (ftail env lenv))))))] [(and (= lenv*-len 1) (= nesting 1) (not ghead-is-hg?)) (let ([fhead (translate-g stx0 (stx-car stx) ghead env-length 'one)]) (lambda (env lenv) (restx stx (let dotsloop ([lenv* (get (vector-ref henv 0) env lenv)]) (if (null? lenv*) (ftail env lenv) (cons (fhead env (car lenv*)) (dotsloop (cdr lenv*))))))))] [else (let ([fhead (if ghead-is-hg? (translate-hg stx0 (stx-car stx) ghead env-length lenv*-len) (translate-g stx0 (stx-car stx) ghead env-length lenv*-len))]) (lambda (env lenv) (define (nestloop lenv* nesting uptos) (cond [(zero? nesting) (fhead env lenv*)] [else (check-lenv stx lenv*) (let ([iters (length (vector-ref lenv* 0))]) (let ([lenv** (make-vector lenv*-len)] [upto** (car uptos)] [uptos** (cdr uptos)]) (let dotsloop ([iters iters]) (if (zero? iters) null (begin (vector-car/cdr! lenv** lenv* upto**) (cons (nestloop lenv** (sub1 nesting) uptos**) (dotsloop (sub1 iters))))))))])) (let ([head-results ;; if ghead-is-hg?, is (listof^(nesting+1) stx) -- extra listof for loop-h ;; otherwise, is (listof^nesting stx) (nestloop (vector-map (lambda (index) (get index env lenv)) henv) nesting uptos)] [tail-result (ftail env lenv)]) (restx stx (nested-append head-results (if ghead-is-hg? nesting (sub1 nesting)) tail-result)))))]))] [(vector 'app ghead gtail) (let ([fhead (loop-h (stx-car stx) ghead)] [ftail (loop (stx-cdr stx) gtail)]) (lambda (env lenv) (restx stx (append (fhead env lenv) (ftail env lenv)))))] [(vector 'escaped g1) (loop (stx-cadr stx) g1)] [(vector 'orelse g1 drivers1 g2) (let ([f1 (loop (stx-cadr stx) g1)] [f2 (loop (stx-caddr stx) g2)]) (for ([var (in-vector drivers1)]) (check-var var env-length lenv-mode)) (lambda (env lenv) (if (for/and ([index (in-vector drivers1)]) (get index env lenv)) (f1 env lenv) (f2 env lenv))))] [(vector 'metafun index g1) (let ([f1 (loop (stx-cdr stx) g1)]) (check-var index env-length lenv-mode) (lambda (env lenv) (let ([v (restx stx (cons (stx-car stx) (f1 env lenv)))] [mark (make-syntax-introducer)] [old-mark (current-template-metafunction-introducer)] [mf (get index env lenv)]) (parameterize ((current-template-metafunction-introducer mark)) (let ([r (mf (mark (old-mark v)))]) (unless (syntax? r) (raise-syntax-error 'template "result of metafunction was not syntax" stx)) (restx stx (old-mark (mark r))))))))] [(vector 'vector g1) (let ([f1 (loop (vector->list (syntax-e stx)) g1)]) (lambda (env lenv) (restx stx (list->vector (f1 env lenv)))))] [(vector 'struct g1) (let ([f1 (loop (cdr (vector->list (struct->vector (syntax-e stx)))) g1)] [key (prefab-struct-key (syntax-e stx))]) (lambda (env lenv) (restx stx (apply make-prefab-struct key (f1 env lenv)))))] [(vector 'box g1) (let ([f1 (loop (unbox (syntax-e stx)) g1)]) (lambda (env lenv) (restx stx (box (f1 env lenv)))))])) (define (translate-hg stx0 stx hg env-length lenv-mode) (define (loop stx g) (translate-g stx0 stx g env-length lenv-mode)) (define (loop-h stx hg) (translate-hg stx0 stx hg env-length lenv-mode)) (define (get index env lenv) (get-var index env lenv lenv-mode)) (match hg [(vector 'app-opt hg1 drivers1) (let ([f1 (loop-h (stx-cadr stx) hg1)]) (for ([var (in-vector drivers1)]) (check-var var env-length lenv-mode)) (lambda (env lenv) (if (for/and ([index (in-vector drivers1)]) (get index env lenv)) (f1 env lenv) null)))] [(vector 'orelse-h hg1 drivers1 hg2) (let ([f1 (loop-h (stx-cadr stx) hg1)] [f2 (loop-h (stx-caddr stx) hg2)]) (for ([var (in-vector drivers1)]) (check-var var env-length lenv-mode)) (lambda (env lenv) (if (for/and ([index (in-vector drivers1)]) (get index env lenv)) (f1 env lenv) (f2 env lenv))))] [(vector 'splice g1) (let ([f1 (loop (stx-cdr stx) g1)]) (lambda (env lenv) (let* ([v (f1 env lenv)] [v* (stx->list v)]) (unless (list? v*) (raise-syntax-error 'template "splicing template did not produce a syntax list" stx)) v*)))] [else (let ([f (loop stx hg)]) (lambda (env lenv) (list (f env lenv))))])) (define (get-var index env lenv lenv-mode) (cond [(positive? index) (vector-ref env (sub1 index))] [(negative? index) (case lenv-mode ((one) lenv) (else (vector-ref lenv (- -1 index))))])) (define (check-var index env-length lenv-mode) (cond [(positive? index) (unless (< (sub1 index) env-length) (error/bad-index index))] [(negative? index) (unless (< (- -1 index) (case lenv-mode ((one) 1) (else lenv-mode))) (error/bad-index))])) (define (check-lenv stx lenv) (for ([v (in-vector lenv)]) (unless v (error 'template "pattern variable used in ellipsis pattern is not defined"))) (let ([len0 (length (vector-ref lenv 0))]) (for ([v (in-vector lenv)]) (unless (= len0 (length v)) (raise-syntax-error 'template "incomplatible ellipsis match counts for template" stx))))) ;; ---- (define current-template-metafunction-introducer (make-parameter (lambda (stx) (if (syntax-transforming?) (syntax-local-introduce stx) stx)))) ;; ---- (define (stx-cadr x) (stx-car (stx-cdr x))) (define (stx-cddr x) (stx-cdr (stx-cdr x))) (define (stx-caddr x) (stx-car (stx-cdr (stx-cdr x)))) (define (stx-drop n x) (cond [(zero? n) x] [else (stx-drop (sub1 n) (stx-cdr x))])) (define (restx basis val) (if (syntax? basis) (let ([stx (datum->syntax basis val basis)] [paren-shape (syntax-property basis 'paren-shape)]) (if paren-shape (syntax-property stx 'paren-shape paren-shape) stx)) val)) ;; nested-append : (listof^(nesting+1) A) nat (listof A) -> (listof A) ;; (Actually, in practice onto is stx, so this is an improper append.) (define (nested-append lst nesting onto) (cond [(zero? nesting) (append lst onto)] [(null? lst) onto] [else (nested-append (car lst) (sub1 nesting) (nested-append (cdr lst) nesting onto))])) (define (check-stx ctx v) (if (syntax? v) v (error/not-stx ctx v))) (define (error/not-stx ctx v) (raise-syntax-error 'template "pattern variable is not syntax-valued" ctx)) (define (error/bad-index index) (error 'template "internal error: bad index: ~e" index)) (define (vector-car/cdr! dest-v src-v upto) (let ([len (vector-length dest-v)]) (let loop ([i 0]) (when (< i upto) (let ([p (vector-ref src-v i)]) (vector-set! dest-v i (car p)) (vector-set! src-v i (cdr p))) (loop (add1 i)))) (let loop ([j upto]) (when (< j len) (vector-set! dest-v j (vector-ref src-v j)) (loop (add1 j)))))) (define (vector-map f src-v) (let* ([len (vector-length src-v)] [dest-v (make-vector len)]) (let loop ([i 0]) (when (< i len) (vector-set! dest-v i (f (vector-ref src-v i))) (loop (add1 i)))) dest-v))
false
868e0ae96973d8a742b5660386d504777e8d7d86
4d204d78919b942b9174bce87efa922ef2f630ed
/itscaleb/ch02/2.59.rkt
c14d6c7f2cc0486d50ae452ea639f54a574227d3
[]
no_license
SeaRbSg/SICP
7edf9c621231c0348cf3c7bb69789afde82998e4
2df6ffc672e9cbf57bed4c2ba0fa89e7871e22ed
refs/heads/master
2016-09-06T02:11:30.837100
2015-07-28T21:21:37
2015-07-28T21:21:37
20,213,338
0
2
null
null
null
null
UTF-8
Racket
false
false
565
rkt
2.59.rkt
#lang racket (require rackunit) (define (element-of-set? x set) (cond [(null? set) false] [(equal? x (car set)) #t] [else (element-of-set? x (cdr set))])) (define (union-set set1 set2) (cond [(null? set1) set2] [(null? set2) set1] [(element-of-set? (car set1) set2) (union-set (cdr set1) set2)] [else (union-set (cdr set1) (cons (car set1) set2))])) (check-equal? (union-set '(1 2) '(2 3)) '(1 2 3)) (check-equal? (union-set '(1 2 3) '(8 9 10)) '(3 2 1 8 9 10))
false
50791a9d06c675567c45d052dd421b957e0fb5c3
d8ea14591f5a72ced999f27341b4425370fd043b
/c-style.rkt
a90dbe0faf424325bcf069838621ecd5b0238340
[]
no_license
GoNZooo/fear-of-macros
2a2f005c7f9eb0df234290c58f5603d110031a67
a3ea14c834da01f4c4b5f3584732db0bdd281a38
refs/heads/master
2020-06-04T04:19:56.641544
2013-11-04T17:59:27
2013-11-04T17:59:27
null
0
0
null
null
null
null
UTF-8
Racket
false
false
1,609
rkt
c-style.rkt
#lang racket (require (for-syntax racket/syntax)) ;;; Macro for defining int. ;;; Automatically defines <int-name>++-function. (define-syntax (int stx) (syntax-case stx () [(_ integer-name value) (with-syntax ([plusplus-func (format-id stx "~a++" #'integer-name)] [minusminus-func (format-id stx "~a--" #'integer-name)]) #'(begin (define integer-name value) (define (plusplus-func) (set! integer-name (add1 integer-name))) (define (minusminus-func) (set! integer-name (sub1 integer-name)))))])) ;;; Macro for while-loops. (define-syntax (while stx) (syntax-case stx () [(_ condition body ...) #'(letrec ([loop (lambda () (when condition body ... (loop)))]) (loop))])) ;;; Macro for c-style for-loop. (define-syntax (c-for stx) (syntax-case stx () [(_ init condition tail-expression body ...) #'(begin init (letrec ([loop (lambda () (when condition body ... tail-expression (loop)))]) (loop)))])) (module+ main (printf "While:~n") (int while-integer 0) (while (< while-integer 10) (printf "~a~n" while-integer) (while-integer++)) (printf "For:~n") (c-for (int i 0) (< i 10) (i++) (printf "~a~n" i)) (printf "For with --:~n") (c-for (int j 10) (> j 0) (j--) (printf "~a~n" j)))
true
d56f2e300365ffb6b7e73953c7ce1f651d62f04a
099418d7d7ca2211dfbecd0b879d84c703d1b964
/whalesong/tests/older-tests/moby-programs/continuation-prompts-2.rkt
aa2d2e0928dbecfc00083d307774b1067b8e8bb6
[]
no_license
vishesh/whalesong
f6edd848fc666993d68983618f9941dd298c1edd
507dad908d1f15bf8fe25dd98c2b47445df9cac5
refs/heads/master
2021-01-12T21:36:54.312489
2015-08-19T19:28:25
2015-08-19T20:34:55
34,933,778
3
0
null
2015-05-02T03:04:54
2015-05-02T03:04:54
null
UTF-8
Racket
false
false
748
rkt
continuation-prompts-2.rkt
#lang s-exp "../../lang/wescheme.rkt" (define (escape v) (abort-current-continuation (default-continuation-prompt-tag) (lambda () v))) (printf "continuation-prompts-2.rkt\n") (printf "testing expected value from abort with default continuation prompt tag\n") (check-expect (+ 1 (call-with-continuation-prompt (lambda () (+ 1 (+ 1 (+ 1 (+ 1 (+ 1 (+ 1 (escape 6)))))))) (default-continuation-prompt-tag))) 7) (check-expect (+ 1 (call-with-continuation-prompt (lambda () (+ 1 (+ 1 (+ 1 (+ 1 (+ 1 (+ 1 (escape 24)))))))) (default-continuation-prompt-tag) (lambda (thunk) (printf "I see the escape\n") (thunk)))) 25) (printf "continuation-prompts-2 tests done!\n")
false
f75592a3ef434ddabc3f0b677c6bb234e5fc6da9
aa0e6a65f31677783b8bd0262ef9fdeca870955e
/racket-graph/testGraph.rkt
1d220febda98a3db471b6450106e8efb47d63a10
[]
no_license
StrongerXi/Traveler-lang
56053d12542d71c6e9f3f0045fdace25369715e4
973f7c802197b4c7a613d2ca835299b274c293d1
refs/heads/master
2021-03-30T17:17:36.943712
2018-02-06T19:04:37
2018-02-06T19:04:37
null
0
0
null
null
null
null
UTF-8
Racket
false
false
359
rkt
testGraph.rkt
#lang s-exp "graphSyntax.rkt" (define-graph (name Boston-map) (directed? #t)) (define-nodes (Harvard -> Cambridge Potter) (Cambridge -> Harvard) (Potter -> Harvard)) (add-nodes (Harvard Cambridge Potter) -> Boston-map) ;(find-all-paths ...) (print-graph Boston-map) (subprocess ...)
false
3f446cebd131da29deee62a193ccd296a31607a9
ded5174b1e1554f106022689d479bb7197d62082
/Racket/Lab6.rkt
982795795517357901b0cdbc402eb1f052c4be7e
[]
no_license
nadazeini/Programming-Paradigms
e968d8669cde01caf7ec51fa18bbd675eae2324e
cc3cbcb57d6acc93521b032a5bbc4bc19bb47d18
refs/heads/master
2020-09-23T10:38:51.526457
2019-12-15T00:42:43
2019-12-15T00:42:43
null
0
0
null
null
null
null
UTF-8
Racket
false
false
917
rkt
Lab6.rkt
#lang racket ;;mine (define-syntax switch (syntax-rules () [(switch a [default d]) d] [(switch a [b c] rest ... ) (begin (if (equal? a b) c (switch a rest ...)))])) ;;solution (define-syntax switch1 (syntax-rules (default) {(switch c) (void)};base case 1 {(switch c [default body]) body} ; base case 2 { (switch c [val1 body1] rest-cases ...) (let ([v c]) (if (eq? v val1) body1 (switch v rest-cases ...)))})) ;;cooler solution (define-syntax switch2 (syntax-rules (default) {(switch c [val body] ... [default def-body]) (let [v c] (cond [eqv? v val] body) ... [else def-body])} (define x 99) (switch x [3 (displayln "x is 3")] [4 (displayln "x is 4")] [5 (displayln "x is 5")] [default (displayln "none of the above")])
true
d785976f4ff1ed2fef86593d202ebeb391e75749
f987ad08fe780a03168e72efce172ea86ad5e6c0
/plai-lib/tests/gc2/good-mutators/yixi.rkt
66b9510dbb141725cb8c41fb0bfa70a55c82b17a
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "Apache-2.0" ]
permissive
racket/plai
a76573fdd29b648e04f8adabcdc8fb1f6825d036
ae42bcb581ab02dcb9ddaea98d5ecded589c8d47
refs/heads/master
2023-08-18T18:41:24.326877
2022-10-03T02:10:02
2022-10-03T02:10:14
27,412,198
11
12
NOASSERTION
2022-07-08T19:16:11
2014-12-02T02:58:30
Racket
UTF-8
Racket
false
false
167
rkt
yixi.rkt
#lang plai/gc2/mutator (allocator-setup "../good-collectors/good-collector.rkt" 255) (define (f b) 17) (define (g l f) ((lambda (x) (f (first l))) 1)) (g '(3) f)
false
9ec4a6f7acd374c634f57ba5d2e8b947190d2097
a5d31dc29c25d1f2c0dab633459de05f5996679a
/delta.rkt
112aaa0324c65ec5fbe7b76d1e905d0ec1557cbd
[]
no_license
jebcat1982/soft-contract
250461a231b150b803df9275f33ee150de043f00
4df509a75475843a2caeb7e235301f277446e06c
refs/heads/master
2021-01-21T22:06:10.092109
2014-05-26T11:51:00
2014-05-26T11:51:00
null
0
0
null
null
null
null
UTF-8
Racket
false
false
40,030
rkt
delta.rkt
#lang typed/racket (require "utils.rkt" "lang.rkt" "closure.rkt" "provability.rkt" "show.rkt") (provide (all-defined-out)) (define-syntax-rule (match/Ans* v [p e ...] ...) (match/nd: (.Ans → .Ans) v [p e ...] ...)) (define-syntax-rule (match/Vns* v [p e ...] ...) (match/nd: (.Vns → .Vns) v [p e ...] ...)) (: δ : .σ .o (Listof .V) Sym → .Ans*) (define (δ σ o V* l) #;(printf "δ: o: ~a~nV*: ~a~n~nσ: ~a~n~n~n" o (map (curry show-E σ) V*) (show-σ σ)) (match* (o V*) ; primitive predicates [((? .pred? o) (list V)) (check-C σ V (→V o))] ; accessors [((.st-ac t _ i) (list (.// (.St t V*) _))) (cons σ (list-ref V* i))] [((.st-ac t n i) (list V)) (match/Ans* (δ σ (.st-p t n) V* 'Λ) [(cons σt (.// (.b #t) _)) (match-let ([(.// (.St _ V*) _) (σ@ σt V)]) (cons σt (list-ref V* i)))] [(cons σf (.// (.b #f) _)) (cons σf (.blm l (name o) V (→V (.st-p t n))))])] ; arithmetics [((.=) (list V1 V2)) (match/Ans* (δ σ (.num?) (list V1) 'Λ) [(cons σt (.// (.b #t) _)) (match/Ans* (δ σt (.num?) (list V2) 'Λ) [(cons σt (.// (.b #t) _)) (Δ σt (.=) V*)] [(cons σf (.// (.b #f) _)) (cons σf (.blm l '= V2 NUM/C))])] [(cons σf (.// (.b #f) _)) (cons σf (.blm l '= V1 NUM/C))])] [((or (.add1) (.sub1)) (list V)) (match/Ans* (δ σ (.num?) V* 'Λ) [(cons σt (.// (.b #t) _)) (Δ σt o V*)] [(cons σf (.// (.b #f) _)) (cons σf (.blm l (name o) V NUM/C))])] [((or (.+) (.-) (.*)) (list V1 V2)) (match/Ans* (δ σ (.num?) (list V1) 'Λ) [(cons σt (.// (.b #t) _)) (match/Ans* (δ σt (.num?) (list V2) 'Λ) [(cons σt (.// (.b #t) _)) (Δ σt o V*)] [(cons σf (.// (.b #f) _)) (cons σf (.blm l (name o) V2 NUM/C))])] [(cons σf (.// (.b #f) _)) (cons σf (.blm l (name o) V1 NUM/C))])] [((./) (list V1 V2)) (match/Ans* (δ σ (.num?) (list V1) 'Λ) [(cons σt (.// (.b #t) _)) (match/Ans* (δ σt (.num?) (list V2) 'Λ) [(cons σt (.// (.b #t) _)) (match/Ans* (δ σt (.=) (list V2 (Prim 0)) 'Λ) [(cons σt (.// (.b #t) _)) (cons σt (.blm l '/ V2 NON-ZERO/C))] [(cons σf (.// (.b #f) _)) (Δ σf (./) V*)])] [(cons σf (.// (.b #f) _)) (cons σf (.blm l '/ V2 NUM/C))])] [(cons σf (.// (.b #f) _)) (cons σf (.blm l '/ V1 NUM/C))])] [((or (.>) (.<) (.≤) (.≥)) (list V1 V2)) (match/Ans* (δ σ (.real?) (list V1) 'Λ) [(cons σt (.// (.b #t) _)) (match/Ans* (δ σt (.real?) (list V2) 'Λ) [(cons σt (.// (.b #t) _)) (Δ σt o V*)] [(cons σf (.// (.b #f) _)) (cons σf (.blm l (name o) V2 REAL/C))])] [(cons σf (.// (.b #f) _)) (cons σf (.blm l (name o) V1 REAL/C))])] [((.str-len) (list V)) (match/Ans* (δ σ (.str?) V* 'Λ) [(cons σt (.// (.b #t) _)) (Δ σt (.str-len) V*)] [(cons σf (.// (.b #f) _)) (cons σf (.blm l 'str-len V STR/C))])] [((.equal?) (list V1 V2)) (V=? σ V1 V2)] [((.sqrt) (list V)) (match/Ans* (δ σ (.real?) (list V) 'Λ) [(cons σt (.// (.b #t) _)) (Δ σt (.sqrt) V*)] [(cons σf (.// (.b #f) _)) (cons σf (.blm l 'sqrt V REAL/C))])] ; arity check [((or (.arity=?) (.arity≥?) (.arity-includes?)) (list V1 V2)) (match/Ans* (δ σ (.proc?) (list V1) 'Λ) [(cons σt (.// (.b #t) _)) (match/Ans* (δ σt (.int?) (list V2) 'Λ) [(cons σt (.// (.b #t) _)) (check-C σt V1 (→C o #:2nd V2))] [(cons σf (.// (.b #f) _)) (cons σf (.blm l (name o) V2 INT/C))])] [(cons σf (.// (.b #f) _)) (cons σf (.blm l (name o) V1 PROC/C))])] ; constructor [((.st-mk t n) _) (if (= (length V*) n) (cons σ (→V (.St t V*))) (cons σ (.blm l t (Prim (length V*)) (arity=/C n))))] ; anything else is error [(_ _) (cons σ (.blm l (name o) ♦ (arity=/C -1 #|HACK|#)))])) (: Δ : .σ .o (Listof .V) → .Vns*) (define (Δ σ o V*) (match* (o V*) [((.add1) (list V)) (Δ σ (.+) (list V ONE))] [((.sub1) (list V)) (Δ σ (.-) (list V ONE))] [((.*) (list V1 V2)) (match (for/list: : (Listof .V) ([Vi V*]) (σ@ σ Vi)) [(list (.// (.b (? num? x)) _) (.// (.b (? num? y)) _)) (cons σ (Prim (* x y)))] [(list (and W1 (.// U1 _)) (and W2 (.// U2 _))) (let ([X1 (if (.•? U1) V1 W1)] [X2 (if (.•? U2) V2 W2)]) (cond [(eq? 'Proved (⊢ σ X1 ZERO/C)) (cons σ ZERO)] [(eq? 'Proved (⊢ σ X2 ZERO/C)) (cons σ ZERO)] [(eq? 'Proved (⊢ σ X1 ONE/C)) (cons σ X2)] [(eq? 'Proved (⊢ σ X2 ONE/C)) (cons σ X1)] [else (σ+ σ (cond [(all-prove? σ V* INT/C) INT/C] [(all-prove? σ V* REAL/C) REAL/C] [else NUM/C]) (cond [(all-prove? σ V* POS/C) POS/C] [(all-prove? σ V* NON-NEG/C) NON-NEG/C] [(all-prove? σ V* NON-ZERO/C) NON-ZERO/C] [else #f]) (*/C X1 X2))]))])] [((./) (list V1 V2)) (match (for/list: : (Listof .V) ([Vi V*]) (σ@ σ Vi)) [(list (.// (.b (? num? x)) _) (.// (.b (? num? y)) _)) (cons σ (Prim (/ x y)))] [(list (and W1 (.// U1 _)) (and W2 (.// U2 _))) (let ([X1 (if (.•? U1) V1 W1)] [X2 (if (.•? U2) V2 W2)]) (cond [(eq? 'Proved (⊢ σ X1 ZERO/C)) (cons σ ZERO)] [else (σ+ σ (cond [(all-prove? σ V* REAL/C) REAL/C] [else NUM/C]) (cond [(all-prove? σ V* POS/C) POS/C] [(all-prove? σ V* NON-NEG/C) NON-NEG/C] [(eq? 'Proved (⊢ σ V1 NON-ZERO/C)) NON-ZERO/C] [else #f]) (÷/C X1 X2) (if (eq? 'Proved (⊢ σ X1 NON-ZERO/C)) NON-ZERO/C #f))]))])] [((.+) (list V1 V2)) (match (for/list: : (Listof .V) ([Vi V*]) (σ@ σ Vi)) [(list (.// (.b (? num? x)) _) (.// (.b (? num? y)) _)) (cons σ (Prim (+ x y)))] [(list (and W1 (.// U1 _)) (and W2 (.// U2 _))) (let ([X1 (if (.•? U1) V1 W1)] [X2 (if (.•? U2) V2 W2)]) (cond [(eq? 'Proved (⊢ σ X1 ZERO/C)) (cons σ X2)] [(eq? 'Proved (⊢ σ X2 ZERO/C)) (cons σ X1)] [else (match-let ([ans (σ+ σ (cond [(all-prove? σ V* INT/C) INT/C] [(all-prove? σ V* REAL/C) REAL/C] [else NUM/C]) (cond [(all-prove? σ V* POS/C) POS/C] [(all-prove? σ V* NEG/C) NEG/C] [(all-prove? σ V* NON-NEG/C) NON-NEG/C] [(all-prove? σ V* NON-POS/C) NON-POS/C] [else #f]) (+/C X1 X2))]) ans)]))])] [((.-) (list V1 V2)) (match (for/list: : (Listof .V) ([Vi V*]) (σ@ σ Vi)) [(list (.// (.b (? num? x)) _) (.// (.b (? num? y)) _)) (cons σ (Prim (- x y)))] [(list (and W1 (.// U1 _)) (and W2 (.// U2 _))) (let ([X1 (if (.•? U1) V1 W1)] [X2 (if (.•? U2) V2 W2)]) (cond [(and (.L? X1) (.L? X2) (equal? X1 X2)) (cons σ ZERO)] [(eq? 'Proved (⊢ σ X2 ZERO/C)) (cons σ X1)] [else (σ+ σ (cond [(all-prove? σ V* INT/C) INT/C] [(all-prove? σ V* REAL/C) REAL/C] [else NUM/C]) (-/C X1 X2))]))])] [((.sqrt) (list V)) (match (for/list: : (Listof .V) ([Vi V*]) (σ@ σ Vi)) [(list (.// (.b (? real? x)) _)) (cons σ (Prim (sqrt x)))] [(list (and W (.// U _))) (let ([X (if (.•? U) V W)]) (cond [(eq? 'Proved (⊢ σ X ZERO/C)) (cons σ ZERO)] [else (σ+ σ (cond [(equal? 'Proved (⊢ σ V POS/C)) {set REAL/C POS/C}] [(equal? 'Proved (⊢ σ V NON-NEG/C)) {set REAL/C NON-NEG/C}] [(equal? 'Proved (⊢ σ V NEG/C)) {set NUM/C (.¬/C REAL/C)}] [else NUM/C]) (sqrt/C V))]))])] [((.<) (list (.L i) (.L i))) (cons σ FF)] [((.<) (list V1 V2)) (match (for/list: : (Listof .V) ([Vi V*]) (σ@ σ Vi)) [(list (.// (.b (? real? x)) _) (.// (.b (? real? y)) _)) (cons σ (Prim (< x y)))] [(list (and W1 (.// U1 _)) (and W2 (.// U2 _))) (let ([X1 (if (.•? U1) V1 W1)] [X2 (if (.•? U2) V2 W2)]) (match (⊢ σ X1 (</C X2)) ['Proved (cons σ TT)] ['Refuted (cons σ FF)] ['Neither (match (⊢ σ X2 (>/C X1)) ['Proved (cons σ TT)] ['Refuted (cons σ FF)] ['Neither (match-let* ([(cons σt _) (match* (X1 X2) [((.L i) (.L j)) (if (> i j) (refine σ X1 (</C X2)) (refine σ X2 (>/C X1)))] [((.L _) _) (refine σ X1 (</C X2))] [(_ (.L _)) (refine σ X2 (>/C X1))] [(_ _) (cons σ 'ignore)])] [(cons σf _) (match* (X1 X2) [((.L i) (.L j)) (if (> i j) (refine σ X1 (≥/C X2)) (refine σ X2 (≤/C X1)))] [((.L _) _) (refine σ X1 (≥/C X2))] [(_ (.L _)) (refine σ X2 (≤/C X1))] [(_ _) (cons σ 'ignore)])]) {set (cons σt TT) (cons σf FF)})])]))])] [((.>) (list V1 V2)) (Δ σ (.<) (list V2 V1))] [((.>) (list (.L i) (.L i))) (cons σ FF)] [((.≥) (list (.L i) (.L i))) (cons σ TT)] [((.≥) (list V1 V2)) (match/Vns* (Δ σ (.<) (list V1 V2)) [(cons σt (.// (.b #t) _)) (cons σt FF)] [(cons σf (.// (.b #f) _)) (cons σf TT)])] [((.≤) (list (.L i) (.L i))) (cons σ TT)] [((.≤) (list V1 V2)) (Δ σ (.≥) (list V2 V1))] [((.=) (list (.L i) (.L i))) (cons σ TT)] [((.=) (list V1 V2)) (match (for/list: : (Listof .V) ([Vi V*]) (σ@ σ Vi)) [(list (.// (.b (? num? x)) _) (.// (.b (? num? y)) _)) (cons σ (Prim (= x y)))] [(list (and W1 (.// U1 _)) (and W2 (.// U2 _))) (let ([X1 (if (.•? U1) V1 W1)] [X2 (if (.•? U2) V2 W2)]) (match (⊢ σ X1 (=/C X2)) ['Proved (cons σ TT)] ['Refuted (cons σ FF)] ['Neither (match (⊢ σ X2 (=/C X1)) ['Proved (cons σ TT)] ['Refuted (cons σ FF)] ['Neither (match-let* ([(cons σt _) (match* (X1 X2) [((.L i) (.L j)) (if (> i j) (refine σ X1 (=/C X2)) (refine σ X2 (=/C X1)))] [((.L _) _) (refine1 σ X1 (=/C X2))] [(_ (.L _)) (refine1 σ X2 (=/C X1))] [(_ _) (cons σ 'ignore)])] [(cons σf _) (match* (X1 X2) [((.L i) (.L j)) (if (> i j) (refine σ X1 (≠/C X2)) (refine σ X2 (≠/C X1)))] [((.L _) _) (refine1 σ X1 (≠/C X2))] [(_ (.L _)) (refine1 σ X2 (≠/C X1))] [(_ _) (cons σ 'ignore)])]) {set (cons σt TT) (cons σf FF)})])]))])] [((.str-len) (list V)) (match (σ@ σ V) [(.// (.b (? str? s)) _) (cons σ (Prim (string-length s)))] [_ (σ+ σ INT/C NON-NEG/C)])])) (: V=? : .σ .V .V → .Vns*) (define (V=? σ V1 V2) (match* (V1 V2) [((.L i) (.L i)) (cons σ TT)] [((.L i) (and (.// (not (? .•?)) _) V2)) (match/Vns* (V=? σ (σ@ σ i) V2) [(cons σt (.// (.b #t) _)) (cons (σ-set σ i V2) TT)] [a a])] [((and (.// (not (? .•?)) _) V1) (.L i)) (match/Vns* (V=? σ V1 (σ@ σ i)) [(cons σt (.// (.b #t) _)) (cons (σ-set σ i V1) TT)] [a a])] [(_ (.L i)) (V=? σ V1 (σ@ σ i))] [((.L i) _) (V=? σ (σ@ σ i) V2)] [(_ (.// (.•) _)) {set (cons σ TT) (cons σ FF)}] [((.// (.•) _) _) {set (cons σ TT) (cons σ FF)}] [((.// (.St t1 V1*) _) (.// (.St t2 V2*) _)) (if (eq? t1 t2) (let loop ([σ σ] [V1* V1*] [V2* V2*]) (match* (V1* V2*) [('() '()) (cons σ TT)] [((cons V1 V1r) (cons V2 V2r)) (match/Vns* (V=? σ V1 V2) [(cons σt (.// (.b #t) _)) (loop σt V1* V2*)] [a a])])) (cons σ FF))] ; default [((.// U1 _) (.// U2 _)) (cons σ (Prim (equal? U1 U2)))])) (: refine : .σ .V (U (Setof .V) (Listof .V) .V) * → .Vns) (define (refine σ V . C**) (: go : .σ .V (Listof (U (Setof .V) (Listof .V) .V)) → .Vns) (define (go σ V C**) #;(printf "REFINE:~n~a~n~a~n~a~n~n" σ V C**) (match C** ['() (cons σ V)] [(cons (? list? C*) Cr*) (match-let ([(cons σ′ V′) (for/fold: ([σV : .Vns (cons σ V)]) ([C : .V C*]) (match-let ([(cons σ V) σV]) (refine σ V C)))]) (go σ′ V′ Cr*))] [(cons (? set? C*) Cr*) (match-let ([(cons σ′ V′) (for/fold: ([σV : .Vns (cons σ V)]) ([C : .V C*]) (match-let ([(cons σ V) σV]) (refine σ V C)))]) (go σ′ V′ Cr*))] [(cons (? .V? C) Cr*) (match (⊢ σ V C) ['Proved (cons σ V)] ['Refuted (error "Bogus refinement")] [_ (match-let ([(cons σ′ V′) (refine1 σ V C)]) (go σ′ V′ Cr*))])])) (go σ V C**)) (: refine1 : .σ .V .V → .Vns) (define (refine1 σ V C) (let ([C (simplify C)]) #;(printf "refine1:~n~a~n~a~n~a~n~n" (show-σ σ) (show-E σ V) (show-E σ C)) (when (match? C (.// (.•) _)) (error "ha!")) (match V [(.L i) (match-let ([(cons σ′ V′) (refine1 σ (σ@ σ i) C)]) (match V′ [(.// (.St t V*) C*) (match-let* ([(cons σ′ V*′) (alloc σ′ V*)] [V′ (.// (.St t V*′) C*)]) (cons (σ-set σ′ i V′) V))] [(? .//? V′) (cons (σ-set σ′ i V′) V)] [(? .μ/V? V′) (cons (σ-set σ′ i V′) V)] ; duplicate to get around TR [_ (error "broken =_=" V)])) #;(match (refine1 σ (σ@ σ i) C) [(cons σ (? .L? L)) (cons σ L)] [(cons σ′ V′) (if (or (.//? V′) (.μ/V? V′)) (cons (σ-set σ′ i V′) V) (error "broken: " V′))])] [(.// U C*) (match C [(.L _) (cons σ (.// U (set-add C* C)))] [(.// Uc _) (match Uc [(.St 'and/c (list C1 C2)) (refine σ V C1 C2)] [(.St 'or/c (list C1 C2)) (match* ((⊢ σ V C1) (⊢ σ V C2)) [('Refuted 'Refuted) (error "WTF??")] [(_ 'Refuted) (refine1 σ V C1)] [('Refuted _) (refine1 σ V C2)] [(_ _) (cons σ (.// U (refine-C* C* C)))])] [(and Uc (.μ/C x C′)) (match U [(.•) (cons σ (reify C))] [(.St t V*) (refine1 σ V (unroll/C Uc))] [_ (cons σ V)])] ; equal contracts [(.λ↓ (.λ 1 (.@ (or (.=) (.equal?)) (list (.x 0) e) _) #f) ρ) (match e [(? .b? b) (cons σ (.// b C*))] [(and (? .λ? f) (? closed?)) (cons σ (.// (.λ↓ f ρ∅) C*))] [(.x i) (match (ρ@ ρ (- i 1)) [(.L a) (match-let ([(.// U′ C*′) (σ@ σ a)]) (cons σ (.// (U+ U U′) (∪ C* C*′ C))))] [(.// U′ C*′) (cons σ (.// (U+ U U′) (∪ C* C*′)))])] [_ (cons σ (.// U (set-add C* C)))])] ; struct contracts [(.St/C t D*) (match-let* ([(cons σ V*) (ann (match U [(.•) (σ++ σ (length D*))] [(.St _ V*) (cons σ V*)]) (Pairof .σ (Listof .V)))] [(cons σ V*) (refine* σ V* D*)]) (cons σ (.// (.St t V*) C*)))] [(.st-p t n) (match U [(.•) (match-let ([(cons σ′ L*) (σ++ σ n)]) (cons σ′ (.// (.St t L*) C*)))] [(.St (? (curry eq? t)) _) (cons σ V)])] ; singleton contracts [(.true?) (cons σ (.// .tt C*))] [(.false?) (cons σ (.// .ff C*))] [(.st-p t 0) (cons σ (.// (.St t '()) C*))] [_ (cons σ (.// U (set-add C* C)))])])] [(and (.μ/V x V*) V) (let*-values ([(σ′ V*′) (for/fold: ([σ : .σ σ] [Vs : (Setof .V) ∅]) ([Vi V*]) (match (⊢ σ Vi C) ['Proved (values σ (set-add Vs Vi))] ['Refuted (values σ Vs)] ['Neither (match-let* ([(cons σ′ Vj) (refine1 σ Vi C)] [(cons Vj′ Vs′) (elim-μ x Vj)]) (values σ′ (compact (compact Vs Vs′) {set Vj′})))]))]) #;(printf "new V* is ~a~n~n" (for/set: Any ([Vi V*′]) (show-V σ′ Vi))) (match (set-count V*′) [0 (error "bogus refinement") #;V∅] [1 (cons σ′ (V/ (set-first V*′) (.X/V x) V))] [_ (cons σ′ (μV x V*′))]))] [(? .X/V? x) (cons σ x)]))) ; abuse μ for non-inductive set (: refine* : .σ (Listof .V) (Listof .V) → (Pairof .σ (Listof .V))) (define (refine* σ V* C*) (let-values ([(σ′ V*′) (for/fold: ([σ : .σ σ] [Vs : (Listof .V) '()]) ([V V*] [C C*]) #;(printf "Got:~n~a~n~a~n~n" V C) (match-let ([(cons σ V) (refine1 σ V C)]) (values σ (cons V Vs))))]) (cons σ′ (reverse V*′)))) (: check-C : .σ .V .V → .Vns*) (define (check-C σ V C) (match (⊢ σ V C) ['Proved (cons σ TT)] ['Refuted (cons σ FF)] ['Neither (match-let ([(cons σt _) (refine σ V C)] [(cons σf _) (refine σ V (.¬/C C))]) {set (cons σt TT) (cons σf FF)})])) (: refine-C* : (Setof .V) .V → (Setof .V)) (define (refine-C* C* C) (if (set-empty? C*) {set C} (for/fold: ([acc : (Setof .V) ∅]) ([Ci C*]) (∪ acc (refine-C Ci C))))) (: refine-C : .V .V → (U .V (Setof .V))) (define (refine-C C D) (cond [(equal? 'Proved (C⇒C C D)) C] [(equal? 'Proved (C⇒C D C)) D] [else (match* (C D) [((.// Uc _) (.// Ud _)) (match* (Uc Ud) ; unroll recursive ones [(_ (.μ/C x D′)) (refine-C C (C/ D′ x D))] [((.μ/C x C′) _) (refine-C (C/ C′ x C) D)] ; break conjunctive ones [(_ (.St 'and/c (list D1 D2))) (∪ (refine-C C D1) (refine-C C D2))] [((.St 'and/c (list C1 C2)) _) (∪ (refine-C C1 D) (refine-C C2 D))] ; prune impossible disjunct [(_ (.St 'or/c _)) (let ([D′ (truncate D C)]) (if (equal? D D′) {set C D} (refine-C C D′)))] [((.St 'or/c _) _) (let ([C′ (truncate C D)]) (if (equal? C C′) {set C D} (refine-C C′ D)))] ; special rules for reals [((.λ↓ (.λ 1 (.@ (.≥) (list e1 e2) l) #f) ρc) (.St '¬/c (list (.// (.λ↓ (.λ 1 (.@ (or (.=) (.equal?)) (or (list e1 e2) (list e2 e1)) _) #f) ρd) _)))) (if (equal? ρc ρd) (→V (.λ↓ (.λ 1 (.@ (.>) (list e1 e2) l) #f) ρc)) {set C D})] [((.St '¬/c (list (.// (.λ↓ (.λ 1 (.@ (or (.=) (.equal?)) (or (list e1 e2) (list e2 e1)) _) #f) ρc) _))) (.λ↓ (.λ 1 (.@ (.≥) (list e1 e2) l) #f) ρd)) (if (equal? ρc ρd) (→V (.λ↓ (.λ 1 (.@ (.>) (list e1 e2) l) #f) ρd)) {set C D})] [((.λ↓ (.λ 1 (.@ (.≤) (list e1 e2) l) #f) ρc) (.St '¬/c (list (.// (.λ↓ (.λ 1 (.@ (or (.=) (.equal?)) (or (list e1 e2) (list e2 e1)) _) #f) ρd) _)))) (if (equal? ρc ρd) (→V (.λ↓ (.λ 1 (.@ (.<) (list e1 e2) l) #f) ρc)) {set C D})] [((.St '¬/c (list (.// (.λ↓ (.λ 1 (.@ (or (.=) (.equal?)) (or (list e1 e2) (list e2 e1)) _) #f) ρc) _))) (.λ↓ (.λ 1 (.@ (.≤) (list e1 e2) l) #f) ρd)) (if (equal? ρc ρd) (→V (.λ↓ (.λ 1 (.@ (.<) (list e1 e2) l) #f) ρd)) {set C D})] [(_ _) {set C D}])] [(_ _) {set C D}])])) ;; throws away all branch in C excluded by D (: truncate : .V .V → .V) (define (truncate C D) (match C [(.// (.St 'or/c (list C1 C2)) C*) (match* ((C⇒C D C1) (C⇒C D C2)) [('Refuted 'Refuted) (error "WTF??")] [(_ 'Refuted) (truncate C1 D)] [('Refuted _) (truncate C2 D)] [(_ _) (.// (.St 'or/c (list (truncate C1 D) (truncate C2 D))) C*)])] [_ C])) (: U+ : .U .U → .U) (define U+ (match-lambda** [((.•) U) U] [(U _) U])) (: ∪ : (U (Setof .V) .V) * → (Setof .V)) (define (∪ . V*) (match V* ['() ∅] [(list (? .V? V)) {set V}] [(list (? set? V)) V] [_ (for/fold: ([acc : (Setof .V) ∅]) ([V V*]) (if (set? V) (set-union acc V) (set-add acc V)))])) (: U^ : .U → (Setof .V)) (define U^ (match-lambda [(.b b) (b^ b)] [(.•) ∅] [(or (? .Ar?) (? .λ↓?)) {set PROC/C}] [(.St t V*) {set (→V (.st-p t (length V*)))}] [_ ∅])) (: b^ : (U Num Str Sym Bool) → (Setof .V)) (define b^ (match-lambda [(? int? n) (set-union {set (Prim 'int?) (Prim 'real?) (Prim 'num?)} (sign/C n))] [(? real? r) (set-union {set (Prim 'real?) (Prim 'num?)} (sign/C r))] [(? num? x) {set (Prim 'num?)}] [(? str?) {set (Prim 'str?)}] [(? sym?) {set (Prim 'symbol?)}] [#t {set (Prim 'true?) (Prim 'bool?)}] [#f {set (Prim 'false?) (Prim 'bool?)}])) (: v-class : .σ (U .V (Setof .V)) → (Setof Any)) (define (v-class σ x) (match x [(.L i) (v-class σ (σ@ σ i))] [(.// U C*) (match U [(.•) (or (for/or: : (Option (Setof Any)) ([C : .V C*] #:when (match? C (.// (.pred) _))) (match-let ([(.// (and o (.pred)) _) C]) {set (name o)})) {set '•})] [(? .o? o) {set `(prim ,(name o))}] [(.b u) {set (cond [(int? u) 'int?] [(real? u) 'real?] [(num? u) 'num?] [(str? u) 'str?] [(false? #f) 'false?] [(eq? u #t) 'true?] [(sym? u) 'sym?] [else 'misc])}] [(.Ar _ V _) (v-class σ V)] [(.St t _) {set t}] [(.λ↓ (.λ n _ v?) _) {set `(proc? ,n ,v?)}] [_ {set 'misc}])] [(.μ/V _ V*) (v-class σ V*)] [(.X/V _) ∅] [(? set? s) (for/fold: ([acc : (Setof Any) ∅]) ([i s]) (set-union acc (v-class σ i)))])) ;; biased approximation (: ⊕ : (case→ [.σ .V .σ .V → (Pairof .σ .V)] [.σ (Listof .V) .σ (Listof .V) → (Pairof .σ (Listof .V))] [.σ .σ .F → .σ] [.V .V → .V] [(Listof .V) (Listof .V) → (Listof .V)] [.ρ .ρ → .ρ])) (define ⊕ #;(printf "⊕:~n~n~a~n~nand~n~n~a~n~n~n" V0 V1) (case-lambda [(σ0 V0 σ1 V1) (match* (V0 V1) [((? .V? V0) (? .V? V1)) (match-let ([Vi (⊕ (V-abs σ0 V0) (V-abs σ1 V1))]) (match V1 [(.L i) (match-let ([(cons σ1′ Vi′) (alloc σ1 Vi)]) (match Vi′ [(.L j) (cons (σ-set σ1′ i (σ@ σ1′ j)) V1)] [(and Vi′ (or (? .//?) (? .μ/V?))) (cons (σ-set σ1′ i Vi′) V1)] [_ (error "⊕: impossible: .X/V")]))] [_ (alloc σ1 Vi)])) #;(let ([Vi (⊕ (V-abs σ0 V0) (V-abs σ1 V1))]) (cond [(or (.//? Vi) (.μ/V? Vi)) (match V1 [(.L i) (cons (σ-set σ1 i Vi) V1)] [_ (cons σ1 Vi)])] [else (error "⊕: impossible")]))] [((? list? V0) (? list? V1)) (match-let ([(cons σ1′ l-rev) (for/fold: ([acc : (Pairof .σ (Listof .V)) (cons σ1 '())]) ([V0i V0] [V1i V1]) (match-let* ([(cons σ1 l) acc] [(cons σ1′ Vi) (⊕ σ0 V0i σ1 V1i)]) (cons σ1′ (cons Vi l))))]) (cons σ1′ (reverse l-rev)))])] [(σ0 σ1 F) (for/fold: : .σ ([σ1 : .σ σ1]) ([i (in-hash-keys F)]) (let* ([j (hash-ref F i)]) (match (⊕ (V-abs σ0 (σ@ σ0 i)) (V-abs σ1 (σ@ σ1 i))) [(and V (or (? .//?) (? .μ/V?))) (σ-set σ1 j V)] [_ (error "⊕: impossible")])))] [(x y) (match* (x y) ; same-length lists expected [((? list? V0) (? list? V1)) (map ⊕ V0 V1)] ; values [((? .V? V0) (? .V? V1)) #;(printf "⊕:~n~a~nand~n~a~n~n" (show-Ans σ∅ V0) (show-Ans σ∅ V1)) #;(printf "⊕:~n~a~nand~n~a~n~n" V0 V1) (let: ([ans : .V (cond [(V∈ V1 V0) V1] ; postpone approximation if value shrinks #;[(and (.//? V1) (.•? (.//-pre V1)) (= 1 (set-count (.//-refine V1)))) V1] #;[(equal? V0 ♦) ♦] [(⊑ V1 V0) V0] [(⊑ V0 V1) V1] [else (match* (V0 V1) [((.// U0 C*) (.// U1 D*)) (match* (U0 U1) ; keep around common values: 0, 1, #t, #f, struct with no component [(_ (or (.•) (? .o?) (.b 0) (.b 1) (.b #t) (.b #f) (.St _ '()))) V1] ; cannot blur higher order value [(_ (.λ↓ f ρ)) (let ([repeated (repeated-lambdas f ρ)]) (match (set-count repeated) [0 V1] ; TODO: μ introduced outside here. Am i sure there's none inside? [_ (let ([V′ (μV 'X (set-add repeated (for/fold: ([V1 : .V V1]) ([Vi repeated]) (V/ V1 Vi (.X/V 'X)))))]) #;(printf "~a~n⇒⊕~n~a~n~n" V1 V′) V′)]))] [((.Ar C V0 l) (.Ar C V1 l)) (.// (.Ar C (⊕ V0 V1) l) D*)] [(_ (or (? .λ?) (? .Ar?))) V1] [((.St t V0*) (.St t V1*)) (.// (.St t (⊕ V0* V1*)) D*)] [(_ (.St t V1*)) #;(printf "⊕:case1~n") #;(printf "⊕:~n~a~nand~n~a~n~n" (show-E σ∅ V0) (show-E σ∅ V1)) (match-let* ([x 'X #;(fresh V1*)] [Vi* (V/ V1* V0 (.X/V x))] [(cons Vi* Vs) (elim-μ x Vi*)]) (if (equal? Vi* V1*) (.// • (set-intersect C* D*)) #;(μV x (compact {set V0 (.// (.St t Vi*) D*)} Vs)) (.// (.St t (V/ Vi* (.X/V x) (μV x (compact {set V0 (.// (.St t Vi*) ∅)} Vs)))) D*)))] [((.b (? num? b0)) (.b (? num? b1))) (cond ; if it moves towards 0, let it take its time #;[(and (int? b0) (int? b1) (or (<= 0 b1 b0) (>= 0 b1 b0))) V1] [else (.// • (set-add (cond [(and (real? b0) (real? b1)) {set (cond [(and (> b0 0) (> b1 0)) POS/C] [(and (< b0 0) (< b1 0)) NEG/C] [(and (not (= b0 0)) (not (= b1 0))) NON-ZERO/C] [(and (>= b0 0) (>= b1 0)) NON-NEG/C] [(and (<= b0 0) (<= b1 0)) NON-POS/C] [else REAL/C])}] [else ∅]) (cond [(and (int? b0) (int? b1)) INT/C] [(and (real? b0) (real? b1)) REAL/C] [else NUM/C])))])] [(_ _) (let ([C* (set-union C* (U^ U0))]) (.// • (for/set: .V ([D (set-union D* (U^ U1))] #:when (eq? 'Proved (C*⇒C C* D))) D)))])] [((.μ/V x V0*) (.μ/V y V1*)) #;(printf "⊕:case2~n") (μV x (compact V0* (V/ V1* (.X/V y) (.X/V x))))] [((.μ/V x V0*) _) #;(printf "⊕:case3~n") #;(printf "~a ∩ ~a~n~n" (v-class σ∅ V0*) (v-class σ∅ V1)) (if (set-empty? (set-intersect (v-class σ∅ V0*) (v-class σ∅ V1))) V1 (match-let ([(cons V1′ Vs) (dbg/off 'case3 (elim-μ x (V/ V1 V0 (.X/V x))))]) (μV x (dbg/off 'compact1 (compact (dbg/off 'compact0 (compact V0* {set V1′})) Vs)))))] [(_ (.μ/V x V1*)) #;(printf "⊕:case4~n") #;(printf "~a ∩ ~a~n~n" (v-class σ∅ V0) (v-class σ∅ V1*)) (if (set-empty? (set-intersect (v-class σ∅ V0) (v-class σ∅ V1*))) V1 (match-let ([(cons V0′ Vs) (elim-μ x (V/ V0 V1 (.X/V x)))]) (μV x (compact (compact {set V0′} Vs) V1*))))] [((? .X/V? x) _) x] [(_ (? .X/V? x)) x])])]) #;(printf "⊕:~n~a~nand~n~a~nis~n~a~n~n" (show-Ans σ∅ V0) (show-Ans σ∅ V1) (show-Ans σ∅ ans)) (check ans) ans)] [((and ρ0 (.ρ m0 l0)) (and ρ1 (.ρ m1 l1))) (let* ([l (max l0 l1)] [m (for/fold: ([m : (Map (U Int Sym) .V) (hash)]) ([sd (in-range 0 l)]) (match* ((hash-ref m0 (- l0 sd 1) (λ () #f)) (hash-ref m1 (- l1 sd 1) (λ () #f))) [(#f #f) m] [(#f (? .V? V)) (hash-set m (- l sd 1) V)] [((? .V? V) #f) (hash-set m (- l sd 1) V)] [((? .V? V0) (? .V? V1)) (hash-set m (- l sd 1) (⊕ V0 V1))]))] [m (for/fold: ([m : (Map (U Int Sym) .V) m]) ([k (in-hash-keys m0)] #:when (sym? k)) (hash-set m k (hash-ref m0 k)))] [m (for/fold: ([m : (Map (U Int Sym) .V) m]) ([k (in-hash-keys m1)] #:when (sym? k)) (hash-set m k (hash-ref m1 k)))]) (.ρ m l))])])) (: check : (case→ [.V → Void] [.V Int → Void])) (define (check V [i 1]) (match V [(.μ/V _ V*) (if (<= i 0) (error "no!") (for ([Vi V*]) (check Vi (- i 1))))] [(.// (.St _ V*) _) (for ([Vi V*]) (check Vi))] [_ (void)])) ;; remove all sub-μ. TODO: generalize allowed μ-depth (: elim-μ : (case→ [Sym .V → (Pairof .V (Setof .V))] [Sym (Listof .V) → (Pairof (Listof .V) (Setof .V))])) (define (elim-μ x V) (define-set: body* : .V [_ add!]) (: go : (case→ [.V → .V] [(Listof .V) → (Listof .V)])) (define go (match-lambda [(? list? V*) (map go V*)] [(? .L? V) V] [(and V (.// U1 C*)) (match U1 [(.St t V*) (.// (.St t (map go V*)) C*)] [(.Ar C V l) (.// (.Ar C (go V) l) C*)] [(.λ↓ f (and ρ (.ρ m l))) #;(printf "elim-μ: ρ:~n~a~n~n" m) (let ([m′ (for/fold: ([m′ : (Map (U Int Sym) .V) m∅]) ([x (in-hash-keys m)]) (hash-set m′ x (go (hash-ref m x))))]) (if (equal? m′ m) V (.// (.λ↓ f (.ρ m′ l)) C*)))] [_ V])] [(.μ/V z V*) (add! (for/set: .V ([Vi V*]) (V/ Vi (.X/V z) (.X/V x)))) (.X/V x)] [(.X/V _) (.X/V x)])) (let ([V′ (go V)]) #;(printf "elim-μ depth ~a → ~a~n~n" (μ-depth V) (μ-depth V′)) (cons V′ body*))) ; remove redundant variable ; simplify to • if body has • (: μV : Sym (Setof .V) → .V) (define (μV x V*) #;(for ([Vi V*]) (check Vi 0)) (let ([V* (for/set: .V ([V V*] #:unless (equal? V (.X/V x))) V)]) (cond [(set-member? V* ♦) ♦] [else (match (set-count V*) [0 V∅] [1 (let* ([V (set-first V*)] [V′ (V/ V (.X/V x) (.X/V '☠))]) (if (equal? V V′) V V∅))] [_ (.μ/V x V*)])]))) ; group values together by top constructors (: compact : (Setof .V) (Setof .V) → (Setof .V)) (define (compact V0s V1s) #;(printf "compact:~n~n~a~nand~n~a~n~n~n" V0s V1s) #;(printf "depth: ~a, ~a~n~n" (for/list: : (Listof Int) ([V V0s]) (μ-depth V)) (for/list: : (Listof Int) ([V V1s]) (μ-depth V))) (: collect : (Setof .V) → (Values (Map Any .V) (Setof .X/V))) (define (collect Vs) #;(printf "collect:~n~a~n~n" Vs) (for/fold: ([m : (Map Any .V) (hash)] [xs : (Setof .X/V) ∅]) ([V Vs]) (match V [(.// U C*) (match U [(.b (? num?)) (values (hash-set m 'num? V) xs)] [(.b (? str?)) (values (hash-set m 'str? V) xs)] [(.b (? sym?)) (values (hash-set m 'sym? V) xs)] [(.b #t) (values (hash-set m #t V) xs)] [(.b #f) (values (hash-set m #f V) xs)] [(? .o? o) (values (hash-set m `(o ,(name o)) V) xs)] [(.•) (values (hash-set m (for/fold: : Any ([ac '•]) ([C C*]) (match C [(.// (? .pred? p) _) (match p [(.st-p t _) t] [_ (name p)])] [_ ac])) V) xs)] [(or (? .Ar?) (? .λ↓?) (.o)) (values (hash-set m 'proc? V) xs)] ; TODO: by arity also? [(.St t _) (values (hash-set m `(struct ,t) V) xs)])] [(? .μ/V? V) (error (format "weird:~n~a~n~a~n~n" V0s V1s)) (values (hash-set m 'μ V) xs)] [(? .X/V? x) (values m (set-add xs x))]))) (: merge : (.V .V → (Pairof .V (Setof .V)))) (define (merge V0 V1) (match* (V0 V1) [((? .X/V? x) V1) (cons x (match V1 [(.X/V _) ∅] [_ {set V1}]))] [((.// (.St t V0*) C*) (.// (.St t V1*) D*)) (let-values ([(q V*) (for/fold: ([q : (Setof .V) ∅] [V* : (Listof .V) '()]) ([Vi V0*] [Vj V1*]) (match-let ([(cons V′ q′) (merge Vi Vj)]) (values (set-union q q′) (cons V′ V*))))]) (cons (.// (.St t (reverse V*)) (set-intersect C* D*)) q))] [(_ _) (match (⊕ V0 V1) ; FIXME hack [(and V (.μ/V x V*)) (elim-μ x V)] [V (cons V ∅)])])) (: go : (Setof .V) (Setof .V) → (Setof .V)) (define (go V0s V1s) #;(printf "go:~n~a~n~nand~n~n~a~n~n~n" V0s V1s) (let-values ([(m0 xs) (collect V0s)] [(m1 zs) (collect V1s)]) (let: ([q : (Setof .V) ∅]) (let ([s0 (for/set: .V ([k (in-hash-keys m0)]) (let ([V0 (hash-ref m0 k)]) (match (hash-ref m1 k (λ () #f)) [#f V0] [(? .V? V1) (match-let ([(cons V′ q′) (dbg/off 'go (merge V0 V1))]) (set! q (set-union q q′)) V′)])))] [s1 (for/set: .V ([k (in-hash-keys m1)] #:unless (hash-has-key? m0 k)) (hash-ref m1 k))]) (let* ([s (set-union s0 s1)]) (if (subset? q s) s (begin #;(printf "q: ~a~n~ns:~a~n~n" (for/set: Any ([x q]) (show-V σ∅ x)) (for/set: Any ([x s]) (show-V σ∅ x))) (go s q)))))))) (go V0s V1s)) (: μ-depth : (case→ [.V → Int] [(Listof .V) → (Listof Int)])) (define μ-depth (match-lambda [(? list? V*) (map μ-depth V*)] [(.// (.St _ V*) _) (apply max (map μ-depth V*))] [(.μ/V _ V*) (+ 1 (for/fold: : Int ([l 0]) ([V V*]) (max l (μ-depth V))))] [(? .V?) 0])) (: alloc : (case→ [.σ .V → .Vns] [.σ (Listof .V) → (Pairof .σ (Listof .V))])) (define (alloc σ V) (match V [(.L _) (cons σ V)] [(.// (.St t V*) Cs) (match-let ([(cons σ V*′) (alloc σ V*)]) (cons σ (.// (.St t V*′) Cs)))] [(.// (.Ar C V l^3) Cs) (match-let ([(cons σ V′) (alloc σ V)]) (cons σ (.// (.Ar C V′ l^3) Cs)))] [(.// (.λ↓ f (.ρ m l)) Cs) (let-values ([(σ m) (for/fold: ([σ : .σ σ] [m′ : (Map (U Int Sym) .V) m]) ([x (in-hash-keys m)]) (match-let ([(cons σ V) (alloc σ (hash-ref m x))]) (values σ (hash-set m′ x V))))]) (cons σ (→V (.λ↓ f (.ρ m l)))))] [(.// (.•) Cs) (match-let ([(cons σ L) (σ+ σ)]) (refine σ L Cs))] [(? .μ/V? V) (match-let ([(cons σ L) (σ+ σ)]) (cons (σ-set σ L V) L))] [(? .V? V) (cons σ V)] [(? list? V*) (let-values ([(σ Vs) (for/fold: ([σ : .σ σ] [Vs : (Listof .V) '()]) ([V V*]) (match-let ([(cons σ V) (alloc σ V)]) (values σ (cons V Vs))))]) (cons σ (reverse Vs)))])) (: refine-V : .V .V → .V) (define (refine-V V C) (match-let* ([(cons σ V) (alloc σ∅ V)] [(cons σ V) (refine1 σ V C)]) (V-abs σ V))) (: reify : .V → .V) (define (reify C) (match C [(.L _) (.// • {set C})] [(.// Uc _) (match Uc [(.St 'and/c (list C1 C2)) (refine-V (reify C1) C2)] [(.St 'or/c (list C1 C2)) (match* ((reify C1) (reify C2)) [((.μ/V x V1*) (.μ/V z V2*)) (μV x {set-union V1* (V/ V2* (.X/V z) (.X/V x))})] [((and V1 (.μ/V x V1*)) V2) (μV x (set-add V1* (V/ V2 V1 (.X/V x))))] [(V1 (and V2 (.μ/V x V2*))) (μV x (set-add V2* (V/ V1 V2 (.X/V x))))] [(V1 V2) (if (equal? V1 V2) V1 (μV '_ {set V1 V2}))])] [(.St/C t D*) (→V (.St t (map reify D*)))] [(.μ/C x D) (match (reify D) [(.μ/V '_ V*) (μV x V*)] [(? .V? V) V])] [(and Uc (.Λ/C C* D v?)) (→V (.Ar (→V Uc) ♦ `(Λ Λ Λ) #|FIXME|#))] [(.X/C x) (.X/V x)] [(.st-p t n) (→V (.St t (make-list n ♦)))] [(.λ↓ (.λ 1 (.b #t) #f) _) ♦] [_ (.// • {set (simplify C)})])]))
true
6766485b2ef8a78f694b962a38fb79b3a057899c
8c638eaa88aff5fc2d4c6c87f20f25081a77570b
/main.rkt
a055dc6289ea04d10571cd50d1eb048e3aedae2f
[]
no_license
rmculpepper/scripting
9cc1f7ec82826886019faddc70cc98db4b4707ff
fb27f8779d53982158ab90baf5433f7a33aa1522
refs/heads/master
2021-03-12T23:07:05.902285
2016-10-28T04:08:54
2016-10-28T04:08:54
1,656,344
0
0
null
null
null
null
UTF-8
Racket
false
false
250
rkt
main.rkt
#lang racket/base (require "file.rkt" "format.rkt" "loud.rkt" "process.rkt") (provide (all-from-out "file.rkt") (all-from-out "format.rkt") (all-from-out "loud.rkt") (all-from-out "process.rkt"))
false
6f578a28c920a270df2e38ee688296ef1298b500
d0ec582c3a6233b8063a542332b7d7b99517ffac
/lib/structs.rkt
f422ff5bcb144689298e9b0e89bec53c891bc0a4
[]
no_license
lordxist/positive-fragment
2b6a0beb19bbfda7a8313e650f9b1e55344fb586
794d924b144197047101c614b3eef379babd96b9
refs/heads/master
2021-05-02T00:32:05.070725
2018-03-26T09:08:40
2018-03-26T09:08:40
120,945,470
0
0
null
null
null
null
UTF-8
Racket
false
false
183
rkt
structs.rkt
#lang racket (provide (all-defined-out)) (struct profile (cont-in-cmd)) (struct limitation (domain prefix error-descr)) (struct shifts (opposite-lambda opposite-var opposite-cmd))
false
cc6ee6c47c84bb16675c811e93a8b2dcf6969f94
e41e4183661cc6fe606292ac7b2a7612c750b854
/net-ip-test/tests/net/run-all-tests.rkt
5c66fe4f85c8ba80b3b1a5f341b2908dba4b7220
[ "BSD-3-Clause" ]
permissive
Bogdanp/racket-net-ip
0cacb5f5758bd7475e6faf5f9e454bf36428a969
be7075c78baf122dc05beaf71faf941159aaad64
refs/heads/master
2023-07-23T11:22:04.453176
2023-07-09T13:43:23
2023-07-09T13:43:23
157,446,124
5
1
null
2020-10-07T08:31:45
2018-11-13T21:00:51
Racket
UTF-8
Racket
false
false
283
rkt
run-all-tests.rkt
#lang racket/base (require rackunit "ip/address.rkt" "ip/common.rkt" "ip/network.rkt") (define all-ip-tests (test-suite "net/ip" common-tests ip-tests network-tests)) (module+ main (require rackunit/text-ui) (run-tests all-ip-tests))
false
a1fe4761149926ccd1f36824b81065b13b970245
2704348d068c658ee71e1ff6be37a65d26c20354
/private/draw.rkt
ea14b3c222cbb4e9189e948a731e13f8327169ca
[ "MIT" ]
permissive
hkrish/chroma
e05eb65d6be514c48c3cabf683029d03aaf22318
cb0bcdb11e904a4c9f3e3b665f4e3f194f9f4138
refs/heads/master
2023-03-17T10:40:10.013387
2021-02-28T02:57:22
2021-02-28T02:57:22
288,245,664
0
0
null
null
null
null
UTF-8
Racket
false
false
5,960
rkt
draw.rkt
#lang racket/base (require pict racket/class racket/contract racket/draw racket/list "./base-types.rkt" "./palette.rkt") (provide (all-defined-out)) (define (->color% c) (unless (color? c) (raise-argument-error '->color% "color?" c)) (let ([c ((cdr (current-display-color-space)) c)]) (unless (rgb-space? c) (raise-argument-error '->color% "(cadr (current-display-color-space-info)) should produce a rgb color" c)) (make-color (rgb-space-r c) (rgb-space-g c) (rgb-space-b c)))) (define/contract (draw-swatch c #:size [wh 25] #:corner-radius [cr #f] #:border-color [bc #f] #:border-width [bw #f]) (->* (color?) (#:size (or/c real? (cons/c real? real?)) #:corner-radius (or/c #f real?) #:border-color (or/c #f color?) #:border-width (or/c #f real?)) pict?) (let ([wh (if (pair? wh) wh (cons wh wh))] [db? (or bc bw)] [bc (and bc (->color% bc))] [ins (if bw (/ bw 2.0) 0.0)]) (inset (if cr (filled-rounded-rectangle (car wh) (cdr wh) cr #:color (->color% c) #:draw-border? db? #:border-color bc #:border-width bw) (filled-rectangle (car wh) (cdr wh) #:color (->color% c) #:draw-border? db? #:border-color bc #:border-width bw)) ins))) (define/contract (draw-swatch-list cls #:max-width [tw #f] #:swatches-per-row [spr #f] #:swatch-size [wh 25] #:spacing [spc #f] #:background [bg #f] #:corner-radius [cr #f] #:border-color [bc #f] #:border-width [bw #f]) (->* ((listof color?)) (#:max-width (or/c #f (and/c (>/c 0) real?)) #:swatches-per-row (or/c #f (integer-in 1 #f)) #:swatch-size (or/c real? (cons/c real? real?)) #:spacing (or/c real? (cons/c (or/c #f real?) (or/c #f real?))) #:background (or/c #f color?) #:corner-radius (or/c #f real?) #:border-color (or/c #f color?) #:border-width (or/c #f real?)) pict?) (let*-values ([(w h) (if (pair? wh) (values (car wh) (cdr wh)) (values wh wh))] [(ncls) (length cls)] [(bw_) (if bw (/ bw -2.0) 0)] [(spcx spcy) (cond [(pair? spc) (values (car spc) (cdr spc))] [spc (values spc spc)] [else (values bw_ bw_)])] [(sw/row/spr) (if spr spr ncls)] [(sw/row) (if tw (floor (/ (- tw spcx) (+ spcx w))) sw/row/spr)] [(nrows) (ceiling (/ ncls sw/row))] [(sws) (map (lambda (c) (draw-swatch c #:size wh #:corner-radius cr #:border-color bc #:border-width bw)) cls)]) (apply vl-append spcy (let loop ([sws sws]) (cond [(null? sws) sws] [else (let-values ([(row left) (if (> (length sws) sw/row) (split-at sws sw/row) (values sws '()))]) (cons (apply ht-append spcx row) (loop left)))]))))) (define/contract (draw-palette/continuous plt width height) (-> (procedure-arity-includes/c 1) (integer-in 1 #f) (integer-in 1 #f) pict?) (let ([cls (map ->color% (palette-quantize plt width))]) (dc (lambda (dc dx dy) (define old-brush (send dc get-brush)) (define old-pen (send dc get-pen)) (send dc set-brush "black" 'transparent) (for ([x (in-range width)] [c (in-list cls)]) (let ([path (new dc-path%)]) (send dc set-pen c 1 'solid) (send path move-to 0.5 0) (send path line-to 0.5 height) (send dc draw-path path (+ dx x) dy))) (send dc set-brush old-brush) (send dc set-pen old-pen)) width height))) (define/contract (draw-palette plt width height) (-> (or/c (procedure-arity-includes/c 1) (non-empty-listof color?)) (integer-in 1 #f) (integer-in 1 #f) pict?) (cond [(procedure? plt) (draw-palette/continuous plt width height)] [else (let ([w (/ width (length plt))]) (draw-swatch-list plt #:swatch-size (cons w height)))])) (define/contract (draw-palette-table plt ncols #:swatch-size [wh 25]) (->* ((procedure-arity-includes/c 1) (integer-in 2 #f)) (#:swatch-size real?) pict?) (let* ([ncls (* ncols ncols)] [cls (list->vector (palette-quantize plt ncls))]) (apply ht-append (let loop-h ([cols ncols] [colidx 0] [colinc 1]) (cond [(= 0 cols) '()] [else (cons (apply vl-append (let loop-v ([rows ncols] [rowidx colidx] [rowinc 2]) (cond [(= rows 0) '()] [else (let ([c (vector-ref cls rowidx)]) (cons (draw-swatch c #:size wh) (loop-v (sub1 rows) (+ rowidx rowinc) (add1 rowinc))))]))) (loop-h (sub1 cols) (+ colidx colinc) (add1 colinc)))])))))
false
75cb76b0d3deff8b0b00de169d7e104923126e6b
1b3782a6d5242fdade7345d3e9157a8af0c4a417
/progs/visitors.rkt
1a58764a269125d9bc2e7e5968d835116ce754d7
[]
no_license
zcc101/dpc
bb75d383f8ff6129d01d1cf33c89f7559143d24f
54455932b8494f64f5c9a53d481968b22a15748f
refs/heads/master
2023-03-15T10:53:55.608180
2017-11-29T21:57:42
2017-11-29T21:57:42
null
0
0
null
null
null
null
UTF-8
Racket
false
false
2,650
rkt
visitors.rkt
#lang class/3 ;; An [IRangeVisitor X] implements: ;; co : Number Number -> X ;; oc : Number Number -> X ;; union : X X -> X ;; A Range is one of ;; - (new range% Number Number) ;; Interp: represents the range between `lo' and `hi' ;; including `lo', but *not* including `hi' ;; - (new hi-range% Number Number) ;; Interp: represents the range between `lo' and `hi' ;; including `hi', but *not* including `lo' ;; - (new union-range% Range Range) ;; Interp: including all the numbers in both ranges ;; and implements IRange: ;; The IRange interface includes: ;; - in-range? : Number -> Boolean ;; determine if the given number is in this range ;; - visit : [IRangeVisitor X] -> X (define-class range% (fields lo hi) (check-expect ((range% 0 1) . in-range? 0) true) (check-expect ((range% 0 1) . in-range? 0.5) true) (check-expect ((range% 0 1) . in-range? 1) false) (check-expect ((range% 0 1) . in-range? 2) false) (check-expect ((range% 0 1) . in-range? -2) false) (define/public (in-range? n) (and (>= n (field lo)) (< n (field hi)))) (define/public (union r) (union-range% this r)) (define/public (visit v) (v . co (field lo) (field hi)))) (define-class hi-range% (fields lo hi) (check-expect ((hi-range% 0 1) . in-range? 0) false) (check-expect ((hi-range% 0 1) . in-range? 0.5) true) (check-expect ((hi-range% 0 1) . in-range? 1) true) (check-expect ((hi-range% 0 1) . in-range? 2) false) (check-expect ((hi-range% 0 1) . in-range? -2) false) (define/public (in-range? n) (and (> n (field lo)) (<= n (field hi)))) (define/public (union r) (union-range% this r)) (define/public (visit v) (v . oc (field lo) (field hi)))) (define-class union-range% (fields left right) (define/public (in-range? n) (or ((field left) . in-range? n) ((field right) . in-range? n))) (define/public (union r) (union-range% this r)) (define/public (visit v) (v . union ((field left) . visit v) ((field right) . visit v)))) (define r1 (range% 0 1)) (define r2 (hi-range% 0 1)) (define r3 (range% 2 4)) (check-expect (r1 . union r2 . union r3 . in-range? 3) true) (check-expect (r1 . union r2 . in-range? 1) true) (check-expect (r1 . union r2 . in-range? 0) true) ;; UBV is (ub-visitor%) and implements [IRangeVisitor Number] ;; Purpose : find the smallest number >= every element in the range (define-class ub-visitor% (define/public (oc lo hi) hi) (define/public (co lo hi) hi) (define/public (union l r) (max l r))) (define big-r (r1 . union r2 . union r3)) (check-expect (big-r . visit (ub-visitor%)) 4)
false
efa3d0cd87a053029062086cd209b3f10b12a29a
95bfc30172b907840a072b8ca62ec69200c9e982
/chapter-1/exercise-1.30.rkt
188c7414f1a70951db43ffbcc41c3561bac17b82
[]
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
494
rkt
exercise-1.30.rkt
#!/usr/bin/env racket #lang scheme ;(define (sum term a next b) ; (if (> a b) ; 0 ; (+ (term a) (sum term (next a) next b)))) (define (sum term a next b) (define (iter a result) (if (> a b) result (iter (next a) (+ result (term a))))) (iter a 0)) (define (integral f a b dx) (define (add-dx x) (+ x dx)) (* (sum f (+ a (/ dx 2.0)) add-dx b) dx)) (define (cube x) (* x x x)) (println (integral cube 0 1 0.01)) (println (integral cube 0 1 0.001))
false
5054331c1ed592d0d347ede93dd484f00698900d
c3a325ec6bcacd8665041ea454d2fdf081148446
/CS 330/Prolog/prolog.rkt
25b4950376c54247dcbbe0768cd2b8cb97225175
[]
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
684
rkt
prolog.rkt
#lang plai (define-syntax-rule (prolog-expression? failure-continuation) (let ((success-continuation "true")) (λ () success-continuation))) (define (time-it f) (define start(current-inexact-milliseconds)) (displayln f) (define end(current-inexact-milliseconds)) (- end start)) (time-it (λ() (expt 2 5000))) (define-syntax-rule (jor lhs rhs) (let ([lhs-v lhs]) (if lhs-v lhs-v rhs))) (jor #t (/ 1 0)) (jor (time-it (+ 1 1)) 7) #;(define-syntax for (syntax-case() [(for from start to end do body ...) (syntax (let lop ([it start]) (unless (= it end) body... (loop (add1 it)))))]))
true
a86518942a24cf48316d5375473c4f78631f0d7d
444087cffe7d9b4d89f6a4f8a7eeee2f26fcf64a
/PartB/section5/hw4/hw4.rkt
f78961b1248bf54f565f87e6114deb0011ac9cdc
[ "Apache-2.0" ]
permissive
changchiajung/ProgrammingLanguages
f5ebe465a22bcb2494ca887139c83a391ad1dc02
98b6de8846a3b6764ce416a20aee7b005cbb1f8f
refs/heads/master
2023-03-16T15:42:16.673647
2020-03-29T17:04:07
2020-03-29T17:21:48
null
0
0
null
null
null
null
UTF-8
Racket
false
false
6,640
rkt
hw4.rkt
#lang racket (provide (all-defined-out)) ;; so we can put tests in a second file ;; put your code below ;; 1. function sequence that takes 3 arguments low, high, and stride, all assumed to be numbers. ;; Further assume stride is positive. sequence produces a list of numbers from low to high (including ;; low and possibly high) separated by stride and in sorted order. (define (sequence low high stride) (if (> low high) null (cons low (sequence (+ low stride) high stride)))) ;; 2. function string-append-map that takes a list of strings xs and a string suffix and returns a ;; list of strings. Each element of the output should be the corresponding element of the input appended ;; with suffix (with no extra space between the element and suffix). (define (string-append-map xs suffix) (map (lambda (x) (string-append x suffix)) xs)) ;; 3. function list-nth-mod that takes a list xs and a number n. If the number is negative, ;; terminate the computation with (error "list-nth-mod: negative number"). Else if the list is ;; empty, terminate the computation with (error "list-nth-mod: empty list"). Else return the ith ;; element of the list where we count from zero and i is the remainder produced when dividing n by the ;; list’s length. (define (list-nth-mod xs n) (if (negative? n) (error "list-nth-mod: negative number") (if (empty? xs) (error "list-nth-mod: empty list") (remainder n (length xs))))) ;; 4. function stream-for-n-steps that takes a stream s and a number n. It returns a list holding ;; the first n values produced by s in order. Assume n is non-negative. (define (stream-for-n-steps s n) (if (= n 0) null (cons (car (s)) (stream-for-n-steps (cdr (s)) (- n 1))))) ;; 5. stream funny-number-stream that is like the stream of natural numbers (i.e., 1, 2, 3, ...) ;; except numbers divisble by 5 are negated (i.e., 1, 2, 3, 4, -5, 6, 7, 8, 9, -10, 11, ...). Remember a stream ;; is a thunk that when called produces a pair. Here the car of the pair will be a number and the cdr will ;; be another stream. (define funny-number-stream (letrec ([f (lambda (x) (cons (if (= (remainder x 5) 0) (- x) x) (lambda () (f (+ x 1)))))]) (lambda () (f 1)))) ;; 6. stream dan-then-dog, where the elements of the stream alternate between the strings "dan.jpg" ;; and "dog.jpg" (starting with "dan.jpg"). More specifically, dan-then-dog should be a thunk that ;; when called produces a pair of "dan.jpg" and a thunk that when called produces a pair of "dog.jpg" ;; and a thunk that when called... etc. (define dan-then-dog (letrec ([f (lambda (s) (if s (cons "dan.jpg" (lambda () (f #f))) (cons "dog.jpg" (lambda () (f #t)))))]) (lambda () (f #t)))) ;; 7. function stream-add-zero that takes a stream s and returns another stream. If s would ;; produce v for its ith element, then (stream-add-zero s) would produce the pair (0 . v) for its ith element. (define (stream-add-zero s) (lambda () (let ([pr (s)]) (cons (cons 0 (car pr)) (stream-add-zero (cdr pr)))))) ;; 8. function cycle-lists that takes two lists xs and ys and returns a stream. The lists may or ;; may not be the same length, but assume they are both non-empty. The elements produced by the ;; stream are pairs where the first part is from xs and the second part is from ys. The stream cycles ;; forever through the lists. For example, if xs is ’(1 2 3) and ys is ’("a" "b"), then the stream ;; would produce, (1 . "a"), (2 . "b"), (3 . "a"), (1 . "b"), (2 . "a"), (3 . "b"), (1 . "a"), ;; (2 . "b"), etc. (define (cycle-lists xs zs) (letrec ([f (lambda (n) (let ([x (list-ref xs (list-nth-mod xs n))] (z (list-ref zs (list-nth-mod zs n)))) (cons (cons x z) (lambda () (f (+ n 1))))))]) (lambda () (f 0)))) ;; 9. function vector-assoc that takes a value v and a vector vec. It should behave like Racket’s ;; assoc library function except (1) it processes a vector (Racket’s name for an array) instead of a list, ;; (2) it allows vector elements not to be pairs in which case it skips them, and (3) it always takes exactly ;; two arguments. Process the vector elements in order starting from 0. ;; You must use library functions vector-length, vector-ref, and equal?. ;; Return #f if no vector element is a pair with a car fieldequal to v, else return the first pair with an equal car field. (define (vector-assoc v vec) (letrec ([f (lambda (n) (if (>= n (vector-length vec)) #f (let ([ith (vector-ref vec n)]) (if (and (pair? ith) (equal? (car ith) v)) ith (f (add1 n))))))]) (f 0))) ;; 10. function cached-assoc that takes a list xs and a number n and returns a function that takes ;; one argument v and returns the same thing that (assoc v xs) would return. However, you should ;; use an n-element cache of recent results to possibly make this function faster than just calling assoc ;; (if xs is long and a few elements are returned often). The cache must be a Racket vector of length n ;; that is created by the call to cached-assoc (use Racket library function vector or make-vector) and ;; used-and-possibly-mutated each time the function returned by cached-assoc is called. Assume n is positive. (define (cached-assoc xs n) (letrec ([memo (make-vector n #f)] [pos 0]) (lambda (v) (or (vector-assoc v memo) (let ([new-ans (assoc v xs)]) (and new-ans (begin (vector-set! memo pos new-ans) (set! pos (remainder (add1 pos) n)) new-ans))))))) ;; 11. (Challenge Problem:) macro that is used like (while-less e1 do e2) where e1 and e2 ;; are expressions and while-less and do are syntax (keywords). The macro should do the following: ;; • It evaluates e1 exactly once. ;; • It evaluates e2 at least once. ;; • It keeps evaluating e2 until and only until the result is not a number less than the result of the evaluation of e1. ;; • Assuming evaluation terminates, the result is #t. ;; • Assume e1 and e2 produce numbers; your macro can do anything or fail mysteriously otherwise. (define-syntax while-less (syntax-rules (do) [(while e1 do e2) (letrec ([val-of-e1 e1] [loop (lambda () (if (>= e2 val-of-e1) #t (loop)))]) (loop))]))
true
f24ebe6c9a0baf949a1818a0d44f75207fb2e7cc
e73f00aa3001beefd7618727cde784b1af5ca17c
/tarjan-scc.rkt
77ee38c5f0bbc499b7b716b035b90054f2c94b5a
[]
no_license
rntz/datalog
88c57bb57addd2de76fee11289cfeae1f32d0846
3a455d4ec87e6c507881c697b4ff0022aa605bd4
refs/heads/master
2021-01-12T03:11:54.243001
2017-12-27T16:26:21
2017-12-27T16:26:21
78,172,717
1
0
null
null
null
null
UTF-8
Racket
false
false
4,139
rkt
tarjan-scc.rkt
#lang racket (provide graph? graph/c scc-info/c scc-info sccs topsort) (struct scc-info (components node->component-index) #:transparent) (define graph? (hash/c any/c set? #:immutable #t #:flat? #t)) (define (graph/c node/c) (hash/c node/c (set/c node/c) #:immutable #t)) (define (scc-info/c node/c) (struct/c scc-info (vectorof (set/c node/c) #:immutable #t) (hash/c node/c exact-nonnegative-integer? #:immutable #t))) ;; takes a graph, represented as a hash from nodes to sets of nodes. ;; returns a graph of notes ;; ;; Hm, what if the edges of the graph have annotations? (for example, ;; positive/negative?) we could just keep a list of them. (define/contract (sccs graph) (-> (graph/c any/c) (scc-info/c any/c)) (define sorted-components '()) (define index 0) (define indices (make-hash)) (define lowlink (make-hash)) (define (next-index!) (begin0 index (set! index (+ index 1)))) (define stack '()) (define on-stack (mutable-set)) (define (try-visit node) (unless (hash-has-key? indices node) (visit node))) (define (visit node) (define index (next-index!)) (hash-set! indices node index) (hash-set! lowlink node index) (set! stack (cons node stack)) (set-add! on-stack node) (define (update-lowlink! node new-lowlink) (hash-update! lowlink node (curry min new-lowlink))) (for ([next-node (hash-ref graph node (set))]) (cond ;; if next-node is totally unvisited... [(not (hash-has-key? indices next-node)) (visit next-node) (update-lowlink! node (hash-ref lowlink next-node))] ;; if next-node is on our stack... [(set-member? on-stack next-node) ;; XXX: why does this use next-node's index, rather than lowlink? ;; my current intuition: it should work either way. ;; (update-lowlink! node (hash-ref indices next-node)) (update-lowlink! node (hash-ref lowlink next-node))] ;; next-node already completely visited, do nothing [#t])) ;; if we're done visiting an SCC... (when (= index (hash-ref lowlink node)) ;; pop its nodes off the stack (define-values (before after) (splitf-at stack (negate (curry equal? node)))) (set! stack (cdr after)) (define nodes (list->set (cons node before))) (set-subtract! on-stack nodes) ;; add the SCC. (set! sorted-components (cons nodes sorted-components)))) ;; The core loop. (for ([n (hash-keys graph)]) (try-visit n)) ;; Postprocessing. (set! sorted-components (reverse sorted-components)) (scc-info (apply vector-immutable sorted-components) (for*/hash ([(scc index) (in-indexed sorted-components)] [node scc]) (values node index)))) (define/contract (topsort graph) (-> (graph/c any/c) list?) (match-define (scc-info sorted-components node->component-index) (sccs graph)) (for*/list ([component sorted-components] [node component]) node)) ;; unfortunately graph isomorphism is ;; 1. a pain to implement ;; 2. inefficient ;; ;; so generative testing is not obviously useful here ;; ;; although, I wouldn't be surprised if there were a simple but inefficient ;; implementation of graph isomorphism I haven't thought of. Maybe in Datafun? ;; ;; TODO: more tests. (module+ test (require rackunit) (define to-list sequence->list) (define to-set (compose list->set to-list)) (define-syntax-rule (graph [v w ...] ...) (make-immutable-hash (list (cons 'v (set 'w ...)) ...))) ;; line graph (a -> b -> c) (check-equal? '(c b a) (topsort (graph [a b] [b c] [c]))) ;; two-node cycle (a -> b -> a) (define two-cycle (sccs (graph [a b] [b a]))) (check-equal? (vector-immutable (set 'a 'b)) (scc-info-components two-cycle)) ;; [a -> b c], [b -> a] graph (define abc (sccs (graph [a b c] [b a] [c]))) (check-equal? (list (set 'c) (set 'a 'b)) (to-list (scc-info-components abc))) ;; diamond graph (define diamond (graph [a b c] [b d] [c d] [d])) (check-equal? (to-set (map set '(a b c d))) (to-set (scc-info-components (sccs diamond)))))
true
4941c50f5ad796ed2912d954d308bfa8029f4e3e
0408ce7e2362217750e07f8bdb3a2849fdd26ec2
/fall19-ps10/Solutions/problem2-factorial.rkt
c1d2b9266fd061b673f0ca43d14c555e6adab43a
[]
no_license
erhant/eopl-scheme
af8e0ae7b617b7e365ecf12af8993c6192c9b3b6
a1fe269153278b1b818eb2746610905244278ef4
refs/heads/master
2023-07-08T09:05:52.519276
2021-08-17T04:02:19
2021-08-17T04:02:19
265,209,851
0
0
null
null
null
null
UTF-8
Racket
false
false
1,163
rkt
problem2-factorial.rkt
#lang racket (define (fact x) (fact-c x (create-final-cont))) (define (fact2 x) (fact-c2 x (create-final-cont))) ;;;;;;;;;; PROBLEM 2 ;;;;;;;;;;;;; ; define create-final-cont here (define (create-final-cont) (lambda (x) x)) ; define fact-c here ; this is the factorial function with continuation passing ; it will be using create-fact-c x cont in its body (define (fact-c x cont) (if (= x 0) (apply-cont cont 1) (fact-c (- x 1) (create-fact-c x cont) ))) ; define create-fact-c here ; it creates the continuation for factorial ; this function will be used by fact-c (define (create-fact-c x cont) (lambda (n) (apply-cont cont (* x n)))) ; define apply-cont here, it will be used by create-fact-c (define (apply-cont c x) (c x)) ; define function fact-c2 here ; this is also a factorial function with continuation passing ; but unlike fact-c, this one does not use create-fact-c function. (define (fact-c2 x cont) (if (= x 0) (cont 1) (fact-c2 (- x 1) (lambda (n) (cont (* x n)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; some tests (display (fact 5)) ; should output 120 (display "\n") (display (fact2 5)) ; should output 120
false
1208cc131a4f86b16e82fc847c676913f0bbcce2
4b1d96db91c4775b9fe402f9372dbbc83430effe
/partB/week1/thunk.rkt
0c17e0c6d932618618cb0639fce57ece5a8f2f5a
[]
no_license
GPF007/Programming-languages
9e3f181f9ff71d7f11c6865ce8d8381f301385a1
24e1c7b6fe5b26a267d0779049af6e424c6bcc0e
refs/heads/master
2020-07-05T00:17:01.469680
2019-08-15T03:33:41
2019-08-15T03:33:41
202,466,832
1
0
null
null
null
null
UTF-8
Racket
false
false
151
rkt
thunk.rkt
#lang racket (define (my-if x y z) (if x (y) (z))) (define (fact x) (my-if (= x 0) (lambda () 1) (lambda () (* x (fact(- x 1))))))
false
73538f114d52a80fa34c83cbbb79c51791a59425
09fc7d8c8ffc75f6338373584e2628ee58d89227
/test.rkt
58df081f0f5f98baee4a77560104616172d8b0a4
[]
no_license
zussitarze/6502
5e4b477e98d21c866eb41e04a0b447dace341abe
ef146ec46292e4966964943df5fef5317d947557
refs/heads/master
2020-06-03T15:09:51.019385
2016-02-04T08:54:11
2016-02-04T08:54:47
41,899,692
1
0
null
null
null
null
UTF-8
Racket
false
false
5,476
rkt
test.rkt
#lang racket/base (require rackunit "core.rkt" "assembler.rkt" "bitutils.rkt" "object.rkt") (define-syntax 6502-test-case (syntax-rules () [(6502-test-case name initials source expectations) (test-case name (define obj (assemble source)) (define mem (make-bytes (* 64 1024) 0)) (load-object obj mem) (for ([i initials]) (bytes-set! mem (car i) (cdr i))) (thread-wait (execute (bus-with-memory mem) (section-start (car obj)) #f #f)) (with-check-info (['obj (dumpobject obj)] ['page0 (dumpbytes (subbytes mem #x000 #x100))] ['page1 (dumpbytes (subbytes mem #x100 #x200))] ['page2 (dumpbytes (subbytes mem #x200 #x300))]) (for ([e expectations]) (check-eq? (bytes-ref mem (car e)) (cdr e)))))])) (6502-test-case "All kinds of storage" '() (6502asm (lda (! 1)) (sta #x50) ; #x50 <= 1 ;;------------------------- (tax) (inx) (stx #x51) ; #x51 <= 2 ;;------------------------- (txa) (tay) (iny) (sty #x52) ; #x52 <= 3 ;;------------------------- (lda (! 4)) (ldx (! 3)) (sta #x50 X) ; #x53 <= 4 ;;------------------------- (lda (! 5)) (sta #x0250 X) ; #x0253 <= 5 ;;------------------------- (lda (! #x55)) (sta #x54) (lda (! #x02)) (sta #x55) (lda (! 6)) (ldx (! 4)) (sta (@ #x50 X)) ; #x0255 <= 6 ;;------------------------- (ldy (! 7)) (lda (! 7)) (sta (@ #x54) Y) ; #x025C <= 7 ;;------------------------- (ldx (! 8)) (ldy (! 2)) (stx #x56 Y) ; #x58 <= 8 ;;------------------------- (lda (! 9)) (ldy (! 2)) (sta #x0256 Y) ;; #x0258 <= 9 ) '((#x50 . 1) (#x51 . 2) (#x52 . 3) (#x53 . 4) (#x0253 . 5) (#x0255 . 6) (#x025C . 7) (#x58 . 8) (#x0258 . 9))) (6502-test-case "Find max (post-indexed)" '((#x41 . 5) (#x42 . 00) (#x43 . #x02) (#x201 . #x67) (#x202 . #x79) (#x203 . 15) (#x204 . #xe3) (#x205 . #x72)) (6502asm (ldy #x41) (lda (! 0)) (: "maximum") (cmp (@ #x42) Y) (bcs "no change") (lda (@ #x42) Y) (: "no change") (dey) (bne "maximum") (sta #x40) (brk)) '((#x40 . #xe3))) (6502-test-case "Pre-indexed test" ;; get the value at address (#x60 + 0) and store it at the address (#x60 + 2) '((#x60 . #x2f) (#x61 . #x02) (#x62 . #x32) (#x63 . #x02) (#x022f . #x88)) (6502asm (% EQU "nil" 0) (ldx (! "nil")) (lda (@ #x60 X)) (inx) (inx) (sta (@ #x60 X)) (brk)) '((#x0232 . #x88))) (6502-test-case "wordsplit2" '((#x40 . #x3f)) (6502asm (lda #x40) (and (! #b00001111)) (sta #x42) (lda #x40) (lsr A) (lsr A) (lsr A) (lsr A) (sta #x41)) '((#x41 . #x03) (#x42 . #x0f))) (6502-test-case "16bit add" '((#x40 . #x2A) (#x41 . #x67) (#x42 . #xf8) (#x43 . #x14)) (6502asm (clc) (lda #x40) (adc #x42) (sta #x44) (lda #x41) (adc #x43) (sta #x45)) '((#x44 . #x22) (#x45 . #x7c))) (6502-test-case "Tests jumping and branching across segments" '() (6502asm (% ORG 10) (sec) (: "Loop") (nop) (bcc "Terminate") (clc) (jmp "Loop") (nop) (nop) (% SECTION "Terminate" 50 10 (lda (! #x33)) (sta #x99) (brk))) '((#x99 . #x33))) (6502-test-case "Lookup square" '() (6502asm (ldx (! 4)) (lda #x60 X) (sta #x90) (ldx (! 7)) (lda #x60 X) (sta #x91) (brk) (% ORG #x60) (: "SQTAB") (% BYTE 0 1 4 9 16 25 36 49)) '((#x90 . 16) (#x91 . 49))) (6502-test-case "Adding sums of data" '((#x41 . #x03) (#x42 . #x28) (#x43 . #x55) (#x44 . #x26)) (6502asm (lda (! 0)) (ldx #x41) (: "SUMD") (clc) (adc #x41 X) (dex) (bne "SUMD") (sta #x40) (brk)) '((#x40 . #xa3))) (6502-test-case "Count negatives" '((#x41 . #x06) (#x42 . #x68) (#x43 . #xf2) (#x44 . #x87) (#x45 . #x30) (#x46 . #x59) (#x47 . #x2a)) (6502asm (ldx (! 0)) (ldy (! 0)) (: "Sum") (lda #x42 X) (bpl "Next") (iny) (: "Next") (inx) (cpx #x41) (bne "Sum") (sty #x40) (brk)) '((#x40 . #x02))) (6502-test-case "String length" '() (6502asm (ldx (! 0)) (lda (! (char->integer #\newline))) (: "Check") (cmp "STR" X) (beq "Done") (inx) (jmp "Check") (: "Done") (stx #x40) (brk) (: "STR") (% STRING "Hello World!\n")) '((#x40 . 12))) (6502-test-case "Bubble sort" '((#x40 . 6) (#x41 . #x2a) (#x42 . #xb5) (#x43 . #x60) (#x44 . #x3f) (#x45 . #xd1) (#x46 . #x19)) (6502asm (: "sort") (ldy (! 0)) (ldx #x40) (dex) (: "pass") (lda #x40 X) (cmp #x41 X) (bcc "count") (ldy (! 1)) (pha) (lda #x41 X) (sta #x40 X) (pla) (sta #x41 X) (: "count") (dex) (bne "pass") (dey) (beq "sort") (brk)) '((#x41 . #x19) (#x42 . #x2a) (#x43 . #x3f) (#x44 . #x60) (#x45 . #xb5) (#x46 . #xd1))) (6502-test-case "Simple subroutine" '((#x40 . 13)) (6502asm (ldx (! #xff)) (txs) (lda #x40) (jsr "ASDEC") (sta #x41) (brk) ;; ASDEC: Convert values to ascii digits. (% ORG #x20) (: "ASDEC") (cmp (! 10)) ;; is digit bigger than 10? (bcc "ASCZ") (clc) (adc (! 7)) (: "ASCZ") (adc (! (char->integer #\0))) (rts)) `((#x41 . ,(char->integer #\D)))) (6502-test-case "Indirect/direct jumping" '((#x40 . 0) (#x41 . 0)) (6502asm (jmp "step1") (: "step2") (lda (! #xcc)) (sta #x40) (brk) (: "step1") (lda (! #xdd)) (sta #x41) (jmp (@ "vector")) (: "vector") (% WORD "step2")) `((#x40 . #xcc) (#x41 . #xdd)))
true
f5829cb7914b841c2ace9159bd57bfc7562fd650
6061bf67c5a52025ed7965b271af49fafe56dc6b
/deps/rackunit-abbrevs/private/error-reporting.rkt
9fa2e6932628a5fdaa64914b0300aa5eb514c34c
[]
no_license
btlachance/ms-thesis-experiments
3069f8221f0b66f384334d24b10d561815452376
12bb1f3552e835e744e7fd3f8eb4a6ffb08c9ce3
refs/heads/master
2021-05-01T07:03:42.525750
2016-10-26T21:58:34
2016-10-26T22:47:56
72,046,708
0
0
null
null
null
null
UTF-8
Racket
false
false
1,320
rkt
error-reporting.rkt
#lang racket/base (provide syntax->location procedure exn-predicate args-and-result-pattern ) (require racket/syntax syntax/parse ) ;; ============================================================================= ;;bg; copied from rackunit library (location.rkt) (define syntax->location (let ([f* (list syntax-source syntax-line syntax-column syntax-position syntax-span)]) (lambda (stx) (for/list ([f (in-list f*)]) (f stx))))) (define-syntax-class procedure ;; cat in the hat style (pattern (~not (~or _:number _:boolean _:char _:str _:keyword)))) (define-syntax-class exn-predicate ;; exn-predicate is a regular expression or a predicate function (pattern (~not (~or _:number _:boolean _:char _:str _:keyword)))) (define-syntax-class args-and-result-pattern #:attributes (arg* check-fn? result) #:datum-literals (!= !=> == => ==>) (pattern [args ... (~or (~and (~or != !=>) (~var make-fail)) (~and (~or == => ==>) (~var make-pass))) res] #:attr arg* #'(args ...) #:attr check-fn? (if (attribute make-pass) (format-id #'res "check-equal?") (format-id #'res "check-not-equal?")) #:attr result #'res))
true
ba293e67eacaadaebe99dd2a37a87644b5dd1661
616e16afef240bf95ed7c8670035542d59cdba50
/redex-doc/redex/scribblings/long-tut/code/delivered-wed-mor.rkt
86a3dd587f01babc8a1467f7312aa0f1aca5651c
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
racket/redex
bd535d6075168ef7be834e7c1b9babe606d5cd34
8df08b313cff72d56d3c67366065c19ec0c3f7d0
refs/heads/master
2023-08-19T03:34:44.392140
2023-07-13T01:50:18
2023-07-13T01:50:18
27,412,456
102
43
NOASSERTION
2023-04-07T19:07:30
2014-12-02T03:06:03
Racket
UTF-8
Racket
false
false
3,044
rkt
delivered-wed-mor.rkt
#lang racket ;; a SEMANTICS for a Lambda-language with variable assignment statements ;; -- equipping a semantics with a store ;; -- variables as locations ;; a CALCULUS for a Lambda-language with a raise-exception expression ;; -- erasing evaluation contexts ;; ----------------------------------------------------------------------------- (require redex "common.rkt" "extend-lookup.rkt") (define-extended-language Assignments Lambda (e ::= .... n + (void) (set! x e)) (n ::= natural)) ;; (let ((x_1 x_2) ...) e_1 e_2) binds the current value of x_2 to x_1, ;; evaluates e_1, throws away its value, and finally evaluates e_2 (define-metafunction Assignments let : ((x e) ...) e e -> e [(let ([x_lhs e_rhs] ...) e_1 e_2) ((lambda (x_lhs ...) ((lambda (x_dummy) e_2) e_1)) e_rhs ...) (where (x_dummy) ,(variables-not-in (term (e_1 e_2)) '(dummy)))]) (define assignments? (redex-match? Assignments e)) (define e1 (term (lambda (x) (lambda (y) (let ([tmp x]) (set! x (+ y 1)) tmp))))) (define p-1 (term ((,e1 1) 2))) (define e2 (term ((lambda (x) (let ([tmp x]) (set! x y) tmp)) (let ([tmp-z z]) (set! z (+ z 1)) (let ([tmp-y y]) (set! y tmp-z) tmp-y))))) (define p-2 (term ((lambda (y) ((lambda (z) ,e2) 1)) 2))) (define p-c (term +)) (module+ test (test-equal (assignments? e2) #true) (test-equal (assignments? e1) #true) (test-equal (assignments? p-1) #true) (test-equal (assignments? p-2) #true) (test-equal (assignments? p-c) #true)) ;; ------------------------------------------------------- ;; ------------------------------------------------------------------- ;; stores for a semantics (define-extended-language Assignments-s Assignments (E ::= hole (v ... E e ...) (set! x E)) (σ ::= ((x v) ...)) (v ::= n + (lambda (x ...) e) (void))) ;; ------------------------------------------------------- ;; the standard reduction (module+ test (define es (term ((lambda (x) ((lambda (y) x) (let ([tmp x]) (set! x 1) tmp))) 0))) (test-->>∃ s->βs (term [,es ()]) (redex-match? Assignments-s [1 σ])) (define e-bug (term (let ([x 42]) (void) (let ([x 84]) (void) x)))) (test-->>∃ s->βs (term [,e-bug ()]) (redex-match? Assignments-s [84 σ])) #; (traces s->βs (term [,e-bug ()]))) (define s->βs (reduction-relation Assignments-s #:domain (e σ) (--> [(in-hole E x) σ] [(in-hole E (lookup σ x)) σ]) (--> [(in-hole E (set! x v)) σ] [(in-hole E (void)) (extend σ (x) (v))]) (--> [(in-hole E (+ n_1 n_2)) σ] [(in-hole E ,(+ (term n_1) (term n_2))) σ]) (--> [(in-hole E ((lambda (x ..._n) e) v ..._n)) σ] [(in-hole E (subst ((x_new x) ...) e)) (extend σ (x_new ...) (v ...))] (where (x_new ...) ,(variables-not-in (term σ) (term (x ...))))))) (module+ test (test-results))
false
c5c34c37a6664eaac231f3525aeebbb60ea0c4ae
a79e5f977aa7fd52bebff56009517feb92b254d5
/src/gui/ext/mouse/click/up/up-click-interface.rkt
365fb2d387e5a690c53b0d97697b7a3a02247417
[]
no_license
paddymahoney/music-grid
a03dafffb9490370f3e84c900ec2579767816d9d
95f3d321cf737b4ff61950c1b9bdb3f8074e1e2a
refs/heads/master
2020-07-04T15:57:18.026469
2012-05-01T17:23:50
2012-05-01T17:23:50
null
0
0
null
null
null
null
UTF-8
Racket
false
false
230
rkt
up-click-interface.rkt
#lang racket (require racket/gui/base) (require racket/class) (require (prefix-in mouse: "../../event/mouse-event-interface.rkt")) (define up-click<%> (interface (mouse:mouse-event<%>) on-up-click)) (provide (all-defined-out))
false
97ea90944d368ba7505cd3475d1f71678153bf12
fc90b5a3938850c61bdd83719a1d90270752c0bb
/web-server-lib/web-server/managers/none.rkt
3843041206447bde530ea87ffc1be31ee0710073
[ "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
1,348
rkt
none.rkt
#lang racket/base (require racket/contract) (require "manager.rkt") (require web-server/servlet/servlet-structs web-server/http) (provide/contract [create-none-manager (-> (or/c false/c (request? . -> . can-be-response?)) manager?)]) (define-struct (none-manager manager) (instance-expiration-handler)) (define (create-none-manager instance-expiration-handler) (define (create-instance expire-fn) 0) (define (adjust-timeout! instance-id secs) (void)) (define (instance-lookup instance-id) (raise (make-exn:fail:servlet-manager:no-instance (format "No instance for id: ~a" instance-id) (current-continuation-marks) instance-expiration-handler))) (define (clear-continuations! instance-id) (instance-lookup instance-id)) (define (continuation-store! instance-id k expiration-handler) (instance-lookup instance-id)) (define (continuation-lookup instance-id a-k-id a-salt) (instance-lookup instance-id)) (make-none-manager create-instance adjust-timeout! clear-continuations! continuation-store! continuation-lookup continuation-lookup ; Specific instance-expiration-handler))
false
5d169c72ff22cf3f7e0c68482a82708c6ae48bae
616e16afef240bf95ed7c8670035542d59cdba50
/redex-test/redex/tests/sewpr/extend/eiswim-test.rkt
4f4def057107cfde6a50014dee212332e3143aca
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
racket/redex
bd535d6075168ef7be834e7c1b9babe606d5cd34
8df08b313cff72d56d3c67366065c19ec0c3f7d0
refs/heads/master
2023-08-19T03:34:44.392140
2023-07-13T01:50:18
2023-07-13T01:50:18
27,412,456
102
43
NOASSERTION
2023-04-07T19:07:30
2014-12-02T03:06:03
Racket
UTF-8
Racket
false
false
798
rkt
eiswim-test.rkt
#lang racket/base (require "../iswim/iswim.rkt" "eiswim.rkt") ;; ENDDEFS (require redex) (module+ main ;; START ex0 (traces e-iswim-red-first-try (term (/ ((λ x (/ 1 x)) 7) 2))) ;; STOP ex0 ) ;; EXAMPLE ex1 (redex-match e-iswim V (term (λ x (/ 1 x)))) ;; BESIDE ex1 (redex-match iswim V (term (λ x (/ 1 x)))) ;; STOP ex1 ;; EXAMPLE ex2 (redex-match e-iswim M (term (λ err err))) ;; BESIDE ex2 (redex-match iswim M (term (λ err err))) ;; STOP ex2 #; (begin (require redex) (traces e-iswim-red-first-try (term (/ ((λ x (+ (/ 1 x) (err 2))) 7) 2)))) #; (begin (require redex) )
false
292571b4a2af21d12923991557713febcea3650e
7b8ebebffd08d2a7b536560a21d62cb05d47be52
/doc/eng/monads-List.scrbl
1c536a8a808ceb8289866779195051e0ff744fc0
[]
no_license
samth/formica
2055045a3b36911d58f49553d39e441a9411c5aa
b4410b4b6da63ecb15b4c25080951a7ba4d90d2c
refs/heads/master
2022-06-05T09:41:20.344352
2013-02-18T23:44:00
2013-02-18T23:44:00
107,824,463
0
0
null
2017-10-21T23:52:59
2017-10-21T23:52:58
null
UTF-8
Racket
false
false
11,151
scrbl
monads-List.scrbl
#lang scribble/doc @(require (for-label formica)) @(require scribble/manual scribble/eval) @(define formica-eval (let ([sandbox (make-base-eval)]) (sandbox '(require formica)) sandbox)) @title{Monads, defined in Formica} @declare-exporting[formica] @section{The Identity monad} @defthing[Id monad?] The identity monad. Definition: @codeblock{return = id bind _m _f = (_f _m)} Examples: @defs+int[#:eval formica-eval ((using-monad Id) (define-formal f)) (return 'x) (bind 'x >>= f)] In the @racket[Id] monad @racket[do] form works like @racket[match-let*] form with ability to produce side effects within calculations: @interaction[#:eval formica-eval (do [x <- 5] [y <- 8] (displayln x) [x <- (+ x y)] (list x y))] @interaction[#:eval formica-eval (do [(cons x y) <- '(1 2 3)] [(z t) <<- (reverse y)] (return (list x y z t)))] @section{Ambiguous computations.} @defproc[(Monoid [#:return ret (Any ... → listable?)] [#:mplus seq-append (listable? listable? → listable?)] [#:map seq-append-map ((Any → listable?) listable? → listable?) mplus-map]) monad-plus?] Returns a monad which performs computations which may return zero or more then one possible result as a sequence (list, stream, set etc.). This is an abstraction of monads operating with monoids. Monads @racket[List], @racket[Stream] and @racket[Amb] are defined through the @racket[Monoid] function. Definition: @codeblock{return = _ret bind _s _f = (_seq-append-map _f _s) mplus = _seq-append mzero = (return) type = listable? failure = (const mzero)} The sequence of arguments is constructed by the @racket[_ret] function. The bound function @racket[_f] is applied to all possible values in the input sequence @racket[_s] and the resulting sequences are concatenated by the @racket[_seq-append] to produce a sequence of all possible results. The details of binding implementation are specified by the mapping function @racket[_seq-append-map]. The @racket[Monoid] function creates monads, operating with @emph{monoids}: sets having a single identity element @racket[(_ret)], and an associative binary operator over the set of objects @racket[_seq-append]. @bold{Examples:} Using @racket[Monoid] it is easy to define monads working with different types of sequences: sets, vectors, strings etc. @def+int[#:eval formica-eval (define-monad Set (Monoid #:return set #:mplus set-union)) (using Set (lift/m + '(1 2 3) '(2 3 4)))] @defs+int[#:eval formica-eval ((define-monad String (Monoid #:return string #:mplus (flipped string-append)))) (using String (collect (char-upcase x) [x <- "abc12xy"] (char-alphabetic? x) [x <- (format "~a(~a)" x (char->integer x))]))] @defproc[(listable? (v Any)) Bool] Returns @racket[#t] if @racket[v] is a sequence, except for @tech{formal applications} or integers. Examples: @interaction[#:eval formica-eval (listable? '(1 2 3)) (listable? 4) (listable? (stream 1 2 (/ 0))) (listable? '(g x y)) (define-formal g) (listable? (g 'x 'y))] @defproc[(mplus-map [f (Any → listable?)] [s listable?]) listable?] Generalized mapping function for the @tech{currently used monad}. Formally equal to @codeblock{(mplus-map f s) = (foldl (∘ mplus f) mzero s)} @defproc[(zip [s listable?] ...) sequence?] Returns a sequence where each element is a list with as many values as the number of supplied sequences; the values, in order, are the values of each sequence. Used to process sequences in parallel, as in @racket[for/list] iterator. Example of using @racket[zip]: @interaction[#:eval formica-eval (using List (do [(list x y) <- (zip '(a b c) '(1 2 3 4))] (return (f x y))))] The same with @racket[for/list] iterator. @interaction[#:eval formica-eval (for/list ([x '(a b c)] [y '(1 2 3 4)]) (f x y))] @subsection{The List monad} @defthing[List monad-plus?] The @racket[List] monad is used for list comprehension and in order to perform calculations with functions, returning more then one value. The main difference between the @racket[List] and monad @tt{[]} in @emph{Haskell}, is the ability of @racket[List] to operate with any sequences as @racket[for] iterators do. Definition: @codeblock{List = (Monoid #:return list #:mplus append #:map append-map)} @bold{Examples} @def+int[#:eval formica-eval (using-monad List)] Examples of list comprehension @interaction[#:eval formica-eval (collect (sqr x) [x <- '(1 2 5 13 4 24)] (odd? x))] @interaction[#:eval formica-eval (collect (cons x y) [x <- '(1 3 4 8 2 4)] [y <- '(3 1 6 4 3)] (< x y) (= (modulo x y) 2))] @interaction[#:eval formica-eval (collect (cons x y) [(list x y) <- '((1 2) (2 4) (3 6) (5 1))] (odd? x) (< x y))] Forms @racket[do] and @racket[collect] in the @racket[List] monad work like @racket[for*/list] form: @interaction[#:eval formica-eval (do [x <- '(1 2)] [y <- '(a b c)] (return (cons x y))) (for*/list ([x '(1 2)] [y '(a b c)]) (cons x y))] @interaction[#:eval formica-eval (collect (cons x y) [x <- '(1 2 3)] (odd? x) [y <- '(a b c)]) (for*/list ([x '(1 2 3)] #:when (odd? x) [y '(a b c)]) (cons x y))] The use of monad @racket[List] goes beyond the simple list generation. The main purpose of monadic computations is to provide computation with functions which may return more then one value (or fail to produce any). The examples of various applications of this monad could be found in the @filepath{nondeterministic.rkt} file in the @filepath{examples/} folder. @subsection{The Stream monad} @defthing[Stream monad-plus?] Like @racket[List] monad, but provides lazy list processing. This monad is equivalent to monad @tt{[]} in @emph{Haskell} and could be used for operating with potentially infinite sequences. Definition: @codeblock{Stream = (Monoid #:return list #:mplus stream-concatenate #:map stream-concat-map)} @defproc[(stream-concatenate (s listable?) ...) stream?] Returns a result of @racket[_s ...] lazy concatenation in a form of a stream. Examples: @interaction[#:eval formica-eval (stream->list (stream-concatenate '(1 2 3) '(a b c))) (stream->list (stream-concatenate (in-range 4) (stream 'a 'b 'c))) (stream-ref (stream-concatenate (stream 1 (/ 0)) (in-naturals)) 0) (stream-ref (stream-concatenate (stream 1 (/ 0)) (in-naturals)) 1)] @defproc[(stream-concat-map (f (Any → stream?)) (s listable?)) stream?] Applies @racket[_f] to elements of @racket[_s] and lazily returns the concatenation of results. Examples: @interaction[#:eval formica-eval (stream->list (stream-concat-map (λ (x) (stream x (- x))) '(1 2 3))) (stream->list (stream-concat-map (λ (x) (stream x (- x))) (in-range 4))) (stream-ref (stream-concat-map (λ (x) (stream x (/ x))) '(1 0 3)) 0) (stream-ref (stream-concat-map (λ (x) (stream x (/ x))) '(1 0 3)) 1) (stream-ref (stream-concat-map (λ (x) (stream x (/ x))) '(1 0 3)) 2) (stream-ref (stream-concat-map (λ (x) (stream x (/ x))) '(1 0 3)) 3)] @defproc[(stream-take (s stream?) (n Nat)) list?] Returns list of @racket[_n] first elements of stream (or sequence) @racket[s]. Examples: @interaction[#:eval formica-eval (stream-take (stream 'a 'b 'c) 2) (stream-take (stream 'a 'b (/ 0)) 2) (stream-take (in-naturals) 3)] @bold{Examples} @def+int[#:eval formica-eval (using-monad Stream)] Two classical examples with infinite sequences. The infinite sequence of Pythagorean triples: @def+int[#:eval formica-eval (define triples (collect (list a b c) [a <- (in-naturals)] [b <- (in-range (ceiling (/ a 2)) a)] [c <-: (sqrt (- (sqr a) (sqr b)))] (integer? c) (> b c))) (stream-take triples 3) (stream-ref triples 100)] The first triangle with area exceeding 100: @interaction[#:eval formica-eval (stream-first (collect t [(and t (list _ b c)) <- triples] (> (* 1/2 b c) 100)))] The infinite sequence of primes: @def+int[#:eval formica-eval (define (primes r) (do [(scons x xs) <-: r] [p <-: (collect y [y <- xs] (not (zero? (modulo y x))))] (stream-cons x (primes p)))) (stream-take (primes (in-naturals 2)) 10) (stream-ref (primes (in-naturals 2)) 100)] Using monad @racket[Stream] all monadic functions work lazily however they still operate on eager lists: @interaction[#:eval formica-eval (stream-first ((compose/m (lift /) (lift (curry * 2))) 1/2 0)) (stream-first (lift/m / (return 1) (return 1 0))) (stream-ref (lift/m / (return 1) (return 1 0)) 1) (stream-ref (map/m (λ (x) (stream x (/ x))) '(1 0 3)) 0) (stream-ref (map/m (λ (x) (stream x (/ x))) '(1 0 3)) 1) (stream-ref (map/m (λ (x) (stream x (/ x))) '(1 0 3)) 2)] @subsection{The Amb monad} @defthing[Amb monad-plus?] Like @racket[Stream] monad, but tries to return a list of unique elements. Definition: @codeblock{Amb = (Monoid #:return amb #:mplus amb-union #:map amb-union-map)} @defproc[(amb (v Any) ...) stream?] Returns a stream of arguments @racket[_v] removing duplicates (in terms of @racket[equal?]). Examples: @interaction[#:eval formica-eval (stream->list (amb 1 3 2 2 3 2 1 2 4 3)) (stream-take (amb 1 2 (/ 0)) 2)] @defproc[(amb-union (s1 listable?) (s2 listable?)) stream?] Returns a stream of elements from @racket[_s1] and @racket[_s2], removing duplicates. Examples: @interaction[#:eval formica-eval (stream->list (amb-union '(1 2 3) '(2 3 4))) (stream->list (amb-union (in-range 4) (amb 'a 'b 'c))) (stream-ref (amb-union (amb 1 (/ 0)) (in-naturals)) 0) (stream-ref (amb-union (amb 1 (/ 0)) (in-naturals)) 1)] @defproc[(amb-union-map (f (Any → stream?)) (s listable?)) stream?] Applies @racket[_f] to elements of @racket[_s] and lazily returns the union of results. Examples: @interaction[#:eval formica-eval (stream->list (amb-union-map (lift sqr) '(-3 -2 -1 0 -1 2 3))) (stream->list (amb-union-map (λ (x) (amb x (- x))) (in-range 4))) (stream-ref (amb-union-map (λ (x) (amb x (/ x))) '(1 0 3)) 0) (stream-ref (amb-union-map (λ (x) (amb x (/ x))) '(1 0 3)) 1) (stream-ref (amb-union-map (λ (x) (amb x (/ x))) '(1 0 3)) 2)] @bold{Examples} @def+int[#:eval formica-eval (using-monad Amb)] Proving logical statements by brute force @interaction[#:eval formica-eval (stream->list (collect (eq? (==> A B) (or B (not A))) [(A B) <<- (amb #t #f)])) (stream->list (collect (==> (==> (==> A B) C) (==> A (==> B C))) [(A B C) <<- (amb #t #f)])) (stream->list (collect (eq? (==> (==> A B) C) (==> A (==> B C))) [(A B C) <<- (amb #t #f)])) (stream->list (collect (list A B C) [(A B C) <<- (amb #t #f)] (not (eq? (==> (==> A B) C) (==> A (==> B C))))))]
false
4b8f29d82e2966371a4411e8f270f2b0c8fa4d91
025c71211d8c0b4cf40c65d5add4c3d1fe10fa59
/stlc/01-eval.rkt
3e84dbae3843af638b62895a30f863435f72498e
[]
no_license
gregr/experiments
5ce58d6ac6ae034d3955a96a434272ab3671bf6f
a6c5461bda9f8e221225a403f21d61ad4673c57a
refs/heads/master
2023-08-10T23:48:05.730805
2023-08-01T18:58:56
2023-08-01T18:58:56
4,839,336
9
2
null
null
null
null
UTF-8
Racket
false
false
6,050
rkt
01-eval.rkt
#lang racket (define env-empty '()) (define (env-lookup-default env name default) (match env (`((,n ,val) . ,env) (if (eq? n name) val ;; Reference binding (env-lookup-default env name default))) ;; Traverse environment ('() (default)))) (define (env-lookup env name) (env-lookup-default env name (lambda () name))) (define (env-lookup-fail env name) (env-lookup-default env name (lambda () (error (format "unbound variable: ~a" name))))) (define (env-extend env name val) `((,name ,val) . ,env)) ;; Extended to support symbolic evaluation under unapplied lambdas (define (eval-term env term) (match term (`(lambda ,name ,body) `(closure ,name ,body ,env)) ;; Close over environment (`(,fn ,arg) (match (eval-term env fn) (`(closure ,name ,body ,cenv) ;; Apply closure (eval-term (env-extend cenv name (eval-term env arg)) body)) (vfn `(,vfn ,(eval-term env arg))))) ;; Symbolic application (_ (env-lookup env term)))) (define (normalize-term env term) (match (eval-term env term) (`(closure ,name ,body ,cenv) (let ((name1 (gensym name))) `(lambda ,name1 ,(normalize-term (env-extend cenv name name1) body)))) (`(,fn ,arg) `(,(normalize-term env fn) ,(normalize-term env arg))) (term term))) (define (denote-term term) (match term (`(closure ,name ,body ,cenv) (let ((clo ((denote-term `(lambda ,name ,body)) (map (lambda (binding) (list (car binding) (list #f (cadr binding)))) cenv)))) (lambda (env) clo))) (`(lambda ,name ,body) (let ((dbody (denote-term body))) (lambda (env) (lambda (arg) (dbody (env-extend env name (list #t arg))))))) (`(,fn ,arg) (let ((dfn (denote-term fn)) (darg (denote-term arg))) (lambda (env) ((dfn env) (darg env))))) (_ (lambda (env) (match (env-lookup-default env term (lambda () (list #t term))) (`(#t ,val) val) (`(#f ,term) ((denote-term term) env))))))) (define (eval term) (eval-term env-empty term)) (define (normalize term) (normalize-term env-empty term)) (define (denote term) ((denote-term term) env-empty)) (define (closure->boolean clo) ((clo #t) #f)) (define (closure->nat clo) ((clo add1) 0)) (define (closure->pair left right clo) (clo (lambda (h) (lambda (t) (cons (left h) (right t)))))) (define (closure->list element clo) (map element ((clo (lambda (h) (lambda (t) (cons h t)))) '()))) (define (denote-boolean term) (closure->boolean (denote term))) (define (denote-nat term) (closure->nat (denote term))) (define (denote-pair left right term) (closure->pair left right (denote term))) (define (denote-list element term) (closure->list element (denote-term))) (define (parse penv stx) (define (free-name? name) (not (env-lookup-default penv name (lambda () #f)))) (define (special? name) (procedure? (env-lookup penv name))) (match stx (`(,(? free-name? 'lambda) ,params ,body) (match params (`(,name) (parse penv `(lambda ,name ,body))) (`(,name . ,names) (parse penv `(lambda ,name (lambda ,names ,body)))) (name `(lambda ,name ,(parse (env-extend penv name name) body))))) (`(,(? symbol? (? special? fn)) . ,args) (parse penv (apply (env-lookup penv fn) args))) (`(,fn . ,args) (let loop ((args args) (pfn (parse penv fn))) (match args (`(,arg . ,args) (loop args `(,pfn ,(parse penv arg)))) ('() pfn)))) (_ (env-lookup penv stx)))) (define-syntax env-extend-params (syntax-rules () ((_ env param params ...) (env-extend-params (env-extend env 'param param) params ...)) ((_ env) env))) (define-syntax lc-module-k (syntax-rules (=) ((_ penv (bindings ...) (clauses ...) (data ...) (name params ...) = rhs rest ...) (lc-module-k penv (bindings ... (name (lambda (params ...) (parse (env-extend-params penv params ...) 'rhs))) (penv (env-extend penv 'name name))) (clauses ... ('name name)) (data ... (list 'name name)) rest ...)) ((_ penv (bindings ...) (clauses ...) (data ...) name = rhs rest ...) (lc-module-k penv (bindings ... (name (parse penv 'rhs)) (penv (env-extend penv 'name name))) (clauses ... ('name name)) (data ... (list 'name name)) rest ...)) ((_ penv bindings (clauses ...) (data ...)) (let* bindings (lambda args (match args ('() (list data ...)) (`(,name) (match name clauses ...)))))))) (define-syntax lc-module (syntax-rules () ((_ body ...) (let ((penv env-empty)) (lc-module-k penv () () () body ...))))) (define example (lc-module true = (lambda (t f) t) false = (lambda (t f) f) (if condition true-alt false-alt) = ((condition (lambda _ true-alt) (lambda _ false-alt)) (lambda _ _)) n0 = (lambda (f x) x) succ = (lambda (n f x) (f (n f x))) (exp a b) = (b a) n1 = (succ n0) n2 = (succ n1) n3 = (succ n2) n8 = (exp n2 n3) n256 = (exp n2 n8) add = (lambda (a b f x) (a f (b f x))) mul = (lambda (a b f) (a (b f))) nil = (lambda (c n) n) cons = (lambda (h t c n) (c h (t c n))) ; (cons A nil) ==> (lambda (c n) (c A n)) ; (cons B (cons A nil)) ==> (lambda (c n) (c B (c A n))) ; ; c = (lambda (a b) (f b)) ==> church numerals ; c = (lambda (a b) a) ==> car ; c = (lambda (a b) b) ==> n ; cdr == subtraction ; ; n == our initial value ; c = (lambda (value acc) (accumulate value acc)) ; foldr = (lambda (combiner init xs) (xs combiner init)) ))
true
18b5a571a802be82def764d7b3452033acd97f93
7a4634df33a813e5f116ac1a9541742104340a56
/pollen/scribblings/top.scrbl
ef774ed0412f8f90c71f44709fba9565619b19b1
[ "MIT" ]
permissive
mbutterick/pollen
d4c9d44838729ac727972eb64d841b3a5104931b
99c43e6ad360f7735ebc9c6e70a08dec5829d64a
refs/heads/master
2023-08-19T06:08:49.719156
2022-07-22T22:26:46
2022-07-22T22:26:46
11,827,835
1,089
93
MIT
2021-11-16T21:00:03
2013-08-01T21:14:01
Racket
UTF-8
Racket
false
false
4,422
scrbl
top.scrbl
#lang scribble/manual @(require scribble/eval pollen/cache pollen/setup (for-label racket (except-in pollen #%module-begin) pollen/setup pollen/tag)) @(define my-eval (make-base-eval)) @(my-eval `(require pollen pollen/setup)) @title{Top} @defmodule[pollen/top] You'll probably never invoke this module directly. But it's implicitly imported into every Pollen markup file. And if you don't know what it does, you might end up surprised by some of the behavior you get. @defform[(#%top . id)]{ In standard Racket, @racket[#%top] is the function of last resort, called when @racket[_id] is not bound to any value. As such, it typically reports a syntax error. @examples[ (code:comment @#,t{Let's call em without defining it}) (em "Bonjour") (code:comment @#,t{(em "Bonjour") is being converted to ((#%top . em) "Bonjour")}) (code:comment @#,t{So calling ((#%top . em) "Bonjour") will give the same result}) ((#%top . em) "Bonjour") ] In the Pollen markup environment, however, this behavior is annoying. Because when you're writing X-expressions, you don't necessarily want to define all your tags ahead of time. So Pollen redefines @racket[#%top]. For convenience, Pollen's version of @racket[#%top] assumes that an undefined tag should just refer to an X-expression beginning with that tag (and uses @racket[default-tag-function] to provide this behavior): @examples[ (code:comment @#,t{Again, let's call em without defining it, but using pollen/top}) (require pollen/top) (em "Bonjour") (code:comment @#,t{(em "Bonjour") is still being converted to ((#%top . em) "Bonjour")}) (code:comment @#,t{But now, ((#%top . em) "Bonjour") gives a different result}) ((#%top . em) "Bonjour") ] The good news is that this behavior means you use any tag you want in your markup without defining it in advance. You can still attach a function to the tag later, which will automatically supersede @racket[#%top]. @examples[ (define (em x) `(span ((style "font-size:100px")) ,x)) (em "Bonjour") ] The bad news is that you'll never get an ``unbound identifier'' error. These unbound identifiers will happily sail through and be converted to tags. @examples[ (require pollen/top) (define (em . xs) `(span ((style "font-size:100px")) ,@xs)) (code:comment @#,t{There's a typo in my tag}) (erm "Bonjour") ] @margin-note{If you prefer the ordinary Racket-style behavior where unbound identifiers raise an error, define @racket[setup:allow-unbound-ids?] in your project to be @racket[#false].} This isn't a bug. It's just a natural consequence of how Pollen's @racket[#%top] works. It can, however, make debugging difficult sometimes. Let's suppose my markup depends on @racket[very-important-function], which I don't import correctly. @examples[ (require pollen/top) (module vif racket/base (define (very-important-function . xs) `(secrets-of-universe ,@xs))) (code:comment @#,t{Forgot to (require 'vif)}) (very-important-function "Bonjour") ] So the undefined-function bug goes unreported. Again, that's not a bug in Pollen — there's just no way for it to tell the difference between an identifier that's deliberately undefined and one that's inadvertently undefined. If you want to guarantee that you're invoking a defined identifier, use @racket[def/c].} @defform[(def/c id)]{Invoke @racket[_id] if it's a defined identifier, otherwise raise an error. This form reverses the behavior of @racket[#%top] (in other words, it restores default Racket behavior). Recall this example from before. In standard Racket, you get an undefined-identifier error. @examples[ (module vif racket/base (define (very-important-function . xs) `(secrets-of-universe ,@xs))) (code:comment @#,t{Forgot to (require 'vif)}) (very-important-function "Bonjour") ] But with @racketmodname[pollen/top], the issue is not treated as an error. @examples[ (require pollen/top) (module vif racket/base (define (very-important-function . xs) `(secrets-of-universe ,@xs))) (code:comment @#,t{Forgot to (require 'vif)}) (very-important-function "Bonjour") ] By adding @racket[def/c], we restore the usual behavior, guaranteeing that we get the defined version of @racket[very-important-function] or nothing. @examples[ (require pollen/top) (module vif racket/base (define (very-important-function . xs) `(secrets-of-universe ,@xs))) (code:comment @#,t{Forgot to (require 'vif)}) ((def/c very-important-function) "Bonjour") ] }
false
2b8a12b2182e815efa29957f867365d7e4228188
2ab75cf02f4f32326516cc5691ad6d15a676ec3b
/video/scribblings/render.scrbl
b367f7771d732920fdbb9c3b587f19ad0b7de3c9
[ "Apache-2.0" ]
permissive
LeifAndersen/racket-video-backup
0edc765c3076f44ae8ea9a4bb04b3c934d1803ef
9ae85bb5d02eb50132a00768c8220eca76a3e78e
refs/heads/master
2021-07-03T19:34:08.935299
2017-05-19T20:14:44
2017-05-19T20:14:44
57,415,017
0
0
null
null
null
null
UTF-8
Racket
false
false
4,110
scrbl
render.scrbl
#lang scribble/manual @;{ Copyright 2016-2017 Leif Andersen Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } @require[scribble/core scribble/example racket/sandbox (except-in pict table) video/init video/private/utils video/private/surface video/render @for-label[(except-in racket/base filter) racket/contract/base racket/set racket/hash (except-in racket/class field) racket/gui/base racket/draw video/init video/base video/core video/render video/player video/init video/lib]] @title{Rendering} @defmodule[video/render] The renderer in this section describes the API for rendering Video files. A simpler interface is to use the @exec{raco video} tool described in @secref["raco-video"]. @section{Render API} @defproc[(render [data video?] [dest (or/c path path-string? #f) #f] [#:dest-filename dest-filename (or/c path-element? string? #f) #f] [#:render-mixin render-mixin (-> (is-a?/c render<%>) (is-a?/c render<%>)) values] [#:profile-name profile-name (or/c string? #f) #f] [#:width width nonnegative-integer? 720] [#:height height nonnegative-integer? 576] [#:start start (or/c nonnegative-integer? #f) #f] [#:end end (or/c nonnegative-integer? #f) #f] [#:fps fps (>=/c 0) 25] [#:speed speed real? #f] [#:timeout timeout boolean? #f]) void?]{ Renders a video object. The given mixin determines what output format the renderer producers.} @section{Render Class} @defclass[render% object% (render<%>)]{ The class used for rendering. By default it outputs the video directly to the screen. Mixins can be used to extend this class to change what it outputs too. @defconstructor[([dest-dir (or/c path? path-string?)] [dest-filename (or/c path-element? string? #f) #f] [prof-name (or/c string? #f) #f] [width nonnegative-integer? 720] [height nonnegative-integer? 576] [fps (>=/c 0) 25])]{ Constructs the Renderer with resolution, fps, and destination values.} @defmethod[(get-fps) (>=/c 0)] @defmethod[(get-profile) (or/c profile? #f)] @defmethod[(setup-profile) void?] @defmethod[(prepare [source video?]) void?] @defmethod[(render) void?] @defmethod[(play) void?]} @;{ @definterface[render<%> (get-fps get-profile setup-profile prepare render play)]{ An interface for the @racket[render%] class. }} @section{Render Mixins} @subsection{JPEG Rendering} @defmodule[video/render/jpg] @defthing[render-mixin (-> (is-a?/c render<%>) (is-a?/c render<%>))] @subsection{PNG Rendering} @defmodule[video/render/png] @defthing[render-mixin (-> (is-a?/c render<%>) (is-a?/c render<%>))] @subsection{XML Rendering} @defmodule[video/render/xml] @defthing[render-mixin (-> (is-a?/c render<%>) (is-a?/c render<%>))] @subsection{List Plugins Rendering} @defmodule[video/render/list] @defthing[render-mixin (-> (is-a?/c render<%>) (is-a?/c render<%>))]{ Rather than outputting any video, this is a special mixin to display the plugins installed for MLT. This module may be removed in the future.}
false
e0e07e50d46b46b9a43eadf0463830a886a113b6
d07380a8836587ff70fdc001e939e232ee202c80
/opencl/c.rkt
4796389e4d968030a1353c34689e3ab39d765614
[]
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
287
rkt
c.rkt
#lang racket/base (require "c/types.rkt" ;; XXX doc these "c/constants.rkt" "c/include/cl.rkt" "c/4.rkt" "c/5.rkt") (provide (all-from-out "c/types.rkt" ;; XXX doc these "c/constants.rkt" "c/include/cl.rkt" "c/4.rkt" "c/5.rkt"))
false
313b85d96b5b0c66385d473b66b27f83fe155fa6
f05fb2cbe45417a0017c71320608d6454681d077
/fontproof/info.rkt
0abd545c62a58e56bc10724a47d7f3e1b923d22f
[ "MIT" ]
permissive
mbutterick/quad
dcca8d99aaacaea274d3636e9f02e75251664d9c
9c6e450b0429ad535edf9480a4b76e5c23161ec0
refs/heads/master
2022-02-01T17:44:32.904785
2022-01-08T15:52:50
2022-01-08T15:52:50
26,788,024
142
9
MIT
2020-07-07T01:54:00
2014-11-18T02:21:39
Racket
UTF-8
Racket
false
false
113
rkt
info.rkt
#lang info (define raco-commands '(("fontproof" (submod fontproof/command raco) "issue fontproof command" #f)))
false
dcfa7c29e00f5783a06e299c04fdc51cfe1c0b14
a6c4b839754b01e1b94a70ec558b631313c9df34
/semi-read-syntax/semi-read-syntax.ss
bb0beb94b2e8de1783b949e92fac8c5fc3e31e9d
[]
no_license
dyoo/divascheme
b6a05f625397670b179a51e13d3cd9aac0b2e7d5
f1a8d82989115e0d0714ce8fdbd452487de12535
refs/heads/master
2021-01-17T09:39:14.664809
2008-08-19T01:46:33
2008-08-19T01:46:33
3,205,925
0
1
null
2018-01-22T01:27:19
2012-01-18T04:11:36
Scheme
UTF-8
Racket
false
false
8,224
ss
semi-read-syntax.ss
(module semi-read-syntax mzscheme (require (lib "lex.ss" "parser-tools") (lib "etc.ss") (lib "contract.ss") (lib "list.ss") (lib "42.ss" "srfi") (lib "port.ss") (only (lib "1.ss" "srfi") take) (only (lib "13.ss" "srfi") string-prefix?) "../utilities.ss" "lexer.ss") ;; A parser for DivaScheme that tries to maintain some of the semi-structure ;; based on comments, dots, and other things that read-syntax ;; normally munges. ;; There are two functions here because ports based on make-pipe are twice as ;; fast as those constructed with make-pipe-with-special, according to ;; my measurements. (provide/contract [semi-read-syntax-list (any/c input-port? . -> . (listof syntax?))] [semi-read-syntax-list/no-specials (any/c input-port? . -> . (listof syntax?))]) (define (semi-read-syntax-list source ip) (-semi-read-syntax-list source ip make-pipe-with-specials)) (define (semi-read-syntax-list/no-specials source ip) (-semi-read-syntax-list source ip make-pipe)) (define (-semi-read-syntax-list source ip make-pipe-f) (local [(define (make-counting-pipe) (let-values ([(ip op) (make-pipe-f #f source source)]) (port-count-lines! ip) (values ip op))) (define-values (pipe-ip pipe-op) (make-counting-pipe)) (define translation-table (feed-tokens ip pipe-op))] (parameterize ([read-accept-reader #t]) (let loop ([stx (read-syntax source pipe-ip)]) (cond [(eof-object? stx) '()] [else (cons (repair-stx stx translation-table) (loop (read-syntax source pipe-ip)))]))))) (define (repair-stx stx translation-table) (local [(define (was-translated? stx) (and (hash-table-get translation-table (syntax-position stx) #f) #t)) (define (untranslate stx translation-table) (local ((define real-value (hash-table-get translation-table (syntax-position stx)))) (cond [(string? real-value) (remake-stx (string->symbol real-value))] [(syntax? real-value) (remake-stx (syntax-object->datum real-value))] [else stx]))) (define (remake-stx datum) (datum->syntax-object stx datum stx stx)) (define (repair-list) (define (repair-list/fast items unchanged) (if (empty? items) stx (let ([sub (repair-stx (first items) translation-table)]) (if (eq? sub (first items)) (repair-list/fast (rest items) (add1 unchanged)) (repair-list/slow (rest items) (cons sub (reverse (take (syntax->list stx) unchanged)))))))) (define (repair-list/slow items result) (if (empty? items) (remake-stx (reverse result)) (repair-list/slow (rest items) (cons (repair-stx (first items) translation-table) result)))) (repair-list/fast (syntax->list stx) 0))] [let ((result (syntax-case stx () [(quote-1 (quote-2 datum)) (was-translated? stx) (remake-stx (list (repair-stx #'datum translation-table)))] [(item ...) (repair-list)] [#(item ...) (remake-stx (list->vector (map (lambda (stx) (repair-stx stx translation-table)) (vector->list (syntax-e stx)))))] [(first . rest) (remake-stx (cons (repair-stx #'first translation-table) (repair-stx #'rest translation-table)))] [_ (and (symbol? (syntax-e stx)) (was-translated? stx)) (untranslate stx translation-table)] [else stx]))) result])) ;; feed-tokens: input-port output-port -> (hash-table-of number string) ;; ;; Writes out tokens from the input-port into the output-port, translating ;; troublesome ones (dots, comments) into a form that syntax-object->datum will ;; be happy with. ;; ;; Returns a hash table mapping positions to places where we had to do this ;; patching to the contents of the input port. (define (feed-tokens from-ip to-op) (define ht (make-hash-table 'equal)) (let loop () (local [(define pos-token (plt-lexer from-ip)) (define token (position-token-token pos-token)) (define type (token-name token)) (define val (token-value token))] ;; Does weird prefix kluding (define (do-weird-prefix-kludge) (define (add-padding! padding-char len) (hash-table-put! ht (position-offset (position-token-start-pos pos-token)) val) (display (make-string len padding-char) to-op) (when (> (string-length val) len) (display (substring val len) to-op))) (cond [(or (string-prefix? "#;" val) (string-prefix? "#s" val)) (add-padding! #\' 2)] [(string-prefix? "#hasheq" val) (add-padding! #\X 7)] [(string-prefix? "#hash" val) (add-padding! #\X 5)] [else (display val to-op)])) (cond [(eq? type 'end) (close-output-port to-op)] [else (case type [(atom) (cond [(equal? val ".") (hash-table-put! ht (position-offset (position-token-start-pos pos-token)) val) (display "X" to-op)] [(string-prefix? ";" val) (hash-table-put! ht (position-offset (position-token-start-pos pos-token)) val) (do-ec (:range x (string-length val)) (display "X" to-op))] [(string-prefix? "#|" val) (hash-table-put! ht (position-offset (position-token-start-pos pos-token)) val) (display "\"X" to-op) (display (string-convert-non-control-chars (substring val 2 (- (string-length val) 2)) #\X) to-op) (display "X\"" to-op) ] [(string-prefix? "#reader" val) (hash-table-put! ht (position-offset (position-token-start-pos pos-token)) val) (display "!!!!!!!" to-op)] [(string-prefix? "#lang" val) (hash-table-put! ht (position-offset (position-token-start-pos pos-token)) val) (display "!!!!!" to-op)] [else (display val to-op)])] [(space) (display val to-op)] [(special-atom) (hash-table-put! ht (position-offset (position-token-start-pos pos-token)) val) (display "X" to-op)] [(prefix quoter-prefix) (do-weird-prefix-kludge)] [(suffix) (display val to-op)]) (loop)]))) ht))
false
56665ffa006eb9fadf1558529927fb1ae52acd82
b08b7e3160ae9947b6046123acad8f59152375c3
/Programming Language Detection/Experiment-2/Dataset/Train/Racket/yin-and-yang.rkt
322bfb6e48905a41659ac96e0585ef2ee0eb15db
[]
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
541
rkt
yin-and-yang.rkt
#lang racket (require slideshow/pict) (define (yin-yang d) (define base (hc-append (inset/clip (circle d) 0 0 (- (/ d 2)) 0) (inset/clip (disk d) (- (/ d 2)) 0 0 0))) (define with-top (ct-superimpose base (cc-superimpose (colorize (disk (/ d 2)) "white") (disk (/ d 8))))) (define with-bottom (cb-superimpose with-top (cc-superimpose (disk (/ d 2)) (colorize (disk (/ d 8)) "white")))) (cc-superimpose with-bottom (circle d))) (yin-yang 200)
false
7a17db00e4d65869ebedf98d02fb619f703ec4d1
c7ba8b5c0b46ba4b467f0c00e9453b6a0828d6b3
/games/cell-game-renderer.rkt
798c78c0f6d9e2cdcecc07a44c9a5c83e6edd40c
[]
no_license
thoughtstem/ai-test
8ac9b77d550ffc42e37c25da8c7114de9488a8bc
a94139b7fffd2228f3f0df79dc72edaf93bb550b
refs/heads/master
2020-04-03T04:37:56.382265
2018-10-29T03:42:20
2018-10-29T03:42:20
155,018,955
0
0
null
null
null
null
UTF-8
Racket
false
false
1,041
rkt
cell-game-renderer.rkt
#lang racket (provide render) (require "../lang.rkt" 2htdp/image posn) (define (render s) (match-define (state gs ms mgs) s) (define g (first gs)) (define m (first ms)) (match-define (mind<->game gi mi p i) (first mgs)) (beside (render-game g) (above (render-channel p) (render-channel i)) (render-mind m))) (define (render-game g) (define s (game-state g)) (scale 20 (place-image (circle 1 'solid 'red) (posn-x s) (posn-y s) (square 10 'solid 'black)))) (define (render-mind m) (define last-seen (func-out (mind-state m))) (overlay (text (if last-seen (~a (mind-id m) " : " last-seen) "#f") 18 'white) (square 200 'solid 'black))) (define (render-channel p) (define o (channel-out p)) (overlay (scale 0.5 (cond [(game? o) (render-game o)] [(mind? o) (render-mind o)] [else (text (~a o) 24 'black)])) (square 200 'solid 'gray)))
false
920992571f52d3e8b22b3be476f3066f55a15062
3a29f8f1166d9c0a20e448693f07e33c7872b936
/Racket/isPrime.rkt
f8a6bb49e93fa9a825be378c17e70570aa90a84f
[]
no_license
yordankapp/functional-programming-uni
1b5027f88fad95aacd15bb295f6a91fa8b83f472
d2495345d9600de982797dc357ce1423743a75d0
refs/heads/master
2020-03-21T07:44:34.967585
2018-06-22T12:34:48
2018-06-22T12:34:48
138,297,559
0
0
null
null
null
null
UTF-8
Racket
false
false
677
rkt
isPrime.rkt
#lang sicp (define (smallest_divisor n) (find_divisor n 2)) (define (find_divisor n test_divisor) (cond ((> (square test_divisor) n) n) ((divides? test_divisor n) test_divisor) (else (find_divisor n (+ test_divisor 1))) ) ) (define (square x) (* x x)) (define (divides? a b) (= (remainder b a) 0)) (define (prime? n) (= n (smallest_divisor n))) (prime? 11) ;;#t (prime? 6) ;;#f (define (prime2? n) ;; not ok (define (helper a n) (cond ((> a (sqrt n)) #t ) ( (= (remainder n a) 0) #f) ( else(helper (+ a 1) n)))) ( if(= a 1) #f (helper 2 n)) ) (prime2? 1)
false
edd43086a97939db84d2922dde57c0b3f5d25071
307e7ce615ea3de155d645c12a63c4deb8817f6f
/dynamic-racket/lang/reader.rkt
884281b4bed33de1ae6e958196d4bf3a883c138c
[]
no_license
leanthonyrn/srcc
be059cf94494c3833f6daf93d625b2292bb17a84
1f1f41c6ed7b402fdde42e887d339fe4708066b0
refs/heads/master
2016-09-06T00:16:43.379168
2011-07-06T10:51:57
2011-07-06T10:51:57
32,238,319
0
0
null
null
null
null
UTF-8
Racket
false
false
1,226
rkt
reader.rkt
#| Summary: This file is part of dynamic-racket. License: Copyright (c) 2011 Mikhail Mosienko <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |# #lang s-exp syntax/module-reader dynamic-racket/main
false
f4a7c34370adf36bdddec2ad0cda576a8398b90d
29e930c187cd502c90ca67a94b721839a5b1e5dd
/tr-pfds-nocheck/pfds/scribblings/helper.rkt
1ae38d595cb4f3b0334151d9646494b98d08ca13
[]
no_license
michaelballantyne/typed-racket-performance
edb5d3780ecf185ef46c01a2287a32269d3d0858
b9421a0a7051a9caf9ef225c56ab3a8535e60692
refs/heads/master
2021-01-16T19:20:04.480743
2015-05-01T16:03:25
2015-05-01T16:03:25
34,907,618
2
2
null
2015-05-01T17:59:29
2015-05-01T14:51:51
Racket
UTF-8
Racket
false
false
637
rkt
helper.rkt
#lang at-exp racket/base (require scribble/manual (for-label racket/base) scribble/eval) (define racket-map @racket[map]) (define racket-foldl @racket[foldl]) (define racket-foldr @racket[foldr]) (define racket-filter @racket[filter]) (define racket-remove @racket[remove]) (define racket-andmap @racket[andmap]) (define racket-ormap @racket[ormap]) (define racket-build-list @racket[build-list]) (define racket-make-list @racket[make-list]) (provide racket-map racket-foldl racket-foldr racket-filter racket-remove racket-andmap racket-ormap racket-build-list racket-make-list make-base-eval examples close-eval)
false
abd7c60f729e3e331131435e95341756be3007f7
e0ea6503b51c4742398ca00e3ee040671d53059f
/emulator/pmp.rkt
4aefa71630c6163f285c6e95196a2700118fd35a
[]
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
8,902
rkt
pmp.rkt
#lang rosette/safe (require (only-in racket/base for in-range)) (require syntax/parse/define) (require (only-in racket/base build-vector)) ;; Macros to Build PMP (define-simple-macro (fresh-symbolic name type) (let () (define-symbolic* name type) name)) (define-simple-macro (make-pmpaddrs n:expr) (build-vector n (lambda (i) (define p (make-pmpaddr)) p))) (define-simple-macro (make-pmpcfgs n:expr) (build-vector n (lambda (i) (define p (make-pmpcfg)) p))) ;; Structs to Build PMP (struct pmp (pmpcfgs pmpaddrs numimplemented) #:mutable #:transparent) (provide (struct-out pmp)) ; pmpcfg struct (struct pmpcfg (value settings) #:mutable #:transparent) (provide (struct-out pmpcfg)) ; pmpaddr struct (struct pmpaddr (value startaddr endaddr) #:mutable #:transparent) (provide (struct-out pmpaddr)) ; pmpcfg settings setting (struct pmpcfg-setting (R W X A L) #:mutable #:transparent) (provide (struct-out pmpcfg-setting)) ;; Helper Functions to Build PMP Structs ; Make a vector of pmpcfg settings (define-simple-macro (make-pmpcfg-settings n:expr) (build-vector n (lambda (i) (define p (make-pmpcfg-setting)) p))) (define (make-pmp) (define numimplemented 0) (pmp (make-pmpcfgs 2) (make-pmpaddrs 16) numimplemented)) (provide make-pmp) (define (make-pmpcfg-setting) (pmpcfg-setting (bv 0 1) (bv 0 1) (bv 0 1) (bv 0 2) (bv 0 1))) (define (make-pmpcfg) (pmpcfg (bv 0 64) (make-pmpcfg-settings 8))) (define (make-pmpaddr) (pmpaddr (bv 0 64) (bv 0 64) (bv 0 64))) ;; PMP utilities for decoding registers and checking (define (get-pmpicfg-setting pmpcfg i) (vector-ref (pmpcfg-settings pmpcfg) i)) (provide get-pmpicfg-setting) (define (ctz64 val) ; If bv with all zeros return 0, else ctz (cond [(bveq val (bv 0 64)) 0] [else (let helper ([i 0]) (if (bveq (extract i i val) (bv 1 1)) i (helper (+ 1 i))))])) (provide ctz64) ; TODO: Missing L bit for locking? ; Decode R W X A settings for cfg register (define (pmp-decode-cfg val idx) (define base (* idx 8)) (define R (extract base base val)) (define W (extract (+ base 1) (+ base 1) val)) (define X (extract (+ base 2) (+ base 2) val)) (define A (extract (+ base 4) (+ base 3) val)) (define L (extract (+ base 7) (+ base 7) val)) (pmpcfg-setting R W X A L)) (provide pmp-decode-cfg) ; Check if pmp-setting is implemented (define (pmp-is-implemented? pmp-setting) (bveq (pmpcfg-setting-A pmp-setting) (bv 0 2))) (provide pmp-is-implemented?) ; Check if pmp-setting is locked (define (pmp-is-locked? pmp-setting) (bveq (pmpcfg-setting-L pmp-setting) (bv 1 1))) (provide pmp-is-locked?) ; Decode start addr and end addr for cfg register (define (pmp-decode-napot val) (define t1 (ctz64 (bvnot val))) (define base (bvshl (bvand val (bvnot (bvsub (bvshl (bv 1 64) (bv t1 64)) (bv 1 64)))) (bv 2 64))) (define range (bvsub (bvshl (bv 1 64) (bvadd (bv t1 64) (bv 3 64))) (bv 1 64))) (list base range)) (provide pmp-decode-napot) (define (pmp-encode-napot base size) (define napot_size (bvsub (bvudiv size (bv 2 64)) (bv 1 64))) (define pmp_addr (bvlshr (bvadd base napot_size) (bv 2 64))) pmp_addr) (define (pmp-none-impl? pmp) (equal? (pmp-numimplemented pmp) 0)) (provide pmp-none-impl?) (define (pmp-pmpaddri pmp i) (vector-ref (pmp-pmpaddrs pmp) i)) (provide pmp-pmpaddri) (define (pmp-pmpcfgi pmp i) (vector-ref (pmp-pmpcfgs pmp) i)) (provide pmp-pmpcfgi) (define (get-pmpaddri-setting pmp i) (let ([pmpcfg0 (pmp-pmpcfgi pmp 0)] [pmpcfg2 (pmp-pmpcfgi pmp 1)]) ; Iterate through each pmpaddr and break at first matching (if (< i 8) (get-pmpicfg-setting pmpcfg0 i) (get-pmpicfg-setting pmpcfg2 (- i 8))))) (define (set-pmpaddri! pmp i val) (define setting (get-pmpaddri-setting pmp i)) (when (not (pmp-is-locked? setting)) ; Set the value for the pmp first (set-pmpaddr-value! (pmp-pmpaddri pmp i) val) ; Decode the value (define pmp_bounds (pmp-decode-napot val)) (define pmp_start (list-ref pmp_bounds 0)) (define pmp_end (bvadd (list-ref pmp_bounds 0) (list-ref pmp_bounds 1))) (set-pmpaddr-startaddr! (pmp-pmpaddri pmp i) pmp_start) (set-pmpaddr-endaddr! (pmp-pmpaddri pmp i) pmp_end))) (provide set-pmpaddri!) (define (set-pmpcfgi! pmp i val) ; (set-pmpcfg-value! (pmp-pmpcfgi pmp i) val) (define pmpcfgi (pmp-pmpcfgi pmp i)) (for ([id (in-range 8)]) (define old_settings (get-pmpicfg-setting pmpcfgi id)) (when (not (pmp-is-locked? old_settings)) (define new_settings (pmp-decode-cfg val id)) ; Adjust Number of Implemented PMPs (when (and (pmp-is-implemented? old_settings) (not (pmp-is-implemented? new_settings))) (set-pmp-numimplemented! pmp (add1 (pmp-numimplemented pmp)))) (when (and (not (pmp-is-implemented? old_settings)) (pmp-is-implemented? new_settings)) (set-pmp-numimplemented! pmp (sub1 (pmp-numimplemented pmp)))) ; Update pmpcfg value for pmp(id)cfg(i) (define start (* id 8)) (define end (* (add1 id) 8)) (define original_value (pmpcfg-value pmpcfgi)) (set-pmpcfg-value! pmpcfgi ; Determine new value based on which part of the bitvector we are modifying ; since the extraction is a little bit weird (can't extract size 0) (cond [(equal? start 0) (concat (extract 63 end original_value) (extract (sub1 end) start val))] [(equal? end 64) (concat (extract (sub1 end) start val) (extract (sub1 start) 0 original_value))] [else (concat (extract 63 end original_value) (extract (sub1 end) start val) (extract (sub1 start) 0 original_value))])) ; Update settings (vector-set! (pmpcfg-settings pmpcfgi) id new_settings)))) (provide set-pmpcfgi!) ; PMP test address ranging from saddr to eaddr (define (pmp-check pmp mode saddr eaddr) (if (pmp-none-impl? pmp) #t (let ([legal null] [pmpcfg0 (pmp-pmpcfgi pmp 0)] [pmpcfg2 (pmp-pmpcfgi pmp 1)]) ; Iterate through each pmpaddr and break at first matching (for ([i (in-range 16)]) #:break (not (equal? legal null)) (define setting (if (< i 8) (get-pmpicfg-setting pmpcfg0 i) (get-pmpicfg-setting pmpcfg2 (- i 8)))) (define R (pmpcfg-setting-R setting)) (define W (pmpcfg-setting-W setting)) (define X (pmpcfg-setting-X setting)) (define A (pmpcfg-setting-A setting)) (define L (pmpcfg-setting-L setting)) ; For now we only implement A = 3 (NAPOT) (define bounds (cond [(bveq A (bv 3 2)) (let* ([pmpaddr (pmp-pmpaddri pmp i)] [pmp_start (pmpaddr-startaddr pmpaddr)] [pmp_end (pmpaddr-endaddr pmpaddr)] ; Test the proper bounds, #t means allow access, #f means disallow access [slegal (bv-between saddr pmp_start pmp_end)] [elegal (bv-between eaddr pmp_start pmp_end)]) (list slegal elegal))] [else (list #f #f)])) (define slegal (list-ref bounds 0)) (define elegal (list-ref bounds 1)) ; Check saddr and eaddr match the pmpaddri range (when (and slegal elegal) ; Check if pmpaddri is locked (if (not (pmp-is-locked? setting)) ; Check machine mode (cond [(bveq mode (bv 1 3)) (set! legal #t)] [(bveq mode (bv 0 3)) ; TODO: actually check what the access type is (set! legal (and (bveq R (bv 1 1)) (bveq W (bv 1 1)) (bveq X (bv 1 1))))] [else ; TODO: implement other mode support (set! legal #f)]) ; TODO: Implement locked variant of access, for now just return false (no access) (set! legal #f)))) (when (null? legal) (set! legal (bveq mode (bv 1 3)))) legal))) (provide pmp-check) ; Check if bv1 satisfies bv2 <= bv1 <= bv3 (define (bv-between bv1 bv2 bv3) (and (bvule bv2 bv1) (bvule bv1 bv3))) (provide bv-between) ; (printf "base: #x80000000, size: #x20000 ~a~n" (pmp-encode-napot (bv #x80020000 64) (bv #x20000 64))) ; (printf "decoding #x: ~a~n" (pmp-decode-napot (bv #x7fffffffffffffff 64))) ; (printf "decoding #x: ~a~n" (pmp-decode-napot (bv #x00000000200003ff 64)))
false
6f243b7812fcefbbe599a6c46b1266ccf049e24a
d89d5fee583c2b5c93bf663cdf761a7026cae259
/http123-lib/private/http2.rkt
9c575ef2f7af88a38d810b3b660f1fe8f2a5aedc
[]
no_license
DavidAlphaFox/racket-http123
9f109c53c938e783cd88db7b4055ebb502d4d80a
8dc1e79f3788994ac6866c3c5e53b6ccb95887f2
refs/heads/master
2023-06-24T06:31:54.924609
2021-07-22T10:38:07
2021-07-22T10:38:07
null
0
0
null
null
null
null
UTF-8
Racket
false
false
22,929
rkt
http2.rkt
;; Copyright 2021 Ryan Culpepper ;; SPDX-License-Identifier: Apache-2.0 #lang racket/base (require racket/class racket/match binaryio/reader scramble/evt "interfaces.rkt" "hpack.rkt" "h2-frame.rkt" "h2-stream.rkt") (provide (all-defined-out)) ;; FIXME/TODO: ;; - add way(s) to shut down connection, including ports ;; - abandon waits for server to send EOF ;; - user could use custodian ;; - implement HPACK policies, limits ;; - HPACK: ;; - be smarter about indexing (eg, don't index huge value that just ;; evicts everything in the table) ;; - reorder fields to enable indexing? ;; - configuration ;; - various limits ;; - flow-control (eg, init in-flow window) ;; - timeouts ;; - handle CONNECT ? ;; References: ;; - https://tools.ietf.org/html/rfc7540 (define http2-alpn-protocol #"h2") (define http2-client-preface #"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n") (define INIT-TARGET-IN-FLOW-WINDOW (expt 2 20)) ;; FIXME: config? ;; FIXME: config? ok defaults? (define TIMEOUT-RECV-NONE-MS 10e3) ;; time after recv to send goaway when no open streams (define TIMEOUT-RECV-STREAMS-MS 10e3) ;; time after recv to send ping when open streams (define TIMEOUT-PING-MS 20e3) ;; time after recv to send goaway when open streams (define TIMEOUT-CLOSED-MS 2e3) ;; time after sending goaway to close ports (define standard-init-config (hasheq 'header-table-size 4096 'enable-push 1 'max-concurrent-streams +inf.0 'initial-window-size INIT-FLOW-WINDOW 'max-frame-size (expt 2 14) 'max-header-list-size +inf.0)) (define init-config (hash-set* standard-init-config 'enable-push 0)) ;; ============================================================ (define counter 0) (define http2-actual-connection% (class* object% (http-actual-connection<%>) (init-field in out parent) (init [my-new-config init-config]) (super-new) (field [ID (string-upcase (format "#~X" (begin0 counter (set! counter (add1 counter)))))]) (define br (make-binary-reader in)) (define config standard-init-config) ;; Config of server (define my-config standard-init-config) ;; Config of client, acked by server (define my-configs/awaiting-ack null) ;; (Listof Config), oldest-first (define/public (get-ID) ID) (define/public (get-config) config) (define/public (get-my-config) my-config) (define/public (get-config-value key) (hash-ref config key)) ;; Connection-wide limit on flow-controlled {sends, receives}. ;; Flow control is only applied to DATA frames (see 6.9). (define out-flow-window INIT-FLOW-WINDOW) (define in-flow-window INIT-FLOW-WINDOW) ;; FIXME: resize on SETTINGS receive or ack? (define reading-dt (make-dtable (hash-ref config 'header-table-size))) (define sending-dt (make-dtable (hash-ref config 'header-table-size))) (define/public (get-sending-dt) sending-dt) ;; is-closed? : (U #f 'by-goaway 'by-error 'user-abandoned 'EOF) ;; Value is #f if allowed to start new streams; symbol if not allowed. (define is-closed? #f) (define/public (open?) (not is-closed?)) (define/public (closed?) (not (open?))) (define/private (set-closed! reason [timeout? #t]) (unless is-closed? (set! is-closed? reason) (when timeout? (start-close-timeout!)))) (define/private (close-ports) (break-thread reader-thread) (close-input-port in) (close-output-port out) (log-http2-debug "~a closed ports and stopped reader thread" ID)) ;; ---------------------------------------- (define/public (queue-frame fr) (log-http2-debug "~a --> ~a" ID (parameterize ((error-print-width 60)) (format "~e" fr))) (adjust-out-flow-window (- (frame-fc-length fr))) (write-frame out fr)) (define/public (queue-frames frs) (for ([fr (in-list frs)]) (queue-frame fr))) (define/public (flush-frames) (unless (port-closed? out) (flush-output out))) (define/public (connection-error errorcode [comment #f] #:debug [debug #""]) (log-http2-debug "~a connection-error ~s, ~s" ID errorcode comment) (queue-frame (frame type:GOAWAY 0 0 (fp:goaway last-server-streamid errorcode debug))) (flush-frames) (set-closed! 'by-error) (for ([(streamid stream) (in-hash stream-table)]) (send stream handle-ua-connection-error errorcode comment)) (raise 'connection-error)) ;; ---------------------------------------- ;; stream-table : Hash[Nat => stream%] ;; If a streamid has no entry in stream-table and it is less than ;; or equal to last-{s,c}-streamid, it is closed. (define stream-table (make-hasheqv)) (define streams-changed? #f) (define last-server-streamid 0) ;; Nat -- last streamid used by server (define last-client-streamid 1) ;; Nat -- last streamid used by client (define/public (get-stream streamid [fail-ok? #f]) (cond [(zero? streamid) (connection-error error:PROTOCOL_ERROR "reference to stream 0")] [(hash-ref stream-table streamid #f) => values] [(and (streamid-from-server? streamid) (> streamid last-server-streamid)) (make-stream streamid #f #f)] [fail-ok? #f] [else (connection-error error:STREAM_CLOSED "unknown stream")])) (define/public (remove-stream streamid) (set! streams-changed? #t) (hash-remove! stream-table streamid)) (define/public (new-client-stream req send-req?) (and (not is-closed?) (make-stream (+ last-client-streamid 2) req send-req?))) (define/public (make-stream streamid req send-req?) (define stream (new http2-stream% (conn this) (streamid streamid) (req req) (send-req? send-req?))) (set! streams-changed? #t) (hash-set! stream-table streamid stream) (cond [(streamid-from-client? streamid) (set! last-client-streamid streamid)] [(streamid-from-server? streamid) (set! last-server-streamid streamid)]) stream) ;; ---------------------------------------- ;; Handling frames received from server (define/private (handle-frame-or-other v) (match v [(? frame? fr) (update-received-time!) (handle-frame fr) (after-handle-frame)] ['EOF (set-closed! 'EOF) (close-ports) (for ([(streamid stream) (in-hash stream-table)]) (send stream handle-eof))] [(? procedure?) (v)])) (define in-continue-frames null) ;; (Listof Frame), reversed (define/private (handle-frame fr) (cond [(pair? in-continue-frames) (define streamid (frame-streamid (car in-continue-frames))) (match fr [(frame (== type:CONTINUATION) flags (== streamid) payload) (cond [(flags-has? flags flag:END_HEADERS) (define frs (reverse (cons fr in-continue-frames))) (set! in-continue-frames null) (handle-multipart-frames frs)] [else (set! in-continue-frames (cons fr in-continue-frames))])] [_ (connection-error error:PROTOCOL_ERROR "expected CONTINUATION frame")])] [else (handle-frame* fr)])) (define/private (handle-multipart-frames frs) (define (get-header streamid first-headerbf) (define rest-headerbfs (for/list ([fr (in-list (cdr frs))]) (fp:continuation-headerbf (frame-payload fr)))) (define headerb (apply bytes-append first-headerbf rest-headerbfs)) (with-handler (lambda (e) (send (get-stream streamid) set-received! 'yes) (connection-error error:COMPRESSION_ERROR "error decoding header")) (decode-header headerb reading-dt))) (match (car frs) [(frame (== type:HEADERS) flags streamid (fp:headers padlen streamdep weight headerbf)) (define header (get-header streamid headerbf)) (send (get-stream streamid) handle-headers-payload flags (fp:headers padlen streamdep weight header))] [(frame (== type:PUSH_PROMISE) flags streamid (fp:push_promise padlen promised-streamid headerbf)) (define header (get-header streamid headerbf)) (send (get-stream streamid) handle-push_promise-payload flags (fp:push_promise padlen promised-streamid header))])) (define/private (handle-frame* fr) (match fr [(frame type flags streamid payload) (define (stream) (get-stream streamid)) (define (check-stream-zero) (unless (= streamid 0) (connection-error error:PROTOCOL_ERROR "requires stream 0"))) (define (check-stream-nonzero) (when (= streamid 0) (connection-error error:PROTOCOL_ERROR "reference to stream 0"))) (match type [(== type:DATA) (check-stream-nonzero) (adjust-in-flow-window (- (frame-fc-length fr))) (send (stream) handle-data-payload flags payload)] [(== type:HEADERS) (check-stream-nonzero) (cond [(flags-has? flags flag:END_HEADERS) (handle-multipart-frames (list fr))] [else (set! in-continue-frames (list fr))])] [(== type:PRIORITY) (check-stream-nonzero) (send (stream) handle-priority-payload payload)] [(== type:RST_STREAM) (match-define (fp:rst_stream errorcode) payload) (check-stream-nonzero) (send (stream) handle-rst_stream errorcode)] [(== type:SETTINGS) (check-stream-zero) (match-define (fp:settings settings) payload) (cond [(flags-has? flags flag:ACK) (unless (null? settings) (connection-error error:FRAME_SIZE_ERROR "non-empty SETTINGS ack")) (unless (pair? my-configs/awaiting-ack) (connection-error error:PROTOCOL_ERROR "unexpected SETTINGS ack")) (set! my-config (car my-configs/awaiting-ack)) (set! my-configs/awaiting-ack (cdr my-configs/awaiting-ack))] [else (handle-settings settings)])] [(== type:PUSH_PROMISE) (check-stream-nonzero) (when (zero? (hash-ref my-config 'enable-push)) (connection-error error:PROTOCOL_ERROR "push not enabled")) (cond [(flags-has? flags flag:END_HEADERS) (handle-multipart-frames (list fr))] [else (set! in-continue-frames (list fr))])] [(== type:PING) (check-stream-zero) (unless (flags-has? flags flag:ACK) (queue-frame (frame type:PING flag:ACK 0 payload)) (flush-frames))] [(== type:GOAWAY) (check-stream-zero) (match-define (fp:goaway last-streamid errorcode debug) payload) ;; If last-streamid=2^31-1 and errorcode = NO_ERROR, it is probably ;; a timeout warning, and it will (proabably) be followed by another ;; GOAWAY with a more specific last-streamid. ;; Note: GOAWAY does not close existing streams! (<= last-streamid) (for ([(streamid stream) (in-hash stream-table)] #:when (> streamid last-streamid)) (send stream handle-goaway last-streamid errorcode debug)) (set-closed! 'by-goaway)] [(== type:WINDOW_UPDATE) (match-define (fp:window_update increment) payload) (when (zero? increment) (connection-error error:PROTOCOL_ERROR "zero increment")) (cond [(zero? streamid) (handle-connection-window_update flags increment)] [else (send (stream) handle-window_update flags increment)])] [(== type:CONTINUATION) (connection-error error:PROTOCOL_ERROR "unexpected CONTINUATION frame")] [_ ;; Ignore unknown frames, per ??. (void)])])) (define/private (handle-settings settings) (define new-config (for/fold ([h config]) ([s (in-list settings)]) (match-define (setting key value) s) (case key [(enable-push) (unless (memv value '(0 1)) (connection-error error:PROTOCOL_ERROR "bad enable_push value"))] [(initial-window-size) (unless (< value FLOW-WINDOW-BOUND) (connection-error error:FLOW_CONTROL_ERROR "window too large")) (define delta (- value (hash-ref h 'initial-window-size))) (for ([(streamid stream) (in-hash stream-table)]) (send stream adjust-out-flow-window delta))]) (hash-set h key value))) (set! config new-config) (queue-frame (frame type:SETTINGS flag:ACK 0 (fp:settings null)))) (define/private (handle-connection-window_update flags delta) (adjust-out-flow-window delta)) (define/private (after-handle-frame) (define target-in-flow-window (get-target-in-flow-window)) (when (< in-flow-window target-in-flow-window) (define delta (- target-in-flow-window in-flow-window)) (define max-frame-size (hash-ref my-config 'max-frame-size)) ;; Only increase window when the difference w/ target is significant. (when (or (>= delta (* 2 max-frame-size)) (< (* 2 in-flow-window) target-in-flow-window)) (queue-frame (frame type:WINDOW_UPDATE 0 0 (fp:window_update delta))) (adjust-in-flow-window delta)))) ;; ------------------------------------------------------------ ;; Flow control ;; The out-flow window is determined by the server. (define/public (get-out-flow-window) out-flow-window) ;; The in-flow window targets a constant. See after-handle-frame. (define/private (get-target-in-flow-window) INIT-TARGET-IN-FLOW-WINDOW) ;; Out-flow window is decreased by queue-frame (on DATA send) and ;; increased by handle-connection-window_update. (define/private (adjust-out-flow-window delta) ;; FIXME: detect negative (set! out-flow-window (+ out-flow-window delta)) (when (positive? delta) ;; avoids loop w/ queue-frame (unless (< out-flow-window FLOW-WINDOW-BOUND) (connection-error error:FLOW_CONTROL_ERROR "window too large")))) ;; In-flow window is decreased by handle-frame* (DATA case), ;; increased by after-handle-frame. (define/private (adjust-in-flow-window delta) (set! in-flow-window (+ in-flow-window delta)) (unless (< in-flow-window FLOW-WINDOW-BOUND) (connection-error error:FLOW_CONTROL_ERROR "window too large"))) ;; ------------------------------------------------------------ ;; Timeouts (define timeout-base-ms (current-milliseconds)) (define timeout-mode 'recv) ;; 'recv | 'ping | 'closed (define/private (start-close-timeout!) (set! timeout-mode 'closed) (set! timeout-base-ms (current-milliseconds))) (define/private (update-received-time!) (case timeout-mode [(recv ping) (set! timeout-base-ms (current-milliseconds)) (unless (eq? timeout-mode 'recv) (set! timeout-mode 'recv))] [(closed) (void)])) (define/private (get-timeout-evt) (define mode timeout-mode) (wrap-evt (alarm-evt (+ timeout-base-ms (case mode [(recv) (if (zero? (hash-count stream-table)) TIMEOUT-RECV-NONE-MS TIMEOUT-RECV-STREAMS-MS)] [(ping) TIMEOUT-PING-MS] [(closed) TIMEOUT-CLOSED-MS]))) (lambda (_) (handle-timeout mode)))) (define/private (handle-timeout mode) (case mode [(recv) (cond [(zero? (hash-count stream-table)) (log-http2-debug "~a timeout, abandoning connection" ID) (set-closed! 'timeout) (send-goaway)] [else (log-http2-debug "~a timeout, sending PING" ID) (queue-frame (frame type:PING 0 0 (fp:ping (make-bytes 8 0)))) (set! timeout-mode 'ping)])] [(ping) (log-http2-debug "~a timeout (no response to PING), abandoning connection" ID) (set-closed! 'timeout) (send-goaway)] [(closed) (close-ports) (for ([stream (in-hash-values stream-table)]) (send stream handle-timeout))])) ;; ============================================================ ;; Connection threads (2 per connection) ;; Manager thread ;; - receives frames from reader thread, handles ;; - receives work from streams/users, handles ;; - must not call any user-supplied procedures, or block on any ;; ports, except okay to write to out (?) ;; Reader thread ;; - just reads frames from input, sends to manager ;; FIXME: make kill-safe (define/private (manager) (define reader-evt (handle-evt (thread-receive-evt) (lambda (tre) (define fr (thread-receive)) (handle-frame-or-other fr)))) (define manager-bored-evt (wrap-evt (if #f (sleep-evt 1) never-evt) (lambda (ignored) (log-http2-debug "~a manager is bored!" ID)))) (define timeout-evt (guard-evt (lambda () (get-timeout-evt)))) ;; ---- (define (loop/streams-changed) (define work-evts (for/list ([stream (in-hash-values stream-table)]) (send stream get-work-evt))) (log-http2-debug "~a manager updating work evts (~s)" ID (length work-evts)) (define streams-evt (apply choice-evt work-evts)) (loop streams-evt)) (define (loop streams-evt) #;(log-http2-debug "~a manager loop ~s" ID (current-inexact-milliseconds)) (with-handlers ([(lambda (e) (eq? e 'escape-without-error)) void] [(lambda (e) (eq? e 'stream-error)) void]) (sync streams-evt reader-evt timeout-evt manager-bored-evt)) (flush-frames) (cond [(port-closed? out) (log-http2-debug "~a manager stopped; closed" ID)] [(begin0 streams-changed? (set! streams-changed? #f)) (loop/streams-changed)] [else (loop streams-evt)])) ;; ---- (with-handlers ([(lambda (e) (eq? e 'connection-error)) (lambda (e) (log-http2-debug "~a manager stopped due to connection error" ID))] [(lambda (e) #t) (lambda (e) (log-http2-debug "~a manager stopped due to uncaught exn: ~e" ID e) (when exn? ((error-display-handler) (exn-message e) e)))]) (loop/streams-changed))) (define/private (reader) (sync (port-closed-evt in) in) ;; wait for input or EOF or closed (cond [(port-closed? in) (log-http2-debug "~a <-- closed" ID) (thread-send manager-thread 'EOF void) ;; treat like EOF (void)] [(with-handlers ([exn:fail? (lambda (e) #t)]) ;; There is a race between the port-closed? guard and peek-byte, ;; so catch the occasional "input port is closed" error. (eof-object? (peek-byte in))) (log-http2-debug "~a <-- EOF" ID) (thread-send manager-thread 'EOF void) (void)] [else (define fr (read-frame br)) ;; FIXME: handle reading errors... (log-http2-debug "~a <-- ~a" ID (parameterize ((error-print-width 60)) (format "~e" fr))) (thread-send manager-thread fr void) (reader)])) (define manager-thread (thread (lambda () (manager)))) (define reader-thread (thread (lambda () (with-handlers ([exn:break? void]) (reader))))) ;; ============================================================ ;; Methods called from user thread (define/public (open-request req) (define streambxe (make-box-evt)) (define (do-open-request) (with-handler (lambda (e) (box-evt-set! streambxe (lambda () (raise e))) (raise e)) (define stream (new-client-stream req #t)) (box-evt-set! streambxe (lambda () stream)))) (thread-send manager-thread do-open-request (lambda () (box-evt-set! streambxe (lambda () #f)))) (define stream ((sync streambxe))) (cond [stream (define-values (pump-data-out resp-bxe) (send stream get-user-communication)) (pump-data-out) resp-bxe] [else #f])) (define/public (register-user-abort-request stream e) (define (do-register-abort) (send stream handle-user-abort e)) (thread-send manager-thread do-register-abort void)) (define/public (abandon) (unless is-closed? (set-closed! 'user-abandoned #f) (thread-send manager-thread (lambda () (start-close-timeout!) (send-goaway)) void))) ;; ============================================================ ;; Hello, Goodbye (define/private (send-goaway) (define payload (fp:goaway last-server-streamid error:NO_ERROR #"")) (queue-frame (frame type:GOAWAY 0 0 payload)) ;; Don't close/abandon output port, because may need to write eg ;; WINDOW_UPDATE frames to finish receiving from existing streams. (void)) (define/private (send-handshake my-new-config) (write-bytes http2-client-preface out) (define settings (for/list ([(key val) (in-hash my-new-config)] #:when (and (hash-has-key? standard-init-config key) (not (equal? (hash-ref standard-init-config key) val)))) (setting (encode-setting-key key) val))) (queue-frame (frame type:SETTINGS 0 0 (fp:settings settings))) (set! my-configs/awaiting-ack (list my-new-config)) (flush-frames)) (send-handshake my-new-config) )) ;; ---------------------------------------- (define (sleep-evt sec) (guard-evt (lambda () (alarm-evt (+ (current-inexact-milliseconds) (* 1000.0 sec))))))
false
e23be96544f974f69bfba6f522cce56a2cede529
37858e0ed3bfe331ad7f7db424bd77bf372a7a59
/book/1ed/06-infinite-&-divergence/anyo.rkt
16edebe1a80bf8f06f352c5b477228b176046b7a
[]
no_license
chansey97/the-reasoned-schemer
ecb6f6a128ff0ca078a45e097ddf320cd13e81bf
a6310920dde856c6c98fbecec702be0fbc4414a7
refs/heads/main
2023-05-13T16:23:07.738206
2021-06-02T22:24:51
2021-06-02T22:24:51
364,944,122
0
0
null
null
null
null
UTF-8
Racket
false
false
170
rkt
anyo.rkt
#lang racket (require "../libs/trs/mk.rkt") (provide (all-defined-out)) ; 6.1 (define anyo (lambda (g) (conde (g succeed) (else (anyo g)))))
false
2f409d0fb9289eac5f2ab0e518c1edfc341f7263
ee37fa4dd086eff8ff6b15dc0fe016ec6cb67e32
/graph/graph-fns-minspantree.rkt
9cf02362ae3d01e6579c6e0483bdbe29fbb3032b
[]
no_license
jpverkamp/graph
4628f2c407e5da7fb4058b67e33b30a388ac9e26
7fe0d439389696ba5638ec70ea88c0ab4cd3c05f
refs/heads/master
2021-01-15T11:23:17.580564
2014-01-06T21:46:15
2014-01-06T21:46:15
null
0
0
null
null
null
null
UTF-8
Racket
false
false
1,833
rkt
graph-fns-minspantree.rkt
#lang racket (require "hash-utils.rkt" "gen-graph.rkt" "graph-fns-basic.rkt" (only-in "../queue/priority.rkt" mk-empty-priority)) (require data/union-find) (provide (all-defined-out)) ;; minimum spanning tree fns ;; kruskal -------------------------------------------------------------------- ;; uses data/union-find (define (mst-kruskal G) (define (w u v) (edge-weight G u v)) (define A null) (define (A-add! e) (set! A (cons e A))) ;; hash mapping vertex to it's representative set ;; different vertices may map to the same rep set (define-hash dset) (for ([v (in-vertices G)]) (dset-set! v (uf-new v))) (define sorted-edges (sort (sequence->list (in-edges G)) < #:key (λ (e) (apply w e)))) (for ([e sorted-edges]) (match-define (list u v) e) (unless (equal? (uf-find (dset u)) (uf-find (dset v))) (A-add! e) (uf-union! (dset u) (dset v)))) A) ;; prim ----------------------------------------------------------------------- ;; uses priority queue based on in data/heap ;; r is root vertex (define (mst-prim G r) (define (w u v) (edge-weight G u v)) (define-hashes key π in-Q?) (do-bfs G r #:init-queue (mk-empty-priority (λ (u v) (< (key u) (key v)))) #:init (for ([u (in-vertices G)]) (key-set! u +inf.0) (π-set! u #f) (in-Q?-set! u #t)) (key-set! r 0) ;; default bfs skips the visit if v has been discovered (ie it's not "white") ;; but here we want to skip only if v has been dequeued (ie it's "black") #:visit? (to from) (in-Q? from) #:discover (to from) (when (< (w to from) (key from)) ; relax (π-set! from to) (key-set! from (w to from))) #:visit (u) (in-Q?-set! u #f) #:return (for/list ([v (in-vertices G)] #:unless (equal? v r)) (list (π v) v))))
false
caa32e2ad689150edfa85d312d41c67238d2504e
17126876cd4ff4847ff7c1fbe42471544323b16d
/beautiful-racket-demo/basic-demo-2a/parser.rkt
5f503d8378aaa66643d85c68e2d2eadf65b9683d
[ "MIT" ]
permissive
zenspider/beautiful-racket
a9994ebbea0842bc09941dc6d161fd527a7f4923
1fe93f59a2466c8f4842f17d10c1841609cb0705
refs/heads/master
2020-06-18T11:47:08.444886
2019-07-04T23:21:02
2019-07-04T23:21:02
196,293,969
1
0
NOASSERTION
2019-07-11T00:47:46
2019-07-11T00:47:46
null
UTF-8
Racket
false
false
394
rkt
parser.rkt
#lang brag b-program : [b-line] (/NEWLINE [b-line])* b-line : b-line-num [b-statement] (/":" [b-statement])* [b-rem] @b-line-num : INTEGER @b-statement : b-end | b-print | b-goto b-rem : REM b-end : /"end" b-print : /"print" [b-printable] (/";" [b-printable])* @b-printable : STRING | b-expr b-goto : /"goto" b-expr b-expr : b-sum b-sum : b-number (/"+" b-number)* @b-number : INTEGER | DECIMAL
false
f7ed9072c1cf5763ba502dbd8b9574b2e449eca3
ad97878cd7ba7051b448df2bc9e4fdb6fae4627b
/color.rkt
3ce26a56de415decea7f5aebcd7243879b808b97
[]
no_license
rfindler/icfp-2014-contracts-talk
ca321e2b3d1a3784014750c64ebeaa117bb1a8db
e1df17f23d7cd4fbb4fa78c15d6eb3f79c576ddf
refs/heads/master
2020-04-17T15:18:09.526351
2015-07-29T18:33:49
2015-07-29T19:42:04
23,713,920
2
1
null
2015-07-29T19:44:24
2014-09-05T18:30:54
Racket
UTF-8
Racket
false
false
219
rkt
color.rkt
#lang racket (provide blue-boundary-color red-boundary-color boundary-line-thickness) (define blue-boundary-color "DeepSkyBlue") (define red-boundary-color "red") (define boundary-line-thickness 60)
false
4cfe47acb8866802b195746c815a2f53dfbcea82
b08b7e3160ae9947b6046123acad8f59152375c3
/Programming Language Detection/Experiment-2/Dataset/Train/Racket/letter-frequency-2.rkt
474d0dd80599373cb03e03e21f7c4072d4bce510
[]
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
54
rkt
letter-frequency-2.rkt
(letter-frequencies (open-input-file "somefile.txt"))
false
5495907871567ed34cb8e5ecff92ad3281f97d40
2bb711eecf3d1844eb209c39e71dea21c9c13f5c
/test/unbound/lra/gcd.rkt
d27c072fe9a3b5234441ba5422e477f694fa64f2
[ "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
595
rkt
gcd.rkt
#lang rosette/unbound (require rackunit rackunit/text-ui rosette/lib/roseunit) (current-bitwidth #f) (define-symbolic n m integer?) (define/unbound (gcd n m) (~> integer? integer? integer?) (cond [(< n m) (gcd m n)] [(zero? n) m] [(zero? m) n] [else (gcd m (- n m))])) (define gcd-tests (test-suite+ "[unbound] Tests for lra/gcd.rkt" (check-unsat (verify/unbound #:assume (assert (and (> n 0) (> m 0))) #:guarantee (assert (> (gcd m n) 0)))) (check-sat (verify/unbound (assert (> (gcd m n) 0)))))) (time (run-tests gcd-tests))
false
99def5f584b9b2347a692bc4d06ec87113bf3837
8ad2bcf76a6bda64f509da5f0844e0285f19d385
/undefined-dispatch-rules.rkt
21f9b8b8c433a8328dee9f45614e837461267548
[]
no_license
jeapostrophe/exp
c5efae0ea7068bb5c8f225df6de45e6c4fa566bd
764265be4bcd98686c46ca173d45ee58dcca7f48
refs/heads/master
2021-11-19T00:23:11.973881
2021-08-29T12:56:11
2021-08-29T12:56:11
618,042
39
5
null
null
null
null
UTF-8
Racket
false
false
807
rkt
undefined-dispatch-rules.rkt
#lang racket/base (require web-server/dispatch) (define (make-site param) (define-values (main-dispatch main-url) (dispatch-rules [("a") a] [("b") b])) (define (good-footer) (list (main-url a) (main-url b))) (define bad-footer (list (main-url a) (main-url b))) (define (a req) (list "A" param (good-footer) bad-footer)) (define (b req) (list "B" param (good-footer) bad-footer)) main-dispatch) (require rackunit net/url web-server/http racket/promise racket/list) (check-equal? ((make-site "customization") (make-request #"GET" (string->url "/a") empty (delay #"") #"" "127.0.0.1" 80 "127.0.0.1")) (list "A" "customization" (list "/a" "/b") (list "/a" "/a")))
false
27272b9d419bc5e1632f0947275f627a576925ab
76df16d6c3760cb415f1294caee997cc4736e09b
/rosette-benchmarks-4/bagpipe/src/bagpipe/racket/main/util/extraction-racket.rkt
4ab9f7350a81b4cafc29050316b9d6b9ab69bba9
[ "MIT" ]
permissive
uw-unsat/leanette-popl22-artifact
70409d9cbd8921d794d27b7992bf1d9a4087e9fe
80fea2519e61b45a283fbf7903acdf6d5528dbe7
refs/heads/master
2023-04-15T21:00:49.670873
2021-11-16T04:37:11
2021-11-16T04:37:11
414,331,908
6
1
null
null
null
null
UTF-8
Racket
false
false
1,143
rkt
extraction-racket.rkt
#lang racket ; Two version of this file are automatically generated by ; the build process. One for the racket language with the ; suffix -racket, and one for rosette with suffix -rosette. ; Do not edit the file with these suffices. Your changes will ; be lost! (require "rosette.rkt") (provide lambdas @ match coqify-list eq-dec?) (define-syntax lambdas (syntax-rules () [(lambdas () es ...) (begin es ...)] [(lambdas (a as ...) es ...) (lambda (a) (lambdas (as ...) es ...))])) (define-syntax @ (syntax-rules () [(@ e) e] [(@ f a as ...) (@ (f a) as ...)])) (define (curried-apply f args) (if (null? args) f (curried-apply (f (car args)) (cdr args)))) (define-syntax match (syntax-rules () [(match e) (error (string-append "Pattern match failed for " (~a e)))] [(match e ((t as ...) f) cs ...) (let ([x e]) (if (eq? 't (car x)) (curried-apply (lambdas (as ...) f) (cdr x)) (match x cs ...)))])) (define (coqify-list l) (if (null? l) `(Nil) `(Cons ,(car l) ,(coqify-list (cdr l))))) (define eq-dec? (lambdas (a b) (if (rosette-eq? a b) '(Left) '(Right))))
true
30f61e5917ddaa4c8390a8d4a6611ac0d4458490
0bda73c4f9c94c63fd36d60c90e9dccb791b74cb
/racket/zmq/main.rkt
f03dc2e76dcd99de76e9de09f9c9da24a3a203c6
[]
no_license
mariorz/zeromq_examples
7d3df5da7b096d898d9341319234386eac38e896
6008ee08d6582fbb81f634ec57adb0ebb2da4be8
refs/heads/master
2016-09-06T09:10:23.773224
2014-03-02T00:56:41
2014-03-02T00:56:41
null
0
0
null
null
null
null
UTF-8
Racket
false
false
5,315
rkt
main.rkt
#lang racket/base ; ; ZeroMQ Bindings ; (require racket/contract racket/function (only-in ffi/unsafe register-finalizer)) (require "private/ffi.rkt") (provide (except-out (all-defined-out) zmq-context socket drain string->bytes/safe)) ;; Single context with only one I/O thread. (define zmq-context (zmq-ctx-new)) (define-struct socket (type ; Socket mode. sock ; The actual C object. inch ; Channel for message receiving. ping) ; Semaphore to ping input pump. #:constructor-name new-socket) (define (socket-type? v) ;; We only support non-blocking socket types. (list? (member v '(pub sub router)))) (define/contract (make-socket type #:identity (identity #f) #:subscribe (subscribe null) #:bind (bind null) #:connect (connect null)) (->* (socket-type?) (#:identity (or/c #f string? bytes?) #:subscribe (listof (or/c string? bytes?)) #:bind (listof string?) #:connect (listof string?)) socket?) ;; Create the underlying C object. (let ((s (zmq-socket zmq-context type)) (inch (make-channel)) (ping (make-semaphore))) ;; Extract notification port. (let-values (((in out) (socket->ports (zmq-getsockopt/int s 'fd) "zmq"))) ;; Create socket structure. (let ((socket (new-socket type s inch ping))) ;; Set socket identity, if specified. (when identity (set-socket-identity! socket identity)) ;; Bind to given endpoints. (for ((endpoint (in-list bind))) (socket-bind socket endpoint)) ;; Connect to given endpoints. (for ((endpoint (in-list connect))) (socket-connect socket endpoint)) ;; Subscribe to given prefixes. (for ((prefix (in-list subscribe))) (socket-subscribe! socket prefix)) ;; Pump channels from socket to the channel. (unless (eq? type 'pub) (define pump (thread (thunk (for ((msg (in-producer drain #f s (choice-evt in ping)))) (channel-put inch msg))))) ;; Kill the pump once our socket gets forgotten. (register-finalizer socket (lambda (socket) (thread-suspend pump)))) ;; Return the new socket. socket)))) ;; Wait for and read a message from socket. (define (drain sock evt) (define (poll) (let ((flags (zmq-getsockopt/int sock 'events))) (unless (bitwise-bit-set? flags 0) (sync evt) (poll)))) (let loop () (with-handlers ((exn:fail:zmq:again? (lambda (exn) (poll) (loop)))) (let ((msg (zmq-msg-recv sock '(dontwait)))) (if (zmq-msg-more? msg) (cons (zmq-msg->bytes msg) (loop)) (list (zmq-msg->bytes msg))))))) (define/contract (set-socket-identity! socket name) (-> socket? (or/c #f string? bytes?) void?) (let ((name (if (string? name) (string->bytes/utf-8 name) name))) (zmq-setsockopt/bstr (socket-sock socket) 'identity name))) (define/contract (socket-identity socket) (-> socket? bytes?) (zmq-getsockopt/bstr (socket-sock socket) 'identity)) (define/contract (string->bytes/safe str) (-> (or/c string? bytes?) bytes?) (if (bytes? str) str (string->bytes/utf-8 str))) (define/contract (socket-send socket . parts) (->* (socket?) () #:rest (listof (or/c bytes? string?)) void?) (if (null? parts) (unless (eq? 'pub (socket-type socket)) ;; All parts have been sent. Ping receiver to catch up. (semaphore-post (socket-ping socket))) ;; Send one more part. (let ((value (string->bytes/safe (car parts))) (flags (if (null? (cdr parts)) '() '(sndmore)))) (zmq-send (socket-sock socket) value flags) ;; Recurse and do the same with other parts. (apply socket-send socket (cdr parts))))) (define/contract (socket-receive/list socket) (-> socket? (listof bytes?)) (channel-get (socket-inch socket))) (define/contract (socket-receive socket) (-> socket? any) (apply values (socket-receive/list socket))) (define/contract (socket-bind socket endpoint) (-> socket? string? void?) (zmq-bind (socket-sock socket) endpoint)) (define/contract (socket-connect socket endpoint) (-> socket? string? void?) (zmq-connect (socket-sock socket) endpoint)) (define/contract (socket-subscribe! socket prefix) (-> socket? (or/c bytes? string?) void?) (let ((prefix (if (string? prefix) (string->bytes/utf-8 prefix) prefix))) (zmq-setsockopt/bstr (socket-sock socket) 'subscribe prefix))) (define/contract (socket-unsubscribe! socket prefix) (-> socket? (or/c bytes? string?) void?) (let ((prefix (if (string? prefix) (string->bytes/utf-8 prefix) prefix))) (zmq-setsockopt/bstr (socket-sock socket) 'unsubscribe prefix))) (define/contract (socket-receive-evt socket) (-> socket? evt?) (guard-evt (thunk (socket-inch socket)))) ; vim:set ts=2 sw=2 et:
false
bbe003a456ab24bd228ce2f3ee993787676276b6
314185c8e11e855274cec4835e768d3739537c83
/RacketPortfolio/CS5510_HW4.rkt
590cbdf6176db310957e2d0fb462d16a2792851d
[]
no_license
519984307/Portfolio
65e8dbc9877a3b91595d45d6f1b2b9192a91c9f8
d7e443dd49479659e3334146ca0ff2d73349b935
refs/heads/master
2023-03-19T21:28:29.299266
2020-02-11T03:20:56
2020-02-11T03:20:56
null
0
0
null
null
null
null
UTF-8
Racket
false
false
21,884
rkt
CS5510_HW4.rkt
#lang plai-typed ;; Andrew Katsanevas ;; 9/21/2016 ;; CS5510 HW4 (require plai-typed/s-exp-match) (define-type-alias Location number) (define-type Value [numV (n : number)] [closV (arg : symbol) (body : ExprC) (env : Env)] [boxV (l : Location)] [recV (members : (listof symbol)) (locs : (listof Location))]) (define-type ExprC [numC (n : number)] [idC (s : symbol)] [plusC (l : ExprC) (r : ExprC)] [multC (l : ExprC) (r : ExprC)] [letC (n : symbol) (rhs : ExprC) (body : ExprC)] [lamC (n : symbol) (body : ExprC)] [appC (fun : ExprC) (arg : ExprC)] [boxC (arg : ExprC)] [unboxC (arg : ExprC)] [setboxC (bx : ExprC) (val : ExprC)] [beginC (subs : (listof ExprC)) (eval : ExprC)] [recordC (members : (listof symbol)) (args : (listof ExprC))] [getC (record : ExprC) (member : symbol)] [setC (rec : ExprC) (n : symbol) (newVal : ExprC)] ) (define-type Binding [bind (name : symbol) (val : Value)]) (define-type-alias Env (listof Binding)) (define mt-env empty) (define extend-env cons) (define-type Storage [cell (location : Location) (val : Value)]) (define-type-alias Store (listof Storage)) (define mt-store empty) (define override-store cons) (define-type Result [v*s (v : Value) (s : Store)]) (module+ test (print-only-errors true)) ;; parse ---------------------------------------- (define (parse [s : s-expression]) : ExprC (cond [(s-exp-match? `NUMBER s) (numC (s-exp->number s))] [(s-exp-match? `SYMBOL s) (idC (s-exp->symbol s))] [(s-exp-match? '{+ ANY ANY} s) (plusC (parse (second (s-exp->list s))) (parse (third (s-exp->list s))))] [(s-exp-match? '{* ANY ANY} s) (multC (parse (second (s-exp->list s))) (parse (third (s-exp->list s))))] [(s-exp-match? '{let {[SYMBOL ANY]} ANY} s) (let ([bs (s-exp->list (first (s-exp->list (second (s-exp->list s)))))]) (letC (s-exp->symbol (first bs)) (parse (second bs)) (parse (third (s-exp->list s)))))] [(s-exp-match? '{lambda {SYMBOL} ANY} s) (lamC (s-exp->symbol (first (s-exp->list (second (s-exp->list s))))) (parse (third (s-exp->list s))))] [(s-exp-match? '{box ANY} s) (boxC (parse (second (s-exp->list s))))] [(s-exp-match? '{unbox ANY} s) (unboxC (parse (second (s-exp->list s))))] [(s-exp-match? '{set-box! ANY ANY} s) (setboxC (parse (second (s-exp->list s))) (parse (third (s-exp->list s))))] [(s-exp-match? '{begin ANY ...} s) (cond [(> (length (rest (s-exp->list s))) 1) (beginC (map parse (reverse (rest (reverse (rest (s-exp->list s)))))) (parse (first (reverse (rest (s-exp->list s))))))] [else (beginC empty (parse (first (rest (s-exp->list s)))))])] [(s-exp-match? '{record {SYMBOL ANY} ...} s) (recordC (map (lambda (memberList) (s-exp->symbol (first (s-exp->list memberList)))) (rest (s-exp->list s))) (map (lambda (argList) (parse (second (s-exp->list argList)))) (rest (s-exp->list s))))] [(s-exp-match? '{get ANY SYMBOL} s) (getC (parse (second (s-exp->list s))) (s-exp->symbol (third (s-exp->list s))))] [(s-exp-match? '{set ANY SYMBOL ANY} s) (setC (parse (second (s-exp->list s))) (s-exp->symbol (third (s-exp->list s))) (parse (fourth (s-exp->list s))))] [(s-exp-match? '{ANY ANY} s) (appC (parse (first (s-exp->list s))) (parse (second (s-exp->list s))))] [else (error 'parse "invalid input")])) (module+ test (test (parse '2) (numC 2)) (test (parse `x) ; note: backquote instead of normal quote (idC 'x)) (test (parse '{+ 2 1}) (plusC (numC 2) (numC 1))) (test (parse '{* 3 4}) (multC (numC 3) (numC 4))) (test (parse '{+ {* 3 4} 8}) (plusC (multC (numC 3) (numC 4)) (numC 8))) (test (parse '{let {[x {+ 1 2}]} y}) (letC 'x (plusC (numC 1) (numC 2)) (idC 'y))) (test (parse '{lambda {x} 9}) (lamC 'x (numC 9))) (test (parse '{double 9}) (appC (idC 'double) (numC 9))) (test (parse '{box 0}) (boxC (numC 0))) (test (parse '{unbox b}) (unboxC (idC 'b))) (test (parse '{set-box! b 0}) (setboxC (idC 'b) (numC 0))) (test (parse '{begin 1 2}) (beginC (cons (numC 1) empty) (numC 2))) (test (parse '(begin 1)) (beginC empty (numC 1))) (test (parse '(record {a 1} {b 2})) (recordC (cons 'a (cons 'b empty)) (cons (numC 1) (cons (numC 2) empty)))) (test (parse '{get {+ 1 2} a}) (getC (plusC (numC 1) (numC 2)) 'a)) (test (parse '{get {get {record {r {record {z 0}}}} r} z}) (getC (getC (recordC (list 'r) (list (recordC (list 'z) (list (numC 0))))) 'r) 'z)) (test/exn (parse '{{+ 1 2}}) "invalid input")) ;; with form ---------------------------------------- (define-syntax-rule (with [(v-id sto-id) call] body) (type-case Result call [v*s (v-id sto-id) body])) ;; interp ---------------------------------------- (define (interp [a : ExprC] [env : Env] [sto : Store]) : Result (type-case ExprC a [numC (n) (v*s (numV n) sto)] [idC (s) (v*s (lookup s env) sto)] [plusC (l r) (with [(v-l sto-l) (interp l env sto)] (with [(v-r sto-r) (interp r env sto-l)] (v*s (num+ v-l v-r) sto-r)))] [multC (l r) (with [(v-l sto-l) (interp l env sto)] (with [(v-r sto-r) (interp r env sto-l)] (v*s (num* v-l v-r) sto-r)))] [letC (n rhs body) (with [(v-rhs sto-rhs) (interp rhs env sto)] (interp body (extend-env (bind n v-rhs) env) sto-rhs))] [lamC (n body) (v*s (closV n body env) sto)] [appC (fun arg) (with [(v-f sto-f) (interp fun env sto)] (with [(v-a sto-a) (interp arg env sto-f)] (type-case Value v-f [closV (n body c-env) (interp body (extend-env (bind n v-a) c-env) sto-a)] [else (error 'interp "not a function")])))] [boxC (a) (with [(v sto-v) (interp a env sto)] (let ([l (new-loc sto-v)]) (v*s (boxV l) (override-store (cell l v) sto-v))))] [unboxC (a) (with [(v sto-v) (interp a env sto)] (type-case Value v [boxV (l) (v*s (fetch l sto-v) sto-v)] [else (error 'interp "not a box")]))] [setboxC (bx val) (with [(v-b sto-b) (interp bx env sto)] (with [(v-v sto-v) (interp val env sto-b)] (type-case Value v-b [boxV (l) (v*s v-v (update-store (cell l v-v) sto-v empty sto-v))] [else (error 'interp "not a box")])))] [beginC (l r) (interp r env (sub-store l env sto))] [recordC (members args) (recHelper members args empty env sto)] [getC (r m) (type-case Value (v*s-v (interp r env sto)) [recV (ms ls) (v*s (find m ms ls (v*s-s (interp r env sto))) (v*s-s (interp r env sto)))] [else (error 'interp "not a record")])] [setC (rec n nv) (type-case Value (v*s-v (interp rec env sto)) [recV (mems locs) (change-store (find-location mems locs n) (v*s-v (interp nv env sto)) empty sto)] [else (error 'interp "not a record")])] )) (define (find-location [mems : (listof symbol)] [locs : (listof Location)] [n : symbol]) : Location (cond [(empty? mems) (error 'interp "field not found")] [(symbol=? n (first mems)) (first locs)] [else (find-location (rest mems) (rest locs) n)])) (define (change-store [loc : Location] [newVal : Value] [beforeSto : Store] [sto : Store]) : Result (cond [(empty? sto) (error 'interp "field not found")] [(= loc (cell-location (first sto))) (v*s newVal (append beforeSto (override-store (cell loc newVal) (rest sto))))] [else (change-store loc newVal (append beforeSto (list (first sto))) (rest sto))])) (define (recHelper [members : (listof symbol)] [args : (listof ExprC)] [locs : (listof Location)] [env : Env] [sto : Store]) : Result (cond [(empty? args) (v*s (recV members locs) sto)] [else (with [(v-v sto-v) (interp (first args) env sto)] (recHelper members (rest args) (append locs (list (next-location sto-v))) env (override-store (cell (next-location sto-v) v-v) sto-v)))])) (define (next-location [sto : Store]) : Location (cond [(empty? sto) 1] [else (+ 1 (cell-location (first sto)))])) (define (interp-expr [a : ExprC]) : s-expression (type-case Value (v*s-v (interp a empty empty)) [numV (n) (number->s-exp n)] [closV (a b e) `function] [boxV (l) `box] [recV (m l) `record])) (define (find [m : symbol] [ms : (listof symbol)] [ls : (listof Location)] [sto : Store]) : Value (cond [(empty? ms) (error 'interp "no such field")] [(symbol=? (first ms) m) (lookup-location (first ls) sto)] [else (find m (rest ms) (rest ls) sto)])) (define (lookup-location [loc : Location] [sto : Store]) : Value (cond [(empty? sto) (error 'interp "no such field")] [(= loc (cell-location (first sto))) (cell-val (first sto))] [else (lookup-location loc (rest sto))])) (define (update-store [c : Storage] [sto : Store] [before : Store] [original : Store]) : Store (cond [(empty? sto) (override-store c original)] [(eq? (cell-location (first sto)) (cell-location c)) (append (override-store c before) (rest sto))] [else (update-store c (rest sto) (override-store (first sto) before) original)])) (define (sub-store [exps : (listof ExprC)] [env : Env] [sto : Store]) : Store (cond [(empty? exps) sto] [else (sub-store (rest exps) env (v*s-s (interp (first exps) env sto)))])) (module+ test (test (update-store (cell 3 (numV 1)) mt-store mt-store mt-store) (list (cell 3 (numV 1)))) (test (update-store (cell 3 (numV 1)) (list (cell 2 (numV 5))) mt-store (list (cell 2 (numV 5)))) (list (cell 3 (numV 1)) (cell 2 (numV 5)))) (test (interp (parse '2) mt-env mt-store) (v*s (numV 2) mt-store)) (test/exn (interp (parse `x) mt-env mt-store) "free variable") (test (interp (parse `x) (extend-env (bind 'x (numV 9)) mt-env) mt-store) (v*s (numV 9) mt-store)) (test (interp (parse '{+ 2 1}) mt-env mt-store) (v*s (numV 3) mt-store)) (test (interp (parse '{* 2 1}) mt-env mt-store) (v*s (numV 2) mt-store)) (test (interp (parse '{+ {* 2 3} {+ 5 8}}) mt-env mt-store) (v*s (numV 19) mt-store)) (test (interp (parse '{lambda {x} {+ x x}}) mt-env mt-store) (v*s (closV 'x (plusC (idC 'x) (idC 'x)) mt-env) mt-store)) (test (interp (parse '{let {[x 5]} {+ x x}}) mt-env mt-store) (v*s (numV 10) mt-store)) (test (interp (parse '{let {[x 5]} {let {[x {+ 1 x}]} {+ x x}}}) mt-env mt-store) (v*s (numV 12) mt-store)) (test (interp (parse '{let {[x 5]} {let {[y 6]} x}}) mt-env mt-store) (v*s (numV 5) mt-store)) (test (interp (parse '{{lambda {x} {+ x x}} 8}) mt-env mt-store) (v*s (numV 16) mt-store)) (test (interp (parse '{box 5}) mt-env mt-store) (v*s (boxV 1) (override-store (cell 1 (numV 5)) mt-store))) (test (interp (parse '{unbox {box 5}}) mt-env mt-store) (v*s (numV 5) (override-store (cell 1 (numV 5)) mt-store))) (test (interp (parse '{begin 1 2}) mt-env mt-store) (v*s (numV 2) mt-store)) (test (interp (parse '{let {[b {box 1}]} {begin {set-box! b 2} {unbox b}}}) mt-env mt-store) (v*s (numV 2) (override-store (cell 1 (numV 2)) mt-store))) (test (interp (parse '{let {[b {box 1}]} {begin {set-box! b {+ 2 {unbox b}}} {set-box! b {+ 3 {unbox b}}} {set-box! b {+ 4 {unbox b}}} {unbox b}}}) mt-env mt-store) (v*s (numV 10) (override-store (cell 1 (numV 10)) mt-store))) (test (interp (parse '(begin (+ 1 1))) mt-env mt-store) (v*s (numV 2) mt-store)) ;; record and get tests (test (interp (parse '{record {a 10} {b {+ 1 2}}}) mt-env mt-store) (v*s (recV (list 'a 'b) (list 1 2)) (override-store (cell 2 (numV 3)) (override-store (cell 1 (numV 10)) mt-store)))) (test (interp-expr (parse '{+ 1 4})) '5) (test (interp-expr (parse '{record {a 10} {b {+ 1 2}}})) `record) (test (interp-expr (parse '(lambda (x) (+ x 9)))) `function) (test (interp-expr (parse '{get {record {a 10} {b {+ 1 0}}} b})) '1) (test/exn (interp-expr (parse '{get {record {a 10}} b})) "no such field") (test (interp-expr (parse '{get {record {r {record {z 0}}}} r})) `record) (test (interp-expr (parse '(box 1))) `box) (test (interp (parse '{record {x 5}}) mt-env mt-store) (v*s (recV (list 'x) (list 1)) (list (cell 1 (numV 5))))) (test (interp (parse '{begin {box 9} {record {x 5}}}) mt-env mt-store) (v*s (recV (list 'x) (list 2)) (list (cell 2 (numV 5)) (cell 1 (numV 9))))) (test (interp (parse '{get {record {z 0}} z}) mt-env mt-store) (v*s (numV 0) (list (cell 1 (numV 0))))) (test (interp (parse '{record {r {record {z 0}}}}) mt-env mt-store) (v*s (recV (list 'r) (list 2)) (list (cell 2 (recV (list 'z) (list 1))) (cell 1 (numV 0))))) (test (interp (parse '{get {get {record {r {record {z 0}}}} r} z}) mt-env mt-store) (v*s (numV 0) (list (cell 2 (recV (list 'z) (list 1))) (cell 1 (numV 0))))) (test (interp-expr (parse '{get {get {record {r {record {z 0}}}} r} z})) '0) ;; mutate tests (test (interp-expr (parse '{let {[r {record {x 1}}]} {get r x}})) '1) (test (interp (parse '{let {[r {record {x 1}}]} {set r x 5}}) mt-env mt-store) (v*s (numV 5) (list (cell 1 (numV 5))))) (test (interp-expr (parse '{let {[r {record {x 1}}]} {begin {set r x 5} {get r x}}})) '5) (test (interp-expr (parse '{let {[r {record {x 1}}]} {let {[get-r {lambda {d} r}]} {begin {set {get-r 0} x 6} {get {get-r 0} x}}}})) '6) (test (interp-expr (parse '{let {[g {lambda {r} {get r a}}]} {let {[s {lambda {r} {lambda {v} {set r b v}}}]} {let {[r1 {record {a 0} {b 2}}]} {let {[r2 {record {a 3} {b 4}}]} {+ {get r1 b} {begin {{s r1} {g r2}} {+ {begin {{s r2} {g r1}} {get r1 b}} {get r2 b}}}}}}}})) '5) (test (interp (parse '{let {[g {lambda {r} {get r a}}]} {let {[s {lambda {r} {lambda {v} {set r b v}}}]} {let {[r1 {record {a 0} {b 2}}]} {let {[r2 {record {a 3} {b 4}}]} {+ {get r1 b} {begin {{s r1} {g r2}} {+ {begin {{s r2} {g r1}} {get r1 b}} {get r2 b}}}}}}}}) mt-env mt-store) (v*s (numV 5) (list (cell 4 (numV 0)) (cell 3 (numV 3)) (cell 2 (numV 3)) (cell 1 (numV 0))))) (test (interp (parse '{let {[r1 {record {a 0} {b 2}}]} {let {[r2 {record {a 3} {b 4}}]} (begin (set r1 b 5) (get r1 b))}}) mt-env mt-store) (v*s (numV 5) (list (cell 4 (numV 4)) (cell 3 (numV 3)) (cell 2 (numV 5)) (cell 1 (numV 0))))) (test (interp (parse '(record {x 10} {y 20} {z 30} {a 40})) mt-env mt-store) (v*s (recV (list 'x 'y 'z 'a) (list 1 2 3 4)) (list (cell 4 (numV 40)) (cell 3 (numV 30)) (cell 2 (numV 20)) (cell 1 (numV 10))))) ;; exception tests (test/exn (interp (parse '{1 2}) mt-env mt-store) "not a function") (test/exn (interp (parse '{+ 1 {lambda {x} x}}) mt-env mt-store) "not a number") (test/exn (interp (parse '{let {[bad {lambda {x} {+ x y}}]} {let {[y 5]} {bad 2}}}) mt-env mt-store) "free variable") (test/exn (interp (parse '{unbox 1}) mt-env mt-store) "not a box") (test/exn (interp (parse '{set-box! 1 2}) mt-env mt-store) "not a box") (test/exn (interp (parse '{get (+ 1 1) a}) mt-env mt-store) "not a record") (test/exn (interp (parse '{set (box 2) a 1}) mt-env mt-store) "not a record") (test/exn (find-location empty empty 'n) "field not found") (test/exn (change-store 1 (numV 1) mt-store mt-store) "field not found") (test/exn (lookup-location 1 mt-store) "no such field") ) ;; num+ and num* ---------------------------------------- (define (num-op [op : (number number -> number)] [l : Value] [r : Value]) : Value (cond [(and (numV? l) (numV? r)) (numV (op (numV-n l) (numV-n r)))] [else (error 'interp "not a number")])) (define (num+ [l : Value] [r : Value]) : Value (num-op + l r)) (define (num* [l : Value] [r : Value]) : Value (num-op * l r)) (module+ test (test (num+ (numV 1) (numV 2)) (numV 3)) (test (num* (numV 2) (numV 3)) (numV 6))) ;; lookup ---------------------------------------- (define (lookup [n : symbol] [env : Env]) : Value (cond [(empty? env) (error 'lookup "free variable")] [else (cond [(symbol=? n (bind-name (first env))) (bind-val (first env))] [else (lookup n (rest env))])])) (module+ test (test/exn (lookup 'x mt-env) "free variable") (test (lookup 'x (extend-env (bind 'x (numV 8)) mt-env)) (numV 8)) (test (lookup 'x (extend-env (bind 'x (numV 9)) (extend-env (bind 'x (numV 8)) mt-env))) (numV 9)) (test (lookup 'y (extend-env (bind 'x (numV 9)) (extend-env (bind 'y (numV 8)) mt-env))) (numV 8))) ;; store operations ---------------------------------------- (define (new-loc [sto : Store]) : Location (+ 1 (max-address sto))) (define (max-address [sto : Store]) : Location (cond [(empty? sto) 0] [else (max (cell-location (first sto)) (max-address (rest sto)))])) (define (fetch [l : Location] [sto : Store]) : Value (cond [(empty? sto) (error 'interp "unallocated location")] [else (if (equal? l (cell-location (first sto))) (cell-val (first sto)) (fetch l (rest sto)))])) (module+ test (test (max-address mt-store) 0) (test (max-address (override-store (cell 2 (numV 9)) mt-store)) 2) (test (fetch 2 (override-store (cell 2 (numV 9)) mt-store)) (numV 9)) (test (fetch 2 (override-store (cell 2 (numV 10)) (override-store (cell 2 (numV 9)) mt-store))) (numV 10)) (test (fetch 3 (override-store (cell 2 (numV 10)) (override-store (cell 3 (numV 9)) mt-store))) (numV 9)) (test/exn (fetch 2 mt-store) "unallocated location"))
true
92338165f8be2254b3e9df4b9c16ec180808175e
3ac344d1cac4caa5eb4842bc0e4d61b1ae7030fb
/main.rkt
d8bfdf0ba59ebbaeac7be89939e035b6dfb8ed20
[ "ISC" ]
permissive
vicampo/riposte
0c2f2a8459a2c6eee43f6f8a83f329eb9741e3fc
73ae0b0086d3e8a8d38df095533d9f0a8ea6b31b
refs/heads/master
2021-10-29T11:18:14.745047
2021-10-13T10:20:33
2021-10-13T10:20:33
151,718,283
42
5
ISC
2019-03-26T12:20:23
2018-10-05T12:35:49
Racket
UTF-8
Racket
false
false
1,407
rkt
main.rkt
#lang racket/base (provide #%module-begin #%app #%top #%datum #%top-interaction riposte-program header-assignment parameter-assignment normal-assignment expression normal-identifier env-identifier json-object json-object-item json-array json-array-item json-boolean json-null command uri-template uri-template-expression uri-template-variable-list uri-template-varspec has-type json-pointer unset schema-ref jp-existence equality disequality inequality header-presence response-head-id sequence-predicate echo exec exec-arg-item riposte-repl bang explode-expression snooze matches function-definition function-call return with-headers) (require (file "expander.rkt")) (module reader racket/base (provide read-syntax read get-info) (require (file "reader.rkt")) (define (get-info port src-mod src-line src-col src-pos) (define (handle-query key default) (case key [(module-language) "expander.rkt"] [else default])) handle-query))
false
807dc0c62dfd57a1abb57793acc2aeb56a8baa32
688feb2eac8bc384583c4f0960cfbc86c3470d91
/racket/sql/db.rkt
c6b4b2501b04f0cc98290500b5b602873ebf1ee5
[]
no_license
halida/code_example
7d2873e92707b4bab673046ff3d0c742e1984b4c
5c882a24b93696c2122a78425ef6b3775adc80fa
refs/heads/master
2023-06-08T15:51:23.150728
2022-03-27T09:57:43
2022-03-27T09:57:43
2,458,466
2
1
null
2023-06-06T02:07:28
2011-09-26T06:01:29
Ruby
UTF-8
Racket
false
false
968
rkt
db.rkt
(require db) (define conn (sqlite3-connect #:database 'memory)) (query-exec conn "create table items (id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar, count integer)") (query-exec conn "insert into items(name, count) values ($1, $2)" "cat" 3) (define id 1) (query-row conn "select name, count from items where id = $1" id) ;; js method (define (model-item id) (match-define (vector name count) (query-row conn "select name, count from items where id = $1" id)) (lambda (method . args) (case method ((name) name) ((set-name) (set! name (first args))) ((count) count) ((save) (query-exec conn "update items set name = $1, count = $2 where id = $3" name count id)) ))) (define i1 (model-item 1)) (i1 'name) (i1 'set-name "v") (i1 'name) (i1 'save) ;; class method (require racquel) (define item% (gen-data-class conn "items")) (define i2 (make-data-object conn item% 1)) (send i2 name)
false
12ec38c362788ac6228c66e1cc35b26bd5e98db9
93fd61180e3ad2db364085053b1ea1bdec19f7bf
/compiler/passes/cps.rkt
173ffbb1a546db738faaf06ba6229c4f30e82bbb
[ "BSD-3-Clause" ]
permissive
nilern/complement
c14de84c1ac08c12b8b1f07038ae3961e423d9d9
7bbf2ed0eafaa0b881926f2c432e3091a522bef5
refs/heads/master
2021-01-21T09:28:33.600811
2018-04-21T11:13:33
2018-04-21T11:13:33
101,971,610
0
0
null
null
null
null
UTF-8
Racket
false
false
27,877
rkt
cps.rkt
#lang racket/base (provide census shrink) (require racket/match racket/class (only-in racket/list first rest empty? filter-map) racket/set data/gvector data/queue (only-in srfi/26 cute) (only-in threading ~>) nanopass/base "../langs.rkt" (only-in "../util.rkt" zip-hash unzip-hash gvector-filter! while if-let if-let-values when-let while-let-values) (only-in "../nanopass-util.rkt" define/nanopass)) (define-pass for-each-usage : CPS (ir callf continuef escapef) -> * () (definitions (define visited (mutable-set))) (CFG : CFG (ir fn-name) -> * () [(cfg ([,n* ,k*] ...) ,n) (define kenv (zip-hash n* k*)) (Cont (hash-ref kenv n) fn-name n kenv) (escapef fn-name #f (with-output-language (CPS Var) `(label ,n)))]) (Cont : Cont (ir fn-name label kenv) -> * () [(cont (,n* ...) ,s* ... ,t) (unless (set-member? visited label) (set-add! visited label) (for-each (cute Stmt <> fn-name label kenv) s*) (Transfer t fn-name label kenv))]) (Stmt : Stmt (ir fn-name label kenv) -> * () [(def ,n ,e) (Expr e n fn-name label kenv)] [,e (Expr e #f fn-name label kenv)]) (Expr : Expr (ir name fn-name label kenv) -> * () [(fn ,blocks) (CFG blocks name)] [(primcall ,p ,a* ...) (for-each (cute Atom <> fn-name label kenv) a*)] [,a (Atom a fn-name label kenv)]) (Transfer : Transfer (ir fn-name label kenv) -> * () [(continue ,x ,a* ...) (Child x fn-name kenv) (for-each (cute Atom <> fn-name label kenv) a*) (continuef fn-name label x a*)] [(if ,a? ,x1 ,x2) (Child x1 fn-name kenv) (Child x2 fn-name kenv) (Atom a? fn-name label kenv) (continuef fn-name label x1 '()) (continuef fn-name label x2 '())] [(call ,x1 ,x2 ,a* ...) (Child x1 fn-name kenv) (Var x2 fn-name label kenv) (for-each (cute Atom <> fn-name label kenv) a*) (callf fn-name label x1 x2 a*)] [(ffncall ,x1 ,x2 ,a* ...) (Var x1 fn-name label kenv) (Var x2 fn-name label kenv) (for-each (cute Atom <> fn-name label kenv) a*)] [(raise ,a) (Atom a fn-name label kenv)] [(halt ,a) (Atom a fn-name label kenv)]) (Atom : Atom (ir fn-name label kenv) -> * () [,x (Var x fn-name label kenv)] [(const ,c) (void)]) (Var : Var (ir fn-name label kenv) -> * () [(lex ,n) (escapef fn-name label ir)] [(label ,n) (Cont (hash-ref kenv n) fn-name n kenv) (escapef fn-name label ir)]) (Child : Var (ir fn-name kenv) -> * () [(lex ,n) (void)] [(label ,n) (Cont (hash-ref kenv n) fn-name n kenv)]) (CFG ir #t)) ;; For every use of a variable, vtab[var]['uses] += delta. ;; For every direct call of a label, ltab[label]['calls] += delta. ;; For every escaping use of a label, ltab[label]['escapes] += delta. (define (census! ir delta ltab vtab) (define (make-var-entry) (make-hash '((uses . 0)))) (define (make-label-entry) (make-hash '((calls . 0) (escapes . 0)))) (define add-delta (cute + <> delta)) (define (used! var-table name) (~> (hash-ref! var-table name make-var-entry) (hash-update! 'uses add-delta))) (define (escapes! label-table name) (~> (hash-ref! label-table name make-label-entry) (hash-update! 'escapes add-delta))) (define (called! label-table name) (~> (hash-ref! label-table name make-label-entry) (hash-update! 'calls add-delta))) (for-each-usage ir (lambda (_ _* callee _** _***) (nanopass-case (CPS Var) callee [(lex ,n) (used! vtab n)] [(label ,n) (called! ltab n)])) (lambda (_ _* callee _**) (nanopass-case (CPS Var) callee [(lex ,n) (used! vtab n)] [(label ,n) (called! ltab n)])) (lambda (_ _* var) (nanopass-case (CPS Var) var [(lex ,n) (used! vtab n)] [(label ,n) (escapes! ltab n)])))) ;; Build var-table where vtab[var]['uses] is the number of uses of that variable ;; and label-table where ltab[label]['calls] is the number of direct calls of that label ;; and ltab[label]['escapes] is the number of escaping uses of that label. (define (census ir delta) (let ([label-table (make-hash)] [var-table (make-hash)]) (census! ir delta label-table var-table) (hash 'label-table label-table 'var-table var-table))) ;; HACK: (define (primops:pure? opcode) (case opcode [(__boxNew __tupleNew __fnNew __contNew __denvNew __recNew) #t] [else #f])) (define/nanopass (CPS Expr) (pure? ir) [(fn ,blocks) #t] [(primcall ,p ,a* ...) (primops:pure? p)] [,a #t]) (define (unify-atoms atoms) (define/nanopass (CPS Atom) (unify2 atom1 atom2) [(const ,c1) (nanopass-case (CPS Atom) atom2 [(const ,c2) (guard (equal? c1 c2)) atom1] [else #f])] [(lex ,n1) (nanopass-case (CPS Atom) atom2 [(lex ,n2) (guard (eq? n1 n2)) atom1] [else #f])] [(label ,n1) (nanopass-case (CPS Atom) atom2 [(label ,n2) (guard (eq? n1 n2)) atom1] [else #f])]) (foldl unify2 (first atoms) (rest atoms))) (struct $fn (labels entry)) (struct $label ((cont #:mutable) (fn #:mutable))) (define symbol-table% (class object% ;;; Fields and initialization (define fns (make-hash)) (define labels (make-hash)) (super-new) ;;; Fn methods (define (fn-ref fn-name) (hash-ref fns fn-name)) (define (fn-labels fn-name) ($fn-labels (fn-ref fn-name))) (define (add-fn-label! fn-name label) (set-add! ($fn-labels (fn-ref fn-name)) label)) (define (remove-fn-label! fn-name label) (set-remove! ($fn-labels (fn-ref fn-name)) label)) ;;; Label methods (define (label-ref label) (hash-ref labels label)) (define/public (cont-ref label) ($label-cont (label-ref label))) (define/public (cont-forget! fn-name label) (remove-fn-label! fn-name label) (hash-remove! labels label)) (define/public (set-cont! label cont) (set-$label-cont! (label-ref label) cont)) (define/public (label-fn label) ($label-fn (label-ref label))) ;;; High-level API (define/public (add-fn! fn-name fn-labels conts entry) (hash-set! fns fn-name ($fn (list->mutable-set fn-labels) entry)) (for ([label fn-labels] [cont conts]) (hash-set! labels label ($label cont fn-name)))) (define/public (move-label! label src dest) (remove-fn-label! src label) (add-fn-label! dest label) (set-$label-fn! (label-ref label) dest)) (define/public (build-cfg fn-name) (with-output-language (CPS CFG) (match-define ($fn label-set entry) (fn-ref fn-name)) (define-values (labels conts) (for/fold ([labels '()] [conts '()]) ([label label-set]) (values (cons label labels) (cons (cont-ref label) conts)))) `(cfg ([,labels ,conts] ...) ,entry))))) (define statistics% (class object% ;;; Fields and initialization (define escapes (make-hash)) (define applications (make-hash)) (super-new) ;;; Escape methods (define (escapes-of name) (hash-ref! escapes name make-gvector)) (define (escape-count name) (gvector-count (escapes-of name))) (define/public (add-escape! name label) (gvector-add! (hash-ref! escapes name make-gvector) label)) (define/public (remove-escape! name label) (let/ec return (define name-escapes (hash-ref! escapes name make-gvector)) (for ([(l i) (in-indexed name-escapes)]) (when (eq? l label) (gvector-remove! name-escapes i) (return (void)))))) ;;; Application methods (define/public (applications-of name) (hash-ref! applications name make-gvector)) (define (application-count name) (gvector-count (applications-of name))) (define/public (add-application! name label) (gvector-add! (hash-ref! applications name make-gvector) label)) (define/public (remove-application! name label) (let/ec return (define name-applications (hash-ref! applications name make-gvector)) (for ([(l i) (in-indexed name-applications)]) (when (eq? l label) (gvector-remove! name-applications i) (return (void)))))) ;;; High-level API (define/public (total-usages name) (+ (escape-count name) (application-count name))) (define/public (used? name) (not (unused? name))) (define/public (unused? name) (zero? (total-usages name))) (define/public (first-order? label) (zero? (escape-count label))) (define/public (transfer-usages! old new) (for ([label (escapes-of old)]) (add-escape! new label)) (hash-remove! escapes old) (for ([label (applications-of old)]) (add-application! new label)) (hash-remove! applications old)) (define/public (cont-forget! label) (hash-remove! escapes label) (for ([(_ escapes*) escapes]) ; OPTIMIZE (gvector-filter! (cute eq? <> label) escapes*)) (hash-remove! applications label) (for ([(_ applications*) applications]) ; OPTIMIZE (gvector-filter! (cute eq? <> label) applications*))))) (struct $non-static-eval exn:fail ()) ;; FIXME: Since return points are processed before callee bodies, their parameters do not get ;; propagated and returns cannot be beta-contracted (without residualizing param `def`:s). ;; ;; * Copy and constant propagation including Cont parameters. ;; * Constant folding. ;; * Integration of first-order functions into their only direct caller. ;; => Some inlining ;; => Some contification ;; * Merging linear sequences of first-order continuations. ;; => Longer basic blocks ;; * Elimination of unused (both 'dead' and 'unreachable') code. (define-pass shrink : CPS (ir) -> CPS () (definitions (define current-fn (make-parameter #t)) (define current-label (make-parameter #f)) (define transient-program% (class object% (init cfg) ;;;; Fields and minimal initialization (define orig-worklists (make-hash)) (define stats (new statistics%)) (define symtab (new symbol-table%)) (define substitution (make-hash)) (define abstract-heap (make-hash)) (super-new) ;;;; Worklist methods (define (orig-worklist-prepend! fn-name callee) (enqueue-front! (hash-ref! orig-worklists fn-name make-queue) callee)) (define (worklist-pop! worklist) (if (non-empty-queue? worklist) (let ([label (dequeue! worklist)]) (values label (send symtab cont-ref label))) (values #f #f))) (define/public (pop-orig-cont! fn-name) (worklist-pop! (hash-ref orig-worklists fn-name))) ;;;; Statistics methods (define/public (total-usages name) (send stats total-usages name)) (define/public (used? name) (send stats used? name)) (define/public (unused? name) (send stats unused? name)) (define/public (add-escape! name label) (send stats add-escape! name label)) (define/public (remove-escape! name label) (send stats remove-escape! name label)) (define/public (add-application! name label) (send stats add-application! name label)) (define/public (remove-application! name label) (send stats remove-application! name label)) ;;;; Label-continuation-fn mapping methods (define/public (cont-ref label) (send symtab cont-ref label)) (define/public (set-cont! label cont) (send symtab set-cont! label cont)) (define/public (cont-forget! fn-name label) (send symtab cont-forget! fn-name label) (send stats cont-forget! label)) (define/public (enter-function! fn-name labels fn-conts entry) (send symtab add-fn! fn-name labels fn-conts entry)) (define (mergeable-into? caller fn-name) (and (send stats first-order? fn-name) (for/and ([usage-label (send stats applications-of fn-name)]) (eq? (send symtab label-fn usage-label) caller)))) (define/public (fn-merge-into! fn-name) (with-output-language (CPS Cont) (define fn-name-worklist (hash-ref orig-worklists fn-name)) (define merged-names (for/list ([(name expr) abstract-heap] #:when (and (not (vector? expr)) ; HACK (mergeable-into? fn-name name))) (nanopass-case (CPS Expr) expr [(fn (cfg ([,n* ,k*] ...) ,n)) (enter-function! name n* k* n) ; HACK? (define name-worklist (hash-ref orig-worklists name)) (while (non-empty-queue? name-worklist) (enqueue! fn-name-worklist (dequeue! name-worklist))) (send stats remove-escape! n #f) (send stats transfer-usages! name n) (for ([label n*] [cont k*]) (send symtab move-label! label name fn-name)) (for ([usage-label (send stats applications-of n)]) (nanopass-case (CPS Cont) (send symtab cont-ref usage-label) [(cont (,n* ...) ,s* ... (call ,x1 ,x2 ,a* ...)) (send symtab set-cont! usage-label `(cont (,n* ...) ,s* ... (continue (label ,n) ,x2 ,a* ...)))] [else (error "fn-merge-into!: callsite not a call")])) name] [else (error "fn-merge-into!: tried to inline non-function")]))) (for-each (cute hash-remove! abstract-heap <>) merged-names) (not (empty? merged-names)))) (define/public (build-cfg name) (send symtab build-cfg name)) ;;;; Environment management (define/public (propagated fn-name name default) (define atom (hash-ref substitution name default)) (nanopass-case (CPS Atom) atom [(label ,n) (guard (not (eq? (send symtab label-fn n) fn-name))) default] [else atom])) (define (label-arglists label) (for/list ([usage-label (send stats applications-of label)]) (nanopass-case (CPS Cont) (send symtab cont-ref usage-label) [(cont (,n* ...) ,s* ... (continue ,x1 ,a* ...)) a*] [(cont (,n* ...) ,s* ... ,t) (error "label-arglists: label callsite is not a continue:" label t)]))) (define/public (propagate-params! label params) (unless (or (not (send stats first-order? label)) (empty? params)) (define (propagate-param! name . atoms) (unless (empty? atoms) (when-let [atom (unify-atoms atoms)] (hash-set! substitution name atom)))) (apply for-each propagate-param! params (label-arglists label)))) (define/public (compact-params! label params) (with-output-language (CPS Cont) (define keepers (map (lambda (param) (send stats used? param)) params)) (define ((compact-arg! usage-label) atom keep) (if keep atom (begin (nanopass-case (CPS Atom) atom [(lex ,n) (send stats remove-escape! n usage-label)] [(label ,n) (send stats remove-escape! n usage-label)] [(const ,c) (void)]) #f))) (if (and (send stats first-order? label) (not (empty? params))) (begin (for ([usage-label (send stats applications-of label)]) (nanopass-case (CPS Cont) (send symtab cont-ref usage-label) [(cont (,n* ...) ,s* ... (continue ,x1 ,a* ...)) (send symtab set-cont! usage-label `(cont (,n* ...) ,s* ... (continue ,x1 ,(filter-map (compact-arg! usage-label) a* keepers) ...)))] [else (error "compact-params: unreachable code reached")])) (filter-map (lambda (param keep) (and keep param)) params keepers)) ; OPTIMIZE params))) (define/public (load name) (if (hash-has-key? abstract-heap name) (values #t (hash-ref abstract-heap name)) (values #f #f))) (define/public (allocate! name expr) (nanopass-case (CPS Expr) expr [(fn ,blocks) (hash-set! abstract-heap name expr)] [(primcall ,p ,a* ...) (guard (eq? p '__tupleNew)) (hash-set! abstract-heap name (list->vector a*))] [(primcall ,p ,a* ...) (void)] ; TODO [,a (hash-set! substitution name expr)])) (define/public (deallocate! name) (hash-remove! abstract-heap name)) (define/public (integrated? name) (not (hash-has-key? abstract-heap name))) ;;;; Completion of field initialization (for-each-usage cfg (lambda (caller label callee cont args) (nanopass-case (CPS Var) callee [(lex ,n) (send stats add-application! n label)] [(label ,n) (send stats add-application! n label)])) (lambda (fn-name label callee args) (nanopass-case (CPS Var) callee [(lex ,n) (send stats add-application! n label)] [(label ,n) (send stats add-application! n label) (orig-worklist-prepend! fn-name n)])) (lambda (fn-name label var) (nanopass-case (CPS Var) var [(lex ,n) (send stats add-escape! n label)] [(label ,n) (send stats add-escape! n label) (orig-worklist-prepend! fn-name n)]))))) (define transient-program (make-object transient-program% ir)) ;;;; (define (fold-stmt name expr) (define (unused? name) (or (not name) (send transient-program unused? name))) (let retry ([expr expr] [first-try #t]) (define pure (pure? expr)) (if (and (unused? name) pure) (begin (EliminateExpr expr) #f) (if first-try (retry (FoldExpr expr) #f) (begin (when pure (send transient-program allocate! name expr)) (if name (with-output-language (CPS Stmt) `(def ,name ,expr)) expr)))))) (define (constant-fold op args) (define/nanopass (CPS Atom) (eval-atom ir) [(const ,c) c] [(lex ,n) (if-let-values [(_ v) (send transient-program load n)] v (raise ($non-static-eval "not in abstract heap" (current-continuation-marks))))] [(label ,n) (raise ($non-static-eval "label" (current-continuation-marks)))]) (with-output-language (CPS Expr) (with-handlers ([$non-static-eval? (lambda (_) #f)]) (match* (op (map eval-atom args)) [('__tupleLength `(,(? vector? tup))) `(const ,(vector-length tup))] [('__tupleGet `(,(? vector? tup) ,(? fixnum? i))) (if (< i (vector-length tup)) (vector-ref tup i) #f)] [('__iEq `(,(? fixnum? a) ,(? fixnum? b))) `(const ,(= a b))] ;; TODO: more operations... [(_ _) #f])))) ;;;; (define (eliminate-label-ref! application label usage-label) (if application (send transient-program remove-application! label usage-label) (send transient-program remove-escape! label usage-label)) (when (send transient-program unused? label) (EliminateCont (send transient-program cont-ref label) label)))) ;;;; ;; Process one function; driver loops and function merging. (CFG : CFG (ir fn-name) -> CFG () [(cfg ([,n* ,k*] ...) ,n) (parameterize ([current-fn fn-name]) (send transient-program enter-function! fn-name n* k* n) ; HACK? (define folded-worklist (make-queue)) ;; FoldCont in reverse postorder (since we only have DAG:s, topologically sorted order): (let loop () (while-let-values [(label cont) (send transient-program pop-orig-cont! fn-name)] (when-let [folded-cont (FoldCont cont label)] (enqueue-front! folded-worklist label) (send transient-program set-cont! label folded-cont))) ;; When at the end, try to expand CFG by merging in other functions that are only called ;; from here and never escape: (when (send transient-program fn-merge-into! fn-name) (loop))) ;; CompactCont in (reversed reverse) postorder: (while (non-empty-queue? folded-worklist) (let* ([label (dequeue! folded-worklist)] [cont (send transient-program cont-ref label)]) (when-let [compacted-cont (CompactCont cont label)] (send transient-program set-cont! label compacted-cont)))) (send transient-program build-cfg fn-name))]) ;;;; ;;; Elimination of dead/unreachable code, collecting information about variables and using said ;;; information for constant/copy propagation and constant folding. (FoldCont : Cont (ir label) -> Cont () [(cont (,n* ...) ,s* ... ,t) (parameterize ([current-label label]) (and (send transient-program used? (current-label)) (begin (send transient-program propagate-params! (current-label) n*) (let* ([stmts (filter-map FoldStmt s*)] [transfer (FoldTransfer t)]) `(cont (,n* ...) ,stmts ... ,transfer)))))]) (FoldStmt : Stmt (ir) -> Stmt () [(def ,n ,e) (fold-stmt n e)] [,e (fold-stmt #f e)]) (FoldExpr : Expr (ir) -> Expr () [(fn ,blocks) ir] [(primcall ,p ,a* ...) (define args (map FoldAtom a*)) (if-let [folded-expr (constant-fold p args)] (begin (DiscoverExpr folded-expr) (for-each EliminateAtom args) folded-expr) `(primcall ,p ,args ...))] [,a (FoldAtom a)]) (FoldTransfer : Transfer (ir) -> Transfer () [(continue ,x ,a* ...) `(continue ,(FoldCallee x) ,(map FoldAtom a*) ...)] [(if ,a? ,x1 ,x2) (define condition (FoldAtom a?)) (nanopass-case (CPS Atom) condition [(const ,c) (guard (eqv? c #t)) (EliminateVar x2) `(continue ,(FoldCallee x1))] [(const ,c) (guard (eqv? c #f)) (EliminateVar x1) `(continue ,(FoldCallee x2))] [else `(if ,condition ,(FoldCallee x1) ,(FoldCallee x2))])] [(call ,x1 ,x2 ,a* ...) `(call ,(FoldCallee x1) ,(FoldVar x2) ,(map FoldAtom a*) ...)] [(ffncall ,x1 ,x2 ,a* ...) `(ffncall ,(FoldVar x1) ,(FoldVar x2) ,(map FoldAtom a*) ...)] [(raise ,a) `(raise ,(FoldAtom a))] [(halt ,a) `(halt ,(FoldAtom a))]) (FoldAtom : Atom (ir) -> Atom () [,x (FoldVar x)] [(const ,c) ir]) (FoldVar : Var (ir) -> Atom () [(lex ,n) (define ir* (send transient-program propagated (current-fn) n ir)) (if (eq? ir ir*) ir* (begin (DiscoverAtom ir*) (EliminateVar ir) ir*))] [(label ,n) ir]) (FoldCallee : Var (ir) -> Var () [(lex ,n) (define ir* (send transient-program propagated (current-fn) n ir)) (if (eq? ir ir*) ir* (begin (DiscoverCallee ir*) (EliminateCallee ir) ir*))] [(label ,n) ir]) ;;;; ;;; More elimination of dead/unreachable code, beta-contraction of continuations (merging linear ;;; sequences of basic blocks). ;; TODO: CompactTransfer for basic block merging (CompactCont : Cont (ir label) -> Cont () [(cont (,n* ...) ,s* ... ,t) (parameterize ([current-label label]) (and (send transient-program used? (current-label)) (let*-values ([(stmts* transfer) (CompactTransfer t)]) (let* ([stmts (foldr (lambda (stmt stmts*) (if-let [stmt* (CompactStmt stmt)] (cons stmt* stmts*) stmts*)) stmts* s*)] [params (send transient-program compact-params! (current-label) n*)]) `(cont (,params ...) ,stmts ... ,transfer)))))]) (CompactStmt : Stmt (ir) -> Stmt () [(def ,n (fn ,blocks)) (guard (send transient-program integrated? n)) #f] [(def ,n ,e) (if (and (send transient-program unused? n) (pure? e)) (begin ; has become useless after StmtForward and needs to be eliminated now (EliminateExpr e) #f) (begin ; remove from abstract heap so that we don't try to inline recursive fns: (send transient-program deallocate! n) `(def ,n ,(CompactExpr e n))))] [,e ir]) (CompactExpr : Expr (ir name) -> Expr () [(fn ,blocks) `(fn ,(CFG blocks name))] [else ir]) (CompactTransfer : Transfer (ir) -> Stmt (transfer) [(continue (label ,n)) (guard (= (send transient-program total-usages n) 1)) (nanopass-case (CPS Cont) (send transient-program cont-ref n) [(cont () ,s* ... ,t) (send transient-program cont-forget! (current-fn) n) (values s* t)] [else (error "unreachable code reached in CompactTransfer")])] [else (values '() ir)]) ;;;; ;;; Elimination of labels and conts works similarly to a (naive) refcounting GC. Since CFG:s are ;;; DAG:s, this will eliminate all the code which becomes unused when the last reference to a ;;; continuation (i.e. some `(label ,n) Var) is eliminated. (EliminateCFG : CFG (ir) -> * () [(cfg ([,n* ,k*] ...) ,n) (eliminate-label-ref! #f n (current-label))]) (EliminateCont : Cont (ir label) -> * () [(cont (,n* ...) ,s* ... ,t) (parameterize ([current-label label]) (for-each EliminateStmt s*) (EliminateTransfer t))]) (EliminateStmt : Stmt (ir) -> * () [(def ,n ,e) (EliminateExpr e)] [,e (EliminateExpr e)]) (EliminateExpr : Expr (ir) -> * () [(fn ,blocks) (EliminateCFG blocks)] [(primcall ,p ,a* ...) (for-each EliminateAtom a*)] [,a (EliminateAtom a)]) (EliminateTransfer : Transfer (ir) -> * () [(continue ,x ,a* ...) (EliminateVar x) (for-each EliminateAtom a*)] [(if ,a? ,x1 ,x2) (EliminateAtom a?) (EliminateVar x1) (EliminateVar x2)] [(call ,x1 ,x2 ,a* ...) (EliminateVar x1) (EliminateVar x2) (for-each EliminateAtom a*)] [(ffncall ,x1 ,x2 ,a* ...) (EliminateVar x1) (EliminateVar x2) (for-each EliminateAtom a*)] [(raise ,a) (EliminateAtom a)] [(halt ,a) (EliminateAtom a)]) (EliminateAtom : Atom (ir) -> * () [,x (EliminateVar x)] [(const ,c) (void)]) (EliminateVar : Var (ir) -> * () [(lex ,n) (send transient-program remove-escape! n (current-label))] [(label ,n) (eliminate-label-ref! #f n (current-label))]) (EliminateCallee : Var (ir) -> * () [(lex ,n) (send transient-program remove-application! n (current-label))] [(label ,n) (eliminate-label-ref! #t n (current-label))]) ;;;; (DiscoverExpr : Expr (ir) -> * () [(fn ,blocks) (error "unimplemented")] [(primcall ,p ,a* ...) (for-each DiscoverAtom a*)] [,a (DiscoverAtom a)]) (DiscoverAtom : Atom (ir) -> * () [,x (DiscoverVar x)] [(const ,c) (void)]) (DiscoverVar : Var (ir) -> * () [(lex ,n) (send transient-program add-escape! n (current-label))] [(label ,n) (send transient-program add-escape! n (current-label))]) (DiscoverCallee : Var (ir) -> * () [(lex ,n) (send transient-program add-application! n (current-label))] [(label ,n) (send transient-program add-application! n (current-label))]) ;;;; (CFG ir #t))
false
a346864567099555b66e8ed3cda16d6e230bb459
cfdfa191f40601547140a63c31e933b16323cf84
/racket/monadic-eval/units/ev-unit.rkt
c105c0a44bf5f24aad7aeb6f255c0805b42cc557
[]
no_license
philnguyen/monadic-eval
6e3415512195d680551ce9203133281790feb7ef
ca1142fd932b17fee7d8e791519eaa8f11d9a9ef
refs/heads/master
2020-05-29T11:43:21.777045
2016-03-02T22:35:01
2016-03-02T22:35:01
53,002,423
0
0
null
2016-03-02T22:49:33
2016-03-02T22:49:32
null
UTF-8
Racket
false
false
1,048
rkt
ev-unit.rkt
#lang racket (require "../signatures.rkt" "../syntax.rkt") (provide ev@) (define-unit ev@ (import monad^ δ^ env^ sto^) (export ev^) (define ((ev e ρ) ev) (match e [(vbl x) (get ρ x)] [(num n) (return n)] [(lam x e) (return (cons (lam x e) ρ))] [(ifz e0 e1 e2) (do v ← (ev e0 ρ) (do b ← (truish? v) (if b (ev e1 ρ) (ev e2 ρ))))] [(op1 o e0) (do v ← (ev e0 ρ) (δ o v))] [(op2 o e0 e1) (do v0 ← (ev e0 ρ) v1 ← (ev e1 ρ) (δ o v0 v1))] [(lrc f (lam x e0) e) (do a ← (ralloc f (lam x e0) ρ) (ev e (ext ρ f a)))] [(app e0 e1) (do v0 ← (ev e0 ρ) v1 ← (ev e1 ρ) (match v0 [(cons (lam x e) ρ0) (do a ← (alloc v0 v1) (ev e (ext ρ0 x a)))]))])) (define-syntax do (syntax-rules (←) [(do b) b] [(do x ← e . r) (bind e (λ (x) (do . r)))])))
true
00168d70f6e8237dee178d77f64ba5db808aa7ab
11f85be1811cd5dcc10356fb0a8736330ef9a74d
/Labs/Lab 3/closures.rkt
c8a7d85e27f098973648635bb51ba692cea7a5bc
[]
no_license
br3nd4nn34l/CSC324-Fall-2016
9915b2e81b4019a9ee6ea75b7ed58ce33844ec90
490e28b9e6f870d553ba6bc7e39a34ebf9f753af
refs/heads/master
2021-04-29T06:22:40.147600
2017-01-04T01:46:33
2017-01-04T01:46:33
77,968,202
0
1
null
null
null
null
UTF-8
Racket
false
false
1,555
rkt
closures.rkt
#lang plai ; Some globals (define x 20) (define y "Hi") ; A function with a parameter shadowing the global definition (define (f x) (+ x x)) ; TODO: Uncomment and fill in the expected value (test (f 2) 4) ; A function that returns a function, using its parameter (define (maker n) (lambda (m) (- n m))) (test ((maker 3) 10) -7) ; A function that returns a function, using a global variable (define (maker-2 n) (lambda (m) (- x m))) (test ((maker-2 3) 10) 10) ; A function that returns a function, using a local variable. ; Also, variable shadowing (why?) (define (maker-3 n y) (let ([y "byeee"]) (lambda (m) (+ n m (string-length y))))) (test ((maker-3 3 15) 20) 28) ; A function that returns a higher-order function (define (maker-4 n) (lambda (f x) (f (+ x n)))) ; TODO: write your own test(s)! (test ((maker-4 15) f 4) 38) (test ((maker-4 17) f 1) 36) ; A function in a let, with shadowing (define let-ex (let* ([x 15] [y (- x 6)]) (lambda (y) (- x y)))) (test (let-ex 3) 12) ; Combining everything (define let-ex-2 (let ([a 15]) ; a = 15 (lambda (y) (let ([b (+ a 5)] ;b = 20 [a 11]) ; a = 11 (lambda (z) (+ (- z y) (- a b))))))); (z - y) + (11 - 20) = (z - y) - 9 = z - y - 9 (test ((let-ex-2 1) 0) -10); ; Last one - lexical vs. dynamic scope ; The const being used is the one defined outside the scope of the let (define const 10) (define (let-ex-3 y) (lambda (z) (+ y (- z const)))) (test (let* ([const 1] [y 2] [z 3]) ((let-ex-3 1) 5)) -4)
false
b00cf5ec7e3f748e8772cd1e53ae65af7b218b37
acb237f6b9091540474140000c222070f65059a4
/src/popl-2022/background.scrbl
72b9c784c58cfd1cfff5b135b0e82132d6a05686
[ "MIT" ]
permissive
bennn/g-pldi-2022
6fef876fb332b9113f4ab2af4072a628d276b2c5
299d4d4c285cbdc2a3139b2c9b1168eff9fd79f6
refs/heads/master
2023-09-05T14:01:06.805156
2022-06-18T20:54:25
2022-06-18T20:54:28
338,459,955
4
0
null
null
null
null
UTF-8
Racket
false
false
7,713
scrbl
background.scrbl
#lang scribble/acmart @acmsmall @10pt @screen @(require "main.rkt" "bib.rkt" (only-in scriblib/footnote note) (only-in "pict.rkt" fig:ds-example)) @; THESIS Natural and Transient are the only realistic options @; - more imagined ideas in JFP submission @; - side benefit, explore two extremes (wrappers / none) @; - don't justify TR, we are simply using it @; - keep this short, get to the model asap @title[#:tag "sec:background"]{Background} @section{Gradual Typing, Migratory Typing, Mixed-Typed Code} @; TODO focus on research, not people For the past two decades, researchers have been investigating methods to combine static and dynamic typing@~cite{st-sfp-2006,tf-dls-2006,mf-toplas-2009,gktff-sfp-2006}. The ultimate goal of these efforts is a mixed-typed (or gradual@note{Following @citet{svcb-snapl-2015}, we prefer to reserve the name @emph{gradual} for mixed-typed languages with a dynamic type that satisfies the gradual guarantees / graduality@~cite{nla-popl-2019}.}) language that supports two styles of code in a convenient manner. Untyped code is free to perform any computation that the language can express. Typed code is restricted to a subset of well-typed computations, but comes with a guarantee that static types are meaningful predictions about run-time behaviors. Distinctions arise over what makes for a convenient mix. Gradually-typed languages include a universal @tt{Dynamic} type that helps to blur the distinction between typed and untyped code@~cite{svcb-snapl-2015}. Migratory typing systems add idiomatic types to an existing language@~cite{tfffgksst-snapl-2017} Other methods include the development of novel languages@~cite{wnlov-popl-2010,mt-oopsla-2017,kas-pldi-2019,rmhn-ecoop-2019} and/or compilers@~cite{rat-oopsla-2017,bbst-oopsla-2017}. The goal of this paper is to advance the state of mixed-typed languages in a general setting. Consequently, the formal development adheres to two ground rules: @itemlist[#:style 'ordered @item{ Use ahead-of-time techniques to enforce types at run-time. } @item{ Focus on the interactions between conventional types and untyped code. } ] @|noindent|These rules ensure a widely-applicable baseline. Specializations are a promising subject for future work. Advanced mechanisms for checking types may yield better performance@~cite{kas-pldi-2019,vsc-dls-2019,bbst-oopsla-2017,rmhn-ecoop-2019}. Gradual languages can motivate the addition of a dynamic type. @section{@|sDeep| and @|sShallow| Types} @(define untyped-fn @tt{text}) Within the realm of sound mixed-typed languages, designs do not agree on how types should guide the behavior of a program. Two leading alternative for run-time properties are @|sdeep| and @|sshallow| types. Roughly speaking, @|sdeep| types try to be equally strong as conventional static types while @|sshallow| types strike a balance between guarantees and pragmatic benefits. @Figure-ref{fig:ds-example} presents a three-module program to illustrate the gap between @|sdeep| and @|sshallow|. The untyped module on the left contains a stub definition for a function @|untyped-fn| that accepts two arguments. This module is a greatly simplified picture of Racket's @tt{images/icons/symbol} module, which incorporates thousands of lines of rendering and raytracing code. The typed module in the middle is an interface for the untyped function. The types correctly state that @|untyped-fn| expects a string and a font object and computes a bitmap object. Finally, the untyped client module on the right mistakenly calls @|untyped-fn| with two strings instead of one string and one font object. @figure*[ "fig:ds-example" @elem{Untyped library, typed interface, and untyped client} fig:ds-example] The question raised by this example is whether static types can catch the mistake in the untyped client. @|sDeep| and @|sshallow| types give opposite answers: @itemlist[ @item{ @|sDeep| types enforce the interface with run-time obligations for both the client and the library. In this case, the client triggers a run-time error because the type asks for a font object. } @item{ @|sShallow| types guarantee the local integrity of typed code, but nothing more. The untyped client is allowed to send any input to the untyped @|untyped-fn| function, including two strings. }] @; TODO be clearer about strong vs weak soundness? May help with understanding From a theoretical perspective, @|sshallow| types satisfy a type soundness property and nothing more@~cite{vss-popl-2017,gf-icfp-2018}. Soundness states that the type of an expression predicts the kinds of values that evaluation can produce. In typed code, these predictions are often useful; for example, an expression with a function type cannot evaluate to a number. The catch is that untyped code makes trivial predictions; soundness merely ensures a well-formed result. The property that distinguishes @|sdeep| types from @|sshallow| is complete monitoring@~cite{dtf-esop-2012,gfd-oopsla-2019}. A semantics that satisfies complete monitoring is able to enforce type obligations on every interaction, thus giving an interface the ability to constrain behaviors. @section{@|sNatural| Semantics} One way to implement @|sdeep| types is the @|sNatural| (aka. guarded) semantics@~cite{tf-dls-2006,mf-toplas-2009,st-sfp-2006} Natural interprets types as contracts in a straightforward manner.@note{ Researchers are actively seeking improved variants of @|sNatural|@~cite{htf-hosc-2010,g-popl-2015,stw-pldi-2015,gct-popl-2016} and measuring the efficiency of implementations@~cite{fgsfs-oopsla-2018,kas-pldi-2019}. Theoretical results about @|sNatural| automatically apply to these semantics-preserving variants. } For example, base types are enforced by predicate checks, types for immutable data are enforced by first-order traversals, and types for higher-order data such as arrays and functions are enforced by higher-order contracts. Because each contract fully enforces a type, these contracts need only guard the boundaries between typed and untyped code. Within typed modules, code can run efficiently and employ the same type-directed optimizations as any non-mixed typed language. @section{@|sTransient| Semantics} The @|sTransient| semantics is an implementation of @|sshallow| types that does not require higher-order wrappers@~cite{vss-popl-2017}. @|sTransient| protects typed code by rewriting it to include simple first-order checks. These checks guard the boundaries between typed and untyped code, but also appear throughout typed modules. Typed, public functions must check their inputs Typed expressions must check the results computed during a function call, the elements extracted from a data structure, and the outcome of any type-level downcasts. This pay-as-you go strategy means that every new line of typed code may impose a cost, but the unit cost of each check is typically low. @;@section{Why @|sTransient| and @|sNatural|?} @; @; 2021-06-30 : the intro already covers this @; @;@|sNatural| and @|sTransient| are prime candidates for a three-way combination @;because they explore distinct points in a complex design space. @;@|sNatural| depends critically on higher-order contracts, and can impose a @;high run-time cost if the boundaries in a codebase call for frequent and @;layered contract checks@~cite{tfgnvf-popl-2016,gtnffvf-jfp-2019}. @;@|sTransient| takes an opposite, first-order approach and spreads checks @;throughout typed code. @;Having the ability to switch between @|snatural| and @|stransient| might address @;the shortcomings of each. @;Additionally, if these semantics can interoperate then other less-extreme @;combinations should be well in reach.
false
48efbc5738dff88cb11fe72c15aa749cd3364511
2767601ac7d7cf999dfb407a5255c5d777b7b6d6
/examples/make-mood-ring.rkt
30b2603eabf0cc1f8741a83442de8d22add240e4
[]
no_license
manbaum/moby-scheme
7fa8143f3749dc048762db549f1bcec76b4a8744
67fdf9299e9cf573834269fdcb3627d204e402ab
refs/heads/master
2021-01-18T09:17:10.335355
2011-11-08T01:07:46
2011-11-08T01:07:46
null
0
0
null
null
null
null
UTF-8
Racket
false
false
111
rkt
make-mood-ring.rkt
#lang racket (require (planet dyoo/moby:3:9)) (create-android-phone-package "mood-ring.rkt" "mood.apk")
false
b11c21d7939ba1fab5219e5bf74f0354c63df5a7
9dc77b822eb96cd03ec549a3a71e81f640350276
/streaming/transducer/private/transposing-test.rkt
16525999d6874fab268dffc248c5bc6d79ed1860
[ "Apache-2.0" ]
permissive
jackfirth/rebellion
42eadaee1d0270ad0007055cad1e0d6f9d14b5d2
69dce215e231e62889389bc40be11f5b4387b304
refs/heads/master
2023-03-09T19:44:29.168895
2023-02-23T05:39:33
2023-02-23T05:39:33
155,018,201
88
21
Apache-2.0
2023-09-07T03:44:59
2018-10-27T23:18:52
Racket
UTF-8
Racket
false
false
15,469
rkt
transposing-test.rkt
#lang racket/base (module+ test (require racket/sequence racket/stream rackunit rebellion/base/comparator rebellion/collection/list rebellion/private/static-name rebellion/streaming/transducer rebellion/streaming/transducer/testing rebellion/type/record)) ;@---------------------------------------------------------------------------------------------------- (module+ test (test-case (name-string transposing) (test-case "nonterminating column reducer" (test-case "no input" (define actual (transduce '() (observing-transduction-events (transposing #:into into-list)) #:into into-list)) (check-equal? actual (list start-event half-close-event finish-event))) (test-case "single empty list" (define actual (transduce (list '()) (observing-transduction-events (transposing #:into into-list)) #:into into-list)) (check-equal? actual (list start-event (consume-event '()) finish-event))) (test-case "multiple empty lists" (define actual (transduce (list '() '() '()) (observing-transduction-events (transposing #:into into-list)) #:into into-list)) (define expected (list start-event (consume-event '()) finish-event)) (check-equal? actual expected)) (test-case "infinite empty lists" (define actual (transduce (for/stream ([_ (in-naturals)]) '()) (observing-transduction-events (transposing #:into into-list)) #:into into-list)) (define expected (list start-event (consume-event '()) finish-event)) (check-equal? actual expected)) (test-case "single list" (define actual (transduce (list (list 1 2 3)) (observing-transduction-events (transposing #:into into-list)) #:into into-list)) (define expected (list start-event (consume-event (list 1 2 3)) half-close-event (half-closed-emit-event (list 1)) (half-closed-emit-event (list 2)) (half-closed-emit-event (list 3)) finish-event)) (check-equal? actual expected)) (test-case "multiple singleton lists" (define actual (transduce (list (list 1) (list 2) (list 3)) (observing-transduction-events (transposing #:into into-list)) #:into into-list)) (define expected (list start-event (consume-event (list 1)) (consume-event (list 2)) (consume-event (list 3)) half-close-event (half-closed-emit-event (list 1 2 3)) finish-event)) (check-equal? actual expected)) (test-case "multiple lists" (define actual (transduce (list (list 1 2 3) (list 4 5 6) (list 7 8 9)) (observing-transduction-events (transposing #:into into-list)) #:into into-list)) (define expected (list start-event (consume-event (list 1 2 3)) (consume-event (list 4 5 6)) (consume-event (list 7 8 9)) half-close-event (half-closed-emit-event (list 1 4 7)) (half-closed-emit-event (list 2 5 8)) (half-closed-emit-event (list 3 6 9)) finish-event)) (check-equal? actual expected))) (test-case "terminating reducer" (define into-list-while-positive (into-transduced (taking-while positive?) #:into into-list)) (test-case "no input" (define actual (transduce '() (observing-transduction-events (transposing #:into into-list-while-positive)) #:into into-list)) (define expected (list start-event half-close-event finish-event)) (check-equal? actual expected)) (test-case "single empty list" (define actual (transduce (list '()) (observing-transduction-events (transposing #:into into-list-while-positive)) #:into into-list)) (define expected (list start-event (consume-event '()) finish-event)) (check-equal? actual expected)) (test-case "multiple empty lists" (define actual (transduce (list '() '() '()) (observing-transduction-events (transposing #:into into-list-while-positive)) #:into into-list)) (define expected (list start-event (consume-event '()) finish-event)) (check-equal? actual expected)) (test-case "infinite empty lists" (define actual (transduce (for/stream ([_ (in-naturals)]) '()) (observing-transduction-events (transposing #:into into-list-while-positive)) #:into into-list)) (define expected (list start-event (consume-event '()) finish-event)) (check-equal? actual expected)) (test-case "multiple singleton lists" (define actual (transduce (list (list 1) (list 2) (list 3)) (observing-transduction-events (transposing #:into into-list-while-positive)) #:into into-list)) (define expected (list start-event (consume-event (list 1)) (consume-event (list 2)) (consume-event (list 3)) half-close-event (half-closed-emit-event (list 1 2 3)) finish-event)) (check-equal? actual expected)) (test-case "multiple singleton lists with stop" (define actual (transduce (list (list 1) (list 2) (list 3) (list 0) (list 4)) (observing-transduction-events (transposing #:into into-list-while-positive)) #:into into-list)) (define expected (list start-event (consume-event (list 1)) (consume-event (list 2)) (consume-event (list 3)) (consume-event (list 0)) (half-closed-emit-event (list 1 2 3)) finish-event)) (check-equal? actual expected)) (test-case "infinite singleton lists with stop" (define input (sequence-append (list (list 1) (list 2) (list 3) (list 0)) (for/stream ([n (in-naturals 4)]) (list n)))) (define actual (transduce input (observing-transduction-events (transposing #:into into-list-while-positive)) #:into into-list)) (define expected (list start-event (consume-event (list 1)) (consume-event (list 2)) (consume-event (list 3)) (consume-event (list 0)) (half-closed-emit-event (list 1 2 3)) finish-event)) (check-equal? actual expected)) (test-case "multiple lists" (define actual (transduce (list (list 1 2 3) (list 4 5 6) (list 7 8 9)) (observing-transduction-events (transposing #:into into-list-while-positive)) #:into into-list)) (define expected (list start-event (consume-event (list 1 2 3)) (consume-event (list 4 5 6)) (consume-event (list 7 8 9)) half-close-event (half-closed-emit-event (list 1 4 7)) (half-closed-emit-event (list 2 5 8)) (half-closed-emit-event (list 3 6 9)) finish-event)) (check-equal? actual expected)) (test-case "multiple lists with first column stopping" (define actual (transduce (list (list 1 2 3) (list 0 5 6) (list 7 8 9)) (observing-transduction-events (transposing #:into into-list-while-positive)) #:into into-list)) (define expected (list start-event (consume-event (list 1 2 3)) (consume-event (list 0 5 6)) (emit-event (list 1)) (consume-event (list 7 8 9)) half-close-event (half-closed-emit-event (list 2 5 8)) (half-closed-emit-event (list 3 6 9)) finish-event)) (check-equal? actual expected)) (test-case "multiple lists with first column stopping with unordered columns" (define actual (transduce (list (list 1 2 3) (list 0 5 6) (list 7 8 9)) (observing-transduction-events (transposing #:into into-list-while-positive #:ordered? #false)) #:into into-list)) (define expected (list start-event (consume-event (list 1 2 3)) (consume-event (list 0 5 6)) (emit-event (list 1)) (consume-event (list 7 8 9)) half-close-event (half-closed-emit-event (list 2 5 8)) (half-closed-emit-event (list 3 6 9)) finish-event)) (check-equal? actual expected)) (test-case "multiple lists with last column stopping" (define actual (transduce (list (list 1 2 3) (list 4 5 0) (list 7 8 9)) (observing-transduction-events (transposing #:into into-list-while-positive)) #:into into-list)) (define expected (list start-event (consume-event (list 1 2 3)) (consume-event (list 4 5 0)) (consume-event (list 7 8 9)) half-close-event (half-closed-emit-event (list 1 4 7)) (half-closed-emit-event (list 2 5 8)) (half-closed-emit-event (list 3)) finish-event)) (check-equal? actual expected)) (test-case "multiple lists with last column stopping with unordered columns" (define actual (transduce (list (list 1 2 3) (list 4 5 0) (list 7 8 9)) (observing-transduction-events (transposing #:into into-list-while-positive #:ordered? #false)) #:into into-list)) (define expected (list start-event (consume-event (list 1 2 3)) (consume-event (list 4 5 0)) (emit-event (list 3)) (consume-event (list 7 8 9)) half-close-event (half-closed-emit-event (list 1 4 7)) (half-closed-emit-event (list 2 5 8)) finish-event)) (check-equal? actual expected)) (test-case "multiple lists with all stopping simultaneously" (define actual (transduce (list (list 1 2 3) (list 0 0 0) (list 7 8 9)) (observing-transduction-events (transposing #:into into-list-while-positive)) #:into into-list)) (define expected (list start-event (consume-event (list 1 2 3)) (consume-event (list 0 0 0)) (half-closed-emit-event (list 1)) (half-closed-emit-event (list 2)) (half-closed-emit-event (list 3)) finish-event)) (check-equal? actual expected)) (test-case "multiple lists with all stopping separately" (define actual (transduce (list (list 1 2 3) (list 4 0 6) (list 0 8 9) (list 0 0 0) (list 0 0 0)) (observing-transduction-events (transposing #:into into-list-while-positive)) #:into into-list)) (define expected (list start-event (consume-event (list 1 2 3)) (consume-event (list 4 0 6)) (consume-event (list 0 8 9)) (emit-event (list 1 4)) (emit-event (list 2)) (consume-event (list 0 0 0)) (half-closed-emit-event (list 3 6 9)) finish-event)) (check-equal? actual expected)) (test-case "multiple lists with all stopping separately with unordered columns" (define actual (transduce (list (list 1 2 3) (list 4 0 6) (list 0 8 9) (list 0 0 0) (list 0 0 0)) (observing-transduction-events (transposing #:into into-list-while-positive #:ordered? #false)) #:into into-list)) (define expected (list start-event (consume-event (list 1 2 3)) (consume-event (list 4 0 6)) (emit-event (list 2)) (consume-event (list 0 8 9)) (emit-event (list 1 4)) (consume-event (list 0 0 0)) (half-closed-emit-event (list 3 6 9)) finish-event)) (check-equal? actual expected)) (test-case "multiple lists with all stopping separately with multiple batches of columns" (define actual (transduce (list (list 1 2 3 4 5) (list 1 0 3 4 0) (list 0 0 3 0 0) (list 0 0 3 0 0) (list 0 0 0 0 0) (list 0 0 0 0 0)) (observing-transduction-events (transposing #:into into-list-while-positive)) #:into into-list)) (define expected (list start-event (consume-event (list 1 2 3 4 5)) (consume-event (list 1 0 3 4 0)) (consume-event (list 0 0 3 0 0)) (emit-event (list 1 1)) (emit-event (list 2)) (consume-event (list 0 0 3 0 0)) (consume-event (list 0 0 0 0 0)) (half-closed-emit-event (list 3 3 3 3)) (half-closed-emit-event (list 4 4)) (half-closed-emit-event (list 5)) finish-event)) (check-equal? actual expected)) (test-case "multiple lists with all stopping separately with multiple batches of columns unordered" (define actual (transduce (list (list 1 2 3 4 5) (list 1 0 3 4 0) (list 0 0 3 0 0) (list 0 0 3 0 0) (list 0 0 0 0 0) (list 0 0 0 0 0)) (observing-transduction-events (transposing #:into into-list-while-positive #:ordered? #false)) #:into into-list)) (define expected (list start-event (consume-event (list 1 2 3 4 5)) (consume-event (list 1 0 3 4 0)) (emit-event (list 2)) (emit-event (list 5)) (consume-event (list 0 0 3 0 0)) (emit-event (list 1 1)) (emit-event (list 4 4)) (consume-event (list 0 0 3 0 0)) (consume-event (list 0 0 0 0 0)) (half-closed-emit-event (list 3 3 3 3)) finish-event)) (check-equal? actual expected)))))
false
d77682a4bb807e8ae12cf11ec87a73fc7a7505e9
4c2dc47a9d9aa20d516a3a70d12d4e33ea28984b
/examples/golden-mean.rkt
e94b0a27f146ebb54ca4faef9e5008f45fbc1a10
[ "CC-BY-4.0" ]
permissive
rfindler/lindenmayer
92c0d0bafdc9097ba60a7dea73a548b5eb27e8b7
695db090aa4cfdb9338cd34ad0a0b8f72b698a54
refs/heads/master
2023-03-13T01:13:59.554157
2023-03-04T16:21:58
2023-03-04T16:50:37
83,209,018
27
4
null
2017-03-05T03:55:58
2017-02-26T13:06:46
Racket
UTF-8
Racket
false
false
766
rkt
golden-mean.rkt
#lang lindenmayer typed/racket ## axiom ## A ## rules ## A -> AB B -> A ## variables ## n=20 ===================================== (provide (all-defined-out)) (: start (-> (HashTable Symbol Real) (Pair Natural Natural))) (define (start variables) (cons 0 0)) (: finish (-> (Pair Natural Natural) (HashTable Symbol Real) Real)) (define (finish pr variables) (/ (car pr) (cdr pr))) (: A (-> (Pair Natural Natural) (HashTable Symbol Real) (Pair Natural Natural))) (define (A pr variables) (cons (+ (car pr) 1) (cdr pr))) (: B (-> (Pair Natural Natural) (HashTable Symbol Real) (Pair Natural Natural))) (define (B pr variables) (cons (car pr) (+ (cdr pr) 1)))
false
e0e0cb68b1eb929a995a96f0fae3d4adb20d7078
73e08bc49ae7a2dae6ed6b828ff3b504c497f6b8
/bench/tptp/ALG197-plain-sat.rkt
af42658de1cc824f139bfc585a463755ea8dc77f
[ "BSD-2-Clause" ]
permissive
altanh/colocolo
9d44efba4d1e0d02927fa371c94d0dae59c92e99
a7a6aeff4d166c0fa3950079f61c7a1da5f17801
refs/heads/master
2020-04-22T18:23:11.311752
2019-03-15T17:38:11
2019-03-15T17:38:11
170,575,439
2
0
null
null
null
null
UTF-8
Racket
false
false
46,130
rkt
ALG197-plain-sat.rkt
#lang rosette (require colocolo colocolo/lang/ast colocolo/engine/interpretation colocolo/lang/bounds colocolo/engine/sat/solver colocolo/lib/skolemize-solve colocolo/engine/symmetry) (define universe$0 (universe (list "e10" "e11" "e12" "e13" "e14" "e15" "e16" "e20" "e21" "e22" "e23" "e24" "e25" "e26"))) (define v$49 (declare-relation 1 "y")) (define v$53 (declare-relation 1 "y")) (define r$12 (declare-relation 2 "h3")) (define v$22 (declare-relation 1 "x")) (define v$27 (declare-relation 1 "y")) (define r$7 (declare-relation 3 "op2")) (define v$11 (declare-relation 1 "vh2")) (define v$25 (declare-relation 1 "x")) (define v$42 (declare-relation 1 "x")) (define r$20 (declare-relation 2 "h7")) (define r$16 (declare-relation 2 "h5")) (define v$24 (declare-relation 1 "y")) (define v$9 (declare-relation 1 "vh1")) (define r$39 (declare-relation 1 "e24")) (define r$40 (declare-relation 1 "e25")) (define r$29 (declare-relation 1 "e11")) (define r$38 (declare-relation 1 "e23")) (define r$18 (declare-relation 2 "h6")) (define v$46 (declare-relation 1 "x")) (define r$10 (declare-relation 2 "h2")) (define v$55 (declare-relation 1 "y")) (define r$35 (declare-relation 1 "e20")) (define v$44 (declare-relation 1 "x")) (define r$3 (declare-relation 3 "op1")) (define r$8 (declare-relation 2 "h1")) (define v$47 (declare-relation 1 "y")) (define v$4 (declare-relation 1 "x")) (define v$21 (declare-relation 1 "vh7")) (define v$17 (declare-relation 1 "vh5")) (define r$30 (declare-relation 1 "e12")) (define r$1 (declare-relation 1 "e1")) (define v$19 (declare-relation 1 "vh6")) (define v$54 (declare-relation 1 "x")) (define v$15 (declare-relation 1 "vh4")) (define r$5 (declare-relation 1 "e2")) (define v$48 (declare-relation 1 "x")) (define v$6 (declare-relation 1 "y")) (define v$0 (declare-relation 1 "x")) (define r$34 (declare-relation 1 "e16")) (define r$36 (declare-relation 1 "e21")) (define v$26 (declare-relation 1 "x")) (define r$32 (declare-relation 1 "e14")) (define v$2 (declare-relation 1 "y")) (define v$23 (declare-relation 1 "x")) (define r$41 (declare-relation 1 "e26")) (define v$43 (declare-relation 1 "y")) (define v$52 (declare-relation 1 "x")) (define r$33 (declare-relation 1 "e15")) (define r$28 (declare-relation 1 "e10")) (define r$37 (declare-relation 1 "e22")) (define r$14 (declare-relation 2 "h4")) (define r$31 (declare-relation 1 "e13")) (define v$50 (declare-relation 1 "x")) (define v$51 (declare-relation 1 "y")) (define v$45 (declare-relation 1 "y")) (define v$13 (declare-relation 1 "vh3")) (define b-ex$322 (join r$30 r$18)) (define b-ex$318 (join r$29 r$18)) (define b-ex$25 (join v$11 r$10)) (define b-ex$374 (join v$45 r$3)) (define b-ex$111 (join r$28 r$3)) (define decl$0 (cons v$0 r$1 #|one|#)) (define b-ex$438 (join v$55 r$20)) (define decl$396 (cons v$49 r$1 #|one|#)) (define b-ex$274 (join r$29 r$14)) (define b-ex$216 (join r$31 r$8)) (define b-ex$348 (join r$31 r$20)) (define b-ex$335 (join r$28 r$20)) (define b-ex$402 (join v$49 r$14)) (define decl$408 (cons v$51 r$1 #|one|#)) (define b-ex$234 (join r$30 r$10)) (define b-ex$434 (join v$55 r$3)) (define b-ex$241 (join r$32 r$10)) (define b-ex$336 (join r$41 r$7)) (define decl$372 (cons v$45 r$1 #|one|#)) (define b-ex$282 (join r$31 r$14)) (define b-ex$117 (join r$30 r$3)) (define decl$64 (cons v$21 r$1 #|one|#)) (define b-ex$304 (join r$31 r$16)) (define b-ex$160 (join r$41 r$7)) (define b-ex$62 (-> r$1 r$5)) (define b-ex$65 (join v$21 r$20)) (define b-ex$362 (join v$43 r$3)) (define b-ex$120 (join r$31 r$3)) (define decl$359 (cons v$42 r$1 #|one|#)) (define decl$71 (cons v$22 r$1 #|one|#)) (define b-ex$437 (join v$54 r$20)) (define b-ex$389 (join v$46 r$12)) (define b-ex$41 (join v$15 r$14)) (define b-ex$203 (join r$28 r$8)) (define b-ex$344 (join r$30 r$20)) (define b-ex$54 (-> r$1 r$5)) (define decl$32 (cons v$13 r$1 #|one|#)) (define b-ex$157 (join r$40 r$7)) (define b-ex$386 (join v$47 r$3)) (define b-ex$230 (join r$29 r$10)) (define b-ex$270 (join r$38 r$7)) (define decl$371 (cons v$44 r$1 #|one|#)) (define b-ex$247 (join r$28 r$12)) (define b-ex$260 (join r$31 r$12)) (define b-ex$307 (join r$32 r$16)) (define b-ex$288 (join r$33 r$14)) (define b-ex$244 (join r$33 r$10)) (define b-ex$291 (join r$28 r$16)) (define b-ex$219 (join r$32 r$8)) (define b-ex$85 (join v$24 r$3)) (define b-ex$95 (join v$25 r$7)) (define b-ex$10 (join v$4 r$7)) (define decl$40 (cons v$15 r$1 #|one|#)) (define decl$16 (cons v$9 r$1 #|one|#)) (define decl$7 (cons v$4 r$5 #|one|#)) (define b-ex$269 (join r$28 r$14)) (define b-ex$410 (join v$51 r$3)) (define b-ex$285 (join r$32 r$14)) (define decl$101 (cons v$27 r$5 #|one|#)) (define decl$431 (cons v$54 r$1 #|one|#)) (define b-ex$425 (join v$52 r$18)) (define b-ex$22 (-> r$1 r$5)) (define b-ex$123 (join r$32 r$3)) (define b-ex$310 (join r$33 r$16)) (define decl$100 (cons v$26 r$5 #|one|#)) (define b-ex$426 (join v$53 r$18)) (define b-ex$300 (join r$30 r$16)) (define decl$360 (cons v$43 r$1 #|one|#)) (define b-ex$105 (join v$27 r$7)) (define b-ex$422 (join v$53 r$3)) (define b-ex$33 (join v$13 r$12)) (define b-ex$126 (join r$33 r$3)) (define b-ex$154 (join r$39 r$7)) (define decl$432 (cons v$55 r$1 #|one|#)) (define b-ex$314 (join r$40 r$7)) (define b-ex$366 (join v$43 r$8)) (define decl$24 (cons v$11 r$1 #|one|#)) (define b-ex$222 (join r$33 r$8)) (define b-ex$351 (join r$32 r$20)) (define b-ex$354 (join r$33 r$20)) (define b-ex$14 (-> r$1 r$5)) (define b-ex$326 (join r$31 r$18)) (define decl$80 (cons v$23 r$1 #|one|#)) (define decl$48 (cons v$17 r$1 #|one|#)) (define b-ex$296 (join r$29 r$16)) (define decl$419 (cons v$52 r$1 #|one|#)) (define b-ex$212 (join r$30 r$8)) (define decl$384 (cons v$47 r$1 #|one|#)) (define b-ex$173 (join r$34 r$3)) (define b-ex$377 (join v$44 r$10)) (define b-ex$49 (join v$17 r$16)) (define decl$91 (cons v$25 r$5 #|one|#)) (define decl$383 (cons v$46 r$1 #|one|#)) (define b-ex$340 (join r$29 r$20)) (define decl$56 (cons v$19 r$1 #|one|#)) (define b-ex$92 (join r$5 r$7)) (define b-ex$72 (join r$1 r$3)) (define b-ex$103 (join v$26 r$7)) (define b-ex$46 (-> r$1 r$5)) (define b-ex$57 (join v$19 r$18)) (define b-ex$38 (-> r$1 r$5)) (define b-ex$390 (join v$47 r$12)) (define b-ex$313 (join r$28 r$18)) (define b-ex$204 (join r$35 r$7)) (define b-ex$148 (join r$37 r$7)) (define b-ex$87 (join v$24 r$3)) (define b-ex$30 (-> r$1 r$5)) (define b-ex$263 (join r$32 r$12)) (define b-ex$292 (join r$39 r$7)) (define decl$81 (cons v$24 r$1 #|one|#)) (define b-ex$329 (join r$32 r$18)) (define b-ex$365 (join v$42 r$8)) (define b-ex$83 (join v$23 r$3)) (define b-ex$256 (join r$30 r$12)) (define b-ex$208 (join r$29 r$8)) (define decl$420 (cons v$53 r$1 #|one|#)) (define b-ex$332 (join r$33 r$18)) (define b-ex$401 (join v$48 r$14)) (define b-ex$129 (join r$34 r$3)) (define b-ex$142 (join r$35 r$7)) (define b-ex$252 (join r$29 r$12)) (define b-ex$398 (join v$49 r$3)) (define b-ex$248 (join r$37 r$7)) (define b-ex$114 (join r$29 r$3)) (define b-ex$225 (join r$28 r$10)) (define b-ex$226 (join r$36 r$7)) (define decl$8 (cons v$6 r$5 #|one|#)) (define b-ex$75 (join v$22 r$3)) (define b-ex$266 (join r$33 r$12)) (define b-ex$278 (join r$30 r$14)) (define b-ex$3 (join v$0 r$3)) (define b-ex$17 (join v$9 r$8)) (define b-ex$107 (join v$27 r$7)) (define decl$1 (cons v$2 r$1 #|one|#)) (define b-ex$145 (join r$36 r$7)) (define b-ex$151 (join r$38 r$7)) (define b-ex$238 (join r$31 r$10)) (define b-ex$378 (join v$45 r$10)) (define decl$407 (cons v$50 r$1 #|one|#)) (define b-ex$414 (join v$51 r$16)) (define decl$395 (cons v$48 r$1 #|one|#)) (define b-ex$413 (join v$50 r$16)) (define b-ex$188 (join r$41 r$7)) (define b-ex$152 (join r$38 b-ex$151)) (define b-ex$93 (join v$25 b-ex$92)) (define b-ex$149 (join r$37 b-ex$148)) (define b-ex$249 (join r$37 b-ex$248)) (define b-ex$391 (join b-ex$390 r$7)) (define decls$385 (list decl$383 decl$384)) (define b-ex$112 (join r$28 b-ex$111)) (define b-ex$11 (join v$6 b-ex$10)) (define cmp-f$47 (in r$16 b-ex$46)) (define decls$102 (list decl$100 decl$101)) (define b-ex$4 (join v$2 b-ex$3)) (define b-ex$403 (join b-ex$402 r$7)) (define mul-f$58 (multiplicity-formula 'one b-ex$57)) (define mul-f$34 (multiplicity-formula 'one b-ex$33)) (define decls$373 (list decl$371 decl$372)) (define b-ex$130 (join r$34 b-ex$129)) (define decls$409 (list decl$407 decl$408)) (define b-ex$379 (join b-ex$378 r$7)) (define b-ex$146 (join r$36 b-ex$145)) (define b-ex$96 (join r$5 b-ex$95)) (define b-ex$439 (join b-ex$438 r$7)) (define mul-f$26 (multiplicity-formula 'one b-ex$25)) (define b-ex$423 (join v$52 b-ex$422)) (define cmp-f$55 (in r$18 b-ex$54)) (define b-ex$415 (join b-ex$414 r$7)) (define b-ex$205 (join r$35 b-ex$204)) (define decls$421 (list decl$419 decl$420)) (define cmp-f$63 (in r$20 b-ex$62)) (define mul-f$66 (multiplicity-formula 'one b-ex$65)) (define b-ex$227 (join r$36 b-ex$226)) (define b-ex$271 (join r$38 b-ex$270)) (define b-ex$189 (join r$41 b-ex$188)) (define b-ex$104 (join v$27 b-ex$103)) (define decls$82 (list decl$80 decl$81)) (define b-ex$158 (join r$40 b-ex$157)) (define b-ex$115 (join r$29 b-ex$114)) (define b-ex$84 (join v$24 b-ex$83)) (define b-ex$155 (join r$39 b-ex$154)) (define b-ex$124 (join r$32 b-ex$123)) (define mul-f$42 (multiplicity-formula 'one b-ex$41)) (define cmp-f$39 (in r$14 b-ex$38)) (define b-ex$435 (join v$54 b-ex$434)) (define decls$361 (list decl$359 decl$360)) (define b-ex$387 (join v$46 b-ex$386)) (define decls$397 (list decl$395 decl$396)) (define b-ex$293 (join r$39 b-ex$292)) (define b-ex$315 (join r$40 b-ex$314)) (define b-ex$337 (join r$41 b-ex$336)) (define decls$9 (list decl$7 decl$8)) (define b-ex$121 (join r$31 b-ex$120)) (define b-ex$363 (join v$42 b-ex$362)) (define b-ex$411 (join v$50 b-ex$410)) (define cmp-f$23 (in r$10 b-ex$22)) (define mul-f$50 (multiplicity-formula 'one b-ex$49)) (define b-ex$375 (join v$44 b-ex$374)) (define b-ex$367 (join b-ex$366 r$7)) (define b-ex$161 (join r$41 b-ex$160)) (define b-ex$399 (join v$48 b-ex$398)) (define decls$433 (list decl$431 decl$432)) (define decls$2 (list decl$0 decl$1)) (define cmp-f$31 (in r$12 b-ex$30)) (define cmp-f$15 (in r$8 b-ex$14)) (define b-ex$174 (join r$34 b-ex$173)) (define b-ex$427 (join b-ex$426 r$7)) (define b-ex$143 (join r$35 b-ex$142)) (define mul-f$18 (multiplicity-formula 'one b-ex$17)) (define b-ex$76 (join r$1 b-ex$75)) (define b-ex$127 (join r$33 b-ex$126)) (define b-ex$118 (join r$30 b-ex$117)) (define b-ex$73 (join v$22 b-ex$72)) (define cmp-f$74 (= r$1 b-ex$73)) (define b-ex$440 (join b-ex$437 b-ex$439)) (define cmp-f$131 (= b-ex$130 r$34)) (define cmp-f$311 (= b-ex$310 b-ex$293)) (define cmp-f$333 (= b-ex$332 b-ex$315)) (define cmp-f$147 (= b-ex$146 r$36)) (define q-f$35 (quantified-formula 'all (list decl$32) mul-f$34)) (define b-ex$206 (join b-ex$205 b-ex$204)) (define b-ex$392 (join b-ex$389 b-ex$391)) (define cmp-f$128 (= b-ex$127 r$33)) (define b-ex$341 (join b-ex$337 r$7)) (define cmp-f$159 (= b-ex$158 r$40)) (define b-ex$319 (join b-ex$315 r$7)) (define cmp-f$267 (= b-ex$266 b-ex$249)) (define cmp-f$122 (= b-ex$121 r$31)) (define b-ex$368 (join b-ex$365 b-ex$367)) (define b-ex$192 (join b-ex$189 r$7)) (define b-ex$400 (join b-ex$399 r$14)) (define b-ex$404 (join b-ex$401 b-ex$403)) (define b-ex$376 (join b-ex$375 r$10)) (define b-ex$388 (join b-ex$387 r$12)) (define b-ex$250 (join b-ex$249 b-ex$248)) (define mul-f$12 (multiplicity-formula 'one b-ex$11)) (define q-f$19 (quantified-formula 'all (list decl$16) mul-f$18)) (define mul-f$5 (multiplicity-formula 'one b-ex$4)) (define b-ex$275 (join b-ex$271 r$7)) (define b-ex$297 (join b-ex$293 r$7)) (define cmp-f$116 (= b-ex$115 r$29)) (define b-ex$175 (join b-ex$174 b-ex$173)) (define cmp-f$125 (= b-ex$124 r$32)) (define cmp-f$223 (= b-ex$222 b-ex$205)) (define b-ex$272 (join b-ex$271 b-ex$270)) (define cmp-f$97 (= r$5 b-ex$96)) (define cmp-f$94 (= r$5 b-ex$93)) (define cmp-f$119 (= b-ex$118 r$30)) (define b-ex$428 (join b-ex$425 b-ex$427)) (define b-ex$231 (join b-ex$227 r$7)) (define q-f$67 (quantified-formula 'all (list decl$64) mul-f$66)) (define cmp-f$162 (= b-ex$161 r$41)) (define b-ex$228 (join b-ex$227 b-ex$226)) (define b-ex$294 (join b-ex$293 b-ex$292)) (define b-ex$209 (join b-ex$205 r$7)) (define q-f$27 (quantified-formula 'all (list decl$24) mul-f$26)) (define b-ex$436 (join b-ex$435 r$20)) (define b-ex$190 (join b-ex$189 b-ex$188)) (define b-ex$86 (join b-ex$84 b-ex$85)) (define cmp-f$150 (= b-ex$149 r$37)) (define cmp-f$144 (= b-ex$143 r$35)) (define b-ex$106 (join b-ex$104 b-ex$105)) (define b-ex$338 (join b-ex$337 b-ex$336)) (define q-f$51 (quantified-formula 'all (list decl$48) mul-f$50)) (define b-ex$177 (join b-ex$174 r$3)) (define cmp-f$153 (= b-ex$152 r$38)) (define q-f$43 (quantified-formula 'all (list decl$40) mul-f$42)) (define cmp-f$245 (= b-ex$244 b-ex$227)) (define q-f$59 (quantified-formula 'all (list decl$56) mul-f$58)) (define b-ex$380 (join b-ex$377 b-ex$379)) (define cmp-f$113 (= b-ex$112 r$28)) (define cmp-f$156 (= b-ex$155 r$39)) (define b-ex$253 (join b-ex$249 r$7)) (define b-ex$316 (join b-ex$315 b-ex$314)) (define cmp-f$77 (= r$1 b-ex$76)) (define b-ex$412 (join b-ex$411 r$16)) (define b-ex$364 (join b-ex$363 r$8)) (define b-ex$416 (join b-ex$413 b-ex$415)) (define cmp-f$289 (= b-ex$288 b-ex$271)) (define cmp-f$355 (= b-ex$354 b-ex$337)) (define b-ex$424 (join b-ex$423 r$18)) (define b-f$28 (&& cmp-f$23 q-f$27)) (define b-f$98 (&& cmp-f$94 cmp-f$97)) (define cmp-f$251 (= b-ex$247 b-ex$250)) (define cmp-f$191 (= r$35 b-ex$190)) (define !-f$165 (! cmp-f$147)) (define !-f$169 (! cmp-f$159)) (define n-f$163 (|| cmp-f$144 cmp-f$147 cmp-f$150 cmp-f$153 cmp-f$156 cmp-f$159 cmp-f$162)) (define q-f$13 (quantified-formula 'all decls$9 mul-f$12)) (define b-ex$108 (join b-ex$106 b-ex$107)) (define !-f$137 (! cmp-f$125)) (define !-f$133 (! cmp-f$113)) (define !-f$134 (! cmp-f$116)) (define b-f$68 (&& cmp-f$63 q-f$67)) (define cmp-f$417 (= b-ex$412 b-ex$416)) (define !-f$139 (! cmp-f$131)) (define cmp-f$441 (= b-ex$436 b-ex$440)) (define !-f$138 (! cmp-f$128)) (define cmp-f$369 (= b-ex$364 b-ex$368)) (define cmp-f$393 (= b-ex$388 b-ex$392)) (define b-ex$88 (join b-ex$86 b-ex$87)) (define cmp-f$405 (= b-ex$400 b-ex$404)) (define b-ex$232 (join b-ex$227 b-ex$231)) (define cmp-f$176 (= r$28 b-ex$175)) (define b-f$78 (&& cmp-f$74 cmp-f$77)) (define !-f$170 (! cmp-f$162)) (define b-f$20 (&& cmp-f$15 q-f$19)) (define b-f$52 (&& cmp-f$47 q-f$51)) (define n-f$132 (|| cmp-f$113 cmp-f$116 cmp-f$119 cmp-f$122 cmp-f$125 cmp-f$128 cmp-f$131)) (define cmp-f$273 (= b-ex$269 b-ex$272)) (define !-f$167 (! cmp-f$153)) (define b-f$36 (&& cmp-f$31 q-f$35)) (define b-ex$254 (join b-ex$249 b-ex$253)) (define cmp-f$429 (= b-ex$424 b-ex$428)) (define b-ex$298 (join b-ex$293 b-ex$297)) (define !-f$135 (! cmp-f$119)) (define b-ex$178 (join b-ex$174 b-ex$177)) (define b-ex$193 (join b-ex$189 b-ex$192)) (define q-f$6 (quantified-formula 'all decls$2 mul-f$5)) (define cmp-f$229 (= b-ex$225 b-ex$228)) (define !-f$166 (! cmp-f$150)) (define b-ex$210 (join b-ex$205 b-ex$209)) (define cmp-f$381 (= b-ex$376 b-ex$380)) (define cmp-f$339 (= b-ex$335 b-ex$338)) (define !-f$136 (! cmp-f$122)) (define b-f$60 (&& cmp-f$55 q-f$59)) (define !-f$168 (! cmp-f$156)) (define b-ex$342 (join b-ex$337 b-ex$341)) (define b-ex$276 (join b-ex$271 b-ex$275)) (define b-f$44 (&& cmp-f$39 q-f$43)) (define cmp-f$317 (= b-ex$313 b-ex$316)) (define cmp-f$295 (= b-ex$291 b-ex$294)) (define cmp-f$207 (= b-ex$203 b-ex$206)) (define b-ex$320 (join b-ex$315 b-ex$319)) (define !-f$164 (! cmp-f$144)) (define n-f$171 (|| !-f$164 !-f$165 !-f$166 !-f$167 !-f$168 !-f$169 !-f$170)) (define b-ex$183 (join b-ex$178 b-ex$173)) (define b-ex$327 (join b-ex$320 b-ex$314)) (define q-f$442 (quantified-formula 'all decls$433 cmp-f$441)) (define cmp-f$255 (= b-ex$252 b-ex$254)) (define app$45 b-f$44) (define app$61 b-f$60) (define app$69 b-f$68) (define b-ex$345 (join b-ex$342 r$7)) (define q-f$79 (quantified-formula 'all (list decl$71) b-f$78)) (define app$53 b-f$52) (define cmp-f$179 (= r$29 b-ex$178)) (define q-f$406 (quantified-formula 'all decls$397 cmp-f$405)) (define app$37 b-f$36) (define b-ex$217 (join b-ex$210 b-ex$204)) (define b-ex$239 (join b-ex$232 b-ex$226)) (define q-f$382 (quantified-formula 'all decls$373 cmp-f$381)) (define cmp-f$321 (= b-ex$318 b-ex$320)) (define b-ex$195 (join b-ex$193 r$7)) (define q-f$394 (quantified-formula 'all decls$385 cmp-f$393)) (define b-ex$180 (join b-ex$178 r$3)) (define cmp-f$233 (= b-ex$230 b-ex$232)) (define q-f$370 (quantified-formula 'all decls$361 cmp-f$369)) (define b-ex$235 (join b-ex$232 r$7)) (define b-ex$283 (join b-ex$276 b-ex$270)) (define b-ex$261 (join b-ex$254 b-ex$248)) (define cmp-f$89 (= v$23 b-ex$88)) (define n-f$140 (|| !-f$133 !-f$134 !-f$135 !-f$136 !-f$137 !-f$138 !-f$139)) (define b-ex$198 (join b-ex$193 b-ex$188)) (define b-ex$257 (join b-ex$254 r$7)) (define cmp-f$277 (= b-ex$274 b-ex$276)) (define app$29 b-f$28) (define cmp-f$211 (= b-ex$208 b-ex$210)) (define b-ex$301 (join b-ex$298 r$7)) (define b-ex$213 (join b-ex$210 r$7)) (define b-ex$323 (join b-ex$320 r$7)) (define b-ex$305 (join b-ex$298 b-ex$292)) (define cmp-f$299 (= b-ex$296 b-ex$298)) (define cmp-f$109 (= v$26 b-ex$108)) (define q-f$99 (quantified-formula 'all (list decl$91) b-f$98)) (define b-ex$279 (join b-ex$276 r$7)) (define b-ex$349 (join b-ex$342 b-ex$336)) (define app$21 b-f$20) (define q-f$418 (quantified-formula 'all decls$409 cmp-f$417)) (define cmp-f$343 (= b-ex$340 b-ex$342)) (define cmp-f$194 (= r$36 b-ex$193)) (define q-f$430 (quantified-formula 'all decls$421 cmp-f$429)) (define b-ex$214 (join b-ex$205 b-ex$213)) (define b-ex$324 (join b-ex$315 b-ex$323)) (define cmp-f$284 (= b-ex$282 b-ex$283)) (define b-ex$264 (join b-ex$261 b-ex$248)) (define b-f$141 (&& n-f$132 n-f$140)) (define b-ex$242 (join b-ex$239 b-ex$226)) (define b-ex$236 (join b-ex$227 b-ex$235)) (define b-ex$330 (join b-ex$327 b-ex$314)) (define b-ex$280 (join b-ex$271 b-ex$279)) (define b-ex$200 (join b-ex$198 b-ex$188)) (define n-f$443 (|| q-f$370 q-f$382 q-f$394 q-f$406 q-f$418 q-f$430 q-f$442)) (define b-ex$181 (join b-ex$174 b-ex$180)) (define b-ex$185 (join b-ex$183 b-ex$173)) (define cmp-f$184 (= r$31 b-ex$183)) (define b-ex$286 (join b-ex$283 b-ex$270)) (define b-ex$302 (join b-ex$293 b-ex$301)) (define b-f$172 (&& n-f$163 n-f$171)) (define b-ex$308 (join b-ex$305 b-ex$292)) (define cmp-f$240 (= b-ex$238 b-ex$239)) (define cmp-f$350 (= b-ex$348 b-ex$349)) (define b-ex$258 (join b-ex$249 b-ex$257)) (define cmp-f$199 (= r$38 b-ex$198)) (define cmp-f$262 (= b-ex$260 b-ex$261)) (define cmp-f$218 (= b-ex$216 b-ex$217)) (define b-ex$220 (join b-ex$217 b-ex$204)) (define b-ex$352 (join b-ex$349 b-ex$336)) (define cmp-f$328 (= b-ex$326 b-ex$327)) (define n-f$70 (&& q-f$6 q-f$13 app$21 app$29 app$37 app$45 app$53 app$61 app$69)) (define q-f$90 (quantified-formula 'all decls$82 cmp-f$89)) (define cmp-f$306 (= b-ex$304 b-ex$305)) (define q-f$110 (quantified-formula 'all decls$102 cmp-f$109)) (define b-ex$346 (join b-ex$337 b-ex$345)) (define b-ex$196 (join b-ex$189 b-ex$195)) (define cmp-f$281 (= b-ex$278 b-ex$280)) (define cmp-f$325 (= b-ex$322 b-ex$324)) (define cmp-f$309 (= b-ex$307 b-ex$308)) (define cmp-f$303 (= b-ex$300 b-ex$302)) (define cmp-f$215 (= b-ex$212 b-ex$214)) (define cmp-f$287 (= b-ex$285 b-ex$286)) (define cmp-f$221 (= b-ex$219 b-ex$220)) (define cmp-f$353 (= b-ex$351 b-ex$352)) (define cmp-f$186 (= r$32 b-ex$185)) (define cmp-f$197 (= r$37 b-ex$196)) (define cmp-f$347 (= b-ex$344 b-ex$346)) (define cmp-f$201 (= r$39 b-ex$200)) (define cmp-f$265 (= b-ex$263 b-ex$264)) (define !-f$444 (! n-f$443)) (define cmp-f$237 (= b-ex$234 b-ex$236)) (define cmp-f$182 (= r$30 b-ex$181)) (define cmp-f$331 (= b-ex$329 b-ex$330)) (define cmp-f$259 (= b-ex$256 b-ex$258)) (define cmp-f$243 (= b-ex$241 b-ex$242)) (define n-f$202 (&& cmp-f$191 cmp-f$194 cmp-f$197 cmp-f$199 cmp-f$201)) (define n-f$246 (&& cmp-f$229 cmp-f$233 cmp-f$237 cmp-f$240 cmp-f$243 cmp-f$245)) (define n-f$334 (&& cmp-f$317 cmp-f$321 cmp-f$325 cmp-f$328 cmp-f$331 cmp-f$333)) (define n-f$224 (&& cmp-f$207 cmp-f$211 cmp-f$215 cmp-f$218 cmp-f$221 cmp-f$223)) (define n-f$356 (&& cmp-f$339 cmp-f$343 cmp-f$347 cmp-f$350 cmp-f$353 cmp-f$355)) (define n-f$187 (&& cmp-f$176 cmp-f$179 cmp-f$182 cmp-f$184 cmp-f$186)) (define n-f$312 (&& cmp-f$295 cmp-f$299 cmp-f$303 cmp-f$306 cmp-f$309 cmp-f$311)) (define n-f$290 (&& cmp-f$273 cmp-f$277 cmp-f$281 cmp-f$284 cmp-f$287 cmp-f$289)) (define n-f$268 (&& cmp-f$251 cmp-f$255 cmp-f$259 cmp-f$262 cmp-f$265 cmp-f$267)) (define n-f$357 (&& n-f$224 n-f$246 n-f$268 n-f$290 n-f$312 n-f$334 n-f$356)) (define n-f$358 (&& n-f$70 q-f$79 q-f$90 q-f$99 q-f$110 b-f$141 b-f$172 n-f$187 n-f$202 n-f$357)) (define b-f$445 (&& n-f$358 !-f$444)) (define ts$21 (list (list "e14"))) (define ts$48 (list (list "e16" "e23"))) (define ts$15 (list (list "e22"))) (define ts$55 (list (list "e10" "e20") (list "e10" "e21") (list "e10" "e22") (list "e10" "e23") (list "e10" "e24") (list "e10" "e25") (list "e10" "e26") (list "e11" "e20") (list "e11" "e21") (list "e11" "e22") (list "e11" "e23") (list "e11" "e24") (list "e11" "e25") (list "e11" "e26") (list "e12" "e20") (list "e12" "e21") (list "e12" "e22") (list "e12" "e23") (list "e12" "e24") (list "e12" "e25") (list "e12" "e26") (list "e13" "e20") (list "e13" "e21") (list "e13" "e22") (list "e13" "e23") (list "e13" "e24") (list "e13" "e25") (list "e13" "e26") (list "e14" "e20") (list "e14" "e21") (list "e14" "e22") (list "e14" "e23") (list "e14" "e24") (list "e14" "e25") (list "e14" "e26") (list "e15" "e20") (list "e15" "e21") (list "e15" "e22") (list "e15" "e23") (list "e15" "e24") (list "e15" "e25") (list "e15" "e26") (list "e16" "e25"))) (define ts$57 (list (list "e16" "e26"))) (define ts$23 (list (list "e24"))) (define ts$29 (list (list "e16"))) (define ts$36 (list (list "e26" "e26" "e25"))) (define ts$45 (list (list "e16" "e22"))) (define ts$17 (list (list "e13"))) (define ts$19 (list (list "e23"))) (define ts$9 (list (list "e11"))) (define ts$37 (list (list "e20" "e20" "e20") (list "e20" "e20" "e21") (list "e20" "e20" "e22") (list "e20" "e20" "e23") (list "e20" "e20" "e24") (list "e20" "e20" "e25") (list "e20" "e20" "e26") (list "e20" "e21" "e20") (list "e20" "e21" "e21") (list "e20" "e21" "e22") (list "e20" "e21" "e23") (list "e20" "e21" "e24") (list "e20" "e21" "e25") (list "e20" "e21" "e26") (list "e20" "e22" "e20") (list "e20" "e22" "e21") (list "e20" "e22" "e22") (list "e20" "e22" "e23") (list "e20" "e22" "e24") (list "e20" "e22" "e25") (list "e20" "e22" "e26") (list "e20" "e23" "e20") (list "e20" "e23" "e21") (list "e20" "e23" "e22") (list "e20" "e23" "e23") (list "e20" "e23" "e24") (list "e20" "e23" "e25") (list "e20" "e23" "e26") (list "e20" "e24" "e20") (list "e20" "e24" "e21") (list "e20" "e24" "e22") (list "e20" "e24" "e23") (list "e20" "e24" "e24") (list "e20" "e24" "e25") (list "e20" "e24" "e26") (list "e20" "e25" "e20") (list "e20" "e25" "e21") (list "e20" "e25" "e22") (list "e20" "e25" "e23") (list "e20" "e25" "e24") (list "e20" "e25" "e25") (list "e20" "e25" "e26") (list "e20" "e26" "e20") (list "e20" "e26" "e21") (list "e20" "e26" "e22") (list "e20" "e26" "e23") (list "e20" "e26" "e24") (list "e20" "e26" "e25") (list "e20" "e26" "e26") (list "e21" "e20" "e20") (list "e21" "e20" "e21") (list "e21" "e20" "e22") (list "e21" "e20" "e23") (list "e21" "e20" "e24") (list "e21" "e20" "e25") (list "e21" "e20" "e26") (list "e21" "e21" "e20") (list "e21" "e21" "e21") (list "e21" "e21" "e22") (list "e21" "e21" "e23") (list "e21" "e21" "e24") (list "e21" "e21" "e25") (list "e21" "e21" "e26") (list "e21" "e22" "e20") (list "e21" "e22" "e21") (list "e21" "e22" "e22") (list "e21" "e22" "e23") (list "e21" "e22" "e24") (list "e21" "e22" "e25") (list "e21" "e22" "e26") (list "e21" "e23" "e20") (list "e21" "e23" "e21") (list "e21" "e23" "e22") (list "e21" "e23" "e23") (list "e21" "e23" "e24") (list "e21" "e23" "e25") (list "e21" "e23" "e26") (list "e21" "e24" "e20") (list "e21" "e24" "e21") (list "e21" "e24" "e22") (list "e21" "e24" "e23") (list "e21" "e24" "e24") (list "e21" "e24" "e25") (list "e21" "e24" "e26") (list "e21" "e25" "e20") (list "e21" "e25" "e21") (list "e21" "e25" "e22") (list "e21" "e25" "e23") (list "e21" "e25" "e24") (list "e21" "e25" "e25") (list "e21" "e25" "e26") (list "e21" "e26" "e20") (list "e21" "e26" "e21") (list "e21" "e26" "e22") (list "e21" "e26" "e23") (list "e21" "e26" "e24") (list "e21" "e26" "e25") (list "e21" "e26" "e26") (list "e22" "e20" "e20") (list "e22" "e20" "e21") (list "e22" "e20" "e22") (list "e22" "e20" "e23") (list "e22" "e20" "e24") (list "e22" "e20" "e25") (list "e22" "e20" "e26") (list "e22" "e21" "e20") (list "e22" "e21" "e21") (list "e22" "e21" "e22") (list "e22" "e21" "e23") (list "e22" "e21" "e24") (list "e22" "e21" "e25") (list "e22" "e21" "e26") (list "e22" "e22" "e20") (list "e22" "e22" "e21") (list "e22" "e22" "e22") (list "e22" "e22" "e23") (list "e22" "e22" "e24") (list "e22" "e22" "e25") (list "e22" "e22" "e26") (list "e22" "e23" "e20") (list "e22" "e23" "e21") (list "e22" "e23" "e22") (list "e22" "e23" "e23") (list "e22" "e23" "e24") (list "e22" "e23" "e25") (list "e22" "e23" "e26") (list "e22" "e24" "e20") (list "e22" "e24" "e21") (list "e22" "e24" "e22") (list "e22" "e24" "e23") (list "e22" "e24" "e24") (list "e22" "e24" "e25") (list "e22" "e24" "e26") (list "e22" "e25" "e20") (list "e22" "e25" "e21") (list "e22" "e25" "e22") (list "e22" "e25" "e23") (list "e22" "e25" "e24") (list "e22" "e25" "e25") (list "e22" "e25" "e26") (list "e22" "e26" "e20") (list "e22" "e26" "e21") (list "e22" "e26" "e22") (list "e22" "e26" "e23") (list "e22" "e26" "e24") (list "e22" "e26" "e25") (list "e22" "e26" "e26") (list "e23" "e20" "e20") (list "e23" "e20" "e21") (list "e23" "e20" "e22") (list "e23" "e20" "e23") (list "e23" "e20" "e24") (list "e23" "e20" "e25") (list "e23" "e20" "e26") (list "e23" "e21" "e20") (list "e23" "e21" "e21") (list "e23" "e21" "e22") (list "e23" "e21" "e23") (list "e23" "e21" "e24") (list "e23" "e21" "e25") (list "e23" "e21" "e26") (list "e23" "e22" "e20") (list "e23" "e22" "e21") (list "e23" "e22" "e22") (list "e23" "e22" "e23") (list "e23" "e22" "e24") (list "e23" "e22" "e25") (list "e23" "e22" "e26") (list "e23" "e23" "e20") (list "e23" "e23" "e21") (list "e23" "e23" "e22") (list "e23" "e23" "e23") (list "e23" "e23" "e24") (list "e23" "e23" "e25") (list "e23" "e23" "e26") (list "e23" "e24" "e20") (list "e23" "e24" "e21") (list "e23" "e24" "e22") (list "e23" "e24" "e23") (list "e23" "e24" "e24") (list "e23" "e24" "e25") (list "e23" "e24" "e26") (list "e23" "e25" "e20") (list "e23" "e25" "e21") (list "e23" "e25" "e22") (list "e23" "e25" "e23") (list "e23" "e25" "e24") (list "e23" "e25" "e25") (list "e23" "e25" "e26") (list "e23" "e26" "e20") (list "e23" "e26" "e21") (list "e23" "e26" "e22") (list "e23" "e26" "e23") (list "e23" "e26" "e24") (list "e23" "e26" "e25") (list "e23" "e26" "e26") (list "e24" "e20" "e20") (list "e24" "e20" "e21") (list "e24" "e20" "e22") (list "e24" "e20" "e23") (list "e24" "e20" "e24") (list "e24" "e20" "e25") (list "e24" "e20" "e26") (list "e24" "e21" "e20") (list "e24" "e21" "e21") (list "e24" "e21" "e22") (list "e24" "e21" "e23") (list "e24" "e21" "e24") (list "e24" "e21" "e25") (list "e24" "e21" "e26") (list "e24" "e22" "e20") (list "e24" "e22" "e21") (list "e24" "e22" "e22") (list "e24" "e22" "e23") (list "e24" "e22" "e24") (list "e24" "e22" "e25") (list "e24" "e22" "e26") (list "e24" "e23" "e20") (list "e24" "e23" "e21") (list "e24" "e23" "e22") (list "e24" "e23" "e23") (list "e24" "e23" "e24") (list "e24" "e23" "e25") (list "e24" "e23" "e26") (list "e24" "e24" "e20") (list "e24" "e24" "e21") (list "e24" "e24" "e22") (list "e24" "e24" "e23") (list "e24" "e24" "e24") (list "e24" "e24" "e25") (list "e24" "e24" "e26") (list "e24" "e25" "e20") (list "e24" "e25" "e21") (list "e24" "e25" "e22") (list "e24" "e25" "e23") (list "e24" "e25" "e24") (list "e24" "e25" "e25") (list "e24" "e25" "e26") (list "e24" "e26" "e20") (list "e24" "e26" "e21") (list "e24" "e26" "e22") (list "e24" "e26" "e23") (list "e24" "e26" "e24") (list "e24" "e26" "e25") (list "e24" "e26" "e26") (list "e25" "e20" "e20") (list "e25" "e20" "e21") (list "e25" "e20" "e22") (list "e25" "e20" "e23") (list "e25" "e20" "e24") (list "e25" "e20" "e25") (list "e25" "e20" "e26") (list "e25" "e21" "e20") (list "e25" "e21" "e21") (list "e25" "e21" "e22") (list "e25" "e21" "e23") (list "e25" "e21" "e24") (list "e25" "e21" "e25") (list "e25" "e21" "e26") (list "e25" "e22" "e20") (list "e25" "e22" "e21") (list "e25" "e22" "e22") (list "e25" "e22" "e23") (list "e25" "e22" "e24") (list "e25" "e22" "e25") (list "e25" "e22" "e26") (list "e25" "e23" "e20") (list "e25" "e23" "e21") (list "e25" "e23" "e22") (list "e25" "e23" "e23") (list "e25" "e23" "e24") (list "e25" "e23" "e25") (list "e25" "e23" "e26") (list "e25" "e24" "e20") (list "e25" "e24" "e21") (list "e25" "e24" "e22") (list "e25" "e24" "e23") (list "e25" "e24" "e24") (list "e25" "e24" "e25") (list "e25" "e24" "e26") (list "e25" "e25" "e20") (list "e25" "e25" "e21") (list "e25" "e25" "e22") (list "e25" "e25" "e23") (list "e25" "e25" "e24") (list "e25" "e25" "e25") (list "e25" "e25" "e26") (list "e25" "e26" "e20") (list "e25" "e26" "e21") (list "e25" "e26" "e22") (list "e25" "e26" "e23") (list "e25" "e26" "e24") (list "e25" "e26" "e25") (list "e25" "e26" "e26") (list "e26" "e20" "e20") (list "e26" "e20" "e21") (list "e26" "e20" "e22") (list "e26" "e20" "e23") (list "e26" "e20" "e24") (list "e26" "e20" "e25") (list "e26" "e20" "e26") (list "e26" "e21" "e20") (list "e26" "e21" "e21") (list "e26" "e21" "e22") (list "e26" "e21" "e23") (list "e26" "e21" "e24") (list "e26" "e21" "e25") (list "e26" "e21" "e26") (list "e26" "e22" "e20") (list "e26" "e22" "e21") (list "e26" "e22" "e22") (list "e26" "e22" "e23") (list "e26" "e22" "e24") (list "e26" "e22" "e25") (list "e26" "e22" "e26") (list "e26" "e23" "e20") (list "e26" "e23" "e21") (list "e26" "e23" "e22") (list "e26" "e23" "e23") (list "e26" "e23" "e24") (list "e26" "e23" "e25") (list "e26" "e23" "e26") (list "e26" "e24" "e20") (list "e26" "e24" "e21") (list "e26" "e24" "e22") (list "e26" "e24" "e23") (list "e26" "e24" "e24") (list "e26" "e24" "e25") (list "e26" "e24" "e26") (list "e26" "e25" "e20") (list "e26" "e25" "e21") (list "e26" "e25" "e22") (list "e26" "e25" "e23") (list "e26" "e25" "e24") (list "e26" "e25" "e25") (list "e26" "e25" "e26") (list "e26" "e26" "e25"))) (define ts$46 (list (list "e10" "e20") (list "e10" "e21") (list "e10" "e22") (list "e10" "e23") (list "e10" "e24") (list "e10" "e25") (list "e10" "e26") (list "e11" "e20") (list "e11" "e21") (list "e11" "e22") (list "e11" "e23") (list "e11" "e24") (list "e11" "e25") (list "e11" "e26") (list "e12" "e20") (list "e12" "e21") (list "e12" "e22") (list "e12" "e23") (list "e12" "e24") (list "e12" "e25") (list "e12" "e26") (list "e13" "e20") (list "e13" "e21") (list "e13" "e22") (list "e13" "e23") (list "e13" "e24") (list "e13" "e25") (list "e13" "e26") (list "e14" "e20") (list "e14" "e21") (list "e14" "e22") (list "e14" "e23") (list "e14" "e24") (list "e14" "e25") (list "e14" "e26") (list "e15" "e20") (list "e15" "e21") (list "e15" "e22") (list "e15" "e23") (list "e15" "e24") (list "e15" "e25") (list "e15" "e26") (list "e16" "e22"))) (define ts$31 (list (list "e26"))) (define ts$51 (list (list "e16" "e24"))) (define ts$25 (list (list "e15"))) (define ts$34 (list (list "e10" "e10" "e10") (list "e10" "e10" "e11") (list "e10" "e10" "e12") (list "e10" "e10" "e13") (list "e10" "e10" "e14") (list "e10" "e10" "e15") (list "e10" "e10" "e16") (list "e10" "e11" "e10") (list "e10" "e11" "e11") (list "e10" "e11" "e12") (list "e10" "e11" "e13") (list "e10" "e11" "e14") (list "e10" "e11" "e15") (list "e10" "e11" "e16") (list "e10" "e12" "e10") (list "e10" "e12" "e11") (list "e10" "e12" "e12") (list "e10" "e12" "e13") (list "e10" "e12" "e14") (list "e10" "e12" "e15") (list "e10" "e12" "e16") (list "e10" "e13" "e10") (list "e10" "e13" "e11") (list "e10" "e13" "e12") (list "e10" "e13" "e13") (list "e10" "e13" "e14") (list "e10" "e13" "e15") (list "e10" "e13" "e16") (list "e10" "e14" "e10") (list "e10" "e14" "e11") (list "e10" "e14" "e12") (list "e10" "e14" "e13") (list "e10" "e14" "e14") (list "e10" "e14" "e15") (list "e10" "e14" "e16") (list "e10" "e15" "e10") (list "e10" "e15" "e11") (list "e10" "e15" "e12") (list "e10" "e15" "e13") (list "e10" "e15" "e14") (list "e10" "e15" "e15") (list "e10" "e15" "e16") (list "e10" "e16" "e10") (list "e10" "e16" "e11") (list "e10" "e16" "e12") (list "e10" "e16" "e13") (list "e10" "e16" "e14") (list "e10" "e16" "e15") (list "e10" "e16" "e16") (list "e11" "e10" "e10") (list "e11" "e10" "e11") (list "e11" "e10" "e12") (list "e11" "e10" "e13") (list "e11" "e10" "e14") (list "e11" "e10" "e15") (list "e11" "e10" "e16") (list "e11" "e11" "e10") (list "e11" "e11" "e11") (list "e11" "e11" "e12") (list "e11" "e11" "e13") (list "e11" "e11" "e14") (list "e11" "e11" "e15") (list "e11" "e11" "e16") (list "e11" "e12" "e10") (list "e11" "e12" "e11") (list "e11" "e12" "e12") (list "e11" "e12" "e13") (list "e11" "e12" "e14") (list "e11" "e12" "e15") (list "e11" "e12" "e16") (list "e11" "e13" "e10") (list "e11" "e13" "e11") (list "e11" "e13" "e12") (list "e11" "e13" "e13") (list "e11" "e13" "e14") (list "e11" "e13" "e15") (list "e11" "e13" "e16") (list "e11" "e14" "e10") (list "e11" "e14" "e11") (list "e11" "e14" "e12") (list "e11" "e14" "e13") (list "e11" "e14" "e14") (list "e11" "e14" "e15") (list "e11" "e14" "e16") (list "e11" "e15" "e10") (list "e11" "e15" "e11") (list "e11" "e15" "e12") (list "e11" "e15" "e13") (list "e11" "e15" "e14") (list "e11" "e15" "e15") (list "e11" "e15" "e16") (list "e11" "e16" "e10") (list "e11" "e16" "e11") (list "e11" "e16" "e12") (list "e11" "e16" "e13") (list "e11" "e16" "e14") (list "e11" "e16" "e15") (list "e11" "e16" "e16") (list "e12" "e10" "e10") (list "e12" "e10" "e11") (list "e12" "e10" "e12") (list "e12" "e10" "e13") (list "e12" "e10" "e14") (list "e12" "e10" "e15") (list "e12" "e10" "e16") (list "e12" "e11" "e10") (list "e12" "e11" "e11") (list "e12" "e11" "e12") (list "e12" "e11" "e13") (list "e12" "e11" "e14") (list "e12" "e11" "e15") (list "e12" "e11" "e16") (list "e12" "e12" "e10") (list "e12" "e12" "e11") (list "e12" "e12" "e12") (list "e12" "e12" "e13") (list "e12" "e12" "e14") (list "e12" "e12" "e15") (list "e12" "e12" "e16") (list "e12" "e13" "e10") (list "e12" "e13" "e11") (list "e12" "e13" "e12") (list "e12" "e13" "e13") (list "e12" "e13" "e14") (list "e12" "e13" "e15") (list "e12" "e13" "e16") (list "e12" "e14" "e10") (list "e12" "e14" "e11") (list "e12" "e14" "e12") (list "e12" "e14" "e13") (list "e12" "e14" "e14") (list "e12" "e14" "e15") (list "e12" "e14" "e16") (list "e12" "e15" "e10") (list "e12" "e15" "e11") (list "e12" "e15" "e12") (list "e12" "e15" "e13") (list "e12" "e15" "e14") (list "e12" "e15" "e15") (list "e12" "e15" "e16") (list "e12" "e16" "e10") (list "e12" "e16" "e11") (list "e12" "e16" "e12") (list "e12" "e16" "e13") (list "e12" "e16" "e14") (list "e12" "e16" "e15") (list "e12" "e16" "e16") (list "e13" "e10" "e10") (list "e13" "e10" "e11") (list "e13" "e10" "e12") (list "e13" "e10" "e13") (list "e13" "e10" "e14") (list "e13" "e10" "e15") (list "e13" "e10" "e16") (list "e13" "e11" "e10") (list "e13" "e11" "e11") (list "e13" "e11" "e12") (list "e13" "e11" "e13") (list "e13" "e11" "e14") (list "e13" "e11" "e15") (list "e13" "e11" "e16") (list "e13" "e12" "e10") (list "e13" "e12" "e11") (list "e13" "e12" "e12") (list "e13" "e12" "e13") (list "e13" "e12" "e14") (list "e13" "e12" "e15") (list "e13" "e12" "e16") (list "e13" "e13" "e10") (list "e13" "e13" "e11") (list "e13" "e13" "e12") (list "e13" "e13" "e13") (list "e13" "e13" "e14") (list "e13" "e13" "e15") (list "e13" "e13" "e16") (list "e13" "e14" "e10") (list "e13" "e14" "e11") (list "e13" "e14" "e12") (list "e13" "e14" "e13") (list "e13" "e14" "e14") (list "e13" "e14" "e15") (list "e13" "e14" "e16") (list "e13" "e15" "e10") (list "e13" "e15" "e11") (list "e13" "e15" "e12") (list "e13" "e15" "e13") (list "e13" "e15" "e14") (list "e13" "e15" "e15") (list "e13" "e15" "e16") (list "e13" "e16" "e10") (list "e13" "e16" "e11") (list "e13" "e16" "e12") (list "e13" "e16" "e13") (list "e13" "e16" "e14") (list "e13" "e16" "e15") (list "e13" "e16" "e16") (list "e14" "e10" "e10") (list "e14" "e10" "e11") (list "e14" "e10" "e12") (list "e14" "e10" "e13") (list "e14" "e10" "e14") (list "e14" "e10" "e15") (list "e14" "e10" "e16") (list "e14" "e11" "e10") (list "e14" "e11" "e11") (list "e14" "e11" "e12") (list "e14" "e11" "e13") (list "e14" "e11" "e14") (list "e14" "e11" "e15") (list "e14" "e11" "e16") (list "e14" "e12" "e10") (list "e14" "e12" "e11") (list "e14" "e12" "e12") (list "e14" "e12" "e13") (list "e14" "e12" "e14") (list "e14" "e12" "e15") (list "e14" "e12" "e16") (list "e14" "e13" "e10") (list "e14" "e13" "e11") (list "e14" "e13" "e12") (list "e14" "e13" "e13") (list "e14" "e13" "e14") (list "e14" "e13" "e15") (list "e14" "e13" "e16") (list "e14" "e14" "e10") (list "e14" "e14" "e11") (list "e14" "e14" "e12") (list "e14" "e14" "e13") (list "e14" "e14" "e14") (list "e14" "e14" "e15") (list "e14" "e14" "e16") (list "e14" "e15" "e10") (list "e14" "e15" "e11") (list "e14" "e15" "e12") (list "e14" "e15" "e13") (list "e14" "e15" "e14") (list "e14" "e15" "e15") (list "e14" "e15" "e16") (list "e14" "e16" "e10") (list "e14" "e16" "e11") (list "e14" "e16" "e12") (list "e14" "e16" "e13") (list "e14" "e16" "e14") (list "e14" "e16" "e15") (list "e14" "e16" "e16") (list "e15" "e10" "e10") (list "e15" "e10" "e11") (list "e15" "e10" "e12") (list "e15" "e10" "e13") (list "e15" "e10" "e14") (list "e15" "e10" "e15") (list "e15" "e10" "e16") (list "e15" "e11" "e10") (list "e15" "e11" "e11") (list "e15" "e11" "e12") (list "e15" "e11" "e13") (list "e15" "e11" "e14") (list "e15" "e11" "e15") (list "e15" "e11" "e16") (list "e15" "e12" "e10") (list "e15" "e12" "e11") (list "e15" "e12" "e12") (list "e15" "e12" "e13") (list "e15" "e12" "e14") (list "e15" "e12" "e15") (list "e15" "e12" "e16") (list "e15" "e13" "e10") (list "e15" "e13" "e11") (list "e15" "e13" "e12") (list "e15" "e13" "e13") (list "e15" "e13" "e14") (list "e15" "e13" "e15") (list "e15" "e13" "e16") (list "e15" "e14" "e10") (list "e15" "e14" "e11") (list "e15" "e14" "e12") (list "e15" "e14" "e13") (list "e15" "e14" "e14") (list "e15" "e14" "e15") (list "e15" "e14" "e16") (list "e15" "e15" "e10") (list "e15" "e15" "e11") (list "e15" "e15" "e12") (list "e15" "e15" "e13") (list "e15" "e15" "e14") (list "e15" "e15" "e15") (list "e15" "e15" "e16") (list "e15" "e16" "e10") (list "e15" "e16" "e11") (list "e15" "e16" "e12") (list "e15" "e16" "e13") (list "e15" "e16" "e14") (list "e15" "e16" "e15") (list "e15" "e16" "e16") (list "e16" "e10" "e10") (list "e16" "e10" "e11") (list "e16" "e10" "e12") (list "e16" "e10" "e13") (list "e16" "e10" "e14") (list "e16" "e10" "e15") (list "e16" "e10" "e16") (list "e16" "e11" "e10") (list "e16" "e11" "e11") (list "e16" "e11" "e12") (list "e16" "e11" "e13") (list "e16" "e11" "e14") (list "e16" "e11" "e15") (list "e16" "e11" "e16") (list "e16" "e12" "e10") (list "e16" "e12" "e11") (list "e16" "e12" "e12") (list "e16" "e12" "e13") (list "e16" "e12" "e14") (list "e16" "e12" "e15") (list "e16" "e12" "e16") (list "e16" "e13" "e10") (list "e16" "e13" "e11") (list "e16" "e13" "e12") (list "e16" "e13" "e13") (list "e16" "e13" "e14") (list "e16" "e13" "e15") (list "e16" "e13" "e16") (list "e16" "e14" "e10") (list "e16" "e14" "e11") (list "e16" "e14" "e12") (list "e16" "e14" "e13") (list "e16" "e14" "e14") (list "e16" "e14" "e15") (list "e16" "e14" "e16") (list "e16" "e15" "e10") (list "e16" "e15" "e11") (list "e16" "e15" "e12") (list "e16" "e15" "e13") (list "e16" "e15" "e14") (list "e16" "e15" "e15") (list "e16" "e15" "e16") (list "e16" "e16" "e15"))) (define ts$49 (list (list "e10" "e20") (list "e10" "e21") (list "e10" "e22") (list "e10" "e23") (list "e10" "e24") (list "e10" "e25") (list "e10" "e26") (list "e11" "e20") (list "e11" "e21") (list "e11" "e22") (list "e11" "e23") (list "e11" "e24") (list "e11" "e25") (list "e11" "e26") (list "e12" "e20") (list "e12" "e21") (list "e12" "e22") (list "e12" "e23") (list "e12" "e24") (list "e12" "e25") (list "e12" "e26") (list "e13" "e20") (list "e13" "e21") (list "e13" "e22") (list "e13" "e23") (list "e13" "e24") (list "e13" "e25") (list "e13" "e26") (list "e14" "e20") (list "e14" "e21") (list "e14" "e22") (list "e14" "e23") (list "e14" "e24") (list "e14" "e25") (list "e14" "e26") (list "e15" "e20") (list "e15" "e21") (list "e15" "e22") (list "e15" "e23") (list "e15" "e24") (list "e15" "e25") (list "e15" "e26") (list "e16" "e23"))) (define ts$54 (list (list "e16" "e25"))) (define ts$5 (list (list "e10"))) (define ts$52 (list (list "e10" "e20") (list "e10" "e21") (list "e10" "e22") (list "e10" "e23") (list "e10" "e24") (list "e10" "e25") (list "e10" "e26") (list "e11" "e20") (list "e11" "e21") (list "e11" "e22") (list "e11" "e23") (list "e11" "e24") (list "e11" "e25") (list "e11" "e26") (list "e12" "e20") (list "e12" "e21") (list "e12" "e22") (list "e12" "e23") (list "e12" "e24") (list "e12" "e25") (list "e12" "e26") (list "e13" "e20") (list "e13" "e21") (list "e13" "e22") (list "e13" "e23") (list "e13" "e24") (list "e13" "e25") (list "e13" "e26") (list "e14" "e20") (list "e14" "e21") (list "e14" "e22") (list "e14" "e23") (list "e14" "e24") (list "e14" "e25") (list "e14" "e26") (list "e15" "e20") (list "e15" "e21") (list "e15" "e22") (list "e15" "e23") (list "e15" "e24") (list "e15" "e25") (list "e15" "e26") (list "e16" "e24"))) (define ts$13 (list (list "e12"))) (define ts$3 (list (list "e20") (list "e21") (list "e22") (list "e23") (list "e24") (list "e25") (list "e26"))) (define ts$42 (list (list "e16" "e21"))) (define ts$1 (list (list "e10") (list "e11") (list "e12") (list "e13") (list "e14") (list "e15") (list "e16"))) (define ts$58 (list (list "e10" "e20") (list "e10" "e21") (list "e10" "e22") (list "e10" "e23") (list "e10" "e24") (list "e10" "e25") (list "e10" "e26") (list "e11" "e20") (list "e11" "e21") (list "e11" "e22") (list "e11" "e23") (list "e11" "e24") (list "e11" "e25") (list "e11" "e26") (list "e12" "e20") (list "e12" "e21") (list "e12" "e22") (list "e12" "e23") (list "e12" "e24") (list "e12" "e25") (list "e12" "e26") (list "e13" "e20") (list "e13" "e21") (list "e13" "e22") (list "e13" "e23") (list "e13" "e24") (list "e13" "e25") (list "e13" "e26") (list "e14" "e20") (list "e14" "e21") (list "e14" "e22") (list "e14" "e23") (list "e14" "e24") (list "e14" "e25") (list "e14" "e26") (list "e15" "e20") (list "e15" "e21") (list "e15" "e22") (list "e15" "e23") (list "e15" "e24") (list "e15" "e25") (list "e15" "e26") (list "e16" "e26"))) (define ts$40 (list (list "e10" "e20") (list "e10" "e21") (list "e10" "e22") (list "e10" "e23") (list "e10" "e24") (list "e10" "e25") (list "e10" "e26") (list "e11" "e20") (list "e11" "e21") (list "e11" "e22") (list "e11" "e23") (list "e11" "e24") (list "e11" "e25") (list "e11" "e26") (list "e12" "e20") (list "e12" "e21") (list "e12" "e22") (list "e12" "e23") (list "e12" "e24") (list "e12" "e25") (list "e12" "e26") (list "e13" "e20") (list "e13" "e21") (list "e13" "e22") (list "e13" "e23") (list "e13" "e24") (list "e13" "e25") (list "e13" "e26") (list "e14" "e20") (list "e14" "e21") (list "e14" "e22") (list "e14" "e23") (list "e14" "e24") (list "e14" "e25") (list "e14" "e26") (list "e15" "e20") (list "e15" "e21") (list "e15" "e22") (list "e15" "e23") (list "e15" "e24") (list "e15" "e25") (list "e15" "e26") (list "e16" "e20"))) (define ts$43 (list (list "e10" "e20") (list "e10" "e21") (list "e10" "e22") (list "e10" "e23") (list "e10" "e24") (list "e10" "e25") (list "e10" "e26") (list "e11" "e20") (list "e11" "e21") (list "e11" "e22") (list "e11" "e23") (list "e11" "e24") (list "e11" "e25") (list "e11" "e26") (list "e12" "e20") (list "e12" "e21") (list "e12" "e22") (list "e12" "e23") (list "e12" "e24") (list "e12" "e25") (list "e12" "e26") (list "e13" "e20") (list "e13" "e21") (list "e13" "e22") (list "e13" "e23") (list "e13" "e24") (list "e13" "e25") (list "e13" "e26") (list "e14" "e20") (list "e14" "e21") (list "e14" "e22") (list "e14" "e23") (list "e14" "e24") (list "e14" "e25") (list "e14" "e26") (list "e15" "e20") (list "e15" "e21") (list "e15" "e22") (list "e15" "e23") (list "e15" "e24") (list "e15" "e25") (list "e15" "e26") (list "e16" "e21"))) (define ts$11 (list (list "e21"))) (define ts$33 (list (list "e16" "e16" "e15"))) (define ts$39 (list (list "e16" "e20"))) (define ts$27 (list (list "e25"))) (define ts$7 (list (list "e20"))) (define bd$35 (bound r$3 ts$33 ts$34)) (define bd$41 (bound r$8 ts$39 ts$40)) (define bd$47 (bound r$12 ts$45 ts$46)) (define bd$14 (bound r$30 ts$13 ts$13)) (define bd$2 (bound r$1 ts$1 ts$1)) (define bd$38 (bound r$7 ts$36 ts$37)) (define bd$59 (bound r$20 ts$57 ts$58)) (define bd$4 (bound r$5 ts$3 ts$3)) (define bd$53 (bound r$16 ts$51 ts$52)) (define bd$24 (bound r$39 ts$23 ts$23)) (define bd$28 (bound r$40 ts$27 ts$27)) (define bd$30 (bound r$34 ts$29 ts$29)) (define bd$12 (bound r$36 ts$11 ts$11)) (define bd$22 (bound r$32 ts$21 ts$21)) (define bd$32 (bound r$41 ts$31 ts$31)) (define bd$26 (bound r$33 ts$25 ts$25)) (define bd$10 (bound r$29 ts$9 ts$9)) (define bd$6 (bound r$28 ts$5 ts$5)) (define bd$16 (bound r$37 ts$15 ts$15)) (define bd$20 (bound r$38 ts$19 ts$19)) (define bd$56 (bound r$18 ts$54 ts$55)) (define bd$50 (bound r$14 ts$48 ts$49)) (define bd$18 (bound r$31 ts$17 ts$17)) (define bd$44 (bound r$10 ts$42 ts$43)) (define bd$8 (bound r$35 ts$7 ts$7)) (define bounds$60 (bounds universe$0 (list bd$35 bd$41 bd$47 bd$14 bd$2 bd$38 bd$59 bd$4 bd$53 bd$24 bd$28 bd$30 bd$12 bd$22 bd$32 bd$26 bd$10 bd$6 bd$16 bd$20 bd$56 bd$50 bd$18 bd$44 bd$8))) (define F b-f$445) (define bnds bounds$60) (displayln "-- instantiating bounds...") (define interp (time (instantiate-bounds bnds))) (displayln "-- making boolean interpretation...") (define F* (time (interpret* F interp))) (define SS (make-SAT)) (displayln "-- making optimized SAT call...") (define sol (time (SAT-solve SS (list F*))))
false
8c7c984a1c572368bf9db5cba55b7d12588397e9
bc38b888675e831a3ec99268be7f5f90a3b5ac9a
/fontland/glyphrun.rkt
fc1ad2911ea19807d3a4e5741194abd0c10f8c19
[ "MIT" ]
permissive
mbutterick/fontland
c3dd739a5c36730edeca3838225dc8a0c285051b
1c1d7db48f2637f7a226435c4fef39a7037204b7
refs/heads/master
2022-02-03T19:48:29.543945
2022-01-08T15:58:14
2022-01-08T15:58:14
157,796,528
12
0
null
null
null
null
UTF-8
Racket
false
false
1,155
rkt
glyphrun.rkt
#lang racket/base (require "glyph-position.rkt") (provide (all-defined-out)) #| approximates https://github.com/mbutterick/fontkit/blob/master/src/layout/GlyphRun.js |# ;; Represents a run of Glyph and GlyphPosition objects. ;; Returned by the font layout method. ; An array of Glyph objects in the run ; An array of GlyphPosition objects for each glyph in the run (struct glyphrun (glyphs positions) #:transparent) (define (+glyphrun [glyphs null] [positions null]) (glyphrun glyphs positions)) (define (glyphrun-advance-width gr) (for/sum ([pos (in-list (glyphrun-positions gr))]) (glyph-position-x-advance pos))) (define (append-glyphruns . grs) (for/fold ([glyphss null] [positionss null] #:result (glyphrun (apply append (reverse glyphss)) (apply append (reverse positionss)))) ([gr (in-list grs)]) (values (cons (glyphrun-glyphs gr) glyphss) (cons (glyphrun-positions gr) positionss)))) (module+ test (require rackunit) (define gr (+glyphrun)) (check-true (glyphrun? gr)) (check-equal? (append-glyphruns gr gr) gr))
false