blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
171
content_id
stringlengths
40
40
detected_licenses
listlengths
0
8
license_type
stringclasses
2 values
repo_name
stringlengths
6
82
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
13 values
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
1.59k
594M
โŒ€
star_events_count
int64
0
77.1k
fork_events_count
int64
0
33.7k
gha_license_id
stringclasses
12 values
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_language
stringclasses
46 values
src_encoding
stringclasses
14 values
language
stringclasses
2 values
is_vendor
bool
2 classes
is_generated
bool
1 class
length_bytes
int64
4
7.87M
extension
stringclasses
101 values
filename
stringlengths
2
149
content
stringlengths
4
7.87M
has_macro_def
bool
2 classes
418052d6429a11c84d4e39fdab8f7759c95c13f2
15b3f9425594407e43dd57411a458daae76d56f6
/Book/Edition2/exercise414.scm
12ab347268fce25a6941cd8b97b7b45be5f0ecfa
[]
no_license
aa10000/scheme
ecc2d50b9d5500257ace9ebbbae44dfcc0a16917
47633d7fc4d82d739a62ceec75c111f6549b1650
refs/heads/master
2021-05-30T06:06:32.004446
2015-02-12T23:42:25
2015-02-12T23:42:25
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,313
scm
exercise414.scm
; Structure and Interpretation of Computer Programs, 2nd edition Exercise 4.14. Eva Lu Ator and Louis Reasoner are each experimenting with the metacircular evaluator. Eva types in the definition of map, and runs some test programs that use it. They work fine. Louis, in contrast, has installed the system version of map as a primitive for the metacircular evaluator. When he tries it, things go terribly wrong. Explain why Louis's map fails even though Eva's works. (define (map proc items) (if (null? items) '() (cons (proc (car items)) (map proc (cdr items))))) ; The problem is that the representation of procedures is totally different ; in our evaluator and in the underlying Scheme implementation. ; ; Now when the map is from the underlying Scheme, the call ; ; (map (lambda (n) (+ n n)) '(1 2 3)) ; ; creates a procedure (from the lambda expression) in our representation ; and it is passed to the system map-function. The map tries to call the ; procedure and finds it "not applicable". This is equivalent to evaluating ; the expression ; ; (map 'a '(1 2 3)) ; ; Here (quote a) is also "not applicable". ; ; The same holds for any higher-order procedure from the underlying ; implementation that tries to call a procedure in our representation.
false
34a5333fcb6f5a0b0e44b792674fac88817a8508
f6ebd0a442b29e3d8d57f0c0935fd3e104d4e867
/ch02/2.2/ex-2-2-okie.scm
3fce82966205f16d0cfc225e2541264b0b232268
[]
no_license
waytai/sicp-2
a8e375d43888f316a063d280eb16f4975b583bbf
4cdc1b1d858c6da7c9f4ec925ff4a724f36041cc
refs/heads/master
2021-01-15T14:36:22.995162
2012-01-24T12:21:30
2012-01-24T12:21:30
23,816,705
1
0
null
null
null
null
UTF-8
Scheme
false
false
28,147
scm
ex-2-2-okie.scm
(cons 1 2) (cons (cons 1 2) (cons 3 4)) (cons (cons 1 (cons 2 3)) 4) (cons 1 (cons 2 (cons 3 (cons 4 nil)))) (define one-through-four (list 1 2 3 4)) (define (list-ref items n) (if (= n 0) (car items) (list-ref (cdr items) (- n 1)))) (define squares (list 1 4 9 16 25)) (list-ref squares 3) (define (length items) (if (null? items) 0 (+ 1 (length (cdr items)))) (define odds (list 1 3 5 7)) (length odds) (define (length items) (define (length-iter a count) (if (null? a) count (length-iter (cdr a) (+ 1 count)))) (length-iter items 0)) (append squares odds) (append odds squares) (define (append list1 list2) (if (null? list1) list2 (cons (car list1) (append (cdr list1) list2)))) ;> (append '(1) 2) ;(1 . 2) ;> (append '(1) '(2)) ;(1 2) ;> ; ex 2.17 (list-pair (list 23 72 149 34)) (define (list-pair list) (if (null? (cdr (cdr list))) (cdr list) (list-pair (cdr list)))) ; ex 2.18 (reverse (list 1 4 9 16 25)) (define (reverse list) (if (null? (cdr list)) list (cons (reverse (cdr list)) (car list)))) (define (reverse list) (define (reverse-iter list result) (if (null? list) result (reverse-iter (cdr list) (cons (car list) result)))) (reverse-iter list '())) ; ex 2.19 (define us-coins (list 50 25 10 5 1)) (define uk-coins (list 100 50 20 10 5 2 1 0.5)) (cc 100 us-coins) (define (cc amount coin-values) (cond ((= amount 0) 1) ((or (< amount 0) (no-more? coin-values)) 0) (else (+ (cc amount (except-first-denomination coin-values)) (cc (- amount (first-denomination coin-values)) coin-values))))) (define (except-first-denomination list) (cdr list)) (define (first-denomination list) (car list)) (define (no-more? list) (null? list)) (define us-coins2 (list 1 5 10 25 50)) (cc 100 us-coins2) (cc 100 us-coins) (cc 100 (reverse us-coins)) (cc 100 uk-coins) ;; no effect ; ex 2.20 (same-parity 1 2 3 4 5 6 7) (same-parity 2 3 4 5 6 7) (same-parity ) ;; TODO (define (same-parity . n) (define (same-parity-inter l parity result) (if (null? l) result (if (boolean=? parity (even? (car l))) (same-parity-inter (cdr l) parity (append result (list (car l)))) (same-parity-inter (cdr l) parity result)))) (same-parity-inter n (even? (car n)) '())) ; list mapping (define (scale-list items factor) (if (null? items) '() (cons (* (car items) factor) (scale-list (cdr items) factor)))) (scale-list (list 1 2 3 4 5) 10) (map + (list 1 2 3) (list 40 50 60) (list 700 800 900)) (map (lambda (x y) (+ x (* 2 y))) (list 1 2 3) (list 4 5 6)) (define (map proc items) (if (null? items) nil (cons (proc (car items)) (map proc (cdr items))))) (map abs (list -10 2.5 -11.6 17)) (define (scale-list items factor) (map (lambda (x) (* x factor)) items)) ; ex 2.21 (square-list (list 1 2 3 4)) (define (square-list items) (if (null? items) '() (cons (* (car items) (car items)) (square-list (cdr items))))) (define (square-list items) (map (lambda (x) (* x x)) items)) ; ex 2.22 (define (square x) (* x x)) (define (square-list items) (define (iter things answer) (if (null? things) answer (iter (cdr things) (cons (square (car things)) answer)))) (let ((result (iter items '()))) (reverse result))) (define (square-list items) (define (iter things answer) (if (null? things) answer (iter (cdr things) (cons answer (square (car things)))))) (iter items '())) ; (cons (list 1 2) 3) ==> ((1 2) . 3) ; (cons 1 (list 2 3)) ==> (1 2 3) ; ex 2.23 (for-each (lambda (x) (newline) (display x)) (list 57 321 88)) (define (for-each proc l) (proc (car l)) (if (not (null? (cdr l))) (for-each proc (cdr l)) #f)) ;; 2.2.2 (cons (list 1 2) (list 3 4)) (define x (cons (list 1 2) (list 3 4))) (length x) (count-leaves x) (list x x) (length (list x x)) (count-leaves (list x x)) (define (count-leaves x) (cond ((null? x) 0) ((not (pair? x)) 1) (else (+ (count-leaves (car x)) (count-leaves (cdr x)))))) ; ex 2.24 (list 1 (list 2 (list 3 4))) ; list type ;; +---------------+ +---+--+ +---+--+ ;; | (1 (2 (3 4))) | --> | | | --> | | | ;; +---------------+ +---+--+ +---+--+ ;; | | ;; | | ;; v v ;; +---+ +---+--+ +---+--+ ;; | 1 | | | | --> | | | ;; +---+ +---+--+ +---+--+ ;; | | ;; | | ;; v v ;; +---+ +---+--+ +---+--+ ;; | 2 | | | | --> | | | ;; +---+ +---+--+ +---+--+ ;; | | ;; | | ;; v v ;; +---+ +---+--+ ;; | 3 | | | | ;; +---+ +---+--+ ;; | ;; | ;; v ;; +---+ ;; | 4 | ;; +---+ ; tree type? ;; +---------------+ +-----------+ +-------+ +---+ ;; | (1 (2 (3 4))) | --> | (2 (3 4)) | --> | (3 4) | --> | 4 | ;; +---------------+ +-----------+ +-------+ +---+ ;; | | | ;; | | | ;; v v v ;; +---------------+ +-----------+ +-------+ ;; | 1 | | 2 | | 3 | ;; +---------------+ +-----------+ +-------+ ; ex 2.25 (define x (list 1 3 (list 5 7) 9)) (define y (list (list 7))) (define z (list 1 (list 2 (list 3 (list 4 (list 5 (list 6 7))))))) (define (find-number x n) (cond ((null? x) 0) ((not (pair? x)) (if (= x n) 1 0)) (else (+ (find-number (car x) n) (find-number (cdr x) n)))))) (car (cdr (car (cdr (cdr x))))) (car (car y)) (car (cdr (car (cdr (car (cdr (car (cdr (car (cdr (car (cdr z)))))))))))) ; ex 2.26 (define x (list 1 2 3)) (define y (list 4 5 6)) (append x y) ; (1 2 3 4 5 6) (cons x y) ; ((1 2 3) 4 5 6) (list x y) ; ((1 2 3) (4 5 6)) ; ex 2.27 (define x (list (list 1 2) (list 3 4))) ; ((1 2) (3 4)) (define y (list (list 1 2) 3 4)) ; ((1 2) 3 4)) (define z (list (list (list 1 2) (list 3 4)) 5 6)) ; (((1 2) (3 4)) 5 6)) (define (deep-reverse x) (cond ((null? x) '()) ((pair? (car x)) (append (deep-reverse (cdr x)) (list (deep-reverse (car x))))) (else (append (deep-reverse (cdr x)) (list (car x)))))) ;(define (deep-reverse x) ; (cond ((null? x) '()) ; ((pair? x) ; (if (null? (cdr x)) ; (append (deep-reverse (car x)) (list (cdr x))) ; (append (deep-reverse (cdr x)) (deep-reverse (car x))))) ; (else (list x)))) (deep-reverse x) (deep-reverse y) (deep-reverse z) (reverse x) ; ex 2.28 (define x (list (list 1 2) (list 3 4))) (define (fringe x) (cond ((null? x) '()) ((pair? x) (append (fringe (car x)) (fringe (cdr x)))) (else (list x)))) (fringe x) (fringe (list x x)) ; ex 2.29 (define (make-mobile left right) (list left right)) (define (make-branch length structure) (list length structure)) ; a. (define (left-branch mobile) (car mobile)) (define (right-branch mobile) (car (cdr mobile))) (define mobile1 (make-mobile (make-branch 1 10) (make-branch 1 20))) (define (branch-length x) (car x)) (define (branch-structure x) (car (cdr x))) ; b. (define total-weight (+ (branch-structure (left-branch mobile1)) (branch-structure (right-branch mobile1)))) ; c. (define (torque x) (* (branch-structure x) (branch-length x))) (= (torque (left-branch mobile1)) (torque (right-branch mobile1))) ; d. (define (make-mobile left right) (cons left right)) (define (make-branch length structure) (cons length structure)) (define (right-branch mobile) (cdr mobile)) (define (branch-structure x) (cdr x)) ; tree mapping (define (scale-tree tree factor) (cond ((null? tree) '()) ((not (pair? tree)) (* tree factor)) (else (cons (scale-tree (car tree) factor) (scale-tree (cdr tree) factor))))) (scale-tree (list 1 (list 2 (list 3 4) 5) (list 6 7)) 10) (define (scale-tree tree factor) (map (lambda (sub-tree) (if (pair? sub-tree) (scale-tree sub-tree factor) (* sub-tree factor))) tree)) ; ex 2.30 (square-tree (list 1 (list 2 (list 3 4) 5) (list 6 7))) (define (square-tree tree) (cond ((null? tree) '()) ((not (pair? tree)) (* tree tree)) (else (cons (square-tree (car tree)) (square-tree (cdr tree)))))) (define (square-tree tree) (map (lambda (sub-tree) (if (pair? sub-tree) (square-tree sub-tree) (* sub-tree sub-tree))) tree)) ; ex 2.31 (define (square x) (* x x)) (define (square-tree tree) (tree-map square tree)) (define (tree-map proc tree) (map (lambda (sub-tree) (if (pair? sub-tree) (tree-map proc sub-tree) (proc sub-tree))) tree)) ; ex 2.32 (define (subsets s) (if (null? s) (list '()) (let ((rest (subsets (cdr s)))) (append rest (map (lambda(x) (cons (car s) x)) rest))))) (subsets (list 1 2 3)) ;1. The powerset of all the elements without the first. ;2. The powerset of all the elements without the first, with the first element prepended to each subset. (subsets '(1)) ; 1. () ; 2. (1) (subsets '(2)) ; 1. () ; 2. (2) (subsets '(1 2)) ; 1. () (2) ; 2. (1) (1 2) (subsets '(2 3)) ; 1. () (3) ; 2. (2) (2 3) (subsets '(1 2 3)) ; 1. () (3) (2) (2 3) ; 2. (1) (1 2) (1 3) (1 2 3) ; 2.2.3 conventional interface (define z (list (list (list 1 2) (list 3 4)) 5 6)) (define (square x) (* x x)) (define (sum-odd-squares tree) (cond ((null? tree) 0) ((not (pair? tree)) (if (odd? tree) (square tree) 0)) (else (+ (sum-odd-squares (car tree)) (sum-odd-squares (cdr tree)))))) (define (fib n) (cond ((= n 0) 0) ((= n 1) 1) (else (+ (fib (- n 1)) (fib (- n 2)))))) (define (even-fibs n) (define (next k) (if (> k n) '() (let ((f (fib k))) (if (even? f) (cons f (next (+ k 1))) (next (+ k 1)))))) (next 0)) (map square (list 1 2 3 4 5)) (define (filter predicate sequence) (cond ((null? sequence) '()) ((predicate (car sequence)) (cons (car sequence) (filter predicate (cdr sequence)))) (else (filter predicate (cdr sequence))))) (filter odd? (list 1 2 3 4 5)) (define (accumulate op initial sequence) (if (null? sequence) initial (op (car sequence) (accumulate op initial (cdr sequence))))) (accumulate + 0 (list 1 2 3 4 5)) (accumulate * 1 (list 1 2 3 4 5)) (* 1 (* 2 (* 3 (* 4 (* 5 1))))) (accumulate cons '() (list 1 2 3 4 5)) (define (enumerate-interval low high) (if (> low high) '() (cons low (enumerate-interval (+ low 1) high)))) (enumerate-interval 2 7) (define (enumerate-tree tree) (cond ((null? tree) '()) ((not (pair? tree)) (list tree)) (else (append (enumerate-tree (car tree)) (enumerate-tree (cdr tree)))))) (enumerate-tree (list 1 (list 2 (list 3 4)) 5)) (define (sum-odd-squares tree) (accumulate + 0 (map square (filter odd? (enumerate-tree tree))))) (define (even-fibs n) (accumulate cons '() (filter even? (map fib (enumerate-interval 0 n))))) (define (list-fib-squares n) (accumulate cons '() (map (lambda (x) (* x x)) (map fib (enumerate-interval 0 n))))) (list-fib-squares 10) (define (product-of-squares-odd-elements sequence) (accumulate * 1 (map (lambda (x) (* x x)) (filter odd? sequence)))) (product-of-squares-odd-elements (list 1 2 3 4 5)) (define (salary-of-highest-paid-programmer records) (accumulate max 0 (map salary (filter programmer? records) ; ex 2.33 (define (map p sequence) (accumulate (lambda (x y) (cons (p x) y)) '() sequence)) (map (lambda (x) (+ x 1)) (list 1 2 3 4 5)) (define (append seq1 seq2) (accumulate cons seq2 seq1)) (append (list 1 2 3 4 5) (list 6 7 8 9 10)) (define (length sequence) (accumulate (lambda (x y) (+ 1 y)) 0 sequence)) (length (list 1 2 3 4 5)) ; ex 2.34 (define (horner-eval x coefficient-sequence) (accumulate (lambda (this-coeff higher-terms) (+ (* higher-terms x) this-coeff)) 0 coefficient-sequence)) (horner-eval 2 (list 1 3 0 5 0 1)) ; 79 ((lambda (x) (+ 1 (* 3 x) (* 5 (* x x x)) (* x x x x x))) 2) ; 79 ; ex 2.35 (define x (cons (list 1 2) (list 3 4))) (define y (cons (cons (list 1 (list 1 2)) (list 3 4)) (cons (list 5 6) (list 7 8)))) (define (count-leaves x) (cond ((null? x) 0) ((not (pair? x)) 1) (else (+ (count-leaves (car x)) (count-leaves (cdr x)))))) (define (count-leaves t) (accumulate + 0 (map (lambda (seq) (if (pair? seq) (accumulate (lambda (x y) (+ 1 y)) 0 seq) 1)) t))) ; ==> error!! (define (count-leaves t) (accumulate + 0 (map (lambda (seq) (if (pair? seq) (count-leaves seq) 1)) t))) ;; (define (count-leaves t) ;; (accumulate (lambda (x y) (+ 1 y)) ;; 0 ;; (map (lambda (seq) ;; (if (pair? seq) (enumerate-tree t) ;; seq)) ;; t))) ;; (define (count-leaves t) ;; (accumulate (lambda (x y) (+ 1 y)) ;; 0 ;; (map enumerate-tree t))) (count-leaves x) (count-leaves y) ; ex 2.36 (define s (list (list 1 2 3) (list 4 5 6) (list 7 8 9) (list 10 11 12))) ;; (define (pick seq) ;; (if (null? seq) ;; '() ;; (cons (car (car seq)) (pick (cdr seq))))) ;; (define (pick2 seq) ;; (if (null? seq) ;; '() ;; (cons (cdr (car seq)) (pick2 (cdr seq))))) ;; (pick s) ;; (pick2 s) (accumulate cons '() (map car s)) (accumulate cons '() (map cdr s)) ;; (define (accumulate-n op init seqs) ;; (if (null? (car seqs)) ;; '() ;; (cons (accumulate op init (accumulate cons '() (map car seqs))) ;; (accumulate-n op init (accumulate cons '() (map cdr seqs)))))) ;; more concise (define (accumulate-n op init seqs) (if (null? (car seqs)) '() (cons (accumulate op init (map car seqs)) (accumulate-n op init (map cdr seqs))))) (accumulate-n + 0 s) ; ex 2.37 (define m (list (list 1 2 3 4) (list 5 6 7 8) (list 9 10 11 12))) (define (dot-product v w) (accumulate + 0 (map * v w))) ;; (define (matrix-*-vector m v) ;; (map ;; (lambda (seq) ;; ; (display (cons seq (list v))) ;; ; (newline) ;; (accumulate-n * 1 (cons seq (list v)))) m)) (define (matrix-*-vector m v) (map (lambda (seq) (accumulate + 0 (accumulate-n * 1 (cons seq (list v))))) m)) (matrix-*-vector m (list 1 2 3 4)) ;; 1 2 3 a 1a + 2b + 3c ;; 4 5 6 b = 4a + 5b + 6c ;; 7 8 9 c 7a + 8b + 9c (define (transpose mat) (accumulate-n cons '() mat)) ;; ((1 2 3) (4 5 6) (7 8 9)) ;; ==> ((1 4 7) (2 5 8) (3 6 9)) (transpose m) ;; 1 2 3 a b c ;; 4 5 6 d e f = ;; 7 8 9 g h i (define (matrix-*-matrix m n) (let ((cols (transpose n))) (map (lambda (v) (matrix-*-vector cols v)) m))) (define m1 (list (list 1 2 3) (list 4 5 6) (list 7 8 9))) (define m2 (list (list 7 8 9) (list 4 5 6) (list 1 2 3))) ;; by wolfram alpha ;; 3(6 | 8 | 10 ;; 18 | 23 | 28 ;; 30 | 38 | 46) (matrix-*-vector m1 (list 7 8 9)) (matrix-*-matrix m1 m2) ;; ((18 24 30) (54 69 84) (90 114 138)) (define (fold-left op initial sequence) (define (iter result rest) (if (null? rest) result (iter (op result (car rest)) ; <--- (cdr rest)))) (iter initial sequence)) (define (fold-right op initial sequence) (define (iter result rest) (if (null? rest) result (iter (op (car rest) result) ; <--- (cdr rest)))) (iter initial sequence)) (define (fold-right op initial sequence) (accumulate op initial sequence)) ; more concise (define fold-right accumulate) (fold-right / 1 (list 1 2 3)) ;(/ 1 (/ 2 (/ 3 1))) ; ์ญ‰๋Š˜์—ฌ๋†“๊ณ  ๋”์ด์ƒ ๋Š˜์–ด๋‚ ๋•Œ๊ฐ€ ์—†์„๋•Œ ๋’ค์—์„œ ๋ถ€ํ„ฐ ์ดˆ๊ธฐ๊ฐ’์ด์šฉ ๊ณ„์‚ฐ ; 3/2 (fold-left / 1 (list 1 2 3)) ;(/ (/ (1 1) 2) 3) ; ์ดˆ๊ธฐ๊ฐ’ ๋ถ€ํ„ฐ ๊ณ„์‚ฐํ•˜๊ณ  ๋’ค๋กœ ๊ณ„์‚ฐ ; 1/6 (fold-right list '() (list 1 2 3)) ;(list 1 (list 2 (list 3 nil))) ; (((() 1) 2) 3) (fold-left list '() (list 1 2 3)) ;(list (list (list nil 1) 2) 3) ; (((() 1) 2) 3) ; fold-right ์™€ fold-left๋Š” ์—ฐ์‚ฐ์ˆœ์„œ๊ฐ€ ๋‹ค๋ฅด๊ณ  ; fold-left๊ฐ€ ์„ฑ๋Šฅ์ƒ ๋” ์šฐ์ˆ˜ ; ex 2.39 (define (reverse sequence) (fold-right (lambda (x y) (append y (list x))) '() sequence)) (reverse (list 1 2 3 4)) (define (reverse sequence) (fold-left (lambda (x y) (append (list y) x)) '() sequence)) ;; nested mapping (define (pairmap n) (accumulate append '() (map (lambda (i) (map (lambda (j) (list i j)) (enumerate-interval 1 (- i 1)))) (enumerate-interval 1 n)))) (pairmap 10) (define (square n) (* n n)) (define (smallest-divisor n) (define (divides? a b) (= (remainder b a) 0)) (define (find-divisor n test-divisor) (cond ((> (square test-divisor) n) n) ((divides? test-divisor n) test-divisor) (else (find-divisor n (+ test-divisor 1))))) (find-divisor n 2)) (define (prime? n) (= n (smallest-divisor n))) (define (flatmap proc seq) (accumulate append '() (map proc seq))) (define (prime-sum? pair) (prime? (+ (car pair) (cadr pair)))) (define (make-pair-sum pair) (list (car pair) (cadr pair) (+ (car pair) (cadr pair)))) (define (prime-sum-pairs n) (map make-pair-sum (filter prime-sum? (flatmap (lambda (i) (map (lambda (j) (list i j)) (enumerate-interval 1 (- i 1)))) (enumerate-interval 1 n))))) (prime-sum-pairs 10) (define (permutations s) (if (null? s) (list '()) (flatmap (lambda (x) (map (lambda (p) (cons x p)) (permutations (remove x s)))) s))) (define (remove item sequence) (filter (lambda (x) (not (= x item))) sequence)) (permutations (list 1 2 3)) ; ex 2.40 (define (unique-pairs n) (flatmap (lambda (i) (map (lambda (j) (list i j)) (enumerate-interval 1 (- i 1)))) (enumerate-interval 2 n))) ; <--- 1 <= j < i <= n (unique-pairs 10) (define (prime-sum-pairs n) (map make-pair-sum (filter prime-sum? (unique-pairs n)))) (prime-sum-pairs 10) ; ex 2.41 (define (triples n) (flatmap (lambda (i) (flatmap (lambda (j) (map (lambda (k) (list i j k)) (enumerate-interval 1 (- j 1)))) (enumerate-interval 1 (- i 1)))) (enumerate-interval 1 n))) (triples 10) ; ex 2.42 (define (queens board-size) (define (queen-cols k) (if (= k 0) (list empty-board) (filter (lambda (positions) (safe? k positions)) (flatmap (lambda (rest-of-queens) (map (lambda (new-row) (adjoin-position new-row k rest-of-queens)) (enumerate-interval 1 board-size))) (queen-cols (- k 1)))))) (queen-cols board-size)) (define (queens-cases board-size) (define (queen-cols k) (if (= k 0) (list empty-board) (flatmap (lambda (rest-of-queens) (map (lambda (new-row) (adjoin-position new-row k rest-of-queens)) (enumerate-interval 1 board-size))) (queen-cols (- k 1))))) (queen-cols board-size)) (queens-cases 4) (map (lambda (new-row) (adjoin-position new-row 3 '())) (enumerate-interval 1 4)) (define (adjoin-position new-row k rest-of-queens) (list k new-row)) ; (list rest-of-queens (cons new-row k)) (define empty-board '()) (define (safe? q seqs) ; (display seqs) (not (or (= (car seqs) q) (= (cadr seqs) q)))) (safe? 2 (list (list 4 4) (list 4 3) (list 4 2) (list 4 1))) (queens 4) ; ex 2.25 (define (queens board-size) (define (queen-cols k) (if (= k 0) (list empty-board) (filter (lambda (positions) (safe? k positions)) (flatmap (lambda (new-row) (map (lambda (rest-of-queens) (adjoin-position new-row k rest-of-queens)) (queens-cols (- k 1)))) (enumerate-interval 1 board-size))))) (queen-cols board-size)) ;; picture language (define wave (segments->painter (list (make-segment (make-vect 0.35 0.85) (make-vect 0.40 1.00)) (make-segment (make-vect 0.65 0.85) (make-vect 0.60 1.00)) (make-segment (make-vect 0.35 0.85) (make-vect 0.40 0.65)) (make-segment (make-vect 0.65 0.85) (make-vect 0.60 0.65)) (make-segment (make-vect 0.50 0.75) (make-vect 0.42 0.78)) ;; ๅฃ (make-segment (make-vect 0.50 0.75) (make-vect 0.58 0.78)) ;; ๅฃ (make-segment (make-vect 0.60 0.65) (make-vect 0.75 0.65)) (make-segment (make-vect 0.40 0.65) (make-vect 0.30 0.65)) (make-segment (make-vect 0.75 0.65) (make-vect 1.00 0.35)) (make-segment (make-vect 0.60 0.45) (make-vect 1.00 0.15)) (make-segment (make-vect 0.60 0.45) (make-vect 0.75 0.00)) (make-segment (make-vect 0.50 0.30) (make-vect 0.60 0.00)) (make-segment (make-vect 0.30 0.65) (make-vect 0.15 0.60)) (make-segment (make-vect 0.30 0.60) (make-vect 0.15 0.40)) (make-segment (make-vect 0.15 0.60) (make-vect 0.00 0.85)) (make-segment (make-vect 0.15 0.40) (make-vect 0.00 0.65)) (make-segment (make-vect 0.30 0.60) (make-vect 0.35 0.50)) (make-segment (make-vect 0.35 0.50) (make-vect 0.25 0.00)) (make-segment (make-vect 0.50 0.30) (make-vect 0.40 0.00))))) (wave canvas-frame) (require (planet soegaard/sicp:2:1/sicp)) (define wave einstein) (define wave2 (beside wave (flip-vert wave))) ;(paint wave2) (define wave4 (below wave2 wave2)) ;(paint wave4) (define (flipped-pairs painter) (let ((painter2 (beside painter (flip-vert painter)))) (below painter2 painter2))) (define wave4 (flipped-pairs wave)) ;(paint wave4) ; recursion (define (right-split painter n) (if (= n 0) painter (let ((smaller (right-split painter (- n 1)))) (beside painter (below smaller smaller))))) ;(paint (right-split wave 1)) (define (corner-split painter n) (if (= n 0) painter (let ((up (up-split painter (- n 1))) (right (right-split painter (- n 1)))) (let ((top-left (beside up up)) (bottom-right (below right right)) (corner (corner-split painter (- n 1)))) (beside (below painter top-left) (below bottom-right corner)))))) (define (square-limit painter n) (let ((quarter (corner-split painter n))) (let ((half (beside (flip-horiz quarter) quarter))) (below (flip-vert half) half)))) ;(paint (right-split wave 4)) ;(paint (corner-split wave 4)) ; ex 2.44 (define (up-split painter n) (if (= n 0) painter (let ((smaller (up-split painter (- n 1)))) (below painter (beside smaller smaller))))) ;(paint (up-split wave 2)) ; high order ;(paint (square-limit wave 0)) ;(paint (flipped-pairs wave)) (define (square-of-four tl tr bl br) (lambda (painter) (let ((top (beside (tl painter) (tr painter))) (bottom (beside (bl painter) (br painter)))) (below bottom top)))) (define (flipped-pairs painter) (let ((combine4 (square-of-four identity flip-vert identity flip-vert))) (combine4 painter))) ;(paint (flipped-pairs wave)) (define (square-limit painter n) (let ((combine4 (square-of-four flip-horiz identity rotate180 flip-vert))) (combine4 (corner-split painter n)))) ;(paint (square-limit wave 0)) ; ex 2.45 (define (split first second) (lambda (painter n) (define (split-inner painter n) (if (= n 0) painter (let ((smaller (split-inner painter (-n 1)))) (first painter (second painter painter))))) (split-inner painter n))) (define right-split2 (split beside below)) (define up-split2 (split below beside)) ;(paint (right-split wave 1)) ;(paint (right-split2 wave 1)) ;(paint (up-split wave 1)) ;(paint (up-split2 wave 1)) ; frame (define (frame-coord-map frame) (lambda (v) (add-vert (origin-frame frame) (add-vert (scale-vert (xcor-vect v) (edge1-frame frame)) (scale-vert (ycor-vect v) (edge2-frame frame)))))) ((frame-coord-map a-frame) (make-vect 0 0)) (origin-frame a-frame) ; ex 2.46 (define (make-vect x y) (cons x y)) (define (xcor-vect v) (car v)) (define (ycor-vect v) (cdr v)) (define (add-vect v1 v2) (make-vect (+ (xcor-vect v1) (xcor-vect v2)) (+ (ycor-vect v1) (ycor-vect v2)))) (define (sub-vect v1 v2) (make-vect (- (xcor-vect v1) (xcor-vect v2)) (- (ycor-vect v1) (ycor-vect v2)))) (define (scale-vect s v) (make-vect (* (xcor-vect v1) s) (* (ycor-vect v1) s))) ; ex 2.47 (define (make-frame origin edge1 edge2) (list origin edge1 edge2)) (define (origin-frame frame) (car frame)) (define (edge1-frame frame) (cadr frame)) (define (edge1-frame frame) (caddr frame)) (define (make-frame origin edge1 edge2) (cons origin (cons edge1 edge2))) (define (origin-frame frame) (car frame)) (define (edge1-frame frame) (cadr frame)) (define (edge2-frame frame) (cddr frame)) ; painter (define (segments->painter segment-list) (lambda (frame) (for-each (lambda (segment) (draw-line ((frame-coord-map frame) (start-segment segment)) ((frmae-coord-map frame) (end-segment segment)))))) segment-list) ; ex 2.48 (define (make-segment v1 v2) (cons v1 v2)) (define (start-segment segment) (car segment)) (define (end-segment segment) (cdr segment)) ; ex 2.49 ; a. painter darwing the boundary of frame (define (boundary->painter frame) ; b. draw two diagonals ; c. draw diamond with 4 midpoints ; d. wave painter ;QuickLisp ;Reddit ;LispM
false
5d7214b21dfb73a625c73133b4004073c668fc07
ac2a3544b88444eabf12b68a9bce08941cd62581
/lib/_prim-boolean#.scm
aa891319529f1d2243a14e846e1396c1eb8f7f35
[ "Apache-2.0", "LGPL-2.1-only" ]
permissive
tomelam/gambit
2fd664cf6ea68859d4549fdda62d31a25b2d6c6f
d60fdeb136b2ed89b75da5bfa8011aa334b29020
refs/heads/master
2020-11-27T06:39:26.718179
2019-12-15T16:56:31
2019-12-15T16:56:31
229,341,552
1
0
Apache-2.0
2019-12-20T21:52:26
2019-12-20T21:52:26
null
UTF-8
Scheme
false
false
454
scm
_prim-boolean#.scm
;;;============================================================================ ;;; File: "_prim-boolean#.scm" ;;; Copyright (c) 1994-2019 by Marc Feeley, All Rights Reserved. ;;;============================================================================ ;;; Boolean operations. (##include "~~lib/_prim-boolean-r4rs#.scm") (##include "~~lib/_prim-boolean-r7rs#.scm") ;;;============================================================================
false
90e17e2485396d27ed44dd71092ac667be5f10e0
703a813a1f802c48f1c4118769434e7ca3383ad7
/src/swish/event-mgr-notify.ss
1b4e3d0759ee510ddc124def199da412a97a202b
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
qzivli/swish
eb3cd2a9c0a4b481935e01899c81168c66ffdee2
1eada0599adf1c4cdd25255b82055e495761b681
refs/heads/master
2020-04-06T21:13:35.456266
2018-11-20T06:35:29
2018-11-20T06:35:29
157,796,773
0
0
MIT
2018-11-16T01:44:31
2018-11-16T01:44:31
null
UTF-8
Scheme
false
false
1,713
ss
event-mgr-notify.ss
;;; Copyright 2018 Beckman Coulter, Inc. ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation ;;; files (the "Software"), to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies ;;; of the Software, and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be ;;; included in all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (library (swish event-mgr-notify) (export event-mgr:notify system-detail ) (import (chezscheme) (swish erlang) (swish meta) ) (define (event-mgr:notify event) (cond [(whereis 'event-mgr) => (lambda (pid) (send pid `#(notify ,event)))] [else (console-event-handler event)]) 'ok) (define-syntax (system-detail x) (syntax-case x () [(_ name [field value] ...) #`(event-mgr:notify (name make #,@(add-if-absent #'timestamp #'(erlang:now) #'([field value] ...))))])) )
true
b792d5edee8853a3c49662aef7cb852e9c12080c
973182ff08776327adc6c70154fc935c19b8fff3
/attic/pcgotchi/code.scm
609f4f41ff2f129840dbb01bbad696e149fcb3b0
[]
no_license
arhuaco/junkcode
cecf067551b76d5d8471c2b7c788064d4705b923
4b5dd1560042ef21e7fa4b1b398de8b172693de7
refs/heads/master
2023-05-25T13:51:19.927997
2023-05-16T11:50:30
2023-05-16T11:50:30
3,691,986
7
3
null
2016-08-09T16:03:20
2012-03-12T04:05:34
C
UTF-8
Scheme
false
false
1,029
scm
code.scm
; Transform a line consisting of a character followed by a space and a number ; into a cons of the character and the number. For example, "a 23" is turned ; into (#\a 23). Note that it receives a stream of characters rather than a ; string. (define (counts-line line) (cons (stream-car line) (stream->number (stream-cddr line)))) ; Given a path for the keystrokes, return a stream with the values of the form ; (char . count), where char is a character and count an integer. (define counts->stream (compose (cut stream-map counts-line <>) stream-cdr stream-lines port->stream open-input-file)) ; Given a path for the keystrokes, return a vector with the counts for each ; character. The characters are indexed according to their byte value ; (obtained through char->integer). (define (counts->vector file) (let ((counts (make-vector 255 0))) (stream-for-each (lambda (data) (vector-set! counts (char->integer (car data)) (cdr data))) (counts->stream file)) counts))
false
d1280a42cd0eaece34c1adde72ca8df7166acf98
bf1c9803ae38f9aad027fbe4569ccc6f85ba63ab
/chapter_3/3.3.Modeling.with.Mutable.Data/ex_3.27.scm
64c59b766dae3f83d4ad6565352b1f735e1d16dc
[]
no_license
mehese/sicp
7fec8750d3b971dd2383c240798dbed339d0345a
611b09280ab2f09cceb2479be98ccc5403428c6c
refs/heads/master
2021-06-12T04:43:27.049197
2021-04-04T22:22:47
2021-04-04T22:23:12
161,924,666
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,254
scm
ex_3.27.scm
#lang sicp (define (make-table) (define (create-empty-node) (list #f #f '() '())) (define (get-key tree) (car tree)) (define (set-root-key! tree key) (set-car! tree key)) (define (set-root-value! tree value) (set-cdr! tree (cons value (cddr tree)))) (define (get-value tree) (cadr tree)) (define (left-node tree) (caddr tree)) (define (right-node tree) (cadddr tree)) (define (set-left-node! tree contents) (set-cdr! tree (list (get-value tree) contents (right-node tree)))) (define (set-right-node! tree contents) (set-cdr! tree (list (get-value tree) (left-node tree) contents))) (let ((local-table (create-empty-node))) (define (lookup key) (define (lookup-rec tree) (let ((root-key (get-key tree))) (cond ((not root-key) root-key) ((eq? root-key key) (cons key (get-value tree))) ((< key root-key) (lookup-rec (left-node tree))) ((> key root-key) (lookup-rec (right-node tree))) (else (error "Got stuck when looking up key" key))))) (lookup-rec local-table)) (define (insert! key value) (define (insert-rec tree) (cond ((not (get-key tree)) (set-root-key! tree key) (set-root-value! tree value) (set-left-node! tree (create-empty-node)) (set-right-node! tree (create-empty-node))) ((eq? (get-key tree) key) (set-root-value! tree value)) ((< key (get-key tree)) (insert-rec (left-node tree))) ((> key (get-key tree)) (insert-rec (right-node tree))) (else (error "Can't decide how to insert this")))) (insert-rec local-table)) (define (dispatch m) (cond ((eq? m 'lookup-proc) lookup) ((eq? m 'insert-proc!) insert!) ((eq? m 'innards) local-table) (else (error "Unknown operation: TABLE" m)))) dispatch)) (define (lookup value table) (let ((query-res ((table 'lookup-proc) value))) (if query-res (cdr query-res) query-res))) (define (insert! key value table) ((table 'insert-proc!) key value)) (define (fib n) (cond ((= n 0) 0) ((= n 1) 1) (else (+ (fib (- n 1)) (fib (- n 2)))))) (define (memoize f) (let ((table (make-table))) (lambda (x) (let ((previously-computed-result (lookup x table))) ;; TIL or doesn't return #t or #f, but the first true value! (or previously-computed-result (let ((result (f x))) (insert! x result table) result)))))) (define memo-fib ;; Tfw decorators aren't implemented in the standard... (memoize (lambda (n) (cond ((= n 0) 0) ((= n 1) 1) (else (+ (memo-fib (- n 1)) (memo-fib (- n 2)))))))) (define t0 (runtime)) (fib 40) (display (list "time to run fib (vanilla)" (- (runtime) t0))) (newline) (set! t0 (runtime)) (memo-fib 40) (display (list "time to run fib with memo" (- (runtime) t0))) (newline) ;; Bonus (set! t0 (runtime)) ((memoize fib) 40) (display (list "time to run (memoize fib)" (- (runtime) t0))) (newline)
false
becfd51fcdf50a08bc43328cd31e7547e4e088db
3ecee09e72582189e8a4a48b3d85447c7927142f
/gx/button-counter.ss
094a67d4016eec7fa33f57a7bef71b5916d50ecb
[ "MIT" ]
permissive
drewc/gx-quasar
6c745b9ec13c60ab6d1af8964a25ff14ceb4549b
17513967f611d46cc2d5a44999c90a7891e5d2d0
refs/heads/main
2023-02-02T17:01:12.011714
2020-12-18T22:18:19
2020-12-18T22:18:19
310,720,698
1
0
null
null
null
null
UTF-8
Scheme
false
false
2,689
ss
button-counter.ss
(import :js/syntax) (def (js#new-plist->jso plist) (def alist []) (let lp ((pl plist)) (if (null? pl) (let ((jso ((lambda () (##inline-host-expression "(() => { foo = (@1@); return g_host2foreign(g_scm2host(foo)); })();" alist))))) ;; (js#console.log jso) jso) (let* ((key (##car pl)) (key (if (or (keyword? key) (symbol? key)) (##symbol->string key) key)) (val (##cadr pl)) (rest (##cddr pl))) (set! alist (##cons (##cons key val) alist)) (lp rest))))) (def (js#jso . plist) (js#new-plist->jso plist)) (def (js#ref obj ref) (##inline-host-expression "((obj, ref) => { if (obj instanceof G_Foreign) { obj = g_foreign2host(obj); } return obj[ref]; })(@1@, @2@);" obj ref)) (def (js#ref-set! obj ref val) (##inline-host-expression "((obj, ref, val) => { if (obj instanceof G_Foreign) { obj = g_foreign2host(obj); } return (obj[ref] = val); })(@1@, @2@, @3@);" obj ref val)) (def (##number->string n) (##inline-host-expression "(() => { n = g_scm2host(@1@) ; return g_host2scm(n.toString()); })();" n)) (defsyntax (js#++ stx) (syntax-case stx () ((macro place number) #'(let ((val place)) (set! place (+ val number)))) ((macro place) #'(macro place 1)))) (def render-button-counter (js#jso name: "ButtonCounter" data: (lambda _ (js#jso count: 0)) render: (js#function (createElement) (createElement "button" (js#jso on: (js#jso click: (lambda _ (js#++ (js#ref js#this count:))))) (##string-append "Scheme Render?: You clicked me " (##number->string (js#ref js#this count:)) " times"))))) (def render-button-counter-js (vue#component name: "ButtonCounter" data: [count: 0] render: #;(lambda (create-element) (create-element "button" "here")) (js#js->foreign (##inline-host-expression "function (createElement) { return createElement( 'button', { on: { click: () => { this.count++ } } }, 'Gerbil Render: You clicked me ' + this.count + ' times.'); }")) )) (##inline-host-statement "exports.lazyButtonCounter = (@1@); exports.renderButtonCounter = g_scm2host(@2@); window.renb = exports.renderButtonCounter; console.log('lazy init!! button!!');" (vue#component name: "button-counter" data: [ count: 0 ] template: '|<button v-on:click="count++"> LAZYYY!!!! You clicked me {{ count }} times.</button>|) render-button-counter)
false
fd0d74b9a01afe6ec639f619b65669913b2bb846
defeada37d39bca09ef76f66f38683754c0a6aa0
/System.Data/mono/data/sql-expressions/substring-function.sls
6816aa0a26b9c27130965a136fa38dad537c0120
[]
no_license
futsuki/ironscheme-port
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
4e7a81b0fbeac9a47440464988e53fb118286c54
refs/heads/master
2016-09-06T17:13:11.462593
2015-09-26T18:20:40
2015-09-26T18:20:40
42,757,369
0
0
null
null
null
null
UTF-8
Scheme
false
false
894
sls
substring-function.sls
(library (mono data sql-expressions substring-function) (export new is? substring-function? get-hash-code eval equals?) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new Mono.Data.SqlExpressions.SubstringFunction a ...))))) (define (is? a) (clr-is Mono.Data.SqlExpressions.SubstringFunction a)) (define (substring-function? a) (clr-is Mono.Data.SqlExpressions.SubstringFunction a)) (define-method-port get-hash-code Mono.Data.SqlExpressions.SubstringFunction GetHashCode (System.Int32)) (define-method-port eval Mono.Data.SqlExpressions.SubstringFunction Eval (System.Object System.Data.DataRow)) (define-method-port equals? Mono.Data.SqlExpressions.SubstringFunction Equals (System.Boolean System.Object)))
true
2bd50ea1f84f642f320e90f10598a726c0424e7b
ac2a3544b88444eabf12b68a9bce08941cd62581
/tests/unit-tests/13-modules/prim_u16vector.scm
7c04501694f790d358a07e83652c783364ede4bb
[ "Apache-2.0", "LGPL-2.1-only" ]
permissive
tomelam/gambit
2fd664cf6ea68859d4549fdda62d31a25b2d6c6f
d60fdeb136b2ed89b75da5bfa8011aa334b29020
refs/heads/master
2020-11-27T06:39:26.718179
2019-12-15T16:56:31
2019-12-15T16:56:31
229,341,552
1
0
Apache-2.0
2019-12-20T21:52:26
2019-12-20T21:52:26
null
UTF-8
Scheme
false
false
1,466
scm
prim_u16vector.scm
(include "#.scm") (check-same-behavior ("" "##" "~~lib/_prim-u16vector#.scm") ;; Gambit (append-u16vectors '(#u16(1) #u16(2) #u16(3))) (list->u16vector '(1 2 3)) (u16vector-length (make-u16vector 5)) (make-u16vector 5 9) (subu16vector '#u16(1 2 3 4 5) 1 3) (let ((x (u16vector 1 2 3 4 5))) (subu16vector-fill! x 1 3 99) x) (let ((x (u16vector 1 2 3 4)) (y (u16vector 6 7 8 9 0))) (subu16vector-move! x 2 3 y 1) y) (u16vector) (u16vector 1) (u16vector 1 2) (u16vector 1 2 3) (u16vector->list '#u16(1 2 3 4 5)) (u16vector-append) (u16vector-append '#u16(1)) (u16vector-append '#u16(1) '#u16(2)) (u16vector-append '#u16(1) '#u16(2) '#u16(3)) (u16vector-copy '#u16(1 2 3 4 5)) (u16vector-copy '#u16(1 2 3 4 5) 1) (u16vector-copy '#u16(1 2 3 4 5) 1 3) (let ((x (u16vector 1 2 3 4)) (y (u16vector 6 7 8 9 0))) (u16vector-copy! y 1 x) y) (let ((x (u16vector 1 2 3 4)) (y (u16vector 6 7 8 9 0))) (u16vector-copy! y 1 x 2) y) (let ((x (u16vector 1 2 3 4)) (y (u16vector 6 7 8 9 0))) (u16vector-copy! y 1 x 2 3) y) (let ((x (u16vector 1 2 3 4 5))) (u16vector-fill! x 99) x) (let ((x (u16vector 1 2 3 4 5))) (u16vector-fill! x 99 1) x) (let ((x (u16vector 1 2 3 4 5))) (u16vector-fill! x 99 1 3) x) (u16vector-length '#u16(1 2 3 4 5)) (u16vector-ref '#u16(1 2 3 4 5) 2) (u16vector-set '#u16(1 2 3 4 5) 2 99) (let ((x (u16vector 1 2 3 4 5))) (u16vector-set! x 2 99) x) (let ((x (u16vector 1 2 3 4 5))) (u16vector-shrink! x 3) x) (u16vector? '#u16(1 2 3)) (u16vector? 123) )
false
2fa59912855420cc71a8621e5587e848030d9b51
7e15b782f874bcc4192c668a12db901081a9248e
/ty-scheme/common/utils.scm
2a8c85ecc38711b098a16e6b1917b7dd3192540c
[]
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
Scheme
false
false
842
scm
utils.scm
; just follow the suggestion here: ; http://stackoverflow.com/questions/15552057/is-it-possible-to-implement-define-macro-in-mit-scheme/ ; we should prefer syntax-rules over define-macro ; so that we'll get clearer codes. (define-syntax define-syntax-rule (syntax-rules () ((define-syntax-rule (name . pattern) template) (define-syntax name (syntax-rules () ((name . pattern) template)))))) ; see: ; http://www.ps.uni-saarland.de/courses/info-i/scheme/doc/refman/refman_11.html#IDX1288 ; in mit-scheme, `gensym` is called `generate-uninterned-symbol` (define gensym generate-uninterned-symbol) (define call/cc call-with-current-continuation) (define out (lambda items (map (lambda (x) (display x) (newline)) items))) ; use newline to finish the line "loading XXX ..." (newline)
true
00aae3716d9722e3acff9025f17f4ae95a9f5186
d074b9a2169d667227f0642c76d332c6d517f1ba
/sicp/ch_2/exercise.2.26.scm
72b7c03b6097fcaeec8baafc58d1b51f21cec8a6
[]
no_license
zenspider/schemers
4d0390553dda5f46bd486d146ad5eac0ba74cbb4
2939ca553ac79013a4c3aaaec812c1bad3933b16
refs/heads/master
2020-12-02T18:27:37.261206
2019-07-14T15:27:42
2019-07-14T15:27:42
26,163,837
7
0
null
null
null
null
UTF-8
Scheme
false
false
478
scm
exercise.2.26.scm
#lang racket/base (require "../lib/test.rkt") ;; Exercise 2.26. ;; Suppose we define x and y to be two lists: (define x (list 1 2 3)) (define y (list 4 5 6)) ;; What result is printed by the interpreter in response to ;; evaluating each of the following expressions: ;; ;; (append x y) ;; ;; (cons x y) ;; ;; (list x y) (assert-equal '(1 2 3 4 5 6) (append x y)) (assert-equal '((1 2 3) 4 5 6) (cons x y)) (assert-equal '((1 2 3) (4 5 6)) (list x y))
false
8cfd60dc4cf1e5c968071a670790d4a6d14fdd3b
defeada37d39bca09ef76f66f38683754c0a6aa0
/System/system/security/cryptography/asn-encoded-data.sls
d4dd110a43e70e0a8062fa38baa473ee1434269a
[]
no_license
futsuki/ironscheme-port
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
4e7a81b0fbeac9a47440464988e53fb118286c54
refs/heads/master
2016-09-06T17:13:11.462593
2015-09-26T18:20:40
2015-09-26T18:20:40
42,757,369
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,314
sls
asn-encoded-data.sls
(library (system security cryptography asn-encoded-data) (export new is? asn-encoded-data? format copy-from oid-get oid-set! oid-update! raw-data-get raw-data-set! raw-data-update!) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Security.Cryptography.AsnEncodedData a ...))))) (define (is? a) (clr-is System.Security.Cryptography.AsnEncodedData a)) (define (asn-encoded-data? a) (clr-is System.Security.Cryptography.AsnEncodedData a)) (define-method-port format System.Security.Cryptography.AsnEncodedData Format (System.String System.Boolean)) (define-method-port copy-from System.Security.Cryptography.AsnEncodedData CopyFrom (System.Void System.Security.Cryptography.AsnEncodedData)) (define-field-port oid-get oid-set! oid-update! (property:) System.Security.Cryptography.AsnEncodedData Oid System.Security.Cryptography.Oid) (define-field-port raw-data-get raw-data-set! raw-data-update! (property:) System.Security.Cryptography.AsnEncodedData RawData System.Byte[]))
true
25c2d164287218dde2659a5ec99420488fb7138f
14fc569de02b02e2132841c41bfafde8312521f0
/temp.scm
a73a1d08ff4272fc5af8034465efbfab9a2b4636
[]
no_license
Zhuxy/scheme-learning
a3f8e78214c4e94e083a283ae29b6848e0e0f296
4763ad2f58a70895a2f24065d6e038fe95945180
refs/heads/master
2022-03-29T11:08:31.352131
2020-01-14T08:33:56
2020-01-14T08:33:56
112,172,049
0
0
null
null
null
null
UTF-8
Scheme
false
false
220
scm
temp.scm
(define (add-it lst) (if (null? (cdr lst)) lst (append (list (car lst) '+) (add-it (cdr lst))))) (display (add-it '(1 2 3 4))) ;(display (add-it (cdr '(1 2)))) ;(display (append (list (car '(1 2)) '+) '(2)))
false
cc165fb46d8814e537b2fc4c1fcf449b439283fe
acc632afe0d8d8b94b781beb1442bbf3b1488d22
/deps/sdl2/lib/shared/types.scm
69d9715eb6c9b03b41b3865e424a7c91514455db
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
kdltr/life-is-so-pretty
6cc6e6c6e590dda30c40fdbfd42a5a3a23644794
5edccf86702a543d78f8c7e0f6ae544a1b9870cd
refs/heads/master
2021-01-20T21:12:00.963219
2016-05-13T12:19:02
2016-05-13T12:19:02
61,128,206
1
0
null
null
null
null
UTF-8
Scheme
false
false
4,445
scm
types.scm
;; ;; chicken-sdl2: CHICKEN Scheme bindings to Simple DirectMedia Layer 2 ;; ;; Copyright ยฉ 2013, 2015-2016 John Croisant. ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; ;; - Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; ;; - Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in ;; the documentation and/or other materials provided with the ;; distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS ;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ;; COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ;; HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ;; STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED ;; OF THE POSSIBILITY OF SUCH DAMAGE. ;;; This file defines type aliases, so that procedure type ;;; declarations will be simpler. ;;; Strict definition. Only allows record types. ;;; This is good for return types, or argument types when you want to ;;; be strict. (define-type sdl2:audio-cvt (struct sdl2:audio-cvt)) (define-type sdl2:audio-spec (struct sdl2:audio-spec)) (define-type sdl2:color (struct sdl2:color)) (define-type sdl2:cursor (struct sdl2:cursor)) (define-type sdl2:display-mode (struct sdl2:display-mode)) (define-type sdl2:finger (struct sdl2:finger)) (define-type sdl2:gl-context (struct sdl2:gl-context)) (define-type sdl2:joystick (struct sdl2:joystick)) (define-type sdl2:joystick-guid (struct sdl2:joystick-guid)) (define-type sdl2:palette (struct sdl2:palette)) (define-type sdl2:pixel-format (struct sdl2:pixel-format)) (define-type sdl2:point (struct sdl2:point)) (define-type sdl2:rect (struct sdl2:rect)) (define-type sdl2:renderer (struct sdl2:renderer)) (define-type sdl2:renderer-info (struct sdl2:renderer-info)) (define-type sdl2:surface (struct sdl2:surface)) (define-type sdl2:texture (struct sdl2:texture)) (define-type sdl2:window (struct sdl2:window)) (define-type sdl2:event (struct sdl2:event)) (define-type sdl2:keysym (struct sdl2:keysym)) ;;; Loose definition. Also allows raw pointers or locatives. ;;; This is good for argument types, but not return types. (define-type sdl2:audio-cvt* (or pointer locative sdl2:audio-cvt)) (define-type sdl2:audio-spec* (or pointer locative sdl2:audio-spec)) (define-type sdl2:color* (or pointer locative sdl2:color)) (define-type sdl2:cursor* (or pointer locative sdl2:cursor)) (define-type sdl2:display-mode* (or pointer locative sdl2:display-mode)) (define-type sdl2:finger* (or pointer locative sdl2:finger)) (define-type sdl2:gl-context* (or pointer locative sdl2:gl-context)) (define-type sdl2:joystick* (or pointer locative sdl2:joystick)) (define-type sdl2:joystick-guid* (or pointer locative sdl2:joystick-guid)) (define-type sdl2:palette* (or pointer locative sdl2:palette)) (define-type sdl2:pixel-format* (or pointer locative sdl2:pixel-format)) (define-type sdl2:point* (or pointer locative sdl2:point)) (define-type sdl2:rect* (or pointer locative sdl2:rect)) (define-type sdl2:renderer* (or pointer locative sdl2:renderer)) (define-type sdl2:renderer-info* (or pointer locative sdl2:renderer-info)) (define-type sdl2:surface* (or pointer locative sdl2:surface)) (define-type sdl2:texture* (or pointer locative sdl2:texture)) (define-type sdl2:window* (or pointer locative sdl2:window)) (define-type sdl2:event* (or pointer locative sdl2:event)) (define-type sdl2:keysym* (or pointer locative sdl2:keysym)) ;;; Other types (define-type enum (or fixnum symbol)) (define-type enum-list (or fixnum (list-of symbol)))
false
effb34b979ae3afdb3b78723c13dad55507b2c08
d95b5e76e17f5e87d636e5f408a4b0045d8dd446
/pixel.scm
5498b9bbd5f011d83ee494727e01670a8d016b27
[]
no_license
kdltr/butine
1bf757253ff4ff2066ad310b2eb37815c3cc2294
b688035b34c62526cc1734d853fbb7f6f7f8e8db
refs/heads/master
2022-04-04T07:00:32.672716
2018-04-26T11:46:41
2018-04-26T11:46:41
113,752,285
1
0
null
null
null
null
UTF-8
Scheme
false
false
1,201
scm
pixel.scm
(use (prefix sdl2 sdl2:) cairo cairo.image) (define ww 32) (define wh 32) (sdl2:set-hint! 'render-scale-quality "0") (sdl2:set-main-ready!) (sdl2:init! '(video)) (define window (sdl2:create-window! "Re-ception" 0 0 1024 1024)) (define renderer (sdl2:create-renderer! window -1 '(accelerated))) (set! (sdl2:render-logical-size renderer) (list ww wh)) (define s (image-surface-create +format-rgb24+ ww wh)) (define c (create s)) (set-antialias! c +antialias-none+) (define t (sdl2:create-texture renderer 'rgb888 'streaming ww wh)) (define (update-texture! t s) (surface-flush! s) (sdl2:update-texture-raw! t #f (image-surface-get-data s) (image-surface-get-stride s))) (define (draw-frame) (set-source-rgb! c 0 0 0) (paint! c) (save! c) (translate! c (+ (/ ww 2) (* 8 (sin (/ now 1000)))) (+ (/ wh 2) (* 8 (cos (/ now 1000))))) (rotate! c (/ now 250)) (rectangle! c -4 -4 8 8) (set-source-rgb! c 1 0 0) (fill! c) (restore! c)) (define (main-loop) (set! now (sdl2:get-ticks)) (draw-frame) (update-texture! t s) (sdl2:render-clear! renderer) (sdl2:render-copy! renderer t) (sdl2:render-present! renderer) (main-loop)) (main-loop)
false
4a1d9580c519a4894192b3515ff7ed0f0fc0c31b
f7dc6abdd30bf5623624073ffe63027bb07dc7d8
/eggs/hyde/hyde-atom.import.scm
487274da1c7ddc63775b868a4523c938bb8926fd
[]
no_license
kobapan/scheme-chicken-hyde
9539bd0cb4e9e1b3775e89e3f042ce4131a485a5
2b0d7a7d6f213646d4736a123d62f6247c04d096
refs/heads/main
2023-04-30T01:10:31.839459
2021-05-18T11:40:19
2021-05-18T11:40:19
316,645,212
0
0
null
null
null
null
UTF-8
Scheme
false
false
280
scm
hyde-atom.import.scm
;;;; hyde-atom.import.scm - GENERATED BY CHICKEN 4.13.0 -*- Scheme -*- (eval '(import scheme chicken hyde atom rfc3339 posix extras srfi-1)) (##sys#register-compiled-module 'hyde-atom (list) '((translate-atom . hyde-atom#translate-atom)) (list) (list)) ;; END OF FILE
false
7039808f9f7a2fdbbf17616760ba6ddd8bf014d9
c693dbc183fdf13b8eeab4590b91bb6cac786a22
/scheme/sum-integers.scm
0edd7292fc7411302fd953fa15eb1085df79ed00
[]
no_license
qianyan/functional-programming
4600a11400176978244f7aed386718614428fd13
34ba5010f9bf68c1ef4fa41ce9e6fdb9fe5a10b5
refs/heads/master
2016-09-01T21:09:32.389073
2015-08-14T07:58:59
2015-08-14T07:58:59
26,963,148
0
0
null
null
null
null
UTF-8
Scheme
false
false
524
scm
sum-integers.scm
(define (sum-integers a b) (if (> a b) 0 (+ a (sum-integers (+ a 1) b)))) (define (sum term a next b) (if (> a b) 0 (+ (term a) (sum term (next a) next b)))) (define (inc n) (+ n 1)) (define (cube n) (* n n n)) (define (sum-cubes a b) (sum cube a inc b)) ;=> always equals itself (define (identity x) x) (define (sum-integers-alias a b) (sum identity a inc b)) ;intergral (define (intergral f a b dx) (define (add-dx x) (+ x dx)) (* (sum f (+ a (/ dx 2.0)) add-dx b) dx))
false
a0419f6f21cad16c582e60b22872592015c66715
4b5dddfd00099e79cff58fcc05465b2243161094
/chapter_5/fact-machine.scm
01784cce626e11f8ffbae88808ce39f40fc2a0cf
[ "MIT" ]
permissive
hjcapple/reading-sicp
c9b4ef99d75cc85b3758c269b246328122964edc
f54d54e4fc1448a8c52f0e4e07a7ff7356fc0bf0
refs/heads/master
2023-05-27T08:34:05.882703
2023-05-14T04:33:04
2023-05-14T04:33:04
198,552,668
269
41
MIT
2022-12-20T10:08:59
2019-07-24T03:37:47
Scheme
UTF-8
Scheme
false
false
1,199
scm
fact-machine.scm
#lang sicp ;; P356 - [้€’ๅฝ’็š„้˜ถไน˜ๆœบๅ™จ] (#%require "ch5-regsim.scm") (define fact-machine (make-machine '(continue n val) (list (list '= =) (list '- -) (list '* *) ) '( (assign continue (label fact-done)) ; set up final return address fact-loop (test (op =) (reg n) (const 1)) (branch (label base-case)) ;; Set up for the recursive call by saving n and continue. ;; Set up continue so that the computation will continue ;; at after-fact when the subroutine returns. (save continue) (save n) (assign n (op -) (reg n) (const 1)) (assign continue (label after-fact)) (goto (label fact-loop)) after-fact (restore n) (restore continue) (assign val (op *) (reg n) (reg val)) ; val now contains n(n - 1)! (goto (reg continue)) ; return to caller base-case (assign val (const 1)) ; base case: 1! = 1 (goto (reg continue)) ; return to caller fact-done ))) (set-register-contents! fact-machine 'n 10) (start fact-machine) (get-register-contents fact-machine 'val)
false
9ee3791d97a8de333939fa63077224a1e5a33b83
6759550fc33a498102bb62413d4b89d0868983a1
/lib/kirjasto/threading.scm
85a9767e5215639b9eab1f4bdcf2229290bee2a2
[]
no_license
mytoh/kirjasto
96140f507bc89eb85c0a104d6f48b5c05b305925
68fd7bedf34dd1abbed88a30f9f8d86faba38cc6
refs/heads/master
2016-09-10T16:38:20.480131
2014-10-06T20:54:26
2014-10-06T20:54:26
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,350
scm
threading.scm
;; author "Moritz Heidkamp" (define-library (kirjasto threading) (export doto -> ->* ->> ->>*) (import (scheme base)) (begin (define-syntax doto (syntax-rules () ((_ x) x) ((_ x (fn args ...) ...) (let ((val x)) (fn val args ...) ... val)))) (define-syntax -> (syntax-rules () ((_ x (f v ...) f2 ...) (-> (f x v ...) f2 ...)) ((_ x f f2 ...) (-> (f x) f2 ...)) ((_ x (f v ...)) (-> (f x v ...))) ((_ x f) (f x)) ((_ x) x))) (define-syntax ->> (syntax-rules () ((_ x (f v ...) rest ...) (->> (f v ... x) rest ...)) ((_ x f rest ...) (->> (f x) rest ...)) ((_ x (f v ...)) (->> (f v ... x))) ((_ x f) (f x)) ((_ x) x))) (define-syntax ->* (syntax-rules () ((_ x (y z ...) rest ...) (->* (receive args x (apply y (append args (list z ...)))) rest ...)) ((_ x) x))) (define-syntax ->>* (syntax-rules () ((_ x) x) ((_ x (y z ...) rest ...) (->>* (receive args x (apply y (append (list z ...) args))) rest ...)))) ))
true
e5772d6609023f6c7edc47cf754886862d001be9
6675ce914fe8f81480bad42f677362f43647f78f
/fronter.scm
620947612c9fc587fc98997cbd3538291a14ce22
[]
no_license
tiancaiamao/yasfs
9ef06398e859fe47c585b17c4535110279ebe0c0
7e8fdb953d1b9bb9bf6ac809464a30ce9226ec18
refs/heads/master
2023-05-13T19:33:00.382963
2023-04-27T08:41:29
2023-04-27T08:41:29
5,788,134
14
5
null
null
null
null
UTF-8
Scheme
false
false
7,972
scm
fronter.scm
(define *env* '()) (define env-init-compiletime '()) (define env-global-compiletime '()) (define env-global-runtime (make-vector 200 '())) (define (init-core-form) (define (add-syntax name) (let ((value `(,name predefined syntax . ,name))) (set! env-init-compiletime (cons value env-init-compiletime)))) (add-syntax 'begin) (add-syntax 'if) (add-syntax 'set!) (add-syntax 'lambda) (add-syntax 'quote)) (define (init-primitive-form) (define (add-primitive name address arity) (let ((value `(,name predefined primitive ,address . ,arity))) (set! env-init-compiletime (cons value env-init-compiletime)))) (add-primitive 'cons cons 2) (add-primitive '+ + 2)) (define (init) (init-core-form) (init-primitive-form)) (define (global-define name value) (let ((index (length env-global-compiletime))) (set! env-global-compiletime (cons (cons name (cons 'global index)) env-global-compiletime)) (vector-set! env-global-runtime index value))) (global-define 'test 35) (define (CONSTANT v) (lambda () v)) (define (PREDEFINED v) (lambda () v)) (define (GLOBAL-REF i) (lambda () (vector-ref env-global-runtime i))) (define (ALTERNATIVE v1 v2 v3) (lambda () (if (v1) (v2) (v3)))) (define (SEQUENCE v1 v2) (lambda () (v1) (v2))) (define (GLOBAL-SET i v) (lambda () (vector-set! env-global-runtime i (v)))) (define (SHALLOW-ARGUMENT-REF j) (lambda () (let ((vec (car *env*))) (vector-ref vec j)))) (define (SHALLOW-ARGUMENT-SET j value) (lambda () (let ((vec (car *env*))) (vector-set! vec j (value))))) (define (DEEP-ARGUMENT-SET i j value) (define (deep-update frame i j v) (if (= i 0) (vector-set! (car frame) j v) (deep-update (cdr frame) (- i 1) j v))) (lambda () (deep-update *env* i j (value)))) (define (DEEP-ARGUMENT-REF i j) (define (deep-fetch frame i j v) (if (= i 0) (vector-ref (car frame) j) (deep-fetch (cdr frame) (- i 1) j))) (lambda () (deep-fetch *env* i j))) (define (CALL0 address) (lambda () (address)) ) (define (CALL1 address m1) (lambda () (address (m1))) ) (define (CALL2 address m1 m2) (lambda () (let ((v1 (m1))) (address v1 (m2)) )) ) (define (CALL3 address m1 m2 m3) (lambda () (let* ((v1 (m1)) (v2 (m2)) ) (address v1 v2 (m3)) )) ) ;;ๅ‡ฝๆ•ฐ่ฐƒ็”จ่ง„ๅˆ™๏ผš็”ฑ่ฐƒ็”จ่€…ๅ‡†ๅค‡ๅฅฝๅ‚ๆ•ฐใ€‚็”ฑ่ขซ่ฐƒๅ‡ฝๆ•ฐๅˆ‡ๆข็Žฏๅขƒ็ป‘ๅฎšใ€‚็”ฑ่ฐƒ็”จ่€…ๆขๅค็Žฏๅขƒ (define (CLOSURE code arity) (lambda () (define (function frame) (if (= arity (vector-length frame)) (begin (set! *env* (cons frame *env*)) (code)) (runtime-wrong "Incorrect number of arity"))) (cons function *env*))) (define (invoke closure arg) (let ((function (car closure)) (frame (cdr closure))) (function arg))) (define (TAIL-CALL op arg) (lambda () (invoke (op) (arg)))) (define (CALL op arg) (lambda () (let ((save *env*)) (let ((result (invoke (op) (arg)))) (set! *env* save) result)))) (define (STORE-ARGUMENT m m* pos) (lambda () (let ((v (m)) (vec (m*))) (vector-set! vec pos v) vec))) (define (ALLOCATE-FRAME size) (lambda () (make-vector size))) (define (local-variable? env i name) (and (pair? env) (let scan ((names (car env)) (j 0)) (cond ((pair? names) (if (eqv? (car names) name) `(local ,i . ,j) (scan (cdr names) (+ j 1)))) ((null? names) (local-variable? (cdr env) (+ i 1) name)) ((eqv? name names) `(local ,i . ,j)))))) (define (global-variable? list name) (let ((find (assv name list))) (and find (cdr find)))) (define (compute-kind env name) (or (local-variable? env 0 name) (global-variable? env-global-compiletime name) (global-variable? env-init-compiletime name))) (define (compile-wrong msg) (display msg)) (define (runtime-wrong msg) (display msg)) (define (compile-variable form env tail?) (let ((kind (compute-kind env form))) (if kind (case (car kind) ((local) (let ((i (cadr kind)) (j (cddr kind))) (if (= i 0) (SHALLOW-ARGUMENT-REF j) (DEEP-ARGUMENT-REF i j)))) ((global) (let ((i (cdr kind))) (GLOBAL-REF i))) ((predefined) (let ((v (cdr kind))) (PREDEFINED v)))) (compile-wrong "No such variable")))) (define (compile-quote v) (CONSTANT v)) (define (compile-if etest etrue efalse env tail?) (let ((v1 (compile etest env #f)) (v2 (compile etrue env tail?)) (v3 (compile efalse env tail?))) (ALTERNATIVE v1 v2 v3))) (define (compile-begin form env tail?) (if (pair? form) (if (pair? (cdr form)) (let ((v1 (compile (car form) env #f)) (v2 (compile-begin (cdr form) env tail?))) (SEQUENCE v1 v2)) (compile (car form) env tail?)) (CONSTANT (begin)))) (define (compile-set name form env tail?) (let ((value (compile form env #f)) (kind (compute-kind env name))) (if kind (case (car kind) ((local) (let ((i (cadr kind)) (j (cddr kind))) (if (= i 0) (SHALLOW-ARGUMENT-SET j value) (DEEP-ARGUMENT-SET i j value)))) ((global) (GLOBAL-SET (cdr kind) value)) ((predefined) (compile-wrong "Immutable predefined variable"))) (compile-wrong "No such variable")))) (define (extend-env env names) (cons names env)) (define (compile-lambda names body env tail?) (let* ((arity (length names)) (new-env (extend-env env names)) (v (compile-begin body new-env #t))) (if (procedure? v) (CLOSURE v arity) (compile-wrong "Compile lambda error:can't compile body of lambda")))) (define (compile-argument-recurse e e* env size pos tail?) (let ((v (compile e env #f)) (v* (compile-argument e* (- size 1) (+ pos 1) env tail?))) (STORE-ARGUMENT v pos v*))) (define (compile-argument arg pos env tail?) (if (pair? arg) (let ((v (compile (car arg) env #f)) (v* (compile-argument (cdr arg) (+ pos 1) env tail?))) (STORE-ARGUMENT v v* pos)) (ALLOCATE-FRAME pos))) (define (compile-regular-application first other env tail?) (let ((op (compile first env tail?)) (arg (compile-argument other 0 env tail?))) (if tail? (TAIL-CALL op arg) (CALL op arg)))) (define (compile-primitive-call info other env tail?) (let ((address (car info)) (arity (cdr info))) (if (= arity (length other)) (case arity ((0) (CALL0 address)) ((1) (let ((m1 (compile (car other) env #f))) (CALL1 address m1))) ((2) (let ((m1 (compile (car other) env #f)) (m2 (compile (cadr other) env #f))) (CALL2 address m1 m2))) ((3) (let ((m1 (compile (car other) env #f)) (m2 (compile (cadr other) env #f)) (m3 (compile (caddr other) env #f))) (CALL3 address m1 m2 m3))) (else (compile-wrong "support atmost 3 arity privitive now!"))) (compile-wrong "Incorrect arity for primitive")))) (define (compile-application first other env tail?) (cond ((symbol? first) (let ((kind (compute-kind env first))) (or (and (pair? kind) (eq? (car kind) 'predefined) (let ((desc (cdr kind))) (case (car desc) ((syntax) (case (cdr desc) ((quote) (compile-quote (car other))) ((if) (compile-if (car other) (cadr other) (caddr other) env tail?)) ((begin) (compile-begin other env tail?)) ((set!) (compile-set (car other) (cadr other) env tail?)) ((lambda) (compile-lambda (car other) (cdr other) env tail?)))) ;; ((define) (compile-define other)))) ((primitive) (compile-primitive-call (cdr desc) other env tail?)) ((macro) '())))) (compile-regular-application first other env tail?)))) ;; ((and (pair? op) (eq? (car op) 'lambda)) ;; (compile-closed-application op arg env tail?)) (else (compile-regular-application first other env tail?)))) (define (compile form env tail?) (if (pair? form) (compile-application (car form) (cdr form) env tail?) (if (symbol? form) (compile-variable form env tail?) (CONSTANT form))))
false
f9c8bf201643fe41b0d33a0ad5e676dc6e493a46
c42881403649d482457c3629e8473ca575e9b27b
/test/nqueen.scm
81e6f0f2b702649fbc0d7269df18656b809d9b0f
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
kahua/Kahua
9bb11e93effc5e3b6f696fff12079044239f5c26
7ed95a4f64d1b98564a6148d2ee1758dbfa4f309
refs/heads/master
2022-09-29T11:45:11.787420
2022-08-26T06:30:15
2022-08-26T06:30:15
4,110,786
19
5
null
2015-02-22T00:23:06
2012-04-23T08:02:03
Scheme
UTF-8
Scheme
false
false
6,313
scm
nqueen.scm
;; -*- coding: utf-8 ; mode: scheme -*- ;; test nqueen script. ;; this test isn't for modules, but the actual scripts. (use srfi-2) (use srfi-11) (use gauche.test) (use gauche.process) (use gauche.net) (use rfc.uri) (use util.list) (use text.tree) (use sxml.ssax) (use sxml.sxpath) (use file.util) (use kahua.test.xml) (use kahua.test.worker) (use kahua.persistence) (use kahua.user) (use kahua.config) (test-start "nqueen test scripts") (define *site* "_site") (sys-system #`"rm -rf ,|*site*|") (kahua-site-create *site*) (copy-file "../plugins/allow-module.scm" #`",|*site*|/plugins/allow-module.scm") (kahua-common-init *site* #f) ;;------------------------------------------------------------ ;; Run nqueen (test-section "kahua-server nqueen.kahua") (with-worker (w `("gosh" "-I../src" "-I../examples" "../src/kahua-server" "-S" ,*site* "../examples/nqueen/nqueen.kahua")) (test* "run nqueen.kahua" #t (worker-running? w)) (test* "initial screen" '(*TOP* (a (@ (href ?&)) "8 queens") (a ?@ "12 queens")) (call-worker/gsid->sxml w '() '() '(// a)) (make-match&pick w)) (test* "8 queen (1)" '(*TOP* (li "(3 0 4 7 5 2 6 1)") (li "(2 5 3 0 7 4 6 1)") (li "(4 6 3 0 2 7 5 1)") (li "(4 2 7 3 6 0 5 1)") (li "(2 5 7 0 3 6 4 1)") (li "(3 5 7 2 0 6 4 1)") (li "(4 6 0 2 7 5 3 1)") (li "(2 4 1 7 5 3 6 0)") (li "(2 5 3 1 7 4 6 0)") (li "(4 1 3 6 2 7 5 0)") (li "(3 1 6 2 5 7 4 0)") (a (@ (href ?&)) "next items") (a ?@ "restart")) (call-worker/gsid->sxml w '() '() '(// (or@ a li))) (make-match&pick w)) (test* "8 queen (2)" '(*TOP* (li "(4 7 3 0 6 1 5 2)") (li "(3 7 0 4 6 1 5 2)") (li "(3 6 0 7 4 1 5 2)") (li "(0 6 4 7 1 3 5 2)") (li "(1 6 4 7 0 3 5 2)") (li "(5 1 6 0 3 7 4 2)") (li "(5 7 1 3 0 6 4 2)") (li "(5 3 6 0 7 1 4 2)") (li "(0 6 3 5 7 1 4 2)") (li "(5 3 1 7 4 6 0 2)") (li "(3 6 4 2 0 5 7 1)") (a (@ (href ?&)) "next items") (a ?@ "restart")) (call-worker/gsid->sxml w '() '() '(// (or@ a li))) (make-match&pick w)) ) ; (test-end) ;;------------------------------------------------------------ ;; Run nqueen (test-section "kahua-server lazy-nqueen.kahua") (with-worker (w `("gosh" "-I../src" "-I../examples" "../src/kahua-server" "-S" ,*site* "../examples/lazy-nqueen/lazy-nqueen.kahua")) (test* "run lazy-nqueen.kahua" #t (worker-running? w)) (test* "initial screen" '(html (head (title ?*)) (body ?@ (h1 ?*) (a ?@ "6-Queens") ?* (a ?@ "7-Queens") ?* (a (@ (href ?&)) "8-Queens") ?* (a ?@ "9-Queens") ?* (a ?@ "10-Queens") ?* (a ?@ "11-Queens") ?* (a ?@ "12-Queens"))) (call-worker/gsid w '() '() (lambda (h b) (tree->string b))) (make-match&pick w)) (test* "8 queen (1)" '(html (head (title ?*)) (body ?@ (h1 ?*) (p ?* (table ?@ (tr (td "โ—‹")(td "โ—‹")(td "โ—‹")(td "โ—") (td "โ—‹")(td "โ—‹")(td "โ—‹")(td "โ—‹")) (tr (td "โ—‹")(td "โ—")(td "โ—‹")(td "โ—‹") (td "โ—‹")(td "โ—‹")(td "โ—‹")(td "โ—‹")) (tr (td "โ—‹")(td "โ—‹")(td "โ—‹")(td "โ—‹") (td "โ—‹")(td "โ—‹")(td "โ—")(td "โ—‹")) (tr (td "โ—‹")(td "โ—‹")(td "โ—")(td "โ—‹") (td "โ—‹")(td "โ—‹")(td "โ—‹")(td "โ—‹")) (tr (td "โ—‹")(td "โ—‹")(td "โ—‹")(td "โ—‹") (td "โ—‹")(td "โ—")(td "โ—‹")(td "โ—‹")) (tr (td "โ—‹")(td "โ—‹")(td "โ—‹")(td "โ—‹") (td "โ—‹")(td "โ—‹")(td "โ—‹")(td "โ—")) (tr (td "โ—‹")(td "โ—‹")(td "โ—‹")(td "โ—‹") (td "โ—")(td "โ—‹")(td "โ—‹")(td "โ—‹")) (tr (td "โ—")(td "โ—‹")(td "โ—‹")(td "โ—‹") (td "โ—‹")(td "โ—‹")(td "โ—‹")(td "โ—‹")) ) (a (@ (href ?&)) "Next") ?*))) (call-worker/gsid w '() '() (lambda (h b) (tree->string b))) (make-match&pick w)) (test* "8 queen (1)" '(html (head (title ?*)) (body ?@ (h1 ?*) (p "2ๅ€‹็›ฎใฎ่งฃ" (table ?@ (tr (td "โ—‹")(td "โ—‹")(td "โ—‹")(td "โ—‹") (td "โ—")(td "โ—‹")(td "โ—‹")(td "โ—‹")) (tr (td "โ—‹")(td "โ—")(td "โ—‹")(td "โ—‹") (td "โ—‹")(td "โ—‹")(td "โ—‹")(td "โ—‹")) (tr (td "โ—‹")(td "โ—‹")(td "โ—‹")(td "โ—") (td "โ—‹")(td "โ—‹")(td "โ—‹")(td "โ—‹")) (tr (td "โ—‹")(td "โ—‹")(td "โ—‹")(td "โ—‹") (td "โ—‹")(td "โ—‹")(td "โ—")(td "โ—‹")) (tr (td "โ—‹")(td "โ—‹")(td "โ—")(td "โ—‹") (td "โ—‹")(td "โ—‹")(td "โ—‹")(td "โ—‹")) (tr (td "โ—‹")(td "โ—‹")(td "โ—‹")(td "โ—‹") (td "โ—‹")(td "โ—‹")(td "โ—‹")(td "โ—")) (tr (td "โ—‹")(td "โ—‹")(td "โ—‹")(td "โ—‹") (td "โ—‹")(td "โ—")(td "โ—‹")(td "โ—‹")) (tr (td "โ—")(td "โ—‹")(td "โ—‹")(td "โ—‹") (td "โ—‹")(td "โ—‹")(td "โ—‹")(td "โ—‹")) ) (a (@ (href ?&)) "Next") ?*))) (call-worker/gsid w '() '() (lambda (h b) (tree->string b))) (make-match&pick w)) ) (test-end)
false
3ca8419c6f2f7af539a4ece2ab744a327206ebed
6bd63be924173b3cf53a903f182e50a1150b60a8
/chapter_1/related/p27-2.scm
8b8cc027b80f0132fe2d4bd13f622ab2c0afe9eb
[]
no_license
lf2013/SICP-answer
d29ee3095f0d018de1d30507e66b12ff890907a5
2712b67edc6df8ccef3156f4ef08a2b58dcfdf81
refs/heads/master
2020-04-06T13:13:51.086818
2019-09-11T11:39:45
2019-09-11T11:39:45
8,695,137
0
1
null
2016-03-17T13:19:21
2013-03-11T02:24:41
Scheme
UTF-8
Scheme
false
false
123
scm
p27-2.scm
(define (pat i j) (cond ((= i 1) 1) ((= j 1) 1) ((= i j) 1) (else (+ (pat (- i 1) j) (pat (- i 1)(- j 1))))))
false
962d784a632391672bb18059353dace1d79f31e5
ffb05b145989e01da075e2a607fb291955251f46
/scheme/experimental/dummy-ctxt.sls
05c2302472ca8831b2210f4c4d95705781d16c7d
[]
no_license
micheles/papers
a5e7f2fa0cf305cd3f8face7c7ecc0db70ce7cc7
be9070f8b7e8192b84a102444b1238266bdc55a0
refs/heads/master
2023-06-07T16:46:46.306040
2018-07-14T04:17:51
2018-07-14T04:17:51
32,264,461
2
0
null
null
null
null
UTF-8
Scheme
false
false
132
sls
dummy-ctxt.sls
#!r6rs (library (experimental dummy-ctxt) (export dummy-ctxt) (import (only (rnrs) define syntax)) (define dummy-ctxt #'here) )
false
28f028f21b10e7830ea79efbeb099209009d8284
b60cb8e39ec090137bef8c31ec9958a8b1c3e8a6
/test/R5RS/scp1-compressed/7.scm
01fe17803161861c7d58df39a1dd7546f23cac0f
[]
no_license
acieroid/scala-am
eff387480d3baaa2f3238a378a6b330212a81042
13ef3befbfc664b77f31f56847c30d60f4ee7dfe
refs/heads/master
2021-01-17T02:21:41.692568
2021-01-15T07:51:20
2021-01-15T07:51:20
28,140,080
32
16
null
2020-04-14T08:53:20
2014-12-17T14:14:02
Scheme
UTF-8
Scheme
false
false
24,116
scm
7.scm
; 7.2 (define (atom? x) (not (pair? x))) (define (depth tree) (cond ((null? tree) 0) ((atom? tree) 0) (else (max (+ 1 (depth (car tree))) (depth (cdr tree)))))) (define (leaf-count tree) (cond ((null? tree) 0) ((atom? tree) 1) (else (+ (leaf-count (car tree)) (leaf-count (cdr tree)))))) (define (depth-and-leaf-count tree) (define make-res cons) (define depth car) (define leaf-count cdr) (cond ((null? tree) (make-res 0 0)) ((atom? tree) (make-res 0 1)) (else (let ((res-car (depth-and-leaf-count (car tree))) (res-cdr (depth-and-leaf-count (cdr tree)))) (make-res (max (+ 1 (depth res-car)) (depth res-cdr)) (+ (leaf-count res-car) (leaf-count res-cdr))))))) (define l '((1 2) ((3 4) 5) (6 7))) (and (= (depth l) 3) (= (leaf-count l) 7) (equal? (depth-and-leaf-count l) (cons 3 7))) ; 7.3 ;(define (atom? x) ; (not (pair? x))) (define (fringe l) (cond ((null? l) '()) ((atom? l) (list l)) (else (append (fringe (car l)) (fringe (cdr l)))))) (equal? (fringe '((1) ((((2)))) (3 (4 5) 6) ((7) 8 9))) '(1 2 3 4 5 6 7 8 9)) ; 7.4 (define (unfringe-1 l) (cond ((null? l) '()) ((null? (cdr l)) (list (car l))) (else (list (car l) (unfringe-1 (cdr l)))))) (define (unfringe-2 l) (define (pair l) (cond ((null? l) '()) ((null? (cdr l)) (list l)) (else (cons (list (car l) (cadr l)) (pair (cddr l)))))) (let loop ((l l)) (if (or (null? l) (null? (cdr l))) l (loop (pair l))))) (and (equal? (unfringe-1 '(1 2 3 4 5 6 7 8 9)) '(1 (2 (3 (4 (5 (6 (7 (8 (9)))))))))) (equal? (unfringe-2 '(1 2 3 4 5 6 7 8 9)) '(((((1 2) (3 4)) ((5 6) (7 8))) (((9))))))) ; 7.5 ;(define (atom? x) ; (not (pair? x))) (define (same-structure? l1 l2) (cond ((and (atom? l1) (atom? l2)) #t) ((or (atom? l1) (atom? l2)) #f) (else (and (same-structure? (car l1) (car l2)) (same-structure? (cdr l1) (cdr l2)))))) (define (same-structure?-or l1 l2) (or (and (atom? l1) (atom? l2)) (and (pair? l1) (pair? l2) (same-structure?-or (car l1) (car l2)) (same-structure?-or (cdr l1) (cdr l2))))) (and (same-structure? '((1 2) ((3 . 4) ((5 6) ((7 8) (9))))) '((a b) ((c . d) ((e f) ((g h) (i)))))) (not (same-structure? '((1 2) ((3 4) ((5 6) ((7 8) (9))))) '((((1 2) (3 4)) ((5 6) (7 8))) 9)))) ; 7.6 ;(define (atom? x) ; (not (pair? x))) (define (deep-combine combiner null-value l) (cond ((null? l) null-value) ((atom? l) l) (else (combiner (deep-combine combiner null-value (car l)) (deep-combine combiner null-value (cdr l)))))) (define (deep-map f l) (cond ((null? l) '()) ((atom? l) (f l)) (else (cons (deep-map f (car l)) (deep-map f (cdr l)))))) (and (= (deep-combine + 0 '((((1 2) (3 4)) ((5 6) (7 8))) 9)) 45) (equal? (deep-map (lambda (x) (* x x)) '((((1 . 2) (3 4)) ((5 6) (7 8))) . 9)) '((((1 . 4) (9 16)) ((25 36) (49 64))) . 81))) ; 7.9 (define boom '((blad (appel . golden)) (blad (appel . granny)) (((appel . golden) blad) blad (appel . cox)))) (define (blad? boom) (eq? boom 'blad)) (define (appel? boom) (and (pair? boom) (eq? (car boom) 'appel))) (define (type appel) (cdr appel)) (define (leafs boom) (cond ((null? boom) 0) ((blad? boom) 1) ((appel? boom) 0) (else (+ (leafs (car boom)) (leafs (cdr boom)))))) (define (all-apples boom) (cond ((null? boom) '()) ((blad? boom) '()) ((appel? boom) (list (type boom))) (else (append (all-apples (car boom)) (all-apples (cdr boom)))))) (define (conditional-append l1 l2) (cond ((null? l1) l2) ((member (car l1) l2)(conditional-append (cdr l1) l2)) (else (cons (car l1)(conditional-append (cdr l1) l2))))) (define (apple-types boom) (cond ((null? boom) '()) ((blad? boom) '()) ((appel? boom) (list (type boom))) (else (conditional-append (apple-types (car boom)) (apple-types (cdr boom)))))) (define (bewerk-boom boom doe-blad doe-appel combiner init) (cond ((null? boom) init) ((blad? boom) (doe-blad boom)) ((appel? boom) (doe-appel boom)) (else (combiner (bewerk-boom (car boom) doe-blad doe-appel combiner init) (bewerk-boom (cdr boom) doe-blad doe-appel combiner init))))) (define (leafs-dmv-bewerk boom) (bewerk-boom boom (lambda (blad) 1) (lambda (appel) 0) + 0)) (define (all-apples-dmv-bewerk boom) (bewerk-boom boom (lambda(blad) '()) (lambda(appel) (list (type appel))) append '())) (define (apple-types-dmv-bewerk boom) (bewerk-boom boom (lambda(blad) '()) (lambda(appel) (list(type appel))) conditional-append '())) (and (= (leafs boom) 4) (equal? (all-apples boom) '(golden granny golden cox)) (equal? (apple-types boom) '(granny golden cox)) (= (leafs-dmv-bewerk boom) 4) (equal? (all-apples-dmv-bewerk boom) '(golden granny golden cox)) (equal? (apple-types-dmv-bewerk boom) '(granny golden cox))) ; 7.11 (define organigram '(directeur (hoofd-verkoop (verkoopsleider-vlaanderen) (verkoopsleider-brussel)) (hoofd-productie (hoofd-inkoop (bediende1) (bediende2) (bediende3)) (hoofd-fakturen)) (hoofd-administratie (hoofd-personeel) (hoofd-boekhouding)))) (define (baas organigram) (car organigram)) (define (sub-organigrammen organigram) (cdr organigram)) (define (hierarchisch? p1 p2 organigram) (define (hierarchisch?-in path organigrammen) (if (null? organigrammen) #f (or (hierarchisch? path (car organigrammen)) (hierarchisch?-in path (cdr organigrammen))))) (define (hierarchisch? path organigram) (cond ((and (eq? p1 (baas organigram)) (member p2 path)) #t) ((and (eq? p2 (baas organigram)) (member p1 path)) #t) (else (hierarchisch?-in (cons (baas organigram) path) (sub-organigrammen organigram))))) (hierarchisch? '() organigram)) (define (collegas p organigram) (define (collegas-in oversten organigrammen) (if (null? organigrammen) #f (or (collegas oversten (car organigrammen)) (collegas-in oversten (cdr organigrammen))))) (define (werknemers-in organigrammen) (if (null? organigrammen) '() (append (werknemers (car organigrammen)) (werknemers-in (cdr organigrammen))))) (define (werknemers organigram) (cons (baas organigram) (werknemers-in (sub-organigrammen organigram)))) (define (collegas oversten organigram) (if (eq? p (baas organigram)) (append oversten (werknemers-in (sub-organigrammen organigram))) (collegas-in (cons (baas organigram) oversten) (sub-organigrammen organigram)))) (collegas '() organigram)) (and (hierarchisch? 'directeur 'verkoopsleider-brussel organigram) (hierarchisch? 'bediende1 'hoofd-productie organigram) (not (hierarchisch? 'hoofd-personeel 'bediende3 organigram)) (equal? (collegas 'hoofd-inkoop organigram) '(hoofd-productie directeur bediende1 bediende2 bediende3))) ; 7.12 ;(define (atom? x) ; (not (pair? x))) ;; (define mijn-vuurwerk '(groen ((blauw (X (blauw (X X)) X X)) ;; (rood ((groen (X X)) X)) ;; X ;; (geel (X X))))) ;; ;; (define (kleur vuurwerk) (car vuurwerk)) ;; (define (takken vuurwerk) (cadr vuurwerk)) ;; (define (low-energy? vuurwerk) (eq? vuurwerk 'X)) ;; ;; (define (tel-knallen vuurwerk) ;; (cond ((null? vuurwerk) 0) ;; ((low-energy? vuurwerk) 0) ;; ((atom? vuurwerk) 1) ;; (else (+ (tel-knallen (car vuurwerk)) ;; (tel-knallen (cdr vuurwerk)))))) ;; ;; (define (tel-low-energies v) ;; (cond ((null? v) 0) ;; ((low-energy? v) 1) ;; ((atom? v) 0) ;; (else (+ (tel-low-energies (car v)) ;; (tel-low-energies (cdr v)))))) ;; ;; (define (tel-einde-in takken een-kleur) ;; (cond ((null? takken) 0) ;; ((low-energy? (car takken)) 0) ;; (else (+ (tel-einde (car takken) een-kleur) ;; (tel-einde-in (cdr takken) een-kleur))))) ;; ;; (define (tel-einde vuurwerk een-kleur) ;; (if (eq? (kleur vuurwerk) een-kleur) ;; (tel-low-energies (takken vuurwerk)) ;; (tel-einde-in (takken vuurwerk) een-kleur))) ;; ;; (define (ster? vuurwerk) ;; (not (member 'X (takken vuurwerk)))) ;; ;; (and (eq? (kleur mijn-vuurwerk) 'groen) ;; (equal? (takken mijn-vuurwerk) ;; '((blauw (X (blauw (X X)) X X)) (rood ((groen (X X)) X)) X (geel (X X)))) ;; (not (low-energy? mijn-vuurwerk)) ;; (low-energy? 'X) ;; (= (tel-knallen mijn-vuurwerk) 6) ;; (= (tel-einde mijn-vuurwerk 'blauw) 5) ;; (not (ster? mijn-vuurwerk))) ; 7.13 (define result '()) (define display2 (lambda (i) (set! result (cons i result)))) (define newline2 (lambda () (set! result (cons 'newline result)))) (define VUBOrganigram '(VUB (academisch (rectoraat) (faculteiten (rechten (bachelor (ba-rechten) (ba-criminologie)) (master (ma-rechten) (ma-criminologie))) (economie) (wetenschappen (bachelor (ba-wiskunde) (ba-fysica) (ba-cw)) (master (ma-wiskunde) (ma-fysica) (ma-cw))))) (administratief (personeel) (financien)))) (define (display-n n d) (if (> n 0)(begin (display2 d)(display-n (- n 1) d)))) (define (print-lijn aantalblanco tekst) (display-n aantalblanco " ") (display2 tekst) (newline2)) (define (label organigram) (car organigram)) (define (takken organigram) (cdr organigram)) (define (organigram-member-in een-label organigrammen) (if (null? organigrammen) #f (or (organigram-member een-label (car organigrammen)) (organigram-member-in een-label (cdr organigrammen))))) (define (organigram-member een-label organigram) (if (eq? een-label (label organigram)) organigram (organigram-member-in een-label (takken organigram)))) (define (print organigram) (define (print diepte organigram) (print-lijn diepte (label organigram)) (for-each (lambda (organigram) (print (+ diepte 1) organigram)) (takken organigram))) (print 0 organigram)) (define (print-vanaf organigram label) (let ((res (organigram-member label organigram))) (if res (print res) #f))) (print-vanaf VUBOrganigram 'rechten) (define (print-tot organigram niveau) (define (print-tot organigram niveau max-niveau) (cond ((<= niveau max-niveau) (print-lijn niveau (label organigram)) (for-each (lambda (organigram) (print-tot organigram (+ niveau 1) max-niveau)) (takken organigram))))) (print-tot organigram 0 niveau)) (print-tot VUBOrganigram 2) (equal? result '(newline financien " " " " newline personeel " " " " newline administratief " " newline faculteiten " " " " newline rectoraat " " " " newline academisch " " newline VUB newline ma-criminologie " " " " newline ma-rechten " " " " newline master " " newline ba-criminologie " " " " newline ba-rechten " " " " newline bachelor " " newline rechten)) ; 7.14 ;(define (atom? x) ; (not (pair? x))) (define (maak-dier naam eigenschappen) (list naam eigenschappen)) (define (naam dier) (car dier)) (define (eigenschappen dier) (cadr dier)) (define (dier? dier) (and (pair? dier) (atom? (naam dier)) (pair? (eigenschappen dier)))) (define (maak-boom knoop deelbomen) (list knoop deelbomen)) (define (knoop boom) (car boom)) (define (deelbomen boom) (cadr boom)) (define (leeg? boom) (null? boom)) ;(define (knoop? boom) (dier? boom)) (define classificatieboom (maak-boom (maak-dier 'dier '(kan-ademen kan-bewegen)) (list (maak-boom (maak-dier 'vis '(kan-zwemmen heeft-schubben heeft-vinnen)) (list (maak-dier 'ballonvis '(kan-zwellen is-geel)))) (maak-boom (maak-dier 'landdier '(heeft-huid kan-lopen heeft-poten)) (list (maak-dier 'olifant '(is-groot)))) (maak-boom (maak-dier 'vogel '(kan-vliegen heeft-vleugels heeft-veren)) (list (maak-dier 'kanarie '(kan-zingen is-geel)) (maak-dier 'arend '(is-groot))))))) (define (all-kinds boom) (cond ((leeg? boom) '()) ((dier? boom) (list (naam boom))) ((dier? (knoop boom)) (append (list (naam (knoop boom))) (all-kinds-in (deelbomen boom)))) (else (all-kinds-in (deelbomen boom))))) (define (all-kinds-in lst) (if (null? lst) '() (append (all-kinds (car lst)) (all-kinds-in (cdr lst))))) (define (geef-eigenschappen boom soort) (define (geef-eig boom eig) (cond ((dier? boom) (if (eq? (naam boom) soort) (append eig (list (eigenschappen boom))) #f)) ((and (dier? (knoop boom)) (eq? (naam (knoop boom)) soort)) (append eig (eigenschappen (knoop boom)))) (else (geef-eig-in (deelbomen boom) (append eig (eigenschappen (knoop boom))))))) (define (geef-eig-in lst eig) (cond ((null? lst) #f) (else (or (geef-eig (car lst) eig) (geef-eig-in (cdr lst) eig))))) (geef-eig boom '())) (define (ask? boom soort eig) (let ((eigenschappen (geef-eigenschappen boom soort))) (pair? (memq eig eigenschappen)))) (and (equal? (all-kinds classificatieboom) '(dier vis ballonvis landdier olifant vogel kanarie arend)) (ask? classificatieboom 'landdier 'kan-lopen) (ask? classificatieboom 'ballonvis 'heeft-vinnen) (not (ask? classificatieboom 'olifant 'kan-vliegen))) ; 7.15 ;(define (atom? x) ; (not (pair? x))) (define (maak-blad type) type) (define (geef-type blad) blad) (define (maak-knoop deelbomen) deelbomen) (define (geef-deelbomen boom) boom) (define (maak-hybride-tak knopen) knopen) (define (geef-knopen tak) tak) ;(define (leeg? boom) (null? boom)) (define (knoop? boom) (pair? boom)) (define (blad2? boom) (atom? boom)) (define hybride-tak (maak-hybride-tak (list (maak-knoop (list (maak-knoop (list (maak-blad 'appel) (maak-blad 'appel) (maak-blad 'blad))) (maak-blad 'peer))) (maak-knoop (list (maak-blad 'blad) (maak-blad 'peer))) (maak-knoop (list (maak-blad 'appel) (maak-knoop (list (maak-blad 'appel) (maak-blad 'blad)))))))) (define tak (maak-hybride-tak (list (maak-knoop (list (maak-knoop (list (maak-blad 'appel) (maak-blad 'appel) (maak-blad 'blad))) (maak-blad 'peer))) (maak-knoop (list (maak-blad 'blad) (maak-blad 'peer) (maak-blad 'appel))) (maak-knoop (list (maak-blad 'appel) (maak-knoop (list (maak-blad 'appel) (maak-blad 'blad)))))))) (define (tel boom) (define (combine-results l1 l2) (list (+ (car l1) (car l2)) (+ (cadr l1) (cadr l2)) (+ (caddr l1) (caddr l2)))) (define (tel-hulp boom) (cond ((leeg? boom) (list 0 0 0)) ((and (blad2? boom) (eq? boom 'appel)) (list 1 0 0)) ((and (blad2? boom) (eq? boom 'peer)) (list 0 1 0)) ((blad2? boom) (list 0 0 1)) (else (tel-hulp-in (geef-knopen boom))))) (define (tel-hulp-in lst) (if (null? lst) (list 0 0 0) (combine-results (tel-hulp (car lst)) (tel-hulp-in (cdr lst))))) (tel-hulp boom)) (define (member? x lst) (pair? (memq x lst))) (define (normaal? knoop) (let ((types (map (lambda (x) (if (pair? x) 'tak x)) knoop))) (not (and (member? 'appel types) (member? 'peer types))))) (define (check-normaal boom) (cond ((leeg? boom) #t) ((blad2? boom) #t) ((knoop? boom) (and (normaal? boom) (check-normaal-in (geef-knopen boom)))) (else (check-normaal-in (geef-knopen boom))))) (define (check-normaal-in lst) (if (null? lst) #t (and (check-normaal (car lst)) (check-normaal-in (cdr lst))))) (and (equal? (tel hybride-tak) '(4 2 3)) (check-normaal hybride-tak)) ; 7.16 (define foldr ; replace (apply + ...) by (foldr + 0 ...) (lambda (f base lst) (define foldr-aux (lambda (lst) (if (null? lst) base (f (car lst) (foldr-aux (cdr lst)))))) (foldr-aux lst))) ;(define (atom? x) ; (not (pair? x))) (define Coca-Cola-NV '(Coca-Cola-NV (Frisdranken (Coca-Cola (Regular-Coca-Cola (Coke (10000000))) (light-Coca-Cola (Coke-Light (800000)) (Coke-Zero (200000)))) (Fanta (Fanta-Orange (800000)) (Fanta-Lemon (200000))) (Sprite (Sprite-Zero (1000000)))) (Sappen (Minute-Maid (Minute-Maid-Sinaas (2000000)) (Minute-Maid-Tomaat (1000000)))))) (define (omzetcijfer categorie) (caadr categorie)) (define (heeft-omzetcijfer categorie) (and (pair? categorie) (pair? (cadr categorie)) (atom? (caadr categorie)) (number? (caadr categorie)))) (define (deel-categorien categorie) (cdr categorie)) (define (hoofdcategorie categorie) (car categorie)) (define (bereken lst) (cond ((null? lst) 0) ((atom? lst) 0) ((number? (car lst)) (car lst)) (else (+ (bereken (car lst)) (bereken (cdr lst)))))) (define (omzet bedrijf categorie) (if (eq? (hoofdcategorie bedrijf) categorie) (bereken bedrijf) (omzet-in (deel-categorien bedrijf) categorie))) (define (omzet-in lst categorie) (if (null? lst) #f (or (omzet (car lst) categorie) (omzet-in (cdr lst) categorie)))) (define (collect-pairs bedrijf) (cond ((heeft-omzetcijfer bedrijf) (list (list (hoofdcategorie bedrijf) (omzetcijfer bedrijf)))) (else (collect-pairs-in (deel-categorien bedrijf))))) (define (collect-pairs-in lst) (if (null? lst) '() (append (collect-pairs (car lst)) (collect-pairs-in (cdr lst))))) (define (verdeel-democratisch bedrijf budget) (let* ((pairs (collect-pairs bedrijf)) (total (foldr + 0 (map cadr pairs))) (factor (/ budget total))) (map (lambda (x) (list (car x) (* factor (cadr x)))) pairs))) (define (verdeel bedrijf budget) (if (heeft-omzetcijfer bedrijf) (list (hoofdcategorie bedrijf) budget) (let* ((rest (deel-categorien bedrijf)) (new-budget (/ budget (length rest)))) (cons (hoofdcategorie bedrijf) (verdeel-in rest new-budget))))) (define (verdeel-in lst budget) (if (null? lst) '() (cons (verdeel (car lst) budget) (verdeel-in (cdr lst) budget)))) (and (= (omzet Coca-Cola-NV 'Coca-Cola) 11000000) (= (omzet Coca-Cola-NV 'Sprite) 1000000) (= (omzet Coca-Cola-NV 'Minute-Maid) 3000000) (equal? (verdeel-democratisch Coca-Cola-NV 128000000) '((Coke 80000000) (Coke-Light 6400000) (Coke-Zero 1600000) (Fanta-Orange 6400000) (Fanta-Lemon 1600000) (Sprite-Zero 8000000) (Minute-Maid-Sinaas 16000000) (Minute-Maid-Tomaat 8000000))) (equal? (verdeel Coca-Cola-NV 1200000) '(Coca-Cola-NV (Frisdranken (Coca-Cola (Regular-Coca-Cola (Coke 100000)) (light-Coca-Cola (Coke-Light 50000) (Coke-Zero 50000))) (Fanta (Fanta-Orange 100000) (Fanta-Lemon 100000)) (Sprite (Sprite-Zero 200000))) (Sappen (Minute-Maid (Minute-Maid-Sinaas 300000) (Minute-Maid-Tomaat 300000)))))) ; 7.17 (define familieboom '(jan (piet (frans (tom) (roel)) (mie)) (bram (inge (bert (ina) (ilse)) (bart)) (iris)) (joost (else (ilse))))) (define (familiehoofd fam) (car fam)) (define (kinderen fam) (cdr fam)) (define (laatste-nakomeling? fam) (null? (kinderen fam))) (define (verdeel-democratisch2 boom budget) (define (verdeel boom) (if (laatste-nakomeling? boom) 1 (+ 1 (verdeel-in (kinderen boom))))) (define (verdeel-in lst) (if (null? lst) 0 (+ (verdeel (car lst)) (verdeel-in (cdr lst))))) (/ budget (verdeel-in (kinderen boom)))) (define (budget boom budget-list) (define (budget-hulp boom budget-list) (+ (car budget-list) (budget-hulp-in (kinderen boom) (cdr budget-list)))) (define (budget-hulp-in bomen budget-list) (if (or (null? bomen)(null? budget-list)) 0 (+ (budget-hulp (car bomen) budget-list) (budget-hulp-in (cdr bomen) budget-list)))) (budget-hulp-in (kinderen boom) budget-list)) (define (verdeel2 boom budget) (cond ((laatste-nakomeling? boom) (list (list (familiehoofd boom) budget))) (else (let* ((rest (kinderen boom)) (new-budget (/ budget (length rest)))) (verdeel2-in rest new-budget))))) (define (verdeel2-in bomen budget) (if (null? bomen) '() (append (verdeel2 (car bomen) budget) (verdeel2-in (cdr bomen) budget)))) (and (= (verdeel-democratisch2 familieboom 1500) 100) (= (budget familieboom '(100 50 20)) 650) (equal? (verdeel2 familieboom 3000) '((tom 250) (roel 250) (mie 500) (ina 125) (ilse 125) (bart 250) (iris 500) (ilse 1000)))) ; 7.18 ;(define (atom? x) ; (not (pair? x))) (define VUB-circus '(ann (mien (eef (bas) (bob)) (els (jan) (jos)) (eva (tom) (tim))) (mies (ine (cas) (cor)) (ils (rik) (raf)) (ines (stef) (staf))))) (define (hoofdartiest piramide) (car piramide)) (define (artiesten piramide) (cdr piramide)) (define (artiest? piramide) (and (pair? piramide) (atom? (car piramide)))) (define (onderaan? piramide) (null? (cdr piramide))) (define (jump piramide artiest) (define (jump-hulp piramide pad) (if (and (artiest? piramide) (eq? (hoofdartiest piramide) artiest)) pad (jump-in (artiesten piramide) (cons (hoofdartiest piramide) pad)))) (define (jump-in lst pad) (if (null? lst) #f (or (jump-hulp (car lst) pad) (jump-in (cdr lst) pad)))) (reverse (jump-hulp piramide '()))) (define (fall piramide artiest) (define (fall-hulp piramide pad) (if (and (artiest? piramide) (eq? (hoofdartiest piramide) artiest)) (append pad (append (list (hoofdartiest piramide)) (map hoofdartiest (artiesten piramide))))) (fall-in (artiesten piramide) (append pad (list (hoofdartiest piramide))))) (define (fall-in lst pad) (if (null? lst) #f (or (fall-hulp (car lst) pad) (fall-in (cdr lst) pad)))) (fall-hulp piramide '())) (and (equal? (jump VUB-circus 'eva) '(ann mien)) (equal? (jump VUB-circus 'stef) '(ann mies ines)) (not (or (fall VUB-circus 'eva) (fall VUB-circus 'stef) (fall VUB-circus 'mies))))
false
4bbbb7b51ad42c320129058d590fb8d5c582b435
4f30ba37cfe5ec9f5defe52a29e879cf92f183ee
/src/scheme/compiler/codegen/letrec.scm
ee07ed300926fc05589e64bcde55c0bb31ea7b4b
[ "MIT" ]
permissive
rtrusso/scp
e31ecae62adb372b0886909c8108d109407bcd62
d647639ecb8e5a87c0a31a7c9d4b6a26208fbc53
refs/heads/master
2021-07-20T00:46:52.889648
2021-06-14T00:31:07
2021-06-14T00:31:07
167,993,024
8
1
MIT
2021-06-14T00:31:07
2019-01-28T16:17:18
Scheme
UTF-8
Scheme
false
false
1,832
scm
letrec.scm
(define (scheme-codegen-letrec expr env target linkage) (define (load-vars idx exps env insns) (if (null? exps) insns (load-vars (+ idx 1) (cdr exps) env (preserving (scheme-preserved-registers) insns (preserving (scheme-preserved-registers) (scheme-codegen (car exps) env '(reg accum) (next-linkage)) (insn-seq `(accum ,(cadr (env-register))) '() `((perform (op store-array) ,(env-register) (const ,idx) (reg accum))))))))) (define (compile-body body env) (scheme-codegen (cons 'begin body) env target linkage)) (let ((var-names (letrec-vars expr)) (exprs (letrec-exps expr)) (body (letrec-body expr)) (sub-env (cons env (letrec-vars expr)))) (append-insn-seq (insn-seq `(,(cadr (env-register)) ,(cadr (link-register))) '(accum index operand ,(cadr (env-register))) `((save ,(env-register)) (save ,(link-register)) (push (const ,(+ 1 (length var-names)))) (perform (op call) (label cp-rtl-array-malloc)) (restore ,(link-register)) (restore ,(env-register)) (perform (op store-array) (reg accum) (const 0) ,(env-register)) (assign ,(env-register) (reg accum)))) (preserving (scheme-preserved-registers) (load-vars 1 exprs sub-env (empty-insn-seq)) (compile-body body sub-env)))))
false
f1d9d648627d83aa48e4b6f04bb61015a196ff41
f60baec01aa2c204a5ec583f95a55494bac0aeaa
/test/test_list.scm
102f6b27e90bf7a9c0d491b03c4ce73012c0f917
[]
no_license
medici/MameScheme
36aef454ea420426d87464cb8961bd1d232d56f4
a32817f2534233db59a3c156cc531d25256ad71d
refs/heads/master
2021-01-14T12:01:36.946604
2015-10-20T09:07:48
2015-10-20T09:07:48
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
4,509
scm
test_list.scm
(run-test "test_list.scm:list1 " (begin [assert (pair? '(8 9)) #t] [assert (pair? 7) #f] [assert (pair? '(a b)) #t] [assert (pair? '(a b c)) #t] [assert (pair? '()) #f] [assert (pair? '#(a b)) #f] [assert (car (cons 5 6)) 5] [assert (car (cons 1 2)) 1] [assert (cdr (cons 1 2)) 2] [assert (let ((kons (cons 3 4)))(set-car! kons 9)(car kons)) 9] [assert (let ((kons (cons 3 4)))(set-cdr! kons 9)(cdr kons)) 9] [assert (null? '()) #t] [assert (null? 6) #f] [assert (car (list 5)) 5] [assert (cdr (list 5)) '()] [assert (car (list 4 5)) 4] [assert (cadr (list 4 5)) 5] [assert (cddr (list 4 5)) '()] [assert (car '(3 4 (5 6))) 3] [assert (cadr '(3 4 (5 6))) 4] [assert (caaddr '(3 4 (5 6))) 5] [assert (car (cdaddr '(3 4 (5 6)))) 6] [assert (cdddr '(3 4 (5 6))) '()] [assert (length '(9)) 1] [assert (length '(4 5)) 2] [assert (length '(4 5 (6 7))) 3] [assert (length '()) 0] [assert (list? '(1 2)) #t] [assert (list? '()) #f] [assert (list? (cons 1 2)) #f] [assert (append '(x) '(y)) '(x y)] [assert (append '(a) '(b c d)) '(a b c d)] [assert (append '(a (b)) '((c))) '(a (b) (c))] [assert (append '(a b) '(c . d)) '(a b c . d)] [assert (append '() 'a) 'a] [assert (append '(a) '(b) '(c)) '(a b c)] [assert (let* ((hd '(x)) (cmp (append hd '(y)))) (eq? hd cmp)) #f] [assert (memq 'a '(a b c)) '(a b c)] [assert (memq 'b '(a b c)) '(b c)] [assert (memq 'a '(b c d)) #f] [assert (memq (list 'a) '(b (a) c)) #f] [assert (memv 101 '(100 101 102)) '(101 102)] [assert (assq 'a '((a 1) (b 2) (c 3))) '(a 1)] [assert (assq 'b '((a 1) (b 2) (c 3))) '(b 2)] [assert (assq 'd '((a 1) (b 2) (c 3))) #f] [assert (assq (list 'a) '(((a)) ((b)) ((c)))) #f] ;; /* (assq 5 '((2 3) (5 7) (11 13))) => unspecified */ ;; /* ARG2( INT2FIX(5), SCH_LIST3( SCH_LIST2( INT2FIX(2), INT2FIX(3) ), */ ;; /* SCH_LIST2( INT2FIX(5), INT2FIX(7) ), */ ;; /* SCH_LIST2( INT2FIX(11),INT2FIX(13) ) ) ); */ [assert (member (list 'a) '(b (a) c)) '((a) c)] [assert (assv 5 '((2 3) (5 7) (11 13))) '(5 7)] [assert (assoc (list 'a) '( ((a)) ((b)) ((c)) )) '((a))] )) (run-test "test_list.scm:list2 " (begin [assert (caar '((77))) 77] [assert (cadr '(99 88)) 88] [assert (cdar '((66 . 77))) 77] [assert (cddr '(22 33 . 44)) 44] [assert (cadar '((44 55))) 55] [assert (caddr '(33 44 55)) 55] [assert (cdddr '(66 77 88 99)) '(99)] [assert (cadddr '(66 77 88 99)) 99] [assert (cddddr '(55 66 77 88 99)) '(99)] [assert (caaaar '((((a))))) 'a] [assert (caaadr '(b ((a)))) 'a] [assert (caaar '(((a)))) 'a] [assert (caadar '((c (a)))) 'a] [assert (caaddr '(c b (a))) 'a] [assert (caadr '(b (a))) 'a] [assert (cadaar '(((b a))) ) 'a] [assert (cadadr '(c (b a))) 'a] [assert (caddar '((c b a)) ) 'a] [assert (cdaaar '((((b . a)))) ) 'a] [assert (cdaadr '(c ((b . a))) ) 'a] [assert (cdaar '(((b . a))) ) 'a] [assert (cdadar '((c (b . a))) ) 'a] [assert (cdaddr '(d c (b . a)) ) 'a] [assert (cdadr '(c (b . a)) ) 'a] [assert (cddaar '(((c b . a))) ) 'a] [assert (cddadr '(d (c b . a)) ) 'a] [assert (cddar '((c b . a)) ) 'a] [assert (cdddar '((d c b . a)) ) 'a] [assert (list-ref '(d e f) 1) 'e] [assert (list-ref '(a b c) 1) 'b] [assert (list-ref '(d e f) 0) 'd] [assert (list-ref '(d e f) 1) 'e] [assert (list-ref '(d e f) 2) 'f] [assert (list-tail '(a b c) 1) '(b c)] [assert (reverse '(a b c)) '(c b a)] ))
false
7e60ab48063fcb92901d51fe7bab008209def102
c085780da34766c02f47f181bd8a7bb515126caa
/lec3.scm
61f5a9b3c784fc7b3b05efcd9fd2d3d4ca79a911
[]
no_license
juleari/r5rs
37ede50989e59b0936f7aac2b204cb9affa22d21
880b0df41e94c103386c158cc172b658f485a465
refs/heads/master
2016-09-16T17:23:42.192923
2016-05-04T11:58:18
2016-05-04T11:58:18
42,339,524
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,090
scm
lec3.scm
(define-syntax compose (syntax-rules () ((_ () () expr) expr) ((_ () (f . rfs) (lambda (x) expr)) (compose () rfs (lambda (x) (f expr)))) ((_ (f . fs) rfs expr) (compose fs (f . rfs) expr)) ((_ f . fs) (compose (f . fs) () (lambda (x) x))))) ((compose sqrt abs sin) -1) (define-syntax arrows (syntax-rules () ((_ q () let-expr) (let* let-expr q)) ((_ q (var . vars) let-expr) (arrows q vars (var . let-expr))) ((_ (return q) vars) (arrows q vars ())) ((_ (x >- f -> y . rest) vars) (arrows rest ((y (f x)) . vars))) ((_ arg . args) (arrows (arg . args) ())))) (define (circuit a b c) (arrows (list a c) >- and -> qa c >- not -> c- (list c- b) >- and -> qb (list qa qb) >- or -> q return q)) (circuit #f #f #f) (define (map-1/x xs) (call-with-current-continuation (lambda (escape) (map (lambda (x) (if (and (number? x) (not (zero? x))) (/ 1 x) (escape 'error))) xs)))) (map-1/x '(1 2 3 4)) (map-1/x '(1 0 2 a 3))
true
1cc017507d10beadb814426722d3006d2c05bcc1
e1fc47ba76cfc1881a5d096dc3d59ffe10d07be6
/ch1/1.28.scm
00f985f66a3895480e60e10075891eb6940da94a
[]
no_license
lythesia/sicp-sol
e30918e1ebd799e479bae7e2a9bd4b4ed32ac075
169394cf3c3996d1865242a2a2773682f6f00a14
refs/heads/master
2021-01-18T14:31:34.469130
2019-10-08T03:34:36
2019-10-08T03:34:36
27,224,763
2
0
null
null
null
null
UTF-8
Scheme
false
false
854
scm
1.28.scm
; Miller-Rabin test (define (square n) (* n n)) (define (trivial-square-test a n) (if (and (not (= a 1)) (not (= a (- n 1))) (= (remainder (square a) n) 1)) 0 ; fail a ; success, return the remainder ) ) (define (expmod base exp n) (cond ((= exp 0) 1) ((even? exp) (remainder (square(trivial-square-test (expmod (square base) (/ exp 2) n) n)) n)) ; check remainder q non-trivial, then as usual q^2 | a (else (remainder (* base (expmod base (- exp 1) n)) n)) ) ) (define (miller-rabin-test n) (define (try-it a) (= (expmod a (- n 1) n) 1) ) (try-it (+ 1 (random(- n 1)))) ) (define (do-miller-rabin-test n times) (cond ((= times 0) true) ((miller-rabin-test n) (do-miller-rabin-test n (- times 1))) (else false) ) ) (display (do-miller-rabin-test 561 10))(newline)
false
e03395857be7ab709335e10359899446343c3db4
fae4190f90ada065bc9e5fe64aab0549d4d4638a
/typed-scheme-lti/private/parse-type.ss
59ec1a8fda0b8189d0113d8245eb2f9d4da9f59f
[]
no_license
ilya-klyuchnikov/old-typed-racket
f161481661a2ed5cfc60e268f5fcede728d22488
fa7c1807231f447ff37497e89b25dcd7a9592f64
refs/heads/master
2021-12-08T04:19:59.894779
2008-04-13T10:54:34
2008-04-13T10:54:34
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
7,088
ss
parse-type.ss
(module parse-type mzscheme (provide parse-type parse-type/id) (require (all-except "type-rep.ss" make-arr) "type-effect-convenience.ss" (rename "type-effect-convenience.ss" make-arr make-arr*) "tc-utils.ss" "union.ss" (lib "stx.ss" "syntax") (all-except "type-environments.ss" Void String) "type-name-env.ss" (only (lib "list.ss") foldl foldr) (all-except (lib "list.ss" "srfi" "1") unfold remove) (lib "plt-match.ss")) (define enable-mu-parsing (make-parameter #t)) (define (parse-type/id loc datum) #;(printf "parse-type/id id : ~a~n ty: ~a~n" (syntax-object->datum loc) (syntax-object->datum stx)) (let* ([stx* (datum->syntax-object loc datum loc loc)]) (parse-type stx*))) (define (stx-cadr stx) (stx-car (stx-cdr stx))) (define (parse-type stx) (parameterize ([current-orig-stx stx]) (syntax-case* stx () symbolic-identifier=? [(fst . rst) (not (syntax->list #'rst)) (-pair (parse-type #'fst) (parse-type #'rst))] [(Tuple ts ...) (eq? (syntax-e #'Tuple) 'Tuple) (begin (add-type-name-reference (stx-car stx)) (foldr -pair (-val '()) (map parse-type (syntax->list #'(ts ...)))))] [(cons fst rst) (eq? (syntax-e #'cons) 'cons) (-pair (parse-type #'fst) (parse-type #'rst))] [(pred t) (eq? (syntax-e #'pred) 'pred) (make-pred-ty (parse-type #'t))] [(dom -> rng : pred-ty) (and (eq? (syntax-e #'->) '->) (eq? (syntax-e #':) ':)) (begin (add-type-name-reference (stx-cadr stx)) (make-pred-ty (list (parse-type #'dom)) (parse-type #'rng) (parse-type #'pred-ty)))] [(dom ... rest ::: -> rng) (and (eq? (syntax-e #'->) '->) (or (symbolic-identifier=? #'::: (quote-syntax ..)) (symbolic-identifier=? #'::: (quote-syntax ...)))) (begin (add-type-name-reference #'->) (->* (map parse-type (syntax->list #'(dom ...))) (parse-type #'rest) (parse-type #'rng)))] ;; has to be below the previous one [(dom ... -> rng) (eq? (syntax-e #'->) '->) (begin (add-type-name-reference #'->) (->* (map parse-type (syntax->list #'(dom ...))) (parse-type #'rng)))] [(values tys ...) (eq? (syntax-e #'values) 'values) (-values (map parse-type (syntax->list #'(tys ...))))] [(case-lambda tys ...) (eq? (syntax-e #'case-lambda) 'case-lambda) (make-Function (map (lambda (ty) (syntax-case* ty (->) symbolic-identifier=? [(dom ... -> rng) (make-arr (map parse-type (syntax->list #'(dom ...))) (parse-type #'rng))])) (syntax->list #'(tys ...))))] ;; I wish I could write this #;[(case-lambda ([dom ... -> rng] ...)) (make-funty (list (make-arr (list (parse-type #'dom) ...) (parse-type #'rng)) ...))] #;[(list-of t) (make-lst (parse-type #'t))] #;[(Listof t) (make-lst (parse-type #'t))] [(Vectorof t) (eq? (syntax-e #'Vectorof) 'Vectorof) (begin (add-type-name-reference #'Vectorof) (make-Vector (parse-type #'t)))] [(mu x t) (and (identifier? #'x) (eq? (syntax-e #'mu) 'mu) (enable-mu-parsing)) (let* ([var (syntax-e #'x)] [tvar (make-F var)]) (add-type-name-reference #'mu) (parameterize ([current-tvars (extend-env (list var) (list tvar) (current-tvars))]) (make-Mu var (parse-type #'t))))] [(U ts ...) (eq? (syntax-e #'U) 'U) (begin (add-type-name-reference #'U) (apply Un (map parse-type (syntax->list #'(ts ...)))))] [(Un-pat ts ...) (eq? (syntax-e #'Un-pat) 'Un) (apply Un (map parse-type (syntax->list #'(ts ...))))] [(quot t) (eq? (syntax-e #'quot) 'quote) (-val (syntax-e #'t))] [(All (vars ...) t) (and (eq? (syntax-e #'All) 'All) (andmap identifier? (syntax->list #'(vars ...)))) (let* ([vars (map syntax-e (syntax->list #'(vars ...)))] [tvars (map make-F vars)]) (add-type-name-reference #'All) (parameterize ([current-tvars (extend-env vars tvars (current-tvars))]) (make-Poly vars (parse-type #'t))))] [(Opaque p?) (eq? (syntax-e #'Opaque) 'Opaque) (begin (add-type-name-reference #'Opaque) (make-Opaque #'p? (syntax-local-certifier)))] [(Parameter t) (eq? (syntax-e #'Parameter) 'Parameter) (let ([ty (parse-type #'t)]) (add-type-name-reference #'Parameter) (-Param ty ty))] [(Parameter t1 t2) (eq? (syntax-e #'Parameter) 'Parameter) (begin (add-type-name-reference #'Parameter) (-Param (parse-type #'t1) (parse-type #'t2)))] ;;[(All . rest) (eq? (syntax-e #'All) 'All) (tc-error "All: bad syntax")] ;;[(Opaque . rest) (eq? (syntax-e #'Opaque) 'Opqaue) (tc-error "Opaque: bad syntax")] ;;[(U . rest) (eq? (syntax-e #'U) 'U) (tc-error "Union: bad syntax")] ;;[(Vectorof . rest) (eq? (syntax-e #'Vectorof) 'Vectorof) (tc-error "Vectorof: bad syntax")] ;;[(mu . rest) (eq? (syntax-e #'mu) 'mu) (tc-error "mu: bad syntax")] ;;[(Un . rest) (eq? (syntax-e #'Un) 'Un) (tc-error "Union: bad syntax")] ;;[(t ... -> . rest) (eq? (syntax-e #'->) '->) (tc-error "->: bad syntax")] [id (identifier? #'id) (lookup (current-tvars) (syntax-e #'id) (lambda (key) (lookup-type-name #'id (lambda () (tc-error "unbound type ~a" key)))))] [(id arg args ...) (identifier? #'id) (let ([ty (parse-type #'id)]) #;(printf "ty is ~a" ty) (unless (Poly? ty) (tc-error "not a polymorphic type: ~a" (syntax-e #'id))) (unless (= (length (syntax->list #'(arg args ...))) (Poly-n ty)) (tc-error "wrong number of arguments to type constructor ~a: expected ~a, got ~a" (syntax-e #'id) (Poly-n ty) (length (syntax->list #'(arg args ...))))) (instantiate-poly ty (map parse-type (syntax->list #'(arg args ...)))))] [t (or (boolean? (syntax-e #'t)) (number? (syntax-e #'t)) (string? (syntax-e #'t))) (-val (syntax-e #'t))] [_ (tc-error "not a valid type: ~a" (syntax-object->datum stx))]))) )
false
b58e1db1af13b6abbde5cdafcf4054473a3b6d01
db0f911e83225f45e0bbc50fba9b2182f447ee09
/the-scheme-programming-language/3.2-more-recursion/homeworks/3.2.5.scm
f83e4532a48c08a5caa27b25a53a52fa2fb26f6f
[]
no_license
ZhengHe-MD/learn-scheme
258941950302b4a55a1d5d04ca4e6090a9539a7b
761ad13e6ee4f880f3cd9c6183ab088ede1aed9d
refs/heads/master
2021-01-20T00:02:38.410640
2017-05-03T09:48:18
2017-05-03T09:48:18
89,069,898
0
0
null
null
null
null
UTF-8
Scheme
false
false
418
scm
3.2.5.scm
(define-syntax let (syntax-rules () [(_ ((x e) ...) b1 b2 ...) ((lambda (x ...) b1 b2 ...) e ...)] [(_ name ((x e) ...) b1 b2 ...) (letrec ([name (lambda (x ...) b1 b2 ...)]) (name e ...)])) (define-syntax let (syntax-rules () [(_ ((x v) ...) e1 e2 ...) ((lambda (x ...) e1 e2 ...) v ...)] [(_ f ((x v) ...) e1 e2 ...) ((letrec ([f (lambda (x ...) e1 e2 ...)]) f) v ...)]))
true
ad528a7fe42bb534d5808be08e0c9bcd989c3a9b
464f876b034b518d8cf8a0b77ea4851f05148916
/Chapter2/ex2_48.scm
ea7f2efe6ab345bfbddb869d1a9778e86c474e94
[]
no_license
billy1kaplan/sicp
3302e6772af205fa8d1ac77c2d203cb329f5958b
71d3f93921e32567ae2becec3c9659cfdf013287
refs/heads/master
2021-03-22T01:01:15.409369
2019-02-10T04:13:56
2019-02-10T04:13:56
98,474,397
0
0
null
null
null
null
UTF-8
Scheme
false
false
780
scm
ex2_48.scm
#lang sicp (define (make-vect x y) (cons x y)) (define (xcor-vect vect) (car vect)) (define (ycor-vect vect) (cdr vect)) (define (add-vect v1 v2) (make-vect ( + (xcor-vect v1) (xcor-vect v2)) ( + (ycor-vect v1) (ycor-vect v2)))) (define (sub-vect v1 v2) (make-vect ( - (xcor-vect v1) (xcor-vect v2)) ( - (ycor-vect v1) (ycor-vect v2)))) (define (scale-vect v s) (make-vect ( * (xcor-vect v) s) ( * (ycor-vect v) s))) ; New stuff (define (make-segment v1 v2) (cons v1 v2)) (define (start-segment v) (car v)) (define (end-segment v) (cdr v)) (define v1 (make-vect 1 2)) (define v2 (make-vect 3 4)) (define segment (make-segment v1 v2)) (start-segment segment) (end-segment segment)
false
96a222ad7563098267533ece1e2b923ff5be4b3c
c3523080a63c7e131d8b6e0994f82a3b9ed901ce
/hertfordstreet/schemes/contfrac.scm
c65cb5aedd8c00a73f9bb54a2301c9486492471e
[]
no_license
johnlawrenceaspden/hobby-code
2c77ffdc796e9fe863ae66e84d1e14851bf33d37
d411d21aa19fa889add9f32454915d9b68a61c03
refs/heads/master
2023-08-25T08:41:18.130545
2023-08-06T12:27:29
2023-08-06T12:27:29
377,510
6
4
null
2023-02-22T00:57:49
2009-11-18T19:57:01
Clojure
UTF-8
Scheme
false
false
1,330
scm
contfrac.scm
(define (cont-frac n d k) (define (iter i) (if (< i k) (/ (n i) (+ (d i) (iter (+ 1 i)))) (/ (n k) (d k)) )) (iter 1)) (define (const n) 1) ;(cont-frac const const 3) (define (cont-frac n d k) (define (iter k total) ( if (> k 0) (iter (- k 1) (/ (n k) (+ (d k) total))) total)) (iter (- k 1)(/ (n k)(d k)))) ;(cont-frac const const 3) (define (invgolden k) (cont-frac (lambda (i) 1.0) (lambda (i) 1.0) k)) (define (approxmetrics exact fn n) (define (err x) (-(fn x) exact)) (define (crate x) (/(err x)(err (+ 1 x)))) (define (iter k) (printf "~s:~s:\t~s--------~s~%" k (fn k) (err k) (crate k)) (if (< k n) (iter (+ k 1)))) (printf "~s~%" exact) (iter 1)) ;(approxmetrics (/ 1 (/(+(sqrt 5) 1) 2)) invgolden 13) (define (power n m) (if (= m 0) 1 (* n (power n (- m 1))))) (define (eulerd n) (if (= 0 (remainder (- n 2) 3)) (+ 2 (* 2 (/ (- n 2) 3))) 1)) (define (e-2 k) (cont-frac (lambda (i) 1) eulerd k)) (define (tann n x) (if (= n 1) x (- (* x x)))) (define (tan-cf x k) (cont-frac (lambda (i) (tann i x)) (lambda (i) (+ 1 (* 2 (- i 1)))) k)) (approxmetrics (tan 0.1) (lambda (k) (tan-cf (/ 1 10) k)) 13)
false
af677434930fe0393276a99ba608e035b9d4bb42
1b771524ff0a6fb71a8f1af8c7555e528a004b5e
/ex376.scm
517ab259cee1bbecfc9301fb568d515ca2077a39
[]
no_license
yujiorama/sicp
6872f3e7ec4cf18ae62bb41f169dae50a2550972
d106005648b2710469067def5fefd44dae53ad58
refs/heads/master
2020-05-31T00:36:06.294314
2011-05-04T14:35:52
2011-05-04T14:35:52
315,072
0
0
null
null
null
null
UTF-8
Scheme
false
false
780
scm
ex376.scm
(load "./chapter3.scm") (define sense-data (list 1 2 1.5 1 0.5 -0.1 -2 -3 -2 -0.5 0.2 3 4)) (define (sign-change-detector cur next) (cond ((and (> 0 cur) (<= 0 next)) -1) ((and (<= 0 cur) (> 0 next)) 1) (else 0))) (define (smooth s) s) (define (smooth s) (let ((x (stream-car s)) (y (stream-ref s 1))) (cons-stream (/ (+ x y) 2) (smooth (stream-cdr s))))) (define (make-zero-crossings input-stream last-value) (cons-stream (sign-change-detector (stream-car input-stream) last-value) (make-zero-crossings (stream-cdr input-stream) (stream-car input-stream)))) ;; ้ƒจๅ“ๅŒ–ใจใ„ใ†ใฎใง้–ขๆ•ฐ้ฉ็”จใ—ใฆใฟใ‚‹ (define zero-crossings (make-zero-crossings (smooth sense-data) 0))
false
95fc33dfdfc20706f2ccf2aab63c496f062d01b2
7666204be35fcbc664e29fd0742a18841a7b601d
/code/2-17.scm
375628944eacf3e4eb22b29c493e94514877b863
[]
no_license
cosail/sicp
b8a78932e40bd1a54415e50312e911d558f893eb
3ff79fd94eda81c315a1cee0165cec3c4dbcc43c
refs/heads/master
2021-01-18T04:47:30.692237
2014-01-06T13:32:54
2014-01-06T13:32:54
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
360
scm
2-17.scm
#lang racket (define (last-elem L) (define (iter ans R) (if (null? R) ans (iter (car R) (cdr R)))) (iter (car L) (cdr L))) (last-elem '(1 2 3 4 5)) (define (last-pair L) (cond ((null? L) (error "empty list")) ((null? (cdr L)) L) (else (last-pair (cdr L))))) (last-pair '(1 2 3 4 5))
false
cc62fc2e71e6ddb6aba8971d0675227fa95abe4e
db24a090a01fab9071864f04079f4dc792e5946d
/swish/src/helpers.ss
6876b1043d6a58b1af78fc74930b03d03856fd0f
[]
no_license
crawfoaj2020/Database-searcher
8020dd83216ae2b51cc5b27293856901966567c6
5c60505027973fe5dda79d96dde481cf21fa7d88
refs/heads/master
2020-03-22T20:14:24.953418
2018-07-27T15:55:16
2018-07-27T15:55:16
140,584,046
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,895
ss
helpers.ss
;;; Copyright 2018 Beckman Coulter, Inc. ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation ;;; files (the "Software"), to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies ;;; of the Software, and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be ;;; included in all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. #!chezscheme (library (helpers) (export string-param integer-param string-param-sql previous-sql-valid? stringify trim-whitespace containsStr? slist->string string-replace flatten valid-file) (import (chezscheme) (swish imports)) ;;Common helpers (define (string-param name params) (let ([value (http:find-param name params)]) (and value (trim-whitespace value)))) (define (string-param-sql name params) (let ([val (string-param name params)]) (if val (string-replace val "'" "''") val))) (define (integer-param name min-value params) (let* ([string-value (http:find-param name params)] [number-value (and string-value (string->number string-value))]) (and string-value (if (and (integer? number-value) (>= number-value min-value)) number-value (raise `#(bad-integer-param ,name ,min-value ,number-value)))))) (define (previous-sql-valid? sql) (and sql (not (string=? sql "")))) ;; String manipulation (define (stringify x) (format "~a" x)) (define (trim-whitespace s) (define (find-start s i len) (cond [(eqv? i len) ""] [(char-whitespace? (string-ref s i)) (find-start s (fx+ i 1) len)] [else (find-end s (fx- len 1) i len)])) (define (find-end s i start len) (cond [(eqv? i start) (if (eqv? len 1) s (string (string-ref s i)))] [(char-whitespace? (string-ref s i)) (find-end s (fx- i 1) start len)] [else (if (and (eqv? start 0) (eqv? (fx- len 1) i)) s (substring s start (fx+ i 1)))])) (find-start s 0 (string-length s))) (define (containsStr? list x) (cond ((null? list) #f) ((string-ci=? (car list) x) #t) (else (containsStr? (cdr list) x)))) (define (slist->string slst div) (cond ((null? slst) "") ((null? (cdr slst)) (car slst)) (else (string-append (car slst) div (slist->string (cdr slst) div))))) (define string-replace (lambda (s match replacement) (let ((ll (string->list s))) (let ((z (map (lambda (x) (if (string-ci=? (stringify x) match) (string->list replacement) x)) ll))) (list->string (flatten z)))))) (define (flatten list) (cond ((null? list) '()) ((list? (car list)) (append (flatten (car list)) (flatten (cdr list)))) (else (cons (car list) (flatten (cdr list)))))) (define (valid-file file-path) (match (catch (read-file file-path)) [#(EXIT ,details) #f] [,value #t])) )
false
0649edeb0adccbc99810826bf9b2557ccf3c0888
1dfe3abdff4803aee6413c33810f5570d0061783
/.chezscheme_libs/spells/string-utils.sls
df55a67a7a990e1f84c4ab0baff69335ea58ef74
[]
no_license
Saigut/chezscheme-libs
73cb315ed146ce2be6ae016b3f86cf3652a657fc
1fd12abbcf6414e4d50ac8f61489a73bbfc07b9d
refs/heads/master
2020-06-12T14:56:35.208313
2016-12-11T08:51:15
2016-12-11T08:51:15
75,801,338
6
2
null
null
null
null
UTF-8
Scheme
false
false
8,780
sls
string-utils.sls
#!r6rs ;;; string-utils.sls --- String utilities ;; Copyright (C) 2009, 2011 Andreas Rottmann <[email protected]> ;; Author: Andreas Rottmann <[email protected]> ;; This program is free software, you can redistribute it and/or ;; modify it under the terms of the new-style BSD license. ;; You should have received a copy of the BSD license along with this ;; program. If not, see <http://www.debian.org/misc/bsd.license>. ;;; Commentary: ;;; Code: ;;@ Utility procedures operating on strings. (library (spells string-utils) (export string-split string-escape string-substitute) (import (except (rnrs base) string-copy string-for-each string->list) (rnrs control) (except (rnrs unicode) string-titlecase string-upcase string-downcase) (rnrs io simple) (rnrs io ports) (srfi srfi-8 receive) (srfi srfi-13 strings) (srfi srfi-14 char-sets) (srfi srfi-26 cut) (spells alist)) ;;@defun string-split string charset ;;@defunx string-split string charset maxsplit ;; ;; Returns a list of words delimited by the characters in ;; @var{charset} in @var{string}. @var{charset} is a list of ;; characters that are treated as delimiters. Leading or trailing ;; delimeters are @emph{not} trimmed. That is, the resulting list ;; will have as many initial empty string elements as there are ;; leading delimiters in @var{string}. ;; ;; If @var{maxsplit} is specified and positive, the resulting list ;; will contain at most @var{maxsplit} elements, the last of which ;; is the string remaining after (@var{maxsplit} - 1) splits. If ;; @var{maxsplit} is specified and non@var{-}positive, the empty ;; list is returned. ``In time critical applications it behooves you ;; not to split into more fields than you really need.'' ;; ;; This is based on the split function in Python/Perl. ;; ;;@lisp ;; (string-split " abc d e f ") ;==> ("abc" "d" "e" "f") ;; (string-split " abc d e f " '() 1) ;==> ("abc d e f ") ;; (string-split " abc d e f " '() 0) ;==> () ;; (string-split ":abc:d:e::f:" '(#\:)) ;==> ("" "abc" "d" "e" "" "f" "") ;; (string-split ":" '(#\:)) ;==> ("" "") ;; (string-split "root:x:0:0:Lord" '(#\:) 2) ;==> ("root" "x:0:0:Lord") ;; (string-split "/usr/local/bin:/usr/bin:/usr/ucb/bin" '(#\:)) ;; ;==> ("/usr/local/bin" "/usr/bin" "/usr/ucb/bin") ;; (string-split "/usr/local/bin" '(#\/)) ;==> ("" "usr" "local" "bin") ;;@end lisp ;;@end defun (define (string-split str splitter . rest) ;; maxsplit is a positive number ;; str is not empty (define (split-by-charset str cs maxsplit) (define (scan-beg-word from yet-to-split-count) (cond ((>= from (string-length str)) '("")) ((zero? yet-to-split-count) (cons (substring str from (string-length str)) '())) (else (scan-word from from yet-to-split-count)))) (define (scan-word i from yet-to-split-count) (cond ((>= i (string-length str)) (cons (substring str from i) '())) ((char-set-contains? cs (string-ref str i)) (cons (substring str from i) (scan-beg-word (+ i 1) (- yet-to-split-count 1)))) (else (scan-word (+ i 1) from yet-to-split-count)))) (scan-beg-word 0 (- maxsplit 1))) ;; resolver of overloading... ;; if omitted, maxsplit defaults to ;; (inc (string-length str)) (if (string-null? str) '() (let ((maxsplit (if (pair? rest) (car rest) (+ 1 (string-length str))))) (cond ((not (positive? maxsplit)) '()) ((pair? splitter) (split-by-charset str (list->char-set splitter) maxsplit)) (else (split-by-charset str (->char-set splitter) maxsplit))))) ) ;;@ Returns a string obtained by adding the character ;; @var{escape-char} before characters matching @var{to-escape}, ;; which may be a character or a character set. If ;; @var{escape-char} is not specified, @code{#\\} is used. (define string-escape (case-lambda ((s to-escape escape-char) (let ((escaped-cs (char-set-adjoin (->char-set to-escape) escape-char))) (string-concatenate (map (lambda (c) (if (char-set-contains? escaped-cs c) (string escape-char c) (string c))) (string->list s))))) ((s to-escape) (string-escape s to-escape #\\)))) ;;@ Simple template string substitution. (define string-substitute (case-lambda ((dst template vals grammar) (%string-substitute dst template vals grammar)) ((template vals grammar) (string-substitute #f template vals grammar)) ((template vals) (string-substitute #f template vals 'braces)))) (define (%string-substitute dst template vals grammar) (define (lose msg . irritants) (apply error 'string-substitute msg irritants)) (receive (open-brace close-brace) (case grammar ((braces) (values #\{ #\})) ((abrackets) (values #\< #\>)) (else (lose "invalid grammar" dst template vals grammar))) (let loop ((i 0) (open-pos #f) (parts '())) (define (output str) (cond ((eqv? dst #f) (cons str parts)) ((eqv? dst #t) (display str) parts) (else (display str dst) parts))) (define (handle-close-brace/escaped pos) (unless (doubled-char? template pos) (lose "unexpected close brace" template pos)) (loop (+ pos 2) open-pos (output (substring/shared template i (+ pos 1))))) (define (handle-open-brace pos) (cond ((doubled-char? template pos) (loop (+ pos 2) #f (output (substring/shared template i (+ pos 1))))) (else (loop (+ pos 1) pos (output (substring/shared template i pos)))))) (if (not i) (if (eqv? dst #f) (string-concatenate-reverse parts)) (cond (open-pos (let ((close-pos (string-index template close-brace i))) (unless close-pos (lose "unmatched opening brace" template open-pos)) (cond ((doubled-char? template close-pos) (loop (+ close-pos 2) open-pos parts)) (else (loop (+ close-pos 1) #f (output (subst-one template open-pos close-pos vals lose))))))) (else (let ((open-pos (string-index template open-brace i)) (close-pos (string-index template close-brace i))) (cond ((not (or open-pos close-pos)) (loop #f #f (output (substring/shared template i)))) ((not open-pos) (handle-close-brace/escaped close-pos)) ((not close-pos) (handle-open-brace open-pos)) ((< open-pos close-pos) (handle-open-brace open-pos)) (else (handle-close-brace/escaped close-pos)))))))))) (define (doubled-char? s i) (let ((c (string-ref s i))) (and (< (+ i 1) (string-length s)) (char=? c (string-ref s (+ i 1)))))) (define (subst-one template open-pos close-pos vals lose) (let* ((placeholder (substring/shared template (+ open-pos 1) close-pos)) (i (or (string->number placeholder) (string->symbol placeholder))) (val (cond ((and (vector? vals) (integer? i)) (vector-ref vals i)) ((and (integer? i) (list? vals)) (list-ref vals i)) ((symbol? i) (assq-ref vals i)) (else (lose "Invalid type for replacements" vals i))))) (cond ((string? val) val) ((number? val) (number->string val)) ((char? val) (string val)) (else (call-with-string-output-port (lambda (port) (display val port))))))) )
false
52a5c82d8b2ae6d0a6413fffd4ba6e453afc8962
ea4e27735dd34917b1cf62dc6d8c887059dd95a9
/table-local.scm
5a4caae5fbee21a1450e5c03aac01a3912aa5a80
[ "MIT" ]
permissive
feliposz/sicp-solutions
1f347d4a8f79fca69ef4d596884d07dc39d5d1ba
5de85722b2a780e8c83d75bbdc90d654eb094272
refs/heads/master
2022-04-26T18:44:32.025903
2022-03-12T04:27:25
2022-03-12T04:27:25
36,837,364
1
0
null
null
null
null
UTF-8
Scheme
false
false
2,279
scm
table-local.scm
(define (assoc key records) (cond ((null? records) #f) ((equal? key (caar records)) (car records)) (else (assoc key (cdr records))))) (define (make-table) (let ((local-table (list '*table*))) (define (lookup key-1 key-2) (let ((subtable (assoc key-1 (cdr local-table)))) (if subtable (let ((record (assoc key-2 (cdr subtable)))) (if record (cdr record) #f)) #f))) (define (insert! key-1 key-2 value) (let ((subtable (assoc key-1 (cdr local-table)))) (if subtable (let ((record (assoc key-2 (cdr subtable)))) (if record (set-cdr! record value) (set-cdr! subtable (cons (cons key-2 value) (cdr subtable))))) (set-cdr! local-table (cons (list key-1 (cons key-2 value)) (cdr local-table))))) 'ok) (define (print) ; print in the same order that items where inserted (define (print-values values) (cond ((null? values) 'done) (else (print-values (cdr values)) (display (car values)) (display " ") ))) (define (print-lines lines) (cond ((null? lines) 'done) (else (print-lines (cdr lines)) (display (caar lines)) (display ": ") ; header (print-values (cdar lines)) ; items (newline) ))) (print-lines (cdr local-table))) (define (dispatch m) (cond ((eq? m 'lookup-proc) lookup) ((eq? m 'insert-proc) insert!) ((eq? m 'print) print) (else (error "Unknown operation - TABLE" m)))) dispatch)) (define operation-table (make-table)) (define get (operation-table 'lookup-proc)) (define put (operation-table 'insert-proc)) (define print-table (operation-table 'print)) ; test ;(put 'a 1 'apple) ;(put 'a 2 'apricot) ;(put 'b 1 'banana) ;(put 'b 2 'beaf) ;(put 'c 1 'cherry) ;(put 'c 2 'chocolate) ;(print-table) ;(get 'a 1) ;(get 'c 2) ;(put 'a 1 'pineapple) ;(get 'a 1) ;(get 'a 3) ;(get 'd 1) ;(print-table)
false
9bccf7b60b63770e8cafe52fa587084a673bbc67
6f86602ac19983fcdfcb2710de6e95b60bfb0e02
/exercises/practice/list-ops/test.scm
c52814d90f6bb35d1c35f6b371541ea524e53457
[ "MIT", "CC-BY-SA-3.0" ]
permissive
exercism/scheme
a28bf9451b8c070d309be9be76f832110f2969a7
d22a0f187cd3719d071240b1d5a5471e739fed81
refs/heads/main
2023-07-20T13:35:56.639056
2023-07-18T08:38:59
2023-07-18T08:38:59
30,056,632
34
37
MIT
2023-09-04T21:08:27
2015-01-30T04:46:03
Scheme
UTF-8
Scheme
false
false
2,805
scm
test.scm
(load "test-util.ss") (use-modules (srfi srfi-64)) (use-modules (srfi srfi-1)) (module-define! (resolve-module '(srfi srfi-64)) 'test-log-to-file #f) (add-to-load-path (dirname (current-filename))) (use-modules (list-ops)) (test-begin "list-ops-test") (test-eqv "length of empty list" 0 (my-length '())) (test-eqv "length of normal list" 4 (my-length '(1 3 5 7))) (test-eqv "length of huge list" 1000000 (my-length (list-tabulate 1000000 values))) (test-equal "reverse of empty list" '() (my-reverse '())) (test-equal "reverse of normal list" '(7 5 3 1) (my-reverse '(1 3 5 7))) (test-equal "reverse of huge list" (list-tabulate 1000000 (lambda (x) (- 999999 x))) (my-reverse (list-tabulate 1000000 values))) (define (inc x) (+ 1 x)) (test-equal "map of empty list" '() (my-map inc '())) (test-equal "map of normal list" '(2 3 4 5) (my-map inc '(1 2 3 4))) (test-equal "map of huge list" (list-tabulate 1000000 (lambda (x) (+ x 1))) (my-map inc (list-tabulate 1000000 values))) (test-equal "filter of empty list" '() (my-filter odd? '())) (test-equal "filter of normal list" '(1 3) (my-filter odd? '(1 2 3 4))) (test-equal "filter of huge list" (filter odd? (list-tabulate 1000000 values)) (my-filter odd? (list-tabulate 1000000 values))) (test-eqv "fold of empty list" 0 (my-fold + 0 '())) (test-eqv "fold of normal list" 7 (my-fold + -3 '(1 2 3 4))) (test-eqv "fold of huge list" (fold + 0 (list-tabulate 1000000 values)) (my-fold + 0 (list-tabulate 1000000 values))) (test-eqv "fold with non-commutative function" 0 (my-fold (lambda (x acc) (- acc x)) 10 '(1 2 3 4))) (test-equal "append of empty lists" '() (my-append '() '())) (test-equal "append of empty and non-empty list" '(1 2 3 4) (my-append '() '(1 2 3 4))) (test-equal "append of non-empty and empty list" '(1 2 3 4) (my-append '(1 2 3 4) '())) (test-equal "append of non-empty lists" '(1 2 3 4 5) (my-append '(1 2 3) '(4 5))) (test-equal "append of huge lists" (list-tabulate 2000000 values) (my-append (list-tabulate 1000000 values) (list-tabulate 1000000 (lambda (x) (+ x 1000000))))) (test-equal "concatenate of empty list of lists" '() (my-concatenate '())) (test-equal "concatenate of normal list of lists" '(1 2 3 4 5 6) (my-concatenate '((1 2) (3) () (4 5 6)))) (test-equal "concatenate of huge list of small lists" (list-tabulate 1000000 values) (my-concatenate (list-tabulate 1000000 list))) (test-equal "concatenate of small list of huge lists" (list-tabulate 1000000 values) (my-concatenate (list-tabulate 10 (lambda (i) (list-tabulate 100000 (lambda (j) (+ (* 100000 i) j))))))) (test-end "list-ops-test") (run-with-cli "list-ops.scm" (list test-cases))
false
b8607df05ca743414842367086aa3be2946ec410
defeada37d39bca09ef76f66f38683754c0a6aa0
/System.Xml/system/xml/schema/xml-schema-keyref.sls
cdc49ab51d8b59dcdaa787d4974377a81eb55c4b
[]
no_license
futsuki/ironscheme-port
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
4e7a81b0fbeac9a47440464988e53fb118286c54
refs/heads/master
2016-09-06T17:13:11.462593
2015-09-26T18:20:40
2015-09-26T18:20:40
42,757,369
0
0
null
null
null
null
UTF-8
Scheme
false
false
611
sls
xml-schema-keyref.sls
(library (system xml schema xml-schema-keyref) (export new is? xml-schema-keyref? refer-get refer-set! refer-update!) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Xml.Schema.XmlSchemaKeyref a ...))))) (define (is? a) (clr-is System.Xml.Schema.XmlSchemaKeyref a)) (define (xml-schema-keyref? a) (clr-is System.Xml.Schema.XmlSchemaKeyref a)) (define-field-port refer-get refer-set! refer-update! (property:) System.Xml.Schema.XmlSchemaKeyref Refer System.Xml.XmlQualifiedName))
true
020e79bdc7c8ffe2a66a49ed8103dd277eed8820
a8216d80b80e4cb429086f0f9ac62f91e09498d3
/lib/chibi/base64.sld
9951113d9c5e6ec5789009b972c906905f6bd486
[ "BSD-3-Clause" ]
permissive
ashinn/chibi-scheme
3e03ee86c0af611f081a38edb12902e4245fb102
67fdb283b667c8f340a5dc7259eaf44825bc90bc
refs/heads/master
2023-08-24T11:16:42.175821
2023-06-20T13:19:19
2023-06-20T13:19:19
32,322,244
1,290
223
NOASSERTION
2023-08-29T11:54:14
2015-03-16T12:05:57
Scheme
UTF-8
Scheme
false
false
1,196
sld
base64.sld
(define-library (chibi base64) (export base64-encode base64-encode-string base64-encode-bytevector base64-decode base64-decode-string base64-decode-bytevector base64-encode-header) (import (scheme base) (chibi string)) (cond-expand ((library (srfi 151)) (import (srfi 151))) ((library (srfi 33)) (import (srfi 33)) (begin (define (%mask size) (bitwise-not (arithmetic-shift -1 size))) (define (bit-field n start end) (bitwise-and (arithmetic-shift n (- start)) (mask (- end start)))))) (else (import (srfi 60)) (begin (define (%mask size) (bitwise-not (arithmetic-shift -1 size))) (define (bit-field n start end) (bitwise-and (arithmetic-shift n (- start)) (mask (- end start))))))) (cond-expand (chibi (import (chibi io))) (else (begin (define (port->string in) (let ((out (open-output-string))) (let lp () (let ((ch (read-char in))) (cond ((eof-object? ch) (get-output-string out)) (else (write-char ch out) (lp)))))))))) (include "base64.scm"))
false
8bdc424fedbb7a3660aadff318bab90c30116044
ab05b79ab17619f548d9762a46199dc9eed6b3e9
/heap/boot/first-load.scm
40ad5fff5f764c97d9e5e27a6d9d678b98758ba7
[ "BSD-2-Clause" ]
permissive
lambdaconservatory/ypsilon
2dce9ff4b5a50453937340bc757697b9b4839dee
f154436db2b3c0629623eb2a53154ad3c50270a1
refs/heads/master
2021-02-28T17:44:05.571304
2017-12-17T12:29:00
2020-03-08T12:57:52
245,719,032
1
0
NOASSERTION
2020-03-07T23:08:26
2020-03-07T23:08:25
null
UTF-8
Scheme
false
false
1,432
scm
first-load.scm
;;; Ypsilon Scheme System ;;; Copyright (c) 2004-2009 Y.FUJITA / LittleWing Company Limited. ;;; See license.txt for terms and conditions of use. ;; subr forward references (begin (set-top-level-value! '.list? list?) (set-top-level-value! '.null? null?) (set-top-level-value! '.pair? pair?) (set-top-level-value! '.car car) (set-top-level-value! '.cdr cdr) (set-top-level-value! '.caar caar) (set-top-level-value! '.cadr cadr) (set-top-level-value! '.cdar cdar) (set-top-level-value! '.cddr cddr) (set-top-level-value! '.caaar caaar) (set-top-level-value! '.caadr caadr) (set-top-level-value! '.cadar cadar) (set-top-level-value! '.caddr caddr) (set-top-level-value! '.cdaar cdaar) (set-top-level-value! '.cdadr cdadr) (set-top-level-value! '.cddar cddar) (set-top-level-value! '.cdddr cdddr) (set-top-level-value! '.cdddar cdddar) (set-top-level-value! '.caddar caddar) (set-top-level-value! '.cddadr cddadr) (set-top-level-value! '.cadadr cadadr) (set-top-level-value! '.caaadr caaadr) (set-top-level-value! '.cddddr cddddr) (set-top-level-value! '.cadddr cadddr) (set-top-level-value! '.cdaadr cdaadr) (set-top-level-value! '.cdaddr cdaddr) (set-top-level-value! '.caaddr caaddr) (set-top-level-value! '.list list) (set-top-level-value! '.cons* cons*) (set-top-level-value! '.memq memq) (set-top-level-value! '.append append) (set-top-level-value! '.apply apply))
false
a9a7c4acef8067052d7a0ab33dd9dcf70868625d
2d1029e750a1cd71a650cceea8b7e02ae854ec01
/various-prologs-exp/prolog-first-pass/prolog_staged5/query.pr.ss
81c6c63d35546a073a2cf4e555468aee26b4458b
[]
no_license
chinacat/unsorted
97f5ce41d228b70452861df707ceff9d503a0a89
46696319d2585c723bbc5bdff3a03743b1425243
refs/heads/master
2018-12-28T22:05:34.628279
2013-08-09T06:36:07
2013-08-09T06:36:07
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,745
ss
query.pr.ss
#lang scheme (require "prolog.ss") (<- (main) (query (?c1 ?d1 ?c2 ?d2))) (<- (query (?c1 ?d1 ?c2 ?d2)) (density ?c1 ?d1) (density ?c2 ?d2) (> ?d1 ?d2) (< (* 20 ?d1) (* 21 ?d2))) (<- (density ?c ?d) (pop ?c ?p) (area ?c ?a) (is ?d (/ (* ?p 100) ?a))) (<- (pop china 8250)) (<- (area china 3380)) (<- (pop india 5863)) (<- (area india 1139)) (<- (pop ussr 2521)) (<- (area ussr 8708)) (<- (pop usa 2119)) (<- (area usa 3609)) (<- (pop indonesia 1276)) (<- (area indonesia 570)) (<- (pop japan 1097)) (<- (area japan 148)) (<- (pop brazil 1042)) (<- (area brazil 3288)) (<- (pop bangladesh 750)) (<- (area bangladesh 55)) (<- (pop pakistan 682)) (<- (area pakistan 311)) (<- (pop w_germany 620)) (<- (area w_germany 96)) (<- (pop nigeria 613)) (<- (area nigeria 373)) (<- (pop mexico 581)) (<- (area mexico 764)) (<- (pop uk 559)) (<- (area uk 86)) (<- (pop italy 554)) (<- (area italy 116)) (<- (pop france 525)) (<- (area france 213)) (<- (pop philippines 415)) (<- (area philippines 90)) (<- (pop thailand 410)) (<- (area thailand 200)) (<- (pop turkey 383)) (<- (area turkey 296)) (<- (pop egypt 364)) (<- (area egypt 386)) (<- (pop spain 352)) (<- (area spain 190)) (<- (pop poland 335)) (<- (area poland 121)) (<- (pop s_korea 335)) (<- (area s_korea 37)) (<- (pop iran 320)) (<- (area iran 628)) (<- (pop ethiopia 272)) (<- (area ethiopia 350)) (<- (pop argentina 251)) (<- (area argentina 1080)) (time (with-input-from-string ";\n;\n;\n;\n;\n" (lambda () (?- (main)))))
false
d181b9e34dc49a2426177d23482afd600bda5f8f
fca0221e2352708d385b790c665abab64e92a314
/redaction/benchmarks/oops/src/oops-macros.scm
af1da87119ef5acf0f0f909f339728aa8277767b
[]
no_license
sthilaid/memoire
a32fdb1f9add0cc0d97c095d11de0c52ae2ed2e2
9b26b0c76fddd5affaf06cf8aad2592b87f68069
refs/heads/master
2020-05-18T04:19:46.976457
2010-01-26T01:18:56
2010-01-26T01:18:56
141,195
1
2
null
null
null
null
UTF-8
Scheme
false
false
3,488
scm
oops-macros.scm
;;; FILE: "oops-macros.scm" ;;; IMPLEMENTS: Macros requires to use Oops ;;; LANGUAGE: Gambit Scheme (v4 beta12) ;;; AUTHOR: Ken Dickey ;;; ;;; COPYRIGHT (c) 2005 by Kenneth Alan Dickey ;;; ;;; 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. ;==============================================================; ;;; Nota Bene: be sure to (include "oops-macros.scm") !!! ;==============================================================; (define-macro (define-class name supers slots . instance-init-fun) (%moby-define-class `,name `,supers `,slots #f `,instance-init-fun)) (define-macro (define-method name . body) `(ensure-generic ,(%method `,name `,body))) (define-macro (define-generic name . default-body) (%define-generic `,name `,default-body)) ;; A Virtual Class is used for native/primitive Scheme values ;; The init-function is required and its values returned in place of an instance. ;; There are 2 interesting places where slot-overrides are used: ;; each-subclass: (class slot) and override: (instance slot). ;; - each-subclass: is used for common properties (e.g. index-type). ;; - override: is used for instance options used to create native objects ;; (e.g. size, fill). ;; Note that virtual classes allow class slots to be accessed even ;; though, for Scheme native objects, there are no instances. ;; One can access class slots of a non-instance. Obviously, it is an ;; error to try and access instance slots of non-instances! ;; Slot options are used is to transmit values to init functions. ;; E.g. (define-virtual-class <vector> <indexed> ( (fill type: <value>) ) ;; (lambda (inst) (make-vector (size inst) (fill inst)))) (define-macro (define-virtual-class name supers slots . instance-init-fun) (%moby-define-class `,name `,supers `,slots #t `,instance-init-fun)) ;; Handlers and Restarts are invoked in the dynamic context of the condition/error. (define-macro (with-handler handler . body) `(parameterize ( (%%condition-handlers%% (cons ,handler (%%condition-handlers%%))) ) ,@body)) (define-macro (with-restart restart . body) `(parameterize ( (%%restart-handlers%% (cons ,restart (%%restart-handlers%%))) ) ,@body)) (define-macro (with-handlers handlers . body) `(parameterize ( (%%condition-handlers%% (append (list ,@handlers) (%%condition-handlers%%))) ) ,@body)) (define-macro (with-restarts restarts . body) `(parameterize ( (%%restart-handlers%% (append (list ,@restarts) (%%restart-handlers%%))) ) ,@body)) ;;; Top-level Handler for oops calls (define-macro (with-oops-handler . forms) `(with-exception-catcher (lambda (exn) (signal (->oops-exception exn))) (lambda () ,@forms))) ;;(define-macro (unwind-condition handler . body) ..) ;===========================E=O=F==============================;
false
abedd126fae92f6754e4a68d10169e627c0de81e
6b8bee118bda956d0e0616cff9ab99c4654f6073
/sdk-ex/matrixMul/matrixMul.scm
2f05404fee1b9196d4791cbfab02a02b2d3413eb
[]
no_license
skchoe/2012.Functional-GPU-Programming
b3456a92531a8654ae10cda622a035e65feb762d
56efdf79842fc465770214ffb399e76a6bbb9d2a
refs/heads/master
2016-09-05T23:42:36.784524
2014-05-26T17:53:34
2014-05-26T17:53:34
20,194,204
1
0
null
null
null
null
UTF-8
Scheme
false
false
7,208
scm
matrixMul.scm
#lang scheme (require scheme/foreign scheme/system srfi/25 "../../schcuda/ffi-ext.ss" "../../schcuda/cutil_h.ss" "../../schcuda/array-utils.ss" "../../schcuda/cuda_h.ss" "../../schcuda/cuda_runtime_api_h.ss" "../../schcuda/vector_types_h.ss" "matrixMul_h.scm") (unsafe!) (define computeGold (get-ffi-obj 'computeGold (ffi-lib "libmatrixMul_gold") (_fun (C : _pointer) _pointer _pointer _int _int _int -> _void -> C) (lambda () (error "computeGold not found\n")))) (define (randomInit size) (let* ([arr (make-array (shape 0 size) 0)]) (for ([i (in-range size)]) (let* ([val (random)]) (array-set! arr i val))) arr)) (define (gen-cubin) (system "make") "data/matrixMul.sm_10.cubin") (define (my-catch-initCUDA status ctx) (printf "ERROR-caught: ~s\n" status) (let ([result (cuCtxDetach ctx)]) (printf "ERROR-detech-ctxz: ~s\n" result) (exit #f))) (define (initCUDA) (let* ([cuDevice (CUT_DEVICE_INIT_DRV)] [module_path (gen-cubin)] [ftn_name #"matrixMul"]) (let-values ([(status ctx) (cuCtxCreate 0 cuDevice)]) (printf "1: status(Context Creation) = ~s\n" status) (unless (equal? status 'CUDA_SUCCESS) (my-catch-initCUDA status ctx)) (when (equal? module_path 0) (my-catch-initCUDA 'CUDA_ERROR_NOT_FOUND ctx)) (let-values ([(result mod) (cuModuleLoad module_path)]) (printf "2: status(Module Loading) = ~s\n" result) ;(cutFree module_path) (unless (equal? 'CUDA_SUCCESS status) (my-catch-initCUDA status ctx)) (let-values ([(result hfunc) (cuModuleGetFunction mod ftn_name)]) (printf "3: status(GetFunction:~s) = ~s, ~s\n" ftn_name hfunc result) (unless (equal? 'CUDA_SUCCESS result) (my-catch-initCUDA result ctx)) (values 'CUDA_SUCCESS hfunc ctx)))))) (define (print-array addr size type) (let loop ([counter 0]) (if (equal? counter size) (begin (printf "\n") addr) (begin (printf "~s\t" (ptr-ref addr type counter)) (loop (add1 counter)))))) ; ;(define (runTest) ; (let*-values ([(status matrixMul ctx) (initCUDA)]) ; (printf "runTest 1: ~s\n" status) ; (let* ( ; [_float-size (ctype-sizeof _float)] ; [_pointer-size (ctype-sizeof _pointer)] ; ; ; ready for mem allocation for operands ; [size_A (* WA HA)] ; [mem_size_A (* _float-size size_A)] ; ;[h_pA (malloc _pointer size_A 'raw)] ; ;; [size_B (* WB HB)] ;; [mem_size_B (* _float-size size_B)] ;; ;[h_pB (malloc _pointer size_B 'raw)] ;; ;; ; ready for mem alloc for result ;; [size_C (* WC HC)] ;; [mem_size_C (* _float-size size_C)] ;; [mem_size_pC (* _pointer-size size_C)] ;; [h_pC (malloc _pointer size_C 'raw)] ;; ;[h_pC (malloc _float size_C 'raw)] ;; ;; [lst-offs (offsets-ctype (list _uint _uint _uint _long _long))] ;; ;; [h_pA (array1d->_pointer (randomInit size_A) _float)] ;; [h_pB (array1d->_pointer (randomInit size_B) _float)] ; ) ; ;; (printf "BEGIN-cudaMalloc/Free testing\n") ;; (let-values ([(a b) (cudaMalloc (malloc 1 _float) mem_size_A)]) ;; (printf "TempFree = ~s\n" (cudaFree b))) ;; (printf "END\nMemcpyTest\n") ;; (print-array h_pAtmp size_A _float) ;; (printf "End MemcpyTest\n") ; #f ;; ;malloc on device, copy hot to device, get kernel and apply ;; (let*-values ( ;;#| ;; [(resultA d_pA) (cudaMalloc #|(malloc 1 _float)|# mem_size_A)] ;; [(resultDA da) (begin ;; (printf "resultA = ~s\n" resultA) ;; (cudaMemcpy d_pA h_pA mem_size_A ;; 'cudaMemcpyHostToDevice))] ;; ;; [(resultB d_pB) (cudaMalloc #|(malloc 1 _float)|# mem_size_B)] ;; [(resultDB db) (begin ;; (printf "resultB = ~s\n" resultB) ;; (cudaMemcpy d_pB h_pB mem_size_B ;; 'cudaMemcpyHostToDevice))] ;;|# ;; [(resultC d_pC) (cudaMalloc #|(malloc 1 _float)|# mem_size_C)] ;; ;; ;; ;;function call ;; [(result1 matrixMul) (begin ;; (printf "resultC = ~s\n" resultC) ;; (cuFuncSetBlockShape ;; matrixMul BLOCK_SIZE BLOCK_SIZE 1))] ;; ;; [(result2 matrixMul) (cuFuncSetSharedSize ;; matrixMul (* 64 BLOCK_SIZE BLOCK_SIZE _float-size))] ;; ;; [(result3 matrixMul) (cuParamSetv matrixMul 0 h_pC size_C)] ;; ;; [(result4 matrixMul) (begin ;; (printf "result of paramset C = ~s\n" result3) ;; (cuParamSetv matrixMul size_C h_pA size_A))] ;; [(result5 matrixMul) (begin ;; (printf "result of paramset A = ~s\n" result4) ;; (cuParamSetv matrixMul (+ size_C size_A) h_pB size_B))] ;; [(result6 matrixMul) (begin ;; (printf "result of paramset B = ~s ~s\n" result5 size_B) ;; (cuParamSeti matrixMul (+ size_C size_A size_B) WA))] ;; ;; [(result7 matrixMul) (begin ;; (printf "result of paramset WA = ~s\n" result6) ;; (cuParamSeti matrixMul (+ size_C size_A size_B 4) WB))] ;; ;; [(result8 matrixMul) (begin ;; (printf "result of paramset WB = ~s\n" result7) ;; (cuParamSetSize matrixMul (+ size_C size_A size_B 8)))] ;;) ;; ;; (printf "Launch NOW: ~s\n" ;; (cuLaunchGrid matrixMul (/ WC BLOCK_SIZE) (/ HC BLOCK_SIZE))) ;;#| ;; (printf "cudaFreeA: ~s\n" (cudaFree d_pA)) ;; (printf "cudaFreeB: ~s\n" (cudaFree d_pB)) ;;|# ;; ;;; (for ([i (in-range size_C)]) ;;; (let* ([ ;; (let-values ([(result gv-ptr) (cudaMemcpy h_pC d_pC mem_size_C ;; 'cudaMemcpyDeviceToHost)]) ;; (let* ([ref (malloc _float size_C 'raw)] ;; [reference (computeGold ref h_pA h_pB HA WA WB)]) ;; ;; (let* ([error (cutCompareL2fe reference gv-ptr mem_size_C 1.0e-6)]) ;; (if error (printf "SUCCESS\n") (printf "FAIL\n"))) ;; ;; (free h_pA) ;; (free h_pB) ;; (free h_pC) ;; (free ref) ;; ;;)) ; ; ) ;(runTest) (initCUDA)
false
4d074ba4c71833c17caa59d819cd5a47322b652f
6a56feed6c35647c58821066bbe3ff0b324b82d9
/all-tests.scm
1bf769a3f40652096fe993c3b8baeb6cead95618
[]
no_license
jpt4/nocksche
2c12eb0d7568dd3b953f77079a87683c53ee6e46
86765c177cb55eb50ccc44959fa397e235187b05
refs/heads/master
2023-01-04T12:19:56.445719
2023-01-01T23:20:51
2023-01-01T23:20:51
153,347,616
0
0
null
null
null
null
UTF-8
Scheme
false
false
549
scm
all-tests.scm
;all-tests.scm ;20191005Z ;jpt4 ;Chez Scheme v9.5 (define-syntax test (syntax-rules () ((_ title tested-expression expected-result) (begin (printf "Testing ~s\n" title) (let* ((expected expected-result) (produced tested-expression)) (or (equal? expected produced) (printf "Failed: ~a~%Expected: ~a~%Computed: ~a~%" 'tested-expression expected produced))))))) (printf "accesory-tests\n") (load "accesory-tests.scm") (printf "nock-tests\n") (load "nock-tests.scm")
true
83766d8edb6b47831ab4df4f740a2a072051b350
e62a04ec2f72cfb2fe6b906f48fa150750f0394d
/dispatch.scm
3ebfafa15d90711b4f991fe11f44d4e1ed9a2893
[]
no_license
klutometis/incubot
4a03dbb27390edeb20de6feb882cfeb6751966c8
44f6eefaadf8d611f3230b5a5ad3e988e57996a8
refs/heads/master
2021-01-15T13:15:26.070586
2010-01-20T11:49:14
2010-01-20T11:49:14
7,971,627
3
1
null
null
null
null
UTF-8
Scheme
false
false
2,023
scm
dispatch.scm
;;; Copyright (C) 2008, Peter Danenberg (define (thread-start/timeout! timeout flag thread) (let ((thread (thread-start! thread))) (let ((join (thread-join! thread timeout flag))) (if (= join flag) (thread-terminate! thread)) join))) (define (make-timer time thunk) (make-thread (lambda () (thread-sleep! time) (thunk)))) (define (interesting? output) (not (eof-object? output))) (define maximum-length 256) (define (process-output output) (let ((length (string-length output))) (if (> length maximum-length) (string-append (string-take output maximum-length) "...") output))) (define (dispatch say string timeout) (let-values (((stdout stdin id stderr) (process* "./incubot-read" '()))) (let ((thread (thread-start! (lambda () (display string stdin) (close-output-port stdin) (let ((output (loop ((for next-line (in-port stdout read-line)) (with line #!eof next-line)) => line)) (error (read-line stderr))) (close-input-port stdout) (close-input-port stderr) (cond ((interesting? error) (say (process-output error))) ((interesting? output) (say (process-output output)))))))) (timer (make-timer timeout (lambda () (condition-case (let-values (((termination normality status) (process-wait id #t))) (if (zero? termination) (begin (process-signal id signal/term) (say (format "Eval ~A timed out." id))))) ((exn process) values)))))) (thread-start! timer) (thread-join! timer))))
false
6580db1930e818c3b497f95130ccf0ce1927e169
84c9e7520891b609bff23c6fa3267a0f7f2b6c2e
/curry.scm
f72d5499751192e4c8ae076c35d64282f8bda174
[]
no_license
masaedw/sicp
047a4577cd137ec973dd9a7bb0d4f58d29ef9cb0
11a8adf49897465c4d8bddb7e1afef04876a805d
refs/heads/master
2020-12-24T18:04:01.909864
2014-01-23T11:10:11
2014-01-23T11:17:38
6,839,863
1
0
null
null
null
null
UTF-8
Scheme
false
false
104
scm
curry.scm
(define (curry proc x) (lambda (arg) (proc x arg))) (define (main args) (print ((curry + 10) 100)))
false
0f518ff2a8daee67e39ad27fbebe6f2a7c900574
6f86602ac19983fcdfcb2710de6e95b60bfb0e02
/input/docs/TESTS.ss
6bd39eb8f9e44c1c0e4254158351948ba5b3a5b4
[ "MIT", "CC-BY-SA-3.0" ]
permissive
exercism/scheme
a28bf9451b8c070d309be9be76f832110f2969a7
d22a0f187cd3719d071240b1d5a5471e739fed81
refs/heads/main
2023-07-20T13:35:56.639056
2023-07-18T08:38:59
2023-07-18T08:38:59
30,056,632
34
37
MIT
2023-09-04T21:08:27
2015-01-30T04:46:03
Scheme
UTF-8
Scheme
false
false
592
ss
TESTS.ss
(section "Running and testing your solutions" (subsection "From the command line" (sentence "Simply type " (inline-code "make chez") " if you're using ChezScheme or " (inline-code "make guile") " if you're using GNU Guile.")) (subsection "From a REPL" (enum (item "Enter " (inline-code "test.scm") " at the repl prompt.") (item "Develop your solution in the file " (inline-code "problem.scm") " reloading as you go.") (item "Run " (inline-code "(test)") " to check your solution."))))
false
3e9308e8db1dd27a936d22076aba51bf6c38443a
58381f6c0b3def1720ca7a14a7c6f0f350f89537
/Chapter 4/4.1/4.12.scm
09f1801a896d9e90ffd05e295c8d9138c6318395
[]
no_license
yaowenqiang/SICPBook
ef559bcd07301b40d92d8ad698d60923b868f992
c8a0228ebf66d9c1ddc5ef1fcc1d05d8684f090a
refs/heads/master
2020-04-19T04:03:15.888492
2015-11-02T15:35:46
2015-11-02T15:35:46
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,240
scm
4.12.scm
#lang racket (define (find-val-in-frame var frame) (define (iter vars vals) (cond ((null? vars) false) ((eq? var (car vars)) vals) (else (iter (cdr vars) (cdr vals))))) (iter (frame-variables frame) (frame-values frame))) (define (define-variable! var val env) (let* ((frame (first-frame env)) (frame-val (find-val-in-frame var frame))) (if frame-val (set-car! frame-val val) (add-binding-to-frame! var val frame)))) (define (set-variable-value! var val env) (define (env-loop env) (if (eq? env the-empty-environment) (error "Unbound variable: SET!" var) (let* ((frame (first-frame env)) (frame-val (find-val-in-frame var frame))) (if frame-val (set-car! frame-val val) (env-loop (enclosing-environment env)))))) (env-loop env)) (define (lookup-variable-value var env) (define (env-loop env) (if (eq? env the-empty-environment) (error "Unbound variable" var) (let* ((frame (first-frame env)) (frame-val (find-val-in-frame var frame))) (if frame-val (car frame-val) (env-loop (enclosing-environment env)))))) (env-loop env))
false
34e0dd091e544056e3af93176a72813c77545146
f03b4ca9cfcdbd0817ec90869b2dba46cedd0937
/figure/angle.scm
fdc5d768d2b452e1e4dbf67c42bb6d0f07104fa7
[]
no_license
lrsjohnson/upptackt
d696059263d18cd7390eb7c3d3650954f0b5f732
9bfd2ec70b82116701e791620ab342f3e7d9750e
refs/heads/master
2021-01-19T00:08:06.163617
2015-06-24T14:01:03
2015-06-24T14:01:03
31,883,429
2
0
null
null
null
null
UTF-8
Scheme
false
false
5,173
scm
angle.scm
;;; angle.scm --- Angles ;;; Commentary: ;; Ideas: ;; - Initially three points, now vertex + two directions ;; - Counter-clockwise orientation ;; - Uniquely determining from elements forces directions ;; - naming of "arms" vs. "directions" ;; Future Ideas: ;; - Automatically discover angles from diagrams (e.g. from a pile of ;; points and segments) ;; - Angle intersections ;;; Code: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Angles ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; dir1 and dir2 are directions of the angle arms ;;; The angle sweeps from dir2 *counter clockwise* to dir1 (define-record-type <angle> (make-angle dir1 vertex dir2) angle? (dir1 angle-arm-1) (vertex angle-vertex) (dir2 angle-arm-2)) (declare-element-component-handler (component-procedure-from-getters ray-from-arm-1 angle-vertex ray-from-arm-2) angle?) (define (angle-equivalent? a1 a2) (and (point-equal? (angle-vertex a1) (angle-vertex a2)) (set-equivalent? (list (angle-arm-1 a1) (angle-arm-2 a1)) (list (angle-arm-1 a2) (angle-arm-2 a2)) direction-equal?))) (defhandler generic-element-name (lambda (angle) `(*angle* ,(element-name (angle-vertex angle)))) angle?) (defhandler print (lambda (a) (if (named? a) (element-name a) `(*angle* ,(print (angle-vertex a))))) angle?) ;;;;;;;;;;;;;;;;;;;;; Transformations on Angles ;;;;;;;;;;;;;;;;;;;;;; (define (reverse-angle a) (let ((d1 (angle-arm-1 a)) (v (angle-vertex a)) (d2 (angle-arm-2 a))) (make-angle d2 v d1))) (define (smallest-angle a) (if (> (angle-measure a) pi) (reverse-angle a) a)) ;;;;;;;;;;;;;;;;;;;;;;; Alternate Constructors ;;;;;;;;;;;;;;;;;;;;;;; (define (angle-from-points p1 vertex p2) (let ((arm1 (direction-from-points vertex p1)) (arm2 (direction-from-points vertex p2))) (make-angle arm1 vertex arm2))) (define (smallest-angle-from-points p1 vertex p2) (smallest-angle (angle-from-points p1 vertex p2))) ;;;;;;;;;;;;;;;;;;;; Angle from pairs of elements ;;;;;;;;;;;;;;;;;;;; (define angle-from (make-generic-operation 2 'angle-from)) (define (angle-from-lines l1 l2) (let ((d1 (line->direction l1)) (d2 (line->direction l2)) (p (intersect-lines l1 l2))) (make-angle d1 p d2))) (defhandler angle-from angle-from-lines line? line?) (define (angle-from-line-ray l r) (let ((vertex (ray-endpoint r))) (assert (on-line? vertex l) "Angle-from-line-ray: Vertex of ray not on line") (let ((d1 (line->direction l)) (d2 (ray->direction r))) (make-angle d1 vertex d2)))) (defhandler angle-from angle-from-line-ray line? ray?) (define (angle-from-ray-line r l) (reverse-angle (angle-from-line-ray l r))) (defhandler angle-from angle-from-ray-line ray? line?) (define (angle-from-segment-segment s1 s2) (define (angle-from-segment-internal s1 s2) (let ((vertex (segment-endpoint-1 s1))) (let ((d1 (segment->direction s1)) (d2 (segment->direction s2))) (make-angle d1 vertex d2)))) (cond ((point-equal? (segment-endpoint-1 s1) (segment-endpoint-1 s2)) (angle-from-segment-internal s1 s2)) ((point-equal? (segment-endpoint-2 s1) (segment-endpoint-1 s2)) (angle-from-segment-internal (flip s1) s2)) ((point-equal? (segment-endpoint-1 s1) (segment-endpoint-2 s2)) (angle-from-segment-internal s1 (flip s2))) ((point-equal? (segment-endpoint-2 s1) (segment-endpoint-2 s2)) (angle-from-segment-internal (flip s1) (flip s2))) (else (error "Angle-from-segment-segment must share vertex")))) (defhandler angle-from angle-from-segment-segment segment? segment?) (define (smallest-angle-from a b) (smallest-angle (angle-from a b))) ;;;;;;;;;;;;;;;;;;;;;;;; Predicates on Angles ;;;;;;;;;;;;;;;;;;;;;;;; (define (angle-measure-equal? a1 a2) (close-enuf? (angle-measure a1) (angle-measure a2))) (define (supplementary-angles? a1 a2) (close-enuf? (+ (angle-measure a1) (angle-measure a2)) pi)) (define (complementary-angles? a1 a2) (close-enuf? (+ (angle-measure a1) (angle-measure a2)) (/ pi 2.0))) ;;;;;;;;;;;;;;;;;;;;;;; Ideas for Definitions ;;;;;;;;;;;;;;;;;;;;;;;; ;;; Not currently used, but could be learned later? (define (linear-pair? a1 a2) (define (linear-pair-internal? a1 a2) (and (point-equal? (angle-vertex a1) (angle-vertex a2)) (direction-equal? (angle-arm-2 a1) (angle-arm-1 a2)) (direction-opposite? (angle-arm-1 a1) (angle-arm-2 a2)))) (or (linear-pair-internal? a1 a2) (linear-pair-internal? a2 a1))) (define (vertical-angles? a1 a2) (and (point-equal? (angle-vertex a1) (angle-vertex a2)) (direction-opposite? (angle-arm-1 a1) (angle-arm-1 a2)) (direction-opposite? (angle-arm-2 a1) (angle-arm-2 a2))))
false
ea186f23fa54ac8f33bebde94cbd4d3034a99209
bb65446a9debece8580bf0a20a229055038a5f6b
/examples/base/cnttransformation.scm
c76a6b570c3139b94cbcfc524bf6e823d8bca597
[]
no_license
arvyy/DataDrivenScreenshots
f4ee1171c03a4a51cd96a3dd26b7205335445080
bd96d5bf22fdd449d681eaa509807108f72be442
refs/heads/master
2020-11-24T13:47:33.153065
2019-12-15T12:10:37
2019-12-15T12:10:37
228,175,925
0
0
null
null
null
null
UTF-8
Scheme
false
false
877
scm
cnttransformation.scm
(use-modules (dds base) (dds gif)) ;create base shape. We'll draw same shape, but with different transformations (define base-shape (rect #:width 30 #:height 30 #:fill (color 255 10 10) #:stroke #f)) ;container without transformations (define cnt1 (cnt #:items (list base-shape))) ;container moved by 50 to right and 50 down (define cnt2 (cnt #:items (list base-shape) #:transform (translate 50 50))) ;container with multiple combined transformations -- first scaled by 2, then rotated by 45, ;and then moved by 50 right and 120 down (define cnt3 (cnt #:items (list base-shape) #:transform (combine (scale 2 2) (rotate 45) (translate 50 120)))) (define item (cnt #:items (list cnt1 cnt2 cnt3))) (define get-dds-gif (dds-gif #:item-getter (const item)))
false
07105fc1ba2f2f0468cbe7c4faa2d25837cd464f
f916d100a0510989b96deaa9d2d2f90d86ecc399
/slib/mularg.scm
3d62cf48a19f7ee1fa6a34aa9cd36a5b2b16959e
[]
no_license
jjliang/UMB-Scheme
12fd3c08c420715812f933e873110e103236ca67
d8479f2f2eb262b94be6040be5bd4e0fca073a4f
refs/heads/master
2021-01-20T11:19:37.800439
2012-09-27T22:13:50
2012-09-27T22:13:50
5,984,440
2
0
null
null
null
null
UTF-8
Scheme
false
false
297
scm
mularg.scm
;;; "mularg.scm" Redefine - and / to take more than 2 arguments. (let ((maker (lambda (op) (lambda (d1 . ds) (cond ((null? ds) (op d1)) ((null? (cdr ds)) (op d1 (car ds))) (else (for-each (lambda (d) (set! d1 (op d1 d))) ds) d1)))))) (set! / (maker /)) (set! - (maker -)))
false
5ece787cc29f7e5e53a07e58317145cae577746d
e358b0cf94ace3520adff8d078a37aef260bb130
/chapter-3/ex3.4.ss
26284df0b1e2a45aa2abaa3ae1cb982f525f0c6b
[]
no_license
dzhus/sicp
784766047402db3fad4884f7c2490b4f78ad09f8
090fa3228d58737d3558f2af5a8b5937862a1c75
refs/heads/master
2021-01-18T17:28:02.847772
2020-05-24T19:15:57
2020-05-24T20:56:00
22,468,805
0
0
null
null
null
null
UTF-8
Scheme
false
false
899
ss
ex3.4.ss
#lang racket ;; make-account which calls the cops after 7 failed access attempts (define (make-account balance password) (define tries 0) (define (call-the-cops) (error "Stay where you are")) (define (with-password given-password on-success) (if (eq? given-password password) on-success (begin (set! tries (add1 tries)) (if (> tries 7) (call-the-cops) (error "Bad password"))))) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Not enough funds")) (define (deposit amount) (set! balance (+ balance amount)) balance) (define (dispatch p m) (with-password p (cond ((eq? m 'withdraw) withdraw) ((eq? m 'deposit) deposit) (else (error "Bad request: make-account" m))))) dispatch)
false
7c5206be039d24a7b13f5a0f823919938448546d
a0298d460500bb2fbb5e079ee99f7f6699e44969
/tests/test-path.ss
0fdce02f6d1cede107b93700099f88c45115765f
[]
no_license
akce/pea
1d1c225c8e007aeb9b0b49c474f203167317b282
eb9a1e57776f56e061fe67f4414e07f0564bd1f3
refs/heads/master
2020-12-18T18:25:57.698040
2020-09-09T04:15:56
2020-09-09T04:16:06
235,483,730
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,269
ss
test-path.ss
#! /usr/bin/env scheme-script (import (rnrs) (srfi :64 testing) (irregex) (pea path)) ; module under test (test-begin "path") ;; A test uri copied from RFC3986. (define rfc-uri (make-uri "http://www.ics.uci.edu/pub/ietf/uri/#Related")) (test-assert "rfc url" (uri-url? rfc-uri)) (test-equal "rfc scheme" "http" (uri-scheme rfc-uri)) (test-equal "rfc auth" "www.ics.uci.edu" (uri-authority rfc-uri)) (test-equal "rfc path" "/pub/ietf/uri/" (uri-path rfc-uri)) (test-equal "rfc query" #f (uri-query rfc-uri)) (test-equal "rfc fragment" "Related" (uri-fragment rfc-uri)) (define rel-path (make-uri "../dir/filename.mp3")) (test-equal "rel url" #f (uri-url? rel-path)) (test-equal "rel path" "../dir/filename.mp3" (uri-path rel-path)) (test-equal "rel absolute?" #f (uri-absolute? rel-path)) (define abs-path (make-uri "/home/user/media/filename.mp4")) (test-equal "abs url" #f (uri-url? abs-path)) (test-equal "abs path" "/home/user/media/filename.mp4" (uri-path abs-path)) (test-assert "abs absolute?" (uri-absolute? abs-path)) ;; strip file tests. (test-equal "file scheme with file" "file:///home" (uri->string (uri-strip-file (make-uri "file:///home/file.mp3")))) (test-equal "no scheme with file" "/home/blah/exy" (uri->string (uri-strip-file (make-uri "/home/blah/exy/playl.m3u")))) ;;; Media types tests. (define media-list '("a.mp3" "a.flac" "a.aac" "a.wv" "a.wav" "a.ogg" "a.mp4" "a.mkv" "a.avi" "a.m4v" "a" "a.m3u" "a.m3u8" "a.pls" "a.txt" "a.log" "a.webm")) (define uri-list (map make-uri media-list)) (test-equal "media types" '(AUDIO AUDIO AUDIO AUDIO AUDIO AUDIO VIDEO VIDEO VIDEO VIDEO DIR M3U M3U PLS #f #f #f) (map uri-media-type uri-list)) (test-equal "ALL urls are AUDIO" '(AUDIO AUDIO AUDIO) (map uri-media-type (map make-uri '("http://localhost/" "file:///home/playlist" ;; NOTE for now that also includes URLs to video files! "http://127.0.0.1:80/a.mkv")))) ;;; Real path construction tests. (test-equal "single relative path" "a" (uri-build-path (map make-uri '("a")))) (test-equal "single absolute dir" "/a" (uri-build-path (map make-uri '("/a")))) (test-equal "single absolute url" "file:///" (uri-build-path (map make-uri '("file:///")))) (test-equal "a + /b" "/b" (uri-build-path (map make-uri '("a" "/b")))) (test-equal "a + http://localhost/" "http://localhost/" (uri-build-path (map make-uri '("a" "http://localhost/")))) (test-equal "/b + a" "/b/a" (uri-build-path (map make-uri '("/b" "a")))) (test-skip "/b/ + a" "/b/a" (uri-build-path (map make-uri '("/b/" "a")))) (test-equal "http://localhost + a" "http://localhost/a" (uri-build-path (map make-uri '("http://localhost" "a")))) (test-skip "http://localhost/ + a" "http://localhost/a" (uri-build-path (map make-uri '("http://localhost/" "a")))) (test-equal "a + /b + c" "/b/c" (uri-build-path (map make-uri '("a" "/b" "c")))) (test-equal "a + http://localhost + c" "http://localhost/c" (uri-build-path (map make-uri '("a" "http://localhost" "c")))) (test-end "path")
false
677bde7b706a162df6481adc2527d76ac2aaeaf3
1b1828426867c9ece3f232aaad1efbd2d59ebec7
/Chapter 3/sicp3-06.scm
705a083e5e0a1448c707fed29362fb19a67f127e
[]
no_license
vendryan/sicp
60c1338354f506e02c714a96f643275d35a7dc51
d42f0cc6f985aaf369f2760f962928381ca74332
refs/heads/main
2023-06-07T02:04:56.332591
2021-06-19T10:28:57
2021-06-19T10:28:57
369,958,898
0
0
null
null
null
null
UTF-8
Scheme
false
false
345
scm
sicp3-06.scm
(define rand (let ((init 0)) (lambda (req) (cond ((eq? req 'generate) (set! init (random-init init)) init) ((eq? req 'reset) (lambda (new) (set! init (random-init new)) init)) (else (error "Unknown request -- RAND" req)))))) (rand 'test)
false
ce7cf431085baab21e0364946892ffe9942bf906
26aaec3506b19559a353c3d316eb68f32f29458e
/modules/ln_glcore/glcore-ffi.scm
e963d3c80e993e41c302def3003406f180cbe184
[ "BSD-3-Clause" ]
permissive
mdtsandman/lambdanative
f5dc42372bc8a37e4229556b55c9b605287270cd
584739cb50e7f1c944cb5253966c6d02cd718736
refs/heads/master
2022-12-18T06:24:29.877728
2020-09-20T18:47:22
2020-09-20T18:47:22
295,607,831
1
0
NOASSERTION
2020-09-15T03:48:04
2020-09-15T03:48:03
null
UTF-8
Scheme
false
false
10,249
scm
glcore-ffi.scm
#| LambdaNative - a cross-platform Scheme framework Copyright (c) 2009-2013, University of British Columbia All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of British Columbia nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |# ;; minimal OpenGL subset ;; NOTE: texture dimensions is an issue, although is supposed to be supported! ;; In a word, the iphone will silently refuse to render non-power of two textures ;; For maximum portability graphics should adhere to power of two restriction! (c-declare #<<end-of-c-declare #ifdef MACOSX #include <Carbon/Carbon.h> #include <OpenGL/OpenGL.h> #include <AGL/agl.h> #endif #if defined(IOS) #include <OpenGLES/ES1/gl.h> #endif #if defined(ANDROID) #define GL_API #define GL_APIENTRY #include <GLES/gl.h> #endif #if defined(WIN32) || defined(LINUX) || defined(OPENBSD) || defined(NETBSD) || defined(FREEBSD) #include <GL/gl.h> #endif // blackberry #if defined(QNX) #include <GLES/gl.h> #endif end-of-c-declare ) ;; definitions (define GL_VERTEX_ARRAY ((c-lambda () int "___result = GL_VERTEX_ARRAY;"))) (define GL_COLOR_ARRAY ((c-lambda () int "___result = GL_COLOR_ARRAY;"))) (define GL_BLEND ((c-lambda () int "___result = GL_BLEND;"))) (define GL_SRC_ALPHA ((c-lambda () int "___result = GL_SRC_ALPHA;"))) (define GL_ONE_MINUS_SRC_ALPHA ((c-lambda () int "___result = GL_ONE_MINUS_SRC_ALPHA;"))) (define GL_TRIANGLES ((c-lambda () int "___result = GL_TRIANGLES;"))) (define GL_TRIANGLE_STRIP ((c-lambda () int "___result = GL_TRIANGLE_STRIP;"))) (define GL_TRIANGLE_FAN ((c-lambda () int "___result = GL_TRIANGLE_FAN;"))) (define GL_LINES ((c-lambda () int "___result = GL_LINES;"))) (define GL_LINE_STRIP ((c-lambda () int "___result = GL_LINE_STRIP;"))) (define GL_LINE_LOOP ((c-lambda () int "___result = GL_LINE_LOOP;"))) (define GL_POINTS ((c-lambda () int "___result = GL_POINTS;"))) (define GL_UNSIGNED_BYTE ((c-lambda () int "___result = GL_UNSIGNED_BYTE;"))) (define GL_FLOAT ((c-lambda () int "___result = GL_FLOAT;"))) (define GL_PROJECTION ((c-lambda () int "___result = GL_PROJECTION;"))) (define GL_MODELVIEW ((c-lambda () int "___result = GL_MODELVIEW;"))) (define GL_COLOR_BUFFER_BIT ((c-lambda () int "___result = GL_COLOR_BUFFER_BIT;"))) (define GL_TEXTURE_2D ((c-lambda () int "___result = GL_TEXTURE_2D;"))) (define GL_TEXTURE_COORD_ARRAY ((c-lambda () int "___result = GL_TEXTURE_COORD_ARRAY;"))) (define GL_SHORT ((c-lambda () int "___result = GL_SHORT;"))) (define GL_TEXTURE_MIN_FILTER ((c-lambda () int "___result = GL_TEXTURE_MIN_FILTER;"))) (define GL_TEXTURE_MAG_FILTER ((c-lambda () int "___result = GL_TEXTURE_MAG_FILTER;"))) (define GL_LINEAR ((c-lambda () int "___result = GL_LINEAR;"))) (define GL_NEAREST ((c-lambda () int "___result = GL_NEAREST;"))) (define GL_LINEAR_MIPMAP_LINEAR ((c-lambda () int "___result = GL_LINEAR_MIPMAP_LINEAR;"))) ;; 20100729: not defined on mingw32 cross compiler ;;(define GL_GENERATE_MIPMAP ((c-lambda () int "___result = GL_GENERATE_MIPMAP;"))) (define GL_RGB ((c-lambda () int "___result = GL_RGB;"))) (define GL_RGBA ((c-lambda () int "___result = GL_RGBA;"))) (define GL_ALPHA ((c-lambda () int "___result = GL_ALPHA;"))) (define GL_SCISSOR_TEST ((c-lambda () int "___result = GL_SCISSOR_TEST;"))) (define GL_TEXTURE_WRAP_S ((c-lambda () int "___result = GL_TEXTURE_WRAP_S;"))) (define GL_TEXTURE_WRAP_T ((c-lambda () int "___result = GL_TEXTURE_WRAP_T;"))) (define GL_REPEAT ((c-lambda () int "___result = GL_REPEAT;"))) ;; GL_CLAMP/GL_CLAMP_TO_EDGE confusion (define GL_CLAMP ((c-lambda () int "#ifdef WIN32 ___result = GL_CLAMP; #else ___result = GL_CLAMP_TO_EDGE; #endif"))) (define GL_INVALID_VALUE ((c-lambda () int "___result = GL_INVALID_VALUE;"))) ;; 3D related (define GL_DEPTH_BUFFER_BIT ((c-lambda () int "___result = GL_DEPTH_BUFFER_BIT;"))) (define GL_DEPTH_TEST ((c-lambda () int "___result = GL_DEPTH_TEST;"))) (define GL_CULL_FACE ((c-lambda () int "___result = GL_CULL_FACE;"))) (define GL_FRONT ((c-lambda () int "___result = GL_FRONT;"))) (define GL_BACK ((c-lambda () int "___result = GL_BACK;"))) (define GL_TRUE ((c-lambda () int "___result = GL_TRUE;"))) (define GL_LINE_SMOOTH ((c-lambda () int "___result = GL_LINE_SMOOTH;"))) ;;(define GL_ ((c-lambda () int "___result = GL_;"))) ;; functions ;; glOrtho is different in OpenGL and GLES. Why, thanks dudes! (define (glOrtho arg1 arg2 arg3 arg4 arg5 arg6) ((c-lambda (float float float float float float) void "#if defined(IOS)||defined(ANDROID)||defined(QNX) glOrthof(___arg1,___arg2,___arg3,___arg4,___arg5,___arg6); #else glOrtho(___arg1,___arg2,___arg3,___arg4,___arg5,___arg6); #endif") (flo arg1) (flo arg2) (flo arg3) (flo arg4) (flo arg5) (flo arg6))) (define (glFrustum arg1 arg2 arg3 arg4 arg5 arg6) ((c-lambda (float float float float float float) void "#if defined(IOS)||defined(ANDROID)||defined(QNX) glFrustumf(___arg1,___arg2,___arg3,___arg4,___arg5,___arg6); #else glFrustum(___arg1,___arg2,___arg3,___arg4,___arg5,___arg6); #endif ") (flo arg1) (flo arg2) (flo arg3) (flo arg4) (flo arg5) (flo arg6))) (define glLoadIdentity (c-lambda () void "glLoadIdentity")) (define glClear (c-lambda (int) void "glClear")) (define glClearColor (c-lambda (float float float float) void "glClearColor")) (define (glColor4f a b c d) ((c-lambda (float float float float) void "glColor4f") (flo a) (flo b) (flo c) (flo d))) (define glMatrixMode (c-lambda (int) void "glMatrixMode")) (define glPushMatrix (c-lambda () void "glPushMatrix")) (define glPopMatrix (c-lambda () void "glPopMatrix")) (define glIsEnabled (c-lambda (int) int "glIsEnabled")) (define glGetError (c-lambda () int "glGetError")) (define (glTranslatef a b c) ((c-lambda (float float float) void "glTranslatef") (flo a) (flo b) (flo c))) (define (glScalef a b c) ((c-lambda (float float float) void "glScalef") (flo a) (flo b) (flo c))) (define (glRotatef a b c d) ((c-lambda (float float float float) void "glRotatef") (flo a) (flo b) (flo c) (flo d))) (define glEnable (c-lambda (int) void "glEnable")) (define glDisable (c-lambda (int) void "glDisable")) (define glBlendFunc (c-lambda (int int) void "glBlendFunc")) (define glEnableClientState (c-lambda (int) void "glEnableClientState")) (define glDisableClientState (c-lambda (int) void "glDisableClientState")) (define glDrawArrays (c-lambda (int int int) void "glDrawArrays")) (define (glVertexPointer arg1 arg2 arg3 arg4) ((c-lambda (int int int scheme-object) void "glVertexPointer(___arg1,___arg2,___arg3, ___CAST(void*,___BODY_AS(___arg4,___tSUBTYPED)));") arg1 arg2 arg3 arg4)) (define (glColorPointer arg1 arg2 arg3 arg4) ((c-lambda (int int int scheme-object) void "glColorPointer(___arg1,___arg2,___arg3, ___CAST(void*,___BODY_AS(___arg4,___tSUBTYPED)));") arg1 arg2 arg3 arg4)) (define (glTexCoordPointer arg1 arg2 arg3 arg4) ((c-lambda (int int int scheme-object) void "glTexCoordPointer(___arg1,___arg2,___arg3, ___CAST(void*,___BODY_AS(___arg4,___tSUBTYPED)));") arg1 arg2 arg3 arg4)) (define (glGenTextures arg1 arg2) ((c-lambda (int scheme-object) void "glGenTextures(___arg1,___CAST(void*,___BODY_AS(___arg2,___tSUBTYPED)));") arg1 arg2)) ;; this was (int int), which caused cfun conversion errors on android (define glBindTexture (c-lambda (unsigned-int unsigned-int) void "glBindTexture")) (define (glDeleteTextures arg1 arg2) ((c-lambda (unsigned-int scheme-object) void "glDeleteTextures(___arg1,___CAST(void*,___BODY_AS(___arg2,___tSUBTYPED)));") arg1 arg2)) (define glTexParameteri (c-lambda (int int int) void "glTexParameteri")) (define (glTexImage2D arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9) ((c-lambda (int int int int int int int int scheme-object) void "glTexImage2D(___arg1,___arg2,___arg3,___arg4,___arg5,___arg6,___arg7,___arg8, ___CAST(void*,___BODY_AS(___arg9,___tSUBTYPED)));") arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9)) ;; 20100730: added for updating existing textures (define (glTexSubImage2D arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9) ((c-lambda (int int int int int int int int scheme-object) void "glTexSubImage2D(___arg1,___arg2,___arg3,___arg4,___arg5,___arg6,___arg7,___arg8, ___CAST(void*,___BODY_AS(___arg9,___tSUBTYPED)));") arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9)) (define glLineWidth (c-lambda (float) void "glLineWidth")) (define glDepthMask (c-lambda (int) void "glDepthMask")) (define glCullFace (c-lambda (int) void "glCullFace")) (define (glReadPixels arg1 arg2 arg3 arg4 arg5 arg6 arg7) ((c-lambda (int int int int int int scheme-object) void "glReadPixels(___arg1,___arg2,___arg3,___arg4,___arg5,___arg6, ___CAST(void*,___BODY_AS(___arg7,___tSUBTYPED)));") arg1 arg2 arg3 arg4 arg5 arg6 arg7)) ;; eof
false
eea5b9115aff5c79901830bc4b8fe21e43fc0f9b
defeada37d39bca09ef76f66f38683754c0a6aa0
/UnityEngine.UI/unity-engine/ui/text.sls
3b07a56139fb964fdb7b206a28746f8dd86f3e4a
[]
no_license
futsuki/ironscheme-port
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
4e7a81b0fbeac9a47440464988e53fb118286c54
refs/heads/master
2016-09-06T17:13:11.462593
2015-09-26T18:20:40
2015-09-26T18:20:40
42,757,369
0
0
null
null
null
null
UTF-8
Scheme
false
false
6,400
sls
text.sls
(library (unity-engine ui text) (export is? text? on-rebuild-requested get-generation-settings calculate-layout-input-vertical get-text-anchor-pivot font-texture-changed calculate-layout-input-horizontal cached-text-generator cached-text-generator-for-layout default-material main-texture font-get font-set! font-update! text-get text-set! text-update! support-rich-text?-get support-rich-text?-set! support-rich-text?-update! resize-text-for-best-fit?-get resize-text-for-best-fit?-set! resize-text-for-best-fit?-update! resize-text-min-size-get resize-text-min-size-set! resize-text-min-size-update! resize-text-max-size-get resize-text-max-size-set! resize-text-max-size-update! alignment-get alignment-set! alignment-update! font-size-get font-size-set! font-size-update! horizontal-overflow-get horizontal-overflow-set! horizontal-overflow-update! vertical-overflow-get vertical-overflow-set! vertical-overflow-update! line-spacing-get line-spacing-set! line-spacing-update! font-style-get font-style-set! font-style-update! pixels-per-unit min-width preferred-width flexible-width min-height preferred-height flexible-height layout-priority) (import (ironscheme-clr-port)) (define (is? a) (clr-is UnityEngine.UI.Text a)) (define (text? a) (clr-is UnityEngine.UI.Text a)) (define-method-port on-rebuild-requested UnityEngine.UI.Text OnRebuildRequested (System.Void)) (define-method-port get-generation-settings UnityEngine.UI.Text GetGenerationSettings (UnityEngine.TextGenerationSettings UnityEngine.Vector2)) (define-method-port calculate-layout-input-vertical UnityEngine.UI.Text CalculateLayoutInputVertical (System.Void)) (define-method-port get-text-anchor-pivot UnityEngine.UI.Text GetTextAnchorPivot (static: UnityEngine.Vector2 UnityEngine.TextAnchor)) (define-method-port font-texture-changed UnityEngine.UI.Text FontTextureChanged (System.Void)) (define-method-port calculate-layout-input-horizontal UnityEngine.UI.Text CalculateLayoutInputHorizontal (System.Void)) (define-field-port cached-text-generator #f #f (property:) UnityEngine.UI.Text cachedTextGenerator UnityEngine.TextGenerator) (define-field-port cached-text-generator-for-layout #f #f (property:) UnityEngine.UI.Text cachedTextGeneratorForLayout UnityEngine.TextGenerator) (define-field-port default-material #f #f (property:) UnityEngine.UI.Text defaultMaterial UnityEngine.Material) (define-field-port main-texture #f #f (property:) UnityEngine.UI.Text mainTexture UnityEngine.Texture) (define-field-port font-get font-set! font-update! (property:) UnityEngine.UI.Text font UnityEngine.Font) (define-field-port text-get text-set! text-update! (property:) UnityEngine.UI.Text text System.String) (define-field-port support-rich-text?-get support-rich-text?-set! support-rich-text?-update! (property:) UnityEngine.UI.Text supportRichText System.Boolean) (define-field-port resize-text-for-best-fit?-get resize-text-for-best-fit?-set! resize-text-for-best-fit?-update! (property:) UnityEngine.UI.Text resizeTextForBestFit System.Boolean) (define-field-port resize-text-min-size-get resize-text-min-size-set! resize-text-min-size-update! (property:) UnityEngine.UI.Text resizeTextMinSize System.Int32) (define-field-port resize-text-max-size-get resize-text-max-size-set! resize-text-max-size-update! (property:) UnityEngine.UI.Text resizeTextMaxSize System.Int32) (define-field-port alignment-get alignment-set! alignment-update! (property:) UnityEngine.UI.Text alignment UnityEngine.TextAnchor) (define-field-port font-size-get font-size-set! font-size-update! (property:) UnityEngine.UI.Text fontSize System.Int32) (define-field-port horizontal-overflow-get horizontal-overflow-set! horizontal-overflow-update! (property:) UnityEngine.UI.Text horizontalOverflow UnityEngine.HorizontalWrapMode) (define-field-port vertical-overflow-get vertical-overflow-set! vertical-overflow-update! (property:) UnityEngine.UI.Text verticalOverflow UnityEngine.VerticalWrapMode) (define-field-port line-spacing-get line-spacing-set! line-spacing-update! (property:) UnityEngine.UI.Text lineSpacing System.Single) (define-field-port font-style-get font-style-set! font-style-update! (property:) UnityEngine.UI.Text fontStyle UnityEngine.FontStyle) (define-field-port pixels-per-unit #f #f (property:) UnityEngine.UI.Text pixelsPerUnit System.Single) (define-field-port min-width #f #f (property:) UnityEngine.UI.Text minWidth System.Single) (define-field-port preferred-width #f #f (property:) UnityEngine.UI.Text preferredWidth System.Single) (define-field-port flexible-width #f #f (property:) UnityEngine.UI.Text flexibleWidth System.Single) (define-field-port min-height #f #f (property:) UnityEngine.UI.Text minHeight System.Single) (define-field-port preferred-height #f #f (property:) UnityEngine.UI.Text preferredHeight System.Single) (define-field-port flexible-height #f #f (property:) UnityEngine.UI.Text flexibleHeight System.Single) (define-field-port layout-priority #f #f (property:) UnityEngine.UI.Text layoutPriority System.Int32))
false
a28b6174baf1f9dcc39caca1355a0fa59ba5c124
9f466767730a64747f02ee934138fcc88c93e1fe
/opengl/lib.scm
fb3a71d50d94e63614058ce6f1a1a7cf519614a4
[]
no_license
lemvik/scheme-playground
81258bd3b5c847e019dfc6088ff1d806fe5dbc74
d32ab822857ecebd82ee28cd97bbbc07b1b56e3f
refs/heads/master
2021-01-25T04:58:15.536631
2017-06-16T13:32:13
2017-06-16T13:32:13
93,491,658
0
0
null
null
null
null
UTF-8
Scheme
false
false
5,249
scm
lib.scm
; -*- geiser-scheme-implementation: chez -*- ;;;; ;;;; OpenGL functions. ;;;; All functions in this package assume that proper OpenGL context was set up. ;;;; (library (opengl lib) (export install-opengl-debug-callback! opengl-state-shaders application-opengl-state set-buffer-data allocate-buffers allocate-vertex-arrays) (import (chezscheme) (containers rvector) (opengl raw)) ;; Error to raise in case of OpenGL errors. (define-condition-type &opengl-error &condition make-opengl-error opengl-error? (message message)) ;; Parameter holding current opengl-debug-callback. (define debug-callback #f) ;; Installs/uninstalls OpenGL debugging callback using given procedure. ;; Procedure must accept following parameters: ;; source, type, id, severity, size, message and param (define (install-opengl-debug-callback! callback) (set! debug-callback (foreign-callable callback (int int unsigned-int int int string uptr) void)) (lock-object debug-callback) (gl-debug-message-callback (foreign-callable-entry-point debug-callback) 0)) (define (uninstall-opengl-debug-callback!) (gl-debug-message-callback 0 0) (unlock-object debug-callback) (set! debug-callback #f)) ;; Retains currently active and defined buffers. (define-record-type opengl-state (nongenerative) (fields (immutable buffer-mapping) (immutable vertex-arrays) (immutable shaders))) ;; Allocates and initializes buffers-state structure. (define (allocate-opengl-state) (make-opengl-state (make-eqv-hashtable) (make-eqv-hashtable) (make-eqv-hashtable))) ;; Global parameter for managing buffers state. (define application-opengl-state (make-parameter (allocate-opengl-state) (lambda (st) (unless (opengl-state? st) (raise (make-opengl-error "Cannot assign non-opengl-state to application-opengl-state parameter."))) st))) ;; Marker for unbound buffer in buffers state. (define unbound-buffer-marker (gensym "unbound-buffer-marker")) ;; Allocates a number of some OpenGL entities via allocator and feeds them into consumer. ;; Allocator is a function of number X bytevector that allocates entities into given bytevector ;; Consumer is a function of one argument that gets the read id. (define (opengl-allocate number allocator consumer) (let* ([size (foreign-sizeof 'unsigned-int)] [storage (make-bytevector (* number size))] [result (make-vector number)]) (allocator number storage) (do ([i 0 (+ 1 i)]) ((>= i number) result) (let ([id (bytevector-u32-native-ref storage (* i size))]) (consumer id) (vector-set! result i id))))) ;; Allocates buffers and returns a vector of allocated buffers. (define (allocate-buffers number) (opengl-allocate number gl-gen-buffers (lambda (id) (hashtable-set! (opengl-state-buffer-mapping (application-opengl-state)) id unbound-buffer-marker)))) ;; Allocates vertex arrays and returns a vector of them. (define (allocate-vertex-arrays number) (opengl-allocate number gl-gen-vertex-arrays (lambda (id) (hashtable-set! (opengl-state-vertex-arrays (application-opengl-state)) id unbound-buffer-marker)))) ;; Binds given buffer to a given target. (define (bind-buffer buffer-id buffer-type) (assert (buffer-exists? buffer-id)) (gl-bind-buffer buffer-type buffer-id) (hashtable-set! (opengl-state-buffer-mapping (application-opengl-state)) buffer-id buffer-type)) ;; Binds given vertex array. (define (bind-vertex-array vertex-array-id) (assert (vertex-array-exists? vertex-array-id)) (gl-bind-vertex-array vertex-array-id)) ;; Checks if given buffer exists in the buffers-state (define (buffer-exists? buffer-id) (hashtable-contains? (opengl-state-buffer-mapping (application-opengl-state)) buffer-id)) ;; Checks if given vertex array exists. (define (vertex-array-exists? vertex-array-id) (hashtable-contains? (opengl-state-vertex-arrays (application-opengl-state)) vertex-array-id)) ;; Allocates array buffer of appropriate size, sets it's data and draw-type and returns id of the buffer. (define (set-buffer-data buffer-id buffer-type source-buffer draw-type) (bind-buffer buffer-id buffer-type) (gl-buffer-data buffer-type (bytevector-length source-buffer) source-buffer draw-type) buffer-id) ;; Unsets the array buffer data (effectively by assigning an empty array to that). (define (unset-buffer-data buffer-id buffer-type) (set-buffer-data buffer-id buffer-type #vu8() :gl-static-draw)))
false
16b72c309a23e6d21ed03dc6a21a3c2a82da3334
958488bc7f3c2044206e0358e56d7690b6ae696c
/scheme/macro/eccentric.scm
30a3256218ddc7bbf7a4e712ff6d5baf762df618
[]
no_license
possientis/Prog
a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4
d4b3debc37610a88e0dac3ac5914903604fd1d1f
refs/heads/master
2023-08-17T09:15:17.723600
2023-08-11T12:32:59
2023-08-11T12:32:59
40,361,602
3
0
null
2023-03-27T05:53:58
2015-08-07T13:24:19
Coq
UTF-8
Scheme
false
false
76,189
scm
eccentric.scm
; JRM's Syntax-rules Primer for the Merely Eccentric ; In learning to write Scheme macros, I have noticed that it is easy to ; find both trivial examples and extraordinarily complex examples, but ; there seem to be no intermediate ones. I have discovered a few tricks ; in writing macros and perhaps some people will find them helpful. ; The basic purpose of a macro is *syntactic* abstraction. As functions ; allow you to extend the functionality of the underlying Scheme ; language, macros allow you to extend the syntax. A well designed ; macro can greatly increase the readability of a program, but a poorly ; designed one can make a program completely unreadable. ; Macros are also often used as a substitute for functions to improve ; performance. In an ideal world this would be unnecessary, but ; compilers have limitations and a macro can often provide a ; workaround. In these cases, the macro should be a `drop-in' ; replacement for the equivalent function, and the design goal is not to ; extend the syntax of the language but to mimic the existing syntax as ; much as possible. ; Very simple macros ; SYNTAX-RULES provides very powerful pattern-matching and destructuring ; facilities. With very simple macros, however, most of this power is ; unused. Here is an example: (define-syntax nth-value (syntax-rules () ((nth-value n values-producing-form) (call-with-values (lambda () values-producing-form) (lambda all-values (list-ref all-values n)))))) ; When using functions that return multiple values, it is occasionally ; the case that you are interested in only one of the return values. ; The NTH-VALUE macro evaluates the VALUES-PRODUCING-FORM and extracts ; the Nth return value. ; Before the macro has been evaluated, Scheme would treat a form that ; begins with NTH-VALUE as it would any other form: it would look up ; the value of the variable NTH-VALUE in the current environment and ; apply it to the values produced by evaluating the arguments. ; DEFINE-SYNTAX introduces a new special form to Scheme. Forms that ; begin with NTH-VALUE are no longer simple procedure applications. ; When Scheme processes such a form, it uses the SYNTAX-RULES we provide ; to rewrite the form. The resulting rewrite is then processed in place ; of the original form. ; *** Forms are only rewritten if the operator position is an IDENTIFIER ; that has been DEFINE-SYNTAX'd. Other uses of the identifier are ; not rewritten. ; You cannot write an `infix' macro, nor can you write a macro in a ; `nested position', i.e., an expression like ((foo x) y z) is ; always considered a procedure application. (The subexpression (foo x) ; will be rewritten of course, but it will not be able to affect the ; processing of subexpressions y and z.) This will be important later ; on. ; SYNTAX-RULES is based on token-replacement. SYNTAX-RULES defines a ; series of patterns and templates. The form is matched against the ; pattern and the various pieces are transcribed into the template. ; This seems simple enough, but there is one important thing to always ; keep in mind. ; *** THE SYNTAX-RULES SUBLANGUAGE IS NOT SCHEME! ; This is a crucial point that is easy to forget. In the example, (define-syntax nth-value (syntax-rules () ((nth-value n values-producing-form) (call-with-values (lambda () values-producing-form) (lambda all-values (list-ref all-values n)))))) ; the pattern (nth-value n values-producing-form) looks like Scheme code ; and the template (call-with-values (lambda () values-producing-form) (lambda all-values (list-ref all-values n))) ; *really* seems to be Scheme code, but when Scheme is applying the ; syntax-rules rewrite there is NO SEMANTIC MEANING attached to the ; tokens. The meaning will be attached at a later point in the process, ; but not here. ; One reason this is easy to forget is that in a large number of cases ; it doesn't make a difference, but when you write more complicated ; rules you may find unexpected expansions. Keeping in mind that ; syntax-rules only manipulates patterns and templates will help avoid ; confusion. ; This example makes good use of patterns and templates. Consider the ; form (nth-value 1 (let ((q (get-number))) (quotient/remainder q d))) ; During the expansion of NTH-VALUE, the *entire* subform ; (let ((q (get-number))) (quotient/remainder q d)) is bound to ; VALUES-PRODUCING-FORM and transcribed into the template at ; (lambda () values-producing-form) The example would not work if ; VALUES-PRODUCING-FORM could only be bound to a symbol or number. ; A pattern consists of a symbol, a constant, a list (proper or ; improper) or vector of more patterns, or the special token "..." (A ; series of three consecutive dots in this paper will *always* mean the ; literal token "..." and *never* be used for any other reason.) It is ; not allowed to use the same symbol twice in a pattern. Since ; the pattern is matched against the form, and since the form *always* ; starts with the defined keyword, it does not participate in the match. ; You may reserve some symbols as `literals' by placing them in the list ; that is the first argument to syntax-rules. Essentially, they will be ; treated as if they were constants but there is some trickiness that ; ensures that users of the macro can still use those names as ; variables. The trickiness `does the right thing' so I won't go into ; details. ; You may find macros written using the token "_" rather than repeating ; the name of the macro: (define-syntax nth-value (syntax-rules () ((_ n values-producing-form) (call-with-values (lambda () values-producing-form) (lambda all-values (list-ref all-values n)))))) ; I personally find this to be confusing and would rather duplicate the ; macro name. ; Here are the rules for pattern matching: ; - A constant pattern will only match against an EQUAL? constant. ; We'll exploit this later on. ; - A symbol that is one of the `literals' can only match against the ; exact same symbol in the form, and then only if the macro user ; hasn't shadowed it. ; - A symbol that is *not* one of the literals can match against *any* ; complete form. (Forgetting this can lead to surprising bugs.) ; - A proper list of patterns can only match against a list form of ; the same length and only if the subpatterns match. ; - An improper list of patterns can only match against a list form of ; the same or greater length and only if the subpatterns match. The ; `dotted tail' of the pattern will be matched against the remaining ; elements of the form. It rarely makes sense to use anything but a ; symbol in the dotted tail of the pattern. ; - The ... token is special and will be discussed a bit later. ; Debugging macros ; As macros get more complicated, they become trickier to debug. Most ; Scheme systems have a mechanism by which you can invoke the macro ; expansion system on a piece of list structure and get back the ; expanded form. In MzScheme you could do this: (syntax-object->datum (expand '(nth-value 1 (let ((q (get-number))) (quotient/remainder q d))))) ; In MIT Scheme, (unsyntax (syntax '(nth-value 1 (let ((q (get-number))) (quotient/remainder q d))) (nearest-repl/environment))) ; Be prepared for some interesting output --- you may not realize how ; many forms are really macros and how much code is produced. The macro ; system may recognize and optimize certain patterns of function usage ; as well. It would not be unusual to see (caddr x) expand into ; (car (cdr (cdr x))) or into (%general-car-cdr 6 x). ; Be prepared, too, for some inexplicable constructs. Some syntax ; objects may refer to bindings that are only lexically visible from ; within the expander. Syntax objects may contain information that is ; lost when they are converted back into list structure. You may ; encounter apparently illegal expansions like this: (lambda (temp temp temp) (set! a temp) (set! b temp) (set! c temp)) ; There are three internal syntax objects that represent the three ; different parameters to the lambda expression, and each assignment ; referred to a unique one, but each individual syntax object had the ; same symbolic name, so their unique identity was lost when they were ; turned back into list structure. ; *** Debugging trick ; One very easy debugging trick is to wrap the template with a quote: (define-syntax nth-value (syntax-rules () ((_ n values-producing-form) '(call-with-values ;; Note the quote! (lambda () values-producing-form) (lambda all-values (list-ref all-values n)))))) ; Now the macro returns the filled-in template as a quoted list: (nth-value (compute-n) (compute-values)) ; => (call-with-values (lambda () (compute-values)) ; (lambda all-values (list-ref all-values (compute-n)))) ; Sometimes it is difficult to understand why a pattern didn't match ; something you thought it should or why it did match something it ; shouldn't. It is easy to write a pattern testing macro: (define-syntax test-pattern (syntax-rules () ((test-pattern one two) "match 1") ((test-pattern one two three) "match 2") ((test-pattern . default) "fail"))) *** Debugging trick A second trick is to write a debugging template: (define-syntax nth-value (syntax-rules () ((_ n values-producing-form) '("Debugging template for nth-value" "n is" n "values-producing-form is" values-producing-form)))) ; N-ary macros ; By using a dotted tail in the pattern we can write macros that take an ; arbitrary number of arguments. (define-syntax when (syntax-rules () ((when condition . body) (if condition (begin . body) #f)))) ; An example usage is (when (negative? x) (newline) (display "Bad number: negative.")) ; The pattern matches as follows: ; condition = (negative? x) ; body = ((newline) (display "Bad number: negative.")) ; Since the pattern variable `body' is in the dotted tail position, it ; is matched against the list of remaining elements in the form. This ; can lead to unusual errors. Suppose I had written the macro this way: (define-syntax when (syntax-rules () ((when condition . body) (if condition (begin body) #f)))) ; The pattern is matched against the list of remaining arguments, so in ; the template it will expand to a list: (when (negative? x) (newline) (display "Bad number: negative.")) ; expands to (if (negative? x) (begin ((newline) (display "Bad number: negative."))) #f) ; But this *almost* works. The consequence of the condition is ; evaluated as if it were a function call. The `function' is the ; return value of the call to newline and the `argument' the return ; value from display. Since the rules for evaluation are to evaluate ; the subforms and then apply the resulting procedure to the resulting ; arguments, this may actually print a newline and display the string ; "Bad number: negative." before raising an error. One could easily ; be fooled into thinking that the WHEN form succesfully ran to ; completion and it was the code *subsequent* to the WHEN that raised ; the error. ; The original code had this in the template: (begin . body) ; When the template is filled in, the body is placed in `the dotted ; tail'. Since the body is a list of forms, the effect is as if you had ; used CONS rather than LIST to create the resultant form. ; Unfortunately, this trick does not generalize; you can only prefix ; things in this manner. ; ; *** Macro `rest args' get bound to a list of forms, so remember to ; `unlist' them at some point. ; There is another bug in the original form: (define-syntax when (syntax-rules () ((when condition . body) (if condition (begin . body) #f)))) (when (< x 5)) ; expands into (if (< x 5) (begin) #f) ; Recall that pattern variables match anything, including the empty ; list. The pattern variable BODY is bound to the empty list. When the ; template form (begin . body) is filled in, the token BEGIN is consed ; to the empty list resulting in an illegal (BEGIN) form. ; Since (when (< x 5)) is unusual itself, one solution is to modify the ; macro like this: (define-syntax when (syntax-rules () ((when condition form . forms) (if condition (begin form . forms) #f)))) ; Now the pattern will match only if the WHEN expression has at least ; one consequent form and the resulting BEGIN subform is guaranteed to ; contain at least one form. ; This sort of macro --- one that takes an arbitrary number of subforms ; and evaluates them in an `implicit begin' --- is extremely common. It ; is valuable to know this macro idiom: ; *** Implicit Begin idiom ; Use this idiom for a macro that allows an arbitrary number of ; subforms and processes them sequentially (possibly returning the ; value of the last subform). ; The pattern should end in "FORM . FORMS)" to ensure a minimum of ; one subform. ; The template has either (begin form . forms) or uses the implicit ; begin of another special form, e.g. (lambda () form . forms) ; A strange and subtle bug ; This section describes a bug in the syntax-rules expander for MzScheme ; v207. A fix has been made to the sources, so versions later than this ; ought to work. You can skip this section (about 1 page) if you wish. ; Suppose you are a former INTERCAL hacker and you truly miss the ; language. You wish to write a macro PLEASE that simply removes ; itself from the expansion: ; (please display "foo") => (display "foo") ; Here is an attempt: (define-syntax please (syntax-rules () ((please . forms) forms))) ; This works on some Scheme systems, but not on others and the reason is ; quite subtle. In Scheme, function application is indicated ; syntactically by a list consisting of a function and zero or more ; arguments. Above macro, although it returns such a list, creates that ; list as part of the pattern matching process. When a macro is ; expanded careful attention is paid to ensure that subforms from the ; point of use continue to refer to the lexical environment at that ; point while subforms that are introduced by the template continue to ; refer to the lexical environment of the macro definition. The list ; that is returned from the PLEASE macro, however, is a subform that was ; not created at either the macro use point *or* at the macro definition ; point, but rather in the environment of the pattern matcher. In ; MzScheme, that environment does not have a syntactic mapping to ; interpret a list as a function call, so the following error results: ; "compile: bad syntax; function application is not allowed, because ; no #%app syntax transformer is bound in: (display 33)" ; The fix is trivial: (define-syntax please (syntax-rules () ((please function . arguments) (function . arguments)))) ; The resulting expansion is now a list constructed within the template ; of the macro rather than one constructed by the pattern matcher. The ; template environment is used and the resulting list is therefore ; interpreted as a function call. ; ; Again, this is an extremely subtle point, but it is easy to remember ; this rule of thumb: ; ; *** Don't use macro `rest' arguments as an implicit function call. ; Use a template with an explicit (function . arguments) element. ; ; ; END OF STRANGE AND SUBTLE BUG SECTION ; ; ; ; Multiple patterns ; ; Syntax rules allows for an arbitrary number of pattern/template pairs. ; When a form is to be rewritten, a match is attempted against the first ; pattern. If the pattern cannot be matched, the next pattern is ; examined. The template associated with the first matching pattern is ; the one used for the rewrite. If no pattern matches, an error is ; raised. We will exploit this heavily. ; ; Syntax errors ; ; The macro system will raise an error if no pattern matches the form, ; but it will become useful to us to write patterns that explicitly ; reject a form if the pattern *does* match. This is easily ; accomplished by making the template for a pattern expand into poorly ; formed code, but the resulting error message is rather unhelpful: (define-syntax prohibit-one-arg (syntax-rules () ((prohibit-one-arg function argument) (if)) ;; bogus expansion ((prohibit-one-arg function . arguments) (function . arguments)))) (prohibit-one-arg + 2 3) ; => 5 (prohibit-one-arg display 'foo) ; if: bad syntax (has 0 parts after keyword) in: (if) ; To make a more helpful error message, and to indicate in the macro ; definition that the bogus expansion is intentional, we'll define a ; macro designed to raise a syntax error. (There is, no doubt a ; procedural way of doing this, but we wish to raise this error during ; macro expansion and the pattern language provides no way to do this ; directly. A more complicated macro system could be used, but this is ; nice, easy, and portable.) (define-syntax syntax-error (syntax-rules () ((syntax-error) (syntax-error "Bad use of syntax error!")))) ; We can now write macros that expand into `calls' to syntax error. If ; the call contains any arguments, the pattern will not match and an ; error will be raised. Most scheme macro systems display the form that ; failed to match, so we can put our debugging messages there. (define-syntax prohibit-one-arg (syntax-rules () ((prohibit-one-arg function argument) (syntax-error "Prohibit-one-arg cannot be used with one argument." function argument)) ((prohibit-one-arg function . arguments) (function . arguments)))) (prohibit-one-arg display 3) ; => syntax-error: bad syntax in: (syntax-error "Prohibit-one-arg cannot ; be used with one argument." display 3) ; *** Write a syntax-error macro. ; Write `rejection' patterns by expanding into a call to ; syntax-error. ; `Accidental' matching ; The pattern roughly resembles what it matches, but this can be a ; source of confusion. A pattern like this: (my-named-let name (binding . more-bindings) . body) ; will match this form: (my-named-let ((x 22) (y "computing square root")) (display y) (display (sqrt x))) ; as follows: name = ((x 22) (y "computing square root")) binding = display more-bindings = (y) body = ((display (sqrt x))) ; *** Nested list structure in the pattern will match similar nested ; list structure in the form, but symbols in the pattern will match ; *anything*. ; In this example we want to prohibit matching NAME with a list. We do ; this by `guarding' the intended pattern with patterns that should not ; be allowed. (define-syntax my-named-let (syntax-rules () ((my-named-let () . ignore) (syntax-error "NAME must not be the empty list.")) ((my-named-let (car . cdr) . ignore) (syntax-error "NAME must be a symbol." (car . cdr))) ((my-named-let name bindings form . forms) ;; implicit begin (let name bindings form . forms)))) ; *** Protect against accidental pattern matching by writing guard ; patterns that match the bad syntax. ; Recursive expansion ; ; Our syntax-error macro can expand into a syntax-error form. If the ; result of a macro expansion is itself a macro form, that resulting ; macro form will be expanded. This process continues until either the ; resulting form is not a macro call or the resulting form fails to ; match a pattern. The syntax-error macro is designed to fail to match ; anything but a no-argument call. A no-argument call to syntax-error ; expands into a one-argument call to syntax-error which fails to match. ; ; The template for a macro can expand to a form that embeds a call to ; the same macro within it. The embedded code will be expanded normally ; if the surrounding code treats it as a normal form. The embedded call ; will normally contain fewer forms than the original call so that the ; expansion eventually terminates with a trivial expansion. ; ; Note, however, that the recursive macro will not be expanded unless ; the intermediate code uses it as a macro call. This is why the ; debugging trick of quoting the template works: the macro form is ; expanded to a quote form. The quote form just treats its argument as ; data so no further expansion is done. ; ; Recursive expansion always produces a nested result. This is used to ; good effect in this example: (define-syntax bind-variables (syntax-rules () ((_ () form . forms) (begin form . forms)) ((_ ((var val0 val1 . more) . more-bindings) form . forms) (syntax-error "bind-variables illegal binding" (var val0 val1 . more))) ((_ ((variable value) . more-bindings) form . forms) (let ((variable value)) (bind-variables more-bindings form . forms))) ((_ ((variable) . more-bindings) form . forms) (let ((variable #f)) (bind-variables more-bindings form . forms))) ((_ (variable . more-bindings) form . forms) (let ((variable #f)) (bind-variables more-bindings form . forms))) ((_ bindings form . forms) (syntax-error "Bindings must be a list." bindings)))) ; BIND-VARIABLES is much like LET*, but you are allowed to omit the ; value in the binding list. If you omit the value, the variable will ; be bound to #F. You can also omit the parenthesis around the variable ; name. (bind-variables ((a 1) ;; a will be 1 (b) ;; b will be #F c ;; so will c (d (+ a 3))) ;; a is visible in this scope. (list a b c d)) ; When bind-variables is processed, its immediate expansion is this: (let ((a 1)) (bind-variables ((b) c (d (+ a 3))) (list a b c d))) ; The LET form is now processed and as part of that processing the body ; of the LET will be expanded. (bind-variables ((b) c (d (+ a 3))) (list a b c d)) ; This expands into another LET form: (let ((b #f)) (bind-variables (c (d (+ a 3))) (list a b c d))) ; The process terminates when the binding list is the empty list. At ; this point each level of expansion is placed back in its surrounding ; context to yield this nested structure: (let ((a 1)) (let ((b #f)) (let ((c #f)) (let ((d (+ a 3))) (list a b c d))))) ; There are several things to note here: ; ; 1. The macro uses the implicit begin idiom. ; ; 2. There is a `guard' patterns to match bindings with more than one ; value form. ; ; 3. In each expansion, the first binding will be removed. The ; remaining bindings appear in the binding position at the ; recursive call, thus the macro is inductive over the list of ; bindings. ; ; 4. There is a base case of the induction that matches the empty ; binding list. ; ; 5. On each iteration a match is attempted on first binding against ; these patterns in order: ; ; (variable value0 value1 . more) a list of more than two elements ; ; (variable value) a list of exactly two elements ; ; (variable) a list of one element ; ; variable not a list ; ; This order is used because the last pattern will match anything ; and would prevent the previous matches from being matched. ; ; This macro idiom is also extremely common. ; ; *** List Recursion idiom ; ; This idiom is used to recursively process a list of macro ; subforms. ; ; The macro has a parenthesised list of items in a fixed position. ; This list may be empty (), but it may not be omitted. ; ; A pattern that matches the empty list at that position preceeds ; the other matches. The template for this pattern does not include ; another use of this macro. ; ; One or more patterns that have dotted tails in the list position ; are present. The patterns are ordered from most-specific to ; most-general to ensure that the later matches do not `shadow' the ; earlier ones. The associated templates are either syntax-errors ; or contain another use of this macro. The list position in the ; recursive call will contain the dotted tail component. ; ; A minimal list recursion looks like this: (define-syntax mli (syntax-rules () ((mli ()) (base-case)) ((mli (item . remaining)) (f item (mli remaining))) ((mli non-list) (syntax-error "not a list"))))) ; Note that the recursive call in the second clause uses the pattern ; variable REMAINING and that it is NOT dotted. Each recursive call ; therefore contains a shorter list of forms at the same point. ; ; <<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>> ; ; At this point, things are starting to get complicated. We can no ; longer look upon macros as `simple rewrites'. We are starting to ; write macros whose purpose is to control the actions of the macro ; processing engine. We will be writing macros whose purpose is not to ; produce code but rather to perform computation. ; ; A macro is a compiler. It takes source code written in one language, ; i.e. Scheme with some syntactic extension, and it generates object ; code written in another language, i.e. Scheme *without* that syntactic ; extension. The language in which we will be writing these compilers ; is NOT Scheme. It is the pattern and template language of ; syntax-rules. ; ; A compiler consists of three basic phases: a parser that reads the ; source language, a transformation and translation process that maps ; the source language semantics into constructs in the target language, ; and a generator that turns the resulting target constructs into code. ; Our macros will have these three identifiable parts. The parser phase ; will use pattern language to extract code fragments from the source ; code. The translator will operate on these code fragments and use ; them to construct and manipulate Scheme code fragments. The generator ; phase will assemble the resulting Scheme fragments of Scheme code with ; a template that will be the final result. ; ; The pattern and template language of syntax-rules is an unusual ; implementation language. The pattern-driven rule model makes it easy ; to write powerful parsers. The template-driven output model makes ; code generation a snap. The automatic hygiene tracks the context of ; the code fragments and essentially allows us to manipulate the ; intermediate code fragments as elements in an abstract syntax tree. ; There is just one problem: the model of computation is ; non-procedural. Simple standard programming abstractions such as ; subroutines, named variables, structured data, and conditionals are ; not only different from Scheme, they don't exist in a recognizable ; form! ; ; But if we look carefully, we will find our familiar programming ; abstractions haven't disappeared at all --- they have been ; destructured, taken apart, and re-formed into strange shapes. We will ; be writing some strange-looking code. This code will be written in ; the form of a macro transformer, but it will not be a macro in the ; traditional sense. ; ; ; When a macro is expanded the original form is rewritten into a new ; form. If the result of macro expansion is a new macro form, the ; expander then expands that result. So if the macro expands into ; another call to itself, we have written a tail-recursive loop. We ; made a minimal use of this above with the syntax-error macro, but now ; we will be doing this as a standard practice. ; ; We encountered the list recursion idiom above. We can create an ; analagous list iteration: ; (define-syntax bind-variables1 (syntax-rules () ((_ () form . forms) (begin form . forms)) ((_ ((var val0 val1 . more) . more-bindings) form . forms) (syntax-error "bind-variables illegal binding" (var val0 val1 . more))) ((_ ((var val) . more-bindings) form . forms) (bind-variables1 more-bindings (let ((var val)) form . forms))) ((_ ((variable) . more-bindings) form . forms) (bind-variables1 more-bindings (let ((variable #f)) form . forms))) ((_ (variable . more-bindings) form . forms) (bind-variables1 more-bindings (let ((variable #f)) form . forms))) ((_ bindings form . forms) (syntax-error "Bindings must be a list." bindings)))) ; Because we process the leftmost variable first, the resulting form ; will be nested in the reverse order from the recursive version. We ; will deal with this issue later and just write the bindings list ; backwards for now. (bind-variables1 ((d (+ a 3)) ;; a is visible in this scope. c ;; c will be bound to #f (b) ;; so will b (a 1)) ;; a will be 1 (list a b c d)) This macro first expands into this: (bind-variables1 (c (b) (a 1)) (let ((d (+ a 3))) (list a b c d))) ; But since this form is a macro, the expander is run again. This ; second expansion results in this: (bind-variables1 ((b) (a 1)) (let ((c #f)) (let ((d (+ a 3))) (list a b c d)))) ; The expander is run once again to produce this: (bind-variables1 ((a 1)) (let ((b #f)) (let ((c #f)) (let ((d (+ a 3))) (list a b c d))))) ; Another iteration produces this: (bind-variables1 () (let ((a 1)) (let ((b #f)) (let ((c #f)) (let ((d (+ a 3))) (list a b c d)))))) ; The next expansion does not contain a call to the macro: (begin (let ((a 1)) (let ((b #f)) (let ((c #f)) (let ((d (+ a 3))) (list a b c d)))))) ; We could call this the `List Iteration Idiom', but let's take this in ; a completely different direction. ; Notice that the template for most of the rules begins with the macro ; name itself in order to cause the macro expander to immediately ; re-expand the result. But let's ignore the expander and pretend that ; ; *the template form is a tail-recursive function call* ; ; By removing the error checking and the multiple formats for argument ; bindings, we can see the essence of what is going on: (define-syntax bind-variables1 (syntax-rules () ((bind-variables1 () . forms) (begin . forms)) ((bind-variables1 ((variable value) . more-bindings) . forms) (bind-variables1 more-bindings (let ((variable value)) . forms))))) ; BIND-VARIABLES1 is tail-recursive function. SYNTAX-RULES functions as ; a COND expression. The arguments to bind-variables1 are unnamed, but ; by placing patterns in the appropriate positions, we can destructure ; the values passed into named variables. ; ; Let us demonstrate this insight through a simple example. ; ; We want to mimic the Common Lisp macro MULTIPLE-VALUE-SETQ. This form ; takes a list of variables and form that returns multiple values. The ; form is invoked and the variables are SET! to the respective return ; values. A putative expansion might be this: (multiple-value-set! (a b c) (generate-values)) => (call-with-values (lambda () (generate-values)) (lambda (temp-a temp-b temp-c) (set! a temp-a) (set! b temp-b) (set! c temp-c))) ; For the sake of clarity, we'll start out with no error checking. ; Since our macros are tail-recursive, we can write separate subroutines ; for each part of the expansion. ; ; First, we write the `entry-point' macro. This macro is the one that ; would be exported to the user. This macro will call the one that ; creates the temporaries and the necessary assignment expressions. It ; passes in empty lists as the initial values for these expressions. (define-syntax multiple-value-set! (syntax-rules () ((multiple-value-set! variables values-form) (gen-temps-and-sets variables () ;; initial value of temps () ;; initial value of assignments values-form)))) ; Assuming that gen-temps-and-sets does the right thing, we will ; want to emit the resulting code. The code is obvious: (define-syntax emit-cwv-form (syntax-rules () ((emit-cwv-form temps assignments values-form) (call-with-values (lambda () values-form) (lambda temps . assignments))))) ; The temps and assignments are just pasted into the right spots. ; ; Now we need to write the routine that generates a temporary and ; an assignment for each variable. We'll again use induction on the ; list of variables. When that list is empty, we'll call EMIT-CMV-FORM ; with the collected results. On each iteration we'll remove one ; variable, generate the temporary and assignment for that variable, and ; collect them with the other temporaries and assignments. (define-syntax gen-temps-and-sets (syntax-rules () ((gen-temps-and-sets () temps assignments values-form) (emit-cwv-form temps assignments values-form)) ((gen-temps-and-sets (variable . more) temps assignments values-form) (gen-temps-and-sets more (temp . temps) ((set! variable temp) . assignments) values-form)))) ; <<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>> ; Before we develop this further, though, there are some important ; points about this macro that should not be overlooked. ; ; ``Did I ever tell you that Mrs. McCave ; Had twenty-three sons, and she named them all Dave?'' ; -- Dr. Seuss ; ; Our MULTIPLE-VALUE-SET! macro generates a temporary variable for each ; of the variables that will be assigned (this is in the second clause ; of GEN-TEMPS-AND-SETS). Unfortunately, all the temporary ; variables are named `TEMP'. We can see this if we print the expanded ; code: (call-with-values (lambda () (generate-values)) (lambda (temp temp temp) (set! c temp) (set! b temp) (set! a temp))) ; ``Well, she did. And that wasn't a smart thing to do. ; You see, when she wants one, and calls out "Yoo-Hoo! ; Come into the house, Dave!" she doesn't get one. ; All twenty-three Daves of hers come on the run!'' ; (Ibid.) ; The importance of unique identifiers to avoid name collisions is ; taught at a very young age. ; ; The funny thing is, though, the code works. There are actually three ; different syntactic objects (all named temp) that will be bound by the ; LAMBDA form, and each SET! refers to the appropriate one. But there ; are six identifiers here with the name TEMP. Why did the macro ; expander decide to create three pairs of associated syntax objects ; rather than six individual ones or two triplets? The answer lies in ; this template: (gen-temps-and-sets more (temp . temps) ((set! variable temp) . assignments) values-form) ; The variable TEMP that is being prepended to the list of temps and the ; variable TEMP in the newly created (SET! VARIABLE TEMP) form will ; refer to the *same* syntactic object because they are created during ; the same expansion step. It will be a *different* syntactic object ; than any created during any other expansion step. ; ; Since we run the expansion step three times, one for each variable to ; be assigned, we get three variables named temp. They are paired up ; properly because we generated all references to them at the same time. ; ; *** Introduce associated code fragments in a single expansion step. ; ; *** Introduce duplicated, but unassociated fragments in different ; expansion steps. ; ; Let's explore two variants of this program. We will separate the ; genaration of the temps and the assignments into two different ; functions, GEN-TEMPS and GEN-SETS. ; ; Because both GEN-TEMPS and GEN-SETS iterate over the list of variables ; as they operate, we modify MULTIPLE-VALUE-SET! to pass the list ; twice. GEN-TEMPS will do induction over one copy, GEN-SETS will work ; with the other. (define-syntax multiple-value-set! (syntax-rules () ((multiple-value-set! variables values-form) (gen-temps variables ;; provided for GEN-TEMPS () ;; initial value of temps variables ;; provided for GEN-SETS values-form)))) ; GEN-TEMPS does induction over the first list of variables and creates ; a list of temp variables. (define-syntax gen-temps (syntax-rules () ((gen-temps () temps vars-for-gen-set values-form) (gen-sets temps vars-for-gen-set () ;; initial set of assignments values-form)) ((gen-temps (variable . more) temps vars-for-gen-set values-form) (gen-temps more (temp . temps) vars-for-gen-set values-form)))) ; GEN-SETS also does induction over the list of variables and creates a ; list of assignment forms. (define-syntax gen-sets (syntax-rules () ((gen-sets temps () assignments values-form) (emit-cwv-form temps assignments values-form)) ((gen-sets temps (variable . more) assignments values-form) (gen-sets temps more ((set! variable temp) . assignments) values-form)))) ; Although the result of expansion looks similar, this version of the ; macro does not work. The name TEMP that is generated in the GEN-TEMPS ; expansion is different from the name TEMP generated in the GEN-SETS ; expansion. The expansion will contain six unrelated identifiers (all ; named TEMP). ; ; But we can fix this. Notice that GEN-SETS carries around the list of ; temps generated by GEN-TEMPS. Instead of generating a new variable ; named TEMP, we can extract the previously generated TEMP from the ; list and use that. ; ; First, we arrange for GEN-TEMPS to pass the temps twice. We need to ; destructure one of the lists to do the iteration, but we need the ; whole list for the final expansion. (define-syntax gen-temps (syntax-rules () ((gen-temps () temps vars-for-gen-set values-form) (gen-sets temps temps ;; another copy for gen-sets vars-for-gen-set () ;; initial set of assignments values-form)) ((gen-temps (variable . more) temps vars-for-gen-set values-form) (gen-temps more (temp . temps) vars-for-gen-set values-form)))) ; GEN-SETS again uses list induction, but on two parallel lists rather ; than a single list (the lists are the same length). Each time around ; the loop we bind TEMP to a previously generated temporary. (define-syntax gen-sets (syntax-rules () ((gen-sets temps () () assignments values-form) (emit-cwv-form temps assignments values-form)) ((gen-sets temps (temp . more-temps) (variable . more-vars) assignments values-form) (gen-sets temps more-temps more-vars ((set! variable temp) . assignments) values-form)))) ; Now we aren't generating new temps in GEN-SETS, we are re-using the ; old ones generated by GEN-SETS. ; ; Ellipses ; ; Ellipses are not really that difficult to understand, but they have ; three serious problems that make them seem mysterious when you first ; encounter them. ; ; - The ... operator is very strange looking. It isn't a `normal' ; token and it has a prior established meaning in the English ; language that is somewhat at odds with what it does. Macros that ; use ellipses look like `sound bites' from movie reviews. ; ; - The ... token is a reserved word in the macro language. Unlike ; all other tokens, it cannot be re-bound or quoted. In the macro ; language, ... acts like a syntactic mark of the same nature as a ; double-quote, dotted tail, or parenthesis. (It is nonsensical to ; try to use an open-parenthesis as a variable name! The same is ; true for ... in the macro language.) But in standard scheme, ; ... is an indetifier token and could conceivably be used as a ; variable. ; ; - Out of every form in Scheme, the ... operator is the *only* one ; that is POSTFIX! The ... operator modifies how the PREVIOUS form ; is interpreted by the macro language. This one exception is ; probably responsible for most of the confusion. (Of course, if ; you were to use ... as a function in normal scheme, it is a prefix ; operator.) ; ; In a macro pattern, ellipses can only appear as the last token in a ; LIST or VECTOR pattern. There must be a pattern immediately before it ; (because it is a postfix operator), so ellipses cannot appear right ; after an unmatched open-paren. In a pattern, the ellipses cause the ; pattern immediately before it to be able to match repeated occurrances ; of itself in the tail of the enclosing list or vector pattern. Here ; is an example. ; Suppose our pattern were this: (foo var #t ((a . b) c) ...) ; This pattern would match: (foo (* tax x) #t ((moe larry curly) stooges)) ; because var matches anything, #t matches #t, and one occurrance of ((a ; . b) c) would match. a would match moe, b would match the tail (larry ; curly) and c would match stooges. ; This pattern would match: (foo 11 #t ((moe larry curly) stooges) ((carthago delendum est) cato) ((egad) (mild oath))) ; because var matches anything, #t matches #t, and three occurrances of ; the ((a . b) c) pattern would each match the three remaining ; elements. Note that the third element matches with a being egad, b ; being empty and the pattern c matching the entire list (mild oath). ; ; This pattern would *not* match: (foo 11 #t ((moe larry curly) stooges) ((carthago delendum est) cato) ((egad) mild oath)) ; The reason is that the final element ((egad) mild oath) cannot match ; ((a . b) c) because it the pattern is a list of two elements and we ; supplied a list of three elements. ; ; This pattern *would* match: (foo #f #t) ; because var matches anything, #t matches #t, and zero occurrances of ; the ((a . b) c) pattern would match the empty tail. ; ; *** Ellipses must be last in a list or vector pattern. The list or ; vector must have at least one initial pattern. ; ; *** Ellipses is a postfix operator that operates on the pattern before ; it. ; *** Ellipses allows the containing list or vector pattern to match ; provided that the head elements of the pattern match the head ; elements of the list or vector up to (but not including) the ; pattern before the ellipses, *and* zero or more copies of that ; pattern match *each and all* of the remaining elements. ; ; *** Remember that zero occurrance of the pattern can `match'. ; ; When a pattern has an ellipses, the pattern variables within the ; clause prior to the ellipses work differently from normal. When you ; use one of these pattern variables in the template, it must be ; suffixed with an ellipses, or it must be contained in a template ; subform that is suffixed with an ellipses. In the template, anything ; suffixed with an ellipses will be repeated as many times as the ; enclosed pattern variables matched. ; ; Suppose our pattern is (foo var #t ((a . b) c) ...) and it is matched ; against (foo 11 #t ((moe larry curly) stooges) ((carthago delendum est) cato) ((egad) (mild oath))) ; These are example templates and the forms produced: ((a ...) (b ...) var (c ...)) => ((moe carthago egad) ((larry curly) (delendum est) ()) 11 (stooges cato (mild-oath))) ((a b c) ... var) => ((moe (larry curly) stooges) (carthago (delendum est) cato) (egad () (mild oath)) 11) ((c . b) ... a ...) => ((stooges larry curly) (cato delendum est) ((mild oath)) moe carthago egad) (let ((c 'b) ...) (a 'x var c) ...) => (let ((stooges '(larry curly)) (cato '(delendum est)) ((mild oath) '())) (moe 'x 11 stooges) (carthago 'x 11 cato) (egad 'x 11 (mild-oath))) ; There can be several unrelated ellipses forms in the pattern: ; The different subpatterns patterns need not have the same length in ; order for the entire pattern to match. (foo (pattern1 ...) ((pattern2) ...) ((pattern3) ...)) ; will match against (foo (a b) ((b) (c) (d) (e)) ()) ; When a template is replicated, it is replicated as many times as the ; embedded pattern variable matched, so if you use variables from ; different subpatterns, the subpatterns must be the same length. (The ; pattern matching will work if the subpatterns are different lengths, ; but the template transcription will break if a subpattern uses two ; different lengths.) ; ; You may have come to the conclusion that ellipses are too complicated ; to think about, and in the general case they can be very complex, but ; there are a couple of very common usage patterns that are easy to ; understand. Let's demonstrate an example. ; ; We wish to write a macro TRACE-SUBFORMS that given an expression ; rewrites it so that some information is printed when each subform is ; evaluated. Let's start by using our list induction pattern. (define-syntax trace-subforms (syntax-rules () ((trace-subforms traced-form) (trace-expand traced-form ())))) ;; initialize the traced element list (define-syntax trace-expand (syntax-rules () ;; when no more subforms, emit the traced code. ((trace-expand () traced) (trace-emit . traced)) ;; Otherwise, wrap some code around the form and CONS it to ;; the traced forms list. ((trace-expand (form . more-forms) traced) (trace-expand more-forms ((begin (newline) (display "Evaluating ") (display 'form) (flush-output) (let ((result form)) (display " => ") (display result) (flush-output) result)) . traced))))) (define-syntax trace-emit (syntax-rules () ((trace-emit function . arguments) (begin (newline) (let ((f function) (a (list . arguments))) (newline) (display "Now applying function.") (flush-output) (apply f a)))))) ; Now let's try it: (trace-subforms (+ 2 3)) ; Evaluating 3 => 3 ; Evaluating 2 => 2 ; Evaluating + => #<primitive:+> ; Now applying function. ; apply: expects type <procedure> as 1st argument, ; given: 3; other arguments were: (2 #<primitive:+>) ; ; It evaluated the subforms backwards and tried to use the final ; argument as the function. The error, of course, is that as we worked ; from left to right on the list of subforms, the results were prepended ; to the list so they ended up in reverse order. We *could* interpose a ; list-reversing macro between trace-expand and trace-emit, but we can ; use ellipses here to good effect: (define-syntax trace-subforms (syntax-rules () ((trace-subforms (form ...)) (trace-emit (begin (newline) (display "Evaluating ") (display 'form) (flush-output) (let ((result form)) (display " => ") (display result) (flush-output) result)) ...)))) ; The tracing code will be replicated as many times FORM is matched so ; the subforms will be handed to trace-emit in the correct order. The ; output is now ; ; Evaluating + => #<primitive:+> ; Evaluating 2 => 2 ; Evaluating 3 => 3 ; Now applying function.5 ; ; You may have noticed in our MULTIPLE-VALUE-SET! form that the ; assignments were happening in reverse order of the variable list. ; This didn't really matter because performing one assignment didn't ; affect the others. But let's print something out before each ; assignment and let's make the assignments happen in the correct ; order. We'll rewrite our MULTIPLE-VALUE-SET! macro using ellipses. (define-syntax multiple-value-set! (syntax-rules () ((multiple-value-set! variables values-form) (gen-temps-and-sets variables values-form)))) (define-syntax gen-temps-and-sets (syntax-rules () ((gen-temps-and-sets (variable ...) values-form) (emit-cwv-form (temp) ;; **** ((begin (newline) (display "Now assigning ") (display 'variable) (display " to value ") (display temp) (force-output) (set! variable temp)) ...) values-form)))) ; We have a problem. We need as many temps as variables, but the form ; that generates the temporaries (marked with the asterisks) isn't ; replicated because it doesn't contain a pattern. We'll fix this by ; putting the variable in with the temps and stripping it back out in ; EMIT-CWV-FORM. (define-syntax gen-temps-and-sets (syntax-rules () ((gen-temps-and-sets (variable ...) values-form) (emit-cwv-form ((temp variable) ...) ((set! variable temp) ...) values-form)))) (define-syntax emit-cwv-form (syntax-rules () ((emit-cwv-form ((temp variable) ...) assignments values-form) (call-with-values (lambda () values-form) (lambda (temp ...) . assignments))))) ; We have another problem. This doesn't work. Recall that when we ; introduce new variables that we need to introduce unrelated copies in ; different expansions. Even though we create a list of temps, they are ; all created in a single expansion, so they will all be the same ; identifier in the resulting code. You cannot use the same identifier ; twice in a lambda argument list. ; ; We will need to return to the list induction form, but the problem is ; that it generates the assignments in reverse order. We therefore use ; ellipses not to iterate over the variables, but to simulate APPEND: (define-syntax multiple-value-set! (syntax-rules () ((multiple-value-set! variables values-form) (gen-temps-and-sets variables () ;; initial value of temps () ;; initial value of assignments values-form)))) (define-syntax gen-temps-and-sets (syntax-rules () ((gen-temps-and-sets () temps assignments values-form) (emit-cwv-form temps assignments values-form)) ((gen-temps-and-sets (variable . more) (temps ...) (assignments ...) values-form) (gen-temps-and-sets more (temps ... temp) (assignments ... (begin (newline) (display "Now assigning value ") (display temp) (display " to variable ") (display 'variable) (flush-output) (set! variable temp))) values-form)))) (define-syntax emit-cwv-form (syntax-rules () ((emit-cwv-form temps assignments values-form) (call-with-values (lambda () values-form) (lambda temps . assignments))))) (multiple-value-set! (a b c) (values 1 2 3)) ; Now assigning value 1 to variable a ; Now assigning value 2 to variable b ; Now assigning value 3 to variable c ; ; When we use the ellipsis subpattern (temps ...) in the pattern, and the ; ellipses subtemplate (temps ... temp) in the template, this is ; analagous to writing (append temps (list temp)). This is a common ; idiom for extending a list ``from the right hand end''. While ; appending to the right-hand end is a terrible idiom to use in normal ; Scheme, it is commonly used in macro expansion because expansion time ; is less important than runtime. ; ; We can now see how to `splice' sublists when generating code. Suppose ; the pattern were this: (foo (f1 ...) (f2 ...) . body-forms) ; and we matched against this: (foo (a b c d) (1 2 3 4) moe larry curly) ; Then we can `flatten' the output by using this template: (f1 ... f2 ... . body-forms) ; => (a b c d 1 2 3 4 moe larry curly) ; *** Use ellipses to extend lists while retaining the order. ; ; *** Use ellipses to `flatten' output. ; ; ----- ; It isn't always convenient to write a separate auxiliary macro for ; each step of a complex macro. There is a trick that can be used to ; put `labels' on patterns. Since a string will only match another ; string if they are EQUAL, we can place a string in our patterns. A ; template that wishes to transfer to a particular pattern simply ; mentions the string. We can combine the gen-sets, gen-temps, and ; emit-cwv-form with this trick: (define-syntax multiple-value-set! (syntax-rules () ((multiple-value-set! (variable . variables) values-form) (mvs-aux "entry" variables values-form)) (define-syntax mvs-aux (syntax-rules () ((mvs-aux "entry" variables values-form) (mvs-aux "gen-code" variables () () values-form)) ((mvs-aux "gen-code" () temps sets values-form) (mvs-aux "emit" temps sets values-form)) ((mvs-aux "gen-code" (var . vars) (temps ...) (sets ...) values-form) (mvs-aux "gen-code" vars (temps ... temp) (sets ... (set! var temp)) values-form)) ((mvs-aux "emit" temps sets values-form) (call-with-values (lambda () values-form) (lambda temps . sets))))) ; <<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>> ; ; Let's compare this form of the macro GEN-TEMPS-AND-SETS (define-syntax gen-temps-and-sets (syntax-rules () ((gen-temps-and-sets () temps assignments values-form) (emit-cwv-form temps assignments values-form)) ((gen-temps-and-sets (variable . more) temps assignments values-form) (gen-temps-and-sets more (temp . temps) ((set! variable temp) . assignments) values-form)))) ; with some Scheme code that iterates over a list and constructs a ; collection of s-expressions. This code is not a macro but it performs ; a superficially similar calculation: (define (gen-temps-and-sets variables temps assignments values-form) (cond ((null? variables) (emit-cwv-form temps assignments values-form)) ((pair? variables) (let ((variable (car variables)) (more (cdr variables))) (gen-temps-and-sets more `(temp ,@ temps) `((set! ,variable temp) ,@ assignments) values-form))))) ; The similarity is striking: ; ; - SYNTAX-RULES is a COND ; ; - The pattern language is a hybrid of predicate (null? and pair?) ; and list destructuring code. A dotted pair in the pattern takes ; the CAR and CDR of the list provided it is a PAIR? ( . ) ; ; - The list structure in the template is QUASIQUOTE (sans ; punctuation) and is equivalent to the appropriate CONS and LIST ; forms. The quoting is implicit: everything is quoted except ; those identifiers that were matched in the pattern. ; ; - Ellipses does a mapcar/append sort of thing. ; ; In our macro language we've identified conditionals, variables, ; tail-recursive calls, and list and pair data structures, and ; primitives such as CAR, CDR, CONS, APPEND, and even a weird mapping ; mechanism. What about non-tail-recursive function calls, data ; structure abstractions, and first-class functions? Unfortunately, ; these constructs are a bit more complex. ; ; The macro language appears to be a variant of Scheme, but as seen ; through the looking glass, where things are not always as they ; appear. How can we characterize the language? ; ; The most important difference between a form in Scheme and a form in ; the macro language is in the meaning of parenthesis. In Scheme, a ; parenthesized form is either a special form or a function call. In ; the macro language it is either a destructuring predicate or a ; constructor. But if we are using parenthesis for that purpose, we ; can't use them for function calls anymore. ; ; - a template in the macro language with a macro name in the ; function position is a macro function call ; ; - like Scheme, the value of variable is passed to the called ; procedure, not the name of the variable. ; ; - like Scheme, arguments are positional ; ; - unlike Scheme, the arguments are unnamed. Patterns must be ; positionally tested. ; ; - unlike Scheme, subexpressions in the pattern can only indirectly ; invoke list manipulation functions like CAR, CDR, PAIR? and EQUAL? ; through a pattern matching mechanism. ; ; - unlike Scheme, subexpressions in the template can only indirectly ; invoke list manipulation functions like CONS or APPEND through a ; quasiquote-like mechanism. ; ; If we are missing the ability to call arbitrary functions from a ; subexpression, we are restricted to a linear calling sequence. For ; the macros written so far this is sufficient, but we will need ; something better for more complicated macros. ; ; How do we write a macro subroutine? Our macro calls so far have been ; tail recursive --- each routine transfered control to another until ; the emit code was finally called. A subroutine, however, needs a ; continuation to determine what macro to return to. We will explicitly ; pass the macro continuation to the macro subroutine. The subroutine ; will `return' by invoking the macro continuation on the values it has ; produced. ; ; So let's use this technique to deeply reverse a list. The ; `continuation' is represented by a list of a string tag and whatever ; values the continuation may need to use (we don't yet have closures, ; so we carry the data along). To return a value, we destructure the ; continuation to obtain the tag and re-invoke sreverse. (define-syntax sreverse (syntax-rules () ((sreverse thing) (sreverse "top" thing ("done"))) ((sreverse "top" () (tag . more)) (sreverse tag () . more)) ((sreverse "top" ((headcar . headcdr) . tail) kont) (sreverse "top" tail ("after-tail" (headcar . headcdr) kont))) ((sreverse "after-tail" new-tail head kont) (sreverse "top" head ("after-head" new-tail kont))) ((sreverse "after-head" () new-tail (tag . more)) (sreverse tag new-tail . more)) ((sreverse "after-head" new-head (new-tail ...) (tag . more)) (sreverse tag (new-tail ... new-head) . more)) ((sreverse "top" (head . tail) kont) (sreverse "top" tail ("after-tail2" head kont))) ((sreverse "after-tail2" () head (tag . more)) (sreverse tag (head) . more)) ((sreverse "after-tail2" (new-tail ...) head (tag . more)) (sreverse tag (new-tail ... head) . more)) ((sreverse "done" value) 'value))) ; Let's closely examine a simple call and return. ; ; This clause recursively invokes sreverse on the head of the ; expression. It creates a new continuation by creating the list ; ("after-head" new-tail kont). ((sreverse "after-tail" new-tail head kont) (sreverse "top" head ("after-head" new-tail kont))) ; This is where we will end up when that continuation is invoked. We ; expect the `return value' as the first `argument' after the tag. The ; remaining arguments after the tag are the remaining list elements of ; the continuation we made. As you can see here, "after-head" is itself ; going to invoke a continuation --- the continuation saved within the ; continuation constructed above. ((sreverse "after-head" () new-tail (tag . more)) (sreverse tag new-tail . more)) ((sreverse "after-head" new-head (new-tail ...) (tag . more)) (sreverse tag (new-tail ... new-head) . more)) ; Something very interesting is going on here. Let's add a rule to our ; macro that causes the macro to halt when the list we wish to reverse ; is the element 'HALT. (define-syntax sreverse (syntax-rules (halt) ((sreverse thing) (sreverse "top" thing ("done"))) ((sreverse "top" () (tag . more)) (sreverse tag () . more)) ((sreverse "top" ((headcar . headcdr) . tail) kont) (sreverse "top" tail ("after-tail" (headcar . headcdr) kont))) ((sreverse "after-tail" new-tail head kont) (sreverse "top" head ("after-head" new-tail kont))) ((sreverse "after-head" () new-tail (tag . more)) (sreverse tag new-tail . more)) ((sreverse "after-head" new-head (new-tail ...) (tag . more)) (sreverse tag (new-tail ... new-head) . more)) ((sreverse "top" (halt . tail) kont) '(sreverse "top" (halt . tail) kont)) ((sreverse "top" (head . tail) kont) (sreverse "top" tail ("after-tail2" head kont))) ((sreverse "after-tail2" () head (tag . more)) (sreverse tag (head) . more)) ((sreverse "after-tail2" (new-tail ...) head (tag . more)) (sreverse tag (new-tail ... head) . more)) ((sreverse "done" value) 'value))) (sreverse (1 (2 3) (4 (halt)) 6 7)) => (sreverse "top" (halt) ("after-head" () ("after-tail2" 4 ("after-head" (7 6) ("after-tail" (2 3) ("after-tail2" 1 ("done"))))))) ; Notice how each continuation to sreverse contains the saved state for ; that continuation in addition to its `parent' continuation. ; ; Let's take a huge leap of imagination: ; ; The intermediate form is a last-in, first-out stack. The topmost ; element on the stack is the current function, the next few elements ; are the arguments, and this is followed by the return address and the ; remaining dynamic context. We have a stack of call frames. ; ; I like to refer to this as `stack-machine style'. ; ; We can exploit the analogy between the macro processor and a stack ; machine more fully by re-arranging the patterns and templates to place ; the continuation in a fixed spot. The logical spot in the first ; position rather than the last. In addition, if we change the way the ; continuation is constructed, i.e., change the format of the stack ; frame, we can arrange for the return value to be delivered to any ; desired location. Rather than place the return value immediately ; after the tag, we'll place the tag and the first few values of the ; frame in a list and upon returning we'll spread the list and put the ; value after the last element. This can all be done with an auxiliary ; macro: (define-syntax return (syntax-rules () ;; Continuation goes first. Location of return value is indicated ;; by end of first list. ((return ((kbefore ...) . kafter) value) (kbefore ... value . kafter)) ;; Special case to just return value from the null continuation. ((return () value) value))) ; Constructing a continuation of the correct form is tedious, if we are ; computing something of the form (f a b (g x) c d), we have to write it ; something like this: (g ((f a b) c d) x) in order to compute G and get ; the result placed into (f a b <result> c d). We can write a helper ; macro for that. It will take 3 arguments, the current continuation, ; the saved elements to come before the return value, the call to the ; subroutine, and the saved elements after the return value. So if we ; want to express a nested function call like this, (f a b (g x) c d) we ; can write ; (macro-subproblem (f a b) (g x) c d) ; We are still limited to exactly one subproblem, though. ; ; To facilitate calls with tags, we allow G to be a list that is spread ; at the head, so (macro-subproblem (f a b) ((g "tag") x) c d) ; becomes (g "tag" ((f a b) (c d)) x) (define-syntax macro-subproblem (syntax-rules () ((macro-subproblem before ((macro-function ...) . args) . after) (macro-function ... (before . after) . args)) ((macro-subproblem before (macro-function . args) . after) (macro-function (before . after) . args)))) ; SREVERSE now becomes this: (define-syntax sreverse (syntax-rules (halt) ((sreverse thing) (macro-subproblem (sreverse "done" ()) ((sreverse "top") thing))) ((sreverse "top" k ()) (return k ())) ((sreverse "top" k ((headcar . headcdr) . tail)) (macro-subproblem (sreverse "after-tail" k) ((sreverse "top") tail) (headcar . headcdr))) ((sreverse "after-tail" k new-tail head) (macro-subproblem (sreverse "after-head" k) ((sreverse "top") head) new-tail)) ((sreverse "after-head" k () new-tail) (return k new-tail)) ((sreverse "after-head" k new-head (new-tail ...)) (return k (new-tail ... new-head))) ((sreverse "top" k (halt . tail)) '(sreverse "top" k (halt . tail))) ((sreverse "top" k (head . tail)) (macro-subproblem (sreverse "after-tail2" k) ((sreverse "top") tail) head)) ((sreverse "after-tail2" k () head) (return k (head))) ((sreverse "after-tail2" k (new-tail ...) head) (return k (new-tail ... head))) ((sreverse "done" k value) (return k 'value)))) ; Although the calling syntax is still rather cumbersome, we have made it easy ; to write macro subroutines. Here is NULL?, CAR, PAIR? and LIST? written as ; macro subroutines: (define-syntax macro-null? (syntax-rules () ((macro-null? k ()) (return k #t)) ((macro-null? k otherwise) (return k #f)))) (define-syntax macro-car (syntax-rules () ((macro-car k (car . cdr)) (return k car)) ((macro-car k otherwise) (syntax-error "Not a list")))) (define-syntax macro-pair? (syntax-rules () ((macro-car k (a . b)) (return k #t)) ((macro-car k otherwise) (return k #f)))) (define-syntax macro-list? (syntax-rules () ((macro-car k (elements ...)) (return k #t)) ((macro-car k otherwise) (return k #f)))) ; The macro analog of IF suggests itself. We just tail call the pred ; after inserting IF-DECIDE into the continuation chain. (define-syntax macro-if (syntax-rules () ((macro-if (pred . args) if-true if-false) (pred ((if-decide) if-true if-false) . args)))) (define-syntax if-decide (syntax-rules () ((if-decide #t if-true if-false) if-true) ((if-decide #f if-true if-false) if-false))) ; An example use would be: (define-syntax whatis (syntax-rules () ((whatis object) (whatis1 () object)))) (define-syntax whatis1 (syntax-rules () ((whatis1 k object) (macro-if (macro-null? object) (return k 'null) (macro-if (macro-list? object) (macro-subproblem (whatis1 "after car" k proper) (macro-car object)) (macro-if (macro-pair? object) (macro-subproblem (whatis1 "after car" k improper) (macro-car object)) (return k 'something-else))))) ((whatis1 "after car" k type c) (return k '(a type list whose car is c))))) ; The first obvious drawback to these stack-machine style macros is the ; clumsy calling sequence. We can only call compute one subproblem at a ; time and we need to have a label to return to for each subproblem. As ; you might imagine, this, too, can be solved by a macro function. ; ; However, there is a bit of a problem. If take the obvious approach ; and scan the macro call for parenthesized subexpressions, we have ; destroyed our ability to use templates as templates. We will need to ; be able to determine which parenthesis are not meant as function calls ; but are meant as list templates. Although we could re-introduce a ; quoting syntax, we would be losing most of the power of templates and ; we would be burying our code in a pile of quote and unquote forms. ; ; Instead, let us place marks within the template to indicate what ; subexpressions are meant as subproblems. (define-syntax macro-call (syntax-rules (!) ((macro-call k (! ((function ...) . arguments))) (function ... k . arguments)) ((macro-call k (! (function . arguments))) (macro-call ((macro-apply k function)) arguments)) ((macro-call k (a . b)) (macro-call ((macro-descend-right k) b) a)) ((macro-call k whatever) (return k whatever)))) (define-syntax macro-apply (syntax-rules () ((macro-apply k function arguments) (function k . arguments)))) (define-syntax macro-descend-right (syntax-rules () ((macro-descend-right k evaled b) (macro-call ((macro-cons k evaled)) b)))) (define-syntax macro-cons (syntax-rules () ((macro-cons k ca cd) (return k (ca . cd))))) ; So if we expand this form: (macro-call () (this is a (! (macro-cdr (a b (! (macro-null? ())) c d))) test)) ; The expansion is (this is a (b #t c d) test) ; Let's write a macro similar to LET. Since let-like binding lists are ; a common macro feature, we'd like to have a subroutine to parse them. ; We'd also like a subroutine to tell us if the first argument to our ; LET is a name or a binding list. (define-syntax my-let (syntax-rules () ((my-let first-subform . other-subforms) (macro-if (is-symbol? first-subform) (expand-named-let () first-subform other-subforms) (expand-standard-let () first-subform other-subforms))))) ; To test if something is a symbol, we first test to see if it is a list ; or vector. If it matches, we simply return if-no. If it doesn't ; match, then we know it is atomic, but we don't know if it is a symbol. ; Recall that symbols in macros match anything, but other atoms only ; match things equal? to themselves. Oleg Kiselyov suggests this nasty ; trick: we build a syntax-rule using it and see if the rule matches a list. (define-syntax is-symbol? (syntax-rules () ((is-symbol? k (form ...)) (return k #f)) ((is-symbol? k #(form ...)) (return k #f)) ((is-symbol? k atom) (letrec-syntax ((test-yes (syntax-rules () ((test-yes) (return k #t)))) (test-no (syntax-rules () ((test-no) (return k #f)))) (test-rule (syntax-rules () ((test-rule atom) (test-yes)) ((test-rule . whatever) (test-no))))) (test-rule (#f)))))) ; We need to use LETREC-SYNTAX here because we do not want our ; continuation forms to be in the template of the test-rule; if the test ; rule matches, the atom we just tested would be rewritten! ; ; Parsing a binding-list list is easy to do with an ellipses: (define-syntax parse-bindings (syntax-rules () ((parse-bindings k ((name value) ...)) (return k ((name ...) (value ...)))))) (define-syntax expand-named-let (syntax-rules () ((expand-named-let k name (bindings . body)) (macro-call k (! (emit-named-let name (! (parse-bindings bindings)) body)))))) (define-syntax expand-standard-let (syntax-rules () ((expand-standard-let k bindings body) (macro-call k (! (emit-standard-let (! (parse-bindings bindings)) body)))))) (define-syntax emit-named-let (syntax-rules () ((emit-named-let k name (args values) body) (return k (((lambda (name) (set! name (lambda args . body)) name) #f) . values))))) The obligatory hack. The following is a small scheme interpreter written as a syntax-rules macro. It is incredibly slow. (define-syntax macro-cdr (syntax-rules () ((macro-cdr k (car . cdr)) (return k cdr)) ((macro-cdr k otherwise) (syntax-error "Not a list")))) (define-syntax macro-append (syntax-rules () ((macro-append k (e1 ...) (e2 ...)) (return k (e1 ... e2 ...))))) (define-syntax initial-environment (syntax-rules () ((initial-environment k) (return k ((cdr . macro-cdr) (null? . macro-null?) (append . macro-append) ))))) (define-syntax scheme-eval (syntax-rules () ((scheme-eval expression) (macro-call ((quote)) (! (meval expression (! (initial-environment)))))))) (define-syntax meval (syntax-rules (if lambda quote) ((meval k () env) (return k ())) ((meval k (if pred cons alt) env) (macro-if (meval pred env) (meval k cons env) (meval k alt env))) ((meval k (lambda names body) env) (return k (closure names body env))) ((meval k (quote object) env) (return k object)) ((meval k (operator . operands) env) (meval-list ((mapply k)) () (operator . operands) env)) ((meval k whatever env) (macro-if (is-symbol? whatever) (mlookup k whatever env) (return k whatever))))) (define-syntax mlookup (syntax-rules () ((mlookup k symbol ()) '(variable not found)) ((mlookup k symbol ((var . val) . env)) (macro-if (is-eqv? symbol var) (return k val) (mlookup k symbol env))))) (define-syntax meval-list (syntax-rules () ((meval-list k evaled () env) (return k evaled)) ((meval-list k (evaled ...) (to-eval . more) env) (macro-call k (! (meval-list (evaled ... (! (meval to-eval env))) more env)))))) (define-syntax mapply (syntax-rules (closure) ((mapply k ((closure names body env) . operands)) (macro-call k (! (meval body (! (extend-environment env names operands)))))) ((mapply k (operator . operands)) (macro-if (is-symbol? operator) (operator k . operands) '(non-symbol application))))) (define-syntax extend-environment (syntax-rules () ((extend-environment k env () ()) (return k env)) ((extend-environment k env names ()) '(too-few-arguments)) ((extend-environment k env () args) '(too-many-arguments)) ((extend-environment k env (name . names) (arg . args)) (extend-environment k ((name . arg) . env) names args))))
true
ab7f95c0dac37fe2b66c2cf00eeb9c55adb401d0
b43e36967e36167adcb4cc94f2f8adfb7281dbf1
/sicp/ch1/exercises/1.43.scm
56ea6e1a7f0f92f6ac959ff39fcbe82ead43f604
[]
no_license
ktosiu/snippets
79c58416117fa646ae06a8fd590193c9dd89f414
08e0655361695ed90e1b901d75f184c52bb72f35
refs/heads/master
2021-01-17T08:13:34.067768
2016-01-29T15:42:14
2016-01-29T15:42:14
53,054,819
1
0
null
2016-03-03T14:06:53
2016-03-03T14:06:53
null
UTF-8
Scheme
false
false
244
scm
1.43.scm
(define (compose f g) (lambda(x) (f (g x)))) (define (repeated f n) (define (iter i result) (if (= i n) result (iter (+ i 1) (compose result f)))) (iter 1 f)) (define (square x) (* x x)) ((repeated square 2) 5)
false
8c4f6dcc3fa7692895dba28ff513a8fbf2cc95d4
afc3bd22ea6bfe0e60396a84a837c82a0d836ea2
/Informatics Basics/Module 1/04-gcd-lcm-prime.scm
c4fe87fe2b7f4ac734079ea6b198925b6af7f956
[]
no_license
BuDashka/BMSTU
c128c2b13065a25ec027c68bcc3bac119163a53f
069551c25bd11ea81e823b2195851f8563271b01
refs/heads/master
2021-04-15T15:22:12.324529
2017-10-19T00:59:25
2017-10-19T00:59:25
126,348,611
1
1
null
2018-03-22T14:35:04
2018-03-22T14:35:04
null
UTF-8
Scheme
false
false
305
scm
04-gcd-lcm-prime.scm
(define (my-gcd a b) (define c (remainder a b)) (define d (remainder b a)) (if (or (= c 0) (= d 0)) c (if (> c d) (my-gcd d a) (my-gcd c b)))) (define (my-lcm a b) (/ (* a b) (my-gcd a b))) (define (prime? n) (define a 10) (= (remainder (expt a (- n 1)) n) 1))
false
936902ccefac8f4ed2a060a8856c3916fe6993ea
f6b62cc3aa282c70248ba864695ffa5f20e6a615
/blosc.scm
4bdf6954e82e49f26a17e0ab601b75d3498826e5
[ "BSD-3-Clause" ]
permissive
iraikov/chicken-blosc
23017ef9d1231083ac6f164a496c507e37cdb6c9
a5ab9df812b424f2a3711798a930084bbac7750d
refs/heads/master
2021-04-28T20:10:59.877620
2019-05-06T13:13:04
2019-05-06T13:13:04
121,918,242
0
0
null
null
null
null
UTF-8
Scheme
false
false
5,590
scm
blosc.scm
#| Chicken Scheme bindings for the Blosc compression library. Written for Chicken Scheme by Ivan Raikov. |# (module blosc ( initialize! compress compress! decompress decompress! sizes set-nthreads! set-compressor! free-resources! version-format max-threads max-overhead ) (import scheme (except (chicken base) compress) (chicken foreign) (chicken format) (chicken blob) srfi-4) #> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <blosc.h> #define C_bytevector_length(x) (C_header_size(x)) <# (define version-format (foreign-value "BLOSC_VERSION_FORMAT" int)) (define max-overhead (foreign-value "BLOSC_MAX_OVERHEAD" int)) (define do-shuffle (foreign-value "BLOSC_DOSHUFFLE" int)) (define mem-cpyed (foreign-value "BLOSC_MEMCPYED" int)) (define max-threads (foreign-value "BLOSC_MAX_THREADS" int)) (define max-typesize 255) (define max-buffersize 4294967295) ;; Initializes the BLOSC compressor (define (initialize!) ((foreign-lambda* void () #<<END blosc_init(); END ))) (define blosc-compress (foreign-safe-lambda* int ((int level) (int shuffle) (unsigned-int itemsize) (scheme-object dest) (scheme-object src)) #<<END int result=0; size_t srcsize=0, destsize=0; void *srcdata=NULL, *destdata=NULL; C_i_check_bytevector (src); C_i_check_bytevector (dest); srcsize = C_bytevector_length(src); srcdata = C_c_bytevector (src); destsize = C_bytevector_length(dest); destdata = C_c_bytevector (dest); result = blosc_compress(level, shuffle, itemsize, srcsize, srcdata, destdata, destsize); if (result < 0) { printf("Blosc compression error. Error code: %d\n", result); } assert(result >= 0); C_return (result); END )) (define (compress! dest src #!key (level 5) (shuffle #t) (itemsize 1)) (if (< itemsize 0) (error 'compress! "item size must be positive")) (if (or (< level 0) (> level 9)) (error 'compress! "level must be between 0 and 9, inclusive")) (blosc-compress level (if shuffle 1 0) itemsize dest src)) (define (compress src #!key (level 5) (shuffle #t) (itemsize 1)) (assert (< 0 (blob-size src))) (let* ((dest (make-blob (+ (blob-size src) max-overhead))) (sz (compress! dest src level: level shuffle: shuffle itemsize: itemsize))) (u8vector->blob/shared (subu8vector (blob->u8vector/shared dest) 0 sz)))) ;; Given a compressed buffer, return the (uncompressed, compressed, block) size (define cbuffer-sizes (foreign-safe-lambda* void ((scheme-object buffer) (u32vector sizes)) #<<END size_t nbytes=0, cbytes=0, blocksize=0; void *cbuffer = NULL; C_i_check_bytevector (buffer); cbuffer = C_c_bytevector (buffer); blosc_cbuffer_sizes(cbuffer, &nbytes, &cbytes, &blocksize); sizes[0] = nbytes; sizes[1] = cbytes; sizes[2] = blocksize; END )) ;; Given a compressed buffer `buf`, return a tuple ;; of the `(uncompressed, compressed, block)` sizes in bytes. (define (sizes buf) (let ((res (make-u32vector 3 0))) (cbuffer-sizes buf res) (u32vector->list res) )) (define blosc-decompress (foreign-safe-lambda* int ((scheme-object dest) (scheme-object src)) #<<END int result=0; size_t destsize=0; void *srcdata=NULL, *destdata=NULL; C_i_check_bytevector (src); C_i_check_bytevector (dest); srcdata = C_c_bytevector (src); destdata = C_c_bytevector (dest); destsize = C_bytevector_length(dest); result = blosc_decompress(srcdata, destdata, destsize); if (result < 0) { printf("Blosc decompression error. Error code: %d\n", result); } assert(result >= 0); C_return (result); END )) (define (decompress! dest src) (let* ((uncompressed-sz (car (sizes src))) (len (blob-size dest))) (if (not (<= uncompressed-sz len)) (error 'decompress! "destination buffer is too small")) (blosc-decompress dest src) dest)) (define (decompress src) (let* ((uncompressed-sz (car (sizes src)))) (decompress! (make-blob uncompressed-sz) src))) ;; Initialize a pool of threads for compression / decompression. ;; If `nthreads` is 1, the the serial version is chosen and a possible previous existing pool is ended. ;; If this function is not callled, `nthreads` is set to 1 internally. (define (set-nthreads! n) ((foreign-lambda* void ((int n)) #<<END blosc_set_nthreads(n); END ) n)) ;; Set the current compression algorithm to `s`. The currently supported ;; algorithms in the default Blosc module build are `"blosclz"`, `"lz4"`, ;; and `"l4hc"`. Throws an error if `s` is not the name ;; of a supported algorithm. Returns a nonnegative integer code used ;; internally by Blosc to identify the compressor. (define (set-compressor! s) (case s (("blosclz" "lz4" "l4hc") ((foreign-lambda* void ((c-string s)) #<<END blosc_set_compressor(s); END ) s)) (else (error 'set-compressor! "unrecognized compression algorithm" s)) )) ;; Free possible memory temporaries and thread resources. ;; Use this when you are not going to use Blosc for a long while. ;; In case of problems releasing resources, it returns `false`, ;; whereas it returns `true` on success. (define (free-resources!) ((foreign-lambda* int () #<<END int result = blosc_free_resources(); C_return(result); END ))) )
false
cd1deab59131654d5c4474f153427e40a315d834
2f24d2157a8e9edbe417e28b1e93ff293f9a3f41
/shmup.ss
68d928bbcc391ae52be271949bb74a2c7c85e692
[]
no_license
jeapostrophe/shmup
d1452ed00bb22227ba9f31e4776930128886f639
12baff4b3e0aeeddfad1b69db0e49614e6de0b10
refs/heads/master
2021-01-25T10:22:20.169966
2013-10-31T01:26:03
2013-10-31T01:26:03
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,532
ss
shmup.ss
#lang scheme (require sgl sgl/gl sgl/gl-vectors (planet jaymccarthy/gl-world) (planet jaymccarthy/gl2d) (planet jaymccarthy/bulletml/lib) (prefix-in col: "collision.ss")) (define filename "/Users/jay/Dev/svn/byu-plt/trunk/planet/bulletml/examples/[Psyvariar]_X-A_boss_winder.xml") (define ship-rad 12.0) (define speed 20.0) (define bullet-rad (/ ship-rad 4.0)) (define screen-scale 25.0) (define screen-width (* screen-scale 16)) (define screen-height (* screen-scale 9)) (define bml (compile-bulletml (parse-file filename))) (define bullet-sim (load-bml screen-width screen-height bml)) (define scale 2) (define dead? #f) (define (collide! b1 b2) (printf "Collide! ~S ~S~n" b1 b2) (set! dead? #t)) (define tick-rate (exact->inexact 1/30)) (define-struct screen (time)) (define initial-screen (make-screen 0)) (define (collision-bullets bullet-sim) (cons (col:make-body 'ship (bullets-target-posn bullet-sim) ship-rad) (map (lambda (b) (col:make-body 'bullet (body-posn b) bullet-rad)) (bullets-bs bullet-sim)))) (define frames 0) (define start-time (current-seconds)) (define (current-fps) (define time-since (- (current-seconds) start-time)) (cond [(zero? time-since) tick-rate] [(zero? frames) tick-rate] [else (/ time-since frames)])) (define step-simulation (match-lambda [(struct screen (time)) (define time-step tick-rate) (set! frames (add1 frames)) (step! bullet-sim) (col:find-collisions! collide! (collision-bullets bullet-sim)) (make-screen (+ time time-step))])) (define (ship-steer s k) (match s [(struct screen (time)) (define speed-adj (* speed 2 tick-rate)) (define adjustment (match (send k get-key-code) ['up (make-cartesian-posn 0.0 speed-adj)] ['down (make-cartesian-posn 0.0 (* -1 speed-adj))] ['right (make-cartesian-posn speed-adj 0.0)] ['left (make-cartesian-posn (* -1 speed-adj) 0.0)] [_ (make-cartesian-posn 0.0 0.0)])) (set-bullets-target-posn! bullet-sim (posn+2 (bullets-target-posn bullet-sim) adjustment)) (make-screen time)])) (define draw-screen (match-lambda [(struct screen (time)) (gl-init display-width display-height) (gl-viewport/restrict screen-width screen-height screen-width screen-height (cartesian-posn-x (bullets-target-posn bullet-sim)) (cartesian-posn-y (bullets-target-posn bullet-sim))) (gl-clear-color 1 1 1 1) (gl-clear 'color-buffer-bit) (gl-color 0 0 0 1) (for ([b (in-list (collision-bullets bullet-sim))]) (match b [(struct col:body (layer (struct cartesian-posn [x y]) radius)) (with-translate x y (with-scale radius radius (gl-draw-circle (case layer [(ship) 'outline] [(bullet) 'solid]))))]))])) (define stop? (match-lambda [(struct screen (time)) dead?])) (define display-width (inexact->exact (* scale screen-width))) (define display-height (inexact->exact (* scale screen-height))) (big-bang screen? initial-screen #:height display-height #:width display-width #:on-tick step-simulation #:tick-rate (inexact->exact tick-rate) #:on-key ship-steer #:draw-init void #:on-draw draw-screen #:stop-when stop? #:stop-timer stop?)
false
66a23afd4fda8a4d46b970a1cf96512e199a3f6a
f5083e14d7e451225c8590cc6aabe68fac63ffbd
/cs/01-Programming/cs61a/exercises/05_week_4.scm
ed39b0e45ac26dbef3f8c1ea20b0289c06f43b00
[]
no_license
Phantas0s/playground
a362653a8feb7acd68a7637334068cde0fe9d32e
c84ec0410a43c84a63dc5093e1c214a0f102edae
refs/heads/master
2022-05-09T06:33:25.625750
2022-04-19T14:57:28
2022-04-19T14:57:28
136,804,123
19
5
null
2021-03-04T14:21:07
2018-06-10T11:46:19
Racket
UTF-8
Scheme
false
false
2,410
scm
05_week_4.scm
; +------------+ ; | Exercise 1 | ; +------------+ ; Write a procedure substitute that takes three arguments: a list, an old word, and a ; new word. It should return a copy of the list, but with every occurrence of the old word ; replaced by the new word, even in sublists. For example: (define (substitute l old-word new-word) (define (sub l old-word new-word new-list) (if (empty? l) new-list (sub (cdr l) old-word new-word (append new-list (cond ((list? (car l)) (list (substitute (car l) old-word new-word))) ((equal? (car l) old-word) (list new-word)) (else (list (car l)))))))) (sub l old-word new-word '())) (substitute '((lead guitar) (bass guitar) (rhythm guitar) drums) 'guitar 'axe) ; => ((lead axe) (bass axe) (rhythm axe) drums) (substitute '((lead guitar (lead bass)) (bass guitar (drum guitar (drum axe))) (rhythm guitar) drums) 'guitar 'axe) ; => '((lead axe (lead bass)) (bass axe (drum axe (drum axe))) (rhythm axe) drums) **PERFECT** ; +------------+ ; | Exercise 2 | ; +------------+ ; Now write substitute2 that takes a list, a list of old words, and a list of new words; the ; last two lists should be the same length. It should return a copy of the first argument, but ; with each word that occurs in the second argument replaced by the corresponding word of ; the third argument: ; (substitute2 '((4 calling birds) (3 french hens) (2 turtle doves)) ; '(1 2 3 4) '(one two three four)) ; ((four calling birds) (three french hens) (two turtle doves)) (define (substitute2 l old new) (define (sub l old-list new-list result) (if (empty? l) result (sub (cdr l) old-list new-list (append result (cond ((list? (car l)) (list (substitute2 (car l) old-list new-list))) (else (list (replace (car l) old-list new-list)))))))) (sub l old new '())) (define (replace value old-list new-list) (if (= (length old-list) (length new-list)) (if (empty? old-list) value (cond ((equal? value (car old-list)) (car new-list)) (else (replace value (cdr old-list) (cdr new-list))))) (error "old list and new list need to have the same size"))) **PERFECT**
false
78b456a42ec1f554450fcf5ef8241a458ed78a42
f4aeaa0812ac15d5a8d2cb6da75ac335c3cf5cf4
/miruKanren/record-inspection.sld
6bc918129dee54dead942974a3405cac79036785
[ "MIT" ]
permissive
orchid-hybrid/microKanren-sagittarius
13f7916f8ef7c946cefeb87e9e52d6d4a5dfe6c9
9e740bbf94ed2930f88bbcf32636d3480934cfbb
refs/heads/master
2021-01-13T01:54:20.589391
2015-06-13T12:40:14
2015-06-13T12:40:14
29,868,626
12
4
null
2015-02-12T07:11:25
2015-01-26T16:01:10
Scheme
UTF-8
Scheme
false
false
147
sld
record-inspection.sld
(define-library (miruKanren record-inspection) (import (scheme base)) (export register-record! record?) (include "record-inspection.scm"))
false
c74ab99b841bc374f36d7bafbaf886264c9b0496
ac2a3544b88444eabf12b68a9bce08941cd62581
/lib/srfi/6/test.scm
8b8a268c33145488f3edef09d6309f1e388d7475
[ "Apache-2.0", "LGPL-2.1-only" ]
permissive
tomelam/gambit
2fd664cf6ea68859d4549fdda62d31a25b2d6c6f
d60fdeb136b2ed89b75da5bfa8011aa334b29020
refs/heads/master
2020-11-27T06:39:26.718179
2019-12-15T16:56:31
2019-12-15T16:56:31
229,341,552
1
0
Apache-2.0
2019-12-20T21:52:26
2019-12-20T21:52:26
null
UTF-8
Scheme
false
false
2,062
scm
test.scm
;;;============================================================================ ;;; File: "test.scm" ;;; Copyright (c) 1994-2019 by Marc Feeley, All Rights Reserved. ;;;============================================================================ ;;; SRFI 6, Basic String Ports (import (srfi 6)) (import (_test)) ;;;============================================================================ (define p (open-input-string "(a . (b . (c . ()))) 34")) (check-true (input-port? p)) (check-equal? (read p) '(a b c)) (check-equal? (read p) 34) (check-true (eof-object? (peek-char p))) (let ((q (open-output-string)) (x '(a b c))) (write (car x) q) (write (cdr x) q) (check-equal? (get-output-string q) "a(b c)")) (check-true (input-port? (open-input-string " (0 ; 1 \n 2 3) (4 5)"))) (check-equal? (read (open-input-string " (0 ; 1 \n 2 3) (4 5)")) '(0 2 3)) (check-true (eof-object? (read (open-input-string "")))) (check-true (output-port? (open-output-string))) (let ((port (open-output-string))) (display "a" port) (write "b" port) (display "c" port) (check-equal? (get-output-string port) "a\"b\"c")) (check-tail-exn type-exception? (lambda () (open-input-string #f))) #; ;; 0 parameters is allowed with Gambit (check-tail-exn wrong-number-of-arguments-exception? (lambda () (open-input-string))) (check-tail-exn wrong-number-of-arguments-exception? (lambda () (open-input-string "" #f))) #; ;; 1 parameter is allowed with Gambit (check-tail-exn wrong-number-of-arguments-exception? (lambda () (open-output-string ""))) #; ;; 1 parameter is allowed with Gambit (check-tail-exn type-exception? (lambda () (open-output-string #f))) (check-tail-exn type-exception? (lambda () (get-output-string #f))) (check-tail-exn wrong-number-of-arguments-exception? (lambda () (get-output-string))) (let ((port (open-output-string))) (check-tail-exn wrong-number-of-arguments-exception? (lambda () (get-output-string port #f)))) ;;;============================================================================
false
f2f28b25488c60a7dec1bec666bb4444a983d8ae
d64d265c68d52602b49c5933d7ab8acc45ca83f0
/chipmunk.setup
7055d6f60364c5c72e588a90f20aa514aa68fc14
[ "MIT" ]
permissive
ChrisBlom/chicken-chipmunk-7
051b9572466c336c572c493fbf89e1d4378a1c63
19e8792bf4d0f954927813ecd1753c404beff45f
refs/heads/master
2022-11-06T13:38:40.441324
2018-02-18T13:00:03
2018-02-18T13:00:03
67,888,524
1
1
null
null
null
null
UTF-8
Scheme
false
false
384
setup
chipmunk.setup
;; -*- scheme -*- (compile -s -I./Chipmunk2D/include/chipmunk -I./Chipmunk2D/include ./Chipmunk2D/src/*.c chipmunk.scm -C -O2 -C --std=gnu99 -C -Wvisibility -C -Wincompatible-pointer-types -j chipmunk) (compile -s chipmunk.import.scm -C -Wincompatible-pointer-types) (install-extension 'chipmunk '("chipmunk.so" "chipmunk.import.so"))
false
7f6ee038522b737e9dbdbbe06378e4da8c6be216
08b21a94e7d29f08ca6452b148fcc873d71e2bae
/src/loki/core/number.sld
c347056e01753f665697e4592c0692e79d946540
[ "MIT" ]
permissive
rickbutton/loki
cbdd7ad13b27e275bb6e160e7380847d7fcf3b3a
7addd2985de5cee206010043aaf112c77e21f475
refs/heads/master
2021-12-23T09:05:06.552835
2021-06-13T08:38:23
2021-06-13T08:38:23
200,152,485
21
1
NOASSERTION
2020-07-16T06:51:33
2019-08-02T02:42:39
Scheme
UTF-8
Scheme
false
false
2,294
sld
number.sld
(define-library (loki core number) (import (loki core primitives)) (import (loki core apply)) (import (loki core intrinsics)) (import (loki core case-lambda)) (export + * - / < <= = > >= zero? positive? negative? abs bitwise-not bitwise-and bitwise-ior bitwise-xor arithmetic-shift bit-count integer-length) (begin (define + (case-lambda (() 0) ((a) a) ((a b) (%add a b)) ((a b . rest) (apply + (%add a b) rest)))) (define * (case-lambda (() 1) ((a) a) ((a b) (%mul a b)) ((a b . rest) (apply * (%mul a b) rest)))) (define - (case-lambda ((a) (%sub 0 a)) ((a b) (%sub a b)) ((a b . rest) (apply - (%sub a b) rest)))) (define / (case-lambda ((a) (%div 1 a)) ((a b) (%div a b)) ((a b . rest) (apply / (%div a b) rest)))) (define < (case-lambda ((a b) (%lt a b)) ((a b . rest) (and (%lt a b) (apply < b rest))))) (define <= (case-lambda ((a b) (%lte a b)) ((a b . rest) (and (%lte a b) (apply <= b rest))))) (define = (case-lambda ((a b) (%number-eq a b)) ((a b . rest) (and (%number-eq a b) (apply = b rest))))) (define > (case-lambda ((a b) (%gt a b)) ((a b . rest) (and (%gt a b) (apply > b rest))))) (define >= (case-lambda ((a b) (%gte a b)) ((a b . rest) (and (%gte a b) (apply >= b rest))))) (define (zero? x) (= x 0)) (define (positive? x) (> x 0)) (define (negative? x) (< x 0)) (define (abs x) (if (< x 0) (- x) x)) (define (bitwise-not i) (%bit-not i)) (define bitwise-and (case-lambda (() -1) ((a b) (%bit-and a b)) ((a b . rest) (%bit-and a (apply bitwise-and b rest))))) (define bitwise-ior (case-lambda (() 0) ((a b) (%bit-ior a b)) ((a b . rest) (%bit-ior a (apply bitwise-ior b rest))))) (define bitwise-xor (case-lambda (() 0) ((a b) (%bit-xor a b)) ((a b . rest) (%bit-xor a (apply bitwise-xor b rest))))) (define (arithmetic-shift i count) (%bit-shift i count)) (define (bit-count i) (%bit-count i)) (define (integer-length i) (%bit-length i)) ))
false
90790de93e906120a9e496859758bd0722bee552
09e309c8c7dd86d201f965a12f4f174fd2bf8cf5
/scheme/tree-call-cc.scm
1dc26d4ae6b8f894810de4c60b1c7c087255fe01
[]
no_license
googol-lab/lang
f21076846b2364ee08875530ab7a6680de61f55c
38cae455f85464a7f918d1a5a481a577ed5549fe
refs/heads/master
2020-03-29T13:32:29.159544
2010-05-24T03:09:54
2010-05-24T03:09:54
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
674
scm
tree-call-cc.scm
(define (dft tree) (cond ((null? tree) ()) ((not (pair? tree)) (write tree)) (else (dft (car tree)) (dft (cdr tree))))) (define *saved* ()) (define (dft-node tree) (cond ((null? tree) (restart)) ((not (pair? tree)) tree) (else (call/cc (lambda (cc) (set! *saved* (cons (lambda () (cc (dft-node (cdr tree)))) *saved*)) (dft-node (car tree))))))) (define (restart) (if (null? *saved*) 'done (let ((cont (car *saved*))) (set! *saved* (cdr *saved*)) (cont)))) (define (dft2 tree) (set! *saved* ()) (let ((node (dft-node tree))) (cond ((eq? node 'done) ()) (else (write node) (restart)))))
false
11399610e35d8ee45bc2d305cf4fffd136f6921b
923209816d56305004079b706d042d2fe5636b5a
/sitelib/http/request.scm
c7a0033bd5ae28954e06c24a85404bc9e3452ed3
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
tabe/http
4144cb13451dc4d8b5790c42f285d5451c82f97a
ab01c6e9b4e17db9356161415263c5a8791444cf
refs/heads/master
2021-01-23T21:33:47.859949
2010-06-10T03:36:44
2010-06-10T03:36:44
674,308
1
0
null
null
null
null
UTF-8
Scheme
false
false
942
scm
request.scm
(library (http request) (export Request) (import (rnrs (6)) (http abnf) (only (http entity-header-field) entity-header) (only (http general-header-field) general-header) (only (http request-header-field) request-header) (only (http message-body) message-body) (only (http request-line) Request-Line)) ;;; 5 Request ;; Request = Request-Line ; Section 5.1 ;; *(( general-header ; Section 4.5 ;; | request-header ; Section 5.3 ;; | entity-header ) CRLF) ; Section 7.1 ;; CRLF ;; [ message-body ] ; Section 4.3 (define Request (seq Request-Line (rep* (seq (bar general-header request-header entity-header) CRLF)) CRLF (opt message-body))) )
false
38b2b2969b801531451ebbab5065f10fc846800e
ac2a3544b88444eabf12b68a9bce08941cd62581
/gsc/tests/14-keyword/if.scm
fae3b061eba36f1fa0ee1c788eb1a335a9837535
[ "Apache-2.0", "LGPL-2.1-only" ]
permissive
tomelam/gambit
2fd664cf6ea68859d4549fdda62d31a25b2d6c6f
d60fdeb136b2ed89b75da5bfa8011aa334b29020
refs/heads/master
2020-11-27T06:39:26.718179
2019-12-15T16:56:31
2019-12-15T16:56:31
229,341,552
1
0
Apache-2.0
2019-12-20T21:52:26
2019-12-20T21:52:26
null
UTF-8
Scheme
false
false
164
scm
if.scm
(declare (extended-bindings) (not constant-fold) (not safe)) (define s1 '||:) (define s2 'hello:) (define (test x) (println (if x 11 22))) (test s1) (test s2)
false
99772549299c7a45dd4a953cf275420824fd2658
2a8dc8faf0275eece40b2aa3a52cf8f5bc06babc
/src/fixbibtex.ss
f1ef8adc4a32815c7f99e1dfc26d8e65f2d597f1
[ "MIT" ]
permissive
dybvig/stex
9da1a299329e9382e09d9f272268771a71fdd8e2
afa607564a5662ffd748e824801277a6b5a3d11c
refs/heads/master
2022-07-01T06:42:23.205482
2021-04-10T22:26:21
2021-04-10T22:28:36
55,739,382
95
25
null
2022-04-29T08:15:31
2016-04-08T01:12:34
Scheme
UTF-8
Scheme
false
false
1,089
ss
fixbibtex.ss
#! /usr/bin/scheme --program ;;; fixbibtex.ss ;;; fixbibtex removes the line breaks inserted by bibtex, sometimes ;;; in the middle of tex commands or urls. #!chezscheme (import (chezscheme) (script)) (define fn (command-line-case (command-line) [((keyword --help)) (usage) (exit 1)] [((keyword --version)) (version) (exit)] [(filename) filename])) (let ([s (call-with-port (open-input-file fn) get-string-all)]) (with-input-from-string s (lambda () (with-output-to-file fn (lambda () (define (s0 c) (unless (eof-object? c) (case c [(#\\) (write-char c) (s1 (read-char))] [(#\%) (s2 (read-char))] [else (write-char c) (s0 (read-char))]))) (define (s1 c) ; seen \ (unless (eof-object? c) (write-char c) (s0 (read-char)))) (define (s2 c) ; seen % (case c [(#\newline) (s0 (read-char))] [else (write-char #\%) (s0 c)])) (s0 (read-char))) 'replace))))
false
9ec7a462bfaae5c4f02e1373b2aa447818bbefb7
d3b0d07e79425dc70669825a176714b292b5d630
/hash.scm
93e292ecd3a0e75791b38dac0e8cd8abe09bf9fe
[]
no_license
corrodedlabs/persistent-records
b28cdcfde6e44feedd3407a0782686a134fc80e1
fe13ef3f92614ff7e547e345167c26c4aa3a55c0
refs/heads/master
2022-12-25T08:36:23.736643
2020-10-04T13:55:54
2020-10-04T13:58:07
301,142,749
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,824
scm
hash.scm
(define *default-bound* (- (expt 2 29) 3)) (define (%string-hash s ch-conv bound) (let ((hash 31) (len (string-length s))) (do ((index 0 (+ index 1))) ((>= index len) (modulo hash bound)) (set! hash (modulo (+ (* 37 hash) (char->integer (ch-conv (string-ref s index)))) *default-bound*))))) (define (string-hash s . maybe-bound) (let ((bound (if (null? maybe-bound) *default-bound* (car maybe-bound)))) (%string-hash s (lambda (x) x) bound))) (define (string-ci-hash s . maybe-bound) (let ((bound (if (null? maybe-bound) *default-bound* (car maybe-bound)))) (%string-hash s char-downcase bound))) (define (symbol-hash s . maybe-bound) (let ((bound (if (null? maybe-bound) *default-bound* (car maybe-bound)))) (%string-hash (symbol->string s) (lambda (x) x) bound))) (define (hash obj . maybe-bound) (let ((bound (if (null? maybe-bound) *default-bound* (car maybe-bound)))) (cond ((integer? obj) (modulo obj bound)) ((string? obj) (string-hash obj bound)) ((symbol? obj) (symbol-hash obj bound)) ((real? obj) (modulo (+ (numerator obj) (denominator obj)) bound)) ((number? obj) (modulo (+ (hash (real-part obj)) (* 3 (hash (imag-part obj)))) bound)) ((char? obj) (modulo (char->integer obj) bound)) ((vector? obj) (vector-hash obj bound)) ((pair? obj) (modulo (+ (hash (car obj)) (* 3 (hash (cdr obj)))) bound)) ((null? obj) 0) ((not obj) 0) ((procedure? obj) (error "hash: procedures cannot be hashed" obj)) (else 1)))) (define hash-by-identity hash) (define (vector-hash v bound) (let ((hashvalue 571) (len (vector-length v))) (do ((index 0 (+ index 1))) ((>= index len) (modulo hashvalue bound)) (set! hashvalue (modulo (+ (* 257 hashvalue) (hash (vector-ref v index))) *default-bound*)))))
false
83eb36e76061580d248d3bb1b143be67ad22f9ba
0bb7631745a274104b084f6684671c3ee9a7b804
/lib/srfi/111/111#.scm
452c1777e1175d190a8a3cfb2531041b5ecd5287
[ "Apache-2.0", "LGPL-2.1-only", "LicenseRef-scancode-free-unknown", "GPL-3.0-or-later", "LicenseRef-scancode-autoconf-simple-exception" ]
permissive
feeley/gambit
f87fd33034403713ad8f6a16d3ef0290c57a77d5
7438e002c7a41a5b1de7f51e3254168b7d13e8ba
refs/heads/master
2023-03-17T06:19:15.652170
2022-09-05T14:31:53
2022-09-05T14:31:53
220,799,690
0
1
Apache-2.0
2019-11-10T15:09:28
2019-11-10T14:14:16
null
UTF-8
Scheme
false
false
393
scm
111#.scm
;;;============================================================================ ;;; File: "111#.scm" ;;; Copyright (c) 2021 by Marc Feeley, All Rights Reserved. ;;;============================================================================ ;;; SRFI 111, Boxes (##namespace ("" box box? unbox set-box! )) ;;;============================================================================
false
a24f2ab4ae6c8df1eedcd9573ddc31e23b59ac6a
f9e4062f24473a22bc9161d86f05ed49ed4e8080
/readline/tags/1.991/readline.setup
76bcf62ebba25db88c1123db271d044fb468de6b
[]
no_license
hwinslow3/eggs
20cee88b249c2daa10760df3e8ca9b9d868c5752
dab1ca2c51f90f4714866e74c3a7f3ebe4b62535
refs/heads/master
2020-03-24T09:40:12.201125
2017-11-04T00:20:11
2017-11-04T00:20:11
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,605
setup
readline.setup
;;;; readline.setup -*- Scheme -*- (define +test-code+ #<<EOF #include <stdio.h> #include <readline/readline.h> #include <readline/history.h> int main() { char *c = readline("foo"); add_history("test"); rl_refresh_line(0, 0); return 0; } EOF ) (define-syntax check-rllibs (syntax-rules () ((_ libs) (and (print "trying: " libs) (try-compile +test-code+ ldflags: libs) libs)))) (define rl-extralib (or (check-rllibs "-lreadline -lhistory -ltermcap") (check-rllibs "-lreadline -lhistory -lcurses") (check-rllibs "-lreadline -lhistory -lncurses") (check-rllibs "-lreadline -ltermcap") (check-rllibs "-lreadline -lcurses") (check-rllibs "-lreadline -lncurses") (check-rllibs "-lreadline -lhistory") (check-rllibs "-lreadline") (error (string-append "This extension requires GNU readline. GNU readline " "may be found at ftp://ftp.gnu.org/pub/gnu/readline\n" "For more information, please consult " "http://chicken.wiki.br/readline#Installation%20problems." )))) (compile -s -O2 readline.scm ,@rl-extralib) (compile -c -O2 -d0 -j readline readline.scm -o readline-static.o -unit readline ,@rl-extralib) (compile -s -O2 -d0 readline.import.scm) (install-extension 'readline '("readline.so" "readline.import.so" "readline-static.o") `((version 1.991) (static "readline-static.o") (static-options ,(string-intersperse (map ->string rl-extralib) " "))))
true
f83380192b8ba4a9d0447413d5483aa9529c157a
eef5f68873f7d5658c7c500846ce7752a6f45f69
/spheres/util/quickcheck/real.scm
edd352983dfb4ee376add50de95fc758e74d66af
[ "MIT" ]
permissive
alvatar/spheres
c0601a157ddce270c06b7b58473b20b7417a08d9
568836f234a469ef70c69f4a2d9b56d41c3fc5bd
refs/heads/master
2021-06-01T15:59:32.277602
2021-03-18T21:21:43
2021-03-18T21:21:43
25,094,121
13
3
null
null
null
null
UTF-8
Scheme
false
false
3,271
scm
real.scm
;;; this is a distribution that correspond to expected intervals ;;; between events with a poisson distribution ;;; l is lambda that is the mean of the distribution ;;; If for example you want to simulate the event arrival of random ;;; indipendent events, like the requests to a web server ;;; with a mean of 4 request per second ;;; you can simulate it by generating this, delaing for this time ;;; and create a new request. (define current-case-limit (make-parameter 100)) (define pi 3.14159265) (define (memoize fn size) (let((cache (make-vector size #!void))) (lambda (j) (let((v0 (vector-ref cache j))) (if (eq? v0 #!void) (let((v (fn j))) (vector-set! cache j v) v) v0))))) (define (range j) (let range ((j j) (rs '())) (if (= 0 j) rs (let((j (- j 1))) (range j (cons j rs)))))) (define (fold f i es) (let fold ((i i) (es es)) (if (null? es) i (fold (f i (car es)) (cdr es))))) (define (sum fn n) (fold (lambda (i e) (+ i (fn e))) 0 (range n))) (define beta (/ (sqrt pi) 2)) (define (quantile:normal #!optional (number-of-terms 10)) (let((calc-c #f) (calc-weight #f) (weight #f) (term #f) (ks #f) (c #f)) (set! calc-c (lambda (k) (if (< k 2) 1 (sum (lambda (m) (/ (* (c m) (c (- k 1 m))) (* (+ m 1) (+ (* 2 m) 1)))) k)))) (set! calc-weight (lambda (k) (/ (c k) (+ (* 2 k) 1)))) (set! term (lambda (k p) (expt (* beta p) (+ (* 2 k) 1)))) (set! weight (memoize calc-weight number-of-terms)) (set! c (memoize calc-c number-of-terms)) (lambda (p) (sum (lambda (k) (* (weight k) (term k (- p 0.5)))) number-of-terms)))) (define (quantile:exponential l) (lambda (p) (- (/ (log (- 1 p)) l)))) (define (quantile:uniform p) p) (define (real<< #!key (distribution quantile:uniform) (cases 100)) (lambda (yield) (let real ((c 0)) (if (< c cases) (begin (yield (distribution (random-real))) ;; (yield (distribution (/ (random-integer 100000) 100000))) (real (+ c 1))))))) (define (normal<< #!key (cases 100) (term-count 5)) (real<< distribution: (quantile:normal term-count) cases: cases)) (define (exponential<< #!key (mean 1) (cases (current-case-limit))) (real<< distribution: (quantile:exponential (/ 1 mean)) cases: cases)) (define (a-real #!key (distribution quantile:uniform) (cases 100)) (generate! (real<< distribution: distribution cases: cases))) (define (a-normal #!key (cases 100) (term-count 5)) (generate! (normal<< cases: cases term-count: term-count))) (define (an-exponential #!key (mean 1) (cases (current-case-limit))) (generate! (exponential<< mean: mean cases: cases)))
false
c3347d3d173bd5dc01aba2752ac556eb433f1e01
432924338995770f121e1e8f6283702653dd1369
/3/3.3.3-test.scm
8e4c2c26b4a92b92edd1db9308b54a41a063cead
[]
no_license
punchdrunker/sicp-reading
dfaa3c12edf14a7f02b3b5f4e3a0f61541582180
4bcec0aa7c514b4ba48e677cc54b41d72c816b44
refs/heads/master
2021-01-22T06:53:45.096593
2014-06-23T09:51:27
2014-06-23T09:51:27
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
698
scm
3.3.3-test.scm
(load "./helper.scm") (load "./3.3.3.scm") (define (install-deriv-package) ;; internal procedures (define (make-sum a1 a2) (list '+ a1 a2)) (define (addend s) (car s)) (define (augend s) (cadr s)) (define (make-product m1 m2) (list '* m1 m2)) (define (multiplier p) (car p)) (define (multiplicand p) (cadr p)) (define (deriv-sum exp var) (make-sum (deriv (addend exp) var) (deriv (augend exp) var))) (define (deriv-product exp var) (make-sum (make-product (multiplier exp) (deriv (multiplicand exp) var)) (make-product (deriv (multiplier exp) var) (multiplicand exp)))) (put 'deriv '+ deriv-sum))
false
ce934c6afd4c13f84da871713d82a4c74604356e
29ea7c27a13dfcd0c7273619d0d915442298764f
/examples/line-demo.scm
9211b810d23023b8453db329893c77a4a10245c2
[]
no_license
kenhys/gauche-hpdf
f637fc85a9a54a8112913b348daa8e04aecebb9b
d0993ead47cceaaee2e0ca2ac57df7964ddcb720
refs/heads/master
2016-09-05T16:54:09.776801
2012-08-19T15:17:50
2012-08-19T15:17:50
3,368,344
0
0
null
null
null
null
UTF-8
Scheme
false
false
6,948
scm
line-demo.scm
(use gauche.sequence) (use gauche.collection) (use gauche.interactive) (use hpdf) (define (draw-line page x y label) (let* () (begin-text page) (move-text-pos page x (- y 10)) (show-text page label) (end-text page) (moveto page x (- y 15)) (lineto page (+ x 220) (- y 15)) (stroke page))) (define (draw-line2 page x y label) (let* () (begin-text page) (move-text-pos page x y) (show-text page label) (end-text page) (moveto page (+ x 30) (- y 25)) (lineto page (+ x 160) (- y 25)) (stroke page))) (define (draw-rect page x y label) (let* () (begin-text page) (move-text-pos page x (- y 10)) (show-text page label) (end-text page) (rectangle page x (- y 40) 220 25))) (define page-title "Line Example") (define DASH_MODE1 '(3)) (define DASH_MODE2 '(3 7)) (define DASH_MODE3 '(8 7 2 7)) (define (main args) (let* ([pdf (hpdf-new)] [page (add-page pdf)] [x 0] [y 0] [x1 0] [y1 0] [x2 0] [y2 0] [x3 0] [y3 0] [font (hpdf-get-font pdf "Helvetica" #f)] [tw 0] [filename (if (rxmatch #/.*examples\/.*\.scm$/ *program-name*) "examples/line-demo.pdf" "line-demo.pdf")]) (line-width! page 1) (rectangle page 50 50 (- (width page) 100) (- (height page) 110)) (stroke page) ;; print the title of the page (with positioning center). (font-and-size! page font 24) (set! tw (text-width page page-title)) (begin-text page) (move-text-pos page (/ (- (width page) tw) 2) (- (height page) 50)) (show-text page page-title) (end-text page) (font-and-size! page font 10) ;; draw verious widths of lines. (line-width! page 0) (draw-line page 60 770 "line width = 0") (line-width! page 1.0) (draw-line page 60 740 "line width = 1.0") (line-width! page 2.0) (draw-line page 60 710 "line width = 2.0") ;; Line dash pattern (line-width! page 1.0) (dash! page DASH_MODE1 1) (draw-line page 60 680 "dash_ptn=[3], phase=1 -- 2 on, 3 off, 3 on...") (dash! page DASH_MODE2 2) (draw-line page 60 650 "dash_ptn=[7, 3], phase=2 -- 5 on 3 off, 7 on,...") (dash! page DASH_MODE3 0) (draw-line page 60 620 "dash_ptn=[8, 7, 2, 7], phase=0") (dash! page '() 0) (line-width! page 30) (rgb-stroke! page 0.0 0.5 0.0) ;; line cap style (line-cap! page HPDF_BUTT_END) (draw-line2 page 60 570 "PDF_BUTT_END") (line-cap! page HPDF_ROUND_END) (draw-line2 page 60 505 "PDF_ROUND_END") (line-cap! page HPDF_PROJECTING_SCUARE_END) (draw-line2 page 60 440 "PDF_PROJECTING_SCUARE_END") ;; Line join style (line-width! page 30) (rgb-stroke! page 0.0 0.0 0.5) (line-join! page HPDF_MITER_JOIN) (moveto page 120 300) (lineto page 160 340) (lineto page 200 300) (stroke page) (begin-text page) (move-text-pos page 60 360) (show-text page "PDF_MITER_JOIN") (end-text page) (line-join! page HPDF_ROUND_JOIN) (moveto page 120 195) (lineto page 160 235) (lineto page 200 195) (stroke page) (begin-text page) (move-text-pos page 60 255) (show-text page "PDF_ROUND_JOIN") (end-text page) (line-join! page HPDF_BEVEL_JOIN) (moveto page 120 90) (lineto page 160 130) (lineto page 200 90) (stroke page) (begin-text page) (move-text-pos page 60 150) (show-text page "PDF_BEVEL_JOIN") (end-text page) ;; draw rectangle (line-width! page 2) (rgb-stroke! page 0 0 0) (rgb-fill! page 0.75 0.0 0.0) (draw-rect page 300 770 "Stroke") (stroke page) (draw-rect page 300 720 "Fill") (fill page) (draw-rect page 300 670 "Fill then Stroke") (fill-stroke page) ;; clip rect (gsave page) ;; save the current graphic state (draw-rect page 300 620 "Clip Rectangle") (clip page) (stroke page) (font-and-size! page font 13) (begin-text page) (move-text-pos page 290 600) (text-leading! page 12) (show-text page "Clip Clip Clip Clip Clip Clipi Clip Clip Clip") (show-text-next-line page "Clip Clip Clip Clip Clip Clip Clip Clip Clip") (show-text-next-line page "Clip Clip Clip Clip Clip Clip Clip Clip Clip") (end-text page) (grestore page) ;; curve example(curveto2) (set! x 330) (set! y 440) (set! x1 430) (set! y1 530) (set! x2 480) (set! y2 470) (set! x3 480) (set! y3 90) (rgb-fill! page 0 0 0) (begin-text page) (move-text-pos page 300 540) (show-text page "CurveTo2(x1, y1, x2, y2)") (end-text page) (begin-text page) (move-text-pos page (+ x 5) (- y 5)) (show-text page "Current point") (move-text-pos page (- x1 x) (- y1 y)) (show-text page "(x1, y1)") (move-text-pos page (- x2 x1) (- y2 y1)) (show-text page "(x2, y2)") (end-text page) (dash! page DASH_MODE1 0) (line-width! page 0.5) (moveto page x1 y1) (lineto page x2 y2) (stroke page) (dash! page '() 0) (line-width! page 1.5) (moveto page x y) (curveto2 page x1 y1 x2 y2) (stroke page) ;; curve example(curveto3) (set! y (- y 150)) (set! y1 (- y1 150)) (set! y2 (- y2 150)) (begin-text page) (move-text-pos page 300 390) (show-text page "CurveTo3(x1, y1, x2, y2)") (end-text page) (begin-text page) (move-text-pos page (+ x 5) (- y 5)) (show-text page "Current point") (move-text-pos page (- x1 x) (- y1 y)) (show-text page "(x1, y1)") (move-text-pos page (- x2 x1) (- y2 y1)) (show-text page "(x2, y2)") (end-text page) (dash! page DASH_MODE1 0) (line-width! page 0.5) (moveto page x y) (lineto page x1 y1) (stroke page) (dash! page '() 0) (line-width! page 1.5) (moveto page x y) (curveto3 page x1 y1 x2 y2) (stroke page) ;; curve example(curveto) (set! y (- y 150)) (set! y1 (- y1 160)) (set! y2 (- y2 130)) (set! x2 (+ x2 10)) (begin-text page) (move-text-pos page 300 240) (show-text page "CurveTo(x1, y1, x2, y2, x3, y3)") (end-text page) (begin-text page) (move-text-pos page (+ x 5) (- y 5)) (show-text page "Current point") (move-text-pos page (- x1 x) (- y1 y)) (show-text page "(x1, y1)") (move-text-pos page (- x2 x1) (- y2 y1)) (show-text page "(x2, y2)") (move-text-pos page (- x3 x2) (- y3 y2)) (show-text page "(x3, y3)") (end-text page) (dash! page DASH_MODE1 0) (line-width! page 0.5) (moveto page x y) (lineto page x1 y1) (stroke page) (moveto page x2 y2) (lineto page x3 y3) (stroke page) (dash! page '() 0) (line-width! page 1.5) (moveto page x y) (curveto page x1 y1 x2 y2 x3 y3) (stroke page) ;; save the document to a file (save-to-file pdf filename) ;; clean up (free pdf)))
false
91e35234d24184be0ae4518b52b4fef9f48e5212
5609fb7205b8aeb4f18767440b2b893d1be6695c
/examples/chicken/library-examples/json.scm
87415d2aeb1f9113c4acfb887756870361e75712
[]
no_license
kyleburton/sandbox
d2a5e59df14f13581ece884738107da571cb2232
ae7d1ec0c8dbce8806f4019a13dcd3501d4af667
refs/heads/master
2023-07-25T20:16:28.474155
2023-06-22T17:32:49
2023-06-22T17:32:49
188,580
13
5
null
2023-06-22T17:32:51
2009-04-29T16:34:21
Clojure
UTF-8
Scheme
false
false
654
scm
json.scm
#!/usr/bin/env csi -q (use medea) (define some-json #<<END { "field1": "value1", "field2": [ {"a": 1, "b": 2}, "stuff" ] } END ) (printf "the json: ~a\n" some-json); (printf "read-json: ~a\n" (read-json some-json)) (define some-data-structure `((time . ,(current-seconds)) (numbers . #(1 2 3 4)))) (define-syntax with-output-to-string* (syntax-rules () ((with-output-to-string* body ...) (with-output-to-string (lambda () body ...))))) (printf "some-data-structure ~a\n" some-data-structure) (printf "write ~a\n" (with-output-to-string* (write-json some-data-structure))) (exit)
true
eedf6c1c39d58193ed67503599f7643e3c020ec8
b8eb3fdd0e4e38a696c4013a8f91054df3f75833
/scheme/j4.ss
9cfb0988356f26b423179e38c1e2b8291c191d00
[ "Zlib" ]
permissive
lojikil/digamma
952a7bdf176227bf82b3583020bc41764b12d906
61c7ffdc501f207a84e5d47157c3c84e5882fa0d
refs/heads/master
2020-05-30T07:11:20.716792
2016-05-11T11:32:15
2016-05-11T11:32:15
58,539,277
6
3
null
null
null
null
UTF-8
Scheme
false
false
34
ss
j4.ss
(def ntest (fn (i) (display i)))
false
daa24ba5bd0df75e020c9bafe9e2e388e893ebc1
2c291b7af5cd7679da3aa54fdc64dc006ee6ff9b
/ch2/prob.2.55.scm
94b9416250a0e8e11d26c4f93c7599792a6b5133
[]
no_license
etscrivner/sicp
caff1b3738e308c7f8165fc65a3f1bc252ce625a
3b45aaf2b2846068dcec90ea0547fd72b28f8cdc
refs/heads/master
2021-01-10T12:08:38.212403
2015-08-22T20:01:44
2015-08-22T20:01:44
36,813,957
1
0
null
null
null
null
UTF-8
Scheme
false
false
120
scm
prob.2.55.scm
(car ''abcradabra) ;; ''abracadabra evaluates to (quote abracadabra) and taking the car of this ;; list produces quote
false
b80779fab09a05176053c0cb53e9d485cb537f3e
6c6cf6e4b77640825c2457e54052a56d5de6f4d2
/ch3/3_64-stream-limit.scm
d25bc9150a809e3e7b4118b76b058e26490e05aa
[]
no_license
leonacwa/sicp
a469c7bc96e0c47e4658dccd7c5309350090a746
d880b482d8027b7111678eff8d1c848e156d5374
refs/heads/master
2018-12-28T07:20:30.118868
2015-02-07T16:40:10
2015-02-07T16:40:10
11,738,761
0
0
null
null
null
null
UTF-8
Scheme
false
false
259
scm
3_64-stream-limit.scm
; ex 3.64 stream-limit (define (stream-limit s tolerance) (define (close-enough? a b) (< (abs (- a b)) tolerance)) (let ((a (stream-car s)) (b (stream-car (stream-cdr s)))) (if (close-enough? a b) b (stream-limit (stream-cdr s) tolerance))))
false
8392dd988680cdc6f2dc5571dcf9475f1880e931
b58f908118cbb7f5ce309e2e28d666118370322d
/src/21.scm
29ed5777f5e213f4161ba2b845cc6b96cccb993d
[ "MIT" ]
permissive
arucil/L99
a9e1b7ad2634850db357f7cc292fa2871997d93d
8b9a3a8e7fb63efb2d13fab62cab2c1254a066d9
refs/heads/master
2021-09-01T08:18:39.029308
2017-12-26T00:37:55
2017-12-26T00:37:55
114,847,976
1
0
null
null
null
null
UTF-8
Scheme
false
false
391
scm
21.scm
(load "prelude.scm") ;;; P21 (define (insert-at x ls n) (cond [(null? ls) (list x)] [(= 1 n) (cons x ls)] [else (cons (car ls) (insert-at x (cdr ls) (1- n)))])) (test (insert-at 'x '() 1) '(x)) (test (insert-at 'x '(a) 1) '(x a)) (test (insert-at 'x '(a b c) 2) '(a x b c)) (test (insert-at 'x '(a b c) 3) '(a b x c)) (test (insert-at 'x '(a b c) 4) '(a b c x))
false
df002ec8eda3cf46d8ed73f4598466e8d34cd787
fb9a1b8f80516373ac709e2328dd50621b18aa1a
/ch1/1-3-4_Procedures_as_Returned_Values.scm
d1e3d18fce58012d952c2e7a8bfa8f2d66432a53
[]
no_license
da1/sicp
a7eacd10d25e5a1a034c57247755d531335ff8c7
0c408ace7af48ef3256330c8965a2b23ba948007
refs/heads/master
2021-01-20T11:57:47.202301
2014-02-16T08:57:55
2014-02-16T08:57:55
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,207
scm
1-3-4_Procedures_as_Returned_Values.scm
;; 1.3.4 ๅ€คใจใ—ใฆ่ฟ”ใ•ใ‚Œใ‚‹ๆ‰‹็ถšใ ;; ๅผ•ๆ•ฐใซๆ‰‹็ถšใใŒๆธกใ›ใ‚‹ใจ๏ผŒ่จ€่ชžใฎ่กจ็พๅŠ›ใŒไธŠใŒใ‚‹ใ“ใจใŒใ‚ใ‹ใฃใŸ๏ผŽ ;; ๆ‰‹็ถšใใ‚’่ฟ”ใ™ๆ‰‹็ถšใใŒไฝœใ‚Œใ‚‹ใจ๏ผŒๆ›ดใซ่กจ็พๅŠ›ใŒไธŠใŒใ‚‹๏ผŽ (load "./ch1/1-3-3_Procedures_as_General_Methods.scm") ;; ๅนณๆ–น็ทฉๅ’Œใฎ่€ƒใˆๆ–น (define (average-damp f) (lambda (x) (average x (f x)))) ;; average-dampใฏๆ‰‹็ถšใfใ‚’ๅผ•ๆ•ฐใซใจใ‚‹๏ผŽ ;; "xใ‚’ๅผ•ๆ•ฐใซใจใ‚Š๏ผŒxใจ(f x)ใฎๅนณๅ‡ๅ€คใ‚’่ฟ”ใ™ๆ‰‹็ถšใ"ใ‚’่ฟ”ใ™ๆ‰‹็ถšใใ‚’่ฟ”ใ™ ((average-damp square) 10) ;; average-dampใ‚’ไฝฟใฃใŸsqrt (define (sqrt x) (fixed-point (average-damp (lambda (y) (/ x y))) 1.0)) (sqrt 16) ;; xใฎ็ซ‹ๆ–นๆ นใŒ้–ขๆ•ฐy->x/y^2ใฎไธๅ‹•็‚นใงใ‚ใ‚‹ใ“ใจใซๆณจๆ„ใ™ใ‚Œใฐ๏ผŒๅนณๆ–นๆ นใฎๆ‰‹็ถšใใ‚’็ซ‹ๆ–นๆ นใ‚’ๅพ—ใ‚‹ใ‚‚ใฎใซไธ€่ˆฌๅŒ–ใ™ใ‚‹ใ“ใจใŒใงใใ‚‹ (define (cube-root x) (fixed-point (average-damp (lambda (y) (/ x (square y)))) 1.0)) (cube-root 27) ;; * Newtonๆณ• (define dx 0.00001) (define (deriv g) (lambda (x) (/ (- (g (+ x dx)) (g x)) dx))) (define (cube x) (* x x x)) ((deriv cube) 5) (define (newton-transform g) (lambda (x) (- x (/ (g x) ((deriv g) x))))) (define (newtons-method g guess) (fixed-point (newton-transform g) guess)) (define (sqrt x) (newtons-method (lambda (y) (- (square y) x)) 1.0)) (sqrt 16) ;; * ๆŠฝ่ฑกใจ็ฌฌไธ€็ดšๆ‰‹็ถšใ (define (fixed-point-of-transform g transform guess) (fixed-point (transform g) guess)) (define (sqrt x) (fixed-point-of-transform (lambda (y) (/ x y)) average-damp 1.0)) (define (sqrt x) (fixed-point-of-transform (lambda (y) (- (square y) x)) newton-transform 1.0)) ;; ไธ€่ˆฌใซ๏ผŒใƒ—ใƒญใ‚ฐใƒฉใƒ ่จ€่ชžใซใฏ๏ผŒ่ฆ็ด ใ‚’ๆ‰ฑใ†ๆ–นๆณ•ใซ่‰ฒใ€…ๅˆถ้™ใŒใ‚ใ‚‹๏ผŽ ;; ใปใจใ‚“ใฉๅˆถ้™ใฎใชใ„่ฆ็ด ใฏ๏ผŒ็ฌฌไธ€็ดš๏ผˆfirst-class๏ผ‰ใงใ‚ใ‚‹ใจใ„ใ†๏ผŽ ;; ็ฌฌไธ€็ดš่ฆ็ด ใฎๆจฉๅˆฉใจ็‰นๆจฉใฏ๏ผŒ ;; * ๅค‰ๆ•ฐใจใ—ใฆๅๅ‰ใŒไป˜ใ‘ใ‚‰ใ‚Œใ‚‹ ;; * ๆ‰‹็ถšใใซๅผ•ๆ•ฐใจใ—ใฆๆธกใ›ใ‚‹ ;; * ๆ‰‹็ถšใใฎ็ตๆžœใจใ—ใฆ่ฟ”ใ•ใ‚Œใ‚‹ ;; * ใƒ‡ใƒผใ‚ฟๆง‹้€ ใซ็ต„ใฟ่พผใ‚ใ‚‹ ;; ใงใ‚ใ‚‹๏ผŽ
false
e41f1b5257b65119222e261600b8edcdecd953df
d074b9a2169d667227f0642c76d332c6d517f1ba
/sicp/ch_3/exercise.3.41.scm
fc7c460faf81fa2254bbc1ae63b3786335ebd69f
[]
no_license
zenspider/schemers
4d0390553dda5f46bd486d146ad5eac0ba74cbb4
2939ca553ac79013a4c3aaaec812c1bad3933b16
refs/heads/master
2020-12-02T18:27:37.261206
2019-07-14T15:27:42
2019-07-14T15:27:42
26,163,837
7
0
null
null
null
null
UTF-8
Scheme
false
false
1,247
scm
exercise.3.41.scm
#lang racket/base ;;; Exercise 3.41 ;; Ben Bitdiddle worries that it would be better to ;; implement the bank account as follows (where the commented line ;; has been changed): ;; ;; (define (make-account balance) ;; (define (withdraw amount) ;; (if (>= balance amount) ;; (begin (set! balance (- balance amount)) ;; balance) ;; "Insufficient funds")) ;; (define (deposit amount) ;; (set! balance (+ balance amount)) ;; balance) ;; (let ((protected (make-serializer))) ;; (define (dispatch m) ;; (cond ((eq? m 'withdraw) (protected withdraw)) ;; ((eq? m 'deposit) (protected deposit)) ;; ((eq? m 'balance) ;; ((protected (lambda () balance)))) ; serialized ;; (else (error "Unknown request -- MAKE-ACCOUNT" ;; m)))) ;; dispatch)) ;; ;; because allowing unserialized access to the bank balance can ;; result in anomalous behavior. Do you agree? Is there any ;; scenario that demonstrates Ben's concern? ;; A: Assuming that memory access can't be read while it is in the ;; middle of writing a word, ben is an idiot.
false
322b1683052933b3529d9012816db91fd80b61da
427586e066e5d7d146d3b24c1400781a91011a94
/code/equation.scm
2352d5a76453efc77c5f1f2def27ab2e8a82dbcb
[ "LicenseRef-scancode-public-domain" ]
permissive
cslarsen/scheme-presentation
07cb3d5d7850cc6e7616dad43718c139178cbd7c
7b66aef60041f95358f0eab72c58ac400e1f902f
refs/heads/master
2016-08-11T14:50:33.517262
2016-01-28T07:25:06
2016-01-28T07:25:06
50,564,125
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,215
scm
equation.scm
(import (scheme base) (scheme write) (scheme cxr) (scheme inexact) (scheme eval) (print)) ;; Replaces all occurrences of symbol with value in the expression. ;; (define (bind symbol value expr) (if (null? expr) '() ;; terminate list with '() (cons (cond ((symbol? (car expr)) ;; replace symbol w/value (if (equal? (car expr) symbol) value (car expr))) ((pair? (car expr)) ;; traverse pairs (bind symbol value (car expr))) (else ;; skip the others (car expr))) (bind symbol value (cdr expr))))) ;; keep replacing ;; Same as (bind ...) but takes a list of symbols and values. ;; (define (bind* symvals expr) (if (null? symvals) expr (bind* (cdr symvals) (bind (caar symvals) (cadar symvals) expr)))) (define equation '(sqrt (+ (* x x) (* y y)))) (println "Equation: " equation) (println "Binding x to 123, y to 456 gives: " (bind* '((x 123) (y 456)) equation)) (println "The result is: " (eval (bind* '((x 123) (y 456)) '(sqrt (+ (* x x) (* y y))))))
false
041a97e2dafd3b53d2747f525b67c2d76f6333b5
44b36cd9ac64433de4d4ea08b0f50748096c4f6b
/mecab-wrap.scm
460e60b443ce3663855f1f7a7db73016989b0a42
[]
no_license
naoyat/camp-langdev-2007
bba3202e668ea055104f2317fcfe4a875db6ccf9
6c3262b3c76ce2a61150e54a047ee52ca0b5544a
refs/heads/master
2021-01-13T01:30:56.603229
2009-04-15T20:26:24
2009-04-15T20:26:24
176,972
1
0
null
null
null
null
UTF-8
Scheme
false
false
1,951
scm
mecab-wrap.scm
(use mecab) (define *mecab-instance* (mecab-new2 "--node-format=(m\\s%m(%F\\s[0,1,2,3])(%F\\s[4,5])%f[6](%F\\s[7,8])) --bos-format=( --eos-format=)")) ; ๏ผ‘ๆฎต็›ฎใฎใƒ‘ใƒผใ‚นใงๅพ—ใŸใƒชใ‚นใƒˆใ‚’ใ€ใ‚ณใƒณใƒ“ใƒใƒผใ‚ฟใƒ‘ใƒผใ‚ตใŒๆ‰ฑใˆใ‚‹ใ‚นใƒˆใƒชใƒผใƒ ใซๅค‰ๆ› (define (mecab str) (read-from-string (mecab-sparse-tostr *mecab-instance* str))) ; (list->stream morpheme-list))) (define (m? m) (and (pair? m) (eq? 'm (car m)))) (define (m-surface m) (cadr m)) (define (m-parts m) (caddr m)) (define (m-conjugs m) (cadddr m)) (define (m-original m) (car (cddddr m))) (define (m-yomis m) (cadr (cddddr m))) (define (m-surface-str m) (if (m? m) (symbol->string (m-surface m)) "")) (define (m-pronounce m) (cadr (m-yomis m))) (define (m-part m) (car (m-parts m))) (define (m-part2 m) (cadr (m-parts m))) ;(define (m-conjug-paradigm m) ; (let1 cs (m-conjugs m) ; (if (null? cs) '* (cadr cs)))) (define (m-conjug m) (let1 cs (m-conjugs m) (if (null? cs) '* (cadr cs)))) ;;; (define (m-surface-eq? m surface) (eq? (m-surface m) surface)) (define (m-surface-check-proc surface) (lambda (m) (eq? (m-surface m) surface))) (define (m-part-eq? m part) (eq? (m-part m) part)) (define (m-part-check-proc part) (lambda (m) (eq? (m-part m) part))) (define (m-parts-check-proc parts) (lambda (m) (equal? (m-parts m) parts))) (define (ๅ่ฉž? m) (m-part-eq? m 'ๅ่ฉž)) (define (ๅฝขๅฎน่ฉž? m) (m-part-eq? m 'ๅฝขๅฎน่ฉž)) (define (้€ฃไฝ“่ฉž? m) (m-part-eq? m '้€ฃไฝ“่ฉž)) (define (ๅŠฉๅ‹•่ฉž? m) (m-part-eq? m 'ๅŠฉๅ‹•่ฉž)) (define (ๅŠฉ่ฉž? m) (m-part-eq? m 'ๅŠฉ่ฉž)) (define (ๅ‰ฏ่ฉž? m) (m-part-eq? m 'ๅ‰ฏ่ฉž)) (define (ๅ‹•่ฉž? m) (m-part-eq? m 'ๅ‹•่ฉž)) (define (ๆŽฅ็ถš่ฉž? m) (m-part-eq? m 'ๆŽฅ็ถš่ฉž)) (define (ๆŽฅ้ ญ่ฉž? m) (m-part-eq? m 'ๆŽฅ้ ญ่ฉž)) (define (ๆ„Ÿๅ‹•่ฉž? m) (m-part-eq? m 'ๆ„Ÿๅ‹•่ฉž)) (define (ๅฅ็‚น? m) (m-surface-eq? m 'ใ€‚)) (define (่ชญ็‚น? m) (m-surface-eq? m 'ใ€)) (define (m-conditional? m) (eq? 'ไปฎๅฎšๅฝข (m-conjug m)))
false
90bbcae7c10016dd78e92cf363ffbc8b2d121e9e
84bd214ba2422524b8d7738fb82dd1b3e2951f73
/02/2_exer-2.1.scm
140ba1b35c8020386660a0dc60b4c6f9f79c9fee
[]
no_license
aequanimitas/sicp-redux
e5ef32529fa727de0353da973425a326e152c388
560b2bd40a12df245a8532de5d76b0bd2e033a64
refs/heads/master
2020-04-10T06:49:13.302600
2016-03-15T00:59:24
2016-03-15T00:59:24
21,434,389
1
0
null
null
null
null
UTF-8
Scheme
false
false
253
scm
2_exer-2.1.scm
; Exercise 2.1 (define (mr n d) (cond ((and (> n 0) (< d 0)) (mr (* -1 n) (* -1 d))) ((and (< d 0) (< n 0)) (mr (* -1 n) (* -1 d))) (else (let ((g (gcd n d))) (cons (/ n g) (/ d g)))))) (mr -1 -3) (mr 1 -3) (mr -1 3)
false
fb02b380f816024640443dc25a8b286a7ff26ce8
46244bb6af145cb393846505f37bf576a8396aa0
/sicp/3_45.scm
5ca717d8f806b403ffd48163be98ee7ea40ac089
[]
no_license
aoeuidht/homework
c4fabfb5f45dbef0874e9732c7d026a7f00e13dc
49fb2a2f8a78227589da3e5ec82ea7844b36e0e7
refs/heads/master
2022-10-28T06:42:04.343618
2022-10-15T15:52:06
2022-10-15T15:52:06
18,726,877
4
3
null
null
null
null
UTF-8
Scheme
false
false
1,698
scm
3_45.scm
; Exercise 3.45. Louis Reasoner thinks our bank-account system is unnecessarily complex and ; error-prone now that deposits and withdrawals aren't automatically serialized. ; He suggests that make-account-and-serializer should have exported the serializer ; (for use by such procedures as serialized-exchange) in addition to (rather than instead of) ; using it to serialize accounts and deposits as make-account did. He proposes to redefine accounts as follows: (define (make-account-and-serializer balance) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount)) balance) (let ((balance-serializer (make-serializer))) (define (dispatch m) (cond ((eq? m 'withdraw) (balance-serializer withdraw)) ((eq? m 'deposit) (balance-serializer deposit)) ((eq? m 'balance) balance) ((eq? m 'serializer) balance-serializer) (else (error "Unknown request -- MAKE-ACCOUNT" m)))) dispatch)) ; Then deposits are handled as with the original make-account: (define (deposit account amount) ((account 'deposit) amount)) ; Explain what is wrong with Louis's reasoning. In particular, consider what happens when serialized-exchange is called. ; Answer ; Let's simplify the problem, let's write some code like this (define a (make-account-and-serializer 100)) (((a 'serializer) (a 'deposit)) 20) ; It will try to lock twice in the same therad, then the 2nd lock will wait for the 1st lock return, but ; the 1st lock is waiting the 2nd lock success
false
7846e8c3ebc8b6ef7cc6f00bce4136cfa3d68ff0
1ed47579ca9136f3f2b25bda1610c834ab12a386
/sec4/q4.50.scm
9e4436b5a11a9fd2ccc5772732ac704202ae0ec3
[]
no_license
thash/sicp
7e89cf020e2bf5ca50543d10fa89eb1440f700fb
3fc7a87d06eccbe4dcd634406e3b400d9405e9c4
refs/heads/master
2021-05-28T16:29:26.617617
2014-09-15T21:19:23
2014-09-15T21:19:23
3,238,591
0
1
null
null
null
null
UTF-8
Scheme
false
false
6,972
scm
q4.50.scm
;; (1). ๅˆ†ๅฒใ‚’ๅทฆใ‹ใ‚‰ๅณใงใฏใชใใƒฉใƒณใƒ€ใƒ ใช้ †ใซๆŽขใ™ ramb ใ‚’ๅฎŸ่ฃ…ใ›ใ‚ˆ. (use srfi-27) (define (random x) (random-integer x)) ;; (random 3) ใง 0,1,2 ใฎใ„ใšใ‚Œใ‹ใŒ่ฟ”ใ‚‹ ;; itemsใ‹ใ‚‰ใƒฉใƒณใƒ€ใƒ ใซไธ€ใคๅ–ใฃใฆใใ‚‹ๆ‰‹็ถšใ ;; * ref: http://d.hatena.ne.jp/rui314/20070118/p1 ;; * ref: http://practical-scheme.net/gauche/man/gauche-refj_44.html (define (pick1 items) (if (null? items) #f (list-ref items (random (length items))))) ;; ใ•ใ‚‰ใซ, ใƒชใ‚นใƒˆไธญใ‹ใ‚‰pick1ใง้ธใ‚“ใ 1ๅ€‹ใ‚’ๅ–ใ‚Š้™คใrejectๆ‰‹็ถšใใ‚’็”จๆ„ใ™ใ‚‹. (define (reject x xs) (cond ((null? xs) '()) ((equal? x (car xs)) (cdr xs)) (else (cons (car xs) (reject x (cdr xs)))))) ;; pick1, rejectใฎใ‚ˆใ†ใซ็ ดๅฃŠ็š„ใซๆ“ไฝœใ—ใชใใฆใ‚‚, ;; ใƒฉใƒณใƒ€ใƒ ใชๆ•ดๆ•ฐindexใงlistใ‚’ๅผ•ใ„ใฆ, ;; rejectใฎไปฃใ‚ใ‚Šใซindex้ƒจๅˆ†ใ‚’่ฆ—ใ„ใŸใƒชใ‚นใƒˆใ‚’appendใ™ใ‚‹ๆ–นๆณ•ใ‚‚ใ‚ใ‚‹ ;; ๅ‹•ไฝœ็ขบ่ช {{{2 ; gosh> (define x '(1 2 3 4 5 6 7 8 9)) ; gosh> (pick1 x) ; 9 ; gosh> (reject 9 x) ; (1 2 3 4 5 6 7 8) ; gosh> (pick1 '(1 2 3 4 5 6 7 8)) ; 2 ; gosh> (reject 2 '(1 2 3 4 5 6 7 8)) ; (1 3 4 5 6 7 8) }}}2 ;; analyze, amb?, amb-choises, analyze-ambใ‚’rambใง็ฝฎใๆ›ใˆใ‚‹. (define (analyze exp) (cond ((self-evaluating? exp) (analyze-self-evaluating exp)) ((quoted? exp) (analyze-quoted exp)) ((variable? exp) (analyze-variable exp)) ((assignment? exp) (analyze-assignment exp)) ((definition? exp) (analyze-definition exp)) ((let? exp) (analyze (let->combination exp))) ((if? exp) (analyze-if exp)) ((lambda? exp) (analyze-lambda exp)) ((begin? exp) (analyze-sequence (begin-actions exp))) ((cond? exp) (analyze (cond->if exp))) ((amb? exp) (analyze-amb exp)) ((ramb? exp) (analyze-ramb exp)) ((application? exp) (analyze-application exp)) (else (error "Unknown expression type -- ANALYZE" exp)))) (define (ramb? exp) (tagged-list? exp 'ramb)) (define (ramb-choices exp) (cdr exp)) (define (analyze-ramb exp) (let ((cprocs (map analyze (ramb-choices exp)))) (lambda (env succeed fail) (define (try-next choices) (if (null? choices) (fail) (let ((item (pick1 choices))) (item env succeed (lambda () (try-next (reject item choices))))))) (try-next cprocs)))) ;; (2). ใ“ใ‚ŒใŒๅ•้กŒ4.49 (q4.49.scm) ใฎAlyssaใฎๅ•้กŒใ‚’ๆ•‘ใ†ใ“ใจใ‚’็คบใ›. ;; ่„šๆณจ54: ๆ–‡ๆณ•ใฏๅคšใใฎๅ ดๆ‰€ใง้ซ˜ๅบฆใซๅ†ๅธฐ็š„ใงใ‚ใ‚Š, Alyssaใฎๆ–‡็ซ ็”Ÿๆˆๆณ•ใฏๅ†ๅธฐใฎไธ€ใคใซใ€Œ่ฝใก่พผใฟใ€‘ๆญขใพใฃใฆใ—ใพใ†. (load "./sec4.3-nondeterministic") ;; rambใƒใƒผใ‚ธใƒงใƒณใ‚’่ฉฆใ™ๅ ดๅˆใฏdriver-loopใฎๅ‰ใซไธŠ่จ˜ใฎๅฎŸ่ฃ…ใ‚’load (driver-loop) ;; (driver-loop)ๅพŒ, requireใฎๅฎŸ่ฃ…ใจๆง‹ๆ–‡่งฃๆžใฎๆๆ–™ใ‚’loadใ™ใ‚‹ {{{1 ;; extracted with $ egrep "^[^;]" sec4.3.2-Examples-of-Nondeterministic-Programs.scm (define (require p) (if (not p) (amb))) (define (an-element-of items) (require (not (null? items))) (amb (car items) (an-element-of (cdr items)))) (define nouns '(noun student professor cat class)) (define verbs '(verbs studies lectures eats sleeps)) (define articles '(articles the a)) (define (parse-sentence) (list 'sentence (parse-noun-phrase) (parse-word verbs))) (define (parse-noun-phrase) (list 'noun-phrase (parse-word articles) (parse-word nouns))) (define (parse-word word-list) (require (not (null? *unparsed*))) (require (memq (car *unparsed*) (cdr word-list))) (let ((found-word (car *unparsed*))) (set! *unparsed* (cdr *unparsed*)) (list (car word-list) found-word))) (define *unparsed* '()) (define (parse input) (set! *unparsed* input) (let ((sent (parse-sentence))) (require (null? *unparsed*)) sent)) (define prepositions '(prep for to in by with)) (define (parse-prepositional-phrase) (list 'prep-phrase (parse-word prepositions) (parse-noun-phrase))) (define (parse-sentence) (list 'sentence (parse-noun-phrase) (parse-verb-phrase))) (define (parse-verb-phrase) (define (maybe-extend verb-phrase) (amb verb-phrase (maybe-extend (list 'verb-phrase verb-phrase (parse-prepositional-phrase))))) (maybe-extend (parse-word verbs))) (define (parse-simple-noun-phrase) (list 'simple-noun-phrase (parse-word articles) (parse-word nouns))) (define (parse-noun-phrase) (define (maybe-extend noun-phrase) (amb noun-phrase (maybe-extend (list 'noun-phrase noun-phrase (parse-prepositional-phrase))))) (maybe-extend (parse-simple-noun-phrase))) ;;; }}}1 ;; ใชใŠใ“ใ“ใง, ใƒฉใƒณใƒ€ใƒ ใซwordใ‚’้ธใถใ‚ˆใ†ใซใ™ใ‚‹ใŸใ‚, an-element-ofใฎๅฎŸ่ฃ…ใ‚’ ramb ใƒใƒผใ‚ธใƒงใƒณใซใ™ใ‚‹. (define (an-element-of items) (require (not (null? items))) (ramb (car items) (an-element-of (cdr items)))) ;; amb -> ramb ;; q4.49.scm ใจๅŒใ˜ parse-word ใ‚’ๅฎš็พฉ (define (parse-word word-list) (list (car word-list) (an-element-of (cdr word-list)))) ;; an-element-ofใ‚’ๆ›ธใๆ›ใˆใฆ q4.49.scm ใจๅŒใ˜parse-wordใ‚’ไฝฟใ†ไปฅๅค–ใซ, ;; parse-wordใ‹ใ‚‰็›ดๆŽฅpick1ใ‚„rejectใ‚’ไฝฟใฃใฆใƒฉใƒณใƒ€ใƒ ใซใƒชใ‚นใƒˆใ‚’็”Ÿๆˆใ™ใ‚‹(?)ๆ–นๆณ•ใ‚‚ใ‚ใ‚‹. ;; ๅฎŸ่กŒ็ตๆžœ {{{2 ; ;;; Amb-Eval input: ; (parse-sentence) ; ; ;;; Starting a new problem ; ; ;;; Amb-Eval value ; (sentence (simple-noun-phrase (articles a) (noun cat)) (verbs eats)) ; ; ;;; Amb-Eval input: ; try-again ; ; ;;; Amb-Eval value ; (sentence (simple-noun-phrase (articles a) (noun cat)) (verb-phrase (verbs eats) (prep-phrase (prep to) (simple-noun-phrase (articles the) (noun professor))))) ; ; ;;; Amb-Eval input: ; try-again ; ; ;;; Amb-Eval value ; (sentence (simple-noun-phrase (articles a) (noun cat)) (verb-phrase (verb-phrase (verbs eats) (prep-phrase (prep to) (simple-noun-phrase (articles the) (noun professor)))) (prep-phrase (prep for) (simple-noun-phrase (articles a) (noun class))))) ; ; ;;; Amb-Eval input: ; try-again ; ; ;;; Amb-Eval value ; (sentence (simple-noun-phrase (articles a) (noun cat)) (verb-phrase (verb-phrase (verb-phrase (verbs eats) (prep-phrase (prep to) (simple-noun-phrase (articles the) (noun professor)))) (prep-phrase (prep for) (simple-noun-phrase (articles a) (noun class)))) (prep-phrase (prep for) (simple-noun-phrase (articles a) (noun cat))))) ; ; ;;; Amb-Eval input: ; try-again ; ; ;;; Amb-Eval value ; (sentence (simple-noun-phrase (articles a) (noun cat)) (verb-phrase (verb-phrase (verb-phrase (verb-phrase (verbs eats) (prep-phrase (prep to) (simple-noun-phrase (articles the) (noun professor)))) (prep-phrase (prep for) (simple-noun-phrase (articles a) (noun class)))) (prep-phrase (prep for) (simple-noun-phrase (articles a) (noun cat)))) (prep-phrase (prep for) (simple-noun-phrase (articles a) (noun student)))))
false
a31cdfa0395ddf8bb9b05d740a648d1c66a62a01
35f859a6933537955f878e97455cd45b312aa042
/example/processing/learning/2darray/eg1.scm
21a68b2ccfee7d984d19b21f75ef9609b6cda4de
[]
no_license
podhmo/gauche-gl-processing
ebbbe2631830cb7d0e62b5e5aa0275bb176c7084
d57b9c055d2dfe199df5652e1afb0cfd1713257f
refs/heads/master
2021-01-23T08:38:44.547876
2010-10-13T08:40:19
2010-10-13T08:40:19
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
630
scm
eg1.scm
(use gl.processing) (define myarray '#(#(236 189 189 0) #(236 80 189 189) #(236 0 189 80) #(236 189 189 80))) (define draw (draw-once$ (^ () (let* ((margin 50) (board (2dvector->board myarray :each-size margin))) (board-for-each* (^ (x y color x* y*) (fill color) (rect x* y* margin margin)) board))) :save "eg1.png")) (define main (setup$ (^ () (window 200 200 "eg1" 100 100)) :draw draw)) (main '())
false
35d9211a4f7d685ae7653a6c2b4084b53786e7e2
99f659e747ddfa73d3d207efa88f1226492427ef
/datasets/srfi/srfi-77/arithmetic-reference/bellerophon.scm
8ba4bb5b69e132120deac7c26e449eed539cc7c6
[ "MIT" ]
permissive
michaelballantyne/n-grams-for-synthesis
241c76314527bc40b073b14e4052f2db695e6aa0
be3ec0cf6d069d681488027544270fa2fd85d05d
refs/heads/master
2020-03-21T06:22:22.374979
2018-06-21T19:56:37
2018-06-21T19:56:37
138,215,290
0
0
MIT
2018-06-21T19:51:45
2018-06-21T19:51:45
null
UTF-8
Scheme
false
false
15,805
scm
bellerophon.scm
; This file is part of the reference implementation of the R6RS Arithmetic SRFI. ; See file COPYING. ; from Larceny ; A version of Algorithm Bellerophon for implementations ; of Scheme that support IEEE double precision arithmetic ; and exact integer arithmetic of unlimited precision. ; #### Mike probably didn't do a great job abstracting this over the ; floating-point precision. (define n fl-ieee-mantissa-width) (define two^n-1 (integer-expt (r5rs->integer 2) (integer- n (r5rs->integer 1)))) (define two^n (integer-expt (r5rs->integer 2) n)) (define p (integer+ n (r5rs->integer 9))) (define two^p-1 (integer-expt (r5rs->integer 2) (integer- p (r5rs->integer 1)))) (define two^p (integer-expt (r5rs->integer 2) p)) (define two^p-n-1 (integer-expt (r5rs->integer 2) (integer- (integer- p n) (r5rs->integer 1)))) (define two^p-n (integer-expt (r5rs->integer 2) (integer- (integer- p n) (r5rs->integer 1)))) (define flonum:zero (r5rs->flonum 0.0)) (define flonum:infinity flinf+) (define flonum:minexponent fl-ieee-min-exponent) (define flonum:minexponent-51 fl-ieee-min-exponent/denormalized) (define bellerophon:big-f (integer-expt (r5rs->integer 2) p)) (define bellerophon:small-e (flonum->integer (flceiling (fl/ (integer->flonum fl-ieee-min-exponent) (fl/ (fllog (r5rs->flonum 10.0)) (fllog (r5rs->flonum 2.0))))))) (define bellerophon:big-e (flonum->integer (flceiling (fl/ (integer->flonum fl-ieee-max-exponent) (fl/ (fllog (r5rs->flonum 10.0)) (fllog (r5rs->flonum 2.0))))))) (define (bellerophon f e p) (cond ((integer-negative? f) (integer- (bellerophon (integer-negate f) e p))) ((integer-zero? f) flonum:zero) ((not (integer= p n)) (fail0 f e (integer-min p (integer- n (r5rs->integer 1))))) ((integer<= bellerophon:big-f f) (fail0 f e p)) ((integer< e bellerophon:small-e) (fail0 f e p)) ((integer< bellerophon:big-e e) flonum:infinity) ((and (integer< f two^n) (integer>= e (r5rs->integer 0)) (integer< e log5-of-two^n)) (fl* (integer->flonum f) (integer->flonum (integer-expt (r5rs->integer 10) e)))) ((and (integer< f two^n) (integer< e (r5rs->integer 0)) (integer< (integer-negate e) log5-of-two^n)) (fl/ (integer->flonum f) (integer->flonum (integer-expt (r5rs->integer 10) (integer-negate e))))) (else (multiply-and-test f e (cond ((integer< e (r5rs->integer -216)) slop-216) ((integer< e (r5rs->integer -108)) slop-108) ((integer< e (r5rs->integer -54)) slop-54) ((integer< e (r5rs->integer -27)) slop-27) ((integer< e (r5rs->integer 0)) slop0) ((integer<= e (r5rs->integer 27)) slop27) ((integer<= e (r5rs->integer 54)) slop54) ((integer<= e (r5rs->integer 108)) slop108) ((integer<= e (r5rs->integer 216)) slop216) (else slop324)))))) (define (multiply-and-test f e slop) (let ((x (integer->extended f)) (y (ten-to-e e))) (let ((z (extended-multiply x y))) (if (integer<= (integer-abs (integer- (extended-lowbits z) two^p-n-1)) slop) (fail f e z) (extended->flonum z))))) (define (fail0 f e n) (AlgorithmM f e n)) (define (fail f e z) (AlgorithmM f e n)) ; Powers of ten are computed from a small table containing ; the best extended precision approximations to ; 10^-216, 10^-108, 10^-54, 10^-27, 10^27, 10^54, 10^108, 10^216. ; The table of powers of ten; see assignments below. (define ten^-216 #f) (define ten^-108 #f) (define ten^-54 #f) (define ten^-27 #f) (define ten^27 #f) (define ten^54 #f) (define ten^108 #f) (define ten^216 #f) (define (ten-to-e e) (cond ((integer< e (r5rs->integer -432)) (error "Impossible case 1 in bellerophon: " e) #t) ((integer< e (r5rs->integer -216)) (extended-multiply ten^-216 (extended-multiply ten^-216 (ten-to-e (integer+ e (r5rs->integer 432)))))) ((integer< e (r5rs->integer -108)) (extended-multiply ten^-216 (ten-to-e (integer+ e (r5rs->integer 216))))) ((integer< e (r5rs->integer -54)) (extended-multiply ten^-108 (ten-to-e (integer+ e (r5rs->integer 108))))) ((integer< e (r5rs->integer -27)) (extended-multiply ten^-54 (ten-to-e (integer+ e (r5rs->integer 54))))) ((integer< e (r5rs->integer 0)) (extended-multiply ten^-27 (ten-to-e (integer+ e (r5rs->integer 27))))) ((integer<= e (r5rs->integer 27)) (integer->extended (integer-expt (r5rs->integer 10) e))) ((integer<= e (r5rs->integer 54)) (extended-multiply ten^27 (ten-to-e (integer- e (r5rs->integer 27))))) ((integer<= e (r5rs->integer 108)) (extended-multiply ten^54 (ten-to-e (integer- e (r5rs->integer 54))))) ((integer<= e (r5rs->integer 216)) (extended-multiply ten^108 (ten-to-e (integer- e (r5rs->integer 108))))) ((integer<= e (r5rs->integer 324)) (extended-multiply ten^216 (ten-to-e (integer- e (r5rs->integer 216))))) (else (error "Impossible case 2 in bellerophon: " e) #t))) ; These slop factors assume that f can be represented exactly ; as an extended precision number, so the slop factor is exactly ; twice the maximum error in the approximation to 10^e. (define slop-216 (r5rs->integer 45)) (define slop-108 (r5rs->integer 9)) (define slop-54 (r5rs->integer 3)) (define slop-27 (r5rs->integer 3)) (define slop0 (r5rs->integer 1)) (define slop27 (r5rs->integer 0)) (define slop54 (r5rs->integer 1)) (define slop108 (r5rs->integer 3)) (define slop216 (r5rs->integer 9)) (define slop324 (r5rs->integer 21)) ; Precomputed so we don't have to rely on LOG in initialization phase. ; (define log5-of-two^n (inexact->exact (ceiling (/ (log two^n) (log 5))))) (define log5-of-two^n (r5rs->integer 23)) ; Extended precision floating point, implemented entirely ; in Scheme for portability and ease of maintenance. ; ; The following operations are used directly by Algorithm Bellerophon: ; ; (integer->extended m) ; (make-extended m q) ; (extended->flonum ex) ; (multiply-extended ex1 ex2) ; (extended-lowbits ex) ; ; All numbers are positive; negative numbers and zero are ; not supported. ; ; An extended is represented as a pair (x t) where x and t are ; exact integers. Its value is x * 2^t. A normalized extended ; is an extended for which 2^{p-1} <= x < 2^p. (define make-extended list) (define (extended-significand f) (car f)) (define (extended-exponent f) (cadr f)) ; This flag is set by some operations to indicate whether ; any accuracy was lost during the operation. ; NOTE: This makes this code not thread-safe. Making all of these ; local definitions internal should fix things. (define inexact-flag #f) ; (expt 2 (- (* 2 p) 1)) (define two^2p-1 (r5rs->integer 170141183460469231731687303715884105728)) ; (expt 2 (- (* 2 n) 1)) (define two^2n-1 (r5rs->integer 40564819207303340847894502572032)) (define (integer->extended n) (cond ((integer< n two^p-1) (extended-normalize (make-extended n (r5rs->integer 0)) two^p-1)) ((integer>= n two^p) (extended-normalize-and-round (make-extended n (r5rs->integer 0)) two^p)) (else (make-extended n (r5rs->integer 0))))) ; Given an extended whose significand is less than two^p-1, ; returns the normalized extended having the same value. ; Because two^p-1 is a parameter, this can be used for various ; precisions other than p. (define (extended-normalize f two^p-1) (let ((x (extended-significand f)) (t (extended-exponent f))) (if (integer<= two^p-1 x) (begin (set! inexact-flag #f) (make-extended x t)) (extended-normalize (make-extended (integer* (r5rs->integer 2) x) (integer- t (r5rs->integer 1))) two^p-1)))) ; Given an extended whose significand is greater than two^p, ; returns the normalized extended closest to the given float, ; rounding to even in case of ties. ; two^p is a parameter so this can be used for different ; precisions. (define (extended-normalize-and-round f two^p) (do ((x (extended-significand f) (integer-quotient x (r5rs->integer 2))) (guard (r5rs->integer 0) (integer-remainder x (r5rs->integer 2))) (sticky (r5rs->integer 0) (integer-max sticky guard)) (t (extended-exponent f) (integer+ t (r5rs->integer 1)))) ((integer< x two^p) ;; The result is probably inexact. ;; This setting will be changed if incorrect. (set! inexact-flag #t) (cond ((integer-zero? guard) (set! inexact-flag (not (integer-zero? sticky))) (make-extended x t)) ((and (integer-zero? sticky) (integer-even? x)) (make-extended x t)) ((integer= x (integer- two^p (r5rs->integer 1))) (make-extended (integer-quotient two^p (r5rs->integer 2)) (integer+ t (r5rs->integer 1)))) (else (make-extended (integer+ x (r5rs->integer 1)) t)))))) ; Given an extended, round it to the nearest flonum ; (with n bits of precision instead of p). (define (extended->flonum f) (let ((ff (extended-normalize-and-round f two^n))) (make-float (extended-significand ff) (extended-exponent ff)))) ; Given normalized extendeds, return their normalized product. (define (extended-multiply f1 f2) (let ((f (integer* (extended-significand f1) (extended-significand f2))) (t (integer+ (integer+ (extended-exponent f1) (extended-exponent f2)) p))) ;; Set flag for most common case. (set! inexact-flag #t) (if (integer<= two^2p-1 f) (let ((q (integer-quotient f two^p)) (r (integer-remainder f two^p))) (cond ((integer< r two^p-1) (if (integer-zero? r) (set! inexact-flag #f)) (make-extended q t)) ((integer> r two^p-1) (make-extended (integer+ q (r5rs->integer 1)) t)) ((integer-even? q) (make-extended q t)) (else (make-extended (integer+ q (r5rs->integer 1)) t)))) (let ((q (integer-quotient f two^p-1)) (r (integer-remainder f two^p-1))) (cond ((integer< r two^p-1) (if (integer-zero? r) (set! inexact-flag #f)) (make-extended q (integer- t (r5rs->integer 1)))) ((integer> r two^p-1) (make-extended (integer+ q (r5rs->integer 1)) (integer- t (r5rs->integer 1)))) ((integer-even? f) (make-extended q (integer- t (r5rs->integer 1)))) ((integer= q (integer- two^p-1 (r5rs->integer 1))) (make-extended two^p-1 t)) (else (make-extended (integer+ q (r5rs->integer 1)) (integer- t (r5rs->integer 1))))))))) (define (extended-lowbits ex) (integer-remainder (extended-significand ex) two^p-n)) ; End of extended precision number implementation. ; Backup algorithm. ; I'm using an extremely slow backup algorithm, mainly because ; the slow algorithm is needed anyway for denormalized numbers ; and I'm trying to keep things simple. ; Given exact integers f, e, and n, with f nonnegative, returns the ; n-bit precision floating point number closest to f * 10^e. (define (AlgorithmM f e n) (define two^n-1 (integer-expt (r5rs->integer 2) (integer- n (r5rs->integer 1)))) (define two^n (integer-expt (r5rs->integer 2) n)) ;; f * 10^e = u/v * 2^k (define (loop u v k) (let ((x (integer-quotient u v))) (cond ((and (integer<= two^n-1 x) (integer< x two^n)) (ratio->float u v k)) ((integer< x two^n-1) (loop (integer* (r5rs->integer 2) u) v (integer- k (r5rs->integer 1)))) ((integer<= two^n x) (loop u (integer* (r5rs->integer 2) v) (integer+ k (r5rs->integer 1))))))) (if (integer-negative? e) (loop f (integer-expt (r5rs->integer 10) (integer-negate e)) (r5rs->integer 0)) (loop (integer* f (integer-expt (r5rs->integer 10) e)) (r5rs->integer 0) (r5rs->integer 1)))) ; Given exact positive integers p and q with ; 2^(n-1) <= u/v < 2^n, and exact integer k, ; returns the float closest to u/v * 2^k. (define (ratio->float u v k) (let* ((q (integer-quotient u v)) (r (integer- u (integer* q v))) (v-r (integer- v r))) (cond ((integer< r v-r) (make-float q k)) ((integer> r v-r) (make-float (integer+ q (r5rs->integer 1)) k)) ((integer-zero? (integer-remainder q (r5rs->integer 2))) (make-float q k)) (else (make-float (integer+ q (r5rs->integer 1)) k))))) ; END OF ALGORITHM MultiplyByTwos ; Primitive operations on flonums. (define (make-float m q) (let loop ((m (if (flonum? m) m (integer->flonum m))) (q q)) (if (integer< q flonum:minexponent) (loop (fl* (r5rs->flonum .5) m) (integer+ q (r5rs->integer 1))) (fl* m (fl-integer-expt (fixnum->flonum (r5rs->integer 2)) q))))) (define (fl-integer-expt x y) (define (recur y) (cond ((integer-zero? y) (r5rs->flonum 1.0)) ((integer-odd? y) (fl* x (recur (integer- y (r5rs->integer 1))))) (else (let ((v (recur (integer-quotient y (r5rs->integer 2))))) (fl* v v))))) (if (integer>= y (r5rs->integer 0)) (recur y) (fl/ (r5rs->flonum 1.0) (recur (integer-negate y))))) (define (slow-ten-to-e e) (define (loop1 y s guardbit) (cond ((integer< y two^p) (make-extended (if (integer-zero? guardbit) y (integer+ y (r5rs->integer 1))) s)) (else (loop1 (integer-quotient y (r5rs->integer 2)) (integer+ s (r5rs->integer 1)) (integer-remainder y (r5rs->integer 2)))))) (define (loop2 y s) (cond ((integer<= two^p-1 y) (make-extended y s)) (else (loop2 (integer* (r5rs->integer 2) y) (integer- s (r5rs->integer 1)))))) (define (loop3 x y n) (cond ((integer>= x (integer* y two^p-1)) (loop3-help x y (integer-negate n))) (else (loop3 (integer* (r5rs->integer 2) x) y (integer+ n (r5rs->integer 1)))))) (define (loop3-help x y n) (let* ((q (integer-quotient x y)) (r (integer- x (integer* q y))) (y-r (integer- y r))) (make-extended (cond ((integer< r y-r) q) ((integer> r y-r) (integer+ q (r5rs->integer 1))) ((integer-zero? (integer-remainder q (r5rs->integer 2))) q) (else (integer+ q (r5rs->integer 1)))) n))) (if (integer-negative? e) (loop3 (r5rs->integer 1) (integer-expt (r5rs->integer 10) (integer-negate e)) (r5rs->integer 0)) (let ((ten^e (integer-expt (r5rs->integer 10) e))) (cond ((integer>= ten^e two^p) (loop1 ten^e (r5rs->integer 0) (r5rs->integer 0))) (else (loop2 ten^e (r5rs->integer 0))))))) ; (set! ten^-216 (slow-ten-to-e (r5rs->integer -216))) ; (set! ten^-108 (slow-ten-to-e (r5rs->integer -108))) ; (set! ten^-54 (slow-ten-to-e (r5rs->integer -54))) ; (set! ten^-27 (slow-ten-to-e (r5rs->integer -27))) ; (set! ten^27 (slow-ten-to-e (r5rs->integer 27))) ; (set! ten^54 (slow-ten-to-e (r5rs->integer 54))) ; (set! ten^108 (slow-ten-to-e (r5rs->integer 108))) ; (set! ten^216 (slow-ten-to-e (r5rs->integer 216))) ; slow-ten-to-e is _really_ slow in Larceny. ; precomputed by slow-ten-to-e (set! ten^-216 (list (r5rs->integer 12718228212127407597) (r5rs->integer -781))) (set! ten^-108 (list (r5rs->integer 10830740992659433045) (r5rs->integer -422))) (set! ten^-54 (list (r5rs->integer 14134776518227074637) (r5rs->integer -243))) (set! ten^-27 (list (r5rs->integer 11417981541647679048) (r5rs->integer -153))) (set! ten^27 (list (r5rs->integer 14901161193847656250) (r5rs->integer 26))) (set! ten^54 (list (r5rs->integer 12037062152420224082) (r5rs->integer 116))) (set! ten^108 (list (r5rs->integer 15709099088952724970) (r5rs->integer 295))) (set! ten^216 (list (r5rs->integer 13377742608693866209) (r5rs->integer 654))) ; eof
false
5d9f0276eb946ede15b10e69061447cbaaa5e850
4f6a6e56a909ffdeb9c6a73790200a68f8f0c82c
/lib/tooling/tooling/test/tooling.scm
927ecbd62be04db7923d3c5980c6caa57fe6aca0
[ "MIT" ]
permissive
eshoo/detroit-scheme
c5ddda1bc19ce85b87a309a2b36299e607e7da65
84c2333d1e04dd3425c2275da94375aedab34a9e
refs/heads/master
2021-01-24T23:11:27.991392
2010-03-02T02:21:45
2010-03-02T02:21:45
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,412
scm
tooling.scm
; Copyright (c) 2009, Raymond R. Medeiros. All rights reserved. ; tests for extras library (use fold amk combine count depth exists explode filter flatten fluid-let for-all implode intersection iota list-to-set make-partitions mergesort partition permute quicksort read-file read-line regex remove replace string-contains string-split substitute transpose union write-to-string) (check (combine 2 '(a b c)) => '((a b) (a c) (b c))) (check (combine* 2 '(a b c)) => '((a a) (a b) (a c) (b b) (b c) (c c))) (check (count '(a (b (c)) d . e)) => 5) (check (depth '(a (b (c d (e))))) => 4) (check (exists < '(9 1) '(8 2) '(7 3)) => #t) (check (explode 'supernova) => '(s u p e r n o v a)) (check (filter number? '(a 1 b 2 c 3)) => '(1 2 3)) (check (flatten '(a (b ((c) d . e)))) => '(a b c d e)) (check (let ((a 0)) (let ((f (lambda () a))) (fluid-let ((a 1)) (f)))) => 1) (check (for-all < '(1 7) '(2 8) '(3 9)) => #t) (check (implode '(b l a c k h o l e)) => 'blackhole) (check (intersection '(v w x) '(w x y) '(x y z)) => '(x)) (check (iota 17 21) => '(17 18 19 20 21)) (check (list->set '(a b c b c)) => '(a b c)) (check (make-partitions 4) => '((4) (3 1) (2 2) (2 1 1) (1 1 1 1))) (check (mergesort < '(5 3 7 9 1)) => '(1 3 5 7 9)) (check (partition even? '(1 2 3 4 5)) => '((2 4) (1 3 5))) (check (permute 2 '(a b c)) => '((a b) (b a) (a c) (c a) (b c) (c b))) (check (permute* 2 '(a b c)) => '((a a) (a b) (a c) (b a) (b b) (b c) (c a) (c b) (c c))) (check (quicksort < '(5 3 7 9 1)) => '(1 3 5 7 9)) (check (re-match (re-comp "^a[b-y]+z$") "abz") => "abz") (check (re-match (re-comp "^a[b-y]+z$") "abbbz") => "abbbz") (check (re-match (re-comp "^a[b-y]+z$") "az") => #f) (check (remove number? '(a 1 b 2 c 3)) => '(a b c)) (check (replace '(x) '(y) '(lambda (x) y)) => '(lambda (y) y)) (check (string-contains "gemeinsam" "ein") => "einsam") (check (string-contains "democracy" "people") => #f) (check (string-split #\space " to be or not to be ") => '("to" "be" "or" "not" "to" "be")) (check (substitute '(* (+ 5 7) 9) '(((+ 5 7) . 12))) => '(* 12 9)) (check (transpose '((1 2 3) (4 5 6))) => '((1 4) (2 5) (3 6))) (check (union '(v w x) '(w x y) '(x y z)) => '(v w x y z)) (check (write-to-string '(a 1 #\c #(v) #t "str" "\"s\"" (a . d))) => "(a 1 #\\c #(v) #t \"str\" \"\\\"s\\\"\" (a . d))") (check (display-to-string '(a 1 #\c #(v) #t "str" "\"s\"" (a . d))) => "(a 1 c #(v) #t str \"s\" (a . d))")
false
4dcc2e3c943dbe2f7fbe6a56ea5a1902292fc7b8
b7ec5209446e33ec4b524c66c4d52ff852e46ae4
/Objets/Deux boules.scm
cf84dfa0b84adb4f3000706d3a73ad55a93f1fb9
[]
no_license
antjacquemin/physics
a2751f69ee0a54bbb17e46c6bbb2d3b478776136
fd0444c838d097c795fdb1af3a8f3507e810fae5
refs/heads/master
2023-03-31T23:58:49.022201
2020-07-13T09:33:35
2020-07-13T09:33:35
279,257,815
1
0
null
null
null
null
UTF-8
Scheme
false
false
780
scm
Deux boules.scm
;***************************************************** ; PROJET PHYSICS ; ANNEE 2008 ; PROGRAMMEURS : F. CORLAIS & A. JACQUEMIN ; MAJ : 27.04.2008 ;***************************************************** ;***************************************************** ; "Deux boules.scm" ; Exemple de la partie "POO" ; Le monde est rรฉduit a deux boules qui s'entrechoquent ;***************************************************** (set! GRAVITE 0.) (set! WORLD (cons (new masse% (ray R1_2B) (masse M1_2B) (couleur "blue") (position (make-vect 350 140)) (vitesse V1_2B)) WORLD)) (set! WORLD (cons (new masse% (ray R2_2B) (masse M2_2B) (couleur "green") (position (make-vect 150 200)) (vitesse V2_2B)) WORLD))
false
2c24e725a25c4af183a7d9952da53b2d9d4f4b0f
ac2a3544b88444eabf12b68a9bce08941cd62581
/gsc/tests/24-proc/ops.scm
b59ce063ff1e7ee67d7de2794d44fa97331c083e
[ "Apache-2.0", "LGPL-2.1-only" ]
permissive
tomelam/gambit
2fd664cf6ea68859d4549fdda62d31a25b2d6c6f
d60fdeb136b2ed89b75da5bfa8011aa334b29020
refs/heads/master
2020-11-27T06:39:26.718179
2019-12-15T16:56:31
2019-12-15T16:56:31
229,341,552
1
0
Apache-2.0
2019-12-20T21:52:26
2019-12-20T21:52:26
null
UTF-8
Scheme
false
false
1,154
scm
ops.scm
(declare (extended-bindings) (not constant-fold) (not safe)) (declare (inlining-limit 0) (block)) ;(declare (debug)) (define (foo) (lambda (x) (##fx+ x x))) (define f (foo)) (define (make-adder x) (lambda (y) (##fx+ y x))) (define add1 (make-adder 1)) (println (##eq? foo (##subprocedure-parent foo))) (println (##eq? foo (##subprocedure-parent f))) (println (##eq? make-adder (##subprocedure-parent make-adder))) (println (##eq? make-adder (##subprocedure-parent (##closure-code add1)))) (define (check fn) (let ((id (##subprocedure-id fn)) (parent (##subprocedure-parent fn)) (name (##subprocedure-parent-name fn))) (println (##subprocedure-parent-info fn)) (println (##subprocedure-nb-closed fn)) (println name) (println (##fx= 0 id)) (println (##eq? fn (##make-subprocedure parent id))) (println (##eq? fn (##make-subprocedure (##global-var-primitive-ref (##make-global-var name)) id))))) (check foo) (check make-adder) (check (##closure-code add1))
false
20cb42ba140bdc80fae4b409b0b71be024567b21
87f1e27952a387ff6a7d0625169d9a4f6cd960b2
/gwl/www/pages/extended-start.scm
8c25c565ef28266a15b13ee625c625065bb868c7
[]
no_license
guixwl/gwl
f5d21ca3563eed71e5cabb076f783fab63309cd1
036a6e043b9ee010b0ca7eaa5bd1381555385808
refs/heads/master
2020-03-17T23:42:10.633451
2018-03-11T11:22:16
2018-05-17T10:11:40
134,056,393
0
0
null
null
null
null
UTF-8
Scheme
false
false
4,370
scm
extended-start.scm
;;; Copyright ยฉ 2018 Roel Janssen <[email protected]> ;;; ;;; This program is free software: you can redistribute it and/or ;;; modify it under the terms of the GNU Affero General Public License ;;; as published by the Free Software Foundation, either version 3 of ;;; the License, or (at your option) any later version. ;;; ;;; This program is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;; Affero General Public License for more details. ;;; ;;; You should have received a copy of the GNU Affero General Public ;;; License along with this program. If not, see ;;; <http://www.gnu.org/licenses/>. (define-module (gwl www pages extended-start) #:use-module (gwl www pages) #:use-module (syntax-highlight) #:use-module (syntax-highlight scheme) #:export (page-extended-start)) (define %guile-manual "https://www.gnu.org/software/guile/manual/html_node") (define (page-extended-start request-path) (page-root-template "Guix Workflow Language" request-path `((h2 "Beyond started with the Guix workflow language") (h3 "Recap") (p "In the " (a (@ (href "/beyond-started")) "previous section") " we" " defined a workflow. This section builds on the knowledge from the " "previous section, so if you haven't read that, now is the time to " (a (@ (href "/beyond-started")) "get beyond started") ".") (h3 "Extending workflows") (p "In the " (code "dynamic-workflow") " we create files and compressed" " those files. In the following workflow we will delete those" " compressed files to learn how we can extend a workflow at any point" " in a new workflow.") (div (@ (class "figure")) (pre (code (@ (class "scheme")) ,(highlights->sxml (highlight lex-scheme "(define-module (extended-example-workflow) #:use-module (guix processes) #:use-module (guix workflows) #:use-module ((gnu packages compression) #:prefix package:) #:use-module (srfi srfi-1) #:use-module (example-workflow)) ; We are going to extend \"example-workflow\". (define (delete-file-template filename) (process (name (string-append \"delete-file-\" (basename filename))) (run-time (complexity (space (megabytes 20)) (time 10))) (procedure `(delete-file ,filename)))) (define-public extended-dynamic-workflow (let* (;; Get all processes of the other workflow. (foreign-processes (workflow-processes dynamic-workflow)) ;; Get the processes that we want to extend on. (compress-file-processes (processes-filter-by-name foreign-processes \"compress-file\")) ;; Create the new processes. (delete-file-processes (map delete-file-template (map process-outputs compress-file-processes)))) (workflow (name \"extended-dynamic-workflow\") (processes (append foreign-processes delete-file-processes)) (restrictions (append (workflow-restrictions dynamic-workflow) (zip delete-file-processes compress-file-processes))))))"))))) (p "With " (code "delete-file-template") " we created a function that" " returns a " (code "process") " that removes a file. We use this" " function in " (code "extended-dynamic-workflow") " to run after" " each " (code "compress-file") " process.") (p "In the " (code "processes") " and " (code "restrictions") " fields we" " include the contents of " (code "dynamic-workflow") ". Explicitly" " expressing the new " (code "restrictions") " displays how this" " workflow extends the other in a concise way. Because " (code "dynamic-workflow") " is defined in a Scheme module, we can" " use the " (code "#:use-module") " facility to refer to it.") (h3 "Further reading") (p "The " (a (@ (href "https://www.gnu.org/software/guile/learn/")) "GNU Guile") " and " (a (@ (href "https://www.gnu.org/software/guix/manual/")) "GNU Guix") " manuals are good places to learn the language and concepts on which " "GWL builds."))))
false
f7cc26bea29e437439ea1549a61274f47f3c7dc0
5667f13329ab94ae4622669a9d53b649c4551e24
/number-theory/math.number-theory.polygonal.scm
6f5408944a6bb67a4b0031740acc0c3adde13e2d
[]
no_license
dieggsy/chicken-math
f01260e53cdb14ba4807f7e662c9e5ebd2da4dda
928c9793427911bb5bb1d6b5a01fcc86ddfe7065
refs/heads/master
2021-06-11T07:14:21.461591
2021-04-12T22:12:14
2021-04-12T22:12:14
172,310,771
2
1
null
null
null
null
UTF-8
Scheme
false
false
2,256
scm
math.number-theory.polygonal.scm
(module math.number-theory.polygonal (triangle-number triangle-number? sqr square-number? pentagonal-number pentagonal-number? hexagonal-number hexagonal-number? heptagonal-number heptagonal-number? octagonal-number octagonal-number?) (import scheme chicken.type (only chicken.base include) (only math.number-theory.quadratic quadratic-natural-solutions) (only miscmacros ensure) (only math.number-theory.base perfect-square) math.racket-shim) (: triangle-number (integer -> integer)) (define (triangle-number n) (quotient (* n (+ n 1)) 2)) (: triangle-number? (integer -> boolean)) (define (triangle-number? n) (not (null? (quadratic-natural-solutions 1/2 1/2 (- n))))) (: sqr (integer -> integer)) (define (sqr n) (* n n)) (: square-number? (integer -> boolean)) (define (square-number? n) (and (perfect-square n) #t)) (: pentagonal-number (integer -> integer)) (define (pentagonal-number n) (ensure natural? (quotient (* n (- (* 3 n) 1)) 2))) (: pentagonal-number? (integer -> boolean)) (define (pentagonal-number? n) (not (null? (quadratic-natural-solutions 3/2 -1/2 (- n))))) (: hexagonal-number (integer -> integer)) (define (hexagonal-number n) (ensure natural? (* n (- (* 2 n) 1)))) (: hexagonal-number? (integer -> boolean)) (define (hexagonal-number? n) (not (null? (quadratic-natural-solutions 2 -1 (- n))))) (: heptagonal-number (integer -> integer)) (define (heptagonal-number n) (ensure natural? (quotient (* n (- (* 5 n) 3)) 2))) (: heptagonal-number? (integer -> boolean)) (define (heptagonal-number? n) (not (null? (quadratic-natural-solutions 5/2 -3/2 (- n))))) (: octagonal-number (integer -> integer)) (define (octagonal-number n) (ensure natural? (* n (- (* 3 n) 2)))) (: octagonal-number? (integer -> boolean)) (define (octagonal-number? n) (not (null? (quadratic-natural-solutions 3 -2 (- n))))))
false
5d8638755a763fd0a8e28a93c1ceff75aeec4fc0
23d78f4c06e9d61b7d90d8ebd035eb1958fe2348
/lib/eopl/c2-16-lambda-exp.scm
6f08cc69e5760c6ded52ac44c9949a259fe042b9
[ "Unlicense" ]
permissive
seckcoder/pl_research
e9f5dbce4f56f262081318e12abadd52c79d081d
79bb72a37d3862fb4afcf4e661ada27574db5644
refs/heads/master
2016-09-16T09:40:34.678436
2014-03-22T02:31:08
2014-03-22T02:31:08
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,434
scm
c2-16-lambda-exp.scm
(library (eopl c2-16-lambda-exp) (export eopl-c2-16) (import (rnrs) (elegant-weapons tester) ) ; representation for lambda expression in which no parenthess around the bound ; variable (define var-exp? symbol?) (define lambda-exp? (lambda (lcexp) (eq? (car lcexp) 'lambda))) (define lambda-exp->bound-var (lambda (lcexp) (cadr lcexp))) (define lambda-exp->body (lambda (lcexp) (caddr lcexp))) (define app-exp->ractor car) (define app-exp->rand cadr) (define occurs-free? (lambda (var lcexp) (cond ((var-exp? lcexp) (eq? var lcexp)) ((lambda-exp? lcexp) (and (not (eq? var (lambda-exp->bound-var lcexp))) (occurs-free? var (lambda-exp->body lcexp)))) (else (or (occurs-free? var (app-exp->ractor lcexp)) (occurs-free? var (app-exp->rand lcexp))))))) (define-test-suite eopl-c2-16 (c2.16 (lambda (fail) (or (equal? (occurs-free? 'x 'x) #t) (fail)) (or (equal? (occurs-free? 'x 'y) #f) (fail)) (or (equal? (occurs-free? 'x '(lambda x (x y))) #f) (fail)) (or (equal? (occurs-free? 'x '(lambda y (x y))) #t) (fail)) (or (equal? (occurs-free? 'x '((lambda x x) (x y))) #t) (fail)) (or (equal? (occurs-free? 'x '(lambda y (lambda (z) (x (y z))))) #t) (fail)) ))) )
false
0d887c603a9f426df162543e4b9cf7f4ccd5258d
b677139ff9a19f61d483c7ba16b58844d15f092c
/mephisto/examples/gauchegong2007.scm
ed2ddc235710051bba68490ce99257b6838ff6f4
[]
no_license
torus/MEPHISTO
d68d63bf8b8083fe4b615e0a5463600a9a2c39ed
fe3664e4745ac33a6c9609ca353d7d6da98e30fe
refs/heads/master
2021-01-01T16:06:40.876833
2012-03-30T15:56:01
2012-03-30T15:56:01
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
15,870
scm
gauchegong2007.scm
;; puppet model with live-paint ;; $Id: live-puppet.scm,v 1.1 2006/08/25 23:38:49 torus Exp $ (use gauche.time) (use srfi-27) (load "./live-paint") (load "./live-puppet-lib") ;(main '()) (define (main args) (mephisto-add-cut! (make-live-stream)) (glut-init args) (glut-init-display-mode (logior GLUT_DOUBLE GLUT_DEPTH GLUT_RGB)) ;; Game mode (full screen) ;; (glut-game-mode-string "width=640 height=480 bpp~24 hertz=30") ;; (glut-enter-game-mode) ;; Window (glut-init-window-size 640 480) (glut-init-window-position 0 0) (glut-create-window "MEPHISTO DEMO") (mephisto-init!) (gl-clear-color 0.0 0.3 1.0 0.0) (thread-start! (make-thread (lambda () (puppet-main-2)))) ; (thread-start! (make-thread (lambda () (puppet-main)))) (glut-mouse-func mouse) (glut-main-loop) 0) (define *mouse-input* #f) (define (mouse button state x y) (set! *mouse-input* (list button state x y))) (define (make-input-stream) (stream-cons (if *mouse-input* (let1 i *mouse-input* (set! *mouse-input* #f) i) #f) (make-input-stream))) (define *mouse-handle* '()) (define (make-linear-path source target) (lambda (param) (point4f-add (point4f 0 0 0) (vector4f-add (vector4f-scale target param) (vector4f-scale source (- 1 param)))))) (define *tempo* 125/60) (define (make-catch-path height puppet1 ball-path source target timer) (time-counter-stop! timer) (time-counter-reset! timer) (let ((r (wire-get-value (puppet1 'r:wrist))) (l (wire-get-value (puppet1 'l:wrist)))) (wire-set-value! (puppet1 'r:wrist-path) (make-linear-path (list->vector4f (point4f->list r)) (vector4f-sub target (vector4f 2 0 0)))) (wire-set-value! (puppet1 'l:wrist-path) (make-linear-path (list->vector4f (point4f->list l)) (vector4f-add target (vector4f 2 0 0))))) (wire-set-value! ball-path (let ((factor (* height 4))) (lambda (param) (point4f-add (point4f 0 (- height (* factor (square (- param 0.5)))) 0) (vector4f-add (vector4f-scale target param) (vector4f-scale source (- 1 param))))))) ) (define (make-catch-anim wires source target mouse-args timer) (define-values (puppet1 ball-path ball-param ball-position motion:catch motion:handclap motion:jump motion:kneel motion:slump) (apply values wires)) (make-catch-path 20 puppet1 ball-path source target timer) (if (eq? (car mouse-args) GLUT_LEFT_BUTTON) (add-mouse-handler! (lambda (args) (make-catch-anim wires (vector4f 0 22 30) (vector4f (+ (random-integer 11) -5) (+ (random-integer 11) 17) 5) args timer))) (add-mouse-handler! (lambda (args) (wire-reset! motion:jump) (make-kneel-anim wires timer) (add-mouse-handler! (lambda (args) (wire-reset! motion:kneel) (wire-set-value! motion:jump #t) (handclap! puppet1 motion:handclap))) (add-mouse-handler! (lambda (args) (initial-state puppet1 motion:jump) )) (add-mouse-handler! (lambda (args) (wire-reset! motion:catch) )) (add-mouse-handler! (lambda (args) (let ((waist (wire-get-value (puppet1 'waist))) (chest (wire-get-value (puppet1 'chest))) (r (wire-get-value (puppet1 'r:wrist))) (l (wire-get-value (puppet1 'l:wrist)))) (wire-reset! motion:jump) (wire-reset! motion:handclap) (wire-reset! (puppet1 'right)) (wire-reset! (puppet1 'downward)) (wire-reset! (puppet1 'forward)) (wires-set-value! ((puppet1 'waist) (point4f 0 16 0)) (motion:slump #t)) (make-bow-anim puppet1 ball-path (vector4f 5 14 8) timer) ))) (add-mouse-handler! (lambda (args) (make-bow-anim puppet1 ball-path (vector4f -5 14 8) timer))) (add-mouse-handler! (lambda (args) (make-bow-anim puppet1 ball-path (vector4f 0 14 8) timer))) (add-mouse-handler! (lambda (args) (let ((wtimer (make <real-time-counter>)) (count (puppet1 'count)) (w (puppet1 'waist))) (let ((src (wire-get-value w)) (dst (point4f 0 5 1))) (time-counter-start! wtimer) (attach-constraint! (count => w) (begin (time-counter-stop! wtimer) (let ((t (time-counter-value wtimer))) (when (< t 1) (time-counter-start! wtimer)) (let1 p (if (< t 1) t 1) (list->point4f (vector4f->list (vector4f-add (vector4f-scale src (- 1 t)) (vector4f-scale dst t))))))) ) )))) (add-mouse-handler! (lambda (args) (make-bow-anim puppet1 ball-path (vector4f 0 3 15) timer))) )))) (define (make-bow-anim puppet1 ball-path target timer) (make-catch-path 1 puppet1 ball-path (vector4f 0 23 7) target timer) ) (define (make-kneel-anim wires timer) (define-values (puppet1 ball-path ball-param ball-position motion:catch motion:handclap motion:jump motion:kneel motion:slump) (apply values wires)) (make-catch-path 10 puppet1 ball-path (vector4f 0 22 30) (vector4f 0 10 17) timer) (wire-set-value! motion:kneel #t) (wire-set-value! (puppet1 'chest-path) (lambda (param) (point4f-add (point4f 0 23 0) (vector4f-scale (vector4f 0 -8 8) param)))) ) (define (make-handclap-anim wires) (define-values (puppet1 ball-path ball-param ball-position motion:catch motion:handclap motion:jump motion:kneel motion:slump) (apply values wires)) (wire-set-value! motion:handclap #t)) (define (add-mouse-handler! proc) (set! *mouse-handle* (append! *mouse-handle* (list proc)))) (define (slump-chest&right target waist up) (let ((t-w (point4f-sub target waist))) (let ((right (vector4f-normalize (vector4f-cross t-w up)))) (let ((l-square (vector4f-dot t-w t-w)) (vec (vector4f-cross right t-w))) (let1 ll (- (/ (square body-length) l-square) (square 1/2)) (list right (point4f-add waist (vector4f-add (vector4f-scale t-w 1/2) (vector4f-scale vec (sqrt (if (> ll 0) ll 0))))))))))) (define (handclap! puppet1 motion:handclap) (wire-set-value! (puppet1 'r:wrist-path) (lambda (param) (point4f-add (point4f 0 22 3) (vector4f-scale (vector4f -10 0 0) param)))) (wire-set-value! (puppet1 'l:wrist-path) (lambda (param) (point4f-add (point4f 0 22 3) (vector4f-scale (vector4f 10 0 0) param)))) (wires-reset! (puppet1 'l:wrist) (puppet1 'r:wrist)) (wire-set-value! motion:handclap #t) ) (define (initial-state puppet1 motion:jump) (wires-set-value! (motion:jump #t) ((puppet1 'forward) (vector4f 0 0 1)) ((puppet1 'downward) (vector4f 0 -1 0)) ((puppet1 'r:ankle) (point4f -3 0 0)) ((puppet1 'l:ankle) (point4f 3 0 0)) ((puppet1 'chest-path) (lambda (param) (point4f-add (point4f 0 25 0) (vector4f-scale (vector4f 0 -3 0) param)))) ((puppet1 'r:wrist) (point4f -4 12 2)) ((puppet1 'l:wrist) (point4f 4 12 2))) ) (define (puppet-main-2) (define puppet1 #f) (define-wires ball-position ball-path ball-param) (define-wires motion:handclap motion:jump motion:catch motion:kneel motion:slump) (define-wires paint-axis) (wire-set-value! paint-axis #t) (set! puppet1 (make-puppet)) (wire-reset! (puppet1 'motion:run)) (wire-set-value! (puppet1 'motion:normal) #t) (let ((pc (puppet1 'chest-param))) (attach-constraint! (motion:kneel ball-param => pc) ball-param)) (let ((pc (puppet1 'chest-param)) (pl (puppet1 'l:wrist-param)) (pr (puppet1 'r:wrist-param))) (attach-constraint! (motion:handclap pc => pl) pc) (attach-constraint! (motion:handclap pc => pr) pc)) (let ((count (puppet1 'count)) (param (make-wire)) (x-param (make-wire))) (let ((timer (make <real-time-counter>))) (attach-constraint! (count => param) (begin (time-counter-stop! timer) (let ((t (* (time-counter-value timer) *tempo*))) (time-counter-start! timer) (- t (floor t))))) (attach-constraint! (param => x-param) (let1 x (- (* param 2) 1) (- 1 (* x x)))) (let ((pc (puppet1 'chest-param))) (attach-constraint! (motion:jump x-param => pc) x-param)) )) (let ((c&r (make-wire)) (l (puppet1 'l:wrist)) (r (puppet1 'r:wrist)) (chest (puppet1 'chest)) (waist (puppet1 'waist)) (right (puppet1 'right))) (attach-constraint! (motion:slump ball-position waist => c&r) (slump-chest&right ball-position waist (vector4f 0 1 0))) (attach-constraint! (motion:slump c&r => chest) (cadr c&r)) (attach-constraint! (motion:slump c&r => right) (car c&r)) (attach-constraint! (motion:slump ball-position right => r) (point4f-add ball-position right)) (attach-constraint! (motion:slump ball-position right => l) (point4f-sub ball-position right)) ) (add-mouse-handler! (lambda (args) (initial-state puppet1 motion:jump) )) (add-mouse-handler! (lambda (args) (handclap! puppet1 motion:handclap) )) (let ((count (puppet1 'count)) (timer (make <real-time-counter>))) (attach-constraint! (ball-path ball-param => ball-position) (ball-path ball-param)) (attach-constraint! (count => ball-param) (begin (time-counter-stop! timer) (let1 t (* (time-counter-value timer) 1.5) (if (< t 1) (begin (time-counter-start! timer) t) 1)))) (let ((pr (puppet1 'r:wrist-param)) (pl (puppet1 'l:wrist-param))) (attach-constraint! (motion:catch ball-param => pr) (* ball-param ball-param)) (attach-constraint! (motion:catch ball-param => pl) (* ball-param ball-param)) (attach-constraint! (motion:slump ball-param => pr) ball-param) (attach-constraint! (motion:slump ball-param => pl) ball-param)) (add-mouse-handler! (lambda (args) ;; Don't jump! (wire-set-value! (puppet1 'chest-path) (lambda (param) (point4f-add (point4f 0 23 0) (vector4f-scale (vector4f 0 -1 0) param)))) (time-counter-start! timer) (make-catch-anim (list puppet1 ball-path ball-param ball-position motion:catch motion:handclap motion:jump motion:kneel motion:slump) (vector4f 0 22 30) (vector4f 0 22 3) args timer) (wire-reset! motion:handclap) (wire-set-value! motion:catch #t) ) )) (append-painter-streams! (stream (lambda () ;; camera control (gl-matrix-mode GL_PROJECTION) (gl-load-identity) (gl-frustum -20 20 -15 15 50 150) (gl-matrix-mode GL_MODELVIEW) (gl-load-identity) (glu-look-at 20.0 60.0 100.0 0.0 10.0 0.0 0.0 1.0 0.0) )) (stream-map (lambda (i) (lambda () (when (and i (eq? (cadr i) GLUT_UP) (pair? *mouse-handle*)) ((car *mouse-handle*) i) (set! *mouse-handle* (cdr *mouse-handle*))))) (make-input-stream)) ;; axis ;; (procedure-stream ;; (lambda/constraint ;; (paint-axis) ;; ((paint-green ;; (lambda () ;; (gl-push-matrix) ;; (gl-scale 10 0.5 0.5) ;; (gl-translate 0.5 0 0) ;; (glut-solid-cube 1) ;; (gl-pop-matrix) ;; (gl-push-matrix) ;; (gl-scale 0.5 10 0.5) ;; (gl-translate 0 0.5 0) ;; (glut-solid-cube 1) ;; (gl-pop-matrix) ;; (gl-push-matrix) ;; (gl-scale 0.5 0.5 10) ;; (gl-translate 0 0 0.5) ;; (glut-solid-cube 1) ;; (gl-pop-matrix) ;; ))))) ;; stage (procedure-stream (paint-green (lambda () (gl-push-matrix) (gl-scale 40 1 40) (gl-translate 0 -0.5 0) (glut-solid-cube 1) (gl-pop-matrix) ))) (procedure-stream (lambda/constraint (ball-position) ((move-to ball-position (paint-yellow (lambda () (gl-push-matrix) (gl-scale 2 2 2) (glut-solid-icosahedron) (gl-pop-matrix)))))) )) (paint-flower paint-red) (paint-flower paint-yellow) (paint-flower paint-green) ) (define (paint-flower paint-color) (let loop ((i 10)) (when (> i 0) (let ((x (- (random-integer 30) 15)) (z (- (random-integer 30) 15))) (append-painter-streams! (procedure-stream (paint-color (lambda () (gl-push-matrix) (gl-translate x 1 z) (glut-solid-cube 1) (gl-pop-matrix)))) )) (loop (- i 1)))) ) (define (puppet-main) (define puppet1 #f) (define puppet2 #f) (define puppet3 #f) (define puppet4 #f) (define puppet5 #f) (define puppet6 #f) (define puppet7 #f) (define puppet8 #f) (define headmat #f) (define chest #f) (append-painter-streams! (stream (lambda () ;; camera control (gl-matrix-mode GL_PROJECTION) (gl-load-identity) (gl-frustum -20 20 -15 15 50 150) (gl-matrix-mode GL_MODELVIEW) (gl-load-identity) (glu-look-at 0.0 60.0 100.0 0.0 20.0 0.0 0.0 1.0 0.0) ))) (set! puppet1 (make-puppet)) (sys-sleep 1) (set! puppet2 (make-puppet)) (sys-sleep 1) (set! puppet3 (make-puppet)) (sys-sleep 1) (set! puppet4 (make-puppet)) (set! puppet5 (make-puppet)) (set! puppet6 (make-puppet)) (set! puppet7 (make-puppet)) (set! puppet8 (make-puppet)) (set! headmat (puppet1 'head:matrix)) (set! chest (puppet1 'chest)) (append-painter-streams! (procedure-stream (lambda/constraint (headmat chest) (gl-push-matrix) (apply gl-translate (take (point4f->list chest) 3)) (gl-mult-matrix headmat) (gl-translate 2 0 1) ((paint-red cube)) (gl-pop-matrix) ))) (let1 u (* 10 pi) (wire-set-value! (puppet1 'count) 0) (wire-set-value! (puppet2 'count) u) (wire-set-value! (puppet3 'count) (* 2 u)) (wire-set-value! (puppet4 'count) (* 3 u)) (wire-set-value! (puppet5 'count) (* 4 u)) (wire-set-value! (puppet6 'count) (* 5 u)) (wire-set-value! (puppet7 'count) (* 6 u)) (wire-set-value! (puppet8 'count) (* 7 u)) ) (wire-set-value! (puppet1 'r:next) puppet8) (wire-set-value! (puppet1 'l:next) puppet2) (wire-set-value! (puppet2 'r:next) puppet1) (wire-set-value! (puppet2 'l:next) puppet3) (wire-set-value! (puppet3 'r:next) puppet2) (wire-set-value! (puppet3 'l:next) puppet4) (wire-set-value! (puppet4 'r:next) puppet3) (wire-set-value! (puppet4 'l:next) puppet5) (wire-set-value! (puppet5 'r:next) puppet4) (wire-set-value! (puppet5 'l:next) puppet6) (wire-set-value! (puppet6 'r:next) puppet5) (wire-set-value! (puppet6 'l:next) puppet7) (wire-set-value! (puppet7 'r:next) puppet6) (wire-set-value! (puppet7 'l:next) puppet8) (wire-set-value! (puppet8 'r:next) puppet7) (wire-set-value! (puppet8 'l:next) puppet1) (wire-reset! (puppet1 'motion:run)) (wire-reset! (puppet2 'motion:run)) (wire-reset! (puppet3 'motion:run)) (wire-reset! (puppet4 'motion:run)) (wire-reset! (puppet5 'motion:run)) (wire-reset! (puppet6 'motion:run)) (wire-reset! (puppet7 'motion:run)) (wire-reset! (puppet8 'motion:run)) (wire-set-value! (puppet1 'motion:pair) #t) (wire-set-value! (puppet2 'motion:pair) #t) (wire-set-value! (puppet3 'motion:pair) #t) (wire-set-value! (puppet4 'motion:pair) #t) (wire-set-value! (puppet5 'motion:pair) #t) (wire-set-value! (puppet6 'motion:pair) #t) (wire-set-value! (puppet7 'motion:pair) #t) (wire-set-value! (puppet8 'motion:pair) #t) (wire-set-value! (puppet1 'partner) puppet2) (wire-set-value! (puppet2 'partner) puppet1) (wire-set-value! (puppet3 'partner) puppet4) (wire-set-value! (puppet4 'partner) puppet3) (wire-set-value! (puppet5 'partner) puppet6) (wire-set-value! (puppet6 'partner) puppet5) (wire-set-value! (puppet7 'partner) puppet8) (wire-set-value! (puppet8 'partner) puppet7) (append-painter-streams! (procedure-stream (lambda/constraint (chest) ((move-to (point4f-add chest (vector4f 0 8 0)) (paint-red (bitmap-char-painter GLUT_BITMAP_HELVETICA_18 "Mayim Mayim"))) ) ))) )
false
9cce05b105d8864ef13e32f950282596263f24c7
e1fc47ba76cfc1881a5d096dc3d59ffe10d07be6
/ch4/4.16.scm
6e706fa88f3de31eb7a9194a3a0d890f7c900c16
[]
no_license
lythesia/sicp-sol
e30918e1ebd799e479bae7e2a9bd4b4ed32ac075
169394cf3c3996d1865242a2a2773682f6f00a14
refs/heads/master
2021-01-18T14:31:34.469130
2019-10-08T03:34:36
2019-10-08T03:34:36
27,224,763
2
0
null
null
null
null
UTF-8
Scheme
false
false
2,304
scm
4.16.scm
; (load "4.12.scm") ;; a) (define (lookup-variable-value var env) (let ((ret (lookup-variable-pair var env))) (if ret (let ((val (cdr ret))) (if (eq? val '*unassigned*) (error "Unassigned variable" var) val ) ) (error "Unboud variable" var) ) ) ) ;; b) ; (define (f x) ; (define (p1 ..) ; ) ; (define (p2 ..) ; ) ; .. ; ) (load "4.01.02.parse.scm") (define (scan-out-defines body) (define (defs seq) (if (null? seq) '() (let ((expr (car seq)) (rest (cdr seq))) (if (definition? expr) (cons expr (defs rest)) (defs rest) ) ) ) ) (define (non-defs seq) (if (null? seq) '() (let ((expr (car seq)) (rest (cdr seq))) (if (definition? expr) (non-defs rest) (cons expr (non-defs rest)) ) ) ) ) ; let ; ( ; var-1 val1 ; var-2 val2 ; .. ; ) ; ( ; (set-1 ..) ; (set-2 ..) ; .. others ; ) (cons 'let (cons (map (lambda (x) (list x '*unassigned*)) (map definition-variable (defs body))) (append (map (lambda (x) (cons 'set! (list (definition-variable x) (definition-value x)))) (defs body)) (non-defs body) ) ) ) ) ; test (display (scan-out-defines '( (define x 1) (define y 2) (+ x y) (display x) ) ) ) ;; c) ;; better in `make-procedure`, check `apply` in 4.01.01.ea.scm: ;; ``` ;; ((compound-procedure? procedure) ;; (eval-sequence ;; (procedure-body procedure) ;; (extend-environment ; do extend env ;; (procedure-parameters procedure) ; name param ;; arguments ; real arg ;; (procedure-environment procedure) ; parent env ;; ) ;; ) ;; ) ;; ``` ;; `procedure-body` is called each time `eval-sequence` (or its upper: `apply`) called on same ;; procedure, thus cause the transformation of `scan-out-defines` processed many times. ;; while in `make-procedure`, the transformation is processed only once, after that each apply on ;; this procedure is evaluated on the transformed expressions. (define (make-procedure parameters body env) (list 'procedure parameters (scan-out-defines body) env) )
false