blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
171
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1ae5bfec7143bc4818f5538f72ffc38d4b84b109 | b5a4c9cfbe35467faf5223271b3a6669fc0888fb | /racket/imp/7-imp++/1-imp++-bigstep/imp-stmt-expander.rkt | 0f46c215358ea88f7b1b9771de99323789845094 | [
"MIT"
] | permissive | kframework/semantic-approaches | 33e87b5336f723d16432e9ef4a4f7ed77e53cf95 | 6f64eac09e005fe4eae7141e3c0e0f5711da0647 | refs/heads/master | 2020-04-12T00:35:22.862491 | 2019-01-07T22:15:57 | 2019-01-07T22:15:57 | 162,204,995 | 11 | 1 | MIT | 2018-12-22T01:42:20 | 2018-12-17T23:59:50 | Haskell | UTF-8 | Racket | false | false | 3,056 | rkt | imp-stmt-expander.rkt | #lang racket
(require racket/match)
(require "imp-sigma.rkt")
; Conditionally executes a statement without-halt with the configuration S
; if S is in a halting state, do nothing and return that same S
; otherwise, runs without-halt with the configuration S
(define stmt-with-halt
(lambda (without-halt)
(lambda (S)
(if (halt? S)
S
(without-halt S)))))
; Given choice1 and choice2 returns a tuple of values where
; the two choices are randomly ordered
(define (non-deterministic choice1 choice2)
(begin (define shuffled (shuffle (list choice1 choice2)))
(values (car shuffled) (cadr shuffled))))
(define accepts-next-stmt?
(lambda (proc)
(let-values ([(_ keywords) (procedure-keywords proc)])
(not (empty? keywords)))))
(require racket/undefined)
(define-syntax-rule
(run-stmt (S) body)
(stmt-with-halt (lambda (S) body)))
(define id_list
(lambda ast
(match ast
[(list id) (run-stmt (S) (add-var S id))]
[(list id "," rest) (run-stmt (S) (rest (add-var S id)))])))
(define stmt
(lambda ast
(match ast
[(list "int" ids ";") (run-stmt (S) (ids S))]
[(list "spawn" b)
(lambda (S #:next-stmt [next-stmt undefined])
(if (halt? S)
S
(if (eq? next-stmt undefined)
(b S)
(let-values ([(s1 s2) (non-deterministic b next-stmt)])
(s2 (s1 S))))))]
[(list id "=" a ";")
(run-stmt (S)
(let-values ([(a-result S+) (a S)])
(if (halt? S+)
S+
(update-var S+ id a-result))))]
[(list "if" "(" c ")" block1 "else" block2)
(run-stmt (S)
(let-values ([(bval S+) (c S)])
(if (halt? S+)
S+
(if bval (block1 S+) (block2 S+)))))]
[(list "while" "(" c ")" body)
(run-stmt (S)
(let-values ([(bval S+) (c S)])
(if (halt? S+)
S+
(if bval
((stmt "while" "(" c ")" body) (body S+))
S+))))]
[(list "print" "(" a ")" ";")
(run-stmt (S)
(let-values ([(a-result S+) (a S)])
(if (halt? S+)
S+
(append-output S+ (list a-result)))))]
[(list "halt" ";") (run-stmt (S) (halt! S))]
[(list b) (run-stmt (S) (b S))])))
(define seq
(lambda ast
(match ast
[(list s) (run-stmt (S) (s S))]
[(list s ss) (run-stmt (S)
(if (accepts-next-stmt? s)
(s S #:next-stmt ss)
(ss (s S))))]
)))
(define block
(lambda ast
(match ast
[(list "{" "}") (lambda (S) S)]
[(list "{" body "}")
(run-stmt (S)
(exit-block (body (enter-block S))))]
)))
(provide id_list
stmt
block
seq
) | true |
45699f87f04d82796ccb637e2f83e7e0f35d258c | 9900dac194d9e0b69c666ef7af5f1885ad2e0db8 | /OutsideRedex/Stack.rkt | 8d062d30a39181c8f1bd1126a07239dd5e33b592 | [] | no_license | atgeller/Wasm-prechk | b1c57616ce1c7adbb4b9a6e1077aacfa39536cd2 | 6d04a5474d3df856cf8af1877638b492ca8d0f33 | refs/heads/canon | 2023-07-20T10:58:28.382365 | 2023-07-11T22:58:49 | 2023-07-11T22:58:49 | 224,305,190 | 5 | 1 | null | 2021-07-01T18:09:17 | 2019-11-26T23:34:11 | Racket | UTF-8 | Racket | false | false | 3,754 | rkt | Stack.rkt | #lang racket
(require (for-syntax racket))
(define empty-stack
(lambda ([expected 't])
(error "Cannot pop from empty stack")))
(define (any-stack [expected 't])
(cons
(match expected
['t 'i32]
[_ expected])
any-stack))
(define (push-stack stack index_type)
(lambda ([expected 't])
(match expected
[(? unification-type?) (cons index_type stack)]
[_ #:when (eq? expected (car index_type)) (cons index_type stack)]
[else #f])))
(define (list->stack list)
'())
#;(define (pop-stack1 stack [expected 't])
(match (stack expected)
[(cons type stack) (cons type stack)]))
(define (unification-type? type)
(or (equal? type 't) (string-prefix? (symbol->string type) "t_")))
(begin-for-syntax
(define (unification-type-stx? type)
(or (equal? type 't) (string-prefix? (symbol->string type) "t_"))))
(define stack empty-stack)
(define stack1 (push-stack stack '(i32 a_1)))
(define stack2 (push-stack stack1 '(i32 a_2)))
(define stack3 (push-stack stack2 '(i32 a_3)))
(define stackbad (push-stack stack1 '(i64 a_1)))
;; Example usage:
;(let-stack stack3 [(i32 a_3) (t_1 a_2) (t_2 a_1) rest] body)
(define (env-from-stack stack pattern)
(for/fold ([matches (make-immutable-hash)]
[rest stack])
([object (syntax->list pattern)]
#:break (not (syntax->list object)))
(match (syntax->datum object)
[`(,expected-type ,index-var)
(let* ([unified-type
(if (unification-type? expected-type)
(dict-ref matches expected-type expected-type)
expected-type)]
[stack-popped (rest unified-type)]
[stack-top (car stack-popped)]
[type-stack (car stack-top)]
[index-var-stack (cadr stack-top)]
[stack-rest (cdr stack-popped)]
[matches* (dict-set matches index-var index-var-stack)]
[matches** (if (unification-type? unified-type)
(dict-set matches* expected-type type-stack)
matches*)])
(values matches** stack-rest))])))
(require racket/trace)
(trace-define-syntax
(let-stack stx)
(syntax-case stx ()
[(let-stack stack pattern body)
#`(let-values ([(env rest) (env-from-stack stack #'pattern)])
(let* #,(for/fold ([acc '()]
[seen '()]
#:result acc)
([object (syntax->list #'pattern)])
(match (syntax->list object)
[`(,type ,index-var)
(let* ([env-type (if (unification-type-stx? (syntax->datum type))
(list type #`(dict-ref env '#,type))
#f)]
[env-index-var (list index-var #`(dict-ref env '#,index-var))]
[acc* (if (and env-type (not (member type seen))) (cons env-type acc) acc)]
[acc** (cons env-index-var acc*)]
[seen* (cons type (cons index-var seen))])
(if (member index-var seen)
(error "Multiply passed index-var to let-stack ~a" index-var)
(values acc** seen*)))]
[#f #:when (symbol? (syntax->datum object)) (values (cons (list object #'rest) acc) seen)]))
body))]))
(let-stack stack3 [(i32 a_3) (t a_2) (t a_1) rest] (displayln t))
(let-stack stack2 [(t a_2) (t a_1) rest] (displayln t))
;; Error example:
;;(let-stack stackbad [(t a_2) (t a_1) rest] (displayln t))
;; Error example #2:
;;(let-stack stackbad [(t a_2) (t_2 a_1) (t_7 a_7) rest] (displayln t)) | true |
0d4cb40197169729363411c2984a3f4b1a2489c0 | 799b5de27cebaa6eaa49ff982110d59bbd6c6693 | /soft-contract/test/programs/safe/issues/unsafe-vector-star.rkt | 9da58706034565e107f104e09f0c77260457f368 | [
"MIT"
] | permissive | philnguyen/soft-contract | 263efdbc9ca2f35234b03f0d99233a66accda78b | 13e7d99e061509f0a45605508dd1a27a51f4648e | refs/heads/master | 2021-07-11T03:45:31.435966 | 2021-04-07T06:06:25 | 2021-04-07T06:08:24 | 17,326,137 | 33 | 7 | MIT | 2021-02-19T08:15:35 | 2014-03-01T22:48:46 | Racket | UTF-8 | Racket | false | false | 297 | rkt | unsafe-vector-star.rkt | #lang racket/base
(require racket/contract
racket/unsafe/ops)
(define v (vector 1 2 3))
(define n (unsafe-vector*-ref v 0))
(define l (unsafe-vector*-length v))
(define (f xs) xs)
(provide
(contract-out
[n integer?]
[l fixnum?]
[f ((vectorof integer?) . -> . impersonator?)]))
| false |
0417324a3d48573531d18e4e2cdb35d326c9bbb6 | 612da163dde8ad5c4ff647a2d37ebacd043dba76 | /tests/make-uid.rkt | 5f9dc661fe7759ecbc2850ca3395eab30271f949 | [] | no_license | danking/tea-script | c777d90b1e25a8ff50716e9f8f4213e958fa5365 | 6c87c4572850d690de9f4411e98f442dbb199da8 | refs/heads/master | 2021-01-01T19:06:51.147052 | 2011-04-25T02:34:47 | 2011-04-25T02:34:47 | 1,093,973 | 2 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 646 | rkt | make-uid.rkt | #lang racket
(require rackunit
"../make-uid.rkt")
(provide make-uid-ts)
(define make-uid-ts
(test-suite
"tests for make-uid.rkt"
(test-case
"clean symbols"
(check-equal? (make-symbol-unique 'foo (list 'foo 'bar))
'foo)
(check-equal? (make-symbol-unique 'bar (list 'foo 'bar))
'bar)
(check-equal? (make-symbol-unique 'baz (list 'foo 'bar))
'baz))
(test-case
"dirty symbols"
(check-equal? (make-symbol-unique 'foo- (list 'foo_))
'foo_0)
(check-equal? (make-symbol-unique 'foo- (list 'foo_ 'foo_0))
'foo_1))))
| false |
685271a51c1d65fb1a9e659aa3039ce09ed93890 | 7779e409be6f3238e811df9be8b7c89dd2986e06 | /src/symbolic/test-simulator.rkt | bcdffed823420245e40b9cbd02010b1f2adb18b8 | [
"BSD-3-Clause"
] | permissive | mangpo/chlorophyll | ffba3d0f8659f8cad7246e70a43cfcb88847f25c | ab6d4268c5d12aa66eff817c678aaf7ebf935ba7 | refs/heads/master | 2020-04-16T01:43:55.873675 | 2016-07-08T13:11:21 | 2016-07-08T13:11:21 | 10,754,851 | 55 | 7 | null | 2016-07-08T13:11:21 | 2013-06-18T05:47:19 | Racket | UTF-8 | Racket | false | false | 2,647 | rkt | test-simulator.rkt | #lang s-exp rosette
(require "../arrayforth.rkt" "simulator.rkt")
(define code
(aforth
;; linklist
(list
(vardecl '(0 -281 5203 -42329 37407 0))
(funcdecl "1if"
;; linklist
(list
(-iftf
;; linklist
(list
(block
"0 b! "
0 0 (restrict #t #f #f #f) #f
"0 b! ")
)
;; linklist
(list
(block
"0 b! "
0 0 (restrict #t #f #f #f) #f
"0 b! ")
)
)
(funccall "1if")
)
#f)
(funcdecl "main"
;; linklist
(list
(funccall "--u/mod")
(block
"0 b!"
0 0 (restrict #t #f #f #f) "0"
"0 b!")
(ift
;; linklist
(list
(forloop
;; linklist
(list
)
;; linklist
(list
(block
"2* "
1 1 (restrict #t #f #f #f) #f
"2* ")
)
#f #f #f)
(block
"dup "
1 2 (restrict #t #f #f #f) #f
"dup ")
)
)
(funccall "1if")
;(funccall "*.")
(block
"0 b! !b "
1 0 (restrict #t #f #f #f) #f
"0 b! !b ")
(block
"3 b! !b "
1 0 (restrict #t #f #f #f) #f
"5 b! !b ")
(forloop
;; linklist
(list
(block
"1 a! 3 "
0 1 (restrict #t #t #f #f) #f
"1 a! 3 ")
)
;; linklist
(list
(block
"3 b! @b "
0 1 (restrict #t #t #f #f) #f
"5 b! @b ")
(block
"0 b! @b "
0 1 (restrict #t #t #f #f) #f
"0 b! @b ")
;(funccall "*.")
(block
"@+ "
1 1 (restrict #t #t #f #f) #f
"@+ ")
(block
"3 b! !b "
1 0 (restrict #t #t #f #f) #f
"5 b! !b ")
)
'((1 . opt) 1 . opt) 0 4)
(block
"3 b! @b "
0 1 (restrict #t #f #f #f) #f
"5 b! @b ")
;(funccall "*.")
(block
"up b! !b "
1 0 (restrict #t #f #f #f) "up"
"up b! !b ")
;(funccall "1if")
)
#f)
)
4 18 #hash((0 . 0) (1 . 1) (3 . 5) (4 . 6)))
)
(define state-i (get-progstate 4))
(define state-f (analyze-reg-b code state-i 0))
(aforth-struct-print code)
| false |
6eb1c44bdca445ea88dbd7db0f639c8be0bddc7b | 259c841b8a205ecaf9a5980923904452a85c5ee5 | /NBE/ch3.rkt | 2e2915bbe1e3c7ce317570a03d5023132390f312 | [] | 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 | 2,994 | rkt | ch3.rkt | #lang racket
;; Untyped NbE
(require rackunit)
(require "error.rkt")
(struct CLOS (env var body)
#:transparent)
(define (extend ρ x v)
(cons (cons x v) ρ))
#| Generating Fresh Names |#
(define (add-* x)
(string->symbol (string-append (symbol->string x) "*")))
(define (freshen used x)
(if (memv x used)
(freshen used (add-* x))
x))
(check-eq? (freshen '() 'x) 'x)
(check-eq? (freshen '(x x*) 'x) 'x**)
(check-eq? (freshen '(x y z) 'y) 'y*)
#| Normalizing Untyped λ-Calculus |#
#|
Normal forms:
<norm> ::= <neu>
| ( λ ( <id> ) <norm> )
<neu> ::= <id>
| ( <neu> <norm> )
|#
;; neutral variable
(struct N-var (name))
;; neutral application
(struct N-ap (rator rand))
(define (val ρ e)
(match e
[`(λ (,x) ,b) (CLOS ρ x b)]
[x #:when (symbol? x)
(let ([xv (assv x ρ)])
(if xv
(cdr xv)
(error 'val "Unknown variable ~v" x)))]
[`(,rator ,rand)
(do-ap (val ρ rator) (val ρ rand))]))
(define (do-ap fun arg)
(match fun
[(CLOS ρ x b)
(val (extend ρ x arg) b)]
; If the argument is neutral, construct a bigger neutral expression.
[neutral-fun
(N-ap fun arg)]))
(define (read-back used-names v)
(match v
[(CLOS ρ x body)
(let* ([y (freshen used-names x)]
[neutral-y (N-var y)])
`(λ (,y) ,(read-back (cons y used-names)
(val (extend ρ x neutral-y) body))))]
[(N-var x) x]
[(N-ap rator rand)
`(,(read-back used-names rator) ,(read-back used-names rand))]))
(check-equal?
(read-back '() (val '() '((λ (x) (λ (y) (x y)))
(λ (z) z))))
'(λ (y) y))
(define (norm ρ e)
(read-back '() (val ρ e)))
(define (run-program ρ exprs)
(match exprs
[(list) (void)]
[(list `(define ,x ,e) rest ...)
(let ([v (val ρ e)])
(run-program (extend ρ x v) rest))]
[(list e rest ...)
(displayln (norm ρ e))
(run-program ρ rest)]))
#| Church Numerals |#
(define (with-numerals e)
`((define church-zero
(λ (f) (λ (x) x)))
(define church-add1
(λ (n-1) (λ (f) (λ (x) (f ((n-1 f) x))))))
,e))
(define (to-church n)
(cond [(zero? n) 'church-zero]
[(positive? n)
(let ([church-of-n-1 (to-church (sub1 n))])
`(church-add1 ,church-of-n-1))]))
(run-program '() (with-numerals (to-church 0))) ;; (λ (f) (λ (x) x))
(run-program '() (with-numerals (to-church 5))) ;; (λ (f) (λ (x) (f (f (f (f (f x)))))))
(define church-add
'(λ (j)
(λ (k)
(λ (f)
(λ (x)
((j f) ((k f) x)))))))
(define church-mult
'(λ (j)
(λ (k)
(λ (f)
(λ (x)
((j (k f)) x))))))
(run-program '()
(with-numerals `((,church-add ,(to-church 2))
,(to-church 2))))
(run-program '()
(with-numerals `((,church-mult ,(to-church 2))
,(to-church 3))))
| false |
6343c46f9ca29595c388cfbb87837cd4f8b9cae3 | 0bf98f73fd1eb721be784f00213796f32a83bcfa | /TPs/tp03_rss/tp03_bd600929.rkt | 466e841d27ea5210ed6fe43fbcebda0c7855a79e | [] | no_license | takitsu21/paradigme | 59469b9e9995bcce54b4914655e906059000d76f | f74739d78b02a8f172ecfb01022f53d8c370a4f2 | refs/heads/main | 2023-06-06T06:14:39.312073 | 2021-07-05T08:20:11 | 2021-07-05T08:20:11 | 333,158,011 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 8,297 | rkt | tp03_bd600929.rkt | ; Cours 03 : Ordre supérieur
#lang plait
;;;;;;;;;;;;;;;;;;;;;;;;
; Définition des types ;
;;;;;;;;;;;;;;;;;;;;;;;;
; Représentation des expressions
(define-type Exp
[numE (n : Number)]
[idE (s : Symbol)]
[plusE (l : Exp) (r : Exp)]
[multE (l : Exp) (r : Exp)]
[ifE (first : Exp) (second : Exp) (third : Exp)]
[boolE (b : Boolean)]
[equalE (l : Exp) (r : Exp)]
[lamE (par : Symbol) (body : Exp)]
[appE (fun : Exp) (arg : Exp)]
[letE (s : Symbol) (rhs : Exp) (body : Exp)]
[unletE (s : Symbol) (body : Exp)]
[delayE (body : Exp)]
[forceE (body : Exp)])
; Représentation des valeurs
(define-type Value
[numV (n : Number)]
[boolV (b : Boolean)]
[thunkV (t : Exp) (env : Env)]
[closV (par : Symbol) (body : Exp) (env : Env)])
; Représentation des liaisons
(define-type Binding
[bind (name : Symbol) (val : Value)])
; Manipulation de l'environnement
(define-type-alias Env (Listof Binding))
(define mt-env empty)
(define extend-env cons)
;;;;;;;;;;;;;;;;;;;;;;
; Analyse syntaxique ;
;;;;;;;;;;;;;;;;;;;;;;
(define (parse [s : S-Exp]) : Exp
(cond
[(s-exp-match? `{delay ANY} s)
(let ([sl (s-exp->list s)])
(delayE (parse (second sl))))]
[(s-exp-match? `{force ANY} s)
(let ([sl (s-exp->list s)])
(forceE (parse (second sl))))]
[(s-exp-match? `NUMBER s) (numE (s-exp->number s))]
[(s-exp-match? `true s) (boolE #t)]
[(s-exp-match? `false s) (boolE #f)]
[(s-exp-match? `SYMBOL s) (idE (s-exp->symbol s))]
[(s-exp-match? `{= ANY ANY} s)
(let ([sl (s-exp->list s)])
(equalE (parse (second sl)) (parse (third sl))))]
[(s-exp-match? `{if ANY ANY ANY} s)
(let ([sl (s-exp->list s)])
(ifE (parse (second sl)) (parse (third sl)) (parse (fourth sl))))]
[(s-exp-match? `{+ ANY ANY} s)
(let ([sl (s-exp->list s)])
(plusE (parse (second sl)) (parse (third sl))))]
[(s-exp-match? `{* ANY ANY} s)
(let ([sl (s-exp->list s)])
(multE (parse (second sl)) (parse (third sl))))]
[(s-exp-match? `{lambda {SYMBOL} ANY} s)
(let ([sl (s-exp->list s)])
(lamE (s-exp->symbol (first (s-exp->list (second sl)))) (parse (third sl))))]
[(s-exp-match? `{ANY ANY} s)
(let ([sl (s-exp->list s)])
(appE (parse (first sl)) (parse (second sl))))]
[(s-exp-match? `{unlet SYMBOL ANY} s)
(let ([sl (s-exp->list s)])
(unletE (s-exp->symbol (second sl)) (parse (third sl))))]
[(s-exp-match? `{let [{SYMBOL ANY}] ANY} s)
(let ([sl (s-exp->list s)])
(let ([subst (s-exp->list (first (s-exp->list (second sl))))])
(letE (s-exp->symbol (first subst))
(parse (second subst))
(parse (third sl)))))]
[else (error 'parse "invalid input")]))
;[(unletE s body) (if (> 2 (length env))
; (error 'interp "free identifier")
; (bind-val (second env)))]))
;;;;;;;;;;;;;;;;;;
; Interprétation ;
;;;;;;;;;;;;;;;;;;
(define (delete-item acc item l mt)
(cond
[(or (empty? l) (equal? #t acc)) (append mt l)]
[(equal? item (bind-name (first l))) (delete-item #t item (rest l) mt)]
[else (delete-item acc item (rest l) (append mt (list (first l))))]))
; Interpréteur
(define (interp [e : Exp] [env : Env]) : Value
(type-case Exp e
[(numE n) (numV n)]
[(boolE b) (boolV b)]
[(idE s) (lookup s env)]
[(plusE l r) (num+ (interp l env) (interp r env))]
[(multE l r) (num* (interp l env) (interp r env))]
[(equalE l r) (num= (interp l env) (interp r env))]
[(lamE par body) (closV par body env)]
[(ifE first second third) (eval-if first second third env)]
[(appE f arg)
(type-case Value (interp f env)
[(closV par body c-env)
(interp body (extend-env (bind par (interp arg env)) c-env))]
[else (error 'interp "not a function")])]
[(letE s rhs body) (interp body (extend-env (bind s (interp rhs env)) env))]
[(forceE body)
(type-case Value (interp body env)
[(thunkV e c-env)
(interp e c-env)]
[else (error 'interp "not a thunk")])]
[(delayE body) (thunkV body env)]
[(unletE s body)
(interp body (delete-item #f s env empty))]))
(define (eval-if [first : Exp]
[second : Exp]
[third : Exp]
[env : Env]) : Value
(let ([if-val (interp first env)])
(if (not (boolV? if-val))
(error 'interp "not a boolean")
(if (boolV? if-val)
(interp second env)
(interp third env)))))
; Fonctions utilitaires pour l'arithmétique
(define (num-op [op : (Number Number -> Number)]
[l : Value] [r : Value]) : Value
(if (and (numV? l) (numV? r))
(numV (op (numV-n l) (numV-n r)))
(error 'interp "not a number")))
(define (num-op-equal [op : (Number Number -> Boolean)]
[l : Value] [r : Value]) : Value
(if (and (numV? l) (numV? r))
(boolV (op (numV-n l) (numV-n r)))
(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-equal = l r))
(define (num* [l : Value] [r : Value]) : Value
(num-op * l r))
; Recherche d'un identificateur dans l'environnement
(define (lookup [n : Symbol] [env : Env]) : Value
(cond
[(empty? env) (error 'lookup "free identifier")]
[(equal? n (bind-name (first env))) (bind-val (first env))]
[else (lookup n (rest env))]))
;;;;;;;;;
; Tests ;
;;;;;;;;;
(define (interp-expr [e : S-Exp]) : Value
(interp (parse e) mt-env))
(test (interp-expr `{let {[f {lambda {x} {+ 1 x}}]} {f 2}})
(numV 3))
(test (interp-expr `{let {[y 1]} {lambda {x} {+ x y}}})
(closV 'x (plusE (idE 'x) (idE 'y)) (extend-env (bind 'y (numV 1)) mt-env)))
(test (interp-expr `{let {[y 1]} {{lambda {x} {+ x y}} 2}})
(numV 3))
(test (interp-expr `{= 1 2}) (boolV #f))
(test/exn (interp-expr `{= true true}) "not a number")
(test (interp-expr `{if true 1 2}) (numV 1))
(test (interp-expr `{if {= {+ 1 3} {* 2 2}} 4 5}) (numV 4))
(test/exn (interp-expr `{if 1 2 3}) "not a boolean")
(test (interp-expr `{if true 1 x}) (numV 1))
(test (interp-expr `{ let {[x 1]} {let {[x 2]} {unlet x x}}}) (numV 1))
(test (interp-expr `{ let {[x 1]}
{ let {[x 2]}
{+ { unlet x x} x} } }) (numV 3))
(test/exn (interp-expr `{ let {[x 1]}
{ unlet x x} }) "free identifier")
(test/exn (interp-expr `{ let {[x 1]}
{ let {[y 2]}
{let {[x 3]}
{let {[x 4]}
{+ { unlet x {unlet y y}} x}}}}}) "free identifier")
(test (interp-expr `{ let {[y 1]}
{ let {[y 2]}
{let {[x 3]}
{let {[x 4]}
{+ { unlet x {unlet y y}} x}}}}}) (numV 5))
;(define (ignore x) (void))
;(test (ignore (interp-expr `{ delay {+ 1 { lambda {x} x} } })) (void))
(test/exn (interp-expr `{ force { delay {+ 1 { lambda {x} x} } } }) "not a number")
(test (interp-expr `{ let {[t { let {[x 1]} { delay x} }]}
{ let {[x 2]}
{ force t} } }) (numV 1))
(test (interp-expr `{force {delay {force {delay {+ 3 1}}}}}) (numV 4))
(test (interp-expr `{force {delay {+ 3 1}}}) (numV 4))
(test (interp-expr `{force {delay { let {[t { let {[x 1]} { delay x} }]}
{ let {[x 2]}
{ force t} } }}}) (numV 1))
(test/exn (interp-expr `{force {lambda {x} x}}) "not a thunk")
(test (interp-expr `{let {[t {let {[x 1]} {delay x}}]}
{let {[g {delay {let {[x 2]} {force t}}}]}
{force g}}})
(numV 1))
(test (interp-expr `{force {delay {delay 0}}}) (thunkV (numE 0) '()))
(test (interp-expr `{let {[y 4]}
{let {[y 3]}
{let {[x 1]}
{let {[x 2]}
{unlet x {+ x {* y {unlet y {* x y}}}}}}}}})
(numV 13))
(test (interp-expr `{let {[x 1]}
{let {[x 2]}
{unlet y x}}})
(numV 2)) | false |
1e11f180760b75ed2d1790ca58c028f9451c7d76 | ed84d789ef8e227aca6af969a8ae0c76015ee3ba | /eval-order/L2/semantics.rkt | 97d8d9a5fccc585fc6196e413c08f876f50db998 | [] | no_license | nthnluu/mystery-languages | 3de265714969fdf8dfa7bedc6df5a84b709c2bbd | 865481a10c22260b2e9a5a3c5873366679fc5283 | refs/heads/master | 2023-08-28T02:46:24.614863 | 2021-10-09T12:38:07 | 2021-10-09T12:38:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,138 | rkt | semantics.rkt | #lang racket
(require [for-syntax syntax/parse] mystery-languages/utils mystery-languages/common)
(require [for-syntax racket])
(require [prefix-in lazy: lazy])
(provide [rename-out (lazy:#%module-begin #%module-begin) (lazy:#%top-interaction #%top-interaction)
(lazy:#%datum #%datum) (lazy:#%top #%top) (lazy:#%app #%app)
(lazy:+ +) (lazy:- -) (lazy:* *) (lazy:/ /)
(lazy:< <) (lazy:<= <=) (lazy:> >) (lazy:>= >=)
(lazy:= =);
(lazy:string-append ++)
(lazy:if if) (lazy:and and) (lazy:or or) (lazy:not not)])
(provide <> defvar deffun)
(provide [rename-out (lazy:begin begin)])
(provide vset)
(lazy:define (<> a b)
(lazy:not (lazy:= a b)))
(define-syntax (deffun stx)
(syntax-parse stx
[(_ (fname:id arg:id ...) body:expr ...+)
#'(lazy:define (fname arg ...) body ...)]))
(define-syntax (defvar stx)
(syntax-parse stx
[(_ var:id rhs:expr)
#'(lazy:define var rhs)]))
(define-syntax (vset stx)
(syntax-parse stx
[(_ var:id val:expr)
#'(lazy:set! var val)]))
| true |
ea88fb6cfd69540520b40431ce495cb71ad11565 | 0ac2d343bad7e25df1a2f2be951854d86b3ad173 | /pycket/test/dot-specialize.rkt | 819b76dd37968894ab1d6148aa0c4d4d40dee7b2 | [
"MIT"
] | permissive | pycket/pycket | 8c28888af4967b0f85c54f83f4ccd536fc8ac907 | 05ebd9885efa3a0ae54e77c1a1f07ea441b445c6 | refs/heads/master | 2021-12-01T16:26:09.149864 | 2021-08-08T17:01:12 | 2021-08-08T17:01:12 | 14,119,907 | 158 | 14 | MIT | 2021-08-08T17:01:12 | 2013-11-04T18:39:34 | Python | UTF-8 | Racket | false | false | 409 | rkt | dot-specialize.rkt | #lang racket/base
(require racket/contract racket/flonum racket/unsafe/ops)
(define N 10000000)
(define (dot3 v1 v2)
(for/sum ([e1 (in-flvector v1)] [e2 (in-flvector v2)]) (fl* e1 e2)))
(define v1 (for/flvector #:length N #:fill 0.0 ([i (in-range N)]) (random)))
(define v2 (for/flvector #:length N #:fill 0.0 ([i (in-range N)]) (random)))
(collect-garbage) (collect-garbage)
'dot1
(time (dot3 v1 v2))
| false |
0eb9ed8ddf63c43890aa23300d7228b54183879c | 58e9b31a12d1037b73675ed48656a37626c5d85e | /principles of programming languages/hws/hw07/test.rkt | b8a2f53e5fc7d03f3f1ce6ba1994d32336fabb40 | [] | no_license | YashasSamaga/college-work | 3dbb278c979baf75a80843c5e3a2a305ece440c7 | caf7f3dd0bd7113039d9b7aba988e8814fc85705 | refs/heads/master | 2022-07-12T14:24:48.787433 | 2022-06-30T06:28:38 | 2022-06-30T06:28:38 | 162,693,749 | 0 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 3,744 | rkt | test.rkt | #lang racket
(require eopl)
(require rackunit)
(require racket/match)
(require rackunit/text-ui)
(require "main.rkt")
(define test-f1
(test-case "f1"
(check-equal? (parse '(recursive ([f1 (x) (< 5 x)])(ifte (f1 2) 0 10)))
(recursive (list
(make-fbind 'f1
'(x)
(app (id-ref '<) (list (num 5) (id-ref 'x)))))
(ifte (app (id-ref 'f1) (list (num 2)))
(num 0)
(num 10))))))
(define test-no-params
(test-case "no params to recur func"
(check-equal? (parse '(recursive ([v () 3]) v))
(recursive (list (make-fbind 'v '() (num 3))) (id-ref 'v)))))
(define test-multi-binds
(test-case "multiple binds"
(check-equal? (parse '(recursive ([f (x) (+ x x)] [g (y) (- (f y) 1)]) (g 1)))
(recursive (list (make-fbind 'f '(x) (app (id-ref '+) (list (id-ref 'x) (id-ref 'x))))
(make-fbind 'g '(y) (app (id-ref '-)
(list (app (id-ref 'f) (list (id-ref 'y)))
(num 1)))))
(app (id-ref 'g) (list (num 1)))))))
(define test-recursive-parsing
(test-suite "Recursive Parsing"
test-f1
test-no-params
test-multi-binds))
(define e1
(extended-env '(x y z) '(1 2 3) (empty-env)))
(define e2
(extended-env '(w x) '(5 6) e1))
(define even-body
(ifte
(app (id-ref '0?) (list (id-ref 'n)))
(bool #t)
(app
(id-ref 'odd?)
(list (app
(id-ref '-)
(list (id-ref 'n) (num 1)))))))
(define odd-body
(ifte (app (id-ref '0?) (list (id-ref 'n)))
(bool #f)
(app (id-ref 'even?)
(list (app (id-ref '-) (list (id-ref 'n) (num 1)))))))
(define e3
(extended-rec-env
'(even? odd?)
'((n) (n))
(list even-body odd-body)
e2))
(check-equal?
(closure '(n) even-body e3)
(lookup-env e3 'even?) "lookup-env-even? test")
(define test-env
(test-case "outer env"
(check-equal? 6 (lookup-env e3 'x))))
(define test-rec-env
(test-case "Outer Rec Env"
(check-equal?
(closure '(n) even-body e3)
(lookup-env e3 'even?))))
(define lookup-test
(test-suite "Lookup"
test-env
test-rec-env))
(define test-even-odd
(test-case "Even Odd"
(check-equal?
(eval-ast
(recursive
(list
(make-fbind 'even?
'(n)
(ifte (app (id-ref '0?) (list (id-ref 'n)))
(bool #t)
(app (id-ref 'odd?)
(list (app (id-ref '-) (list (id-ref 'n) (num 1)))))))
(make-fbind 'odd?
'(n)
(ifte (app (id-ref '0?) (list (id-ref 'n)))
(bool #f)
(app (id-ref 'even?)
(list (app (id-ref '-) (list (id-ref 'n) (num 1))))))))
(app (id-ref 'even?) (list (num 3))))
*init-env*)
#f)))
(define test-factorial
(test-case "factorial"
(check-equal?
(eval-ast (parse '(recursive ([f (n) (ifte (0? n) 1 (* n (f (- n 1))))])
(f 3))) *init-env*)
6)))
(define test-recursive-evaluation
(test-suite "test-eval"
test-even-odd
test-factorial))
(define test-recursive
(test-suite "Recursive Tests"
test-recursive-parsing
lookup-test
test-recursive-evaluation))
(define run-all-tests
(lambda ()
(run-tests test-recursive)))
(module+ test
(run-all-tests))
| false |
4f562c188c9766f24f76672842de4a1918e7d0f7 | 82c76c05fc8ca096f2744a7423d411561b25d9bd | /typed-racket-test/optimizer/tests/real-part-loop.rkt | 4bf2629101cdced25628de6b5c1e5b75046320ad | [
"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 | 1,128 | rkt | real-part-loop.rkt | #;#;
#<<END
TR opt: real-part-loop.rkt 3:1 (let loop ((v 0.0+1.0i)) (if (> (real-part v) 70000.2) 0 (loop (+ v 3.6)))) -- unboxed call site
TR opt: real-part-loop.rkt 3:13 v -- unboxed var -> table
TR opt: real-part-loop.rkt 3:15 0.0+1.0i -- unboxed literal
TR opt: real-part-loop.rkt 3:6 loop -- fun -> unboxed fun
TR opt: real-part-loop.rkt 3:6 loop -- unboxed let loop
TR opt: real-part-loop.rkt 4:20 v -- leave var unboxed
TR opt: real-part-loop.rkt 4:6 (> (real-part v) 70000.2) -- binary float comp
TR opt: real-part-loop.rkt 4:9 (real-part v) -- complex accessor elimination
TR opt: real-part-loop.rkt 6:12 (+ v 3.6) -- unboxed binary float complex
TR opt: real-part-loop.rkt 6:15 v -- leave var unboxed
TR opt: real-part-loop.rkt 6:17 3.6 -- float in complex ops
TR opt: real-part-loop.rkt 6:6 (loop (+ v 3.6)) -- call to fun with unboxed args
TR opt: real-part-loop.rkt 6:6 (loop (+ v 3.6)) -- unboxed call site
END
#<<END
0
END
#lang typed/racket/base
#:optimize
#reader typed-racket-test/optimizer/reset-port
(ann
(let loop ([v 0.0+1.0i])
(if (> (real-part v) 70000.2)
0
(loop (+ v 3.6))))
Integer)
| false |
92350b487bfb3255f9cebc457730ee8b63649928 | a148422eee91a5c6105427ef2c48c02bd4e3eaae | /site/stories/location-administrators/pta-sets-up-in-school-coding-classes.rkt | 49fa9f6dcee35f93d474e51ea6e69f5cd3ec47b6 | [] | no_license | thoughtstem/metapolis-stories | 05ddc38843904a05bb43eaccf4af566c5cc901ef | 3e4af8559c98096082e322fda75512274e0e4d8e | refs/heads/master | 2020-08-30T09:45:39.680415 | 2019-12-11T20:15:16 | 2019-12-11T20:15:16 | 218,338,179 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 926 | rkt | pta-sets-up-in-school-coding-classes.rkt | #lang at-exp metapolis-stories/lang/story
(define title "A PTA Sets Up In-School Coding Classes")
(define place places:lovelace-elementary)
(define characters (list characters:sylvia
characters:sandy))
(define time (unnamed-time
(moment 2021 3 25 14 00)
(moment 2021 3 25 15 00)))
(define links '())
@paras{
@heading{Outline...}
@ul{
@li{The parents at this school are really keen on more coding education for their kids. PTA has been discussing this for a while at their meetings.}
@li{Sylvia reflects on her previous conversations with Sandy, Program Manager at MetaCoders.}
@li{Recently, the PTA has fundraised enough to get MetaCoders in-school.}
@li{Sylvia and Sandy make final plans to start in-school classes in the Fall. Discuss: days, times, having teachers remain in 1 classroom while students rotate.}
}
}
| false |
14a8d8c3e4313a8bb08dc676a3ee1af33714c184 | 8b7986599eedd42030ef3782e4a2a9eba0596f4a | /biber/main.rkt | 2eca9ab76ee50e3faa8076024c5c2c0fe44ab122 | [] | no_license | lihebi/biber | 70ddf33ff98a73ef3fa274fe7265953200814c1c | 18de3b5af039f1e95872694bec6d0af0c3ddb9ca | refs/heads/master | 2020-05-03T19:33:43.491843 | 2020-04-25T17:40:00 | 2020-04-25T17:40:00 | 178,786,246 | 2 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,568 | rkt | main.rkt | #lang racket
(require "bibgen.rkt"
"bib-write.rkt")
;; tests
(module+ test
(parameterize ([BIBDIR "~/git/biber-dist/"])
;; AI
(gen-bib-and-write 'icml 2019)
(gen-bib-and-write 'naacl 2019)
(gen-bib-and-write 'aistats 2019)
(gen-bib-and-write 'cvpr 2019)
(gen-bib-and-write 'iclr 2019)
(gen-bib-and-write 'iclr 2020)
;; system
(for ([year (in-range 2015 2020)])
(gen-bib-and-write 'isca year))
(gen-bib-and-write 'iccad 2003)
(for ([year (in-range 2000 2019)])
(gen-bib-and-write 'iccad year))
(for ([year (in-range 2000 2020)])
(gen-bib-and-write 'dac year))
(for ([year (in-range 2000 2020)])
(gen-bib-and-write 'ispd year))
;; PL
(gen-bib-and-write 'popl 2018)
(gen-bib-and-write 'popl 2019)
(gen-bib-and-write 'pldi 2019)
(gen-bib-and-write 'icfp 2019)
(gen-bib-and-write 'icfp 2018)
;; arxiv
(for ([cat (list "cs.AI" "cs.CV" "cs.LG" "stat.ML"
;; "cs.PL" "cs.RO"
)]
#:when #t
[year (in-range 2017 2019)]
#:when #t
[month (in-range 1 13)])
(gen-bib-and-write-arxiv cat year month arxiv-bib))
(for ([cat (list "cs.AI" "cs.CV" "cs.LG" "stat.ML")]
#:when #t
[month (in-range 1 12)])
(gen-bib-and-write-arxiv cat 2019 month arxiv-bib))
(for ([m (in-range 1 13)])
(gen-bib-and-write-arxiv "cs.AI" 2018 m arxiv-bib))
(for ([m (in-range 1 7)])
(gen-bib-and-write-arxiv "cs.AI" 2019 m arxiv-bib))))
| false |
d04a564085f24448cd2fc1bf7bdccf82a1e5df7d | 268fdccab709a844eed3f2fc2eb67c565c2f3bc6 | /sentientmonkey/racket/day12.rkt | 185d7bde87c0c300f7a7b3a969124c35a73a0c60 | [] | no_license | SeaRbSg/advent_of_code | b2b51b000f6cb1dd969ebe6570daaf4295d1645b | d94efa1c837dcf205de51a72732a2fb48c95e6f0 | refs/heads/master | 2022-07-01T13:42:48.228023 | 2019-12-11T10:58:34 | 2019-12-11T10:58:34 | 75,670,777 | 1 | 0 | null | 2022-06-06T21:10:59 | 2016-12-05T22:09:51 | Ruby | UTF-8 | Racket | false | false | 1,127 | rkt | day12.rkt | #lang racket
(require rackunit)
(define-namespace-anchor anc)
(define ns (namespace-anchor->namespace anc))
(define-syntax-rule (while condition body ...)
(let loop ()
(when condition
body ...
(loop))))
(define cpu (vector 0 0 0 0))
(define pc 0)
(define (register-index register)
(case register
['a 0]
['b 1]
['c 2]
['d 3]))
(define (set-register register value)
(vector-set! cpu (register-index register) value))
(define (get-register register)
(vector-ref cpu (register-index register)))
(define (inc x)
(set-register x (add1 (get-register x))))
(define (dec x)
(set-register x (sub1 (get-register x))))
(define (cpy x y)
(set-register y x))
(define (jnz x y)
(when (not (zero? (get-register x)))
(set! pc (+ pc y))))
(define (run p)
(while (< pc (vector-length p))
(eval (vector-ref p pc) ns)
(set! pc (add1 pc))))
(define program
(vector
'(cpy 41 'a)
'(inc 'a)
'(inc 'a)
'(dec 'a)
'(jnz 'a 2)
'(dec 'a)))
(println program)
(run program)
(println cpu)
| true |
0e26a03d866557bddc2d186a87c669ed82004271 | 24338514b3f72c6e6994c953a3f3d840b060b441 | /cur-test/cur/tests/curnel/runtime.rkt | 45627ac0d25176b2f1c053b3d938d54be7866486 | [
"BSD-2-Clause"
] | permissive | graydon/cur | 4efcaec7648e2bf6d077e9f41cd2b8ce72fa9047 | 246c8e06e245e6e09bbc471c84d69a9654ac2b0e | refs/heads/master | 2020-04-24T20:49:55.940710 | 2018-10-03T23:06:33 | 2018-10-03T23:06:33 | 172,257,266 | 1 | 0 | BSD-2-Clause | 2019-02-23T19:53:23 | 2019-02-23T19:53:23 | null | UTF-8 | Racket | false | false | 7,827 | rkt | runtime.rkt | #lang racket/base
(require
chk
syntax/parse
cur/curnel/racket-impl/runtime
cur/curnel/racket-impl/runtime-utils
racket/function
(for-syntax
cur/curnel/racket-impl/stxutils
racket/base))
(provide (all-defined-out) (for-syntax (all-defined-out)))
(struct constant:Nat constant () #:transparent
; #:extra-constructor-name Nat
#:reflection-name 'Nat
#:property prop:parameter-count 0)
(define Nat ((curry constant:Nat)))
(define-for-syntax Nat
(constant-info
;; TODO PERF: When not a dependent type, can we avoid making it a function?
#`(#%plain-app cur-Type '0)
#f
0
(list) (list) (list) (list)
2
(list #'z #'s)
#f
#f))
(define Nat-dispatch (box #f))
(struct constant:z constant () #:transparent
; #:extra-constructor-name z
#:reflection-name 'z
#:property prop:parameter-count 0
#:property prop:dispatch Nat-dispatch
#:property prop:recursive-index-ls null)
(define z ((curry constant:z)))
(define-for-syntax z
(constant-info
#`Nat
#f
0 (list) (list) (list) (list)
2 (list #'z #'s)
0
(list)))
(struct constant:s constant (pred) #:transparent
; #:extra-constructor-name s
#:reflection-name 's
#:property prop:parameter-count 0
#:property prop:dispatch Nat-dispatch
#:property prop:recursive-index-ls (list 0))
(define s ((curry constant:s)))
(define-for-syntax s
(constant-info
#`(#%plain-app cur-Π Nat (#%plain-lambda (x) Nat))
#f
0
(list) (list) (list #'n) (list #'Nat)
2 (list #'z #'s)
1 (list 0)))
(set-box! Nat-dispatch (build-dispatch (list constant:z? constant:s?)))
(require (for-syntax racket/syntax))
(define-syntax (define-from-delta stx)
(syntax-case stx ()
[(_ arg)
(syntax-local-eval #'arg)]))
(define-for-syntax delta:two #'(#%plain-app cur-apply s (#%plain-app cur-apply s z)))
(define two (define-from-delta delta:two))
(define-for-syntax two
(identifier-info #`Nat delta:two))
;; TODO PERF: Could we remove λ procedure indirect for certain defines? The type is given
;; separately, so we may not need the annotations we use the λ indirect for.
;; However, the delta: definition has to remain, so it would only be the run-time definition that is
;; optimized, resulting in code duplication. Perhaps should be opt-in
(define-for-syntax delta:plus
#`(#%plain-app cur-λ Nat
(#%plain-lambda (n1)
(#%plain-app cur-λ Nat
(#%plain-lambda (n2)
(#%plain-app cur-elim n1 (#%plain-app cur-λ Nat
(#%plain-lambda (n) Nat))
n2
(#%plain-app cur-λ Nat (#%plain-lambda (n1-1)
(#%plain-app cur-λ Nat
(#%plain-lambda
(ih)
(#%plain-app
cur-apply
s
ih)))))))))))
(define plus (define-from-delta delta:plus))
(define-for-syntax plus
(identifier-info
#`(#%plain-app cur-Π Nat (#%plain-lambda (x) (#%plain-app cur-Π Nat
(#%plain-lambda (y)
Nat))))
delta:plus))
;; TODO PERF: When the constant has no fields, optimize into a singleton structure. this can be
;; detected at transformer time using struct-info, by a null field-accessor list
;; TODO PERF: When we make singletons, should be possible to optimize equality checks into eq?
;; instead of equal?.
;; "A structure type can override the default equal? definition through the gen:equal+hash generic interface."
(chk
#:t (cur-Type 0)
#:t (cur-Type 1)
#:t (cur-λ (Type 1) (#%plain-lambda (x) x))
#:t (cur-Π (Type 1) (#%plain-lambda (x) (cur-Type 1)))
#:= (#%plain-app (cur-λ (cur-Type 1) (#%plain-lambda (x) x)) (cur-Type 0)) (cur-Type 0)
#:? constant:z? z
#:? constant:s? (s z)
#:= (cur-elim z void z (lambda (p) (lambda (ih) p))) z
#:! #:= (cur-elim (cur-apply s (cur-apply s z)) void z (lambda (p) (lambda (ih) p))) z
#:= (cur-elim (cur-apply s (cur-apply s z)) void z (lambda (p) (lambda (ih) p))) (cur-apply s z)
#:= ((plus (s (s z))) (s (s z))) (s (s (s (s z)))))
(begin-for-syntax
(require
chk
; NB: For testing renaming
(for-template (rename-in cur/curnel/racket-impl/runtime [cur-Type meow] [cur-Type Type])))
(define-values (universe? id? lambda? pi? app? elim? term?)
(apply
values
(for/list ([f (list cur-runtime-universe? cur-runtime-identifier? cur-runtime-lambda?
cur-runtime-pi? cur-runtime-app? cur-runtime-elim?
cur-runtime-term?)])
(compose f local-expand-expr))))
(chk
#:? universe? #'(cur-Type 0)
#:? universe? #'(meow 0)
#:? universe? #'(Type 0)
#:? term? #'(cur-Type 0)
#:! #:? identifier? #'(cur-Type 0)
; #:! #:? constant? #'(cur-Type 0)
#:! #:? lambda? #'(cur-Type 0)
#:! #:? pi? #'(cur-Type 0)
#:! #:? app? #'(cur-Type 0)
#:! #:? elim? #'(cur-Type 0)
#:? identifier? #'two
#:? term? #'two
; #:! #:? constant? #'two
#:! #:? universe? #'two
#:! #:? pi? #'two
#:! #:? lambda? #'two
#:! #:? app? #'two
#:! #:? elim? #'two
#:? pi? #'(cur-Π (cur-Type 0) (lambda (x) x))
#:? term? #'(cur-Π (cur-Type 0) (lambda (x) x))
#:! #:? lambda? #'(cur-Π (cur-Type 0) (lambda (x) x))
#:! #:? app? #'(cur-Π (cur-Type 0) (lambda (x) x))
#:! #:? elim? #'(cur-Π (cur-Type 0) (lambda (x) x))
#:! #:? universe? #'(cur-Π (cur-Type 0) (lambda (x) x))
#:! #:? identifier? #'(cur-Π (cur-Type 0) (lambda (x) x))
; #:! #:? constant? #'(cur-Π (cur-Type 0) (lambda (x) x))
; #:? constant? #'(z)
; #:! #:? identifier? #'(z)
; #:! #:? app? #'(z)
; #:! #:? universe? #'(z)
; #:? constant? #'(s (z))
; #:! #:? app? #'(s (z))
#:? app? #'(cur-apply s z)
#:? lambda? #'(cur-λ (Type 0) (lambda (x) x))
#:! #:? pi? #'(cur-λ (Type 0) (lambda (x) x))
#:! #:? app? #'(cur-λ (Type 0) (lambda (x) x))
#:? app? #'(cur-apply plus z)
#:? term? #'(cur-apply plus z)
; #:! #:? constant? #'(cur-apply plus (z))
#:! #:? elim? #'(cur-apply plus z)
#:! #:? identifier? #'(cur-apply plus z)
#:! #:? universe? #'(cur-apply plus z)
#:! #:? lambda? #'(cur-apply plus z)
#:! #:? pi? #'(cur-apply plus z)
#:? app? #'(cur-apply (cur-apply plus z) z)
#:? term? #'(cur-apply (cur-apply plus z) z)
#:? elim? #'(cur-elim z void z (s z))
#:? term? #'(cur-elim z void z (s z))
#:! #:? app? #'(cur-elim z void z (s z))
; #:! #:? constant? #'(cur-elim (z) void (z) (s (z)))
#:! #:? lambda? #'(cur-elim z void z (s z))
#:! #:? pi? #'(cur-elim z void z (s z))))
| true |
4ff21e08a959127fd76a8e26bdc767a91d921a75 | 62d1d3c4bb5ef001a5653e49f70d42cde941a423 | /practice/recur/rcfae.rkt | ed88a29a8b7a472eece38524d64931b497804773 | [] | no_license | zshen0x/EECS-321 | d2923f4576c25b6e1fc3ab86b9a6703c63876dd3 | e4832951effa8e3c35ffe1eca105d5d89f43beae | refs/heads/master | 2021-05-30T12:00:39.351290 | 2015-12-12T03:18:05 | 2015-12-12T03:18:05 | 46,182,331 | 1 | 7 | null | null | null | null | UTF-8 | Racket | false | false | 4,620 | rkt | rcfae.rkt | #lang plai
;; recursion with mutation
;(let ([fac 10])
; (begin
; (set! fac
; (λ (n)
; (if (zero? n)
; 1
; (* n (fac (sub1 n))))))
; (fac 10)))
; BNF grammer
;<RCFAE> ::= <num>
;| {+ <RCFAE> <RCFAE>}
;| {- <RCFAE> <RCFAE>}
;| <id>
;| {fun {<id>} <RCFAE>}
;| {<RCFAE> <RCFAE>}
;| {if0 <RCFAE> <RCFAE> <RCFAE>}
;| {rec {<id> <RCFAE>} <RCFAE>}
;; define data structure
(define-type RCFAE
[num (n number?)]
[add (lhs RCFAE?) (rhs RCFAE?)]
[sub (lhs RCFAE?) (rhs RCFAE?)]
[id (name symbol?)]
[fun (param symbol?) (body RCFAE?)]
[app (fun-expr RCFAE?) (arg-expr RCFAE?)]
[if0 (test-expr RCFAE?) (then-expr RCFAE?) (else-expr RCFAE?)]
[rec (name symbol?) (named-expr RCFAE?) (body RCFAE?)])
(define-type DefrdSub
[mtSub]
[aSub (id symbol?)
(value RCFAE-Value?)
(rest DefrdSub?)]
[aRecSub (id symbol?)
(value-box (box/c RCFAE-Value?))
(rest DefrdSub?)])
(define-type RCFAE-Value
[numV (n number?)]
[closureV (param symbol?)
(body RCFAE?)
(ds DefrdSub?)])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; parser s-expr -> internal ast
(define/contract (parse s-expr)
(-> any/c RCFAE?)
(match s-expr
[(? number?) (num s-expr)]
[(? symbol?) (id s-expr)]
[`{+ ,lhs ,rhs} (add (parse lhs) (parse rhs))]
[`{- ,lhs ,rhs} (sub (parse lhs) (parse rhs))]
[`{with {,id ,e1} ,e2} (parse `{{fun {,id} ,e2} ,e1})]
[`{if0 ,test ,then-expr ,else-expr} (if0 (parse test)
(parse then-expr)
(parse else-expr))]
[`{rec {,id ,e1} ,e2} (rec id (parse e1) (parse e2))]
[`{fun {,(? symbol? param)} ,body} (fun param (parse body))]
[`{fun {,(? symbol? params) ..2} ,body} (parse `{fun {,(first params)}
{fun ,(rest params) ,body}})]
[`{,fun-expr ,arg-expr} (app (parse fun-expr) (parse arg-expr))]
[`{,fun-expr ,arg-exprs ..2} (parse (append `{{,fun-expr ,(first arg-exprs)}}
(rest arg-exprs)))]
[_ (error "bad syntax when parsing:\n" s-expr)]))
(define/contract (numV-op op)
(-> (-> number? number? number?)
(-> RCFAE-Value? RCFAE-Value? numV?))
(λ (lhs rhs)
(if (and (numV? lhs) (numV? rhs))
(numV (op (numV-n lhs) (numV-n rhs)))
(error 'add-or-sub "numeric operation expected number"))))
(define numV+ (numV-op +))
(define numV- (numV-op -))
;; interpreter
(define/contract (lookup-ds name ds)
(-> symbol? DefrdSub? RCFAE-Value?)
(type-case DefrdSub ds
[mtSub () (error "free identifier:\n" name)]
[aSub (id val rest) (if (symbol=? id name)
val
(lookup-ds name rest))]
[aRecSub (id val-box rest) (if (symbol=? id name)
(unbox val-box)
(lookup-ds name rest))]))
(define/contract (interp a-rcfae ds)
(-> RCFAE? DefrdSub? RCFAE-Value?)
(type-case RCFAE a-rcfae
[num (n) (numV n)]
[add (l r) (numV+ (interp l ds) (interp r ds))]
[sub (l r) (numV- (interp l ds) (interp r ds))]
[id (name) (lookup-ds name ds)]
[fun (param body) (closureV param body ds)]
[app (fun-expr arg-expr)
(let ([appV (interp fun-expr ds)])
(let ([argV (interp arg-expr ds)])
(type-case RCFAE-Value appV
[numV (n) (error 'app "given: ~a\napplication expected procedure" n)]
[closureV (param body ds)
(interp body
(aSub param argV ds))])))]
[if0 (test then else) (if (equal? (interp test ds)
(numV 0))
(interp then ds)
(interp else ds))]
[rec (bound-id named-expr body-expr)
(let ([value-houlder (box 'free-identifier)])
(let ([new-ds (aRecSub bound-id value-houlder ds)])
(begin (set-box! value-houlder (interp named-expr new-ds))
(interp body-expr new-ds))))]))
(define/contract (interp-expr a-rcfae)
(-> RCFAE? (or/c number? (symbols 'procedure)))
(type-case RCFAE-Value (interp a-rcfae (mtSub))
[numV (n) n]
[closureV (param body ds) 'procedure]))
(interp-expr (parse '{rec {sum {fun {n}
{if0 n
0
{+ n {sum {- n 1}}}}}}
{sum 0}}))
| false |
11ad34cd13ff4b340a56027030e7fb73180d2ff3 | 6bfcfd4f7bde69f34b03dc2e7448d8282ab51d13 | /src/main.rkt | dd3520252cd4b95e32772bf625e1fea83cf1eae5 | [
"MIT"
] | permissive | walkeri/Aristarchus | 1fd9de7a303d8dee0e8bee8a92d1a057d7299ad3 | 4105e7654ffe2552a776943836518ab6d784837d | refs/heads/master | 2021-01-25T10:55:52.019162 | 2018-08-31T20:16:37 | 2018-08-31T20:16:37 | 123,375,745 | 7 | 1 | null | 2018-03-02T04:27:11 | 2018-03-01T03:16:41 | null | UTF-8 | Racket | false | false | 2,105 | rkt | main.rkt | #lang racket
(require (for-syntax syntax/parse)
htdp/matrix
"built-in-formulas.rkt")
(provide
#%module-begin
#%datum
#%app
#%top-interaction
quote
list
(all-from-out "built-in-formulas.rkt")
;; Connection -> VOID
;; outputs all 5 of the lagrange points of a connection
;; lagrange
;; ---------------------------- Conversions ------------------------------------
;; Number -> Number
;; Converts seconds to days
seconds->days
;; Number -> Number
;; Converts days to seconds
days->seconds
;; Number -> Number
;; Converts hours to seconds
hours->seconds
;; Number -> Number
;; Converts seconds to hours
seconds->hours
;; Number -> Number
;; Converts minutes to seconds
minutes->seconds
;; Number -> Number
;; Converts seconds to minutes
seconds->minutes
;; Number -> Number
;; Converts kilometers to meters
kilometers->meters
;; Number -> Number
;; Converts meters to kilometers
meters->kilometers
;; Number -> Number
;; Converts meters to centimeters
meters->centimeters
;; Number -> Number
;; Converts centimeters to meters
centimeters->meters
)
#;(define (lagrange connect)
(make-matrix 5 5
`(L1: x: ,(posn-x (L1 connect)) y: ,(posn-y (L1 connect))
L2: x: ,(posn-x (L2 connect)) y: ,(posn-y (L2 connect))
L3: x: ,(posn-x (L3 connect)) y: ,(posn-y (L3 connect))
L4: x: ,(posn-x (L4 connect)) y: ,(posn-y (L4 connect))
L5: x: ,(posn-x (L5 connect)) y: ,(posn-y (L5 connect)))))
;;-------------------------------- Conversions ----------------------------------
(define (seconds->days n)
(/ (/ (/ n 60) 60) 24))
(define (days->seconds n)
(* (* (* n 24) 60) 60))
(define (hours->seconds n)
(* (* n 60) 60))
(define (seconds->hours n)
(/ (/ n 60) 60))
(define (minutes->seconds n)
(* n 60))
(define (seconds->minutes n)
(/ n 60))
(define (kilometers->meters n)
(* 1000 n))
(define (meters->kilometers n)
(/ n 1000))
(define (meters->centimeters n)
(* 100 n))
(define (centimeters->meters n)
(/ n 100))
| false |
a465a97ee8430f60a5bccce5fc497a10fe85723c | 86ca36c87143c4362192b5e0d120c71fa65d214c | /constructor-style-print/racket/init.rkt | 275c1834b47d2cabce6050a1e6c116b05fee6ae2 | [
"MIT"
] | permissive | AlexKnauth/quote-bad | 90da03b90fb8264ccdef80df1b8f80d4bdc8d9b9 | 251c2ed6f6cfd24b733ea7e0d41ff44c63cb3b2d | refs/heads/master | 2022-01-17T13:12:07.197442 | 2022-01-07T14:21:19 | 2022-01-07T14:21:19 | 59,908,740 | 8 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 136 | rkt | init.rkt | #lang racket/base
(require racket/init constructor-style-print/lang/runtime-config)
(provide (all-from-out racket/init))
(configure #f)
| false |
04624e1ae51c853e46eed19885bd3a2c4c6a3703 | 964bb56e1e21091cf07a49b51394d02fcdb018f7 | /ch03/3.4/3_39.rkt | e43fb88d3b0a6cd5c1fd7d43e12b04f81ab3702a | [] | no_license | halee99/SICP | fa7758f96c6363b3b262e3b695f11f1c1072c628 | de282c9f595b3813d3f6b162e560b0a996150bd2 | refs/heads/master | 2020-04-06T14:52:39.639013 | 2019-10-10T09:14:56 | 2019-10-10T09:14:56 | 157,557,554 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 459 | rkt | 3_39.rkt | ; 未实现 make-serializer parallel-execute 无法运行
(define x 10)
(define s (make-serializer))
(parallel-execute (lambda () (set! x ((s (lambda () (* x x))))))
(s (lambda () (set! x (+ x 1)))))
; 产生3种结果
; 1 (set! x (+ 10 1)) => x = 11 => (set! x (* 11 11)) => x = 121
; 2 (set! x ?)[打断] => (set! x (+ 10 1)) => x = 11 => (set! x (* 11 11)) => x = 121
; 3 (set! x (* 10 10)) => x = 100 => (set! x (+ 100 1)) => x = 101
| false |
cd0cd25290bca3071fcac0bee97660f03aa4fc4f | 5782922f05d284501e109c3bd2a2e4b1627041b9 | /codes/racket/racket-book-master/docs/04-advanced-racket/index.scrbl | d9efb956e2358c869c4d79824a9ad55d2c28ffec | [] | no_license | R4mble/Notes | 428e660369ac6dc01aadc355bf31257ce83a47cb | 5bec0504d7ee3e5ef7bffbc80d50cdddfda607e6 | refs/heads/master | 2022-12-11T12:31:00.955534 | 2019-09-23T08:46:01 | 2019-09-23T08:46:01 | 192,352,520 | 0 | 0 | null | 2022-12-11T03:48:32 | 2019-06-17T13:28:24 | JavaScript | UTF-8 | Racket | false | false | 414 | scrbl | index.scrbl | #lang scribble/doc
@(require (for-label racket)
scribble/manual
"../../util/common.rkt")
@title[#:tag "advanced-racket"]{Racket语言进阶}
@table-of-contents[]
@; -------------------------------------------------
@include-section["01-concepts.scrbl"]
@include-section["02-functional-programming.scrbl"]
@include-section["03-debug.scrbl"]
@include-section["04-look-into-executable.scrbl"]
| false |
1a3690baa1aa9cd37ab1359de764809d117322bd | 50508fbb3a659c1168cb61f06a38a27a1745de15 | /macrotypes-example/macrotypes/examples/mlish+adhoc.rkt | cf684e547b9f3b46839130f2e8cf3654ea74872a | [
"BSD-2-Clause"
] | permissive | phlummox/macrotypes | e76a8a4bfe94a2862de965a4fefd03cae7f2559f | ea3bf603290fd9d769f4f95e87efe817430bed7b | refs/heads/master | 2022-12-30T17:59:15.489797 | 2020-08-11T16:03:02 | 2020-08-11T16:03:02 | 307,035,363 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 79,053 | rkt | mlish+adhoc.rkt | #lang s-exp macrotypes/typecheck
(require (only-in macrotypes/typecheck
[define-typed-syntax def-typed-stx/no-provide]))
(require (postfix-in - racket/fixnum)
(postfix-in - racket/flonum)
(postfix-in - racket/match)
(for-syntax racket/set racket/string)
(for-meta 2 racket/base syntax/parse racket/syntax))
(extends
"ext-stlc.rkt"
#:except → define begin #%app λ #%datum
+ - * void = zero? sub1 add1 not let let* and
#:rename [~→ ~ext-stlc:→])
(require (rename-in (only-in "sysf.rkt" inst) [inst sysf:inst]))
(provide inst)
(require (only-in "ext-stlc.rkt" →?))
(require (only-in "sysf.rkt" ~∀ ∀ ∀? mk-∀- Λ))
(reuse × tup proj define-type-alias #:from "stlc+rec-iso.rkt")
(require (only-in "stlc+rec-iso.rkt" ~× ×?)) ; using current-type=? from here
(provide (rename-out [ext-stlc:and and] [ext-stlc:#%datum #%datum]))
(reuse member length reverse list-ref cons nil isnil head tail list #:from "stlc+cons.rkt")
(require (prefix-in stlc+cons: (only-in "stlc+cons.rkt" list cons nil)))
(require (only-in "stlc+cons.rkt" ~List List? List mk-List-))
(reuse ref deref := Ref #:from "stlc+box.rkt")
(require (rename-in (only-in "stlc+reco+var.rkt" tup proj × mk-×-)
[tup rec] [proj get] [× ××]))
(provide rec get ××)
;; for pattern matching
(require (prefix-in stlc+cons: (only-in "stlc+cons.rkt" list)))
(require (prefix-in stlc+tup: (only-in "stlc+tup.rkt" tup)))
;; ML-like language + ad-hoc polymorphism
;; - top level recursive functions
;; - user-definable algebraic datatypes
;; - pattern matching
;; - (local) type inference
;;
;; - type classes
(provide → →/test => =>/test
List Channel Thread Vector Sequence Hash String-Port Input-Port Regexp
define-type define-types define-typeclass define-instance
match2)
(define-type-constructor => #:arity > 0)
;; providing version of define-typed-syntax
(define-syntax (define-typed-syntax stx)
(syntax-parse stx
[(_ name:id #:export-as out-name:id . rst)
#'(begin-
(provide- (rename-out [name out-name]))
(def-typed-stx/no-provide name . rst))]
[(_ name:id . rst)
#'(define-typed-syntax name #:export-as name . rst)]))
;; type class helper fns
(begin-for-syntax
(define (mk-app-err-msg stx #:expected [expected-τs #'()]
#:given [given-τs #'()]
#:note [note ""]
#:name [name #f]
#:action [other #f])
(syntax-parse stx
#;[(app . rst)
#:when (not (equal? '#%app (syntax->datum #'app)))
(mk-app-err-msg (syntax/loc stx (#%app app . rst))
#:expected expected-τs
#:given given-τs
#:note note
#:name name)]
[(app e_fn e_arg ...)
(define fn-name
(if name name
(format "function ~a"
(syntax->datum (or (get-orig #'e_fn) #'e_fn)))))
(define action (if other other "applying"))
(string-append
(format "~a (~a:~a):\nType error "
(syntax-source stx) (syntax-line stx) (syntax-column stx))
action " "
fn-name ". " note "\n"
(format " Expected: ~a argument(s) with type(s): " (stx-length expected-τs))
(types->str expected-τs) "\n"
" Given:\n"
(string-join
(map (λ (e t) (format " ~a : ~a" e t)) ; indent each line
(syntax->datum #'(e_arg ...))
(if (stx-length=? #'(e_arg ...) given-τs)
(stx-map type->str given-τs)
(stx-map (lambda (e) "?") #'(e_arg ...))))
"\n")
"\n")]))
(define (type-hash-code tys) ; tys should be fully expanded
(equal-hash-code (syntax->datum (if (syntax? tys) tys #`#,tys))))
(define (mangle o tys)
(format-id o "~a~a" o (type-hash-code tys)))
;; pattern expander for type class
(define-syntax ~TC
(pattern-expander
(syntax-parser
[(_ [generic-op ty-concrete-op] (~and ooo (~literal ...)))
#'(_ (_ (_ generic-op) ty-concrete-op) ooo)]
[(_ . ops+tys)
#:with expanded (generate-temporary)
#'(~and expanded
(~parse (_ (_ (_ gen-op) ty-op) (... ...))
#'expanded)
(~parse ops+tys #'((gen-op ty-op) (... ...))))])))
(define-syntax ~TC-base
(pattern-expander
(syntax-parser
[(_ . pat)
#:with expanded (generate-temporary)
#'(~and expanded
(~parse ((~TC . pat) . _) (flatten-TC #'expanded)))])))
(define-syntax ~TCs
(pattern-expander
(syntax-parser
;; pat should be of shape ([op ty] ...)
[(_ pat (~and ooo (~literal ...)))
#:with expanded (generate-temporary)
;; (stx-map (compose remove-dups flatten-TC) #'expanded)
;; produces [List [List [List op+ty]]]
;; - inner [List op+ty] is from the def of a TC
;; - second List is from the flattened subclass TCs
;; - outer List is bc this pattern matces multiple TCs
;; This pattern expander collapses the inner two Lists
#'(~and expanded
(~parse (((~TC [op ty] (... ...)) (... ...)) ooo)
(stx-map (compose remove-dups flatten-TC) #'expanded))
(~parse (pat ooo) #'(([op ty] (... ...) (... ...)) ooo)))])))
(define (flatten-TC TC)
(syntax-parse TC
[(~=> sub-TC ... base-TC)
(cons #'base-TC (stx-appendmap flatten-TC #'(sub-TC ...)))]))
(define (remove-dups TCs)
(syntax-parse TCs
[() #'()]
[(TC . rst)
(cons #'TC (stx-filter (lambda (s) (not (typecheck? s #'TC))) (remove-dups #'rst)))])))
;; type inference constraint solving
(begin-for-syntax
;; matching possibly polymorphic types
(define-syntax ~?∀
(pattern-expander
(lambda (stx)
(syntax-case stx ()
[(?∀ vars-pat body-pat)
#'(~or (~∀ vars-pat body-pat)
(~and (~not (~∀ _ _))
(~parse vars-pat #'())
body-pat))]))))
;; type inference constraint solving
(define (compute-constraint τ1-τ2)
(syntax-parse τ1-τ2
[(X:id τ) #'((X τ))]
[((~Any tycons1 τ1 ...) (~Any tycons2 τ2 ...))
#:when (typecheck? #'tycons1 #'tycons2)
(compute-constraints #'((τ1 τ2) ...))]
; should only be monomorphic?
[((~∀ () (~ext-stlc:→ τ1 ...)) (~∀ () (~ext-stlc:→ τ2 ...)))
(compute-constraints #'((τ1 τ2) ...))]
[_ #'()]))
(define (compute-constraints τs)
(stx-appendmap compute-constraint τs))
(define (solve-constraint x-τ)
(syntax-parse x-τ
[(X:id τ) #'((X τ))]
[_ #'()]))
(define (solve-constraints cs)
(stx-appendmap compute-constraint cs))
(define (lookup x substs)
(syntax-parse substs
[((y:id τ) . rst)
#:when (free-identifier=? #'y x)
#'τ]
[(_ . rst) (lookup x #'rst)]
[() #f]))
;; find-unsolved-Xs : (Stx-Listof Id) Constraints -> (Listof Id)
;; finds the free Xs that aren't constrained by cs
(define (find-unsolved-Xs Xs cs)
(for/list ([X (in-list (stx->list Xs))]
#:when (not (lookup X cs)))
X))
;; lookup-Xs/keep-unsolved : (Stx-Listof Id) Constraints -> (Listof Type-Stx)
;; looks up each X in the constraints, returning the X if it's unconstrained
(define (lookup-Xs/keep-unsolved Xs cs)
(for/list ([X (in-list (stx->list Xs))])
(or (lookup X cs) X)))
;; solve for Xs by unifying quantified fn type with the concrete types of stx's args
;; stx = the application stx = (#%app e_fn e_arg ...)
;; tyXs = input and output types from fn type
;; ie (typeof e_fn) = (-> . tyXs)
;; It infers the types of arguments from left-to-right,
;; and it short circuits if it's done early.
;; It returns list of 3 values if successful, else throws a type error
;; - a list of the arguments that it expanded
;; - a list of the the un-constrained type variables
;; - the constraints for substituting the types
(define (solve Xs tyXs stx)
(syntax-parse tyXs
[(τ_inX ... τ_outX)
;; generate initial constraints with expected type and τ_outX
#:with expected-ty (get-expected-type stx)
(define initial-cs
(if (syntax-e #'expected-ty)
(compute-constraint (list #'τ_outX ((current-type-eval) #'expected-ty)))
#'()))
(syntax-parse stx
[(_ e_fn . args)
(define-values (as- cs)
(for/fold ([as- null] [cs initial-cs])
([a (in-list (syntax->list #'args))]
[tyXin (in-list (syntax->list #'(τ_inX ...)))]
#:break (null? (find-unsolved-Xs Xs cs)))
(define/with-syntax [a- ty_a] (infer+erase a))
(values
(cons #'a- as-)
(stx-append cs (compute-constraint (list tyXin #'ty_a))))))
(list (reverse as-) (find-unsolved-Xs Xs cs) cs)])]))
(define (raise-app-poly-infer-error stx expected-tys given-tys e_fn)
(type-error #:src stx
#:msg (mk-app-err-msg stx #:expected expected-tys #:given given-tys
#:note (format "Could not infer instantiation of polymorphic function ~a."
(syntax->datum (get-orig e_fn))))))
;; instantiate polymorphic types
;; inst-type : (Listof Type) (Listof Id) Type -> Type
;; Instantiates ty with the tys-solved substituted for the Xs, where the ith
;; identifier in Xs is associated with the ith type in tys-solved
(define (inst-type tys-solved Xs ty)
(substs tys-solved Xs ty))
;; inst-type/cs : (Stx-Listof Id) Constraints Type-Stx -> Type-Stx
;; Instantiates ty, substituting each identifier in Xs with its mapping in cs.
(define (inst-type/cs Xs cs ty)
(define tys-solved (lookup-Xs/keep-unsolved Xs cs))
(inst-type tys-solved Xs ty))
;; inst-types/cs : (Stx-Listof Id) Constraints (Stx-Listof Type-Stx) -> (Listof Type-Stx)
;; the plural version of inst-type/cs
(define (inst-types/cs Xs cs tys)
(stx-map (lambda (t) (inst-type/cs Xs cs t)) tys))
;; compute unbound tyvars in one unexpanded type ty
(define (compute-tyvar1 ty)
(syntax-parse ty
[X:id #'(X)]
[() #'()]
[(C t ...) (stx-appendmap compute-tyvar1 #'(t ...))]))
;; computes unbound ids in (unexpanded) tys, to be used as tyvars
(define (compute-tyvars tys)
(define Xs (stx-appendmap compute-tyvar1 tys))
(filter
(lambda (X)
(with-handlers
([exn:fail:syntax:unbound? (lambda (e) #t)]
[exn:fail:type:infer? (lambda (e) #t)])
(let ([X+ ((current-type-eval) X)])
(not (type? X+)))))
(stx-remove-dups Xs))))
;; define --------------------------------------------------
;; for function defs, define infers type variables
;; - since the order of the inferred type variables depends on expansion order,
;; which is not known to programmers, to make the result slightly more
;; intuitive, we arbitrarily sort the inferred tyvars lexicographically
(define-typed-syntax define/tc #:export-as define
[(_ x:id e)
#:with (e- τ) (infer+erase #'e)
#:with x- (generate-temporary)
#'(begin-
(define-typed-variable-rename x ≫ x- : τ)
(define- x- e-))]
; explicit "forall"
[(_ Ys (f:id [x:id (~datum :) τ] ... (~or (~datum ->) (~datum →)) τ_out)
e_body ... e)
#:when (brace? #'Ys)
;; TODO; remove this code duplication
#:with f- (add-orig (generate-temporary #'f) #'f)
#:with e_ann (syntax/loc #'e (add-expected e τ_out))
#:with (τ+orig ...) (stx-map (λ (t) (add-orig t t)) #'(τ ... τ_out))
;; TODO: check that specified return type is correct
;; - currently cannot do it here; to do the check here, need all types of
;; top-lvl fns, since they can call each other
#:with (~and ty_fn_expected (~∀ _ (~ext-stlc:→ _ ... out_expected)))
((current-type-eval) #'(∀ Ys (ext-stlc:→ τ+orig ...)))
#`(begin-
(define-typed-variable-rename f ≫ f- : ty_fn_expected)
(define- f-
(Λ Ys (ext-stlc:λ ([x : τ] ...) (ext-stlc:begin e_body ... e_ann)))))]
;; alternate type sig syntax, after parameter names
[(_ (f:id x:id ...) (~datum :) ty ... (~or (~datum ->) (~datum →)) ty_out . b)
(syntax/loc stx (define/tc (f [x : ty] ... -> ty_out) . b))]
[(_ (f:id [x:id (~datum :) τ] ... ; no TC
(~or (~datum ->) (~datum →)) τ_out)
e_body ... e)
#:with (~and Ys (Y ...)) (compute-tyvars #'(τ ... τ_out))
#:with f- (add-orig (generate-temporary #'f) #'f)
#:with e_ann (syntax/loc #'e (add-expected e τ_out)) ; must be macro bc t_out may have unbound tvs
#:with (τ+orig ...) (stx-map (λ (t) (add-orig t t)) #'(τ ... τ_out))
;; TODO: check that specified return type is correct
;; - currently cannot do it here; to do the check here, need all types of
;; top-lvl fns, since they can call each other
#:with ty_fn_expected
(set-stx-prop/preserved
((current-type-eval) #'(∀ Ys (ext-stlc:→ τ+orig ...)))
'orig
(list #'(→ τ+orig ...)))
#`(begin-
(define-typed-variable-rename f ≫ f- : ty_fn_expected)
(define- f-
(Λ Ys (ext-stlc:λ ([x : τ] ...) (ext-stlc:begin e_body ... e_ann)))))]
[(_ (f:id [x:id (~datum :) τ] ...
(~seq #:where TC ...)
(~or (~datum ->) (~datum →)) τ_out)
e_body ... e)
#:with (~and Ys (Y ...)) (compute-tyvars #'(τ ... τ_out))
#:with f- (add-orig (generate-temporary #'f) #'f)
#:with e_ann (syntax/loc #'e (add-expected e τ_out)) ; must be macro bc t_out may have unbound tvs
#:with (τ+orig ...) (stx-map (λ (t) (add-orig t t)) #'(τ ... τ_out))
;; TODO: check that specified return type is correct
;; - currently cannot do it here; to do the check here, need all types of
;; top-lvl fns, since they can call each other
#:with (~and ty_fn_expected (~∀ _ (~=> _ ... (~ext-stlc:→ _ ... out_expected))))
(syntax-property
((current-type-eval) #'(∀ Ys (=> TC ... (ext-stlc:→ τ+orig ...))))
'orig
(list #'(→ τ+orig ...)))
#`(begin-
(define-typed-variable-rename f ≫ f- : ty_fn_expected)
#,(quasisyntax/loc stx
(define- f-
;(Λ Ys (ext-stlc:λ ([x : τ] ...) (ext-stlc:begin e_body ... e_ann)))))])
(liftedλ {Y ...} ([x : τ] ... #:where TC ...)
#,(syntax/loc #'e_ann (ext-stlc:begin e_body ... e_ann))))))])
;; define-type -----------------------------------------------
(define-for-syntax (make-type-constructor-transformer
name ; Name of type constructor we're defining
internal-name ; Identifier used for internal rep of type
op ; numeric operator to compare expected arg count
n ; Expected arity, relative to op
)
(define/syntax-parse τ- internal-name)
(syntax-parser
[(_ . args)
#:fail-unless (op (stx-length #'args) n)
(format
"wrong number of arguments, expected ~a ~a"
(object-name op) n)
#:with (arg- ...) (expands/stop #'args #:stop-list? #f)
;; args are validated on the next line rather than above
;; to ensure enough stx-parse progress for proper err msg,
;; ie, "invalid type" instead of "improper tycon usage"
#:with (~! _:type ...) #'(arg- ...)
(add-orig (mk-type (syntax/loc this-syntax (#%plain-app- τ- arg- ...))) this-syntax)]
[_ ;; else fail with err msg
(type-error #:src this-syntax
#:msg
(string-append
"Improper usage of type constructor ~a: ~a, expected ~a ~a arguments")
#`#,name this-syntax #`#,(object-name op) #`#,n)]))
(begin-for-syntax
(define-syntax-class constructor
(pattern
;; constructors must have the form (Cons τ ...)
;; but the first ~or clause accepts 0-arg constructors as ids;
;; the ~and is a workaround to bind the duplicate Cons ids (see Ryan's email)
(~and C (~or
; Nullary constructor, without parens. Like `Nil`.
; Ensure fld, τ are bound though empty.
(~and IdCons:id
(~parse (Cons [fld (~datum :) τ] ...) #'(IdCons)))
; With named fields
(Cons [fld (~datum :) τ] ...)
; Fields not named; generate internal names
(~and (Cons τ ...)
(~parse (fld ...) (generate-temporaries #'(τ ...)))))))))
;; defines a set of mutually recursive datatypes
(define-syntax (define-types stx)
(syntax-parse stx
[(_ [(Name:id X:id ...)
c:constructor ...]
...)
;; validate tys
#:with ((ty_flat ...) ...) (stx-map (λ (tss) (stx-flatten tss)) #'(((c.τ ...) ...) ...))
#:with ((_ _ (_ _ (_ _ (_ _ ty+ ...)))) ...)
(stx-map expand/df
#`((lambda (X ...)
(let-syntax
([X (make-rename-transformer (mk-type #'X))] ...
; Temporary binding of the type we are now defining,
; so that we can expand the types of constructor arguments
; that refer to it. This binding is the reason we can't use infer
; here; infer is specifically about attaching types, not binding
; general transformers.
[Name
(make-type-constructor-transformer
#'Name #'void = (stx-length #'(X ...)))] ...)
(void ty_flat ...))) ...))
#:when (stx-map
(λ (ts+ ts)
(stx-map
(lambda (t+ t) (unless (type? t+)
(type-error #:src t
#:msg "~a is not a valid type" t)))
ts+ ts))
#'((ty+ ...) ...) #'((ty_flat ...) ...))
#:with (NameExtraInfo ...) (stx-map (λ (n) (format-id n "~a-extra-info" n)) #'(Name ...))
#:with (n ...) (stx-map (λ (Xs) #`#,(stx-length Xs)) #'((X ...) ...))
#`(begin-
(define-type-constructor Name
#:arity = n
#:extra-info 'NameExtraInfo) ...
(define-type-rest (Name X ...) c.C ...) ...
)]))
;; defines the runtime components of a define-datatype
(define-syntax (define-type-rest stx)
(syntax-parse stx
[(_ (Name:id X:id ...)
c:constructor ...)
#:with Name? (mk-? #'Name)
#:with NameExtraInfo (format-id #'Name "~a-extra-info" #'Name)
#:with (StructName ...) (generate-temporaries #'(c.Cons ...))
#:with ((exposed-acc ...) ...)
(stx-map
(λ (C fs) (stx-map (λ (f) (format-id C "~a-~a" C f)) fs))
#'(c.Cons ...) #'((c.fld ...) ...))
#:with ((acc ...) ...)
(stx-map
(λ (S fs) (stx-map (λ (f) (format-id S "~a-~a" S f)) fs))
#'(StructName ...) #'((c.fld ...) ...))
#:with (Cons? ...) (stx-map mk-? #'(StructName ...))
#:with (exposed-Cons? ...) (stx-map mk-? #'(c.Cons ...))
#`(begin-
(define-syntax NameExtraInfo
(make-extra-info-transformer
#'(X ...)
#'(#%plain-app- (#%plain-app- 'c.Cons 'StructName Cons? [#%plain-app- acc c.τ] ...) ...)))
(struct- StructName (c.fld ...) #:reflection-name 'c.Cons #:transparent) ...
(define-syntax exposed-acc ; accessor for records
(make-variable-like-transformer
(assign-type #'acc #'(∀ (X ...) (ext-stlc:→ (Name X ...) c.τ)))))
... ...
(define-syntax exposed-Cons? ; predicates for each variant
(make-variable-like-transformer
(assign-type #'Cons? #'(∀ (X ...) (ext-stlc:→ (Name X ...) Bool))))) ...
(define-syntax c.Cons
(make-constructor-transformer #'(X ...) #'(c.τ ...) #'Name #'StructName Name?))
...)]))
;; defines a single datatype; dispatches to define-types
(define-syntax (define-type stx)
(syntax-parse stx
[(_ Name:id . rst)
#:with NewName (generate-temporary #'Name)
#:with Name2 (add-orig #'(NewName) #'Name)
#`(begin-
(define-type Name2 . #,(subst #'Name2 #'Name #'rst))
(stlc+rec-iso:define-type-alias Name Name2))]
[(_ Name . Cs) #'(define-types [Name . Cs])]))
(begin-for-syntax
(define (make-extra-info-transformer Xs stuff)
(syntax-parser
[(_ Y ...)
(substs #'(Y ...) Xs stuff)]))
(define (make-constructor-transformer Xs τs Name-arg StructName-arg Name?)
(define/syntax-parse (X ...) Xs)
(define/syntax-parse (τ ...) τs)
(define/syntax-parse Name Name-arg)
(define/syntax-parse StructName StructName-arg)
(syntax-parser
; no args and not polymorphic
[C:id #:when (and (stx-null? #'(X ...)) (stx-null? #'(τ ...))) #'(C)]
; no args but polymorphic, check inferred type
[C:id
#:when (stx-null? #'(τ ...))
#:with τ-expected (syntax-property #'C 'expected-type)
#:fail-unless (syntax-e #'τ-expected)
(raise
(exn:fail:type:infer
(format "~a (~a:~a): ~a: ~a"
(syntax-source this-syntax) (syntax-line this-syntax) (syntax-column this-syntax)
(syntax-e #'C)
(no-expected-type-fail-msg))
(current-continuation-marks)))
#:with τ-expected+ ((current-type-eval) #'τ-expected)
#:fail-unless (Name? #'τ-expected+)
(format "Expected ~a type, got: ~a"
(syntax-e #'Name) (type->str #'τ-expected+))
#:with (~Any _ τ-expected-arg ...) #'τ-expected+
#'(C {τ-expected-arg ...})]
[_:id (⊢ StructName (∀ (X ...) (ext-stlc:→ τ ... (Name X ...))))] ; HO fn
[(C τs e_arg ...)
#:when (brace? #'τs) ; commit to this clause
#:with {~! τ_X:type ...} #'τs
#:with (τ_in:type ...) ; instantiated types
(stx-map
(λ (t) (substs #'(τ_X.norm ...) #'(X ...) t))
#'(τ ...))
#:with ([e_arg- τ_arg] ...)
(stx-map
(λ (e τ_e)
(infer+erase (set-stx-prop/preserved e 'expected-type τ_e)))
#'(e_arg ...) #'(τ_in.norm ...))
#:fail-unless (typechecks? #'(τ_arg ...) #'(τ_in.norm ...))
(typecheck-fail-msg/multi #'(τ_in.norm ...) #'(τ_arg ...) #'(e_arg ...))
(⊢ (#%plain-app- StructName e_arg- ...) : (Name τ_X ...))]
[(C . args) ; no type annotations, must infer instantiation
#:with StructName/ty
(set-stx-prop/preserved
(⊢ StructName : (∀ (X ...) (ext-stlc:→ τ ... (Name X ...))))
'orig
(list #'C))
; stx/loc transfers expected-type
(syntax/loc this-syntax (mlish:#%app StructName/ty . args))])))
;; match --------------------------------------------------
(begin-for-syntax
(define (get-ctx pat ty)
(unify-pat+ty (list pat ty)))
(define (unify-pat+ty pat+ty)
(syntax-parse pat+ty
[(pat ty) #:when (brace? #'pat) ; handle root pattern specially (to avoid some parens)
(syntax-parse #'pat
[{(~datum _)} #'()]
[{(~literal stlc+cons:nil)} #'()]
[{A:id} ; disambiguate 0-arity constructors (that don't need parens)
#:when (get-extra-info #'ty)
#'()]
;; comma tup syntax always has parens
[{(~and ps (p1 (unq p) ...))}
#:when (not (stx-null? #'(p ...)))
#:when (andmap (lambda (u) (equal? u 'unquote)) (syntax->datum #'(unq ...)))
(unify-pat+ty #'(ps ty))]
[{p ...}
(unify-pat+ty #'((p ...) ty))])] ; pair
[((~datum _) ty) #'()]
[((~or (~literal stlc+cons:nil)) ty) #'()]
[(A:id ty) ; disambiguate 0-arity constructors (that don't need parens)
#:with (_ (_ (_ C) . _) ...) (get-extra-info #'ty)
#:when (member (syntax->datum #'A) (syntax->datum #'(C ...)))
#'()]
[(x:id ty) #'((x : ty))]
[((p1 (unq p) ...) ty) ; comma tup stx
#:when (not (stx-null? #'(p ...)))
#:when (andmap (lambda (u) (equal? u 'unquote)) (syntax->datum #'(unq ...)))
#:with (~× t ...) #'ty
#:with (pp ...) #'(p1 p ...)
(unifys #'([pp t] ...))]
[(((~literal stlc+tup:tup) p ...) ty) ; tup
#:with (~× t ...) #'ty
(unifys #'([p t] ...))]
[(((~literal stlc+cons:list) p ...) ty) ; known length list
#:with (~List t) #'ty
(unifys #'([p t] ...))]
[(((~seq p (~datum ::)) ... rst) ty) ; nicer cons stx
#:with (~List t) #'ty
(unifys #'([p t] ... [rst ty]))]
[(((~literal stlc+cons:cons) p ps) ty) ; arb length list
#:with (~List t) #'ty
(unifys #'([p t] [ps ty]))]
[((Name p ...) ty)
#:with (_ (_ Cons) _ _ [_ _ τ] ...)
(stx-findf
(syntax-parser
[(_ 'C . rst)
(equal? (syntax->datum #'Name) (syntax->datum #'C))])
(stx-cdr (get-extra-info #'ty)))
(unifys #'([p τ] ...))]
[p+t #:fail-when #t (format "could not unify ~a" (syntax->datum #'p+t))
#'()]))
(define (unifys p+tys) (stx-appendmap unify-pat+ty p+tys))
(define (compile-pat p ty)
(syntax-parse p
[pat #:when (brace? #'pat) ; handle root pattern specially (to avoid some parens)
(syntax-parse #'pat
[{(~datum _)} #'_]
[{(~literal stlc+cons:nil)} (syntax/loc p (list))]
[{A:id} ; disambiguate 0-arity constructors (that don't need parens)
#:when (get-extra-info ty)
(compile-pat #'(A) ty)]
;; comma tup stx always has parens
[{(~and ps (p1 (unq p) ...))}
#:when (not (stx-null? #'(p ...)))
#:when (andmap (lambda (u) (equal? u 'unquote)) (syntax->datum #'(unq ...)))
(compile-pat #'ps ty)]
[{pat ...} (compile-pat (syntax/loc p (pat ...)) ty)])]
[(~datum _) #'_]
[(~literal stlc+cons:nil) ; nil
#'(list)]
[A:id ; disambiguate 0-arity constructors (that don't need parens)
#:with (_ (_ (_ C) . _) ...) (get-extra-info ty)
#:when (member (syntax->datum #'A) (syntax->datum #'(C ...)))
(compile-pat #'(A) ty)]
[x:id p]
[(p1 (unq p) ...) ; comma tup stx
#:when (not (stx-null? #'(p ...)))
#:when (andmap (lambda (u) (equal? u 'unquote)) (syntax->datum #'(unq ...)))
#:with (~× t ...) ty
#:with (p- ...) (stx-map (lambda (p t) (compile-pat p t)) #'(p1 p ...) #'(t ...))
#'(list p- ...)]
[((~literal stlc+tup:tup) . pats)
#:with (~× . tys) ty
#:with (p- ...) (stx-map (lambda (p t) (compile-pat p t)) #'pats #'tys)
(syntax/loc p (list p- ...))]
[((~literal stlc+cons:list) . ps)
#:with (~List t) ty
#:with (p- ...) (stx-map (lambda (p) (compile-pat p #'t)) #'ps)
(syntax/loc p (list p- ...))]
[((~seq pat (~datum ::)) ... last) ; nicer cons stx
#:with (~List t) ty
#:with (p- ...) (stx-map (lambda (pp) (compile-pat pp #'t)) #'(pat ...))
#:with last- (compile-pat #'last ty)
(syntax/loc p (list-rest p- ... last-))]
[((~literal stlc+cons:cons) p ps)
#:with (~List t) ty
#:with p- (compile-pat #'p #'t)
#:with ps- (compile-pat #'ps ty)
#'(cons p- ps-)]
[(Name . pats)
#:with (_ (_ Cons) (_ StructName) _ [_ _ τ] ...)
(stx-findf
(syntax-parser
[(_ 'C . rst)
(equal? (syntax->datum #'Name) (syntax->datum #'C))])
(stx-cdr (get-extra-info ty)))
#:with (p- ...) (stx-map compile-pat #'pats #'(τ ...))
(syntax/loc p (StructName p- ...))]))
;; pats = compiled pats = racket pats
(define (check-exhaust pats ty)
(define (else-pat? p)
(syntax-parse p [(~literal _) #t] [_ #f]))
(define (nil-pat? p)
(syntax-parse p
[((~literal list)) #t]
[_ #f]))
(define (non-nil-pat? p)
(syntax-parse p
[((~literal list-rest) . rst) #t]
[((~literal cons) . rst) #t]
[_ #f]))
(define (tup-pat? p)
(syntax-parse p
[((~literal list) . _) #t] [_ #f]))
(cond
[(or (stx-ormap else-pat? pats) (stx-ormap identifier? pats)) #t]
[(List? ty) ; lists
(unless (stx-ormap nil-pat? pats)
(error 'match2 (let ([last (car (stx-rev pats))])
(format "(~a:~a) missing nil clause for list expression"
(syntax-line last) (syntax-column last)))))
(unless (stx-ormap non-nil-pat? pats)
(error 'match2 (let ([last (car (stx-rev pats))])
(format "(~a:~a) missing clause for non-empty, arbitrary length list"
(syntax-line last) (syntax-column last)))))
#t]
[(×? ty) ; tuples
(unless (stx-ormap tup-pat? pats)
(error 'match2 (let ([last (car (stx-rev pats))])
(format "(~a:~a) missing pattern for tuple expression"
(syntax-line last) (syntax-column last)))))
(syntax-parse pats
[((_ p ...) ...)
(syntax-parse ty
[(~× t ...)
(apply stx-andmap
(lambda (t . ps) (check-exhaust ps t))
#'(t ...)
(syntax->list #'((p ...) ...)))])])]
[else ; algebraic datatypes
(syntax-parse (get-extra-info ty)
[(_ (_ (_ C) (_ Cstruct) . rst) ...)
(syntax-parse pats
[((Cpat _ ...) ...)
(define Cs (syntax->datum #'(C ...)))
(define Cstructs (syntax->datum #'(Cstruct ...)))
(define Cpats (syntax->datum #'(Cpat ...)))
(unless (set=? Cstructs Cpats)
(error 'match2
(let ([last (car (stx-rev pats))])
(format "(~a:~a) clauses not exhaustive; missing: ~a"
(syntax-line last) (syntax-column last)
(string-join
(for/list ([C Cs][Cstr Cstructs] #:unless (member Cstr Cpats))
(symbol->string C))
", ")))))
#t])]
[_ #t])]))
;; TODO: do get-ctx and compile-pat in one pass
(define (compile-pats pats ty)
(stx-map (lambda (p) (list (get-ctx p ty) (compile-pat p ty))) pats))
)
(define-syntax (match2 stx)
(syntax-parse stx #:datum-literals (with)
[(_ e with . clauses)
#:fail-when (null? (syntax->list #'clauses)) "no clauses"
#:with [e- τ_e] (infer+erase #'e)
(syntax-parse #'clauses #:datum-literals (->)
[([(~seq p ...) -> e_body] ...)
#:with (pat ...) (stx-map ; use brace to indicate root pattern
(lambda (ps) (syntax-parse ps [(pp ...) (syntax/loc stx {pp ...})]))
#'((p ...) ...))
#:with ([(~and ctx ([x _ ty] ...)) pat-] ...) (compile-pats #'(pat ...) #'τ_e)
#:with ([(x- ...) e_body- ty_body] ...)
(stx-map
infer/ctx+erase
#'(ctx ...) #`((pass-expected e_body #,stx) ...))
#:when (check-exhaust #'(pat- ...) #'τ_e)
#:with τ_out (stx-foldr (current-join) (stx-car #'(ty_body ...)) (stx-cdr #'(ty_body ...)))
(⊢ (match- e- [pat- (let-values- ([(x-) x] ...) e_body-)] ...) : τ_out)
])]))
(define-typed-syntax match #:datum-literals (with)
[(_ e with . clauses)
#:fail-when (null? (syntax->list #'clauses)) "no clauses"
#:with [e- τ_e] (infer+erase #'e)
(cond
[(×? #'τ_e) ;; e is tuple
(syntax-parse #'clauses #:datum-literals (->)
[([x ... -> e_body])
#:with (~× ty ...) #'τ_e
#:fail-unless (stx-length=? #'(ty ...) #'(x ...))
"match clause pattern not compatible with given tuple"
#:with [(x- ...) e_body- ty_body] (infer/ctx+erase #'([x : ty] ...)
#`(pass-expected e_body #,stx))
#:with (acc ...) (for/list ([(a i) (in-indexed (syntax->list #'(x ...)))])
#`(#%plain-lambda- (s) (#%plain-app- list-ref- s #,(datum->syntax #'here i))))
#:with z (generate-temporary)
(⊢ (let-values- ([(z) e-])
(let-values- ([(x-) (#%plain-app- acc z)] ...) e_body-))
: ty_body)])]
[(List? #'τ_e) ;; e is List
(syntax-parse #'clauses #:datum-literals (-> ::)
[([(~or (~and (~and xs [x ...]) (~parse rst (generate-temporary)))
(~and (~seq (~seq x ::) ... rst:id) (~parse xs #'())))
-> e_body] ...+)
#:fail-unless (stx-ormap
(lambda (xx) (and (brack? xx) (zero? (stx-length xx))))
#'(xs ...))
"match: missing empty list case"
#:fail-when (and (stx-andmap brack? #'(xs ...))
(= 1 (stx-length #'(xs ...))))
"match: missing non-empty list case"
#:with (~List ty) #'τ_e
#:with ([(x- ... rst-) e_body- ty_body] ...)
(stx-map
infer/ctx+erase
#'(([x : ty] ... [rst : τ_e]) ...)
#`((pass-expected e_body #,stx) ...))
#:with τ_out (stx-foldr (current-join) (stx-car #'(ty_body ...)) (stx-cdr #'(ty_body ...)))
#:with (len ...) (stx-map (lambda (p) #`#,(stx-length p)) #'((x ...) ...))
#:with (lenop ...) (stx-map (lambda (p) (if (brack? p) #'=- #'>=-)) #'(xs ...))
#:with (pred? ...) (stx-map
(lambda (l lo) #`(#%plain-lambda- (lst) (#%plain-app- #,lo (length- lst) #,l)))
#'(len ...) #'(lenop ...))
#:with ((acc1 ...) ...) (stx-map
(lambda (xs)
(for/list ([(x i) (in-indexed (syntax->list xs))])
#`(#%plain-lambda- (lst) (#%plain-app- list-ref- lst #,(datum->syntax #'here i)))))
#'((x ...) ...))
#:with (acc2 ...) (stx-map (lambda (l) #`(#%plain-lambda- (lst) (#%plain-app- list-tail- lst #,l))) #'(len ...))
(⊢ (let-values- ([(z) e-])
(cond-
[(#%plain-app- pred? z)
(let-values- ([(x-) (#%plain-app- acc1 z)] ... [(rst-) (#%plain-app- acc2 z)]) e_body-)] ...))
: τ_out)])]
[else ;; e is variant
(syntax-parse #'clauses #:datum-literals (->)
[([Clause:id x:id ...
(~optional (~seq #:when e_guard) #:defaults ([e_guard #'(ext-stlc:#%datum . #t)]))
-> e_c_un] ...+) ; un = unannotated with expected ty
;; length #'clauses may be > length #'info, due to guards
#:with info-body (get-extra-info #'τ_e)
#:with (_ (_ (_ ConsAll) . _) ...) #'info-body
#:fail-unless (set=? (syntax->datum #'(Clause ...))
(syntax->datum #'(ConsAll ...)))
(type-error #:src stx
#:msg (string-append
"match: clauses not exhaustive; missing: "
(string-join
(map symbol->string
(set-subtract
(syntax->datum #'(ConsAll ...))
(syntax->datum #'(Clause ...))))
", ")))
#:with ((_ _ _ Cons? [_ acc τ] ...) ...)
(map ; ok to compare symbols since clause names can't be rebound
(lambda (Cl)
(stx-findf
(syntax-parser
[(_ 'C . rst) (equal? Cl (syntax->datum #'C))])
(stx-cdr #'info-body))) ; drop leading #%app
(syntax->datum #'(Clause ...)))
;; this commented block experiments with expanding to unsafe ops
;; #:with ((acc ...) ...) (stx-map
;; (lambda (accs)
;; (for/list ([(a i) (in-indexed (syntax->list accs))])
;; #`(lambda (s) (unsafe-struct*-ref s #,(datum->syntax #'here i)))))
;; #'((acc-fn ...) ...))
#:with (e_c ...+) (stx-map (lambda (ec) #`(pass-expected #,ec #,stx)) #'(e_c_un ...))
#:with (((x- ...) (e_guard- e_c-) (τ_guard τ_ec)) ...)
(stx-map
infers/ctx+erase
#'(([x : τ] ...) ...)
#'((e_guard e_c) ...))
#:fail-unless (and (same-types? #'(τ_guard ...))
(Bool? (stx-car #'(τ_guard ...))))
"guard expression(s) must have type bool"
#:with τ_out (stx-foldr (current-join) (stx-car #'(τ_ec ...)) (stx-cdr #'(τ_ec ...)))
#:with z (generate-temporary) ; dont duplicate eval of test expr
(⊢ (let-values- ([(z) e-])
(cond-
[(if- (#%plain-app- Cons? z)
(let-values- ([(x-) (#%plain-app- acc z)] ...) e_guard-)
(quote- #f))
(let-values- ([(x-) (#%plain-app- acc z)] ...) e_c-)] ...))
: τ_out)])])])
(define-syntax → ; wrapping →
(syntax-parser
[(_ ty ... #:TC TC ...)
#'(∀ () (=> TC ... (ext-stlc:→ ty ...)))]
[(_ Xs . rst)
#:when (brace? #'Xs)
#:with (X ...) #'Xs
(syntax-property
#'(∀ (X ...) (ext-stlc:→ . rst))
'orig (list #'(→ . rst)))]
[(_ . rst) (set-stx-prop/preserved #'(∀ () (ext-stlc:→ . rst)) 'orig (list #'(→ . rst)))]))
; special arrow that computes free vars; for use with tests
; (because we can't write explicit forall
(define-syntax →/test
(syntax-parser
[(_ (~and Xs (X:id ...)) . rst)
#:when (brace? #'Xs)
#'(∀ (X ...) (ext-stlc:→ . rst))]
[(_ . rst)
#:with Xs (compute-tyvars #'rst)
#'(∀ Xs (ext-stlc:→ . rst))]))
(define-syntax =>/test
(syntax-parser
[(_ . (~and rst (TC ... (_arr . tys_arr))))
#:with Xs (compute-tyvars #'rst)
#'(∀ Xs (=> TC ... (ext-stlc:→ . tys_arr)))]))
; redefine these to use lifted →
(provide (typed-out/unsafe [+ : (→ Int Int Int)]
[- : (→ Int Int Int)]
[* : (→ Int Int Int)]
[max : (→ Int Int Int)]
[min : (→ Int Int Int)]
[void : (→ Unit)]
[= : (→ Int Int Bool)]
[<= : (→ Int Int Bool)]
[>= : (→ Int Int Bool)]
[< : (→ Int Int Bool)]
[> : (→ Int Int Bool)]
[modulo : (→ Int Int Int)]
[zero? : (→ Int Bool)]
[sub1 : (→ Int Int)]
[add1 : (→ Int Int)]
[not : (→ Bool Bool)]
[abs : (→ Int Int)]
[even? : (→ Int Bool)]
[odd? : (→ Int Bool)]))
;; λ --------------------------------------------------------------------------
(define-typed-syntax BindTC
[(_ (TC ...) body)
#:with (~and (TC+ ...) (~TCs ([op-sym ty-op] ...) ...))
(stx-map expand/df #'(TC ...))
#:with (op* ...)
(stx-appendmap
(lambda (os tc)
(stx-map (lambda (o) (format-id tc "~a" o)) os))
#'((op-sym ...) ...) #'(TC ...))
#:with (ty-op* ...) (stx-flatten #'((ty-op ...) ...))
#:with ty-in-tagsss (stx-map get-fn-ty-in-tags #'(ty-op* ...))
#:with (mangled-op ...) (stx-map mangle #'(op* ...) #'ty-in-tagsss)
#:with (mangled-ops- body- t-) (infer/ctx+erase #'([mangled-op : ty-op*] ...)
#'body)
(⊢ (#%plain-lambda- mangled-ops- body-) : #,(mk-=>- #'(TC+ ... t-)))])
; all λs have type (∀ (X ...) (→ τ_in ... τ_out)), even monomorphic fns
(define-typed-syntax liftedλ #:export-as λ
[(_ ([x:id (~datum :) ty] ... #:where TC ...) body)
#:with (X ...) (compute-tyvars #'(ty ...))
(syntax/loc stx (liftedλ {X ...} ([x : ty] ... #:where TC ...) body))]
[(_ (~and Xs (X ...)) ([x:id (~datum :) ty] ... #:where TC ...) body)
#:when (brace? #'Xs)
#'(Λ (X ...) (BindTC (TC ...) (ext-stlc:λ ([x : ty] ...) body)))]
[(_ ([x:id (~datum :) ty] ...) body) ; no TC
#:with (X ...) (compute-tyvars #'(ty ...))
#:with (~∀ () (~ext-stlc:→ _ ... body-ty)) (get-expected-type stx)
#'(Λ (X ...) (ext-stlc:λ ([x : ty] ...) (add-expected body body-ty)))]
[(_ ([x:id (~datum :) ty] ...) body) ; no TC, ignoring expected-type
#:with (X ...) (compute-tyvars #'(ty ...))
#'(Λ (X ...) (ext-stlc:λ ([x : ty] ...) body))]
[(_ (x:id ...+) body)
#:with (~?∀ Xs expected) (get-expected-type stx)
#:do [(unless (→? #'expected)
(type-error #:src stx #:msg "λ parameters must have type annotations"))]
#:with (~ext-stlc:→ arg-ty ... body-ty) #'expected
#:do [(unless (stx-length=? #'[x ...] #'[arg-ty ...])
(type-error #:src stx #:msg
(format "expected a function of ~a arguments, got one with ~a arguments"
(stx-length #'[arg-ty ...] #'[x ...]))))]
#`(Λ Xs (ext-stlc:λ ([x : arg-ty] ...) (add-expected body body-ty)))]
#;[(_ args body)
#:with (~∀ () (~ext-stlc:→ arg-ty ... body-ty)) (get-expected-type stx)
#`(Λ () (ext-stlc:λ args #,(add-expected-type #'body #'body-ty)))]
#;[(_ (~and x+tys ([_ (~datum :) ty] ...)) . body)
#:with Xs (compute-tyvars #'(ty ...))
;; TODO is there a way to have λs that refer to ids defined after them?
#'(Λ Xs (ext-stlc:λ x+tys . body))])
;; #%app --------------------------------------------------
(define-typed-syntax mlish:#%app #:export-as #%app
[(_ e_fn . e_args)
; #:when (printf "app: ~a\n" (syntax->datum #'(e_fn . e_args)))
;; ) compute fn type (ie ∀ and →)
#:with [e_fn- (~and ty_fn (~∀ Xs ty_fnX))] (infer+erase #'e_fn)
(cond
[(stx-null? #'Xs)
(define/with-syntax tyX_args
(syntax-parse #'ty_fnX
[(~ext-stlc:→ . tyX_args) #'tyX_args]))
(syntax-parse #'(e_args tyX_args)
[((e_arg ...) (τ_inX ... _))
#:fail-unless (stx-length=? #'(e_arg ...) #'(τ_inX ...))
(mk-app-err-msg stx #:expected #'(τ_inX ...)
#:note "Wrong number of arguments.")
#:with e_fn/ty (⊢ e_fn- : #,(mk-→- #'tyX_args))
#'(ext-stlc:#%app e_fn/ty (add-expected e_arg τ_inX) ...)])]
[else
(syntax-parse #'ty_fnX
;; TODO: combine these two clauses
;; no typeclasses, duplicate code for now --------------------------------
[(~ext-stlc:→ . tyX_args)
;; ) solve for type variables Xs
(define/with-syntax ((e_arg1- ...) (unsolved-X ...) cs) (solve #'Xs #'tyX_args stx))
;; ) instantiate polymorphic function type
(syntax-parse (inst-types/cs #'Xs #'cs #'tyX_args)
[(τ_in ... τ_out) ; concrete types
;; ) arity check
#:fail-unless (stx-length=? #'(τ_in ...) #'e_args)
(mk-app-err-msg stx #:expected #'(τ_in ...)
#:note "Wrong number of arguments.")
;; ) compute argument types; re-use args expanded during solve
#:with ([e_arg2- τ_arg2] ...) (let ([n (stx-length #'(e_arg1- ...))])
(infers+erase
(stx-map add-expected-type
(stx-drop #'e_args n) (stx-drop #'(τ_in ...) n))))
#:with (τ_arg1 ...) (stx-map typeof #'(e_arg1- ...))
#:with (τ_arg ...) #'(τ_arg1 ... τ_arg2 ...)
#:with (e_arg- ...) #'(e_arg1- ... e_arg2- ...)
;; ) typecheck args
#:fail-unless (typechecks? #'(τ_arg ...) #'(τ_in ...))
(mk-app-err-msg stx
#:given #'(τ_arg ...)
#:expected
(stx-map
(lambda (tyin)
(define old-orig (get-orig tyin))
(define new-orig
(and old-orig
(substs
(stx-map get-orig (lookup-Xs/keep-unsolved #'Xs #'cs)) #'Xs old-orig
(lambda (x y)
(equal? (syntax->datum x) (syntax->datum y))))))
(syntax-property tyin 'orig (list new-orig)))
#'(τ_in ...)))
#:with τ_out* (if (stx-null? #'(unsolved-X ...))
#'τ_out
(syntax-parse #'τ_out
[(~?∀ (Y ...) τ_out)
(unless (→? #'τ_out)
(raise-app-poly-infer-error stx #'(τ_in ...) #'(τ_arg ...) #'e_fn))
(mk-∀- #'(unsolved-X ... Y ...) #'(τ_out))]))
(⊢ (#%plain-app- e_fn- e_arg- ...) : τ_out*)])]
;; handle type class constraints ----------------------------------------
[(~=> TCX ... (~ext-stlc:→ . tyX_args))
;; ) solve for type variables Xs
(define/with-syntax ((e_arg1- ...) (unsolved-X ...) cs) (solve #'Xs #'tyX_args stx))
;; ) instantiate polymorphic function type
(syntax-parse (inst-types/cs #'Xs #'cs #'((TCX ...) tyX_args))
[((TC ...) (τ_in ... τ_out)) ; concrete types
#:with (~TCs ([generic-op ty-concrete-op] ...) ...) #'(TC ...)
#:with (op ...)
(stx-appendmap
(lambda (gen-ops conc-op-tys TC)
(map
(lambda (o tys)
(with-handlers
([exn:fail:syntax:unbound?
(lambda (e)
(type-error #:src stx
#:msg
(format
(string-append
"~a instance undefined. "
"Cannot instantiate function with constraints "
"~a with:\n ~a")
(type->str
(let*
([old-orig (get-orig TC)]
[new-orig
(and
old-orig
(substs (stx-map get-orig (lookup-Xs/keep-unsolved #'Xs #'cs)) #'Xs old-orig
(lambda (x y)
(equal? (syntax->datum x)
(syntax->datum y)))))])
(syntax-property TC 'orig (list new-orig))))
(types->str #'(TCX ...))
(string-join
(stx-map
(lambda (X ty-solved)
(string-append (type->str X) " : " (type->str ty-solved)))
#'Xs (lookup-Xs/keep-unsolved #'Xs #'cs)) ", "))))])
(lookup-op o tys)))
(stx-map (lambda (o) (format-id stx "~a" o #:source stx)) gen-ops)
(stx-map
(syntax-parser
[(~∀ _ (~ext-stlc:→ ty_in ... _)) #'(ty_in ...)])
conc-op-tys)))
#'((generic-op ...) ...) #'((ty-concrete-op ...) ...) #'(TC ...))
;; ) arity check
#:fail-unless (stx-length=? #'(τ_in ...) #'e_args)
(mk-app-err-msg stx #:expected #'(τ_in ...)
#:note "Wrong number of arguments.")
;; ) compute argument types; re-use args expanded during solve
#:with ([e_arg2- τ_arg2] ...) (let ([n (stx-length #'(e_arg1- ...))])
(infers+erase
(stx-map add-expected-type
(stx-drop #'e_args n) (stx-drop #'(τ_in ...) n))))
#:with (τ_arg1 ...) (stx-map typeof #'(e_arg1- ...))
#:with (τ_arg ...) #'(τ_arg1 ... τ_arg2 ...)
#:with (e_arg- ...) #'(e_arg1- ... e_arg2- ...)
;; ) typecheck args
#:fail-unless (typechecks? #'(τ_arg ...) #'(τ_in ...))
(mk-app-err-msg stx
#:given #'(τ_arg ...)
#:expected
(stx-map
(lambda (tyin)
(define old-orig (get-orig tyin))
(define new-orig
(and old-orig
(substs
(stx-map get-orig (lookup-Xs/keep-unsolved #'Xs #'cs)) #'Xs old-orig
(lambda (x y)
(equal? (syntax->datum x) (syntax->datum y))))))
(syntax-property tyin 'orig (list new-orig)))
#'(τ_in ...)))
#:with τ_out* (if (stx-null? #'(unsolved-X ...))
#'τ_out
(syntax-parse #'τ_out
[(~?∀ (Y ...) τ_out)
(unless (→? #'τ_out)
(raise-app-poly-infer-error stx #'(τ_in ...) #'(τ_arg ...) #'e_fn))
(mk-∀- #'(unsolved-X ... Y ...) #'(τ_out))]))
(⊢ (#%plain-app- (#%plain-app- e_fn- op ...) e_arg- ...) : τ_out*)])])])]
[(_ e_fn . e_args) ; err case; e_fn is not a function
#:with [e_fn- τ_fn] (infer+erase #'e_fn)
(type-error #:src stx
#:msg (format "Expected expression ~a to have → type, got: ~a"
(syntax->datum #'e_fn) (type->str #'τ_fn)))])
;; cond and other conditionals
(define-typed-syntax cond
[(_ [(~or (~and (~datum else) (~parse test #'(ext-stlc:#%datum . #t)))
test)
b ... body] ...+)
#:with (test- ...) (⇑s (test ...) as Bool)
#:with ([body- ty_body] ...) (infers+erase #`((pass-expected body #,this-syntax) ...))
#:with (([b- ty_b] ...) ...) (stx-map infers+erase #'((b ...) ...))
#:with τ_out (stx-foldr (current-join) (stx-car #'(ty_body ...)) (stx-cdr #'(ty_body ...)))
(⊢ (cond- [test- b- ... body-] ...) : τ_out)])
(define-typed-syntax when
[(_ test body ...)
#:with [test- _] (infer+erase #'test)
#:with [(body- _) ...] (infers+erase #'(body ...))
(⊢ (when- test- body- ...) : #,Unit+)])
(define-typed-syntax unless
[(_ test body ...)
; #:with test- (⇑ test as Bool)
#:with [test- _] (infer+erase #'test)
#:with [(body- _) ...] (infers+erase #'(body ...))
(⊢ (unless- test- body- ...) : #,Unit+)])
;; sync channels and threads
(define-type-constructor Channel)
(define-typed-syntax make-channel
[(_ (~and tys {ty:type}))
#:when (brace? #'tys)
(⊢ (#%plain-app- make-channel-) : #,(mk-Channel- #'(ty.norm)))])
(define-typed-syntax channel-get
[(_ c)
#:with (c- (ty)) (⇑ c as Channel)
(⊢ (#%plain-app- channel-get- c-) : ty)])
(define-typed-syntax channel-put
[(_ c v)
#:with (c- (ty)) (⇑ c as Channel)
#:with [v- ty_v] (infer+erase #'v)
#:fail-unless (typechecks? #'ty_v #'ty)
(format "Cannot send ~a value on ~a channel."
(type->str #'ty_v) (type->str #'ty))
(⊢ (#%plain-app- channel-put- c- v-) : #,Unit+)])
(define-base-type Thread)
;; threads
(define-typed-syntax thread
[(_ th)
#:with (th- (~∀ () (~ext-stlc:→ τ_out))) (infer+erase #'th)
(⊢ (#%plain-app- thread- th-) : #,Thread+)])
(provide (typed-out/unsafe [random : (→ Int Int)]
[integer->char : (→ Int Char)]
[string->list : (→ String (List Char))]
[string->number : (→ String Int)]))
(define-typed-syntax num->str #:export-as number->string
[f:id (assign-type #'number->string (mk-→- (list Int+ String+)))]
[(_ n)
#'(num->str n (ext-stlc:#%datum . 10))]
[(_ n rad)
#:with args- (⇑s (n rad) as Int)
(⊢ (#%plain-app- number->string- . args-) : #,String+)])
(provide (typed-out/unsafe [string : (→ Char String)]
[sleep : (→ Int Unit)]
[string=? : (→ String String Bool)]
[string<? : (→ String String Bool)]
[string<=? : (→ String String Bool)]
[string>? : (→ String String Bool)]
[string>=? : (→ String String Bool)]
[char=? : (→ Char Char Bool)]
[char<? : (→ Char Char Bool)]
[char<=? : (→ Char Char Bool)]
[char>? : (→ Char Char Bool)]
[char>=? : (→ Char Char Bool)]))
(define-typed-syntax string-append
[(_ . strs)
#:with strs- (⇑s strs as String)
(⊢ (#%plain-app- string-append- . strs-) : #,String+)])
;; vectors
(define-type-constructor Vector)
(define-typed-syntax vector
[(_ (~and tys {ty:type}))
#:when (brace? #'tys)
(⊢ (vector-) : #,(mk-Vector- #'(ty.norm)))]
[(_ v ...)
#:with ([v- ty] ...) (infers+erase #'(v ...))
#:when (same-types? #'(ty ...))
#:with one-ty (stx-car #'(ty ...))
(⊢ (#%plain-app- vector- v- ...) : #,(mk-Vector- #'(one-ty)))])
(define-typed-syntax make-vector/tc #:export-as make-vector
[(_ n) #'(make-vector/tc n (ext-stlc:#%datum . 0))]
[(_ n e)
#:with n- (⇑ n as Int)
#:with [e- ty] (infer+erase #'e)
(⊢ (#%plain-app- make-vector- n- e-) : #,(mk-Vector- #'(ty)))])
(define-typed-syntax vector-length
[(_ e)
#:with [e- _] (⇑ e as Vector)
(⊢ (#%plain-app- vector-length- e-) : #,Int+)])
(define-typed-syntax vector-ref
[(_ e n)
#:with n- (⇑ n as Int)
#:with [e- (ty)] (⇑ e as Vector)
(⊢ (#%plain-app- vector-ref- e- n-) : ty)])
(define-typed-syntax vector-set!
[(_ e n v)
#:with n- (⇑ n as Int)
#:with [e- (ty)] (⇑ e as Vector)
#:with [v- ty_v] (infer+erase #'v)
#:when (typecheck? #'ty_v #'ty)
(⊢ (#%plain-app- vector-set!- e- n- v-) : #,Unit+)])
(define-typed-syntax vector-copy!
[(_ dest start src)
#:with start- (⇑ start as Int)
#:with [dest- (ty_dest)] (⇑ dest as Vector)
#:with [src- (ty_src)] (⇑ src as Vector)
#:when (typecheck? #'ty_dest #'ty_src)
(⊢ (#%plain-app- vector-copy!- dest- start- src-) : #,Unit+)])
;; sequences and for loops
(define-type-constructor Sequence)
(define-typed-syntax in-range/tc #:export-as in-range
[(_ end)
#'(in-range/tc (ext-stlc:#%datum . 0) end (ext-stlc:#%datum . 1))]
[(_ start end)
#'(in-range/tc start end (ext-stlc:#%datum . 1))]
[(_ start end step)
#:with (e- ...) (⇑s (start end step) as Int)
(⊢ (#%plain-app- in-range- e- ...) : #,(mk-Sequence- (list Int+)))])
(define-typed-syntax in-naturals/tc #:export-as in-naturals
[(_) #'(in-naturals/tc (ext-stlc:#%datum . 0))]
[(_ start)
#:with start- (⇑ start as Int)
(⊢ (#%plain-app- in-naturals- start-) : #,(mk-Sequence- (list Int+)))])
(define-typed-syntax in-vector
[(_ e)
#:with [e- (ty)] (⇑ e as Vector)
(⊢ (#%plain-app- in-vector- e-) : #,(mk-Sequence- #'(ty)))])
(define-typed-syntax in-list
[(_ e)
#:with [e- (ty)] (⇑ e as List)
(⊢ (#%plain-app- in-list- e-) : #,(mk-Sequence- #'(ty)))])
(define-typed-syntax in-lines
[(_ e)
#:with e- (⇑ e as String)
(⊢ (#%plain-app- in-lines- (#%plain-app- open-input-string- e-)) : #,(mk-Sequence- (list String+)))])
(define-typed-syntax for
[(_ ([x:id e]...) b ... body)
#:with ([e- (ty)] ...) (⇑s (e ...) as Sequence)
#:with [(x- ...) (b- ... body-) (ty_b ... ty_body)]
(infers/ctx+erase #'([x : ty] ...) #'(b ... body))
(⊢ (for- ([x- e-] ...) b- ... body-) : #,Unit+)])
(define-typed-syntax for*
[(_ ([x:id e]...) body)
#:with ([e- (ty)] ...) (⇑s (e ...) as Sequence)
#:with [(x- ...) body- ty_body] (infer/ctx+erase #'([x : ty] ...) #'body)
(⊢ (for*- ([x- e-] ...) body-) : #,Unit+)])
(define-typed-syntax for/list
[(_ ([x:id e]...) body)
#:with ([e- (ty)] ...) (⇑s (e ...) as Sequence)
#:with [(x- ...) body- ty_body] (infer/ctx+erase #'([x : ty] ...) #'body)
(⊢ (for/list- ([x- e-] ...) body-) : #,(mk-List- #'(ty_body)))])
(define-typed-syntax for/vector
[(_ ([x:id e]...) body)
#:with ([e- (ty)] ...) (⇑s (e ...) as Sequence)
#:with [(x- ...) body- ty_body] (infer/ctx+erase #'([x : ty] ...) #'body)
(⊢ (for/vector- ([x- e-] ...) body-) : #,(mk-Vector- #'(ty_body)))])
(define-typed-syntax for*/vector
[(_ ([x:id e]...) body)
#:with ([e- (ty)] ...) (⇑s (e ...) as Sequence)
#:with [(x- ...) body- ty_body] (infer/ctx+erase #'([x : ty] ...) #'body)
(⊢ (for*/vector- ([x- e-] ...) body-) : #,(mk-Vector- #'(ty_body)))])
(define-typed-syntax for*/list
[(_ ([x:id e]...) body)
#:with ([e- (ty)] ...) (⇑s (e ...) as Sequence)
#:with [(x- ...) body- ty_body] (infer/ctx+erase #'([x : ty] ...) #'body)
(⊢ (for*/list- ([x- e-] ...) body-) : #,(mk-List- #'(ty_body)))])
(define-typed-syntax for/fold
[(_ ([acc init]) ([x:id e] ...) body)
#:with [init- ty_init] (infer+erase #`(pass-expected init #,this-syntax))
#:with ([e- (ty)] ...) (⇑s (e ...) as Sequence)
#:with [(acc- x- ...) body- ty_body]
(infer/ctx+erase #'([acc : ty_init][x : ty] ...) #'body)
#:fail-unless (typecheck? #'ty_body #'ty_init)
(type-error #:src stx
#:msg
"for/fold: Type of body and initial accumulator must be the same, given ~a and ~a"
#'ty_init #'ty_body)
(⊢ (for/fold- ([acc- init-]) ([x- e-] ...) body-) : ty_body)])
(define-typed-syntax for/hash
[(_ ([x:id e]...) body)
#:with ([e- (ty)] ...) (⇑s (e ...) as Sequence)
#:with [(x- ...) body- (~× ty_k ty_v)]
(infer/ctx+erase #'([x : ty] ...) #'body)
(⊢ (for/hash- ([x- e-] ...)
(let-values- ([(t) body-])
(#%plain-app- values- (#%plain-app- car- t) (#%plain-app- cadr- t))))
: #,(mk-Hash- #'(ty_k ty_v)))])
(define-typed-syntax for/sum
[(_ ([x:id e]...
(~optional (~seq #:when guard) #:defaults ([guard #'(ext-stlc:#%datum . #t)])))
body)
#:with ([e- (ty)] ...) (⇑s (e ...) as Sequence)
#:with [(x- ...) (guard- body-) (_ ty_body)]
(infers/ctx+erase #'([x : ty] ...) #'(guard body))
#:when (Int? #'ty_body)
(⊢ (for/sum- ([x- e-] ... #:when guard-) body-) : #,Int+)])
; printing and displaying
(define-typed-syntax printf
[(_ str e ...)
#:with s- (⇑ str as String)
#:with ([e- ty] ...) (infers+erase #'(e ...))
(⊢ (#%plain-app- printf- s- e- ...) : #,Unit+)])
(define-typed-syntax format
[(_ str e ...)
#:with s- (⇑ str as String)
#:with ([e- ty] ...) (infers+erase #'(e ...))
(⊢ (#%plain-app- format- s- e- ...) : #,String+)])
(define-typed-syntax display
[(_ e)
#:with [e- _] (infer+erase #'e)
(⊢ (#%plain-app- display- e-) : #,Unit+)])
(define-typed-syntax displayln
[(_ e)
#:with [e- _] (infer+erase #'e)
(⊢ (#%plain-app- displayln- e-) : #,Unit+)])
(provide (typed-out/unsafe [newline : (→ Unit)]))
(define-typed-syntax list->vector
[(_ e)
#:with [e- (ty)] (⇑ e as List)
(⊢ (#%plain-app- list->vector- e-) : #,(mk-Vector- #'(ty)))])
(define-typed-syntax let
[(_ name:id (~datum :) ty:type ~! ([x:id e] ...) b ... body)
#:with ([e- ty_e] ...) (infers+erase #'(e ...))
#:with [(name- . xs-) (body- ...) (_ ... ty_body)]
(infers/ctx+erase #'([name : (→ ty_e ... ty.norm)][x : ty_e] ...)
#'(b ... body))
#:fail-unless (typecheck? #'ty_body #'ty.norm)
(format "type of let body ~a does not match expected typed ~a"
(type->str #'ty_body) (type->str #'ty))
(⊢ (letrec-values- ([(name-) (#%plain-lambda- xs- body- ...)])
(name- e- ...))
: ty_body)]
[(_ ([x:id e] ...) body ...)
#'(ext-stlc:let ([x e] ...) (begin/tc body ...))])
(define-typed-syntax let*
[(_ ([x:id e] ...) body ...)
#'(ext-stlc:let* ([x e] ...) (begin/tc body ...))])
(define-typed-syntax begin/tc #:export-as begin
[(_ body ... b)
#:with b_ann #`(pass-expected b #,this-syntax)
#'(ext-stlc:begin body ... b_ann)])
;; hash
(define-type-constructor Hash #:arity = 2)
(define-typed-syntax in-hash
[(_ e)
#:with [e- (ty_k ty_v)] (⇑ e as Hash)
(⊢ (#%plain-app- map-
(#%plain-lambda- (k+v)
(#%plain-app- list- (#%plain-app- car- k+v) (#%plain-app- cdr- k+v)))
(#%plain-app- hash->list- e-))
; (⊢ (hash->list e-)
: #,(mk-Sequence- (list (mk-×- #'(ty_k ty_v)))))])
; mutable hashes
(define-typed-syntax hash
[(_ (~and tys {ty_key:type ty_val:type}))
#:when (brace? #'tys)
(⊢ (#%plain-app- make-hash-) : #,(mk-Hash- #'(ty_key.norm ty_val.norm)))]
[(_ (~seq k v) ...)
#:with ([k- ty_k] ...) (infers+erase #'(k ...))
#:with ([v- ty_v] ...) (infers+erase #'(v ...))
#:when (same-types? #'(ty_k ...))
#:when (same-types? #'(ty_v ...))
#:with ty_key (stx-car #'(ty_k ...))
#:with ty_val (stx-car #'(ty_v ...))
(⊢ (#%plain-app- make-hash- (#%plain-app- list- (#%plain-app- cons- k- v-) ...)) : #,(mk-Hash- #'(ty_key ty_val)))])
(define-typed-syntax hash-set!
[(_ h k v)
#:with [h- (ty_key ty_val)] (⇑ h as Hash)
#:with [k- ty_k] (infer+erase #'k)
#:with [v- ty_v] (infer+erase #'v)
#:when (typecheck? #'ty_k #'ty_key)
#:when (typecheck? #'ty_v #'ty_val)
(⊢ (#%plain-app- hash-set!- h- k- v-) : #,Unit+)])
(define-typed-syntax hash-ref/tc #:export-as hash-ref
[(_ h k) #'(hash-ref/tc h k (ext-stlc:#%datum . #f))]
[(_ h k fail)
#:with [h- (ty_key ty_val)] (⇑ h as Hash)
#:with [k- ty_k] (infer+erase #'k)
#:when (typecheck? #'ty_k #'ty_key)
#:with (fail- _) (infer+erase #'fail) ; default val can be any
(⊢ (#%plain-app- hash-ref- h- k- fail-) : ty_val)])
(define-typed-syntax hash-has-key?
[(_ h k)
#:with [h- (ty_key _)] (⇑ h as Hash)
#:with [k- ty_k] (infer+erase #'k)
#:when (typecheck? #'ty_k #'ty_key)
(⊢ (#%plain-app- hash-has-key?- h- k-) : #,Bool+)])
(define-typed-syntax hash-count
[(_ h)
#:with [h- _] (⇑ h as Hash)
(⊢ (#%plain-app- hash-count- h-) : #,Int+)])
(define-base-type String-Port)
(define-base-type Input-Port)
(provide (typed-out/unsafe [open-output-string : (→ String-Port)]
[get-output-string : (→ String-Port String)]
[string-upcase : (→ String String)]))
(define-typed-syntax write-string/tc #:export-as write-string
[(_ str out)
#'(write-string/tc str out (ext-stlc:#%datum . 0) (string-length/tc str))]
[(_ str out start end)
#:with str- (⇑ str as String)
#:with out- (⇑ out as String-Port)
#:with start- (⇑ start as Int)
#:with end- (⇑ end as Int)
(⊢ (#%plain-app- write-string- str- out- start- end-) : #,Unit+)])
(define-typed-syntax string-length/tc #:export-as string-length
[(_ str)
#:with str- (⇑ str as String)
(⊢ (string-length- str-) : Int)])
(provide (typed-out/unsafe [make-string : (→ Int String)]
[string-set! : (→ String Int Char Unit)]
[string-ref : (→ String Int Char)]))
(define-typed-syntax string-copy!/tc #:export-as string-copy!
[(_ dest dest-start src)
#'(string-copy!/tc
dest dest-start src (ext-stlc:#%datum . 0) (string-length/tc src))]
[(_ dest dest-start src src-start src-end)
#:with dest- (⇑ dest as String)
#:with src- (⇑ src as String)
#:with dest-start- (⇑ dest-start as Int)
#:with src-start- (⇑ src-start as Int)
#:with src-end- (⇑ src-end as Int)
(⊢ (#%plain-app- string-copy!- dest- dest-start- src- src-start- src-end-) : #,Unit+)])
(provide (typed-out/unsafe [fl+ : (→ Float Float Float)]
[fl- : (→ Float Float Float)]
[fl* : (→ Float Float Float)]
[fl/ : (→ Float Float Float)]
[fl= : (→ Float Float Bool)]
[flsqrt : (→ Float Float)]
[flceiling : (→ Float Float)]
[inexact->exact : (→ Float Int)]
[exact->inexact : (→ Int Float)]
[char->integer : (→ Char Int)]
[real->decimal-string : (→ Float Int String)]
[fx->fl : (→ Int Float)]))
(define-typed-syntax quotient+remainder
[(_ x y)
#:with x- (⇑ x as Int)
#:with y- (⇑ y as Int)
(⊢ (#%plain-app- call-with-values- (#%plain-lambda- () (#%plain-app- quotient/remainder- x- y-)) list-)
: #,(mk-×- (list Int+ Int+)))])
(provide (typed-out/unsafe [quotient : (→ Int Int Int)]))
(define-typed-syntax set!
[(_ x:id e)
#:with [x- ty_x] (infer+erase #'x)
#:with [e- ty_e] (infer+erase #'e)
#:when (typecheck? #'ty_e #'ty_x)
(⊢ (set!- x- e-) : #,Unit+)])
(define-typed-syntax provide-type [(_ ty ...) #'(provide- ty ...)])
(define-typed-syntax mlish-provide #:export-as provide
[(_ x:id ...)
#:with ([x- ty_x] ...) (infers+erase #'(x ...))
; TODO: use hash-code to generate this tmp
#:with (x-ty ...) (stx-map (lambda (y) (format-id y "~a-ty" y)) #'(x ...))
#'(begin-
(provide- x ...)
(stlc+rec-iso:define-type-alias x-ty ty_x) ...
(provide- x-ty ...))])
(define-typed-syntax require-typed
[(_ x:id ... #:from mod)
#:with (x-ty ...) (stx-map (lambda (y) (format-id y "~a-ty" y)) #'(x ...))
#:with (x- ...) (generate-temporaries #'(x ...))
#'(begin-
(require- (rename-in- (only-in- mod x ... x-ty ...) [x x-] ...))
(define-typed-variable-rename x ≫ x- : x-ty) ...)])
(define-base-type Regexp)
(provide (typed-out/unsafe [regexp-match : (→ Regexp String (List String))]
[regexp : (→ String Regexp)]))
(define-typed-syntax equal?
[(_ e1 e2)
#:with [e1- ty1] (infer+erase #'e1)
#:with [e2- ty2] (infer+erase #'(add-expected e2 ty1))
#:fail-unless (typecheck? #'ty1 #'ty2) "arguments to equal? have different types"
(⊢ (#%plain-app- equal?- e1- e2-) : #,Bool+)])
(define-syntax (inst stx)
(syntax-parse stx
[(_ e ty ...)
#:with [ee tyty] (infer+erase #'e)
#:with [e- ty_e] (infer+erase #'(sysf:inst e ty ...))
#:with ty_out (cond
[(→? #'ty_e) (mk-∀- #'() #'(ty_e))]
[(=>? #'ty_e) (mk-∀- #'() #'(ty_e))]
[else #'ty_e])
(⊢ e- : ty_out)]))
(define-typed-syntax read
[(_)
(⊢ (let-values- ([(x) (#%plain-app- read-)])
(cond- [(#%plain-app- eof-object?- x) ""]
[(#%plain-app- number?- x) (#%plain-app- number->string- x)]
[(#%plain-app- symbol?- x) (#%plain-app- symbol->string- x)])) : #,String+)])
(begin-for-syntax
;; - this function should be wrapped with err handlers,
;; for when an op with the specified generic op and input types does not exist,
;; otherwise, will get "unbound id" err with internal mangled id
;; - gen-op must be identifier, eg should already have proper context
;; and mangled-op is selected based on input types,
;; ie, dispatch to different concrete fns based on input tpyes
;; TODO: currently using input types only, but sometimes may need output type
;; eg, Read typeclass, this is currently unsupported
;; - need to use expected-type?
(define (lookup-op gen-op tys)
(define (transfer-gen-op-ctx o) (format-id gen-op "~a" o))
(define (transfer-gen-op-ctxs os) (stx-map transfer-gen-op-ctx os))
(syntax-parse tys
;; TODO: for now, only handle uniform tys, ie tys must be all
;; tycons or all base types or all tyvars
;; tycon --------------------------------------------------
;; - recur on ty-args
[((~Any tycon ty-arg ...) ...)
;; 1) look up concrete op corresponding to generic op and input tys
#:with [conc-op ty-conc-op] (infer+erase (mangle gen-op #'(tycon ...)))
;; 2) compute sub-ops based on TC constraints
;; (will include gen-op --- for smaller type)
#:with (~∀ Xs (~=> TC ... (~ext-stlc:→ . ty-args))) #'ty-conc-op
#:with (~TCs ([op _] ...) ...) #'(TC ...) ; order matters, must match order of arg types
#:with ((sub-op ...) ...) (stx-map transfer-gen-op-ctxs #'((op ...) ...))
;; 3) recursively call lookup-op for each subop and input ty-args
(⊢ (conc-op
#,@(apply stx-appendmap
(lambda (ops . tys) (stx-map (lambda (o) (lookup-op o tys)) ops))
#'((sub-op ...) ...)
(syntax->list #'((ty-arg ...) ...))))
; 4) drop the TCs in result type, the proper subops are already applied
: #,(mk-∀- #'Xs (list (mk-→- #'ty-args))))]
;; base type --------------------------------------------------
[(((~literal #%plain-app) tag) ...) (expand/stop (mangle gen-op #'(tag ...)))]
;; tyvars --------------------------------------------------
[_ (expand/stop (mangle gen-op tys))]))
(define (get-type-tag t)
(syntax-parse t
[((~literal #%plain-app) tycons . _) #'tycons]
[X:id #'X]
[_ (type-error #:src t #:msg "Can't get internal id: ~a" t)]))
(define (get-type-tags ts)
(stx-map get-type-tag ts))
(define (get-fn-ty-in-tags ty-fn)
(syntax-parse ty-fn
[(~∀ _ (~ext-stlc:→ ty_in ... _))
(get-type-tags #'(ty_in ...))]
[(~∀ _ (~=> _ ... (~ext-stlc:→ ty_in ... _)))
(get-type-tags #'(ty_in ...))]))
(define (TC-exists? TC #:ctx [ctx TC]) ; throws exn if fail
(syntax-parse TC
[(~TC-base [gen-op ty-op] . _) ; only need 1st op
(with-handlers
([exn:fail:syntax:unbound?
(lambda (e)
(type-error #:src ctx
#:msg "No instance defined for ~a" TC))])
(expand/df
(mangle (format-id ctx "~a" #'gen-op)
(get-fn-ty-in-tags #'ty-op))))]))
(define (TCs-exist? TCs #:ctx [ctx TCs])
(stx-map (lambda (tc) (TC-exists? tc #:ctx ctx)) TCs)))
;; adhoc polymorphism ---------------------------------------------------------
;; lifted transformer fns, to avoid stx-parse expansion overhead
(begin-for-syntax
;; TODO: can this just be variable-like-transformer?
(define (make-typeclass-op-transformer)
(syntax-parser
[(o . es)
#:with ([e- ty_e] ...) (infers+erase #'es)
#:with out-op
(with-handlers
([exn:fail:syntax:unbound?
(lambda (e)
(type-error #:src #'o
#:msg (format
"~a operation undefined for input types: ~a"
(syntax->datum #'o)
(types->str #'(ty_e ...)))))])
(lookup-op #'o #'(ty_e ...)))
#:with app (datum->syntax #'o '#%app)
(datum->syntax this-syntax (cons #'app (cons #'out-op #'(e- ...))))]))
(define (make-typeclass-transformer TCs ops+tys Xs Name-stx)
(define/syntax-parse (TC ...) TCs)
(define/syntax-parse Name Name-stx)
(syntax-parser
[(_ . rst)
#:when (= (stx-length Xs) (stx-length #'rst))
(add-orig
(substs #'rst Xs #`(=> TC ... #,(mk-type ops+tys)))
#'(Name . rst))])))
;; TODO: make this a formal type?
;; - or at least define a pattern expander - DONE 2016-05-01
;; A TC is a #'(=> subclassTC ... ([generic-op gen-op-ty] ...))
(define-syntax (define-typeclass stx)
(syntax-parse stx
[(~or (_ TC ... (~datum =>) (Name X ...) [op (~datum :) ty] ...)
(~and (_ (Name X ...) [op (~datum :) ty] ...) ; no subclass
(~parse (TC ...) #'())))
#'(begin-
(define-syntax- op (make-typeclass-op-transformer)) ...
(define-syntax- Name
(make-typeclass-transformer
#'(TC ...) #'(#%plain-app- (#%plain-app- 'op ty) ...) #'(X ...) #'Name)))]))
(define-syntax (define-instance stx)
(syntax-parse stx
;; base type, possibly with subclasses ------------------------------------
[(_ (Name ty ...) [generic-op concrete-op] ...)
#:with (~=> TC ... (~TC [generic-op-expected ty-concrete-op-expected] ...))
(expand/df #'(Name ty ...))
#:when (TCs-exist? #'(TC ...) #:ctx stx)
#:fail-unless (set=? (syntax->datum #'(generic-op ...))
(syntax->datum #'(generic-op-expected ...)))
(type-error #:src stx
#:msg (format "Type class instance ~a incomplete, missing: ~a"
(syntax->datum #'(Name ty ...))
(string-join
(map symbol->string
(set-subtract (syntax->datum #'(generic-op-expected ...))
(syntax->datum #'(generic-op ...))))
", ")))
;; sort, using order from define-typeclass
#:with ([generic-op-sorted concrete-op-sorted] ...)
(stx-map
(lambda (expected-op)
(stx-findf
(lambda (gen+conc)
(equal? (syntax->datum (stx-car gen+conc))
(syntax->datum expected-op)))
#'([generic-op concrete-op] ...)))
#'(generic-op-expected ...))
;; typecheck type of given concrete-op with expected type from define-typeclass
#:with ([concrete-op+ ty-concrete-op] ...) (infers+erase #'(concrete-op-sorted ...))
#:fail-unless (typechecks? #'(ty-concrete-op ...) #'(ty-concrete-op-expected ...))
(mk-app-err-msg (syntax/loc stx (#%plain-app (Name ty ...) concrete-op ...))
#:expected #'(ty-concrete-op-expected ...)
#:given #'(ty-concrete-op ...)
#:action "defining typeclass instance"
#:name (format "~a" (syntax->datum #'(Name ty ...))))
;; generate mangled name from tags in input types
#:with (ty_in-tags ...) (stx-map get-fn-ty-in-tags #'(ty-concrete-op-expected ...))
;; use input types
#:with (mangled-op ...) (stx-map mangle #'(generic-op ...) #'(ty_in-tags ...))
#'(begin-
(define-syntax mangled-op
(make-variable-like-transformer
(assign-type #'concrete-op+ #'ty-concrete-op-expected))) ...)]
;; tycon, possibly with subclasses -----------------------------------------
[(_ TC ... (~datum =>) (Name ty ...) [generic-op concrete-op] ...)
#:with (X ...) (compute-tyvars #'(ty ...))
;; ok to drop TCsub ...? I think yes
;; - the same TCsubs will be part of TC+,
;; so proper op will be looked up, depending on input args,
;; using inherited ops in TC+
;; This is assuming Name and TC ... are the same typeclass
;; Won't work for, eg (TC1 (List X)) that depends on some other (TC2 X)
#:with (Xs+
(TC+ ...
(~=> TCsub ...
(~TC [generic-op-expected ty-concrete-op-expected] ...))))
(expands/tvctx #'(TC ... (Name ty ...)) #'(X ...) #:stop-list? #f)
#:when (TCs-exist? #'(TCsub ...) #:ctx stx)
;; simulate as if the declared concrete-op* has TC ... predicates
;; TODO: fix this manual deconstruction and assembly
#:with ((app fa (lam _ ei (app2 lst ty_fn))) ...) #'(ty-concrete-op-expected ...)
#:with (ty-concrete-op-expected-withTC ...)
(stx-map (current-type-eval) #'((app fa (lam Xs+ ei (app2 lst (=> TC+ ... ty_fn)))) ...))
; (stx-map (lambda (t) (mk-∀- #'Xs+ (mk-=>- #`(TC+ ... #,t)))) #'(ty_fn ...))
#:fail-unless (set=? (syntax->datum #'(generic-op ...))
(syntax->datum #'(generic-op-expected ...)))
(type-error #:src stx
#:msg (format "Type class instance ~a incomplete, missing: ~a"
(syntax->datum #'(Name ty ...))
(string-join
(map symbol->string
(set-subtract (syntax->datum #'(generic-op-expected ...))
(syntax->datum #'(generic-op ...))))
", ")))
;; - sort, using order from define-typeclass
;; - insert TC ... if lambda
#:with ([generic-op-sorted concrete-op-sorted] ...)
(stx-map
(lambda (expected-op)
(syntax-parse
(stx-findf
(lambda (gen+conc)
(equal? (syntax->datum (stx-car gen+conc))
(syntax->datum expected-op)))
#'([generic-op concrete-op] ...))
[(g c)
(syntax-parse #'c
;; add TCs to (unexpanded) lambda
[((~and lam (~literal liftedλ)) (args ...) . body)
#'(g (lam (args ... #:where TC ...) . body))]
[_ #'(g c)])]))
#'(generic-op-expected ...))
;; ;; for now, dont expand (and typecheck) concrete-op
;; #:with ([concrete-op+ ty-concrete-op] ...) (infers+erase #'(concrete-op ...))
;; #:when (typechecks? #'(ty-concrete-op ...) #'(ty-concrete-op-expected ...))
;; TODO: right now, dont recur to get nested tags
;; but may need to do so, ie if an instance needs to define more than one concrete op,
;; eg (define-instance (Eq (List Int)) ...)
#:with (ty_in-tags ...) (stx-map get-fn-ty-in-tags #'(ty-concrete-op-expected ...))
#:with (mangled-op ...) (stx-map mangle #'(generic-op ...) #'(ty_in-tags ...))
;; need a name for concrete-op because concrete-op and generic-op may be
;; mutually recursive, eg (Eq (List X))
#:with (f ...) (generate-temporaries #'(concrete-op-sorted ...))
#'(begin-
(define- f concrete-op-sorted) ...
(define-typed-variable-rename mangled-op ≫ f
: ty-concrete-op-expected-withTC) ...)]))
| true |
21c4d61082b73b502901c202208662ca4bda3dbd | 25e9e3c3626e37ed570b01128bff05d327d6351a | /examples/skeeterize.rkt | 437fe0dd97ca3530166847fd495a095810e4972a | [
"MIT"
] | permissive | johnstonskj/racket-playground | de4989ac38a3340900422bc88b3aa478e2ffd9c4 | 8285d2580a7f6fcd61b2fec1427cd6d84aaeab1c | refs/heads/master | 2022-07-02T18:49:12.767384 | 2022-06-20T18:50:57 | 2022-06-20T18:51:05 | 134,638,912 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,504 | rkt | skeeterize.rkt | #lang racket
;; We create a structure that supports the
;; prop:exn:srcloc protocol. It carries
;; with it the location of the syntax that
;; is guilty.
(define-struct (exn:fail:he-who-shall-not-be-named
exn:fail)
(a-srcloc)
#:property prop:exn:srclocs
(lambda (a-struct)
(match a-struct
[(struct exn:fail:he-who-shall-not-be-named
(msg marks a-srcloc))
(list a-srcloc)])))
;; We can play with this by creating a form that
;; looks at identifiers, and only flags specific ones.
(define-syntax (skeeterize stx)
(syntax-case stx ()
[(_ expr)
(cond
[(and (identifier? #'expr)
(eq? (syntax-e #'expr) 'voldemort))
(quasisyntax/loc stx
(raise (make-exn:fail:he-who-shall-not-be-named
"oh dear don't say his name"
(current-continuation-marks)
(srcloc '#,(syntax-source #'expr)
'#,(syntax-line #'expr)
'#,(syntax-column #'expr)
'#,(syntax-position #'expr)
'#,(syntax-span #'expr)))))]
[else
;; Otherwise, leave the expression alone.
#'expr])]))
(define (f x)
(* (skeeterize x) x))
(define (g voldemort)
(* (skeeterize voldemort) voldemort))
(define (h voldemort)
(* (skeeterize voldemort "hi") voldemort))
;; Examples:
(f 7)
(g 7)
(h 7)
;; The error should highlight the use
;; of the one-who-shall-not-be-named
;; in g.
| true |
8d66abfc4a956d4422558f06414cdbd8821b97e8 | 8e0ccbb121927b3258afa5fb50f50963ed2f915d | /a5.rkt | 878bd60a0132799782662c51ce5316e9b1bc8caa | [] | no_license | gzxultra/B521_Programming_Language_Principles | 00976a88619456f67a89f0c9042bcf753d7cd68f | 00c60a119bdc52a7501114bb76e558a9d7ec0cae | refs/heads/master | 2020-08-02T12:36:13.856774 | 2018-12-06T14:48:04 | 2018-12-06T14:48:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 5,562 | rkt | a5.rkt | #lang racket
(define (empty-env)
(lambda (y) (error "unbound variable ~s" y)))
(define (val-of-cbv exp env)
(define (apply-env env a)
(env a))
(define (ext-env env k v)
(lambda (arg) (if (eqv? arg k) v (env arg))))
(define (make-closure x body env)
(lambda (arg) (let ((barg (box arg))) (val-of-cbv body (ext-env env x barg)))))
(define (apply-closure clos x)
(clos x))
(match exp
[`(quote ()) '()]
[`,b #:when (boolean? b) b]
[`,n #:when (number? n) n]
[`(zero? ,n) (zero? (val-of-cbv n env))]
[`(null? ,n) (null? (val-of-cbv n env))]
[`(add1 ,n) (add1 (val-of-cbv n env))]
[`(sub1 ,n) (sub1 (val-of-cbv n env))]
[`(* ,n1 ,n2) (* (val-of-cbv n1 env) (val-of-cbv n2 env))]
[`(set! ,x ,v) (set-box! (apply-env env x) (val-of-cbv v env))]
[`(cons^ ,a ,d) (cons (lambda () (val-of-cbv a env)) (lambda () (val-of-cbv d env)))]
[`(car^ ,ll) ((car (val-of-cbv ll env)))]
[`(cdr^ ,ll) ((cdr (val-of-cbv ll env)))]
[`(cons ,a ,d) (cons (val-of-cbv a env) (val-of-cbv d env))]
[`(car ,l) (car (val-of-cbv l env))]
[`(cdr ,l) (cdr (val-of-cbv l env))]
[`(if ,test ,conseq ,alt) (if (val-of-cbv test env)
(val-of-cbv conseq env)
(val-of-cbv alt env))]
[`(begin2 ,e1 ,e2) (begin (val-of-cbv e1 env) (val-of-cbv e2 env))]
[`(random ,n) (random (val-of-cbv n env))]
[`,y #:when (symbol? y) (unbox (apply-env env y))]
[`(let ((,x ,e)) ,body) (let ((v (box (val-of-cbv e env)))) (val-of-cbv body (ext-env env x v)))]
[`(lambda (,x) ,body) (make-closure x body env)]
[`(,rator ,rand) (apply-closure (val-of-cbv rator env)
(val-of-cbv rand env))]))
(define (val-of-cbr exp env)
(define (apply-env env a)
(env a))
(define (ext-env env k v)
(lambda (arg) (if (eqv? k arg) v (env arg))))
(define (make-closure x body env)
(lambda (arg) (val-of-cbr body (ext-env env x arg))))
(define (apply-closure clos x)
(clos x))
(match exp
[`,b #:when (boolean? b) b]
[`,n #:when (number? n) n]
[`(zero? ,n) (zero? (val-of-cbr n env))]
[`(sub1 ,n) (sub1 (val-of-cbr n env))]
[`(* ,n1 ,n2) (* (val-of-cbr n1 env) (val-of-cbr n2 env))]
[`(set! ,x ,a) (set-box! (apply-env env x) (val-of-cbr a env))]
[`(if ,test ,conseq ,alt) (if (val-of-cbr test env)
(val-of-cbr conseq env)
(val-of-cbr alt env))]
[`(begin2 ,e1 ,e2) (begin (val-of-cbr e1 env) (val-of-cbr e2 env))]
[`(random ,n) (random (val-of-cbr n env))]
[`,y #:when (symbol? y) (unbox (apply-env env y))]
[`(lambda (,x) ,body) (make-closure x body env)]
[`(,rator ,x) #:when (symbol? x) (apply-closure (val-of-cbr rator env) (apply-env env x))]
[`(,rator ,rand) (apply-closure (val-of-cbr rator env)
(box (val-of-cbr rand env)))]))
(define (val-of-cbname exp env)
(define (apply-env env a)
(env a))
(define (ext-env env k v)
(lambda (arg) (if (eqv? k arg) v (env arg))))
(define (make-closure x body env)
(lambda (arg) (val-of-cbname body (ext-env env x arg))))
(define (apply-closure clos x)
(clos x))
(match exp
[`,b #:when (boolean? b) b]
[`,n #:when (number? n) n]
[`(zero? ,n) (zero? (val-of-cbname n env))]
[`(sub1 ,n) (sub1 (val-of-cbname n env))]
[`(* ,n1 ,n2) (* (val-of-cbname n1 env) (val-of-cbname n2 env))]
[`(if ,test ,conseq ,alt) (if (val-of-cbname test env)
(val-of-cbname conseq env)
(val-of-cbname alt env))]
[`(begin2 ,e1 ,e2) (begin (val-of-cbname e1 env) (val-of-cbname e2 env))]
[`(random ,n) (random (val-of-cbname n env))]
[`,y #:when (symbol? y) ((apply-env env y))]
[`(lambda (,x) ,body) (make-closure x body env)]
[`(,rator ,x) #:when (symbol? x) (apply-closure (val-of-cbname rator env) (apply-env env x))]
[`(,rator ,rand) (apply-closure (val-of-cbname rator env)
(lambda () (val-of-cbname rand env)))]))
(define (val-of-cbneed exp env)
(define (apply-env env a)
(env a))
(define (ext-env env k v)
(lambda (arg) (if (eqv? k arg) v (env arg))))
(define (make-closure x body env)
(lambda (arg) (val-of-cbneed body (ext-env env x arg))))
(define (apply-closure clos x)
(clos x))
(match exp
[`,b #:when (boolean? b) b]
[`,n #:when (number? n) n]
[`(zero? ,n) (zero? (val-of-cbneed n env))]
[`(sub1 ,n) (sub1 (val-of-cbneed n env))]
[`(* ,n1 ,n2) (* (val-of-cbneed n1 env) (val-of-cbneed n2 env))]
[`(if ,test ,conseq ,alt) (if (val-of-cbneed test env)
(val-of-cbneed conseq env)
(val-of-cbneed alt env))]
[`(begin2 ,e1 ,e2) (begin (val-of-cbneed e1 env) (val-of-cbneed e2 env))]
[`(random ,n) (random (val-of-cbneed n env))]
[`,y #:when (symbol? y) (let* ((b (apply-env env y)) (v ((unbox b)))) (begin (set-box! b (lambda () v)) v))]
[`(lambda (,x) ,body) (make-closure x body env)]
[`(,rator ,x) #:when (symbol? x) (apply-closure (val-of-cbneed rator env) (apply-env env x))]
[`(,rator ,rand) (apply-closure (val-of-cbneed rator env)
(box (lambda () (val-of-cbneed rand env))))])) | false |
636223f8ffcd29304b4a0e4922a7fe1f743512c0 | 16eb81c19bb81bf3e46664989ef4f33a9165bd11 | /examples/2-colorfade.rkt | c030a65706e8b4fb238e770000db246c88cb4130 | [
"Apache-2.0"
] | permissive | videolang/typed-video | 4fefee5d8bb51a8ff7fe1abf80af6eed290aca5e | 8e07fa76d7231b1f386456ad54be2411b79e4d06 | refs/heads/master | 2021-03-27T11:03:34.830622 | 2018-05-01T18:28:10 | 2018-05-01T19:27:12 | 81,873,708 | 2 | 2 | null | null | null | null | UTF-8 | Racket | false | false | 378 | rkt | 2-colorfade.rkt | #lang typed/video
(require turnstile/examples/tests/rackunit-typechecking)
(define g75 (color "green" #:length 75))
(check-type g75 : (Producer 75))
(define fade25 (fade-transition #:length 25))
(check-type fade25 : (Transition 25))
(define b75 (color "blue" #:length 75))
(check-type b75 : (Producer 75))
(check-type (playlist g75 fade25 b75) : (Producer 125))
g75
fade25
b75
| false |
1396f86b1b6f25935aeb6722d4a70d99a83f8339 | 204668b065a065cd7a76a253b4a6029d7cd64453 | /www/notes/hustle.scrbl | 7057ed4d7150a2799a3d68358c7ce7d3d9b5e475 | [
"AFL-3.0"
] | permissive | shalomlhi/www | 9c4cb29ea28132328efeeff8e57e321e57458678 | 8c5cd01e39aec2fbf0fb350cd56a406878a485ed | refs/heads/main | 2023-02-24T23:54:15.886442 | 2021-01-30T14:23:10 | 2021-01-30T14:23:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 15,175 | scrbl | hustle.scrbl | #lang scribble/manual
@(require (for-label (except-in racket ...)))
@(require redex/pict
racket/runtime-path
scribble/examples
"../../langs/hustle/semantics.rkt"
"utils.rkt"
"ev.rkt"
"../fancyverb.rkt"
"../utils.rkt")
@(define codeblock-include (make-codeblock-include #'h))
@(for-each (λ (f) (ev `(require (file ,(path->string (build-path notes "hustle" f))))))
'() #;'("interp.rkt" "ast.rkt" "parse.rkt" "compile.rkt" "asm/interp.rkt" "asm/printer.rkt"))
@title[#:tag "Hustle"]{Hustle: heaps and lists}
@emph{A little and a little, collected together, become a great deal;
the heap in the barn consists of single grains, and drop and drop
makes an inundation.}
@table-of-contents[]
@verbatim|{
TODO:
* Add section introducing '()
* Describe new use of 'rbx for heap pointer
- picked a callee-saved register, therefore
save once on entry, restore once on exit (use empty stack-alignment word)
no need to do anything at C prim calls
}|
@section{Inductive data}
So far all of the data we have considered can fit in a single machine
word (64-bits). Well, integers can't, but we truncated them and only
consider, by fiat, those integers that fit into a register.
In the @bold{Hustle} language, we will add two @bold{inductively
defined data types}, boxes and pairs, which will require us to relax
this restriction.
Boxes are like unary pairs, they simply hold a value, which can be
projected out. Pairs hold two values which each can be projected out.
The new operations include constructors @racket[(box _e)] and
@racket[(cons _e0 _e1)] and projections @racket[(unbox _e)],
@racket[(car _e)], and @racket[(cdr _e)].
@margin-note{Usually boxes are @emph{mutable} data structures, like
OCaml's @tt{ref} type, but we will examine this aspect later. For now,
we treat boxes as immutable data structures.}
These features will operate like their Racket counterparts:
@ex[
(unbox (box 7))
(car (cons 3 4))
(cdr (cons 3 4))
]
We use the following grammar for Hustle:
@centered[(render-language H)]
We can model this as an AST data type:
@filebox-include-fake[codeblock "hustle/ast.rkt"]{
#lang racket
;; type Op1 = ...
;; | 'box | 'car | 'cdr | 'unbox
;; type Op2 = ...
;; | 'cons
}
@section{Meaning of Hustle programs, implicitly}
The meaning of Hustle programs is just a slight update to Grift
programs, namely we add a few new primitives.
The update to the semantics is just an extension of the semantics of
primitives:
@(judgment-form-cases #f)
@;centered[(render-judgment-form 𝑯-𝒆𝒏𝒗)]
@centered[(render-metafunction 𝑯-𝒑𝒓𝒊𝒎 #:contract? #t)]
The interpreter similarly has an update to the @racket[interp-prims]
module:
@codeblock-include["hustle/interp-prims.rkt"]
Inductively defined data is easy to model in the semantics and
interpreter because we can rely on inductively defined data at the
meta-level in math or Racket, respectively.
In some sense, the semantics and interpreter don't shed light on
how constructing inductive data works because they simply use
the mechanism of the defining language to construct inductive data.
Let's try to address that.
@section{Meaning of Hustle programs, explicitly}
Let's develop an alternative semantics and interpreter that
describes constructing inductive data without itself
constructing inductive data.
The key here is to describe explicitly the mechanisms of
memory allocation and dereference. Abstractly, memory can be
thought of as association between memory addresses and
values stored in those addresses. As programs run, there is
a current state of the memory, which can be used to look up
values (i.e. dereference memory) or to extend by making a
new association between an available address and a value
(i.e. allocating memory). Memory will be assumed to be
limited to some finite association, but we'll always assume
programs are given a sufficiently large memory to run to
completion.
In the semantics, we can model memory as a finite function
from addresses to values. The datatype of addresses is left
abstract. All that matters is we can compare them for
equality.
We now change our definition of values to make it
non-recursive:
@centered{@render-language[Hm]}
We define an alternative semantic relation equivalent to 𝑯 called
𝑯′:
@centered[(render-judgment-form 𝑯′)]
Like 𝑯, it is defined in terms of another relation. Instead
of 𝑯-𝒆𝒏𝒗, we define a similar relation 𝑯-𝒎𝒆𝒎-𝒆𝒏𝒗 that has an
added memory component both as input and out:
@centered[(render-judgment-form 𝑯-𝒎𝒆𝒎-𝒆𝒏𝒗)]
For most of the relation, the given memory σ is simply
threaded through the judgment. When interpreting a primitive
operation, we also thread the memory through a relation
analagous to 𝑯-𝒑𝒓𝒊𝒎 called 𝑯-𝒎𝒆𝒎-𝒑𝒓𝒊𝒎. The key difference
for 𝑯-𝒎𝒆𝒎-𝒑𝒓𝒊𝒎 is that @racket[cons] and @racket[box]
operations allocate memory by extending the given memory σ
and the @racket[car], @racket[cdr], and @racket[unbox]
operations dereference memory by looking up an association
in the given memory σ:
@centered[(render-metafunction 𝑯-𝒎𝒆𝒎-𝒑𝒓𝒊𝒎 #:contract? #t)]
There are only two unexplained bits at this point:
@itemlist[
@item{the metafunction
@render-term[Hm (alloc σ (v ...))] which consumes a memory
and a list of values. It produces a memory and an address
@render-term[Hm (σ_′ α)] such that @render-term[Hm σ_′] is
like @render-term[Hm σ] except it has a new association for
some @render-term[Hm α] and @render-term[Hm α] is @bold{
fresh}, i.e. it does not appear in the domain of
@render-term[Hm σ].}
@item{the metafunction @render-term[Hm (unload σ a)] used
in the conclusion of @render-term[Hm 𝑯′]. This function does
a final unloading of the answer and memory to obtain a answer
in the style of 𝑯.}]
The definition of @render-term[Hm (alloc σ (v ...))] is
omitted, since it depends on the particular representation
chosen for @render-term[Hm α], but however you choose to
represent addresses, it will be easy to define appropriately.
The definition of @render-term[Hm (unload σ a)] just traces
through the memory to reconstruct an inductive piece of data:
@centered[(render-metafunction unload #:contract? #t)]
With the semantics of explicit memory allocation and
dereference in place, we can write an interepreter to match
it closely.
We could define something @emph{very} similar to the
semantics by threading through some representation of a
finite function serving as the memory, just like the
semantics. Or we could do something that will produce the
same result but using a more concrete mechanism that is like
the actual memory on a computer. Let's consider the latter
approach.
We can use a Racket @racket[list] to model the memory.
@;{
We will use a @racket[vector] of some size to model the
memory used in a program's evaluation. We can think of
@racket[vector] as giving us a continguous array of memory
that we can read and write to using natural number indices
as addresses. The interpreter keeps track of both the
@racket[vector] and an index for the next available memory
address. Every time the interpreter allocates, it writes in
to the appropriate cell in the @racket[vector] and bumps the
current address by 1.}
@codeblock-include["hustle/interp-heap.rkt"]
The real trickiness comes when we want to model such data in an
impoverished setting that doesn't have such things, which of course is
the case in assembly.
The problem is that a value such as @racket[(box _v)] has a value
inside it. Pairs are even worse: @racket[(cons _v0 _v1)] has
@emph{two} values inside it. If each value is represented with 64
bits, it would seem a pair takes @emph{at a minimum} 128-bits to
represent (plus we need some bits to indicate this value is a pair).
What's worse, those @racket[_v0] and @racket[_v1] may themselves be
pairs or boxes. The great power of inductive data is that an
arbitrarily large piece of data can be constructed. But it would seem
impossible to represent each piece of data with a fixed set of bits.
The solution is to @bold{allocate} such data in memory, which can in
principle be arbitrarily large, and use a @bold{pointer} to refer to
the place in memory that contains the data.
@;{ Really deserves a "bit" level interpreter to bring this idea across. }
@;codeblock-include["hustle/interp.rkt"]
@section{Representing Hustle values}
The first thing do is make another distinction in the kind of values
in our language. Up until now, each value could be represented in a
register. We now call such values @bold{immediate} values.
We introduce a new category of values which are @bold{pointer} values.
We will (for now) have two types of pointer values: boxes and pairs.
So we now have a kind of hierarchy of values:
@verbatim{
- values
+ pointers (non-zero in last 3 bits)
* boxes
* pairs
+ immediates (zero in last three bits)
* integers
* characters
* booleans
* ...
}
We will represent this hierarchy by shifting all the immediates over 3
bits and using the lower 3 bits to tag things as either being
immediate (tagged @code[#:lang "racket"]{#b000}) or a box or pair.
To recover an immediate value, we just shift back to the right 3 bits.
The pointer types will be tagged in the lowest three bits. A box
value is tagged @code[#:lang "racket"]{#b001} and a pair is tagged
@code[#:lang "racket"]{#b010}. The remaining 61 bits will hold a
pointer, i.e. an integer denoting an address in memory.
The idea is that the values contained within a box or pair will be
located in memory at this address. If the pointer is a box pointer,
reading 64 bits from that location in memory will produce the boxed
value. If the pointer is a pair pointer, reading the first 64 bits
from that location in memory will produce one of the value in the pair
and reading the next 64 bits will produce the other. In other words,
constructors allocate and initialize memory. Projections dereference
memory.
The representation of pointers will follow a slightly different scheme
than that used for immediates. Let's first talk a bit about memory
and addresses.
A memory location is represented (of course, it's all we have!) as a
number. The number refers to some address in memory. On an x86
machine, memory is @bold{byte-addressable}, which means each address
refers to a 1-byte (8-bit) segment of memory. If you have an address
and you add 1 to it, you are refering to memory starting 8-bits from the
original address.
We will make a simplifying assumption and always store things in
memory in multiples of 64-bit chunks. So to go from one memory
address to the next @bold{word} of memory, we need to add 8 (1-byte
times 8 = 64 bits) to the address.
What is 8 in binary? @code[#:lang "racket"]{#b1000}
What's nice about this is that if we start from a memory location that
is ``word-aligned,'' i.e. it ends in @code[#:lang "racket"]{#b000},
then every 64-bit index also ends in @code[#:lang "racket"]{#b000}.
What this means is that @emph{every} address we'd like to represent
has @code[#:lang "racket"]{#b000} in its least signficant bits. We
can therefore freely uses these three bits to tag the type of the
pointer @emph{without needing to shift the address around}. If we
have a box pointer, we can simply zero out the box type tag to obtain
the address of the boxes content. Likewise with pairs.
So for example the following creates a box containing the value 7:
@#reader scribble/comment-reader
(racketblock
(seq (Mov 'rax (arithmetic-shift 7 imm-shift))
(Mov (Offset 'rdi 0) 'rax) ; write '7' into address held by rdi
(Mov 'rax 'rdi) ; copy pointer into return register
(Or 'rax type-box) ; tag pointer as a box
(Add 'rdi 8)) ; advance rdi one word
)
If @racket['rax] holds a box value, we can ``unbox'' it by erasing the
box tag, leaving just the address of the box contents, then
dereferencing the memory:
@#reader scribble/comment-reader
(racketblock
(seq (Xor 'rax type-box) ; erase the box tag
(Mov 'rax (Offset 'rax 0))) ; load memory into rax
)
Pairs are similar. Suppose we want to make @racket[(cons 3 4)]:
@#reader scribble/comment-reader
(racketblock
(seq (Mov 'rax (arithmetic-shift 3 imm-shift))
(Mov (Offset 'rdi 0) 'rax) ; write '3' into address held by rdi
(Mov 'rax (arithmetic-shift 4 imm-shift))
(Mov (Offset 'rdi 1) 'rax) ; write '4' into word after address held by rdi
(Mov 'rax rdi) ; copy pointer into return register
(Or 'rax type-pair) ; tag pointer as a pair
(Add 'rdi 16)) ; advance rdi 2 words
)
If @racket['rax] holds a pair value, we can project out the elements
by erasing the pair tag, leaving just the address of the pair contents,
then dereferencing either the first or second word of memory:
@#reader scribble/comment-reader
(racketblock
(seq (Xor 'rax type-pair) ; erase the pair tag
(Mov 'rax (Offset 'rax 0)) ; load car into rax
(Mov 'rax (Offset 'rax 1))) ; or... load cdr into rax
)
From here, writing the compiler for @racket[box], @racket[unbox],
@racket[cons], @racket[car], and @racket[cdr] is just a matter of
putting together pieces we've already seen such as evaluating multiple
subexpressions and type tag checking before doing projections.
@section{Allocating Hustle values}
We use a register, @racket['rdi], to hold the address of the next free
memory location in memory. To allocate memory, we simply increment
the content of @racket['rdi] by a multiple of 8. To initialize the
memory, we just write into the memory at that location. To contruct a
pair or box value, we just tag the unused bits of the address.
... will have to coordinate with the run-time system to
initialize @racket['rdi] appropriately.
@secref["hustle-run-time"]
@section{A Compiler for Hustle}
The complete compiler is given below.
@codeblock-include["hustle/compile.rkt"]
@section[#:tag "hustle-run-time"]{A Run-Time for Hustle}
The run-time system for Hustle is more involved for two main reasons:
The first is that the compiler relies on a pointer to free memory
residing in @racket['rdi]. The run-time system will be responsible
for allocating this memory and initializing the @racket['rdi]
register. To allocate memory, it uses @tt{malloc}. It passes the
pointer returned by @tt{malloc} to the @tt{entry} function. The
protocol for calling functions in C says that the first argument will
be passed in the @racket['rdi] register. Since @tt{malloc} produces
16-byte aligned addresses on 64-bit machines, @racket['rdi] is
initialized with an address that ends in @code[#:lang
"racket"]{#b000}, satisfying our assumption about addresses.
The second complication comes from printing. Now that values include
inductively defined data, the printer must recursively traverse these
values to print them.
The complete run-time system is below.
@filebox-include[fancy-c "hustle/main.c"]
| false |
4e8e2392a2507a12aa268cb71214288d9f8abba8 | 9dc73e4725583ae7af984b2e19f965bbdd023787 | /eopl-solutions/chap2/2-5.rkt | ef5e0ff9b0b06f471e01d9a9ac28c60eb09380ff | [] | no_license | hidaris/thinking-dumps | 2c6f7798bf51208545a08c737a588a4c0cf81923 | 05b6093c3d1239f06f3657cd3bd15bf5cd622160 | refs/heads/master | 2022-12-06T17:43:47.335583 | 2022-11-26T14:29:18 | 2022-11-26T14:29:18 | 83,424,848 | 6 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,036 | rkt | 2-5.rkt | #lang eopl
;;; A data-structure representation of environments
;;; Env = (empty-env) | (extend-env Var SchemeVal Env)
;;; Var = Sym
;;; empty-env : () -> Env
(define empty-env
(lambda ()'()))
;;; extend-env : Var x SchemeVal x Env -> Env
(define extend-env
(lambda (var val env)
(cons `(,var ,val) env)))
;;; apply-env : Env x Var -> SchemeVal
(define apply-env
(lambda (env search-var)
(cond
((null? env)
(report-no-binding-found search-var))
((and (pair? env) (pair? (car env)))
(let ((saved-var (caar env))
(saved-val (cdar env))
(saved-env (cdr env)))
(if (eqv? search-var saved-var)
saved-val
(apply-env saved-env search-var))))
(else
(report-invalid-env env)))))
(define report-no-binding-found
(lambda (search-var)
(eopl:error 'apply-env
"No binding for ~s" search-var)))
(define report-invalid-env
(lambda (env)
(eopl:error 'apply-env
"Bad environment: ~s" env)))
| false |
0b6a45cedd6586bebc19704ff3e14f35e9af65ee | 47dc5ce5904856bb57f5a7fe2e89772f542b1331 | /brandeis-sicp/brandeis-fact.rkt | 883b918a75c97a84c5bdc064ead602b0cb3bd1dd | [] | no_license | dvanhorn/play | d951e49fa1905050d0b2130915a5bba22ff19086 | 0bee209f013383f3a507e37779b2b0cddc063b7d | refs/heads/master | 2020-04-26T04:22:00.621949 | 2013-02-27T04:42:51 | 2013-02-27T04:42:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 734 | rkt | brandeis-fact.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 brandeis-fact) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ())))
;; Computes n!
;; Natural -> Natural
(define (factorial n)
(if (= n 0)
1
(* n (factorial (- n 1)))))
(check-expect (factorial 5) 120)
;; Computes (k n!)
;; Natural (Natural -> Natural) -> Natural
(define (factorial/cps n k)
(if (= n 0)
(k 1)
(factorial/cps (- n 1)
(λ (n-1!)
(k (* n n-1!))))))
| false |
fd60cb86dc08aa14aa61f9f41dfd2cb264419de6 | 49d98910cccef2fe5125f400fa4177dbdf599598 | /exercises-for-programmers/01-saying-hello/ex1b.rkt | 5435426a5720539c09277843b1eb304ec85b9d27 | [] | no_license | lojic/LearningRacket | 0767fc1c35a2b4b9db513d1de7486357f0cfac31 | a74c3e5fc1a159eca9b2519954530a172e6f2186 | refs/heads/master | 2023-01-11T02:59:31.414847 | 2023-01-07T01:31:42 | 2023-01-07T01:31:42 | 52,466,000 | 30 | 4 | null | null | null | null | UTF-8 | Racket | false | false | 176 | rkt | ex1b.rkt | #lang racket/base
; Challenge: Write a new version of the program without using any variables.
(display "What is your name? ")
(printf "Hello, ~a, nice to meet you!" (read))
| false |
2c26d66387ffc07a8b0e56321f8142c5ae7abba8 | 7b8ebebffd08d2a7b536560a21d62cb05d47be52 | /private/types/ordering.rkt | 6866242cd4a798362681be2439e284804425cd95 | [] | 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 | 3,038 | rkt | ordering.rkt | #lang racket/base
;;______________________________________________________________
;; ______
;; ( // _____ ____ . __ __
;; ~//~ ((_)// // / / // ((_ ((_/_
;; (_//
;;..............................................................
;; Provides generic ordering function.
;;;=============================================================
(require racket/dict
"types.rkt"
"../tools/functionals.rkt")
(provide
ordered?
(contract-out
(type-ordering (parameter/c (list: (cons: contract? Fun) ..)))
(add-to-type-ordering (->* (contract?) (contract? Fun) void?))
(symbol<? (->* (Sym Sym) #:rest (list: Sym ..) Bool))
(pair<? (->* (pair? pair?) #:rest (list: pair? ..) Bool))))
;; generic ordering function.
(define (ordered? . x)
(apply
(case-lambda
[() #t]
[(x) #t]
[(x y) (for/or ([px (in-list (dict-keys (type-ordering)))]
[i (in-naturals)]
#:when (is x px))
(for/and ([(py f) (in-dict (type-ordering))]
[j (in-range (+ i 1))]
#:when (is y py))
(and (= i j) (f x y))))]
[(x y . z) (and (ordered? x y)
(apply ordered? y z))]) x))
;; ordering for booleans #t < #f
(define (boolean<? x y) (and x (not y)))
;; ordering for symbols
(define symbol<?
(/@ string<? symbol->string))
;; ordering for pairs
(define pair<?
(orf (/@ ordered? car)
(andf (/@ equal? car)
(/@ ordered? cdr))))
(define (add-to-type-ordering type (prec-type 'last) (ord-fun (const #f)))
(type-ordering
(let ([new-type (cons type ord-fun)])
(cond
[(eq? prec-type 'last) (append (type-ordering) (list new-type))]
[(eq? prec-type 'first) (append (list new-type) (type-ordering))]
[(dict-has-key? (type-ordering) type) (type-ordering (dict-remove (type-ordering) type))
(add-to-type-ordering type prec-type ord-fun)
(type-ordering)]
[else (let next ([lst (type-ordering)])
(cond
[(null? lst) (list new-type)]
[(equal? (caar lst) prec-type) (list* (car lst)
new-type
(cdr lst))]
[else (cons (car lst) (next (cdr lst)))]))]))))
;; type-ordering = [(<type> . <ordering-function>) ... ]
;; the oreder in the list defines the order of types
;; if compared objects have the same type
;; the <ordering-function> is used to compare them.
(define type-ordering
(make-parameter (list (cons #t (const #f))
(cons #f (const #f))
(cons real? <)
(cons string? string<?)
(cons symbol? symbol<?)
(cons null? (const #f))
(cons pair? pair<?))))
| false |
8ca0c92b19d917c1d5fd81a4ad9b36926cdfb486 | 30e5578d82f77b67153d38abce61e00e80694f6e | /bitmap/composite.rkt | 577f4daf13cdbd666814b03126976d6fffb9b70d | [] | no_license | soegaard/graphics | b492b414d38d0df9ecf8bb79a56d026454df1f59 | 3d2f9a008322b541237b7cb52a9116e2f8164ef2 | refs/heads/master | 2022-11-15T11:19:58.815282 | 2020-07-11T03:52:23 | 2020-07-11T03:52:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 8,240 | rkt | composite.rkt | #lang typed/racket
(provide (except-out (all-defined-out) make-pin make-append make-append* make-superimpose make-superimpose*))
(provide (rename-out [bitmap-pin-over bitmap-pin]))
(require "constructor.rkt")
(require "digitama/composite.rkt")
(require "digitama/unsafe/composite.rkt")
(require "digitama/unsafe/convert.rkt")
(define default-pin-operator : (Parameterof Symbol) (make-parameter 'over))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define bitmap-composite : (case-> [Symbol Bitmap Complex Bitmap -> Bitmap]
[Symbol Bitmap Real Real Bitmap -> Bitmap]
[Symbol Bitmap Complex Bitmap Complex -> Bitmap]
[Symbol Bitmap Real Real Bitmap Real Real -> Bitmap])
(case-lambda
[(op bmp1 x/pt y/bmp2 bmp2/pt)
(cond [(real? y/bmp2) (bitmap-composite op bmp1 x/pt y/bmp2 bmp2/pt 0.0 0.0)]
[else (bitmap-composite op bmp1 (- x/pt bmp2/pt) y/bmp2)])]
[(op bmp1 pt bmp2)
(bitmap_composite (or (bitmap-operator->integer op) CAIRO_OPERATOR_OVER)
(bitmap-surface bmp1) (bitmap-surface bmp2)
(real->double-flonum (real-part pt)) (real->double-flonum (imag-part pt))
(bitmap-density bmp1))]
[(op bmp1 x1 y1 bmp2 x2 y2)
(bitmap_composite (or (bitmap-operator->integer op) CAIRO_OPERATOR_OVER)
(bitmap-surface bmp1) (bitmap-surface bmp2)
(- (real->double-flonum x1) (real->double-flonum x2))
(- (real->double-flonum y1) (real->double-flonum y2))
(bitmap-density bmp1))]))
(define bitmap-pin* : (-> Real Real Real Real Bitmap Bitmap * Bitmap)
;;; TODO: what if one or more bmps are larger then the base one
(lambda [x1-frac y1-frac x2-frac y2-frac bmp0 . bmps]
(cond [(null? bmps) bmp0]
[else (bitmap_pin* (or (bitmap-operator->integer (default-pin-operator)) CAIRO_OPERATOR_OVER)
(real->double-flonum x1-frac) (real->double-flonum y1-frac)
(real->double-flonum x2-frac) (real->double-flonum y2-frac)
(bitmap-surface bmp0) (map bitmap-surface bmps)
(bitmap-density bmp0))])))
(define bitmap-table : (->* (Integer (Listof Bitmap))
((Listof Superimpose-Alignment)
(Listof Superimpose-Alignment)
(Listof Nonnegative-Real)
(Listof Nonnegative-Real))
Bitmap)
(lambda [ncols bitmaps [col-aligns null] [row-aligns null] [col-gaps null] [row-gaps null]]
(cond [(or (<= ncols 0) (null? bitmaps)) (bitmap-blank)]
[else (let-values ([(maybe-nrows extra-ncols) (quotient/remainder (length bitmaps) ncols)])
(define nrows : Nonnegative-Fixnum (+ maybe-nrows (sgn extra-ncols)))
(bitmap_table (map bitmap-surface bitmaps) ncols nrows
(if (null? col-aligns) '(cc) col-aligns)
(if (null? row-aligns) '(cc) row-aligns)
(if (null? col-gaps) '(0.0) (map real->double-flonum col-gaps))
(if (null? row-gaps) '(0.0) (map real->double-flonum col-gaps))
(bitmap-density (car bitmaps))))])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define make-pin : (-> Bitmap-Composition-Operator Bitmap-Pin)
(lambda [op]
(case-lambda
[(bmp1 pt bmp2) (bitmap-composite op bmp1 (real-part pt) (imag-part pt) bmp2)]
[(bmp1 x/pt y/bmp2 bmp2/pt) (bitmap-composite op bmp1 x/pt y/bmp2 bmp2/pt)]
[(bmp1 x1 y1 bmp2 x2 y2) (bitmap-composite op bmp1 x1 y1 bmp2 x2 y2)])))
(define make-append* : (-> Symbol (-> (Listof Bitmap) [#:gapsize Real] Bitmap))
(lambda [alignment]
(define blend-mode : Integer CAIRO_OPERATOR_OVER)
(λ [bitmaps #:gapsize [delta 0.0]]
(cond [(null? bitmaps) (bitmap-blank)]
[(null? (cdr bitmaps)) (car bitmaps)]
[(and (zero? delta) (null? (cddr bitmaps)))
(let-values ([(base bmp) (values (car bitmaps) (cadr bitmaps))])
(case alignment
[(vl) (bitmap_pin blend-mode 0.0 1.0 0.0 0.0 (bitmap-surface base) (bitmap-surface bmp) (bitmap-density base))]
[(vc) (bitmap_pin blend-mode 0.5 1.0 0.5 0.0 (bitmap-surface base) (bitmap-surface bmp) (bitmap-density base))]
[(vr) (bitmap_pin blend-mode 1.0 1.0 1.0 0.0 (bitmap-surface base) (bitmap-surface bmp) (bitmap-density base))]
[(ht) (bitmap_pin blend-mode 1.0 0.0 0.0 0.0 (bitmap-surface base) (bitmap-surface bmp) (bitmap-density base))]
[(hc) (bitmap_pin blend-mode 1.0 0.5 0.0 0.5 (bitmap-surface base) (bitmap-surface bmp) (bitmap-density base))]
[(hb) (bitmap_pin blend-mode 1.0 1.0 0.0 1.0 (bitmap-surface base) (bitmap-surface bmp) (bitmap-density base))]
[else base]))]
[else (let-values ([(base children) (values (car bitmaps) (cdr bitmaps))])
(bitmap_append alignment blend-mode
(bitmap-surface base) (map bitmap-surface children)
(real->double-flonum delta) (bitmap-density base)))]))))
(define make-append : (-> Symbol (-> [#:gapsize Real] Bitmap * Bitmap))
(lambda [alignment]
(define append-apply : (-> (Listof Bitmap) [#:gapsize Real] Bitmap) (make-append* alignment))
(λ [#:gapsize [delta 0.0] . bitmaps] (append-apply #:gapsize delta bitmaps))))
(define make-superimpose* : (-> Symbol (-> (Listof Bitmap) Bitmap))
(lambda [alignment]
(λ [bitmaps]
(define blend-mode : Integer (or (bitmap-operator->integer (default-pin-operator)) CAIRO_OPERATOR_OVER))
(cond [(null? bitmaps) (bitmap-blank)]
[(null? (cdr bitmaps)) (car bitmaps)]
[(null? (cddr bitmaps))
(let-values ([(base bmp) (values (car bitmaps) (cadr bitmaps))])
(case alignment
[(lt) (bitmap_pin blend-mode 0.0 0.0 0.0 0.0 (bitmap-surface base) (bitmap-surface bmp) (bitmap-density base))]
[(lc) (bitmap_pin blend-mode 0.0 0.5 0.0 0.5 (bitmap-surface base) (bitmap-surface bmp) (bitmap-density base))]
[(lb) (bitmap_pin blend-mode 0.0 1.0 0.0 1.0 (bitmap-surface base) (bitmap-surface bmp) (bitmap-density base))]
[(ct) (bitmap_pin blend-mode 0.5 0.0 0.5 0.0 (bitmap-surface base) (bitmap-surface bmp) (bitmap-density base))]
[(cc) (bitmap_pin blend-mode 0.5 0.5 0.5 0.5 (bitmap-surface base) (bitmap-surface bmp) (bitmap-density base))]
[(cb) (bitmap_pin blend-mode 0.5 1.0 0.5 1.0 (bitmap-surface base) (bitmap-surface bmp) (bitmap-density base))]
[(rt) (bitmap_pin blend-mode 1.0 0.0 1.0 0.0 (bitmap-surface base) (bitmap-surface bmp) (bitmap-density base))]
[(rc) (bitmap_pin blend-mode 1.0 0.5 1.0 0.5 (bitmap-surface base) (bitmap-surface bmp) (bitmap-density base))]
[(rb) (bitmap_pin blend-mode 1.0 1.0 1.0 1.0 (bitmap-surface base) (bitmap-surface bmp) (bitmap-density base))]
[else base]))]
[else (bitmap_superimpose alignment blend-mode (map bitmap-surface bitmaps) (bitmap-density (car bitmaps)))]))))
(define make-superimpose : (-> Symbol (-> Bitmap * Bitmap))
(lambda [alignment]
(define superimpose-apply : (-> (Listof Bitmap) Bitmap) (make-superimpose* alignment))
(λ bitmaps (superimpose-apply bitmaps))))
(define-combiner
[make-append "bitmap-~a-append" (vl vc vr ht hc hb)]
[make-append* "bitmap-~a-append*" (vl vc vr ht hc hb)]
[make-superimpose "bitmap-~a-superimpose" (lt lc lb ct cc cb rt rc rb)]
[make-superimpose* "bitmap-~a-superimpose*" (lt lc lb ct cc cb rt rc rb)])
(define bitmap-pin-over : Bitmap-Pin (make-pin 'over))
(define bitmap-pin-under : Bitmap-Pin (make-pin 'dest-over))
| false |
492805f2ccefcd7bd07f7779b7af72653c196182 | 0779e92f249247753b5f2369972866d478efa596 | /planet/info.rkt | 5b1ec921bd04d980079a724029eb429d9cd9fba5 | [] | no_license | dvanhorn/typed-student | 1976d86289eb1afce248b949f2271fb7b8067c5a | 77809141168e2659912aacf383e5e0378ada8825 | refs/heads/master | 2021-01-01T19:15:33.969618 | 2011-05-05T01:33:41 | 2011-05-05T01:33:41 | 1,704,319 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 436 | rkt | info.rkt | #lang setup/infotab
(define name "Typed Student.")
(define categories '(metaprogramming))
(define required-core-version "4.1.0")
(define repositories (list "4.x"))
(define primary-file
'("advanced.rkt" "world.rkt"))
(define blurb
(list '(div "Typed Student: typed languages and teachpacks for HtDP.")))
(define release-notes
(list
'(div "Refined some uses of Number into Integer.")
'(div "Initial, incomplete, release."))) | false |
f54c5ea5d43d58b99be191490a725fc67fb80150 | 2bee16df872240d3c389a9b08fe9a103f97a3a4f | /racket/digits.rkt | 7ed922b61efe7b5c2cccb4291c8cd59ed8e966d4 | [] | no_license | smrq/project-euler | 3930bd5e9b22f2cd3b802e36d75db52a874bd542 | 402419ae87b7180011466d7443ce22d010cea6d1 | refs/heads/master | 2021-01-16T18:31:42.061121 | 2016-07-29T22:23:05 | 2016-07-29T22:23:05 | 15,920,800 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 688 | rkt | digits.rkt | #lang racket
(provide digits)
(provide digits->number)
(provide number-length)
(provide digital-sum)
(provide is-permutation?)
(define (digits n)
(let loop ([n n] [acc null])
(if (< n 10)
(cons n acc)
(loop (quotient n 10) (cons (remainder n 10) acc)))))
(define (digits->number ds)
(let loop ([ds ds] [acc 0])
(if (null? ds)
acc
(loop (cdr ds) (+ (* 10 acc) (car ds))))))
(define (number-length n)
(let loop ([n n] [acc 0])
(if (> n 0)
(loop (quotient n 10) (add1 acc))
acc)))
(define (digital-sum n)
(for/sum ([i (digits n)]) i))
(define (is-permutation? a b)
(equal? (sort (digits a) <) (sort (digits b) <)))
| false |
8589c92e3a6114554ec61bc031ffe12ec090790f | 954cbc297b8e659888639dfc1f153879c4401226 | /labs/scheme/6-7-lists/lab-6.rkt | 186b9286cb15b777d6834abaa032742725aaed3a | [] | no_license | kirilrusev00/fmi-fp | 3beb41d8e86d3ddba048e2b853a74bc8eaf24caa | 1c6c76e18982b13fcdfb9dc274eb29b73c2f6167 | refs/heads/main | 2023-03-01T09:23:01.540527 | 2021-02-06T20:04:03 | 2021-02-06T20:04:03 | 309,650,566 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 4,446 | rkt | lab-6.rkt | #lang racket
(define nil '())
;; '() е списък
;; Ако l е списък (cons x l) е списък
(define p (cons "first" "second"))
(define l '((11 12) (21 22)))
;; map, filter, foldl, foldr
(define (map f l)
(if (null? l)
'()
(cons (f (car l))
(map f (cdr l)))))
(define (imap f l)
(define (loop left result)
(if (null? left)
result
(loop (cdr left)
(cons (f (car left)) result))))
(reverse (loop l '())))
(define (filter p? l)
(cond
([null? l] '())
([p? (car l)] (cons (car l) (filter p? (cdr l))))
(else (filter p? (cdr l)))))
(define (foldr op init l)
(if (null? l)
init
(op (car l)
(foldr op init (cdr l)))))
(define (foldl op init l)
(define (loop left result)
(if (null? left)
result
(loop (cdr left) (op result (car left)))))
(loop l init))
(define (ifoldr op init l)
(define (loop left result)
(if (null? left)
result
(loop (cdr left) (op (car left) result))))
(loop (reverse l) init))
(define (lfoldl op init l)
(define (loop left result)
(if (null? left)
(cdr (reverse result))
(loop (cdr left)
(cons (op (car result) (car left))
result))))
(loop l (list init)))
; Задaча 1
(define (take n lst)
(cond
((null? lst) '())
((= n 0) '())
(else (cons (car lst) (take (- n 1) (cdr lst))))))
(define (drop n lst)
(cond
((null? lst) '())
((= n 0) lst)
(else (drop (- n 1) (cdr lst)))))
; Задaча 2
(define (all? p? lst)
(cond
((null? lst) #t)
((not (p? (car lst))) #f)
(else (all? p? (cdr lst)))))
(define (any? p? lst)
(cond
((null? lst) #f)
((p? (car lst)) #t)
(else (any? p? (cdr lst)))))
; Задaча 3
(define (zip lst1 lst2)
(define (loop left1 left2 result)
(if (or (null? left1) (null? left2))
(reverse result)
(loop (cdr left1)
(cdr left2)
(cons (cons (car left1) (car left2)) result))))
(loop lst1 lst2 '()))
; Задaча 4
(define (zipWith f lst1 lst2)
(define (loop left1 left2 result)
(if (or (null? left1) (null? left2))
(reverse result)
(loop (cdr left1)
(cdr left2)
(cons (f (car left1) (car left2)) result))))
(loop lst1 lst2 '()))
; (define (zip lst1 lst2)
; (zipWith cons lst1 lst2))
; Задaча 5
(define (sorted? lst)
(cond
((null? lst) #t)
((null? (cdr lst)) #t)
(else (if (> (car lst) (car (cdr lst)))
(sorted? (cdr lst))
#f))))
; Задaча 6
(define (uniques lst)
(define (loop left result)
(cond
((null? left) result)
((any? (lambda (el) (equal? el (car left))) result) (loop (cdr left) result))
(else (loop (cdr left)
(cons (car left) result)))))
(reverse (loop lst '())))
; Задaча 7
(define (insert val lst)
(cond
((null? lst) (list val))
((< val (car lst)) (cons val lst))
(else (cons (car lst)
(insert val (cdr lst))))))
; Задaча 8
(define (insertion-sort lst)
(define (loop left result)
(if (null? left)
result
(loop (cdr left) (insert (car left) result))))
(loop lst '()))
; Задaча 9
(define (longest-interval-subsets il)
(define (longest-interval)
(define (interval-length i)
(if (null? i)
0
(- (cdr i) (car i))))
(define (loop left result)
(cond
((null? left) result)
((> (interval-length (car left)) (interval-length result)) (loop (cdr left) (car left)))
(else (loop (cdr left) result))))
(loop il '()))
(define (loop left result longest)
(cond
((null? left) result)
((and (>= (car (car left)) (car longest)) (<= (cdr (car left)) (cdr longest)))
(loop (cdr left) (cons (car left) result) longest))
(else (loop (cdr left) result longest))))
(define (insertion-sort-intervals lst)
(define (insert-interval int lst)
(cond
((null? lst) (list int))
((< (car int) (car (car lst))) (cons int lst))
(else (cons (car lst)
(insert-interval int (cdr lst))))))
(define (loop left result)
(if (null? left)
result
(loop (cdr left) (insert-interval (car left) result))))
(loop lst '()))
(insertion-sort-intervals (loop il '() (longest-interval))))
| false |
b28ec41927e5da08e0abd7939778422a25f41b83 | bc399abcf769c03a4e0b69b769e9a1311298ff63 | /inject-syntax/examples/ex-string.rkt | 9e1504d71f45abe031fe04bd8528d02237853bae | [] | no_license | rmculpepper/racket-inject-syntax | e28c72ad6ca98e97f97ffe88fdcb26afff22bd73 | 878f79e9449542901782f3106fbd282fe1a1ae66 | refs/heads/master | 2021-07-11T10:20:12.251985 | 2021-04-11T12:22:57 | 2021-04-11T12:22:57 | 242,144,153 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 732 | rkt | ex-string.rkt | #lang racket/base
(require (for-syntax racket/base) inject-syntax racket/list)
;; ----
(define-for-syntax do-require? #t)
(begin/inject-syntax
(if do-require? #'(require racket/string) #'(begin)))
(define (my-string-join xs sep)
(eprintf "using my string-join!\n")
(apply string-append (add-between xs sep)))
(begin/inject-syntax
(if (identifier-binding #'string-join)
#'(begin)
#'(define string-join my-string-join)))
(string-join '("hello" "world!") " ")
(define (my-string-exclaim str)
(regexp-replace* #rx"[.]" str "!"))
(begin/inject-syntax
(if (identifier-binding #'string-exclaim)
#'(begin)
#'(define string-exclaim my-string-exclaim)))
(string-exclaim "Hello. Nice to see you.")
| false |
440d26e0859dbbeb24e1e2dab45094603bba7e0d | 8a20d6515efe669fdcb9906111cd0815b55a46a9 | /examples/exists.rkt | 5cb7e0bcdd58d234ead62368df1cbd3c68be9a3e | [
"MIT"
] | permissive | brownplt/judgmental-resugaring | b3cda6c1356574d67b2756d7bfb9c45cb9a03588 | a05e572bd3d80de87e8ad9a25e87f99f8c283d41 | refs/heads/master | 2021-09-12T14:44:55.928564 | 2018-04-17T19:53:44 | 2018-04-17T19:53:44 | 74,395,526 | 7 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 3,942 | rkt | exists.rkt | #lang racket
(require redex)
(require "../sweet-t.rkt")
;; existentials (TAPL pg.366)
(define-resugarable-language exists-lang
#:keywords(if true false succ pred iszero zero
λ thunk let = : ∃ of as in
pair fst snd
calctype
Bool Num Pair ->)
(e ::= ....
; booleans
(if e e e)
; numbers
(+ e e)
; lambda
(e e)
; let
(let x = e in e)
; pair
(pair e e)
(fst e)
(snd e)
; exists
(pack (t e) as t)
(unpack e as (∃ x x) in e))
(v ::= ....
; booleans
true
false
; numbers
number
; lambda
(λ (x : t) e)
; pair
(pair v v)
; exists
(∃ t v as t))
(t ::= ....
Bool
Num
(t -> t)
; pair
(Pair t t)
; exists
(∃ x t))
(s ::= ....
(let-new-type (x x) of t as x in s)))
(define-core-type-system exists-lang
; boolean
[(⊢ Γ e_1 t_1)
(⊢ Γ e_2 t_2)
(⊢ Γ e_3 t_3)
(con (t_1 = Bool))
(con (t_2 = t_3))
------ t-if
(⊢ Γ (if e_1 e_2 e_3) t_3)]
[------ t-true
(⊢ Γ true Bool)]
[------ t-false
(⊢ Γ false Bool)]
; number
[------ t-num
(⊢ Γ number Num)]
[(⊢ Γ e_1 t_1)
(⊢ Γ e_2 t_2)
(con (t_1 = Num))
(con (t_2 = Num))
------ t-plus
(⊢ Γ (+ e_1 e_2) Nat)]
; lambda
[(side-condition ,(variable? (term x)))
(where t (lookup x Γ))
------ t-id
(⊢ Γ x t)]
[(side-condition ,(variable? (term x)))
(where #f (lookup x Γ))
(where x_Γ ,(fresh-type-var-named 'Γ))
(where x_t (fresh-var))
(con (Γ = (bind x x_t x_Γ)))
------ t-id-bind
(⊢ Γ x x_t)]
[(⊢ (bind x t Γ) e t_ret)
------ t-lambda
(⊢ Γ (λ (x : t) e) (t -> t_ret))]
[(⊢ Γ e_fun t_fun)
(⊢ Γ e_arg t_arg)
(where x_ret (fresh-var))
(con (t_fun = (t_arg -> x_ret)))
------ t-apply
(⊢ Γ (e_fun e_arg) x_ret)]
; let
[(⊢ Γ e_1 t_1)
(⊢ (bind x t_1 Γ) e_2 t_2)
------ t-let
(⊢ Γ (let x = e_1 in e_2) t_2)]
; pairs
[(⊢ Γ e_1 t_1)
(⊢ Γ e_2 t_2)
------ t-pair
(⊢ Γ (pair e_1 e_2) (Pair t_1 t_2))]
[(⊢ Γ e t)
(where x_t1 (fresh-var))
(where x_t2 (fresh-var))
(con (t = (Pair x_t1 x_t2)))
------ t-fst
(⊢ Γ (fst e) x_t1)]
[(⊢ Γ e t)
(where x_t1 (fresh-var))
(where x_t2 (fresh-var))
(con (t = (Pair x_t1 x_t2)))
------ t-snd
(⊢ Γ (snd e) x_t2)]
; exists
[(⊢ Γ e t_e)
(con (t_e = (substitute t_2 x t)))
------ t-pack
(⊢ Γ (pack (t e) as (∃ x t_2)) (∃ x t_2))]
[(⊢ Γ e_def t_def)
(where x_ex (fresh-var))
(con (t_def = (∃ x_t x_ex)))
(⊢ (bind x x_ex Γ) e_body t_body)
------ t-unpack
(⊢ Γ (unpack e_def as (∃ x_t x) in e_body) t_body)])
(define-global id (a -> a))
; newtype as bindings (as shown in paper)
(define rule_newtype
(ds-rule "newtype" #:capture()
(new-type (wrap unwrap) of T as X in ~body)
(unpack (pack (T (pair id id))
as (∃ X (Pair (T -> X) (X -> T))))
as (∃ X w)
in (let wrap = (fst w) in
(let unwrap = (snd w) in
~body)))))
; newtype as a pair (another way that 'newtype' could be defined)
#;(define rule_newtype
(ds-rule "newtype" #:capture()
(let-new-type w of T as X in ~body)
(let (∃ X w) = (∃ T (pair id id) as
(∃ X (Pair (T -> X) (X -> T)))) in
~body)))
; newtype as a record (another way that 'newtype' could be defined)
#;(define rule_newtype
(ds-rule "newtype" #:capture()
(let-new-type w of T as X in ~body)
(let (∃ X w) = (∃ T (record (field wrap id (field unwrap id ϵ))) as
(∃ X (Record (field wrap (T -> X) (field unwrap (X -> T) ϵ))))) in
~body)))
(view-sugar-type-rules exists-lang ⊢ (list rule_newtype))
| false |
d007e4ccc7aa9ff2691b20d1bd8fe380502b83ec | 6ad6a306035858ad44e5e4f71a10ce23f83d781b | /2/usr_lib.rkt | e767b59162a64758abaa5782bece8e4d6dafd6a1 | [] | no_license | lzq420241/sicp_exercise | 0217b334cef34910590656227db26a486eff907f | 84839a30376cbc263df6ec68883f3d6d284abd41 | refs/heads/master | 2020-04-24T01:28:31.427891 | 2017-04-24T00:01:33 | 2017-04-24T00:01:33 | 66,690,658 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,209 | rkt | usr_lib.rkt | #lang sicp
(#%require (only racket provide))
(#%require (only racket error))
(provide put)
(provide get)
(provide error)
(provide attach-tag)
(provide type-tag)
(provide contents)
(define global-array '())
(define (make-entry k v) (list k v))
(define (key entry) (car entry))
(define (value entry) (cadr entry))
(define (put op type item)
(define (put-helper k array)
(cond ((null? array) (list (make-entry k item)))
((equal? (key (car array)) k) array)
(else (cons (car array) (put-helper k (cdr array))))))
(set! global-array (put-helper (list op type) global-array)))
(define (get op type)
(define (get-helper k array)
(cond ((null? array) #f)
((equal? (key (car array)) k) (value (car array)))
(else (get-helper k (cdr array)))))
(get-helper (list op type) global-array))
(define (attach-tag type-tag contents)
(cons type-tag contents))
(define (type-tag datum)
(if (pair? datum)
(car datum)
(error "Bad tagged datum -- TYPE-TAG" datum)))
(define (contents datum)
(if (pair? datum)
(cdr datum)
(error "Bad tagged datum -- CONTENTS" datum)))
(define (apply-generic op . args)
(let ((type-tags (map type-tag args)))
(let ((proc (get op type-tags)))
(if proc
(apply proc (map contents args))
(if (= (length args) 2)
(let ((type1 (car type-tags))
(type2 (cadr type-tags))
(a1 (car args))
(a2 (cadr args)))
(if (eq? type1 type2)
(error "No method for these types"
(list op type-tags))
(let ((t1->t2 (get type1 type2))
(t2->t1 (get type2 type1)))
(cond (t1->t2
(apply-generic op (t1->t2 a1) a2))
(t2->t1
(apply-generic op a1 (t2->t1 a2)))
(else
(error "No method for these types"
(list op type-tags)))))))
(error "No method for these types"
(list op type-tags)))))))
| false |
b0a977c0e99486ccd92bfc2a536ae5e7e36a1be2 | ed84d789ef8e227aca6af969a8ae0c76015ee3ba | /conditionals/L1/semantics.rkt | 00a0181b150bdb65377c4287d1e4800f4399fe0d | [] | no_license | nthnluu/mystery-languages | 3de265714969fdf8dfa7bedc6df5a84b709c2bbd | 865481a10c22260b2e9a5a3c5873366679fc5283 | refs/heads/master | 2023-08-28T02:46:24.614863 | 2021-10-09T12:38:07 | 2021-10-09T12:38:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,236 | rkt | semantics.rkt | #lang racket
(require [for-syntax syntax/parse] mystery-languages/utils mystery-languages/common)
(require [for-syntax racket])
(provide #%module-begin #%top-interaction
#%datum #%top #%app)
(provide + - * /
< <= > >=
= <>
defvar)
(provide [rename-out (strict-if if) (strict-and and) (strict-or or) (strict-not not)])
(define-syntax strict-if
(syntax-rules ()
[(_ C T E)
(let ([C-val C])
(if (boolean? C-val)
(if C-val T E)
(error 'if "condition must be a boolean: ~a" C-val)))]))
(define-syntax strict-and
(syntax-rules ()
[(_) #true]
[(_ e0 e1 ...)
(let ([e0-val e0])
(if (boolean? e0-val)
(if e0-val
(strict-and e1 ...)
#false)
(error 'and "condition must be a boolean: ~a" e0-val)))]))
(define-syntax strict-or
(syntax-rules ()
[(_) #false]
[(_ e0 e1 ...)
(let ([e0-val e0])
(if (boolean? e0-val)
(if e0-val
#true
(tf-or e1 ...))
(error 'or "condition must be a boolean: ~a" e0-val)))]))
(define (strict-not v)
(if (boolean? v)
(not v)
(error 'not "argument must be a boolean: ~a" v)))
| true |
a9ddfde801c1a4d6acd7e27ba35500395c0e55b0 | 0bbf33de1afce7cace30371d43dfdeb9614be79f | /profj/libs/java/lang/ArithmeticException.rkt | d6e19a85e4ed2e67d6da871cfa5503b27dc89fee | [] | no_license | aptmcl/profj | e51e69d18c5680c89089fe725a66a3a5327bc8bd | 90f04acbc2bfeb62809234f64443adc4f6ca665a | refs/heads/master | 2021-01-21T19:19:22.866429 | 2016-01-27T20:14:16 | 2016-01-27T20:14:16 | 49,766,712 | 0 | 0 | null | 2016-01-16T09:04:05 | 2016-01-16T09:04:05 | null | UTF-8 | Racket | false | false | 294 | rkt | ArithmeticException.rkt | (module ArithmeticException racket/base
(require "Object-composite.rkt")
(provide
ArithmeticException
guard-convert-ArithmeticException
convert-assert-ArithmeticException
wrap-convert-assert-ArithmeticException
dynamic-ArithmeticException/c
static-ArithmeticException/c))
| false |
ab811f6aaa9fb6bb845b1a1e1a6ba5908fd79d1e | 5bbc152058cea0c50b84216be04650fa8837a94b | /experimental/micro/suffixtree/both/data-label-adapted.rkt | 7f92bdb680a0bcebc7b7285e0a4c933e14fd5285 | [] | no_license | nuprl/gradual-typing-performance | 2abd696cc90b05f19ee0432fb47ca7fab4b65808 | 35442b3221299a9cadba6810573007736b0d65d4 | refs/heads/master | 2021-01-18T15:10:01.739413 | 2018-12-15T18:44:28 | 2018-12-15T18:44:28 | 27,730,565 | 11 | 3 | null | 2018-12-01T13:54:08 | 2014-12-08T19:15:22 | Racket | UTF-8 | Racket | false | false | 575 | rkt | data-label-adapted.rkt | #lang typed/racket/base
(provide (struct-out label)
set-label-j!
set-label-i!
Label)
;; -----------------------------------------------------------------------------
(require benchmark-util)
(require/typed/check "data-label.rkt"
[#:struct label ([datum : (Vectorof (U Char Symbol))]
[i : Natural]
[j : Natural])]
[set-label-j! (-> label Natural Void)]
[set-label-i! (-> label Natural Void)])
;; =============================================================================
(define-type Label label)
| false |
6b84dc102abc6c3e53379ff473ce6b0c84294c41 | b0c07ea2a04ceaa1e988d4a0a61323cda5c43e31 | /langs/test-programs/jig/let-x-y-if-truenontail-x-5.rkt | 194ef3588ab88badb9346f480592526a10853259 | [
"AFL-3.0"
] | permissive | cmsc430/www | effa48f2e69fb1fd78910227778a1eb0078e0161 | 82864f846a7f8f6645821e237de42fac94dff157 | refs/heads/main | 2023-09-03T17:40:58.733672 | 2023-08-28T15:26:33 | 2023-08-28T15:26:33 | 183,064,322 | 39 | 30 | null | 2023-08-28T15:49:59 | 2019-04-23T17:30:12 | Racket | UTF-8 | Racket | false | false | 89 | rkt | let-x-y-if-truenontail-x-5.rkt | #lang racket
(define (double x) (+ x x))
(let ((x 2)) (let ((y 3)) (if (double 5) x 5)))
| false |
3d45b6b8175a6dd73f5b6221d634333b3b466594 | 802e5218649a189232dd046e94df069bda4af0b2 | /src/board.rkt | bd19d1c4fccc18c246c3f579731e26d40a5ae574 | [
"MIT"
] | permissive | lojic/RacketChess | 096f78b20446908e7656552c9725a9ef052ab4ba | 115ca7fecca9eaf31f9b2f4ef59935372c9920c8 | refs/heads/master | 2023-03-11T10:15:36.733625 | 2021-02-27T18:55:01 | 2021-02-27T18:55:01 | 330,496,789 | 9 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 12,042 | rkt | board.rkt | #lang racket
(require "./global.rkt"
"./state.rkt")
(require racket/performance-hint)
(provide black-king-idx
create-board
file-rank->idx
full-move
get-ep-idx
idx->pos
init-moves!
is-end-game?
is-whites-move?
may-castle?
pop-game-state!
pos->idx
push-game-state!
quiet-head
quiet-moves
reset-depth!
revoke-castling!
set-black-king-idx!
set-ep-idx!
set-full-move!
set-quiet-head!
set-tactical-head!
set-white-king-idx!
set-whites-move?!
tactical-head
tactical-moves
white-king-idx
(struct-out board))
;; 10x12 Board Representation
;; Index of upper left is 0. Index of lower right is 119
;;
;; FF FF FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF FF FF
;; FF FF FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF FF FF
;; FF 44 42 43 45 46 43 42 44 FF | FF 021 022 023 024 025 026 027 028 FF 8
;; FF 41 41 41 41 41 41 41 41 FF | FF 031 032 033 034 035 036 037 038 FF 7
;; FF 00 00 00 00 00 00 00 00 FF | FF 041 042 043 044 045 046 047 048 FF 6
;; FF 00 00 00 00 00 00 00 00 FF | FF 051 052 053 054 055 056 057 058 FF 5
;; FF 00 00 00 00 00 00 00 00 FF | FF 061 062 063 064 065 066 067 068 FF 4
;; FF 00 00 00 00 00 00 00 00 FF | FF 071 072 073 074 075 076 077 078 FF 3
;; FF 81 81 81 81 81 81 81 81 FF | FF 081 082 083 084 085 086 087 088 FF 2
;; FF 84 82 83 85 88 83 82 84 FF | FF 091 092 093 094 095 096 097 098 FF 1
;; FF FF FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF FF FF
;; FF FF FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF FF FF
;; a b c d e f g h
(struct board (depth
squares
move-i
game-state
game-stack ; Indexed by move-i
quiet-moves ; Indexed by depth
quiet-head ; Indexed by depth
tactical-moves ; Indexed by depth
tactical-head) ; Indexed by depth
#:transparent #:mutable)
(define initial-squares
(bytes->immutable-bytes
(bytes
#xFF #xFF #xFF #xFF #xFF #xFF #xFF #xFF #xFF #xFF
#xFF #xFF #xFF #xFF #xFF #xFF #xFF #xFF #xFF #xFF
#xFF #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xFF
#xFF #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xFF
#xFF #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xFF
#xFF #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xFF
#xFF #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xFF
#xFF #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xFF
#xFF #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xFF
#xFF #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xFF
#xFF #xFF #xFF #xFF #xFF #xFF #xFF #xFF #xFF #xFF
#xFF #xFF #xFF #xFF #xFF #xFF #xFF #xFF #xFF #xFF)))
(define positions
(vector-immutable
" " " " " " " " " " " " " " " " " " " " ; 0 - 9
" " " " " " " " " " " " " " " " " " " " ; 10 - 19
" " "a8" "b8" "c8" "d8" "e8" "f8" "g8" "h8" " " ; 20 - 29
" " "a7" "b7" "c7" "d7" "e7" "f7" "g7" "h7" " " ; 30 - 39
" " "a6" "b6" "c6" "d6" "e6" "f6" "g6" "h6" " " ; 40 - 49
" " "a5" "b5" "c5" "d5" "e5" "f5" "g5" "h5" " " ; 50 - 59
" " "a4" "b4" "c4" "d4" "e4" "f4" "g4" "h4" " " ; 60 - 69
" " "a3" "b3" "c3" "d3" "e3" "f3" "g3" "h3" " " ; 70 - 79
" " "a2" "b2" "c2" "d2" "e2" "f2" "g2" "h2" " " ; 80 - 89
" " "a1" "b1" "c1" "d1" "e1" "f1" "g1" "h1" " " ; 90 - 99
" " " " " " " " " " " " " " " " " " " " ; 100 - 109
" " " " " " " " " " " " " " " " " " " ")) ; 120 - 119
(define max-depth 200)
(define max-moves 250)
(define (create-board)
(let ([ b (board
0 ; depth
(bytes-copy initial-squares) ; squares
0 ; move-i
(initial-game-state pos->idx) ; game-state
(make-fxvector max-moves) ; game-stack
(make-vector max-depth) ; quiet-moves
(make-fxvector max-depth) ; quiet-head
(make-vector max-depth) ; tactical-moves
(make-fxvector max-depth)) ]) ; tactical-head
(for ([ i (in-range max-depth) ])
(fxvector-set! (board-quiet-head b) i -1)
(vecset! (board-quiet-moves b) i (make-vector max-moves))
(fxvector-set! (board-tactical-head b) i -1)
(vecset! (board-tactical-moves b) i (make-vector max-moves)))
b))
(define-inline (file-rank->idx file rank)
(+ 21 file (* rank 10)))
(define-inline (full-move b)
(fx+ 1 (arithmetic-shift (board-move-i b) -1)))
(define (idx->pos idx)
(vector-ref positions idx))
(define-inline (init-moves! b)
(let ([ d (board-depth b) ])
(fxvector-set! (board-quiet-head b) d -1)
(fxvector-set! (board-tactical-head b) d -1)))
(define-inline (is-end-game? b)
;; TODO make this better!
(fx> (board-move-i b) 50))
;; Decrement move-i and pop the game state off the stack
(define (pop-game-state! b)
(let* ([ move-i (sub1 (board-move-i b)) ]
[ state (fxvector-ref (board-game-stack b) move-i) ])
(set-board-game-state! b state)
(set-board-move-i! b move-i)))
(define (pos->idx pos)
(vector-member pos positions))
;; Push the game state onto the stack and increment move-i
(define (push-game-state! b)
(let ([ state (board-game-state b) ]
[ move-i (board-move-i b) ])
(fxvector-set! (board-game-stack b) move-i state)
(set-board-move-i! b (fx+ 1 move-i))))
(define-inline (quiet-head b [ d #f ])
(fxvector-ref (board-quiet-head b)
(if d d (board-depth b))))
(define-inline (quiet-moves b [ d #f ])
(vecref (board-quiet-moves b)
(if d d (board-depth b))))
(define-inline (reset-depth! b)
(set-board-depth! b 0))
(define-inline (set-full-move! b full-move blacks-move?)
(if blacks-move?
(set-board-move-i! b (fx+ 1 (arithmetic-shift (sub1 full-move) 1)))
(set-board-move-i! b (arithmetic-shift (sub1 full-move) 1))))
(define-inline (set-quiet-head! b v [ d #f ])
(fxvector-set! (board-quiet-head b)
(if d d (board-depth b))
v))
(define-inline (set-tactical-head! b v [ d #f ])
(fxvector-set! (board-tactical-head b)
(if d d (board-depth b))
v))
(define-inline (tactical-head b [ d #f ])
(fxvector-ref (board-tactical-head b)
(if d d (board-depth b))))
(define-inline (tactical-moves b [ d #f ])
(vecref (board-tactical-moves b)
(if d d (board-depth b))))
;; --------------------------------------------------------------------------------------------
;; Convenience functions for getting/setting state fields through the
;; board struct. When multiple fields need to be manipulated, it may
;; be more efficient to obtain the state fixnum, and then make
;; multiple calls.
;; --------------------------------------------------------------------------------------------
(define-inline (black-king-idx b)
(state-black-king-idx (board-game-state b)))
(define-inline (get-ep-idx b)
(state-ep-idx (board-game-state b)))
(define-inline (is-whites-move? b)
(state-whites-move? (board-game-state b)))
(define-inline (may-castle? b white?)
(let ([ s (board-game-state b) ])
(if white?
(or (state-w-kingside-ok? s) (state-w-queenside-ok? s))
(or (state-b-kingside-ok? s) (state-b-queenside-ok? s)))))
;; TODO just mask the bits out
(define-inline (revoke-castling! b white?)
(if white?
(begin
(set-board-game-state! b
(unset-state-w-queenside-ok?
(unset-state-w-kingside-ok?
(board-game-state b)))))
(begin
(set-board-game-state! b
(unset-state-b-queenside-ok?
(unset-state-b-kingside-ok?
(board-game-state b)))))))
(define-inline (set-black-king-idx! b idx)
(set-board-game-state!
b
(update-state-black-king-idx (board-game-state b) idx)))
(define-inline (set-ep-idx! b v)
(set-board-game-state! b (update-state-ep-idx (board-game-state b) v)))
(define-inline (set-white-king-idx! b idx)
(set-board-game-state!
b
(update-state-white-king-idx (board-game-state b) idx)))
(define-inline (set-whites-move?! b bool)
(set-board-game-state!
b
(if bool
(set-state-whites-move? (board-game-state b))
(unset-state-whites-move? (board-game-state b)))))
(define-inline (white-king-idx b)
(state-white-king-idx (board-game-state b)))
;; --------------------------------------------------------------------------------------------
(module+ test
(require rackunit)
;; ------------------------------------------------------------------------------------------
;; create-board
;; ------------------------------------------------------------------------------------------
(let ([ b (create-board) ])
;; depth
(check-equal? (board-depth b) 0)
;; squares
(check-equal? (bytes-length (board-squares b)) (* 10 12))
;; whites-move?
(check-not-false (is-whites-move? b))
;; black-king-idx
(check-equal? (black-king-idx b) 25)
;; white-king-idx
(check-equal? (white-king-idx b) 95)
;; move-i
(check-equal? (board-move-i b) 0)
;; ep-idx
(check-equal? (get-ep-idx b) 0)
;; moves
(check-equal? (fxvector-length (board-quiet-head b)) max-depth)
(check-equal? (vector-length (board-quiet-moves b)) max-depth)
(check-equal? (fxvector-length (board-tactical-head b)) max-depth)
(check-equal? (vector-length (board-tactical-moves b)) max-depth)
(for ([ i (in-range max-depth) ])
(check-equal? (fxvector-ref (board-quiet-head b) i) -1)
(check-equal? (fxvector-ref (board-tactical-head b) i) -1)
(check-equal? (vector-length (vector-ref (board-quiet-moves b) i)) max-moves)
(check-equal? (vector-length (vector-ref (board-tactical-moves b) i)) max-moves)))
;; ------------------------------------------------------------------------------------------
;; file-rank->idx
;; ------------------------------------------------------------------------------------------
(check-equal? (file-rank->idx 0 0) 21)
(check-equal? (file-rank->idx 7 0) 28)
(check-equal? (file-rank->idx 0 7) 91)
(check-equal? (file-rank->idx 7 7) 98)
;; ------------------------------------------------------------------------------------------
;; init-moves!
;; ------------------------------------------------------------------------------------------
(let ([ b (create-board) ])
(fxvector-set! (board-quiet-head b) 0 7)
(fxvector-set! (board-tactical-head b) 0 8)
(check-not-equal? (fxvector-ref (board-quiet-head b) 0) -1)
(check-not-equal? (fxvector-ref (board-tactical-head b) 0) -1)
(init-moves! b)
(check-equal? (fxvector-ref (board-quiet-head b) 0) -1)
(check-equal? (fxvector-ref (board-tactical-head b) 0) -1))
;; ------------------------------------------------------------------------------------------
;; pos->idx / idx->pos
;; ------------------------------------------------------------------------------------------
(for ([ pair (in-list '(("a8" 21) ("h8" 28) ("a8" 21) ("a1" 91) ("h1" 98))) ])
(check-equal? (pos->idx (first pair)) (second pair))
(check-equal? (idx->pos (second pair)) (first pair)))
;; ------------------------------------------------------------------------------------------
;; reset-depth!
;; ------------------------------------------------------------------------------------------
(let ([ b (create-board) ]
[ idx (pos->idx "e3") ])
(set-board-depth! b 7)
(set-ep-idx! b idx)
(reset-depth! b)
(check-equal? (board-depth b) 0)
(check-equal? (get-ep-idx b) idx))
)
| false |
b53126ee531bee262cffa4dfc254b4ab72a478c1 | 60b6707dbd61950877e4a7fd8c3cc627efb79a5b | /examples/polymorphism/or.rkt | 38ec56c0057cce7ff65cfea68202e6cf63f381dd | [] | no_license | chrisnevers/racket-compiler | 536e2a4aa3e8bc71c5637bc887a1bdb6084d0e43 | 900d190b1ca4046a39047e18682a623324e7f68a | refs/heads/master | 2020-03-28T17:24:06.380557 | 2019-05-03T21:02:58 | 2019-05-03T21:02:58 | 148,785,877 | 7 | 0 | null | 2019-02-04T17:59:34 | 2018-09-14T12:32:58 | OCaml | UTF-8 | Racket | false | false | 197 | rkt | or.rkt | (let ((generic-or (Lambda A
(lambda ((x : A)) : (-> A A)
(lambda ((y : A)) : A
(or x y))))))
(let ((rhs ((inst generic-or Bool) #f)))
(rhs #f)))
| false |
abe9768d47c9170f1a2d40219afca5fc17fbd0f4 | fc69a32687681f5664f33d360f4062915e1ac136 | /test/dssl2/zero-huh.rkt | f35b58f2bd85c8ec6f94140d0021f63a2d7d7916 | [] | no_license | tov/dssl2 | 3855905061d270a3b5e0105c45c85b0fb5fe325a | e2d03ea0fff61c5e515ecd4bff88608e0439e32a | refs/heads/main | 2023-07-19T22:22:53.869561 | 2023-07-03T15:18:32 | 2023-07-03T15:18:32 | 93,645,003 | 12 | 6 | null | 2021-05-26T16:04:38 | 2017-06-07T14:31:59 | Racket | UTF-8 | Racket | false | false | 67 | rkt | zero-huh.rkt | #lang dssl2
assert zero?(0)
assert zero?(0.0)
assert not zero?(1)
| false |
096290af2099bd9f04a99f82a04f5274709690c6 | 6215d857fbc65b096fdbe449c89b5883762bcc04 | /flow.rkt | 55ca0781b556553b0da37cf549509113a0ae684a | [] | no_license | deeglaze/polymorphic-splitting-port | 5692c7b76830b26abbd81b00263b762dea2b1029 | 3ba8dd2fd3357a4414c7b864ed233daa5fc25923 | refs/heads/master | 2020-04-12T13:52:06.692788 | 2012-10-08T20:22:36 | 2012-10-08T20:22:36 | 6,067,493 | 2 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 30,593 | rkt | flow.rkt | #lang racket
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Polymorphic Flow Analysis
(require "library.rkt"
"data.rkt"
"env.rkt"
"free.rkt"
"intset.rkt"
"unparse.rkt"
"used-before.rkt"
"abstract.rkt"
"contour.rkt"
"callmap.rkt"
"flags.rkt"
"mutrec.rkt")
(provide analyse)
;; Statistics Collection
(set-running-time! 0)
(set-starting-time! 0)
(define init-statistics!
(lambda ()
(set-running-time! 0)
(set-starting-time! (current-inexact-milliseconds))))
(define finish-statistics!
(lambda ()
(set-running-time! (- (current-inexact-milliseconds) starting-time))
(printf "Analyzing took ~a ms~%" running-time)
running-time))
(define analyse
(lambda ()
(set! memo-propagate (memo-rec propagate propagate-compare))
(set! memo-make-read-result (memo make-read-result))
(set! memo-make-recursive-list (memo make-recursive-list))
(set! memo-make-ap-get-args (memo make-ap-get-args))
;; Label the tree and initialize global data structures.
(let ([initial-contour (make-initial-contour)])
(prepare initial-contour)
(init-abstract!)
(init-call-map!)
(init-statistics!)
(init-abstract-statistics!)
;; Here we go!
(propagate tree (make-context initial-contour aenv-empty) aenv-empty)
(propagate-across-edges!)
;; Return the analysis time.
(finish-statistics!))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Labels
(define read-like-procedures (list %read %eval %get %expand-once))
;; Add labels to expressions.
(define prepare
(lambda (initial-contour)
(define (note-variable! x)
(unless (or (Name-primitive? x) (memq x variables))
(set-variables! (cons x variables))))
(define labels '())
(define fresh-label
(let ([label-counter (generate-counter 0)])
(lambda (e)
(begin0 (label-counter)
(set! labels (cons e labels))))))
(define read-labels (list initial-contour (fresh-label #f) (fresh-label #f)))
(define (prepare e recursive)
;; recursive is a list of names whose recursive definitions we are currently inside
(let ([prep (lambda (e) (prepare e recursive))])
(match e
[(Define x e1)
(note-variable! x)
(prepare e1 (append (or (Name-component x) '()) recursive))]
[(? Defstruct?) #f]
[(? Defmacro?) #f]
[(E: (? Const?))
(set-E-labels! e (list (fresh-label e)))]
[(E: (Var x))
(note-variable! x)
(define l (fresh-label e))
(define ls
(cond [(Name-primitive? x)
;; Most primitives need one "result" label.
(cond [(memq x read-like-procedures)
read-labels]
[(or (Selector? (Name-primop x))
(eq? x %internal-apply))
'()]
[(eq? x %Qmerge-list)
(list (fresh-label #f) (fresh-label #f))]
[else
(list (fresh-label #f))])]
[else
;; For non-primitives, the second "label"
;; marks whether this occurrence is recursive.
;; This should be determined by the parser.
(list (and (Name-let-bound? x)
(not (Name-mutated? x))
(memq x recursive)))]))
(set-E-labels! e (cons l ls))]
[(E: (Lam: x e1))
(prep e1)
(for ([id (in-list x)]) (note-variable! id))
(set-E-labels! e (list (fresh-label e)))]
[(E: (Vlam: x rest e1))
(prep e1)
(for ([id (in-list (cons rest x))]) (note-variable! id))
(set-E-labels! e (list (fresh-label e)))]
[(E: (App e0 args))
(prep e0)
(for ([arg (in-list args)]) (prep arg))
(define l (fresh-label e))
(define ls
(for/list ([_ (in-list (list* #f #f args))])
(fresh-label #f)))
(set-E-labels! e (cons l ls))]
[(E: (Let b e2))
(for ([cl (in-list b)]) (prep cl))
(prep e2)
(set-E-labels! e (list (labelof e2)))]
[(E: (Letr b e2))
(mark-used-before-defined! b)
(for ([cl (in-list b)]) (prep cl))
(prep e2)
(set-E-labels! e (list (labelof e2)))]
[(E: (Begin exps))
(for ([e (in-list exps)]) (prep e))
(set-E-labels! e (list (labelof (rac exps))))]
[(E: (or (And exps) (Or exps)))
(for ([e (in-list exps)]) (prep e))
(set-E-labels! e (list (fresh-label e)))]
[(E: (If test then els))
(prep test)
(prep then)
(prep els)
(set-E-labels! e (list (fresh-label e) (fresh-label #f) (fresh-label #f)))]
[(E: (Set! x body))
(note-variable! x)
(prep body)
(set-E-labels! e (list (fresh-label e)))]
[(E: (Letcc x e1))
(note-variable! x)
(prep e1)
(set-E-labels! e (list (fresh-label e)))]
[_ (error 'prep "Bad ~a" e)])))
(set-variables! '())
(prepare tree '())
(define v (list->vector (reverse labels)))
(set-label->node! (lambda (l) (vector-ref v l)))
(set-n-labels! (vector-length v))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Abstract Evaluation.
;; Compute abstract values.
(define memo-propagate #f)
(define propagate-compare
(lambda (a b)
(and (= (labelof (car a)) (labelof (car b)))
(equal? (cadr a) (cadr b))
(andmap (lambda (c d)
(and (eq? (car c) (car d))
(equal? (cdr c) (cdr d))))
(env->list (caddr a))
(env->list (caddr b))))))
(define noisy-propagate
(lambda (e k aenv)
(printf "Propagate ~a ~a ~a~%" (labelof e) k (map (lambda (b) (list (pname (car b)) (cdr b))) (env->list aenv)))
(propagate e k aenv)))
;; exp x context x env -> point
(define propagate
(lambda (e k aenv)
(define l (labelof e))
(match e
[(E: (Const c))
(define p (index-result-map l k))
(p+aval p
(match c
[(? symbol?) (aval 'sym l)]
[#t (aval 'true l)]
[#f (aval 'false l)]
['() (aval 'nil l)]
[(? number?) (aval 'num l)]
[(? char?) (aval 'char l)]
[(? string?) (aval 'str l)]
[(? void?) (aval 'void l)]))
p]
[(E: (or (? Lam?) (? Vlam?)))
(define p (index-result-map l k))
(define frees (free-in-exp e))
(define aenv* (aenv-restrict aenv frees))
(p+aval p (aval 'closure l (make-closure-contour k) aenv*))
p]
[(E: (Var x))
(cond [(Name-primitive? x)
(define p (index-result-map l k))
(p+aval p (aval 'prim l))
p]
[(Name-unbound? x)
(define p (index-result-map l k))
(p+aval p (aval 'unbound 0))
p]
[(and (Name-let-bound? x) (not (Name-mutated? x)))
(define let-label (labelof (Name-binding x)))
(define recursive? (recursive-var? e))
(define component (or (Name-component x) (list x)))
(var-split x aenv l k let-label recursive? component)]
[else
(result-map= l k (index-var-map x (aenv-lookup aenv x)))
(index-result-map l k)])]
[(E: (App e0 args))
(let loop ([a* args])
(if (pair? a*)
(p->1 (propagate (car a*) k aenv)
(lambda () (loop (cdr a*))))
;; call e0 functions with args' labels
(p-> (propagate e0 k aenv)
(make-ap-action
l
k
(make-ap-get-args args k (cdr (extra-labels e)))))))
(index-result-map l k)]
[(E: (or (Let b e2) (Letr b e2)))
(define new-aenv
(for/fold ([env aenv])
([cl (in-list b)]
#:when (Define? cl))
(aenv-extend env (Define-name cl) k)))
(define (make-new-k eb)
(make-context
(let-binding-contour (context->contour k) (labelof eb))
new-aenv))
(let loop ([b b])
(match b
[(cons (Define x eb) rest)
(when (Name-used-before-defined? x)
(p+aval (index-var-map x k) (aval 'unspecified 0)))
(let ([p (index-var-map x k)])
(p->p (propagate eb (make-new-k eb) new-aenv) p)
(p->1 p (lambda () (loop rest))))]
[(cons (? E? eb) rest)
(p->1 (propagate eb (make-new-k eb) new-aenv)
(lambda () (loop rest)))]
[(cons _ rest)
(loop rest)]
['()
(propagate e2 k new-aenv)]
[_ (error 'flow "Bad clause in let ~a" b)]))
(index-result-map l k)]
[(E: (Begin exps))
(let eloop ([exps exps])
(when (pair? exps)
(p->1 (propagate (car exps) k aenv)
(lambda () (eloop (cdr exps))))))
(index-result-map l k)]
[(E: (If test then els))
(match-let* ([tst (propagate test k aenv)]
[(list then-lbl else-lbl) (extra-labels e)]
[(cons then-env else-env)
(if If-split
(split-if test k aenv aenv then-lbl else-lbl)
(cons aenv aenv))]
[p (index-result-map l k)])
(p-> tst
(let ([first #t])
(lambda (new)
(when (and first (except-in-avals? '(false) new))
(set! first #f)
(p->p (propagate then k then-env) p)))))
(p-> tst
(let ([first #t])
(lambda (new)
(when (and first (in-avals? '(unspecified unbound false) new))
(set! first #f)
(p->p (propagate els k else-env) p)))))
p)]
[(E: (Set! x body))
(let ([p1 (propagate body k aenv)])
(unless (Name-unbound? x)
(p->p p1 (index-var-map x (aenv-lookup aenv x)))))
(let* ([p (index-result-map l k)])
(p+aval p (aval 'void l))
p)]
[(E: (And exps))
(let* ([p (index-result-map l k)])
(if (null? exps)
(p+aval p (aval 'true l))
(let loop ([exps exps])
(if (pair? (cdr exps))
(p-> (propagate (car exps) k aenv)
(let ([first #t])
(lambda (new)
(when (and first (except-in-avals? '(false) new))
(set! first #f)
(loop (cdr exps)))
(p+avals p (filter-avals '(false unspecified unbound) new)))))
(p->p (propagate (car exps) k aenv) p))))
p)]
[(E: (Or exps))
(let* ([p (index-result-map l k)])
(if (null? exps)
(p+aval p (aval 'false l))
(let loop ([exps exps])
(if (pair? (cdr exps))
(p-> (propagate (car exps) k aenv)
(let ([first #t])
(lambda (new)
(when (and first (in-avals? '(false unspecified unbound) new))
(set! first #f)
(loop (cdr exps)))
(p+avals p (except-avals '(false) new)))))
(p->p (propagate (car exps) k aenv) p))))
p)]
[(E: (Letcc x e1))
(let* ([p (index-result-map l k)]
[aenv (aenv-extend aenv x k)])
(p+aval (index-var-map x k) (aval 'cont l k))
(p->p (propagate e1 k aenv) p)
p)])))
;; Make an edge that filters based on type
(define typed-p->
(lambda (type p1 p2)
(p-> p1
(lambda (new)
(p+avals
p2
(intset-filter (lambda (v) (equal? (aval-type v) type)) new))))))
;; Build arg successor for type-based contours.
(define make-typed-arg-successor
(lambda (contour-maps formals args current-contour eval-body)
(lambda (from contour-map)
(p-> from
(lambda (new)
(intset-for-each
(lambda (v)
(define type (aval-type v))
(unless (assoc type (unbox contour-map))
;; For a new type of arg, compute new contours,
;; record them, evaluate function body in new
;; contours, and add typed edges for all args
;; and all appropriate types to formals.
(define arg-types
(for/list ([z (in-list contour-maps)])
(if (eq? z contour-map)
(list type)
(map car (unbox z)))))
(define new-contours
(make-type-based-contours
arg-types
current-contour))
(set-box! contour-map
(cons (cons type new-contours) (unbox contour-map)))
(for ([c (in-list new-contours)])
(eval-body c)
(for ([formal (in-list formals)]
[arg (in-list args)]
[types (in-list arg-types)])
(typed-p-> type arg (index-var-map formal c))))))
new))))))
(define make-ap-action
(lambda (l k get-args)
(define p (index-result-map l k))
(lambda (fns)
(intset-for-each
(lambda (new)
(define l-closure (aval-label new))
(case (aval-kind new)
[(closure)
(extend-call-map! l-closure l)
(define aenv2 (aval-env new))
(define c (call-site-contour l k (aval-contour new)))
(define (action x arg* eval-body)
(cond
[(and Type (< (contour-length c) Type))
(cond [(null? x) (eval-body c)]
[else
(define contour-maps (map (lambda (_) (box '())) x))
(define arg-successor
(make-typed-arg-successor
contour-maps
x
arg*
c
eval-body))
(for ([arg (in-list arg*)]
[contour (in-list contour-maps)])
(arg-successor arg contour))])]
[else
(for ([arg (in-list arg*)]
[contour (in-list x)])
(p->p arg (index-var-map contour c)))
(eval-body c)]))
(define node (label->node l-closure))
(match node
[(E: (Lam: x e2))
(match (get-args (length x) #f #f)
[#f #f]
[(cons arg* _)
(define (eval-body c)
(define new-aenv
(aenv-extend* aenv2 x (map (lambda (_) c) x)))
(define new-context (make-context c aenv2))
(memo-propagate e2 new-context new-aenv)
(p->p (index-result-map (labelof e2) new-context) p))
(action x arg* eval-body)])]
[(E: (Vlam: x rest e2))
(match (get-args (length x) #f #t)
[#f #f]
[(cons arg* arg-rest)
(define (eval-body c)
(p->p arg-rest (index-var-map rest c))
(let* ([vars (cons rest x)]
[new-aenv (aenv-extend* aenv2 vars (map (lambda (_) c) vars))]
[new-context (make-context c aenv2)])
(memo-propagate e2 new-context new-aenv)
(p->p (index-result-map (labelof e2) new-context) p)))
(action x arg* eval-body)])])]
[(unbound)
(p+aval p (aval 'unbound 0))]
[(cont)
(extend-call-map! l-closure l)
(let ([k2 (aval-contour new)])
(match (label->node l-closure)
[(and e2 (E: (? Letcc?)))
(match (get-args 1 #f #f)
[#f #f]
[`((,arg) . ,_)
(p->p arg (index-result-map (labelof e2) k2))])]))]
[(prim)
(extend-call-map! l-closure l)
(match (label->node l-closure)
[(and e2 (E: (Var x)))
(for-each
(lambda (arity)
(match (if (negative? arity)
(get-args (- (- arity) 1) #t #f)
(get-args arity #f #f))
[#f #f]
[`(,arg* . ,arg-rest)
(cond
[(eq? %internal-apply x)
(let* ([f (car arg*)]
[args-list (cadr arg*)]
[get-args (make-apply-get-args args-list)])
(p-> f (make-ap-action l k get-args)))]
[(or (eq? %vector x) (eq? %Qvector x))
(let* ([l-result (car (extra-labels e2))]
[p-result (index-result-map l-result k)])
(for-each
(lambda (arg) (p->p arg p-result))
arg*)
(when arg-rest
(p->p arg-rest p-result))
(when (zero? (length arg*))
(p+aval p (aval 'vec0 l-result)))
(p+aval p (aval 'vec l-result k p-result)))]
[(eq? %make-vector x)
(let* ([l-result (car (extra-labels e2))]
[p-result (index-result-map l-result k)])
(if (= 2 arity)
(p->p (cadr arg*) p-result)
(p+aval p-result (aval 'unspecified 0)))
(p+aval p (aval 'vec0 l-result))
(p+aval p (aval 'vec l-result k p-result)))]
[(memq x read-like-procedures)
(match (extra-labels e2)
[(list k l3 l4)
(p->p (memo-make-read-result k l3 l4) p)])]
[(eq? %Qlist x)
(let ([l3 (car (extra-labels e2))])
(p->p (memo-make-recursive-list l3 k arg*) p))]
[(eq? %Qmerge-list x)
(let* ([l-result (car (extra-labels e2))]
[lm (cadr (extra-labels e2))]
[pm (index-result-map lm k)])
(for-each
(lambda (arg) (p->p arg pm))
arg*)
(p->p (memo-make-recursive-list l-result k (list pm)) p))]
[else
(match (Name-primop x)
[(Constructor tag)
(let ([l3 (car (extra-labels e2))])
(p+aval p
(apply aval
tag
l ;;; TEMP l3 -> l
k
arg*)))]
[(Selector tag idx)
(p-> (car arg*)
(lambda (new)
(intset-for-each
(lambda (v)
(when (eq? tag (aval-kind v))
(p->p (list-ref (aval-fields v) idx)
p)))
new)))]
[(Mutator tag idx val)
(let ([l3 (car (extra-labels e2))])
(p-> (car arg*)
(lambda (new)
(intset-for-each
(lambda (v)
(when (eq? tag (aval-kind v))
(p->p (list-ref arg* val)
(list-ref (aval-fields v) idx))))
new)))
(p+aval p (aval 'void l3)))]
[(Predicate tags)
(let ([l3 (car (extra-labels e2))])
(p-> (car arg*)
(lambda (new)
(intset-for-each
(lambda (v)
(when (memq (aval-kind v)
`(unspecified unbound ,@tags))
(p+aval p (aval 'true l3)))
(unless (memq (aval-kind v) tags)
(p+aval p (aval 'false l3))))
new))))]
[_
(let ([l3 (car (extra-labels e2))])
(p+avals
p
(list->avals
(map (lambda (c) (aval c l)) ;;; TEMP l3 -> l
(Primitive-result-type (Name-binder x))))))])])]))
(Primitive-arity (Name-binder x)))])]))
fns))))
;; Build a get-args closure for an ordinary application. A get-args
;; closure takes three args: n, or-more?, and rest?. n is the
;; minimum number of args required. or-more? is true if an arbitrary
;; number of args can be accepted. rest? is true if an arbitrary
;; number of args can be accepted and they are to be returned as
;; a list (for a Vlam). Only one of or-more? and rest? may be true.
;; A get-args closure returns
;; #f if the args request cannot be satisfied;
;; a pair of (list of length n) and #f if both or-more? and rest? are false
;; a pair of (list of length >= n) and a rest point if or-more? is true
;; a pair of (list of length n) and a rest point if rest? is true.
(define memo-make-ap-get-args #f) ; not used
(define make-ap-get-args
(lambda (args k labels)
(let ([nargs (length args)]
[largs (map labelof args)])
(lambda (n or-more? rest?)
(if (cond (or-more? (< nargs n))
(rest? (< nargs n))
(else (not (= n nargs))))
#f
(let ([points (map (lambda (l) (index-result-map l k))
(if or-more? largs (sublist largs n)))])
(cons points
(cond [rest? (make-varargs-list
(list-tail largs n)
k
(list-tail labels n))]
[or-more? (if (null? points) #f (car points))]
[else #f]))))))))
;; This function assumes that p includes a single recursive cons
;; whose cdr refers to a program point equivalent to p.
;; This program point is expected to be the result of list-copy.
(define make-apply-get-args
(lambda (p)
(let* ([pairs (intset->list (filter-avals '(cons) (point-elements p)))]
[v (if (= 1 (length pairs))
(car pairs)
(error 'internal-apply "args not correctly formed"))]
[arg-k (aval-contour v)]
[arg-car (car (aval-fields v))])
(lambda (n or-more? rest?)
(cons (iota n arg-car)
(cond (rest? p)
(or-more? arg-car)
(else #f)))))))
(define make-varargs-list
(lambda (largs k labels)
(let ([p (index-result-map (car labels) k)])
(if (null? largs)
(p+aval p (aval 'nil (car labels)))
(begin
(p+aval p (aval 'cons (car labels) k
(index-result-map (car largs) k)
(index-result-map (cadr labels) k)))
(make-varargs-list (cdr largs) k (cdr labels))))
p)))
(define memo-make-read-result #f)
(define make-read-result
(lambda (k l1 l2)
(define p (index-result-map l1 k))
(define p2 (index-result-map l2 k))
(define vals (list
(aval 'nil l1)
(aval 'sym l1)
(aval 'true l1)
(aval 'false l1)
(aval 'num l1)
(aval 'char l1)
(aval 'str l1)
(aval 'cons l1 k p2 p2)
(aval 'vec0 l1)
(aval 'vec l1 k p2)))
(p+avals p2 (list->avals vals))
(p+avals p (list->avals (cons (aval 'eof l1) vals)))
p))
(define memo-make-recursive-list #f)
(define make-recursive-list
(lambda (l k elts)
(let* ([p (index-result-map l k)]
[vals (cons (aval 'nil l)
(map (lambda (elt) (aval 'cons l k elt p))
elts))])
(p+avals p (list->avals vals))
p)))
;; Split variables in the test of an if-expression if we can
;; determine that they have a certain shape in the then and/or else branches.
(define split-if
(lambda (exp k then-env else-env then-label else-label)
(letrec ([split-variable
(lambda (sense tags x-label x)
(let* ([xpoint (index-result-map x-label k)]
[then-contour (if-contour
(aenv-lookup then-env x)
then-label)]
[x-then-point (index-var-map x then-contour)]
[then-env (aenv-extend then-env x then-contour)]
[else-contour (if-contour
(aenv-lookup else-env x)
else-label)]
[x-else-point (index-var-map x else-contour)]
[else-env (aenv-extend else-env x else-contour)]
[f (case sense
[(both)
(lambda (new)
(let ([filtered (filter-avals tags new)])
(p+avals x-then-point filtered)
(p+avals x-else-point filtered)))]
[(#t)
(lambda (new)
(p+avals x-then-point (filter-avals tags new))
(p+avals x-else-point (except-avals tags new)))]
[(#f)
(lambda (new)
(p+avals x-then-point (except-avals tags new))
(p+avals x-else-point (filter-avals tags new)))])])
(p-> xpoint f)
(cons then-env else-env)))]
[find-var-to-split
(lambda (exp then-env else-env)
(match exp
[(E: (App (E: (Var p-or-s)) (list (and (E: (Var x)) expr))))
(define xl (labelof expr))
(cond [(or (Name-mutated? x)
(Name-primitive? x)
(Name-unbound? x)
(not (Name-primitive? p-or-s))
(and (not (Predicate? (Name-primop p-or-s)))
(not (Selector? (Name-primop p-or-s)))))
(cons then-env else-env)]
[(Predicate? (Name-primop p-or-s))
(split-variable #t (Predicate-tag (Name-primop p-or-s)) xl x)]
[else ; Selector
(split-variable 'both (list (Selector-tag (Name-primop p-or-s))) xl x)])]
[(E: (Var x))
(cond [(or (Name-mutated? x) (Name-unbound? x))
(cons then-env else-env)]
[else
(split-variable #f (list 'false) (labelof exp) x)])]
[(E: (App (E: (Var p-or-s)) (list arg)))
(if (and (Name-primitive? p-or-s)
(or (Predicate? (Name-primop p-or-s))
(Selector? (Name-primop p-or-s))))
(find-var-to-split arg then-env else-env)
(cons then-env else-env))]
[(E: (And (list exp)))
(find-var-to-split exp then-env else-env)]
[(E: (And exps))
(let loop ([exps exps] [then-env then-env])
(if (null? exps)
(cons then-env else-env)
(match-let ([`(,then-env . ,_)
(find-var-to-split (car exps) then-env else-env)])
(loop (cdr exps) then-env))))]
[_ (cons then-env else-env)]))])
(find-var-to-split exp then-env else-env))))
(define warn-unused-vars
(lambda ()
(for-each
(lambda (x)
(when (intset-empty? (values-at-var x))
(printf "; Note: ~a never gets a value~%" (pname* x))))
variables)))
(define not-called?
(lambda (v)
(null? (index-call-map (aval-label v)))))
(define warn-uncalled
(lambda ()
(match tree
[(E: (Letr b _))
(for-each
(match-lambda
[(Define x e)
(when (intset-exists?
not-called?
(filter-avals '(closure prim) (values-at-label (labelof e))))
(printf "; Note: ~a is never called~%" (pname* x)))]
[_ #f])
b)])))
| false |
d9fb14d1e4c3dcafd542a0b9f0f32d4c5079b81b | 907673ff4c102e921c9d4d84ce5f708d83ad7cac | /blog/markdown/parse.rkt | 8f3ab7a99f20ab0212dbfae47342dbf060e5fece | [] | no_license | dannypsnl-fork/blog2 | 2932b09ddf0faf52009970e2ac5c26ebf7bf760b | c9243ff38465b0cdf0969622cb49d010df5c1d74 | refs/heads/master | 2023-06-18T02:54:42.086873 | 2021-07-13T08:01:32 | 2021-07-13T08:01:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 16,902 | rkt | parse.rkt | #lang racket/base
(require data/applicative
data/monad
megaparsack
megaparsack/text
racket/contract
racket/function
racket/list
racket/match
threading
"parse/content.rkt"
"parse/util.rkt")
(provide (all-from-out "parse/content.rkt")
block?
horizontal-rule
horizontal-rule?
(contract-out
(struct document ([blocks (listof block?)]
[link-targets (hash/c string? string?)]
[footnotes (listof (cons/c string? (listof block?)))]))
(struct heading ([depth exact-nonnegative-integer?] [content content?]))
(struct paragraph ([content content?]))
(struct code-block ([content content?] [language (or/c #f string?)]))
(struct unordered-list ([blockss (listof (listof block?))]))
(struct ordered-list ([blockss (listof (listof block?))]))
(struct blockquote ([blocks (listof block?)]))
[document/p (parser/c char? document?)]))
;; -----------------------------------------------------------------------------
(struct document (blocks link-targets footnotes) #:transparent)
(struct heading (depth content) #:transparent)
(struct paragraph (content) #:transparent)
(struct code-block (content language) #:transparent)
(struct unordered-list (blockss) #:transparent)
(struct ordered-list (blockss) #:transparent)
(struct blockquote (blocks) #:transparent)
(define-values [horizontal-rule horizontal-rule?]
(let ()
(struct horizontal-rule ())
(values (horizontal-rule) horizontal-rule?)))
(define (block? v)
(or (heading? v)
(paragraph? v)
(code-block? v)
(unordered-list? v)
(ordered-list? v)
(blockquote? v)
(horizontal-rule? v)))
;; -----------------------------------------------------------------------------
(define (spaces/p n) (repeat/p n (char/p #\space)))
(define maybe-indent/p (map/p length (many/p (char/p #\space))))
(define unordered-list-bullet/p (or/p (string/p "* ") (string/p "- ")))
(define ordered-list-bullet/p (do integer/p (string/p ". ")))
;; -----------------------------------------------------------------------------
#| This module implements a simple markdown parser based very loosely on the
algorithm given in the CommonMark specification:
https://spec.commonmark.org/0.30/#appendix-a-parsing-strategy
This implementation is very much /not/ CommonMark-compliant. For the most part,
it is stricter than CommonMark---not all inputs are accepted as valid markdown.
The accepted subset is chosen to be both simple to parse and relatively portable
with other markdown implementations.
Although the parser is implemented using megaparsack, it is unusual in that it
is really a one-line-at-a-time parser that switches between various states. This
makes it easier to parse Markdown’s indentation-sensitive block structure.
Note [Open blocks]
~~~~~~~~~~~~~~~~~~
Philosophically, the parser is a context-sensitive state machine. Some example
states are “start of line”, “scanning block prefixes”, and “scanning content”.
Each state is implemented as a parser-returning function that accepts its
context as arguments. Different states accept the context in slightly different
ways, but in all cases, the parsing context is a stack of /open blocks/, as
described in the CommonMark appendix linked above.
Internally, the parser represents most open blocks using the same structures it
uses to represent closed blocks (the latter of which are recognized by the
public `block?` predicate), but there are two differences:
* Open lists are represented by the `open-list` and `list-element` structures,
which record additional indentation information.
* Open footnote declarations are represented by the `footnote` structure.
These never appear in closed blocks, since they are collected into a field
of the top-level `document` structure, but they can appear nested in other
blocks, so parsing them must still be indentation-aware.
Note [In-blocks and out-blocks]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The naming conventions in this module distinguish two forms of block context:
* When a function accepts a list of open blocks /shallowest-first/, the
argument is named `out-blocks`. This is because it’s useful to access
shallower blocks before deeper blocks when the parser is “outside” the blocks.
* Dually, when a function accepts a list of open blocks /deepest-first/, the
argument is named `in-blocks`.
As an example, the `scan-line-start` function accepts an `out-blocks` argument
because it must traverse the open blocks from the outside in to parse the
indentation at the start of the line. In contrast, the `scan-block-content`
function accepts an `in-blocks` argument, since the indentation has been parsed
for all open blocks, and the content should be added to the innermost block.
The `scan-block-prefixes` function bridges the gap between `scan-line-start` and
`scan-block-content`, so it accepts both `in-blocks` and `out-blocks` arguments.
As it parses the indentation for each block, it transfers it from the
`out-blocks` stack to the `in-blocks` stack, morally “entering” the block. |#
; see Note [Open blocks]
(struct open-list (type indent blockss) #:transparent)
(struct list-element (indent blocks) #:transparent)
(struct footnote (name blocks) #:transparent)
(define (leaf-block? block)
(or (paragraph? block)
(code-block? block)
(heading? block)
(horizontal-rule? block)))
(define (close-block block)
(match block
[(open-list 'unordered _ blockss) (unordered-list blockss)]
[(open-list 'ordered _ blockss) (ordered-list blockss)]
[(paragraph content) (paragraph (simplify-content content))]
[_ block]))
; Closes a sequence of open blocks. Returns two values:
; 1. a list of (closed) blocks
; 2. a list of footnotes declared in the given blocks
(define (close-blocks out-blocks)
(for/foldr ([blocks '()] [notes '()])
([out-block (in-list out-blocks)])
(match out-block
[(? leaf-block?)
(values (list (close-block out-block)) notes)]
[(footnote name old-blocks)
(values '() (cons (cons name (append old-blocks blocks)) notes))]
[_
(values (list (close-block (add-blocks out-block blocks))) notes)])))
(define (add-blocks open-block new-blocks)
(match open-block
[(document blocks targets notes) (document (append blocks new-blocks) targets notes)]
[(open-list type indent blockss) (open-list type indent (append blockss (map list-element-blocks new-blocks)))]
[(list-element indent blocks) (list-element indent (append blocks new-blocks))]
[(blockquote blocks) (blockquote (append blocks new-blocks))]
[(footnote name blocks) (footnote name (append blocks new-blocks))]))
(define (add-footnotes doc new-notes)
(define notes (append (document-footnotes doc) new-notes))
(struct-copy document doc [footnotes notes]))
(define (add-footnotes-to-out-blocks out-blocks new-notes)
(cons (add-footnotes (first out-blocks) new-notes) (rest out-blocks)))
(define (add-footnotes-to-in-blocks in-blocks new-notes)
(if (empty? new-notes)
in-blocks
(reverse (add-footnotes-to-out-blocks (reverse in-blocks) new-notes))))
; Handles the case where we reach the end of a line before we’ve seen enough
; indentation to enter all open blocks. Any blockquotes we aren’t already
; inside must be closed, since we didn’t see the `>` yet. Also, a paragraph is
; necessarily closed by a blank line.
(define (finish-blank-line in-blocks out-blocks)
(define-values [in-blocks* out-blocks*]
(splitf-at out-blocks (negate (disjoin paragraph? blockquote?))))
(match-define (cons inner-block other-blocks) (append (reverse in-blocks*) in-blocks))
(define-values [closed-blocks notes] (close-blocks out-blocks*))
(~> (reverse (cons (add-blocks inner-block closed-blocks) other-blocks))
(add-footnotes-to-out-blocks notes)))
;; -----------------------------------------------------------------------------
;; the parser
(define document/p
(lazy/p (scan-line-start (list (document '() (hash) '())))))
(define (scan-line-start out-blocks)
(or/p (do eof/p
(match-define-values [(list doc) notes] (close-blocks out-blocks))
(pure (add-footnotes doc notes)))
(lazy/p (scan-block-prefixes '() out-blocks))))
(define (scan-block-prefixes in-blocks out-blocks) ; see Note [In-blocks and out-blocks]
(match out-blocks
[(cons out-block out-blocks*)
(or/p
; Case 1: We’re definitely still in this block. (Well, mostly.
; See Note [Unconditionally parse list elements] for an example
; where we backtrack past `scan-block-prefix`.)
(do (scan-block-prefix out-block)
(scan-block-prefixes (cons out-block in-blocks) out-blocks*))
; Case 2: End of the (blank) line. We’re done.
(do newline/p
(scan-line-start (finish-blank-line in-blocks out-blocks)))
; Case 3: New content, but after some closed blocks.
(lazy/p (do (define-values [closed-blocks notes] (close-blocks out-blocks))
(match-define (cons inner-block other-blocks) (add-footnotes-to-in-blocks in-blocks notes))
(scan-block-content (add-blocks inner-block closed-blocks) other-blocks))))]
['()
; Case 4: Still inside every block, but there might be new content.
(do (match-define (cons inner-block other-blocks) in-blocks)
(scan-block-content inner-block other-blocks))]))
(define (scan-block-prefix out-block)
(do (try/p (do (match out-block
; Paragraphs must have actual content to enter them, since
; blank lines end paragraphs.
[(? paragraph?) (lookahead/p (char-not-in/p "\r\n"))]
[(open-list _ indent _) (spaces/p indent)]
[(list-element indent _) (spaces/p indent)]
[(? blockquote?) (char/p #\>)]
[(? footnote?) (spaces/p 4)]
[_ void/p])))
(match out-block
[(? blockquote?)
; If this is a blockquote, we need to consume an additional space, but
; it can be omitted if we’re at the end of a line.
(or/p (lookahead/p newline/p)
(char/p #\space))]
[_ void/p])))
(define (scan-block-content inner-block in-blocks)
(match inner-block
; If we’re in a paragraph, just append to its content.
[(paragraph content)
(do [new-content <- (many/p content/p)]
newline/p
(scan-line-start (reverse (cons (paragraph (list content new-content "\n")) in-blocks))))]
; If we’re in a codeblock, check for an end marker, otherwise append to its content.
[(code-block content language)
(or/p (do (try/p (string/p "```"))
newline/p
(scan-line-start (reverse (cons (add-blocks (first in-blocks) (list inner-block)) (rest in-blocks)))))
(do [new-content <- rest-of-line/p]
(scan-line-start (reverse (cons (code-block (string-append content new-content "\n") language) in-blocks)))))]
; If we’re in a list (but not a list element), parse a new list element.
; See Note [Unconditionally parse list elements] for why we don’t have to handle anything else.
[(open-list 'unordered _ _)
(do unordered-list-bullet/p
(scan-block-content (list-element 2 '()) (cons inner-block in-blocks)))]
[(open-list 'ordered _ _)
(do [bullet <- (syntax-box/p ordered-list-bullet/p)]
(scan-block-content (list-element (srcloc-span (syntax-box-srcloc bullet)) '())
(cons inner-block in-blocks)))]
; Otherwise, we’re in a container block, so try to start a new block.
[_
(or/p (do newline/p
(scan-line-start (reverse (cons inner-block in-blocks))))
; horizontal rules
(do (try/p (string/p "---"))
(many/p (char/p #\-))
newline/p
(scan-line-start (reverse (cons (add-blocks inner-block (list horizontal-rule)) in-blocks))))
; headings
(do [depth <- (try/p (do [depth-chars <- (many+/p (char/p #\#))]
space/p
(pure (length depth-chars))))]
[content <- (map/p simplify-content (many/p content/p))]
(scan-line-start (reverse (cons (add-blocks inner-block (list (heading depth content))) in-blocks))))
; footnote and link declarations
(scan-footnote-declaration (cons inner-block in-blocks))
(scan-link-target-declaration (cons inner-block in-blocks))
; blockquotes
(do (char/p #\>)
(or/p (lookahead/p newline/p)
(char/p #\space))
(scan-block-content (blockquote '()) (cons inner-block in-blocks)))
; code blocks
(do (try/p (string/p "```"))
[language <- (or/p (do newline/p (pure #f))
rest-of-line/p)]
(scan-line-start (reverse (list* (code-block "" language) inner-block in-blocks))))
; lists
(scan-list-start (cons inner-block in-blocks) 'unordered unordered-list-bullet/p)
(scan-list-start (cons inner-block in-blocks) 'ordered ordered-list-bullet/p)
; free-form content (new paragraph)
(scan-block-content (paragraph '()) (cons inner-block in-blocks)))]))
(define (scan-link-target-declaration in-blocks)
(do [name <- (try/p (do [name <- (around-string/p (char/p #\[) (char/p #\]))]
(char/p #\:)
(pure name)))]
(many/p (char/p #\space))
[dest <- rest-of-line/p]
(match-define (cons (document blocks targets notes) out-blocks) (reverse in-blocks))
(scan-line-start (cons (document blocks (hash-set targets name dest) notes) out-blocks))))
(define (scan-footnote-declaration in-blocks)
(do [name <- (try/p (do [name <- (around-string/p (string/p "[^") (char/p #\]))]
(char/p #\:)
(pure name)))]
(many/p (char/p #\space))
(scan-block-content (footnote name '()) in-blocks)))
(define (scan-list-start in-blocks type start-p)
(do [indent <- (try/p (do [indent <- maybe-indent/p]
(lookahead/p start-p)
(pure indent)))]
(scan-block-content (open-list type indent '()) in-blocks)))
#| Note [Unconditionally parse list elements]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider a markdown document that looks like this:
1 |* foo
2 |
3 |bar
The correct parse here is clearly an unordered list with a single element,
followed by a paragraph. However, because the list is unindented, we will end up
in a parsing context that looks like this at the beginning of line 3:
location: 3 |bar
^
state: scan-block-content
in blocks: document
inner block: open-list['unordered 0]
└ paragraph{foo}
At first blush, this is a problem, because in `scan-block-content`, we
/unconditionally/ parse a list element if the innermost block is an `open-list`.
Since line 3 does not start with a `*` or `-`, the parser fails.
However, note that the parser fails /without consuming input/. It is not
immediately obvious that this helps---calls to `scan-block-content` are usually
placed as the /last/ alternative of an `or/p` sequence---but in fact this
failure allows backtracking to an even earlier choice point. Specifically, it
can backtrack all the way to this state:
location: 3 |bar
^
state: scan-block-prefixes
in blocks: document
out blocks: open-list['unordered 0]
list-element[2]
└ paragraph{foo}
Note, crucially, that we’ve backtracked far enough that the `open-list` is still
in `out-blocks`, not `in-blocks`. This is somewhat surprising, because
`scan-block-prefix` will always succeed on an unindented `open-list`,
immediately moving it into `in-blocks`. However, since `scan-block-prefix` does
not consume any input in that case, the parser has not yet committed to entering
that block.
This subtlety means we do not need to treat this case specially in
`scan-block-content`: we can just unconditionally parse a list element when
inside an `open-list`. And intuitively, this makes some sense given
megaparsack’s backtracking behavior: the parser only commits when consuming
input, and at the start of the line, no input has been consumed. |#
| false |
3a55c81a1864e894638af14db075e3fc3e692c43 | 6359e6a83c6e867c7ec4ee97c5b4215fe6867fdf | /survival-minecraft/scribblings/assets-library.rkt | 209e98be64e225b9e47cc18c94c5791b9de2f75e | [] | no_license | thoughtstem/TS-GE-Languages | 629cba7d38775f4b636b328dfe8297cd79b5e787 | 49a8ad283230e5bcc38d583056271876c5d6556e | refs/heads/master | 2020-04-13T21:22:38.618374 | 2020-02-03T22:44:30 | 2020-02-03T22:44:30 | 163,454,521 | 3 | 0 | null | 2020-02-03T22:44:32 | 2018-12-28T22:28:18 | Racket | UTF-8 | Racket | false | false | 1,508 | rkt | assets-library.rkt | #lang scribble/manual
@(require game-engine
game-engine-demos-common
fandom-sprites-ge)
@require[scribble/extract]
@title{Assets Library}
@section{Skins, Mobs and Entities}
@defthing[steve-sprite animated-sprite?]
@(sprite->sheet steve-sprite)
@defthing[alex-sprite animated-sprite?]
@(sprite->sheet alex-sprite)
@defthing[chicken-sprite animated-sprite?]
@(sprite->sheet chicken-sprite)
@defthing[pig-sprite animated-sprite?]
@(sprite->sheet pig-sprite)
@defthing[sheep-sprite animated-sprite?]
@(sprite->sheet sheep-sprite)
@defthing[creeper-sprite animated-sprite?]
@(sprite->sheet creeper-sprite)
@defthing[skeleton-sprite animated-sprite?]
@(sprite->sheet skeleton-sprite)
@defthing[ghast-sprite animated-sprite?]
@(sprite->sheet ghast-sprite)
@section{Ores and Other Items}
@defthing[coalore-sprite image?]
@coalore-sprite
@defthing[ironore-sprite image?]
@ironore-sprite
@defthing[copperore-sprite image?]
@copperore-sprite
@defthing[goldore-sprite image?]
@goldore-sprite
@defthing[meseore-sprite image?]
@meseore-sprite
@defthing[diamondore-sprite image?]
@diamondore-sprite
@defthing[coallump-sprite image?]
@coallump-sprite
@defthing[ironlump-sprite image?]
@ironlump-sprite
@defthing[copperlump-sprite image?]
@copperlump-sprite
@defthing[goldingot-sprite image?]
@goldingot-sprite
@defthing[mesecrystal-sprite image?]
@mesecrystal-sprite
@defthing[diamond-sprite image?]
@diamond-sprite
@; ---
@(include-section survival/scribblings/assets-library) | false |
1d984ebb8e33b236f89c383c0266d12960b590cb | 53542701f473a1bf606ae452ed601543d686e514 | /Minor Assignment 1/submission/160050064/5.rkt | 61875bf55150ff398ff0e0b02bd537454deaaebe | [
"MIT"
] | permissive | vamsi3/IITB-Abstractions-and-Paradigms | f6c187a6d1376ca08dd4c2b18258144627eaed6b | ab80fc33341ba0ba81d1519c92efd7e06127b86b | refs/heads/master | 2022-10-23T23:45:18.907063 | 2020-06-09T15:41:33 | 2020-06-09T15:41:33 | 271,042,673 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 264 | rkt | 5.rkt | #lang racket
;Define function coeffs below
;Do not call the function here
(define (coeffs a b)
(if (= b 0) (cons 1 0)
(let* [(x (car (coeffs b (modulo a b))))
(y (cdr (coeffs b (modulo a b))))]
(cons y (- x (* (quotient a b) y))))))
| false |
13469a09d0544a7ca442bda616004afee7668196 | 9dc77b822eb96cd03ec549a3a71e81f640350276 | /streaming/transducer/private/enumerating.rkt | a32bbc3a7537e2d21427d15ca38dbc4830132517 | [
"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 | 1,167 | rkt | enumerating.rkt | #lang racket/base
(require racket/contract/base)
(provide
(contract-out
[enumerated? predicate/c]
[enumerated (-> #:element any/c #:position natural? enumerated?)]
[enumerated-element (-> enumerated? any/c)]
[enumerated-position (-> enumerated? natural?)]
[enumerating (transducer/c any/c enumerated?)]))
(require racket/math
rebellion/base/impossible-function
rebellion/base/variant
rebellion/private/static-name
rebellion/streaming/transducer/private/contract
rebellion/streaming/transducer/base
rebellion/type/record)
;@------------------------------------------------------------------------------
(define-record-type enumerated (element position))
(define/name enumerating
(make-transducer
#:starter (λ () (variant #:consume 0))
#:consumer
(λ (position element)
(variant #:emit (enumerated #:element element #:position position)))
#:emitter
(λ (enum)
(emission (variant #:consume (add1 (enumerated-position enum))) enum))
#:half-closer (λ (_) (variant #:finish #f))
#:half-closed-emitter impossible
#:finisher void
#:name enclosing-variable-name))
| false |
fd925d16d3cdf4675f3c375e39719f0e4f69e530 | fb979eb8befb69705ac6814965fad57ae8e76749 | /ui/utilities.rkt | 591dbc06c7a3826889857cac855b7a30710020b3 | [] | no_license | stamourv/roguelike | a0371ece8cae44d5a596ce2625257f38bf223874 | c3edf2d602e215ecf28d0cad68dc545b7599a93b | refs/heads/master | 2021-01-01T18:43:15.324004 | 2013-04-07T22:46:19 | 2013-04-07T22:46:19 | 2,559,500 | 3 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 3,256 | rkt | utilities.rkt | #lang racket
(require racket/require)
(require (multi-in "../utilities" ("grid.rkt" "terminal.rkt"))
(multi-in "../engine" ("character.rkt" "player.rkt" "common.rkt"
"items.rkt"))
"display.rkt")
(provide (all-defined-out))
(define command-table '())
(define (new-command char thunk category desc)
(set! command-table (cons (list char thunk category desc) command-table)))
(define (reverse-command-table)
(set! command-table (reverse command-table)))
(define (invalid-command) (display "Invalid command.\n"))
;; print a large block of text
;; if it doesn't fit, ask to continue, then display
;; returns new line number
(define (print-paragraph s line-at)
(let ([n-lines (length (regexp-split "\n" s))])
(cond [(> (+ line-at n-lines) 22) ; to leave space for scroll message
(display "There's more.")
(wait-after-long-output)
(display s)
n-lines] ; we had to wrap around
[else
(display s)
(+ line-at n-lines)])))
(define (wait-after-long-output)
(newline)
(displayln "Press any key to continue.")
(read-char)
(for ([i (in-range 30)]) (newline)))
(define (choose-direction)
(if (= (char->integer (read-char)) 27) ; escape
(case (which-direction?)
((up) up)
((down) down)
((left) left)
((right) right))
(begin (invalid-command)
#f)))
(define (which-direction?)
(define char (read-char))
(when (not (or (eq? char #\[)
(eq? char #\O))) ; emacs's ansi-term uses this
(invalid-command))
(case (read-char)
((#\A) 'up)
((#\B) 'down)
((#\C) 'right)
((#\D) 'left)
(else (invalid-command))))
(define (read-number n) ; read a number up to n, or q to cancel
(let loop ((nb (read-char)))
(cond ((eq? nb #\q)
#f) ; cancel
((not (and (char>=? nb #\1)
(<= (- (char->integer nb) (char->integer #\0)) n)))
(loop (read-char)))
(else
(- (char->integer nb)
(char->integer #\0) 1)))))
(define (choice items f null-message question feedback)
(cond [(null? items)
(printf "~a\n" null-message)]
[else
(cursor-home)
(clear-to-bottom)
(printf "~a\nq: Cancel\n" question)
(for ([o (in-list items)]
[i (in-naturals)])
(printf "~a: ~a\n" (+ i 1) (item-info o)))
(define nb (read-number (length items)))
(when nb
(define item (list-ref items nb))
(print-state)
(f item)
(printf "~a~a.\n" feedback (item-info item)))]))
(define (direction-command name f)
(clear-to-bottom)
(printf "~a in which direction? " name)
(flush-output)
(let ((dir (choose-direction))) ; evaluates to a function, or #f
(when dir
(let* ((grid (player-map player))
(cell (grid-ref grid (dir (character-pos player)))))
(f grid cell player)))))
;; console from which arbitrary expressions can be evaluated
(define (console)
(restore-tty)
(display ": ")
;; untouched from the Gambit version. unlikely to work
(display (eval (read)))
(read-char)
(intercept-tty))
| false |
719a22173cbcdb9db0cb494f7eae11a49cb398f4 | e553691752e4d43e92c0818e2043234e7a61c01b | /sdsl/ifc/call.rkt | abcb49835841b8eac1234a41c0b439fcc3dbff77 | [
"BSD-2-Clause"
] | permissive | emina/rosette | 2b8c1bcf0bf744ba01ac41049a00b21d1d5d929f | 5dd348906d8bafacef6354c2e5e75a67be0bec66 | refs/heads/master | 2023-08-30T20:16:51.221490 | 2023-08-11T01:38:48 | 2023-08-11T01:38:48 | 22,478,354 | 656 | 89 | NOASSERTION | 2023-09-14T02:27:51 | 2014-07-31T17:29:18 | Racket | UTF-8 | Racket | false | false | 4,810 | rkt | call.rkt | #lang rosette
(require "machine.rkt" )
(provide (all-defined-out))
; See Section 5 of the full draft of "Testing Noninterference, Quickly".
; The basic semantics is expressed using the next, goto,
; peek, push, pop, pop-until, read and write primitives
; for manipulating machine state. These are defined in machine.rkt.
; The basic semantics is defined in basic.rkt.
;
; To make instruction implementation uniform, we use values rather
; than integers for Call and Return arguments; the label of the value
; is simply ignored.
(define (Call*B m k)
(let@ ([(k Lk) k]
[(x Lx) (peek m 0)]
[(pc Lpc) (pc m)])
(assert (equal? Lk ⊥))
(goto (push (pop m) k (R (@ (add1 pc) Lpc))) (@ x (∨ Lx Lpc)))))
(define (Return*AB m n)
(let@ ([(n Ln) n]
[v (peek m 0)]
[m (pop-until m return?)]
[r (peek m 0)])
(assert (equal? Ln ⊥))
(assert (|| (= 0 n) (= 1 n)))
(if (= n 0)
(goto (pop m) (Rpc r))
(goto (push (pop m) v) (Rpc r)))))
(define (Return*B m n)
(let@ ([(n Ln) n]
[(_ Lpc) (pc m)]
[(v _) (peek m 0)]
[m (pop-until m return?)]
[r (peek m 0)])
(assert (equal? Ln ⊥))
(assert (|| (= 0 n) (= 1 n)))
(if (= n 0)
(goto (pop m) (Rpc r))
(goto (push (pop m) (@ v Lpc)) (Rpc r))))) ; bug (see Return)
; We use StoreCR for the Store rule that is correct in
; the presence of Call/Return to avoid conflict with the
; basic Store rule.
(define (StoreCR m)
(let@ ([(x Lx) (peek m 0)]
[(y Ly) (peek m 1)]
[(_ Lpc) (pc m)]
[(_ Lmx) (read m x)])
(assert (⊑ (∨ Lpc Lx) Lmx) "no sensitive upgrade")
(next (write (pop m 2) x (@ y (∨ Lx Ly Lpc))))))
(define (PopCR m)
(assert (value? (peek m)))
(next (pop m)))
(define (Call m k n)
(let@ ([(k Lk) k]
[(vn Ln) n]
[(x Lx) (peek m 0)]
[(pc Lpc) (pc m)])
(assert (equal? Lk ⊥))
(assert (equal? Ln ⊥))
(assert (|| (= 0 vn) (= 1 vn)))
(goto (push (pop m) k (R (@ (add1 pc) Lpc) n)) (@ x (∨ Lx Lpc)))))
; Bug in the paper: the label on the returned value should be joined
; with the PC label (it cannot be just the PC label).
(define (Return m)
(let@ ([(v Lv) (peek m 0)]
[m (pop-until m return?)]
[r (peek m 0)]
[(n _) (Rn r)]
[(_ Lpc) (pc m)])
(if (= n 0)
(goto (pop m) (Rpc r))
(goto (push (pop m) (@ v (∨ Lv Lpc))) (Rpc r)))))
#|
(define p0
(vector-immutable
(instruction Push (@ 3 ⊤))
(instruction Call*B 0@⊥)
(instruction Halt)
(instruction Push (@ 1 ⊥))
(instruction Push 0@⊥)
(instruction Store)
(instruction Return*AB 0@⊥)))
(define p1
(vector-immutable
(instruction Push (@ 6 ⊤))
(instruction Call*B 0@⊥)
(instruction Halt)
(instruction Push (@ 1 ⊥))
(instruction Push 0@⊥)
(instruction Store)
(instruction Return*AB 0@⊥)))
(define m0 (init p0))
(define m1 (init p1))
(define m0k (step m0 7))
(define m1k (step m1 7))
m0k
m1k|#
#|
(define (Call*B m n)
(let@ ([(n Ln) n]
[(x Lx) (peek m 0)]
[(pc Lpc) (pc m)])
(assert (equal? Ln ⊥)) ; ignore Ln
(goto (push (pop m) n (R (@ (add1 pc) Lpc))) (@ x (∨ Lx Lpc)))))
(define (Return*AB m n)
(cond [(= (@int n) 0)
(let@ ([m (pop-until m return?)]
[r (peek m 0)])
(goto (pop m) (Rpc r)))]
[else
(assert (= (@int n) 1))
(let@ ([v (peek m 0)]
[m (pop-until (pop m) return?)]
[r (peek m 0)])
(goto (push (pop m) v) (Rpc r)))]))
(define (Return*B m n)
(cond [(= (@int n) 0)
(let@ ([m (pop-until m return?)]
[r (peek m 0)])
(goto (pop m) (Rpc r)))]
[else
(assert (= (@int n) 1))
(let@ ([(v Lv) (peek m 0)]
[m (pop-until (pop m) return?)]
[r (peek m 0)]
[(_ Lpc) (pc m)])
(goto (push (pop m) (@ v Lpc)) (Rpc r)))]))
(define (Call m n v)
(assert (|| (= 0 (@int v)) (= 1 (@int v))))
(assert (equal? ⊥ (@label v)))
(assert (equal? ⊥ (@label n)))
(let@ ([(n _) n]
[(x Lx) (peek m 0)]
[(pc Lpc) (pc m)])
(goto (push (pop m) n (R (@ (add1 pc) Lpc) v)) (@ x (∨ Lx Lpc)))))
; Bug in the paper: the label on the returned value should be joined
; with the PC label (it cannot be just the PC label).
(define (Return m)
(let@ ([(v Lv) (peek m 0)]
[m (pop-until m return?)]
[r (peek m 0)]
[(n _) (Rn r)]
[(_ Lpc) (pc m)])
(if (= n 0)
(goto (pop m) (Rpc r))
(goto (push (pop m) (@ v (∨ Lv Lpc))) (Rpc r)))))
|#
| false |
9c2f89ce111bfdd95c0b91ba217fcb9aca422e9f | 657061c0feb2dcbff98ca7a41b4ac09fe575f8de | /Racket/Exercises/Week3/06_increasing_digits.rkt | 1d7f6eb1858c3c40fd1574d9b152ef15b893d6a7 | [] | no_license | vasil-pashov/FunctionalProgramming | 77ee7d9355329439cc8dd89b814395ffa0811975 | bb998a5df7b715555d3272c3e39b0a7481acf80a | refs/heads/master | 2021-09-07T19:31:05.031600 | 2018-02-27T20:50:44 | 2018-02-27T20:50:44 | 108,046,015 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 328 | rkt | 06_increasing_digits.rkt | #lang racket
;Check if the digits of a number are in increasing order
(define (increasing? n)
(define (increasing-helper n prev)
(define last (remainder n 10))
(cond
([= n 0] #t)
([< prev last] #f)
[(= prev last) #f]
[else (increasing-helper (quotient n 10) last)]))
(increasing-helper n 10)) | false |
36393ce5e41500abd408007e5310f7a0b04ee562 | 061099091e885c2667a618cf4da2a1eb435f1231 | /src/vm.rkt | 503ddc3c9180ef91b3d03ff801b4d94fc3d6efc9 | [] | no_license | Idorobots/low-level-linear-logic-lisp-like-language | 4c1f19a5a25b63435fef27bc9c0a66160da6a43d | 1605c10bc3e7ac7fd134c1a4bffef7b749edc24c | refs/heads/master | 2021-06-16T22:23:42.013445 | 2017-05-31T17:27:11 | 2017-05-31T17:27:11 | 90,410,899 | 0 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 1,384 | rkt | vm.rkt | ;; VM & runtime state
#lang racket
(provide (all-defined-out))
(require "utils.rkt")
(define :halt -1)
(define pc 0)
(define tpc 1) ;; FIXME Get rid of this.
(define r0 2)
(define r1 3)
(define r2 4)
(define r3 5)
(define t0 6)
(define t1 7)
(define t2 8)
(define t3 9)
(define sp 10)
(define fr 11)
(define (state pc tpc r0 r1 r2 r3 t0 t1 t2 t3 sp fr)
(list pc tpc r0 r1 r2 r3 t0 t1 t2 t3 sp fr))
(define (init-state cells)
(state 0
0
'nil 'nil 'nil 'nil ;; Main registers.
'nil 'nil 'nil 'nil ;; Temp registers.
'nil ;; Stack pointer.
(make-cells cells))) ;; Free list.
(define (state-format state)
(define (n-cells cells)
(if (pair? cells)
(+ 1 (n-cells (cdr cells)))
0))
(string-append
(apply format
"pc=~s, tpc=~s, r0=~s, r1=~s, r2=~s, r3=~s, t0=~s, t1=~s, t2=~s, t3=~s, sp=~s, "
(take state (- (length state) 1)))
(let ((v (last state)))
(if (atom? v)
(format "fr=~s" v)
(format "fr: ~s cells" (n-cells v))))))
(define (reg state r)
(list-ref state r))
(define (reg-set state r value)
(if (equal? r 0)
(cons value (cdr state))
(cons (car state)
(reg-set (cdr state) (- r 1) value))))
(define (set-pc-jmp state value)
;; Accomodates the pc increment when running.
(reg-set state pc (- value 1)))
| false |
41012461643d7eb0beb791fddbf5bf9df107dc2a | 53543edaeff891dd1c2a1e53fc9a1727bb9c2328 | /benchmarks/lnm/typed/pict-adapted.rkt | a37cd8ddbd4f7198894767711b9a3f1fda6935e9 | [
"MIT"
] | permissive | bennn/gtp-checkup | b836828c357eb5f9f2b0e39c34b44b46f2e97d22 | 18c69f980ea0e59eeea2edbba388d6fc7cc66a45 | refs/heads/master | 2023-05-28T16:26:42.676530 | 2023-05-25T03:06:49 | 2023-05-25T03:06:49 | 107,843,261 | 2 | 0 | NOASSERTION | 2019-04-25T17:12:26 | 2017-10-22T06:39:33 | Racket | UTF-8 | Racket | false | false | 92 | rkt | pict-adapted.rkt | #lang typed/racket/base
(require/typed pict
[#:opaque Pict pict?])
(provide Pict pict?)
| false |
84372d368c96a3ed702a596ba1127400348d3bb4 | 6607830c82e96892649a15fe8866cdac1ee8ba1d | /sequential/examples/Church/rkt-code/Abstraction.rkt | e6ab4ad4dfd1f051477d3bb30f52e8676b233ad2 | [] | no_license | ericmercer/javalite | 6d83b4d539b31a5f2ff9b73a65a56f48368f1aa0 | 6de3f4de11ca04e8b94fca65037aee5ba9498b5b | refs/heads/master | 2020-06-08T22:12:55.071149 | 2012-11-02T04:30:10 | 2012-11-02T04:30:10 | 5,751,778 | 2 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 5,324 | rkt | Abstraction.rkt | #lang racket
(require redex/reduction-semantics)
(provide (all-defined-out))
(define Abstraction-class
(term (class Abstraction extends LambdaTerm
([LambdaTerm t]
[Variable x]
[Function f])
(
(Abstraction construct-x-t([Variable x] [LambdaTerm t])
(begin
(this $ t := t)
(this $ x := x)
(this $ f := null)
this))
(Abstraction construct-x-f([Variable x] [Function f])
(begin
(this $ t := x)
(this $ x := x)
(this $ f := f)
this))
(Abstraction construct-x-t-f([Variable x] [LambdaTerm t] [Function f])
(begin
(this $ t := t)
(this $ x := x)
(this $ f := f)
this))
(LambdaTerm cas ([Variable x] [LambdaTerm r])
(var LamdaTerm v := null in
(var Variable y := (this $ x) in
(var Variable z := null in
(begin
(if (x == y)
(v := this)
else
(if
((r @ isFree (y)) == false)
(v := ((new Abstraction) @ construct-x-t-f (y ((this $ t) @ cas (x r)) (this $ f))))
else
(begin
(z := (new Variable))
(v := ((new Abstraction) @ construct-x-t-f (z (((this $ t) @ ar (y z)) @ cas (x r)) (this $ f)))))))
v)))))
(bool isFree ([Variable x])
(var bool v := false in
(begin
(if ((x == (this $ x)) == false)
(if (((this $ t) @ isFree (x)) == true)
(v := true)
else
(v := false))
else
(v := false))
v)))
(LambdaTerm br([LambdaTerm s])
(var LambdaTerm v := ((this $ t) @ cas ((this $ x) s)) in
(begin
(if (((this $ f) == null) == false)
((this $ f) @ eval ())
else
unit)
v)))
(LambdaTerm ar-abstraction([Variable x])
(var Variable y := (this $ x) in
((new Abstraction) @ construct-x-t-f (x ((this $ t) @ ar(y x)) (this $ f)))))
(LambdaTerm ar([Variable oldVar] [Variable newVar])
(var LambdaTerm v := null in
(var Variable y := (this $ x) in
(var Variable z := null in
(begin
(if (y == oldVar)
(v := this)
else
(if (y == newVar)
(begin
(z := (new Variable))
(v := ((this @ ar-abstraction (z)) @ ar (oldVar newVar))))
else
(v := ((new Abstraction) @ construct-x-t-f ((this $ x)
((this $ t) @ ar (oldVar newVar))
(this $ f))))))
v)))))
(bool isAe ([LambdaTerm x])
(var bool v := false in
(var Abstraction a := null in
(begin
(if (x instanceof Abstraction)
(begin
(a := (Abstraction x))
(if (((this $ x) @ isAe ((a $ x))) == false)
(a := (Abstraction (a @ ar-abstraction ((this $ x)))))
else
unit)
(v := ((this $ t) @ isAe ((a $ t)))))
else
unit)
v))))
(LambdaTerm eval ()
this)
))))
| false |
3b5f61ddd7fc98d63ecc350e708f966b1c4fc2d3 | 7e15b782f874bcc4192c668a12db901081a9248e | /eopl/ch4/ex-4.40/interp.rkt | 1ed7046b2701d5b26976f701961ac6a8de698bb8 | [] | no_license | Javran/Thinking-dumps | 5e392fe4a5c0580dc9b0c40ab9e5a09dad381863 | bfb0639c81078602e4b57d9dd89abd17fce0491f | refs/heads/master | 2021-05-22T11:29:02.579363 | 2021-04-20T18:04:20 | 2021-04-20T18:04:20 | 7,418,999 | 19 | 4 | null | null | null | null | UTF-8 | Racket | false | false | 4,643 | rkt | interp.rkt | (module interp (lib "eopl.ss" "eopl")
;; interpreter for the CALL-BY-NEED language.
(require "drscheme-init.rkt")
(require "lang.rkt")
(require "data-structures.rkt")
(require "environments.rkt")
(require "store.rkt")
(require "pairvals.rkt")
(provide value-of-program value-of instrument-newref)
;;; exercise: add instrumentation around let and procedure calls, as
;;; in the call-by-reference language.
;;;;;;;;;;;;;;;; the interpreter ;;;;;;;;;;;;;;;;
;; value-of-program : Program -> ExpVal
(define value-of-program
(lambda (pgm)
(initialize-store!)
(cases program pgm
(a-program (body)
(value-of body (init-env))))))
;; value-of : Exp * Env -> ExpVal
;; Page: 137 and 138
(define value-of
(lambda (exp env)
(cases expression exp
(const-exp (num) (num-val num))
(var-exp (var)
(let ((ref1 (apply-env env var)))
(let ((w (deref ref1)))
(if (expval? w)
w
(let ((v1 (value-of-thunk w)))
(begin
(setref! ref1 v1)
v1))))))
(diff-exp (exp1 exp2)
(let ((val1
(expval->num
(value-of exp1 env)))
(val2
(expval->num
(value-of exp2 env))))
(num-val
(- val1 val2))))
(zero?-exp (exp1)
(let ((val1 (expval->num (value-of exp1 env))))
(if (zero? val1)
(bool-val #t)
(bool-val #f))))
(if-exp (exp0 exp1 exp2)
(if (expval->bool (value-of exp0 env))
(value-of exp1 env)
(value-of exp2 env)))
(let-exp (var exp1 body)
(let ((val (value-of exp1 env)))
(value-of body
(extend-env var (newref val) env))))
(proc-exp (var body)
(proc-val
(procedure var body env)))
(call-exp (rator rand)
(let ((proc (expval->proc (value-of rator env)))
(arg (value-of-operand rand env)))
(apply-procedure proc arg)))
(letrec-exp (p-names b-vars p-bodies letrec-body)
(value-of letrec-body
(extend-env-rec* p-names b-vars p-bodies env)))
(begin-exp (exp1 exps)
(letrec
((value-of-begins
(lambda (e1 es)
(let ((v1 (value-of e1 env)))
(if (null? es)
v1
(value-of-begins (car es) (cdr es)))))))
(value-of-begins exp1 exps)))
(assign-exp (x e)
(begin
(setref!
(apply-env env x)
(value-of e env))
(num-val 27)))
(newpair-exp (exp1 exp2)
(let ((v1 (value-of exp1 env))
(v2 (value-of exp2 env)))
(mutpair-val (make-pair v1 v2))))
(left-exp (exp1)
(let ((v1 (value-of exp1 env)))
(let ((p1 (expval->mutpair v1)))
(left p1))))
(setleft-exp (exp1 exp2)
(let ((v1 (value-of exp1 env))
(v2 (value-of exp2 env)))
(let ((p (expval->mutpair v1)))
(begin
(setleft p v2)
(num-val 82)))))
(right-exp (exp1)
(let ((v1 (value-of exp1 env)))
(let ((p1 (expval->mutpair v1)))
(right p1))))
(setright-exp (exp1 exp2)
(let ((v1 (value-of exp1 env))
(v2 (value-of exp2 env)))
(let ((p (expval->mutpair v1)))
(begin
(setright p v2)
(num-val 83)))))
)))
;; apply-procedure : Proc * Ref -> ExpVal
(define apply-procedure
(lambda (proc1 arg)
(cases proc proc1
(procedure (var body saved-env)
(value-of body
(extend-env var arg saved-env))))))
;; value-of-operand : Exp * Env -> Ref
;; Page: 137
(define value-of-operand
(lambda (exp env)
(cases expression exp
(var-exp (var) (apply-env env var)) ; no deref!
; * constants need to be stored to get a ref
(const-exp (n)
; use `value-of` as it has already handled everything for us.
(newref (value-of exp env)))
(proc-exp (var body)
(newref (value-of exp env)))
(else
(newref (a-thunk exp env))))))
;; value-of-thunk : Thunk -> ExpVal
(define value-of-thunk
(lambda (th)
(cases thunk th
(a-thunk (exp1 saved-env)
(value-of exp1 saved-env)))))
)
| false |
df391a928d8cdc17b4c26cfe87cbbf82bbf92d1b | b98c135aff9096de1311926c2f4f401be7722ca1 | /sgml/digitama/prentity.rkt | 91ab7c03ac2f747ff9e068300c21f0306db5bba4 | [] | no_license | wargrey/w3s | 944d34201c16222abf51a7cf759dfed11b7acc50 | e5622ad2ca6ec675fa324d22dd61b7242767fb53 | refs/heads/master | 2023-08-17T10:26:19.335195 | 2023-08-09T14:17:45 | 2023-08-09T14:17:45 | 75,537,036 | 3 | 1 | null | 2022-02-12T10:59:27 | 2016-12-04T12:49:33 | Racket | UTF-8 | Racket | false | false | 865 | rkt | prentity.rkt | #lang typed/racket/base
(provide (all-defined-out))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define < : Symbol (string->unreadable-symbol "lt"))
(define > : Symbol (string->unreadable-symbol "gt"))
(define & : Symbol (string->unreadable-symbol "amp"))
(define &apos : Symbol (string->unreadable-symbol "apos"))
(define " : Symbol (string->unreadable-symbol "quot"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define xml-prentity-value-ref : (-> Symbol (Option Char))
;;; https://www.w3.org/TR/xml/#sec-predefined-ent
(lambda [name]
(cond [(eq? name <) #\u3c]
[(eq? name >) #\u3e]
[(eq? name &) #\u26]
[(eq? name &apos) #\u27]
[(eq? name ") #\u22]
[else #false])))
| false |
e2d020e97ffc2d355acd7d766265e94dbfa31744 | 01f1f5d15fcd3e29fb6086131963cd17fb4669d3 | /src/spec/colors.rkt | d824e898cb84569e223da0d9a7dbd52b6dde9d58 | [
"MIT"
] | permissive | uwplse/Cassius | 1664e8c82c10bcc665901ea92ebf4a48ee28525e | 60dad9e9b2b4de3b13451ce54cdc1bd55ca64824 | refs/heads/master | 2023-02-22T22:27:54.223521 | 2022-12-24T18:18:25 | 2022-12-24T18:18:25 | 29,879,625 | 88 | 1 | MIT | 2021-06-08T00:13:38 | 2015-01-26T20:18:28 | Racket | UTF-8 | Racket | false | false | 6,558 | rkt | colors.rkt | #lang racket
(require "../common.rkt" "../smt.rkt" "../encode.rkt")
(provide colors color-table)
(define color-table
#hash((aliceblue . (rgb 240 248 255))
(antiquewhite . (rgb 250 235 215))
(aqua . (rgb 0 255 255))
(aquamarine . (rgb 127 255 212))
(azure . (rgb 240 255 255))
(beige . (rgb 245 245 220))
(bisque . (rgb 255 228 196))
(black . (rgb 0 0 0))
(blanchedalmond . (rgb 255 235 205))
(blue . (rgb 0 0 255))
(blueviolet . (rgb 138 43 226))
(brown . (rgb 165 42 42))
(burlywood . (rgb 222 184 135))
(cadetblue . (rgb 95 158 160))
(chartreuse . (rgb 127 255 0))
(chocolate . (rgb 210 105 30))
(coral . (rgb 255 127 80))
(cornflowerblue . (rgb 100 149 237))
(cornsilk . (rgb 255 248 220))
(crimson . (rgb 220 20 60))
(cyan . (rgb 0 255 255))
(darkblue . (rgb 0 0 139))
(darkcyan . (rgb 0 139 139))
(darkgoldenrod . (rgb 184 134 11))
(darkgray . (rgb 169 169 169))
(darkgrey . (rgb 169 169 169))
(darkgreen . (rgb 0 100 0))
(darkkhaki . (rgb 189 183 107))
(darkmagenta . (rgb 139 0 139))
(darkolivegreen . (rgb 85 107 47))
(darkorange . (rgb 255 140 0))
(darkorchid . (rgb 153 50 204))
(darkred . (rgb 139 0 0))
(darksalmon . (rgb 233 150 122))
(darkseagreen . (rgb 143 188 143))
(darkslateblue . (rgb 72 61 139))
(darkslategray . (rgb 47 79 79))
(darkslategrey . (rgb 47 79 79))
(darkturquoise . (rgb 0 206 209))
(darkviolet . (rgb 148 0 211))
(deeppink . (rgb 255 20 147))
(deepskyblue . (rgb 0 191 255))
(dimgray . (rgb 105 105 105))
(dimgrey . (rgb 105 105 105))
(dodgerblue . (rgb 30 144 255))
(firebrick . (rgb 178 34 34))
(floralwhite . (rgb 255 250 240))
(forestgreen . (rgb 34 139 34))
(fuchsia . (rgb 255 0 255))
(gainsboro . (rgb 220 220 220))
(ghostwhite . (rgb 248 248 255))
(gold . (rgb 255 215 0))
(goldenrod . (rgb 218 165 32))
(gray . (rgb 128 128 128))
(grey . (rgb 128 128 128))
(green . (rgb 0 128 0))
(greenyellow . (rgb 173 255 47))
(honeydew . (rgb 240 255 240))
(hotpink . (rgb 255 105 180))
(indianred . (rgb 205 92 92))
(indigo . (rgb 75 0 130))
(ivory . (rgb 255 255 240))
(khaki . (rgb 240 230 140))
(lavender . (rgb 230 230 250))
(lavenderblush . (rgb 255 240 245))
(lawngreen . (rgb 124 252 0))
(lemonchiffon . (rgb 255 250 205))
(lightblue . (rgb 173 216 230))
(lightcoral . (rgb 240 128 128))
(lightcyan . (rgb 224 255 255))
(lightgoldenrodyellow . (rgb 250 250 210))
(lightgray . (rgb 211 211 211))
(lightgrey . (rgb 211 211 211))
(lightgreen . (rgb 144 238 144))
(lightpink . (rgb 255 182 193))
(lightsalmon . (rgb 255 160 122))
(lightseagreen . (rgb 32 178 170))
(lightskyblue . (rgb 135 206 250))
(lightslategray . (rgb 119 136 153))
(lightslategrey . (rgb 119 136 153))
(lightsteelblue . (rgb 176 196 222))
(lightyellow . (rgb 255 255 224))
(lime . (rgb 0 255 0))
(limegreen . (rgb 50 205 50))
(linen . (rgb 250 240 230))
(magenta . (rgb 255 0 255))
(maroon . (rgb 128 0 0))
(mediumaquamarine . (rgb 102 205 170))
(mediumblue . (rgb 0 0 205))
(mediumorchid . (rgb 186 85 211))
(mediumpurple . (rgb 147 112 219))
(mediumseagreen . (rgb 60 179 113))
(mediumslateblue . (rgb 123 104 238))
(mediumspringgreen . (rgb 0 250 154))
(mediumturquoise . (rgb 72 209 204))
(mediumvioletred . (rgb 199 21 133))
(midnightblue . (rgb 25 25 112))
(mintcream . (rgb 245 255 250))
(mistyrose . (rgb 255 228 225))
(moccasin . (rgb 255 228 181))
(navajowhite . (rgb 255 222 173))
(navy . (rgb 0 0 128))
(oldlace . (rgb 253 245 230))
(olive . (rgb 128 128 0))
(olivedrab . (rgb 107 142 35))
(orange . (rgb 255 165 0))
(orangered . (rgb 255 69 0))
(orchid . (rgb 218 112 214))
(palegoldenrod . (rgb 238 232 170))
(palegreen . (rgb 152 251 152))
(paleturquoise . (rgb 175 238 238))
(palevioletred . (rgb 219 112 147))
(papayawhip . (rgb 255 239 213))
(peachpuff . (rgb 255 218 185))
(peru . (rgb 205 133 63))
(pink . (rgb 255 192 203))
(plum . (rgb 221 160 221))
(powderblue . (rgb 176 224 230))
(purple . (rgb 128 0 128))
(rebeccapurple . (rgb 102 51 153))
(red . (rgb 255 0 0))
(rosybrown . (rgb 188 143 143))
(royalblue . (rgb 65 105 225))
(saddlebrown . (rgb 139 69 19))
(salmon . (rgb 250 128 114))
(sandybrown . (rgb 244 164 96))
(seagreen . (rgb 46 139 87))
(seashell . (rgb 255 245 238))
(sienna . (rgb 160 82 45))
(silver . (rgb 192 192 192))
(skyblue . (rgb 135 206 235))
(slateblue . (rgb 106 90 205))
(slategray . (rgb 112 128 144))
(slategrey . (rgb 112 128 144))
(snow . (rgb 255 250 250))
(springgreen . (rgb 0 255 127))
(steelblue . (rgb 70 130 180))
(tan . (rgb 210 180 140))
(teal . (rgb 0 128 128))
(thistle . (rgb 216 191 216))
(tomato . (rgb 255 99 71))
(turquoise . (rgb 64 224 208))
(violet . (rgb 238 130 238))
(wheat . (rgb 245 222 179))
(white . (rgb 255 255 255))
(whitesmoke . (rgb 245 245 245))
(yellow . (rgb 255 255 0))
(yellowgreen . (rgb 154 205 50))
))
(define-constraints (colors)
(declare-datatypes () ((RGBColor (color (color.r Real) (color.g Real) (color.b Real)
(color.r-corr Real) (color.g-corr Real) (color.b-corr Real)))))
(define-fun lum ((c RGBColor)) Real
(+
(* 0.2126 (color.r-corr c))
(* 0.7152 (color.g-corr c))
(* 0.0722 (color.b-corr c))))
(define-fun color.diff ((c1 RGBColor) (c2 RGBColor)) Real
(let ([r (- (color.r c1) (color.r c2))]
[g (- (color.g c1) (color.g c2))]
[b (- (color.b c1) (color.b c2))])
(+
(ite (>= r 0) r (- r))
(ite (>= g 0) g (- g))
(ite (>= b 0) b (- b))))))
| false |
410e496396b7a2071ee250e7f1bc15fa846bfd17 | bfdea13ca909b25a0a07c044ec456c00124b6053 | /mischief/scribblings/transform.scrbl | 2240c621ea4de5f6d974e4932971dcf45d833506 | [] | 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 | 6,489 | scrbl | transform.scrbl | #lang scribble/manual
@(require mischief/examples)
@(define-example-form transform-examples mischief (for-syntax mischief))
@title[#:tag "transform"]{@racketmodname[mischief/transform]: Syntax Transformers}
@defmodule[mischief/transform]
@section{Converting Values to/from Syntax}
@defproc[
(to-syntax
[x any/c]
[#:stx stx (or/c syntax? #false) #false]
[#:context context (or/c syntax? #false) stx]
[#:source source source-location? stx]
[#:prop prop (or/c syntax? #false) stx])
syntax?
]{
Converts @racket[x] to a syntax object using the lexical context of
@racket[context], the source location of @racket[source], and the syntax
properties of @racket[prop], using @racket[stx] for any of the above that are
not provided. Equivalent to
@racket[(datum->syntax context x (build-source-location-list source) prop)].
@transform-examples[
(define stx (to-syntax 'car #:stx #'here))
stx
(build-source-location stx)
(free-identifier=? stx #'car)
]
}
@defproc[(to-datum [x any/c]) any/c]{
Replaces any syntax objects contained in @racket[x] with their content;
equivalent to @racket[(syntax->datum (datum->syntax #false x))].
@transform-examples[
(to-datum (list #'(quote (1 2 3)) #'(#%datum . "text")))
]
}
@defproc[(quote-transformer [x any/c]) syntax?]{
Produces a expression that reconstructs @racket[x] when evaluated. Useful when
@racket[x] may contain syntax objects, which are not preserved by simply
wrapping @racket[x] in @racket[quote].
@transform-examples[
(to-datum (quote-transformer (list (quote (1 2)) (syntax (3 4)))))
]
}
@section{Constructing Identifiers}
@defproc[
(fresh [x (or/c symbol? string? identifier? keyword? char? number?) 'fresh]
[#:source source source-location? (if (identifier? x) x #false)]
[#:add-suffix? add-suffix? boolean? #true])
identifier?
]{
Constructs an identifier with a unique binding named @racket[x], with a unique
suffix if @racket[add-suffix?] is true, and using the source location of
@racket[source].
@transform-examples[
(fresh)
(fresh)
(define x #'x)
(define fresh-x (fresh x #:add-suffix? #false))
x
fresh-x
(free-identifier=? x fresh-x)
]
}
@defproc[
(format-fresh [fmt string?]
[arg (or/c symbol? string? identifier? keyword? char? number?)] ...
[#:source source source-location? #false]
[#:add-suffix? add-suffix? boolean? #true])
identifier?
]{
Equivalent to:
@racketblock[
(fresh (format-symbol fmt arg ...)
#:source source
#:add-suffix? add-suffix?)
]
@transform-examples[
(format-fresh "~a-~a" #'string #'length)
]
}
@defproc[(fresh-mark) (-> syntax? syntax?)]{
An alias for @racket[make-syntax-introducer].
@transform-examples[
(define id1 (fresh))
(define mark (fresh-mark))
(define id2 (mark id1))
(define id3 (mark id2))
(bound-identifier=? id1 id2)
(bound-identifier=? id2 id3)
(bound-identifier=? id1 id3)
]
}
@deftogether[(
@defproc[(identifier-upcase [id identifier?]) identifier?]
@defproc[(identifier-downcase [id identifier?]) identifier?]
@defproc[(identifier-titlecase [id identifier?]) identifier?]
@defproc[(identifier-foldcase [id identifier?]) identifier?]
)]{
Change the letters in the name of an identifier by analogy to
@racket[string-upcase], @racket[string-downcase], @racket[string-titlecase],
and @racket[string-foldcase].
@transform-examples[
(identifier-upcase #'Two-words)
(identifier-downcase #'Two-words)
(identifier-titlecase #'Two-words)
(identifier-foldcase #'Two-words)
]
}
@section{Common Syntax Transformer Patterns}
@defproc[
(id-transform
[original syntax?]
[replace (or/c syntax? (-> identifier? syntax?))])
syntax?
]{
Transforms the identifier that controls the expansion of @racket[original] as a
macro application, @racket[set!] transformer application, or identifier macro
reference. Replaces that identifier with @racket[replace] if @racket[replace]
is a syntax object, or with the result of applying @racket[replace] to the
identifier if @racket[replace] is a procedure.
@transform-examples[
(id-transform #'simple-identifier #'replacement)
(id-transform #'(simple macro application) #'replacement)
(id-transform #'(set! macro application) #'replacement)
]
}
@defproc[
(id-transformer [proc (-> identifier? syntax?)])
(and/c set!-transformer? (-> syntax? syntax?))
]{
Produces a @racket[set!] transformer that, when defined as a macro, applies
@racket[proc] to the name of the macro in any application.
@transform-examples[
(define x 1)
(define-syntax X (id-transformer identifier-downcase))
(set! X (add1 X))
X
]
}
@defproc[
(set!-transformer [proc (-> syntax? syntax?)])
(and/c set!-transformer? (-> syntax? syntax?))
]{
Produces a @racket[set!] transformer that can also be used as a procedure.
@transform-examples[
(define-for-syntax f
(set!-transformer
(lambda {x}
#'(error 'undefined "Oh, no!"))))
(define-syntax (x stx) (f stx))
x
(x 1)
(set! x 1)
(define-syntax y f)
y
(y 1)
(set! y 1)
]
}
@deftogether[(
@defproc[
(rename-transformer [id identifier?])
(and/c (-> syntax? syntax?) rename-transformer?)
]
@defproc[
(rename-transformers [id identifier?] ...)
(values (and/c (-> syntax? syntax?) rename-transformer?) ...)
]
)]{
Produces one or many rename transformers that can also be used as procedures.
@transform-examples[
(define-syntaxes {pair left right}
(rename-transformers #'cons #'car #'cdr))
(pair (left '(1 2)) (right '(3 4)))
(define-syntax (tuple stx)
((rename-transformer #'list) stx))
tuple
(tuple 1 2 3)
]
}
@section{Phase 1 Helpers}
@defproc[(syntax-error [stx syntax?] [fmt string?] [x any/c] ...) none/c]{
An alias for @racket[wrong-syntax].
}
@defproc[(syntax-local-variable-reference) variable-reference?]{
Produces an anonymous variable reference representing the context currently
being expanded.
@transform-examples[
(module var-ref-example racket
(require (for-syntax mischief/transform))
(define-syntax (macro stx)
(printf "Transforming: ~s\n"
(resolved-module-path-name
(variable-reference->resolved-module-path
(syntax-local-variable-reference))))
#'(begin))
(macro))
(require 'var-ref-example)
]
}
@defproc[
(check-missing-identifier
[actual (listof identifier?)]
[expected (listof identifier?)])
(or/c identifier? #false)
]{
If @racket[actual] is missing a @racket[free-identifier=?] counterpart for any
identifier in @racket[expected], produces the first such identifier found.
Otherwise, produces @racket[#false]
@transform-examples[
(check-missing-identifier
(list #'cons #'car #'cdr)
(list #'cons #'first #'rest))
]
}
| true |
961d769dbda832adb72a07c7be377a0f6864690b | cf1a50c34977f12888f4d76120db52b677560cfa | /xrepl-doc/info.rkt | c832f7dd1ebad280e38b12a05e34b17df26dc6ae | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | racket/xrepl | 5bc3697a0b4158b091473e0531671807481a2a71 | b1399e0fcfd8e0af1e4c6528dd6d513b20fc1698 | refs/heads/master | 2023-08-17T05:28:33.279503 | 2022-02-26T18:04:26 | 2022-02-26T18:04:26 | 27,453,949 | 6 | 9 | NOASSERTION | 2020-07-26T14:51:45 | 2014-12-02T21:18:35 | Racket | UTF-8 | Racket | false | false | 619 | rkt | info.rkt | #lang info
(define collection 'multi)
(define build-deps '("errortrace-doc"
"macro-debugger"
"profile-doc"
"readline-doc"
"macro-debugger-text-lib"
"profile-lib"
"readline-lib"
"xrepl-lib"
"racket-doc"))
(define deps '("base"
"sandbox-lib"
"scribble-lib"))
(define update-implies '("xrepl-lib"))
(define pkg-desc "documentation part of \"xrepl\"")
(define pkg-authors '(eli))
(define license
'(Apache-2.0 OR MIT))
| false |
116deac81dd59f6737687c6796d8cba3f00dde8a | 9b9512f0f63ddaca315c3eccb63ff19e884a56fa | /pymve.rkt | a3e945086cee42c0a2614c6deb0e3475bc0682cc | [] | no_license | yashton/compiler | d793cf69c668ee68928ab74af70e17c53ffadeef | 40007da3af04a7ee31380ae29e23dcfbb50a1c8d | refs/heads/master | 2020-08-02T15:43:35.181718 | 2019-09-27T23:04:37 | 2019-09-27T23:04:37 | 211,413,896 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 4,166 | rkt | pymve.rkt | #lang racket
(require "pytoc-common.rkt")
;(define (mve-transform-program input)
; (match input
; [`(program (define ,global ,val) ... ,exprs ...)
; `(program
; ,@(map (lambda (var val) `(define ,var ,val)) global val)
; ,@(map (lambda (expr) (mve-transform-cexp '() global expr)) exprs))]))
;(define (mve-transform-cexp env global input)
; (match input
; [`(error ,aexp)
; ; =>
; `(error ,(mve-transform-aexp env global aexp))]
; [`(if ,test ,true ,false)
; ; =>
; `(if ,(mve-transform-aexp env global test)
; ,(mve-transform-cexp env global true)
; ,(mve-transform-cexp env global false))]
; [`(set-then! ,var ,val ,then)
; ; =>
; (let ([new-global (cons var global)])
; `(set-then! ,var
; ,(mve-transform-aexp env new-global val)
; ,(mve-transform-cexp env new-global then)))]
; [`(,f ,aexp ...)
; ;=>
; `(,(mve-transform-aexp env global f)
; ,@(map (lambda (aexp) (mve-transform-aexp env global aexp)) aexp))]))
;
;(define (mve-transform-aexp env global input)
; (match input
; [`(dict (,k ,v) ...)
; `(dict
; ,(map
; (lambda (k v)
; `(,(mve-transform-aexp env global k)
; ,(mve-transform-aexp env global v)))
; k v))]
; [(? basic-nonvar?) input]
; [(? symbol?)
; (if (or (member input global)
; (member input env))
; input
; `(get-cell ,input))]
; [`(lambda (,vars ...) ,body)
; ; =>
; (let ([new-env (append env vars)])
; `(lambda (,@vars) ,(mve-transform-cexp new-env global body)))]
; [`(,f ,aexp ...)
; `(,(mve-transform-aexp env global f)
; ,@(map (lambda (aexp) (mve-transform-aexp env global aexp)) aexp))]))
(define (mve-transform-program free input)
(match input
[`(program (define ,global ,val) ... ,exprs ...)
`(program
,@(map (lambda (var val) `(define ,var ,val)) global val)
,@(map (lambda (expr) (mve-transform-cexp free expr)) exprs))]))
(define (mve-transform-cexp free input)
(match input
[`(error ,aexp)
; =>
`(error ,(mve-transform-aexp free aexp))]
[`(if ,test ,true ,false)
; =>
`(if ,(mve-transform-aexp free test)
,(mve-transform-cexp free true)
,(mve-transform-cexp free false))]
[`(set-then! ,var ,val ,then)
; =>
(let ([op (if (set-member? free var) 'set-cell! 'set-then!)])
`(,op ,var
,(mve-transform-aexp free val)
,(mve-transform-cexp free then)))]
[`(,f ,aexp ...)
;=>
`(,(mve-transform-aexp free f)
,@(map (lambda (aexp) (mve-transform-aexp free aexp)) aexp))]))
(define (mve-transform-aexp free input)
(match input
[`(dict (,k ,v) ...)
`(dict
,@(map
(lambda (k v)
`(,(mve-transform-aexp free k)
,(mve-transform-aexp free v)))
k v))]
[(? basic-nonvar?) input]
[(? symbol?)
(if (set-member? free input)
`(get-cell ,input)
input)]
[`(lambda (,vars ...) ,body)
; =>
`(lambda (,@vars)
,(mve-lambda free vars (mve-transform-cexp free body)))]
[`(,f ,aexp ...)
`(,(mve-transform-aexp free f)
,@(map (lambda (aexp) (mve-transform-aexp free aexp)) aexp))]))
(define (mve-lambda free vars body)
(if (empty? vars)
body
(let ([var (car vars)]
[rest (mve-lambda free (cdr vars) body)])
(if (set-member? free var)
`(set-then! ,var (make-cell ,var) ,rest)
rest))))
; Finds all non-global mutable variables
(define (mve-find input)
(match input
[`(program (define ,global ,val) ... ,exprs ...)
(set-subtract (set-union* (map mve-find exprs)) (apply set global))]
[`(error ,aexp) (mve-find aexp)]
[`(if ,test ,true ,false)
; =>
(set-union
(mve-find test)
(mve-find true)
(mve-find false))]
[`(set-then! ,var ,val ,then)
; =>
(set-union (set var)
(mve-find val)
(mve-find then))]
[`(dict (,k ,v) ...)
; =>
(set-union*
(map
(lambda (k v)
(set-union
(mve-find k)
(mve-find v)))
k v))]
[(? basic-nonvar?) (set)]
[(? symbol?) (set)]
[`(lambda (,vars ...) ,body)
; =>
(mve-find body)]
[`(,f ,aexp ...) (set-union* (map mve-find input))]))
(let ([in (read)])
(pretty-write (mve-transform-program (mve-find in) in)))
| false |
e9f5cd75d4948f03ad6119d90a6f848a1b49c7dd | 6a517ffeb246b6f87e4a2c88b67ceb727205e3b6 | /eval.rkt | 5da4d60a1d81a99354272329e73061f252225618 | [] | no_license | LiberalArtist/ecmascript | 5fea8352f3152f64801d9433f7574518da2ae4ee | 69fcfa42856ea799ff9d9d63a60eaf1b1783fe50 | refs/heads/master | 2020-07-01T01:12:31.808023 | 2019-02-13T00:42:35 | 2019-02-13T00:42:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,315 | rkt | eval.rkt | #lang racket/base
(require racket/port
racket/runtime-path
racket/contract/base
"private/global-object.rkt"
"lang/compile.rkt"
"lang/read.rkt"
"object.rkt"
"parse.rkt")
(provide (contract-out
(rename ecma:eval eval
(->* (string?)
(Object? namespace?)
any))
[make-global-namespace (-> namespace?)])
eval-read-interaction)
(define (ecma:eval prog
[scope global-object]
[namespace (make-global-namespace)])
(let ([stx (with-input-from-string prog
(λ ()
(ecma:read-syntax)))])
(if (eof-object? stx)
(void)
(eval
#`(begin #,@stx)
namespace))))
(define-namespace-anchor here)
(define-runtime-module-path-index main-module "main.rkt")
(define (make-global-namespace)
(parameterize
([current-namespace
(namespace-anchor->empty-namespace here)])
(namespace-require main-module)
(current-namespace)))
(define (eval-read-interaction src in)
(let ([line (read-line in)])
(if (eof-object? line)
line
#`(begin
#,@(ecmascript->racket
(read-program src (open-input-string line)))))))
| false |
da0fbfe13268294fa2687f017e57dc8c028e851d | 98fd4b7b928b2e03f46de75c8f16ceb324d605f7 | /drracket-test/tests/drracket/snips.rkt | 8cfb75d507262b09ee9bc2659ba1250820b2d4b7 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | racket/drracket | 213cf54eb12a27739662b5e4d6edeeb0f9342140 | 2657eafdcfb5e4ccef19405492244f679b9234ef | refs/heads/master | 2023-08-31T09:24:52.247155 | 2023-08-14T06:31:49 | 2023-08-14T06:32:14 | 27,413,460 | 518 | 120 | NOASSERTION | 2023-09-11T17:02:44 | 2014-12-02T03:36:22 | Racket | UTF-8 | Racket | false | false | 1,071 | rkt | snips.rkt | #lang racket/base
(require "private/drracket-test-util.rkt"
racket/class
racket/runtime-path
racket/file
racket/gui/base)
(define-runtime-path snip "snip")
(fire-up-drracket-and-run-tests
(λ ()
(define drs (wait-for-drracket-frame))
(define tmpdir (make-temporary-file "drracketsniptest~a" 'directory))
(define defs (queue-callback/res (λ () (send drs get-definitions-text))))
(for ([rfile (in-list (directory-list snip))])
(define file (build-path snip rfile))
(when (file-exists? file) ;; skip subdirectories
(unless (equal? file (build-path "info.rkt"))
(printf " trying ~a\n" rfile)
(queue-callback/res
(λ () (send defs load-file file)))
(save-drracket-window-as (build-path tmpdir rfile))
(define drs2 (wait-for-drracket-frame))
(unless (eq? drs drs2)
(error 'snips.rkt "lost drracket frame while saving ~s" rfile)))))
(delete-directory/files tmpdir)))
(module+ test
(module config info
(define timeout 200)))
| false |
956b1f09ef80849f699376b449c22b07276ac9a9 | 488e71ad2d41100fa1978661cec5c7399872949a | /info.rkt | 5961773069053ebb79a2c5e327066b77a8a49a62 | [] | no_license | bennn/matrix-computations | 0b2277abda22c6ba0d5033dba4988efbc1000e9d | 0cf703ccf372368c6b5fccbe26ddd31d9ff70b96 | refs/heads/master | 2021-01-10T14:11:41.340147 | 2015-10-11T00:17:39 | 2015-10-11T00:24:08 | 44,492,761 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 353 | rkt | info.rkt | #lang info
(define collection "matrix-computations")
(define deps '("base"))
(define build-deps
'(;"cover"
;"cover-coveralls"
"scribble-lib"
"rackunit-abbrevs"
"racket-doc"
"rackunit-lib"))
(define pkg-desc "Matrix computations")
(define version "0.0")
(define pkg-authors '(ben))
(define scribblings '(("scribblings/api.scrbl")))
| false |
99827fc3d8077dcdeda50b03b1dcee6ea480593f | 82c76c05fc8ca096f2744a7423d411561b25d9bd | /typed-racket-test/succeed/optional/optional-provide.rkt | 8dc3bfa5912956fb4a820a47e03d49c999623c36 | [
"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 | 250 | rkt | optional-provide.rkt | #lang racket/base
;; Test providing value to untyped
(module a typed/racket/base/optional
(provide f)
(define (f (x : (Boxof Integer)))
(unbox x)))
(require 'a rackunit)
(check-exn exn:fail:contract?
(lambda () (f 0)))
| false |
fd38fe4b4a18e0e16597097f764debd2da2e86e9 | 4b1d96db91c4775b9fe402f9372dbbc83430effe | /partB/week2/homework/test.rkt | 458d494faef66ed21c3dc93b1e71e2d4a5d793d5 | [] | 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 | 36 | rkt | test.rkt | #lang racket
(define p1 (cons 1 2))
| false |
cf614a501a410014e529c1aac3187e5a2535275c | e6a49e4b40a02be3f3afc282cc23c60bb65f95ca | /racket/hw5/mupl_programs.rkt | 6fcd25153c465f0d034e527a956f0422a09bd613 | [] | no_license | wuyuanpei/Programming_Language_Labs | 41ccc81a4cef0cb630b9281b23643a3676d77bbe | 7ddd70353bc16c1960f1b35164bb87ece583692f | refs/heads/master | 2022-07-06T18:52:09.997591 | 2020-05-10T01:00:31 | 2020-05-10T01:00:31 | 262,686,418 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 970 | rkt | mupl_programs.rkt | ;; Programming Languages, Homework 5 Bonus
#lang racket
(provide (all-defined-out)) ;; so we can put tests in a second file
(require "hw5.rkt")
; Richard Wu
; racket version for reference
(define (racket-double n) (+ n n))
; mupl-double return a mupl-function which doubles its mupl-int argument
(define mupl-double
(fun #f "n" (add (var "n") (var "n"))))
; racket version for reference
(define (racket-sum-curry a) (lambda (b) (+ a b)))
; mupl-sum-curry return a mupl-function which returns a mupl-function which adds the two mupl-function's mupl-int arguments together
(define mupl-sum-curry
(fun #f "a"
(fun #f "b"
(add (var "a") (var "b")))))
; racket version for reference
(define (racket-map-one proc) (proc 1))
; mupl-map-one: return a mupl-function that invoks the mupl-function passed in with the mupl-int argument 1
(define mupl-map-one
(fun #f "proc"
(call (var "proc") (int 1))))
| false |
9096e957e0464e1d865d510053d30739be1a58da | b9eb119317d72a6742dce6db5be8c1f78c7275ad | /btree/btree.rkt | f7c4885f6dcf6535f00c1d5be701ce1c838cff26 | [] | no_license | offby1/doodles | be811b1004b262f69365d645a9ae837d87d7f707 | 316c4a0dedb8e4fde2da351a8de98a5725367901 | refs/heads/master | 2023-02-21T05:07:52.295903 | 2022-05-15T18:08:58 | 2022-05-15T18:08:58 | 512,608 | 2 | 1 | null | 2023-02-14T22:19:40 | 2010-02-11T04:24:52 | Scheme | UTF-8 | Racket | false | false | 9,661 | rkt | btree.rkt | #lang racket
(include "convenience.rkt")
(define key? number?) ; TODO -- make this, and our
; equality and ordering tests,
; parameterizable
(define (tree-count t)
(sequence-length (in-dict-keys t)))
;; Our "pos" is a stack of tree nodes -- the nodes we need to pass
;; through to get to a particular node, starting at the root.
;; TODO -- combine with find-subtree -- they're awfully similar
(define (tree-iterate-first t [pos (make-pos t)])
(cond
((tree-empty? t)
#f)
((tree-empty? (tree-left t))
(pos-push t pos))
(else
(tree-iterate-first (tree-left t) (pos-push t pos)))))
(define (tree-iterate-next t pos)
(pos-validate t pos)
(let loop ([pos pos])
(cond
((not (tree-empty? (tree-right (pos-head pos))))
(tree-iterate-first (tree-right (pos-head pos)) (pos-rest pos)))
((pos-empty? (pos-rest pos)) #f)
((< (tree-key (pos-head (pos-rest pos)))
(tree-key (pos-head pos)))
(loop (pos-rest pos)))
(else (pos-rest pos)))))
(define (tree-iterate-key t pos)
(pos-validate t pos)
(tree-key (pos-head pos)))
(define (tree-iterate-value t pos)
(pos-validate t pos)
(tree-value (pos-head pos)))
(define (make-tree k v
#:left [l #f]
#:right [r #f]
#:MaxNodeCount [MaxNodeCount 1])
(set! l (or l (public-make-tree)))
(set! r (or r (public-make-tree)))
(tree (node k v l r
(add1 (+ (tree-weight l) (tree-weight r))))
MaxNodeCount))
(define (tree-empty? t)
(not (tree-node-or-false t)))
(define (find-subtree t k [stack (make-pos t)])
(cond
((tree-empty? t) (pos-push t stack))
((equal? k (tree-key t)) (pos-push t stack))
((< k (tree-key t))
(find-subtree (tree-left t) k (pos-push t stack)))
(else
(find-subtree (tree-right t) k (pos-push t stack)))))
(define (tree-ref t k [failure-result (lambda ()
(raise
(make-exn:fail
"Not found"
(current-continuation-marks))))])
(let ([path (find-subtree t k)])
(cond
((not (tree-empty? (pos-head path)))
(tree-value (pos-head path)))
((procedure? failure-result) (failure-result))
(else failure-result))))
;; "Install" NEW-LEAF at the location indicated by STACK, and return
;; the root of the new tree.
;; tree? pos? -> tree?
(define (graft new-leaf stack)
(for/fold ([result new-leaf])
([parent (pos-rest stack)]
[child stack])
(case (which-child parent child)
((left)
(make-tree
(tree-key parent)
(tree-value parent)
#:left result
#:right (tree-right parent)
#:MaxNodeCount (max (tree-MaxNodeCount parent)
(tree-MaxNodeCount result))))
((right)
(make-tree
(tree-key parent)
(tree-value parent)
#:left (tree-left parent)
#:right result
#:MaxNodeCount (max (tree-MaxNodeCount parent)
(tree-MaxNodeCount result)))))))
(define alpha 3/4)
(define (h-alpha weight)
(floor (/ (log weight) (log (/ alpha)))))
(define (is-deep? pos)
((pos-depth pos) . > . (h-alpha (add1 (tree-weight (pos-last pos))))))
(define (alpha-weight-balanced t)
(and
((tree-weight (tree-left t)) . <= . (* alpha (tree-weight t)))
((tree-weight (tree-right t)) . <= . (* alpha (tree-weight t)))))
;; tree? key? any/c -> tree?
(define (tree-set t k v)
;; This whole function looks laughably inefficient.
(define (maybe-post-insert-rebalance root)
(define (find-scapegoat root pos)
(define scapeulous (compose not alpha-weight-balanced))
(let loop ([pos pos])
(cond
((pos-empty? pos)
(error 'scapeulous "This isn't supposed to happen"))
((scapeulous (pos-head pos))
pos)
(else
(loop (pos-rest pos))))))
;; Calling find-subtree here, when we just computed the stack, is
;; wasteful; but it's O(log(N)) wasteful, and we're about to
;; rewrite a chunk of the tree in O(N) time, so ... it's probably
;; OK.
(let ([new-entry-pos (find-subtree root k)])
(if (is-deep? new-entry-pos)
(let ([path-to-scapegoat (find-scapegoat root new-entry-pos)])
(let ([sg (pos-head path-to-scapegoat)])
(graft
(balance sg)
path-to-scapegoat)))
root)))
(let ([stack-o-trees (find-subtree t k)])
(maybe-post-insert-rebalance
(graft
(make-tree k v #:MaxNodeCount
(max (add1 (tree-weight t))
(tree-MaxNodeCount t)))
stack-o-trees))))
(define (in-order-successor t)
(cond
((tree-iterate-first (tree-right t)) => pos-head)
(else #f)))
;; This should be private to tree-remove, but it's at top level so
;; that the tests can get at it.
(define (decapitate target)
(cond
((tree-empty? (tree-left target))
(tree
(tree-node-or-false (tree-right target))
(tree-MaxNodeCount target)))
((tree-empty? (tree-right target))
(tree
(tree-node-or-false (tree-left target))
(tree-MaxNodeCount (tree-left target))))
(else
;; TODO -- flip a coin, and choose child randomly so as to not
;; get too unbalanced
(let ([s (in-order-successor target)])
(make-tree (tree-key s)
(tree-value s)
#:left (tree-left target)
#:right (tree-right s)
#:MaxNodeCount (max (tree-MaxNodeCount target)
(tree-MaxNodeCount s)))))))
(define (which-child parent child)
(cond
((eq? child (tree-left parent)) 'left )
((eq? child (tree-right parent)) 'right)
(else
(error 'which-child (format "~a is not the parent of ~a" parent child)))))
(define (tree-remove t k)
(define (maybe-rebalance t)
(if ((tree-weight t) . <= . (/ (tree-MaxNodeCount t) 2))
(balance t)
t))
(let ([stack-o-trees (find-subtree t k)])
(cond
((tree-empty? (pos-head stack-o-trees))
t)
(else
(maybe-rebalance
(graft (decapitate (pos-head stack-o-trees))
stack-o-trees))))))
(define (tree-weight t)
(cond
((tree-node-or-false t) => node-weight)
(else 0)))
;; Code for rebuilding a new balanced tree
;; See
;; http://www.akira.ruc.dk/~keld/teaching/algoritmedesign_f07/Artikler/03/Galperin93.pdf,
;; section 6.1
(define (partition-nonempty-sorted-list a)
(let* ([half (/ (length a) 2)]
[small (take a (floor half))]
[large-plus-median (list-tail a (floor half))]
)
(values small (car large-plus-median) (cdr large-plus-median))))
(define (alist->new-tree a #:MaxNodeCount [MaxNodeCount #f])
(if (null? a)
(public-make-tree)
(let-values ([(small median large) (partition-nonempty-sorted-list a)])
(make-tree (car median)
(cdr median)
#:left (alist->new-tree small)
#:right (alist->new-tree large)
#:MaxNodeCount (or MaxNodeCount (length a))))))
(define (balance t)
(alist->new-tree (dict-map t cons)))
(define (public-make-tree) (tree #f 0))
(provide (rename-out [public-make-tree tree])
tree?
tree-weight)
(define prop-dict-vector
(vector
tree-ref
#f ;set!
tree-set
#f ;remove!
tree-remove
tree-count
tree-iterate-first
tree-iterate-next
tree-iterate-key
tree-iterate-value
))
;; this is overkill :)
;; (for ([proc prop-dict-vector]) (when (procedure? proc) (trace proc)))
(struct tree (node-or-false MaxNodeCount)
#:property prop:dict prop-dict-vector
;; we never mutate input trees, but on occasion we will
;; construct a private tree, mutate it, and then return it
#:mutable
#:transparent)
(define (treenode->string t)
(let ([n (tree-node-or-false t)])
(if n
(format
"Node (~a, ~a) has weight ~a, MaxNodeCount ~a"
(tree-key t)
(tree-value t)
(tree-weight t)
(tree-MaxNodeCount t))
(format "Empty node"))))
(struct node (key value left right weight)
#:mutable
#:transparent)
;; a POS is basically a list, with a pointer to the original tree, so
;; that we can raise exn:fail:contract when needed.
(struct pos (original-tree stack)
#:transparent
#:property prop:sequence (lambda (p) (pos-stack p)))
(define (make-pos original-tree) (pos original-tree '()))
(define (pos-push thing p)
(pos (pos-original-tree p)
(cons thing (pos-stack p))))
(define (pos-rest p)
(pos (pos-original-tree p)
(cdr (pos-stack p))))
(define pos-depth (compose length pos-stack))
(define pos-head (compose car pos-stack))
(define pos-last (compose last pos-stack))
(define pos-empty? (compose null? pos-stack))
(define (pos-validate t p)
(when (not (eq? t (pos-original-tree p)))
(raise (exn:fail:contract
(format "Dude, ~a and ~a aren't related" t p)
(current-continuation-marks)))))
;; Convenience wrappers
(define (tree-left t) (node-left (tree-node-or-false t)))
(define (tree-right t) (node-right (tree-node-or-false t)))
(define (tree-key t) (node-key (tree-node-or-false t)))
(define (tree-value t) (node-value (tree-node-or-false t)))
| false |
687b8df331332805e249f997a2bd4c3daddba1d5 | 00ff1a1f0fe8046196c043258d0c5e670779009b | /sdsl/ifc/verify.rkt | 6cc04f4b7dc4fff93fe9d25b8e561080f8ecf648 | [
"BSD-2-Clause"
] | permissive | edbutler/rosette | 73364d4e5c25d156c0656b8292b6d6f3d74ceacf | 55dc935a5b92bd6979e21b5c12fe9752c8205e7d | refs/heads/master | 2021-01-14T14:10:57.343419 | 2014-10-26T05:12:03 | 2014-10-26T05:12:03 | 27,899,312 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 5,108 | rkt | verify.rkt | #lang s-exp rosette
(require "machine.rkt" "indistinguishable.rkt")
(provide verify-EENI verify-SSNI)
; Verifies the EENI[start, end, ≈] property for machines executing
; k steps of a program that is indistinguishable from the given program.
; The start argument is a procedure that takes as input a program and
; returns a fresh machine m initialized with that program. The pc,
; stack and memory of every machine m0 and m1 returned by start must be
; indistinguishable. The end argument is a predicate on machines, and
; ≈ is an indistinguishability relation on machines. The length
; of the program list is used as the default value for the number of steps.
; (-> (-> (listof instruction?) machine?)
; (-> machine? boolean?)
; (-> machine? machine? boolean?)
; (listof instruction?)
; [number?]
; void?)
(define (verify-EENI start end ≈ prog [k (length prog)])
(printf "\n-------Verify EENI[~a, ~a, ~a] for ~a steps of ~s-------\n"
(object-name start) (object-name end) (object-name ≈) k (format-program prog))
(define t0 (current-milliseconds))
(define m0 (start prog))
(define m1 (start (map instruction (map procedure prog)))) ; Use a fresh program (same procedures, fresh args).
(define cex
(with-handlers ([exn:fail? (lambda (e) #f)]) ; The verify form throws an exception if no cex is found.
(verify
#:assume (begin
(assert (≈ m0 m1))
(set! m0 (step m0 k))
(set! m1 (step m1 k))
(assert (end m0))
(assert (end m1)))
#:guarantee (assert (≈ m0 m1)))))
(define t (- (current-milliseconds) t0))
(print-cex cex t (cons "m0" m0) (cons "m1" m1)))
; Returns a printable representation of the given program.
(define (format-program prog)
(match prog
[(list (instruction (? union? r) _) _ ...)
(sort (map object-name (union-values r)) string<? #:key symbol->string)]
[(list (instruction (? procedure? proc) _) ...)
(map object-name proc)]))
; Prints the given counterexample for the specified label/machine pairs.
(define (print-cex cex t . labeled-machines)
(cond [cex (printf "Counterexample found (~a ms).\n" t)
(for ([label/machine labeled-machines])
(printf "~a:\n~s\n" (car label/machine) (evaluate (cdr label/machine) cex)))]
[else (printf "No counterexample found (~a ms).\n" t)]))
;; ------ Ignore SSNI implementation (not sure what it should be) ------ ;;
; Verifies the SSNI[all, full≈] property for machines executing
; 1 step of two indisitinguishable machines executing a single
; instruction that performs the given procedure. The S and M arguments
; determine the initial size of the machines' stack and memory,
; respectively. Both arguments are 2 by default.
; (-> (-> machine? value? ... machine?) [number?] [number?] void?)
(define (verify-SSNI proc [S 2] [M 2])
(printf "\n-------Verify SSNI[All, full≈] for ~s with stack depth ~s and memory size ~a-------\n"
(object-name proc) S M)
(define t0 (current-milliseconds))
(define m0 (all (list (instruction proc)) S M))
(define m1 (all (list (instruction proc)) S M))
(define m01 m0)
(define m11 m1)
(define cex
(with-handlers ([exn:fail? (lambda (e) #f)]) ; The verify form throws an exception if no cex is found.
(verify
#:assume (begin
(assert (full≈ m0 m1)) ; Assume that m0 and m1 are full≈, and
(set! m01 (step m0 1)) ; that each takes one step to states m01 and m11,
(set! m11 (step m1 1)) ; respectively.
(assert (equal? (@label (pc m01)) ; m01 and m11 must be either both high or both low.
(@label (pc m11))))
(assert (not (eq? m0 m01))) ; Neither m0 nor m1 is stuck.
(assert (not (eq? m1 m11))))
#:guarantee (let@ ([(pc0 Lpc0) (pc m0)]
[(pc01 Lpc01) (pc m01)]
[(pc1 Lpc1) (pc m1)]
[(pc11 Lpc11) (pc m11)])
(cond [(equal? Lpc0 ⊥) ; If m0 and m1 started in low states, their end
(assert (full≈ m01 m11))] ; states must be full≈.
[(equal? Lpc01 ⊥) ; If m0 and m1 ended in low states, their end
(assert (full≈ m01 m11))] ; those end states must be full≈.
[else
(assert (full≈ m0 m01)) ; If m0 and m1 ended in high states, then the ending
(assert (full≈ m1 m11))]))))) ; state for each is full≈ to its starting state.
(define t (- (current-milliseconds) t0))
(print-cex cex t (cons "m0" m0) (cons "m1" m1) (cons "(step m0)" m01) (cons "(step m1)" m11)))
| false |
3df107c760c36d0a712a094d5b2d874a4fd65991 | 799b5de27cebaa6eaa49ff982110d59bbd6c6693 | /soft-contract/test/count-checks.rkt | 42721107935b16b4c67c618a27e838320edcde58 | [
"MIT"
] | permissive | philnguyen/soft-contract | 263efdbc9ca2f35234b03f0d99233a66accda78b | 13e7d99e061509f0a45605508dd1a27a51f4648e | refs/heads/master | 2021-07-11T03:45:31.435966 | 2021-04-07T06:06:25 | 2021-04-07T06:08:24 | 17,326,137 | 33 | 7 | MIT | 2021-02-19T08:15:35 | 2014-03-01T22:48:46 | Racket | UTF-8 | Racket | false | false | 3,505 | rkt | count-checks.rkt | #lang typed/racket/base
(provide (all-defined-out))
(require racket/match
"../ast/signatures.rkt"
"../main.rkt")
(define-type Count (HashTable Symbol Natural))
(: make-counter : → (Values Count (Symbol * → Void)))
(define (make-counter)
(define m : Count (make-hasheq))
(values m
(λ ks
(for ([k ks])
(hash-update! m k add1 (λ () 0))))))
(define-type Stx (Rec X (U -top-level-form
-e
-general-top-level-form
-e
-module
-begin/top
-module-level-form
(Listof X))))
(: count-checks : Stx → Count)
;; Return a static estimation of run-time checks.
;; Numbers are conservative in that we only count up checks that definitely need to be there
(define (count-checks stx)
(define-values (stats up!) (make-counter))
(: go! : Stx → Void)
(define (go! stx)
(match stx
[(? list? es) (for-each go! es)]
[(-provide specs)
(for ([spec specs])
(match-define (-p/c-item _ c _) spec)
(c.go! c))]
[(-define-values _ e) (up! 'values) (go! e)]
[(-λ _ e) (go! e)] ; don't count arity check here
[(-case-λ clauses) (for-each go! clauses)]
[(or (? -x?) (? -rec/c?)) (up! #;'undefined)]
[(-@ f xs _)
(up! 'procedure? 'arity 'values) (go! f)
(for ([x xs]) (up! 'values) (go! x))
;; TODO: count up for each non-total primitive appearing in `f`.
(match f
[(or (? -st-ac?) (? -st-mut?)) (up! 'partial)]
[(? symbol? o) #:when (hash-has-key? partial-prims o) (up! 'partial)]
[_ (void)])]
[(-if i t e) (up! 'values) (go! i) (go! t) (go! e)]
[(-wcm k v e) (go! k) (go! v) (go! e)]
[(-begin es) (for-each go! es)]
[(-begin0 e es) (go! e) (for-each go! es)]
[(or (-let-values bindings e _)
(-letrec-values bindings e _))
(for ([binding (in-list bindings)])
(up! 'values)
(go! (cdr binding)))
(go! e)]
[(-set! _ e) (up! 'values) (go! e)]
;; Switch to `c.go!` mode for contracts
[(and c (or (? -->?)) (? -->i?) (? -case->?) (? -struct/c?))
(c.go! c)]
[(-module _ body) (for-each go! body)]
;; FIXME count up for primitives
[_
(log-warning "conservatively not counting checks for ~a~n" stx)
(void)]))
(: c.go! : -e → Void)
;; Mostly similar to `go!`, but count up every value at leaves of contracts
(define (c.go! c)
(up! 'values 'contract?)
(match c
[(? -rec/c?) #|TODO|# (void)]
[(--> dom rng _)
(match dom
[(-var cs c) (for-each c.go! cs) (c.go! c)]
[(? list? cs) (for-each c.go! cs)])
(c.go! rng)
(up! 'procedure? 'arity)]
[(-->i dom rng _)
(for-each c.go! dom) (c.go! rng)
(up! 'procedure? 'arity)]
[(-case-> clauses)
(for ([clause clauses])
(match-define (cons cs d) clause)
(for-each c.go! cs) (c.go! d))
(up! 'procedure? 'arity)]
[(-struct/c _ cs _) (for-each c.go! cs) (up! 'struct)]
[(? -o? o) (up! 'leaf)]
[(-@ (or 'and/c 'or/c 'not/c) cs _) (for-each c.go! cs)]
;; Switch to `go!` for expressions
[e (go! e) (up! 'leaf)]))
(go! stx)
(let ([total (apply + (hash-values stats))])
(hash-set! stats 'total total)
stats))
| false |
fc517724d021a8b9fd1b01bcdf4afce0392b4497 | e65a1d690c53dd3d097313443b8e4d554187d53d | /asn1-test/info.rkt | d31d1ab06c084a1bb74c610230d183c24df11255 | [] | no_license | rmculpepper/asn1 | 635720a2665f7a56679dfdaf05b4c1b70349e6f9 | 3cd32b61a68b40ec03bed98cd0c4d4d4f72cacf2 | refs/heads/master | 2022-04-26T22:00:02.606282 | 2022-04-16T19:54:27 | 2022-04-16T19:54:27 | 17,492,061 | 4 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 389 | rkt | info.rkt | ;; Copyright 2014-2018 Ryan Culpepper
;; SPDX-License-Identifier: Apache-2.0
#lang info
;; ========================================
;; pkg info
(define version "1.0")
(define collection "asn1")
(define deps '("base" "rackunit-lib" "asn1-lib"))
(define pkg-authors '(ryanc))
(define license 'Apache-2.0)
;; ========================================
;; collect info
(define name "asn1")
| false |
7b6f08f1180bb66fb783fd1e1d814cc257536d60 | f19259628cd30021f354f1326e946e1fb9dfa701 | /src/domain.rkt | 25ebbb0936e78107b212f1833254af55b35bedd4 | [] | no_license | anthonyquizon/ckanren | 1cfd6b65894e8f174a45848a98ca4bf612f418c7 | 53b69e3ef2d95ae74714cfe15f077914ce298c8e | refs/heads/master | 2021-07-23T13:49:08.318957 | 2017-10-27T01:08:38 | 2017-10-27T01:08:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,201 | rkt | domain.rkt | #lang racket
(require
(prefix-in v: "variable.rkt")
(prefix-in u: "util.rkt"))
(provide
copy-before
drop-before
(rename-out [make-dom make]
[empty-d empty]
[get-dom get]
[value?-dom value?]
[memv?-dom memv?]
[singleton?-dom singleton?]
[singleton-element-dom singleton-element]
[min-dom min]
[max-dom max]
[disjoint?-dom disjoint?]
[diff-dom diff]
[intersection-dom intersection]))
(define (make-dom n*) n*)
(define empty-d '())
(define (copy-before pred dom)
(cond
[(null? dom) '()]
[(pred (car dom)) '()]
[else (cons (car dom) (copy-before pred (cdr dom)))]))
(define (drop-before pred dom)
(cond
[(null? dom) '()]
[(pred (car dom)) dom]
[else (drop-before pred (cdr dom))]))
(define (get-dom x d)
(cond
[(assq x d) => u:rhs]
[else #f]))
(define (value?-dom v) (and (integer? v) (<= 0 v)))
(define (memv?-dom v dom) (and (value?-dom v) (memv v dom)))
(define (null?-dom dom) (null? dom))
(define (singleton?-dom dom) (null? (cdr dom)))
(define (singleton-element-dom dom) (car dom))
(define (min-dom dom) (car dom))
(define (max-dom dom)
(cond
[(null? (cdr dom)) (car dom)]
[else (max-dom (cdr dom))]))
(define (disjoint?-dom dom-1 dom-2)
(cond
[(or (null? dom-1) (null? dom-2)) #t]
[(= (car dom-1) (car dom-2)) #f]
[(< (car dom-1) (car dom-2))
(disjoint?-dom (cdr dom-1) dom-2)]
[else (disjoint?-dom dom-1 (cdr dom-2))]))
(define (diff-dom dom-1 dom-2)
(cond
[(or (null? dom-1) (null? dom-2)) dom-1]
[(= (car dom-1) (car dom-2)) (diff-dom (cdr dom-1) (cdr dom-2))]
[(< (car dom-1) (car dom-2))
(cons (car dom-1) (diff-dom (cdr dom-1) dom-2))]
[else (diff-dom dom-1 (cdr dom-2))]))
(define (intersection-dom dom-1 dom-2)
(cond
[(or (null? dom-1) (null? dom-2)) '()]
[(= (car dom-1) (car dom-2))
(cons (car dom-1)
(intersection-dom (cdr dom-1) (cdr dom-2)))]
[(< (car dom-1) (car dom-2))
(intersection-dom (cdr dom-1) dom-2)]
[else (intersection-dom dom-1 (cdr dom-2))]))
| false |
6ce8d0283e6e4da201678eae4f5d95191a3325b6 | d9276fbd73cdec7a5a4920e46af2914f8ec3feb1 | /data/scheme/utils-and-no-gui.rkt | 3c5ef2a31698718fbf90fa1d695659805e11039f | [] | no_license | CameronBoudreau/programming-language-classifier | 5c7ab7d709b270f75269aed1fa187e389151c4f7 | 8f64f02258cbab9e83ced445cef8c1ef7e5c0982 | refs/heads/master | 2022-10-20T23:36:47.918534 | 2016-05-02T01:08:13 | 2016-05-02T01:08:13 | 57,309,188 | 1 | 1 | null | 2022-10-15T03:50:41 | 2016-04-28T14:42:50 | C | UTF-8 | Racket | false | false | 5,466 | rkt | utils-and-no-gui.rkt | #lang typed/racket/base
(require "common/types.rkt")
(provide
Treeof
Anchor
Plot-Color
Plot-Pen-Style
Plot-Brush-Style
Point-Sym
List-Generator
Plot-Colors
Plot-Pen-Styles
Pen-Widths
Plot-Brush-Styles
Alphas
Labels
Contour-Levels
Image-File-Format)
(require "common/math.rkt")
(provide
(struct-out ivl))
(require "common/axis-transform.rkt"
(only-in "common/leftover-contracts.rkt"
axis-transform/c))
(provide
(struct-out invertible-function)
Axis-Transform
axis-transform/c
id-function
invertible-compose
invertible-inverse
id-transform
apply-axis-transform
make-axis-transform
axis-transform-compose
axis-transform-append
axis-transform-bound
log-transform
cbrt-transform
hand-drawn-transform
stretch-transform
collapse-transform)
(require "common/parameters.rkt")
(provide
plot-deprecation-warnings?
;; General plot parameters
plot-x-axis?
plot-y-axis?
plot-z-axis?
plot-x-far-axis?
plot-y-far-axis?
plot-z-far-axis?
plot-x-tick-label-anchor
plot-y-tick-label-anchor
plot-x-far-tick-label-anchor
plot-y-far-tick-label-anchor
plot-x-tick-label-angle
plot-y-tick-label-angle
plot-x-far-tick-label-angle
plot-y-far-tick-label-angle
plot-width plot-height
plot-foreground
plot-foreground-alpha
plot-background
plot-background-alpha
plot-line-width
plot-tick-size
plot-font-size
plot-font-face
plot-font-family
plot-legend-anchor
plot-legend-box-alpha
plot-decorations?
plot-animating?
plot3d-samples
plot3d-angle
plot3d-altitude
plot3d-ambient-light
plot3d-diffuse-light?
plot3d-specular-light?
plot-new-window?
plot-jpeg-quality
plot-ps/pdf-interactive?
plot-ps-setup
plot-title
plot-x-label
plot-y-label
plot-z-label
plot-x-far-label
plot-y-far-label
plot-z-far-label
plot-x-transform
plot-x-ticks
plot-x-far-ticks
plot-y-transform
plot-y-ticks
plot-y-far-ticks
plot-z-transform
plot-z-ticks
plot-z-far-ticks
plot-d-ticks
plot-r-ticks
;; Renderer parameters
line-samples
line-color
line-width
line-style
line-alpha
interval-color
interval-style
interval-line1-color
interval-line1-width
interval-line1-style
interval-line2-color
interval-line2-width
interval-line2-style
interval-alpha
point-sym
point-color
point-size
point-x-jitter
point-y-jitter
point-z-jitter
point-line-width
point-alpha
vector-field-samples
vector-field-color
vector-field-line-width
vector-field-line-style
vector-field-scale
vector-field-alpha
vector-field3d-samples
error-bar-width
error-bar-color
error-bar-line-width
error-bar-line-style
error-bar-alpha
contour-samples
contour-levels
contour-colors
contour-widths
contour-styles
contour-alphas
contour-interval-colors
contour-interval-styles
contour-interval-alphas
rectangle-color
rectangle-style
rectangle-line-color
rectangle-line-width
rectangle-line-style
rectangle-alpha
rectangle3d-line-width
discrete-histogram-gap
discrete-histogram-skip
discrete-histogram-invert?
stacked-histogram-colors
stacked-histogram-styles
stacked-histogram-line-colors
stacked-histogram-line-widths
stacked-histogram-line-styles
stacked-histogram-alphas
x-axis-ticks?
y-axis-ticks?
z-axis-ticks?
x-axis-labels?
y-axis-labels?
z-axis-labels?
x-axis-far?
y-axis-far?
z-axis-far?
x-axis-alpha
y-axis-alpha
z-axis-alpha
polar-axes-number
polar-axes-ticks?
polar-axes-labels?
polar-axes-alpha
label-anchor
label-angle
label-alpha
label-point-size
surface-color
surface-style
surface-line-color
surface-line-width
surface-line-style
surface-alpha
contour-interval-line-colors
contour-interval-line-widths
contour-interval-line-styles
isosurface-levels
isosurface-colors
isosurface-styles
isosurface-line-colors
isosurface-line-widths
isosurface-line-styles
isosurface-alphas
;; Functions
pen-gap
animated-samples
default-contour-colors
default-contour-fill-colors
default-isosurface-colors
default-isosurface-line-colors)
(require "common/date-time.rkt")
(provide
(struct-out plot-time)
plot-time->seconds
seconds->plot-time
datetime->real)
(require "common/ticks.rkt"
(only-in "common/leftover-contracts.rkt"
ticks-layout/c
ticks-format/c))
(provide
(struct-out pre-tick)
(struct-out tick)
(struct-out ticks)
Ticks-Layout
Ticks-Format
ticks-layout/c
ticks-format/c
ticks-generate
24h-descending-date-ticks-formats
12h-descending-date-ticks-formats
24h-descending-time-ticks-formats
12h-descending-time-ticks-formats
us-currency-scales
uk-currency-scales
eu-currency-scales
us-currency-formats
uk-currency-formats
eu-currency-formats
no-ticks-layout
no-ticks-format
no-ticks
ticks-default-number
ticks-mimic
ticks-scale
ticks-add
linear-scale
linear-ticks-layout
linear-ticks-format
linear-ticks
log-ticks-layout
log-ticks-format
log-ticks
date-ticks-formats
date-ticks-layout
date-ticks-format
date-ticks
time-ticks-formats
time-ticks-layout
time-ticks-format
time-ticks
bit/byte-ticks-format
bit/byte-ticks
currency-ticks-scales
currency-ticks-formats
currency-ticks-format
currency-ticks
fraction-ticks-format
fraction-ticks
collapse-ticks
contour-ticks
format-tick-labels)
(require "common/plot-element.rkt"
"common/nonrenderer.rkt"
"plot2d/renderer.rkt"
"plot3d/renderer.rkt")
(provide
(struct-out plot-element)
(struct-out nonrenderer)
(struct-out renderer2d)
(struct-out renderer3d))
| false |
551e12c7cb3fdeeca99cf835a0fae1045412c1d1 | 679ce4b323f79b2425976201324c6c1f88b95199 | /Racket/bin-map.rkt | a60aa1da9a6ec4642fb604a897f4775b16729fc4 | [] | no_license | abriggs914/Coding_Practice | ff690fb5f145a11f4da144f3882b37f473b10450 | 3afd7c59e0d90f0ef5f6203853e69f853312019b | refs/heads/master | 2023-08-31T04:04:58.048554 | 2023-08-29T13:23:29 | 2023-08-29T13:23:29 | 161,865,421 | 0 | 1 | null | 2022-10-27T08:35:29 | 2018-12-15T03:20:14 | Python | UTF-8 | Racket | false | false | 1,251 | rkt | bin-map.rkt | #lang racket
#|
(define (binmap1 func lst1 lst2)
(cond
[(empty? lst1) lst2]
[(empty? lst2) lst1]
[(append (cons (func (first lst1) (first lst2)) '()) (binmap1 func (rest lst1) (rest lst2)))]))
(define (binmap2 func lst1 lst2)
(cond
[(empty? lst1) lst2]
[(empty? lst2) lst1]
[else (foldl (func (first lst1) (first lst2)) (binmap func (rest lst1) (rest lst2)) '())]))
|#
(define (helper acc func lsta lstb)
(cond
[(or (empty? lstb) (empty? lsta)) acc]
[else (helper (cons (func (first lsta) (first lstb)) acc) func (rest lsta) (rest lstb))]))
(define (binmap func lst1 lst2)
(cond
[(empty? lst1) lst2]
[(empty? lst2) lst1]
[else (reverse (helper '() func lst1 lst2))]))
(module+ test
(require rackunit)
(check-equal? (binmap + '(1 2 3) '(4 5 6)) '(5 7 9))
(check-equal? (binmap * '(1 2 3) '(4 5 6)) '(4 10 18))
(check-equal? (binmap string-append '("hello" "world ")
'(" mom" "travel"))
'("hello mom" "world travel"))
(check-equal? (binmap + '(1 2 3) '(4 5 6 7)) '(5 7 9))
(check-equal? (binmap + '(1 2 3 4) '(4 5 6)) '(5 7 9))
(check-equal? (binmap + '() '(4 5 6)) '(4 5 6))
(check-equal? (binmap + '(1 2 3 4) '()) '(1 2 3 4))) | false |
ffc055748664ddee6b7eb132998fdde25b42b645 | f05c1f175f69ec97ebeb367e153b211c4f3ca64e | /Racket/a9-2.rkt | 87e058e4e4965c9c754c0f87faab1f1f82541410 | [] | no_license | peterbuiltthis/FP | 2bea66def72a3e3592b3a57eccdbffdc440920bc | 3bfdb457cbe58c1f5502e3ff232bb6ac45f89936 | refs/heads/master | 2020-12-20T04:20:21.684915 | 2020-01-24T07:55:26 | 2020-01-24T07:55:26 | 235,959,816 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 4,563 | rkt | a9-2.rkt | #lang racket
(require "parenthec.rkt")
;; Step 2 -- RI
(define empty-k
(lambda ()
(let ((once-only #f))
(lambda (v)
(if once-only
(error 'empty-k "You can only invoke the empty continuation once")
(begin (set! once-only #t) v))))))
(define-union exp
(const n)
(var v)
(if test conseq alt)
(mult rand1 rand2)
(sub1 rand)
(zero rand)
(capture body)
(return vexp kexp)
(let vexp body)
(lambda body)
(app rator rand))
(define app-k
(lambda (k v)
(k v)))
(define if-inner
(lambda (conseq alt env k)
(lambda (v^)
(if v^
(value-of conseq env k)
(value-of alt env k)))))
(define mult-inner
(lambda (k v^)
(lambda (w)
(app-k k (* v^ w)))))
(define mult-outer
(lambda (rand2 env k)
(lambda (v^)
(value-of rand2 env (mult-inner k v^)))))
(define sub-inner
(lambda (k)
(lambda (v^)
(app-k k (- v^ 1)))))
(define zero-inner
(lambda (k)
(lambda (v^)
(app-k k (zero? v^)))))
(define return-inner
(lambda (vexp env)
(lambda (k^)
(value-of vexp env k^))))
(define let-inner
(lambda (body env k)
(lambda (v^)
(value-of body (envr_extend v^ env) k))))
(define app-inner
(lambda (v^ k)
(lambda (w)
(apply-closure v^ w k))))
(define app-outer
(lambda (rand env k)
(lambda (v^)
(value-of rand env (app-inner v^ k)))))
(define value-of
(lambda (expr env k)
(union-case expr exp
[(const n) (app-k k n)]
[(var v) (apply-env env v k)]
[(if test conseq alt) (value-of test env (if-inner conseq alt env k))]
[(mult rand1 rand2) (value-of rand1 env (mult-outer rand2 env k))]
[(sub1 rand) (value-of rand env (sub-inner k))]
[(zero rand) (value-of rand env (zero-inner k))]
[(capture body)
(value-of body (envr_extend k env) k)]
[(return vexp kexp)
(value-of kexp env (return-inner vexp env))]
[(let vexp body)
(value-of vexp env (let-inner body env k))]
[(lambda body) (k (clos_closure body env))]
[(app rator rand) (value-of rator env (app-outer rand env k))])))
(define-union envr
(empty)
(extend arg env))
(define apply-env
(lambda (env num k)
(union-case env envr
[(empty) (error 'env "unbound variable")]
[(extend arg env)
(if (zero? num)
(k arg)
(apply-env env (sub1 num) k))])))
(define-union clos
(closure code env))
(define apply-closure
(lambda (c a k)
(union-case c clos
[(closure code env)
(value-of code (envr_extend a env) k)])))
; Basic test...should be 5.
(pretty-print
(value-of (exp_app
(exp_app
(exp_lambda (exp_lambda (exp_var 1)))
(exp_const 5))
(exp_const 6))
(envr_empty)
(empty-k)))
; Factorial of 5...should be 120.
(pretty-print
(value-of (exp_app
(exp_lambda
(exp_app
(exp_app (exp_var 0) (exp_var 0))
(exp_const 5)))
(exp_lambda
(exp_lambda
(exp_if (exp_zero (exp_var 0))
(exp_const 1)
(exp_mult (exp_var 0)
(exp_app
(exp_app (exp_var 1) (exp_var 1))
(exp_sub1 (exp_var 0))))))))
(envr_empty)
(empty-k)))
; Test of capture and return...should evaluate to 24.
(pretty-print
(value-of
(exp_mult (exp_const 2)
(exp_capture
(exp_mult (exp_const 5)
(exp_return (exp_mult (exp_const 2) (exp_const 6))
(exp_var 0)))))
(envr_empty)
(empty-k)))
;; (let ([fact (lambda (f)
;; (lambda (n)
;; (if (zero? n)
;; 1
;; (* n ((f f) (sub1 n))))))])
;; ((fact fact) 5))
(pretty-print
(value-of (exp_let
(exp_lambda
(exp_lambda
(exp_if
(exp_zero (exp_var 0))
(exp_const 1)
(exp_mult
(exp_var 0)
(exp_app
(exp_app (exp_var 1) (exp_var 1))
(exp_sub1 (exp_var 0)))))))
(exp_app (exp_app (exp_var 0) (exp_var 0)) (exp_const 5)))
(envr_empty)
(empty-k))) | false |
e12102460a0edce98e3f4ccb561c43ce76129783 | 95bfc30172b907840a072b8ca62ec69200c9e982 | /chapter-2/exercise-2.60.rkt | 25ff136f24d1476aef77d7d903ef1f89db8cee13 | [] | 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 | 638 | rkt | exercise-2.60.rkt | #!/usr/bin/env racket
#lang racket
(define (element-of-set? x set)
(cond ((null? set) #f)
((eq? x (car set)) set)
(else (element-of-set? x (cdr set)))))
(define (adjoin-set x set)
(cons x set))
(define (intersection-set set1 set2)
(append set1 set2))
(define (union-set set1 set2)
(cond ((null? set1) set2)
((null? set2) set1)
((element-of-set? (car set1) set2)
(union-set (cdr set1) set2))
(else (cons (car set1)
(union-set (cdr set1) set2)))))
(define A '(2 3 5 7 11))
(define B '(1 3 5 7 9))
(adjoin-set 100 A)
(intersection-set A B)
(union-set A B)
| false |
f53c981b956da94ceadfa407ee38a3a2f5c8a83f | 17126876cd4ff4847ff7c1fbe42471544323b16d | /beautiful-racket-demo/info.rkt | d8df683aad7fa8966bb7ae8b72631b92b2705c57 | [
"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 | 667 | rkt | info.rkt | #lang info
;; the subdirectories here are suffixed with -demo
;; so they don't collide in the #lang namespace
;; with the test projects that readers will be making themselves
(define collection 'multi)
(define version "1.6")
;; base v6.7 dependency needs to be called 6.6.0.900
;; due to strange little bug in `raco pkg install`
(define deps '(["base" #:version "6.6.0.900"]
"sugar"
"beautiful-racket-lib"
"rackunit-lib"
"brag"
"srfi-lib"
"draw-lib"
"syntax-color-lib"
"gui-lib"
"math-lib"))
(define build-deps '("at-exp-lib")) | false |
3cf3a01205d9fe304517183190727eeecb2c59ab | efd3f3a245a7a1f44b2d79bd1976ef7f0b90999d | /show_display.rkt | 65e8f55b3255a5a0b107280e0656dc9401877ed5 | [] | no_license | scareaphina/Simply-Scheme | dbf00dbf6b6d23426445cc247ba3e536622a7741 | 280d68c45567c912fc124225c9c68d4157910ee3 | refs/heads/master | 2020-06-26T00:14:55.838602 | 2019-09-27T18:12:22 | 2019-09-27T18:12:22 | 199,463,271 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,132 | rkt | show_display.rkt | (require racket/trace)
(require rackunit)
; lists
; (check-equal? (function variable(s)) desired result)
; longer but with detailed show and display
(define (same-arg-twice fn y)
(show "outer")
(display "outer y ")
(show y)
(lambda (arg)
(show "inner")
(display "inner y ")
(show y)
(fn arg y))
)
(show 'preexecute)
(define square (same-arg-twice (lambda (x yi)
(display "innnerest x ")
(show x)
(display "innerest yi ")
(show yi)
(* x yi))
7))
(show 'postexecute)
(square 5)
(square 7)
(square 9)
; using trace-define and trace-lambda
(trace-define (same-arg-twice fn y)
(trace-lambda #:name innner (arg)
(fn arg y))
)
(show 'preexecute)
(define square (same-arg-twice (trace-lambda #:name innerest (x yi)
(* x yi))
7))
(show 'postexecute)
(square 5)
(square 7)
(square 9)
((trace-define-syntax 'ab (lambda (x y) (* x y))) 5 4)
| true |
881b6701febe36e93293e7d80d805cd5850c0dfb | 4d204d78919b942b9174bce87efa922ef2f630ed | /itscaleb/ch01/1.42.rkt | c924cc9c7a7aa5f59f23322738e7a553a5b4ee55 | [] | 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 | 199 | rkt | 1.42.rkt | #lang racket
(require rackunit)
(define (compose f g)
(lambda (x) (f (g x))))
(define (square x) (* x x))
(define (inc x) (+ 1 x))
(check-equal?
((compose square inc) 6)
49)
(provide compose) | false |
a7265512903aeb5713434e0723bfa71cc55ec3be | 18a51a897441d33155dda9b1969c1d4898820530 | /base/builtins/module.rkt | 5823100121fe2b86a7fac1871c36c6f5032cdf3a | [
"Apache-2.0"
] | permissive | jpolitz/lambda-py | 6fc94e84398363c6bb2e547051da9db6466ab603 | a2d1be7e017380414429a498435fb45975f546dd | refs/heads/master | 2019-04-21T09:36:42.116912 | 2013-04-16T13:30:44 | 2013-04-16T13:30:44 | 7,525,003 | 1 | 0 | null | 2013-01-09T22:32:47 | 2013-01-09T16:54:10 | Racket | UTF-8 | Racket | false | false | 503 | rkt | module.rkt | #lang plai-typed/untyped
(require "../python-core-syntax.rkt"
"type.rkt"
"../util.rkt")
(define module-class : CExpr
(seq-ops
(list
(CAssign (CId '$module (GlobalId))
(builtin-class
'$module
(list 'object)
(CNone)))
(def '$module '__str__
(CFunc (list 'self) (none)
(CReturn (make-builtin-str "<module>"))
(some '$module)))
(def '$module '__name__
(CNone)))))
| false |
6d25b0151c288493a1fbcb82891742f44807ae09 | ef61a036fd7e4220dc71860053e6625cf1496b1f | /HTDP2e/01-fixed-size-data/ch-02-functions-and-programs/ex-15-sunny-and-friday.rkt | 976000e5c5bc05cb81553fc16777ae68f8a307da | [] | no_license | lgwarda/racket-stuff | adb934d90858fa05f72d41c29cc66012e275931c | 936811af04e679d7fefddc0ef04c5336578d1c29 | refs/heads/master | 2023-01-28T15:58:04.479919 | 2020-12-09T10:36:02 | 2020-12-09T10:36:02 | 249,515,050 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 793 | rkt | ex-15-sunny-and-friday.rkt | ;; The first three lines of this file were inserted by DrRacket. They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-reader.ss" "lang")((modname ex-15-sunny-and-friday) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp")) #f)))
; ==>: Boolean Boolean -> Boolean
; produce always #true if sunny is fales or friday is true
(check-expect (==> #t #t) #t)
(check-expect (==> #t #f) #f)
(check-expect (==> #f #t) #t)
(check-expect (==> #f #f) #t)
(define (==> sunny friday)
(or (not sunny) friday))
| false |
71cfde531c4d159bc79ab4fb9a46c45059b09620 | 9e5f7de7265162c38f3e482266b819ede76113ba | /Assignment 2/a2q5.rkt | b60631f71bfbb62dca484ef162d58f1c39e29c7c | [
"Apache-2.0"
] | permissive | xiaroy/Comp-3007 | b34eb4859115415290302a9b4fb46c6bba9d173b | 4d65c7692ea69562fd94cd9a2f5ec28e9d1048fb | refs/heads/master | 2021-04-27T00:48:42.762857 | 2018-02-23T19:06:15 | 2018-02-23T19:06:15 | 122,661,050 | 0 | 2 | null | null | null | null | UTF-8 | Racket | false | false | 525 | rkt | a2q5.rkt | ;Name:Roy Xia
;Student Number: 101009419
;Question: 5
(define (inc x) (+ x 1))
(define (identity x) x)
(define (s a b)
(define (s-interative c d count)
(if (> c d)
count
(s-interative (inc c) (identity d) (+ count c))))
(if (> a b) "invalid"
(s-interative a b 0)))
;Test cases
(write "for (s 2 5) expect 14 answer: ")
(write (s 2 5))
(newline)
(write "for (s 2 10) expect 54 answer: ")
(write (s 2 10))
(newline)
(write "for (s 3 5) expect 12 answer: ")
(write (s 3 5))
(newline)
| false |
dd0cffb979d83222203a85cb02daaae4d7e1a8ff | 65c1f9548ad23d102a42be54ae7ef16f54767dba | /gregor-lib/gregor/private/pattern/l10n/trie.rkt | b8da414b860212e8c80a0c3acfce5581f69a16e7 | [
"MIT"
] | permissive | 97jaz/gregor | ea52754ce7aa057941a5a7080415768687cc4764 | 2d20192e8795e01a1671869dddaf1984f0cbafee | refs/heads/master | 2022-07-20T12:52:15.088073 | 2022-06-28T09:48:59 | 2022-07-19T16:01:18 | 32,499,398 | 45 | 11 | null | 2022-06-28T09:50:43 | 2015-03-19T03:47:23 | Racket | UTF-8 | Racket | false | false | 1,405 | rkt | trie.rkt | #lang racket/base
(require racket/match)
(provide invert-hash->trie
list->trie
trie-longest-match)
(struct nothing ())
(struct trie (v m) #:transparent)
(struct cased-trie (t ci?))
(define empty (trie (nothing) '()))
(define (list->trie xs ci?)
(define =? (get=? ci?))
(cased-trie
(for/fold ([t empty]) ([x (in-list xs)])
(ins t (string->list x) (cons (string->symbol x) x) =?))
=?))
(define (invert-hash->trie h ci?)
(define =? (get=? ci?))
(cased-trie
(for/fold ([t empty]) ([(k v) (in-hash h)])
(ins t (string->list v) (cons k v) =?))
=?))
(define (trie-longest-match ct cs)
(match-define (cased-trie t =?) ct)
(longest t cs =?))
(define (ins t ks v =?)
(match* (t ks v)
[((trie _ m) '() x)
(trie x m)]
[((trie v m) (cons k ks) x)
(let* ([t (or (ref m k =?) empty)]
[t (ins t ks x =?)])
(trie v (set m k t)))]))
(define (longest t ks =? [best #f])
(match* (t ks)
[((trie (nothing) _) '()) best]
[((trie x _) '()) x]
[((trie x m) (cons k ks))
(define new-best (if (nothing? x) best x))
(match (ref m k =?)
[#f new-best]
[m (longest m ks =? new-best)])]))
(define (ref m k =?)
(for/first ([p (in-list m)]
#:when (=? (car p) k))
(cdr p)))
(define (set m k v)
(cons (cons k v) m))
(define (get=? ci?)
(if ci? char-ci=? char=?))
| false |
3fddf6a89515fe24852f3cfb15d366b672506598 | 749ef37fcdbd3e56ceca9202ae72efd294397223 | /project1.rkt | 8a5583177423d0c9c825ff862d14c5889dff8c73 | [] | no_license | dogsdude/CompilerConstruction | 9f37828b654489a396cf30d12cf6059fc879669c | 6b565f42cba6db6b08f32584ed8d21fa2c120f63 | refs/heads/master | 2022-01-19T18:20:13.995263 | 2019-07-22T23:06:53 | 2019-07-22T23:06:53 | 198,311,261 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 8,884 | rkt | project1.rkt | ;Sam Lindsey, Project1, 1/24/2019
#lang racket
; needed for parsing stuff
(require parser-tools/lex
; this last gives us prettier names for common regular expression stuff,
; and also renames it so they're all prefixed with ':' in their names
(prefix-in : parser-tools/lex-sre))
(require test-engine/racket-tests)
(provide (all-defined-out))
(define-tokens value-tokens (NUM ID STRING BOOL))
(define-empty-tokens paren-types (LPAREN RPAREN LBRACKET RBRACKET LBRACE RBRACE))
(define-empty-tokens operators (ADD MULT DIV SUB DOT))
(define-empty-tokens punctuation (COMMA COLON SEMI))
(define-empty-tokens comparators (EQ NE LT GT LE GE))
(define-empty-tokens boolops (BOOLOR BOOLAND))
(define-empty-tokens keywords (AND ARRAY AS BREAK DEFINE DO ELSE END IF IN IS
JUNIPER KIND LET NEEWOM NI NOW OF PENG THEN
TO WHILE WITH))
(define-empty-tokens endoffile (EOF))
(define nilex
(lexer-src-pos
;Values, Types, Operators, Punctuation, Comparators, Boolean Operations
[#\( (token-LPAREN)]
[#\) (token-RPAREN)]
[#\[ (token-LBRACKET)]
[#\] (token-RBRACKET)]
[#\{ (token-LBRACE)]
[#\} (token-RBRACE)]
[#\+ (token-ADD)]
[#\* (token-MULT)]
[#\/ (token-DIV)]
[#\- (token-SUB)]
[#\. (token-DOT)]
[#\, (token-COMMA)]
[#\: (token-COLON)]
[#\; (token-SEMI)]
[#\= (token-EQ)]
[#\< (token-LT)]
["<=" (token-LE)]
[#\> (token-GT)]
[">=" (token-GE)]
[#\| (token-BOOLOR)]
[#\& (token-BOOLAND)]
;Keywords
[(:or "AND" "And" "and") (token-AND)]
[(:or "ARRAY" "Array" "array") (token-ARRAY)]
[(:or "AS" "As" "as") (token-AS)]
[(:or "BREAK" "Break" "break") (token-BREAK)]
[(:or "DEFINE" "Define" "define")(token-DEFINE)]
[(:or "DO" "Do" "do") (token-DO)]
[(:or "ELSE" "Else" "else") (token-ELSE)]
[(:or "END" "End" "end") (token-END)]
[(:or "IF" "If" "if") (token-IF)]
[(:or "IN" "In" "in") (token-IN)]
[(:or "IS" "Is" "is") (token-IS)]
[(:or "JUNIPER" "Juniper" "juniper") (token-JUNIPER)]
[(:or "KIND" "Kind" "kind") (token-KIND)]
[(:or "LET" "Let" "let") (token-LET)]
[(:or "NEEWOM" "Neewom" "neewom")(token-NEEWOM)]
[(:or "NI" "Ni" "ni") (token-NI)]
[(:or "NOW" "Now" "now") (token-NOW)]
[(:or "OF" "Of" "of") (token-OF)]
[(:or "PENG" "Peng" "peng") (token-PENG)]
[(:or "THEN" "Then" "then") (token-THEN)]
[(:or "TO" "To" "to") (token-TO)]
[(:or "WHILE" "While" "while") (token-WHILE)]
[(:or "WITH" "With" "with") (token-WITH)]
;Boolean
["true" (token-BOOL #t)]
["false" (token-BOOL #f)]
;EOF
[(eof) (token-EOF)]
;Num
[(:+ numeric) (token-NUM lexeme)]
;Identifier
[(:: (:+ alphabetic) (:* (:or numeric alphabetic #\_ #\-))(:* #\')) (token-ID lexeme)]
;String
[(:: #\" (:* (:or (:: #\\ any-char)(complement (:or #\\ #\")))) #\") (token-STRING lexeme)]
;Single Line Comment
[(:: "//" (:+ (char-complement #\newline))) (return-without-pos (nilex input-port)) ]
;Block Comment
[(:: "/*" (complement (:: any-string "*/" any-string)) "*/") (return-without-pos (nilex input-port))]
[(:: #\" (:* (:or (:: #\\ any-char) (char-complement (char-set "\"\\")))) #\") (token-STRING lexeme)]
; match // followed by anything that ends in \n
;White Space
[whitespace (return-without-pos (nilex input-port))]
))
; position -> string -> error
; raises a lexing error
(define (raise-lex-error pos lexeme)
(let* ([linenums? (not (eq? (position-line pos) #f))]
[loc (if linenums? (position-line pos) (position-offset pos))]
[col (position-col pos)]
[partial-msg (string-append (if linenums? "syntax error at line "
"syntax error at offset ") (number->string loc))]
[msg (string-append partial-msg (if linenums? (string-append ", col " (number->string col)) "")
": '" lexeme "'")])
;(lexer-error #t)
(raise-syntax-error 'nilex msg)))
; input port -> thunk
; creates a thunk that when called will return the next token from the input stream
(define (get-tokenizer in)
(λ () (nilex in)))
; input port -> list of tokens
; this function takes an input port and returns a list of
; tokens read from it (until it hits eof)
(define (lex in)
(port-count-lines! in)
(let ([tokenize (get-tokenizer in)])
(define (lexfun)
(let ([tok (tokenize)])
(cond
; test to see if we hit eof as the base case
[(eq? (position-token-token tok) (token-EOF)) null]
[else (cons (position-token-token tok) (lexfun))])))
(lexfun)))
; string -> list of tokens
; this function takes a string and returns a list of
; tokens read from it (until it reaches the end)
(define (lexstr str)
(lex (open-input-string str)))
; filename -> list of tokens
; this function takes a filename, opens it as an input port,
; and then reads tokens until the end is reached
(define (lexfile filename)
(lex (open-input-file filename)))
;Test Cases
(check-expect (lexstr "and") (list (token-AND)))
(check-expect (lexstr "array") (list (token-ARRAY)))
(check-expect (lexstr "as") (list (token-AS)))
(check-expect (lexstr "break") (list (token-BREAK)))
(check-expect (lexstr "do") (list (token-DO)))
(check-expect (lexstr "else") (list (token-ELSE)))
(check-expect (lexstr "end") (list (token-END)))
(check-expect (lexstr "if") (list (token-IF)))
(check-expect (lexstr "in") (list (token-IN)))
(check-expect (lexstr "is") (list (token-IS)))
(check-expect (lexstr "juniper") (list (token-JUNIPER)))
(check-expect (lexstr "kind") (list (token-KIND)))
(check-expect (lexstr "let") (list (token-LET)))
(check-expect (lexstr "neewom") (list (token-NEEWOM)))
(check-expect (lexstr "ni") (list (token-NI)))
(check-expect (lexstr "now") (list (token-NOW)))
(check-expect (lexstr "of") (list (token-OF)))
(check-expect (lexstr "peng") (list (token-PENG)))
(check-expect (lexstr "]") (list (token-RBRACKET)))
(check-expect (lexstr "[") (list (token-LBRACKET)))
(check-expect (lexstr "}") (list (token-RBRACE)))
(check-expect (lexstr "{") (list (token-LBRACE)))
(check-expect (lexstr ")") (list (token-RPAREN)))
(check-expect (lexstr "(") (list (token-LPAREN)))
(check-expect (lexstr "+") (list (token-ADD)))
(check-expect (lexstr "-") (list (token-SUB)))
(check-expect (lexstr "/") (list (token-DIV)))
(check-expect (lexstr "*") (list (token-MULT)))
(check-expect (lexstr ";") (list (token-SEMI)))
(check-expect (lexstr ",") (list (token-COMMA)))
(check-expect (lexstr ":") (list (token-COLON)))
(check-expect (lexstr ">") (list (token-GT)))
(check-expect (lexstr "<") (list (token-LT)))
(check-expect (lexstr "=") (list (token-EQ)))
(check-expect (lexstr ">=") (list (token-GE)))
(check-expect (lexstr "<=") (list (token-LE)))
(check-expect (lexstr "&") (list (token-BOOLAND)))
(check-expect (lexstr "|") (list (token-BOOLOR)))
(check-expect (lexstr "1") (list (token-NUM "1")))
(check-expect (lexstr "ax") (list (token-ID "ax")))
(check-expect (lexstr (string-append (string #\") (string #\\) (string #\") "Hello world" (string #\\) (string #\") (string #\")))
(list (token-STRING (string-append (string #\") (string #\\) (string #\") "Hello world" (string #\\) (string #\") (string #\") ))))
(check-expect (lexstr "") '())
(check-expect (lexstr "ni") (list (token-NI)))
(check-expect (lexstr "5") (list (token-NUM "5")))
(check-expect (lexstr "56") (list (token-NUM "56")))
(check-expect (lexstr "/* Hello
there */") '())
(check-expect (lexstr "/* hello */5/*there*/") (list (token-NUM "5")))
(check-expect (lexstr "// this is a comment \n5+3") (list (token-NUM "5") (token-ADD) (token-NUM "3")))
(check-expect (lexstr "\"\\\\\"a\"\"") (list (token-STRING "\"\\\\\"") (token-ID "a") (token-STRING "\"\"")))
(check-expect (lexstr "\"you had me at \\\"hello\\\"\"") (list (token-STRING "\"you had me at \\\"hello\\\"\"")))
(test) | false |
aeb12d53154ff0bbeabe32a13805448fe1351cdd | 50508fbb3a659c1168cb61f06a38a27a1745de15 | /turnstile/info.rkt | 2c70b35cd043d888c7c9cee1a11ab1a2276bff06 | [
"BSD-2-Clause"
] | permissive | phlummox/macrotypes | e76a8a4bfe94a2862de965a4fefd03cae7f2559f | ea3bf603290fd9d769f4f95e87efe817430bed7b | refs/heads/master | 2022-12-30T17:59:15.489797 | 2020-08-11T16:03:02 | 2020-08-11T16:03:02 | 307,035,363 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 414 | rkt | info.rkt | #lang info
(define collection 'multi)
(define deps
'(("turnstile-lib" #:version "0.3.1")
("turnstile-example" #:version "0.3.1")
("turnstile-doc" #:version "0.3.1")
("turnstile-test" #:version "0.3.1")))
(define build-deps '())
(define pkg-desc
"A meta-package for turnstile-lib, turnstile-example, turnstile-doc, and turnstile-test.")
(define pkg-authors '(stchang))
(define version "0.3.1")
| false |
ecde3d2ba486ebed7d52b8ddb168dd6df5d740cf | 3b4437400fc746d3d161adfa43311d348f4fcde5 | /rooms/display.rkt | 238107f2dff3979b5398c964a8e5096d93136c02 | [] | no_license | ChaseWhite3/linear-logic | bdd52382c26b1274b4fbf7c3857ac98dfb1cb3b8 | e7f8526408c7f9128094c3cac891f31d850aaffc | refs/heads/master | 2020-07-04T02:54:18.260024 | 2018-06-24T04:48:56 | 2018-06-24T04:48:56 | 4,196,429 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 15,476 | rkt | display.rkt | #lang s-exp "../rooms.rkt"
; North of USB cable
6 "display"
(success (command (look (room (name "53th Street and Dorchester Avenue")(description "You are standing at the corner of 53th Street and Dorchester Avenue. From here, you can go north, east, or south. ")(items ((item (name "N-1623-AOE")(description "an exemplary instance of part number N-1623-AOE")(adjectives ((adjective "fern-green") ))(condition (pristine ))(piled_on ((item (name "R-4292-FRL")(description "an exemplary instance of part number R-4292-FRL")(adjectives ((adjective "burgundy") ))(condition (broken (condition (broken (condition (pristine ))(missing ((kind (name "V-9887-KUS")(condition (pristine ))) ))))(missing ((kind (name "Z-6458-PXZ")(condition (broken (condition (pristine ))(missing ((kind (name "D-5065-UBI")(condition (pristine ))) ))))) ))))(piled_on ((item (name "F-6458-DDN")(description "an exemplary instance of part number F-6458-DDN")(adjectives ((adjective "pale-magenta") ))(condition (broken (condition (pristine ))(missing ((kind (name "J-5065-IGU")(condition (pristine ))) ))))(piled_on ((item (name "H-1623-MYO")(description "an exemplary instance of part number H-1623-MYO")(adjectives ((adjective "peach-yellow") ))(condition (broken (condition (broken (condition (pristine ))(missing ((kind (name "L-4292-RCV")(condition (pristine ))) ))))(missing ((kind (name "T-6458-BIL")(condition (broken (condition (broken (condition (broken (condition (pristine ))(missing ((kind (name "X-5065-GLS")(condition (pristine ))) ))))(missing ((kind (name "T-5065-OQC")(condition (broken (condition (pristine ))(missing ((kind (name "B-6678-LOZ")(condition (pristine ))) ))))) ))))(missing ((kind (name "F-9247-QRI")(condition (pristine ))) ))))) ((kind (name "P-9887-WFE")(condition (pristine ))) )))))(piled_on ((item (name "H-4292-ZHF")(description "an exemplary instance of part number H-4292-ZHF")(adjectives ((adjective "rotating") ))(condition (broken (condition (pristine ))(missing ((kind (name "J-4832-VUP")(condition (pristine ))) ))))(piled_on ((item (name "R-6458-FXP")(description "an exemplary instance of part number R-6458-FXP")(adjectives ((adjective "low-carb") ))(condition (broken (condition (pristine ))(missing ((kind (name "V-5065-KBW")(condition (pristine ))) ((kind (name "H-1623-MYO")(condition (broken (condition (broken (condition (pristine ))(missing ((kind (name "L-4292-RCV")(condition (pristine ))) ))))(missing ((kind (name "P-9887-WFE")(condition (pristine ))) ))))) ((kind (name "H-4292-ZHF")(condition (broken (condition (pristine ))(missing ((kind (name "J-4832-VUP")(condition (pristine ))) ))))) ))))))(piled_on ((item (name "T-6458-BIL")(description "an exemplary instance of part number T-6458-BIL")(adjectives ((adjective "mysterious") ))(condition (broken (condition (broken (condition (broken (condition (pristine ))(missing ((kind (name "X-5065-GLS")(condition (pristine ))) ))))(missing ((kind (name "T-5065-OQC")(condition (broken (condition (pristine ))(missing ((kind (name "B-6678-LOZ")(condition (pristine ))) ))))) ))))(missing ((kind (name "F-9247-QRI")(condition (pristine ))) ))))(piled_on ((item (name "R-9247-SMK")(description "an exemplary instance of part number R-9247-SMK")(adjectives ((adjective "brass") ))(condition (broken (condition (pristine ))(missing ((kind (name "V-4832-XPR")(condition (pristine ))) ))))(piled_on ((item (name "Z-1403-CSY")(description "an exemplary instance of part number Z-1403-CSY")(adjectives ((adjective "puce") ))(condition (broken (condition (pristine ))(missing ((kind (name "D-0010-HVH")(condition (pristine ))) ))))(piled_on ((item (name "N-6678-NJD")(description "an exemplary instance of part number N-6678-NJD")(adjectives ((adjective "pink") ))(condition (broken (condition (pristine ))(missing ((kind (name "R-9247-SMK")(condition (broken (condition (pristine ))(missing ((kind (name "V-4832-XPR")(condition (pristine ))) ))))) ))))(piled_on ((item (name "X-4292-TWX")(description "an exemplary instance of part number X-4292-TWX")(adjectives ((adjective "jade") ))(condition (broken (condition (pristine ))(missing ((kind (name "N-6678-NJD")(condition (pristine ))) ((kind (name "B-9887-YAG")(condition (pristine ))) )))))(piled_on ((item (name "Z-6678-PEF")(description "an exemplary instance of part number Z-6678-PEF")(adjectives ((adjective "flax") ))(condition (broken (condition (pristine ))(missing ((kind (name "X-4292-TWX")(condition (broken (condition (pristine ))(missing ((kind (name "B-9887-YAG")(condition (pristine ))) ))))) ))))(piled_on ((item (name "H-4832-ZKT")(description "an exemplary instance of part number H-4832-ZKT")(adjectives ((adjective "pale-blue") ))(condition (broken (condition (pristine ))(missing ((kind (name "L-1403-ENC")(condition (pristine ))) ))))(piled_on ((item (name "P-0010-JQJ")(description "an exemplary instance of part number P-0010-JQJ")(adjectives ((adjective "gray60") ))(condition (broken (condition (broken (condition (pristine ))(missing ((kind (name "P-9247-WCO")(condition (pristine ))) ))))(missing ((kind (name "T-1623-OTQ")(condition (pristine ))) ))))(piled_on ((item (name "J-1403-IDG")(description "an exemplary instance of part number J-1403-IDG")(adjectives ((adjective "olive-green") ))(condition (broken (condition (pristine ))(missing ((kind (name "H-4832-ZKT")(condition (broken (condition (pristine ))(missing ((kind (name "L-1403-ENC")(condition (pristine ))) ))))) ))))(piled_on ((item (name "D-9247-UHM")(description "an exemplary instance of part number D-9247-UHM")(adjectives ((adjective "swamp-green") ))(condition (pristine ))(piled_on ((item (name "N-6458-NDX")(description "an exemplary instance of part number N-6458-NDX")(adjectives ((adjective "khaki") ))(condition (broken (condition (broken (condition (pristine ))(missing ((kind (name "L-6678-RYH")(condition (pristine ))) ))))(missing ((kind (name "Z-6678-PEF")(condition (pristine ))) ((kind (name "J-1403-IDG")(condition (pristine ))) ((kind (name "P-9247-WCO")(condition (pristine ))) ))))))(piled_on ((item (name "V-9887-KUS")(description "an exemplary instance of part number V-9887-KUS")(adjectives ((adjective "red-violet") ))(condition (broken (condition (pristine ))(missing ((kind (name "R-6458-FXP")(condition (broken (condition (pristine ))(missing ((kind (name "V-5065-KBW")(condition (pristine ))) ))))) ((kind (name "T-4832-BFV")(condition (pristine ))) ((kind (name "H-6678-ZEP")(condition (broken (condition (pristine ))(missing ((kind (name "V-9887-KUS")(condition (pristine ))) ))))) ))))))(piled_on ((item (name "N-0010-NGN")(description "an exemplary instance of part number N-0010-NGN")(adjectives ((adjective "tea-green") ))(condition (broken (condition (pristine ))(missing ((kind (name "N-6458-NDX")(condition (broken (condition (broken (condition (pristine ))(missing ((kind (name "L-6678-RYH")(condition (pristine ))) ))))(missing ((kind (name "P-9247-WCO")(condition (pristine ))) ))))) ((kind (name "R-1623-SJU")(condition (pristine ))) )))))(piled_on ((item (name "X-1403-GIE")(description "an exemplary instance of part number X-1403-GIE")(adjectives ((adjective "cinnamon") ))(condition (broken (condition (broken (condition (pristine ))(missing ((kind (name "B-0010-LLL")(condition (pristine ))) ))))(missing ((kind (name "F-1623-QOS")(condition (broken (condition (broken (condition (pristine ))(missing ((kind (name "J-4292-VRZ")(condition (pristine ))) ))))(missing ((kind (name "N-9887-AUI")(condition (pristine ))) ))))) ))))(piled_on ((item (name "T-4832-BFV")(description "an exemplary instance of part number T-4832-BFV")(adjectives ((adjective "gray20") ))(condition (pristine ))(piled_on ((item (name "D-6458-HSR")(description "an exemplary instance of part number D-6458-HSR")(adjectives ((adjective "beige") ))(condition (broken (condition (pristine ))(missing ((kind (name "H-5065-MVY")(condition (pristine ))) ))))(piled_on ((item (name "F-4832-DAX")(description "an exemplary instance of part number F-4832-DAX")(adjectives ((adjective "ghost-white") ))(condition (broken (condition (pristine ))(missing ((kind (name "J-1403-IDG")(condition (pristine ))) ((kind (name "D-6458-HSR")(condition (broken (condition (pristine ))(missing ((kind (name "H-5065-MVY")(condition (pristine ))) ))))) ((kind (name "V-4292-XMD")(condition (broken (condition (pristine ))(missing ((kind (name "Z-9887-CPK")(condition (pristine ))) ))))) ((kind (name "N-0010-NGN")(condition (broken (condition (pristine ))(missing ((kind (name "R-1623-SJU")(condition (pristine ))) ))))) )))))))(piled_on ((item (name "V-4292-XMD")(description "an exemplary instance of part number V-4292-XMD")(adjectives ((adjective "olive-green") ))(condition (broken (condition (pristine ))(missing ((kind (name "Z-9887-CPK")(condition (pristine ))) ))))(piled_on ((item (name "H-4292-ZHF")(description "an exemplary instance of part number H-4292-ZHF")(adjectives ((adjective "light-brown") ))(condition (broken (condition (pristine ))(missing ((kind (name "L-9887-EKM")(condition (pristine ))) ))))(piled_on ((item (name "X-6678-TTJ")(description "an exemplary instance of part number X-6678-TTJ")(adjectives ((adjective "lawn-green") ))(condition (broken (condition (broken (condition (pristine ))(missing ((kind (name "B-9247-YWQ")(condition (pristine ))) ))))(missing ((kind (name "X-9887-GFO")(condition (pristine ))) ((kind (name "F-4832-DAX")(condition (broken (condition (pristine ))(missing ((kind (name "J-1403-IDG")(condition (pristine ))) ))))) )))))(piled_on ((item (name "T-4292-BCH")(description "an exemplary instance of part number T-4292-BCH")(adjectives ((adjective "aquamarine") ))(condition (broken (condition (pristine ))(missing ((kind (name "X-9887-GFO")(condition (pristine ))) ((kind (name "X-6678-TTJ")(condition (broken (condition (broken (condition (pristine ))(missing ((kind (name "B-9247-YWQ")(condition (pristine ))) ))))(missing ((kind (name "X-9887-GFO")(condition (pristine ))) ))))) )))))(piled_on ((item (name "P-6458-JNT")(description "an exemplary instance of part number P-6458-JNT")(adjectives ((adjective "maroon") ))(condition (broken (condition (pristine ))(missing ((kind (name "T-5065-OQC")(condition (pristine ))) ))))(piled_on ((item (name "Z-0010-PBP")(description "an exemplary instance of part number Z-0010-PBP")(adjectives ((adjective "rust") ))(condition (broken (condition (pristine ))(missing ((kind (name "D-1623-UEW")(condition (pristine ))) ((kind (name "H-4292-ZHF")(condition (broken (condition (pristine ))(missing ((kind (name "L-9887-EKM")(condition (pristine ))) ))))) )))))(piled_on ((item (name "F-5065-QLE")(description "an exemplary instance of part number F-5065-QLE")(adjectives ((adjective "cyan") ))(condition (broken (condition (broken (condition (broken (condition (pristine ))(missing ((kind (name "J-6678-VOL")(condition (pristine ))) ))))(missing ((kind (name "N-9247-ARS")(condition (pristine ))) ))))(missing ((kind (name "Z-0010-PBP")(condition (broken (condition (pristine ))(missing ((kind (name "D-1623-UEW")(condition (pristine ))) ))))) ((kind (name "R-4832-FUZ")(condition (broken (condition (pristine ))(missing ((kind (name "V-1403-KXI")(condition (pristine ))) ))))) )))))(piled_on ((item (name "V-9887-KUS")(description "an exemplary instance of part number V-9887-KUS")(adjectives ((adjective "lavender-blush") ))(condition (broken (condition (pristine ))(missing ((kind (name "H-1403-MSK")(condition (pristine ))) ))))(piled_on ((item (name "B-6458-LIV")(description "an exemplary instance of part number B-6458-LIV")(adjectives ((adjective "olive-drab") ))(condition (pristine ))(piled_on ((item (name "D-5065-UBI")(description "an exemplary instance of part number D-5065-UBI")(adjectives ((adjective "plum") ))(condition (broken (condition (broken (condition (broken (condition (pristine ))(missing ((kind (name "R-5065-SGG")(condition (pristine ))) ))))(missing ((kind (name "V-6678-XJN")(condition (pristine ))) ))))(missing ((kind (name "Z-9247-CMU")(condition (pristine ))) ((kind (name "T-4292-BCH")(condition (broken (condition (pristine ))(missing ((kind (name "X-9887-GFO")(condition (pristine ))) ))))) )))))(piled_on ((item (name "L-9247-EHW")(description "an exemplary instance of part number L-9247-EHW")(adjectives ((adjective "magenta") ))(condition (broken (condition (pristine ))(missing ((kind (name "P-4832-JKF")(condition (broken (condition (pristine ))(missing ((kind (name "T-1403-ONM")(condition (pristine ))) ))))) ((kind (name "D-5065-UBI")(condition (broken (condition (broken (condition (broken (condition (pristine ))(missing ((kind (name "R-5065-SGG")(condition (pristine ))) ))))(missing ((kind (name "V-6678-XJN")(condition (pristine ))) ))))(missing ((kind (name "Z-9247-CMU")(condition (pristine ))) ))))) ((kind (name "P-1623-WYY")(condition (pristine ))) ))))))(piled_on ((item (name "P-1623-WYY")(description "an exemplary instance of part number P-1623-WYY")(adjectives ((adjective "ochre") ))(condition (pristine ))(piled_on ((item (name "D-4832-HPD")(description "an exemplary instance of part number D-4832-HPD")(adjectives ((adjective "gray60") ))(condition (broken (condition (pristine ))(missing ((kind (name "H-1403-MSK")(condition (broken (condition (pristine ))(missing ((kind (name "L-0010-RVR")(condition (pristine ))) ))))) ))))(piled_on ((item (name "B-1623-YTC")(description "an exemplary instance of part number B-1623-YTC")(adjectives ((adjective "chestnut") ))(condition (broken (condition (pristine ))(missing ((kind (name "F-4292-DWJ")(condition (pristine ))) ((kind (name "Z-6458-PXZ")(condition (broken (condition (pristine ))(missing ((kind (name "J-9887-IAQ")(condition (pristine ))) ))))) )))))(piled_on ((item (name "Z-6458-PXZ")(description "an exemplary instance of part number Z-6458-PXZ")(adjectives ((adjective "rust") ))(condition (broken (condition (pristine ))(missing ((kind (name "N-6458-NDX")(condition (pristine ))) ))))(piled_on ((item (name "Z-6458-PXZ")(description "an exemplary instance of part number Z-6458-PXZ")(adjectives ((adjective "robin-egg-blue") ))(condition (broken (condition (pristine ))(missing ((kind (name "J-9887-IAQ")(condition (pristine ))) ))))(piled_on ((item (name "display")(description "a handheld device for showing textual data")(adjectives )(condition (broken (condition (pristine ))(missing ((kind (name "L-9247-EHW")(condition (broken (condition (pristine ))(missing ((kind (name "P-4832-JKF")(condition (broken (condition (pristine ))(missing ((kind (name "T-1403-ONM")(condition (pristine ))) ))))) ))))) ((kind (name "B-1623-YTC")(condition (broken (condition (pristine ))(missing ((kind (name "F-4292-DWJ")(condition (pristine ))) ))))) ((kind (name "R-4292-FRL")(condition (broken (condition (broken (condition (pristine ))(missing ((kind (name "V-9887-KUS")(condition (pristine ))) ))))(missing ((kind (name "Z-6458-PXZ")(condition (broken (condition (pristine ))(missing ((kind (name "D-5065-UBI")(condition (pristine ))) ))))) ))))) ((kind (name "N-1623-AOE")(condition (pristine ))) )))))))(piled_on ((item (name "X-0010-TQT")(description "an exemplary instance of part number X-0010-TQT")(adjectives ((adjective "navajo-white") ))(condition (broken (condition (pristine ))(missing ((kind (name "H-6678-ZEP")(condition (pristine ))) ))))(piled_on )) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))) ))))))
#<<END
END | false |
05b598c9f7675411d085610aae8a96ba8f9c5fbe | 2b1821134bb02ec32f71ddbc63980d6e9c169b65 | /lisp/racket/SPD/11/same-house-as-parent.rkt | 6b1ba7580e06cf5d29fe9e088260a2589754da92 | [] | no_license | mdssjc/study | a52f8fd6eb1f97db0ad523131f45d5caf914f01b | 2ca51a968e254a01900bffdec76f1ead2acc8912 | refs/heads/master | 2023-04-04T18:24:06.091047 | 2023-03-17T00:55:50 | 2023-03-17T00:55:50 | 39,316,435 | 3 | 1 | null | 2023-03-04T00:50:33 | 2015-07-18T23:53:39 | Java | UTF-8 | Racket | false | false | 6,632 | rkt | same-house-as-parent.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-advanced-reader.ss" "lang")((modname same-house-as-parent-v1) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #t #t none #f () #f)))
;; same-house-as-parent.rkt
;; PROBLEM:
;;
;; In the Harry Potter movies, it is very important which of the four
;; houses a wizard is placed in when they are at Hogwarts. This is so
;; important that in most families multiple generations of wizards are
;; all placed in the same family.
;;
;; Design a representation of wizard family trees that includes, for
;; each wizard, their name, the house they were placed in at Hogwarts
;; and their children. We encourage you to get real information for
;; wizard families from:
;; http://harrypotter.wikia.com/wiki/Main_Page
;;
;; The reason we do this is that designing programs often involves
;; collection domain information from a variety of sources and
;; representing it in the program as constants of some form. So this
;; problem illustrates a fairly common scenario.
;;
;; That said, for reasons having to do entirely with making things fit
;; on the screen in later videos, we are going to use the following
;; wizard family tree, in which wizards and houses both have 1 letter
;; names. (Sigh)
;; =================
;; Data definitions:
(define-struct wiz (name house kids))
;; Wizard is (make-wiz String String (listof Wizard))
;; interp. A wizard, with name, house and list of children.
(define Wa (make-wiz "A" "S" empty))
(define Wb (make-wiz "B" "G" empty))
(define Wc (make-wiz "C" "R" empty))
(define Wd (make-wiz "D" "H" empty))
(define We (make-wiz "E" "R" empty))
(define Wf (make-wiz "F" "R" (list Wb)))
(define Wg (make-wiz "G" "S" (list Wa)))
(define Wh (make-wiz "H" "S" (list Wc Wd)))
(define Wi (make-wiz "I" "H" empty))
(define Wj (make-wiz "J" "R" (list We Wf Wg)))
(define Wk (make-wiz "K" "G" (list Wh Wi Wj)))
#; ;template, arb-arity-tree, encapsulated w/ local
(define (fn-for-wiz w)
(local [(define (fn-for-wiz w)
(... (wiz-name w)
(wiz-house w)
(fn-for-low (wiz-kids w))))
(define (fn-for-low low)
(cond [(empty? low) (...)]
[else
(... (fn-for-wiz (first low))
(fn-for-low (rest low)))]))]
(fn-for-wiz w)))
;; ==========
;; Functions:
;; PROBLEM:
;;
;; Design a function that consumes a wizard and produces the names of
;; every wizard in the tree that was placed in the same house as their
;; immediate parent.
;; Wizard -> (listof String)
;; Produce the names of every descendant in the same house as their parent.
(check-expect (same-house-as-parent Wa) empty)
(check-expect (same-house-as-parent Wh) empty)
(check-expect (same-house-as-parent Wg) (list "A"))
(check-expect (same-house-as-parent Wk) (list "E" "F" "A"))
; template from Wizard plus lost context accumulator
(define (same-house-as-parent w)
;; parent-house is String; the house of this wizard's immediate parent ("" for root of tree)
;; (same-house-as-parent Wk)
;; (fn-for-wiz Wk "")
;; (fn-for-wiz Wh "G")
;; (fn-for-wiz Wc "S")
;; (fn-for-wiz Wd "S")
;; (fn-for-wiz Wi "G")
(local [(define (fn-for-wiz w parent-house)
(if (string=? (wiz-house w) parent-house)
(cons (wiz-name w)
(fn-for-low (wiz-kids w)
(wiz-house w)))
(fn-for-low (wiz-kids w)
(wiz-house w))))
(define (fn-for-low low parent-house)
(cond [(empty? low) empty]
[else
(append (fn-for-wiz (first low) parent-house)
(fn-for-low (rest low) parent-house))]))]
(fn-for-wiz w "")))
;; PROBLEM:
;;
;; Design a function that consumes a wizard and produces the number of
;; wizards in that tree (including the root). Your function should be
;; tail recursive.
;; Wizard -> Natural
;; produces the number of wizards in that tree (including the root)
(check-expect (count Wa) 1)
(check-expect (count Wk) 11)
;template from Wizard, add an accumulator for tail recursion
(define (count w)
;; rsf is Natural; the number of wizards seen so far
;; todo is (listof Wizard); wizards we still need to visit with fn-for-wiz
;; (count Wk)
;; (fn-for-wiz Wk 0)
;; (fn-for-wiz Wh 1)
;; (fn-for-wiz Wc 2)
(local ((define (fn-for-wiz w todo rsf)
(fn-for-low (append (wiz-kids w) todo)
(add1 rsf)))
(define (fn-for-low todo rsf)
(cond [(empty? todo) rsf]
[else
(fn-for-wiz (first todo) (rest todo) rsf)])))
(fn-for-wiz w empty 0)))
;; PROBLEM:
;;
;; Design a new function definition for same-house-as-parent that is
;; tail recursive. You will need a worklist accumulator.
;; Wizard -> (listof String)
;; Produce the names of every descendant in the same house as their parent.
(check-expect (same-house-as-parent-v2 Wa) empty)
(check-expect (same-house-as-parent-v2 Wh) empty)
(check-expect (same-house-as-parent-v2 Wg) (list "A"))
(check-expect (same-house-as-parent-v2 Wk) (list "A" "F" "E"))
; template: from Wizard plus lost context accumulator
; added worklist accumulator for tail recursion
; added result so far accumulator for tail recursion
; added compound data definition for wish list entries
(define (same-house-as-parent-v2 w)
;; todo is (listof ...); a worklist accumulator
;; rsf is (listof String); a result so far accumulator
(local [(define-struct wle (w ph))
;; WLE (worklist entry) is (make-wle Wizard String)
;; interp. a worklist entry with the wizard to pass to fn-for-wiz,
;; and that wizard's parent house
(define (fn-for-wiz todo w ph rsf)
(fn-for-low (append (map (lambda (k)
(make-wle k (wiz-house w)))
(wiz-kids w))
todo)
(if (string=? (wiz-house w) ph)
(cons (wiz-name w) rsf)
rsf)))
(define (fn-for-low todo rsf)
(cond [(empty? todo) rsf]
[else
(fn-for-wiz (rest todo)
(wle-w (first todo))
(wle-ph (first todo))
rsf)]))]
(fn-for-wiz empty w "" empty)))
| false |
b3d2ab06e5e3d7cfa94214e52583061ac48ccb35 | 21b370ff97102f8e39c7bbdc63c2b04622677d5e | /htdp/第三部分再论任意大数据的处理/习题17.8.3.rkt | 00537b183de1e92287f958a21f8bce6ec4982228 | [] | no_license | imxingquan/scheme | d8ba9a34b31cfbf796448686ff7b22491ea68cfe | 531da0b60a23ac1d83deeaba1fc29dc954c55a65 | refs/heads/master | 2021-07-16T12:17:19.429706 | 2021-05-18T11:01:00 | 2021-05-18T11:01:00 | 124,641,579 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,749 | rkt | 习题17.8.3.rkt | ;; The first three lines of this file were inserted by DrRacket. They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname 习题17.8.3) (read-case-sensitive #t) (teachpacks ((lib "hangman.rkt" "teachpack" "htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "hangman.rkt" "teachpack" "htdp")) #f)))
#|https://htdp.org/2003-09-26/Solutions/list-1.html
习题 17.8.3 开发 sym-list=?,该函数判断两个符号表是不是相等。
;Data Definition:
a list-of-symbols is either
1. empty or
2. (cons s los)
where s is a symbol and los is a list-of-symbols
;Templete
(define (sym-list=? a-list another-list)
(cond
[(empty? a-list)...]
[else
...(first a-list)...(first another-list)...
...(sym-list=? (rest a-list) (rest another-list)...]))
|#
;;sym-list=? : list-of-symbols list-of-symbols -> boolean
;; to determine whether a-list and another-list
;; contain the same symbols in the same order
(define (sym-list=? a-list another-list)
(cond
[(empty? a-list) (empty? another-list)]
[else
(and (cons? another-list)
(and (symbol=? (first a-list) (first another-list))
(sym-list=? (rest a-list) (rest another-list))))]))
;Examples as tests:
(check-expect
(sym-list=? empty empty)
true)
(check-expect
(sym-list=? empty (cons 'a empty))
false)
(check-expect
(sym-list=? (cons 'a empty) empty)
false)
(check-expect
(sym-list=? (cons 'a (cons 'b (cons 'c empty)))
(cons 'a (cons 'b (cons 'c empty))))
true)
(check-expect
(sym-list=? (cons 'a (cons 'b (cons 'c empty)))
(cons 'a (cons 'c (cons 'b empty))))
false) | false |
e672ea0932a5851096b2d63e23f8c8c1e572ace8 | 76df16d6c3760cb415f1294caee997cc4736e09b | /rosette-benchmarks-4/run.rkt | 48552077359188f6f7a6fe083bbb9fa426a34d73 | [
"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 | 6,431 | rkt | run.rkt | #lang racket
(require racket/runtime-path racket/cmdline
(only-in rosette clear-state! terms-count))
(define-runtime-path root ".")
(define-namespace-anchor top-ns)
; map from benchmark names to relative file paths
(define BENCHMARKS
(hash "bagpipe" "bagpipe/setups/textbook/run.rkt"
"bonsai" "bonsai/nanoscala.rkt"
"cosette" "cosette/cidr-benchmarks/oracle-12c-bug.rkt"
"ferrite" "ferrite/rename.rkt"
"fluidics" "fluidics/ex2.rkt"
"greenthumb" "greenthumb/GA/output/0/driver-0.rkt"
"memsynth" "memsynth/case-studies/synthesis/ppc/ppc0.rkt"
"neutrons" "neutrons/filterWedgeProp.rkt"
"nonograms" "nonograms/puzzle/src/run-batch-learn-rules.rkt"
"quivela" "quivela/test-inc-arg.rkt"
"rtr" "rtr/benchmarks/all.rkt"
"wallingford" "wallingford/tests/all-tests.rkt"
"frpsynth" "frpsynth/paperbenchmarks/program1.rkt"
"swizzle" "swizzle/ex2-conv1d.rkt"
"ifcl" "ifcl/test.rkt"
"synthcl" "synthcl/examples/sobelFilter/test.rkt"
"websynth" "websynth/test/all-tests.rkt"))
; groups of benchmarks
(define GROUPS
(hash "fast" (sort (set->list (set-subtract (list->set (hash-keys BENCHMARKS)) (set "greenthumb" "rtr"))) string<?)
"sympro" (sort (set->list (set-subtract (list->set (hash-keys BENCHMARKS)) (set "frpsynth" "swizzle"))) string<?)))
; Run a benchmark at a given relative path.
; Returns 3 values -- (cpu, real, gc) time
(define (run-file relative-path)
(with-output-to-file "/tmp/term-log.txt" #:exists 'replace void)
(define module-path `(file ,(path->string (build-path root relative-path))))
; run in a fresh namespace so that we can run the same file multiple times.
; however, we must copy our own namespace's instantiation of rosette into
; the fresh namespace so that profiling parameters are preserved.
(define ns (make-base-namespace))
(namespace-attach-module (namespace-anchor->namespace top-ns) 'rosette ns)
(parameterize ([current-namespace ns])
; first visit the module without instantiating,
; to get it compiled
(dynamic-require module-path (void))
; now time the module instantiation
(define-values (_ cpu real gc)
(time-apply (thunk (dynamic-require module-path #f)) '()))
(define the-term-count
(apply + (terms-count) (map string->number (file->lines "/tmp/term-log.txt"))))
(clear-state!)
(values cpu real gc the-term-count)))
; Run the benchmark with the given name,
; printing our progress and results.
; Compute mean and confidence interval if iters > 1.
(define (run-benchmark bm #:csv? csv? #:verbose? verbose? #:iters iters)
(if csv?
(let ()
(printf "~a," bm)
(flush-output))
(printf "=== ~a ===\n" bm))
(define-values (cpu real gc term-count)
(for/fold ([cpus '()][reals '()][gcs '()][term-counts '()]) ([i (in-range iters)])
(define-values (cpu real gc the-term-count)
(parameterize ([current-output-port (if verbose? (current-output-port) (open-output-nowhere))])
(run-file (hash-ref BENCHMARKS bm))))
(if csv?
(printf "~a,~a,~a,~a\n" cpu real gc the-term-count)
(printf "cpu time: ~v real time: ~v gc time: ~v term count: ~v\n" cpu real gc the-term-count))
(values (cons cpu cpus) (cons real reals) (cons gc gcs) (cons the-term-count term-counts))))
(when (not csv?)
(printf "\n"))
(when (and (not csv?) (> iters 1))
(define (mean+ci lst)
(define t-scores
'(0 12.71 4.303 3.182 2.776 2.571 2.447 2.365 2.306 2.262))
(define μ (exact->inexact (/ (apply + lst) (length lst))))
(define σ (sqrt (exact->inexact (/ (apply + (for/list ([x lst]) (expt (- x μ) 2))) (- (length lst) 1)))))
(define δ (* (list-ref t-scores (min (- (length lst) 1) (- (length t-scores) 1))) (/ σ (sqrt (length lst)))))
(define (fmt x) (~r x #:precision 1))
(format "~a [~a, ~a]" (fmt μ) (fmt (- μ δ)) (fmt (+ μ δ))))
(printf "cpu time: ~a\n" (mean+ci cpu))
(printf "real time: ~a\n" (mean+ci real))
(printf "gc time: ~a\n" (mean+ci gc))
(printf "term count: ~a\n" (mean+ci term-count))
(printf "\n")))
(module+ main
(define csv? #f)
(define verbose? #f)
(define iters 1)
(define bms
(parse-command-line
"run.rkt"
(current-command-line-arguments)
(list
(list 'once-each
(list '("-c" "--csv")
(lambda (flag) (set! csv? #t))
(list "Produce CSV output"))
(list '("-v" "--verbose")
(lambda (flag) (set! verbose? #t))
(list "Report output from benchmarks"))
(list '("-n" "--num-iters")
(lambda (flag n) (set! iters (string->number n)))
(list "Number of trials (default 1)" "n")))
(append
(list 'usage-help
"where each <bm> is one of:"
" * all (all benchmarks below)")
(for/list ([s (sort (hash-keys GROUPS) string<?)]) (format " * ~a (~a)" s (string-join (hash-ref GROUPS s) ",")))
(for/list ([s (sort (hash-keys BENCHMARKS) string<?)]) (format " * ~a" s))
(list "prefix a <bm> with ~ to remove it from the set"
"e.g. `all ~greenthumb` to run all except greenthumb")))
(lambda (accum bm . bms)
(for/fold ([bms '()]) ([s (cons bm bms)])
(define spec (string-downcase s))
(cond
[(equal? spec "all")
(sort (hash-keys BENCHMARKS) string<?)]
[(equal? (string-ref spec 0) #\~)
(define spec* (substring spec 1))
(cond [(equal? spec* "all") '()]
[(hash-has-key? GROUPS spec*)
(for/fold ([bms bms]) ([s (hash-ref GROUPS spec*)]) (remove s bms))]
[(hash-has-key? BENCHMARKS spec*)
(remove spec* bms)]
[else (error "unknown benchmarks" s)])]
[(hash-has-key? GROUPS spec)
(append bms (hash-ref GROUPS spec))]
[(hash-has-key? BENCHMARKS spec)
(append bms (list spec))]
[else
(error "unknown benchmark" s)])))
(list "bm" "bm")))
(for ([bm (remove-duplicates bms)])
(run-benchmark bm #:csv? csv?
#:verbose? verbose?
#:iters iters)))
| false |
47acbf4438809b433a6a7a7f974697f95b2f6359 | c161c2096ff80424ef06d144dacdb0fc23e25635 | /chapter4/exercise/ex4.19.rkt | cfb73fcce8a2341bb603c6bd1e1c251b9734814a | [] | no_license | tangshipoetry/SICP | f674e4be44dfe905da4a8fc938b0f0460e061dc8 | fae33da93746c3f1fc92e4d22ccbc1153cce6ac9 | refs/heads/master | 2020-03-10T06:55:29.711600 | 2018-07-16T00:17:08 | 2018-07-16T00:17:08 | 129,242,982 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 6,071 | rkt | ex4.19.rkt | #lang racket
;实际情况如Alyssa所说,报错
(define (em)
(let ((a 1))
(define (f x)
(define b (+ a x))
(define a 5)
(+ a b))
(f 10)))
;通用有效的机制这里实现不出来,scheme采用报错的方式强制要求编写更好的程序
;网上的,还没仔细看
I will describe how to implement Eva's scheme (no pun intended).
One way to do so is to topologically sort the non-function definitions in order of dependency. This can be done by converting the sequence of definitions into a directed graph according to the interdependency of the variables. Meanwhile, we can check the graph for cycles and signal an error if found, and evaluate the definitions in topologically sorted order if no cycles are found.
Needless to say, trying to implement directed acyclic graphs in Scheme, to say nothing of topological sort, is probably non-trivial and may arguably be overkill for implementing a measly little Scheme interpreter.
Hence, here is a conceptually easier way to do it. We first take out all the function definitions and put them at the top, since their bodies are delayed and hence will not pose any issues whatsoever. Then, we take the list of the non-function definitions, generate a list of the matching dependent variables in each body, and repeatedly take out all non-function definitions whose bodies are independent of any remaining non-function variables. This is probably asymptotically slower than topological sort, but it works fine, and has the added bonus of being able to naturally check for cycles.
First, we redefine make-procedure: (note I am assuming all code in chapter 4 up to this exercise has been evaluated, so all the helper functions used by the book to redefine eval is available).
(define (function-definition? exp)
(and (definition? exp)
(lambda? (definition-value exp))))
(define (non-function-definition? exp)
(and (definition? exp)
(not (function-definition? exp))))
(define (reorder-procedure-body body)
(let ((func-defs (filter function-definition? body))
(var-defs (filter non-function-definition? body))
(non-defs (remove definition? body)))
(append func-defs
(reorder-non-function-definitions var-defs)
non-defs)))
(define (make-procedure parameters body env)
(list 'procedure
parameters
(reorder-procedure-body body)
env))
Then, a few helper functions:
;; unrolls nested lists
(define (tree->list tree)
(if (list? tree)
(apply-in-underlying-scheme
append
(map tree->list tree))
(list tree)))
;; removes duplicates
(define (list->set lst)
(if (or (null? lst)
(null? (cdr lst)))
lst
(cons (car lst)
(delete (car lst)
(list->set (cdr lst))))))
(define (all-included-symbols symbol-pool seq)
(intersection-set symbol-pool
(list->set (tree->list seq))))
;; intersection-set is given in chapter 2 of SICP
;; there are likely faster ways to do this
;; computes set1 - set2 nondestructively
(define (difference-set set1 set2)
(define (in-set2? obj1)
(find (lambda (obj2) (eq? obj1 obj2))
set2))
(remove in-set2? set1))
Finally, the main workhorse function:
;; assume no duplicate variables in var-defs, otherwise undefined behavior
(define (reorder-non-function-definitions var-defs)
(define (no-dependencies? pair)
(null? (cdr pair)))
;; pair here means definition / included symbol pair
(define (pairs-with-symbols-removed pairs symbols)
(map (lambda (pair)
(cons (car pair) (difference-set (cdr pair) symbols)))
pairs))
(define (iter pairs-defs-included result)
(if (null? pairs-defs-included)
result
(let ((independent (filter no-dependencies? pairs-defs-included))
(dependent (remove no-dependencies? pairs-defs-included)))
(if (null? independent)
(error "cycle detected in inner non-function defines")
(let ((symbols-to-remove
(map (lambda (pair)
(definition-variable (car pair)))
independent)))
(iter
(pairs-with-symbols-removed dependent symbols-to-remove)
(append (map car independent) result)))))))
(let* ((symbol-pool (map definition-variable var-defs))
(pairs-defs-included
(map (lambda (def)
(cons def (all-included-symbols symbol-pool
(definition-value def))))
var-defs)))
(reverse (iter pairs-defs-included '()))))
;; need to reverse because results built using cons, in reverse order
Now, assuming that eval is *not* the builtin eval but rather the simplified one that has been defined as in the code from the SICP text, here are some examples:
(assert (equal? '((define (f x) 7) (define a 3) (define b a))
(reorder-procedure-body
'((define a 3) (define b a) (define (f x) 7)))))
;; example from the exercise
(assert (= 20 (eval '(let ((a 1))
(define (f x)
(define b (+ a x))
(define a 5)
(+ a b))
(f 10)) the-global-environment)))
;; 20, as Eva required.
I ran all code above in MIT Scheme.
note we are assuming the bodies of the non-function definitions do not contain redefinitions of variables shared with other non-function definitions. For example, the following should be perfectly legal but may break our program and result in undefined behavior:
(define (f)
(define a 5)
(define b
(let ((a 6))
a))
b)
This is an admitted limitation of our program: to account for this case requires significant further work.
| false |
32f7b83d0e1b603b20a672436a164e80e9b180ec | bd528140fc0a7ada47a4cb848f34eae529620c1e | /1-27.rkt | d3b885d7237dd8adc2b5b5acc6aae85b9639f513 | [] | no_license | michaldarda/sicp | c09c197b35014d66f516f4a0a8d49f33e3c09a37 | 8ea78f8f0780f786057dfdaae24e44f16abf063b | refs/heads/master | 2020-07-15T01:23:51.573237 | 2020-05-24T19:54:59 | 2020-05-24T19:54:59 | 205,447,221 | 4 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 494 | rkt | 1-27.rkt | #lang racket
(define (square x) (* x x))
(define (expmod base exp m)
(cond [(= exp 0) 1]
[(even? exp) (remainder (square (expmod base (/ exp 2) m)) m)]
[else (remainder (* base (expmod base (- exp 1) m)) m)]))
(define (fermat-test n)
(define (try-it a)
(if (= a 0)
true
(and (= (expmod a n n) a) (try-it (- a 1)))))
(try-it (- n 1)))
(fermat-test 561)
(fermat-test 1105)
(fermat-test 1729)
(fermat-test 2465)
(fermat-test 2821)
(fermat-test 6601)
| false |
8f57fa6d9503ac2f2ba33e563ac01e0d47b30eb6 | fc90b5a3938850c61bdd83719a1d90270752c0bb | /web-server-lib/web-server/dispatch.rkt | 24cda1cc5d6d486aa18e06e7388d07dc1419d0a5 | [
"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 | 381 | rkt | dispatch.rkt | #lang racket/base
(require web-server/dispatch/syntax
web-server/dispatch/serve
web-server/dispatch/url-patterns
web-server/dispatch/container)
(provide (all-from-out web-server/dispatch/syntax
web-server/dispatch/serve
web-server/dispatch/url-patterns
web-server/dispatch/container))
| false |
acd17d5e79884d9a0ffee2e969cbf78a397c4ece | d2fc383d46303bc47223f4e4d59ed925e9b446ce | /courses/2016/fall/301/notes/3.rkt | 16b58425f460c541a8d43dc2265bffb7c6cdf344 | [] | no_license | jeapostrophe/jeapostrophe.github.com | ce0507abc0bf3de1c513955f234e8f39b60e4d05 | 48ae350248f33f6ce27be3ce24473e2bd225f6b5 | refs/heads/master | 2022-09-29T07:38:27.529951 | 2022-09-22T10:12:04 | 2022-09-22T10:12:04 | 3,734,650 | 14 | 5 | null | 2022-03-25T14:33:29 | 2012-03-16T01:13:09 | HTML | UTF-8 | Racket | false | false | 6,209 | rkt | 3.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 |3|) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
;; A binary tree is either
;; - a (make-leaf)
;; - a (make-branch bt number? bt)
(define (binary-tree? x)
(or (leaf? x) (branch? x)))
(define-struct leaf ())
(define-struct branch (left data right))
(define ex1
(make-branch (make-branch (make-leaf) 4 (make-leaf))
5
(make-branch (make-leaf) 8 (make-leaf))))
;; generic-tree-func : bt -> Ans
(define (generic-tree-func bt)
(cond
[(leaf? bt)
....]
[(branch? bt)
;; AVAILABLE: bt : branch
;; (branch-left bt) : bt
;; (branch-right bt) : bt
;; (branch-data bt) : num
;; (gtf (branch-left bt)) : ans
;; (gtf (branch-right bt)) : ans
;;
....]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (generic-list-fun l1)
;; AVAILABLE: l1 : (list-of A)
;; (empty? l1) : bool
;; (cons? l1) : bool
(cond
[(empty? l1)
;; AVAILABLE:
....]
[else
;; AVAILABLE: l1 : (cons-of A)
;; (first l1) : A
;; (rest l1) : (list-of A)
;; (generic-list-fun (rest l1)) : Answer
....]))
;;;;;;
;; squares : list-of-num -> list-of-num
;; Compute squares of those given
(define (squares l1)
;; AVAILABLE: l1 : (list-of A)
;; (empty? l1) : bool
;; (cons? l1) : bool
;; FAIL l1 = 1::[]
(cond
[(empty? l1)
;; AVAILABLE:
empty]
[else
;; AVAILABLE: l1 : (cons-of A)
;; (first l1) : A
;; (rest l1) : (list-of A)
;; (generic-list-fun (rest l1)) : Answer
(cons (square (first l1))
(squares (rest l1)))
;; FAIL l1 = 1:[]
;; f = 1
;; r = []
;; sqs r = []
;; sq f = 1
;; ret = 1 : []
;; ACTUAL = 2 : []
]))
;; square : num -> num
;; squares it
(define (square x) (* x x))
(check-expect (square 1) 1)
(check-expect (square 2) 4)
;;(check-expect (square 3) 9)
(check-expect (squares empty) empty)
(check-expect (squares (cons 1 empty)) (cons 1 empty))
(check-expect (squares (cons 2 empty)) (cons 4 empty))
(check-expect (squares (list 1 2 3 4)) (list 1 4 9 16))
;; doubles : list-of-num -> list-of-num
;; Compute doubles of those given
(define (doubles l1)
;; AVAILABLE: l1 : (list-of A)
;; (empty? l1) : bool
;; (cons? l1) : bool
;; FAIL l1 = 1::[]
(cond
[(empty? l1)
;; AVAILABLE:
empty]
[else
;; AVAILABLE: l1 : (cons-of A)
;; (first l1) : A
;; (rest l1) : (list-of A)
;; (generic-list-fun (rest l1)) : Answer
(cons (double (first l1))
(doubles (rest l1)))
;; FAIL l1 = 1:[]
;; f = 1
;; r = []
;; sqs r = []
;; sq f = 1
;; ret = 1 : []
;; ACTUAL = 2 : []
]))
;; double : num -> num
;; doubles it
(define (double x) (+ x x))
(check-expect (double 1) 2)
(check-expect (double 2) 4)
(check-expect (double 3) 6)
(check-expect (doubles empty) empty)
(check-expect (doubles (cons 1 empty)) (cons 2 empty))
(check-expect (doubles (cons 2 empty)) (cons 4 empty))
(check-expect (doubles (list 1 2 3 4)) (list 2 4 6 8))
;;;
(define test-list-1 (list 1 2 3 4))
(check-expect (squares test-list-1) (list 1 4 9 16))
(check-expect (doubles test-list-1) (list 2 4 6 8))
;;;;; LEVEL UP to ISL
;; make-function-like-squares-and-doubles
;; (num -> num)
;; ->
;; ((listof num) -> lon)
(define (make-function-like-squares-and-doubles
something-like-square-or-double)
(local
[;; function-like-squares-and-doubles : (listof num) -> lon
(define (function-like-squares-and-doubles lon)
(cond
[(empty? lon)
empty]
[(cons? lon)
(cons (something-like-square-or-double (first lon))
(function-like-squares-and-doubles (rest lon)))]))]
function-like-squares-and-doubles))
;; heavenly-doubles : lon -> lon
(define heavenly-doubles
(make-function-like-squares-and-doubles double))
(check-expect (heavenly-doubles test-list-1) (list 2 4 6 8))
(define heavenly-squares
(make-function-like-squares-and-doubles square))
(check-expect (heavenly-squares test-list-1) (list 1 4 9 16))
;; make-function-like-squares-and-doubles is called "higher order"
(require 2htdp/image)
;; circulate : num -> image
(define (circulate r)
(circle r "solid" "red"))
(define circulates
(make-function-like-squares-and-doubles circulate))
(circulates test-list-1)
;; A MAP
;; map : (A -> B) (listof A) -> (listof B)
(map circulate test-list-1)
;;;;; LEVEL UP to ISL + λ
;; Command-\ = λ
;; Control-\ = λ
(map (λ (r) (circle r "solid" "red"))
test-list-1)
;; A FOLD
(define (how-many l)
(cond
[(empty? l) 0]
[(cons? l) (+ 1 (how-many (rest l)))]))
(define (all-of-the-stuff l)
(cond
[(empty? l) ""]
[(cons? l) (string-append (number->string (first l))
" "
(all-of-the-stuff (rest l)))]))
(how-many test-list-1)
(all-of-the-stuff test-list-1)
;; ??? : B (A B -> B) (listof A) -> B
(define (??? ???-empty ???-cons l)
(cond
[(empty? l) ???-empty]
[(cons? l)
(???-cons
(first l)
(??? ???-empty ???-cons (rest l)))]))
(check-expect
(??? 0 (λ (f ???-of-rest) (+ 1 ???-of-rest)) test-list-1)
(how-many test-list-1))
(check-expect
(??? "" (λ (f ???-of-rest) (string-append (number->string f) " " ???-of-rest)) test-list-1)
(all-of-the-stuff test-list-1))
(cons 1 (cons 2 empty))
;; (???-cons 1 (???-cons 2 ???-empty))
;; ??? = FOLD or REDUCE
;; MAP-REDUCE (where ???-cons is associative)
;; (C 1 (C 2 (C 3 (C 4 E))))
;; =
;; (C (C (C 1 2)
;; (C 3 4))
;; E)
| false |
ef8f011f73b5985694f5783c64c4da198b5dd04b | cca8bf34af009b057562975a03995e5b1d4625a0 | /private/repro-test-3.rkt | 08786abf62c54e5c945dec38ae88be23287e696f | [
"MIT",
"Apache-2.0"
] | permissive | willghatch/racket-syntax-implicits | f7c1e1cd011bc0337c2e09ca4496c33ac9e3cfa0 | 59e10754cc0e96b899e4194e83b4966801262a63 | refs/heads/master | 2023-03-05T04:02:27.242319 | 2023-02-24T17:47:33 | 2023-02-24T17:47:33 | 159,539,843 | 2 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 176 | rkt | repro-test-3.rkt | #lang racket/base
(require
"../main.rkt"
(for-syntax racket/base
syntax/parse))
(define-syntax-implicit i3 (syntax-parser [_ #'(printf "i3\n")]))
(provide i3)
| true |
3bfbfca87d7a36333118f4354ae12bca194c34c9 | 9910cb51ccc1b9ca880c6876de6ff1d2094a3c87 | /db.rkt | b28d0d71c3db4d6f074ccc5a0ad08cb487d6cebb | [
"Apache-2.0"
] | permissive | nickcollins/zinal | 0b3a2321bd78541a2a55c5784b8ad8db73a126e4 | 7c77e792a8873fbf34bafa12d9926695b140b1ef | refs/heads/master | 2021-01-20T04:29:48.072021 | 2017-06-19T21:23:49 | 2017-06-19T21:23:49 | 89,699,525 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 42,174 | rkt | db.rkt | ; Copyright 2017 Nick Collins
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
; Similar to "#lang racket"
(module db racket
(provide (all-defined-out))
(define ILLEGAL-STANDARD-RACKETS '(
"new"
"super-new"
"make-object"
"super-make-object"
"super"
"send"
"this"
"class"
"class*"
"interface"
"init"
"abstract"
"define/public"
"define/override"
"augment"
"define"
"lambda"
"assert"
"module"
"require"
"provide"
"define-syntax-rule"
))
; This is an abstract interface to the storage db. This interface should be abstract and clean
; enough to permit hot swapping out the db/storage format. It also gives us an idea of what a
; minimalistic (albeit with basic OOP support) scheme-like tree protocol for logic description
; might look like, regardless storage format or implementation details. Racket identifiers,
; definitions, functions, macros, and names will be referred to collectively as "rackets"
;
; VISIBILITY RULES:
;
; All referables are visible to any reference except:
; 1) If the referable is in the same module but is out of scope. A referable that's obviously in
; scope, is, well, in scope. I.e., the params of any parent/ancestor lambda are visible, any
; parent/ancestor is visible, and all "older siblings" of the reference itself or any
; parent/ancestor are visible.
;
; Somewhat less intuitively, some "younger siblings" of the reference's parent/ancestors
; are visible. A node is "elder visible" if it's a function definition (i.e., a define whose
; expr is a lambda), a zinal:db:define-method%% , zinal:db:override-racket-method%% , or
; zinal:db:define-class%% . Let's say R is a descendant of A. If A is elder visible, then an
; unbroken sequence of elder visible nodes immediately following A are also visible to R.
; That is, if A is the Nth sibling, then if siblings N+1, N+2, ... N+M are all elder visible,
; then they are all visible to R. But if sibling N+M is not elder visible, then siblings N+M+X
; are not visible to R or A, even if they are elder visible.
;
; Somewhat less unintuitively, here's an example:
; (define vis 0)
; (1 2 R1)
; (do-something
; (lambda (p1)
; (define thing R2)
; (define f1 (lambda () R3))
; (define f2 (lambda () R4))
; (define stuff 0)
; (define f3 (lambda () R5))
; )
; )
; (def invis (lambda () 0))
;
; vis is, of course, visible to all the references, and invis is invisible to all of them.
; p1 and thing are visible only to R2-5 (yes, thing is visible to R2, sorry). f1 and f2
; are visible only to R3-4. It's obvious that f1 is visible to both, but it's only due to
; the "younger sibling" rule that f2 is visible to R3. As you can see, this rule allows
; mutually recursing functions without allowing any other weird stuff. f3 is only visible
; to R5. If the lines defining stuff and f3 were swapped, then f3 would be visible to
; R3-4. Unlike in scheme, the stuff definition breaks the sequence of visible defs because
; its evaluation could hypothetically invoke the function that depends on it, creating
; a dependency cycle that does not necessarily involve intentional recursion.
; If "do-something" was instead replaced by "define blah", then invis would be visible to
; R2-5. Note that the function definitions in the example could be method definitions,
; method overrides, or class definitions, without changing the visibility of anything.
; 2) If the referable is in a different module and is not public.
; 3) If the referable is in a different module, and that module is not "require"d by this
; module
;
; When a reference is first created, the referable it points to must be visible to it, or an
; exception is thrown. After that, it is possible that during the course of editing, a referable
; becomes invisible to some of its references. This is legal, but there is an invariant that is
; maintained:
; 1) if a reference points to a referable in a different module, then that referable is a
; zinal:db:def%% or zinal:db:define-class%% and the direct child of its module.
; 2) if a reference points to a referable in the same module, then the reference and its referable
; are not "cousins". Two nodes are cousins if neither descends from the other, and neither is
; the direct child of their youngest common ancestor.
; Given that each reference has visibility at creation, all operations that currently exist (should)
; preserve this invariant. This invariant makes it easy to delete nodes. A node can't be deleted
; if any references to it are not descendants of it - the invariant proves that if that is the
; case, then all references to the node's descendants are also descendants of the node, so the
; whole subtree can be deleted without any further checks. The invariant also means that to delete
; a module, we must check that there are no references in other modules to its direct child defs,
; but we don't have to check whether there are references to params or descendant defs. It is legal
; to mess up a def's publicity, or a module's requires, such that references lose vision, because
; none of these changes can violate the invariant.
(define zinal:db%% (interface ()
; Returns zinal:db:module%% handles for all modules
get-all-modules ; ()
; Returns a zinal:db:module%% for the main module, for #f if there's no main module
get-main-module ; ()
; short-desc may be #f to indicate no short descriptor. Returns a zinal:db:module%% handle
; for the newly minted module
create-module!! ; ([short-desc] [long-desc])
; Returns a list of all zinal:db:racket%% in this db, in no particular order
get-all-rackets ; ()
; Returns a list of all zinal:db:referable%% in this db, in no particular order
get-all-referables ; ()
; Returns a list of all zinal:db:interface%% in this db, in no particular order. Currently,
; interfaces are completely public and visible to all modules, being associated with no particular module.
get-all-interfaces ; ()
; Returns a zinal:db:interface%% handle for the newly minted interface
create-interface!! ; ([short-desc] [long-desc])
))
; Everything in the db is an element - includes both elements of the tree and non-tree elements
(define zinal:db:element%% (interface ()
; returns the zinal:db%%
get-db ; ()
accept ; (zinal:db:element-visitor% [data])
; Returns #t if and only if this handle and the other handle both refer to the same element
equals? ; (zinal:db:element%%)
))
; a describable can have a short and long descriptor that explain and document it
(define zinal:db:describable%% (interface (zinal:db:element%%)
; A short string description of the element, that should be much less than a line long.
; Comparable to an identifier, but only used by humans; business logic should never use this value.
; Returns #f if none is specified
get-short-desc ; ()
; An indefinitely long string explanation of the element. Comparable to documentation.
; Returns #f if none is specified
get-long-desc ; ()
; Send #f to specify that there is no short descriptor
set-short-desc!! ; (string OR #f)
; Send #f to specify that there is no long descriptor
set-long-desc!! ; (string OR #f)
))
; All elements of the db that are part of a tree. Each tree is rooted by a module, each non-leaf node
; (i.e. zinal:db:parent-node%% ) has a list of children - properties of a node which are sets (e.g.
; the set of all modules required by a particular module) are generally not part of the tree.
(define zinal:db:node%% (interface (zinal:db:element%%)
; Returns a zinal:db:node%% handle to the parent of this node. Returns #f for a module
get-parent ; ()
; returns the containing zinal:db:module%%
get-module ; ()
; Returns a list of all zinal:db:referable%% that are visible underneath this node.
; Included in the list is this node (if it's a referable) and its params (if it's a lambda).
; See the comment about visibility rules above to see what is and isn't visible.
get-visible-referables-underneath ; ()
; Returns a list of all zinal:db:referable%% that are visible after this node.
; Included in the list is this node (if it's a referable) but not its params (if it's a lambda).
; See the comment about visibility rules above to see what is and isn't visible.
get-visible-referables-after ; ()
; Returns #t iff unassign!! can be called without throwing an exception. Returns #f if this
; node is a module, or if deleting this node as well as all associated data and children would
; "orphan" any extant references. Returns #t for unassigned nodes, as for them unassign!! is a
; no-op.
can-unassign? ; ()
; Deletes all the data associated with this node and any children it may have, converting
; this node to a zinal:db:unassigned%% . This handle will be invalidated and cannot be used
; again. Returns a handle to the new zinal:db:unassigned%% .
; If this is called on a zinal:db:unassigned%% , nothing happens, and this is returned.
; If this is called when can-unassign? would return #f, then an exception is thrown.
unassign!! ; ()
))
(define zinal:db:parent-node%% (interface (zinal:db:node%%)
; Returns a list of zinal:db:node%% handles to all children of this non-leaf node. The children
; are returned in programmatic order, so if child B depends on child A, A must appear before B in
; the returned list
get-children ; ()
))
; Any element which refers to some zinal:db:referable%%
(define zinal:db:reference%% (interface (zinal:db:node%%)
; Goto-declaration, effectively.
; Returns the unique zinal:db:referable%% that this refers to
get-referable ; ()
; It is legal in the database for a reference's referable to not be visible to it. The code,
; of course, cannot be compiled, but it is useful to allow broken references so that small,
; incremental changes to the code (such as reordering things, or changing an access modifier)
; do not become illegal. This method returns #t if the reference is valid, and #f if it is not
; valid due to lack of visibility.
; See the comment about visibility rules above to see what is and isn't visible.
is-referable-visible? ; ()
))
; Any element which can be pointed to by some type of zinal:db:reference%% ; generally definitions
(define zinal:db:referable%% (interface (zinal:db:element%% zinal:db:describable%%)
; Find-usages, effectively.
; Returns a list of all zinal:db:reference%% that refer to this referable
get-references ; ()
))
; A node which has a list of parameters.
(define zinal:db:has-params%% (interface (zinal:db:parent-node%%)
; Returns all params, with the required first
get-all-params ; ()
get-required-params ; ()
; Returns #f if the specified param cannot be deleted. A required param can't be deleted
; if there are any references to it
can-remove-required-param? ; (index)
; Deletes the specified param, or throws an exception if can-remove-required-param? would
; return #f
remove-required-param!! ; (index)
; short-desc is #f by default. If #f, the param will not have a short descriptor
insert-required-param!! ; (index [short-desc])
; Converts the last required param to an optional param, with an unassigned default. If
; there are no required params, throws an exception. Does not affect or invalidate any
; handles for the converted param. No meaningful return value.
make-last-required-param-optional!! ; ()
get-optional-params ; ()
; Returns #f if the specified param cannot be deleted. An optional param can't be deleted
; if there are any references to it that occur outside its own subtree
can-remove-optional-param? ; (index)
; Deletes the specified param, or throws an exception if can-remove-optional-param? would
; return #f
remove-optional-param!! ; (index)
; short-desc is #f by default. If #f, the param will not have a short descriptor.
; The newly created param's default value is unassigned
insert-optional-param!! ; (index [short-desc])
; Converts the last optional param to a required param, completely deleting the default value.
; If there are no optional params, throws an exception. Does not affect or invalidate any
; handles for the converted param. No meaningful return value.
make-last-optional-param-required!! ; ()
))
; A node which has a list of nodes that constitute its body.
(define zinal:db:has-body%% (interface (zinal:db:parent-node%%)
; Returns a list of zinal:db:node%% handles representing the statements/expressions
; constituting this node's body.
get-body ; ()
; Inserts a new unassigned node into the body at the specified index.
; E.g. if the node is (lambda (x y) (define a (+ x y)) (define b (* x y)) (- a b)),
; then (insert-into-body!! 1) creates an unassigned node after the definition of a .
; Returns a zinal:db:unassigned%% handle to the new unassigned node
insert-into-body!! ; (non-negative-integer)
; Deletes the nth expr (which must be a zinal:db:unassigned%%) of the body,
; and shifts all latter exprs in the body down by one index.
; E.g. if the node is (lambda (x y) (define a (+ x y)) (define b (* x y)) <?>),
; then (remove-from-body!! 2) deletes the <?>.
; Any handles associated with the deleted expr are now invalid and cannot be used.
; No meaningful return value. If the node at the specified index isn't a
; zinal:db:unassigned%% , an exception is thrown.
remove-from-body!! ; (non-negative-integer)
))
; A node which has a list of nodes which represent arguments to some function or class.
(define zinal:db:has-args%% (interface (zinal:db:parent-node%%)
; Returns a list of zinal:db:node%% handles representing the argument expressions.
get-args ; ()
; Inserts a new unassigned node into the argument list at the specified index.
; Returns a zinal:db:unassigned%% handle to the new unassigned node
insert-arg!! ; (non-negative-integer)
; Deletes a zinal:db:unassigned%% at the argument specified position, and shifts all latter
; items in the list down by one index. Any handles associated with that node are
; now invalid and cannot be used. No meaningful return value. If the node at the
; specified index is not zinal:db:unassigned%% , an exception will be thrown
remove-arg!! ; (non-negative-integer)
))
(define zinal:db:has-method%% (interface (zinal:db:parent-node%%)
get-method ; ()
))
; OOP
; Common interface for any zinal element that extends/implements interfaces, i.e.
; zinal:db:interface%% , zinal:db:define-class%% , zinal:db:class-instance%% . By "direct", we mean an
; immediate super interface, as opposed to grandparent interfaces.
(define zinal:db:subtype%% (interface (zinal:db:element%%)
; Returns a list of zinal:db:interface%% , in no particular order, for the interfaces that this
; subtype explicitly extends.
get-direct-super-interfaces ; ()
; Returns #t if directly extending the argument would not cause a cycle in the type DAG.
; Otherwise #f
can-add-direct-super-interface? ; (zinal:db:interface%%)
; Makes this type directly extend the argument. Idempotent.
; Throws an exception if can-add-direct-super-interface? would return #f
; No meaningful return value
add-direct-super-interface!! ; (zinal:db:interface%%)
; Returns #f if removing this super type would "orphan" a zinal:db:define-method%% . "orphaning"
; occurs when this or a subclass defines a method that it would not inherit if the argument were
; removed from this type's supers.
; i.e., if a method is declared by the argument or one of its supertypes, and this or a subclass
; which defines the method has no type DAG path (except those including the edge
; that is about to be severed) that reaches the declaring type, this method returns #f.
; Throws if the argument is not a direct super interface of this
can-remove-direct-super-interface? ; (zinal:db:interface%%)
; This type will no longer directly extend the argument. Idempotent.
; Throws an exception if can-remove-direct-super-interface? would return #f or throw
; No meaningful return value
remove-direct-super-interface!! ; (zinal:db:interface%%)
; Returns a list of all zinal:db:method%% that are defined directly by this or by any super
; type, in no particular order
get-all-methods ; ()
))
; A defined type, which can be referenced and have subtypes. Has methods for getting, adding,
; and removing method declarations. The supertype of zinal:db:interface%% and zinal:db:define-class%% .
; By "direct", we mean a method directly defined by the type, as opposed to methods of grandparent
; types
(define zinal:db:type%% (interface (zinal:db:subtype%% zinal:db:referable%%)
; Returns a list of zinal:db:method%% representing the methods directly defined by this type, in
; no particular order.
get-direct-methods ; ()
; The only way to create a new method. Returns a handle to the newly created method.
add-direct-method!! ; ([short-desc] [long-desc])
; Returns #f if there is any reference to this method whatsoever, either a
; zinal:db:define-method%% , zinal:db:invoke-super-method%% or zinal:db:invoke-method%% .
; Throws an exception if the argument isn't a direct method.
can-remove-direct-method? ; (zinal:db:method%%)
; Deletes the argument. All handles to the deleted method become invalid.
; Throws an exception if can-remove-direct-method? would throw or return #f
; No meaningful return value
remove-direct-method!! ; (zinal:db:method%%)
))
; Comparable to racket interfaces. Each defines a type, the direct super types, and the methods
; of that type. Interfaces are universally public, and attached to the db as a whole, rather than
; being attached to any particular module.
(define zinal:db:interface%% (interface (zinal:db:type%%)
; Returns a list of zinal:db:interface%% , in no particular order, for the interfaces that explicitly
; extends this.
get-direct-sub-interfaces ; ()
; Returns #t if this interface has no subtypes, if there are no references to it, and all
; of its methods can be deleted.
; Otherwise #f
can-delete? ; ()
; Deletes this interface. All handles for this interface become invalid.
; Throws an exception if can-delete? would return #f
; No meaningful return value
delete!! ; ()
))
(define zinal:db:interface-ref%% (interface (zinal:db:reference%%)
; Returns a zinal:db:interface%% handle for the interface that this reference refers to
get-interface ; ()
))
; Super type of zinal:db:define-class%% and zinal:db:class-instance%% . The former defines a class as a
; type, complete with its own methods and the ability to be referenced. The latter instantly creates
; an instance of an anonymous class with the specified properties; it cannot define
; its own methods and cannot be referenced in any way. It may seem silly to have two different
; types of nodes for non-anonymous and anonymous classes, but there are enough practical reasons to
; do so. This interface defines the basic functionality common to both types of classes, including the
; fact that each has a body of expressions, statements, and method definitions. The body must contain
; exactly one zinal:db:super-init%% in order to transpile.
(define zinal:db:class%% (interface (zinal:db:subtype%% zinal:db:has-body%%)
; Gets the zinal:db:define-method%% corresponding to the argument if one exists, otherwise #f
; Can be called on any method of this or a super-type. Will throw exception if invoked on any
; other method
get-direct-definition-of-method ; (zinal:db:method%%)
; Returns #t if the argument is not defined by this or by any super class. Otherwise #f
; Can be called on any method of this or a super-type. Will throw exception if invoked on any
; other method
is-method-abstract? ; (zinal:db:method%%)
; Returns #t if the argument is directly defined and is also defined by some super class.
; Otherwise #f
; Note that this does not correspond to the racket define/override , which is used for a method
; declared by any superclass, even if it's not defined by any superclass.
; Can be called on any method of this or a super-type. Will throw exception if invoked on any
; other method
is-method-overridden? ; (zinal:db:method%%)
; Returns a zinal:db:racket%% or zinal:db:class-ref%% corresponding to the super class of
; this class. At initiation the super class is a zinal:db:racket%% corresponding to the
; racket object% .
get-super-class ; ()
; Returns #f if changing the super class would "orphan" a zinal:db:define-method%% or
; zinal:db:invoke-super-method%% . "orphaning" occurs when this or a subclass defines or super
; invokes a method that it would not inherit if the super class were changed to, say, object% .
; i.e., if a method is declared by the super class or one of its supertypes, and this or a subclass
; which defines or super invokes the method has no type DAG path (except those including the edge
; that is about to be severed) that reaches the declaring type, this method returns #f.
; Otherwise #t
can-set-super-class? ; ()
; Changes the super class to be the argument. Any handles previously returned by get-super-class
; become invalid.
; Throws an exception if can-set-super-class? would return #f
; Returns a handle to the new zinal:db:class-ref%%
set-super-class!! ; (zinal:db:define-class%%)
; Changes the super class to be a zinal:db:racket%% with the name and library specified by
; the arguments. Any handles previously returned by get-super-class become invalid.
; Throws an exception if can-set-super-class? would return #f
; Returns a handle to the new zinal:db:racket%%
set-racket-super-class!! ; (library name)
))
; Comparable to a racket class definition. Defines a class. The init params are represented by the
; zinal:db:has-params%% parameters. The methods are not nodes and thus not children and not part of
; the tree. If the class is instantiated (i.e. it's not abstract) then all direct methods and all
; methods of direct or indirect super types must be defined by this class or by super classes.
(define zinal:db:define-class%%
(interface (zinal:db:class%% zinal:db:has-params%% zinal:db:type%%))
)
(define zinal:db:class-ref%% (interface (zinal:db:reference%%)
; Returns a zinal:db:define-class%% handle for the param that this reference refers to
get-define-class ; ()
))
; Comparable to immediately creating an object of an anonymous class in racket, e.g.
; (make-object (class <super> ...)) . The anonymous class that the resulting object is implicitly a
; member of has no init params, cannot define its own methods, cannot be referenced, and won't
; transpile if any methods are abstract.
(define zinal:db:class-instance%% (interface (zinal:db:class%%)))
; A node which evaluates to the object it is the child of. Corresponds to the racket "this"
(define zinal:db:this%% (interface (zinal:db:node%%)))
; represents a method declaration. Each zinal:db:method%% represents a distinct, canonical method,
; which can be defined in a zinal:db:class%% via zinal:db:define-method%% or invoked anywhere via
; zinal:db:invoke-method%% . Overrides of methods are not themselves new methods - rather they are
; simply zinal:db:define-method%% for a method already defined by a super-class.
(define zinal:db:method%% (interface (zinal:db:describable%%)
; Returns a zinal:db:type%% for the type that directly defines this method
get-containing-type ; ()
))
; A node which defines a method. This node is only permitted in the body of a zinal:db:class%% .
; There must be no more than one such node per method per class. If the method is defined by any
; super class, then this is an override, otherwise it's not. A class can only define a method
; which it or a supertype declares
(define zinal:db:define-method%% (interface (zinal:db:has-method%%)
; Returns a zinal:db:lambda%% that defines the method. The returned lambda cannot be unassign!! .
; Thus the returned lambda is permanent in a sense - it can be manipulated but neither created nor
; destroyed
get-lambda ; ()
; Returns #t if any super class contains a zinal:db:define-method%% for this method. Otherwise #f
; Note that this does not correspond to the racket define/override , which is used for a method
; declared by any superclass, even if it's not defined by any superclass.
is-override? ; ()
))
; A node which overrides a method of a racket super class. Should be used sparingly
(define zinal:db:override-racket-method%% (interface (zinal:db:parent-node%%)
; Returns a string for the name of the racket method that is to be overridden
get-racket-method-name ; ()
; Sets a string corresponding to the name of the racket method to invoke.
; No meaningful return value.
set-racket-method-name!! ; (string)
; Returns the lambda that defines the overridden method. Comparable to zinal:db:define-method%% ,
; the returned lambda is permanent and cannot be unassign!! , created nor destroyed
get-lambda ; ()
; Returns #t if this is meant to augment a racket super method rather than override, per se
is-augment? ; ()
; If should-be-augment? is #f , makes this no longer be an augmentation of the racket super
; method. Otherwise, makes this become an augmentation. No meaningful return value.
set-is-augment!! ; (should-be-augment?)
))
; A node which, when evaluated, intializes the immediate/direct super class. In order to transpile,
; there must be exactly one of these per zinal:db:class%% body.
(define zinal:db:super-init%% (interface (zinal:db:has-args%%)))
; A node which, when evaluated, will invoke the specified method.
(define zinal:db:invoke-method%% (interface (zinal:db:has-args%% zinal:db:has-method%%)
; Returns a node for the object to invoke the method on. At first, the node will be a
; zinal:db:unassigned%% , which of course cannot transpile. assign!! it to a node which will
; evaluate to an object of the method's class. zinal is not smart enough to understand types
; so type failure will occur at runtime.
get-object ; ()
; Sets the method that this invokation invokes. The type that contains the method must be
; visible at this location. No meaningful return value
set-method!! ; (zinal:db:method%%)
))
; A node which, when evaluated, invokes a method of some racket class.
(define zinal:db:invoke-racket-method%% (interface (zinal:db:has-args%%)
; Returns a node for the object to invoke the racket method on. At first, the node will be a
; zinal:db:unassigned%% , which of course cannot transpile. assign! it to a node which will
; evaluate to an object that extends (directly or indirectly) a racket class that possesses a
; public method whose name corresponds to the result of get-racket-method-name .
get-object ; ()
; Returns a string corresponding to the name of the racket method to invoke.
get-racket-method-name ; ()
; Sets a string corresponding to the name of the racket method to invoke.
; No meaningful return value.
set-racket-method-name!! ; (string)
))
; A node which, when evaluated, invokes a super-class's definition of the method.
; Trying to create this node for a method which is abstract in the super class will throw an exception.
; Corresponds to racket of the form '(super <method-name> <args...>) .
(define zinal:db:invoke-super-method%% (interface (zinal:db:has-args%% zinal:db:has-method%%)
; Sets the method that this invokation invokes. If the method is abstract in the super class, or the
; type containing the method is not visible to this node, an exception is thrown.
; No meaningful return value
set-method!! ; (zinal:db:method%%)
))
; A node which, when evaluated, invokes a racket super-class's definition of the method, if one
; exists. Corresponds to racket of the form '(super <method-name> <args...>) .
(define zinal:db:invoke-racket-super-method%% (interface (zinal:db:has-args%%)
; Returns a string corresponding to the name of the racket method to invoke.
get-racket-method-name ; ()
; Sets a string corresponding to the name of the racket method to invoke.
; No meaningful return value.
set-racket-method-name!! ; (string)
))
; A node which, when evaluated, creates a new object of the corresponding defined class.
(define zinal:db:create-object%% (interface (zinal:db:has-args%%)
; Returns a node for the class to create a new instance of. At first, the node will be a
; zinal:db:unassigned%% , which of course cannot transpile. assign!! it to a node which will
; evaluate to the proper class, either a zinal:db:racket%% for racket classes, a
; zinal:db:class-ref%% for zinal classes, or any expression which evaluates to one of those. It's
; not valid for it to evaluate to zinal:db:define-class%% or zinal:db:class-instance%%
get-class-node ; ()
))
; NON-OOP
; when evaluated, it will evaluate get-assertion , and if true, nothing else happens. If false,
; an exception is thrown, whose message is composed by evaluating get-format-string and
; get-format-args and applying standard racket formatting rules to them. Unlike some languages,
; get-assertion is always evaluated, so it's safe to have it do stateful operations.
(define zinal:db:assert%% (interface (zinal:db:parent-node%%)
; Returns a zinal:db:node%% for the expression that is to be asserted as true.
get-assertion ; ()
; Returns a zinal:db:node%% that evaluates to the format string that is used for an exception
; if thrown. Follows standard racket ~a formatting rules. Only evaluated if get-assertion
; evaluates false
get-format-string ; ()
; Returns a list of zinal:db:node%% for the arguments to get-format-string . Only evaluated if
; get-assertion evaluates false
get-format-args ; ()
; Inserts a new unassigned node into the list of format args at the specified index.
; Returns a zinal:db:unassigned%% handle to the new unassigned node
insert-format-arg!! ; (index)
; Deletes the nth format arg . Any handles associated with the deleted arg are now invalid and
; cannot be used. No meaningful return value. If the node at the specified index isn't a
; zinal:db:unassigned%% , an exception is thrown.
remove-format-arg!! ; (index)
))
; Any node which has no children and is self-descriptive; literals, essentially.
; (A list literal is really a list of literals)
(define zinal:db:atom%% (interface (zinal:db:node%%)
; Returns the literal value represented by this node,
; as a scheme value of the proper type
get-val ; ()
))
(define zinal:db:lambda%% (interface (zinal:db:has-params%% zinal:db:has-body%%)))
(define zinal:db:number%% (interface (zinal:db:atom%%)))
(define zinal:db:char%% (interface (zinal:db:atom%%)))
(define zinal:db:string%% (interface (zinal:db:atom%%)))
(define zinal:db:bool%% (interface (zinal:db:atom%%)))
(define zinal:db:symbol%% (interface (zinal:db:atom%%)))
(define zinal:db:keyword%% (interface (zinal:db:atom%%)))
(define zinal:db:list%% (interface (zinal:db:parent-node%%)
; Returns a list of zinal:db:node%% , constituting the items of this list
get-items ; ()
; Inserts a new unassigned node into the list at the specified index.
; Returns a zinal:db:unassigned%% handle to the new unassigned node
insert!! ; (non-negative-integer)
; Deletes a zinal:db:unassigned%% at the specified position, and shifts all latter
; items in the list down by one index. Any handles associated with that node are
; now invalid and cannot be used. No meaningful return value. If the node at the
; specified index is not zinal:db:unassigned%% , an exception will be thrown
remove!! ; (non-negative-integer)
))
; A module is comparable in scope to a racket module. It contains a list of nodes,
; which are evaluated in order by any program which requires it. Each module is the root
; of a tree of zinal:db:node%% . A module can require other modules in order to refer to
; their public defs. No module is allowed to require the main module, and the graph of
; requires must form a DAG.
; There can be any number of modules, but only one main module. If the program is run,
; it is the main module that is executed; if there is no main module, then the program
; cannot be run as an executable. Generally, referables are only visible within their
; own module, but each get-public-defs exposes a set of direct children that can
; be referred to by any module that requires this one.
(define zinal:db:module%% (interface (zinal:db:describable%% zinal:db:has-body%%)
; Returns a list of all direct child zinal:db:def%% and zinal:db:define-class%% that
; can be referenced in other modules, in no particular order. Each public child must
; be a direct child, not an indirect descendant.
get-public-defs ; ()
; The first argument specifies which direct child to change the publicity of. If the
; index is out of bounds, or the node is not a direct child of this module, an
; exception is thrown. new-value is #t if the child should be public, #f otherwise.
; Note that it is legal to make a public def non-public, even if doing so makes it
; invisible to some of its references. See the comment about visibility rules.
; No meaningful return value.
set-public!! ; (index OR zinal:db:def%% OR zinal:db:define-class%% , new-value)
is-main-module? ; ()
; Returns #t if this module can be made the main module via (set-main-module #t),
; #f otherwise. This module can be made the main module as long as no other module
; is already the main module, and as long as no other module requires this module.
can-be-main-module? ; ()
; If new-value is #f, makes this not the main module, otherwise it becomes the main
; module. If new-value is true, but can-be-main-module? would return #f , an
; exception is thrown. No meaningful return value
set-main-module!! ; (new-value)
; Gets a list of all zinal:db:module%% that this module requires, in no particular
; order
get-required-modules ; ()
; Gets a list of all zinal:db:module%% that require this module, in no particular
; order
get-requiring-modules ; ()
; Returns #t if this module is allowed to require the argument, #f otherwise. The
; argument can be required as long as it's not the main module, and as long as doing
; so would not create a cycle in the require graph.
can-require? ; (zinal:db:module%%)
; If can-require? would return #t, adds the argument to this module's require list.
; Otherwise, throws an exception.
; No meaningful return value
require!! ; (zinal:db:module%%)
; If the argument is currently require'd by this module, removes the argument from
; this module's requires. If it's not already required, this method does nothing.
; unrequire!! can cause references to lose vision, which is perfectly legal; see
; the comment about visibility rules.
; No meaningful return value.
unrequire!! ; (zinal:db:module%%)
; Returns #t if this module can be deleted via delete!! , #f otherwise. The module
; can be deleted so long as no other module contains a reference to one of its
; children and no other module requires it.
can-delete? ; ()
; If can-delete? would return #t, deletes this module. Otherwise, throws an exception.
; No meaningful return value.
delete!! ; ()
))
; A definition, comparable to scheme define - note this is used for both constants and
; for functions, tho not for some OOP definitions like method, class, or interface defs
(define zinal:db:def%% (interface (zinal:db:parent-node%% zinal:db:referable%%)
; Returns a zinal:db:node%% handle for the expression of this define
get-expr ; ()
))
(define zinal:db:def-ref%% (interface (zinal:db:reference%%)
; Returns a zinal:db:def%% handle for the define that this reference refers to
get-def ; ()
))
(define zinal:db:param%% (interface (zinal:db:parent-node%% zinal:db:referable%%)
; Returns a zinal:db:lambda%% handle for the lambda that this param belongs to.
; Equivalent to get-parent
get-lambda ; ()
; Returns a zinal:db:node%% handle for the default expression. Returns #f for required params.
get-default ; ()
))
(define zinal:db:param-ref%% (interface (zinal:db:reference%%)
; Returns a zinal:db:param%% handle for the param that this reference refers to
get-param ; ()
))
; Used for invoking (or identifying) scheme functions, macros, constants, classes, etc.
; E.g., a zinal:db:racket%% with library #f and name "string->symbol" represents the
; scheme string->symbol function. If it were the first node in a zinal:db:list%% , then
; that list is probably an invokation of string->symbol. This is used for all important
; built-ins, such as 'send, 'quote, '+, and 'list.
(define zinal:db:racket%% (interface (zinal:db:node%%)
; Returns the name (as a string) of the library the specified identifier belongs to.
; Returns #f for the default library
get-library ; ()
; Returns a string of the identifier itself
get-name ; ()
))
; A placeholder node that has not been assigned an actual value yet. A db that contains
; these cannot be compiled. The assign!! methods transform this node
; into one of a different type. In doing so, any handles to this node become invalid,
; and may no longer be used. The assign!! methods return a handle to the newly created
; node.
; These nodes are describable so that a little "TODO"
; note can be written, or so the intended purpose can be described before it must
; actually be implemented
(define zinal:db:unassigned%%
(interface (zinal:db:node%% zinal:db:describable%%)
assign-lambda!! ; ()
assign-def!! ; ([short-desc] [long-desc])
assign-list!! ; ()
assign-assert!! ; ()
; Use #f for library to specify the standard library
assign-racket!! ; (library name)
; If a reference is assigned to a referable that is not visible, an exception is
; thrown. See the section about reference visibility.
assign-def-ref!! ; (zinal:db:def%%)
assign-param-ref!! ; (zinal:db:param%%)
assign-class-ref!! ; (zinal:db:define-class%%)
assign-interface-ref!! ; (zinal:db:interface%%)
assign-number!! ; (value)
assign-char!! ; (value)
assign-string!! ; (value)
assign-bool!! ; (value)
assign-symbol!! ; (value)
assign-keyword!! ; (value)
assign-define-class!! ; ([short-desc] [long-desc])
assign-class-instance!! ; ()
assign-invoke-method!! ; (zinal:db:method%%)
assign-invoke-racket-method!! ; (string)
assign-create-object!! ; ()
; attempting to call any of the following methods on a node that is not inside a
; zinal:db:class%% body will throw an exception
assign-this!! ; ()
assign-invoke-super-method!! ; (zinal:db:method%%)
assign-invoke-racket-super-method!! ; (string)
; attempting to call these methods at any location besides the direct child of a
; class will throw an exception
assign-super-init!! ; ()
assign-define-method!! ; (zinal:db:method%%)
assign-override-racket-method!! ; (string)
)
)
(define zinal:db:element-visitor%
(class object%
(super-make-object)
(define/public (visit-element e data) #f)
(define/public (visit-node n data) (visit-element n data))
(define/public (visit-reference r data) (visit-node r data))
(define/public (visit-atom a data) (visit-node a data))
(define/public (visit-interface i data) (visit-element i data))
(define/public (visit-interface-ref ir data) (visit-reference ir data))
(define/public (visit-method m data) (visit-element m data))
(define/public (visit-module m data) (visit-node m data))
(define/public (visit-list l data) (visit-node l data))
(define/public (visit-lambda l data) (visit-node l data))
(define/public (visit-assert a data) (visit-node a data))
(define/public (visit-number n data) (visit-atom n data))
(define/public (visit-char c data) (visit-atom c data))
(define/public (visit-string s data) (visit-atom s data))
(define/public (visit-bool b data) (visit-atom b data))
(define/public (visit-symbol s data) (visit-atom s data))
(define/public (visit-keyword k data) (visit-atom k data))
(define/public (visit-def d data) (visit-node d data))
(define/public (visit-def-ref dr data) (visit-reference dr data))
(define/public (visit-param p data) (visit-node p data))
(define/public (visit-param-ref pr data) (visit-reference pr data))
(define/public (visit-racket l data) (visit-node l data))
(define/public (visit-invoke-method im data) (visit-node im data))
(define/public (visit-invoke-racket-method ilm data) (visit-node ilm data))
(define/public (visit-create-object co data) (visit-node co data))
(define/public (visit-super-init si data) (visit-node si data))
(define/public (visit-invoke-super-method ism data) (visit-node ism data))
(define/public (visit-invoke-racket-super-method ilsm data) (visit-node ilsm data))
(define/public (visit-define-method dm data) (visit-node dm data))
(define/public (visit-override-racket-method olm data) (visit-node olm data))
(define/public (visit-this t data) (visit-node t data))
(define/public (visit-class c data) (visit-node c data))
(define/public (visit-define-class c data) (visit-class c data))
(define/public (visit-define-class-ref cr data) (visit-reference cr data))
(define/public (visit-class-instance c data) (visit-class c data))
(define/public (visit-unassigned u data) (visit-node u data))
)
)
)
| true |
1ae30c276ac740f3e469c1140611cd5f538ca8a8 | 9508c612822d4211e4d3d926bbaed55e21e7bbf3 | /design/statechart-examples/statecharts-login.rkt | 3b9e097f7f7587c3ff7ef76c4ce4ebcf07c255bd | [
"MIT",
"Apache-2.0"
] | permissive | michaelballantyne/syntax-spec | 4cfb17eedba99370edc07904326e3c78ffdb0905 | f3df0c72596fce83591a8061d048ebf470d8d625 | refs/heads/main | 2023-06-20T21:50:27.017126 | 2023-05-15T19:57:55 | 2023-05-15T19:57:55 | 394,331,757 | 13 | 1 | NOASSERTION | 2023-06-19T23:18:13 | 2021-08-09T14:54:47 | Racket | UTF-8 | Racket | false | false | 464 | rkt | statecharts-login.rkt | #lang racket
; Very much not complete...
(define-statechart submitready
(state missing-input)
(state ready))
(define-statechart authenticate
(state connecting)
(state connected))
(define-statechart session
(data time)
(state connected)
(state disconnected))
(define-statechart login
(parallel
submitready
authenticate))
(define-statechart login-with-freeze
(data attempts 0)
(state can-login
login)
(state frozen))
| false |
cdd72233aa28481778e08871e66580055cd002f6 | 37c451789020e90b642c74dfe19c462c170d9040 | /cap-1/solucao-1.29.rkt | 726ab96fe7af8a769cfc0546678e0c5133244d8c | [] | no_license | hmuniz/LP-2016.2 | 11face097c3015968feea07c218c662dc015d1cf | 99dc28c6da572701dbfc885f672c2385c92988e7 | refs/heads/master | 2021-01-17T21:26:06.154594 | 2016-12-20T15:22:16 | 2016-12-20T15:22:16 | 71,069,658 | 1 | 0 | null | 2016-10-16T18:41:10 | 2016-10-16T18:41:09 | null | UTF-8 | Racket | false | false | 624 | rkt | solucao-1.29.rkt | #lang racket
;; codigo do livro
(define (sum term a next b)
(if (> a b)
0
(+ (term a)
(sum term (next a) next b))))
(define (integral f a b dx)
(define (add-dx x) (+ x dx))
(* (sum f (+ a (/ dx 2.0)) add-dx b)
dx))
;; solucao
(define (simpson f a b n)
(define h (/ (- b a) n))
(define (y k)
(f (+ a (* k h))))
(define (term k)
(* (cond ((odd? k) 4)
((or (= k 0) (= k n)) 1)
((even? k) 2))
(y k)))
(/ (* h (sum term 0 (lambda (x) (+ 1 x)) n)) 3))
;; teste
(define (cube x) (* x x x))
(simpson cube 0 1 100.0)
(integral cube 0 1 0.01)
| false |
27a53a5aed71c0d5d6c2d5cf2236c549e66cbc57 | 94c038f61575ec72929634d05bfa369f524462f1 | /old-mk-cps/a9-skmonads2/#micro-ks-5.rkt# | 9e7b606a94459b64515ad62656d294ea08d03baf | [
"MIT"
] | permissive | jasonhemann/mk-search-w-continuations | b53026134db8224f71ebc5c442d12f1d29a0b303 | aa37bf956fee875b9f503ea3364876ec6fd48580 | refs/heads/master | 2021-08-04T10:13:31.479834 | 2021-07-27T16:31:55 | 2021-07-27T16:31:55 | 236,832,420 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,327 | #micro-ks-5.rkt# | #lang racket
;; inline-fn call
;; back off the existence of dk;
;; remove the dk from the program, only add it in after CPSing, and
;; see what happens when you do that.
;; re-introduce dk, as the 4th and final element.
;; is disj serious or simple?
;; is fail serious or simple?
;; let us try treating it as serious, and see where that gets us.
;; it seems to get pretty far. There's only a couple of places where
;; we have questionable behavior that requires modification: bind and
;; disj
;; but this doesn't seem to be getting us the right answers.
(define ((ee g s) dk)
(match g
[`(ore ,g1 ,g2) ((ee g1 s) (λ (c) ((ee g2 s) (λ (c2) ((disj c c2) dk)))))]
;; pass along?
;; apply to it?
;; both?
[`(ande ,g1 ,g2) ((ee g1 s) (λ (c) ((bind c g2) dk)))]
[`(succeed) ((unit s) dk)]
[`(fail) ((fail) dk)]
[`(alwayso) ((mdelay (ee `(ore (succeed) (alwayso)) s)) dk)]
))
(define-syntax-rule (mdelay c)
(λ (dk)
(λ (sk fk)
(dk c))))
(define ((unit s) dk)
(λ (sk fk)
(sk s fk)))
(define ((fail) dk)
(λ (sk fk)
(fk)))
(define ((disj c c2) dk)
(λ (sk fk)
((c (λ (c) ((disj c2 c) dk)))
;;
sk
(λ () ((c2 dk) sk fk))))) ;; dk
(define ((bind c g) dk)
(λ (sk fk) ;; dk
((c dk)
;; (λ (c) (dk (bind c g)))
(λ (s fk) (λ (dk^) (((ee g s) dk) sk fk))) ;; changed back to a dk^
;; how different is it?
;; we used to not take it from the site of the other, but from this one.
fk)))
;; and possibly the original continuations too.
(define kons (λ (s fk) (cons s (fk))))
(define nill (λ () '()))
(define identity (λ (c) c))
(define (looper n c)
(match n
[`Z ((c identity) kons nill)] ;; identity
[`(S ,n^) ((c (λ (c) (looper n^ c))) kons nill)])) ;; add in serious dk rather than identity here
;; Could instead nest up computations here
(looper '(S Z) (ee '(ore (ande (succeed) (succeed)) (fail)) '()))
(looper '(S Z) (ee '(alwayso) '()))
(looper '(S (S (S (S (S (S (S (S (S (S Z)))))))))) (ee '(ore (alwayso) (ore (alwayso) (succeed))) '()))
(looper '(S (S (S (S (S (S (S (S (S (S Z)))))))))) (ee '(ande (ore (alwayso) (succeed)) (succeed)) '()))
(looper '(S (S (S (S (S (S (S (S (S (S Z)))))))))) (ee '(ande (ore (alwayso) (succeed)) (fail)) '()))
| true |
|
fd18f6c73882da776d6d1938ce070421048560a0 | f0916dac3f6f73d721db09e137ce6201efd027d2 | /doc/rnrs/records/inspection.scrbl | 8a5206acd2fc2dd209137a36d152bf9e22e2165f | [
"BSD-3-Clause",
"LicenseRef-scancode-other-permissive",
"MIT",
"BSD-2-Clause"
] | permissive | christoff-buerger/sagittarius-scheme | b8b9289650b4245c1f4d8d92d03d6d8e8e0faacf | f2ac5bbc48a65ca89f036000e5a658a429e0a8b9 | refs/heads/master | 2021-11-12T12:26:17.738912 | 2021-10-28T10:06:47 | 2021-10-28T10:06:47 | 243,363,196 | 0 | 0 | NOASSERTION | 2020-02-26T20:52:02 | 2020-02-26T20:52:01 | null | UTF-8 | Racket | false | false | 1,969 | scrbl | inspection.scrbl | @; -*- mode:scribble; coding: utf-8 -*-
@subsection[:tag "rnrs.records.inspection.6"]{Records inspection}
@define[Library]{@name{(rnrs records syntactic (6))}}
@desc{The @code{(rnrs records inspection (6))}library provides procedures for
inspecting records and their record-type descriptors. These procedures are designed
to allow the writing of portable printers and inspectors.
}
@define[Function]{@name{record?} @args{obj}}
@desc{[R6RS] Returns #t if @var{obj} is a record, and its record type is not
opaque, and returns #f otherwise.
}
@define[Function]{@name{record-rtd} @args{record}}
@desc{[R6RS] Returns the rtd representing the type of @var{record} if the type
is not opaque. The rtd of the most precise type is returned; that is, the type
@var{t} such that @var{record} is of type @var{t} but not of any type that
extends @var{t}. If the type is opaque, an exception is raised with condition
type @code{&assertion}.
}
@define[Function]{@name{record-type-name} @args{rtd}}
@define[Function]{@name{record-type-parent} @args{rtd}}
@define[Function]{@name{record-type-uid} @args{rtd}}
@desc{[R6RS] Returns the name/parent/uid of the record-type descriptor @var{rtd}.
}
@define[Function]{@name{record-type-generative?} @args{rtd}}
@define[Function]{@name{record-type-sealed?} @args{rtd}}
@define[Function]{@name{record-type-opaque?} @args{rtd}}
@desc{[R6RS] Returns #t if the record-type descriptor is generative/sealed/opaque,
and #f if not.
}
@define[Function]{@name{record-type-field-names} @args{rtd}}
@desc{[R6RS] Returns a vector of symbols naming the fields of the type represented
by @var{rtd} (not including the fields of parent types) where the fields are
ordered as described under @code{make-record-type-descriptor}.
}
@define[Function]{@name{record-type-mutable?} @args{rtd k}}
@desc{[R6RS] Returns #t if the field specified by @var{k} of the type represented
by @var{rtd} is mutable, and #f if not. @var{K} is as in @code{record-accessor}.
}
| false |
281614b76747a3e93f62214e75ee3bcb233fb7bf | e1cf61b84282c33b7a245f4d483883cf77739b91 | /se3-bib/sim/simAppl/simServerStationsViewClass-module.rkt | 93d299ad8d9ddff18df573283c402111ceb9c8c2 | [] | no_license | timesqueezer/uni | c942718886f0366b240bb222c585ad7ca21afcd4 | 5f79a40b74240f2ff88faccf8beec7b1b3c28a7c | refs/heads/master | 2022-09-23T21:57:23.326315 | 2022-09-22T13:17:29 | 2022-09-22T13:17:29 | 71,152,113 | 0 | 2 | null | null | null | null | UTF-8 | Racket | false | false | 2,761 | rkt | simServerStationsViewClass-module.rkt | #lang swindle
#|
################################################################################
## ##
## This file is part of the se3-bib Racket module v3.0 ##
## Copyright by Leonie Dreschler-Fischer, 2010 ##
## Ported to Racket v6.2.1 by Benjamin Seppke, 2015 ##
## ##
################################################################################
|#
(provide
idle-pic serving-pic reject-pic clerk-pic bg-pic
set-idle-pic! set-serving-pic! set-reject-pic!
set-clerk-pic! set-bg-pic!)
(require se3-bib/sim/bilder/bilder-module
se3-bib/sim/simBase/sim-base-package)
(define *default-bg-pic*
(rectangle (image-width *default-idle-pic*)
(image-height *default-reject-pic*)
'solid 'gray))
(defclass* server-station-view
(sim-actor-view)
(clerk-picture
:reader clerk-pic
:writer set-clerk-pic!
:initarg :clerk-pic
:initvalue *default-idle-pic*
; :allocation :class
:documentation
"A picture of an idle server"
)
(idle-picture
:reader idle-pic
:writer set-idle-pic!
:initarg :idle-pic
:initvalue *default-idle-pic*
; :allocation :class
:documentation
"A picture of an idle server"
)
(serving-picture
:reader serving-pic
:writer set-serving-pic!
:initarg :serving-pic
:initvalue *default-serving-pic*
; :allocation :class
:documentation
"A picture of the current state of the actor"
)
(reject-picture
:reader reject-pic
:writer set-reject-pic!
:initarg :reject-pic
:initvalue *default-reject-pic*
; :allocation :class
:documentation
"A picture of the current state of the actor"
)
(bg-picture
:reader bg-pic
:writer set-bg-pic!
:initarg :bg-pic
:initvalue *default-bg-pic*
:allocation :class
:documentation
"A picture of the current state of the actor"
)
:autopred #t ; auto generate predicate queue?
:printer #t
:documentation
"The View of a server station")
(defgeneric* picture-of-clerk ((s server-station-view))
:documentation "a picture of the state of the clerk"
)
(defgeneric* picture-of-counter ((s server-station-view))
:documentation
"Picture of clerk and an advertisement of the station service")
(defgeneric* init-clerk-bg ((s server-station-view))
:documentation
"compute the dimensions of the view, create gray background plate")
(defgeneric* all-stations-picture ((sc sim-scenario))
:documentation
"a picture of all the server stations and waiting lines"
)
| false |
995014d6c86dc0454c7afc10018c73debecfe4d9 | 76df16d6c3760cb415f1294caee997cc4736e09b | /examples/incorrect-ex-1.rkt | 5f6fce1c81b68d933a9963d968605f81e1583379 | [
"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 | 168 | rkt | incorrect-ex-1.rkt | #lang rosette
(define (abs x)
(if (< x 0)
(- x)
x))
(define-symbolic y integer?)
(verify
(begin
(assume (not (= y 1)))
(assert (> (abs y) 0))))
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.