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
186ac907713d8032926e4d6730a9f8b970cfcee5
f07bc117302b8959f25449863c6fdabdda510c48
/test-header.scm
a9da19e124d01201b31f4f180171c01e3e8e2c28
[ "MIT" ]
permissive
namin/clpsmt-miniKanren
3a1165a20dc1c50e4d568e2e493b701fb9f5caea
d2270aa14410805fa7068150bc2ab2f3bf9391b4
refs/heads/master
2022-03-10T07:05:21.950751
2022-02-26T23:54:05
2022-02-26T23:54:05
129,262,229
33
9
MIT
2021-08-03T16:02:50
2018-04-12T14:14:59
Scheme
UTF-8
Scheme
false
false
63
scm
test-header.scm
(load "mk.scm") (load "z3-driver.scm") (load "test-check.scm")
false
bfd4d388c9607cfc163e30436768011de3b748dc
ebf028b3a35ae1544bba1a1f9aa635135486ee6c
/sitelib/lunula/session.scm
7b9958348ab1b1fd8ad4cdf3376dfc5d1f4987f2
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
tabe/lunula
b4b666151874271211744cce1346e58e3a56fa79
b7699a850b9c9a64c1d3a52d50ce20050bd17475
refs/heads/master
2021-01-01T20:04:43.571993
2010-05-06T15:39:31
2010-05-06T15:39:31
334,916
2
0
null
null
null
null
UTF-8
Scheme
false
false
2,308
scm
session.scm
(library (lunula session) (export session session? make-session session-user session-uuid confirmation confirmation? ok? account account? make-account account-nick account-name account-password account-mail-address account-hash-algorithm account-hash-key user user? user-account make-user do-login do-logout logged-in?) (import (rnrs) (core) (concurrent) (lunula concurrent) (lunula persistent-record)) (define-record-type confirmation (fields (immutable ok ok?))) (define-persistent-record-type account (fields nick name password mail-address hash-algorithm hash-key) (protocol (persistent-protocol (lambda (p) (lambda (nick name password mail-address hash-algorithm hash-key) (p nick name password mail-address hash-algorithm hash-key)))))) (define-record-type user (fields account)) (define-record-type session (fields user uuid)) (define *logged-in* (make-messenger-bag 1024)) (define (generate-session a) (assert (account? a)) (let ((uuid (make-uuid)) (params (list (id-of a) (account-nick a) (account-name a) (account-password a) (account-mail-address a) (account-hash-algorithm a) (account-hash-key a) ))) (messenger-bag-put! *logged-in* uuid params 100) (make-session (make-user a) uuid))) (define (do-login a) (assert (account? a)) (generate-session a)) (define (do-logout sess) (assert (session? sess)) (messenger-bag-get-gracefully! *logged-in* (session-uuid sess) 100)) (define (logged-in? x) (and (string? x) (let ((params (messenger-bag-get-gracefully! *logged-in* x 100 #f))) (and (list? params) (let ((a (apply make-account (cdr params)))) (id-set! a (car params)) (generate-session a)))))) )
false
05220c53cd8efbc827283381fa9c7e8c90bd5399
ecfd9ed1908bdc4b099f034b121f6e1fff7d7e22
/old1/sicp/3/p65.scm
6dc0f04b777a120210eec97849bce930f3fa8f1d
[ "MIT" ]
permissive
sKabYY/palestra
36d36fc3a03e69b411cba0bc2336c43b3550841c
06587df3c4d51961d928bd8dd64810c9da56abf4
refs/heads/master
2021-12-14T04:45:20.661697
2021-11-25T08:29:30
2021-11-25T08:29:30
12,856,067
6
3
null
null
null
null
UTF-8
Scheme
false
false
594
scm
p65.scm
(load "stream.scm") (define (ln2-summands n) (cons (/ 1.0 n) (delay (stream-map-n - (ln2-summands (+ n 1)))))) (define ln2-stream (partial-sums (ln2-summands 1))) (define (display-10 s) (stream-for-n println s 10)) (println "#1:") (display-10 ln2-stream) (println "#2:") (display-10 (euler-transform ln2-stream)) (define (repeated f n) (lambda (x) (if (= n 0) x ((repeated f (- n 1)) (f x))))) (println "#repeated:") (display-10 ((repeated euler-transform 7) ln2-stream)) (println "super:") (display-10 (accelerated-sequence euler-transform ln2-stream))
false
d75ef7966d90f783c4651a5468b203137e704e02
26aaec3506b19559a353c3d316eb68f32f29458e
/modules/ln_core/unit-test.scm
66933d7bfbad889518b616266ca710bc74e6ff6b
[ "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
3,257
scm
unit-test.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. |# ;; very simple unit testing framework ;; this can be used to test cases in code ;; API ;; (unit-test <unit-name> <test-name> <test-proc>) ;; (unit-test <unit-name>) ;; (unit-test-all) (define unit-test:table (make-table init: #f)) (define unit-test:stdout #f) (define (unit-test-stdout bool) (set! unit-test:stdout bool)) (define (unit-test:log . x) (if unit-test:stdout (for-each display (append x (list "\n"))) (apply log-status x))) (define (unit-test n . x) ;; add a test to the test group (define (unit-test-add n tn tp) (let* ((t (table-ref unit-test:table n)) (tt (if (table? t) t (make-table init: #f)))) (table-set! tt tn tp) (table-set! unit-test:table n tt))) ;; run a test and catch all errors (define (unit-test-try p) (with-exception-catcher log:exception-handler (lambda () (p)))) ;; run all tests with-in a group (define (unit-test-run n) (let ((t (table-ref unit-test:table n)) (res #t)) (if (table? t) (table-for-each (lambda (tn tp) (let ((outcome (unit-test-try tp))) (if (and res (not outcome)) (set! res #f)) (unit-test:log n ": " tn ".. " (if outcome "OK" "FAIL")))) t) (begin (unit-test:log n ": no tests found.") (set! res #f) ) ) res )) (if (> (length x) 0) (apply unit-test-add (append (list n) x)) (unit-test-run n))) (define (unit-test-all) (let ((l (list)) (ret #t)) (table-for-each (lambda (k v) (if (not (unit-test k)) (begin (set! ret #f) (set! l (append l (list k))) )) ) unit-test:table) (if ret ret l) )) ;; eof
false
540517729ee7387d3b35d10ae9e89fff17cb5a86
895daaa3a466ec7f61773b892920dfbe8d78780e
/examples/labels.scm
e2c9de0d801b023531896867eaf7e65bc0ee582e
[]
no_license
jwalsh/scheme-workshop-2014
feac007278a4255ccdb6c82814ea18bbf646d8fa
32718dbdc3a83d0508f7b6110c59e7e960db7b62
refs/heads/master
2016-09-05T16:18:50.247061
2015-03-25T19:17:42
2015-03-25T19:17:42
26,870,183
0
0
null
null
null
null
UTF-8
Scheme
false
false
62
scm
labels.scm
(let ((x (list โ€™a โ€™b โ€™c))) (set-cdr! (cddr x) x) x)
false
e745e4b0eca44f0e81ea93501944c92571a05cb1
e5ac4ced6654e03a8d66ee15da3fc025e28f5b85
/srfi/17.scm
eecc080ee96ad73ec07f1dd5a7ecbcdf986bcbde
[ "MIT" ]
permissive
stibear/stibear-picrin-lib
dea5d59251e07ef1b77052f65519a25fef532b2a
a2c0e35f0b1e295a4f7757a77578eb7931b7eda4
refs/heads/master
2020-12-24T13:44:45.265642
2014-07-28T05:56:37
2014-07-28T05:56:37
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,461
scm
17.scm
(define-library (srfi 17) (import (scheme base) (srfi 1) (picrin dictionary)) (define-syntax update! (syntax-rules () ((_ (proc args ...) val) ((setter proc) args ... val)) ((_ var val) (set! var val)))) ;; now, dictionary will take only symbols as its keys (define setter-dict (let ((dict (dictionary))) (dictionary-set! dict car set-car!) (dictionary-set! dict cdr set-cdr!) (dictionary-set! dict caar (lambda (p v) (set-car! (car p) v))) (dictionary-set! dict cadr (lambda (p v) (set-car! (cdr p) v))) (dictionary-set! dict cdar (lambda (p v) (set-cdr! (car p) v))) (dictionary-set! dict cddr (lambda (p v) (set-cdr! (cdr p) v))) (dictionary-set! dict vector-ref vector-set!) (dictionary-set! dict string-ref string-set!) (dictionary-set! dict bytevector-u8-ref bytevector-u8-set!) (dictionary-set! dict list-ref list-set!) dict)) (define setter (letrec ((setter (lambda (proc) (dictionary-ref dict proc))) (set-setter! (lambda (proc setter) (dictionary-set! setter-dict proc setter)))) (set-setter! setter set-setter!) setter)) (define (getter-with-setter get set) (let ((proc (lambda args (apply get args)))) (update! (setter proc) set) proc)) (export update! setter getter-with-setter))
true
f75f4187c53c971a98f0a430b00752d06ce95a35
e358b0cf94ace3520adff8d078a37aef260bb130
/simple/2.36.scm
96e0009b5b8b89d7bca5256f813b3f7206c54be7
[]
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
383
scm
2.36.scm
(define (accumulate op initial sequence) (if (null? sequence) initial (op (car sequence) (accumulate op initial (cdr sequence))))) (define (accumulate-n op initial seqs) (if (null? (car seqs)) (list) (cons (accumulate op initial (map car seqs)) (accumulate-n op initial (map cdr seqs)))))
false
4ef88de5f075477ea5c147f174a9042b2c1ad62e
923209816d56305004079b706d042d2fe5636b5a
/sitelib/http/message-header.scm
ebe62ca34a62b375fd17beb1cfc0b3a93fcc3f9d
[ "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
443
scm
message-header.scm
(library (http message-header) (export field-name message-header) (import (rnrs (6)) (http abnf) (http basic-rule)) ;;; 4.2 Message Headers (define field-content OCTET) (define field-name token) (define field-value (rep* (bar LWS field-content))) ; LWS must precedes field-content since field-content includes LWS. (define message-header (seq field-name (char->rule #\:) (opt field-value))) )
false
5483d0ed7e28aa5ca94463ff881bd46caf3aeaad
4b570eebce894b4373cba292f09883932834e543
/ch1/1.12.scm
4affeabfba8e6d772f0892570e4d63d33dae4bf6
[]
no_license
Pulkit12083/sicp
ffabc406c66019e5305ad701fbc022509319e4b1
8ea6c57d2b0be947026dd01513ded25991e5c94f
refs/heads/master
2021-06-17T13:44:06.381879
2021-05-14T16:52:30
2021-05-14T16:52:30
197,695,022
0
0
null
2021-04-14T17:04:01
2019-07-19T03:25:41
Scheme
UTF-8
Scheme
false
false
377
scm
1.12.scm
#lang scheme ; Pascal's triangle ; Compute elements of pascal's triangle using recursive process ; 1 ; 1 1 ; 1 2 1 ; 1 3 3 1 ; 1 4 6 4 1 ;recursive (define (pascal row col) (cond ((or (< row 1) (< col 1) (< row col)) 0) ((= col 1) 1) ((= row col) 1) (else (+ (pascal (- row 1) (- col 1)) (pascal (- row 1) col))))) ;iterative would require a table.
false
30859d3f6a0f028aa302710ed57f0087f836af62
0bdfa3fdb0467776e4e06a41c683b01d2b8902fd
/src/test/pinholes.ss
b9de62c0b128f72d8a9c62666a9ca237219691c5
[]
no_license
VijayEluri/moby-scheme
e792d818dfec2c26fbc04451119eaab8556bb786
e2aa51b61a0d95499b71ef5d844e5eeecafb839d
refs/heads/master
2020-05-20T10:59:09.974728
2009-07-09T19:12:04
2009-07-09T19:12:04
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
877
ss
pinholes.ss
;; The first three lines of this file were inserted by DrScheme. They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-reader.ss" "lang")((modname pinholes) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ()))) (require (lib "world.ss" "moby" "stub")) (define x 50) (define y 50) (define (draw-world a-world) #;(place-image (circle x "solid" "green") 100 y (empty-scene 100 100)) (place-image (circle x "solid" "red") x y (place-image (circle x "solid" "green") 100 y (empty-scene 320 480)))) (big-bang 320 480 1 false (on-redraw draw-world))
false
ac91a9baeb5db69441d6b335261d7cc9c8745dba
0011048749c119b688ec878ec47dad7cd8dd00ec
/src/spoilers/321/solution.scm
e25bcab9731762fb0179f2eebd586f141b1d9dc2
[ "0BSD" ]
permissive
turquoise-hexagon/euler
e1fb355a44d9d5f9aef168afdf6d7cd72bd5bfa5
852ae494770d1c70cd2621d51d6f1b8bd249413c
refs/heads/master
2023-08-08T21:01:01.408876
2023-07-28T21:30:54
2023-07-28T21:30:54
240,263,031
8
0
null
null
null
null
UTF-8
Scheme
false
false
1,173
scm
solution.scm
(import (srfi 69)) (define (next/1 function n) (apply (lambda (a b) (list (+ (* 3 a) (* 2 b) 3) (+ (* 4 a) (* 3 b) 5))) (function (- n 1)))) (define (next/2 function n) (apply (lambda (a b) (list (+ (* 3 a) (* -2 b) 1) (+ (* -4 a) (* 3 b) -3))) (function (- n 1)))) (define (make-function init/indexes init/values next) (let ((cache (make-hash-table))) (for-each (lambda (index value) (hash-table-set! cache index value)) init/indexes init/values) (define (function n) (if (hash-table-exists? cache n) (hash-table-ref cache n) (let ((acc (next function n))) (hash-table-set! cache n acc) acc))))) (define (solve limit) (let ((function/1 (make-function '(0) '((0 0)) next/1)) (function/2 (make-function '(0) '((0 0)) next/2))) (do ((i 0 (+ i 1)) (acc 0 (let ((_ (quotient (+ i 1) 2))) (if (even? i) (+ acc (car (function/1 _))) (+ acc (car (function/2 _))))))) ((> i limit) acc)))) (let ((_ (solve 40))) (print _) (assert (= _ 2470433131948040)))
false
e686cc396c4e2a4e4d39a2fa61f57bb1a35d9bd8
51926823ecd9c82f9ffd758a45c6985eec7d60c6
/tests/goedel-number.scm
78c5794f51669103626b0dcac2f4fcd4a80dffca
[ "BSD-3-Clause" ]
permissive
tabe/goedel-number
2e739b53e5f11ce235b7a022c389914a43360520
36c06e576581a29bd103d57e02f91efa09a29c89
refs/heads/master
2020-05-30T05:38:53.592430
2010-01-02T12:38:17
2010-01-02T12:38:17
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
989
scm
goedel-number.scm
#!r6rs (import (rnrs (6)) (xunit) (goedel-number)) (define-syntax assert-encode-and-decode (syntax-rules () ((_ ls) (let ((t (length ls))) (call-with-values (lambda () (encode-numbers ls t)) (lambda (u v) (assert-equal? ls (decode-numbers u v t)))))))) (assert-encode-and-decode '(0 0 0)) (assert-encode-and-decode '(0 0 1)) (assert-encode-and-decode '(0 1 0)) (assert-encode-and-decode '(1 0 0)) (assert-encode-and-decode '(0 1 1)) (assert-encode-and-decode '(1 1 0)) (assert-encode-and-decode '(1 0 1)) (assert-encode-and-decode '(1 1 1)) (assert-encode-and-decode '(1 2 3)) (assert-encode-and-decode '(1 2 3 4)) (assert-encode-and-decode '(1 2 3 4 5)) (assert-encode-and-decode '(10 20 30 40 50)) (assert-encode-and-decode '(230 0 9 2354 121 9640222 1 77)) (let ((v (make-vector 1000 7))) (do ((i 0 (+ i 1))) ((= i 1000)) (vector-set! v i (* i i))) (assert-encode-and-decode (vector->list v))) (report)
true
b8ab07063d49536c010547fe27bbc016e7f630c7
c9eafeafeae9324eb4837ec78a54e89ae6168cc8
/commands/search.scm
153f96e8c97ab237d2304879f80b04a199d8f7ef
[]
no_license
mario-goulart/vault
b4330cc3c153e826b6c5f51404c6397b7d2a7391
1ff4aa01897165e783314c0cb7ab5cb3dec41a94
refs/heads/master
2023-07-08T17:24:13.688302
2023-06-24T20:54:28
2023-06-24T20:54:28
71,500,429
3
1
null
null
null
null
UTF-8
Scheme
false
false
1,174
scm
search.scm
(define-command 'search #<#EOF search [-I] [-e <except regex>] <regex> Search for <regex> in the vault database. -I makes search case-sensitive. -e can be provided multiple times and is not affected by -I. EOF (lambda (args) (when (null? args) (show-command-help 'search 1)) (let ((case-insensitive? #t) (excepts '()) (regex '())) (let loop ((args args)) (unless (null? args) (let ((arg (car args))) (cond ((string=? arg "-I") (set! case-insensitive? #f) (loop (cdr args))) ((string=? arg "-e") (when (null? (cdr args)) (die! "-e requires an argument.")) (set! excepts (cons (cadr args) excepts)) (loop (cddr args))) (else (set! regex (cons arg regex)) (loop (cdr args))))))) (when (or (null? regex) (not (null? (cdr regex)))) (die! "Exactly one regex must be provided.")) (for-each print-vault-obj (db-search (car regex) excepts case-insensitive?)))))
false
e80565fae8c1bc68c71122d97691a0040b00c448
1de3d2f5aea84e4d19825c290980a3b4f7815f32
/refactory/sake-tasks.scm
30cd9e0e18d5c81e85313632d11594def855bba5
[]
no_license
certainty/lisp-misc
37798607ca0275552c39683bad3080a42ba931fe
d5ee799f3ab0f2cc74bf3b2a83604dace160a649
refs/heads/master
2017-12-30T03:02:25.789701
2016-11-12T09:27:43
2016-11-12T09:27:43
69,743,925
0
0
null
null
null
null
UTF-8
Scheme
false
false
5,418
scm
sake-tasks.scm
(module sake-tasks ((define-task add-task! make-task) run-task current-sheduled-task task-lambda no-deps depends-on) (import chicken scheme) (use srfi-69 matchable (only posix current-directory glob) (only srfi-1 append-map reverse! delete-duplicates fold) (only srfi-13 string-append substring string-length) (only extras fprintf pp read-line) (only data-structures flatten topological-sort constantly)) (import-for-syntax matchable) (define current-sheduled-task (make-parameter #f)) (define *tasks* (make-hash-table)) (define-record task name action deps documentation) (define-record-printer (task t out) (fprintf out "#task<~a - ~a>" (task-name t) (excerpt (or (task-documentation t) ":nodoc")))) (define (excerpt str #!optional (len 30)) (if (> (string-length str) len) (string-append (substring str 0 len) "...") str)) (define (task-dependencies task) (let ((deps (task-deps task))) (deps))) (define (add-task! name task) ;; TODO if override of tasks is disallowed ;; raise an error (hash-table-set! *tasks* name task)) (define (run-task task . args) (cond ((symbol? task) (let ((task (hash-table-ref/default *tasks* task #f))) (if task (apply run-task task args) (signal (make-composite-condition (make-property-condition 'exn 'message "Could not find given task" 'arguments (list task)) (make-property-condition 'sake) (make-property-condition 'task-not-found task)))))) ((task? task) (run-tasks (resolve-dependencies task) args)) (else (error "Invalid argument given. Exepected symbol or task" task)))) (define (run-tasks tasks args) ;; dependencies have been resolved at this point and ;; are guaranteed to be in the correct order, containing no cycles ;; TODO: think about passing the result of one task to the other ;; What would be the seed? (let ((run (lambda (task) ((task-action task))))) (for-each run tasks))) (define (resolve-dependencies task) (reverse! (topological-sort (dependency-graph task) eq?))) (define (task-direct-dependencies task) (delete-duplicates (task-dependencies task))) (define (dependency-graph task) (dependency-graph-helper task (list) (make-hash-table eq?))) (define (dependency-graph-helper task graph visited) (when (hash-table-ref/default visited (task-name task) #f) (signal (make-composite-condition (make-property-condition 'exn 'message "Detected cyclic dependencies" 'arguments (list task graph)) (make-property-condition 'sake) (make-property-condition 'cycle task graph)))) (let* ((deps (task-direct-dependencies task)) (node (cons task deps))) (cond ((null? deps) (cons node graph)) (else (hash-table-set! visited (task-name task) #t) (cons node (fold (lambda (task graph) (dependency-graph-helper task graph visited)) graph deps)))))) ;; the following macros are just convenience. You don't need these ;; you can just as well work with make-task ;; example: ;; (define t (make-task 'test (lambda () (print "test task")) (no-deps) "test task")) ;; (define t2 (make-task 'test (lambda () (print "test2 task")) (depends-on t) "test2 task") ;; use these procedures if you have difficulties with the macros, for example ;; when you want to compose tasks ;; (define-task name dep-proc doc-string proc) ;; (define-task name dep-proc proc) (define-syntax define-task (syntax-rules () ((_ ?name ?dep-proc ?doc ?proc) (begin (define ?name (make-task '?name ?proc ?dep-proc ?doc)) (add-task! '?name ?name))) ((_ ?name ?dep-proc ?proc) (define-task ?name ?dep-proc #f ?proc)) ((_ ...) (syntax-error "Invalid syntax for define-task")))) ;; this can be used to create anonymous tasks ;; in dependency procedures ;; (task-lambda (dep ...) (arg ...) code ...) (define-syntax task-lambda (ir-macro-transformer (lambda (exp inj cmp) (match exp ((_ ?dep-proc ?lambda-list ?code ?more-code ...) `(make-task ,(quote (gensym "task")) (lambda ,?lambda-list ,?code ,@?more-code) ,?dep-proc "task-lambda")) (else (syntax-error "Invalid syntax for task-lambda")))))) (define (no-deps) (lambda () (list))) (define (depends-on . tasks) (lambda () tasks)) ) ;; example usage ;; (import sake-tasks) ;; example (define-task foo (no-deps) "This is my description" (lambda () (print "foo called"))) (define-task bar (depends-on foo) (lambda () (print "bar called"))) (define (baz-deps) (list bar foo)) (define-task baz baz-deps "depends on foo and bar" (lambda () (print "baz called"))) (define (dynamic-tasks) (list (task-lambda (no-deps) () (print "I'm a dynamically generated task")))) (define-task bar-baz dynamic-tasks "it generates dependent tasks on the fly" (lambda () (print "foo"))) (run-task baz) (print "================") (run-task bar) (print "================") (run-task bar-baz)
true
53d8ee6aadc02cf9b049630c813b15e14051c5cf
8d2197af6ab9abe4e7767b424499aeae2331e3f6
/examples/outputs/io/erased-IR.scm
b8b9cc87719f1dabbb61259df68684ff97021666
[]
permissive
ziman/ttstar
ade772d6dd2b31b40b736bd36bd9ef585bd0d389
4ac6e124bddfbeaa133713d829dccaa596626be6
refs/heads/master
2021-09-08T23:20:19.446353
2019-06-30T19:17:02
2019-06-30T19:17:02
35,721,993
19
1
BSD-3-Clause
2022-08-09T13:28:36
2015-05-16T11:58:56
Idris
UTF-8
Scheme
false
false
3,265
scm
erased-IR.scm
(import (chicken process-context)) (define-syntax curried-lambda (syntax-rules () ((curried-lambda () body) body) ((curried-lambda (x . xs) body) (lambda (x) (curried-lambda xs body))))) (define-syntax rts-unpack (syntax-rules () ((rts-unpack xs () rhs) rhs) ((rts-unpack xs (v . vs) rhs) (let ((v (car xs)) (rest (cdr xs))) (rts-unpack rest vs rhs))))) (define-syntax rts-case-int (syntax-rules (_) ((rts-case-int tag args) (error "pattern match failure" (list tag args))) ((rts-case-int tag args (_ rhs) . rest) rhs) ((rts-case-int tag args ((_ . pvs) rhs) . rest) (rts-unpack args pvs rhs)) ((rts-case-int tag args ((cn . pvs) rhs) . rest) (if (eq? tag 'cn) (rts-unpack args pvs rhs) (rts-case-int tag args . rest))))) (define-syntax rts-case (syntax-rules () ((rts-case s . alts) (rts-case-int (car s) (cdr s) . alts)))) (define Type '(Type)) (define (number->peano z s i) (if (= i 0) (list z) (list s (number->peano z s (- i 1))))) (define (rts-arg-peano z s i) (number->peano z s (string->number (list-ref (command-line-arguments) i)))) (define (rts-arg-read i) (read (open-input-string (list-ref (command-line-arguments) i)))) (display (letrec* ( (Z `(Z)) (S (lambda (e0) `(S ,e0))) (MkPair (curried-lambda (e0 e1) `(MkPair ,e0 ,e1))) (snd (lambda (_pv0) (rts-unpack (cdr _pv0) (_pv1 _pv2) _pv2))) (MkSt (lambda (e0) `(MkSt ,e0))) (runState (lambda (_pv0) (rts-unpack (cdr _pv0) (_pv1) _pv1))) (execState (lambda (x) (lambda (s) (snd ((runState x) s))))) (stGet (MkSt (lambda (s) ((MkPair s) s)))) (stReturn (lambda (x) (MkSt (lambda (s) ((MkPair s) x))))) (stBind (curried-lambda (_pv0 _pv1) (rts-unpack (cdr _pv0) (_pv2) (letrec* ( (stBind3 (curried-lambda (_pv3 _pv4) (rts-unpack (cdr _pv4) (_pv5) (_pv5 _pv3)))) (stBind2 (curried-lambda (_pv3 _pv4) (rts-unpack (cdr _pv4) (_pv5 _pv6) ((stBind3 _pv5) (_pv3 _pv6))))) ) (MkSt (lambda (s) ((stBind2 _pv1) (_pv2 s)))))))) (ioReturn (lambda (x) (stReturn x))) (ioBind (lambda (x) (lambda (y) ((stBind x) y)))) (ioWrapImpure (lambda (impureF) ((stBind stGet) (lambda (w) (stReturn (impureF w)))))) (unsafePerformIO (lambda (x) (letrec ((TheWorld `(TheWorld))) ((execState x) TheWorld)))) (intS (lambda (x) (+ x 1))) (intZ 0) (printSchemeRepr (lambda (x) (letrec ((nativePrint print)) (ioWrapImpure (lambda (w) (nativePrint x)))))) (natToInt (lambda (_pv0) (rts-case _pv0 ((S _pv1) (intS (natToInt _pv1))) ((Z) intZ)))) (intToNat (lambda (x) (number->peano 'Z 'S x))) (printNat (lambda (x) (printSchemeRepr (natToInt x)))) (main (unsafePerformIO ((ioBind (ioReturn (S (S (S (S Z)))))) (lambda (v) ((ioBind (printNat v)) (lambda (_do0) (printSchemeRepr (intToNat (intS (intS (intS intZ))))))))))) ) main)) (newline)
true
c5f7d705b3083714ed84fad9f91080b71496d129
c9548b7e89f384fb53fc0d0a3c008d17416dd6c6
/test/arguments.scm
ea1a914edad74ed750441e65c1f3fef1c64fee69
[ "Zlib" ]
permissive
euccastro/sphere-energy
8c4a02632ea848569f9acfb2ecb6eda1e2db492b
e532a7274be2dbf54a62620b658564710354d469
refs/heads/master
2021-01-15T09:18:44.389023
2014-10-25T14:28:37
2014-10-25T14:28:37
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
59
scm
arguments.scm
(##spheres-load core: testing) (##spheres-load arguments)
false
73f4a1b0ccb80748678120e0f6a1c0c4fc008e83
4f30ba37cfe5ec9f5defe52a29e879cf92f183ee
/src/sasm/tx/stmt.scm
50543f7214eb79206d1656fb639f54c4f95aca99
[ "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
2,285
scm
stmt.scm
(define (sasm-assemble-statement stmt) (case (car stmt) ((function) (emit-whitespace) (assemble-instructions (append `((label ,(cadr (assoc 'name (cdr stmt)))) (perform (op function-preamble))) (cdr (assoc 'body (cdr stmt)))))) ((entry) (assemble-instructions `((export sasm-entry) (label sasm-entry) (goto (label ,(cadr stmt)))))) ((export extern) (assemble-instructions (list stmt))) ((label data) (assemble-instruction stmt)) ((global) (cond ((null? (cddr stmt)) (assemble-instructions `((label ,(cadr stmt)) (data (const 0))))) ((and (eqv? 'const (caaddr stmt)) (string? (cadar (cddr stmt))) (null? (cdddr stmt))) (let ((label (cadr stmt)) (str (cadar (cddr stmt)))) (assemble-instructions `((data (const ,(string-length str))) (data (const #x8000000)) (label ,(cadr stmt)) ,@(map (lambda (c) `(data (const ,(char->integer c)))) (string->list str)))))) ((all? (lambda (x) (and (pair? x) (pair? (cdr x)) (null? (cddr x)) (or (and (eqv? 'const (car x)) (integer? (cadr x))) (and (eqv? 'label (car x)) (symbol? (cadr x)))))) (cddr stmt)) (assemble-instructions `((label ,(cadr stmt)) ,@(map (lambda (x) `(data ,x)) (cddr stmt))))) (else ;; backend-specific global form? (assemble-instructions (list stmt))))) ((define-symconst) (sasm-symconst-alist-append (cdr stmt))) ((class) (emit-whitespace) (assemble-instructions (sasm-assemble-class stmt))) ((class-info) 'nothing) (else (error "Unable to assemble SASM statement " stmt))))
false
b3eceacd402d6b59c5dee2f3fed0eaed8b45339c
d35144c1ad0d53e13a43722a2357fd0aeefe98da
/gl-utils-mesh.scm
0c3a409a37eb07987d51b08944e81ada5b2ad8c5
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
AlexCharlton/gl-utils
e86e98796ce46c5f5b98e081e720671a52f38d21
5d31808418c5a9031d62aa12867e136f4254c357
refs/heads/master
2021-01-18T21:34:02.303086
2016-05-04T12:39:10
2016-05-04T12:39:10
23,294,015
2
1
null
2016-01-31T15:29:24
2014-08-24T21:56:25
Scheme
UTF-8
Scheme
false
false
27,336
scm
gl-utils-mesh.scm
(module gl-utils-mesh (make-mesh mesh? mesh-vertex-attributes mesh-index-type mesh-vertex-data mesh-index-data mesh-n-vertices mesh-n-indices mesh-vertex-buffer mesh-index-buffer mesh-stride mesh-mode mesh-vao mesh-usage mesh-vertex-ref mesh-vertex-set! vertex-attribute-name vertex-attribute-type vertex-attribute-number vertex-attribute-normalized vertex-attribute-offset mesh-make-vao! mesh-update! with-mesh mesh-copy! mesh-copy mesh-append mesh-transform! mesh-transform-append usage->gl mode->gl) (import chicken scheme foreign) (use (prefix gl-utils-core gl:) (prefix opengl-glew gl:) gl-utils-bytevector srfi-1 srfi-4 srfi-99 miscmacros matchable extras lolevel gl-math data-structures) ;;;; Mesh record (define-record-type mesh (make-mesh%) #t (vertex-attributes) (index-type) (vertex-data) (index-data) (n-vertices) (n-indices) (vertex-buffer) (index-buffer) (vao) (stride) (mode) (usage) (dirty)) (define-record-type vertex-attribute #t #t name type number normalized (offset)) (define-record-printer (vertex-attribute s out) (fprintf out "#(vertex-attribute name: ~S type: ~S number: ~S normalized: ~S offset: ~S)" (vertex-attribute-name s) (vertex-attribute-type s) (vertex-attribute-number s) (vertex-attribute-normalized s) (vertex-attribute-offset s))) (define (delete-mesh m) (if* (mesh-vertex-buffer m) (gl:delete-buffer it)) (if* (mesh-index-buffer m) (gl:delete-buffer it)) (if* (mesh-vao m) (gl:delete-vertex-array it))) ;;;; Mesh initialization (define (make-mesh #!key vertices indices (mode triangles:)) (unless vertices (error 'make-mesh "Must be called with vertices: keyword")) (let ((mesh (make-mesh%))) (make-mesh-vertices mesh vertices) (if indices (make-mesh-indices mesh indices) (begin (mesh-index-data-set! mesh #f) (mesh-index-type-set! mesh #f) (mesh-n-indices-set! mesh (mesh-n-vertices mesh)))) (mesh-vertex-buffer-set! mesh #f) (mesh-index-buffer-set! mesh #f) (mesh-vao-set! mesh #f) (mesh-dirty-set! mesh #f) (mesh-usage-set! mesh #f) (mesh-mode-set! mesh mode) mesh)) ;;; Vertex initialization (define (get-vertex-attribute name attributes) (if* (find (lambda (attribute) (equal? name (vertex-attribute-name attribute))) attributes) it (error 'make-mesh "No attribute of this name in mesh's vertex-attributes" name attributes))) (define (vertex-length attributes init) (let* ((lengths (map (lambda (i) (quotient (length (cdr i)) (vertex-attribute-number (get-vertex-attribute (car i) attributes)))) init)) (length (car lengths))) (for-each (lambda (l) (unless (= l length) (error 'make-mesh "Vertex elements do not all have the same number of vertices"))) (cdr lengths)) length)) (define (get-attributes vertices) (map (match-lambda (((? symbol? name) (? (cut member <> valid-type) type) (? (lambda (x) (and (integer? x) (< 0 x 5))) n) . keywords) (make-vertex-attribute name type n (get-keyword normalized: keywords) 0)) (attr (error 'make-mesh "Expected attribute attributes in the form (NAME TYPE NUMBER [NORMALIZED])" attr))) (get-keyword attributes: vertices (lambda () (error 'make-mesh "vertices: keyword must contain a attributes: keyword" vertices))))) (define (get-stride attributes) (let ((offset 0)) (fold (lambda (a n) (let ((size (* (gl:type->bytes (vertex-attribute-type a)) (vertex-attribute-number a)))) (cond-expand (gles (set! size (align-to-word size))) (else)) (vertex-attribute-offset-set! a offset) (inc! offset size) (+ size n))) 0 attributes))) (define (unsigned? type) (member type '(uchar: uint8: unsigned-byte: ushort: uint16: unsigned-short: uint: uint32: unsigned-int: unsigned-int32: unsigned-integer: unsigned-integer32:))) (define (set-vertices mesh vertices) (let ((attributes (mesh-vertex-attributes mesh)) (stride (mesh-stride mesh)) (vertex-vector (mesh-vertex-data mesh))) (let loop ((inits vertices)) (unless (null? inits) (let* ((init (car inits)) (attribute (get-vertex-attribute (car init) attributes)) (set (type->setter (vertex-attribute-type attribute))) (offset (vertex-attribute-offset attribute)) (size (gl:type->bytes (vertex-attribute-type attribute))) (number (vertex-attribute-number attribute)) (type (vertex-attribute-type attribute)) (de-normalize (if (and (vertex-attribute-normalized attribute) (not (member type '(float: float32: double: float64:)))) (if (unsigned? type) (lambda (x) (inexact->exact (fpfloor (* (fpmax -1.0 (min 1.0 (exact->inexact x))) (sub1 (expt 2 (* size 8))))))) (lambda (x) (fx- (inexact->exact (fpfloor (* (fp+ (fp* (fpmax -1.0 (min 1.0 (exact->inexact x))) 0.5) 0.5) (sub1 (expt 2 (* size 8)))))) (fxshl 2 (fx- (fx* size 8) 1))))) (lambda (x) x)))) (do ((i 0 (add1 i)) (init (cdr init) (cdr init))) ((null? init)) (set vertex-vector (+ (* (quotient i number) stride) (* (remainder i number) size) offset) (de-normalize (car init))))) (loop (cdr inits)))))) (define (make-mesh-vertices mesh vertices) (let* ((vertex-init (get-keyword initial-elements: vertices)) (attributes (get-attributes vertices)) (stride (get-stride attributes))) (mesh-vertex-attributes-set! mesh attributes) (mesh-stride-set! mesh stride) (if (bytevector? vertex-init) (begin (mesh-vertex-data-set! mesh vertex-init) (mesh-n-vertices-set! mesh (quotient (bytevector-length (mesh-vertex-data mesh)) stride))) (begin (mesh-n-vertices-set! mesh (if vertex-init (vertex-length attributes vertex-init) (get-keyword n-vertices: vertices (lambda () (error 'make-mesh "n-vertices: keyword required when no intial-elements: is provided" vertices))))) (mesh-vertex-data-set! mesh (make-bytevector (* (mesh-n-vertices mesh) stride))) (when vertex-init (set-vertices mesh vertex-init)))))) ;;; Index initialization (define (set-indices mesh indices) (let* ((index-type (mesh-index-type mesh)) (stride (gl:type->bytes index-type)) (index-vector (mesh-index-data mesh)) (set (type->setter index-type))) (do ((i 0 (add1 i)) (init indices (cdr init))) ((null? init)) (set index-vector (* i stride) (car init))))) (define (make-mesh-indices mesh indices) (let* ((index-init (get-keyword initial-elements: indices)) (index-type (get-keyword type: indices (lambda () (error 'make-mesh "indices: keyword must contain a type: keyword" indices)))) (stride (gl:type->bytes index-type))) (unless (unsigned? index-type) (error 'make-mesh "Mesh index-type must be a valid, unsigned type)" index-type)) (mesh-index-type-set! mesh index-type) (if (bytevector? index-init) (begin (mesh-index-data-set! mesh index-init) (mesh-n-indices-set! mesh (quotient (bytevector-length (mesh-index-data mesh)) stride))) (begin (mesh-n-indices-set! mesh (if index-init (length index-init) (get-keyword n-indices: indices (lambda () (error 'make-mesh "n-indices: keyword required when no intial-elements: is provided" indices))))) (mesh-index-data-set! mesh (make-bytevector (* (mesh-n-indices mesh) stride))) (when index-init (set-indices mesh index-init)))))) ;;;; Mesh accessors (define (with-mesh mesh thunk) (gl:bind-buffer gl:+array-buffer+ (mesh-vertex-buffer mesh)) (thunk) (if* (mesh-dirty mesh) (let ((usage (mesh-usage mesh))) (ecase usage ((dynamic: dynamic-draw: dynamic-read: dynamic-copy:) (let ((lower (car it)) (upper (cdr it))) (gl:buffer-sub-data gl:+array-buffer+ (car it) (- upper lower) (pointer+ (bytevector->pointer (mesh-vertex-data mesh)) lower)))) ((stream: stream-draw: stream-copy: stream-read:) (gl:buffer-data gl:+array-buffer+ (* (mesh-stride mesh) (mesh-n-vertices mesh)) (bytevector->pointer (mesh-vertex-data mesh)) (usage->gl usage)))) (mesh-dirty-set! mesh #f))) (gl:bind-buffer gl:+array-buffer+ 0)) ;; Note: value is unsafe: entering a vector that is too short will have unspecified, bad consequences. (define (mesh-vertex-set! mesh attribute vertex value) (when (or (negative? vertex) (>= vertex (mesh-n-vertices mesh))) (error 'mesh-vertex-ref "Vertex not in range" vertex)) (let* ((attribute (get-vertex-attribute attribute (mesh-vertex-attributes mesh))) (type (vertex-attribute-type attribute)) (number (vertex-attribute-number attribute)) (length (* (gl:type->bytes type) number)) (offset (vertex-attribute-offset attribute)) (stride (mesh-stride mesh)) (position (+ offset (* stride vertex)))) ((foreign-lambda* void ((u8vector to) (c-pointer from) (size_t start) (size_t length)) "memcpy((&((char *)to)[start]), from, length);") (mesh-vertex-data mesh) (gl:->pointer value) position length) (when (mesh-vertex-buffer mesh) (if (member (mesh-usage mesh) '(stream: stream-read: stream-copy:)) (mesh-dirty-set! mesh #t) (let* ((dirty (mesh-dirty mesh)) (lower (if dirty (min (car dirty) position) position)) (upper (if dirty (max (cdr dirty) (+ position length)) (+ position length)))) (mesh-dirty-set! mesh (cons lower upper))))))) (define (mesh-vertex-ref mesh attribute vertex) (when (or (negative? vertex) (>= vertex (mesh-n-vertices mesh))) (error 'mesh-vertex-ref "Vertex not in range" vertex)) (let* ((attribute (get-vertex-attribute attribute (mesh-vertex-attributes mesh))) (type (vertex-attribute-type attribute)) (number (vertex-attribute-number attribute)) (length (* (gl:type->bytes type) number)) (offset (vertex-attribute-offset attribute)) (stride (mesh-stride mesh)) (vec ((type->make-vector type) number))) ((foreign-lambda* void ((c-pointer to) (u8vector from) (size_t start) (size_t length)) "memcpy(to, (&((char *)from)[start]), length);") (gl:->pointer vec) (mesh-vertex-data mesh) (+ (* stride vertex) offset) length) vec)) (define (mesh-update! mesh vertices #!optional indices) (let ((usage (and (mesh-usage mesh) (usage->gl (mesh-usage mesh)))) (stride (mesh-stride mesh)) (index-stride (gl:type->bytes (mesh-index-type mesh))) (vertex-data (mesh-vertex-data mesh)) (index-data (mesh-index-data mesh)) (n-vertices (vertex-length (mesh-vertex-attributes mesh) vertices)) (n-indices (and indices (length indices))) (vertex-buffer (mesh-vertex-buffer mesh)) (index-buffer (mesh-index-buffer mesh))) (unless vertex-data (error 'mesh-update! "Trying to update a mesh with no data. Usage should be dynamic or stream")) (when (> n-vertices (/ (bytevector-length vertex-data) stride)) (error 'mesh-update! "Cannot update mesh with more vertices than will fit in its array:" vertices)) (when (and indices (> n-indices (/ (bytevector-length index-data) index-stride))) (error 'mesh-update! "Cannot update mesh with more indices than will fit in its array:" indices)) (mesh-n-vertices-set! mesh n-vertices) (set-vertices mesh vertices) (when indices (mesh-n-indices-set! mesh n-indices) (set-indices mesh indices)) (when vertex-buffer (gl:bind-buffer gl:+array-buffer+ vertex-buffer) (gl:buffer-data gl:+array-buffer+ (* stride n-vertices) (bytevector->pointer vertex-data) usage) (gl:bind-buffer gl:+array-buffer+ 0)) (when (and indices index-buffer) (gl:bind-buffer gl:+element-array-buffer+ index-buffer) (gl:buffer-data gl:+element-array-buffer+ (* index-stride n-indices) (bytevector->pointer index-data) usage) (gl:bind-buffer gl:+element-array-buffer+ 0))) mesh) ;;;; Mesh operations (define (mesh-make-vao! mesh locations #!optional (usage #:static)) (when (mesh-vao mesh) (error 'mesh-make-vao! "Mesh already has vao" mesh)) (let* ((vao (gl:gen-vertex-array)) (stride (mesh-stride mesh)) (vertex-buffer (gl:gen-buffer)) (index-data (mesh-index-data mesh)) (index-buffer (if index-data (gl:gen-buffer))) (gl-usage (usage->gl usage))) (gl:bind-buffer gl:+array-buffer+ vertex-buffer) (gl:buffer-data gl:+array-buffer+ (* stride (mesh-n-vertices mesh)) (bytevector->pointer (mesh-vertex-data mesh)) gl-usage) (when index-data (gl:bind-buffer gl:+element-array-buffer+ index-buffer) (gl:buffer-data gl:+element-array-buffer+ (* (gl:type->bytes (mesh-index-type mesh)) (mesh-n-indices mesh)) (bytevector->pointer index-data) gl-usage)) ;; start vertex-array (gl:bind-vertex-array vao) (for-each (lambda (attribute) (let ((location (alist-ref (vertex-attribute-name attribute) locations))) (when location (gl:vertex-attrib-pointer location (vertex-attribute-number attribute) (gl:type->gl (vertex-attribute-type attribute)) (vertex-attribute-normalized attribute) stride (address->pointer (vertex-attribute-offset attribute))) (gl:enable-vertex-attrib-array location)))) (mesh-vertex-attributes mesh)) (when index-data (gl:bind-buffer gl:+element-array-buffer+ index-buffer)) (gl:bind-vertex-array 0) ;; end vertex-array (mesh-usage-set! mesh usage) (mesh-vertex-buffer-set! mesh vertex-buffer) (when index-data (mesh-index-buffer-set! mesh index-buffer)) (mesh-vao-set! mesh vao) (set-finalizer! mesh delete-mesh))) (define (mesh-copy! to at from #!optional (start 0) (end (mesh-n-vertices mesh))) (let ((stride (mesh-stride from))) (bytevector-copy! (mesh-vertex-data to) (* at (mesh-stride to)) (mesh-vertex-data from) (* start stride) (* end stride)))) (define (mesh-copy mesh) (make-mesh vertices: `(attributes: ,(map (lambda (a) (list (vertex-attribute-name a) (vertex-attribute-type a) (vertex-attribute-number a) normalized: (vertex-attribute-normalized a))) (mesh-vertex-attributes mesh)) initial-elements: ,(bytevector-copy (mesh-vertex-data mesh))) indices: `(type: ,(mesh-index-type mesh) initial-elements: ,(bytevector-copy (mesh-index-data mesh))))) (define (mesh-append meshes) (let* ((mesh (car meshes)) (new (make-mesh vertices: `(attributes: ,(map (lambda (a) (list (vertex-attribute-name a) (vertex-attribute-type a) (vertex-attribute-number a) normalized: (vertex-attribute-normalized a))) (mesh-vertex-attributes mesh)) initial-elements: ,(bytevector-append (map mesh-vertex-data meshes))) indices: `(type: ,(mesh-index-type mesh) initial-elements: ,(bytevector-append (map mesh-index-data meshes))))) (index-data (mesh-index-data new)) (index-type (mesh-index-type new)) (index-size (gl:type->bytes index-type)) (set (type->setter index-type)) (get (type->getter index-type))) (let loop ((meshes meshes) (index-index 0) (vertex-offset 0)) (if (null? meshes) new (let* ((mesh (car meshes)) (n-vertices (mesh-n-vertices mesh)) (n-indices (mesh-n-indices mesh))) (do ((i 0 (add1 i))) ((= i n-indices)) (let ((k (* (+ index-index i) index-size))) (set index-data k (+ (get index-data k) vertex-offset)))) (loop (cdr meshes) (+ index-index n-indices) (+ vertex-offset n-vertices))))))) (define (mesh-transform! mesh transform #!key (start 0) (end (mesh-n-vertices mesh)) (position-name 'position) (normal-name 'normal) normal-transform) (when (or (negative? start) (> end (mesh-n-vertices mesh)) (<= (- end start) 0)) (error 'mesh-vertex-ref "Bad vertex range" start end)) (let* ((stride (mesh-stride mesh)) (attributes (mesh-vertex-attributes mesh)) (position-offset (vertex-attribute-offset (get-vertex-attribute position-name attributes))) (normal-offset (if* (find (lambda (attribute) (equal? normal-name (vertex-attribute-name attribute))) attributes) (vertex-attribute-offset it) #f)) (inverse-transpose (when normal-offset (transpose (inverse (or normal-transform transform)))))) (m*vector-array! transform (pointer+ (bytevector->pointer (mesh-vertex-data mesh)) (+ position-offset (* start stride))) stride: stride length: (- end start)) (when normal-offset (m*vector-array! inverse-transpose (pointer+ (bytevector->pointer (mesh-vertex-data mesh)) (+ normal-offset (* start stride))) stride: stride length: (- end start))))) (define (mesh-transform-append pairs #!key (position-name 'position) (normal-name 'normal)) (let* ((meshes (map first pairs)) (transforms (map second pairs)) (normal-transforms (if (> (length (car pairs)) 2) (map third pairs) #f)) (mesh (mesh-append meshes)) (attributes (mesh-vertex-attributes mesh)) (position-offset (vertex-attribute-offset (get-vertex-attribute position-name attributes))) (normal-offset (if* (find (lambda (attribute) (equal? normal-name (vertex-attribute-name attribute))) attributes) (vertex-attribute-offset it) #f)) (stride (mesh-stride mesh)) (vertex-data (bytevector->pointer (mesh-vertex-data mesh)))) (let loop ((meshes meshes) (transforms transforms) (normal-transforms normal-transforms) (vertex-offset 0)) (if (null? meshes) mesh (let ((n-vertices (mesh-n-vertices (car meshes))) (offset (* vertex-offset stride))) (m*vector-array! (car transforms) (pointer+ vertex-data (+ position-offset offset)) stride: stride length: n-vertices) (when normal-offset (m*vector-array! (transpose (inverse (car (or normal-transforms transforms)))) (pointer+ vertex-data (+ normal-offset offset)) stride: stride length: n-vertices)) (loop (cdr meshes) (cdr transforms) (and normal-transforms (cdr normal-transforms)) (+ vertex-offset n-vertices))))))) ;;;; Type keywords (define valid-type '(char: int8: byte: uchar: uint8: unsigned-byte: short: int16: ushort: uint16: unsigned-short: int: int32: uint: uint32: unsigned-int: unsigned-int32: integer: integer32: unsigned-integer: unsigned-integer32: float: float32: double: float64:)) (define (type->make-vector type) (ecase type ((char: int8: byte:) make-s8vector) ((uchar: uint8: unsigned-byte:) make-u8vector) ((short: int16:) make-s16vector) ((ushort: uint16: unsigned-short:) make-u16vector) ((int: int32: integer: integer32:) make-s32vector) ((uint: uint32: unsigned-int: unsigned-int32: unsigned-integer: unsigned-integer32:) make-u32vector) ((float: float32:) make-f32vector) ((double: float64:) make-f64vector))) (define (type->setter type) (ecase type ((char: int8: byte:) bytevector-s8-set!) ((uchar: uint8: unsigned-byte:) bytevector-u8-set!) ((short: int16:) bytevector-s16-set!) ((ushort: uint16: unsigned-short:) bytevector-u16-set!) ((int: int32: integer: integer32:) bytevector-s32-set!) ((uint: uint32: unsigned-int: unsigned-int32: unsigned-integer: unsigned-integer32:) bytevector-u32-set!) ((float: float32:) bytevector-f32-set!) ((double: float64:) bytevector-f64-set!))) (define (type->getter type) (ecase type ((char: int8: byte:) bytevector-s8-ref) ((uchar: uint8: unsigned-byte:) bytevector-u8-ref) ((short: int16:) bytevector-s16-ref) ((ushort: uint16: unsigned-short:) bytevector-u16-ref) ((int: int32: integer: integer32:) bytevector-s32-ref) ((uint: uint32: unsigned-int: unsigned-int32: unsigned-integer: unsigned-integer32:) bytevector-u32-ref) ((float: float32:) bytevector-f32-ref) ((double: float64:) bytevector-f64-ref))) (define (usage->gl usage) (ecase usage ((dynamic: dynamic-draw:) gl:+dynamic-draw+) ((stream: stream-draw:) gl:+stream-draw+) ((static: static-draw:) gl:+static-draw+) ((dynamic-read:) gl:+dynamic-read+) ((stream-read:) gl:+stream-read+) ((static-read:) gl:+static-read+) ((dynamic-copy:) gl:+dynamic-copy+) ((stream-copy:) gl:+stream-copy+) ((static-copy:) gl:+static-copy+))) (cond-expand (gles (define (mode->gl mode) (ecase mode ((points:) gl:+points+) ((lines:) gl:+lines+) ((line-strip:) gl:+line-strip+) ((line-loop:) gl:+line-loop+) ((triangle-strip:) gl:+triangle-strip+) ((triangle-fan:) gl:+triangle-fan+) ((triangles:) gl:+triangles+)))) (else (define (mode->gl mode) (ecase mode ((points:) gl:+points+) ((lines:) gl:+lines+) ((line-strip:) gl:+line-strip+) ((line-loop:) gl:+line-loop+) ((line-strip-adjacency:) gl:+line-strip-adjacency+) ((lines-adjacency:) gl:+lines-adjacency+) ((triangle-strip:) gl:+triangle-strip+) ((triangle-fan:) gl:+triangle-fan+) ((triangles:) gl:+triangles+) ((triangle-strip-adjacency:) gl:+triangle-strip-adjacency+) ((triangles-adjacency:) gl:+triangles-adjacency+) ((patches:) gl:+patches+))))) ) ; end gl-utils-mesh
false
59867e5fa70e2448161a352bd99ecefcb31c57e0
669b06943e802449ed812bfafec9eec2c50647da
/deps/share/guile/site/2.2/chickadee/render/gl.scm
e6d73057df3cb7bb7ab3aeba9191a4608a26fe7f
[]
no_license
bananaoomarang/chickadee-game
f9dcdb8b2e2b3b1909d30af52c1e6a7c16b27194
8733941202243956252b19a1a3ceb35a84b61e56
refs/heads/master
2020-06-04T17:35:32.420313
2019-06-24T22:59:04
2019-06-24T22:59:04
192,126,835
1
1
null
null
null
null
UTF-8
Scheme
false
false
11,483
scm
gl.scm
;;; Chickadee Game Toolkit ;;; Copyright ยฉ 2016 David Thompson <[email protected]> ;;; ;;; Chickadee is free software: you can redistribute it and/or modify ;;; it under the terms of the GNU General Public License as published ;;; by the Free Software Foundation, either version 3 of the License, ;;; or (at your option) any later version. ;;; ;;; Chickadee 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 ;;; General Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License ;;; along with this program. If not, see ;;; <http://www.gnu.org/licenses/>. ;;; Commentary: ;; ;; Custom wrappers over low level OpenGL commands that aren't part of ;; guile-opengl. ;; ;;; Code: (define-module (chickadee render gl) #:use-module (srfi srfi-4) #:use-module ((system foreign) #:select (bytevector->pointer)) #:use-module (gl) #:use-module ((gl low-level) #:renamer (symbol-prefix-proc '%)) #:use-module (gl enums) #:use-module (gl runtime) #:use-module (gl types)) (re-export (%glClearColor . gl-clear-color) (%glScissor . gl-scissor) (%glBlendFunc . gl-blend-func) (%glBlendEquation . gl-blend-equation)) ;;; ;;; 3.8.1 Texture Image Specification ;;; (re-export (%glTexImage3D . gl-texture-image-3d) (%glTexImage2D . gl-texture-image-2d) (%glTexImage1D . gl-texture-image-1d)) ;;; ;;; 3.8.2 Alternate Texture Image Specification Commands ;;; (re-export (%glCopyTexImage2D . gl-copy-texture-image-2d) (%glCopyTexImage1D . gl-copy-texture-image-1d) (%glCopyTexSubImage3D . gl-copy-texture-sub-image-3d) (%glCopyTexSubImage2D . gl-copy-texture-sub-image-2d) (%glCopyTexSubImage1D . gl-copy-texture-sub-image-1d) (%glTexSubImage3D . gl-texture-sub-image-3d) (%glTexSubImage2D . gl-texture-sub-image-2d) (%glTexSubImage1D . gl-texture-sub-image-1d)) ;;; ;;; 3.8.3 Compressed Texture Images ;;; (re-export (%glCompressedTexImage1D . gl-compressed-texture-image-1d) (%glCompressedTexImage2D . gl-compressed-texture-image-2d) (%glCompressedTexImage3D . gl-compressed-texture-image-3d) (%glCompressedTexSubImage1D . gl-compressed-texture-sub-image-1d) (%glCompressedTexSubImage2D . gl-compressed-texture-sub-image-2d) (%glCompressedTexSubImage3D . gl-compressed-texture-sub-image-3d)) ;;; ;;; 3.8.4 Texture Parameters ;;; (re-export (%glTexParameteri . gl-texture-parameter) (%glBindTexture . gl-bind-texture)) ;;; ;;; Instancing extension ;;; (define-gl-procedure (glDrawArraysInstanced (mode GLenum) (first GLint) (count GLsizei) (primcount GLsizei) -> void) "Draw multiple instances of a set of arrays.") (define-gl-procedure (glDrawElementsInstanced (mode GLenum) (count GLsizei) (type GLenum) (indices void-*) (primcount GLsizei) -> void) "Draw multiple instances of a set of elements.") (define-gl-procedure (glVertexAttribDivisor (index GLuint) (divisor GLuint) -> void) "Modify the rate at which generic vertex attributes advance during instanced rendering.") (export (glDrawArraysInstanced . gl-draw-arrays-instanced) (glDrawElementsInstanced . gl-draw-elements-instanced) (glVertexAttribDivisor . gl-vertex-attrib-divisor)) ;;; ;;; VBOs ;;; (re-export (%glGenBuffers . gl-gen-buffers) (%glDeleteBuffers . gl-delete-buffers) (%glBufferData . gl-buffer-data) (%glBufferSubData . gl-buffer-sub-data) (%glMapBuffer . gl-map-buffer) (%glUnmapBuffer . gl-unmap-buffer)) ;;; ;;; VAOs ;;; (define-gl-procedure (glGenVertexArrays (n GLsizei) (arrays GLuint-*) -> void) "Generate N vertex arrays.") (define-gl-procedure (glDeleteVertexArrays (n GLsizei) (arrays GLuint-*) -> void) "Delete vertex array objects.") (define-gl-procedure (glBindVertexArray (array GLuint) -> void) "Bind vertex array object ARRAY.") (define-gl-procedure (glEnableVertexAttribArray (index GLuint) -> void) "Enable or disable a generic vertex attribute array.") (define-gl-procedure (glVertexAttribPointer (index GLuint) (size GLint) (type GLenum) (normalized GLboolean) (stride GLsizei) (pointer GLvoid-*) -> void) "Define an array of generic vertex attribute data.") (define-gl-procedure (glDrawElements (mode GLenum) (count GLsizei) (type GLenum) (indices GLvoid-*) -> void) "Render primitives from array data.") (export (glGenVertexArrays . gl-gen-vertex-arrays) (glDeleteVertexArrays . gl-delete-vertex-arrays) (glBindVertexArray . gl-bind-vertex-array) (glEnableVertexAttribArray . gl-enable-vertex-attrib-array) (glVertexAttribPointer . gl-vertex-attrib-pointer) (glDrawElements . gl-draw-elements)) (define-syntax-rule (with-gl-client-state state body ...) (begin (gl-enable-client-state state) body ... (gl-disable-client-state state))) (export with-gl-client-state) ;;; ;;; Framebuffers ;;; (define-gl-procedure (glGenFramebuffers (n GLsizei) (ids GLuint-*) -> void) "Generate framebuffer object names.") (define-gl-procedure (glDeleteFramebuffers (n GLsizei) (framebuffers GLuint-*) -> void) "Delete framebuffer objects.") (define-gl-procedure (glBindFramebuffer (target GLenum) (framebuffer GLuint) -> void) "Bind a framebuffer to a framebuffer target.") (define-gl-procedure (glFramebufferTexture2D (target GLenum) (attachment GLenum) (textarget GLenum) (texture GLuint) (level GLint) -> void) "Attach a level of a texture object as a logical buffer to the currently bound framebuffer object.") (define-gl-procedure (glCheckFramebufferStatus (target GLenum) -> GLenum) "Return the framebuffer completeness status of a framebuffer object.") (define-gl-procedure (glGenRenderbuffers (n GLsizei) (ids GLuint-*) -> void) "Generate renderbuffer object names.") (define-gl-procedure (glDeleteRenderbuffers (n GLsizei) (renderbuffers GLuint-*) -> void) "Delete renderbuffer objects.") (define-gl-procedure (glBindRenderbuffer (target GLenum) (renderbuffer GLuint) -> void) "Bind a named renderbuffer object.") (define-gl-procedure (glRenderbufferStorage (target GLenum) (internalformat GLenum) (width GLsizei) (height GLsizei) -> void) "Create and initialize a renderbuffer object's data store.") (define-gl-procedure (glFramebufferRenderbuffer (target GLenum) (attachment GLenum) (renderbuffertarget GLenum) (renderbuffer GLuint) -> void) "Attach a renderbuffer object to a framebuffer object.") (export (glGenFramebuffers . gl-gen-framebuffers) (glDeleteFramebuffers . gl-delete-framebuffers) (glBindFramebuffer . gl-bind-framebuffer) (glFramebufferTexture2D . gl-framebuffer-texture-2d) (glCheckFramebufferStatus . gl-check-framebuffer-status) (glGenRenderbuffers . gl-gen-renderbuffers) (glDeleteRenderbuffers . gl-delete-renderbuffers) (glBindRenderbuffer . gl-bind-renderbuffer) (glRenderbufferStorage . gl-renderbuffer-storage) (glFramebufferRenderbuffer . gl-framebuffer-renderbuffer)) (re-export (%glDrawBuffers . gl-draw-buffers)) ;;; ;;; Shaders ;;; (define-gl-procedure (glUniform1ui (location GLint) (v0 GLuint) -> void) "Specify the value of a uniform variable for the current program object") (export (glUniform1ui . gl-uniform1ui)) (re-export (%glUseProgram . gl-use-program) (%glDeleteProgram . gl-delete-program) (%glDetachShader . gl-detach-shader) (%glLinkProgram . gl-link-program) (%glBindAttribLocation . gl-bind-attrib-location) (%glAttachShader . gl-attach-shader) (%glGetAttribLocation . gl-get-attrib-location) (%glGetUniformLocation . gl-get-uniform-location) (%glCreateProgram . gl-create-program) (%glGetProgramInfoLog . gl-get-program-info-log) (%glGetProgramiv . gl-get-programiv) (%glDeleteProgram . gl-delete-program) (%glDeleteShader . gl-delete-shader) (%glGetShaderiv . gl-get-shaderiv) (%glGetShaderInfoLog . gl-get-shader-info-log) (%glCompileShader . gl-compile-shader) (%glShaderSource . gl-shader-source) (%glCreateShader . gl-create-shader) (%glGetActiveUniform . gl-get-active-uniform) (%glGetActiveAttrib . gl-get-active-attrib) (%glUniform1i . gl-uniform1i) (%glUniform2i . gl-uniform2i) (%glUniform3i . gl-uniform3i) (%glUniform4i . gl-uniform4i) (%glUniform1f . gl-uniform1f) (%glUniform2f . gl-uniform2f) (%glUniform2fv . gl-uniform2fv) (%glUniform3f . gl-uniform3f) (%glUniform3fv . gl-uniform3fv) (%glUniform4f . gl-uniform4f) (%glUniformMatrix4fv . gl-uniform-matrix4fv) (%glUniform4f . gl-uniform4f)) (re-export (%glPointSize . gl-point-size))
true
c9011d31c737caaca005df563c78b7a74c409768
58381f6c0b3def1720ca7a14a7c6f0f350f89537
/Chapter 4/4.4/4.58.scm
58f9cf480e96b2fe01fc106268812c2179b9ce8c
[]
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
208
scm
4.58.scm
#lang racket (rule (big-shot ?person) (and (supervisor ?person ?super) (job ?person (?division . ?a)) (job ?super (?super-div . ?a)) (not (same ?division ?super-div))))
false
d22e0fec2aa4cf22dfa8d6c08726475b180d6439
bc7dedf210f3ef1035d687aa18ead2afb7879e63
/src/cfz.scm
148a7ccedaee45e1500b5090e1853ab491719cdd
[]
no_license
meganeka/cfz
80d7571298a6d000486aa56080050846ef9022a1
3ddd67ae7c8c799da9baa5ecf3a0e87252ae454e
refs/heads/master
2020-04-11T13:04:56.244754
2018-12-16T08:48:52
2018-12-16T08:48:52
161,803,479
0
0
null
null
null
null
UTF-8
Scheme
false
false
9,985
scm
cfz.scm
(module cfz () (import scheme) (cond-expand (chicken-5 (import (chicken base)) (import (only (chicken format) format)) (import (only (chicken process-context) command-line-arguments)) (import (chicken type)) (import (only (chicken io) read-lines read-line)) (import (only (chicken string) string-split)) (import (only (srfi 1) filter drop append! reverse!)) (import (only (srfi 18) make-thread thread-start! thread-yield!)) (import (only typed-records defstruct)) (import (prefix curses-loop loop:)) (import (only matchable match)) (import (prefix ncurses c:)) (import (chicken condition)) (import (only (chicken bitwise) arithmetic-shift)) (import (only (chicken irregex) irregex irregex-search)) (import (prefix mailbox mb:)) ) (else (import chicken) (use (only data-structures string-split)) (use (only extras read-lines read-line)) (use (only matchable match)) (use (only srfi-1 drop filter)) (use (only typed-records defstruct)) (use (prefix curses-loop loop:)) (use (prefix ncurses c:)) (use (only irregex irregex irregex-search)) )) (define-type strings (list-of string)) (define-type cands strings) (define backspace #\x107) (define selection-style (+ c:A_REVERSE c:A_BOLD)) ;;; ** --- State ------------------------------------------------------------------- (defstruct state [(cur-cand 0) : fixnum] [(old-cand -1) : fixnum] [(cand-offs 0) : fixnum] [(query "") : string] [(old-query #f) : (or false string)] [(cands '()) : (list-of string)] [(input '()) : (list-of string)] [(retval #f) : (or boolean (list-of string))] [(done? #f) : boolean] [(mb-input (mb:make-mailbox)) : (struct mailbox)]) ;;; ** --- Render ------------------------------------------------------------------ (define-syntax with-attrs (ir-macro-transformer (lambda (e inj cmp) (apply (lambda (attrs #!rest body) `(begin (c:attron ,attrs) ,@body (c:attroff ,attrs))) (cdr e))))) (define (idx-to-line idx offs count line-min line-max) (let ([i (- idx offs)] [h (- line-max line-min)]) (if (or (< i 0) (<= count i) (< h i)) #f (+ line-min (- h i))))) (: print-candidates (strings fixnum fixnum fixnum -> *)) (define (print-candidates cands cur-cand cand-offs max-line) (let recur ([line max-line] [cs (drop cands cand-offs)]) (when (and (<= 0 line) (not (null? cs))) (c:mvprintw line 0 "~a" (car cs)) (recur (sub1 line) (cdr cs))))) (define (redraw-selection cands n-cands cand-offs old-cand new-cand c-mi c-ma) (define (cand-to-line idx) (idx-to-line idx cand-offs n-cands c-mi c-ma)) (and-let* ([l (cand-to-line new-cand)]) (with-attrs selection-style (c:mvprintw l 0 "~a" (list-ref cands new-cand)))) (and-let* ([l (cand-to-line old-cand)] [(< old-cand n-cands)]) (c:mvprintw l 0 "~a" (list-ref cands old-cand)))) (define (render state) (define cand-win-min 0) (define cand-win-max (- (c:LINES) 2)) (define cands-height (add1 (- cand-win-max cand-win-min))) (define redraw-cands? #f) (unless (eq? (state-query state) (state-old-query state)) (state-old-query-set! state (state-query state)) (let ([old-cands (state-cands state)]) (state-cands-set! state (filter-input (state-input state) (state-query state))) (unless (equal? old-cands (state-cands state)) (set! redraw-cands? #t)))) (define n-cands (length (state-cands state))) (define cur-cand (let ([cc (state-cur-cand state)]) (cond [(< cc n-cands) cc] [else (state-cur-cand-set! state 0) 0]))) (define cand-offs (if (not (idx-to-line cur-cand (state-cand-offs state) n-cands cand-win-min cand-win-max)) (begin (set! redraw-cands? #t) (let ([o (max 0 (- cur-cand (arithmetic-shift cands-height -1)))]) (state-cand-offs-set! state o) o)) (state-cand-offs state))) (when redraw-cands? (c:clear) (print-candidates (state-cands state) cur-cand cand-offs cand-win-max)) (redraw-selection (state-cands state) n-cands cand-offs (state-old-cand state) cur-cand cand-win-min cand-win-max) (with-attrs c:A_BOLD (c:mvprintw (sub1 (c:LINES)) 0 "~a ~a > ~a" (length (state-input state)) n-cands (state-query state) (list (state-old-query state)))) (c:refresh)) ;;; ** --- Logic ------------------------------------------------------------------- (: filter-input (strings string --> strings)) (define (filter-input input query) (define (make-pred q) (let ([irxs (map (lambda (s) (irregex `(: ,s) 'i)) (string-split q " "))]) (lambda (line) (let lp ([ixs irxs]) (or (null? ixs) (and (irregex-search (car ixs) line) (lp (cdr ixs)))))))) (if (string=? "" query) input (filter (make-pred query) input))) (define (num-cands cands) (length cands)) (define (find-parent state cands) (state-old-cand-set! state (state-cur-cand state)) (let* ([cur (list-ref cands (state-cur-cand state))] [cur-len (string-length cur)]) (let recur ([best-len 0] [best -1] [cs cands] [idx 0]) (cond [(null? cs) (state-cur-cand-set! state (if (= -1 best) (state-cur-cand state) best))] [else (let* ([c (car cs)] [cl (string-length c)]) (cond [(or (not (< cl cur-len)) (not (< best-len cl)) (not (string=? (substring cur 0 cl) c))) (recur best-len best (cdr cs) (add1 idx))] [else (recur cl idx (cdr cs) (add1 idx))]))])))) (define (init-state) (make-state)) (define (get-message state) (thread-yield!) (let ([mb-in (state-mb-input state)]) (cond [(not (mb:mailbox-empty? mb-in)) (mb:mailbox-receive! mb-in)] [else #f]))) ;;; ** --- Update ------------------------------------------------------------------ (define (update state msg) (loop:log-msg "update" (car msg)) (define cand-up (lambda (cands #!optional (count 1)) (unless (null? cands) (state-old-cand-set! state (state-cur-cand state)) (state-cur-cand-set! state (modulo (+ count (state-cur-cand state)) (num-cands cands)))))) (define (back? c) (or (eq? backspace c) (eq? c:KEY_BACKSPACE c))) (define (set-query new) (state-query-set! state new)) (define (set-return-val v) (state-done?-set! state #t) (state-retval-set! state v)) ;; (match '(foo: a #\a) [(or (foo: 'a #\a) (foo: 'b #\b))]) ;; TODO: matchable bug? (match msg [('key: 'meta #\j) (cand-up (state-cands state) -1)] [('key: 'meta #\k) (cand-up (state-cands state))] [('key: 'meta #\u) (find-parent state (state-cands state))] [('key: 'meta #\escape) (set-return-val #t)] [('key: 'meta #\g) (set-return-val #t)] [('key: 'meta #\e) (error 'eee)] [('key: #\alarm) (set-return-val #t)] [('key: #\newline) (set-return-val (let ([cands (filter-input (state-input state) (state-query state))]) (if (null? cands) #f (list (list-ref cands (state-cur-cand state))))))] [('key: (? back?)) (set-query (substring (state-query state) 0 (max 0 (sub1 (string-length (state-query state))))))] [('key: c) (set-query (string-append (state-query state) (format "~a" c)))] [('add-strings: strs) (state-old-query-set! state #f) ; refilter (state-input-set! state (append! (state-input state) strs))] [t (error 'update "unknown msg" t)]) state) (define (read-input-loop mb-out port) (let lp ([lines '()] [c 0]) (let ([l (read-line port)]) (cond [(or (eof-object? l) (= 5000 c)) (mb:mailbox-send! mb-out (list add-strings: (reverse! lines))) (when (not (eof-object? l)) (lp '() 0))] [else (lp (cons l lines) (add1 c))])))) (define (main input-file output-file) (let* ([state (init-state)] [input (if input-file (with-input-from-file input-file (lambda () (mb:mailbox-send! (state-mb-input state) (list add-strings: (read-lines))))) (thread-start! (make-thread (lambda () (read-input-loop (state-mb-input state) (current-input-port))))))]) (let* ([ret (state-retval (loop:main-loop state update render get-message state-done?))]) (define (pres) (when (list? ret) (for-each print ret))) (cond [(not ret) (exit 1)] [output-file (with-output-to-file output-file (lambda () (loop:log-msg "outputting") (pres)))] [else (pres)])))) (match (command-line-arguments) [(in-file out-file) (main in-file out-file)] [() (main #f #f)] [t (print "expected args: in-file out-file, got " t) (exit 1)]) )
true
184f129fc7d284ec5435175cf76a9bb094d456e4
fae4190f90ada065bc9e5fe64aab0549d4d4638a
/pre-effect/info.ss
659efdde85bd119ab5ed0d1e205b0393b19cede4
[]
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
649
ss
info.ss
(module info (lib "infotab.ss" "setup") (define name "Typed Scheme") (define html-docs (list "doc")) (define doc.txt "doc.txt") (define tools (list "private/tool.ss")) (define tool-names (list "Typed Scheme")) (define compile-omit-files (list)) (define categories (list 'devtools 'metaprogramming)) (define can-be-loaded-with 'all) (define homepage "http://www.ccs.neu.edu/home/samth/typed-scheme") (define primary-file "typed-scheme.ss") (define required-core-version "369.1") (define version "0.1") (define blurb `("This language allows the definition and execution of typed scheme programs.")) )
false
b797d96fca7e135133912246848ad51e023ac813
1ed47579ca9136f3f2b25bda1610c834ab12a386
/sec5/q5.11.scm
ee9ce5c9b7a1101794ac500d7b26f1385cc52570
[]
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,275
scm
q5.11.scm
;; ๆœฌๆ–‡ใฎrestoreๅฎš็พฉใงใฏ, (save y) (save x) (restore y) ;; ใจใ—ใŸๆ™‚ใฎๆŒ™ๅ‹•ใซใคใ„ใฆ็‰นใซ่งฆใ‚Œใชใ‹ใฃใŸ. ;; restoreใฎๅฎŸ่ฃ…ใจใ—ใฆไปฅไธ‹ใฎ3ใคใŒ่€ƒใˆใ‚‰ใ‚Œใ‚‹. ใกใชใฟใซๆœฌๆ–‡ใฎๅฎŸ่ฃ…ใฏ(a)ใซใชใฃใฆใ„ใ‚‹ ;; (a). (resotre y) ใฏใฉใฎใƒฌใ‚ธใ‚นใ‚ฟๅ‡บ่บซใ‹ใฏ้–ขไฟ‚ใชใ, stackใซ้€€้ฟใ—ใŸๆœ€ๅพŒใฎๅ€คใ‚’yใซ็ฝฎใ. ;; (b). (resotre y) ใฏyใจใ—ใฆsaveใ—ใŸๅ€คไปฅๅค–ใ‚’resotreใ—ใ‚ˆใ†ใ™ใ‚‹ใจใ‚จใƒฉใƒผใซใชใ‚‹. ;; (c). (resotre y) ใฏใฉใ‚“ใช็Šถๆณใงใ‚ใ‚ใ†ใจๆœ€ๅพŒใซ(save y)ใ—ใŸyใฎๅ€คใ‚’ๅพฉๆดปใ™ใ‚‹. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ๅ•้กŒ(a). (a)ใฎๆ–น้‡ใŒ, 5.1.4็ฏ€(ๅ›ณ5.12)ใฎFibonacci่จˆ็ฎ—ใ‹ใ‚‰1ๅ‘ฝไปคใ‚’้™คๅŽปใ™ใ‚‹ใฎใซไฝฟใˆใ‚‹ใ“ใจใ‚’็คบใ›. ;; saveใ—ใŸๆ™‚ใจ้•ใ†registerใซrestoreใ—ใฆใ‚‚่‰ฏใ„ใจใ„ใ†็‰นๆ€งใ‚’ๅˆฉ็”จใ—ใŸใ‚ทใƒงใƒผใƒˆใ‚ซใƒƒใƒˆ (assign continue (label fib-done)) fib-loop (test (op <) (reg n) (const 2)) (branch (label immediate-answer)) (save continue) (assign continue (label afterfib-n-1)) (save n) (assign n (op -) (reg n) (const 1)) (goto (label fib-loop)) afterfib-n-1 (restore n) (restore continue) (assign n (op -) (reg n) (const 2)) (save continue) (assign continue (label afterfib-n-2)) (save val) (goto (label fib-loop)) afterfib-n-2 (assign n (reg val)) ;; * (restore val) ;; * (restore continue) (assign val (op +) (reg val) (reg n)) (goto (reg continue)) immediate-answer (assign val (reg n)) (goto (reg continue)) fib-done) ;; * ใฎ2่กŒใ‚’ใพใจใ‚ใฆ (restore n) ;; ใจๆ›ธใใ“ใจใŒๅ‡บๆฅใ‚‹. valใจใ—ใฆsaveใ•ใ‚Œใฆใ„ใ‚‹ๅ€คใ‚’็›ดๆŽฅnใซๅ…ฅใ‚Œใฆใ‚‹. ;; valใฎregisterใฏใใฎ2่กŒไธ‹ใงๆ–ฐใ—ใ„ใ‚‚ใฎใซๆ›ดๆ–ฐใ•ใ‚Œใ‚‹ใฎใงๅ•้กŒใชใ„. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ๅ•้กŒ(b). (b)ใ‚’ๅฎŸ่ฃ…ใ›ใ‚ˆ. ใ‚นใ‚ฟใƒƒใ‚ฏใซๅ€คใจไธ€็ท’ใซใƒฌใ‚ธใ‚นใ‚ฟๅใ‚’็ฝฎใใ‚ˆใ†, saveใ‚’ไฟฎๆญฃใ™ใ‚‹ๅฟ…่ฆใŒใ‚ใ‚‹. (define (make-save inst machine stack pc) (let ((stack-name (stack-inst-reg-name inst))) (let ((reg (get-register machine stack-name))) (lambda () (push stack (cons stack-name (get-contents reg))) (advance-pc pc))))) (define (make-restore inst machine stack pc) (let ((stack-name (stack-inst-reg-name inst))) (let ((reg (get-register machine stack-name))) (lambda () (let ((top (pop stack))) (if (eq? (car top) stack-name) (begin (set-contents! reg (cdr top)) (advance-pc pc)) (error "Cannot restore different name register -- MAKE-RESTORE" stack-name))))))) ;;; ๅ‹•ไฝœ็ขบ่ช ;;; (define fib-machine (make-machine '(n val continue) (list (list '< <) (list '+ +) (list '- -)) '((assign continue (label fib-done)) fib-loop (test (op <) (reg n) (const 2)) (branch (label immediate-answer)) (save continue) (assign continue (label afterfib-n-1)) (save n) (assign n (op -) (reg n) (const 1)) (goto (label fib-loop)) afterfib-n-1 (restore n) (restore continue) (assign n (op -) (reg n) (const 2)) (save continue) (assign continue (label afterfib-n-2)) (save val) (goto (label fib-loop)) afterfib-n-2 (restore n) ;; (a)ใง่จ€ๅŠใ—ใŸ็œ็•ฅ็‰ˆ. ๆ€’ใ‚‰ใ‚Œใ‚‹ใฏใš (restore continue) (assign val (op +) (reg val) (reg n)) (goto (reg continue)) immediate-answer (assign val (reg n)) (goto (reg continue)) fib-done))) (set-register-contents! fib-machine 'n 6) (start fib-machine) ;; gosh> !!!*** ERROR: Cannot restore different name register -- MAKE-RESTORE n!!! ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ๅ•้กŒ(c). (c)ใ‚’ๅฎŸ่ฃ…ใ›ใ‚ˆ. ใƒฌใ‚ธใ‚นใ‚ฟๆฏŽใซๅ€‹ๅˆฅใฎstackใ‚’็”จๆ„ใ™ใ‚‹ๅฟ…่ฆใŒใ‚ใ‚‹. ;; ่ค‡ๆ•ฐใฎ่งฃใๆ–นใ‚’่ฆ‹ใคใ‘ใŸ. ;; ๆ–น้‡(1): stackใฎsๅ†…ใซregisterๅไป˜ใใงๅ€‹ๅˆฅใซstackใ‚’็”Ÿๆˆ, assocใง่ฆ‹ใคใ‘ใ‚‹. ;; http://community.schemewiki.org/?sicp-ex-5.11 ;; ๆ–น้‡(2): register่‡ช่บซใซstackใ‚’ใ‚‚ใŸใ›ใ‚‹ ;; http://d.hatena.ne.jp/rsakamot/20090723/1248328615 ;; ๅค‰ๆ›ดใ‚’ๆœ€ๅฐ้™ใซใ™ใ‚‹ใซใฏmake-stack, make-save, make-restoreใ‚’ๅค‰ใˆใ‚Œใฐไบ‹่ถณใ‚Šใ‚‹(1)ใŒ่‰ฏใ„ใจๆ€ใฃใŸใฎใงใ“ใฃใกใง. ;; s = ((n . (1 2 3 4...)) (continue . ((...) (...))))) ใฟใŸใ„ใชๆง‹้€ . ;; make-new-machineใงregisterใ‚’็™ป้Œฒใ™ใ‚‹้š›ใซๅฐ‚็”จstackใ‚‚ไธ€็ท’ใซไฝœใ‚‹. ;; NEXT-LOOP: ๅˆฅ่งฃใจใ—ใฆ, ๆœ€ๅˆใซsaveใ—ใ‚ˆใ†ใจใ—ใŸๆ™‚ใซๅฐ‚็”จstackใ‚’ไฝœใ‚‹ใจใ„ใ†LazyใชๅฎŸ่ฃ…ใงใ‚‚ใ‚ˆใ„. (define (make-new-machine) ;;... (define (allocate-register name) (if (assoc name register-table) (error "Multiply defined register: " name) (begin (set! register-table (cons (list name (make-register name)) register-table)) (set! stack (cons (cons name '()) stack)))) ; ++ 'register-allocated) ;; ... ) (define (make-stack) (let ((s '())) (define (push reg-name value) ;; reg-stack = (n . (1 2 3 ...)) (let ((reg-stack (assoc reg-name s))) (if reg-stack (set-cdr! reg-stack (cons value reg-stack)) (error "Named Stack Not Found -- PUSH" reg-name)))) (define (pop reg-name) (let ((reg-stack (assoc reg-name s))) (if reg-stack (let ((top (cadr reg-stack)) (set-cdr! reg-stack (cddr reg-stack)) top) (error "Named Stack Not Found -- POP" reg-name)))) (define (initialize) (for-each (lambda (stack) ;; (n . (1 2 3...))ใฎcdr้ƒจๅˆ†ใ‚’ใ‚ซใƒฉใซ. (set-cdr! stack '())) s) 'done) (define (show) s) ; my (define (dispatch message) (cond ((eq? message 'push) push) ((eq? message 'pop) (pop)) ((eq? message 'show) (show)) ; my ((eq? message 'initialize) (initialize)) (else (error "Unknown request -- STACK" message)))) dispatch)) ;; (define (pop stack) (stack 'pop)) ใ‹ใ‚‰ (define (pop stack reg-name) ((stack 'pop) reg-name)) ;; (define (push stack value) ((stack 'push) value)) ใ‹ใ‚‰ (define (push stack reg-name value) ((stack 'push) reg-name value)
false
c08e80b116282f9e7126e7644839b3e109a6ca3c
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
/sitelib/rfc/smtp/format.scm
28640ad31b4cabf6e26c458beb982262a78fadfd
[ "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "MIT", "BSD-2-Clause" ]
permissive
ktakashi/sagittarius-scheme
0a6d23a9004e8775792ebe27a395366457daba81
285e84f7c48b65d6594ff4fbbe47a1b499c9fec0
refs/heads/master
2023-09-01T23:45:52.702741
2023-08-31T10:36:08
2023-08-31T10:36:08
41,153,733
48
7
NOASSERTION
2022-07-13T18:04:42
2015-08-21T12:07:54
Scheme
UTF-8
Scheme
false
false
2,629
scm
format.scm
;;; -*- mode:scheme; coding:utf-8; -*- ;;; ;;; rfc/smtp/format.scm - SMTP format check ;;; ;;; Copyright (c) 2010-2017 Takashi Kato <[email protected]> ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. 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 ;;; OWNER 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. ;;; ;; references ;; - https://tools.ietf.org/html/rfc5321 ;; - https://tools.ietf.org/html/rfc5322 (library (rfc smtp format) (export smtp-valid-address?) (import (rnrs) (srfi :2) (srfi :13) (srfi :14) (rfc :5322)) ;; https://tools.ietf.org/html/rfc5321#section-2.3.11 ;; local-part@domain ;; this is a bit too naive but for now (define (smtp-valid-address? s) (define in (if (input-port? s) s (open-string-input-port s))) (let ((local (rfc5322-next-token in))) (and (eqv? #\@ (get-char in)) ;; this doesn't handle domain-literal properly... (let ((domain (rfc5322-next-token in))) (and (string? domain) (check-length local domain) (eof-object? (get-char in))))))) ;; TODO add mailbox format ;; mailbox format is more strict than address ;; though, not sure if we need it... ;; (define (smtp-valid-mailbox? s)) (define (check-length local-part domain) (define llen (string-length local-part)) (define dlen (string-length domain)) (and (<= llen 64) (<= dlen 255) ;; exclude '@' (< (+ llen dlen) 253))) )
false
591915b7c85777a6baeb4f29b55747ab5c349972
a09ad3e3cf64bc87282dea3902770afac90568a7
/3/59.scm
c2c085232119187f877e59d636cd2fdaeb8e6ce9
[]
no_license
lockie/sicp-exercises
aae07378034505bf2e825c96c56cf8eb2d8a06ae
011b37387fddb02e59e05a70fa3946335a0b5b1d
refs/heads/master
2021-01-01T10:35:59.759525
2018-11-30T09:35:35
2018-11-30T09:35:35
35,365,351
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,050
scm
59.scm
#lang sicp ;; nasty boilerplate (#%require racket/stream) (define-syntax cons-stream (syntax-rules () ((_ a b) (stream-cons a b)))) (define stream-car stream-first) (define stream-cdr stream-rest) (define stream-null? stream-empty?) (define the-empty-stream empty-stream) (define (stream-for-each proc s) (if (stream-null? s) 'done (begin (proc (stream-car s)) (stream-for-each proc (stream-cdr s))))) (define (stream-filter pred stream) (cond ((stream-null? stream) the-empty-stream) ((pred (stream-car stream)) (cons-stream (stream-car stream) (stream-filter pred (stream-cdr stream)))) (else (stream-filter pred (stream-cdr stream))))) (define (stream-enumerate-interval low high) (if (> low high) the-empty-stream (cons-stream low (stream-enumerate-interval (+ low 1) high)))) (define (display-stream s) (define (display-line x) (newline) (display x)) (stream-for-each display-line s)) (define (stream-map proc . argstreams) (if (stream-null? (car argstreams)) the-empty-stream (cons-stream (apply proc (map stream-car argstreams)) (apply stream-map (cons proc (map stream-cdr argstreams)))))) (define (add-streams s1 s2) (stream-map + s1 s2)) (define (scale-stream stream factor) (stream-map (lambda (x) (* x factor)) stream)) (define ones (cons-stream 1 ones)) (define integers (cons-stream 1 (add-streams ones integers))) ;; actual code (display "Boring integrate-series") (newline) (define (integrate-series S) (define (integrate-series-iter S n) (cons-stream (/ (stream-car S) (stream-car n)) (integrate-series-iter (stream-cdr S) (stream-cdr n)))) (integrate-series-iter S integers)) (define S (integrate-series integers)) (stream-ref S 0) (stream-ref S 1) (stream-ref S 2) (stream-ref S 3) (stream-ref S 4) (stream-ref S 5) (stream-ref S 6) (display "Exp series") (newline) (define exp-series (cons-stream 1 (integrate-series exp-series))) (stream-ref exp-series 0) (stream-ref exp-series 1) (stream-ref exp-series 2) (stream-ref exp-series 3) (stream-ref exp-series 4) (stream-ref exp-series 5) (stream-ref exp-series 6) (display "Cosine series") (newline) (define cosine-series (cons-stream 1 (scale-stream (integrate-series sine-series) -1))) (define sine-series (cons-stream 0 (integrate-series cosine-series))) (stream-ref cosine-series 0) (stream-ref cosine-series 1) (stream-ref cosine-series 2) (stream-ref cosine-series 3) (stream-ref cosine-series 4) (stream-ref cosine-series 5) (stream-ref cosine-series 6) (display "Sine series") (newline) (stream-ref sine-series 0) (stream-ref sine-series 1) (stream-ref sine-series 2) (stream-ref sine-series 3) (stream-ref sine-series 4) (stream-ref sine-series 5) (stream-ref sine-series 6)
true
1c6e15dafd99c0abd649d132cfab3cfcf15f6f74
5fe14ef1ced9caa3b7d1fc3248ba86155e9628f5
/tests/srfi-26.scm
01c56b5ca8baf89b2f5b657972e98794176acc16
[]
no_license
mario-goulart/chicken-tests
95720ed5b29e7a7c209d4431b9558f21916752f1
04b8e059aaacaea308aac40082d346e884cb901c
refs/heads/master
2020-06-02T08:18:08.888442
2012-07-12T14:02:29
2012-07-12T14:02:29
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,071
scm
srfi-26.scm
; CONFIDENCE TEST FOR IMPLEMENTATION OF SRFI-26 ; ============================================= ; ; [email protected], 3-Jun-2002. ; ; This file checks a few assertions about the implementation. ; If you run it and no error message is issued, the implementation ; is correct on the cases that have been tested. ; (cond-expand (srfi-26)) (define (writeln . xs) (for-each display xs) (newline)) ; (check expr) ; evals expr and issues an error if it is not #t. (define (check expr) (if (not (eq? (eval expr (interaction-environment)) #t)) (writeln "Error: test failed: " expr))) ; (check-all) ; runs several tests on cut and reports. (define (check-all) (for-each check '( ; cuts (equal? ((cut list)) '()) (equal? ((cut list <...>)) '()) (equal? ((cut list 1)) '(1)) (equal? ((cut list <>) 1) '(1)) (equal? ((cut list <...>) 1) '(1)) (equal? ((cut list 1 2)) '(1 2)) (equal? ((cut list 1 <>) 2) '(1 2)) (equal? ((cut list 1 <...>) 2) '(1 2)) (equal? ((cut list 1 <...>) 2 3 4) '(1 2 3 4)) (equal? ((cut list 1 <> 3 <>) 2 4) '(1 2 3 4)) (equal? ((cut list 1 <> 3 <...>) 2 4 5 6) '(1 2 3 4 5 6)) (equal? (let* ((x 'wrong) (y (cut list x))) (set! x 'ok) (y)) '(ok)) (equal? (let ((a 0)) (map (cut + (begin (set! a (+ a 1)) a) <>) '(1 2)) a) 2) ; cutes (equal? ((cute list)) '()) (equal? ((cute list <...>)) '()) (equal? ((cute list 1)) '(1)) (equal? ((cute list <>) 1) '(1)) (equal? ((cute list <...>) 1) '(1)) (equal? ((cute list 1 2)) '(1 2)) (equal? ((cute list 1 <>) 2) '(1 2)) (equal? ((cute list 1 <...>) 2) '(1 2)) (equal? ((cute list 1 <...>) 2 3 4) '(1 2 3 4)) (equal? ((cute list 1 <> 3 <>) 2 4) '(1 2 3 4)) (equal? ((cute list 1 <> 3 <...>) 2 4 5 6) '(1 2 3 4 5 6)) (equal? (let ((a 0)) (map (cute + (begin (set! a (+ a 1)) a) <>) '(1 2)) a) 1)))) ; run the checks when loading (check-all) (writeln "Done.")
false
babd650c1cfc06a722ecc8934b0413b127ecc723
665da87f9fefd8678b0635e31df3f3ff28a1d48c
/tests/unit-tests.scm
c535dc63541c693dd4ffe13b97f95b829ead1041
[ "MIT" ]
permissive
justinethier/cyclone
eeb782c20a38f916138ac9a988dc53817eb56e79
cc24c6be6d2b7cc16d5e0ee91f0823d7a90a3273
refs/heads/master
2023-08-30T15:30:09.209833
2023-08-22T02:11:59
2023-08-22T02:11:59
31,150,535
862
64
MIT
2023-03-04T15:15:37
2015-02-22T03:08:21
Scheme
UTF-8
Scheme
false
false
14,199
scm
unit-tests.scm
(import (scheme base) (scheme char) (scheme file) (scheme lazy) (scheme read) (scheme write) (scheme eval) ;(srfi 9) ) (define *num-passed* 0) (define (assert:equal msg actual expected) (if (not (equal? actual expected)) (error "Unit test failed [" msg "] actual [" actual "] expected [" expected "]") (set! *num-passed* (+ *num-passed* 1)))) (define (assert:not-equal msg x y) (assert:equal msg (not (equal? x y)) #t)) (define (assert msg val) (assert:equal msg (not val) #f)) (assert "Testing assert function" #t) (assert "Testing assert function" 1) ;; Quotation / Quasi-quotes (assert:equal "quasi-quote #1" `(read ,(+ 1 2 3)) '(read 6)) (assert:equal "quasi-quote #2" `(read ,(list 1 2 3)) '(read (1 2 3))) (assert:equal "quasi-quote splicing" `(read ,@(list 1 2 3)) '(read 1 2 3)) ;; Lists (define l (list 'a 'b 'c)) ; TODO: seems to break eval below, is there a GC problem with a circular list? ;(set-cdr! l l) (set-cdr! l '(c b)) ; Above seems to break if it replaces this line (assert:equal "list? on circular list" (list? l) #t) ;; Circular data structures (define v1 (vector #f)) (define v2 (vector v1)) (vector-set! v1 0 v2) (cond-expand (memory-streams (let ((fp (open-output-string))) (display v1 fp) (assert:equal "display circular vector" (> (string-length (get-output-string fp)) 0) #t)))) (assert:equal "equality on circular vectors" (equal? v1 v2) #t) (newline) (define v1 (vector 1 2 3)) (define v2 (vector 1 v1 3)) (vector-set! v1 1 v2) (cond-expand (memory-streams (let ((fp (open-output-string))) (write v1 fp) (assert:equal "display circular vector" (> (string-length (get-output-string fp)) 0) #t)))) (assert:equal "equality on circular vectors, test 2" (equal? v1 v2) #t) (newline) (define l1 (list #f)) (define l2 (list l1)) (set-cdr! l1 l2) (cond-expand (memory-streams (let ((fp (open-output-string))) (display l1 fp) (assert:equal "display circular list" (> (string-length (get-output-string fp)) 0) #t)))) (assert:equal "equality on circular lists" (equal? l1 l2) #f) (define l1 (list 1 2 3)) (define l2 (list 1 l1 3)) (set-cdr! (cdr l1) l2) (cond-expand (memory-streams (let ((fp (open-output-string))) (write l1 fp) (assert:equal "display circular list" (> (string-length (get-output-string fp)) 0) #t)))) (assert:equal "equality on circular lists, test 2" (equal? l1 l2) #f) ;; Adder example (define (make-adder x) (lambda (y) (+ x y))) (define increment (make-adder +1)) (assert:equal "Adder #1" (increment 41) 42) (define decrement (make-adder -1)) (assert:equal "Adder #2" (decrement 42) 41) (assert:equal "Application example" ((lambda (x) x) (+ 41 1)) 42) ;; Apply section (assert:equal "" (apply length '((#t #f))) 2) (assert:equal "" (apply cons '(#t #f)) '(#t . #f)) (assert:equal "" (apply cadr (list (list 1 2 3 4))) 2) (assert:equal "" (apply null? (list '())) #t) ;; Varargs (define (list2 a b . objs) objs) (assert:equal "apply varargs" (list 42 1) '(42 1)) (assert:equal "apply varargs" (list 42 1 2) '(42 1 2)) (assert:equal "apply varargs" (list2 42 1) '()) (assert:equal "apply varargs" (list2 42 1 2) '(2)) (assert:equal "begin" (begin 1 2 (+ 1 2) (+ 3 4)) 7) ;; Continuation section (assert:equal "simple call/cc" (call/cc (lambda (k) (k 2))) 2) (assert:equal "escape continuation" (call/cc (lambda (return) (begin (return 'return)))) 'return) ;; Closure section (assert:equal "simple closure" (((lambda (x.1) (lambda (y.2) (cons x.1 y.2))) #t) #f) '(#t . #f)) (assert:equal "closure #2" ((lambda (x y) ((lambda () (- x y)))) 5 4) 1) ;; Anonymous lambda's (assert:equal "execute anonymous lambda" ((lambda (a . Y) Y) 'x) '()) (assert:equal "execute anonymous lambda" ((lambda (a . Y) Y) 'x 'y) '(y)) (assert:equal "execute anonymous lambda" ((lambda (a . Y) Y) 'x 'y 'z) '(y z)) (assert:equal "execute anonymous lambda" ((lambda (a b . Y) Y) 'x 'y 'z) '(z)) (assert:equal "execute anonymous lambda" ((lambda Y Y) 'x 'y 'z) '(x y z)) (assert:equal "execute anonymous lambda" ((lambda Y Y) ) '()) ;; Factorial (define (fac n) (if (= n 0) 1 (* n (fac (- n 1))))) (assert:equal "Factorial example" (fac 10) 3628800) ;; If section (assert:equal "if example" (if #t 1 2) 1) (assert:equal "if example" (if #f 1 2) 2) (assert:equal "if example" (if (+ 1 2) (+ 3 4) (* 3 4)) 7) (assert:equal "if" (if ((lambda (x) (+ x 1)) 0) (+ 1 1) (* 0 0)) 2) (assert:equal "no else clause" (if #t 'no-else-clause) 'no-else-clause) (assert:equal "" (+ (+ 1 1) (* 3 4)) 14) ;; Set section ((lambda (x) (set! x #t) ; (+ 2 (* 3 4))) (assert:equal "set local x" x #t)) #f) (define a (list #f #f)) (define b (cons #f #f)) (set-car! a 1) (set-cdr! a '(2)) (assert:equal "set car/cdr a" a '(1 2)) (set-cdr! a 2) (set-car! b '(#t)) (set-cdr! b '#t) (assert:equal "set a" a '(1 . 2)) (assert:equal "set b" b '((#t) . #t)) ;; Scoping example (define scope #f) (assert:equal "outer scope" scope #f) ((lambda (scope) (assert:equal "inner scope" scope #t) ) #t) ;; Square example (let ((x 10) (y 20) (square (lambda (x) (* x x)))) (begin (assert:equal "square x" (square x) 100) (assert:equal "square y" (square y) 400))) ;; String section (define a "a0123456789") (assert:equal "string eq" a "a0123456789") (assert:not-equal "string eq" a 'a0123456789) (define b "abcdefghijklmnopqrstuvwxyz") (define c "hello, world!") (define d (list->string '(#\( #\" #\a #\b #\c #\" #\)))) (assert:equal "strings" d "(\"abc\")") (assert:equal "strings" d "(\"abc\")") ;; Test GC (assert:equal "strings" d "(\"abc\")") ;; Test GC (set! a "hello 2") (assert:equal "strings" a "hello 2") (define (f) (make-string 3 #\*)) (define (g) "***") (assert:equal "string-set!" (string-set! (f) 0 #\?) "?**") (define a "12345") (define b (string-copy "abcde")) (assert:equal "string-copy!" (string-copy! b 1 a 0 2) "a12de") (let ((v '())) (string-for-each (lambda (c) (set! v (cons (char->integer c) v))) "abcde") (assert:equal "string-for-each" v '(101 100 99 98 97))) (assert:equal "interline whitespace" "1 2 \ 3 4" "1 2 3 4") (assert:equal "interline whitespace" "1 2 \ 3 4" "1 2 \n\n3 4") ;; UTF-8 / Strings (assert:equal "UTF8 string length" (string-length (make-string 1 (integer->char 128))) 1) (assert:equal "UTF8 bv length" (bytevector-length (string->utf8 (make-string 1 (integer->char 128)))) 2) (assert:equal "UTF8 char" (string-ref (make-string 1 (integer->char 128)) 0) #\x80) ;; Recursion example: (letrec ((fnc (lambda (i) (begin ;(display i) (if (> i 0) (fnc (- i 1)) 0))))) (fnc 10)) (assert:equal "numeric small reverse" (reverse '(1 2)) '(2 1)) (assert:equal "small reverse" (reverse '(a b c)) '(c b a)) (assert:equal "larger reverse" (reverse '(1 2 3 4 5 6 7 8 9 10)) '(10 9 8 7 6 5 4 3 2 1)) ;; ;TODO: improper list, this is an error: (reverse '(1 . 2)) (assert:equal "char whitespace" (char-whitespace? #\space) #t) (assert:equal "char whitespace" (char-whitespace? #\a) #f) (assert:equal "char numeric" (char-numeric? #\1) #t) (assert:equal "char numeric" (char-numeric? #\newline) #f) (assert:equal "" (and 1 2 3) 3) (assert:equal "" (and #t #f 'a 'b 'c) #f) (assert:equal "" (or 1 2 3) 1) (assert:equal "" (or #f 'a 'b 'c) 'a) (assert:equal "" (string-append "") "") ;error - (string-append 1) (assert:equal "" (string-append "test") "test") (assert:equal "" (string-append "ab" "cdefgh ij" "klmno" "p" "q" "rs " "tuv" "w" " x " "yz") "abcdefgh ijklmnopqrs tuvw x yz") (assert:equal "" (string->number "0") 0) (assert:equal "" (string->number "42") 42) ;(assert:equal "" (string->number "343243243232") ;; Note no bignum support (assert:equal "" (string->number "3.14159") 3.14159) (assert:equal "" (list->string (list #\A #\B #\C)) "ABC") (assert:equal "" (list->string (list #\A)) "A") (assert:equal "" (list->string (list)) "") (assert:equal "" (integer->char 65) #\A) (assert:equal "" (char->integer #\a) 97) (assert:equal "" (number->string (+ 1 2)) "3") (assert:equal "" (string->list "test") '(#\t #\e #\s #\t)) (assert:equal "" (string->symbol "a-b-c-d") 'a-b-c-d) (assert:equal "" (symbol->string 'a/test-01) "a/test-01") (assert:equal "" (eq? 'a-1 'a-1) #t) (assert:equal "" (eq? (string->symbol "aa") 'aa) #t) (assert:equal "" (eq? 0.0 0.0) #f) (assert:equal "" (eq? 33333333333333 33333333333333) #f) (assert:equal "" (eqv? 'a-1 'a-1) #t) (assert:equal "" (eqv? (string->symbol "aa") 'aa) #t) (assert:equal "" (eqv? 0.0 0.0) #t) (assert:equal "" (eqv? 33333333333333 33333333333333) #t) (assert:equal "" (equal? (string->symbol "aa") 'aa) #t) ;; Map (assert:equal "map 1" (map (lambda (x) (car x)) '((a . b) (1 . 2) (#\h #\w))) '(a 1 #\h)) (assert:equal "map 2" (map car '((a . b) (1 . 2) (#\h #\w))) '(a 1 #\h)) (assert:equal "map 3" (map cdr '((a . b) (1 . 2) (#\h #\w))) '(b 2 (#\w))) (assert:equal "map length" (map length '(() (1) (1 2) (1 2 3) (1 2 3 4))) '(0 1 2 3 4)) ;; Prove internal defines are compiled properly ;; ;; Illustrates an old problem with compiling parser. ;; how to handle the internal define p? ;; trans was trying to wrap p with a lambda, which is not going to ;; work because callers want to pass a,b,c directly. (define (glob a b c) (define (p d) (list a b c d)) (p 4)) (assert:equal "internal defs for global funcs" (glob 1 2 3) '(1 2 3 4)) ;; Global shadowing issue ;; Do not allow global define to shadow local ones (define x 'global) ((lambda () (define x 1) ((lambda () (define x 2) (assert:equal "local define of x" x 2))) (assert:equal "another local define of x" x 1))) (assert:equal "global define of x" x 'global) ; TODO: could add parser tests for these ;( ;123(list) ;1'b ;(write ; (list ; 1;2 ; )) ;1;2 ;3"four five" ;#\space ;) ;; EVAL section (define x 1) (define y 2) (define *z* 3) ;(write (eval '(Cyc-global-vars))) (assert:equal "eval compiled - x" (eval 'x) x) (eval '(set! x 'mutated-x)) (assert:equal "Access var with a mangled name" (eval '*z*) *z*) (assert:equal "Access compiled var mutated by eval" x 'mutated-x) ;; END eval ;; Vectors (assert:equal "vector-ref" (vector-ref #(1 1 2 3 5 8 13 21) 5) 8) (assert:equal "vector-set!" (vector-set! #(0 '(2 2 2 2) "anna") 1 "test") #(0 "test" "anna")) (assert:equal "vector->list" (vector->list #(dah dah didah)) '(dah dah didah)) ;(vector->list .#(dah dah didah) 1 2) ;=. (dah) (assert:equal "list->vector" (list->vector '(dididit dah)) #(dididit dah)) (assert:equal "string->vector" (string->vector "ABC") #(#\A #\B #\C)) (assert:equal "vector->string" (vector->string #(#\1 #\2 #\3)) "123") (define a (vector 1 2 3 4 5)) (define b (vector 10 20 30 40 50)) (vector-copy! b 1 a 0 2) (assert "vector-copy!" (equal? b #(10 1 2 40 50))) (define a (vector 1 2 3 4 5)) (vector-fill! a 'smash 2 4) (assert:equal "vector-fill!" a #(1 2 smash smash 5)) ;; END vectors ;; I/O (with-output-to-file "test.out" (lambda () (write 'hello-world))) ;(write "done with output") (with-input-from-file "test.out" (lambda () (assert:equal "I/O with-*-file test" (read) 'hello-world))) (call-with-output-file "test.txt" (lambda (port) (write 'ok port))) ;; Note: was a good test, did not always work in icyc (call-with-input-file "test.txt" (lambda (port) (assert:equal "read input" (read port) 'ok))) ;(write "done with input") ;; TODO: (delete-file "test.out") ;; TODO: (delete-file "test.txt") ;; END I/O ;; Macros (define-syntax test (er-macro-transformer (lambda (expr rename compare) (cond ((null? (cdr expr)) #t) ((null? (cddr expr)) (cadr expr)) (else (list (rename 'if) (cadr expr) (cons (rename 'and) (cddr expr)) #f)))))) (define-syntax test2 (er-macro-transformer (lambda (expr rename compare) (test 1 2) (test 1 2 3) (and ''test ''test2)))) (define-syntax indirect-def (syntax-rules () ( (indirect-def x y) (begin (define z y) (define x z) ) ) ) ) (define x 42) (assert:equal "macro: test2" (test2 1 2 3) 'test2) (assert:equal "macro: test" (test 1 2 3) 3) (assert:equal "macro: eval test" (eval '(test 1 2 x)) x) (assert:equal "macro: define syntax indirect-def" (indirect-def a 3) '(3)) (assert:equal "macro: let syntax indirect-def" (let-syntax ( (indirect-def (syntax-rules () ( (indirect-def x y) (begin (define z y) (define x z) ) ) ) ) ) (indirect-def a 3) a) '3) ;; END macros ;; Record types (define-record-type <pare> (kons x y) pare? (x kar set-kar!) (y kdr)) (define-record-type <point> (point x y) point? (x get-x set-x!) (y get-y set-y!) (z get-z set-z!)) (assert:equal "Records predicate (t)" (pare? (kons 1 2)) #t) (assert:equal "Records predicate (f)" (pare? (cons 1 2)) #f) (assert:equal "Records kar" (kar (kons 1 2)) 1) (assert:equal "Records kdr" (kdr (kons 1 2)) 2) (assert:equal "Records setter" (let ((k (kons 1 2))) (set-kar! k 3) (kar k)) 3) (assert:equal "Record type predicate (t)" (record? (kons 1 2)) #t) (assert:equal "Record type predicate (f)" (record? (cons 1 2)) #f) (assert:equal "Record type field not in constructor (f)" (get-z (point 1 2)) #f) (let ((p (point 1 2))) (set-z! p 99) (assert:equal "Record type get field not in constructor" (get-z p) 99)) ;; END records ;; Lazy evaluation (assert:equal "Basic lazy" (force (delay (+ 1 2))) 3) (assert:equal "Lazy test #2" (let ((p (delay (+ 1 2)))) (list (force p) (force p))) '(3 3)) ((lambda () (define integers (letrec ((next (lambda (n) (delay (cons n (next (+ n 1))))))) (next 0))) (define head (lambda (stream) (car (force stream)))) (define tail (lambda (stream) (cdr (force stream)))) (assert:equal "Lazy #3" (head (tail (tail integers))) 2))) ; TODO: use display, output without surrounding quotes (display (list *num-passed* "tests passed with no errors")) (newline) ;;
true
bd168084641675c217c8f6f08803fb58ffd15e88
a2f4977a74580743fc52832321a65d72074f265c
/meroonet.scm
a6721e6c7c81ee598cfdc8b0829f9c6f1dba2e48
[]
no_license
jacobstern/lisp-book
eab395f6255d71248e04a7b629063817b983022e
c2a3a076a3bc7a717844fc05349ea0a4051c62f6
refs/heads/master
2022-02-18T15:21:06.163648
2019-08-12T05:51:00
2019-08-12T05:51:00
198,126,222
0
0
null
null
null
null
UTF-8
Scheme
false
false
215
scm
meroonet.scm
;;; Adapted from https://github.com/appleby/Lisp-In-Small-Pieces (define-macro (define-meroonet-macro call . body) `(define-macro ,call . ,body) ) (define meroonet-error error) (load "./meroonet/meroonet.scm")
false
9b20d212081f89cae24bf8bca14c4555987404bd
d8bdd07d7fff442a028ca9edbb4d66660621442d
/scam/tests/10-scheme/00-base/math/misc.scm
a39071e78b6990c23d3c8d004c0866948997ebd2
[]
no_license
xprime480/scam
0257dc2eae4aede8594b3a3adf0a109e230aae7d
a567d7a3a981979d929be53fce0a5fb5669ab294
refs/heads/master
2020-03-31T23:03:19.143250
2020-02-10T20:58:59
2020-02-10T20:58:59
152,641,151
0
0
null
null
null
null
UTF-8
Scheme
false
false
247
scm
misc.scm
(import (only (scheme base) + - * /) (only (scheme inexact) nan?) (test narc)) (narc-label "Math Miscellaneous") (narc-expect (16/5 (+ (* 2 3) (/ 1 5) (- 3))) (#t (nan? (+ (* 2 3) (/ 1 (+ +nan.0 -5)) (- 3))))) (narc-report)
false
2f90740afb1b17bf702af498f10d02bdf07b2372
ae76253c0b7fadf8065777111d3aa6b57383d01b
/chap2/exec-2.14.ss
fddb7f0abec9105a470d53011cc244add5b4dceb
[]
no_license
cacaegg/sicp-solution
176995237ad1feac39355f0684ee660f693b7989
5bc7df644c4634adc06355eefa1637c303cf6b9e
refs/heads/master
2021-01-23T12:25:25.380872
2014-04-06T09:35:15
2014-04-06T09:35:15
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,122
ss
exec-2.14.ss
(define (make-interval a b) (cons a b)) (define (lower-bound i) (car i)) (define (upper-bound i) (cdr i)) (define (width i) (/ (- (upper-bound i) (lower-bound i)) 2.0)) (define (sub-interval a b) (make-interval (- (lower-bound a) (lower-bound b)) (- (upper-bound a) (upper-bound b)))) (define (add-interval a b) (make-interval (+ (lower-bound a) (lower-bound b)) (+ (upper-bound a) (upper-bound b)))) (define (mul-interval x y) (let ((lx (lower-bound x)) (ux (upper-bound x)) (ly (lower-bound y)) (uy (upper-bound y))) (cond ((and (>= lx 0) (>= ux 0) (>= ly 0) (>= uy 0)) ; x++ y++ (make-interval (* lx ly) (* ux uy))) ((and (< lx 0) (>= ux 0) (>= ly 0) (>= uy 0)) (make-interval (* lx uy) (* ux uy))) ; x+- y++ ((and (< lx 0) (< ux 0) (>= ly 0) (>= uy 0)) (make-interval (* lx uy) (* ly ux))) ; x-- y++ ((and (>= lx 0) (>= ux 0) (< ly 0) (>= uy 0)) (make-interval (* ly ux) (* ux uy))) ; x++ y+- ((and (>= lx 0) (>= ux 0) (< ly 0) (< uy 0)) (make-interval (* ux ly) (* lx uy))) ; x++ y-- ((and (< lx 0) (>= ux 0) (< ly 0) (>= uy 0)) ; x+- y+- (let ((p1 (* lx ly)) (p2 (* lx uy)) (p3 (* ux uy)) (p4 (* ux ly))) (make-interval (min p2 p4) (max p1 p3)))) ((and (< lx 0) (< ux 0) (< ly 0) (< uy 0)) (make-interval (* ux uy) (* lx ly))) ; x-- y-- ((and (< lx 0) (< ux 0) (< ly 0) (>= uy 0)) (make-interval (* lx uy) (* lx ly))) ; x-- y+- ((and (< lx 0) (>= ux 0) (< ly 0) (< uy 0)) (make-interval (* ly ux) (* ly lx)))))) ; x+- y-- (define (div-interval x y) (let ((uby (upper-bound y)) (lby (lower-bound y))) (if (or (= uby 0) (= lby 0)) "Divide by Zero" (mul-interval x (make-interval (/ 1.0 (upper-bound y)) (/ 1.0 (lower-bound y))))))) ; p is percent. 1 for 100%, 0.1 for 10% (define (make-center-percent c p) (make-interval (- c (* c p)) (+ c (* c p)))) (define (center i) (/ (+ (upper-bound i) (lower-bound i)) 2.0)) (define (percent i) (/ (- (center i) (lower-bound i)) (center i))) (define (par1 r1 r2) (div-interval (mul-interval r1 r2) (add-interval r1 r2))) (define (par2 r1 r2) (let ((one (make-interval 1 1))) (div-interval one (add-interval (div-interval one r1) (div-interval one r2))))) (let ((i1 (make-center-percent 20000 0.00001)) (i2 (make-center-percent 40000 0.00002))) (div-interval i1 i1)) ; Even a/a, still can't get [1, 1] (let ((i1 (make-center-percent 20000 0.00001)) (i2 (make-center-percent 40000 0.00002))) (div-interval i1 i2)) (let ((i1 (make-center-percent 20000 0.00001)) (i2 (make-center-percent 40000 0.00002))) (par1 i1 i2)) (let ((i1 (make-center-percent 20000 0.00001)) (i2 (make-center-percent 40000 0.00002))) (par2 i1 i2))
false
8dce1bf8d0d420389494d3995f5e6b5485719a10
b21f59bbd4faf31159321e8d26eb170f9aa410c0
/2.5-system-with-generic-operations/represent-numbers-as-scheme-numbers.scm
5452f5be31db5e4d2587a702d93b618ff5ecbe7a
[]
no_license
furkhat/sicp-practice
4774048022718c165e0ec35602bb192241d9f97a
301fea9ee4d6cea895cec4b618c664b48c2106f0
refs/heads/master
2021-06-08T06:01:01.760120
2016-12-11T08:11:34
2016-12-11T08:11:34
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
669
scm
represent-numbers-as-scheme-numbers.scm
(load "the-system.scm") ; redefine type-tag, contents and attach-tag ; so the system will work as before except that ; ordinary numbers are represented as Scheme numbers ; rather then pairs with symbol (define (type-tag x) (cond ((number? x) 'scheme-number) ((pair? x) (car x)) (else (error "Wrong argument")))) (define (contents x) (cond ((number? x) x) ((pair? x) (cdr x)) (else (error "Wrong argument")))) (define (attach-tag type-tag contents) (if (number? contents) contents (cons type-tag contents))) (install-scheme-number-package) (define x (make-scheme-number 1)) (define y (make-scheme-number 2)) (add x y)
false
51d4bbc56f13f30ac7447dfa34cf8227878293e8
eb2cb6452e5690a3e7475e342c6698c855b10d70
/work.scm
8bf258ebf97217452141eadca597210569af2918
[ "Boehm-GC", "X11-distribute-modifications-variant", "BSD-2-Clause" ]
permissive
david135/mosh-scheme
67375fcef15209e0af1dae6df937f2c268bf52b0
8247d45bc34c8b503047600b9f2eacb5443aaa83
refs/heads/master
2021-01-15T17:07:12.792938
2009-11-23T08:42:02
2009-11-23T08:42:02
32,497,499
0
0
null
null
null
null
UTF-8
Scheme
false
false
59
scm
work.scm
(import (rnrs) (foreign databases sqlite sizeof))
false
75cc701f0357bbf7c22b4bf4dba91d2d9414a470
b9eb119317d72a6742dce6db5be8c1f78c7275ad
/double-dummy-solver/filler.ss
5d00d549ef0e0da3733d1793fd91584426569dd3
[]
no_license
offby1/doodles
be811b1004b262f69365d645a9ae837d87d7f707
316c4a0dedb8e4fde2da351a8de98a5725367901
refs/heads/master
2023-02-21T05:07:52.295903
2022-05-15T18:08:58
2022-05-15T18:08:58
512,608
2
1
null
2023-02-14T22:19:40
2010-02-11T04:24:52
Scheme
UTF-8
Scheme
false
false
12,090
ss
filler.ss
#! /bin/sh #| Hey Emacs, this is -*-scheme-*- code! #$Id$ exec mzscheme --require "$0" --main -- ${1+"$@"} |# #lang scheme (require (only-in rnrs/base-6 assert) (only-in (lib "list.ss") sort) (only-in (lib "1.ss" "srfi") every first fold fourth second third ) (lib "cmdline.ss") (lib "trace.ss") (only-in "card.ss" *suits* card-suit ) (prefix-in dds: "dds.ss") "deck.ss" "fill-out-hands.ss" (planet "shuffle.ss" ("offby1" "offby1.plt")) "hand.ss" (only-in "history.ss" trick-summaries history-empty? history-latest-trick history-length hi:trick-complete? make-history whose-turn) "run-for-a-while.ss" (except-in "trick.ss" whose-turn) "zprintf.ss") ;; given a history and partially-known hands, generate a random ;; conforming hand, then figure the best card for the first player. (define (choose-card history handset max-lookahead) (dds:choose-card history (map sorted (fill-out-hands handset history)) max-lookahead #f)) (define (mask-out handset me dummy opening-lead?) (assert ((lambda (thing) (memq thing *seats*)) me)) (assert ((lambda (thing) (memq thing *seats*)) dummy)) ;; assume we're given a handset where we can see all the cards. ;; if me and the dummy are the same, "mask off" (i.e., replace ;; with ? hands) the odd-numbered elements -- namely the ;; opponents. (cond (opening-lead? (list (list-ref handset 0) (make-hand '? (seat (list-ref handset 1))) (make-hand '? (seat (list-ref handset 2))) (make-hand '? (seat (list-ref handset 3))))) ((eq? me dummy) (list (list-ref handset 0) (make-hand '? (seat (list-ref handset 1))) (list-ref handset 2) (make-hand '? (seat (list-ref handset 3))))) (else ;; udderwise, mask off the two that are neither me nor the ;; dummy. (map (lambda (h) (if (or (eq? me (seat h)) (eq? dummy (seat h))) h (make-hand '? (seat h)))) handset)))) ;(trace mask-out) (define *seconds-per-card* (make-parameter 5 ; five seconds seems about ; right -- since there are 52 ; cards in a game, 260 seconds ; is 4.3 minutes; add some ; time for the auction, and ; you should be in the ; neighborhood of seven ; minutes, which is typical ; for a hand in a duplicate ; club game )) (define *lookahead* (make-parameter 2)) (define *num-hands* (make-parameter 1)) (define *dummy* (make-parameter #f (lambda (d) (unless (memq d *seats*) (raise-mismatch-error '*dummy* (format "wanted one of ~d, not " *seats*) d)) d))) (define (choose-best-card-no-peeking history hands max-lookahead quick-and-dirty?) (define counts-by-choice (make-hash)) (define me (seat (car hands))) (let* ( ;; just for fun -- make e/w always play stupidly. That way, ;; if we find that n/w aren't regularly beating them, we'll ;; know that something is terribly wrong. Conversely, if n/w ;; regularly beat them, I haven't been wasting my time :-) (stupid? (member me '(e w))) (hands (mask-out hands me (*dummy*) (history-empty? history))) (fallback (dds:choose-card history hands 0 #t))) (p "~a ~aplays ~a~%" me (if stupid? "stupidly " "") (if (or stupid? quick-and-dirty?) fallback (begin (for-each (lambda (c) (hash-set! counts-by-choice c (add1 (hash-ref counts-by-choice c 0)))) (map car (run-for-a-while (lambda () (choose-card history hands max-lookahead)) (*seconds-per-card*) (lambda (seconds-remaining) (fprintf (current-error-port) ".") (flush-output (current-error-port))) ))) (let ((alist (hash-map counts-by-choice cons))) (if (null? alist) (begin (fprintf (current-error-port) "!") (flush-output (current-error-port)) fallback) (let* ((sorted (sort alist (lambda (a b) (> (cdr a) (cdr b))))) (best (first sorted))) (when (< 1 (length sorted)) (let ((2nd-best (second sorted))) (printf "(Second-best choice was ~a, at ~a%) " (car 2nd-best) (round (* 100.0 (/ (cdr 2nd-best) (cdr best))))))) (car best))))))) )) ;(trace choose-best-card-no-peeking) (command-line "filler" (current-command-line-arguments) (once-each (("-s" "--seconds-per-card") spc "How long to think about each card" (*seconds-per-card* (string->number spc))) (("-l" "--lookahead") ml "Maximum number of tricks to look ahead when predicting" (*lookahead* (string->number ml))) (("-n" "--number-of-hands") h "Number of hands to play" (*num-hands* (string->number h))) (("-r" "--rng") vec "pseudo-random-generator vector like #6(1888977131 3014825601 3849035281 163056249 698545751 4293483726)" (current-pseudo-random-generator (vector->pseudo-random-generator (read (open-input-string vec))))))) (printf "rng state: ~s~%" (pseudo-random-generator->vector (current-pseudo-random-generator))) ;; list of hands => (list seat-symbol suit-sym-or-#f integer) (define (plausible-trump-suit hands) ;; (list hand hand) => (seat-sym suit-symbol integer) (define (best-suit h1 h2) ;; alist alist -> alist (define (add-counts c1 c2) (let loop ((c1 c1) (c2 c2) (result '())) (if (null? c1) result (loop (cdr c1) (cdr c2) (let ((p1 (car c1)) (p2 (car c2))) (cons (cons (car p1) (+ (cdr p1) (cdr p2))) result)))))) (let* ((cbs1 (counts-by-suit h1)) (cbs2 (counts-by-suit h2)) (counts-by-suit-both-hands (add-counts cbs1 cbs2)) (best (fold (lambda (suit-count-pair best-so-far) (if (< (cdr suit-count-pair) (cdr best-so-far)) best-so-far suit-count-pair)) (car counts-by-suit-both-hands) counts-by-suit-both-hands))) (cons (if (< (cdr (assoc (car best) cbs1)) (cdr (assoc (car best) cbs2))) (seat h2) (seat h1)) (list (car best) (cdr best))))) (let ((our-max (best-suit (list-ref hands 0) (list-ref hands 2))) (their-max (best-suit (list-ref hands 1) (list-ref hands 3)) )) (let ((random-choice (if (zero? (random 2)) our-max their-max))) (cond ((and (= 7 (third our-max) (third their-max))) (list (first random-choice) #f 7)) ;; both hands are square? Then notrump. TODO: pick ;; the strongest hand, not just our-max ((< (third our-max) (third their-max)) their-max) ((= (third our-max) (third their-max)) random-choice) (else our-max))))) (define (display-side-by-side l1 l2 padding port) (port-count-lines! port) (for-each (lambda (s1 s2) (display s1 port) (let-values (((line col pos) (port-next-location port))) (display (make-string (- padding col) #\space) port)) (display s2 port) (newline port)) l1 l2)) (*shaddap* #t) (let loop ((hands-played 0)) (when (< hands-played (*num-hands*)) (let* ((hands (deal (shuffle *deck*) (map (lambda (s) (make-hand '() s)) *seats*))) (pts (plausible-trump-suit hands)) (me (with-seat-circle (first pts) (lambda (circ) (list-ref circ 1))))) (parameterize ((*dummy* (with-seat-circle me (lambda (circ) (list-ref circ 1)))) (*trump-suit* (second pts))) (printf "~a~%Trump suit is ~a" #\page (*trump-suit*)) (printf (if (*trump-suit*) " (of which declarer's side has ~a)" "; declarer's longest suit has ~a cards") (third pts)) (printf "~%~s makes the opening lead; dummy is ~a~%" me (*dummy*))(flush-output) (printf "The hands are:~%") (let ((hands (rotate-until hands (lambda (hands) (eq? (seat (first hands)) (*dummy*)))))) (for-each (lambda (s) (display (string-append (make-string 30 #\space) s) (current-output-port)) (newline (current-output-port))) (->stringlist (first hands))) (display-side-by-side (->stringlist (fourth hands)) (->stringlist (second hands)) 60 (current-output-port)) (for-each (lambda (s) (display (string-append (make-string 30 #\space) s) (current-output-port)) (newline (current-output-port))) (->stringlist (third hands)))) (flush-output (current-output-port)) (dds:play-loop (make-history me) hands (lambda (history hands max-lookahead quick-and-dirty?) ;; have it tell me what it's thinking when this hand plays ;; to this trick, but shaddap otherwise. (parameterize ((*shaddap* (or #t (not (and (= 2 (history-length history)) (eq? 'e (whose-turn history))))))) (choose-best-card-no-peeking history hands max-lookahead quick-and-dirty?))) ;; TODO: find a way to adjust this value so that it's as ;; large as possible while still not taking too long. Thus ;; on very fast machines we can look ahead further. (*lookahead*) (lambda (history hands) (when (and (not (history-empty? history)) (hi:trick-complete? history)) (let ((t (history-latest-trick history))) (printf "===== ~a won trick ~a with the ~a~%" (cdr (winner/int t)) (history-length history) (car (winner/int t))) (flush-output))) #f) (lambda (history hands) (printf "We're done.~%~aSuits taken by seat: ~a~%" history (trick-summaries history)))) (loop (add1 hands-played))))))
false
b06f43e06eb24f8a8240f68a0e2cf3a8391ba306
6bd63be924173b3cf53a903f182e50a1150b60a8
/4.2.scm
6a1a4deed317910faaf569d6adeba34a7117b7e1
[]
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
521
scm
4.2.scm
; things worth doing typically take time and effort. ; 4.2 ; a) ; can't fine 'define ; b) (define (eval exp env) (cond ((self-evaluating? exp) exp) ((call? exp) (apply (eval (operator exp) (env) (list-of-values (operands exp) env)))) (else (error "Unknown expression")))) (define (call? exp) (if (pair? exp) (equal? (car exp) 'call) false)) (define (call-operator exp) (cadr exp)) (define (call-operands exp) (cddr exp))
false
3395104bbba7dde0e826aa8402ed68208c954806
de82217869618b0a975e86918184ecfddf701172
/draft/bytes/bytes-proto.sch
503b2c27eaeaae43689e52f6edd1d61e9d309006
[]
no_license
schemedoc/r6rs
6b4ef7fd87d8883d6c4bcc422b38b37f588e20f7
0009085469e47df44068873f834a0d0282648750
refs/heads/master
2021-06-18T17:44:50.149253
2020-01-04T10:50:50
2020-01-04T10:50:50
178,081,881
5
0
null
null
null
null
UTF-8
Scheme
false
false
10,038
sch
bytes-proto.sch
; Bytes objects ; Copyright (C) Michael Sperber (2005). All Rights Reserved. ; ; 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. ; Modified by William D Clinger, beginning 2 August 2006. ; ; Calls to many of these procedures should be compiled ; into a short sequence of machine instructions. ; Many of the definitions below could be made faster ; by inlining help procedures and unrolling loops, ; but that would not be as fast as generating machine ; code. ; ; This file defines all of the operations on bytes objects ; except for those defined in bytes-core.sch and in bytes-ieee.sch. ; (library bytes-proto (export endianness native-endianness bytes? make-bytes bytes-length bytes-u8-ref bytes-s8-ref bytes-u8-set! bytes-s8-set! bytes-uint-ref bytes-sint-ref bytes-uint-set! bytes-sint-set! bytes-u16-ref bytes-s16-ref bytes-u16-set! bytes-s16-set! bytes-u16-native-ref bytes-s16-native-ref bytes-u16-native-set! bytes-s16-native-set! bytes-u32-ref bytes-s32-ref bytes-u32-set! bytes-s32-set! bytes-u32-native-ref bytes-s32-native-ref bytes-u32-native-set! bytes-s32-native-set! bytes-u64-ref bytes-s64-ref bytes-u64-set! bytes-s64-set! bytes-u64-native-ref bytes-s64-native-ref bytes-u64-native-set! bytes-s64-native-set! bytes=? bytes-copy! bytes-copy bytes->u8-list u8-list->bytes bytes->uint-list bytes->sint-list uint-list->bytes sint-list->bytes) (import (r6rs base) bytes-core) ; Help procedures; not exported. (define (u8->s8 octet) (if (> octet 127) (- octet 256) octet)) (define (s8->u8 val) (if (negative? val) (+ val 256) val)) (define (make-uint-ref size) (lambda (bytes k endianness) (bytes-uint-ref bytes k endianness size))) (define (make-sint-ref size) (lambda (bytes k endianness) (bytes-sint-ref bytes k endianness size))) (define (make-uint-set! size) (lambda (bytes k n endianness) (bytes-uint-set! bytes k n endianness size))) (define (make-sint-set! size) (lambda (bytes k n endianness) (bytes-sint-set! bytes k n endianness size))) (define (make-ref/native base base-ref) (lambda (bytes index) (ensure-aligned index base) (base-ref bytes index (native-endianness)))) (define (make-set!/native base base-set!) (lambda (bytes index val) (ensure-aligned index base) (base-set! bytes index val (native-endianness)))) (define (ensure-aligned index base) (if (not (zero? (bytes:mod index base))) (error "non-aligned bytes access" index base))) (define (make-bytes->int-list bytes-ref) (lambda (b endness size) (let ((ref (lambda (i) (bytes-ref b i endness size))) (length (bytes-length b))) (let loop ((i 0) (r '())) (if (>= i length) (reverse r) (loop (+ i size) (cons (ref i) r))))))) (define (make-int-list->bytes bytes-set!) (lambda (l endness size) (let* ((bytes (make-bytes (* size (length l)))) (setter! (lambda (i n) (bytes-set! bytes i n endness size)))) (let loop ((i 0) (l l)) (if (null? l) bytes (begin (setter! i (car l)) (loop (+ i size) (cdr l)))))))) ; Exported syntax and procedures. (define-syntax endianness (syntax-rules (little big) ((endianness little) 'little) ((endianness big) 'big))) (define (bytes-s8-ref b k) (u8->s8 (bytes-u8-ref b k))) (define (bytes-s8-set! b k val) (bytes-u8-set! b k (s8->u8 val))) (define (bytes-uint-ref bytes index endness size) (case endness ((big) (do ((i 0 (+ i 1)) (result 0 (+ (* 256 result) (bytes-u8-ref bytes (+ index i))))) ((>= i size) result))) ((little) (do ((i (- size 1) (- i 1)) (result 0 (+ (* 256 result) (bytes-u8-ref bytes (+ index i))))) ((< i 0) result))) (else (error 'bytes-uint-ref "Invalid endianness: " endness)))) (define (bytes-sint-ref bytes index endness size) (let* ((high-byte (bytes-u8-ref bytes (if (eq? endness 'big) index (+ index size -1)))) (uresult (bytes-uint-ref bytes index endness size))) (if (> high-byte 127) (- uresult (expt 256 size)) uresult))) ; FIXME: Some of these procedures may not do enough range checking. (define (bytes-uint-set! bytes index val endness size) (case endness ((little) (do ((i 0 (+ i 1)) (val val (bytes:div val 256))) ((>= i size) (unspecified)) (bytes-u8-set! bytes (+ index i) (bytes:mod val 256)))) ((big) (do ((i (- size 1) (- i 1)) (val val (bytes:div val 256))) ((< i 0) (unspecified)) (bytes-u8-set! bytes (+ index i) (bytes:mod val 256)))) (else (error 'bytes-uint-set! "Invalid endianness: " endness)))) ; FIXME: incorrect. (define (bytes-sint-set! bytes index val endness size) (bytes-uint-set! bytes index vala endness size)) (define bytes-u16-ref (make-uint-ref 2)) (define bytes-u16-set! (make-uint-set! 2)) (define bytes-s16-ref (make-sint-ref 2)) (define bytes-s16-set! (make-sint-set! 2)) (define bytes-u16-native-ref (make-ref/native 2 bytes-u16-ref)) (define bytes-u16-native-set! (make-set!/native 2 bytes-u16-set!)) (define bytes-s16-native-ref (make-ref/native 2 bytes-s16-ref)) (define bytes-s16-native-set! (make-set!/native 2 bytes-s16-set!)) (define bytes-u32-ref (make-uint-ref 4)) (define bytes-u32-set! (make-uint-set! 4)) (define bytes-s32-ref (make-sint-ref 4)) (define bytes-s32-set! (make-sint-set! 4)) (define bytes-u32-native-ref (make-ref/native 4 bytes-u32-ref)) (define bytes-u32-native-set! (make-set!/native 4 bytes-u32-set!)) (define bytes-s32-native-ref (make-ref/native 4 bytes-s32-ref)) (define bytes-s32-native-set! (make-set!/native 4 bytes-s32-set!)) (define bytes-u64-ref (make-uint-ref 8)) (define bytes-u64-set! (make-uint-set! 8)) (define bytes-s64-ref (make-sint-ref 8)) (define bytes-s64-set! (make-sint-set! 8)) (define bytes-u64-native-ref (make-ref/native 8 bytes-u64-ref)) (define bytes-u64-native-set! (make-set!/native 8 bytes-u64-set!)) (define bytes-s64-native-ref (make-ref/native 8 bytes-s64-ref)) (define bytes-s64-native-set! (make-set!/native 8 bytes-s64-set!)) (define (bytes=? b1 b2) (if (or (not (bytes? b1)) (not (bytes? b2))) (error 'bytes=? "Illegal arguments: " b1 b2) (let ((n1 (bytes-length b1)) (n2 (bytes-length b2))) (and (= n1 n2) (do ((i 0 (+ i 1))) ((or (= i n1) (not (= (bytes-u8-ref b1 i) (bytes-u8-ref b2 i)))) (= i n1))))))) ; FIXME: should use word-at-a-time when possible (define (bytes-copy! source source-start target target-start count) (if (>= source-start target-start) (do ((i 0 (+ i 1))) ((>= i count) (unspecified)) (bytes-u8-set! target (+ target-start i) (bytes-u8-ref source (+ source-start i)))) (do ((i (- count 1) (- i 1))) ((< i 0) (unspecified)) (bytes-u8-set! target (+ target-start i) (bytes-u8-ref source (+ source-start i)))))) (define (bytes-copy b) (let* ((n (bytes-length b)) (b2 (make-bytes n))) (bytes-copy! b 0 b2 0 n) b2)) (define (bytes->u8-list b) (let ((n (bytes-length b))) (do ((i (- n 1) (- i 1)) (result '() (cons (bytes-u8-ref b i) result))) ((< i 0) result)))) (define (bytes->s8-list b) (let ((n (bytes-length b))) (do ((i (- n 1) (- i 1)) (result '() (cons (bytes-s8-ref b i) result))) ((< i 0) result)))) (define (u8-list->bytes vals) (let* ((n (length vals)) (b (make-bytes n))) (do ((vals vals (cdr vals)) (i 0 (+ i 1))) ((null? vals)) (bytes-u8-set! b i (car vals))) b)) (define (s8-list->bytes l) (let* ((n (length vals)) (b (make-bytes n))) (do ((vals vals (cdr vals)) (i 0 (+ i 1))) ((null? vals)) (bytes-s8-set! b i (car vals))) b)) (define bytes->uint-list (make-bytes->int-list bytes-uint-ref)) (define bytes->sint-list (make-bytes->int-list bytes-sint-ref)) (define uint-list->bytes (make-int-list->bytes bytes-uint-set!)) (define sint-list->bytes (make-int-list->bytes bytes-sint-set!)) ; FIXME: not implemented yet (define (bytes-ieee-single-native-ref bytes k) ...) (define (bytes-ieee-single-ref bytes k endianness) ...) (define (bytes-ieee-double-native-ref bytes k) ...) (define (bytes-ieee-double-ref bytes k endianness) ...) (define (bytes-ieee-single-native-set! bytes k x) ...) (define (bytes-ieee-single-set! bytes k x endianness) ...) (define (bytes-ieee-double-native-set! bytes k x) ...) (define (bytes-ieee-double-set! bytes k x endianness) ...) )
true
6646e585fa86773112b6b88928d9f7b8f2dc6f73
a6a1c8eb973242fd2345878e5a871a89468d4080
/3.04.scm
549425040e3ede357929e66ef9dda4a90c655ac0
[]
no_license
takkyuuplayer/sicp
ec20b6942a44e48d559e272b07dc8202dbb1845a
37aa04ce141530e6c9803c3c7122016d432e924b
refs/heads/master
2021-01-17T07:43:14.026547
2017-02-22T03:40:07
2017-02-22T03:40:07
15,771,479
1
1
null
null
null
null
UTF-8
Scheme
false
false
1,669
scm
3.04.scm
(use slib) (require 'trace) (define (make-account balance password) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount)) balance) (define (dispatch m) (cond ((eq? m 'withdraw) withdraw) ((eq? m 'deposit) deposit) (else (error "Unknown request -- MAKE-ACCOUNT" m)))) (define error-count 0) (define (password-check-and-dispatch p m) (if (eq? p password) (begin (set! error-count 0) (dispatch m) ) (begin (set! error-count (+ error-count 1)) (if (= error-count 7) (error "calling-the-cops...") (lambda (args...) "Incorrect password")) ) ) ) password-check-and-dispatch) (define acc (make-account 100 'secret-password)) (print ((acc 'secret-password 'withdraw) 40)) (print ((acc 'some-other-password 'withdraw) 1)) (print ((acc 'some-other-password 'withdraw) 2)) (print ((acc 'some-other-password 'withdraw) 3)) (print ((acc 'some-other-password 'withdraw) 4)) (print ((acc 'some-other-password 'withdraw) 5)) (print ((acc 'some-other-password 'withdraw) 6)) (print ((acc 'secret-password 'withdraw) 40)) (print ((acc 'some-other-password 'withdraw) 1)) (print ((acc 'some-other-password 'withdraw) 2)) (print ((acc 'some-other-password 'withdraw) 3)) (print ((acc 'some-other-password 'withdraw) 4)) (print ((acc 'some-other-password 'withdraw) 5)) (print ((acc 'some-other-password 'withdraw) 6)) (print ((acc 'some-other-password 'withdraw) 7))
false
0bf8e38fef7c56a8839f363385f3d331f544c908
b1939ca2ae84f5c82cc3bbbe04b3b75e4b2d421f
/rosettacode/rle.scm
7b3b11e1786455fe687d992b4881ec86bda9ec9c
[]
no_license
orchid-hybrid/scheme-testing-code
d47f2b08087a4130c808043100890d8857b27753
b5afbebb4b6f04f95b18ed39e1bf92658b34db4a
refs/heads/master
2016-09-05T16:36:09.782517
2014-09-20T02:15:37
2014-09-20T02:15:37
24,111,238
3
1
null
null
null
null
UTF-8
Scheme
false
false
756
scm
rle.scm
(define (run-length-decode v) (apply string-append (map (lambda (p) (make-string (car p) (cdr p))) v))) (define (run-length-encode s) (let ((n (string-length s))) (let loop ((i (- n 2)) (c (string-ref s (- n 1))) (k 1) (v '())) (if (negative? i) (cons (cons k c) v) (let ((x (string-ref s i))) (if (char=? c x) (loop (- i 1) c (+ k 1) v) (loop (- i 1) x 1 (cons (cons k c) v)))))))) (run-length-encode "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") ; ((12 . #\W) (1 . #\B) (12 . #\W) (3 . #\B) (24 . #\W) (1 . #\B) (14 . #\W)) (run-length-decode '((12 . #\W) (1 . #\B) (12 . #\W) (3 . #\B) (24 . #\W) (1 . #\B) (14 . #\W))) ; "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
false
8f96164ca49c625b4568413229f66010e41a65bf
4bd59493b25febc53ac9e62c259383fba410ec0e
/Scripts/Task/reduced-row-echelon-form/scheme/reduced-row-echelon-form-1.ss
502bb8722f927f843aea00de87b3a15257869577
[]
no_license
stefanos1316/Rosetta-Code-Research
160a64ea4be0b5dcce79b961793acb60c3e9696b
de36e40041021ba47eabd84ecd1796cf01607514
refs/heads/master
2021-03-24T10:18:49.444120
2017-08-28T11:21:42
2017-08-28T11:21:42
88,520,573
5
1
null
null
null
null
UTF-8
Scheme
false
false
1,906
ss
reduced-row-echelon-form-1.ss
(define (reduced-row-echelon-form matrix) (define (clean-down matrix from-row column) (cons (car matrix) (if (zero? from-row) (map (lambda (row) (map - row (map (lambda (element) (/ (* element (list-ref row column)) (list-ref (car matrix) column))) (car matrix)))) (cdr matrix)) (clean-down (cdr matrix) (- from-row 1) column)))) (define (clean-up matrix until-row column) (if (zero? until-row) matrix (cons (map - (car matrix) (map (lambda (element) (/ (* element (list-ref (car matrix) column)) (list-ref (list-ref matrix until-row) column))) (list-ref matrix until-row))) (clean-up (cdr matrix) (- until-row 1) column)))) (define (normalise matrix row with-column) (if (zero? row) (cons (map (lambda (element) (/ element (list-ref (car matrix) with-column))) (car matrix)) (cdr matrix)) (cons (car matrix) (normalise (cdr matrix) (- row 1) with-column)))) (define (repeat procedure matrix indices) (if (null? indices) matrix (repeat procedure (procedure matrix (car indices) (car indices)) (cdr indices)))) (define (iota start stop) (if (> start stop) (list) (cons start (iota (+ start 1) stop)))) (let ((indices (iota 0 (- (length matrix) 1)))) (repeat normalise (repeat clean-up (repeat clean-down matrix indices) indices) indices)))
false
e4a0676d87d5ddd0b78b27d5ddc3d904be264702
2bcf33718a53f5a938fd82bd0d484a423ff308d3
/programming/sicp/ch2/ex-2.11.scm
1b4a9d9c0e2449f8eec6dd54364c61373e05c350
[]
no_license
prurph/teach-yourself-cs
50e598a0c781d79ff294434db0430f7f2c12ff53
4ce98ebab5a905ea1808b8785949ecb52eee0736
refs/heads/main
2023-08-30T06:28:22.247659
2021-10-17T18:27:26
2021-10-17T18:27:26
345,412,092
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,449
scm
ex-2.11.scm
#lang scheme ;; https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-14.html#%_thm_2.11 ;; The cases are the permutations of each interval being entirely below zero, ;; entirely above zero, or spanning zero. ;; When ;; The case that requires multiple multiplications is the case where both span ;; zero. (define )) (define (mul-interval x y) (let ((xl (lower-bound x)) (xu (upper-bound x)) (yl (lower-bound y)) (yu (upper-bound y)) (xpos? (> 0 xl)) (xneg? (< 0 xu)) (ypos? (> 0 yl)) (yneg? (< 0 yu)))) (cond (xpos? (cond (ypos? (make-interval (* xl yl) (* xu yu))) (yneg? (make-interval (* xu yl) (* xl yu))) ;; x is strictly positive, but y spans zero, so the lower ;; and upper bounds are the biggest x (xu)) times the ;; corresponding yl/yu (else (make-interval (* xu yl) (* xu yu))))) (xneg? (cond (ypos? (make-interval (* xl yu) (* xu yl))) (yneg? (make-interval (* xu yu) (* xl yl))) (else (make-interval (* xl yu) (* xl yl)))))) (else (cond (ypos? (make-interval (* xl yu) (* xu yu))) (yneg? (make-interval (* xu yl) (* xl yl))) (else (make-interval (min (* xl yu) (* xu yl)) (max (* xl yl) (* xu yu)))))))
false
45dde776e2d40c678f82e97d199944360e94d580
a8216d80b80e4cb429086f0f9ac62f91e09498d3
/lib/chibi/char-set/full.sld
99aa740d325054bedc6462d17e2225f93e591c73
[ "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
455
sld
full.sld
(define-library (chibi char-set full) (import (chibi) (chibi iset base) (chibi char-set base)) (export char-set:lower-case char-set:upper-case char-set:title-case char-set:letter char-set:digit char-set:letter+digit char-set:graphic char-set:printing char-set:whitespace char-set:iso-control char-set:punctuation char-set:symbol char-set:hex-digit char-set:blank) (include "full.scm"))
false
fa0f5b38da9f68027c41229755b9f15948ed7fa2
6488db22a3d849f94d56797297b2469a61ad22bf
/bind/bind.meta
dbac33c93ad69aa5adb21594c7ef9cc75c9c2476
[]
no_license
bazurbat/chicken-eggs
34d8707cecbbd4975a84ed9a0d7addb6e48899da
8e741148d6e0cd67a969513ce2a7fe23241df648
refs/heads/master
2020-05-18T05:06:02.090313
2015-11-18T16:07:12
2015-11-18T16:07:12
22,037,751
0
0
null
null
null
null
UTF-8
Scheme
false
false
472
meta
bind.meta
;;; bind.meta -*- Scheme -*- ((synopsis "Automatically generate bindings from C/C++ declarations") (category ffi) (license "public domain") (needs silex matchable coops regex make) (test-depends test) (doc-from-wiki #t) (author "[[felix winkelmann]]") (files "bind-translator.scm" "bind.release-info" "bind.scm" "bind.meta" "cplusplus-object.scm" "c.l" "bind.setup" "runsilex.scm" "tests/cplusplus-test.scm" "tests/run.scm" "tests/tests.scm" "chicken-bind.scm"))
false
0180f50479c4a3662f7cec8e3976947a3e643419
82d8e8948f60e96ad378ba253776a93e97842891
/utilities.scm
23b35fa7b9f47a49a89bc8497f48ba6da0642a99
[]
no_license
indraniel/slilme
2af9b6956cbb5cd2bb7a96f60d2ed50d2c76532d
cdac7589813d46708cc3f1b6fb188a9edad5dd2d
refs/heads/master
2020-06-05T07:32:10.758855
2018-10-30T15:49:43
2018-10-30T15:49:43
192,361,112
0
0
null
null
null
null
UTF-8
Scheme
false
false
4,150
scm
utilities.scm
(define *center-dead-zone* 0.25) (define *border-dead-zone* 0.9) (define deadzone-func (let* ((x1 *center-dead-zone*) (y1 0.0) (x2 *border-dead-zone*) (y2 1.0) (a (fp/ (fp- y2 y1) (fp- x2 x1))) (b (fp/ (fp- (fp* x2 y1) (fp* x1 y2)) (fp- x2 x1)))) (lambda (x) (fp+ (fp* a x) b)))) (define (joy-improve x y) (let* ((v (glm:make-point x y 0)) (mag (glm:vector-magnitude v)) (_ (glm:normalize! v)) (better-mag (if (<= mag *center-dead-zone*) 0.0 (if (>= mag *border-dead-zone*) 1.0 (deadzone-func mag)))) (v (glm:v* v better-mag))) (if (zero? mag) (glm:make-point 0 0 0) v))) (define (pointer->vector ptr len datum-size ref) (let* ((v (make-vector len))) (do ((i 0 (add1 i)) (p ptr (pointer+ p datum-size))) ((= i len) v) (vector-set! v i (ref p))))) ;; TODO integrate that to the glfw3 egg (define (get-joystick-buttons joy) (let ((ptr len (glfw:get-joystick-buttons joy))) (pointer->vector ptr len 1 pointer-u8-ref))) ;; TODO integrate that to the glfw3 egg (define (get-joystick-axes joy) (let ((ptr len (glfw:get-joystick-axes joy))) (pointer->vector ptr len 4 pointer-f32-ref))) (define (load-texture filename) (let* ((data width height channels (with-input-from-file filename img:read-image)) (texture-id (glu:gen-texture)) (format (case channels ((3) gl:+rgb+) ((4) gl:+rgba+)))) (assert (or (= channels 3) (= channels 4))) (glu:with-texture gl:+texture-2d+ texture-id (gl:tex-parameteri gl:+texture-2d+ gl:+texture-wrap-s+ gl:+clamp-to-edge+) (gl:tex-parameteri gl:+texture-2d+ gl:+texture-wrap-t+ gl:+clamp-to-edge+) (gl:tex-parameteri gl:+texture-2d+ gl:+texture-min-filter+ gl:+linear-mipmap-linear+) (gl:tex-parameteri gl:+texture-2d+ gl:+texture-mag-filter+ gl:+linear+) (gl:tex-image-2d gl:+texture-2d+ 0 format width height 0 format gl:+unsigned-byte+ (glu:->pointer data)) (gl:generate-mipmap gl:+texture-2d+)) texture-id)) (define (find-pixel-index data reference-pixel) (let lp ((i 0)) (let ((pixel (subu8vector data i (+ i 3)))) (if (equal? pixel reference-pixel) i (lp (+ i 3)))))) (define (index->pos i width channels) (let ((y x (quotient&remainder (/ i channels) width))) (values x y))) (define (image-ref data pt) (let* ((x (inexact->exact (round (glm:point-x pt)))) (y (inexact->exact (round (glm:point-y pt)))) (i (* (+ (* y 1920) x) 3))) (subu8vector data i (+ i 3)))) (define (world->view pt) (let ((x (glm:point-x pt)) (y (glm:point-y pt))) (glm:make-point (- (/ x 960.) 1) (- (- (/ y 540.) 1)) 0))) (define (view->world pt) (let ((x (glm:point-x pt)) (y (glm:point-y pt))) (glm:make-point (round (* (+ x 1) 960.)) (round (* (+ (- y) 1) 540.)) 0))) (define (ray-cast origin increment max-magnitude pixel-searched) (let lp ((pt origin)) (cond ((or (zero? max-magnitude) (> (glm:vector-magnitude (glm:v- pt origin)) max-magnitude)) #f) ((equal? (image-ref *collision-map* pt) pixel-searched) (glm:v- pt increment)) (else (lp (glm:v+ pt increment)))))) (define (resource-path level resource) (make-pathname (list "resources" "gras_fik" (string-append "level" (number->string level))) resource)) (define (file->blob filename) (let* ((size (file-size filename)) (buf (make-u8vector size 0 #t #f))) (with-input-from-file filename (lambda () (read-u8vector! size buf) (u8vector->blob/shared buf)))))
false
baa704853b25a81526df3908fcb85ccf704b3245
51d30de9d65cc3d5079f050de33d574584183039
/http/standard-test.scm
9cf455ab9cf4c43ae59fff87ea5865974e089e7c
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
langmartin/ykk
30feb00265d603ef765b5c664d2f759be34b7b89
dd6e441dddd5b6363ee9adbbdd0f346c1522ffcf
refs/heads/master
2016-09-05T20:01:19.353224
2009-12-10T16:25:55
2009-12-10T16:25:55
408,478
0
1
null
null
null
null
UTF-8
Scheme
false
false
3,394
scm
standard-test.scm
(define-syntax let-server-command-page (syntax-rules () ((_ text body ...) (lambda () (http-server-exec (lambda () body ...) (let-http-response (220 "ok") (let-headers ((content-type "text/plain")) (begin-content-length text)))))))) (http-register-code-handler! 404 (lambda () (let-http-response (404 "Not Found") (let-headers ((content-type "text/plain")) (begin-content-length "404\n The path " (request-path) " is not registered.\n\n" (request-version) newline (request-method) newline (request-url) newline (request-parameters)))))) (http-register-page! "/stop" (let-server-command-page "server stopping" #t)) (define-syntax let-content-type-page (syntax-rules () ((_ type body ...) (let-http-response (220 "ok") (let-headers ((content-type type)) (begin-content-length body ...)))))) (define-syntax let-html-page (syntax-rules () ((_ body ...) (let-content-type-page "text/html" body ...)))) (define-syntax let-text-page (syntax-rules () ((_ body ...) (let-content-type-page "text/plain" body ...)))) (define (text name) `(input (@ (type "text") (name ,name)))) (define (code lst) `(pre ,(let-string-output-port (newline) (write lst) (newline)))) (define (include-file file) (call-with-input-file file (lambda (p) (read-line p #f)))) (http-register-page! "/test" (lambda () (let-html-page (shtml->html `(html (head (title "test") (script (@ (src "http://webtools.php5.iago/js/jquery-1.2.2.min.js"))) (script (@ (src "http://rco.abla2/secure/checkout/js-ext/jquery.json.js")))) (body (div ,(code (standard-parameters))) (div (form (@ (action "/test?foo=1&bar=2") (method "post")) ,(text "foo[bar]") ,(text "foo[baz]") (input (@ (type "submit") (name "submit") (value "hit me"))))) (div (@ (onclick "javascript:ajaxTest('json')") (id "json")) "json") (div (@ (onclick "javascript:xmlTest()") (id "xml")) "xml") (script (@ (type "text/javascript")) ,(include-file "http/standard-test.js")) )))))) (http-register-page! "/ajax" (lambda () (let-text-page (lambda () (write (standard-parameters)))))) (http-register-page! "/path" (lambda (foo bar) (let-text-page (lambda () (write (standard-parameters))) newline "my path is " foo " and " bar))) (http-register-page! "/break" (lambda () (error "broken"))) (define (go) (standard-http-server)) ;; (let-http-response ;; (status 500) ;; (header foo "bar") ;; (header baz "blit") ;; (begin-http-body ;; type: text/html ;; "thinngs" ;; (header location "http://foo.com") ;; (lambda () ;; (stuff)))) ;; (let-http-response ;; 200 ;; ((accepts "*")) ;; (begin-content-length ;; (shtml->html ;; `(*top* ;; (head) ;; (body ;; (p "thing")))))) ;; (let-http-response (200 "I found it!") ;; (let-headers ((thing "bar")) ;; (begin-content-length ;; "thing" ;; "baz")))
true
aaa2b226cbfab9d53278116bd2a4a287df40637e
73feea4b4fbdcf415dcc9e8fd501a1552d70d921
/src/core/core.scm
4ca02dea3e8fbcee1293f47a3a9fda72898613bc
[ "MIT" ]
permissive
per-gron/spork
1a31045d318d346ad74bb7bf9aa1883fba3441fd
8ac9a551a24b436b4d3ddef07ebecad3b07eaddc
refs/heads/master
2021-05-27T02:45:46.584552
2012-05-21T09:43:09
2012-05-21T09:43:09
208,810
2
0
null
null
null
null
UTF-8
Scheme
false
false
18,766
scm
core.scm
(import (std net/http-server net/http-session net/uri srfi/1 srfi/13 string/util string/sxml-to-xml misc/exception misc/al) splice counter) (syntax-begin (import (only: (std srfi/1) filter))) (export make-spork spork? spork-pattern spork-function spork-prefix spork-prefix! spork add-spork cutlery? make-cutlery cutlery-join cutlery-join! cutlery-add-spork! cutlery-add! cutlery-sporks cutlery-prefix cutlery-prefix! registry-put! register-function spork-die spork-reply-dont-die spork-reply spork-reply-xml goto goto-here fork ajax-fork show spork-server? spork-server-errors spork-server-errors-set! spork-server-public-kids spork-server-public-kids-set! spork-server-cutlery spork-server-cutlery-set! spork-server-root spork-server-root-set! make-spork-server spork-server-define-error show-error force-method spork-server-run spork-serve splice splice? unsplice make-backtrackable-variable make-session-variable make-variable) ;; Sporks (define-type spork id: 3E6E0900-4308-4D58-8DF9-EE220A415355 (pattern read-only:) (function read-only:)) (define (spork-prefix spork prefix) (make-spork (cons prefix (spork-pattern spork)) (spork-function spork))) (define (spork-prefix! spork prefix) (spork-pattern spork (cons prefix (spork-pattern spork)))) ;; TODO This is only used by spork, so it should be in a let-syntax ;; really, but the module system doesn't support that right now. (define-syntax lambda-ignorestring (sc-macro-transformer (lambda (form env) `(lambda ,(filter identifier? (cadr form)) ,@(cddr form))))) (define-syntax spork (syntax-rules () ((spork (args ...) body ...) (make-spork '(args ...) (lambda-ignorestring (args ...) (show (lambda (url) body ...))))))) (define-syntax add-spork (syntax-rules () ((add-spork name (args ...) body ...) (cutlery-add-spork! name (spork (args ...) body ...))))) ;; Cutleries (define-type cutlery id: D9017117-DA9D-4C17-AF35-63B02220B414 constructor: make-cutlery-internal pages) (define (make-cutlery . sporks) (make-cutlery-internal sporks)) (define (cutlery-join a b) (make-cutlery-internal (append (cutlery-pages a) (cutlery-pages b)))) (define (cutlery-join! a b) (cutlery-pages-set! a (append (cutlery-pages a) (cutlery-pages b))) a) (define (cutlery-add-spork! c spork) (cutlery-pages-set! c (cons spork (cutlery-pages c))) (void)) (define (cutlery-add! c address fun) (cutlery-add-spork! c (make-spork address fun))) (define (cutlery-sporks c) (cutlery-pages c)) (define (cutlery-prefix c prefix) (apply make-cutlery (map (lambda (spork) (spork-prefix spork prefix)) (cutlery-sporks c)))) (define (cutlery-prefix! c prefix) (for-each (lambda (spork) (spork-prefix! spork prefix)) (cutlery-sporks c))) ;; Pages (define (address-match? s addrs) (let ((ret '())) (and (let loop ((addr addrs) (str s)) (if (null? addr) (eq? 0 (string-length str)) (let ((hd (car addr))) (cond ((symbol? hd) (let ((pos (if (null? (cdr addr)) (string-length str) (string-contains str (cadr addr))))) (if pos (begin (set! ret (cons (substring str 0 pos) ret)) (loop (cdr addr) (substring str pos (string-length str)))) #f))) ((string? hd) (if (string-prefix? hd str) (loop (cdr addr) (string-remove-prefix str hd)) #f)))))) (reverse ret)))) (define (split-path url) (let ((pos (string-contains url "/@"))) (if pos (cons (string-remove-prefix (substring url 0 pos) "/") (substring url (+ pos 2) (string-length url))) (cons (string-remove-prefix url "/") #f)))) (define (call-page cutlery addr) (let loop ((page (cutlery-sporks cutlery))) (if (null? page) #f (if (let ((res (address-match? addr (spork-pattern (car page))))) (if res (parameterize ((current-frame (cons '() #f))) (apply (spork-function (car page)) res) (spork-reply (lambda () (print "Ehh... return to call-page (this is an error)\n")))) #f)) #t (loop (cdr page)))))) (define current-path/server (make-parameter #f)) ;; Core (define kid-registry (make-session-variable (make-table))) (define public-kid-registry (make-table)) (define current-frame (make-parameter #f)) (define generate-continuation-id (make-randomizer "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_.,:;$[]*/")) (define (generate-unique-continuation-id #!optional registry) (let loop ((tries 0)) (if (> tries 1000) (error "Failed to generate continuation id") (let ((id (generate-continuation-id))) (if (table-ref (or registry (kid-registry)) id #f) (loop (+ tries 1)) id))))) (define (registry-put! fun #!optional public kid) (let* ((registry (if public (spork-server-public-kids public) (kid-registry))) (kid (or kid (generate-unique-continuation-id registry)))) (table-set! registry kid (cons fun (current-frame))) (let* ((cp (current-path/server)) (server (if cp (cdr cp) default-server)) (root (spork-server-root server))) (string-append root (if cp (let ((str (caar cp))) (if (eq? 0 (string-length str)) "" (string-append "/" str))) "") (if public "/@@" "/@") kid)))) (define (registry-run kid param #!optional public) (let ((res (table-ref (if public public-kid-registry (kid-registry)) kid #f))) (if res (parameterize ((current-frame (cons '() (cdr res)))) ((car res) param)) #f))) (define suicide (make-parameter #f)) (define (spork-die) ((suicide) #f)) (define (register-function fun #!optional public kid) (registry-put! (lambda (ret) (fun) (reply (lambda () (print "ehh.. return from register-function"))) (spork-die)) public kid)) (define (spork-reply-dont-die . args) (run-before-show) (apply reply args)) (define (spork-reply . args) (apply spork-reply-dont-die args) (spork-die)) (define (spork-reply-xml . args) (run-before-show) (apply reply-xml args) (spork-die)) (define (goto url #!optional (run-before #t)) (if run-before (run-before-show)) (http-redirect 303 (render-widget-with-env url)) (spork-die)) (define (goto-here #!optional (run-before #t)) (call/cc (lambda (k) (goto (registry-put! k) run-before)))) ;; Widgets (define (fork a b) (letrec ((forked (make-backtrackable-variable (delay ;; Registry put has to be called from within ;; the lambda below and the a function must ;; only be invoked once, hence the delay. ;; ;; It's important that render-widget-cont is ;; captured here; It's not initialized when fork ;; is called first, and it will be lost at the time ;; the registry-put! callback is invoked. ;; ;; Ie: render-widget-cont is only valid in ;; the widget rendering phase (let* ((rwc (render-widget-cont))) (a (lambda () (registry-put! (lambda (ret) ;; The modification of forked is sent as ;; a thunk to rwc. This is because ;; forked has to be set in the dynamic ;; environment of the render and not of ;; this request. (rwc (cons (current-frame) (lambda () (forked (delay ;; Who knows when this will be ;; called. It's best to use the ;; query of the current dynamic ;; environment and not ret above. (b (request-query (current-request))))))))))))))))) (lambda () (force (forked))))) (define run-before-show-redirect (make-parameter #t)) (define (run-before-show) ;; This is to assist ajax-fork. (if (and (run-before-show-redirect) (assoc "__frk" (request-get-query (current-request)))) (parameterize ((run-before-show-redirect #f)) (show (lambda (url) `(e (@ (r ,url)))) doctype: 'xml mime: "text/xml")))) (define generate-ajax-fork-id (make-randomizer "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")) (define (ajax-fork a b) (let* ((id (generate-ajax-fork-id)) (f (fork (lambda (url) `(span (@ (id ,id)) ,(a (lambda () (string-append (url) "?_frk=" id))))) b))) (lambda () ;; The call to (f) has to be first, because it might do lots of ;; strange stuff with the continuation and it's important that ;; we don't cache values taken from (current-request) before ;; that. (Hence the let*) (let* ((v (render-widget (f))) (req-frk-id (al-get (request-get-query (current-request)) "__frk"))) (if (equal? req-frk-id id) (parameterize ((run-before-show-redirect #f)) (show (lambda (url) `(e (@ (xmlns "http://www.w3.org/1999/xhtml")) ,v)) doctype: 'xml mime: "text/xml")) v))))) ;; This is initialized when the widget tree is being rendered, ;; it points to the continuation just before the tree starts ;; to be rendered. ;; It is used by fork. (define render-widget-cont (make-parameter #f)) (define (render-widget xml) (cond ((pair? xml) (let ((head (render-widget (car xml)))) (if (splice? head) (append (map render-widget (unsplice head)) (render-widget (cdr xml))) (cons head (render-widget (cdr xml)))))) ((procedure? xml) (render-widget (xml))) (else xml))) (define (render-widget-with-env xml) (let* ((kont #f) (r (call/cc (lambda (k) (set! kont k) #f))) (thunk (lambda () (parameterize ((render-widget-cont kont)) (render-widget xml))))) (if r (parameterize ((current-frame (cons '() (car r)))) ((cdr r)) ;; see fork (thunk)) (thunk)))) (define (show fun #!key (doctype 'xhtml1) (code 200) (headers '()) (mime "text/html")) (call/cc (lambda (k) ;; Only save the continuation in the registry if it's actually used. (let* ((kid-promise (delay (registry-put! k))) (kid (lambda () (force kid-promise)))) (spork-reply (lambda () (let ((val (fun kid))) (if (and (not (string? val)) doctype) (let ((val (render-widget-with-env val))) (if (eq? doctype 'xml) (sxml>>xml-fast val) (sxml>>xhtml-fast val))) (print val)))) code: code headers: headers type: mime))))) ;; Web server (define-type spork-server id: 97796622-0CCE-4422-9521-6C1C054B3A2F constructor: make-spork-server-internal errors public-kids cutlery root) (define default-server (make-spork-server-internal '() #f #f "")) (define (make-spork-server cutlery #!key errors root) (make-spork-server-internal (or errors (spork-server-errors default-server)) (make-table) cutlery (or root ""))) (define (spork-server-define-error server num lambda) (spork-server-errors-set! server (cons (cons num lambda) (spork-server-errors server)))) (define (show-error num . args) (let* ((path/server (current-path/server)) (server (if path/server (cdr path/server) default-server)) (v (assq num (spork-server-errors server)))) (if v (spork-reply-xml (apply (cdr v) args) code: num) (error "Error page not defined" num)))) ;; Method is expected to be an uppercase string (define (force-method method) (if (not (equal? (request-method (current-request)) method)) (show-error 405))) (spork-server-define-error default-server 400 (lambda (#!optional msg) `(html (head (title "Bad Request")) (body (h1 "Bad Request") (p ,(or msg "Invalid request.")))))) (spork-server-define-error default-server 403 (lambda () `(html (head (title "Forbidden")) (body (h1 "Forbidden") (p "You don't have permission to access this page."))))) (spork-server-define-error default-server 404 (lambda () `(html (head (title "File Not Found")) (body (h1 "File Not Found") (p "The URL you requested could not be found."))))) (spork-server-define-error default-server 405 (lambda () `(html (head (title "Method Not Allowed")) (body (h1 "Method Not Allowed") (p "The request was made using an invalid method."))))) (spork-server-define-error default-server 500 (lambda (#!optional exc) `(html (head (title "Internal Server Error")) (body (h1 "Internal Server Error") ,@(if (not exc) `((p "The server encountered an internal error or " "misconfiguration and was unable to complete " "your request.")) `((pre ,(exception/continuation->string exc)))))))) (define (handle-req server) (let ((cutlery (spork-server-cutlery server))) (call/cc (lambda (exit) (suicide exit) (let* ((req (current-request)) (uri (request-uri req)) (path (uri-path uri)) (s-path (split-path path))) (parameterize ((current-path/server (cons s-path server))) (let ((id (cdr s-path)) (url (car s-path))) (if id (if (let ((public (and (positive? (string-length id)) (eq? #\@ (string-ref id 0))))) (not (registry-run (if public (substring id 1 (string-length id)) id) (request-query req) public))) (goto (string-append "/" url))) (if (not (call-page cutlery url)) (show-error 404)))))))))) (define (handle-req-catch-errs server) (lambda () (with-exception/continuation-catcher (lambda (e) (show-error 500 e)) (lambda () (handle-req server))))) (define (spork-server-run server #!optional (port 8080)) (http-server-start! (make-http-server (handle-req-catch-errs server) port))) (define (spork-serve #!key (port 8080) errors root) (let ((c (make-cutlery))) (thread-start! (make-thread (lambda () (spork-server-run (make-spork-server c errors: errors root: root) port)))) c)) ;; Backtrackable variables (define generate-bt-id #f) (let ((bt 0)) (set! generate-bt-id (lambda () (set! bt (+ bt 1)) bt))) (define (bt-get id cf default) (let ((fv (assq id (car cf)))) (if fv (cdr fv) (let ((parent-frame (cdr cf))) (if parent-frame (bt-get id parent-frame default) default))))) (define (bt-set! id val) (let ((cf (current-frame))) (set-car! cf (cons (cons id val) (car cf))) val)) (define backtrackable-variable-nochange (gensym)) (define (make-backtrackable-variable #!optional default-val) (let ((id (generate-bt-id))) (lambda (#!optional (val backtrackable-variable-nochange)) (if (eq? val backtrackable-variable-nochange) (bt-get id (current-frame) default-val) (bt-set! id val))))) (define (make-variable #!optional default-val) (let ((val default-val)) (lambda (#!optional (new-val backtrackable-variable-nochange)) (if (eq? val backtrackable-variable-nochange) val (begin (set! val new-val) new-val)))))
true
0d83f0dc5927bdc5aadb8480139d063daaff594b
defeada37d39bca09ef76f66f38683754c0a6aa0
/make-clr-importer.sls
b8e9821e2246ddd7091a17ba0b47ac8038f6e731
[]
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
12,604
sls
make-clr-importer.sls
(library (make-clr-importer) (export make-clr-importer clr-importer-make-all proc-method) (import (rnrs) (ironscheme) (ironscheme clr) (ironscheme strings) (only (srfi :1) iota any every) (srfi private let-opt) (as-match) ) (clr-using System) (clr-using System.Reflection) (define (get-type name) (let ([t (clr-static-call IronScheme.Runtime.Helpers GetTypeFast name)]) (if (null? t) #f t))) (define (symbol-format fmt . args) (string->symbol (apply format fmt args))) (define (get-name n) (cond [(clr-is Type n) (clr-prop-get Type Name n)] [(clr-is MethodInfo n) (clr-prop-get MethodInfo Name n)] [(clr-is PropertyInfo n) (clr-prop-get PropertyInfo Name n)] [(clr-is FieldInfo n) (clr-prop-get FieldInfo Name n)] [else (assertion-violation 'get-name "wrong type" n)])) (define (get-name-symbol n) (format "~a" (get-name n))) (define (get-fullname-symbol t) (format "~a" (clr-prop-get Type FullName t))) (define (identity s) s) (define (clr-name->scheme-like s) (let-values ([(ip) (open-string-input-port s)] [(op result) (open-string-output-port)]) (let loop ([prechar-upper? #t] [c (get-char ip)]) (cond [(eof-object? c) (result)] [(or (eqv? c #\.) (eqv? c #\_)) (write-char #\- op) (loop #t (get-char ip))] [else (if (and (char-upper-case? c) (not prechar-upper?)) (write-char #\- op)) (write-char (char-downcase c) op) (loop (char-upper-case? c) (get-char ip))])))) (define (symbol-valid-string? s) (let ([ip (open-string-input-port s)]) (let loop ([first #t] [c (read-char ip)]) (if (eof-object? c) #t (if (cond [(or (char-numeric? c) (eqv? c #\[) (eqv? c #\])) (not first)] [(char-alphabetic? c) #t] [else (case c [(#\. #\+ #\- #\* #\/ #\$ #\% #\& #\~ #\: #\> #\< #\? #\! #\_ #\^ #\=) #t] [else #f])]) (loop #f (read-char ip)) #f))))) (define (able->symbol s) (if (symbol-valid-string? s) (string->symbol s) s)) (define (symbol/string-format s . args) (able->symbol (apply format s args))) (define (cast-to-ironscheme t) (case (clr-prop-get Type FullName t) [("System.Byte" "System.SByte" "System.Int16" "System.UInt16" "System.UInt32") (lambda (e) `(clr-cast System.Int32 ,e))] [("System.Single") (lambda (e) `(clr-cast System.Double ,e))] [else (lambda (e) e)])) (define (null->false e) (if (eq? e '()) #f e)) (define (proc-field-prop type symconv p enforce-syntax?) (clr-guard (ex [#t (raise (list 'proc-field-prop type p ex))]) (let* ([typesym (symbol/string-format "~a" (clr-prop-get Type FullName type))] [propsym (symbol/string-format "~a" (get-name p))] [field? (clr-is FieldInfo p)] [prop-type (if field? (clr-prop-get FieldInfo FieldType p) (clr-prop-get PropertyInfo PropertyType p))] [booltype (get-type "System.Boolean")] [prop-boolean? (eq? booltype prop-type)] [name-sym (symbol/string-format (if prop-boolean? "~a?" "~a") (symconv (get-name p)))] [prop-type-sym (symbol/string-format "~a" (clr-prop-get Type FullName prop-type))] [canget? (if field? #t (null->false (clr-call PropertyInfo GetGetMethod p)))] [canset? (if field? (and (not (clr-prop-get FieldInfo IsInitOnly p)) (not (clr-prop-get FieldInfo IsLiteral p))) (null->false (clr-call PropertyInfo GetSetMethod p)))] [static? (if field? (clr-prop-get FieldInfo IsStatic p) (clr-prop-get MethodInfo IsStatic (if canget? (clr-call PropertyInfo GetGetMethod p) (clr-call PropertyInfo GetSetMethod p))))] [getsym (cond [(and canget? canset?) (symbol/string-format "~a-get" name-sym)] [canget? (symbol/string-format "~a" name-sym)] [else #f])] [setsym (cond [(and canget? canset?) (symbol/string-format "~a-set!" name-sym)] [canset? (symbol/string-format "~a" name-sym)] [else #f])] [updatesym (if (and canget? canset?) (symbol/string-format "~a-update!" name-sym) #f)] [staticinsert (if static? '(static:) '())] [propertyinsert (if field? '() '(property:))]) `((define-field-port ,getsym ,setsym ,updatesym ,(append staticinsert propertyinsert) ,typesym ,propsym ,prop-type-sym))))) (define (proc-method type symconv p enforce-syntax?) (let* ([typesym (symbol/string-format "~a" (clr-prop-get Type FullName type))] [name (car p)] [lst (cdr p)] [func-src (symbol/string-format "~a" name)] [booltype (get-type "System.Boolean")] [all-pred? (every (lambda (m) (eq? booltype (clr-prop-get MethodInfo ReturnType m))) lst)] [def-name (symbol/string-format (if all-pred? "~a?" "~a") (symconv name))] [overloaded? (< 1 (length lst))] [impls (map (lambda (m) (let ([static? (if (clr-prop-get MethodInfo IsStatic m) '(static:) '())] [rettype (symbol/string-format "~a" (clr-prop-get Type FullName (clr-prop-get MethodInfo ReturnType m)))] [argtypes (map (lambda (p) (symbol/string-format "~a" (clr-prop-get Type FullName (clr-prop-get ParameterInfo ParameterType p)))) (vector->list (clr-call MethodInfo GetParameters m)))]) `(,@static? ,rettype ,@argtypes))) (filter (lambda (e) (and (not (clr-prop-get MethodInfo IsGenericMethod e)) (not (clr-prop-get MethodInfo IsGenericMethodDefinition e)) (not (any (lambda (e) (let ([pt (clr-prop-get ParameterInfo ParameterType e)]) (or (clr-prop-get Type IsGenericType pt) (clr-prop-get Type IsGenericTypeDefinition pt)))) (vector->list (clr-call MethodInfo GetParameters e)))))) lst))]) `((define-method-port ,def-name ,typesym ,func-src ,@impls)))) (define (lookup lst keyselector . option) (let-optionals* option ([valueselector identity]) (let ([ht (make-eq-hashtable)]) (let loop ([lst lst]) (if (null? lst) (hashtable-map ht cons) (let* ([head (car lst)] [tail (cdr lst)] [k (keyselector head)] [v (valueselector head)]) (hashtable-update! ht k (lambda (p) (cons v p)) '()) (loop tail))))))) #;(define-syntax trace (lambda (e) (syntax-case e () [(_ v) #'(begin (let ([val v]) (displayln (format "trace: ~a" (call-with-string-output-port (lambda (op) (pretty-print (syntax->datum val) op))))) val))]))) (define-syntax trace (lambda (e) (syntax-case e () [(_ v) #'v]))) (define (clr-importer-make-all type symconv enforce-syntax?) (let* ([typename (clr-prop-get Type FullName type)] [typesym (symbol/string-format "~a" typename)] [issym (symbol/string-format "~a?" (symconv (clr-prop-get Type Name type)))] [bindflag '(Public InvokeMethod Instance Static DeclaredOnly)] [->int (lambda (x) (clr-static-call System.Convert (ToInt32 Object) (clr-cast Object x)))] [varargs-flag (->int (clr-cast System.Reflection.CallingConventions '(VarArgs)))] ; for varargs method removing [bit-all-set? (lambda (a b) (eq? b (bitwise-and a b)))] [methods (filter (lambda (e) (and (not (clr-prop-get MethodInfo IsSpecialName e)) (not (bit-all-set? (->int (clr-cast System.Reflection.CallingConventions (clr-prop-get MethodInfo CallingConvention e))) varargs-flag)))) (vector->list (clr-call Type GetMethods type (clr-cast BindingFlags bindflag))))] [methods-lu (lookup methods (lambda (e) (clr-prop-get MethodInfo Name e)))] [defs (append (if (eq? 0 (vector-length (clr-call Type GetConstructors type (clr-cast BindingFlags bindflag)))) '() `((define-syntax new (lambda (e) (syntax-case e () [(_ a ...) #'(clr-new ,typesym a ...)]))))) `((define (is? a) (clr-is ,typesym a))) `((define (,issym a) (clr-is ,typesym a))) (apply append (map (lambda (p) (proc-method type symconv p enforce-syntax?)) methods-lu)) (apply append (map (lambda (p) (proc-field-prop type symconv p enforce-syntax?)) (filter (lambda (e) (not (clr-prop-get FieldInfo IsSpecialName e))) (vector->list (clr-call Type GetFields type (clr-cast BindingFlags bindflag)))))) (apply append (map (lambda (p) (proc-field-prop type symconv p enforce-syntax?)) (filter (lambda (e) (and (not (clr-prop-get PropertyInfo IsSpecialName e)) (not (equal? "Chars" (clr-prop-get PropertyInfo Name e))))) (vector->list (clr-call Type GetProperties type (clr-cast BindingFlags bindflag)))))))] [syms (apply append (map (lambda (l) (match l [('define (def ps ...) body ...) (list def)] [('define def body ...) (list def)] [('define-syntax def body ...) (list def)] [('define-field-port def1 def2 def3 attr body ...) (filter (lambda (e) e) (list def1 def2 def3))] [('define-method-port def body ...) (list def)])) defs))]) (list syms defs))) (define (make-clr-importer type/name . option) (let-optionals* option ([scheme-like-name? #t] [enforce-syntax? #f]) (let* ([symconv (if scheme-like-name? clr-name->scheme-like identity)] [type (guard (e [#t #f]) (if (string? type/name) (get-type type/name) type/name))] [all (clr-importer-make-all type symconv enforce-syntax?)] [fullname (clr-prop-get Type FullName type)] [namespace (map (lambda (e) (symbol/string-format "~a" (symconv e))) (vector->list (string-split fullname ".")))]) `(library (,@namespace) (export ,@(car all)) (import (ironscheme-clr-port)) ,@(cadr all) )))) )
true
94753b852fe351ed58ac0a11e7de57fc481935f6
f6ebd0a442b29e3d8d57f0c0935fd3e104d4e867
/ch03/3.3/ex-3-3-byulparan.scm
7789728951613d9422f91027e45f210b706d5a8b
[]
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
21,363
scm
ex-3-3-byulparan.scm
;; racket -l r5rs/run ;; ์—ฐ์Šต๋ฌธ์ œ 3.12 (define (append! x y) (set-cdr! (last-pair x) y) x) (define (last-pair x) (if (null? (cdr x)) x (last-pair (cdr x)))) (define x (list 'a 'b)) (define y (list 'c 'd)) (define z (append x y)) z (car x) (define w (append! x y)) w (cdr x) ;; ์—ฐ์Šต๋ฌธ์ œ 3.13 (define (make-cycle x) (set-cdr! (last-pair x) x) x) (define z (make-cycle (list 'a 'b 'c))) ;; what happen? (last-pair z) ;; ์—ฐ์Šต๋ฌธ์ œ 3.14 (define (mystery x) (define (loop x y) (if (null? x) y (let ((temp (cdr x))) (set-cdr! x y) (loop temp x)))) (loop x '())) (define v (list 'a 'b 'c 'd)) (define w (mystery v)) (define x (list 'a 'b)) (define z1 (cons x x)) (define z2 (cons (list 'a 'b) (list 'a 'b))) (define (set-to-wow! x) (set-car! (car x) 'wow) x) z1 (set-to-wow! z1) z2 (set-to-wow! z2) ;; ์—ฐ์Šต๋ฌธ์ œ 3.15 ;; ์—ฐ์Šต๋ฌธ์ œ 3.16 (define (count-pairs x) (if (not (pair? x)) 0 (+ (count-pairs (car x)) (count-pairs (cdr x)) 1))) ;; (define (count-pairs x) ;; (if (not (pair? x)) (begin ;; (display x) (display "\n") ;; 0) ;; (+ (count-pairs (car x)) ;; (count-pairs (cdr x)) 1))) ;; car ๊ณผ cdr ์ด ๊ฐ™์€ pair ๋ฅผ ๊ฐ€๋ฆฌํ‚ค๊ณ  ์žˆ๋‹ค๋ฉด?! ;; ์„ธ๊ณ„์˜ pair ๊ฐ€ ์žˆ์ง€๋งŒ..4๋ฅผ ์ถœ๋ ฅ. (let ((a (list 'a))) (let ((b (list a a))) (count-pairs b))) ;; 7 (let ((a (cons 10 20))) (let ((b (cons a a))) (let ((c (cons b b))) (count-pairs c)))) ;; ์˜์›ํžˆ ๋„๋Š” ํ”„๋กœ์‹œ์ ธ (let ((a (list 1 2))) (let ((b (cons 10 a))) (set-cdr! (cdr a) b) (count-pairs a))) ;; ์—ฐ์Šต๋ฌธ์ œ 3.17 (define (find-item item seq) (cond ((null? seq) #f) ((eq? item (car seq)) #t) (else (find-item item (cdr seq))))) ;; (let ((a '(1 2 3))) ;; (let ((b (list 10 20 a 30))) ;; (find-item a b))) (define (new-count-pairs x) (let ((repo '())) (define (count-pairs x) (if (or (not (pair? x)) (find-item x repo)) 0 (begin (set! repo (cons x repo)) (+ (count-pairs (car x)) (count-pairs (cdr x)) 1)))) (count-pairs x))) (let ((a (list 'a))) (let ((b (list a a))) (new-count-pairs b))) (let ((a (cons 10 20))) (let ((b (cons a a))) (let ((c (cons b b))) (new-count-pairs c)))) (let ((a (list 1 2))) (let ((b (cons 10 a))) (set-cdr! (cdr a) b) (new-count-pairs a))) ;; ์—ฐ์Šต๋ฌธ์ œ 3.18 (define (make-cycle list) (set-cdr! (last-pair list) list) list) (let ((a (make-cycle '(1 2 3)))) (eq? a (cdddr a))) (define (find-cycle list) (let ((copy '())) (define (inner-find-cycle x) (cond ((null? x) #f) ((find-item x copy) #t) (else (begin (set! copy (cons x copy)) (inner-find-cycle (cdr x)))))) (inner-find-cycle (cdr list)))) (find-cycle '(1 2 3 4)) (find-cycle (make-cycle '(1 2 3 4))) (find-cycle (cons 'q (make-cycle '(1 2 3 4)))) ;; ์—ฐ์Šต๋ฌธ์ œ 3.19 ์ •ํ•ด์ง„ ๊ณต๊ฐ„๋งŒํผ๋งŒ ์“ฐ๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜(์ •๋ง ๊ผผ๊ผผํžˆ ์ž˜ ์ƒ๊ฐํ•ด์•ผ ํ’€ ์ˆ˜ ์žˆ๋‹ค) ;; Floyd's idea: (define (contains-cycle? lst) (define (safe-cdr l) (if (pair? l) (cdr l) '())) (define (iter a b) (cond ((not (pair? a)) #f) ((not (pair? b)) #f) ((eq? a b) #t) ((eq? a (safe-cdr b)) #t) (else (iter (safe-cdr a) (safe-cdr (safe-cdr b)))))) (iter (safe-cdr lst) (safe-cdr (safe-cdr lst)))) (contains-cycle? (make-cycle '(1 2 3 4))) ;; ์—ฐ์Šต๋ฌธ์ œ 3.20 (define (cons2 x y) (define (set-x! v) (set! x v)) (define (set-y! v) (set! y v)) (define (dispatch m) (cond ((eq? m 'car) x) ((eq? m 'cdr) y) ((eq? m 'set-car!) set-x!) ((eq? m 'set-cdr!) set-y!) (else (error "Undefined operation --CONS")))) dispatch) (define (car2 z) (z 'car)) (define (cdr2 z) (z 'cdr)) (define (set-car2! z new-value) ((z 'set-car!) new-value) z) (define (set-cdr2! z new-value) ((z 'set-cdr!) new-value) z) (define x (cons2 1 2)) (define z (cons2 x x)) (set-car2! (cdr2 z) 17) (car2 x) ;; 3.3.2 ํ (define (front-ptr queue) (car queue)) (define (rear-ptr queue) (cdr queue)) (define (set-front-ptr! queue item) (set-car! queue item)) (define (set-rear-ptr! queue item) (set-cdr! queue item)) (define (empty-queue? queue) (null? (front-ptr queue))) (define (make-queue) (cons '() '())) (define (front-queue queue) (if (empty-queue? queue) (error "FRONT called with an empty queue") (car (front-ptr queue)))) (define (insert-queue! queue item) (let ((new-pair (cons item '()))) (cond ((empty-queue? queue) (begin (set-front-ptr! queue new-pair) (set-rear-ptr! queue new-pair) queue)) (else (set-cdr! (rear-ptr queue) new-pair) (set-rear-ptr! queue new-pair) queue)))) (define (delete-queue! queue) (cond ((empty-queue? queue) (error "DELETE! called with an empty queue")) (else (set-front-ptr! queue (cdr (front-ptr queue))) queue))) ;; ์—ฐ์Šต๋ฌธ์ œ 3.21 (define (error message) (display message) (display "\n")) (define q1 (make-queue)) (insert-queue! q1 'a) (insert-queue! q1 'b) (delete-queue! q1) (delete-queue! q1) (empty-queue? q1) (define (print-queue queue) (front-ptr queue)) (print-queue q1) ;; ์—ฐ์Šต๋ฌธ์ œ 3.22 (define (make-queue) (let ((front-ptr '()) (rear-ptr '())) (define (empty-queue?) (null? front-ptr)) (define (front-queue) (if (empty-queue?) (error "FRONT called with empty queue") (car front-ptr))) (define (insert-queue! item) (let ((new-pair (cons item '()))) (cond ((empty-queue?) (begin (set! front-ptr new-pair) (set! rear-ptr new-pair))) (else (set-cdr! rear-ptr new-pair) (set! rear-ptr new-pair))))) (define (delete-queue!) (cond ((empty-queue?) (error "DELETE! called on emtpy queue")) (else (set! front-ptr (cdr front-ptr))))) (define (print-queue) front-ptr) (define (dispatch m) (cond ((eq? m 'empty-queue?) empty-queue?) ((eq? m 'insert-queue!) insert-queue!) ((eq? m 'delete-queue!) delete-queue!) ((eq? m 'front-queue) front-queue) ((eq? m 'print-queue) print-queue) (else (error "ERR")))) dispatch)) ;; ์—ฐ์Šต๋ฌธ์ œ 3.23 ;; deque (define (make-deque) (let ((deque (cons '() '()))) (define (front-ptr) (car deque)) (define (rear-ptr) (cdr deque)) (define (set-front-ptr! item) (set-car! deque item)) (define (set-rear-ptr! item) (set-cdr! deque item)) (define (empty-deque?) (null? (front-ptr))) (define (front-deque) (cond ((empty-deque?) (error "FRONT called with an empty deque")) (else (caar (front-ptr))))) (define (rear-deque) (cond ((empty-deque?) (error "REAR called with an empty deque")) (else (caar (rear-ptr))))) (define (front-insert-deque! item) (let ((new-pair (cons (cons item '()) '()))) (cond ((empty-deque?) (begin (set-front-ptr! new-pair) (set-rear-ptr! new-pair))) (else (set-cdr! new-pair (front-ptr)) (set-cdr! (car (front-ptr)) new-pair) (set-front-ptr! new-pair))))) (define (rear-insert-deque! item) (let ((new-pair (cons (cons item '()) '()))) (cond ((empty-deque?) (begin (set-front-ptr! new-pair) (set-rear-ptr! new-pair))) (else (set-cdr! (rear-ptr) new-pair) (set-cdr! (car new-pair) (rear-ptr)) (set-rear-ptr! new-pair))))) (define (front-delete-deque!) (cond ((empty-deque?) (error "FRONT-DELETE called with on empty deque")) ((eq? (front-ptr) (rear-ptr)) (set-front-ptr! '()) (set-rear-ptr! '())) (else (set-front-ptr! (cdr (front-ptr))) (set-cdr! (car (front-ptr)) '())))) (define (rear-delete-deque!) (cond ((empty-deque?) (error "REAR-DELETE called with on emtpy deque")) ((eq? (front-ptr) (rear-ptr)) (set-front-ptr! '()) (set-rear-ptr! '())) (else (set-rear-ptr! (cdar (rear-ptr))) (set-cdr! (rear-ptr) '())))) (define (print-deque) (define (print-deque-inner deque acc) (cond ((null? deque) acc) (else (print-deque-inner (cdr deque) (append acc (list (caar deque))))))) (print-deque-inner (front-ptr) '())) (define (dispatch m) (cond ((eq? m 'empty-deque?) empty-deque?) ((eq? m 'front-deque) front-deque) ((eq? m 'rear-deque) rear-deque) ((eq? m 'front-insert-deque!) front-insert-deque!) ((eq? m 'front-delete-deque!) front-delete-deque!) ((eq? m 'rear-insert-deque!) rear-insert-deque!) ((eq? m 'rear-delete-deque!) rear-delete-deque!) ((eq? m 'print-deque) print-deque) (else (error "ERROR")))) dispatch)) ;; 3.3.3 ;; ํ‘œ (define (lookup key table) (let ((record (byul-assoc key (cdr table)))) (if record (cdr record) #f))) (define (byul-assoc key records) (cond ((null? records) #f) ((equal? key (caar records)) (car records)) (else (byul-assoc key (cdr records))))) (define (insert! key value table) (let ((record (assoc key (cdr table)))) (if record (set-cdr! record value) (set-cdr! table (cons (cons key value) (cdr table))))) 'ok!) (define (make-table) (list '*table*)) ;; ์ด์ฐจ์› ํ‘œ (define (lookup key-1 key-2 table) (let ((subtable (byul-assoc key-1 (cdr table)))) (if subtable (let ((record (byul-assoc key-2 (cdr subtable)))) (if record (cdr record) #f)) #f))) (define (insert! key-1 key-2 value table) (let ((subtable (byul-assoc key-1 (cdr table)))) (if subtable (let ((record (byul-assoc key-2 (cdr subtable)))) (if record (set-cdr! record value) (set-cdr! subtable (cons (cons key-2 value) (cdr subtable))))) (set-cdr! table (cons (list key-1 (cons key-2 value)) (cdr table))))) 'ok) ;; ํ”„๋กœ์‹œ์ € ์†์— ํ‘œ ๊ฐ์ถ”๊ธฐ (define (make-table) (let ((local-table (list '*table*))) (define (lookup key-1 key-2) (let ((subtable (byul-assoc key-1 (cdr local-table)))) (if subtable (let ((record (byul-assoc key-2 (cdr subtable)))) (if record (cdr record) #f)) #f))) (define (insert! key-1 key-2 value) (let ((subtable (byul-assoc key-1 (cdr local-table)))) (if subtable (let ((record (byul-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 (dispatch m) (cond ((eq? m 'lookup-proc) lookup) ((eq? m 'insert-proc!) insert!) (else (error "Unknown operation --TABLE")))) dispatch)) (define operation-table (make-table)) (define get (operation-table 'lookup-proc)) (define put (operation-table 'insert-proc!)) (put 'letters 'a 97) (put 'letters 'b 98) (get 'letters 'b) (get 'letters 'a) ;; ์—ฐ์Šต๋ฌธ์ œ 3.24 (define (make-table same-key?) (let ((local-table (list '*table*))) (define (byul-assoc key records) (cond ((null? records) #f) ((same-key? key (caar records)) (car records)) (else (byul-assoc key (cdr records))))) (define (lookup key-1 key-2) (let ((subtable (byul-assoc key-1 (cdr local-table)))) (if subtable (let ((record (byul-assoc key-2 (cdr subtable)))) (if record (cdr record) #f)) #f))) (define (insert! key-1 key-2 value) (let ((subtable (byul-assoc key-1 (cdr local-table)))) (if subtable (let ((record (byul-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 (dispatch m) (cond ((eq? m 'lookup-proc) lookup) ((eq? m 'insert-proc!) insert!) (else (error "Unknown operation --TABLE")))) dispatch)) (define table1 (make-table equal?)) ((table1 'insert-proc!) 'a 100 10) ((table1 'insert-proc!) 'a 101 20) ((table1 'lookup-proc) 'a 100.2) ((table1 'lookup-proc) 'a 101.2) (define table2 (make-table (lambda (a b) (cond ((number? a) (if (> 0.5 (abs (- a b))) #t #f)) (else (equal? a b)))))) ((table2 'insert-proc!) 'a 100 10) ((table2 'insert-proc!) 'a 101 20) ((table2 'lookup-proc) 'a 100.2) ((table2 'lookup-proc) 'a 100.8) ;; ์—ฐ์Šต๋ฌธ์ œ 3.25 (define (make-table same-key?) (let ((local-table (list '*table*))) (define (byul-assoc key records) (cond ((null? records) #f) ((same-key? key (caar records)) (car records)) (else (byul-assoc key (cdr records))))) (define (lookup key-list) (define (look-inner key table) (let ((subtable (byul-assoc (car key) (cdr table)))) (if subtable (cond ((null? (cdr key)) (cdr subtable)) (else (look-inner (cdr key) subtable))) #f))) (look-inner key-list local-table)) (define (insert! key-list value) (define (insert-inner key table) (let ((subtable (byul-assoc (car key) (cdr table)))) (if subtable (cond ((null? (cdr key)) (set-cdr! subtable value)) (else (insert-inner (cdr key) subtable))) (begin (if (null? (cdr key)) (set-cdr! table (cons (cons (car key) value) (cdr table))) (let ((new-subtable (list (car key)))) (set-cdr! table (cons new-subtable (cdr table))) (insert-inner (cdr key) new-subtable))))))) (insert-inner key-list local-table)) (define (dispatch m) (cond ((eq? m 'lookup-proc) lookup) ((eq? m 'insert-proc!) insert!) (else (error "Unknown operation --TABLE")))) dispatch)) (define table (make-table equal?)) ((table 'lookup-proc) '(a)) ((table 'insert-proc!) '(a b c) 2110) ((table 'insert-proc!) '(a b d) 20) ((table 'insert-proc!) '(a b) 80) ((table 'insert-proc!) '(a c) 80) ((table 'insert-proc!) '(a d e f g) 10) ((table 'insert-proc!) '(a d e f x) 100) ((table 'insert-proc!) '(a d e g h) 40) ((table 'lookup-proc) '(a d e)) ((table 'lookup-proc) '(a d e f)) ((table 'lookup-proc) '(a d e g)) ;; ์—ฐ์Šต๋ฌธ์ œ 3.26 ;; ์—ฐ์Šต๋ฌธ์ œ 3.27 (define (lookup key table) (let ((record (byul-assoc key (cdr table)))) (if record (cdr record) #f))) (define (byul-assoc key records) (cond ((null? records) #f) ((equal? key (caar records)) (car records)) (else (byul-assoc key (cdr records))))) (define (insert! key value table) (let ((record (assoc key (cdr table)))) (if record (set-cdr! record value) (set-cdr! table (cons (cons key value) (cdr table))))) 'ok!) (define (make-table) (list '*table*)) (define *inner-table* '()) (define (memoize f) (let ((table (make-table))) (set! *inner-table* table) (lambda (x) (let ((previously-computed-result (lookup x table))) (or previously-computed-result (let ((result (f x))) (insert! x result table) result)))))) (define memo-fib (memoize (lambda (n) (cond ((= n 0) 0) ((= n 1) 1) (else (+ (memo-fib (- n 1)) (memo-fib (- n 2)))))))) (memo-fib 30) (let ((table (make-table))) (define (fib n) (cond ((= n 0) 0) ((= n 1) 1) (else (+ (fib (- n 1)) (fib (- n 2)))))) (define test-fib (memoize fib)) (test-fib 31) ;; 3.3.4 ๋””์ง€ํ„ธ ํšŒ๋กœ ์‹œ๋ฎฌ๋ ˆ์ดํ„ฐ (define (half-adder a b s c) (let ((d (make-wire)) (e (make-wire))) (or-gate a b d) (and-gate a b c) (inverter c e) (and-gate d e s) 'ok)) (define (full-adder a b c-in sum c-out) (let ((s (make-wire)) (c1 (make-wire)) (c2 (make-wire))) (half-adder b c-in s c1) (half-adder a s sum c2) (or-gate c1 c2 c-out) 'ok)) ;; ๊ธฐ๋ณธํ•จ์ˆ˜ ์†Œ์ž (define (inverter input output) (define (invert-input) (let ((new-value (logical-not (get-signal input)))) (after-delay inverter-delay (lambda () (set-signal! output new-value))))) (add-action! input invert-input) 'ok) (define (logical-not s) (cond ((= s 0) 1) ((= s 1) 0) (else (error "Invalid signal" s)))) (define (and-gate a1 a2 output) (define (and-action-procedure) (let ((new-value (logical-and (get-signal a1) (get-signal a2)))) (after-delay and-gate-delay (lambda () (set-signal! output new-value))))) (add-action! a1 and-action-procedure) (add-action! a2 and-action-procedure) 'ok) (define (logical-and s1 s2) (cond ((and (= s1 1) (= s2 1)) 1) (else 0))) ;; ์—ฐ์Šต๋ฌธ์ œ 3.28 (define (or-gate a1 a2 output) (define (or-action-procedure) (let ((new-value (logical-or (get-signal a1) (get-signal a2)))) (after-delay or-gate-delay (lambda () (set-signal! output new-value))))) (add-action! a1 or-action-procedure) (add-action! a2 or-action-procedure)) (define (logical-or s1 s2) (if (and (or (= s1 0) (= s1 1)) (or (= s2 0) (= s2 1))) (cond ((and (= s1 0) (= s2 0)) 0) (else 1)) (error "Invalid signal"))) ;; ์—ฐ์Šต๋ฌธ์ œ 3.29 (define (or-gate a1 a2 output) (define (or-action-procedure) (let ((a (make-wire)) (b (make-wire)) (c (make-wire))) (inverter a1 a) (inverter a2 b) (and-gate a b c) (inverter c output))) (add-action! a1 or-action-procedure) (add-action! a2 or-action-procedure)) ;; The delay = 3*inverter-delay + and-gate-delay ;; ์—ฐ์Šต๋ฌธ์ œ 3.30 (define (ripple-carry-adder a b s c) (cond ((null? a) 'ok) (else (let ((c-out (make-wire))) (full-adder (car a) (car b) c (car s) c-out) (ripple-carry-adder (cdr a) (cdr b) (cdr s) c-out))))) ;; ์ค„๋งŒ๋“ค๊ธฐ (define (make-wire) (let ((signal-value 0) (action-procedures '())) (define (set-my-signal! new-value) (if (not (= signal-value new-value)) (begin (set! signal-value new-value) (call-each action-procedures)) 'done)) (define (accept-action-procedure! proc) (set! action-procedures (cons proc action-procedures)) (proc) ) (define (get-action-procedures) action-procedures) (define (dispatch m) (cond ((eq? m 'get-signal) signal-value) ((eq? m 'set-signal!) set-my-signal!) ((eq? m 'add-action!) accept-action-procedure!) ((eq? m 'get-action) get-action-procedures) (else (error "Unknown operation --WIRE" m)))) dispatch)) (define (call-each procedures) (if (null? procedures) 'done (begin ((car procedures)) (call-each (cdr procedures))))) (define (get-signal wire) (wire 'get-signal)) (define (set-signal! wire new-value) ((wire 'set-signal!) new-value)) (define (add-action! wire action-procedure) ((wire 'add-action!) action-procedure)) ;; ์‹œ๊ฐ„ํ‘œ (define (after-delay delay action) (add-to-agenda! (+ delay (current-time the-agenda)) action the-agenda)) (define (propagate) (if (empty-agenda? the-agenda) 'done (let ((first-item (first-agenda-item the-agenda))) (first-item) (remove-first-agenda-item! the-agenda) (propagate)))) ;; ์‹œ๋ฎฌ๋ ˆ์ด์…˜ ํ•ด๋ณด๊ธฐ (define (probe name wire) (add-action! wire (lambda () (newline) (display name) (display " ") (display (current-time the-agenda)) (display " new-value = ") (display (get-signal wire))))) (define the-agenda (make-agenda)) (define inverter-delay 2) (define and-gate-delay 3) (define or-gate-delay 5) (define input-1 (make-wire)) (define input-2 (make-wire)) (define sum (make-wire)) (define carry (make-wire)) ;; ์—ฐ์Šต๋ฌธ์ œ 3.31 ;; ;; ์‹œ๊ฐ„ํ‘œ ๋งŒ๋“ค๊ธฐ (define (make-time-segment time queue) (cons time queue)) (define (segment-time s) (car s)) (define (segment-queue s) (cdr s)) (define (make-agenda) (list 0)) (define (current-time agenda) (car agenda)) (define (set-current-time! agenda time) (set-car! agenda time)) (define (segments agenda) (cdr agenda)) (define (set-segments! agenda segments) (set-cdr! agenda segments)) (define (first-segment agenda) (car (segments agenda))) (define (rest-segments agenda) (cdr (segments agenda))) (define (empty-agenda? agenda) (null? (segments agenda))) (define (add-to-agenda! time action agenda) (define (belongs-before? segments) (or (null? segments) (< time (segment-time (car segments))))) (define (make-new-time-segment time action) (let ((q (make-queue))) (insert-queue! q action) (make-time-segment time q))) (define (add-to-segments! segments) (if (= (segment-time (car segments)) time) (insert-queue! (segment-queue (car segments)) action) (let ((rest (cdr segments))) (if (belongs-before? rest) (set-cdr! segments (cons (make-new-time-segment time action) (cdr segments))) (add-to-segments! rest))))) (let ((segments (segments agenda))) (if (belongs-before? segments) (set-segments! agenda (cons (make-new-time-segment time action) segments)) (add-to-segments! segments)))) (define (remove-first-agenda-item! agenda) (let ((q (segment-queue (first-segment agenda)))) (delete-queue! q) (if (empty-queue? q) (set-segments! agenda (rest-segments agenda))))) (define (first-agenda-item agenda) (if (empty-agenda? agenda) (error "Agenda is empty -- FIRSTAGENDA-ITEM") (let ((first-seg (first-segment agenda))) (set-current-time! agenda (segment-time first-seg)) (front-queue (segment-queue first-seg)))))
false
b56016dd2a4469bf3421bae62925b67540510db0
92b8d8f6274941543cf41c19bc40d0a41be44fe6
/testsuite/srfi-45-test2.scm
d56f26b566d43707a5af222d298d6a3184e7ec36
[ "MIT" ]
permissive
spurious/kawa-mirror
02a869242ae6a4379a3298f10a7a8e610cf78529
6abc1995da0a01f724b823a64c846088059cd82a
refs/heads/master
2020-04-04T06:23:40.471010
2017-01-16T16:54:58
2017-01-16T16:54:58
51,633,398
6
0
null
null
null
null
UTF-8
Scheme
false
false
3,985
scm
srfi-45-test2.scm
; Run: kawa -f testsuite/srfi-45-test2.scm -e '(leak-test-1)' ; and so on up to '(leak-test-7) ; Should run contunuously without running out of memory or stack space; ; (leak-test-6) and (leak-test-7) do finish after running a while. ; If run as-is, does finish in a short time. ;========================================================================= ; Test leaks: All the leak tests should run in bounded space. ;========================================================================= ; Leak test 1: Infinite loop in bounded space. (define (loop) (lazy (loop))) (define (leak-test-1) (force (loop))) ;(leak-test-1) ;========================================================================= ; Leak test 2: Pending memos should not accumulate ; in shared structures. (define s2 (loop)) (define (leak-test-2) (force s2)) ;(leak-test-2) ;========================================================================= ; Leak test 3: Safely traversing infinite stream. (define (from n) (delay (cons n (from (+ n 1))))) (define (traverse s) (lazy (traverse (cdr (force s))))) (define (leak-test-3) (force (traverse (from 0)))) ;==> bounded space ;(leak-test-3) ;========================================================================= ; Leak test 4: Safely traversing infinite stream ; while pointer to head of result exists. (define s4 (traverse (from 0))) (define (leak-test-4) (force s4)) ;==> bounded space ;(leak-test-4) ;========================================================================= ; Convenient list deconstructor used below. (define-syntax match (syntax-rules () ((match exp (() exp1) ((h . t) exp2)) (let ((lst exp)) (cond ((null? lst) exp1) ((pair? lst) (let ((h (car lst)) (t (cdr lst))) exp2)) (else 'match-error)))))) ;======================================================================== ; Leak test 5: Naive stream-filter should run in bounded space. ; Simplest case. (define (stream-filter p? s) (lazy (match (force s) (() (delay '())) ((h . t) (if (p? h) (delay (cons h (stream-filter p? t))) (stream-filter p? t)))))) (define (leak-test-5) (force (stream-filter (lambda (n) (= n 10000000000)) (from 0)))) ;(leak=test-5) ;==> bounded space ;======================================================================== ; Leak test 6: Another long traversal should run in bounded space. ; The stream-ref procedure below does not strictly need to be lazy. ; It is defined lazy for the purpose of testing safe compostion of ; lazy procedures in the times3 benchmark below (previous ; candidate solutions had failed this). (define (stream-ref s index) (lazy (match (force s) (() 'error) ((h . t) (if (zero? index) (delay h) (stream-ref t (- index 1))))))) ; Check that evenness is correctly implemented - should terminate: (force (stream-ref (stream-filter zero? (from 0)) 0)) ;==> 0 (display (force (stream-ref (from 0) 200))) (newline) ;; Output: 200 (define s6 (stream-ref (from 0) 100000000)) (define (leak-test-6) (force s6)) ;==> bounded space ;(leak-test-6) ;====================================================================== ; Leak test 7: Infamous example from SRFI 40. (define (times3 n) (stream-ref (stream-filter (lambda (x) (zero? (modulo x n))) (from 0)) 3)) (display (force (times3 7))) (newline) ;; Output: 21 (define (leak-test-7) (force (times3 100000000))) ;==> bounded space ;(leak-test-7) (display "Ok.") (newline) ;; Output: Ok.
true
468472f4474fda2ff1fd4e9a34aad9712cf78d71
025c71211d8c0b4cf40c65d5add4c3d1fe10fa59
/acl2/intro-challenges/problem1.scm
47cb16b237ec0aa5f81849248a4d4e0a46f0653b
[]
no_license
gregr/experiments
5ce58d6ac6ae034d3955a96a434272ab3671bf6f
a6c5461bda9f8e221225a403f21d61ad4673c57a
refs/heads/master
2023-08-10T23:48:05.730805
2023-08-01T18:58:56
2023-08-01T18:58:56
4,839,336
9
2
null
null
null
null
UTF-8
Scheme
false
false
501
scm
problem1.scm
(defun rev (x) (if (endp x) nil (append (rev (cdr x)) (list (car x))))) ;Subgoal *1/2'' ;(IMPLIES (AND (CONSP X) ;(EQUAL (REV (REV (REV (CDR X)))) ;(REV (CDR X)))) ;(EQUAL (REV (REV (APPEND (REV (CDR X)) (LIST (CAR X))))) ;(APPEND (REV (CDR X)) (LIST (CAR X))))) (defthm double-rev (implies (true-listp x) (equal (rev (rev x)) x))) (thm (equal (rev (rev (rev x))) (rev x)))
false
682a03ba783cc30903bffed173d8569ea3b60bce
defeada37d39bca09ef76f66f38683754c0a6aa0
/System.Xml/system/xml/serialization/xml-reflection-member.sls
07ab64bf0aca9a3811704589ded41caf6e6101a4
[]
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
2,335
sls
xml-reflection-member.sls
(library (system xml serialization xml-reflection-member) (export new is? xml-reflection-member? is-return-value?-get is-return-value?-set! is-return-value?-update! member-name-get member-name-set! member-name-update! member-type-get member-type-set! member-type-update! override-is-nullable?-get override-is-nullable?-set! override-is-nullable?-update! soap-attributes-get soap-attributes-set! soap-attributes-update! xml-attributes-get xml-attributes-set! xml-attributes-update!) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Xml.Serialization.XmlReflectionMember a ...))))) (define (is? a) (clr-is System.Xml.Serialization.XmlReflectionMember a)) (define (xml-reflection-member? a) (clr-is System.Xml.Serialization.XmlReflectionMember a)) (define-field-port is-return-value?-get is-return-value?-set! is-return-value?-update! (property:) System.Xml.Serialization.XmlReflectionMember IsReturnValue System.Boolean) (define-field-port member-name-get member-name-set! member-name-update! (property:) System.Xml.Serialization.XmlReflectionMember MemberName System.String) (define-field-port member-type-get member-type-set! member-type-update! (property:) System.Xml.Serialization.XmlReflectionMember MemberType System.Type) (define-field-port override-is-nullable?-get override-is-nullable?-set! override-is-nullable?-update! (property:) System.Xml.Serialization.XmlReflectionMember OverrideIsNullable System.Boolean) (define-field-port soap-attributes-get soap-attributes-set! soap-attributes-update! (property:) System.Xml.Serialization.XmlReflectionMember SoapAttributes System.Xml.Serialization.SoapAttributes) (define-field-port xml-attributes-get xml-attributes-set! xml-attributes-update! (property:) System.Xml.Serialization.XmlReflectionMember XmlAttributes System.Xml.Serialization.XmlAttributes))
true
637ff4619146391f6d898c277da740bf087ef1ec
c101248570a9c3c6717547dbdf908b592406befb
/dl.ss
e1a0f516010c7959fc362c0a7ec68e989cecd181
[]
no_license
jeapostrophe/bulletml
6027c79bf6a1921cd6dbeb51f4d5fb5fab39b771
50baab9fae4065edf4011e2732e6f4d5231e2127
refs/heads/master
2020-05-17T09:52:47.918333
2013-10-31T01:14:27
2013-10-31T01:14:27
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,170
ss
dl.ss
#lang scheme (require "fake-typed.ss") ; XXX Add term language (define-struct: bulletdl ([type : (U 'vertical 'horizontal)] [top : (Option action)])) ; XXX Add data (define-struct: bullet ([direction : (Option direction)] [speed : (Option speed)] [params : (Vectorof Expression)] [action : (Option action)])) (define-type-alias action (U seqn repeat fire changeSpeed changeDirection accel wait vanish)) (define-struct: seqn ([actions : (Listof action)])) ; XXX Add data ; XXX Add firing many bullets (define-struct: fire ([direction : (Option direction)] [speed : (Option speed)] [bullet : bullet])) (define-struct: changeDirection ([direction : direction] [frames : Expression])) (define-struct: changeSpeed ([speed : speed] [frames : Expression])) (define-struct: accel ([horizontal : (Option horizontal)] [vertical : (Option vertical)] [frames : Expression])) (define-struct: wait ([frames : Expression])) (define-struct: vanish ()) (define-struct: repeat ([times : Expression] [action : action])) (define-struct: direction ([type : (U 'aim 'absolute 'relative 'sequence)] [degrees : Expression])) (define-struct: speed ([type : (U 'absolute 'relative 'sequence)] [units : Expression])) (define-struct: horizontal ([type : (U 'absolute 'relative 'sequence)] [units : Expression])) (define-struct: vertical ([type : (U 'absolute 'relative 'sequence)] [units : Expression])) (define-struct: stalled-params ([evector : (Vectorof Expression)] [inner : action])) (define-struct: saved-params ([pvector : (Vectorof Number)] [inner : action])) (define-struct: Expression ([value-or-fun : (U Number (Number (Vectorof Number) -> Number))])) (provide (all-defined-out))
false
c575a321af9389078842bfbe9adad19caf603d51
defeada37d39bca09ef76f66f38683754c0a6aa0
/System/system/net/mime/content-type.sls
d579b562db08a63c57b8eaaaf36947969eea0bbd
[]
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,863
sls
content-type.sls
(library (system net mime content-type) (export new is? content-type? get-hash-code to-string equals? boundary-get boundary-set! boundary-update! char-set-get char-set-set! char-set-update! media-type-get media-type-set! media-type-update! name-get name-set! name-update! parameters) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Net.Mime.ContentType a ...))))) (define (is? a) (clr-is System.Net.Mime.ContentType a)) (define (content-type? a) (clr-is System.Net.Mime.ContentType a)) (define-method-port get-hash-code System.Net.Mime.ContentType GetHashCode (System.Int32)) (define-method-port to-string System.Net.Mime.ContentType ToString (System.String)) (define-method-port equals? System.Net.Mime.ContentType Equals (System.Boolean System.Object)) (define-field-port boundary-get boundary-set! boundary-update! (property:) System.Net.Mime.ContentType Boundary System.String) (define-field-port char-set-get char-set-set! char-set-update! (property:) System.Net.Mime.ContentType CharSet System.String) (define-field-port media-type-get media-type-set! media-type-update! (property:) System.Net.Mime.ContentType MediaType System.String) (define-field-port name-get name-set! name-update! (property:) System.Net.Mime.ContentType Name System.String) (define-field-port parameters #f #f (property:) System.Net.Mime.ContentType Parameters System.Collections.Specialized.StringDictionary))
true
ee9f86f6fdc4f024d4c86745c7d08e0ffc17745d
483a1c3d153edd17f637ad1c304062776651fb33
/m-sol.scm
c981ba51db288e3ce0370e4e8783f6d7098a6250
[]
no_license
namin/lambdajam
c4fb047044676ba52c800c1343ffd4360afeb085
1ea7b3e424551c3d389199f392abb83ea27b046c
refs/heads/master
2023-08-30T19:54:06.203073
2023-08-12T19:56:36
2023-08-12T19:56:36
11,259,139
10
4
null
null
null
null
UTF-8
Scheme
false
false
674
scm
m-sol.scm
(load "test-check.scm") (load "pmatch.scm") (load "sugar.scm") (let () (define M (lambda (f) (lambda (xs) (if (null? xs) '() (cons (f (car xs)) ((M f) (cdr xs))))))) (eg ((M add1) '(1 2 3)) '(2 3 4))) ;;; CPS (let () (define M (lambda (f k) (k (lambda (xs k) (if (null? xs) (k '()) (M f (lambda (p) (p (cdr xs) (lambda (d) (f (car xs) (lambda (a) (k (cons a d))))))))))))) (eg (M (lambda (x k) (k (add1 x))) (lambda (p) (p '(1 2 3) (lambda (v) v)))) '(2 3 4)))
false
67de9f120c6c5fc37f9e48c1b3bc18cdbf57d172
46244bb6af145cb393846505f37bf576a8396aa0
/sicp/1_3.scm
33da67dab8508d28ce1aeef837aabfaaa1619512
[]
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
572
scm
1_3.scm
#lang racket ; Exercise 1.3. Define a procedure that ; takes three numbers as arguments and ; returns the sum of the squares of the two larger numbers. (define (squ-num n) (* n n)) (define (sum-squ n1 n2) (+ (squ-num n1) (squ-num n2))) (define (sum-squ-2 n1 n2 n3) (if (> n1 n2) (if (> n2 n3) (sum-squ n1 n2) (sum-squ n1 n3)) (if (> n1 n3) (sum-squ n1 n2) (sum-squ n2 n3)))) ; here are the tests (sum-squ-2 1 2 3) (sum-squ-2 1 3 2) (sum-squ-2 2 1 3) (sum-squ-2 2 3 1) (sum-squ-2 3 1 2) (sum-squ-2 3 2 1)
false
0f78bfddcca4786ac4a5cc2858fe1ff5503458ed
40f36bb0b41c6a27b2e4802ddb128f7354ea38a3
/self/schemeR7RS/lib/parse.sld
8f6c106d79de58749bb6ffac030c6abe88670d82
[]
no_license
simalaia/modules
b5d2d4c015646b0ea9edc17576a31493f520197c
45f58e17b1faab48c6f0c46cb17cc010f30872fe
refs/heads/main
2023-04-05T19:42:12.407065
2021-04-22T22:05:04
2021-04-22T22:05:04
343,354,627
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,324
sld
parse.sld
;; -*- mode:scheme -*- ;; Attempts at implementing the clojure transducer idea (define-library (lib parse) (import (chibi) ;; (chibi match) (lib misc) ;;(scheme case-lambda) (only (scheme base) define-record-type) ;;(scheme cxr) (only (scheme base) symbol=? when unless) ) (export skip-const read-const oneof range skip skip-until skip-while reads read-until read-while ) (begin (define (sar s) (substring s 0 1) ) (define (sdr s) (substring s 1 (string-length s)) ) (define (char s) (if (and (string? s) (= (string-length s) 1)) (car (string->list s)) s) ) (define (explode s) (cond ((string=? s "") '() ) (#t (cons (char (sar s)) (explode (sdr s))) )) ) (define (implode s) (apply string-append (map string s))) (define (skip-const s) (let ( (s (explode s)) ) (lambda (p) (let lop ( (s s) ) (cond ((or (null? s) (eof-object? (peek-char p))) '() ) ((char=? (car s) (char (peek-char p))) (read-char p) (lop (cdr s)) )) )) )) (define (read-const s) (let ( (s (explode s)) ) (lambda (p) (let lop ( (s s) ) (cond ((or (null? s) (eof-object? (peek-char p))) '() ) ((char=? (car s) (char (peek-char p))) (let ( (c (read-char p)) ) (cons c (lop (cdr s))) ) ) (#t '() )) )) )) (define (skip ? p) (cond ((or (eof-object? (peek-char p)) (not (? (peek-char p)))) '() ) (#t (read-char p) (skip ? p) )) ) (define (reads ? p) (cond ((or (eof-object? (peek-char p)) (not (? (peek-char p)))) '() ) (#t (let ( (c (read-char p)) ) (cons c (reads ? p)) ) )) ) (define (oneof s) (let ( (s (map char (string->list s))) ) (lambda (x) (did? (member (char x) s))) )) (define (range s) (define (nextchar r) (integer->char (+ 1 (char->integer (char r)))) ) (let ( (s (let lop ( (b (sar s)) (e (sdr s)) ) (cond ((char=? (char b) (char e)) `(,(char e)) ) (#t (cons (char b) (lop (string (nextchar b)) e)) )) )) ) (lambda (x) (did? (member (char x) s))) )) (define (skip-until ?) (lambda (p) (skip (lambda (x) (not (? x)) ) p) )) (define (skip-while ?) (lambda (p) (skip ? p) )) (define (read-until ?) (lambda (p) (reads (lambda (x) (not (? x)) ) p) )) (define (read-while ?) (lambda (p) (reads ? p) )) ) )
false
1d1770bfbe58987b8e804404f271a0547917f241
f6c954bac9db8e566fdd24249a4970dd759455eb
/PT-1300012785-2.33.scm
fd71b77cbef28f5bf6cf6bbd9a0a1a96f304f543
[]
no_license
yangzhixuan/sicp_hw
247de20628128345d22b417b86b30ce981cdaa12
48b67ec630cf5b57954ae7e18e4c1d915db148b9
refs/heads/master
2021-01-13T02:16:57.495913
2014-05-14T07:49:23
2014-05-14T07:49:23
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
334
scm
PT-1300012785-2.33.scm
(define (accumulate combiner init l) (if (null? l) init (combiner (car l) (accumulate combiner init (cdr l))))) (define (map p l) (accumulate (lambda (x y) (cons (p x) y)) '() l)) (define (append l1 l2) (accumulate cons l2 l1)) (define (length l) (accumulate (lambda (x y) (+ 1 y)) 0 l))
false
4cd0590d2a955930c3f48e2a5c3f3e149ac121c8
eef5f68873f7d5658c7c500846ce7752a6f45f69
/test/codec-bignum.scm
8a881591b617912d93fc306c6e75ca48963b984b
[ "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
54
scm
codec-bignum.scm
(##spheres-load core: testing) (##spheres-load util)
false
bebdad255d511acbc73616ea3f56270ede844452
c5de45adc74a609415f9318fda24479561a5728b
/7b.ss
a3708a6e9a9fb45aa4a151de2dd70938988acd3e
[]
no_license
rhit-zhuz9/CSSE304
8b7498336cf9573b18b3cd0f5654ddfb1b1dfc69
f3a10bf17ca1daa532f277a0cf4f7c9746ea89e7
refs/heads/master
2023-03-15T11:54:52.913169
2018-05-30T03:00:43
2018-05-30T03:00:43
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,591
ss
7b.ss
; CSSE304-01 Yuankai Wang (Kevin) Assignment7b ; Problem 6 (define map-by-position (lambda (fn-list arg-list) (map (lambda (a b) (a b)) fn-list arg-list))) ; Problem 7 (define bt-leaf-sum (lambda (T) (bt-leaf-sum-node T))) (define bt-leaf-sum-node (lambda (T) (if (list? T) (+ (bt-leaf-sum-node (cadr T)) (bt-leaf-sum-node (caddr T))) T))) (define bt-inorder-list (lambda (T) (bt-inorder-list-node T))) (define bt-inorder-list-node (lambda (T) (if (list? T) (if (or (list? (cadr T)) (list? (caddr T))) (append (bt-inorder-list-node (cadr T)) (list (car T)) (bt-inorder-list-node (caddr T))) (list (car T))) '()))) (define bt-max (lambda (T) (bt-max-node T))) (define bt-max-node (lambda (T) (if (list? T) (max (bt-max-node (cadr T)) (bt-max-node (caddr T))) T))) (define bt-max-interior (lambda (T) (third (bt-max-interior-fourcases T)))) (define first (lambda (list) (car list))) (define second ;left (lambda (list) (cadr list))) (define third ;right (lambda (list) (caddr list))) (define bt-max-interior-fourcases (lambda (T) (cond [(and (number? (second T)) (number? (third T))) (list (+ (second T) (third T)) (+ (second T) (third T)) (first T))]; A list that first element is the largest sum, second element is the sum under current letter, third element is the largest letter [(number? (second T)) (let* ([right (bt-max-interior-fourcases (third T))] [the-max (max (first right) (+ (second right) (second T)))]) (if (equal? the-max (first right)) (list (first right) (+ (second right) (second T)) (third right)) (list (+ (second right) (second T)) (+ (second right) (second T)) (first T))))] [(number? (third T)) (let* ([left (bt-max-interior-fourcases (second T))] [the-max (max (first left) (+ (second left) (third T)))]) (if (equal? the-max (first left)) (list (first left) (+ (second left) (third T)) (third left)) (list (+ (second left) (third T)) (+ (second left) (third T)) (first T))))] [else (let* ([left (bt-max-interior-fourcases (second T))] [right (bt-max-interior-fourcases (third T))] [the-max (max (first left) (first right) (+ (second right) (second left)))]) (cond [(equal? the-max (first left)) (list (first left) (+ (second right) (second left)) (third left))] [(equal? the-max (first right)) (list (first right) (+ (second right) (second left)) (third right))] [else (list (+ (second right) (second left)) (+ (second right) (second left)) (first T))]))])))
false
772236790932d57ffb3bedfece1bd3ee5c3553b8
defeada37d39bca09ef76f66f38683754c0a6aa0
/System/system/code-dom/code-direction-expression.sls
af5919d3e42220f6a58bb687365ea2c0924a81a4
[]
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,005
sls
code-direction-expression.sls
(library (system code-dom code-direction-expression) (export new is? code-direction-expression? direction-get direction-set! direction-update! expression-get expression-set! expression-update!) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.CodeDom.CodeDirectionExpression a ...))))) (define (is? a) (clr-is System.CodeDom.CodeDirectionExpression a)) (define (code-direction-expression? a) (clr-is System.CodeDom.CodeDirectionExpression a)) (define-field-port direction-get direction-set! direction-update! (property:) System.CodeDom.CodeDirectionExpression Direction System.CodeDom.FieldDirection) (define-field-port expression-get expression-set! expression-update! (property:) System.CodeDom.CodeDirectionExpression Expression System.CodeDom.CodeExpression))
true
03cbc719b33f43d981d434d434232861feae6db9
e82d67e647096e56cb6bf1daef08552429284737
/ex3-30.scm
dbeca4345d01c689a4e5a0dca60b366d5003c118
[]
no_license
ashishmax31/sicp-exercises
97dfe101dd5c91208763dcc4eaac2c17977d1dc1
097f76a5637ccb1fba055839d389541a1a103e0f
refs/heads/master
2020-03-28T11:16:28.197294
2019-06-30T20:25:18
2019-06-30T20:25:18
148,195,859
6
0
null
null
null
null
UTF-8
Scheme
false
false
3,191
scm
ex3-30.scm
(define (or-gate a1 a2 output) (define (or-action) (let ((new-output (logical-or (get-signal a1) (get-signal a2)))) (after-delay or-gate-delay (lambda () (set-signal! output new-output))))) (add-action! a1 or-action) (add-action! a2 or-action)) (define (and-gate a1 a2 output) (define (and-action) (let ((new-output (logical-and (get-signal a1) (get-signal a2)))) (after-delay and-gate-delay (lambda () (set-signal! output new-output))))) (add-action! a1 and-action) (add-action! a2 and-action)) (define (not-gate a output) (define (invert-input) (let ((new-output (logical-not a))) (after-delay not-gate-delay (lambda () (set-signal! output new-output))))) (add-action! a invert-input)) (define (logical-not a) (cond ((= a 0) 1) ((= a 1) 0) (else (error "Unsupported signal in the wire!")))) (define (logical-or a1 a2) (cond ((and (= a1 0) (= a2 0)) 0) ((or (= a1 1) (= a2 1)) 1) (else (error "Unsupported signal in the wire!")))) (define (logical-and a1 a2) (cond ((or (= a1 0) (= a2 0)) 0) ((and (= a1 1) (= a2 1)) 1) (else (error "Unsupported signal in the wire!")))) (define (half-adder a b sum carry) (let ((a1 (make-wire)) (a2 (make-wire))) (or-gate a b a1) (and-gate a b carry) (not-gate carry a2) (and-gate a2 a1 sum))) (define (full-adder a b c-in sum c-out) (let ((a1 (make-wire)) (a2 (make-wire)) (a3 (make-wire))) (half-adder b c-in a1 a2) (half-adder a a1 sum a3) (or-gate a3 a2 c-out))) (define (ripple-carry-adder a-lines b-lines sum-lines carry) (if (equal? (length a-lines) (length b-lines)) (ripple-carry-adder-helper (reverse a-lines) (reverse b-lines) carry (reverse sum-lines) (make-wire)) (error "Expected same number of inputs in both the input lines!"))) (define (ripple-carry-adder-helper a-lines b-lines carry-out sum-lines previous-carry) (if (last-bit? a-lines) (full-adder (car a-lines) (car b-lines) previous-carry (car sum-lines) carry-out ) (let ((carry-for-the-next-adder (make-wire))) (full-adder (car a-lines) (car b-lines) previous-carry (car sum-lines) carry-for-the-next-adder) (ripple-carry-adder-helper (cdr a-lines) (cdr b-lines) carry-out (cdr sum-lines) carry-for-the-next-adder)))) (define (last-bit? line) (equal? (length line) 1))
false
d15645a9db3b97dda32f0039e840d6f0d7254553
a4d6eeda1e8e80653fb874bd04883c212f19a9fb
/sweep-test.ss
b482be191e37d6099ee5036e4e268e2daac7664d
[]
no_license
mml/incr
a199ff01f41238775730fceb75db41d86045017a
5b9657dcecc9474ee88c2b78369374f2dc0bcd38
refs/heads/master
2023-01-01T12:32:36.980967
2020-10-27T11:17:13
2020-10-27T11:17:13
282,290,358
0
0
null
null
null
null
UTF-8
Scheme
false
false
181
ss
sweep-test.ss
(require "test-driver.ss") (let f ([i 0]) (cond [(<= i (sub1 (expt 2 29))) (/test-case i (number->string i)) (f (add1 i))] [else (void)]))
false
36eabe27347d4a1de82a4e78647ccddcb5abaf3d
f782cd9c608a6aaac795d6a0758681e5caf08e11
/options.sm
91e2ff944043697d9a9a3e929bdb795f3392b9c0
[]
no_license
plesner/scsh
7d4d6ab632da4188e8c4ab0c9123878e5711d1c5
f4f2e7f7f9c73737f0acb2b19e7f7f3e78218f25
refs/heads/master
2016-09-05T09:47:12.069802
2015-05-31T10:07:44
2015-05-31T10:07:44
18,053,607
6
0
null
null
null
null
UTF-8
Scheme
false
false
1,840
sm
options.sm
; -*- mode: scheme -*- ; ; Command-line option parser. (define (option-parser* options) ; Returns a list whose car is the first n elements of the given list ; and whose cdr is the remaining elements, after the first n. (define (split-list list n) (cond ((= 0 n) (cons '() list)) ((and (null? list) (< 0 n)) #f) (else (let ((tail (split-list (cdr list) (- n 1)))) (if tail (cons (cons (car list) (car tail)) (cdr tail)) tail))))) ; Process the given list of arguments and return a list of elements ; that were not recognized as options. (define (process args) (if (null? args) '() (let* ((arg (car args)) (match (assq (string->symbol arg) options))) (if match (let* ((arg-count (cadr match)) (arg-fun (caddr match)) (split (split-list (cdr args) arg-count))) (if split (let ((param-args (car split)) (rest (cdr split))) (apply arg-fun param-args) (process rest)))) (cons arg (process (cdr args))))))) process) (define-syntax *option-parse-transform* (syntax-rules () ((*option-parse-transform*) '()) ((*option-parse-transform* ((name arg) body ...) . rest) (cons `(name 1 ,(lambda (arg) body ...)) (*option-parse-transform* . rest))) ((*option-parse-transform* (name body ...) . rest) (cons `(name 0 ,(lambda () body ...)) (*option-parse-transform* . rest))))) ; Define a function that processes command-line arguments. (define-syntax option-parser (syntax-rules () ((option-parser . body) (option-parser* (*option-parse-transform* . body)))))
true
15e0485594f0cbe30c5daef24a8e0ea815cb4d5b
a416300cfff2efcf5749349330566b7db70cf4a6
/negative-tests/testSetIntegrity.scm
ff99a7706646c42d073ddb0d49ea88bfe8643fba
[]
no_license
lukaspj/LaBSec-Project
c4e24ba395a990c8facd24d8a4cb5780bfa69e20
47f37726f7531080b14f4039276968e942b34c02
refs/heads/master
2020-04-02T03:07:49.662099
2016-06-13T10:04:41
2016-06-13T10:04:41
58,653,567
0
0
null
2016-06-12T11:54:08
2016-05-12T15:26:05
Scheme
UTF-8
Scheme
false
false
174
scm
testSetIntegrity.scm
(load "framework.scm") (define a (label-lambda '(label (integrity . 0) ()) () '(label (integrity . 0) ()) 42)) (set! a 3)
false
4a9bdff5d84bf4e59271b775b16a1417f53dd43b
4bd59493b25febc53ac9e62c259383fba410ec0e
/Scripts/Task/averages-simple-moving-average/scheme/averages-simple-moving-average.ss
13e5fbc594381d0a301d7122e7c276b564b417e0
[]
no_license
stefanos1316/Rosetta-Code-Research
160a64ea4be0b5dcce79b961793acb60c3e9696b
de36e40041021ba47eabd84ecd1796cf01607514
refs/heads/master
2021-03-24T10:18:49.444120
2017-08-28T11:21:42
2017-08-28T11:21:42
88,520,573
5
1
null
null
null
null
UTF-8
Scheme
false
false
248
ss
averages-simple-moving-average.ss
(define ((simple-moving-averager size . nums) num) (set! nums (cons num (if (= (length nums) size) (reverse (cdr (reverse nums))) nums))) (/ (apply + nums) (length nums))) (define av (simple-moving-averager 3)) (map av '(1 2 3 4 5 5 4 3 2 1))
false
d608ed3f758ce1b8953ce3c53d8ce350f0ff49bd
fb9a1b8f80516373ac709e2328dd50621b18aa1a
/ch2/exercise2-43.scm
51449daa6a5ed69410e44d4428471bd5547e837c
[]
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
1,060
scm
exercise2-43.scm
;; ๅ•้กŒ2.43 ; Louis Reasoner ใฏๅ•้กŒ2.42ใ‚’ใ‚„ใ‚‹ใฎใซใŠใใ‚ใ—ใๆ™‚้–“ใŒใ‹ใ‹ใฃใŸ ; ๅฝผใฎๆ‰‹็ถšใqueensใฏๅ‹•ใใŒใ™ใ”ใ้…ใ„ ; Eva Lu AtorใซๅŠฉใ‘ใ‚’ๆฑ‚ใ‚ใŸใจใ๏ผŒๅฝผๅฅณใฏๅฝผใŒflatmapใฎๅ†™ๅƒใฎๅ…ฅใ‚Œๅญใฎ้ †็•ชใ‚’ๅ…ฅใ‚Œๆ›ฟใˆใฆ (flatmap (lambda (new-row) (map (lambda (rest-of-queens) (adjoin-position new-row k rest-of-queens)) (queen-cols (- k 1)))) (enumerate-interval 1 board-size)) ; ๅ…ƒใฎ็‰ˆ (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))) ; ใจๆ›ธใ„ใฆใ„ใŸ ; ใชใœ้…ใ„ใฎใ‹ ; ๅ•้กŒ2.42ใฎๅ‡ฆ็†ๆ™‚้–“ใ‚’Tใจใ—ใŸใจใLouisใฎใƒ—ใƒญใ‚ฐใƒฉใƒ ใฏใฉใฎใใ‚‰ใ„ใ‹ใ‹ใ‚‹ใฎใ‹ ; ๅ‚่€ƒ ; http://www.serendip.ws/archives/798 ; ้…ใ„ๆ–นใ ใจ๏ผŒenumerate-intervalๅˆ†ใ ใ‘queen-colsใ‚’่จˆ็ฎ—ใ™ใ‚‹ๅฟ…่ฆใŒใ‚ใ‚‹ ; ้€šๅธธใฎ็‰ˆใ ใจ๏ผŒenumerate-intervalใฎใƒซใƒผใƒ—ใฏไธ€ๅ›žใงใ™ใ‚€ ; T * board-size ^ borad-size ; ใฎๆ™‚้–“ใŒใ‹ใ‹ใ‚‹
false
37047d2fb9a08f45b158473c4ee933846d8784a7
eef5f68873f7d5658c7c500846ce7752a6f45f69
/spheres/crypto/hmac.sld
fab97bf2c257b092e2ff959dff2d82dcd4b62c78
[ "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
436
sld
hmac.sld
(define-library (spheres/crypto hmac) (export hmac-u8vector hmac-subu8vector hmac-ansi-string hmac-ansi-substring hmac-string hmac-substring hmac-crc32 hmac-md5 hmac-sha-1 hmac-sha-224 hmac-sha-256) (import (spheres/algorithm u8vector) (spheres/string u8vector) (spheres/crypto digest)) (include "hmac.scm"))
false
a201ef3ef2736028780c08b4405c3fa2cddb5540
b946259dec865fd015e98ad09212692dcd0ee073
/interpreter/objects.scm
81906a4391db3c57303c08f7f07cc25b8d56441b
[ "MIT" ]
permissive
TurtleKitty/Vaquero
5e5ce1419bcd0fe841d8cd3d791d1a9174bac022
d4c3823f7f7a88a67679ee774532d499ef1ac982
refs/heads/master
2021-06-09T14:45:54.658784
2021-05-28T04:31:09
2021-05-28T04:31:09
81,528,904
22
2
MIT
2020-02-06T01:50:16
2017-02-10T05:08:28
Scheme
UTF-8
Scheme
false
false
3,521
scm
objects.scm
(define-record-type vaq-obj (vaquero-udo fields autos forwards default) vaquero-object? (fields vaquero-obj-fields) (autos vaquero-obj-autos) (forwards vaquero-obj-forwards) (default vaquero-obj-default vaquero-obj-set-default!)) (define (vaquero-object-get-message fields forwards msg) (if (hte? fields msg) (htr fields msg) (if (hte? forwards msg) (htr forwards msg) #f))) (define (default-udo-type this fields forwards) (define type (vaquero-object-get-message fields forwards 'type)) (if type (if (and (list? type) (every symbol? type)) 'cool (vaquero-warning 'improper-type `(object 'type ,type) "An object type must be a list of symbols.")) (hts! fields 'type '(object)))) (define (default-udo-view this fields forwards) (define autos (vaquero-obj-autos this)) (define has-view (hte? fields 'view)) (if has-view (let ((view-obj (htr fields 'view))) (define view-obj-messages (vaquero-send-atomic view-obj 'messages)) (define has-apply (member 'apply view-obj-messages)) (define has-arity (member 'arity view-obj-messages)) (define view-view (vaquero-send-atomic view-obj 'view)) (define (wrong) (write (htr fields 'type)) (newline) (write view-obj-messages) (newline) (vaquero-warning 'view-must-be-a-thunk `(object 'view ,(vaquero-view view-obj)) "The 'view message of a user-defined object must be a thunk.")) (if (eq? view-view primitive-code) 'ignore-it (if (and has-apply has-arity) (let* ((arity (vaquero-send-atomic view-obj 'arity)) (zero-arity (and (number? arity) (= 0 arity)))) (if zero-arity 'cool (wrong))) (wrong)))) (let () (define type (car (htr fields 'type))) (define messages (append (htks fields) (htks forwards))) (hts! fields 'view (lambda () (apply vector (cons type messages)))))) (hts! autos 'view #t)) (define (default-udo-eq? this fields forwards) (define eq?-msg (vaquero-object-get-message fields forwards 'eq?)) (if eq?-msg 'cool (hts! fields 'eq? (lambda (other) (eq? this other))))) (define (default-udo-idk this) (vaquero-proc primitive-code 'object (lambda (args opts cont err) (idk this (car args) cont err)))) (define (vaquero-set-udo-defaults this) (define fields (vaquero-obj-fields this)) (define forwards (vaquero-obj-forwards this)) (define default (vaquero-obj-default this)) (default-udo-type this fields forwards) (default-udo-view this fields forwards) (default-udo-eq? this fields forwards) (vaquero-obj-set-default! this (or default (default-udo-idk this)))) (define (vaquero-object args autos forwards initial) (define fields (mkht)) (define delegates (mkht)) (define autoexec (mkht)) (define (fset! k v) (hts! fields k v)) (define (aset! k) (hts! autoexec k #t)) (define (rset! k v) (hts! delegates k v)) (define (set-forward! rlist) (let ((delegate (car rlist)) (msgs (cdr rlist))) (map (lambda (msg) (rset! msg delegate)) msgs))) (for-pairs fset! args) (if forwards (map set-forward! forwards)) (if autos (map aset! autos)) (let ((this (vaquero-udo fields autoexec delegates initial))) (vaquero-set-udo-defaults this) this))
false
1cd6dfb420eddf6d0265dd67ce885e554e470146
98fd12cbf428dda4c673987ff64ace5e558874c4
/sicp/v3/1.2/shikhar/1.11.scm
02f6c0979de2d14edabb0e09cac65aafc0b80193
[ "Unlicense" ]
permissive
CompSciCabal/SMRTYPRTY
397645d909ff1c3d1517b44a1bb0173195b0616e
a8e2c5049199635fecce7b7f70a2225cda6558d8
refs/heads/master
2021-12-30T04:50:30.599471
2021-12-27T23:50:16
2021-12-27T23:50:16
13,666,108
66
11
Unlicense
2019-05-13T03:45:42
2013-10-18T01:26:44
Racket
UTF-8
Scheme
false
false
250
scm
1.11.scm
(define (f n) (if (< n 3) n (+ (f (- n 1)) (* 2 (f (- n 2))) (* 3 (f (- n 3)))))) (define (f n) (define (f-iter a b c count) (if (= count 0) c (f-iter b c (+ c (* 2 b) (* 3 a)) (- count 1)))) (if (< n 3) n (f-iter 0 1 2 (- n 2))))
false
bc920ad5acaac056454a56be693d1d1039ab9f2c
495f2fe2a919d687d17fc78f9a3ada45b908ee09
/rlists-impl.scm
315a0c40d4ed9f017fdf386496c9bc51c52a8bc6
[]
no_license
pre-srfi/rlists
95b99f886a59e269d0c905f1da01fccbc780d7a3
1f13811f46ae4366c19cd4c179aa50141d53a53a
refs/heads/master
2022-12-11T14:58:33.421239
2020-09-11T23:48:45
2020-09-11T23:48:45
294,834,094
0
0
null
null
null
null
UTF-8
Scheme
false
false
13,521
scm
rlists-impl.scm
(define-record-type kons (make-kons size tree rest) kons? (size kons-size) (tree kons-tree) (rest kons-rest)) (define-record-type node (make-node val left right) node? (val node-val) (left node-left) (right node-right)) ;; Nat -> Nat (define (sub1 n) (- n 1)) (define (add1 n) (+ n 1)) ;; [Tree X] -> X (define (tree-val t) (if (node? t) (node-val t) t)) ;; [X -> Y] [Tree X] -> [Tree Y] (define (tree-map f t) (if (node? t) (make-node (f (node-val t)) (tree-map f (node-left t)) (tree-map f (node-right t))) (f t))) ;; [X -> Y] [Tree X] -> unspecified (define (tree-for-each f t) (if (node? t) (begin (f (node-val t)) (tree-for-each f (node-left t)) (tree-for-each f (node-right t))) (f t))) ;; [X Y Z ... -> R] [List [Tree X] [Tree Y] [Tree Z] ...] -> [Tree R] (define (tree-map/n f ts) (let recr ((ts ts)) (if (and (pair? ts) (node? (car ts))) (make-node (apply f (map node-val ts)) (recr (map node-left ts)) (recr (map node-right ts))) (apply f ts)))) ;; [X Y Z ... -> R] [List [Tree X] [Tree Y] [Tree Z] ...] -> unspecified (define (tree-for-each/n f ts) (let recr ((ts ts)) (if (and (pair? ts) (node? (car ts))) (begin (apply f (map node-val ts)) (recr (map node-left ts)) (recr (map node-right ts))) (apply f ts)))) ;; Nat [Nat -> X] -> [Tree X] ;; like build-list, but for complete binary trees (define (build-tree i f) ;; i = 2^j-1 (let rec ((i i) (o 0)) (if (= 1 i) (f o) (let ((i/2 (half i))) (make-node (f o) (rec i/2 (add1 o)) (rec i/2 (+ 1 o i/2))))))) ;; Consumes n = 2^i-1 and produces 2^(i-1)-1. ;; Nat -> Nat (define (half n) (arithmetic-shift n -1)) ;; Nat X -> [Tree X] (define (tr:make-tree i x) ;; i = 2^j-1 (let recr ((i i)) (if (= 1 i) x (let ((n (recr (half i)))) (make-node x n n))))) ;; Nat [Tree X] Nat [X -> X] -> X [Tree X] (define (tree-ref/update mid t i f) (cond ((zero? i) (if (node? t) (values (node-val t) (make-node (f (node-val t)) (node-left t) (node-right t))) (values t (f t)))) ((<= i mid) (let-values (((v* t*) (tree-ref/update (half (sub1 mid)) (node-left t) (sub1 i) f))) (values v* (make-node (node-val t) t* (node-right t))))) (else (let-values (((v* t*) (tree-ref/update (half (sub1 mid)) (node-right t) (sub1 (- i mid)) f))) (values v* (make-node (node-val t) (node-left t) t*)))))) ;; Special-cased above to avoid logarathmic amount of cons'ing ;; and any multi-values overhead. Operates in constant space. ;; [Tree X] Nat Nat -> X ;; invariant: (= mid (half (sub1 (tree-count t)))) (define (tree-ref/a t i mid) (cond ((zero? i) (tree-val t)) ((<= i mid) (tree-ref/a (node-left t) (sub1 i) (half (sub1 mid)))) (else (tree-ref/a (node-right t) (sub1 (- i mid)) (half (sub1 mid)))))) ;; Nat [Tree X] Nat -> X ;; invariant: (= size (tree-count t)) (define (tree-ref size t i) (if (zero? i) (tree-val t) (tree-ref/a t i (half (sub1 size))))) ;; Nat [Tree X] Nat [X -> X] -> [Tree X] (define (tree-update size t i f) (let recr ((mid (half (sub1 size))) (t t) (i i)) (cond ((zero? i) (if (node? t) (make-node (f (node-val t)) (node-left t) (node-right t)) (f t))) ((<= i mid) (make-node (node-val t) (recr (half (sub1 mid)) (node-left t) (sub1 i)) (node-right t))) (else (make-node (node-val t) (node-left t) (recr (half (sub1 mid)) (node-right t) (sub1 (- i mid)))))))) ;; ------------------------ ;; Random access lists ;; [RaListof X] (define rnull (quote ())) ;; [Any -> Boolean] (define rpair? kons?) ;; [Any -> Boolean] (define rnull? null?) ;; X [RaListof X] -> [RaListof X] /\ ;; X Y -> [RaPair X Y] (define (rcons x ls) (if (kons? ls) (let ((s (kons-size ls))) (if (and (kons? (kons-rest ls)) (= (kons-size (kons-rest ls)) s)) (make-kons (+ 1 s s) (make-node x (kons-tree ls) (kons-tree (kons-rest ls))) (kons-rest (kons-rest ls))) (make-kons 1 x ls))) (make-kons 1 x ls))) ;; [RaPair X Y] -> X Y (define rcar+cdr (lambda (p) ;(assert (kons? p)) (if (node? (kons-tree p)) (let ((s* (half (kons-size p)))) (values (tree-val (kons-tree p)) (make-kons s* (node-left (kons-tree p)) (make-kons s* (node-right (kons-tree p)) (kons-rest p))))) (values (kons-tree p) (kons-rest p))))) ;; [RaPair X Y] -> X (define (rcar p) (call-with-values (lambda () (rcar+cdr p)) (lambda (car cdr) car))) ;; [RaPair X Y] -> Y (define (rcdr p) (call-with-values (lambda () (rcar+cdr p)) (lambda (car cdr) cdr))) ;; [RaListof X] Nat [X -> X] -> X [RaListof X] (define (rlist-ref/update ls i f) ;(assert (< i (rlength ls))) (let recr ((xs ls) (j i)) (if (< j (kons-size xs)) (let-values (((v* t*) (tree-ref/update (half (sub1 (kons-size xs))) (kons-tree xs) j f))) (values v* (make-kons (kons-size xs) t* (kons-rest xs)))) (let-values (((v* r*) (recr (kons-rest xs) (- j (kons-size xs))))) (values v* (make-kons (kons-size xs) (kons-tree xs) r*)))))) ;; [RaListof X] Nat [X -> X] -> [RaListof X] (define (rlist-update ls i f) ;(assert (< i (rlength ls))) (let recr ((xs ls) (j i)) (let ((s (kons-size xs))) (if (< j s) (make-kons s (tree-update s (kons-tree xs) j f) (kons-rest xs)) (make-kons s (kons-tree xs) (recr (kons-rest xs) (- j s))))))) ;; [RaListof X] Nat X -> (values X [RaListof X]) (define (rlist-ref/set ls i v) (rlist-ref/update ls i (lambda (_) v))) ;; X ... -> [RaListof X] (define (rlist . xs) (fold-right rcons rnull xs)) ;; Nat X -> [RaListof X] (define make-rlist (case-lambda ((k) (make-rlist k 0)) ((k obj) (let loop ((n k) (a rnull)) (cond ((zero? n) a) (else (let ((t (largest-skew-binary n))) (loop (- n t) (make-kons t (tr:make-tree t obj) a))))))))) ;; A Skew is a Nat 2^k-1 with k > 0. ;; Skew -> Skew (define (skew-succ t) (add1 (arithmetic-shift t 1))) ;; Computes the largest skew binary term t <= n. ;; Nat -> Skew (define (largest-skew-binary n) (if (= 1 n) 1 (let* ((t (largest-skew-binary (half n))) (s (skew-succ t))) (if (> s n) t s)))) ;; [Any -> Boolean] ;; Is x a PROPER list? (define (rlist? x) (or (rnull? x) (and (kons? x) (rlist? (kons-rest x))))) (define rcaar (lambda (ls) (rcar (rcar ls)))) (define rcadr (lambda (ls) (rcar (rcdr ls)))) (define rcddr (lambda (ls) (rcdr (rcdr ls)))) (define rcdar (lambda (ls) (rcdr (rcar ls)))) (define rcaaar (lambda (ls) (rcar (rcar (rcar ls))))) (define rcaadr (lambda (ls) (rcar (rcar (rcdr ls))))) (define rcaddr (lambda (ls) (rcar (rcdr (rcdr ls))))) (define rcadar (lambda (ls) (rcar (rcdr (rcar ls))))) (define rcdaar (lambda (ls) (rcdr (rcar (rcar ls))))) (define rcdadr (lambda (ls) (rcdr (rcar (rcdr ls))))) (define rcdddr (lambda (ls) (rcdr (rcdr (rcdr ls))))) (define rcddar (lambda (ls) (rcdr (rcdr (rcar ls))))) (define rcaaaar (lambda (ls) (rcar (rcar (rcar (rcar ls)))))) (define rcaaadr (lambda (ls) (rcar (rcar (rcar (rcdr ls)))))) (define rcaaddr (lambda (ls) (rcar (rcar (rcdr (rcdr ls)))))) (define rcaadar (lambda (ls) (rcar (rcar (rcdr (rcar ls)))))) (define rcadaar (lambda (ls) (rcar (rcdr (rcar (rcar ls)))))) (define rcadadr (lambda (ls) (rcar (rcdr (rcar (rcdr ls)))))) (define rcadddr (lambda (ls) (rcar (rcdr (rcdr (rcdr ls)))))) (define rcaddar (lambda (ls) (rcar (rcdr (rcdr (rcar ls)))))) (define rcdaaar (lambda (ls) (rcdr (rcar (rcar (rcar ls)))))) (define rcdaadr (lambda (ls) (rcdr (rcar (rcar (rcdr ls)))))) (define rcdaddr (lambda (ls) (rcdr (rcar (rcdr (rcdr ls)))))) (define rcdadar (lambda (ls) (rcdr (rcar (rcdr (rcar ls)))))) (define rcddaar (lambda (ls) (rcdr (rcdr (rcar (rcar ls)))))) (define rcddadr (lambda (ls) (rcdr (rcdr (rcar (rcdr ls)))))) (define rcddddr (lambda (ls) (rcdr (rcdr (rcdr (rcdr ls)))))) (define rcdddar (lambda (ls) (rcdr (rcdr (rcdr (rcar ls)))))) ;; [RaList X] -> Nat (define (rlength ls) ;(assert (rlist? ls)) (let recr ((ls ls)) (if (kons? ls) (+ (kons-size ls) (recr (kons-rest ls))) 0))) (define (make-foldl empty? first rest) (letrec ((f (lambda (cons empty ls) (if (empty? ls) empty (f cons (cons (first ls) empty) (rest ls)))))) f)) (define (make-foldr empty? first rest) (letrec ((f (lambda (cons empty ls) (if (empty? ls) empty (cons (first ls) (f cons empty (rest ls))))))) f)) ;; [X Y -> Y] Y [RaListof X] -> Y (define rfoldl/1 (make-foldl rnull? rcar rcdr)) (define rfoldr/1 (make-foldr rnull? rcar rcdr)) ;; [RaListof X] ... -> [RaListof X] (define (rappend . lss) (cond ((null? lss) rnull) (else (let recr ((lss lss)) (cond ((null? (cdr lss)) (car lss)) (else (rfoldr/1 rcons (recr (cdr lss)) (car lss)))))))) ;; [RaListof X] -> [RaListof X] (define (rreverse ls) (rfoldl/1 rcons rnull ls)) ;; [RaListof X] Nat -> [RaListof X] (define (rlist-tail ls i) (let loop ((xs ls) (j i)) (cond ((zero? j) xs) (else (loop (rcdr xs) (sub1 j)))))) ;; [RaListof X] Nat -> X ;; Special-cased above to avoid logarathmic amount of cons'ing ;; and any multi-values overhead. Operates in constant space. (define (rlist-ref ls i) ;(assert (< i (rlength ls))) (let loop ((xs ls) (j i)) (if (< j (kons-size xs)) (tree-ref (kons-size xs) (kons-tree xs) j) (loop (kons-rest xs) (- j (kons-size xs)))))) ;; [RaListof X] Nat X -> [RaListof X] (define (rlist-set ls i v) (let-values (((_ l*) (rlist-ref/set ls i v))) l*)) ;; [X ... -> y] [RaListof X] ... -> [RaListof Y] ;; Takes advantage of the fact that map produces a list of equal size. (define rmap (case-lambda ((f ls) (let recr ((ls ls)) (if (kons? ls) (make-kons (kons-size ls) (tree-map f (kons-tree ls)) (recr (kons-rest ls))) rnull))) ((f . lss) ;(check-nary-loop-args 'rmap (lambda (x) x) f lss) (let recr ((lss lss)) (cond ((rnull? (car lss)) rnull) (else ;; IMPROVE ME: make one pass over lss. (make-kons (kons-size (car lss)) (tree-map/n f (map kons-tree lss)) (recr (map kons-rest lss))))))))) ;; [X ... -> Y] [RaListof X] ... -> unspecified (define rfor-each (case-lambda ((f ls) (when (kons? ls) (tree-for-each f (kons-tree ls)) (rfor-each f (kons-rest ls)))) ((f . lss) ;(check-nary-loop-args 'rmap (lambda (x) x) f lss) (let recr ((lss lss)) (when (rpair? (car lss)) (tree-map/n f (map kons-tree lss)) (recr (map kons-rest lss))))))) ;; [RaListof X] -> [Listof X] (define (rlist->list x) (rfoldr/1 cons '() x)) ;; [Listof X] -> [RaListof X] (define (list->rlist x) (fold-right rcons '() x)) ;; This code based on code written by Abdulaziz Ghuloum ;; http://ikarus-scheme.org/pipermail/ikarus-users/2009-September/000595.html (define get-cached (let ((h (make-hash-table eq?))) (lambda (x) (define (f x) (cond ((pair? x) (rcons (f (car x)) (f (cdr x)))) ((vector? x) (vector-map f x)) (else x))) (cond ((not (or (pair? x) (vector? x))) x) ((hash-table-ref/default h x #f)) (else (let ((v (f x))) (hash-table-set! h x v) v)))))) (define-syntax rquote (syntax-rules () ((rquote datum) (get-cached 'datum))))
true
7edb90488b6b2a4327be6cf80fd468dcc79455fc
9a7db5dd62219d341b366cad42173d30478367b6
/gen-id.sls
e035f1a9cdbbef1668e5477f677b799a34ab396d
[ "MIT" ]
permissive
dharmatech/indexable-sequence
2d36c1622d7435701d9d16e18371087cfce4e1f4
7a1628022ef25776b789798caede4a68071420a7
refs/heads/master
2016-09-06T01:08:15.056397
2011-11-27T22:10:42
2011-11-27T22:10:42
2,052,298
4
0
null
null
null
null
UTF-8
Scheme
false
false
385
sls
gen-id.sls
(library (indexable-sequence gen-id) (export gen-id) (import (rnrs)) (define (gen-id template-id . args) (datum->syntax template-id (string->symbol (apply string-append (map (lambda (x) (if (string? x) x (symbol->string (syntax->datum x)))) args))))))
false
cd133cc978b7799928677dfa992a304042abf603
5bbc152058cea0c50b84216be04650fa8837a94b
/pre-benchmark/htdp/base/Images/latex.ss
d444418a396320dab5e8b2ebccf97ff0e6fa734c
[]
no_license
nuprl/gradual-typing-performance
2abd696cc90b05f19ee0432fb47ca7fab4b65808
35442b3221299a9cadba6810573007736b0d65d4
refs/heads/master
2021-01-18T15:10:01.739413
2018-12-15T18:44:28
2018-12-15T18:44:28
27,730,565
11
3
null
2018-12-01T13:54:08
2014-12-08T19:15:22
Racket
UTF-8
Scheme
false
false
5,077
ss
latex.ss
#lang at-exp racket (require "../latex.rkt") ;; Examples ;; @latex{\sum_{i=0}^{\infty}\lambda_i} ;; Prologue: @(latex "y = x \\cdot x") (@latex #<<eos \mbox{\it sign}(x) = \left\{ \begin{array}{r@{\mbox{ if }}l} +1 & x > 0 \\ 0 & x = 0 \\ -1 & x < 0 \end{array}\right. eos ) (@latex #<<eos d = v \cdot t - {1\over2} \cdot a \cdot t^2 eos ) (@latex #<<eos d(t) = v \cdot t - {1\over2} \cdot a \cdot t^2 eos ) (@latex #<<eos 200! = 200 \cdot 199 \cdot \ldots \cdot 2 \cdot 1 \cdot 1 eos ) (@latex #<<eos c = \frac59 \cdot (f - 32) eos ) (@latex #<<eos \sqrt{x^2 + y^2} eos ) (@latex #<<eos \underbrace{x + \ldots + y}_n eos ) (@latex #<<eos \frac{-b+\sqrt{b^2 - 4 \cdot a \cdot c}}{2 \cdot a} eos ) (@latex #:file "quadratic" #<<eos \frac{-b}{2 \cdot a} eos ) (@latex #<<eos \frac{-b-\sqrt{b^2 - 4 \cdot a \cdot c}}{2 \cdot a} eos ) (@latex #<<eos \sqrt{(x0 - x1)^2 + (y0 - y1)^2} eos ) (@latex #:file "ex-poly1" #<<eos 5 \cdot x eos ) (@latex #:file "ex-poly2" #<<eos 5 \cdot x + 17 \cdot y eos ) (@latex #:file "ex-poly3" #<<eos 5 \cdot x + 17 \cdot y + 3 \cdot z eos ) (@latex #:file "ex-integrate" #<<eos (\mbox{\it right} - \mbox{\it left}) \cdot \frac{f (\mbox{\it right}) + f (\mbox{\it left})} {2} eos ) (@latex #:file "ex-integrate2" #<<eos \mbox{\it TOLERANCE\/} \cdot (\mbox{\it right\/} - \mbox{\it left\/}) eos ) ;; f(x) - f(r1) ;; slope = -------------- ;; x - r1 ;; ;; f(x) - f(r1) = slope * (x - r1) ;; f(x) = slope * (x - r1) + f(r1) ;; 0 = slope * (x_0 - r1) + f(r1) ;; f(r1) ;; x_0 = r1 - ------- ;; slope (@latex #:file "newton-tangent-line" #<<eos \mbox{\it tangent\/}(x) = \mbox{{\it slope\/}} \cdot x + f(r1) eos ) (@latex #:file "newton-tangent-root0" #<<eos 0 = \mbox{{\it slope\/}} \cdot \mbox{\it root-of-tangent\/} + f(r1) eos ) (@latex #:file "newton-tangent-root" #<<eos \mbox{\it root-of-tangent\/} = r1 - \frac{f(r1)}{\mbox{{\it slope\/}}} eos ) (@latex #:file "newton0" #<<eos \mbox{\it slope\/} = \frac{f(r1+\epsilon) - f(r1-\epsilon)}{(r1+\epsilon) - (r1-\epsilon)} = \frac{f(r1+\epsilon) - f(r1-\epsilon)}{2 \cdot \epsilon} eos ) (@latex #:file "newton1" #<<eos \begin{array}{lcl} t(x) & = & f'(r0) * (x - r0) + f(r0)\\ & = & f'(r0) * x + [f(r0) - f'(r0) \cdot r0] \\ \end{array} eos ) (@latex #:file "newton2" #<<eos y(x) = a \cdot x + b eos ) (@latex #:file "newton3" #<<eos r - \frac{f(r0)}{f'(r0)} \ . eos ) (@latex #:file "eq" #<<eos a_1 \cdot x_1 + ... + a_n \cdot x_n = b eos ) (@latex #:file "gauss1" #<<eos \begin{array}{lclcrcrr} 2 \cdot x & + & 2 \cdot y & + & 3 \cdot z & = & 10 \\ 2 \cdot x & + & 5 \cdot y & + & 12 \cdot z & = & 31 & \qquad (\dagger)\\ 4 \cdot x & + & 1 \cdot y & - & 2 \cdot z & = & 1 \end{array} eos ) (@latex #:file "gauss2" #<<eos \begin{array}{lclcrcrr} 2 \cdot 1 & + & 2 \cdot 1 & + & 3 \cdot 2 & = & 10 \\ 2 \cdot 1 & + & 5 \cdot 1 & + & 12 \cdot 2 & = & 31 & \\ % \qquad (\dagger)\\ 4 \cdot 1 & + & 1 \cdot 1 & - & 2 \cdot 2 & = & 1 \end{array} eos ) (@latex #:file "gauss5" #<<eos \begin{array}{lclcrcrr} 2 \cdot x & + & 2 \cdot y & + & 3 \cdot z & = & 10 \\ & & 3 \cdot y & + & 9 \cdot z & = & 21 & \qquad (\ddagger)\\ & - & 3 \cdot y & - & 8 \cdot z & = & -19 \end{array} eos ) (@latex #:file "gaussA" #<<eos \begin{array}{lclcrcrr} 2 \cdot x & + & 2 \cdot y & + & 3 \cdot z & = & 10 \\ & & 3 \cdot y & + & 9 \cdot z & = & 21 & \qquad (*)\\ & & & & 1 \cdot z & = & 2 \end{array} eos ) (@latex #:file "gaussG" #<<eos \begin{array}{lclcrcrr} 2 \cdot x & + & 2 \cdot y & + & 2 \cdot z & = & 6 \\ 2 \cdot x & + & 2 \cdot y & + & 4 \cdot z & = & 8 \\ 2 \cdot x & + & 2 \cdot y & + & 1 \cdot z & = & 2 \end{array} eos ) (@latex #:file "gaussGT" #<<eos \begin{array}{lclcrcrr} 2 \cdot x & + & 2 \cdot y & + & 2 \cdot z & = & 6 \\ 0 \cdot x & + & 0 \cdot y & + & 2 \cdot z & = & 2 \\ 0 \cdot x & + & 0 \cdot y & - & 1 \cdot z & = & -4 \end{array} eos ) (@latex #:file "gaussH" #<<eos 3 \cdot y + 9 \cdot 2 = 21 \ . eos ) (@latex #:file "gaussHY" #<<eos y = \frac{21 - 9 \cdot 3}{3} eos ) (@latex #:file "gaussHX" #<<eos 2 \cdot x + 2 \cdot 1 + 3 \cdot 2 = 10 eos ) (@latex #:file "gaussHXS" #<<eos x = \frac{10 - (2 \cdot 1 + 3 \cdot 2)}{2} eos ) (@latex #:file "gaussI" #<<eos \begin{array}{llrrrrr} ({\sf list} & ({\sf list} & a_{11} & \ldots & \ldots & b_1) \\ & ({\sf list} & & a_{21} & \ldots & b_2) \\ & ({\sf list} & & \vdots & \vdots & \vdots) \\ & ({\sf list} & & & a_{nn} & b_n) & ) \\ \end{array} eos ) (@latex #:file "gaussJ" #<<eos \frac{b_n}{a_{nn}} \ . eos ) (@latex #:file "gaussK" #<<eos 3 \cdot x + 9 \cdot y = 21 eos ) (@latex #:file "gaussL" #<<eos y = 2 \ , eos ) (@latex #:file "gaussM" #<<eos 3 \cdot x + 9 \cdot 2 = 21 \ . eos ) (@latex #:file "gaussN" #<<eos 9 \cdot 2 - 21 eos ) (@latex #:file "dagger" "\\dagger")
false
e7fc184b0c94f614961c37fc67fd19fcbfc1ef91
5927f3720f733d01d4b339b17945485bd3b08910
/hato-config.scm
3ec3db3b8bb3375f49d3ff9f66e3eeab5131824e
[]
no_license
ashinn/hato
85e75c3b6c7ca7abca512dc9707da6db3b50a30d
17a7451743c46f29144ce7c43449eef070655073
refs/heads/master
2016-09-03T06:46:08.921164
2013-04-07T03:22:52
2013-04-07T03:22:52
32,322,276
5
0
null
null
null
null
UTF-8
Scheme
false
false
8,664
scm
hato-config.scm
;; hato-config.scm -- loading and referencing config files ;; ;; Copyright (c) 2005-2009 Alex Shinn. All rights reserved. ;; BSD-style license: http://synthcode.com/license.txt ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (require-library srfi-1 srfi-13 srfi-69 matchable hato-db) (module hato-config (assq-ref read-from-file alist? conf? conf-load conf-load-in-path conf-load-cascaded conf-get conf-get-list conf-get-alist conf-multi conf-extend conf-verify conf-load-table) (import scheme chicken data-structures srfi-1 srfi-13 srfi-69 extras utils files posix ports hato-db) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Config lists (cascaded lists of alists) (define (assq-ref ls key . o) (let ((cell (assq key ls))) (if cell (cdr cell) (and (pair? o) (car o))))) (define (read-from-file file . opt) (condition-case (call-with-input-file file read) (exn () (and (pair? opt) (car opt))))) (define (alist? x) (and (list? x) (every pair? x))) (define (conf? x) (and (list? x) (every alist? x))) (define (conf-load-cascaded cfg-path file) (let ((res (conf-load-in-path cfg-path (if (symbol? file) (symbol->string file) file)))) (append res (map (lambda (x) (conf-load-cascaded cfg-path x)) (conf-get-list (list res) 'inherits))))) (define (conf-load-in-path cfg-path file) (filter pair? (append-map (lambda (dir) (conf-load (if (eqv? #\/ (string-ref file 0)) file (make-pathname dir file)))) cfg-path))) (define (conf-load file . o) (cons (parameterize ((case-sensitive #f)) (read-from-file file '())) (if (pair? o) (car o) '()))) (define (conf-get-cell cfg key) (let search ((ls cfg)) (and (pair? ls) (or (assq key (car ls)) (search (cdr ls)))))) (define (conf-get cfg key . opt) (let ((cell (conf-get-cell cfg key))) (if (not cell) (and (pair? opt) (car opt)) (if (and (pair? (cdr cell)) (null? (cddr cell))) (cadr cell) (cdr cell))))) (define (conf-get-list cfg key . opt) (let ((res (conf-get cfg key))) (if res (if (or (pair? res) (null? res)) res (list res)) (if (pair? opt) (car opt) '())))) (define (conf-get-alist cfg key . opt) (let ((res (conf-get cfg key))) (if res (if (null? res) res (if (and (pair? res) (pair? (car res))) res (list res))) (if (pair? opt) (car opt) '())))) (define (conf-multi cfg key) (append-map (cut assq-ref <> key '()) cfg)) (define (conf-extend alist cfg) (if (pair? alist) (cons alist cfg) cfg)) ;; convert a config setting to a table for lookups. can be either a ;; list, which is converted directly to a hash-table, or a file, which ;; is either opened as a db file (thus reflecting run-times changes) or ;; if a text file is loaded assuming one line per entry (define (conf-load-table x) (cond ((or (pair? x) (null? x)) (alist->hash-table (map (lambda (x) (cons x #t)) x) string=?)) ((string? x) (and (file-exists? x) (if (db-file? x) (open-db x) (conf-load-table (remove string-null? (with-input-from-file x (port-map string-trim-both read-line))))))) (else #f))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; conf verification tests (define (conf-verify cfg spec . o) (let ((warn (if (pair? o) (car o) warning))) (for-each (lambda (alist) (for-each (lambda (cell) (conf-verify-one cell spec warn)) alist)) cfg))) (define (conf-verify-one cell spec warn) (cond ((not (pair? cell)) (warn (sprintf "bad config entry: ~S" cell))) ((not (symbol? (car cell))) (warn (sprintf "non-symbol config entry name: ~S" (car cell)))) (else (let ((def (assq (car cell) spec))) (cond ((not def) (warn (sprintf "unknown config entry: ~S" (car cell)))) ((null? (cdr def))) (else (conf-verify-match cell (cadr def) warn))))))) (define (conf-verify-symbol->predicate sym) (case sym ((integer) integer?) ((number) number?) ((list) list?) ((alist) alist?) ((boolean) boolean?) ((char) char?) ((string) string?) ((symbol) symbol?) ((pair) pair?) ((filename dirname) string?) (else (error "no known conf predicate for" sym)))) ;; non-short-circuit versions (define (and* . args) (every identity args)) (define (every* pred ls) (apply and* (map pred ls))) (define (conf-verify-match cell def warn) (define (cell-value) (if (and (pair? (cdr cell)) (null? (cddr cell))) (cadr cell) (cdr cell))) (define (cell-list) (if (and (pair? (cdr cell)) (null? (cddr cell)) (not (pair? (cadr cell)))) (list (cadr cell)) (cdr cell))) (cond ((procedure? def) (or (def (cell-value)) (begin (warn (sprintf "bad conf value for ~S: ~S" (car cell) (cell-value))) #f))) ((symbol? def) (case def ((existing-filename) (cond ((not (string? (cell-value))) (warn (sprintf "bad conf value for ~S: expected a filename but got ~S" (car cell) (cell-value))) #f) ((not (file-exists? (cell-value))) (warn (sprintf "conf setting ~S references a non-existent file: ~S" (car cell) (cell-value))) #f) (else #t))) ((existing-dirname) (cond ((not (string? (cell-value))) (warn (sprintf "bad conf value for ~S: expected a dirname but got ~S" (car cell) (cell-value))) #f) ((not (directory? (cell-value))) (cond ((file-exists? (cell-value)) (warn (sprintf "conf setting ~S expected a directory but found a file: ~S" (car cell) (cell-value))) #f) (else (warn (sprintf "conf setting ~S references a non-existent directory: ~S" (car cell) (cell-value))) #f))) (else #t))) ((integer number char string symbol filename dirname boolean pair) (or ((conf-verify-symbol->predicate def) (cell-value)) (begin (warn (sprintf "bad conf value for ~S: expected ~S but got ~S" (car cell) def (cell-value))) #f))) ((list alist) (or ((conf-verify-symbol->predicate def) (cell-list)) (begin (warn (sprintf "bad conf value for ~S: expected ~S but got ~S" (car cell) def (cell-list))) #f))) (else (warn (sprintf "bad conf spec list: ~S" def)) #f))) ((pair? def) (case (car def) ((cons) (and* (conf-verify-match (cons `(car ,(car cell)) (car (cell-list))) (cadr def) warn) (conf-verify-match (cons `(car ,(car cell)) (cdr (cell-list))) (caddr def) warn))) ((list) (and (list? (cell-list)) (every* (lambda (x) (conf-verify-match (cons `(list ,(car cell)) x) (cadr def) warn)) (cell-list)))) ((alist) ;;(every* ;; (lambda (cell) (conf-verify-one cell (cdr def) warn)) ;; (cell-list)) (alist? (cell-list)) ) ((or) (or (any (lambda (x) (conf-verify-match cell x identity)) (cdr def)) (begin (warn (sprintf "bad spec value for ~S: expected ~S but got ~S" (car cell) def (cell-value))) #f))) ((member) (or (member (cell-value) (cdr def)) (begin (warn (sprintf "bad spec value ~S for ~S, expected one of ~S" (cell-value) (car cell) (cdr def))) #f))) ((quote) (or (equal? (cadr def) (cell-value)) (begin (warn (sprintf "bad conf value for ~S: expected '~S but got ~S" (car cell) (cadr def) (cell-value))) #f))) (else (warn (sprintf "bad conf list spec name: ~S" (car def))) #f))) (else (or (equal? def (cell-value)) (begin (warn (sprintf "bad conf value for ~S: expected ~S but got ~S" (car cell) def (cell-value))) #f))))) )
false
5c3a6dae92bc275c3d600cb69781a245299da366
cb8cccd92c0832e056be608063bbec8fff4e4265
/chapter2/Examples/2.2.1_ListOperations.scm
ff1419411860b0e593bacdad3607cc26d8c9941c
[]
no_license
JoseLGF/SICP
6814999c5fb15256401acb9a53bd8aac75054a14
43f7a8e6130095e732c6fc883501164a48ab2229
refs/heads/main
2023-07-21T03:56:35.984943
2021-09-08T05:19:38
2021-09-08T05:19:38
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,061
scm
2.2.1_ListOperations.scm
#lang scheme ; List operations ; The procedure list-ref takes as arguments a list and a num- ; ber n and returns the nth item of the list. ; For n=0, list-ref should return the car of the list ; Otherwise, list-ref should return the (n-1)st item of the ; cdr of the list. (define (list-ref l n) (if (= n 0) (car l) (list-ref (cdr l) (- n 1)))) (list-ref (list 1 2 3 4) 3) ; The procedure length returns the number of items in a list: (define (length items) (if (null? items) 0 (+ 1 (length (cdr items))))) (length (list 1)) ; This can also be done iteratively: (define (length-i items) (define (length-iter a count) (if (null? a) count (length-iter (cdr a) (+ 1 count)))) (length-iter items 0)) ; We can append two lists as follows: ; If list1 is the empty list, then the result is just list2 ; Otherwise, append the cdr of list1 and list2, and cons the ; car of list1 onto the result (define (append list1 list2) (if (null? list1) list2 (cons (car list1) (append (cdr list1) list2))))
false
022e684dc9a389dd84cd68dd3ac2eb42a646b402
5355071004ad420028a218457c14cb8f7aa52fe4
/1.3/e-1.44.scm
c83f2402a04bbfdb9b93d80e5a61d1c3fd3d5322
[]
no_license
ivanjovanovic/sicp
edc8f114f9269a13298a76a544219d0188e3ad43
2694f5666c6a47300dadece631a9a21e6bc57496
refs/heads/master
2022-02-13T22:38:38.595205
2022-02-11T22:11:18
2022-02-11T22:11:18
2,471,121
376
90
null
2022-02-11T22:11:19
2011-09-27T22:11:25
Scheme
UTF-8
Scheme
false
false
1,146
scm
e-1.44.scm
; Exercise 1.44. ; ; The idea of smoothing a function is an important concept in signal processing. ; If f is a function and dx is some small number, then the smoothed version of f ; is the function whose value at a point x is the average of f(x - dx), f(x), and f(x + dx). ; ; Write a procedure smooth that takes as input a procedure that computes f and returns a procedure that ; computes the smoothed f. It is sometimes valuable to repeatedly smooth a function (that is, smooth the ; smoothed function, and so on) to obtained the n-fold smoothed function. ; Show how to generate the n-fold smoothed function of any given function using smooth and repeated from exercise 1.43. ; ; ------------------------------------------------ ; (load "../common.scm") (load "e-1.43.scm") (define dx 0.001) (define (smooth f) (lambda (x) (average-of-3 (f (- x dx)) (f x) (f (+ x dx))))) ; (display ((smooth square) 2)) ; (newline) ; now we repeat smoothing n times by reusing the ; repeat function and smooth defined above (define (n-fold-smooth f n) ((repeated smooth n) f)) (display ((n-fold-smooth square 2) 2)) ; and it returns (newline)
false
189f3e5b23595714918387c4680c3307a6bcfbe2
018a7ce673c5be3cf3df61bd5c5036581d6646a7
/spec/fail/bad-letrecs.scm
d9c3d177c62a1eb2261c8c755c4735b154199827
[ "MIT" ]
permissive
iwillspeak/feersum
e857deec2b8683960f9ac6d1f395fb5f625204a8
1602e8333aa11c0335c9775c0ab49bf01389ba98
refs/heads/main
2023-08-07T17:15:19.843607
2023-06-20T06:28:28
2023-06-20T06:28:28
223,348,583
31
2
MIT
2023-06-10T21:29:11
2019-11-22T07:33:04
F#
UTF-8
Scheme
false
false
389
scm
bad-letrecs.scm
(import (scheme base)) (letrec ((first (+ second 1)) ; Can't reference second here, it isn't intialised (second first)) ; Can't reference first here, initialisation ; order isn't specified. second) (letrec* ((first (- second 100)) ; Can't referenc second, not initialised (second first)) ; This is actually OK. second)
false
5fca79e2f7e5c87cfb2d318a2e29e96f4891a6dc
42e0a1ffb4ccc7643f282f805566fc38aa376027
/jcommand.scm
b27decb24b1a37228df8849e10901f5dd94e45b2
[]
no_license
rmrfchik/jc
a0dd353659d6faf3b283b07002671d186b7e92b8
b4d09f92bcd7298f829131c4fa0704cfe78ca27f
refs/heads/master
2016-08-04T23:22:47.026582
2010-02-16T18:54:29
2010-02-16T18:54:29
520,652
1
0
null
null
null
null
UTF-8
Scheme
false
false
1,299
scm
jcommand.scm
(require 'xmlp) (define newline-string (string #\newline)) (define (jc:do-help) (format "help: print this help~neval: eval a sexp")) ;; escape < > to entity (define (escape-special str) (define specials '((#\< "&lt;") (#\> "&gt;"))) (let loop ((strings (map (lambda (c) (let ((a (assoc c specials))) (if a (cadr a) (string c)))) (string->list str))) (result "")) (if (null? strings) result (loop (cdr strings) (string-append result (car strings)))))) (define (jc:do-eval sexp) (lambda () (let* ((cmdline (format "csi -p '~a' 2>&1" sexp)) (port (open-input-pipe cmdline))) (printf "CMDLINE: ~a~n" cmdline) (let loop ((l (read-line port)) (a "")) (if (eof-object? l) (escape-special a) (loop (read-line port) (string-append a l newline-string))))))) (define (jc:help ctx) (>>= (<- comm xp:qname) (if (string=? comm "help") (m:return jc:do-help) (m:fail (format "help expected. got ~s" comm))))) (define (jc:eval ctx) (>>= (<- comm xp:qname) (if (string=? comm "eval") (>>= (<- sexp (mp:+/s (mp:char-parser char? ""))) (m:return (jc:do-eval sexp))) (m:fail (format "eval expected. got ~s" comm))))) (define (jc:command ctx) (mp:any (jc:help ctx) (jc:eval ctx)))
false
3f73a0d80483fa376be0afecbbcb8675f1569e9d
65e1e67976f31c6593d22820db4ce2d2a7a9d6f5
/sdl2-events.scm
2b85a825ab1ed8f4c85b6783f6e13eb35ff92891
[]
no_license
anykey111/sdl2-egg
0916957a5911817d67cd645c003c30b0af5684c8
0be01729e0f0ccb1248f6300f9c08232ae7e389b
refs/heads/master
2020-05-29T15:50:24.330463
2013-11-16T20:23:20
2013-11-16T20:23:20
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,705
scm
sdl2-events.scm
(module sdl2-events (sdl-poll-event sdl-event-type sdl-event-user sdl-event-key) (import scheme chicken foreign) (use sdl2-defs c-struct) (foreign-declare "#include <SDL2/SDL_events.h>") (define-c-struct (sdl-event "SDL_Event") (constructor: make-sdl-event) (unsigned-integer type sdl-event-type) ((struct "SDL_UserEvent") user sdl-event-user) ((struct "SDL_KeyboardEvent") key sdl-event-key)) (define-c-struct (sdl-user-event "SDL_UserEvent") (constructor: make-sdl-user-event) (unsigned-integer type sdl-user-event-type) (unsigned-integer timestamp sdl-user-event-timestamp) (unsigned-integer windowID sdl-user-event-window-id) (integer code sdl-user-event-code) (c-pointer data1 sdl-user-event-data1) (c-pointer data2 sdl-user-event-data2)) (define-c-struct (sdl-keyboard-event "SDL_KeyboardEvent") (constructor: make-sdl-keyboard-event) (unsigned-integer type sdl-keyboard-event-type) (unsigned-integer timestamp sdl-keyboard-event-time) (unsigned-integer windowID sdl-keyboard-event-window-id) (byte state sdl-keyboard-event-state) (byte repeat sdl-keyboard-event-repeat) ((struct "SDL_Keysym") keysym sdl-keyboard-event-keysym)) (define-c-struct (sdl-keysym "SDL_Keysym") (constructor: make-sdl-keysym) (integer scancode sdl-keysym-scancode) (integer sym sdl-keysym-sym) (unsigned-short mod sdl-keysym-mod)) (define-c-struct (sdl-mouse-button-event "SDL_MouseButtonEvent") (integer x sdl-mouse-button-event-x) (integer y sdl-mouse-button-event-y)) (define (sdl-poll-event) (let ((e (make-sdl-event))) (and (= 1 ((foreign-lambda int "SDL_PollEvent" (c-pointer "SDL_Event")) (c-struct->pointer e))) e))) )
false
9756a62b628e38060ab82560385e41728c15a7e9
880bb9d4ed95741e553d903238083f69b8fcfd84
/srfi/r6rs/arithmetic/fixnums.body.scm
64375ea860341f63ac00227d93675898464f627d
[ "MIT" ]
permissive
pre-srfi/r6rs-r7rs-compat
8c16aa991f924fa14676e6298a82ff5e6651d14c
ac6ae78f59575b341b4848be23f3b867a795dd11
refs/heads/master
2023-01-23T20:28:08.748274
2020-12-07T19:41:54
2020-12-07T19:41:54
310,610,604
1
0
null
null
null
null
UTF-8
Scheme
false
false
14,391
scm
fixnums.body.scm
;;; Copyright 2015 Taylan Ulrich Bayฤฑrlฤฑ/Kammer <[email protected]>. ;;; ;;; Permission to copy this software, in whole or in part, to use this ;;; software for any lawful purpose, and to redistribute this software ;;; is granted subject to the restriction that all copies made of this ;;; software must include this copyright and permission notice in full. ;;; ;;; I also request that you send me a copy of any improvements that you ;;; make to this software so that they may be incorporated within it to ;;; the benefit of the Scheme community. ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; For Emacs: ;;; (put 'fxdefine 'scheme-indent-function 1) ;;; (put 'fxdefine+ 'scheme-indent-function 1) (define-syntax assert (syntax-rules () ((_ <expr> <message> . <objs>) (unless <expr> (apply error <message> (list . <objs>)))))) ;;; Basically (x1 x2 ...) -> (begin (f x1) (f x2) ...), but resorting to ;;; run-time 'for-each' in the last position when the input list is improper, ;;; i.e. it contains a rest-arguments parameter. 'f' may be a macro. (define-syntax for-args (syntax-rules () ((_ <operator> ()) #f) ((_ <operator> <args>) (for-args <operator> <args> ())) ((_ <operator> (<first> . <rest>) (<body> ...)) (for-args <operator> <rest> (<body> ... (<operator> <first>)))) ((_ <operator> () (<body> ...)) (begin <body> ... (values))) ((_ <operator> <rest> (<body> ...)) (begin <body> ... (for-each (lambda (arg) (<operator> arg)) <rest>))))) (define (fixnum? obj) (and (exact-integer? obj) (<= (least-fixnum) obj (greatest-fixnum)))) (define (fixnum-width) W) (define (least-fixnum) (expt -2 (- W 1))) (define (greatest-fixnum) (- 0 (+ 1 (least-fixnum)))) (define-syntax assert-fixnum-arg (syntax-rules () ((_ <arg>) (assert (fixnum? <arg>) "argument is not a fixnum" <arg>)))) (define-syntax assert-fixnum-result (syntax-rules () ((_ <result>) (assert (fixnum? <result>) "result is not a fixnum" <result>)))) ;;; fxdefine checks the arguments; fxdefine+ also checks the return value. (define-syntax fxdefine (syntax-rules () ((fxdefine <name> (<args> <body0> <body> ...) ...) (define <name> (case-lambda (<args> (for-args assert-fixnum-arg <args>) <body0> <body> ...) ...))))) (define-syntax fxdefine+ (syntax-rules () ((fxdefine+ <name> (<args> <body0> <body> ...) ...) (fxdefine <name> (<args> (let ((result (begin <body0> <body> ...))) (assert-fixnum-result result) result)) ...)))) (define-syntax fxdefine-comparison (syntax-rules () ((_ <name> <compare>) (fxdefine <name> ((fx1 fx2) (<compare> fx1 fx2)) ((fx1 fx2 fx3) (<compare> fx1 fx2 fx3)) ((fx1 fx2 fx3 fx4) (<compare> fx1 fx2 fx3 fx4)) ((fx1 fx2 fx3 fx4 fx5) (<compare> fx1 fx2 fx3 fx4 fx5)) ((fx1 fx2 fx3 fx4 fx5 . rest) (and (<compare> fx1 fx2 fx3) (let loop ((fx1 fx4) (fx2 fx5) (rest rest)) (and (<compare> fx1 fx2) (or (null? rest) (apply loop fx2 rest)))))))))) (fxdefine-comparison fx=? =) (fxdefine-comparison fx>? >) (fxdefine-comparison fx<? <) (fxdefine-comparison fx>=? >=) (fxdefine-comparison fx<=? <=) (define-syntax fxdefine-predicate (syntax-rules () ((_ <name> <predicate>) (fxdefine <name> ((fx) (<predicate> fx)))))) (fxdefine-predicate fxzero? zero?) (fxdefine-predicate fxpositive? positive?) (fxdefine-predicate fxnegative? negative?) (fxdefine-predicate fxodd? odd?) (fxdefine-predicate fxeven? even?) (define-syntax fxdefine-selection (syntax-rules () ((_ <name> <selector>) (fxdefine <name> ((fx1) fx1) ((fx1 fx2) (<selector> fx1 fx2)) ((fx1 fx2 fx3) (<selector> fx1 fx2 fx3)) ((fx1 fx2 fx3 fx4) (<selector> fx1 fx2 fx3 fx4)) ((fx1 fx2 fx3 fx4 fx5) (<selector> fx1 fx2 fx3 fx4 fx5)) (all (apply <selector> all)))))) (fxdefine-selection fxmax max) (fxdefine-selection fxmin min) (fxdefine+ fx+ ((fx1 fx2) (+ fx1 fx2))) (fxdefine+ fx* ((fx1 fx2) (* fx1 fx2))) (fxdefine+ fx- ((fx1) (- fx1)) ((fx1 fx2) (- fx1 fx2))) (define-syntax fxdefine-division (syntax-rules () ((_ <name> <operator>) (fxdefine+ <name> ((fx1 fx2) (<operator> fx1 fx2)))))) ;;; fxdiv-and-mod and fxdiv0-and-mod0 have to check both return values ;;; FIXME: this is less efficient than it should be (define (fxdiv-and-mod x y) (values (fxdiv x y) (fxmod x y))) (fxdefine-division fxdiv div) (fxdefine-division fxmod mod) (define (fxdiv0-and-mod0 x y) (values (fxdiv0 x y) (fxmod0 x y))) (fxdefine-division fxdiv0 div0) (fxdefine-division fxmod0 mod0) (fxdefine fx+/carry ((fx1 fx2 fx3) (let*-values (((s) (+ fx1 fx2 fx3)) ((s1 s0) (div0-and-mod0 s (expt 2 W)))) (values s0 s1)))) (fxdefine fx-/carry ((fx1 fx2 fx3) (let*-values (((d) (- fx1 fx2 fx3)) ((d1 d0) (div0-and-mod0 d (expt 2 W)))) (values d0 d1)))) (fxdefine fx*/carry ((fx1 fx2 fx3) (let*-values (((s) (+ (* fx1 fx2) fx3)) ((s1 s0) (div0-and-mod0 s (expt 2 W)))) (values s0 s1)))) (fxdefine fxnot ((fx1) (- 0 fx1 1))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Bit-level hacking. ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define fixnum-powers-of-two (let ((v (make-vector W 1))) (do ((i 1 (+ i 1))) ((= i W) v) (let ((n (vector-ref v (- i 1)))) (vector-set! v i (+ n n)))))) (define (fixnum->bitvector fx) (let ((v (make-vector W))) (let ((sign-bit (negative? fx))) (vector-set! v (- W 1) sign-bit) (let loop ((fx (if sign-bit (- fx (least-fixnum)) fx)) (i (- W 2))) (let* ((one-hot (expt 2 i)) (bit-set? (>= fx one-hot))) (vector-set! v i bit-set?) (unless (zero? i) (loop (if bit-set? (- fx one-hot) fx) (- i 1)))))) v)) (define (bitvector->fixnum v) (let loop ((result (if (vector-ref v (- W 1)) (least-fixnum) 0)) (i (- W 2))) (let ((result (if (vector-ref v i) (+ result (expt 2 i)) result))) (if (zero? i) result (loop result (- i 1)))))) ;;; Given the <name> of a fixnum-only bitwise procedure to be defined, ;;; an identity for the operation performed by the procedure, ;;; and a procedure that takes two bits and returns their result, ;;; defines the procedure. (define-syntax fxdefine-bitwise (syntax-rules () ((_ <name> <identity> <operation>) (fxdefine <name> (() <identity>) ((fx1) fx1) ((fx1 fx2) (let loop ((fx1 (if (negative? fx1) (- fx1 (least-fixnum)) fx1)) (fx2 (if (negative? fx2) (- fx2 (least-fixnum)) fx2)) (i (- W 2)) (bits (let* ((bit1 (if (negative? fx1) 1 0)) (bit2 (if (negative? fx2) 1 0)) (bit (<operation> bit1 bit2))) (if (= 0 bit) 0 (vector-ref fixnum-powers-of-two (- W 1)))))) (if (< i 0) bits (let* ((n (vector-ref fixnum-powers-of-two i)) (bit1? (>= fx1 n)) (bit2? (>= fx2 n)) (bit (<operation> (if bit1? 1 0) (if bit2? 1 0))) (fx1 (if bit1? (- fx1 n) fx1)) (fx2 (if bit2? (- fx2 n) fx2)) (bits (if (= 0 bit) bits (+ bits n)))) (loop fx1 fx2 (- i 1) bits))))) ((fx1 fx2 . rest) (let loop ((result (<name> fx1 fx2)) (rest rest)) (if (null? rest) result (loop (<name> result (car rest)) (cdr rest))))))))) (fxdefine-bitwise fxand -1 (lambda (b1 b2) (cond ((= 0 b1) 0) ((= 0 b2) 0) (else 1)))) (fxdefine-bitwise fxior 0 (lambda (b1 b2) (cond ((= 1 b1) 1) ((= 1 b2) 1) (else 0)))) (fxdefine-bitwise fxxor 0 (lambda (b1 b2) (cond ((= 1 (+ b1 b2)) 1) (else 0)))) (fxdefine fxif ((fx1 fx2 fx3) (cond ((negative? fx1) (fxif (fxnot fx1) fx3 fx2)) ((or (negative? fx2) (negative? fx3)) (fxior (fxand fx1 fx2) (fxand (fxnot fx1) fx3))) (else (let loop ((fx1 fx1) (fx2 fx2) (fx3 fx3) (i (- W 1)) (bits 0)) (if (< i 0) bits (let* ((n (vector-ref fixnum-powers-of-two i)) (bit1? (>= fx1 n)) (bit2? (>= fx2 n)) (bit3? (>= fx3 n)) (fx1 (if bit1? (- fx1 n) fx1)) (fx2 (if bit2? (- fx2 n) fx2)) (fx3 (if bit3? (- fx3 n) fx3)) (bits (if bit1? (if bit2? (+ bits n) bits) (if bit3? (+ bits n) bits)))) (loop fx1 fx2 fx3 (- i 1) bits)))))))) (fxdefine fxbit-count ((fx) (if (< fx 0) (fxnot (fxbit-count (fxnot fx))) (let loop ((fx fx) (i (- W 1)) (result 0)) (if (= fx 0) result (let ((n (vector-ref fixnum-powers-of-two i))) (if (>= fx n) (loop (- fx n) (- i 1) (+ result 1)) (loop fx (- i 1) result)))))))) (fxdefine fxlength ((fx) (let ((fx (if (negative? fx) (fxnot fx) fx))) (let loop ((i 0) (n 1)) (if (< fx n) i (loop (+ i 1) (+ n n))))))) (fxdefine fxfirst-bit-set ((fx) (if (zero? fx) -1 (let ((fx (if (negative? fx) (- fx) fx))) (let loop ((fx (if (negative? fx) (- fx) fx)) (i (- W 1))) (let ((n (vector-ref fixnum-powers-of-two i))) (cond ((= fx n) i) ((> fx n) (loop (- fx n) (- i 1))) (else (loop fx (- i 1)))))))))) (define-syntax assert-index (syntax-rules () ((_ <fx>) (assert (and (not (negative? <fx>)) (< <fx> W)) "index must be non-negative and less than (fixnum-width)" <fx>)))) (fxdefine fxbit-set? ((fx1 fx2) (assert-index fx2) (if (>= fx2 W) (negative? fx1) (not (fxzero? (fxand fx1 (expt 2 fx2))))))) (fxdefine fxcopy-bit ((fx1 fx2 fx3) (assert-index fx2) (assert (or (zero? fx3) (= 1 fx3)) "third argument must be 1 or 0" fx3) (let* ((mask (expt 2 fx2)) (bit (if (= fx3 0) 0 mask))) (fxif mask bit fx1)))) (define-syntax assert-indices (syntax-rules () ((_ fx1 fx2) (begin (assert-index fx1) (assert-index fx2) (assert (<= fx1 fx2) "first index must be less than or equal to second" fx1 fx2))))) (fxdefine fxbit-field ((fx1 fx2 fx3) (assert-indices fx2 fx3) (let* ((mask (fxnot (- (expt 2 fx3))))) (fxarithmetic-shift-right (fxand fx1 mask) fx2)))) (fxdefine fxcopy-bit-field ((fx1 fx2 fx3 fx4) (assert-indices fx2 fx3) (let* ((to fx1) (start fx2) (end fx3) (from fx4) (mask1 (- (expt 2 start))) (mask2 (fxnot (- (expt 2 end)))) (mask (fxand mask1 mask2))) (fxif mask (fxarithmetic-shift-left from start) to)))) (define-syntax assert-shift-count (syntax-rules () ((_ <fx>) (assert (< (abs <fx>) W) "shift count's absolute value must be less than (fixnum-width)" <fx>)))) (fxdefine+ fxarithmetic-shift ((fx1 fx2) (assert-shift-count fx2) (floor (* fx1 (expt 2 fx2))))) (fxdefine+ fxarithmetic-shift-left ((fx1 fx2) (assert-index fx2) (floor (* fx1 (expt 2 fx2))))) (fxdefine+ fxarithmetic-shift-right ((fx1 fx2) (assert-index fx2) (floor (* fx1 (expt 2 (- fx2)))))) (fxdefine fxrotate-bit-field ((fx1 fx2 fx3 fx4) (assert-indices fx2 fx3) (let ((field-length (- fx3 fx2))) (assert (< fx4 field-length) "shift count must be less than the field width" fx2 fx3 fx4) (let* ((n fx1) (start fx2) (end fx3) (count fx4) (width (fx- end start))) (if (fxpositive? width) (let* ((count (fxmod count width)) (field0 (fxbit-field n start end)) (field1 (fxarithmetic-shift-left field0 count)) (field2 (fxarithmetic-shift-right field0 (fx- width count))) (field (fxior field1 field2))) (fxcopy-bit-field n start end field)) n))))) (fxdefine fxreverse-bit-field ((fx1 fx2 fx3) (assert-indices fx2 fx3) (assert (<= fx2 fx3) "bit field widths must be non-negative" fx2 fx3) (let* ((field (fxbit-field fx1 fx2 fx3)) (field (fxreverse-fixnum field (- fx3 fx2)))) (fxcopy-bit-field fx1 fx2 fx3 field)))) ;;; Private to this file. (define (fxreverse-fixnum fx k) (if (negative? fx) (+ 1 (fxreverse-fixnum (- fx (least-fixnum)))) (let loop ((fx fx) (i (- k 1)) (bits 0) (val 1)) (if (< i 0) bits (let* ((n (vector-ref fixnum-powers-of-two i)) (bit1? (>= fx n)) (fx (if bit1? (- fx n) fx)) (bits (if bit1? (+ bits val) bits))) (loop fx (- i 1) bits (+ val val)))))))
true
41e2be63b1ad08816cb7ef65a5c014a0aa8ba040
1c7b5b39d41b63322f16979b01492dfb162122e7
/lib/elegant-weapons/record-case-tests.scm
552184e7df248cfe57cf46e058735c46dad0f111
[ "BSD-3-Clause-Open-MPI" ]
permissive
david135/elegant-weapons
83b144531959c1fea88e02735c2796eeb538eb7c
ce51432c614cdba5d2f12c7b5451af01095257a4
refs/heads/master
2021-01-22T16:13:42.004079
2015-11-03T21:53:29
2015-11-03T21:53:29
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
503
scm
record-case-tests.scm
(library (elegant-weapons record-case-tests) (export record-case-tests) (import (rnrs) (elegant-weapons tester) (elegant-weapons record-case)) (define-record-type foo (fields a b)) (define-record-type bar (fields c)) (define-test-suite record-case-tests (record-case-1 (lambda (fail) (let ((a (make-foo 1 2))) (record-case a ((bar x) (fail)) ((foo a b) (+ a b))))))) )
false
f7d37fcaa9ef3d548398ea5fd97f973fd8c2c611
92b8d8f6274941543cf41c19bc40d0a41be44fe6
/testsuite/misc-test.scm
6c7c44645acfb93158c819a6cf4ff9264d3dc420
[ "MIT" ]
permissive
spurious/kawa-mirror
02a869242ae6a4379a3298f10a7a8e610cf78529
6abc1995da0a01f724b823a64c846088059cd82a
refs/heads/master
2020-04-04T06:23:40.471010
2017-01-16T16:54:58
2017-01-16T16:54:58
51,633,398
6
0
null
null
null
null
UTF-8
Scheme
false
false
30,801
scm
misc-test.scm
(test-init "Miscellaneous" 217) ;;; DSSSL spec example 11 (test '(3 4 5 6) (lambda x x) 3 4 5 6) (test '(5 6) (lambda (x y #!rest z) z) 3 4 5 6) (test '(3 4 5 i: 6 j: 1) (lambda ( x y #!optional z #!rest r #!key i (j 1)) (list x y z i: i j: j)) 3 4 5 i: 6 i: 7) ;; Test for optional argument handling. ;; (Savannah bug #10613 was a bug in name scoping of default arguments.) (define (test-opt-args a b c d) (define n 0) ;; We add a side-effect to check that default arguments are evaluated ;; at the correct time. (define (next-n) (set! n (+ 1 n)) n) (define (inner a #!optional (b (list a b c d (next-n))) (c (list a b c d (next-n))) #!key (d (list a b c d (next-n)))) (vector arg-a: a arg-b: b arg-c: c argd: d)) (list inner1: (inner 'a2) n: (next-n) inner2: (inner 'a3 'b3 'c3 d: 'd3) n: (next-n))) (test '(inner1: #( arg-a: a2 arg-b: (a2 b1 c1 d1 1) arg-c: (a2 (a2 b1 c1 d1 1) c1 d1 2) argd: (a2 (a2 b1 c1 d1 1) (a2 (a2 b1 c1 d1 1) c1 d1 2) d1 3)) n: 4 inner2: #(arg-a: a3 arg-b: b3 arg-c: c3 argd: d3) n: 5) test-opt-args 'a1 'b1 'c1 'd1) (test '(200 . 100) (lambda (x #!optional (y (* 2 x)) (p (lambda () (cons y x)))) (p)) 100) (test '(100 . 200) (lambda (x #!optional (y (* 2 x))) (cons x y)) 100) (test #t keyword? 'foo:) (test #f keyword? 'foo\:) (test #t keyword? 'foo:) (test #f keyword? 'foo) (test #f keyword? ':) (test #t keyword? '||:) (test #t keyword? (car '(a: b:))) (test #f keyword? "bar") ;; This is Savannah bug #39059: Method keywords problem (define (key-1 #!key (a "default a") (b "default b") (c "default c")) (list c a)) (test '("c" "a") 'key-1 (key-1 a: "a" b: "b" c: "c")) (define key-2-counter 0) (define (incr-key-2-counter) (set! key-2-counter (+ key-2-counter 1)) key-2-counter) (define (key-2 #!key (a "default a") (b (incr-key-2-counter)) (c "default c")) (list c a key-2-counter)) (test '("c" "a" 0) 'key-2a (key-2 a: "a" b: "b" c: "c")) (test '("default c" "a" 1) 'key-2b (key-2 a: "a")) ;;; DSSSL spec example 44 (test "Argentina" keyword->string 'Argentina:) (test "foo" keyword->string 'foo:) (test "" keyword->string '||:) (test "a b c" keyword->string (string->keyword "a b c")) (test 'foo: string->keyword "foo") (test '||: string->keyword "") ;; Test keyword parameter with primitive type. (define (fun-with-keys1 #!key (code ::int 400) (message ::string "brrp")) (format "code: ~a message: ~a." code message)) (test "code: 400 message: brrp." 'test-fun-with-keys1 (fun-with-keys1)) (test "code: 200 message: brrp." 'test-fun-with-keys1 (fun-with-keys1 code: 200)) (test "Hello" symbol->string 'H\x65;llo) ;;; DSSSL spec example 45 (test foobar: string->keyword "foobar") (define-unit ft 12in) (test 18in + 6in 1ft) (test 5 call-with-values (lambda () (values 4 5)) (lambda (a b) b)) (test -1 call-with-values * -) ;; Test from: [email protected] (test '(() #!eof) call-with-values (lambda () (values '() '#!eof)) (lambda (x y) (list x y))) ;;; This caused a spurious warning in earlier releases. (test '(1 2 3) 'let (let ((x (lambda l l))) (x 1 2 3))) ;;; test old reader bugs (test '(b) cdr '(a .(b))) (test "foo" cdr '(a ."foo")) (test 'a car '(a #||#)) (define (try-vector-ref vec index) (try-catch (vector-ref vec index) (ex <java.lang.IndexOutOfBoundsException> "Bad array index"))) (test 3 try-vector-ref #(1 2 3) 2) (test "Bad array index" try-vector-ref #(1 2 3) 10) ;; Extracted from bug reported by [email protected] (define (test-unary-minus) (- (char->integer #\0))) (test -48 test-unary-minus) (define (test-string->integer str start end) (and (< -1 start end (+ (string-length str) 1)) (let loop ((pos start) (accum 0)) (cond ((>= pos end) accum) ((char-numeric? (string-ref str pos)) (loop (+ pos 1) (+ (char->integer (string-ref str pos)) (- (char->integer #\0)) (* 10 accum)))) (else #f))))) (test 123 test-string->integer "123" 0 3) (test 123 test-string->integer "123456" 0 3) (test 23 test-string->integer "123456" 1 3) (section "new-line handling") ;;; Test that #\return and #\newline are read robustly. (define cr-test-string (string-copy "a \"bRLc\" dRklLXY")) (do ((i 0 (+ i 1))) ((= i (string-length cr-test-string)) #t) (if (char=? #\R (string-ref cr-test-string i)) (string-set! cr-test-string i #\Return)) (if (char=? #\L (string-ref cr-test-string i)) (string-set! cr-test-string i #\Linefeed))) (call-with-input-string cr-test-string (lambda (iport ::input-port) (iport:setConvertCR #t) (test 1 input-port-column-number iport) (test 1 input-port-line-number iport) (test 'a read iport) (test "b\nc" read iport) (test 'd read iport) (test 'kl read iport) (test 'XY read iport) (test #!eof read iport))) (call-with-input-string cr-test-string (lambda (iport) (test #\a read-char iport) (test #\Space read-char iport) (test #\" read-char iport) (test #\b read-char iport) (test #\Return peek-char iport) (test 5 input-port-column-number iport) (test 1 input-port-line-number iport) (test #\Return read-char iport) (test #\Linefeed read-char iport) (test #\c read-char iport) (test #\" read-char iport) (test #\Space read-char iport) (test #\d read-char iport) (test #\Return read-char iport) (test 3 input-port-line-number iport) (test 1 input-port-column-number iport) (test #\k read-char iport) (test #\l read-char iport) (test #\Linefeed read-char iport) (test #\X read-char iport) (test #\Y read-char iport) (test #!eof read-char iport))) (define str-inport (open-input-string "(a . (b c . ())) 34")) (test #t input-port? str-inport) (test '(a b c) read str-inport) (test 34 read str-inport) (test #t eof-object? (peek-char str-inport)) (close-input-port str-inport) (test "a/b (c d)" 'open-output-string (let ((q (open-output-string)) (x '(a b c d))) (write (car x) q) (display "/" q) (write (cadr x) q) (write (cddr x) q) (get-output-string q))) ;;; From: Hallvard Traetteberg <[email protected]> ;;; Triggered bug with try-finally nested in an expression. (define (quote-keyword-values list) (if (null? list) list `(,(car list) ',(car (cdr list)) . ,(quote-keyword-values (cdr (cdr list))))) ) (defmacro with-content (object-form . content) (let ((var-symbol (string->symbol (string-append "context-" (symbol->string (car object-form))))) (object-form `(,(car object-form) . ,(quote-keyword-values (cdr object-form))))) `(fluid-let ((,var-symbol ,object-form)) (let ((content (list . ,content))) (cons ,var-symbol content))) )) (define (document) (list 'document)) (define (view #!key type) (list 'view type: type)) (test '((view type: text)) 'with-content (with-content (view type: text))) (test '((document) ((view type: diagram)) ((view type: text))) 'with-content (with-content (document) (with-content (view type: diagram)) (with-content (view type: text)))) (test '("X" . "X:abc") 'synchronized (let* ((x "X") (y "abc") (z (synchronized y (set! y (string-append x ":" y)) (cons x y)))) z)) (define *xx* 3) (define (fluid-test *xx*) (fluid-let ((*xx* *xx*)) (set! *xx* (+ 100 (twice-*xx*))) (set! *xx* (let ((*xx* *xx*)) (+ 100 *xx*))) *xx*)) (define (twice-*xx*) (* 2 *xx*)) (test '(206 . 3) 'fluid-let-1 (let ((res (fluid-test 10))) (cons res *xx*))) (test 'bar 'fluid-let-2 (fluid-let ((flt (lambda () 'bar))) (flt))) (section "closures") (define (f1 a) (define (f2 b) (cons a b)) (cons a f2)) (define f1-100 (f1 100)) (define f2-20 ((cdr f1-100) 20)) (test 100 'closure-f2-car (car f2-20)) (test 20 'closure-f2-cdr (cdr f2-20)) ;; Here f4 should be optimized away. (define (f3 a) (define (f4 b) (cons a b)) (define (f5 c) (cons a c)) (cons a f5)) (define f3-10 (f3 10)) (define f4-20 ((cdr f3-10) 20)) (test '(10 . 20) 'closure-f4-20 f4-20) (define (f30 a) (define (f31 b) (cons a b)) (define (f32 c) (cons a c)) (list a f31 f32)) (define f30-10 (f30 10)) (define f31-20 ((cadr f30-10) 20)) (define f32-33 ((caddr f30-10) 33)) (test '(10 . 20) 'closure-f31-20 f31-20) (test '(10 . 33) 'closure-f32-33 f32-33) (define (f6 a) (define (f7 b) (define (f8 c) (define (f9 d) (list a b c d)) (list a b c f9)) (list a b f8)) (list a f7)) (define f6-100 (f6 100)) (define f7-20 ((cadr f6-100) 20)) (define f8-10 ((caddr f7-20) 10)) (test '(100 20 10 2) 'closure-test3 ((cadddr f8-10) 2)) (define (f60 a) (define (x6 b) a) (define (f70 b) (define (x7 c) b) (define (f8 c) (define (x8 d) c) (define (f9 d) (list a b c d)) (list a b c f9)) (list a b f8)) (list a f70)) (define f60-100 (f60 100)) (define f70-20 ((cadr f60-100) 20)) (define f80-10 ((caddr f70-20) 10)) (test '(100 20 10 2) 'closure-test4 ((cadddr f80-10) 2)) ;; A bug reported by Edward Mandac <[email protected]>. (test "Done" 'do-future (do ((test 'empty)) (#t "Done") (future (begin(set! test 'goodbye))))) (define p1 (cons 9 45)) (define-alias p2 p1) (define-alias p2car (car p2)) (set! p2car 40) (test '(40 . 45) 'test-alias-1 p1) (define p1-cdr-loc (location (cdr p1))) (set! (p1-cdr-loc) 50) (set! (car p2) 49) (test '(49 . 50) 'test-alias-2 p2) (test '(49 . 50) 'test-alias-3 ((location p1))) (define (test-alias-4 x y) (define-alias xcar (car x)) (define-alias yy y) (set! yy (+ yy xcar)) (set! xcar yy) (list yy xcar x y)) (test '(59 59 (59 . 50) 59) test-alias-4 p1 10) (define (test-alias-5 x) (define y (list x)) (define-alias z y) (list x y z)) (test '(8 (8) (8)) test-alias-5 8) (define test-nesting-1 (lambda () ((lambda (bar) (letrec ((foo (lambda (bar1) (foo bar)))) 33)) 100))) (test 33 test-nesting-1) (define (test-nesting-2) ((lambda (bar1) (lambda () (lambda () bar1))) #t) (let ((bar2 34)) (lambda () (lambda () bar2)))) (test 34 ((test-nesting-2))) (define (test-nesting-3 k l m n o) (define (foo a b c d e f) (list a b c d e f k l m n o)) (foo foo (+ k k) (+ k l) (+ k m) (+ k n) (+ k o))) (test '(20 21 22 23 24 10 11 12 13 14) 'test-nesting-3 (cdr (test-nesting-3 10 11 12 13 14))) ;;; Testcase from "Walter C. Pelissero" <[email protected]>: (test #t procedure? (let* ((is-equal eqv?) (false (lambda () (is-equal 'bar 'foo))) (foo (lambda () 'foo))) (lambda () (foo)))) (test #t pair? (let* ((is-equal eqv?) (false (lambda () (is-equal 'bar 'foo))) (foo (lambda () (false)))) (list false (lambda () (foo))))) (test #t pair? (let* ((is-equal eqv?) (false (lambda () (is-equal 'bar 'foo))) (foo (lambda () (false)))) (list false (lambda () (define (bar) (foo)) (list bar (bar)))))) (test #t not (let* ((foo (lambda () 'foo)) (bar (lambda () (let loop ((arg 'bar)) (foo) (not (loop (foo))))))) #f)) (define (test-duplicate-names) (let ((bar #t)) (lambda () (lambda () bar))) (let ((bar #t)) (lambda () (lambda () bar))) (let ((bar #t)) (lambda () (lambda () bar))) 97) (test 97 test-duplicate-names) (test #f 'mutual-recursion-1 (letrec ((a (lambda () (b))) (b (lambda () (a)))) #f)) (test #f 'mutual-recursion-2 (letrec ((a (lambda () 10)) (b (lambda () (a))) (c (lambda () (e) (b))) (d (lambda () (c))) (e (lambda () (d)))) #f)) ;; Used to cause a verification error. (define (sql-rsmd-all op rsmd . iter) (if (null? iter) (sql-rsmd-all op rsmd (sql-rsmd-columncount rsmd) '()) (if (zero? (car iter)) (cadr iter) (sql-rsmd-all op rsmd (- (car iter) 1) (cons (op rsmd (car iter)) (cadr iter)))))) (define (test-location-local x) (let* ((xl (location x)) ;; test location of formal parameter x (z (xl)) (zl (location z))) ;; test location of local variable z (set! (xl) (+ (zl) 100)) x)) (test 110 test-location-local 10) (test 15 'tail-call (let loop ((a 1) (b 2) (c 3) (d 4) (e 5) (f 6)) (if (> a 10) b (loop b c d e f (+ a b c))))) ;;; read-line should handle CR, LF and CRLF equally (section "read-line") (define (test-read-split port) (call-with-values (lambda () (read-line port 'split)) (lambda x (car x)))) (define (test-read-line proc) (call-with-input-string "line\rline\nline\r\nline" (lambda (strport) (list (proc strport) (proc strport) (proc strport) (proc strport))))) (test '("line" "line" "line" "line") test-read-line read-line) (test '("line" "line" "line" "line") test-read-line test-read-split) (define plus10 (make-procedure foo: 33 name: 'Plus10 method: (lambda (x y) (+ x (if (number? y) y 0) 10)) method: (lambda () 10))) (test 50 plus10 30 10) (test 10 plus10) (test 12 plus10 2 #!null) ;;(test 10 'plus10-error ;; (try-catch (plus10 3) (ex <java.lang.Exception> "error"))) (test 33 procedure-property plus10 'foo) (set-procedure-property! plus10 'foo 44) (test 44 procedure-property plus10 'foo) (test "#<procedure Plus10>" 'plus10-name1 (format "~s" plus10)) (set-procedure-property! plus10 'name 'PlusTen) (test "#<procedure PlusTen>" 'plus10-name2 (format "~s" plus10)) (define-procedure Plus (lambda ((x :: <number>) (y :: <number>)) (+ x y)) (lambda ((x :: <string>) (y :: <string>)) (string-append x y))) (test 12 Plus 5 7) (test "57" Plus "5" "7") (define (return-null) #!null) (test #!null return-null) ;;; Based on bug report 2002-3-1 from Petter &Ouml;sterlund <[email protected]> (define (fie-1) (fie-2) (fie-3)) (define (fie-4) (fie-3) (fie-3)) (test #t 'names (and (procedure? fie-1) (procedure? fie-4))) ;; Test from Jim White <[email protected]> - fails if --full-tailscalls. (define (systime) (invoke-static <java.lang.System> 'currentTimeMillis)) (define systime-1 (systime)) (define systime-2 (systime)) (test #t >= systime-2 systime-1) ;; Bug reported by Wen-Chun Ni <[email protected]>. (define (fl-f y) (+ 10 y)) (fluid-let ((fl-x 2)) (fl-f 1)) (test "10a" 'to-hex-1 (java.lang.Integer:toHexString 266)) (define (to-hex (x :: <int>)) (java.lang.Integer:toHexString x)) (test "10b" to-hex 267) (define-namespace Long "class:java.lang.Long") (test "10d" 'to-hex-1 (Long:toHexString 269)) (define (long-to-hex (x :: <long>)) (Long:toHexString x)) (test "10e" long-to-hex 270) (test "123" Long:toString (Long:new '00123)) (define (to-int-string x :: <long>) (java.lang.Object:toString (Long:new x))) (test "124" to-int-string '00124) ;;; Based on bug report 2002-12-3 from Petter &Ouml;sterlund <[email protected]> (define (fie-6) 6 (define (runn) foo) (define (foo) 'done) (apply runn '())) (test 'done 'call-fie-6 ((fie-6))) ;; Test instance? (test #t instance? 1 <number>) (test #t instance? "x" <string>) (test #f instance? "x" <number>) (test #f instance? #!null <string>) ;; Tests based on Savannah bug #31353 "boolean type" (test #t instance? #f boolean) (test #f instance? 123 boolean) (test #t 'test-instance (instance? #f boolean)) (test #f 'test-instance (instance? 123 boolean)) (define (is-prim-boolean x) (instance? x boolean)) (test #f is-prim-boolean 123) (test #t is-prim-boolean #t) ;; Based on a bug reported 05-26 [email protected] (define (list-cond compare a b) (cons (compare a (list b)) b)) (define (make-mf forms results) (let ((r (map (lambda (result) (map (lambda (form) (list-cond (lambda (a b) (string<? (cadr a) (caar b))) forms (list form))) forms)) results))) (call-with-output-string (lambda (output-stream) (for-each (lambda (form) (format output-stream "[f:~a]" form)) r))))) (test "[f:((#f a1) (#f a2))][f:((#f a1) (#f a2))]" make-mf '("a1" "a2") '("b1" "b2")) (require 'printf) (define (test-printf format value) (call-with-output-string (lambda (out) (fprintf out format value)))) (test "[ 23]" test-printf "[%3d]" 23) (test "[3.50 ]" test-printf "[%-5.2f]" 3.5) (define fluid-stack '()) (define fluid-let-test-level 'main) (define (push-fluid-let-test-level!) (set! fluid-stack (cons fluid-let-test-level fluid-stack))) (define (test-fluid-let-levels) (push-fluid-let-test-level!) (force (future (fluid-let ((fluid-let-test-level 'thread)) (push-fluid-let-test-level!) (force (future (push-fluid-let-test-level!)))))) fluid-stack) (test '(thread thread main) test-fluid-let-levels) (define (not-a) ((lambda (x) (not x)) 'a)) (test #f not-a) (test "Test." 'from-psyntax ((lambda () (letrec ((topfun (lambda (marks) ((lambda () ((lambda () (lambda () marks))))))) (chifun (lambda () (list topfun)))) "Test.")))) (require 'list-lib) (test '(1 3) 'filter!-test (filter! odd? (iota 5))) ;; Test fluid-let in the presence of threads (define-variable *X* #f) (define (get-*X*) *X*) ;; Should return '(1 2) (define (fluid-let-and-threads) (let* ((t1 (future (begin (fluid-let ((*X* 1)) (sleep 0.5) (get-*X*))))) (t2 (future (begin (sleep 0.25) (fluid-let ((*X* 2)) (sleep 0.5) (get-*X*)))))) (list (force t1) (force t2)))) (test '(1 2) fluid-let-and-threads) (define param1 (make-parameter 10 number->string)) (test "10" 'param-test1 (param1)) (define-alias param1v (param1)) (set! (param1) 11) (test "11" 'param-test2 param1v) (param1 12) (test "12" 'param-test3 (param1)) (set! param1v 13) (test "13" 'param-test4 (param1)) (test '("15" "15" "16" "16" "13" "13") 'param-test5 (let ((r0 (fluid-let ((param1v (+ (string->number param1v) 2))) (let ((r1 (list (param1) param1v))) (set! param1v 16) (append r1 (list (param1) param1v)))))) (append r0 (list (param1) param1v)))) (param1 20) (test '("22" "22" "17" "17" "20" "20") 'param-test5 (let ((r0 (parameterize ((param1 (+ (string->number (param1)) 2))) (let ((r1 (list (param1) param1v))) (set! param1v 17) (append r1 (list (param1) param1v)))))) (append r0 (list (param1) param1v)))) (begin (define var1 1) (test 2 'test-fluid-future-1a (force (fluid-let ((var1 2)) (future (begin (sleep 0.1s) var1))))) (test 1 'test-fluid-future-1b var1)) (define-variable var2 1) (test 2 'test-fluid-future-2a (force (fluid-let ((var2 2)) (future (begin (sleep 0.1s) var2))))) (test 1 'test-fluid-future-2b var2) ;; Bug reported 2005-05-08 by [email protected]. (require <moduleFT>) (define (test-neg-abs) (let ((x (neg-abs 4))) (format #f "x = ~S." x))) (test "x = -4." test-neg-abs) (test '((prefix-test 11) (prefix-test:var2 12) (prefix-test:var2:var3 13) (prefix-test:filler:var4 14)) 'prefix-test prefix-test-list) (test '(12) 'prefix-test:var2 prefix-test:var2) (test '(13) 'prefix-test:var2:var3 prefix-test:var2:var3) (test '(14) 'prefix-test:filler:var4 prefix-test:filler:var4) ;; Common Lisp hyperspec (test "[#24rn]" 'print-base-1 ;; Common Lisp returns upper-case #24rN (fluid-let ((*print-base* 24) (*print-radix* #t)) (format #f "[~s]" 23))) (test '("101000" "1111" "220" "130" "104" "55" "50" "44" "40" "37" "34" "31" "2c" "2a" "28" "26" "24" "22" "20" "1j" "1i" "1h" "1g" "1f" "1e" "1d" "1c" "1b" "1a" "19" "18" "17" "16" "15" "14") 'print-base-2 ;print the decimal number 40 in each base from 2 to 36 (let loop ((i 36) (r '())) (if (= i 1) r (loop (- i 1) (cons (fluid-let ((*print-base* i)) (format #f "~s" 40)) r))))) (test '("#b1010 #b1/1010" "#3r101 #3r1/101" "#o12 #o1/12" "10. #10r1/10" "#xa #x1/a") 'print-base-3 ;;print the integer 10 and the ratio 1/10 in bases 2, 3, 8, 10, 16 (map (lambda (pb) (fluid-let ((*print-radix* #t) (*print-base* pb)) (format #f "~S ~S" 10 1/10))) '(2 3 8 10 16))) ;; Savannah bug #14697 Error using :: <int> ;; Submitted by: Gerardo Horvilleur <mago> (define bug14697-result "") (let ((GS.261 :: <int> 10) (GS.262 :: <int> 1)) (do ((i :: <int> 1 (+ i GS.262))) ((> i GS.261)) (set! bug14697-result (string-append bug14697-result " " (number->string i))))) (test " 1 2 3 4 5 6 7 8 9 10" 'bug14697 bug14697-result) (require 'xml) (test "<code xmlns=\"http://www.w3.org/1999/xhtml\">Foo</code>" 'html-contructor-1 (as-xml (html:code "Foo"))) (test "<a xmlns=\"http://www.w3.org/1999/xhtml\" href=\"foo.html\">Foo</a>" 'html-contructor-2 (as-xml (html:a href:"foo.html" "Foo"))) (define-xml-namespace h "HTML") (test "<h:code xmlns:h=\"HTML\">Foo</h:code>" 'html-contructor-3 (as-xml (h:code "Foo"))) (test "<b xmlns=\"http://www.w3.org/1999/xhtml\"><code>Foo</code></b>" 'html-contructor-4 (as-xml (html:b (html:code "Foo")))) (test "<code xmlns=\"http://www.w3.org/1999/xhtml\">Foo</code>" 'html-contructor-1lit (as-xml #<html:code>Foo</html:code>)) (test "<a xmlns=\"http://www.w3.org/1999/xhtml\" href=\"foo.html\">Foo</a>" 'html-contructor-2lit (as-xml #<html:a ['href]="&["foo"].&(string-append "ht" "ml")">Foo</>)) ;; old syntax (test "<a xmlns=\"http://www.w3.org/1999/xhtml\" href=\"foo.html\">Foo</a>" 'html-contructor-2lit (as-xml #<html:a ['href]="&["foo"].&(string-append "ht" "ml")">Foo</>)) (define-xml-namespace h "HTML") (test "<h:code xmlns:h=\"HTML\">Foo</h:code>" 'html-contructor-3lit (as-xml #<h:code>Foo</>)) (test "<b xmlns=\"http://www.w3.org/1999/xhtml\"><code>Foo</code></b>" 'html-contructor-4lit (as-xml #<html:b><html:code>Foo</></>)) (test "<b xmlns=\"http://www.w3.org/1999/xhtml\"><code>FooBar</code></b>" 'html-contructor-4enc (let ((body1 "Foo") (body2 "Bar") (code 'html:code)) (as-xml #<[(quote html:b)]><[code]>&[body1]&(car (list body2))</></>))) (test "<list><b xmlns=\"http://www.w3.org/1999/xhtml\">bold 1</b> <b xmlns=\"http://www.w3.org/1999/xhtml\">bold2</b></list>" 'html-contructor-5 (as-xml (map html:b '("bold 1" "bold2")))) ;; Test for Savannah bug #18909 "Recursive call to function in closure causes ;; NullPointerException". Chris Wegrzyn <[email protected]> (define (savannah-18909-outerproc foo) (define (innerproc) (if foo (lambda () (innerproc)) '())) (innerproc)) (define savannah-18909-destroy ((savannah-18909-outerproc #t))) (test savannah-18909-destroy 'savannah-18909 (savannah-18909-destroy)) ;; Bug reported by Yaroslav Kavenchuk <[email protected]> 2008-02-26: (define primes (<integer[]> 2 3 5 7 11 13)) (test 11 'primes-integer-indexing (primes 4)) (define sum 0) (define (test-exit-with-finally-1 x) (call-with-current-continuation (lambda (exit) (try-finally (if (< x 0) (exit (list x)) (* 2 x)) (set! sum (+ sum 1)))))) (test '(8 10 (-9) (-1) 24) 'test-exit-with-finally-1 (map test-exit-with-finally-1 '(4 5 -9 -1 12))) (set! sum 0) (define list-inner '()) (define (test-exit-with-finally-2 x) (call-with-current-continuation (lambda (exit1) (try-finally (call-with-current-continuation (lambda (exit2) (try-finally (begin (if (< x 0) (exit2 (list 2 x))) (if (odd? x) (exit1 (list 1 x))) (set! list-inner (cons x list-inner)) (list 0 x)) (set! sum (+ sum 1)) #| Inner finally |#))) (set! sum (+ sum 10)) #| Outer finally |#)))) (test '((0 4) (1 5) (2 -9) (0 14) (2 -1) (0 12) (1 7)) 'test-exit-with-finally-2 (map test-exit-with-finally-2 '(4 5 -9 14 -1 12 7))) (test "Sum: 77 Inner: (12 14 4)" 'test-exit-with-finally-2-results (format #f "Sum: ~s Inner: ~s" sum list-inner)) ;; R6RS and SRFI-62 S-expression comments (test 5 'srfi-62-test-1 (+ 1 #;(* 2 3) 4)) (test '(x z) 'srfi-62-test-2 (list 'x #;'y 'z)) (test 12 'srfi-62-test-3 (* 3 4 #;(+ 1 2))) (test 16 'srfi-62-test-4 (#;sqrt abs -16)) (test '(a d) 'srfi-62-test-5 (list 'a #; #;'b 'c 'd)) (test '(a e) 'srfi-62-test-6 (list 'a #;(list 'b #;c 'd) 'e)) (test '(a . c) 'srfi-62-test-7 '(a . #;b c)) (test '(a . b) 'srfi-62-test-8 '(a . b #;c)) ;; Savannah bug #26940 "Compiler stuck in endless loop" ;; Reported by Helmut Eller (define (mutual-tailcalls x) ;; Note that the order of the functions is reversed relative to the ;; Savannah bug report, because I recently fixed the implementation of ;; the letrec macro, which used to create declarations in reverse order. (letrec ((f0 (lambda () (if (= x 0) 1 (f1)))) (f1 (lambda () (if (= x 0) (f0) (f2)))) (f2 (lambda () (if (= x 0) (f1) 0)))) (f2))) (test 0 mutual-tailcalls 4) ;; Savannah bug #24249 "Local define miscompiled" (let () ;; Added 'list' to suppress tail-call-optimization. (define (baz) (list (bar))) (define (bar) (let ((k (lambda () #f))) (cond ((not (procedure? k)) (error 'bad-k k))) k)) (define (foo) (bar)) (test "#<procedure k>" 'test-savannah-24249 ((foo):toString))) (require <InliningTest>) (test 16 inline-two-calls 5) (test 7 inline-two-calls -5) (test #f check-even 200001) (test #t check-even 18) (test #f check-even-unspec-return 23) ;; Savannah bug #27011: ArrayIndexOutOfBoundsException after 20 local variables (define (big-let) ; no argument! (define x0 "a") (define x1 "a") (define x2 "a") (define x3 "a") (define x4 "a") (define x5 "a") (define x6 "a") (define x7 "a") (define x8 "a") (define x9 "a") (define x10 "a") (define x11 "a") (define x12 "a") (define x13 "a") (define x14 "a") (define x15 "a") (define x16 "a") (define x17 "a") (define x18 "a") (define x19 "a") (define x20 "a") (set! x0 x1 ) (set! x1 x2 ) (set! x2 x3 ) (set! x3 x4 ) (set! x4 x5 ) (set! x5 x6 ) (set! x6 x7 ) (set! x7 x8 ) (set! x8 x9 ) (set! x9 x10) (set! x10 x11) (set! x11 x12) (set! x12 x13) (set! x13 x14) (set! x14 x15) (set! x15 x16) (set! x16 x17) (set! x17 x18) (set! x18 x19) (set! x19 x20) (set! x20 x0 ) x0) (test "a" big-let) ;; Savannah bug #27019 "setLength method of StringBuilder not found" (define sb (java.lang.StringBuilder "abcdef")) (define (set-length (builder :: java.lang.StringBuilder) (len :: int)) (with-compile-options warn-invoke-unknown-method: #t warn-as-error: #t (builder:setLength len))) (set-length sb 4) (test "abcd" 'test-savannah-27019 (sb:toString)) ;; Savannah bug #27188 "Sequence printing" (define sublist-27188 (invoke #(10 11 12 13 14 15) 'subList 1 3)) (test "#(11 12)" 'test-savannah-27188 (format #f "~s" sublist-27188)) (require "test-cycle12.scm") (test '(8 12) c1x-c2x) ;; Savannah bug #27257 "non-int dim. spec. in emitNewArray" (define (alloc-array count val) (object[] length: (+ 1 count) 1: val 2: (+ 1 val))) (test "[#!null 10 11 #!null #!null]" 'test-savannah-27257 (format #f "~s" (alloc-array 4 10))) (define shared-1 '(#2=(3 4) 9 #2# #2#)) (test '((3 4) 9 (3 4) (3 4)) 'shared-1 shared-1) (test 25 'multiple-do-with-type-specs (let ((ll '(1 3 5 7 9))) (do ((x :: list ll (cdr x)) (sum :: int 0 (+ sum (car x)))) ((null? x) sum)))) ;; Savannah bug #28957: exception in inliner, from Helmut Eller (test "Type java.lang.CharSequence[]" 'test-savannah-28957 (((string[]):getClass):toString)) ;; Savannah bug #28926: EOL conversion in READ (test "(#\\X #\\return #\\Y #\\return #\\newline #\\Z)" 'test-savannah-28926 (format "~w" (let ((in (string #\" #\X #\return #\Y #\return #\newline #\Z #\"))) (string->list (call-with-input-string in read))))) ;; Savannah bug #31250: try/catch & endless loop (define (test-savannah-31250 f) (try-catch (let loop () (f) (loop)) (e java.lang.Exception (e:printStackTrace)))) ;; Savannah bug #32656: ArrayIndexOutOfBoundsException in mergeLocalType (test 2 'savannah-32656 (letrec ((f (lambda (x) (case x ((0) (f x)) ((1) (g x)) ((2) (h x))))) (g (lambda (x) (case x ((0) (f x)) ((1) (g x)) ((2) (h x))))) (h (lambda (x) (case x ((0) (f x)) ((1) (g x)) ((2) ;(h x) x))))) (f 2))) ;; Savannah bug #32657: Verification error with JDK7 (begin (define (foo-savannah-32657) () (let ((x (bar-savannah-32657)) (fail (lambda () (error "fail")))) (if (instance? x <pair>) (let ((y :: <pair> x)) (let ((z (y:getCar))) (if (eq? (y:getCdr) '()) z (fail)))) (fail)))) (define (bar-savannah-32657) ::<list> (list 1)) (test 1 'savannah-32657 (foo-savannah-32657))) ;; Testcase simplified from slime/config/swank-kawa.scm (define-syntax mif (syntax-rules () ((mif ((p . ps) value) then) (let ((fail (lambda () (error "mlet failed"))) (tmp value)) (if (instance? tmp <pair>) (let* ((tmp :: <pair> tmp)) then) (fail)))))) (define (dispatch-events) (let ((tmp0 '(a b c))) (mif ((c . event) tmp0) 1234))) (test 1234 dispatch-events) ;; Savavvah bug #36592 "nested map causes compiler inliner NPE" (test '(1 2 3) 'savannah-36592 (map (lambda (x) x) (map (lambda (x) x) '(1 2 3)))) (define falseBool1 (java.lang.Boolean #f)) (define falseBool2 (java.lang.Boolean #f)) (test #f 'eq1-falseBool (eq? falseBool1 falseBool2)) (test #f 'eq2-falseBool (apply eq? falseBool1 falseBool2 '())) (test #t 'eqv1-falseBool (eqv? falseBool1 falseBool2)) (test #t 'eqv2-falseBool (apply eqv? falseBool1 falseBool2 '())) (test #t 'eqv3-falseBool (eqv? falseBool1 #f)) (test #t 'equal1-falseBool (equal? falseBool1 falseBool2)) (test #t 'equal2-falseBool (apply equal? falseBool1 falseBool2 '())) ;; # is a terminating macro character in Scheme. (test '(a b) 'adjacent-sharp-comment '(a#|com|#b)) ;; Savannah bug report #39944 "Possible bug with omitted keyword arguments" (define (f-39944 #!key (y -1) (z -2)) z) (test 42 'savannah-39944 (f-39944 z: 42))
true
ab6a57f936d9b82134c9038801621a0b2ca79b9f
046590754b56f6e3d5f43041f9a7afab5dbbdd77
/game-code-examples/BomberMan-example/code/bomb.scm
50bdc251a0bd86c963cdbdb9f3cd3d8b3762cda0
[]
no_license
simonklimek/bomberman
895e61cfaf99a9bdb748f087ff3886c20646f288
4afb209c1168c6ca9e65176a2f685940b584d8e2
refs/heads/master
2021-05-15T03:58:06.433172
2019-01-29T13:00:29
2019-01-29T13:00:29
120,118,528
1
0
null
null
null
null
UTF-8
Scheme
false
false
816
scm
bomb.scm
;Defining bomb% class , all bombs that are placed and exploded are objects of this class (define bomb% (class object% (init-field (timer 0.0)) ; timer that keeps record of time after which bomb should explode like in circuit simulation (init-field (bomb-pos (cons 0 0))) ; Position where bomb is set (init-field (flame-l '())) ; List of positions where flame of any bomb can reach in form of cons pairs (super-new) (define/public (get-timer-value) timer) (define/public (get-bomb-pos) bomb-pos) (define/public (get-flame-l) flame-l) (define/public (set-timer-value val) (set! timer val)) (define/public (update-timer) (set! timer (- timer 0.2))) (define/public (set-flame-l l) (set! flame-l l)) (define/public (set-bomb-pos p) (set! bomb-pos p))))
false
fa0bbf7b429953054a48615eabbbceb42c1436ec
382770f6aec95f307497cc958d4a5f24439988e6
/projecteuler/072/072.scm
0ae4d191558710060a8b2b45e5293a606023cedd
[ "Unlicense" ]
permissive
include-yy/awesome-scheme
602a16bed2a1c94acbd4ade90729aecb04a8b656
ebdf3786e54c5654166f841ba0248b3bc72a7c80
refs/heads/master
2023-07-12T19:04:48.879227
2021-08-24T04:31:46
2021-08-24T04:31:46
227,835,211
1
0
null
null
null
null
UTF-8
Scheme
false
false
807
scm
072.scm
(define N 1000001) (define phi (make-vector N 0)) (vector-set! phi 1 1) (let pro ([i 2]) (cond ((= i N)) ((zero? (vector-ref phi i)) (let f ([j i]) (cond ((>= j N) (pro (+ i 1))) ((zero? (vector-ref phi j)) (vector-set! phi j j) (vector-set! phi j (* (- i 1) (vector-ref phi j) (/ i))) (f (+ j i))) (else (vector-set! phi j (* (- i 1) (vector-ref phi j) (/ i))) (f (+ j i)))))) (else (pro (+ i 1))))) (do ([i 1 (+ i 1)] [sum 0 (+ sum (vector-ref phi i))]) ((> i 1000000) sum)) #| (time (begin (define N ...) ...)) 18 collections 0.312500000s elapsed cpu time, including 0.000000000s collecting 0.310303720s elapsed real time, including 0.009847920s collecting 78050896 bytes allocated, including 73163424 bytes reclaimed 303963552392 |#
false
43a7d55a5829069c4d3d3f2c48071bd3f433ab01
4fd95c081ccef6afc8845c94fedbe19699b115b6
/chapter_2/2.1.scm
38ee92757bde4f0242d06bd0ca219b1a15aca002
[ "MIT" ]
permissive
ceoro9/sicp
61ff130e655e705bafb39b4d336057bd3996195d
7c0000f4ec4adc713f399dc12a0596c770bd2783
refs/heads/master
2020-05-03T09:41:04.531521
2019-08-08T12:14:35
2019-08-08T12:14:35
178,560,765
1
0
null
null
null
null
UTF-8
Scheme
false
false
1,315
scm
2.1.scm
(define (gcd a b) (define (min a b) (if (< a b) a b )) (define (max a b) (if (> a b) a b )) (define (gcd-iter a b) (if (= b 0) a (gcd-iter b (remainder a b)))) (gcd-iter (max a b) (min a b))) (define (make-rat n d) (let ((g (gcd n d))) (define result (cons (/ n g) (/ d g))) (cond ((and (< n 0) (> g 0)) result) ((and (> n 0) (< g 0)) (make-rat (* -1 n) (* -1 d))) (else result)))) (define (numer x) (car x)) (define (denom x) (cdr x)) (define (print-rat x) (newline) (display (numer x)) (display "/") (display (denom x))) (define (revert x) (make-rat (denom x) (numer x))) (define (add-rat x y) (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (sub-rat x y) (make-rat (- (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (mul-rat x y) (make-rat (* (numer x) (numer y)) (* (denom x) (denom y)))) (define (div-rat x y) (mul-rat x (revert y))) (print-rat (make-rat 10 -5))
false
b27000f4c5289861208513e721469bba00ecd5fd
648776d3a0d9a8ca036acaf6f2f7a60dcdb45877
/queries/rust/locals.scm
c5f4c187ee3f2b4a39530847996ed54551ceb2c9
[ "Apache-2.0" ]
permissive
nvim-treesitter/nvim-treesitter
4c3c55cbe6ff73debcfaecb9b7a0d42d984be3e6
f8c2825220bff70919b527ee68fe44e7b1dae4b2
refs/heads/master
2023-08-31T20:04:23.790698
2023-08-31T09:28:16
2023-08-31T18:19:23
256,786,531
7,890
980
Apache-2.0
2023-09-14T18:07:03
2020-04-18T15:24:10
Scheme
UTF-8
Scheme
false
false
1,973
scm
locals.scm
; Imports (extern_crate_declaration name: (identifier) @definition.import) (use_declaration argument: (scoped_identifier name: (identifier) @definition.import)) (use_as_clause alias: (identifier) @definition.import) (use_list (identifier) @definition.import) ; use std::process::{Child, Command, Stdio}; ; Functions (function_item name: (identifier) @definition.function) (function_item name: (identifier) @definition.method parameters: (parameters (self_parameter))) ; Variables (parameter pattern: (identifier) @definition.var) (let_declaration pattern: (identifier) @definition.var) (const_item name: (identifier) @definition.var) (tuple_pattern (identifier) @definition.var) (let_condition pattern: (_ (identifier) @definition.var)) (tuple_struct_pattern (identifier) @definition.var) (closure_parameters (identifier) @definition.var) (self_parameter (self) @definition.var) (for_expression pattern: (identifier) @definition.var) ; Types (struct_item name: (type_identifier) @definition.type) (constrained_type_parameter left: (type_identifier) @definition.type) ; the P in remove_file<P: AsRef<Path>>(path: P) (enum_item name: (type_identifier) @definition.type) ; Fields (field_declaration name: (field_identifier) @definition.field) (enum_variant name: (identifier) @definition.field) ; References (identifier) @reference ((type_identifier) @reference (#set! reference.kind "type")) ((field_identifier) @reference (#set! reference.kind "field")) ; Macros (macro_definition name: (identifier) @definition.macro) ; Module (mod_item name: (identifier) @definition.namespace) ; Scopes [ (block) (function_item) (closure_expression) (while_expression) (for_expression) (loop_expression) (if_expression) (match_expression) (match_arm) (struct_item) (enum_item) (impl_item) ] @scope
false
d1a6fc7b50af1d47175ef94b56a2fbd195e08840
2d868c9428b8f4772d2ede375a3492b3b6885e1d
/Register Machines/5.8.scm
54304a354e436d504849936384a129cb8ccd0d04
[]
no_license
transducer/sicp
2428223945da87836fa2a82c02d965061717ae95
2cec377aa7805edfd7760c643c14127e344ee962
refs/heads/master
2021-06-06T20:06:47.156461
2016-09-16T22:05:02
2016-09-16T22:05:02
25,219,798
1
0
null
null
null
null
UTF-8
Scheme
false
false
1,312
scm
5.8.scm
;; The following register-machine code is ambiguous, because the label here is defined more ;; than once: ; start ; (goto (label here)) ; here ; (assign a (const 3)) ; (goto (label there)) ; here ; (assign a (const 4)) ; (goto (label there)) ; there ;; With the simulator as written, what will the contents of register a be when control ;; reaches there? ; => lookup-label uses assoc to find the label-name in the labels. assoc returns the first ; hit. Therefore 3 will be returned ;; Modify the extract-labels procedure so that the assembler will signal an ;; error if the same label name is used to indicate two different locations. (define (extract-labels text receive) (if (null? text) (receive '() '()) (extract-labels (cdr text) (lambda (insts labels) (let ((next-inst (car text))) (if (symbol? next-inst) (if (assoc labels next-inst) (error "already contains label EXTRACT-LABELS") (receive insts (cons new-label labels))) (receive (cons (make-instruction next-inst) insts) labels)))))))
false
65d2ca4723ee858124388a8be1d97931ae6bf62f
320a615ef54449a39e2ca9e59847106e30cc8d7a
/test/run-force-field.scm
05dddcf466a2f68d3cb4c2f41907d4e13e6f8b4b
[]
no_license
alexei-matveev/bgy3d
5cf08ea24a5c0f7b0d6e1d572effdeef8232f173
0facadd04c6143679033202d18017ae2a533b453
refs/heads/master
2021-01-01T17:47:22.766959
2015-07-10T09:21:49
2015-07-10T09:21:49
38,872,299
2
1
null
null
null
null
UTF-8
Scheme
false
false
1,203
scm
run-force-field.scm
;;; ;;; Copyright (c) 2014 Alexei Matveev ;;; ;;; ../bgy3d -L ../ -s ./run-force-field.scm ;;; (use-modules (guile bgy3d) ; ccap0, ccap1, etc. (guile utils) ; dfridr (ice-9 pretty-print)) (define RMIN 0.5) ; see bgy3d-solutes.c (define h 1.0e-7) (define RMIN+ (+ RMIN h)) (define RMIN- (- RMIN h)) (define (test name f0 f1) (let ((rs (list RMIN- RMIN RMIN+))) (pretty-print name) (for-each (lambda (r) (let* ((pair (dfridr f0 r h)) ; num diff (f1-num (car pair)) (f1-err (cdr pair))) (pretty-print (list r (f0 r) (f1 r) f1-num)))) rs))) ;;; FIXME: RMIN here and in bgy3d-solutes.c may diverge: (unless (equal? (ccap0 RMIN+) (/ 1.0 RMIN+)) (error "Capped Coulomb is wrong for r > RMIN")) (when (equal? (ccap0 RMIN-) (/ 1.0 RMIN-)) (error "Capped Coulomb is wrong for r < RMIN")) (define primitives (list (list "lj" lj0 lj1) (list "ljcap" ljcap0 ljcap1) (list "cl" cl0 cl1) (list "cs" cs0 cs1) (list "cscap" cscap0 cscap1) (list "ccap" ccap0 ccap1))) (for-each (lambda (args) (apply test args)) primitives)
false
c419ad324c9a4722d2ca1d5e6d0080f9ce39c63d
26aaec3506b19559a353c3d316eb68f32f29458e
/modules/ln_core/packtool.scm
8b6f8dff9390f74c048171aba0cbc1831c6a5b94
[ "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
2,797
scm
packtool.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. |# ;; simple code to package files within an application ;; this will allow default arbitrary files to be transferred to any platform (define (packtool:prep file) (let* ((tmp (string-split file #\/)) (basename (car (reverse tmp)))) (let loop ((dirs (reverse (cdr (reverse tmp)))) (path (system-directory))) (if (= (length dirs) 0) (string-append path (system-pathseparator) basename) (let ((newpath (string-append path (system-pathseparator) (car dirs)))) (if (not (file-exists? newpath)) (create-directory newpath)) ;; sometimes directories are not instantly available?? (let loop2 () (if (not (file-exists? newpath)) (begin (thread-sleep! 0.1) (loop2)))) (loop (cdr dirs) newpath)))))) ;; extract an embedded file (define (packtool-unpack file cdata overwrite) (let ((rootpath (system-directory))) (if (not (file-exists? rootpath)) (create-directory rootpath))) (let ((path (packtool:prep file))) (if (or overwrite (not (file-exists? path))) (let ((data (u8vector-decompress cdata))) (log-system "packtool: extracting " path) (u8vector->file data path))))) ;; eof
false
1d34a3c97c7bd5a3cee47045b7f262d8f506b915
eb87c8b1ce8591d207643d3924b7939228f1a4fe
/pj-7.1/talk.ss
a9626ea941354a35a189cc3d4e63c16aed9154db
[]
no_license
brownplt/insta-model
06543b43dde89913c219d476ced0f51a439add7b
85e2c794ec4b1befa19ecb85f2c8d2509ec8cf42
refs/heads/main
2023-08-30T19:06:58.083150
2023-05-03T18:53:58
2023-05-10T22:29:18
387,500,638
5
0
null
2022-04-23T23:06:52
2021-07-19T14:53:09
Racket
UTF-8
Scheme
false
false
63,103
ss
talk.ss
#lang at-exp slideshow ;; TALKING NOTES ;; - can call chklist from untyped --- it's the value constructor not the types, don't have to type the full path! ;; - ;; TODO ;; [X] thorn, strongscript + nom (M,T) at the end, related work shout out ;; [X] 541 is the old number, be clear old vs new ;; [X] add slide about Pyre: defer ; migrations => lots using Optional types, ;; more info in paper; types do give benefits ;; [X] show good untyped avg() call; don't need types, do need value constructor ;; 30 min slot ;; 20:00 March 15 ;; https://docs.google.com/presentation/d/1zbi3st3HDC29_o79D9vgjwEFo4l5VDKnAN92TXBlLcE/edit#slide=id.g2128e74c6b5_0_10 ;; - gradual class hierarchy ;; - rare in RW: Thorn, SafeTS don't allow it ;; - Nom allows plenty, makes dispatch tricky, optimistic / pess. ;; - no m overloading (python) ;; - single inheritance ;; - typed code, type-based override ;; - no @property for typed fields ;; - attrs set by __init__ (all PEP checkers want this) ;; - table for all generic/concrete instantiations ;; - no recursive types anywhere (Dyn for that, as default like for Set[T]?) ;; - no **kwargs, coming soon (require images/icons/misc images/icons/symbol images/icons/style images/icons/control (only-in pict/face face) (only-in racket/random random-sample) racket/class racket/draw racket/format racket/match racket/list racket/string pict ppict/2 pict-abbrevs ppict/pict ppict/tag pict-abbrevs/slideshow (only-in slideshow para bt) plot/no-gui (except-in plot/utils min* max*)) (define turn revolution) (define x%->pixels w%->pixels) (define y%->pixels h%->pixels) (define pico-x-sep (w%->pixels 1/100)) (define tiny-x-sep (w%->pixels 2/100)) (define border-x-sep (w%->pixels 4/100)) (define small-x-sep (w%->pixels 5/100)) (define smol-x-sep small-x-sep) (define med-x-sep (w%->pixels 10/100)) (define big-x-sep (w%->pixels 15/100)) (define pico-y-sep (h%->pixels 1/100)) (define tiny-y-sep (h%->pixels 2/100)) (define small-y-sep (h%->pixels 5/100)) (define smol-y-sep small-y-sep) (define med-y-sep (h%->pixels 10/100)) (define big-y-sep (h%->pixels 15/100)) (define slide-top 4/100) (define slide-left 2/100) (define slide-right (- 1 slide-left)) (define slide-bottom 82/100) (define slide-text-left (* 3 slide-left)) ;; 3/2 SD 4:3 (define head-left 20/100) ;; slide-left SD 4:3 (define head-right (- 1 head-left)) ;; slide-right SD 4:3 (define text-left slide-text-left) (define slide-text-right (- 1 slide-text-left)) (define text-right slide-text-right) (define slide-heading-top (* 1.4 slide-top)) (define slide-text-top (* 4 slide-top)) (define hi-text (* 6 slide-top)) (define lo-text (* 2.5 hi-text)) (define slide-text-bottom slide-bottom) (define lesson-x 18/100) (define slide-text-coord (coord slide-text-left slide-text-top 'lt)) (define slide-text-coord-left slide-text-coord) (define slide-text-coord-mid (coord 1/2 slide-text-top 'ct)) (define slide-text-coord-right (coord slide-text-right slide-text-top 'rt)) (define slide-text-coord-l slide-text-coord-left) (define slide-text-coord-m slide-text-coord-mid) (define slide-text-coord-r slide-text-coord-right) (define heading-text-coord (coord head-left slide-heading-top 'lt)) (define heading-text-coord-left heading-text-coord) (define heading-text-coord-mid (coord 1/2 slide-heading-top 'ct)) (define heading-text-coord-right (coord head-right slide-heading-top 'rt)) (define heading-coord heading-text-coord) (define heading-coord-left heading-text-coord-left) (define heading-coord-mid heading-text-coord-mid) (define heading-coord-right heading-text-coord-right) (define heading-coord-l heading-coord-left) (define heading-coord-m heading-coord-mid) (define heading-coord-r heading-coord-right) (define bottom-coord-left (coord slide-left slide-text-bottom 'lb)) (define bottom-coord-mid (coord 1/2 slide-text-bottom 'cb)) (define bottom-coord-right (coord slide-right slide-text-bottom 'rb)) (define bottom-coord-l bottom-coord-left) (define bottom-coord-m bottom-coord-mid) (define bottom-coord-r bottom-coord-right) (define center-coord (coord 1/2 1/2 'cc)) (define title-coord (coord 1/2 26/100 'ct)) (define hi-text-coord-left (coord slide-text-left hi-text 'lt)) (define hi-text-coord-mid (coord 1/2 hi-text 'ct)) (define hi-text-coord-right (coord slide-text-right hi-text 'rt)) (define hi-text-coord-l hi-text-coord-left) (define hi-text-coord-m hi-text-coord-mid) (define hi-text-coord-r hi-text-coord-right) (define hi-text-coord-ll (coord 48/100 hi-text 'rt)) (define hi-text-coord-rr (coord 52/100 hi-text 'lt)) (define lo-text-coord-left (coord slide-text-left lo-text 'lt)) (define lo-text-coord-mid (coord 1/2 lo-text 'ct)) (define lo-text-coord-right (coord slide-text-right lo-text 'rt)) (define title-coord-m (coord 1/2 26/100 'ct)) (define all-lang-coord (coord 99/100 1/2 'rc)) (define lesson-coord-h (coord lesson-x hi-text 'lt)) (define lesson-coord-m (coord lesson-x (+ 15/100 hi-text) 'lt)) (define lesson-coord-l (coord lesson-x (+ 30/100 hi-text) 'lt)) (define default-line-width 4) (define default-arrow-size 14) (define large-arrow-size 18) (define code-brush-alpha 0.6) (define (color%++ c n) (make-object color% (byte-round (+ (send c red) n)) (byte-round (+ (send c green) n)) (byte-round (+ (send c blue) n)) (send c alpha))) (define (byte-round n) (if (< n 0) 0 (if (< 255 n) 255 n))) (define at-sign @"@") (define black (hex-triplet->color% #x222222)) (define gray (string->color% "light gray")) (define white (string->color% "white")) (define lite-grey (hex-triplet->color% #xeeeeee)) ; "gainsboro" (define transparent (color%-update-alpha white 0)) (define dark-orange (hex-triplet->color% #xE05626)) (define lite-orange (hex-triplet->color% #xF89C3F)) (define dark-blue (hex-triplet->color% #x002E6D)) (define bg-dark-blue (hex-triplet->color% #x2C6B91)) (define bg-lite-blue (hex-triplet->color% #x357C9F)) (define lite-blue (hex-triplet->color% #xC0EFFF)) (define lite-green (hex-triplet->color% #x00b18f)) ;; TODO (define python-blue (hex-triplet->color% #x357C9F)) (define utah-red (hex-triplet->color% #xCC0000)) (define utah-black (hex-triplet->color% #x000000)) (define utah-white (hex-triplet->color% #xFFFFFF)) (define utah-sunrise (hex-triplet->color% #xFFB81D)) (define utah-lake (hex-triplet->color% #x3ABFC0)) (define utah-crimson (hex-triplet->color% #x890000)) (define utah-granite (hex-triplet->color% #x708E99)) (define utah-darkgrey (hex-triplet->color% #xE2E6E6)) (define utah-litegrey (hex-triplet->color% #xF7F9FB)) (define typed-color utah-sunrise) (define untyped-color utah-granite) (define shallow-color utah-sunrise) (define concrete-color utah-crimson) (define primitive-color utah-lake) (define deep-color typed-color) (define typed-brush-color (color%++ typed-color 20)) (define shallow-pen-color shallow-color #;(hex-triplet->color% #xffc20a) ) (define deep-pen-color deep-color #;(hex-triplet->color% #x0c7bdc)) (define concrete-pen-color concrete-color) (define primitive-pen-color primitive-color) (define untyped-pen-color untyped-color) (define shallow-brush-color (color%-update-alpha shallow-pen-color 0.4) #;lite-orange #;(hex-triplet->color% #xfdc008)) (define deep-brush-color (color%-update-alpha deep-pen-color 0.4) #;(hex-triplet->color% #x0a79da)) (define concrete-brush-color (color%-update-alpha concrete-pen-color 0.4) #;(hex-triplet->color% #x0a79da)) (define primitive-brush-color (color%-update-alpha primitive-pen-color 0.4) #;(hex-triplet->color% #x0a79da)) (define untyped-brush-color (color%-update-alpha untyped-pen-color 0.4) #;(color%++ untyped-color 20)) (define fog-3k1 (hex-triplet->color% #xDBCAC2)) (define neutral-brush-color fog-3k1) (define green0-3k1 (hex-triplet->color% #x71BE8D)) (define green1-3k1 (hex-triplet->color% #x598F61)) (define green2-3k1 (hex-triplet->color% #x4F7459)) (define red0-3k1 (hex-triplet->color% #xF0749C)) (define red1-3k1 (hex-triplet->color% #xC3476F)) (define apple-green lite-green) (define apple-red red1-3k1) (define typed-pen-color #f) (define validate-pen-color red1-3k1) (define validate-brush-color (color%-update-alpha validate-pen-color code-brush-alpha)) (define happy-cloud-color lite-blue) (define sad-cloud-color dark-blue) (define default-line-color dark-blue) (define browncs-frame-color dark-blue) (define hilite-frame-color dark-orange) (define blame-color typed-color) (define shallow-bg-color (color%-update-alpha shallow-pen-color 0.2)) (define deep-bg-color (color%-update-alpha deep-pen-color 0.2)) (define typed-bg-color deep-bg-color) (define untyped-bg-color (color%-update-alpha untyped-pen-color 0.2)) (define bg-color utah-darkgrey) (define (color-off c) (color%-update-alpha c 0.2)) (define title-font "Montserrat" #;"Bree Serif") (define body-font "Source Sans Pro" #;"Open Sans") (define code-font "Inconsolata") (define title-size 42) (define subtitle-size 32) (define head-size 38) (define body-size 30) (define code-size 28) (define tcode-size (- code-size 4)) (define ((make-string->text #:font font #:size size #:color color) . str*) (colorize (text (apply string-append str*) font size) color)) (define (bold-style font) (cons 'bold font)) (define (italic-style font) (cons 'italic font)) (define body-font-lo (make-object font% body-size body-font 'default 'normal 'light)) (define body-font-it (make-object font% body-size body-font 'default 'italic 'light)) (define body-font-itbf (make-object font% body-size body-font 'default 'italic 'semibold)) (define body-font-md (make-object font% body-size body-font 'default 'normal 'medium)) (define body-font-hi (make-object font% body-size body-font 'default 'normal 'semibold)) (define utah-web-headline-font (make-object font% title-size title-font 'default 'normal 'semibold)) (define page-font (make-font #:face code-font #:size tcode-size)) (define titlerm (make-string->text #:font utah-web-headline-font #:size title-size #:color black)) (define titlerm2 (make-string->text #:font utah-web-headline-font #:size (- title-size 8) #:color black)) (define subtitlerm (make-string->text #:font title-font #;body-font-md #:size subtitle-size #:color black)) (define subtitlermem (make-string->text #:font (bold-style title-font) #:size subtitle-size #:color dark-orange)) (define subtitlermemlo (make-string->text #:font title-font #:size subtitle-size #:color dark-orange)) (define subtitlermlo (let ((ff (make-string->text #:font title-font #:size subtitle-size #:color black))) (lambda str* (cellophane (apply ff str*) 0.7)))) (define headrm (make-string->text #:font title-font #:size head-size #:color dark-blue)) (define coderm (make-string->text #:font code-font #:size code-size #:color black)) (define codebf (make-string->text #:font (bold-style code-font) #:size code-size #:color black)) (define codeemrm (make-string->text #:font (bold-style code-font) #:size code-size #:color green2-3k1)) (define codeemrm2 (make-string->text #:font (bold-style code-font) #:size code-size #:color dark-orange)) (define codeembf (make-string->text #:font (bold-style code-font) #:size code-size #:color apple-red)) (define tcoderm (make-string->text #:font code-font #:size tcode-size #:color black)) (define tcodebf (make-string->text #:font (bold-style code-font) #:size tcode-size #:color black)) (define tt coderm) (define bodyrm (make-string->text #:font body-font-md #:size body-size #:color black)) (define hugerm (make-string->text #:font body-font-md #:size (+ 20 body-size) #:color black)) (define bodyrmlo (make-string->text #:font body-font-lo #:size body-size #:color black)) (define rm bodyrmlo) (define rmem (make-string->text #:font body-font-lo #:size body-size #:color dark-orange)) (define bodyrmlobb (make-string->text #:font body-font-lo #:size body-size #:color deep-pen-color)) (define bodyrmloyy (make-string->text #:font body-font-lo #:size body-size #:color shallow-pen-color)) (define bodyrmhi (make-string->text #:font body-font-hi #:size body-size #:color black)) (define bodyrmhibb (make-string->text #:font body-font-hi #:size body-size #:color deep-pen-color)) (define bodyrmhiyy (make-string->text #:font body-font-hi #:size body-size #:color shallow-pen-color)) (define bodyit (make-string->text #:font body-font-it #:size body-size #:color black)) (define bodyitbf (make-string->text #:font body-font-itbf #:size body-size #:color black)) (define bodybf (make-string->text #:font (bold-style body-font) #:size body-size #:color black)) (define bodyemit (make-string->text #:font body-font-it #:size body-size #:color dark-orange)) (define bodyemrm (make-string->text #:font body-font-md #:size body-size #:color dark-orange)) (define bodyrmem bodyemrm) (define bodyembf (make-string->text #:font (bold-style body-font) #:size body-size #:color dark-orange)) (define bodyemrm2 (make-string->text #:font body-font-md #:size body-size #:color green2-3k1)) (define bodyembf2 (make-string->text #:font (bold-style body-font-md) #:size body-size #:color green2-3k1)) (define bodyembf3 (make-string->text #:font (bold-style body-font-md) #:size body-size #:color apple-red)) (define bodyemty (make-string->text #:font body-font-md #:size body-size #:color deep-pen-color)) (define bodyemun (make-string->text #:font body-font-md #:size body-size #:color untyped-color)) (define bodyembl (make-string->text #:font body-font-md #:size body-size #:color blame-color)) (define (at-find-right tag) (at-find-pict tag rc-find 'lc #:abs-x pico-x-sep)) (define (arrowhead-pict rad #:color [color black] #:size [size 20]) (colorize (arrowhead 20 rad) color)) (define up-arrow-pict (arrowhead-pict (* 1/4 turn) #:color black)) (define right-arrow-pict (arrowhead-pict (* 0 turn) #:color black)) (define left-arrow-pict (arrowhead-pict (* 1/2 turn) #:color black)) (define down-arrow-pict (arrowhead-pict (* 3/4 turn) #:color black)) (define (author-append . pp*) (apply hc-append (pict-width @rm{xx}) pp*)) (define (affiliation-pict) (bbox (vc-append (yblank tiny-y-sep) (ht-append smol-x-sep (brown-logo) (meta-logo))))) (define main-logo-w 200) (define main-logo-h 100) (define (brown-logo) (main-logo "img/browncs-logo.png")) (define (meta-logo) (main-logo "img/meta-logo.png")) (define (main-logo str [ww main-logo-w] [hh main-logo-h]) (freeze (scale-to-fit (bitmap str) ww ww))) (define (scale-to-square pp dim) (scale-to-fit pp dim dim)) (define ((slide-assembler/background2 base-assembler make-rect) slide-title slide-vspace slide-pict) (define foreground-pict (base-assembler slide-title slide-vspace slide-pict)) (define background-pict (let ((+margin (* 2 margin)) (-margin (- margin))) (inset (make-rect (+ +margin client-w) (+ +margin client-h)) -margin))) (cc-superimpose background-pict foreground-pict)) (define (make-solid-bg w h color) (let* ((bg (filled-rectangle w h #:color white #:draw-border? #f)) (fg (filled-rectangle w h #:color color #:draw-border? #f))) (cc-superimpose bg fg))) (define (make-bg w h) (make-solid-bg w h bg-color)) (define bg-orig (current-slide-assembler)) (define bg-bg (slide-assembler/background2 bg-orig make-bg)) (define browncs-x-margin (make-parameter small-x-sep)) (define browncs-y-margin (make-parameter tiny-y-sep)) (define bbox-radius (make-parameter 1)) (define bbox-x-margin (make-parameter small-x-sep)) (define bbox-y-margin (make-parameter tiny-y-sep)) (define bbox-frame-width (make-parameter 2)) (define bbox-frame-color (make-parameter utah-granite)) (define (bbox pp #:color [color white] #:x-margin [x-margin #f] #:y-margin [y-margin #f] #:frame-color [frame-color #f] #:backup? [backup? #f]) (define xm (or x-margin (bbox-x-margin))) (define ym (or y-margin (bbox-y-margin))) (define rr (bbox-radius)) (add-rounded-border (if backup? (add-rounded-border pp #:x-margin xm #:y-margin ym #:radius rr #:background-color color #:frame-width 0) pp) #:x-margin (if backup? 0 xm) #:y-margin (if backup? 0 ym) #:radius rr #:background-color (if backup? white color) #:frame-width (bbox-frame-width) #:frame-color (or frame-color (bbox-frame-color)))) (struct code-arrow (src-tag src-find tgt-tag tgt-find start-angle end-angle start-pull end-pull style) #:transparent) (define (add-code-arrow pp arrow #:both [both-arrow #f] #:arrow-size [pre-arrow-size #f] #:line-width [pre-line-width #f] #:color [color #f] #:label [label (blank)] #:x-adjust-label [x-label 0] #:y-adjust-label [y-label 0] #:hide? [hide? #false]) (define line-width (or pre-line-width default-line-width)) (define arrow-size (or pre-arrow-size default-arrow-size)) ((if both-arrow pin-arrows-line pin-arrow-line) arrow-size pp (let ((src-tag (code-arrow-src-tag arrow))) (if (symbol? src-tag) (find-tag pp src-tag) src-tag)) (code-arrow-src-find arrow) (let ((tgt-tag (code-arrow-tgt-tag arrow))) (if (symbol? tgt-tag) (find-tag pp tgt-tag) tgt-tag)) (code-arrow-tgt-find arrow) #:line-width line-width #:label label #:x-adjust-label x-label #:y-adjust-label y-label #:hide-arrowhead? hide? #:style (code-arrow-style arrow) #:start-angle (code-arrow-start-angle arrow) #:end-angle (code-arrow-end-angle arrow) #:start-pull (code-arrow-start-pull arrow) #:end-pull (code-arrow-end-pull arrow) #:color (or color default-line-color))) (define (add-code-line pp arrow #:line-width [pre-line-width #f] #:color [color default-line-color] #:label [label (blank)] #:x-adjust-label [x-label 0] #:y-adjust-label [y-label 0] #:hide? [hide? #false]) (add-code-arrow pp arrow #:arrow-size 0 #:line-width pre-line-width #:color color #:label label #:x-adjust-label x-label #:y-adjust-label y-label #:hide? hide?)) (define (add-code-arrows pp #:arrow-size [arrow-size #f] #:color [color #f] . arrow*) (add-code-arrows* pp arrow* #:arrow-size arrow-size #:color color)) (define (add-code-arrows* pp* arrow* #:color [color #f] #:arrow-size [arrow-size #f]) (for/fold ((pp pp*)) ((arrow (in-list arrow*))) (add-code-arrow pp arrow #:color color #:arrow-size arrow-size))) (define add-code-arrow* add-code-arrows*) (define (add-code-lines pp #:color [color #f] . arrow*) (add-code-line* pp arrow* #:color color)) (define (add-code-line* pp arrow* #:color [color #f]) (for/fold ((pp pp)) ((arrow (in-list arrow*))) (add-code-line pp arrow #:color color))) (define (ben-rule w h #:color [color #f]) (filled-rectangle w h #:color (or color browncs-frame-color) #:draw-border? #f)) (define (bvrule h #:thickness [thickness #f] #:color [color #f]) (ben-rule (or thickness 1) h #:color color)) (define (bhrule w #:thickness [thickness #f] #:color [color #f]) (ben-rule w (or thickness 1) #:color color)) (define (scale-to-pict pp bg) (scale-to-fit pp (pict-width bg) (pict-height bg))) (define (add-lang str) (string-append "lang/" str)) (define (add-src str) (string-append "img/" str)) (define add-img add-src) (define word-sep 0) (define (word-append . pp*) (apply hb-append word-sep pp*)) (define line-sep2 (+ 2)) (define (left-line-append2 . pp*) (left-line-append2* pp*)) (define (left-line-append2* pp*) (apply vl-append line-sep2 pp*)) (define (mid-line-append2 . pp*) (mid-line-append2* pp*)) (define (mid-line-append2* pp*) (apply vc-append line-sep2 pp*)) (define (right-line-append2 . pp*) (right-line-append2* pp*)) (define (right-line-append2* pp*) (apply vr-append line-sep2 pp*)) (define ll-append left-line-append2) (define lc-append mid-line-append2) (define lr-append right-line-append2) (define line-sep tiny-y-sep) (define (left-line-append #:sep [sep #f] . pp*) (left-line-append* #:sep sep pp*)) (define l-line-append left-line-append) (define (left-line-append* #:sep [sep #f] pp*) (apply vl-append (or sep line-sep) pp*)) (define (mid-line-append #:sep [sep #f] . pp*) (apply vc-append (or sep line-sep) pp*)) (define m-line-append mid-line-append) (define (right-line-append . pp*) (apply vr-append line-sep pp*)) (define r-line-append right-line-append) (define code-line-sep (h%->pixels 12/1000)) (define (code-line-append . pp*) (code-line-append* pp*)) (define (code-line-append* pp*) (apply vl-append code-line-sep pp*)) (define (codeblock-append #:sep [sep #f] . pp*) (codeblock-append* pp*)) (define (codeblock-append* #:sep [sep #f] pp*) (apply vl-append (or sep tiny-y-sep) pp*)) (define (hcodeblock-append #:sep [sep #f] . pp*) (hcodeblock-append* #:sep sep pp*)) (define (hcodeblock-append* #:sep [sep #f] pp*) (apply ht-append (or sep tiny-x-sep) pp*)) (define (scale-lang-lo pp) (scale-to-fit pp 120 80)) (define (lang-lo str) (scale-lang-lo (bitmap str))) (define (symbol->lang-pict sym #:ext [ext #f]) (lang-lo (add-img (add-lang (format "~a.~a" sym (or ext 'png)))))) (define (split/n lang-img* n) (let loop ((pp* lang-img*)) (if (< (length pp*) n) (list pp*) (let-values (((a b) (split-at pp* n))) (cons a (loop b)))))) (define (X-codeblock pp* #:dark? [dark? #f] #:title [title #f] #:label [label #f] #:frame-color [frame-color #f] #:background-color [background-color #f]) (define title-pict (if (pict? title) title (if (string? title) (bodyrmlo title) #f))) (define label-margin (if title-pict (* 10/100 (pict-height title-pict)) 0)) (define (add-label-margin pp [extra 0]) (vl-append (+ extra label-margin) (blank) pp)) (define radius 1) (define fw 5) (let* ((block-pict (bbox (code-line-append* pp*) #:backup? #t #:frame-color #f #;(if dark? #f background-color) #:color (if dark? background-color (color%-update-alpha background-color 0.4))))) (if label (let ((block-pict (add-label-margin block-pict 2))) (ppict-do (if title-pict (lt-superimpose block-pict (ht-append 4 (blank) title-pict)) block-pict) #:go (coord 1/2 0 'ct) label)) (if title-pict (vc-append 0 (ht-append 4 (blank) title-pict) (add-label-margin block-pict)) block-pict)))) (define (conslang x y) (if x (list* (tt x) (blank) y) y)) (define (untyped-code str) (untyped-codeblock #:title #f #:lang #f str)) (define (untyped-codeblock #:dark? [dark? #f] #:title [title #f] #:lang [lang #f #;"#lang untyped"] . str*) (untyped-codeblock* #:dark? dark? #:title title (conslang lang (map tt str*)))) (define (untyped-codeblock* pp* #:dark? [dark? #f] #:title [title #f]) (X-codeblock pp* #:dark? dark? #:title title #:frame-color untyped-pen-color #:background-color untyped-brush-color)) (define (shallow-code str) (shallow-codeblock #:title #f #:lang #f str)) (define (shallow-codeblock #:dark? [dark? #f] #:title [title #f] #:lang [lang #f #;"#lang shallow"] . str*) (shallow-codeblock* #:dark? dark? #:title title (conslang lang (map tt str*)))) (define (shallow-codeblock* pp* #:dark? [dark? #f] #:title [title #f]) (X-codeblock pp* #:dark? dark? #:title title #:frame-color shallow-pen-color #:background-color shallow-brush-color)) (define (deep-code str) (deep-codeblock #:title #f #:lang #f str)) (define (deep-codeblock #:dark? [dark? #f] #:title [title #f] #:lang [lang #f #;"#lang deep"] . str*) (deep-codeblock* #:dark? dark? #:title title (conslang lang (map tt str*)))) (define (deep-codeblock* pp* #:dark? [dark? #f] #:title [title #f]) (X-codeblock pp* #:dark? dark? #:title title #:frame-color deep-pen-color #:background-color deep-brush-color)) (define typed-codeblock* deep-codeblock*) (define (concrete-code str) (concrete-codeblock #:title #f #:lang #f str)) (define (concrete-codeblock #:dark? [dark? #f] #:title [title #f] #:lang [lang #f #;"#lang concrete"] . str*) (concrete-codeblock* #:dark? dark? #:title title (conslang lang (map tt str*)))) (define (concrete-codeblock* pp* #:dark? [dark? #f] #:title [title #f]) (X-codeblock pp* #:dark? dark? #:title title #:frame-color concrete-pen-color #:background-color concrete-brush-color)) (define (primitive-code str) (primitive-codeblock #:title #f #:lang #f str)) (define (primitive-codeblock #:dark? [dark? #f] #:title [title #f] #:lang [lang #f #;"#lang primitive"] . str*) (primitive-codeblock* #:dark? dark? #:title title (conslang lang (map tt str*)))) (define (primitive-codeblock* pp* #:dark? [dark? #f] #:title [title #f]) (X-codeblock pp* #:dark? dark? #:title title #:frame-color primitive-pen-color #:background-color primitive-brush-color)) (define (ucode str) (untyped-codeblock* (list (coderm str)))) (define (tcode str) (typed-codeblock* (list (coderm str)))) (define (ccode str) (concrete-codeblock* (list (coderm str)))) (define (untyped-box pp) (bbox #:x-margin 0 #:y-margin 0 #:color untyped-brush-color pp)) (define (typed-box pp) (bbox #:x-margin 0 #:y-margin 0 #:color deep-brush-color pp)) (define (typed-codeblock #:dark? [dark? #f] #:title [title #f] #:lang [lang #f #;"#lang typed"] . str*) (deep-codeblock* #:dark? dark? #:title title (conslang lang (map tt str*)))) (define (xblank n) (blank n 0)) (define (yblank n) (blank 0 n)) (define (pblank pp) (blank (pict-width pp) (pict-height pp))) (define (bblur pp #:alpha [alpha #f] #:bg [bg? #f]) (define fg (cellophane pp (or alpha 4/10))) (if bg? (cc-superimpose (bgrect fg) fg) fg)) (define (bblur2 pp) (bblur pp #:alpha 0.7)) (define (maybe-bblur yes? pp) (if yes? (bblur pp) pp)) (define (bgrect pp) (brect pp bg-color)) (define (brect pp cc) (filled-rectangle (pict-width pp) (pict-height pp) #:draw-border? #f #:color cc)) (define xsep xblank) (define ysep yblank) (define (check-pict h) (bitmap (check-icon #:color apple-green #:height h #:material rubber-icon-material))) (define (stop-pict h) (bitmap (stop-icon #:color utah-crimson #:height h #:material plastic-icon-material))) (define (bghost pp) (blank (pict-width pp) (pict-height pp))) (define (table2 #:col-sep [pre-col-sep #f] #:row-sep [pre-row-sep 4] #:col-align [col-align lc-superimpose] #:row-align [row-align cc-superimpose] . kv*) (table2* kv* #:col-sep pre-col-sep #:row-sep pre-row-sep #:col-align col-align #:row-align row-align)) (define (table2* kv** #:col-sep [pre-col-sep #f] #:row-sep [pre-row-sep #f] #:col-align [col-align lc-superimpose] #:row-align [row-align cc-superimpose]) (define col-sep (or pre-col-sep 328/5)) (define row-sep (or pre-row-sep 364/5)) (table 2 (flatten kv**) col-align row-align col-sep row-sep)) (define big-swatch-blank (blank (w%->pixels 6/100) small-y-sep)) (define (untyped-icon #:lbl [lbl "U"]) (center-label (untyped-codeblock* #:title #f (list big-swatch-blank)) lbl)) (define (typed-icon #:lbl [lbl "T"]) (center-label (deep-codeblock* #:title #f (list big-swatch-blank)) lbl)) (define (center-label pp lbl) (ppict-do pp #:go (coord 1/2 46/100 'cc) (if lbl (scale (headrm lbl) 0.9) (blank)))) (define (tr-pict) (racket-pict)) (define (racket-pict) (symbol->lang-pict 'racket)) (define (ts-pict) (symbol->lang-pict 'typescript)) (define (flow-pict) (symbol->lang-pict 'flow)) (define (typed-clojure-pict) (ppict-do (symbol->lang-pict 'typed-clojure) #:go (coord 65/100 1/2 'cc) (clojure-pict))) (define (clojure-pict) (symbol->lang-pict 'clojure)) (define (php-pict) (symbol->lang-pict 'php)) ;; NOTE room for research / improvement (define (pyre-pict) (symbol->lang-pict 'pyre)) (define (ruby-pict) (symbol->lang-pict 'ruby)) (define (strongtalk-pict) (symbol->lang-pict 'strongtalk)) (define (typescript-pict) (symbol->lang-pict 'typescript)) (define (typed-lua-pict) (symbol->lang-pict 'lua) #;(ppict-do (symbol->lang-pict 'lua) #:go center-coord @coderm{T. Lua})) (define (pyret-pict) (symbol->lang-pict 'pyret)) (define sp-pict (let ((pp (box #f))) (lambda () (or (unbox pp) (let ((vv (freeze (scale-lang-lo (static-python-logo #:title? #f))))) (set-box! pp vv) vv))))) (define (dart2-pict) (symbol->lang-pict 'dart)) (define (js-pict) (symbol->lang-pict 'javascript)) (define (safets-pict) (ppict-do (js-pict) #:go (coord 1/2 0 'ct) @coderm{SafeTS})) (define (strongscript-pict) (ppict-do (js-pict) #:go (coord 1/2 0 'ct) @coderm{StrS.})) (define (thorn-pict) (symbol->lang-pict 'thorn)) (define (nom-pict base) (define logo (freeze (ppict-do (scale-to-pict (bitmap "img/lang/nom.png") base) #:go (coord 0 1 'rb) (ben-rule 20 20 #:color white)))) (define text (freeze (scale (bitmap "img/lang/nom-text.png") 9/10))) (hc-append text logo)) (define (label-below base . pp*) (vc-append 0 base (apply vc-append 2 pp*))) (define (label-above base . pp*) (vc-append 0 (apply vc-append 2 pp*) base)) (define (python-pict) (symbol->lang-pict 'python)) (define (title-pict) (let* ([title-pict (bbox #:y-margin small-y-sep (let* ((str* (string-split the-title-str " Lessons"))) (vc-append (titlerm (car str*)) (titlerm2 (string-append "Lessons" (cadr str*))))))] [pypy (freeze (bitmap "img/python-large.png"))] [ben-pict (vc-append smol-y-sep (vc-append 8 (author-append @subtitlermemlo{Kuang-Chen Lu} @subtitlermem{Ben Greenman} @subtitlermlo{Carl Meyer} @subtitlermlo{Dino Viehland}) (author-append @subtitlermlo{Aniket Panse} @subtitlermemlo{Shriram Krishnamurthi})) )] [author-pict (vc-append tiny-y-sep (bbox ben-pict) (hc-append med-x-sep (affiliation-pict) (bbox @subtitlerm{โ€นProgrammingโ€บ 2023})))] [fg (vc-append smol-y-sep title-pict author-pict)]) (ppict-do (pblank fg) #:go (coord 80/100 82/100 'cc) (cellophane pypy 0.5) #:go center-coord fg))) (define (static-python-logo #:title? [title? #t]) (define mm 2) (define oo 12) (define py (big-python-pict)) (define body (add-rounded-border #:x-margin mm #:y-margin mm (ppict-do (blank (+ 40 (pict-width py)) (- (pict-height py) 0)) #:go (coord 1/2 8/100 'ct) (ppict-do py #:go (coord 1 0 'rt #:abs-x oo #:abs-y (- oo)) (insta-pict))))) (if title? (vc-append tiny-y-sep @titlerm2{Static Python} body) body)) (define (big-python-pict) (define ww 300) (main-logo "img/python-large.png" ww ww)) (define (insta-pict) (define ww 90) (main-logo "img/instagram.jpeg" ww ww)) (define (T<=>U) (define-values [tt uu] (parameterize ((bbox-x-margin pico-x-sep)) (values (typed-icon) (untyped-icon)))) (define arr (code-arrow tt rc-find uu lc-find 0 0 0 0 'solid)) (let* ((pp (hc-append tiny-x-sep tt uu)) (pp (add-code-line pp arr)) (pp (scale pp 7/10))) pp)) (define (low-lbl str pp) (ppict-do pp #:go (coord 1/2 1 'cb #:abs-y (- 2)) (coderm str))) (define (low-lbl2 str pp) (vc-append pico-y-sep pp (coderm str))) (define insta-modules (let ((cache (box #f))) (lambda () (or (unbox cache) (let () (define txt (bbox (vc-append tiny-y-sep (lr-append (word-append @rm{+500 modules with } @bodyrm{sound types}) @rm{(upgraded from Pyre)}) ;; 20k typed exports, 10k untyped imports (word-append @rm{+30k } (T<=>U) @rm{ interactions})))) (define mod (let* ((pp (blank (+ (pict-width txt) (* 2 smol-x-sep)) (* 2 (pict-height txt)))) (tgt* '((12 28/100 29/100) (06 45/100 72/100) (11 75/100 40/100)))) (parameterize ((current-pseudo-random-generator (make-pseudo-random-generator))) (random-seed 96345) (for*/fold ((pp pp)) ((tgt (in-list tgt*)) (_n (in-range (car tgt)))) (define x0 (second tgt)) (define y0 (third tgt)) (define x (+ x0 (random-offset 20/100))) (define y (+ y0 (random-offset 16/100))) (define ii (if (zero? (random 3)) (typed-icon) (untyped-icon))) (ppict-do pp #:go (coord x y 'cc) ii))))) (define pp (vc-append tiny-y-sep txt mod)) (set-box! cache pp) pp))))) (define (random-offset fraction) (define nn (random)) (- (* nn 2 fraction) fraction)) (define (insta-boost n) (define txt (bbox (word-append @bodyrm{3.9% increase} @rm{ in CPU efficiency}))) (define body (if (< n 1) (blank) (let* ((env (envelope-pict 48 30 #:color "Linen")) (top (add-hubs ((if (< n 2) bghost values) (hpictx 5 env)) 'top)) (ss (hpictx 3 (server-pict 38 55))) (lhs (add-hubs ((if (< n 2) values add-stopwatch) (cbox (low-lbl2 "control" ss))) 'lhs)) (rhs (add-hubs ((if (< n 2) values add-stopwatch) (ebox (low-lbl2 "experiment" ss))) 'rhs)) (bot (ht-append smol-x-sep lhs rhs)) (pp (vc-append med-y-sep bot top)) (arr* (for/list ((tgt (in-list (if (< n 2) '() '(lhs-S rhs-S))))) (code-arrow 'top-N ct-find tgt cb-find (* 1/4 turn) (* 1/4 turn) 1/2 1/2 'solid))) (pp (add-code-arrow* pp arr* #:color black))) pp))) (vc-append tiny-y-sep txt body)) (define (add-stopwatch pp) (ppict-do pp #:go (coord 1 1 'lb #:abs-y pico-y-sep #:abs-x (- pico-y-sep)) (stopwatch-pict))) (define (stopwatch-pict) ;; (bitmap (clock-icon 10 8 #:height 40)) (define rr 40) (ppict-do (disk rr #:color white #:border-color black #:border-width 3) #:go (coord 46/100 1/2 'cb) (bvrule (* rr 1/3) #:thickness 2 #:color black) #:go (coord 54/100 1/2 'cb) (rotate (bvrule (* rr 1/3) #:thickness 2 #:color black) (* -6/100 turn)))) (define (serverbox pp) (parameterize ((bbox-x-margin tiny-x-sep)) (bbox pp #:color utah-litegrey))) (define cbox serverbox) (define ebox serverbox) (define (py-migration n) ;; TODO check insta syntax for functions, return types ;; https://pandas.pydata.org/pandas-docs/stable/reference/ (define arr right-arrow-pict) (define ucode* (list @coderm|{# Python code}| @coderm|{}| @coderm|{def join(d0,d1,sort,how):}| @coderm|{ ....}| @coderm|{}| @coderm|{}| )) (define tcode* (list @coderm|{def join(d0:DataFrame,}| @coderm|{ d1:DataFrame,}| @coderm|{ sort:bool,}| @coderm|{ how:Left|Right)}| @coderm|{ -> DataFrame:}| @coderm|{ ....}| )) (define uu (untyped-codeblock* ucode*)) (define tt (vc-append tiny-y-sep (typed-codeblock* (list @coderm{DataFrame})) (typed-codeblock* (list @coderm{bool})) (typed-codeblock* (list @coderm{Left|Right})))) (define gg (let ((maxw (+ 4 (apply max (map pict-width tcode*))))) (cc-superimpose (untyped-codeblock* (list* @coderm{# Python + Types} @coderm{} @coderm{} (map (lambda (pp) (blank maxw (pict-height pp))) ucode*))) (typed-codeblock* tcode*)))) (if (< n 3) (hc-append tiny-x-sep (tag-pict uu 'ucode) arr ((if (< n 1) bghost values) tt) ((if (< n 1) bghost values) arr) (tag-pict ((if (< n 2) bghost values) gg) 'gcode)) gg)) (define (types-traditional-benefits) (bbox (vc-append tiny-y-sep (table2 ;; TODO icons #:col-sep tiny-x-sep @rm{Types for:} @rm{static checks} (blank) @rm{run-time guarantees} (blank) @rm{optimizations}) @rm{vs. cost of untyped interop.}))) (define (happy-face) (tiny-face 'sortof-happy)) (define (confused-face) (tiny-face 'unhappy)) (define (tiny-face sym) (scale (face sym) 24/100)) ;; ----------------------------------------------------------------------------- (define the-title-str "Gradual Soundness: Lessons from Static Python") (define (sec:title) (pslide #:go title-coord-m (title-pict)) (void)) (define (sec:what) (pslide #:next #:go hi-text-coord-ll (static-python-logo) #:next #:go hi-text-coord-rr (yblank med-y-sep) @rm{Enhanced Python, by Instagram} (yblank smol-y-sep) (word-append @rm{ +2 years running } @bodyrm{in production}) #:next (yblank smol-y-sep) (ll-append @rm{Gradually typed} (word-append @rm{ ... for some value of } @rmem{gradual})) ) (pslide #:go heading-coord-r @titlerm2{What is Gradual Typing?} ;; one main point of talk = subtle question! #:next #:go hi-text-coord-m (bbox @rm{Idea: combine the best parts of typed and untyped code}) ;; untyped as before, flexible ... idiomatic, handy, lovable, concise ;; typed, use statics soundness performance #:next (yblank smol-y-sep) #:alt ((py-migration 0) #:go (at-find-pict 'ucode ct-find 'lc #:abs-x smol-x-sep) (bbox (hc-append (confused-face) @rm{ so many parameters!}))) #:alt ((py-migration 1)) (py-migration 2) #:go (at-find-pict 'gcode rt-find 'rc #:abs-x (- 4)) (bbox (happy-face)) #:next #:go (coord 1/2 40/100 'ct) (bbox (lc-append @rm{Great!} @rm{} (word-append @rm{But, } @bodyrm{what happens} @rm{ when}) (yblank pico-y-sep) (hc-append (typed-codeblock* (list @rm{typed code})) @rm{ and } (untyped-codeblock* (list @rm{untyped code}))) (yblank pico-y-sep) @rm{interact?} @rm{} @rm{Are types sound?})) ) (pslide #:go heading-coord-r @titlerm2{What is Gradual Typing?} #:next #:go hi-text-coord-l (three-answers 0) #:next #:go (at-find-right 'a1) #:alt ((a1-optional 0)) #:alt ((a1-optional 1)) (a1-optional 2) #:next #:go (at-find-right 'a2) #:alt ((a2-deep 0)) #:alt ((a2-deep 1)) (a2-deep 2) #:next ;; TODO perf interlude?? (highlight word in RED then use RED background or something for the detour) ;; why = 1: lattice, 2: build suspense for the SP perf improvement ;; 2014: "in the context of current impl tech sound gradual typing is dead" #:go (at-find-right 'a3) (a3-concrete 2) #:go (at-find-pict 'a3 cb-find 'ct #:abs-y pico-y-sep) (parameterize ((bbox-x-margin pico-x-sep)) (bbox @rm{Today!})) ) (pslide #:go hi-text-coord-l #:alt ( (three-answers 1) #:go (at-find-right 'a3) (a3-concrete 2) ) (bblur2 (three-answers 1)) #:go (at-find-right 'a3) (bblur2 (a3-concrete 2)) #:go heading-coord-m @titlerm2{Experience @|at-sign| Instagram Web Server} #:next #:go hi-text-coord-ll (yblank (- smol-y-sep)) (insta-modules) #:next #:go hi-text-coord-rr #:alt ((insta-boost 0)) #:alt ((insta-boost 1)) (insta-boost 2) ) (void)) (define (sec:how) (center-slide "How is Static Python so Fast?") (pslide #:go heading-coord-m ;; https://github.com/facebookincubator/cinder @titlerm2{Step 0. Better Compiler & Runtime} #:next (yblank med-y-sep) (lc-append (freeze (scale (bitmap "img/cinder.png") 45/100)) @tcoderm{https://github.com/facebookincubator/cinder}) #:next (yblank smol-y-sep) ;; TODO staging #:alt ((runtime-support 0)) (runtime-support 1) ) (pslide #:go heading-coord-m @titlerm2{Step 1. Fast Soundness Checks} #:next #:go hi-text-coord-ll (tag-pict (vc-append smol-y-sep (tag-pict (untyped-codeblock* (list @coderm{avg(nums)})) 'ucode) (tag-pict down-arrow-pict 'boundary) (typed-codeblock* (list @coderm{def avg(ns:chklist[int]) -> int:} @coderm{ ....}))) 'main) #:next #:go hi-text-coord-rr (bbox (lc-append @rm{Q. How to enforce soundness?} (yblank tiny-y-sep) (word-append @rm{A. } @bodyrm{Tag check}) (yblank tiny-y-sep) (parameterize ((bbox-x-margin pico-x-sep)) (hc-append @rm{Is } @ucode{nums} @rm{ an instance of } @tcode{chklist[int]} @rm{ ?})))) #:next (yblank tiny-y-sep) (vc-append tiny-y-sep (hc-append (xblank tiny-x-sep) (table2 #:row-sep tiny-y-sep #:col-sep tiny-x-sep (list (check-pict 40) @rm{Fast! No traversal, no wrapper} (stop-pict 40) @rm{Rejects built-in Python lists}))) (vc-append 4 @rm{Need constructor:} @ucode{avg(chklist[int](nums))})) ) (pslide #:go heading-coord-m @titlerm2{Step 2. Progressive Types} #:next (yblank smol-y-sep) (pstripe 'p0 'p1 'p2) #:next #:go (at-find-pict 'p1 cc-find 'cc) (tag-pict (typed-codeblock* (list @coderm{chklist[int]})) 'clist) #:go (at-find-pict 'p2 cc-find 'cc) (tag-pict (bghost @tcode{int64}) 'pint) #:next #:go (at-find-pict 'clist cc-find 'cc #:abs-y (- (stripe-h))) (tag-pict (typed-codeblock* (list @coderm{list})) 'slist) #:set (bvline ppict-do-state 'slist 'clist) #:next #:go (at-top-left 'p0) (types-nametag "Shallow" "Python value-shapes") #:go (at-top-left 'p1) (types-nametag "Concrete" "sound generics") #:go (at-find-pict 'clist cb-find 'ct #:abs-y pico-y-sep) (hc-append pico-y-sep @tcode{chkdict[string, int]} @tcode{chklist[T]}) #:go (at-find-pict 'pint cc-find 'cc #:abs-y (- (stripe-h))) (tag-pict @tcode{int} 'sint) #:go (at-find-pict 'slist rt-find 'lt #:abs-x med-x-sep) (vc-append pico-y-sep @tcode{dict} (hc-append pico-y-sep @tcode{string} @tcode{bool})) #:next #:go (at-find-pict 'pint cc-find 'cc) (ppict-do @tcode{int64} #:go (coord 1/2 1 'lt #:abs-x pico-y-sep #:abs-y pico-y-sep) @tcode{Array[float32]}) #:set (bvline ppict-do-state 'sint 'pint) #:go (at-top-left 'p2) (types-nametag "Primitive" "C values") ) (pslide #:go heading-coord-m @titlerm2{Step 3. Limited Dyn Type} #:next (yblank smol-y-sep) #:alt ((dyn-theory-practice 0)) #:alt ((dyn-theory-practice 1)) (dyn-theory-practice 2) (yblank pico-y-sep) (sp-types-enable 1) #:next (yblank tiny-y-sep) (pvstripe 'stype 'ctype 'ptype) #:go (at-bot-mid 'stype) (shallow-box "dispatch") #:go (at-bot-mid 'ctype) (concrete-box "fast checks") #:go (at-bot-mid 'ptype) (primitive-box "unboxing") #:next #:go (at-top-mid 'stype) #:alt ((shallow-dynlimit 0)) (shallow-dynlimit 1) #:go (at-top-mid 'ptype) #:alt ((primitive-dynlimit 0)) (primitive-dynlimit 1) #:go (at-top-mid 'ctype) (concrete-dynlimit 0) ) (pslide #:go heading-coord-m @titlerm2{Step 4. Limited Scope} #:next (yblank med-y-sep) (bbox (lc-append (word-append @rm{Focus on high-payoff } @bodyrmem{optimizations}) @rm{rather than feature-completeness})) (yblank med-y-sep) #:next (defer-to 'python (vc-append tiny-y-sep (hc-append tiny-y-sep @ucode{eval} @ucode{first-class class}) @ucode{multiple inheritance})) (yblank med-y-sep) (defer-to 'pyre (vc-append tiny-y-sep (hc-append tiny-y-sep @tcode{Callable[T0, T1]} @tcode{Setof[T]}) @tcode{Union[T0, T1, T2]})) ) (pslide #:go heading-coord-m @titlerm2{How is Static Python so Fast?} #:go hi-text-coord-ll #:alt ((step-summary 0)) (ppict-do (step-summary 1) #:go (coord 1 1/2 'lc #:abs-x smol-x-sep) (vc-append pico-y-sep (scale (pstripe-icon) 8/10) (bbox (lc-append @rm{Types gradually enable optimizations} @bodyrm{Gradual Soundness})))) ) (pslide #:go heading-coord-m (ppict-do @titlerm2{More Experience} #:go (coord 1 1/2 'lt #:abs-x med-x-sep) (scale (pstripe-icon) 6/10)) #:next #:go (coord 1/2 32/100 'ct) #:alt ((gradual-soundness 0)) (gradual-soundness 1) ) (void)) (define (sec:lesson) (center-slide "Takeaways") (pslide #:go heading-coord-m @titlerm2{Takeaways} #:go lesson-coord-h #:alt ( (prior-work-concrete (takeaway:gt 1))) #:alt ( #:go lesson-coord-m (takeaway:imp 0)) #:go lesson-coord-l (takeaway:lang 0) ) (pslide #:go heading-coord-m @titlerm2{The End} #:go lesson-coord-h (ppict-do (vl-append smol-y-sep (takeaway:gt 2) (takeaway:imp 2) (takeaway:lang 2)) #:go (coord 1 1/2 'lc #:abs-x smol-x-sep) (vc-append tiny-y-sep (scale (static-python-logo #:title? #t) 7/10) (scale (pstripe-icon) 7/10))) ) (void)) ;; --- (define microbench-data ;; lots more in paper: SP JIT SF, T-Max T-Min Orig '((deltablue 1 0.59 0.30) (fannkuch 1 1.03 0.46) (nbody 1 1.09 0.24) (richards 1 0.53 0.22))) (define (python-baseline-bar) (hrule 1 #:width 2 #:color python-blue #:alpha 0.9)) (define (runtime-support nn) ;; https://docs.python.org/3.8/library/dis.html#python-bytecode-instructions (define lhs (if (< nn 0) (blank) (label-above (bbox (lc-append @rm{V Tables} @rm{Method-based JIT} @rm{...})) @bodyrm{Cinder Runtime}))) (define rhs ((if (< nn 1) bghost values) (label-above (bbox (table2 #:row-sep pico-y-sep #:col-sep tiny-x-sep @coderm{CALL_FUNCTION} @rm{Python default} @coderm{INVOKE_METHOD} @rm{V Table lookup} @coderm{INVOKE_FUNCTION} @rm{direct call})) @bodyrm{Type-Aware Bytecode}))) (ht-append med-x-sep lhs rhs)) (define (dyn-theory-practice n) (define lhs (dyn-vs-untyped "GT Theory" "==")) (define rhs (dyn-vs-untyped "Static Python" "!=")) (ht-append med-x-sep ((if (< 1 n) bblur values) lhs) ((if (< n 1) bghost values) rhs))) (define (dyn-vs-untyped name eq) (define shim (make-list 1 (bghost @coderm{xxxx}))) (define lhs (untyped-codeblock* shim)) (define rhs (typed-codeblock* shim)) (define llbl @rm{Untyped code}) (define rlbl @rm{Dyn-Typed code}) (define hshim (bghost @rm{X})) (label-above (bbox (ht-append pico-x-sep (label-above lhs llbl) (word-append hshim (coderm eq) hshim) (label-above rhs rlbl))) (bodyrm name))) (define (microbenchmarks [n 0] #:h [hh #f] #:w [ww #f]) (define row->title first) (define row->python second) (define row->tmin third) (define row->tmax fourth) (define skip-len (length (car microbench-data))) (define y-max (let* ((nn (apply max (filter real? (flatten microbench-data)))) (nn (exact-ceiling (* 10 nn))) (nn (/ nn 10))) nn)) (parameterize ((plot-x-ticks (microbench-ticks '(delta fannk nbody richa))) (plot-y-ticks (exact-overhead-ticks '(0 1/2 1 3/2))) (plot-font-family 'modern) (plot-font-size 22)) (plot-pict (list (python-baseline-bar) (for/list ((acc (in-list (list row->python row->tmin row->tmax row->tmax))) (c0 (in-list (list untyped-color shallow-color concrete-color primitive-color))) (c1 (in-list (list untyped-brush-color shallow-brush-color concrete-brush-color primitive-brush-color))) (-jj (in-naturals))) (define overlap? (> -jj 2)) (define jj (min -jj 2)) (rectangles (for/list ((rr (in-list microbench-data)) (ii (in-naturals))) (define x0 (+ (* ii skip-len) jj)) (vector (ivl x0 (+ x0 1)) (ivl 0 (acc rr)))) #:color c1 #:style (if overlap? 'bdiagonal-hatch 'solid) #:line-width (if overlap? 2 1) #:line-color c0 #:alpha (if (< n jj) 0 0.95)))) #:y-max (+ 1/2 y-max) #:title #f #:x-label #f #:y-label #f #:legend-anchor 'no-legend #:width (or ww (x%->pixels 7/10)) #:height (or hh (h%->pixels 6/10))))) (define (microbench-ticks name*) (define (my-layout ax-min ax-max) (for/list ((n (in-list '(3/2 11/2 19/2 27/2)))) (pre-tick n #true))) (define (my-format ax-min ax-max pt*) (for/list ((pt (in-list pt*)) (nn (in-list name*))) (format "~a" nn))) (ticks my-layout my-format)) (define (exact-overhead-ticks n*) (define (my-layout ax-min ax-max) (for/list ((n (in-list n*))) (pre-tick n #true))) (define (my-format ax-min ax-max pt*) (for/list ((pt (in-list pt*))) (define vv (pre-tick-value pt)) (format "~ax" (if (integer? vv) vv (exact->inexact vv))))) (ticks my-layout my-format)) (define (step-summary n) (define fmt (if (< n 1) bodyrmlo bodyrm)) (bbox (ll-append @rm{0. Better Compiler & Runtime} @rm{1. Fast Soundness Checks} @fmt{2. Progressive Types} @rm{3. Limited Dyn Type} @rm{4. Limited Overall Scope}))) (define (gradual-soundness n) (define lhs (bbox (label-above (table2 #:row-sep pico-y-sep #:col-sep tiny-x-sep #:col-align cc-superimpose (list (typed-codeblock* (list (word-append @bodyrm{959 typed} @rm{ modules}))) (blank) (concrete-codeblock* (list (word-append @bodyrm{ 10} @rm{ with } @bodyrm{Concrete}))) @rm{(fast reads)}) (primitive-codeblock* (list (word-append @bodyrm{ 16} @rm{ with } @bodyrm{Primitives}))) @rm{(unboxed math)}) @rm{Instagram, March 2023:} (yblank tiny-y-sep)))) (define rhs ;; - typed = shallow ;; - refined = concrete + primitive ;; - T speedup = some benefits out of box, wow ;; - T slowdown = high cost of checks / low opt ;; - R all speedups, nice (bbox (label-above (microbenchmarks 2 #:h (* 2 big-y-sep) #:w (* 2.5 big-x-sep)) @rm{Microbenchmarks} (word-append @rm{1x = Python, } @bodyrm{lower} @rm{ is faster}) (yblank pico-y-sep)))) (ht-append smol-x-sep lhs ((if (< n 1) bghost values) rhs))) (define (a1-optional n) (define txt @rm{Optional static checks, nothing at run-time}) (define logo (ts-pict)) (define extra (hc-append @rm{How to debug? } (untyped-codeblock* (list @coderm{join(42, "hola", ...)})))) (three-part-description n txt logo extra)) (define (a2-deep n) (define txt @rm{Static types + contracts}) (define logo (tr-pict)) (define extra (hc-append @rm{Performance? } (join-call-huge))) (three-part-description n txt logo extra)) (define (join-call-huge) (untyped-codeblock* (list (word-append @coderm{join(} @codeembf{huge0} @coderm{, } @codeembf{huge1} @coderm{, ...)})))) (define (a3-concrete n) (define txt (word-append @bodyrmlo{Progressive static types + tags} ; @rm{ (} ; (xblank 2) ; @bodyrm{gradual soundness} ; (xblank 2) ; @rm{)} )) (define logo (sp-pict)) (define extra (blank)) (three-part-description n txt logo extra)) (define (three-part-description n txt logo extra) (ppict-do txt #:go (coord 5/100 1 'lt #:abs-y pico-y-sep) (ppict-do ((if (< n 1) bghost values) logo) #:go (coord 1 3/10 'lt #:abs-x tiny-x-sep) ((if (< n 2) bghost values) extra)))) (define (center-slide str) (pslide #:go center-coord (titlerm2 str))) (define (stripe-h) (* 35/100 client-h)) (define (stripe cc [wscale #f]) (filled-rectangle (* (or wscale 1) (+ (* 2 margin) client-w)) (stripe-h) #:color cc #:draw-border? #f)) (define (vstripe cc) (filled-rectangle (* 1/3 client-w) (- (* 1/2 client-h) margin) #:color cc #:draw-border? #f)) (define (at-cc sym) (at-find-pict sym cc-find 'cc)) (define (at-top-left sym) (at-find-pict sym lt-find 'lt #:abs-x 8 #:abs-y 4)) (define (at-bot-mid sym) (at-find-pict sym cb-find 'cb #:abs-y -4)) (define (at-top-mid sym) (at-find-pict sym ct-find 'ct #:abs-y tiny-y-sep)) (define (types-nametag name what) (bbox (word-append (bodyrm (string-append name " types")) (bodyrmlo (string-append " for " what))))) (define (pstripe s0 s1 s2) (define l0-color shallow-color) (define l1-color concrete-color) (define l2-color primitive-color) (bblur #:alpha 6/10 #:bg #true (vc-append (tag-pict (stripe l0-color) s0) (hc-append (tag-pict (stripe l1-color 1/2) s1) (tag-pict (stripe l2-color 1/2) s2))))) (define (pvstripe s0 s1 s2) (define l0-color shallow-color) (define l1-color concrete-color) (define l2-color primitive-color) (bblur #:alpha 6/10 #:bg #true (ht-append (tag-pict (vstripe l0-color) s0) (tag-pict (vstripe l1-color) s1) (tag-pict (vstripe l2-color) s2)))) (define (pstripe-icon) (ppict-do (scale (pstripe 'a 'b 'c) 4/10) #:go (at-cc 'a) (shallow-box) #:go (at-cc 'b) (concrete-box) #:go (at-cc 'c) (primitive-box))) (define (shallow-box [extra #f]) (progressivebox "Shallow" extra)) (define (concrete-box [extra #f]) (progressivebox "Concrete" extra)) (define (primitive-box [extra #f]) (progressivebox "Primitive" extra)) (define (progressivebox name [extra #f]) (define pp (bodyrm name)) (bbox (if extra (hc-append pp @rm{ ~ } (rmem extra)) pp))) (define (shallow-dynlimit n) (maybe-bblur (< 0 n) (vc-append tiny-y-sep ;(untyped-codeblock* ; (list ; @coderm{class A:} ; @coderm{ def f(self):})) (typed-codeblock* (list @coderm{class A:} @coderm{ def f(self)->int:})) (typed-codeblock* (list @coderm{class B(A):} @coderm{ def f(self):} @codebf{ # Type Error}))))) (define (primitive-dynlimit n) (maybe-bblur (< 0 n) (typed-codeblock* (list @coderm{x:int64 = 42} @coderm{y = x} @codebf{# Type Error})))) (define (concrete-dynlimit n) (maybe-bblur (< 0 n) (vc-append pico-y-sep (typed-codeblock* (list @coderm{def avg(ns:chklist[dyn]):} @coderm{ ....})) (typed-codeblock* (list @coderm{avg(chklist[int](1,2))} @codebf{# Runtime Error}))))) (define (sp-types-enable n) (define sp-yes (word-append @rm{Types enable } @bodyrmem{optimizations})) (define sp-no (hc-append (scale (lc-append @rm{Types enable arbitrary migrations} @rm{(gradual guarantees)}) 90/100) @coderm{ << })) (bbox (hc-append ((if (< n 1) bghost values) sp-no) sp-yes))) (define (bvline pp src tgt) (define arr (code-arrow src cb-find tgt ct-find (* 1/4 turn) (* 3/4 turn) 0 0 'solid)) (add-code-line pp arr #:line-width 4 #:color (bbox-frame-color))) (define (defer-to sym pp) (define-values [img name] (case sym ((python) (values (python-pict) "Python")) ((pyre) (values (pyre-pict) "Pyre")) (else (raise-argument-error 'defer-to "(or/c 'python 'pyre)" sym)))) (define txt (hb-append smol-x-sep (word-append @coderm{==> } @rm{defer to @|name| }) img)) (hc-append tiny-x-sep pp txt)) (define (lesson-for pp str n) (if (< n 2) (hc-append smol-x-sep pp (rm str)) pp)) (define (three-answers n) (hc-append smol-x-sep ((if (< n 1) values bghost) (py-migration 4)) (vl-append big-y-sep ((if (< n 1) values bghost) (add-hubs @headrm{A1.} 'a1)) ((if (< n 1) values bghost) (add-hubs @headrm{A2.} 'a2)) (add-hubs @headrm{A3.} 'a3)))) (define (envelope-pict ww hh #:color [color utah-litegrey] #:line-width [line-width 2]) (define (draw dc dx dy) (define old-brush (send dc get-brush)) (define old-pen (send dc get-pen)) (send dc set-brush (new brush% [style 'solid] [color color])) (send dc set-pen (new pen% [width line-width] [color black])) ;; --- (define path (new dc-path%)) (send path rectangle 0 0 ww hh) (send dc draw-path path dx dy) (send dc draw-lines `((0 . 0) (,(* ww 1/2) . ,(* hh 6/10)) (,ww . 0)) dx dy) ;; --- (send dc set-brush old-brush) (send dc set-pen old-pen)) (dc draw ww hh)) (define (hpictx n pp) (apply hc-append pico-x-sep (make-list n pp))) (define (server-pict ww hh) (define color "dark gray") (define line-width 2) (define (draw dc dx dy) (define old-brush (send dc get-brush)) (define old-pen (send dc get-pen)) (send dc set-brush (new brush% [style 'solid] [color color])) (send dc set-pen (new pen% [width line-width] [color black])) ;; --- (define ygap (* 2/10 hh)) (define xgap (* 2/10 ww)) (let ((path (new dc-path%))) (send path move-to 0 hh) (send path line-to 0 (+ 0 ygap)) (send path line-to (+ 0 xgap) 0) (send path line-to ww 0) (send path line-to ww (- hh ygap)) (send path line-to (- ww xgap) hh) (send path close) (send dc draw-path path dx dy)) (send dc draw-lines `((0 . ,ygap) (,(- ww xgap) . ,ygap) (,ww . 0)) dx dy) (send dc draw-lines `((,(- ww xgap) . ,ygap) (,(- ww xgap) . ,hh)) dx dy) (let ((path (new dc-path%))) (for ((ym (in-list '(1/2 1)))) (send path rounded-rectangle (* 1/2 xgap) (- hh (* ym ygap)) (* 3 xgap) (* 1/8 ygap)) (send dc draw-path path dx dy))) ;; --- (send dc set-brush old-brush) (send dc set-pen old-pen)) (dc draw ww hh)) (define (takeaway:gt n) (define concrete-rqs ((if (< n 1) bghost values) (bbox (parameterize ((bbox-x-margin pico-x-sep)) (ll-append @rm{Qs for Concrete:} (hc-append @rm{ * migrating } @tcode{list} @rm{ to } @ccode{chklist[T]} @rm{ etc.}) (yblank pico-y-sep) (hc-append @rm{ * fast tags for } @ccode{Union[T0, T1, T2]})))))) (define theory-perf (bbox @rm{Guarantees vs. Performance?})) ((if (< n 2) ht-append hc-append) smol-x-sep (lesson-for (gt-research-pict) "GT Researchers" n) (if (< n 2) (vc-append tiny-y-sep theory-perf concrete-rqs) (bbox @rm{New research directions})))) (define (takeaway:imp n) (hc-append smol-x-sep (lesson-for (practitioner-pict) "Practitioners" n) (if (< n 2) (ppict-do (bbox @rm{Why not your language?}) #:go (coord 1/2 1 'ct #:abs-y pico-y-sep) (scale (pstripe-icon) 6/10)) (bbox @rm{Who's next?})))) (define (takeaway:lang n) (define pp (bbox (if (< n 2) (ll-append @rm{Redex model found:} ;; @rm{* Redex model of Static Python} ;; @rm{* Converted 265 tests} (word-append @bodyrm{ 5} @rm{ critical soundness bugs}) (word-append @bodyrm{ 16} @rm{ correctness issues})) (ll-append @rm{Model found:} (word-append @bodyrm{ 5} @rm{ soundness + } @bodyrm{16} @rm{ other issues}))))) ((if (< n 2) hb-append hc-append) smol-x-sep (lesson-for (designers-pict) "Language Designers" n) (ppict-do pp #:go (coord 1 1) (if (< n 2) (racket-pict) (blank))))) (define (gt-research-pict) (define pp (ppict-do (blank 36 55) #:go (coord 0 0 'lt) @hugerm{ฯ„} #:go (coord 1 1 'rb) @hugerm{ฮป})) (ppict-do (blank 100) #:go center-coord (scale pp 3/2))) (define (practitioner-pict) (define ww 70) (define pp (ppict-do (blank ww ww) #:go (coord 1 1) (js-pict) #:go (coord 0 0) (ruby-pict) #:go (coord 1 0) (php-pict) #:go (coord 0 1) (clojure-pict) )) (ppict-do (blank 100) #:go center-coord (scale pp 8/10))) (define (designers-pict) (define ww 130) (ppict-do (blank 100) #:go center-coord (frame (freeze (scale-to-square (bitmap "img/msn.jpeg") ww))))) (define (prior-work-concrete pp) (define tp (thorn-pict)) (define cc* (parameterize ((bbox-x-margin 10) (bbox-y-margin 4)) (hc-append pico-y-sep (bbox tp) (bbox (nom-pict tp))))) (ppict-do pp #:go (coord 1 1 'ct #:abs-y pico-y-sep #:abs-x (- smol-x-sep)) (ppict-do cc* #:go (coord 0 1/2 'rc #:abs-x (- pico-x-sep)) @rm{Prior work:}))) ;; ----------------------------------------------------------------------------- (define (do-show) ;; (set-page-numbers-visible! #true) (set-spotlight-style! #:size 60 #:color (color%-update-alpha highlight-brush-color 0.6)) ;; [current-page-number-font page-font] ;; [current-page-number-color white] ;; -- (parameterize ((current-slide-assembler bg-bg)) (sec:title) (sec:what) (sec:how) (sec:lesson) (pslide) (void)) (void)) (module+ main (do-show)) ;; ============================================================================= ;; open RQs ;; - debugging with unsoundness; or slow sound mode ;; - more sound types, unions ;; - reduce dyn limits (module+ raco-pict (provide raco-pict) ;;(define client-w 984) (define client-h 728) ;; 4:3 (define client-w 1320) (define client-h 726) ;; 16:9 sort of, too thin (define raco-pict (ppict-do (make-bg client-w client-h) #;(make-titlebg client-w client-h) )))
false
047d22540423f334c8744e2953f0519575792fb0
0a345b89eae9a12e18e8d30f24d592a724284a59
/plugins/prng/prng-impl.scm
1dd3abfc62ae57468fa487ae7b5319b7cf44e2e7
[ "0BSD", "MIT" ]
permissive
DeMOSic/bintracker
7b26ecb3b8ad315727bb65f1051206b2dcac7123
bed6356b7d177d969ea3873527a1698a00305acf
refs/heads/master
2023-03-26T19:11:49.396339
2021-03-29T08:51:12
2021-03-29T08:51:12
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
18,371
scm
prng-impl.scm
;; Copyright (c) 2020 Michael Neidel ;; 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. ;;; Various pseudo-random number generators. (module prng (prng::middle-square prng::middle-square-weyl-seq prng::blum-blum-shub prng::pcg prng::xorshift64 prng::randu prng::el-cheapo-zx prng::dmg-noise prng::sid-noise prng::tia-noise prng::pi-digits prng::info) (import scheme (chicken base) (chicken bitwise) (chicken random) srfi-1 srfi-13) ;;; > Anyone who considers arithmetical methods of producing random digits is, ;;; > of course, in a state of sin. ;;; ;;; *J. v. Neumann* (define-constant pi 3.14159265358979323846) (define-constant e 2.71828182845904523536) ;;; Alias for `arithmetic-shift` (define << arithmetic-shift) (define (rand bits) (pseudo-random-integer (sub1 (expt 2 bits)))) ;;; Addition of arbitrary-sized integers. (define (uint-arithmetic operator integer-bits operands) (bitwise-and (apply operator operands) (sub1 (expt 2 integer-bits)))) (define (add-uint integer-bits operands) (uint-arithmetic + integer-bits operands)) (define (mul-uint integer-bits operands) (uint-arithmetic * integer-bits operands)) ;;; 8-bit unsigned addition (define (add/8 . operands) (add-uint 8 operands)) ;;; 16-bit unsigned addition (define (add/16 . operands) (add-uint 16 operands)) ;;; 32-bit unsigned addition (define (add/32 . operands) (add-uint 32 operands)) ;;; 64-bit unsigned addition (define (add/64 . operands) (add-uint 64 operands)) ;;; 8-bit unsigned multiply (define (mul/8 . operands) (mul-uint 8 operands)) ;;; 16-bit unsigned multiply (define (mul/16 . operands) (mul-uint 16 operands)) ;;; 32-bit unsigned multiply (define (mul/32 . operands) (mul-uint 32 operands)) ;;; 64-bit unsigned multiply (define (mul/64 . operands) (mul-uint 64 operands)) ;;; 8-bit rotation (define (rol/8 i amount) (let ((j (bitwise-and i #xff))) (if (zero? amount) j (rol/8 (bitwise-ior (<< (bitwise-and j #x80) -7) (<< j 1)) (sub1 amount))))) ;;; Collect bits represented the list of zeroes and ones BSTREAM into ;;; integers of size BITS. (define (bitstream->int bstream bits) (letrec* ((collect-bits (lambda (bs val count) (if (zero? count) val (collect-bits (cdr bs) (bitwise-ior (car bs) (* 2 val)) (sub1 count))))) (collect-vals (lambda (bs) (if (null? bs) '() (cons (collect-bits bs 0 bits) (collect-vals (drop bs bits)))))) (pad (- bits (modulo (length bstream) bits)))) (collect-vals (if (zero? (modulo (length bstream) bits)) bstream (append bstream (make-list (- bits (modulo (length bstream) bits)) 0)))))) ;; ;;; Adjust the size of the integer N by performing a logical bitshift. WANT ;; ;;; is the desired size (number of bits) of the resulting integer, and HAVE is ;; ;;; the actual size of integer N. ;; (define (adjust-integer-size n want have) ;; (bitwise-and (arithmetic-shift n (- want have)) ;; (sub1 (expt 2 want)))) ;; ;;; Calculate the number of 1-bits in the integer x. ;; (define (population-count x) ;; (arithmetic-shift (mul/64 #x1111111111111111 ;; (bitwise-and #x1111111111111111 ;; (mul/64 x #x2000400080010))) ;; -60)) ;;; A generator based on the Middle-Square Method, as devised by John von ;;; Neumann in 1946. It is statistically very poor and may break with ;;; unsuitable seeds. This implementation deviates from von Neumann's design ;;; by considering only the lower half of the 8 digits extracted from the ;;; 16-digit square. This is done to mitigate the effects of the convergence ;;; towards lower number sequences that is a common trait of the Middle Square ;;; method. (define (prng::middle-square amount maxint #!optional (seed 12345678)) (letrec ((gen-next (lambda (n s) (if (zero? n) '() (let ((squared-str (string-pad (number->string (expt s 2)) 16 #\0))) (cons (string->number (string-drop (string-take squared-str 12) 8)) (gen-next (sub1 n) (string->number (string-append (string-take squared-str 4) (string-take-right squared-str 4)))))))))) (map (lambda (x) (inexact->exact (round (* maxint (/ x 10000))))) (gen-next amount seed)))) ;;; A variation of von Neumann's Middle Square Method that applies a Weyl ;;; sequence to the Middle Square generator, developed by Bernard Widynski. ;;; Very good statistical quality. See https://arxiv.org/abs/1704.00358v4 (define (prng::middle-square-weyl-seq amount maxint #!optional (seed (rand 32)) (magic #xb5ad4eceda1ce2a9)) (letrec ((gen-next (lambda (n x w) (if (zero? n) '() (let* ((next-w (add/64 w magic)) (x-squared+w (add/64 next-w (expt x 2))) (next-x (bitwise-ior (<< x-squared+w -32) (bitwise-and #xffffffffffffffff (<< x-squared+w 32))))) (cons (bitwise-and next-x #xffffffff) (gen-next (sub1 n) next-x next-w))))))) (map (lambda (x) (inexact->exact (round (* maxint (/ x #x100000000))))) (gen-next amount seed 0)))) ;;; Blum Blum Shub Generator. SEED must be greater than 1, and neither p nor q ;;; may be a factor of SEED. The generator will replace invalid seeds with a ;;; random seed if SEED fails to satisfy these conditions. ;;; https://en.wikipedia.org/wiki/Blum_Blum_Shub (define (prng::blum-blum-shub amount maxint #!optional (seed (rand 32)) (p 5651) (q 5623)) (letrec* ((mod (* p q)) (make-bits (lambda (n seed) (if (zero? n) '() (let* ((next-seed (modulo (expt seed 2) mod))) (cons (bitwise-and next-seed 1) (make-bits (sub1 n) next-seed))))))) (if (and (> seed 1) (not (zero? (modulo seed p))) (not (zero? (modulo seed q)))) (map (lambda (x) (inexact->exact (round (* maxint (/ x #x10000000000000000))))) (bitstream->int (map (cute bitwise-and 1 <>) (make-bits (* amount 64) seed)) 64)) (prng::blum-blum-shub amount maxint (rand 32) p q)))) ;;; Xorshift-Rotate-Right Permuted Congruential Generator, ;;; see https://www.pcg-random.org/ (define (prng::pcg amount maxint #!optional (seed (rand 64))) (letrec* ((ror (lambda (n amnt) (bitwise-and #xffffffff (bitwise-ior (bitwise-and (<< n (- amnt)) (sub1 (expt 2 (- 32 amnt)))) (<< n (bitwise-and (- amnt) #x1f)))))) (make-values (lambda (n state) (if (zero? n) '() (cons (ror (bitwise-and #xffffffff (<< (bitwise-xor state (bitwise-and (<< state -18) (sub1 (expt 2 46)))) -27)) (bitwise-and (<< state -59) #x1f)) (make-values (sub1 n) (bitwise-and #xffffffffffffffff (+ (* state 6364136223846793005) 1442695040888963407)))))))) (map (lambda (x) (inexact->exact (round (* maxint (/ x #x100000000))))) (make-values amount (bitwise-and #xffffffffffffffff (+ seed 1442695040888963407)))))) ;;; Classic non-scrambled 64-bit Xorshift generator, as developed by George ;;; Marsaglia. See https://en.wikipedia.org/wiki/Xorshift (define (prng::xorshift64 amount maxint #!optional (state (rand 64))) (letrec ((make-values (lambda (amount state) (if (zero? amount) '() (let* ((x1 (bitwise-xor state (bitwise-and #xffffffffffffffff (arithmetic-shift state 13)))) (x2 (bitwise-xor x1 (arithmetic-shift x1 -17))) (next-state (bitwise-xor x2 (bitwise-and #xffffffffffffffff (arithmetic-shift x2 5))))) (cons next-state (make-values (sub1 amount) next-state))))))) (map (lambda (x) (inexact->exact (round (* maxint (/ x #x10000000000000000))))) (make-values amount state)))) ;;; A notoriously flawed LCG-type PRNG developed by IBM in the 1960s. (define (prng::randu amount maxint #!optional (seed (rand 32))) (letrec ((make-values (lambda (v0 n) (if (zero? n) '() (let ((v1 (bitwise-and #xffffffff (* 65539 (modulo v0 (expt 2 31)))))) (cons v1 (make-values v1 (sub1 n)))))))) (map (lambda (x) (inexact->exact (round (* maxint (/ x #x100000000))))) (make-values (bitwise-ior seed 1) amount)))) ;;; Very fast but extremely poor 8-bit PRNG used to generate noise in various ;;; ZX Spectrum beeper engines. (define (prng::el-cheapo-zx amount maxint #!optional (seed (rand 16)) (magic #x2175)) (letrec ((make-values (lambda (amount state) (if (zero? amount) '() (let* ((next-accu (add/16 state magic)) (next-state (add/16 (<< (rol/8 (<< next-accu -8) 1) 8) (bitwise-and next-accu #xff)))) (cons (quotient next-state #x100) (make-values (sub1 amount) next-state))))))) (map (lambda (x) (inexact->exact (round (* maxint (/ x #x100))))) (make-values amount seed)))) ;;; Returns a Linear feedback shift register implementation. SIZE shall be ;;; the number of bits of the LFSR, and FEEDBACK-FN shall be a procedure that ;;; takes an integer state as argument and returns the next state. (define (make-lfsr size feedback-fn) (lambda (amount maxint #!optional (seed (rand (sub1 size)))) (letrec ((make-values (lambda (amount state) (if (zero? amount) '() (let ((next-state (feedback-fn state))) (cons next-state (make-values (sub1 amount) next-state))))))) (if (= 1 maxint) (map (cute bitwise-and 1 <>) (cons seed (make-values (sub1 amount) (bitwise-and (sub1 (expt 2 size)) (bitwise-ior seed 1))))) (let ((bits (inexact->exact (+ 1 (floor (/ (log maxint) (log 2))))))) (map (lambda (x) (inexact->exact (round (* maxint (/ x (expt 2 bits)))))) (bitstream->int (map (cute bitwise-and 1 <>) (cons seed (make-values (* (sub1 amount) bits) (bitwise-and (sub1 (expt 2 size)) (bitwise-ior seed 1))))) bits))))))) ;;; A PRNG based on the noise waveform generator of the Gameboy APU, which is ;;; a 15-bit LFSR with a tap at bit 1. (define prng::dmg-noise (make-lfsr 15 (lambda (in) (bitwise-ior (bitwise-and #x3fff (quotient in 2)) (arithmetic-shift (bitwise-xor (modulo in 2) (modulo (quotient in 2) 2)) 14))))) ;;; A PRNG based on the noise waveform on the MOS 6581/8580 Sound Interface ;;; Device, which is a Fibonacci LFSR using the feedback polynomial ;;; x^22 + x^17 + 1. See http://www.sidmusic.org/sid/sidtech5.html. For added ;;; authenticity, initialize SEED to #x7ffff8. (define prng::sid-noise (make-lfsr 23 (lambda (in) (bitwise-and #x7fffff (bitwise-ior (arithmetic-shift in -1) (arithmetic-shift (bitwise-xor (arithmetic-shift in -1) (arithmetic-shift in -6)) 22)))))) ;;; A PRNG based on the noise waveform (AUDCx = 8) on the Atari VCS/2600, ;;; which is a 9-bit LFSR with a tap at bit 4, resulting in a period of 511. ;;; For added authenticity, initialize SEED to #x1ff. (define prng::tia-noise (make-lfsr 9 (lambda (in) (bitwise-and #x1ff (bitwise-ior (arithmetic-shift in -1) (arithmetic-shift (bitwise-and 1 (bitwise-xor in (arithmetic-shift in -4))) 8)))))) ;;; Not an actual PRNG. Creates random-looking integer sequences from pi. ;;; Uses the Baileyโ€“Borweinโ€“Plouffe formula to calculate hexadecimal digits ;;; of pi. SEED is the initial fractional digit index, ie. SEED = 0 starts ;;; extracting digits from the first fractional digit. (define (prng::pi-digits amount maxint #!optional (seed (rand 10))) (letrec* ((powermod (lambda (base exp mod) (letrec ((pm (lambda (b e acc) (if (zero? e) acc (pm (modulo (* b b) mod) (arithmetic-shift e -1) (if (even? e) acc (modulo (* b acc) mod))))))) (pm base exp 1)))) (fractional-part (lambda (r) (- r (floor r)))) (finite-sum (lambda (s k n denom) (if (> k n) (cons s denom) (finite-sum (fractional-part (exact->inexact (+ s (/ (powermod 16 (- n k) denom) denom)))) (+ k 1) n (+ denom 8))))) (infinite-sum (lambda (s num denom lastfrac) (let ((newfrac (exact->inexact (/ num denom)))) (if (= lastfrac newfrac) s (infinite-sum (+ s newfrac) (/ num 16) (+ denom 8) newfrac))))) (sigma (lambda (n j) (let ((finite (finite-sum 0.0 0 n j))) (fractional-part (infinite-sum (car finite) (/ 1 16) (cdr finite) 0))))) (nth-digit (lambda (n) (inexact->exact (floor (* 16 (fractional-part (- (* 4 (sigma (sub1 n) 1)) (* 2 (sigma (sub1 n) 4)) (sigma (sub1 n) 5) (sigma (sub1 n) 6)))))))) (digit->bin-lst (lambda (d) (list (quotient (bitwise-and d 8) 8) (quotient (bitwise-and d 4) 4) (quotient (bitwise-and d 2) 2) (bitwise-and d 1)))) (bits (inexact->exact (+ 1 (floor (/ (log maxint) (log 2))))))) (map (lambda (x) (inexact->exact (round (* maxint (/ x (expt 2 bits)))))) (bitstream->int (flatten (map (o digit->bin-lst nth-digit) (iota (if (zero? (modulo bits 4)) (* amount (quotient bits 4)) (+ 1 (* amount (quotient bits 4)))) (+ 1 seed) 1))) bits)))) ;;; Retrieve information on the pseudo-random number generators available in ;;; this package. Call with no arguments to retrieve the complete list. Call ;;; with a symbol naming a procedure in this package to retrieve the ;;; documentation for that procedure. (define (prng::info . args) (let ((prngs `((prng::middle-square . ,(string-append "A generator based on the Middle-Square Method, as devised by" " John von Neumann in 1946. It is statistically very poor and" " may break with unsuitable seeds. This implementation deviates" " from von Neumann's design by considering only the lower half" " of the 8 digits extracted from the 16-digit square. This is" " done to mitigate the effects of the convergence towards lower" " number sequences that is a common trait of the Middle Square" " method.")) (prng::middle-square-weyl-seq . ,(string-append "A variation of von Neumann's Middle Square Method that applies" " a Weyl sequence to the Middle Square generator, developed by" " Bernard Widynski. Very good statistical quality." " See https://arxiv.org/abs/1704.00358v4")) (prng::blum-blum-shub . ,(string-append "The original 1986 design by Lenore Blum, Manuel Blum and" " Michael Shub. SEED must be greater than 1, and neither p nor" " q may be a factor of SEED. The generator will replace invalid" " seeds with a random seed if SEED fails to satisfy these" " conditions." " See https://en.wikipedia.org/wiki/Blum_blum_shub")) (prng::pcg . ,(string-append "Xorshift-Rotate-Right Permuted Congruential" " Generator, see https://www.pcg-random.org")) (prng::xorshift64 . ,(string-append "Classic non-scrambled 64-bit Xorshift generator, as developed" " by George Marsaglia. See" " https://en.wikipedia.org/wiki/Xorshift")) (prng::randu . ,(string-append "A notoriously flawed LCG-type PRNG developed by" " IBM in the 1960s.")) (prng::el-cheapo-zx . ,(string-append "Very fast but extremely poor 8-bit PRNG used to generate noise" " in various ZX Spectrum beeper engines.")) (prng::dmg-noise . ,(string-append "A PRNG based on the noise waveform generator of the Gameboy" " APU, which is a 15-bit LFSR with a tap at bit 1.")) (prng::sid-noise . ,(string-append "A PRNG based on the noise waveform on the MOS" " 6581/8580 Sound Interface Device, which is a Fibonacci LFSR" " using the feedback polynomial x^22 + x^17 + 1. See" " http://www.sidmusic.org/sid/sidtech5.html. For added" " authenticity, initialize SEED to #x7ffff8.")) (prng::tia-noise . ,(string-append "A PRNG based on the noise waveform (AUDCx = 8) on" " the Atari VCS/2600, which is a 9-bit LFSR with a tap at bit" " 4, resulting in a period of 511. For added authenticity," " initialize SEED to #x1ff.")) (prng::pi-digits . ,(string-append "Not an actual PRNG. Creates random-looking integer sequences" " from pi. Uses the Baileyโ€“Borweinโ€“Plouffe formula to calculate" " hexadecimal digits of pi. SEED is the initial fractional" " digit index, ie. SEED = 0 starts extracting digits from the" " first fractional digit."))))) (if (null? args) prngs (alist-ref (car args) prngs)))) ) ;; end module prng
false
d078e5a781dc0603bfc1c8f020a9197b4f73a6bf
0a345b89eae9a12e18e8d30f24d592a724284a59
/libmdal/mdal-targets/m6502.scm
9bf03024c9341d8c0d8fc526f5d31f5065c5da81
[ "MIT" ]
permissive
DeMOSic/bintracker
7b26ecb3b8ad315727bb65f1051206b2dcac7123
bed6356b7d177d969ea3873527a1698a00305acf
refs/heads/master
2023-03-26T19:11:49.396339
2021-03-29T08:51:12
2021-03-29T08:51:12
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
13,239
scm
m6502.scm
(asm-target endian: little registers: ((x 4) (y 0) (a 0)) register-sets: ((ptr (x y)) (accu (a)) (regx (x)) (regy (y))) addressing-modes: ((imm (preceded-by* numeric (is #\#))) (zp (any-of (bind a-number (lambda (r) (if (and (>= r -128) (<= r 255)) (result r) fail))) (preceded-by* numeric (is #\<)))) (ind (in-parens numeric)) (izx-part1 (preceded-by* numeric (is #\())) (izx-part2 (char-seq "x)"))) instructions: ((adc (1 (((address 'imm) (#x69 (lsb %op1))) ((address 'zp) (#x65 (lsb %op1))) ;; absolute (numeric (#x6d (lsb %op1) (msb %op1))))) (2 (;; zeropage,x ((address 'zp) (((register 'regx) (#x75 (lsb %op1))))) ;; indirect,x ((address 'izx-part1) (((address 'izx-part2) (#x61 (lsb %op1))))) ;; indirect,y ((address 'ind) (((register 'regy) (#x71 (lsb %op1))))) ;; absolute,x/y (numeric (((register 'ptr) ((+ #x79 (register-value %op2)) (lsb %op1) (msb %op1)))))))) (ahx (2 (((address 'ind) (((register 'regy) (#x93 (lsb %op1))))) (numeric (((register 'regy) (#x9f (lsb %op1) (msb %op1)))))))) (and (1 (((address 'imm) (#x29 (lsb %op1))) ((address 'zp) (#x25 (lsb %op1))) (numeric (#x2d (lsb %op1) (msb %op1))))) (2 (((address 'zp) (((register 'regx) (#x35 (lsb %op1))))) ((address 'izx-part1) (((address 'izx-part2) (#x21 (lsb %op1))))) ((address 'ind) (((register 'regy) (#x31 (lsb %op1))))) (numeric (((register 'ptr) ((+ #x39 (register-value %op2)) (lsb %op1) (msb %op1)))))))) (anc (1 (((address 'imm) (#x0b (lsb %op1)))))) (alr (1 (((address 'imm) (#x4b (lsb %op1)))))) (arr (1 (((address 'imm) (#x6b (lsb %op1)))))) (asl (0 (#x0a)) (1 (((register 'accu) (#x0a)) ((address 'zp) (#x06 (lsb %op1))) (numeric (#x0e (lsb %op1) (msb %op1))))) (2 (((address 'izx-part1) (((address 'izx-part2) (#x16 (lsb %op1))))) (numeric (((register 'regx) (#x1e (lsb %op1) (msb %op1)))))))) (aso (1 (((address 'zp) (#x07 (lsb %op1))) (numeric (#x0f (lsb %op1) (msb %op1))))) (2 (((address 'zp) (((register 'regx) (#x17 (lsb %op1))))) ((address 'izx-part1) (((address 'izx-part2) (#x03 (lsb %op1))))) ((address 'ind) (((register 'regy) (#x13 (lsb %op1))))) (numeric (((register 'ptr) ((+ #x1b (register-value %op2)) (lsb %op1) (msb %op1)))))))) (axs (1 (((address 'imm) (#xcb (lsb %op1)))))) (bit (1 (((address 'zp) (#x24 (lsb %op1))) (numeric (#x2c (lsb %op1) (msb %op1)))))) (bcc (1 (((signed-number-range 8) (#x90 (lsb %op1))) (numeric (#x90 (lsb (- %op1 (+ 2 current-origin)))))))) (bcs (1 (((signed-number-range 8) (#xb0 (lsb %op1))) (numeric (#xb0 (lsb (- %op1 (+ 2 current-origin)))))))) (beq (1 (((signed-number-range 8) (#xf0 (lsb %op1))) (numeric (#xf0 (lsb (- %op1 (+ 2 current-origin)))))))) (bmi (1 (((signed-number-range 8) (#x30 (lsb %op1))) (numeric (#x30 (lsb (- %op1 (+ 2 current-origin)))))))) (bne (1 (((signed-number-range 8) (#xd0 (lsb %op1))) (numeric (#xd0 (lsb (- %op1 (+ 2 current-origin)))))))) (bpl (1 (((signed-number-range 8) (#x10 (lsb %op1))) (numeric (#x10 (lsb (- %op1 (+ 2 current-origin)))))))) (bvc (1 (((signed-number-range 8) (#x50 (lsb %op1))) (numeric (#x50 (lsb (- %op1 (+ 2 current-origin)))))))) (bvs (1 (((signed-number-range 8) (#x70 (lsb %op1))) (numeric (#x70 (lsb (- %op1 (+ 2 current-origin)))))))) (brk (0 (#x00))) (clc (0 (#x18))) (cld (0 (#xd8))) (cli (0 (#x58))) (clv (0 (#xb8))) (cmp (1 (((address 'imm) (#xc9 (lsb %op1))) ((address 'zp) (#xc5 (lsb %op1))) (numeric (#xcd (lsb %op1) (msb %op1))))) (2 (((address 'zp) (((register 'regx) (#xd5 (lsb %op1))))) ((address 'izx-part1) (((address 'izx-part2) (#xc1 (lsb %op1))))) ((address 'ind) (((register 'regy) (#xd1 (lsb %op1))))) (numeric (((register 'ptr) ((+ #xd9 (register-value %op2)) (lsb %op1) (msb %op1)))))))) (cpx (1 (((address 'imm) (#xe0 (lsb %op1))) ((address 'zp) (#xe4 (lsb %op1))) (numeric (#xec (lsb %op1) (msb %op1)))))) (cpy (1 (((address 'imm) (#xc0 (lsb %op1))) ((address 'zp) (#xc4 (lsb %op1))) (numeric (#xcc (lsb %op1) (msb %op1)))))) (dcp (1 (((address 'zp) (#xc7 (lsb %op1))) (numeric (#xcf (lsb %op1) (msb %op1))))) (2 (((address 'zp) (((register 'regx) (#xd7 (lsb %op1))))) ((address 'izx-part1) (((address 'izx-part2) (#xc3 (lsb %op1))))) ((address 'ind) (((register 'regy) (#xd3 (lsb %op1))))) (numeric (((register 'ptr) ((+ #xdb (register-value %op2)) (lsb %op1) (msb %op1)))))))) (dec (1 (((address 'zp) (#xc6 (lsb %op1))) (numeric (#xce (lsb %op1) (msb %op1))))) (2 (((address 'izx-part1) (((address 'izx-part2) (#xd6 (lsb %op1))))) (numeric (((register 'regx) (#xde (lsb %op1) (msb %op1)))))))) (dex (0 (#xca))) (dey (0 (#x88))) (eor (1 (((address 'imm) (#x49 (lsb %op1))) ((address 'zp) (#x45 (lsb %op1))) (numeric (#x4d (lsb %op1) (msb %op1))))) (2 (((address 'zp) (((register 'regx) (#x55 (lsb %op1))))) ((address 'izx-part1) (((address 'izx-part2) (#x41 (lsb %op1))))) ((address 'ind) (((register 'regy) (#x51 (lsb %op1))))) (numeric (((register 'ptr) ((+ #x59 (register-value %op2)) (lsb %op1) (msb %op1)))))))) (hlt (0 (#x02))) (inc (1 (((address 'zp) (#xe6 (lsb %op1))) (numeric (#xee (lsb %op1) (msb %op1))))) (2 (((address 'izx-part1) (((address 'izx-part2) (#xf6 (lsb %op1))))) (numeric (((register 'regx) (#xfe (lsb %op1) (msb %op1)))))))) (inx (0 (#xe8))) (iny (0 (#xc8))) (isb (1 (((address 'zp) (#xe7 (lsb %op1))) (numeric (#xef (lsb %op1) (msb %op1))))) (2 (((address 'zp) (((register 'regx) (#xf7 (lsb %op1))))) ((address 'izx-part1) (((address 'izx-part2) (#xe3 (lsb %op1))))) ((address 'ind) (((register 'regy) (#xf3 (lsb %op1))))) (numeric (((register 'ptr) ((+ #xfb (register-value %op2)) (lsb %op1) (msb %op1)))))))) (isc (1 (((address 'zp) (#xe7 (lsb %op1))) (numeric (#xef (lsb %op1) (msb %op1))))) (2 (((address 'zp) (((register 'regx) (#xf7 (lsb %op1))))) ((address 'izx-part1) (((address 'izx-part2) (#xe3 (lsb %op1))))) ((address 'ind) (((register 'regy) (#xf3 (lsb %op1))))) (numeric (((register 'ptr) ((+ #xfb (register-value %op2)) (lsb %op1) (msb %op1)))))))) (jmp (1 ((numeric (#x4c (lsb %op1) (msb %op1))) ((address 'ind) (#x6c (lsb %op1) (msb %op1)))))) (jsr (1 ((numeric (#x20 (lsb %op1) (msb %op1)))))) (kil (0 (#x02))) (lar (2 ((numeric (((register 'regy) (#xbb (lsb %op1) (msb %op1)))))))) (las (2 ((numeric (((register 'regy) (#xbb (lsb %op1) (msb %op1)))))))) (lax (1 (((address 'imm) (#xab (lsb %op1))) ((address 'zp) (#xa7 (lsb %op1))) (numeric (#xaf (lsb %op1) (msb %op1))))) (2 (((address 'zp) (((register 'regy) (#xb7 (lsb %op1))))) ((address 'izx-part1) (((address 'izx-part2) (#xa3 (lsb %op1))))) ((address 'ind) (((register 'regy) (#xb3 (lsb %op1))))) (numeric (((register 'regy) (#xbf (lsb %op1) (msb %op1)))))))) (lda (1 (((address 'imm) (#xa9 (lsb %op1))) ((address 'zp) (#xa5 (lsb %op1))) (numeric (#xad (lsb %op1) (msb %op1))))) (2 (((address 'zp) (((register 'regx) (#xb5 (lsb %op1))))) ((address 'izx-part1) (((address 'izx-part2) (#xa1 (lsb %op1))))) ((address 'ind) (((register 'regy) (#xb1 (lsb %op1))))) (numeric (((register 'ptr) ((+ #xb9 (register-value %op2)) (lsb %op1) (msb %op1)))))))) (ldx (1 (((address 'imm) (#xa2 (lsb %op1))) ((address 'zp) (#xa6 (lsb %op1))) (numeric (#xae (lsb %op1) (msb %op1))))) (2 (((address 'zp) (((register 'regy) (#xb6 (lsb %op1))))) (numeric (((register 'regy) (#xbe (lsb %op1) (msb %op1)))))))) (ldy (1 (((address 'imm) (#xa0 (lsb %op1))) ((address 'zp) (#xa4 (lsb %op1))) (numeric (#xac (lsb %op1) (msb %op1))))) (2 (((address 'zp) (((register 'regx) (#xb4 (lsb %op1))))) (numeric (((register 'regx) (#xbc (lsb %op1) (msb %op1)))))))) (lse (1 (((address 'zp) (#x47 (lsb %op1))) (numeric (#x4f (lsb %op1) (msb %op1))))) (2 (((address 'zp) (((register 'regx) (#x57 (lsb %op1))))) ((address 'izx-part1) (((address 'izx-part2) (#x43 (lsb %op1))))) ((address 'ind) (((register 'regy) (#x53 (lsb %op1))))) (numeric (((register 'ptr) ((+ #x5b (register-value %op2)) (lsb %op1) (msb %op1)))))))) (lsr (0 (#x4a)) (1 (((register 'accu) (#x4a)) ((address 'zp) (#x46 (lsb %op1))) (numeric (#x4e (lsb %op1) (msb %op1))))) (2 (((address 'izx-part1) (((address 'izx-part2) (#x56 (lsb %op1))))) (numeric (((register 'regx) (#x5e (lsb %op1) (msb %op1)))))))) (nop (0 (#xea))) (ora (1 (((address 'imm) (#x09 (lsb %op1))) ((address 'zp) (#x05 (lsb %op1))) (numeric (#x0d (lsb %op1) (msb %op1))))) (2 (((address 'zp) (((register 'regx) (#x15 (lsb %op1))))) ((address 'izx-part1) (((address 'izx-part2) (#x01 (lsb %op1))))) ((address 'ind) (((register 'regy) (#x11 (lsb %op1))))) (numeric (((register 'ptr) ((+ #x19 (register-value %op2)) (lsb %op1) (msb %op1)))))))) (rla (1 (((address 'zp) (#x27 (lsb %op1))) (numeric (#x2f (lsb %op1) (msb %op1))))) (2 (((address 'zp) (((register 'regx) (#x37 (lsb %op1))))) ((address 'izx-part1) (((address 'izx-part2) (#x23 (lsb %op1))))) ((address 'ind) (((register 'regy) (#x33 (lsb %op1))))) (numeric (((register 'ptr) ((+ #x3b (register-value %op2)) (lsb %op1) (msb %op1)))))))) (rol (0 (#x2a)) (1 (((register 'accu) (#x2a)) ((address 'zp) (#x26 (lsb %op1))) (numeric (#x2e (lsb %op1) (msb %op1))))) (2 (((address 'izx-part1) (((address 'izx-part2) (#x36 (lsb %op1))))) (numeric (((register 'regx) (#x3e (lsb %op1) (msb %op1)))))))) (ror (0 (#x6a)) (1 (((register 'accu) (#x6a)) ((address 'zp) (#x66 (lsb %op1))) (numeric (#x6e (lsb %op1) (msb %op1))))) (2 (((address 'izx-part1) (((address 'izx-part2) (#x76 (lsb %op1))))) (numeric (((register 'regx) (#x7e (lsb %op1) (msb %op1)))))))) (rra (1 (((address 'zp) (#x67 (lsb %op1))) (numeric (#x6f (lsb %op1) (msb %op1))))) (2 (((address 'zp) (((register 'regx) (#x77 (lsb %op1))))) ((address 'izx-part1) (((address 'izx-part2) (#x63 (lsb %op1))))) ((address 'ind) (((register 'regy) (#x73 (lsb %op1))))) (numeric (((register 'ptr) ((+ #x7b (register-value %op2)) (lsb %op1) (msb %op1)))))))) (rti (0 (#x40))) (rts (0 (#x60))) (pha (0 (#x48))) (php (0 (#x08))) (pla (0 (#x68))) (plp (0 (#x28))) (sax (1 (((address 'zp) (#x87 (lsb %op1))) (numeric (#x8f (lsb %op1) (msb %op1))))) (2 (((address 'zp) (((register 'regy) (#x97 (lsb %op1))))) ((address 'izx-part1) (((address 'izx-part2) (#x83 (lsb %op1)))))))) (sbc (1 (((address 'imm) (#xe9 (lsb %op1))) ((address 'zp) (#xe5 (lsb %op1))) (numeric (#xed (lsb %op1) (msb %op1))))) (2 (((address 'zp) (((register 'regx) (#xf5 (lsb %op1))))) ((address 'izx-part1) (((address 'izx-part2) (#xe1 (lsb %op1))))) ((address 'ind) (((register 'regy) (#xf1 (lsb %op1))))) (numeric (((register 'ptr) ((+ #xf9 (register-value %op2)) (lsb %op1) (msb %op1)))))))) (sec (0 (#x38))) (sed (0 (#xf8))) (sei (0 (#x78))) (shx (2 ((numeric (((register 'regy) (#x9e (lsb %op1) (msb %op1)))))))) (shy (2 ((numeric (((register 'regx) (#x9c (lsb %op1) (msb %op1)))))))) (slo (1 (((address 'zp) (#x07 (lsb %op1))) (numeric (#x0f (lsb %op1) (msb %op1))))) (2 (((address 'zp) (((register 'regx) (#x17 (lsb %op1))))) ((address 'izx-part1) (((address 'izx-part2) (#x03 (lsb %op1))))) ((address 'ind) (((register 'regy) (#x13 (lsb %op1))))) (numeric (((register 'ptr) ((+ #x1b (register-value %op2)) (lsb %op1) (msb %op1)))))))) (sre (1 (((address 'zp) (#x47 (lsb %op1))) (numeric (#x4f (lsb %op1) (msb %op1))))) (2 (((address 'zp) (((register 'regx) (#x57 (lsb %op1))))) ((address 'izx-part1) (((address 'izx-part2) (#x43 (lsb %op1))))) ((address 'ind) (((register 'regy) (#x53 (lsb %op1))))) (numeric (((register 'ptr) ((+ #x5b (register-value %op2)) (lsb %op1) (msb %op1)))))))) (sta (1 (((address 'zp) (#x85 (lsb %op1))) (numeric (#x8d (lsb %op1) (msb %op1))))) (2 (((address 'zp) (((register 'regx) (#x95 (lsb %op1))))) ((address 'izx-part1) (((address 'izx-part2) (#x81 (lsb %op1))))) ((address 'ind) (((register 'regy) (#x91 (lsb %op1))))) (numeric (((register 'ptr) ((+ #x99 (register-value %op2)) (lsb %op1) (msb %op1)))))))) (stx (1 (((address 'zp) (#x86 (lsb %op1))) (numeric (#x8e (lsb %op1) (msb %op1))))) (2 (((address 'zp) (((register 'regy) (#x96 (lsb %op1)))))))) (sty (1 (((address 'zp) (#x84 (lsb %op1))) (numeric (#x8c (lsb %op1) (msb %op1))))) (2 (((address 'zp) (((register 'regx) (#x94 (lsb %op1)))))))) (tas (2 ((numeric (((register 'regy) (#x9b (lsb %op1) (msb %op1)))))))) (tax (0 (#xaa))) (tay (0 (#xa8))) (tsx (0 (#xba))) (txa (0 (#x8a))) (txs (0 (#x9a))) (tya (0 (#x98))) (xaa (1 (((address 'imm) (#x8b (lsb %op1))))))))
false
9728a82f481705227706ab54a7610105d96e48fb
6488db22a3d849f94d56797297b2469a61ad22bf
/typed-records/typed-records.scm
d7ea47d1a5de4e08821f4a9ebc2315233605accb
[]
no_license
bazurbat/chicken-eggs
34d8707cecbbd4975a84ed9a0d7addb6e48899da
8e741148d6e0cd67a969513ce2a7fe23241df648
refs/heads/master
2020-05-18T05:06:02.090313
2015-11-18T16:07:12
2015-11-18T16:07:12
22,037,751
0
0
null
null
null
null
UTF-8
Scheme
false
false
7,781
scm
typed-records.scm
;;;; typed-records.scm (module typed-records (define-record define-record-type defstruct) (import scheme (rename chicken (define-record-type define-record-type1) (define-record define-record1)) (rename defstruct (defstruct defstruct1)) type-stubs) (import-for-syntax srfi-1 chicken) (define-syntax define-record (er-macro-transformer (lambda (x r c) (##sys#check-syntax 'define-record x '(_ symbol . #(_ 0))) (let* ((name (strip-syntax (cadr x))) (slots (cddr x)) (%define-record (r 'define-record1)) (%begin (r 'begin)) (%setter (r 'setter)) (%colon (r ':)) (slots (map (lambda (slot) (if (symbol? slot) `(,slot ,%colon *) slot)) slots)) (names/types (map (lambda (slot) (##sys#check-syntax 'define-record slot '(_ _ _)) (assert (c %colon (r (second slot))) "invalid syntax in slot specification" slot) (cond ((symbol? (car slot)) (cons (car slot) (third slot))) ((and (pair? (car slot)) (c %setter (caar slot)) (symbol? (second (car slot)))) (cons (second (car slot)) (third slot))) (else (syntax-error 'define-record "invalid syntax in slot specification" slot)))) slots))) `(,%begin (,%colon ,(r (symbol-append 'make- name)) (,@(map cdr names/types) -> (struct ,name)) (,(map cdr names/types) (##sys#make-structure ',name ,@(list-tabulate (length names/types) (lambda (i) `#(,(add1 i))))))) (,%colon ,(r (symbol-append name '?)) (* -> boolean : (struct ,name))) ,@(append-map (lambda (n/t slot i) (let ((sname (strip-syntax (car n/t))) (slot (if (symbol? slot) `(,slot ,%colon *) slot))) (cond ((symbol? (car slots)) ; explicit setter procedure? `((,%colon ,(r (symbol-append name '- sname)) ((struct ,name) -> ,(cdr n/t)) (((struct ,name)) (##sys#slot #(1) ',i))) (,%colon ,(r (symbol-append name '- sname '-set!)) ((struct ,name) ,(cdr n/t) -> undefined) (((struct ,name) *) (##sys#setslot #(1) ',i #(2)))))) (else `((,%colon ,(r (symbol-append name '- sname)) ((struct ,name) -> ,(cdr n/t)) (((struct ,name)) (##sys#slot #(1) ',i)))))))) names/types slots (iota (length names/types) 1)) (,%define-record ,name ,@(unzip1 slots))))))) (define-syntax define-record-type (er-macro-transformer (lambda (x r c) (##sys#check-syntax 'define-record-type x '(_ symbol (symbol . #(symbol 0)) symbol . #(_ 0))) (let* ((name (strip-syntax (second x))) (ctor (third x)) (pred (fourth x)) (fields (cddddr x)) (%define-record-type (r 'define-record-type1)) (%begin (r 'begin)) (%setter (r 'setter)) (%colon (r ':)) (accs/mods/types (map (lambda (field) (let* ((len (length field))) (assert (and (list? field) (>= len 2) (symbol? (first field)) (symbol? (second field)) (case len ((4) (c %colon (third field))) ((5) (and (c %colon (fourth field)) (or (symbol? (third field)) (and (pair? (third field)) (c %setter (r (car (third field)))) (symbol? (second (third field))))))) ((2) #t) ((3) (symbol? (third field))) (else #f))) "invalid syntax in field specification" field) (cons* (first field) (second field) (case len ((2) (list #f '*)) ((3) (list (third field) '*)) ((4) (list #f (fourth field))) ((5) (list (third field) (fifth field))))))) fields))) `(,%begin (,%colon ,(car ctor) (,@(map (lambda (tag) (let loop ((fields accs/mods/types)) (cond ((null? fields) (syntax-error 'define-record-type "constructor tag refers to nonexistent record field" ctor)) ((c tag (caar fields)) (fourth (car fields))) (else (loop (cdr fields)))))) (cdr ctor)) -> (struct ,name)) (,(map (lambda (fname) (cond ((assq fname accs/mods/types) => fourth) (else (error 'define-record-type "contructor tag refers to unknown field" ctor)))) (cdr ctor)) (##sys#make-structure ',name ,@(let lp [(names (map first accs/mods/types)) (l '())] (if (null? names) (begin (reverse l)) (cond ((list-index (cute eq? <> (first names)) (cdr ctor)) => (lambda (ctor-idx) (lp (cdr names) (cons (vector (add1 ctor-idx)) l)))) (else ;; XXX this indicates a problem: the initial value ;; of the slot is not necessarily of type ;; undefined - should be make this an error? (lp (cdr names) (cons '(##core#undefined) l))))))))) (,%colon ,pred (* -> boolean : (struct ,name))) ,@(append-map (lambda (a/m/t i) (let ((mod (third a/m/t))) `((,%colon ,(second a/m/t) ((struct ,name) -> ,(fourth a/m/t)) (((struct ,name)) (##sys#slot #(1) ',i))) ,@(if (symbol? mod) `((,%colon ,(third a/m/t) ((struct ,name) ,(fourth a/m/t) -> undefined) (((struct ,name) *) (##sys#setslot #(1) ',i #(2))))) '())))) accs/mods/types (iota (length accs/mods/types) 1)) (,%define-record-type ,name ,ctor ,pred ,@(map (lambda (a/m/t) (if (third a/m/t) (list (first a/m/t) (second a/m/t) (third a/m/t)) (list (first a/m/t) (second a/m/t)))) accs/mods/types))))))) (define-syntax defstruct (er-macro-transformer (lambda (x r c) (##sys#check-syntax 'defstruct x '(_ symbol . #(_ 0))) (let* ((name (strip-syntax (cadr x))) (%colon (r ':)) (slots (map (lambda (slot) (cond ((symbol? slot) `(,slot ,%colon *)) ((and (list? slot) (= 2 (length slot))) (cons slot `(,%colon *))) (else slot))) (cddr x)))) ;; we do this to ensure the same order of fields as in the ;; original "defstruct" (let-values (((init-fields no-init-fields) (partition (o pair? car) slots))) (let* ((slots (append no-init-fields init-fields)) (%defstruct (r 'defstruct1)) (%begin (r 'begin)) (names/types (map (lambda (slot) (##sys#check-syntax 'defstruct slot '(_ _ _)) (assert (c %colon (r (second slot))) "invalid syntax in slot specification" slot) (cond ((symbol? (car slot)) (cons (car slot) (third slot))) ((and (pair? (car slot)) (symbol? (caar slot))) (cons (caar slot) (third slot))) (else (syntax-error 'defstruct "invalid syntax in slot specification" slot)))) slots))) `(,%begin (,%colon ,(r (symbol-append 'make- name)) (#!rest -> (struct ,name))) (,%colon ,(r (symbol-append name '?)) (* -> boolean : (struct ,name))) (,%colon ,(r (symbol-append 'update- name)) ((struct ,name) #!rest -> (struct ,name))) (,%colon ,(r (symbol-append 'set- name '!)) ((struct ,name) #!rest -> undefined)) (,%colon ,(r (symbol-append name '->alist)) ((struct ,name) -> (list-of (pair symbol *)))) (,%colon ,(r (symbol-append 'alist-> name)) ((list-of (pair symbol *)) -> (struct ,name))) ,@(append-map (lambda (n/t slot i) (let ((sname (strip-syntax (car n/t)))) `((,%colon ,(r (symbol-append name '- sname)) ((struct ,name) -> ,(cdr n/t)) (((struct ,name)) (##sys#slot #(1) ',(add1 i)))) (,%colon ,(r (symbol-append name '- sname '-set!)) ((struct ,name) ,(cdr n/t) -> undefined) (((struct ,name) *) (##sys#setslot #(1) ',(add1 i) #(2))))))) names/types slots (iota (length slots))) (,%defstruct ,name ,@(unzip1 slots))))))))) )
true
c128df31119405a0044a6f563cdbbeaf49852a08
be06d133af3757958ac6ca43321d0327e3e3d477
/99problems/73.scm
6a817405370bdbaa203cca622216de31a161d3f9
[]
no_license
aoyama-val/scheme_practice
39ad90495c4122d27a5c67d032e4ab1501ef9c15
f133d9326699b80d56995cb4889ec2ee961ef564
refs/heads/master
2020-03-13T12:14:45.778707
2018-04-26T07:12:06
2018-04-26T07:12:06
131,115,150
0
0
null
null
null
null
UTF-8
Scheme
false
false
607
scm
73.scm
(define (prefix->infix lis) (if (pair? lis) (case (car lis) ((*) (list (prefix->infix (cadr lis)) '* (prefix->infix (caddr lis)))) ((+) (list (prefix->infix (cadr lis)) '+ (prefix->infix (caddr lis)))) ((-) (list (prefix->infix (cadr lis)) '- (prefix->infix (caddr lis)))) ((/) (list (prefix->infix (cadr lis)) '/ (prefix->infix (caddr lis)))) (else (car lis))) lis)) (print (prefix->infix 4)) (print (prefix->infix '(* 2 3))) (print (prefix->infix '(* (+ 1 2) (- 3 4)))) ; (1 2 + 3 4 - *) (print (prefix->infix '(* (+ 1 2) (- 3 (/ 4 5))))) ; (1 2 + 3 4 5 / - *)
false
60616ec66626930ed873bd625055819d197fd46d
1f48fb14898799bf9ee1118bf691586b430c5e9e
/223.scm
6fbc6b00fa825242c9264f4980ae6061f09d69ed
[]
no_license
green-93-nope/sicp
0fa79dd59414808a9cdcbfa18bd3a1c7f0b8191c
59241b6c42621c2ef967efebdd281b845f98e923
refs/heads/master
2021-01-10T10:51:22.328123
2017-05-21T08:33:25
2017-05-21T08:33:25
48,210,972
0
0
null
null
null
null
UTF-8
Scheme
false
false
357
scm
223.scm
(define (map procedure list) (if (null? list) '() (cons (procedure (car list)) (map procedure (cdr list))))) (define (for-each procedure list) (if (not (null? list)) (if (null? (cdr list)) (procedure (car list)) (begin (procedure (car list)) (for-each procedure (cdr list))))))
false
894d8613cce75344b5b9dbbe1c6a4a462662f48e
2fc7c18108fb060ad1f8d31f710bcfdd3abc27dc
/ext/sys-unix/runtime-stats.scm
cf747449aec28dfe0aa9f6b8a6884d133219ce98
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-warranty-disclaimer", "CC0-1.0" ]
permissive
bakul/s9fes
97a529363f9a1614a85937a5ef9ed6685556507d
1d258c18dedaeb06ce33be24366932143002c89f
refs/heads/master
2023-01-24T09:40:47.434051
2022-10-08T02:11:12
2022-10-08T02:11:12
154,886,651
68
10
NOASSERTION
2023-01-25T17:32:54
2018-10-26T19:49:40
Scheme
UTF-8
Scheme
false
false
7,537
scm
runtime-stats.scm
; Scheme 9 from Empty Space, Unix Function Library ; By Nils M Holm, 2010, 2012, 2018 ; In the public domain ; ; (runtime-stats procedure <option> ...) ==> list ; ; Measure the runtime of the unary PROCEDURE when applied to ; a range of values (see below). RUNTIME-STATS returns a list ; containing the data it gathered. Each entry of the list has ; the following form: ; ; (value (seconds microsecs) conses nodes vcells gcs) ; ; VALUE is the valued passed to the procedure. The sum of SECONDS ; and MICROSECS is the time the procedure took to complete. ; CONSES and NODES are the number of cons cells and the total ; amount of node storage allocated, respectively. VCELLS is the ; total number of vector cells allocated (which is used for ; strings, vectors, and symbol names).GCs is the number of ; garbage collections performed during the computation. ; ; The following options are used to pass ranges to RUNTIME-STATS: ; ; 'START: INTEGER The smallest value to be measured. ; 'END: INTEGER The largest value to be measured. ; 'STEP: INTEGER The increment between values. ; 'SET: LIST A set of values. ; ; There options are used to control the output of RUNTIME-STATS: ; ; 'PLOT: SYMBOL Instead of returning the data, plot them. ; SYMBOL is used to specify the field to plot: ; 'VALUE, 'TIME, 'CONSES, 'NODES, VCELLS, 'GC. ; 'WIDTH: INTEGER The width and height of the graph printed by ; 'HEIGHT: INTEGER the 'PLOT: option (default: h x w = 77x22 plus ; border). ; 'TABLE: #T Instead of returning the data, print a nicely ; formatted table containing the values. ; 'COMPRESS: #F By default RUNTIME-STATS will compress the curve ; so that the graph will always fill the entire ; X-range. Setting this value to #F will disable ; compression. ; ; (Example): (runtime-stats (lambda (x) (expt 2 x)) ; 'start: 1000 'end: 10000 'step: 1000) ; ==> (( 1000 (0 23755) 276 96237 97242 0) ; ( 2000 (0 86518) 297 353246 354328 3) ; ( 3000 (0 177415) 322 783333 784501 6) ; ( 4000 (0 301546) 318 1354943 1356102 11) ; ( 5000 (0 477758) 335 2140334 2141561 18) ; ( 6000 (0 681763) 343 2935950 2937195 25) ; ( 7000 (0 923639) 343 4145271 4146516 36) ; ( 8000 (1 180418) 339 5293779 5295015 46) ; ( 9000 (1 519193) 356 6806279 6807583 60) ; (10000 (1 855957) 356 8327850 8329154 73)) (require-extension sys-unix) (load-from-library "package.scm") (load-from-library "keyword-value.scm") (load-from-library "char-plot.scm") (load-from-library "position.scm") (load-from-library "count.scm") (load-from-library "format.scm") (package *runtime-stats* (:import keyword-value accept-keywords char-plot posq count format) (:export runtime-stats) (:make-aliases) (define data-names '(value time nodes conses vcells gcs)) (define (map-data-ref data what) (let* ((pos (posq what data-names)) (data (map (lambda (x) (list-ref x pos)) data))) (if (eq? 'time what) (map (lambda (time) (+ (cadr time) (* 1000000 (car time)))) data) data))) (define (print-stats data) (letrec ((digits (lambda (x) (let loop ((i 1) (v 9)) (if (< v x) (loop (+ 1 i) (+ 9 (* 10 v))) (+ i (quotient i 3))))))) (let* ((size #f) (data* (map (lambda (name) (map-data-ref data name)) data-names)) (data* (map (lambda (rec) (map (lambda (x) (if (pair? x) (begin (set! size #t) (count x)) x)) rec)) data*)) (width* (map (lambda (x) (max 4 (digits (apply max x)))) data*))) (for-each (lambda (v w) (format #t "~V@A" (+ 2 w) v)) (list (if size "SIZE" "VAL") "USEC" "REDN" "CONS" "STOR" "GCS") width*) (newline) (for-each (lambda (v*) (for-each (lambda (v w) (format #t "~V:D" (+ 2 w) v)) v* width*) (newline)) (transpose data*))))) (define (run-stats proc val) (letrec ((sval->integer (lambda (sval) (let loop ((sval sval) (int 0)) (if (null? sval) int (loop (cdr sval) (+ (* 1000 int) (car sval))))))) (seconds (lambda (t0 tn) (let ((d (- (car tn) (car t0)))) (if (< (cadr tn) (cadr t0)) (- d 1) d)))) (useconds (lambda (t0 tn) (if (< (cadr tn) (cadr t0)) (- 1000000 (- (cadr t0) (cadr tn))) (- (cadr tn) (cadr t0)))))) (let* ((t0 (sys:gettimeofday)) (sval* (cdr (stats `(,proc ',val)))) (tn (sys:gettimeofday)) (time (list (seconds t0 tn) (useconds t0 tn)))) `(,val ,time ,@(map sval->integer sval*))))) (define (runtime-stats proc . opts) (accept-keywords "runtime-stats" opts '(start: end: step: set: plot: table: height: width: compress:)) (let* ((start (keyword-value opts 'start: 1)) (end (keyword-value opts 'end: 10)) (step (keyword-value opts 'step: 1)) (set (keyword-value opts 'set: #f)) (plot (keyword-value opts 'plot: #f)) (height (keyword-value opts 'height: 22)) (width (keyword-value opts 'width: 77)) (table (keyword-value opts 'table: #f)) (compr (keyword-value opts 'compress: #t)) (data (if set (let loop ((set set) (res '())) (if (null? set) (reverse! res) (loop (cdr set) (cons (run-stats proc (car set)) res)))) (let loop ((i start) (res '())) (if (> i end) (reverse! res) (loop (+ i step) (cons (run-stats proc i) res))))))) (cond (plot (char-plot (map-data-ref data plot) plot height width compr)) (table (print-stats data)) (else data)))))
false
91bafaf1dc575de6cd8fcf44dfd13a6589e5d424
5e8aea0ba10b9689ad580a8a61c31a83299ba6d5
/10.scm
0312ed62e1f36066e8b3658743df223830ec672b
[]
no_license
hanachin/TheLittleSchemer
3479751fd9278a0d740ec53438321bd064c35367
3fba462d310d7c4d18e60343aa22d3c1c96feae0
refs/heads/master
2021-01-19T19:39:52.390489
2011-08-09T18:46:56
2011-08-09T18:46:56
1,525,986
1
0
null
null
null
null
UTF-8
Scheme
false
false
2,013
scm
10.scm
(use gauche.test) (add-load-path ".") (load "func") (load "test-util") (test-start "chapter 10") (test-section "new-entry") (test* "(equal? '((appetizer entree beverage) (patee boeuf vin)) (new-entry '(appetizer entree beverage) '(patee boeuf vin)))" #t (equal? '((appetizer entree beverage) (patee boeuf vin)) (new-entry '(appetizer entree beverage) '(patee boeuf vin)))) (test* "(equal? '((appetizer entree beverage) (beer beer beer)) (new-entry '(appetizer entree beverage) '(beer beer beer)))" #t (equal? '((appetizer entree beverage) (beer beer beer)) (new-entry '(appetizer entree beverage) '(beer beer beer)))) (test* "(equal? '((beverage dessert) ((food is) (number one with us))) (new-entry '(beverage dessert) '((food is) (number one with us))))" #t (equal? '((beverage dessert) ((food is) (number one with us))) (new-entry '(beverage dessert) '((food is) (number one with us))))) (f-test (lookup-in-entry ['entree '((appetizer entree beverage) (food tastes good)) (lambda (name) name) => 'tastes]) (lookup-in-table ['entree '(((entree dessert) (spaghetti spumoni)) ((appetizer entree beverage) (food tastes good))) (lambda (name) name) => 'spaghetti]) (apply-closure ['((((u v w) (1 2 3)) ((x y z) (4 5 6))) (x y) (cons z x)) '((a b c) (d e f)) => '(6 a b c)])) (test-end)
false
f28d4122332102bcff11c65f47ca04ccb89b7b7d
de82217869618b0a975e86918184ecfddf701172
/reference/exceptions/condition.scm
6b4593433ac109af7db0a1a40f0b8c304bed90c7
[]
no_license
schemedoc/r6rs
6b4ef7fd87d8883d6c4bcc422b38b37f588e20f7
0009085469e47df44068873f834a0d0282648750
refs/heads/master
2021-06-18T17:44:50.149253
2020-01-04T10:50:50
2020-01-04T10:50:50
178,081,881
5
0
null
null
null
null
UTF-8
Scheme
false
false
8,505
scm
condition.scm
; Reference implementation for conditions library ; Copyright (C) Michael Sperber (2007). All Rights Reserved. ; 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 (r6rs conditions) (export condition condition? simple-conditions condition-predicate condition-accessor define-condition-type &condition &message make-message-condition message-condition? condition-message &warning make-warning warning? &serious make-serious-condition serious-condition? &error make-error error? &violation make-violation violation? &non-continuable make-noncontinuable-violation non-continuable-violation? &implementation-restriction make-implementation-restriction-violation implementation-restriction-violation? &lexical make-lexical-violation lexical-violation? &syntax make-syntax-violation syntax-violation? &undefined make-undefined-violation undefined-violation? &assertion make-assertion-violation assertion-violation? &irritants make-irritants-condition irritants-condition? condition-irritants &who make-who-condition who-condition? condition-who assertion-violation) (import (r6rs base) (r6rs records explicit) (r6rs i/o ports) (r6rs conditions internal)) (define-record-type (&condition make-simple-condition simple-condition?)) (define-record-type (:compound-condition make-compound-condition compound-condition?) (fields (immutable components explode-condition))) (define (simple-conditions con) (cond ((simple-condition? con) (list con)) ((compound-condition? con) (map list (explode-condition con))) (else (assertion-violation 'simple-conditions "not a condition" con)))) (define (condition? thing) (or (simple-condition? thing) (compound-condition? thing))) (define (condition . components) (make-compound-condition (apply append (map (lambda (component) (cond ((simple-condition? component) (list component)) ((compound-condition? component) (explode-condition component)) (else (assertion-violation 'condition "component wasn't a condition" component)))) components)))) ;; does RTD-1 represent an ancestor of RTD-2? (define (rtd-ancestor? rtd-1 rtd-2) (let loop ((rtd-2 rtd-2)) (or (eq? rtd-1 rtd-2) (and rtd-2 (loop (record-type-parent rtd-2)))))) (define (condition-predicate rtd) (if (not (rtd-ancestor? (record-type-descriptor &condition) rtd)) (assertion-violation 'condition-predicate "not a subtype of &condition" rtd)) (let ((simple-pred (record-predicate rtd))) (lambda (con) (cond ((simple-condition? con) (simple-pred con)) ((compound-condition? con) (any? simple-pred (explode-condition con))) (else #f))))) (define (condition-accessor rtd simple-access) (if (not (rtd-ancestor? (record-type-descriptor &condition) rtd)) (assertion-violation 'condition-predicate "not a subtype of &condition" rtd)) (let ((simple-pred (record-predicate rtd))) (lambda (con) (cond ((simple-condition? con) (simple-access con)) ((compound-condition? con) (cond ((first simple-pred (explode-condition con)) => simple-access) (else (assertion-violation '<condition-accessor> "condition isn't of type" con rtd)))) (else (assertion-violation '<condition-accessor> "condition isn't of type" con rtd)))))) (define-syntax define-condition-type (syntax-rules () ((define-condition-type ?name ?supertype ?constructor ?predicate (?field1 ?accessor1) ...) (define-condition-type-helper ?name ?supertype ?constructor ?predicate ((?field1 ?accessor1) ...) ())))) (define-syntax define-condition-type-helper (syntax-rules () ((define-condition-type-helper ?name ?supertype ?constructor ?predicate ((?field1 ?accessor1) ?rest ...) (?spec1 ...)) (define-condition-type-helper ?name ?supertype ?constructor ?predicate (?rest ...) (?spec1 ... (?field1 ?accessor1 temp-condition-accessor)))) ((define-condition-type-helper ?name ?supertype ?constructor ?predicate () ((?field1 ?accessor1 ?condition-accessor1) ...)) (begin (define-record-type (?name ?constructor record-predicate) (parent ?supertype) (fields (immutable ?field1 ?accessor1) ...)) (define ?predicate (condition-predicate (record-type-descriptor ?name))) (define ?condition-accessor1 (condition-accessor (record-type-descriptor ?name) ?accessor1)) ...)))) ;; Utilities, defined locally to avoid having to load SRFI 1 ;; (These need to come before the standard condition types below.) (define (first pred list) (let loop ((list list)) (cond ((null? list) #f) ((pred (car list)) (car list)) (else (loop (cdr list)))))) (define (any? proc list) (let loop ((list list)) (cond ((null? list) #f) ((proc (car list)) #t) (else (loop (cdr list)))))) ;; Standard condition types (define-condition-type &message &condition make-message-condition message-condition? (message condition-message)) (define-condition-type &warning &condition make-warning warning?) (define-condition-type &serious &condition make-serious-condition serious-condition?) (define-condition-type &error &serious make-error error?) (define-condition-type &violation &serious make-violation violation?) (define-condition-type &non-continuable &violation make-noncontinuable-violation non-continuable-violation?) (define-condition-type &implementation-restriction &violation make-implementation-restriction-violation implementation-restriction-violation?) (define-condition-type &lexical &violation make-lexical-violation lexical-violation?) (define-condition-type &syntax &violation make-syntax-violation syntax-violation? (form syntax-violation-form) (subform syntax-violation-subform)) (define-condition-type &undefined &violation make-undefined-violation undefined-violation?) (define-condition-type &assertion &violation make-assertion-violation assertion-violation?) (define-condition-type &irritants &condition make-irritants-condition irritants-condition? (irritants condition-irritants)) (define-condition-type &who &condition make-who-condition who-condition? (who condition-who)) (define (assertion-violation who message . irritants) (raise (condition (make-assertion-violation) (make-who-condition who) (make-message-condition message) (make-irritants-condition irritants)))) ; Completing exceptions library (set-operate-non-continuable! (lambda (raise who . irritants) (raise (condition (make-noncontinuable-violation) (make-who-condition who) (make-message-condition "returned from non-continuable exception") (make-irritants-condition irritants))))) (set-operate-unhandled! (lambda (abort cond) (if (serious-condition? cond) (abort "unhandled serious exception") (begin (put-string (standard-error-port) "unhandled non-serious exception") (if (message-condition? cond) (begin (put-string (standard-error-port) ": ") (put-string (standard-error-port) (condition-message cond)))))))) ) ; end of library form
true
b030ee4e6253dd66f11016f5dc4aaa903fbea9ed
defeada37d39bca09ef76f66f38683754c0a6aa0
/System/system/code-dom/code-type-declaration.sls
4d3408fff8c5071cc823c7f742670233ef3e0802
[]
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
2,579
sls
code-type-declaration.sls
(library (system code-dom code-type-declaration) (export new is? code-type-declaration? base-types is-class?-get is-class?-set! is-class?-update! is-enum?-get is-enum?-set! is-enum?-update! is-interface?-get is-interface?-set! is-interface?-update! is-struct?-get is-struct?-set! is-struct?-update! members type-attributes-get type-attributes-set! type-attributes-update! is-partial?-get is-partial?-set! is-partial?-update! type-parameters) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.CodeDom.CodeTypeDeclaration a ...))))) (define (is? a) (clr-is System.CodeDom.CodeTypeDeclaration a)) (define (code-type-declaration? a) (clr-is System.CodeDom.CodeTypeDeclaration a)) (define-field-port base-types #f #f (property:) System.CodeDom.CodeTypeDeclaration BaseTypes System.CodeDom.CodeTypeReferenceCollection) (define-field-port is-class?-get is-class?-set! is-class?-update! (property:) System.CodeDom.CodeTypeDeclaration IsClass System.Boolean) (define-field-port is-enum?-get is-enum?-set! is-enum?-update! (property:) System.CodeDom.CodeTypeDeclaration IsEnum System.Boolean) (define-field-port is-interface?-get is-interface?-set! is-interface?-update! (property:) System.CodeDom.CodeTypeDeclaration IsInterface System.Boolean) (define-field-port is-struct?-get is-struct?-set! is-struct?-update! (property:) System.CodeDom.CodeTypeDeclaration IsStruct System.Boolean) (define-field-port members #f #f (property:) System.CodeDom.CodeTypeDeclaration Members System.CodeDom.CodeTypeMemberCollection) (define-field-port type-attributes-get type-attributes-set! type-attributes-update! (property:) System.CodeDom.CodeTypeDeclaration TypeAttributes System.Reflection.TypeAttributes) (define-field-port is-partial?-get is-partial?-set! is-partial?-update! (property:) System.CodeDom.CodeTypeDeclaration IsPartial System.Boolean) (define-field-port type-parameters #f #f (property:) System.CodeDom.CodeTypeDeclaration TypeParameters System.CodeDom.CodeTypeParameterCollection))
true
21417f6bc509b116618d483bb961ef4c4929d1c0
b9eb119317d72a6742dce6db5be8c1f78c7275ad
/random-scheme-stuff/coroutines.scm
8a2fe99580c32922ac48d23340fbf193d946ea14
[]
no_license
offby1/doodles
be811b1004b262f69365d645a9ae837d87d7f707
316c4a0dedb8e4fde2da351a8de98a5725367901
refs/heads/master
2023-02-21T05:07:52.295903
2022-05-15T18:08:58
2022-05-15T18:08:58
512,608
2
1
null
2023-02-14T22:19:40
2010-02-11T04:24:52
Scheme
UTF-8
Scheme
false
false
2,019
scm
coroutines.scm
;; from http://www.cs.smsu.edu/~pete/csc326/Chap12f.html (define call/cc call-with-current-continuation) ; demo of Scheme coroutines implemented using continuations. ; ; source: Scheme and the Art of Programming, ; George Springer and Daniel Friedman ; McGraw-Hill ; 1992 ; ISBN 0-07-060522-X ; see pages 567-571. (define coroutine-maker (lambda (proc) (let ((saved-continuation "any continuation")) (let ((update-continuation! (lambda (v) (set! saved-continuation v)))) (let ((resumer (resume-maker update-continuation!)) (first-time #t)) (lambda (value) (if first-time (begin (set! first-time #f) (proc resumer value)) (saved-continuation value)))))))) (define resume-maker (lambda (update-proc!) (lambda (next-coroutine value) (let ((receiver (lambda (continuation) (update-proc! continuation) (next-coroutine value)))) (call/cc receiver))))) ; helpful procedure to display any number of args on stdout (define writeln (lambda args (for-each display args) (newline))) ; Three coroutines are defined: A, B, and C. ; Their interactions demonstrate non-hierarchical flow (define A (let ((A-proc (lambda (resume v) (writeln "This is A") (writeln "Came from " (resume B "A")) (writeln "Back in A") (writeln "Came from " (resume C "A"))))) (coroutine-maker A-proc))) (define B (let ((B-proc (lambda (resume v) (writeln " This is B") (writeln " Came from " (resume C "B")) (writeln " Back in B") (writeln " Came from " (resume A "B"))))) (coroutine-maker B-proc))) (define C (let ((C-proc (lambda (resume v) (writeln " This is C") (writeln " Came from " (resume A "C")) (writeln " Back in C") (writeln " Came from " (resume B "C"))))) (coroutine-maker C-proc)))
false
0a7c5d101f2b60ad17c06a0d354653de803d9028
d074b9a2169d667227f0642c76d332c6d517f1ba
/sicp/ch_2/exercise.2.76.scm
5df526b6c5ee4bec950a3c6ff7f672e8a4c73c0f
[]
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
592
scm
exercise.2.76.scm
#lang racket/base ;;; Exercise 2.76 ;; As a large system with generic operations ;; evolves, new types of data objects or new operations may be needed. ;; For each of the three strategies--generic operations with explicit ;; dispatch, data-directed style, and message-passing-style--describe ;; the changes that must be made to a system in order to add new ;; types or new operations. Which organization would be most ;; appropriate for a system in which new types must often be added? ;; Which would be most appropriate for a system in which new ;; operations must often be added? ;; no
false
1339cd2802508b5e7e202ec84fb64c0a9060ec5a
a2d8b4843847507b02085bb8adabd818f57dd09f
/scheme/sicp/ch_3/sample-sim.scm
9e370acb3fe4c5ea80e210129c95b11bad448647
[]
no_license
tcharding/self_learning
df911b018fc86bd5f918394b79d2456bf51f35a8
f6bb5c6f74092177aa1b71da2ce87ca1bfc5ef3c
refs/heads/master
2022-05-13T05:09:32.284093
2022-05-02T08:25:18
2022-05-02T08:25:18
41,029,057
13
2
null
null
null
null
UTF-8
Scheme
false
false
1,243
scm
sample-sim.scm
;;;; Circuits Sample simulation (load-from-path "circuits.scm") (load-from-path "agenda.scm") ;;; Initialize and configure simulation (define the-agenda (make-agenda)) (define inverter-delay 2) (define and-gate-delay 3) (define or-gate-delay 5) ;;; Simulation specific procedures (define (probe name wire) (add-action! wire (lambda () (newline) (display name) (display " ") (display (current-time the-agenda)) (display " New-value = ") (display (get-signal wire))))) (define (after-delay delay action) (add-to-agenda! (+ delay (current-time the-agenda) action the-agenda))) (define (propogate) (if (empty-agenda? the-agenda) 'done (let ((first-item (first-agend-item the-agenda))) (first-item) (remove-first-agenda-item! the-agenda) (propogate)))) ;;; Setup Simulation (define input-1 (make-wire)) (define input-2 (make-wire)) (define sum (make-wire)) (define carry (make-wire)) (probe 'sum sum) (probe 'carry carry) (hald-adder input-1 input-2 sum carry) (set-signal! input-1 1) (propogate) (set-signal! input-2 1) (propogate)
false
c97c55a46498fae75b6a620bd8e0d30f808e357e
f6ebd0a442b29e3d8d57f0c0935fd3e104d4e867
/ch02/2.2/ex-2-2-likerivers12.scm
5f1c4d0ec3b900f8e354a2a413d4f9704a087af8
[]
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
54,649
scm
ex-2-2-likerivers12.scm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Ch 2 ๋ฐ์ดํ„ฐ๋ฅผ ์š”์•ฝํ•ด์„œ ํ‘œํ˜„๋ ฅ์„ ๋Œ์–ด์˜ฌ๋ฆฌ๋Š” ๋ฐฉ๋ฒ• ;;; Ch 2.2 ๊ณ„์ธต ๊ตฌ์กฐ ๋ฐ์ดํ„ฐ์™€ ๋‹ซํž˜ ์„ฑ์งˆ ;;; p126 ;;;----------- ;;; ์Œ ๋งŒ๋“ค๊ธฐ ;;; 1๊ณผ 2์˜ ์Œ (cons 1 2) ;; (1 . 2) ;;; ์ƒ์ž์™€ ํ™”์‚ดํ‘œ๋กœ ๋‚˜ํƒ€๋‚ด๋ฉด. ;;; [ + | + ] ;;; | | ;;; 1 2 ;;; ์Œ์€ ๋ชจ๋“  ์ข…๋ฅ˜์˜ ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ๋ฅผ ์งœ๋งž์ถ”๋Š”๋ฐ ๋‘๋ฃจ ์“ธ ์ˆ˜ ์žˆ๋‹ค. ;;;----------- ;;; * ๋‹ซํž˜ ์„ฑ์งˆ ;;; - ์–ด๋–ค ์—ฐ์‚ฐ์ด ๋‹ซํž˜ ์„ฑ์งˆ์„ ๊ฐ€์ง„๋‹ค. ;;; -> ์—ฐ์‚ฐ์œผ๋กœ ๋งŒ๋“  ๋ฌผ์ฒด๊ฐ€ ๋‹ค์‹œ ๊ทธ ์—ฐ์‚ฐ์˜ ๋Œ€์ƒ์ด ๋  ์ˆ˜ ์žˆ์Œ. ;;; ๋‹ซํž˜ ์„ฑ์งˆ์„ ์ด์šฉํ•œ ์ž์—ฐ์ˆ˜์˜ ์ •์˜ ;;; N -> 1 ;;; N -> N V (N + 1) ;;; - ๋‹ซํž˜ ์„ฑ์งˆ์€ ๊ณ„์ธต ๊ตฌ์กฐ๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋„๋ก ํ•ด์ฃผ๊ธฐ ๋•Œ๋ฌธ์— ;;; ๋ฐ์ดํ„ฐ๋ฅผ ํ•ฉ์น˜๋Š” ๋ชจ๋“  ํ‘œํ˜„ ์ˆ˜๋‹จ์—์„œ ํ‘œํ˜„๋ ฅ์„ ๋Œ์–ด์˜ฌ๋ฆฌ๋Š” ์—ด์‡ ๊ฐ€ ๋œ๋‹ค. ;;;;=================<ch 2.2.1 ์ฐจ๋ก€์—ด์˜ ํ‘œํ˜„ ๋ฐฉ๋ฒ•>===================== ;;; p129 ;;; ๋ฆฌ์ŠคํŠธ : cons๋ฅผ ๊ฒน์ณ ๋งŒ๋“  ์Œ์˜ ์ฐจ๋ก€์—ด. (cons 1 (cons 2 (cons 3 (cons 4 '())))) ;; (1 2 3 4) ;;; ๋ฆฌ์ŠคํŠธ์—์„œ car, cdr, cons ;;; car : ๋ฆฌ์ŠคํŠธ์˜ ์ฒซ๋ฒˆ์งธ ์›์†Œ๋ฅผ ๊ณจ๋ผ๋‚ด๋Š” ์—ฐ์‚ฐ ;;; cdr : ๋ฆฌ์ŠคํŠธ์˜ ์ฒซ๋ฒˆ์งธ ์›์†Œ๋ฅผ ๋บ€ ๋‚˜๋จธ์ง€ ๋ฆฌ์ŠคํŠธ๋ฅผ ๊ณจ๋ผ๋‚ด๋Š” ์—ฐ์‚ฐ ;;; cons : ์›๋ž˜ ๋ฆฌ์ŠคํŠธ์˜ ๋งจ ์•ž์— ์ƒˆ ์›์†Œ๋ฅผ ๋ณดํƒœ์–ด ๋ฆฌ์ŠคํŠธ๋กœ ๋งŒ๋“ค์–ด ๋‚ด๋Š” ์—ฐ์‚ฐ ;;; nil - '() : ์›์†Œ๋ฅผ ๊ฐ€์ง€์ง€ ์•Š์€ ์ฐจ๋ก€์—ด(๋นˆ ๋ฆฌ์ŠคํŠธ) (define one-through-four (list 1 2 3 4)) ;;; p130 (car one-through-four) ;; 1 (cdr one-through-four) ;; (2 3 4) (car (cdr one-through-four)) ;; 2 (cons 10 one-through-four) ;; (10 1 2 3 4) (cons 5 one-through-four) ;; (5 1 2 3 4) ;;;----------------------------- ;;; ๋ฆฌ์ŠคํŠธ ์—ฐ์‚ฐ ;;; p131 ;;; ๋ฆฌ์ŠคํŠธ์˜ n๋ฒˆ์งธ ์›์†Œ๋ฅผ ๋‚ด๋†“๋Š” ํ”„๋กœ์‹œ์ € ;;; <๊ทœ์น™> ;;; - n=0 ์ด๋ฉด ๋ฆฌ์ŠคํŠธ์˜ car ;;; ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด ๋ฆฌ์ŠคํŠธ์˜ cdr์—์„œ n-1๋ฒˆ์งธ ์›์†Œ. (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) ;; 16 ;;; null? : ๋นˆ๋ฆฌ์ŠคํŠธ์ธ์ง€ ์•„๋‹Œ์ง€ ํ™•์ธํ•˜๋Š” ๊ธฐ๋ณธ ์ˆ ์–ด ํ”„๋กœ์‹œ์ € ;;; ๋ฆฌ์ŠคํŠธ์˜ ์›์†Œ๊ฐ€ ๋ช‡ ๊ฐœ์ธ์ง€ ์•Œ์•„๋ณด๋Š” ํ”„๋กœ์‹œ์ € (define (length items) (if (null? items) 0 (+ 1 (length (cdr items))))) (define odds (list 1 3 5 7)) (length odds) ;; 4 ;;; ๋ฐ˜๋ณตํ•˜๋Š” length (define (length items) (define (length-iter a count) (if (null? a) count (length-iter (cdr a) (+ 1 count)))) (length-iter items 0)) (length odds) ;; 4 (append squares odds) ;; (1 4 9 16 25 1 3 5 7) (append odds squares) ;; (1 3 5 7 1 4 9 16 25) ;;; ๋˜๋„๋Š” append ์ •์˜ (define (append list1 list2) (if (null? list1) list2 (cons (car list1) (append (cdr list1) list2)))) (append squares odds) ;; (1 4 9 16 25 1 3 5 7) (append odds squares) ;; (1 3 5 7 1 4 9 16 25) ;;;--------------------------< ex 2.17 >-------------------------- ;;; p133 (define (last-pair lst) (if (null? lst) '() (if (null? (cdr lst)) lst (last-pair (cdr lst))))) (last-pair (list 23 72 149 34)) ;; (34) (last-pair (list 1)) ;; (1) (last-pair '()) ;; () ;;;--------------------------< ex 2.18 >-------------------------- ;;; p133 (define (reverse lst) (define (reverse-iter lst2 acc) (if (null? lst2) acc (reverse-iter (cdr lst2) (cons (car lst2) acc)))) (reverse-iter lst '())) (reverse (list 1 4 9 16 25)) ;; (25 16 9 4 1) ;;;--------------------------< ex 2.19 >-------------------------- ;;; ๋™์ „ ๋ฐ”๊พธ๊ธฐ ๋‹ค์‹œ ๋ณด๊ธฐ ;;; p133,4 (define us-coins (list 50 25 10 5 1)) (define uk-coins (list 100 50 20 10 5 2 1 0.5)) (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 (first-denomination coin-values) (car coin-values)) (define (except-first-denomination coin-values) (cdr coin-values)) (define (no-more? coin-values) (null? coin-values)) (cc 100 us-coins) ;; 292 (cc 100 uk-coins) (define us-coins (reverse (list 50 25 10 5 1))) (cc 100 us-coins) ;; 292 ;; ๋ฆฌ์ŠคํŠธ ์›์†Œ์˜ ์ฐจ๋ก€๊ฐ€ cc ํ”„๋กœ์‹œ์ €์˜ ๊ฒฐ๊ณผ์— ์˜ํ–ฅ์„ ์ฃผ๋Š”๊ฐ€? ;; : ์˜ํ–ฅ์„ ์ฃผ์ง€ ์•Š๋Š”๋‹ค. ;; coin-values ์•ˆ์— ์žˆ๋Š” ๋™์ „์˜ ์ข…๋ฅ˜๋ฅผ ๋ชจ๋‘ ๊ณ ๋ คํ•˜๋Š”๋ฐ, ;; ๋ฆฌ์ŠคํŠธ ์›์†Œ์˜ ์ˆœ์„œ๊ฐ€ ๋ฐ”๋€Œ๋Š” ๊ฒƒ์€ ๋ฐฉ๋ฒ•์„ ๋”ฐ์ ธ๋ณด๋Š” ์ˆœ์„œ๊ฐ€ ๋ฐ”๋€Œ๋Š” ๊ฒƒ ๋ฟ์ด๋‹ค. ;;;--------------------------< ex 2.20 >-------------------------- ;;; p134,5,6 (define (f x y . z) (list x y z)) (f 1 2 3 4 5 6) ;; (1 2 (3 4 5 6)) (define (g . w) w) (g 1 2 3 4 5 6) ;; (1 2 3 4 5 6) (define (same-parity . lst) (define (same-parity-inner predicate lst2) (if (null? lst2) '() (let ((el (car lst2))) (if (predicate (car lst2)) (cons el (same-parity-inner predicate (cdr lst2))) (same-parity-inner predicate (cdr lst2)))))) (if (null? lst) '() (if (even? (car lst)) (same-parity-inner even? lst) (same-parity-inner odd? lst)))) (same-parity 1 2 3 4 5 6 7) ;; (1 3 5 7) (same-parity 2 3 4 5 6 7) ;; (2 4 6) (same-parity ) ;; () (same-parity 1 2 4 6) ;; (1) ;;;----------------------------- ;;; ๋ฆฌ์ŠคํŠธ ๋งคํ•‘(mapping) ;;; p136 (define (scale-list items factor) (if (null? items) '() ;nil (cons (* (car items) factor) (scale-list (cdr items) factor)))) (scale-list (list 1 2 3 4 5) 10) ;; (10 20 30 40 50) ;;; p137 (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)) ;; (10 2.5 11.6 17) (map (lambda (x) (* x x)) (list 1 2 3 4)) ;; (1 4 9 16) (define (scale-list items factor) (map (lambda (x) (* x factor)) items)) (scale-list (list 1 2 3 4 5) 10) ;; (10 20 30 40 50) ;;;--------------------------< ex 2.21 >-------------------------- ;;; p138 (define (square-list items) (if (null? items) '() (cons (square (car items)) (square-list (cdr items))))) ;;;--- (define (square x) (* x x)) ;;;--- (square-list (list 1 2 3 4)) ;; (1 4 9 16) (define (square-list items) (map (lambda (x) (square x)) items)) (square-list (list 1 2 3 4)) ;; (1 4 9 16) ;;;--------------------------< ex 2.22 >-------------------------- ;;; p138 ;;; ๋ฐ˜๋ณตํ•˜๋Š” square-list (define (square-list items) (define (iter things answer) (if (null? things) answer (iter (cdr things) (cons (square (car things)) answer)))) (iter items '())) ;;nil)) (square-list (list 1 2 3 4)) ;; (16 9 4 1) (cons (square 2) (cons (square 1) '())) ; ... ;; items์—์„œ ๋’ค์ชฝ์— ์žˆ๋Š” ์›์†Œ๊ฐ€ answer์˜ ์•ž์ชฝ์— cons๋œ๋‹ค. ;; [ + | + ] <- 2) ;; | | ;; 2 | ;; [ + | + ] <- 1) ;; | | ;; 1 nil (define (square-list items) (define (iter things answer) (if (null? things) answer (iter (cdr things) (cons answer (square (car things)))))) (iter items '())) (square-list (list 1 2 3 4)) ;; '((((() . 1) . 4) . 9) . 16) ;;; 1. (cons answer (...)) ์—์„œ answer ๊ฐ€ atom์ด ์•„๋‹ˆ๋ผ cons cell ์ด๋‹ค. ;;; 2. (cons answer (...)) ์—์„œ (...)๊ฐ€ cons cell ์ด ์•„๋‹ˆ๋ผ atom ์ด๋‹ค. (cons '(1) 2) ;; ((1) . 2) ;;;; ์ˆ˜ํ–‰ ๋‹จ๊ณ„ ๋ถ„์„ ;; 1) (cons '() 1) ;; [ + | + ] <- new cons cell ;; | | ;; nil 1 ;; ;;-> (() . 1) ;; 2) (define ans '(() . 1)) (cons ans 4) ;; [ + | + ] <- new cons cell ;; | | ;; ans 4 ;; ;; => [ + | + ] ;; | | ;; | 4 ;; | ;; [ + | + ] <- ans ;; | | ;; nil 1 ;; ;;-> '((() . 1) . 4) ;; 3) (define ans '((() . 1) . 4)) (cons ans 9) ;; '(((() . 1) . 4) . 9) ;;; ์›ํ•˜๋Š”๋Œ€๋กœ ๋‹ต์ด ๋‚˜์˜ค๊ฒŒ ํ•˜๋ ค๋ฉด ;;; a) ๋งค๋ฒˆ list์— ๋Œ€ํ•œ append๋ฅผ ์ˆ˜ํ–‰ (define (square-list items) (define (iter things answer) (if (null? things) answer (iter (cdr things) (append answer (list (square (car things))))))) (iter items '())) (square-list (list 1 2 3 4)) ;; (1 4 9 16) (append (append (append (append '() (list 1)) (list 4)) (list 9)) (list 16)) ;; ^^^^^^^^^^^^^^^^^^^^^ ;; 1) - (1) ;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ;; 2) - (1 4) ;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ;; 3) - (1 4 9) ;;^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ;; 4) - (1 4 9 16) ;;; b) ์ฒซ๋ฒˆ์งธ ๋ฐฉ์‹์œผ๋กœ ํ’€๊ณ  ์ตœ์ข…๊ฒฐ๊ณผ๋ฅผ reverse (define (square-list items) (define (iter things answer) (if (null? things) answer (iter (cdr things) (cons (square (car things)) answer)))) (let ((res (iter items '()))) (reverse res))) (square-list (list 1 2 3 4)) ;; (1 4 9 16) ;;;--------------------------< ex 2.23 >-------------------------- ;;; p139 ;; ํ’€์ด 1) (define (for-each proc items) (if (null? items) '() (begin (proc (car items)) (for-each proc (cdr items))))) (for-each (lambda (x) (newline) (display x)) (list 57 321 88)) ;; 57 ;; 321 ;; 88 ;; ํ’€์ด 2) (define (for-each proc items) (if (null? items) '() (let ((tmp (proc (car items)))) (for-each proc (cdr items))))) (for-each (lambda (x) (newline) (display x)) (list 57 321 88)) ;; 57 ;; 321 ;; 88 ;;;;=================<ch 2.2.2 ๊ณ„์ธต ๊ตฌ์กฐ๋ฒ•>===================== ;;; p139 (cons (list 1 2) (list 3 4)) ;; ((1 2) 3 4) (define x (cons (list 1 2) (list 3 4))) (length x) ;; 3 (define (count-leaves x) (cond ((null? x) 0) ((not (pair? x)) 1) (else (+ (count-leaves (car x)) (count-leaves (cdr x)))))) (count-leaves x) ;; 4 (list x x) ;; '(((1 2) 3 4) ((1 2) 3 4)) (length (list x x)) ;; 2 (count-leaves (list x x)) ;; 8 ;;;--------------------------< ex 2.24 >-------------------------- ;;; p142 (list 1 (list 2 (list 3 4))) ;์— ๋Œ€ํ•œ ๋‚˜๋ฌด๊ผด ;; (1 (2 (3 4))) ;;=> ;; [ + | + ]-->[ + | / ] ;; | | ;; 1 [ + | + ]-->[ + | / ] ;; | | ;; 2 [ + | + ]--[ + | / ] ;; | | ;; 3 4 ;;;--------------------------< ex 2.25 >-------------------------- ;;; p142,3 ;;; 7์„ ๊บผ์ง‘์–ด ๋‚ด๋ ค๋ฉด (car (cdaddr '(1 3 (5 7) 9))) ;; 7 (third (caar '((7))) ;; 7 (cadadr (cadadr (cadadr '(1 (2 (3 (4 (5 (6 7))))))))) ;; 7 ;;;--------------------------< ex 2.26 >-------------------------- ;;; p143 (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 >-------------------------- ;;; p143,4 ;((1 2) (3 4)) ; ((3 4) (1 2)) ;; ((4 3) (2 1)) ;; ๋ฆฌ์ŠคํŠธ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ์—๋„ ๊ฐ€๋Šฅํ•˜๋„๋ก list์ธ์ง€ ์—ฌ๋ถ€๋ฅผ ํ™•์ธํ•˜๋Š” ๋‚ด์šฉ์„ ์ถ”๊ฐ€ํ•จ (define (reverse items) (define (reverse-iter items2 acc) (if (list? items2) (if (null? items2) acc (reverse-iter (cdr items2) (cons (car items2) acc))) items2)) (reverse-iter items '())) (reverse '(1 2 3 4)) ;; (4 3 2 1) (reverse 1) ;; 1 (reverse '(1 . 2)) ;; (1 . 2) (reverse '(1 (2 . 3))) ;; ((2 . 3) 1) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ํ’€์ด 1) ;; ์ธ์ž๊ฐ€ ํ•ญ์ƒ 2 ๋‹จ๊ณ„์˜ ๋ฆฌ์ŠคํŠธ๋ผ๋ฉด ์•„๋ž˜์™€ ๊ฐ™์ด ํ•ด๋„ ๋œ๋‹ค. (define (deep-reverse items) (reverse (map reverse items))) (deep-reverse '(1 2 3 4)) ;; (4 3 2 1) (deep-reverse '((1 2) (3 4))) ;; ((4 3) (2 1)) ;; ๊ทธ๋Ÿฌ๋‚˜! ์ด ๋ฐฉ๋ฒ•์—์„œ๋Š” 3๋‹จ๊ณ„ ์ด์ƒ์˜ ๋ฆฌ์ŠคํŠธ์— ๋Œ€ํ•ด์„œ ๋‚ด๋ถ€์˜ ์ˆœ์„œ๋ฅผ ๋ฐ”๊พธ์ง€ ๋ชปํ•œ๋‹ค. (deep-reverse '((1 2) (3 (4 5)))) ;;-> (((4 5) 3) (2 1)) ;; (((5 4) 3) (2 1)) ์ด ๋ฐ”๋ฅธ ๋‹ต์ž„. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ๋ฐ”๋ฅธ ํ’€์ด (define (deep-reverse items) (cond ((null? items) '()) ((list? items) (reverse (map deep-reverse items))) (else items))) (deep-reverse '(1 2 3 4)) ;; (4 3 2 1) (deep-reverse '((1 2) (3 4))) ;; ((4 3) (2 1)) (deep-reverse '((1 2) (3 (4 5)))) ;; (((5 4) 3) (2 1)) (deep-reverse 1) ;; 1 (deep-reverse '(1 . 2)) ;; (1 . 2) <- ๋ฆฌ์ŠคํŠธ๊ฐ€ ์•„๋‹ˆ๋ฏ€๋กœ ๋งž๋Š” ๊ฒฐ๊ณผ์ž„. (deep-reverse '(1 2 (3 4 (5 6)) 7 8 (9 . 10))) ;; ((9 . 10) 8 7 ((6 5) 4 3) 2 1) (define x (list (list 1 2) (list 3 4))) x ;; ((1 2) (3 4)) (reverse x) ;; ((3 4) (1 2)) (deep-reverse x) ;; ((4 3) (2 1)) ;; ๋ฆฌ์ŠคํŠธ ํ™•์ธ (list? 1) ; #f (list? '()) ; #t (list? '(1 . 2)) ; #f (list? '(1 2)) ; #t (list? '(1 . (2 3))) ; #t (pair? 1) ; #f (pair? '()) ; #f (pair? '(1 . 2)) ; #t (pair? '(1 2)) ; #t (pair? '(1 . (2 3))) ; #t (define (my-list? x) (or (null? x) (and (pair? x) (pair? (cdr x))))) (my-list? 1) ; #f (my-list? '()) ; #t (my-list? '(1 . 2)) ; #f (my-list? '(1 2)) ; #t (my-list? '(1 . (2 3))) ; #t ;;;--------------------------< ex 2.28 >-------------------------- ;;; p144 ;; ํ’€์ด 1) (define (fringe items) (cond ((null? items) '()) ((list? items) (append (fringe (car items)) (fringe (cdr items)))) (else (list items)))) (fringe '(1 2 3 4)) ;; (1 2 3 4) (fringe '((1 2) (3 4))) ;; (1 2 3 4) (fringe '(1 2 (3 4 (5 6) 7) 8 9 (10 . 11) 12)) ;; (1 2 3 4 5 6 7 8 9 (10 . 11) 12) (define x (list (list 1 2) (list 3 4))) x ;; ((1 2) (3 4)) (fringe x) ;; (1 2 3 4) (fringe (list x x)) ;; (1 2 3 4 1 2 3 4) ;;---------------------------------- ;; ์—ฌ๋Ÿฌ๊ฐ€์ง€ ์‹œ๋„... ;; ์•„๋ž˜์™€ ๊ฐ™์ด ํ•˜๋ฉด.. (define (fringe items) (cond ((null? items) '()) ((list? items) (cons (fringe (car items)) (fringe (cdr items)))) (else (list items)))) ;;== (define (fringe items) (cond ((null? items) '()) ((list? items) (append (map fringe items))) (else (list items)))) (fringe '(1 2 3 4)) ;; ((1) (2) (3) (4)) (fringe '((1 2) (3 4))) ;; (((1) (2)) ((3) (4))) (fringe '(1 2 (3 4 (5 6) 7) 8 9 (10 . 11) 12)) ;; ((1) (2) ((3) (4) ((5) (6)) (7)) (8) (9) ((10 . 11)) (12)) ;; ์œ ์‚ฌ.. (define (fringe items) (cond ((null? items) '()) ((list? items) (cons (fringe (car items)) (cons (fringe (cdr items)) '()))) (else items))) (fringe '(1 2 3 4)) ;; '(1 (2 (3 (4 ())))) (fringe '((1 2) (3 4))) ;; '((1 (2 ())) ((3 (4 ())) ())) (fringe '(1 2 (3 4 (5 6) 7) 8 9 (10 . 11) 12)) ;; '(1 (2 ((3 (4 ((5 (6 ())) (7 ())))) (8 (9 ((10 . 11) (12 ()))))))) ;;;--------------------------< ex 2.29 >-------------------------- ;;; p144,5 (define (make-mobile left right) (list left right)) (define (make-branch length structure) (list length structure)) ;;------------------------------------------------- ;; a) - ๋ชจ๋นŒ์—์„œ ๊ฐ€์ง€๋ฅผ ๊ณจ๋ผ๋‚ด๋Š” ๊ณ ๋ฅด๊ฐœ ์ •์˜ ;; - ๊ฐ€์ง€์˜ ๊ตฌ์„ฑ์š”์†Œ๋ฅผ ๊ณจ๋ผ๋‚ด๋Š” ๊ณ ๋ฅด๊ฐœ (define (left-branch m) (car m)) (define (right-branch m) (cadr m)) (define (branch-length b) (car b)) (define (branch-structure b) (cadr b)) ;;;-------------------------- ;;; ํ…Œ์ŠคํŠธ ;; m0 ;; * ;; | ;; m1 | m2 ;; *-=----+----=---* ;; | | ;; m3 | s4 m5 | m6 ;; *---+---6 *--+----=--* ;; | | | ;; s7 | s8 s9 | s10 s11| s12 ;; 4-+--2 2=----+--5 1--+--1 (define s12 1) (define b12 (make-branch 2 s12)) (define s11 1) (define b11 (make-branch 2 s11)) (define s10 5) (define b10 (make-branch 2 s10)) (define s9 2) (define b9 (make-branch 5 s9)) (define s8 2) (define b8 (make-branch 2 s8)) (define s7 4) (define b7 (make-branch 1 s7)) (define m6 (make-mobile b11 b12)) (define b6 (make-branch 7 m6)) (define m5 (make-mobile b9 b10)) (define b5 (make-branch 2 m5)) (define s4 6) (define b4 (make-branch 3 s4)) (define m3 (make-mobile b7 b8)) (define b3 (make-branch 3 m3)) (define m2 (make-mobile b5 b6)) (define b2 (make-branch 8 m2)) (define m1 (make-mobile b3 b4)) (define b1 (make-branch 6 m1)) (define m0 (make-branch b1 b2)) m0 ;; '((6 ((3 ((1 4) (2 2))) (3 6))) (8 ((2 ((5 2) (2 5))) (7 ((2 1) (2 1)))))) m5 ;; '((5 2) (2 5)) s10 ;; 5 s4 ;; 6 (left-branch m5) ; '(5 2) (right-branch m5) ; '(2 5) (branch-length (right-branch m5)) ; 2 (branch-structure (right-branch m5)) ; 5 ;;------------------------------------------------- ;; b) ๋ชจ๋นŒ์˜ ์ „์ฒด ๋ฌด๊ฒŒ (define (total-weight m) (if (mobile? m) (let ((left (left-branch m)) (right (right-branch m))) (+ (total-branch-weight left) (total-branch-weight right))) m)) (define (total-branch-weight b) (let ((s (branch-structure b))) (if (mobile? s) (total-weight s) s))) (define (mobile? s) (if (pair? s) #t #f)) (total-weight m1) ;; 12 (total-weight m2) ;; 9 (total-weight m0) ;; 21 (total-weight s10) ;; 5 ;;------------------------------------------------- ;; c) ๊ท ํ˜• ์žกํžŒ ์ƒํƒœ ;; 1) ์™ผ์ชฝ ๋งจ ์œ—๊ฐ€์ง€์˜ ๋Œ๋ฆผํž˜ = ์˜ค๋ฅธ์ชฝ ๋งจ ์œ—๊ฐ€์ง€์˜ ๋Œ๋ฆผํž˜ ;; ๋Œ๋ฆผํž˜ = (๋ง‰๋Œ€ ๊ธธ์ด) * (๋ง‰๋Œ€์— ๋งค๋‹ฌ๋ฆฐ ์ถ” ๋ฌด๊ฒŒ ํ•ฉ) ;; 2) ๊ฐ€์ง€๋งˆ๋‹ค ๋งค๋‹ฌ๋ฆฐ ๋ชจ๋“  ๋ถ€๋ถ„ ๋ชจ๋นŒ๋„ ๊ท ํ˜• ์žกํžŒ ์ƒํƒœ (define (mobile-torque m) (if (mobile? m) (let ((lb (left-branch m)) (rb (right-branch m))) (cons (branch-torque lb) (branch-torque rb))) 0)) (define (branch-torque b) (* (total-branch-weight b) (branch-length b))) (define (mobile-balanced? m) (if (mobile? m) (let ((lb (left-branch m)) (rb (right-branch m))) (and (= (branch-torque lb) (branch-torque rb)) (branch-balanced? lb) (branch-balanced? rb))) #t)) (define (branch-balanced? b) (if (pair? b) (let ((s (branch-structure b))) (if (mobile? s) (mobile-balanced? s) #t)) #t)) (mobile-torque m0) ;; (72 . 72) (mobile-balanced? m0) ;; #t (mobile-torque m1) ;; (18 . 18) (mobile-balanced? m1) ;; #t (mobile-torque m2) ;; (14 . 14) (mobile-balanced? m2) ;; #t (mobile-torque m6) ;; (2 . 2) (mobile-balanced? m6) ;; #t (mobile-torque s10) ;; 0 (mobile-balanced? s10) ;; #t s4 ;; 6 m1 ;;'((3 ((1 4) (2 2))) (3 6)) ;; ๋ชจ๋นŒ ์ˆ˜์ • (define s4 4) ;; <------------ 6์—์„œ 4๋กœ ์ˆ˜์ • (define b4 (make-branch 3 s4)) (define m3 (make-mobile b7 b8)) (define b3 (make-branch 3 m3)) (define m2 (make-mobile b5 b6)) (define b2 (make-branch 8 m2)) (define m1 (make-mobile b3 b4)) (define b1 (make-branch 6 m1)) (define m0 (make-branch b1 b2)) s4 ;; 4 (mobile-torque s4) ;; 0 ;;!!!!! (mobile-balanced? s10) ;; #t ;;; (mobile-torque m0) ;; (60 . 72) (mobile-balanced? m0) ;; #f (mobile-torque m1) ;; (18 . 12) (mobile-balanced? m1) ;; #f (mobile-torque m2) ;; (14 . 14) (mobile-balanced? m2) ;; #t (mobile-torque m6) ;; (2 . 2) (mobile-balanced? m6) ;; #t (mobile-torque s10) ;; 0 (mobile-balanced? s10) ;; #t ;;------------------------------------------------- ;; d) ์งœ๋งž์ถ”๊ฐœ๋ฅผ ๋ฐ”๊พธ๋ฉด ์ง€๊ธˆ๊นŒ์ง€ ์ง  ํ”„๋กœ๊ทธ๋žจ์„ ์–ผ๋งˆ๋‚˜ ์†๋ด์•ผํ•˜๋‚˜? (define (make-mobile left right) (cons left right)) (define (make-branch length structure) (cons length structure)) ;;;---------------------- ;;; ์ˆ˜์ • ํ•„์š” (define (right-branch m) (cdr m)) ; <- cadr (define (branch-structure b) (cdr b)) ; <- cadr ;;;---------------------- ;;; ๋‚˜๋ฌด ๋งคํ•‘ ;;; p145 (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) ;; (10 (20 (30 40) 50) (60 70)) ;;; map ์ด์šฉ (define (scale-tree tree factor) (map (lambda (sub-tree) (if (pair? sub-tree) (scale-tree sub-tree factor) (* sub-tree factor))) tree)) (scale-tree (list 1 (list 2 (list 3 4) 5) (list 6 7)) 10) ;; (10 (20 (30 40) 50) (60 70)) ;;;--------------------------< ex 2.30 >-------------------------- ;;; p146,7 ;;;--- (define (square x) (* x x)) ;; ๊ณง ๋ฐ”๋กœ ์ •์˜ (define (square-tree tree) (cond ((null? tree) '()) ((not (pair? tree)) (square tree)) (else (cons (square-tree (car tree)) (square-tree (cdr tree)))))) (square-tree (list 1 (list 2 (list 3 4) 5) (list 6 7))) ;; ์ž…๋ ฅ : '(1 (2 (3 4) 5) (6 7)) ;; ๊ฒฐ๊ณผ : '(1 (4 (9 16) 25) (36 49)) ;; map๊ณผ ์žฌ๊ท€๋ฅผ ์จ์„œ ์ •์˜ (define (square-tree tree) (map (lambda (sub-tree) (if (pair? sub-tree) (square-tree sub-tree) (square sub-tree))) tree)) (square-tree (list 1 (list 2 (list 3 4) 5) (list 6 7))) ;; '(1 (4 (9 16) 25) (36 49)) ;;;--------------------------< ex 2.31 >-------------------------- ;;; p147 (define (tree-map proc tree) (map (lambda (sub-tree) (if (pair? sub-tree) (tree-map proc sub-tree) (proc sub-tree))) tree)) (define (square-tree tree) (tree-map square tree)) (square-tree (list 1 (list 2 (list 3 4) 5) (list 6 7))) ;; '(1 (4 (9 16) 25) (36 49)) ;;;--------------------------< ex 2.32 >-------------------------- ;;; p147 ;; ์˜์‹๋‹˜์˜ ๋ฐฉ๋ฒ•์œผ๋กœ (define (subsets s) (if (null? s) (list '()) (let ((rest (subsets (cdr s)))) (append rest (map (lambda (x) (cons (car s) x)) rest))))) (subsets '(1 2 3)) ;; (() (3) (2) (2 3) (1) (1 3) (1 2) (1 2 3)) (define (subsets s) (begin (print "---->") (print s) (newline) (if (null? s) (list '()) (let ((rest (subsets (cdr s)))) (print "s :") (print s) (newline) (print "rest :") (print rest) (newline) (newline) (append rest (map (lambda (x) (cons (car s) x)) rest)))))) (subsets '(1 2 3)) ;; "---->"'(1 2 3) ;; "---->"'(2 3) ;; "---->"'(3) ;; "---->"'() ;; "s :"'(3) ;; "rest :"'(()) ;; ;; "s :"'(2 3) ;; "rest :"'(() (3)) ;; ;; "s :"'(1 2 3) ;; "rest :"'(() (3) (2) (2 3)) ;; ;; '(() (3) (2) (2 3) (1) (1 3) (1 2) (1 2 3)) ;;;;==============<ch 2.2.3 ๊ณตํ†ต ์ธํ„ฐํŽ˜์ด์Šค๋กœ์จ ์ฐจ๋ก€์—ด์˜ ์“ฐ์ž„์ƒˆ>================== ;;; p147 ;;;--- (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)))))) (sum-odd-squares '((1 2 (3 4)) ((5 6 7) (8 9 10)))) ;; 3^2 + 5^2 + 7^2 + 9^2 ;; 165 (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)) ;;;--- (define (fib n) (cond ((= n 0) 0) ((= n 1) 1) (else (+ (fib (- n 1)) (fib (- n 2)))))) ;;;--- (even-fibs 10) ; '(0 2 8 34) ;;; enumerate -> filter -> map -> accumulate ;;; enumerate -> map -> filter -> accumulate ;;;;;;;;;;;;;;;;;;;;;; ;;; ์ฐจ๋ก€์—ด ์—ฐ์‚ฐ ;; p150 ;;;--- (define nil '()) ;;;--- ;;; ๋งคํ•‘ ๋‹จ๊ณ„ - map ;;; ๊ณจ๋ผ๋‚ด๋Š” ์—ฐ์‚ฐ - filter (define (filter predicate sequence) (cond ((null? sequence) nil) ((predicate (car sequence)) (cons (car sequence) (filter predicate (cdr sequence)))) (else (filter predicate (cdr sequence))))) (filter odd? (list 1 2 3 4 5)) ; '(1 3 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)) ; 15 (accumulate * 1 (list 1 2 3 4 5)) ; 120 (accumulate cons nil (list 1 2 3 4 5)) ; '(1 2 3 4 5) ;;; ์–ด๋–ค ๋ฒ”์œ„์— ์žˆ๋Š” ๋ชจ๋“  ์ •์ˆ˜๋ฅผ ๋ฝ‘์•„๋‚ด๋Š” ์—ฐ์‚ฐ (define (enumerate-interval low high) (if (> low high) nil (cons low (enumerate-interval (+ low 1) high)))) (enumerate-interval 2 7) ; '(2 3 4 5 6 7) ;;; ๋‚˜๋ฌด์—์„œ ์žŽ์‚ฌ๊ท€๋ฅผ ๋–ผ์–ด๋‚ผ ๋•Œ (define (enumerate-tree tree) (cond ((null? tree) nil) ((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)) ;; '(1 2 3 4 5) ;;; sum-odd-square๋ฅผ ๋‹ค์‹œ ์ •์˜ (define (sum-odd-squares tree) (accumulate + 0 (map square (filter odd? (enumerate-tree tree))))) (sum-odd-squares '(1 2 3 4 5)) ; 35 ;;; even-fibs๋ฅผ ๋‹ค์‹œ ์ •์˜ (define (even-fibs n) (accumulate cons nil (filter even? (map fib (enumerate-interval 0 n))))) (even-fibs 10) ; '(0 2 8 34) ;;; p153 ;;; ์ฐจ๋ก€์—ด ์—ฐ์‚ฐ์œผ๋กœ ํ”„๋กœ๊ทธ๋žจ์„ ํ‘œํ˜„ํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ๋ชจ๋“ˆ ๋ฐฉ์‹ ;;; ๊ณง ๋…๋ฆฝ๋œ ๋ถ€ํ’ˆ์„ ์งœ ๋งž์ถ”๋“ฏ์ด ํ”„๋กœ๊ทธ๋žจ์„ ์„ค๊ณ„ํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ์ ์—์„œ ๊ฐ€์น˜๊ฐ€ ์žˆ๋‹ค. ;;; ๋ถ€ํ’ˆ ์žฌ์‚ฌ์šฉ (define (list-fib-squares n) (accumulate cons nil (map square (map fib (enumerate-interval 0 n))))) (list-fib-squares 10) ; '(0 1 1 4 9 25 64 169 441 1156 3025) (define (product-of-squares-of-odd-elements sequence) (accumulate * 1 (map square (filter odd? sequence)))) (product-of-squares-of-odd-elements '(1 2 3 4 5)) ; 225 ;; (define (salary-of-highest-paid-programmer records) ;; (accumulate max ;; 0 ;; (map salary ;; (filter programmer? records)))) ;;;--------------------------< ex 2.33 >-------------------------- ;;; p155 (define (map2 p sequence) (accumulate (lambda (x y) (cons (p x) y)) ;; <--- nil sequence)) ;;; accumulate ์ฝ”๋“œ์—์„œ ;; (op (car sequence) (accumulate op initial (cdr sequence))) ;; ^^^ ^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ;; lambda.. x y (map square '(1 2 3 4)) ; '(1 4 9 16) (map2 square '(1 2 3 4)) ; '(1 4 9 16) ;;;---------------- (define (append2 seq1 seq2) (accumulate cons seq2 ;;<-- seq1 ;;<-- )) (append '(1 2) '(3 4)) ; '(1 2 3 4) (append '(1) 2) ; '(1 . 2) (append2 '(1 2) '(3 4)) ; '(1 2 3 4) (append2 '(1) 2) ; '(1 . 2) ;;;---------------- (define (length2 sequence) (accumulate (lambda (x y) (+ 1 y)) 0 sequence)) (length '(1 2 3 4)) ; 4 (length2 '(1 2 3 4)) ; 4 ;;;--------------------------< ex 2.34 >-------------------------- ;;; p155,6 ;; a_n * x^n + ;; a_(n-1) * x^(n-1) + ;; ... ;; a_1 * x^1 + ;; a_0 ;; ;;=> (ํ˜ธ๋„ˆ์˜ ๊ทœ์น™) ;; ;; ( ... (a_n*x + a_(n-1) )*x + ... + a_1)*x + a_0 ;; ;;=> ;; a_0 + x*(a_1 + ... + x*( a_(n-1) + x*a_n) ... ) (define (horner-eval x coefficient-sequence) (accumulate (lambda (this-coeff higher-terms) (+ this-coeff (* x higher-terms))) ;;<-- 0 coefficient-sequence)) ;; x=2์ผ ๋•Œ, 1 + 3x + 5x^3 + x^5 (horner-eval 2 (list 1 3 0 5 0 1)) ; 79 ;; (+ 1 (* 2 3) (* 5 (* 2 2 2)) (* 2 2 2 2 2)) ;;;; -> 79 ;;;--------------------------< ex 2.35 >-------------------------- ;;; p156 ;;; 2.2.2์ ˆ์˜ count-leaves ๋ฅผ accumulate๋ฅผ ์ด์šฉํ•ด์„œ ์ •์˜ (define (count-leaves x) (cond ((null? x) 0) ((not (pair? x)) 1) (else (+ (count-leaves (car x)) (count-leaves (cdr x)))))) (define (count-leaves2 t) (accumulate + 0 (map length t))) ;;ํ•ญ์ƒ ๊นŠ์ด๊ฐ€ 2์ด๊ณ , ๊นŠ์ด 2์—์„œ๋งŒ leaf๊ฐ€ ๋งค๋‹ฌ๋ฆฐ๋‹ค๋ฉด ์œ„์™€ ๊ฐ™์ด ํ•ด๋„ ๋œ๋‹ค. (count-leaves2 '((1 2) (3 4) (5 6))) ;; ์–ด๋–ค tree์—๋„ ๋Œ€์‘. (define (count-leaves2 t) (accumulate + 0 (map (lambda (x) (if (not (pair? x)) 1 (count-leaves2 x))) t))) ;; tree์˜ ์›์†Œ๊ฐ€ leaf์ด๋ฉด map์—์„œ 1์„ ์นด์šดํŠธํ•˜๊ณ  ;; tree์˜ ์›์†Œ๊ฐ€ ๋‹ค์‹œ tree์ด๋ฉด count-leaves๋ฅผ ๋˜๋ˆ๋‹ค. ;; accumulate๋Š” ๊ทธ๋ƒฅ map์—์„œ 1์˜ ์ˆ˜๋ฅผ ๋˜๋Œ๋ฉด์„œ ๋”ํ•˜๋ฉด ๋œ๋‹ค. (count-leaves '((1 2) ((3 4 5) 6) 7)) ; 7 (count-leaves2 '((1 2) ((3 4 5) 6) 7)) ; 7 ;;;-------------------- ;;; ๋˜๋„๋Š” map ํ…Œ์ŠคํŠธ (define (test-map t) (if (null? t) nil (map (lambda (x) (if (not (pair? x)) 1 (test-map x))) t))) (test-map '((1 2) ((3 4 5) 6) 7)) ;; '((1 1) ((1 1 1) 1) 1) ;;;--------------------------< ex 2.36 >-------------------------- ;;; p156 (define (accumulate-n op init seqs) (if (null? (car seqs)) nil (cons (accumulate op init (map car seqs)) (accumulate-n op init (map cdr seqs))))) (define s '((1 2 3) (4 5 6) (7 8 9) (10 11 12))) (accumulate-n + 0 s) ; '(22 26 30) ;; ๋˜ ๋‹ค๋ฅธ accumulate-n ;; ๊ฐ ์ฐจ๋ก€์—ด์„ ๋”ํ•œ ์ฐจ๋ก€์—ด์„ ๋‚ด๋†“๋Š” ํ”„๋กœ์‹œ์ € (define (another-accumulate-n op init seqs) (if (not (pair? seqs)) nil (if (null? (car seqs)) nil (cons (accumulate op init (car seqs)) (another-accumulate-n op init (cdr seqs)))))) (another-accumulate-n + 0 s) ;; '(6 15 24 33) ;;;--------------------------< ex 2.37 >-------------------------- ;;; p157 ;;; ํ–‰๋ ฌ ;;; ((1 2 3 4) (4 5 6 6) (6 7 8 9)) ;;=> ;; [ 1 2 3 4 ;; 4 5 6 6 ;; 6 7 8 9 ] ;; (dot-product v w) ;; S_i : vi * wi ;; (matrix-*-vector m v) ;; ti = Sj : mij * vj ;; (matrix-*-matrix m n) ;; Pij = Sk : mik * nkj ;; (transpose m) ;; nij = mji (define m '((1 2) (3 4))) (define v '(5 6)) (define (dot-product v w) (accumulate + 0 (map * v w))) ;;; 2.2.1 ์—์„œ ์ •์˜ํ•œ map์œผ๋กœ๋Š” ์•ˆ๋จ. (dot-product v v) ; 61 ;; (5 6) .* (5 6) = 5*5 + 6*6 = 61 (define (matrix-*-vector m v) (map (lambda (x) (accumulate + 0 (map * x v))) m)) (matrix-*-vector m v) ; '(17 39) ;; [ 1 2 | * [ 5 | = [ 1*5 + 2*6 | = [ 17 | ;; | 3 4 ] | 6 ] | 3*5 + 4*6 ] | 39 ] (define (transpose mat) (accumulate-n cons nil mat)) (define m2 '((1 2 3) (4 5 6) (7 8 9))) (transpose m2) ; '((1 4 7) (2 5 8) (3 6 9)) ;; [ 1 2 3 | -> [ 1 4 7 | ;; | 4 5 6 | | 2 5 8 | ;; | 7 8 9 ] | 3 6 9 ] (define (matrix-*-matrix m n) (let ((cols (transpose n))) (map (lambda (x) (accumulate cons nil (matrix-*-vector cols x))) m))) (matrix-*-matrix m m) ; '((7 10) (15 22)) ;; [ 1 2 | * [ 1 2 | = [ 1*1 + 2*3 1*2 + 2*4 | = [ 7 10 | ;; | 3 4 ] | 3 4 ] | 3*1 + 4*3 3*2 + 4*4 ] | 15 22 ] (matrix-*-matrix m2 m2) ; '((30 36 42) (66 81 96) (102 126 150)) ;;;--------------------------< ex 2.38 >-------------------------- ;;; p158 (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 accumulate) (fold-right / 1 (list 1 2 3)) ; 3/2 ;; (/ 1 (/ 2 (/ 3 1))) ;; i ;; ;; 1 2 3 ;; | | | ;; | | /--> 1 ;; | | | (3/1) ;; | | v ;; | /-------> 3 ;; | | (2 / 3) ;; | v ;; /------------ > 2/3 ;; | (1 / (2/3)) ;; v ;; 3/2 (fold-right / 1 (list 4 5 6)) ; 24/5 ;; (/ 4 (/ 5 (/ 6 1))) (fold-left / 1 (list 1 2 3)) ; 1/6 ;; (/ (/ (/ 1 1) 2) 3) ;; i ;; ;; 1 2 3 ;; | | | ;; 1 <-- / | | ;; (1 / 1) | | | ;; v | | ;; 1 <-------- / | ;; (1 / 2) | | ;; v | ;; 1/2 <-------------- / ;; (1/2) / 3 | ;; v ;; 1/6 (fold-left / 1 (list 4 5 6)) ; 1/120 ;; (/ (/ (/ 1 4) 5) 6) (fold-right list nil (list 1 2 3)) ; '(1 (2 (3 ()))) (fold-left list nil (list 1 2 3)) ; '(((() 1) 2) 3) ;; ์œ„์—์„œ ๋ณผ ๋•Œ ;; right์—์„œ๋Š” 2 3 -> (x / 2) / 3 ;; left์—์„œ๋Š” 2 3 -> (y / 3) / 2 ;; ์ฆ‰ 2,3์˜ ์ˆœ์„œ๊ฐ€ ๋ฐ”๋€๋‹ค. ;; ๊ฐ™์œผ๋ ค๋ฉด ์ˆœ์„œ๊ฐ€ ๋ฐ”๊ปด๋„ ์—ฐ์‚ฐ์˜ ๊ฒฐ๊ณผ๊ฐ€ ๊ฐ™์•„์•ผ ํ•œ๋‹ค : ์ฆ‰ ๊ตํ™˜ ๋ฒ•์น™ ์„ฑ๋ฆฝ (fold-left * 1 (list 4 5 6)) ; 120 (fold-right * 1 (list 4 5 6)) ; 120 (fold-left + 1 (list 4 5 6)) ; 16 (fold-right + 1 (list 4 5 6)) ; 16 ;;;--------------------------< ex 2.39 >-------------------------- ;;; p159 (define (reverse2 sequence) ;; initial ๊ฐ’์ด y์— ๋“ค์–ด๊ฐ„๋‹ค. ;; ์ค‘๊ฐ„ ๊ฒฐ๊ณผ๋ฌผ์ด y์— ๋“ค์–ด๊ฐ„๋‹ค. ;; sequence์˜ ์›์†Œ๋Š” ๋’ค์—์„œ๋ถ€ํ„ฐ x์— ๋“ค์–ด๊ฐ„๋‹ค (fold-right (lambda (x y) (append y (cons x nil))) nil sequence)) (reverse2 '(1 2 3 4)) (define (reverse2 sequence) ;; initial ๊ฐ’์ด x์— ๋“ค์–ด๊ฐ„๋‹ค. ;; ์ค‘๊ฐ„ ๊ฒฐ๊ณผ๋ฌผ์ด x์— ๋“ค์–ด๊ฐ„๋‹ค. ;; sequence์˜ ์›์†Œ๋Š” ์•ž์—์„œ๋ถ€ํ„ฐ y์— ๋“ค์–ด๊ฐ„๋‹ค. (fold-left (lambda (x y) (cons y x)) nil sequence)) (reverse2 '(1 2 3 4)) ;;;;;;;;;;;;;;;;;;;;;; ;;; ๊ฒน์นœ ๋งคํ•‘ ;; p159 ;;(1) (enumerate-interval 1 n) ์œผ๋กœ ์ฐจ๋ก€์—ด ๋ฝ‘์•„๋‚ด๊ธฐ ;;(2) ์›์†Œ i๋งˆ๋‹ค (enumerate-interval 1 (- i 1)) ์„ ์ ์šฉํ•˜์—ฌ ๋‹ค์‹œ ์ฐจ๋ก€์—ด ๋ฝ‘๊ธฐ ;;(3) ์ฐจ๋ก€์—ด ์›์†Œ j์— ๋Œ€ํ•˜์—ฌ (list i j) ๋งŒ๋“ค๊ธฐ ;; (accumulate append ;; nil ;; (map (lambda (i) ;; (map (lambda (j) (list i j)) ;; (enumerate-interval 1 (- i 1)))) ;; (enumerate-interval 1 n))) (define (flatmap proc seq) (accumulate append nil (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 6) ;; '((2 1 3) (3 2 5) (4 1 5) (4 3 7) (5 2 7) (6 1 7) (6 5 11)) (let ((n 4)) (flatmap (lambda (i) (map (lambda (j) (list i j)) (enumerate-interval 1 (- i 1)))) (enumerate-interval 1 n))) ;; '((2 1) (3 1) (3 2) (4 1) (4 2) (4 3)) ;;;--- ;; p64 ch 1.2.6 (define (smallest-divisor n) (find-divisor n 2)) (define (find-divisor n test-divisor) (cond ((> (square test-divisor) n) n) ((divides? test-divisor n) test-divisor) (else (find-divisor n (+ test-divisor 1))))) (define (divides? a b) (= (remainder b a) 0)) (define (prime? n) (= n (smallest-divisor n))) ;;;--- ;;; p161 ;;; ์ˆœ์—ด ;;(1) S์˜ ๊ฐ ์›์†Œ x์— ๋Œ€ํ•˜์…”, S - x ์˜ ์ˆœ์—ด์„ ๋ชจ๋‘ ๊ตฌํ•ด ์ฐจ๋ก€์—ด๋กœ ๋ฌถ์–ด๋‚ธ๋‹ค. ;;(2) ์ฐจ๋ก€์—ด ์†์— ์žˆ๋Š” ๊ฐ ์ˆœ์—ด์˜ ๋งจ ์•ž์— x๋ฅผ ๋ง๋ถ™์ธ๋‹ค. (define (permutations s) (if (null? s) (list nil) (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 '(1 2 3)) ;; '((1 2 3) (1 3 2) (2 1 3) (2 3 1) (3 1 2) (3 2 1)) ;;;--------------------------< ex 2.40 >-------------------------- ;;; p162 ;; ์ •์ˆ˜ n์„ ์ธ์ž๋กœ ๋ฐ›์•„์„œ 1<= j < i <= n ์„ ๋งŒ์กฑํ•˜๋Š” (i,j) ์Œ์˜ ์ฐจ๋ก€์—ด ๋ฝ‘๊ธฐ (define (unique-pairs n) (flatmap (lambda (i) (map (lambda (j) (list i j)) (enumerate-interval 1 (- i 1)))) (enumerate-interval 2 n))) (unique-pairs 5) ;; '((2 1) (3 1) (3 2) (4 1) (4 2) (4 3) (5 1) (5 2) (5 3) (5 4)) ;;; unique-pairs๋ฅผ ์ด์šฉํ•ด์„œ prime-sum-pairs ์ •์˜ ์ค„์ด๊ธฐ (define (prime-sum-pairs2 n) (map make-pair-sum (filter prime-sum? (unique-pairs n)))) (prime-sum-pairs 5) ;; '((2 1 3) (3 2 5) (4 1 5) (4 3 7) (5 2 7)) (prime-sum-pairs2 5) ;; '((2 1 3) (3 2 5) (4 1 5) (4 3 7) (5 2 7)) ;;;--------------------------< ex 2.41 >-------------------------- ;;; p162 (define (unique-triple n) (define (unique-triple? items) (let ((a (car items)) (b (cadr items)) (c (caddr items))) (cond ((= a b) #f) ((= b c) #f) ((= a c) #f) (else #t)))) (filter unique-triple? (accumulate append nil (flatmap (lambda (i) (map (lambda (j) (map (lambda (k) (list i j k)) (enumerate-interval 1 n))) (enumerate-interval 1 n))) (enumerate-interval 1 n))))) (unique-triple 3) ;; '((1 2 3) (1 3 2) (2 1 3) (2 3 1) (3 1 2) (3 2 1)) (unique-triple 4) ;; '((1 2 3) ;; (1 2 4) ;; (1 3 2) ;; (1 3 4) ;; (1 4 2) ;; (1 4 3) ;; (2 1 3) ;; (2 1 4) ;; (2 3 1) ;; (2 3 4) ;; (2 4 1) ;; (2 4 3) ;; (3 1 2) ;; (3 1 4) ;; (3 2 1) ;; (3 2 4) ;; (3 4 1) ;; (3 4 2) ;; (4 1 2) ;; (4 1 3) ;; (4 2 1) ;; (4 2 3) ;; (4 3 1) ;; (4 3 2)) (define (unique-triple-sum n s) (filter (lambda (x) (= s (accumulate + 0 x))) (unique-triple n))) (unique-triple-sum 4 7) ;; '((1 2 4) (1 4 2) (2 1 4) (2 4 1) (4 1 2) (4 2 1)) ;;;--------------------------< ex 2.42 >-------------------------- ;;; p162,3,4 (define (queens board-size) (define empty-board (map (lambda (r) (map (lambda (c) (list r c 0)) (enumerate-interval 1 board-size))) (enumerate-interval 1 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 (adjoin-position new-row k rest-of-queens) (map (lambda (r) (if (= (caar r) new-row) ; (caar r) : ํ–‰๋ฒˆํ˜ธ ์ถ”์ถœ (map (lambda (c) (if (= (cadr c) k) ; (cadr c) : ์—ด๋ฒˆํ˜ธ ์ถ”์ถœ (list new-row k 1) ; (new-rowํ–‰, k์—ด)์— ํ€ธ์„ ๋†“์Œ. c)) ; ๋‚˜๋จธ์ง€ ํ–‰๋ ฌ์€ ๊ทธ๋Œ€๋กœ r) r)) rest-of-queens)) (define (safe? k positions) (and (safe-row? k positions) (safe-diag? k positions))) ;; ์„ฑ๊ณต! (queens 3) ;; '() (queens 4) ;; '((((1 1 0) (1 2 0) (1 3 1) (1 4 0)) ;; ((2 1 1) (2 2 0) (2 3 0) (2 4 0)) ;; ((3 1 0) (3 2 0) (3 3 0) (3 4 1)) ;; ((4 1 0) (4 2 1) (4 3 0) (4 4 0))) ;; (((1 1 0) (1 2 1) (1 3 0) (1 4 0)) ;; ((2 1 0) (2 2 0) (2 3 0) (2 4 1)) ;; ((3 1 1) (3 2 0) (3 3 0) (3 4 0)) ;; ((4 1 0) (4 2 0) (4 3 1) (4 4 0)))) (queens 5) ;; '((((1 1 1) (1 2 0) (1 3 0) (1 4 0) (1 5 0)) ;; ((2 1 0) (2 2 0) (2 3 0) (2 4 1) (2 5 0)) ;; ((3 1 0) (3 2 1) (3 3 0) (3 4 0) (3 5 0)) ;; ((4 1 0) (4 2 0) (4 3 0) (4 4 0) (4 5 1)) ;; ((5 1 0) (5 2 0) (5 3 1) (5 4 0) (5 5 0))) ;; (((1 1 1) (1 2 0) (1 3 0) (1 4 0) (1 5 0)) ;; ((2 1 0) (2 2 0) (2 3 1) (2 4 0) (2 5 0)) ;; ((3 1 0) (3 2 0) (3 3 0) (3 4 0) (3 5 1)) ;; ((4 1 0) (4 2 1) (4 3 0) (4 4 0) (4 5 0)) ;; ((5 1 0) (5 2 0) (5 3 0) (5 4 1) (5 5 0))) ;; ... ;; (((1 1 0) (1 2 0) (1 3 0) (1 4 1) (1 5 0)) ;; ((2 1 0) (2 2 1) (2 3 0) (2 4 0) (2 5 0)) ;; ((3 1 0) (3 2 0) (3 3 0) (3 4 0) (3 5 1)) ;; ((4 1 0) (4 2 0) (4 3 1) (4 4 0) (4 5 0)) ;; ((5 1 1) (5 2 0) (5 3 0) (5 4 0) (5 5 0))) ;; (((1 1 0) (1 2 0) (1 3 1) (1 4 0) (1 5 0)) ;; ((2 1 0) (2 2 0) (2 3 0) (2 4 0) (2 5 1)) ;; ((3 1 0) (3 2 1) (3 3 0) (3 4 0) (3 5 0)) ;; ((4 1 0) (4 2 0) (4 3 0) (4 4 1) (4 5 0)) ;; ((5 1 1) (5 2 0) (5 3 0) (5 4 0) (5 5 0)))) ;;;-------------------------------- ;;; ์ถœ๋ ฅ์šฉ (define (display-all-boards boards) (if (null? boards) (display "no boards") (begin (let ((size (length (car boards)))) (map (lambda (b) (begin (display-board size b) (newline))) (rc-val-all-boards boards)))))) (display-all-boards (queens 4)) ;; 0 0 1 0 ;; 1 0 0 0 ;; 0 0 0 1 ;; 0 1 0 0 ;; 0 1 0 0 ;; 0 0 0 1 ;; 1 0 0 0 ;; 0 0 1 0 (display-all-boards (queens 5)) ;; 1 0 0 0 0 ;; 0 0 0 1 0 ;; 0 1 0 0 0 ;; 0 0 0 0 1 ;; 0 0 1 0 0 ;;... ;; 0 0 1 0 0 ;; 0 0 0 0 1 ;; 0 1 0 0 0 ;; 0 0 0 1 0 ;; 1 0 0 0 0 ;; '(#<void> ;; #<void> ;; #<void> ;; #<void> ;; #<void> ;; #<void> ;; #<void> ;; #<void> ;; #<void> ;; #<void>) (define (display-board size board) (if (null? board) (display "no board") (map (lambda (row) (begin (map (lambda (cv) (begin (display cv) (display " "))) row) (newline))) board))) (display-board 5 (rc-val-board 5 (car (queens 5)))) ;; 1 0 0 0 0 ;; 0 0 0 1 0 ;; 0 1 0 0 0 ;; 0 0 0 0 1 ;; 0 0 1 0 0 ;; '(#<void> #<void> #<void> #<void> #<void>) (define (rc-val-board size board) (if (null? board) nil (map (lambda (r) (map (lambda (c) (rc-val r c board)) (enumerate-interval 1 size))) (enumerate-interval 1 size)))) (define (rc-val-all-boards boards) (if (null? boards) nil (let ((size (length (car boards)))) (map (lambda (b) (rc-val-board size b)) boards)))) (rc-val-all-boards (queens 4)) ;; '(((0 0 1 0) (1 0 0 0) (0 0 0 1) (0 1 0 0)) ;; ((0 1 0 0) (0 0 0 1) (1 0 0 0) (0 0 1 0))) (rc-val-board 5 (car (queens 5))) ;; '((1 0 0 0 0) (0 0 0 1 0) (0 1 0 0 0) (0 0 0 0 1) (0 0 1 0 0)) ;;;--------------------------------- ;;----------------------------- ;; safe ์ •์˜์šฉ ํ•จ์ˆ˜๋“ค (define (occupied-row j positions) (let ((row (filter (lambda (r) (= (caddr r) 1)) (filter-cols j positions)))) (if (null? row) 0 (caar row)))) ;; ํ…Œ์ŠคํŠธ ;; (occupied-row 3 empty-board) ;; (occupied-row 3 test-board) ;; ;; 2 (define (safe-diag? k positions) (let ((cr (occupied-row k positions)) (cc k) (size (length positions))) (and (safe-all-diag? 1 size (- cr 1) (- cc 1) positions) (safe-all-diag? 2 size (+ cr 1) (- cc 1) positions)))) (define (safe-all-diag? dir size cr cc positions) (cond ((or (<= cr 0) (<= cc 0) (> cr size)) #t) ((= (rc-val cr cc positions) 1) #f) (else (if (= dir 1) (safe-all-diag? 1 size (- cr 1) (- cc 1) positions) (safe-all-diag? 2 size (+ cr 1) (- cc 1) positions))))) ;; (define test-board ;; '(((1 1 1) (1 2 1) (1 3 1)) ;; ((2 1 1) (2 2 0) (2 3 0)) ;; ((3 1 1) (3 2 1) (3 3 0)))) ;; (safe-diag? 3 test-board) (define (safe-row? k positions) (let ((cr (occupied-row k positions)) (cc k)) (if (<= cr 0) #t (safe-all-row? cr (- cc 1) positions)))) (define (safe-all-row? cr cc positions) (cond ((<= cc 0) #t) ((= (rc-val cr cc positions) 1) #f) (else (safe-all-row? cr (- cc 1) positions)))) ;; ํ…Œ์ŠคํŠธ ;; (define test-board ;; '(((1 1 1) (1 2 1) (1 3 0)) ;; ((2 1 1) (2 2 0) (2 3 1)) ;; ((3 1 1) (3 2 1) (3 3 0)))) ;; (safe-row? 3 test-board) ;;; ์•„๋ž˜ ์ฝ”๋“œ๋„ ์ œ๋Œ€๋กœ ๋™์ž‘ํ•จ. ;; (define (safe-row? k positions) ;; (if (null? ;; (filter (lambda (x) (not x)) ;; (accumulate append nil ;; (accumulate append nil ;; (map ;; (lambda (r) ;; (map ;; (lambda (c) ;; (if (> k 1) ;; (map ;; (lambda (j) ;; ;; ํ˜„์žฌ (ํ–‰,์—ด)์ด 1์ด๊ณ  ;; ;; ํ˜„์žฌํ–‰, ์ด์ „์—ด์ด 1 ์ด๋ฉด #f ;; (let ((rn (caar r))) ;; (cond ((and (= (rc-val rn k positions) 1) ;; (= (rc-val rn j positions) 1)) ;; #f) ;; (else #t)))) ;; (enumerate-interval 1 (- k 1))) ; 1์—ด๋ถ€ํ„ฐ k-1์—ด๊นŒ์ง€ ;; (list #t))) ;; r)) ;; positions)) ;; ) ;; ) ;; ) ;; #t ;; #f)) ;;----------------------------- ;;;------------------------------------------------ ;;; ํ–‰,์—ด,๊ฐ’ ์ถ”์ถœ ํ•จ์ˆ˜๋“ค ;; (define empty-board ;; (map (lambda (r) ;; (map (lambda (c) (list r c 0)) ;; (enumerate-interval 1 board-size))) ;; (enumerate-interval 1 board-size))) ;; empty-board ;; ;; ((1ํ–‰ : (1ํ–‰ 1์—ด 0๊ฐ’) (...) (...)) ;; ;; (2ํ–‰ : ...) ;; ;; (3ํ–‰ : ...) ) ;; ;;=> ;; ;; '(((1 1 0) (1 2 0) (1 3 0)) ;; ;; ((2 1 0) (2 2 0) (2 3 0)) ;; ;; ((3 1 0) (3 2 0) (3 3 0))) ;; iํ–‰ ๋ฝ‘์•„๋‚ด๊ธฐ (define (filter-rows i positions) (accumulate append nil (filter (lambda (r) (if (= (caar r) i) #t #f)) positions))) ;; ํ…Œ์ŠคํŠธ ;; (filter-rows 1 empty-board) ;; ;; '((1 1 0) (1 2 0) (1 3 0)) ;; j์—ด ๋ฝ‘์•„๋‚ด๊ธฐ (define (filter-cols j positions) (flatmap (lambda (r) (filter (lambda (c) (if (= (cadr c) j) #t #f)) r)) positions)) ;; ํ…Œ์ŠคํŠธ ;; (filter-cols 1 empty-board) ;; ;; '((1 1 0) (2 1 0) (3 1 0)) ;; ;;=> ;; ;; '( (1 1 0) ;; ;; (2 1 0) ;; ;; (3 1 0) ) ;; (filter-cols 2 empty-board) ;; ;; '((1 2 0) (2 2 0) (3 2 0)) ;; ;;=> ;; ;; '( (1 2 0) ;; ;; (2 2 0) ;; ;; (3 2 0) ) ;; (accumulate append nil (filter-cols 1 (list (filter-rows 1 empty-board)))) ;; ;; '(1 1 0) ;; (iํ–‰, j์—ด) ๋ฝ‘์•„๋‚ด๊ธฐ (define (filter-rc i j positions) (accumulate append nil (filter-cols j (list (filter-rows i positions))))) ;; ํ…Œ์ŠคํŠธ ;; (filter-rc 1 1 empty-board) ; '(1 1 0) ;; (filter-rc 2 1 empty-board) ; '(2 1 0) ;; (filter-rc 1 2 empty-board) ; '(1 2 0) ;; iํ–‰ j์—ด์˜ ๊ฐ’ ์–ป๊ธฐ (define (rc-val i j positions) (caddr (filter-rc i j positions))) ;; ํ…Œ์ŠคํŠธ ;; (rc-val 1 1 empty-board) ; 0 ;; (rc-val 1 1 test-board) ; 1 ;;;---------------------------------------------------- ;;;---------------------------------------------------- ;;; empty-board, adjoin-position, queen-cols ํ…Œ์ŠคํŠธ, ์‹คํ—˜ ;;; (define board-size 3) (define (queen-cols k) (if (= k 0) (list empty-board) (flatmap (lambda (rest-of-queens) (map (lambda (new-row) ;; new-row : 1,2,...,borad-size (adjoin-position new-row k rest-of-queens)) (enumerate-interval 1 board-size))) (queen-cols (- k 1))))) (define empty-board (map (lambda (r) (map (lambda (c) (list r c 0)) (enumerate-interval 1 board-size))) (enumerate-interval 1 board-size))) empty-board ;; ((1ํ–‰ : (1ํ–‰ 1์—ด 0๊ฐ’) (...) (...)) ;; (2ํ–‰ : ...) ;; (3ํ–‰ : ...) ) ;;=> ;; '(((1 1 0) (1 2 0) (1 3 0)) ;; ((2 1 0) (2 2 0) (2 3 0)) ;; ((3 1 0) (3 2 0) (3 3 0))) ;; ์ตœ์ดˆ์— empty-board๊ฐ’์ด rest-of-queens์— ;; ์ตœ์ดˆ์— new-row 1, k 1 (define (adjoin-position new-row k rest-of-queens) (map (lambda (r) (if (= (caar r) new-row) ; (caar r) : ํ–‰๋ฒˆํ˜ธ ์ถ”์ถœ (map (lambda (c) (if (= (cadr c) k) ; (cadr c) : ์—ด๋ฒˆํ˜ธ ์ถ”์ถœ (list new-row k 1) ; new-rowํ–‰, k์—ด์— ํ€ธ์„ ๋†“์Œ. c)) ; ๋‚˜๋จธ์ง€ ํ–‰๋ ฌ์€ ๊ทธ๋Œ€๋กœ r) r)) rest-of-queens)) (adjoin-position 1 1 empty-board) ;; '(((1 1 1) (1 2 0) (1 3 0)) ;; ((2 1 0) (2 2 0) (2 3 0)) ;; ((3 1 0) (3 2 0) (3 3 0))) ;; 1ํ–‰ 1์—ด์˜ ๊ฐ’์ด 1๋กœ ์„ค์ •๋จ (adjoin-position 1 2 empty-board) ;; '(((1 1 0) (1 2 1) (1 3 0)) ;; ((2 1 0) (2 2 0) (2 3 0)) ;; ((3 1 0) (3 2 0) (3 3 0))) ;; 1ํ–‰ 2์—ด์˜ ๊ฐ’์ด 1๋กœ ์„ค์ •๋จ ;; k=0 ์ผ ๋•Œ (queen-cols 0) ;; empty-board ;; k=1 ์ผ ๋•Œ (queen-cols 1) ;; '((((1 1 1) (1 2 0) (1 3 0)) ;; ^^^ ;; ((2 1 0) (2 2 0) (2 3 0)) ;; ((3 1 0) (3 2 0) (3 3 0))) ;; ;; ;; (((1 1 0) (1 2 0) (1 3 0)) ;; ((2 1 1) (2 2 0) (2 3 0)) ;; ^^^ ;; ((3 1 0) (3 2 0) (3 3 0))) ;; ;; ;; (((1 1 0) (1 2 0) (1 3 0)) ;; ((2 1 0) (2 2 0) (2 3 0)) ;; ((3 1 1) (3 2 0) (3 3 0)))) ;; ^^^ ;; 1ํ–‰ 1์—ด์˜ ๊ฐ’์ด 1๋กœ ์„ค์ •๋œ board ;; 2ํ–‰ 1์—ด์˜ ๊ฐ’์ด 1๋กœ ์„ค์ •๋œ board ;; 3ํ–‰ 1์—ด์˜ ๊ฐ’์ด 1๋กœ ์„ค์ •๋œ board ;; => ;; 1์—ด์—์„œ ๊ฐ ํ–‰์— ํ€ธ์„ ์œ„์น˜์‹œ์ผœ๋ณด๋Š” ์…ˆ์ด๋‹ค. ;; k์—ด์˜ rํ–‰์ด 1์ผ ๋•Œ ;; k-1์—ด์˜ rํ–‰์ด 0์ด๊ณ , ;; r-1ํ–‰์ด 0์ด๊ณ , ;; r+1ํ–‰์ด 0์ด๋ฉด ์•ˆ์ „ํ•˜๋‹ค ;; (2์—ด ์ด์ „, ๋Œ€๊ฐ์„ ์— ๋Œ€ํ•ด์„œ ์™„์ „ํ•˜์ง€ ์•Š๋‹ค.) (define (safe? k positions) ;; (if (null? ;; (filter (lambda (x) (not x)) ;; (accumulate append nil (map (lambda (r) (map (lambda (c) (let ((rn (caar r))) ;; ํ˜„์žฌ ํ–‰,์—ด์ด 1์ด๊ณ  ;; ํ˜„์žฌํ–‰, ์ด์ „์—ด์ด 1 ์ด๋ฉด #f (cond ((and (> k 1) (= (rc-val rn k positions) 1) (= (rc-val rn (- k 1) positions) 1)) #f) (else #t)))) r)) positions)) ;; )) ;; #t ;; #f)) ;;; ;;;----------------------------------------------- ;;;--------------------------< ex 2.43 >-------------------------- ;;; p164,5 ;;; ๋‚˜์ค‘์—.. ;;;;==============<ch 2.2.4 ์—ฐ์Šต : ๊ทธ๋ฆผ ์–ธ์–ด>================== ;;; p165 ;;;;;;;;;;;;;;;;;;;;;; ;;; ๊ทธ๋ฆผ ์–ธ์–ด ;; wave ; ๊ทธ๋ฆผ ;; beside ; ์ขŒ,์šฐ ;; below ; ์œ„,์•„๋ž˜ ;; flip-vert ; ์œ„์•„๋ž˜ ๋’ค์ง‘๊ธฐ ;; flip-horiz ; ์˜†์œผ๋กœ ๋’ค์ง‘๊ธฐ ;;----------------------------- (define (beside pa1 pa2) nil) (define (below pa1 pa2) nil) (define (flip-vert pa) nil) (define (flip-horiz pa) nil) (define wave nil) ;;----------------------------- (define wave2 (beside wave (flip-vert wave))) (define wave4 (below wave2 wave2)) ;; p170 (define (flipped-pairs painter) (let ((painter2 (beside painter (flip-vert painter)))) (below painter2 painter2))) (define wave4 (flipped-pairs wave)) ;; p171 (define (right-split painter n) (if (= n 0) painter (let ((smaller (right-split painter (- n 1)))) (beside painter (below smaller smaller))))) ;; p172 (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)))) ;;;--------------------------< ex 2.44 >-------------------------- ;;; p172 (define (up-split painter n) (if (= n 0) painter (let ((smaller (up-split painter (- n 1)))) (below (beside smaller smaller) painter)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ์ฐจ์ˆ˜ ๋†’์€ ์—ฐ์‚ฐ ;;; p172 ;;; p173 ;;; ํŽ˜์ธํ„ฐ ์—ฐ์‚ฐ ๋„ค ๊ฐœ๋ฅผ ๋ฐ›์•„์„œ ์ œ๊ฐ๊ธฐ ํŽ˜์ธํ„ฐ์— ์ ์šฉํ•œ ๋‹ค์Œ ;;; ๊ทธ ๊ฒฐ๊ณผ๋ฅผ ๋„ค๋ชจ ์•ˆ์— ์ฑ„์šฐ๊ธฐ (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)))) ;; square-of-four๋ฅผ ์จ์„œ filpped-pairs, square-limit ์žฌ์ •์˜ (define (flipped-pairs painter) (let ((combine4 (square-of-four identity flip-vert identity flip-vert))) (combine4 painter))) (define (square-limit painter n) (let ((combine4 (square-of-four flip-horiz identity rotate180 flip-vert))) (combine4 (corner-split painter n)))) ;;;--------------------------< ex 2.45 >-------------------------- ;;; p173,4 (define (split p1 p2) (define n 10) (define (split-inner painter p1 p2 k) (if (= k 0) painter (let ((smaller (split-inner painter p1 p2 (- k 1)))) (p1 painter (p2 smaller smaller))))) (lambda (painter) (split-inner painter p1 p2 n))) (define right-split (split beside below)) (define up-split (split below beside)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ๊ทธ๋ฆผํ‹€ ;;; p174 (define (frame-coord-map frame) (lambda (v) (add-vect (origin-frame frame) (add-vect (scale-vect (xcor-vect v) (edge1-frame frame)) (scale-vect (ycor-vect v) (edge2-frame frame)))))) ((frame-coord-map a-frame) (make-vect 0 0)) (origin-frame a-frame) ;;;--------------------------< ex 2.46 >-------------------------- ;;; p176 (define (make-rect x y) (cons x y)) (define (xcor-vect v) (car v)) (define (ycor-vect v) (cdr v)) (define (add-vect v1 v2) (make-rect (+ (xcor-vect v1) (xcor-vect v2)) (+ (ycor-vect v1) (ycor-vect v2)))) (define (sub-vect v1 v2) (make-rect (- (xcor-vect v1) (xcor-vect v2)) (- (ycor-vect v1) (ycor-vect v2)))) (define (scale-vect s v) (make-rect (* s (xcor-vect v)) (* s (ycor-vect v)))) ;;;--------------------------< ex 2.47 >-------------------------- ;;; p176 ;;;------------ (define (make-frame origin edge1 edge2) (list origin edge1 edge2)) (define (origin-frame frame) (car frame)) (define (edge1-frame frame) (cadr frame)) (define (edge2-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)) ;;;------------ ;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ํŽ˜์ธํ„ฐ ;;; p176 (define (segments->painter segment-list) (lambda (frame) (for-each (lambda (segment) (draw-line ((frame-coord-map frame) (start-segment segment)) ((frame-coord-map frame) (end-segment segment)))) segment-list))) ;;;--------------------------< ex 2.48 >-------------------------- ;;; p178 (define (make-segment sx sy ex ey) (list (make-rect sx sy) (make-rect ex ey))) (make-segment 0 1 1 2) ; '((0 . 1) (1 . 2)) (define (start-segment seg) (car seg)) (start-segment (make-segment 0 1 1 2)) ; '(0 . 1) (define (end-segment seg) (cadr seg)) (end-segment (make-segment 0 1 1 2)) ; '(1 . 2) ;;;--------------------------< ex 2.49 >-------------------------- ;;; p178 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ํŽ˜์ธํ„ฐ๋ฅผ ๋ณ€ํ™˜ํ•ด์„œ ์—ฎ์–ด์“ฐ๋Š” ๋ฐฉ๋ฒ• ;;; p178 (define (transform-painter painter origin corner1 corner2) (lambda (frame) (let ((m (frame-coord-map frame))) (let ((new-origin (m origin))) (painter (make-frame new-origin (sub-vect (m corner1) new-origin) (sub-vect (m corner2) new-origin))))))) ;;; ํŽ˜์ธํ„ฐ ๊ทธ๋ฆผ์„ ์ˆ˜์ง์œผ๋กœ ๋’ค์ง‘๊ธฐ (define (flip-vert painter) (transform-painter painter (make-vect 0.0 1.0) ; ์ƒˆ origin (make-vect 1.0 1.0) ; edge1์˜ ์ƒˆ ๋์  (make-vect 0.0 1.0))) ; edge2์˜ ์ƒˆ ๋์  ;;; 1 ์‚ฌ๋ถ„๋ฉด์— ๋งž์ถ”์–ด ์ค„์ด๋Š” ํŽ˜์ธํ„ฐ (define (shrink-to-upper-right painter) (transform-painter painter (make-vect 0.5 0.5) (make-vect 1.0 0.5) (make-vect 0.5 1.0))) ;;; ์‹œ๊ณ„ ๋ฐฉํ–ฅ์œผ๋กœ 90๋„ ๋Œ๋ฆฌ๋Š” ์—ฐ์‚ฐ (define (rotate90 painter) (transform-painter painter (make-vect 1.0 0.0) (make-vect 1.0 1.0) (make-vect 0.0 0.0))) ;;; ์ •ํ•ด์ง„ ํ‹€ ๊ฐ€์šด๋ฐ๋กœ ๊ทธ๋ฆผ์„ ์ฐŒ๊ทธ๋Ÿฌ๋œจ๋ฆฌ๋Š” ์—ฐ์‚ฐ (define (squash-inwards painter) (transform-painter painter (make-vect 0.0 0.0) (make-vect 0.65 0.35) (make-vect 0.35 0.65))) ;;; beside ๋‹ค์‹œ (define (beside painter1 painter2) (let ((split-point (make-vect 0.5 0.0))) (let ((paint-left (transform-painter painter1 (make-vect 0.0 0.0) split-point (make-vect 0.0 1.0))) (paint-right (transform-painter painter2 split-point (make-vect 1.0 0.0) (make-vect 0.5 1.0)))) (lambda (frame) (paint-left frame) (paint-right frame))))) ;;;--------------------------< ex 2.50 >-------------------------- ;;; p181 ;;; flip-horiz ;;; 180๋„ ํšŒ์ „ ;;; 270๋„ ํšŒ์ „ ;;;--------------------------< ex 2.51 >-------------------------- ;;; p181 ;;; below ;;;1. beside ์ฒ˜๋Ÿผ ;;;2. beside ์™€ ๋Œ๋ฆฌ๋Š” ์—ฐ์‚ฐ์„ ์จ์„œ\ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ๋‹จ๋‹จํ•˜๊ฒŒ ์„ค๊ณ„ํ•  ๋•Œ ์“ฐ๋Š” ์–ธ์–ด ๊ณ„์ธต ;;; p181 ;;;--------------------------< ex 2.52 >-------------------------- ;;; p183
false