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
0f53698a8dc853105b3e8dbadff0e35c6a672a7e
72bf2fe3779f38fff065810eeb958dbb903dc1d0
/lib/core/scalability/primitives.scm
ccc5fe63bd3a0c4a39ba4bc009ac4cc898821d2b
[ "BSD-2-Clause" ]
permissive
thunknyc/patchbay
4ad9813fc35db7155836b9677ef13a29b5e91ed2
038c4f0f690875165ffaba6c32cdeb76fc1bb8de
refs/heads/master
2021-01-10T02:37:57.442206
2015-12-16T14:55:10
2015-12-16T14:55:10
47,904,530
0
0
null
null
null
null
UTF-8
Scheme
false
false
6,652
scm
primitives.scm
(define-module (core scalability primitives) #:use-module (system foreign) #:use-module (rnrs bytevectors) #:use-module (core combinators) #:use-module (core foreign) #:replace (socket bind connect shutdown recv send close) #:export (bus-socket pair-socket pipeline-push-socket pipeline-pull-socket pubsub-pub-socket pubsub-sub-socket survey-respondent-socket survey-surveyor-socket reqrep-request-socket reqrep-reply-socket set-send-timeout set-recv-timeout set-linger set-surveyor-deadline set-reqrep-reply-resend-interval subscribe subscribe* unsubscribe shutdown send-string freemsg errno eagain?)) (define nanomsg-func (partial lib-func (dynamic-link "libnanomsg"))) (define EAGAIN 35) (define ETIMEDOUT 60) (define AF_SP 1) (define NN_SOL_SOCKET 0) ;;; For `setsockopt` (define NN_LINGER 1) (define NN_SNDBUF 2) (define NN_RCVBUF 3) (define NN_SNDTIMEO 4) (define NN_RCVTIMEO 5) (define NN_RECONNECT_IVL 6) (define NN_RECONNECT_IVL_MAX 7) (define NN_SNDPRIO 8) (define NN_RCVPRIO 9) (define NN_SNDFD 10) (define NN_RCVFD 11) (define NN_DOMAIN 12) (define NN_PROTOCOL 13) (define NN_IPV4ONLY 14) (define NN_SOCKET_NAME 15) (define NN_RCVMAXSIZE 16) (define NN_MSG -1) (define NN_PROTO_PAIR 1) (define NN_PAIR (+ (* NN_PROTO_PAIR 16) 0)) (define NN_PROTO_PUBSUB 2) (define NN_PUB (+ (* NN_PROTO_PUBSUB 16) 0)) (define NN_SUB (+ (* NN_PROTO_PUBSUB 16) 1)) (define NN_SUB_SUBSCRIBE 1) (define NN_SUB_UNSUBSCRIBE 2) (define NN_PROTO_REQREP 3) (define NN_REQ (+ (* NN_PROTO_REQREP 16) 0)) (define NN_REP (+ (* NN_PROTO_REQREP 16) 1)) (define NN_REQ_RESEND_IVL 1) (define NN_PROTO_PIPELINE 5) (define NN_PUSH (+ (* NN_PROTO_PIPELINE 16) 0)) (define NN_PULL (+ (* NN_PROTO_PIPELINE 16) 1)) (define NN_PROTO_SURVEY 6) (define NN_SURVEYOR (+ (* NN_PROTO_SURVEY 16) 2)) (define NN_RESPONDENT (+ (* NN_PROTO_SURVEY 16) 3)) (define NN_SURVEYOR_DEADLINE 1) (define NN_PROTO_BUS 7) (define NN_BUS (+ (* NN_PROTO_BUS 16) 0)) (define (make-null-pointer) (bytevector->pointer (make-bytevector (sizeof size_t) 0))) ;;; int nn_setsockopt (int s, int level, int option, ;;; const void *optval, size_t optvallen); (define nn-setsockopt (nanomsg-func int "nn_setsockopt" int int int '* size_t)) (define (setsockopt s level option opt-val-bytevector) (if (null? opt-val-bytevector) (zero? (nn-setsockopt s level option (dereference-pointer (make-null-pointer)) 0)) (let* ((opt-val-ptr (bytevector->pointer opt-val-bytevector)) (opt-val-len (bytevector-length opt-val-bytevector))) (zero? (nn-setsockopt s level option opt-val-ptr opt-val-len))))) (define (setsockopt-string s level option value) (let ((v (string->utf8 value))) (setsockopt s level option v))) (define (setsockopt-int s level option value) (let ((v (make-bytevector (sizeof int)))) (bytevector-s32-native-set! v 0 value) (setsockopt s level option v))) (define (subscribe-1 s topic) (setsockopt-string s NN_SUB NN_SUB_SUBSCRIBE topic)) (define (subscribe s . topics) (let loop ((topics topics)) (cond ((null? topics) #t) ((subscribe-1 s (car topics)) (loop (cdr topics))) (else #f)))) (define (subscribe* s topics) (apply subscribe s topics)) (define (unsubscribe-1 s topic) (setsockopt-string s NN_SUB NN_SUB_UNSUBSCRIBE topic)) (define (unsubscribe s . topics) (let loop ((topics topics)) (cond ((null? topics) #t) ((unsubscribe-1 s (car topics)) (loop (cdr topics))) (else #f)))) (define (set-linger s millis) (setsockopt-int s NN_SOL_SOCKET NN_LINGER millis)) (define (set-send-timeout s millis) (setsockopt-int s NN_SOL_SOCKET NN_SNDTIMEO millis)) (define (set-recv-timeout s millis) (setsockopt-int s NN_SOL_SOCKET NN_RCVTIMEO millis)) (define (set-surveyor-deadline s millis) (setsockopt-int s NN_SURVEYOR NN_SURVEYOR_DEADLINE millis)) (define (set-reqrep-reply-resend-interval s millis) (setsockopt-int s NN_PROTO_REQREP NN_REQ_RESEND_IVL millis)) ;;; int nn_socket (int domain, int protocol); (define nn-socket (nanomsg-func int "nn_socket" int int)) (define (socket domain protocol) (let ((sock (nn-socket domain protocol))) (if (>= sock 0) sock #f))) (define (pipeline-push-socket) (socket AF_SP NN_PUSH)) (define (pipeline-pull-socket) (socket AF_SP NN_PULL)) (define (pubsub-pub-socket) (socket AF_SP NN_PUB)) (define (pubsub-sub-socket) (socket AF_SP NN_SUB)) (define (bus-socket) (socket AF_SP NN_BUS)) (define (survey-surveyor-socket) (socket AF_SP NN_SURVEYOR)) (define (survey-respondent-socket) (socket AF_SP NN_RESPONDENT)) (define (pair-socket) (socket AF_SP NN_PAIR)) (define (reqrep-request-socket) (socket AF_SP NN_REQ)) (define (reqrep-reply-socket) (socket AF_SP NN_REP)) ; int nn_bind (int s, const char *addr); (define nn-bind (nanomsg-func int "nn_bind" int '*)) (define (bind s addr) (nn-bind s (string->pointer addr))) ; int nn_connect (int s, const char *addr); (define nn-connect (nanomsg-func int "nn_connect" int '*)) (define (connect s addr) (nn-connect s (string->pointer addr))) ; int nn_shutdown (int s, int how); (define nn-shutdown (nanomsg-func int "nn_shutdown" int int)) (define (shutdown s how) (>= (nn-shutdown s how) 0)) ; int nn_close (int s); (define nn-close (nanomsg-func int "nn_close" int)) (define (close s) (>= (nn-close s) 0)) ; int nn_send (int s, const void *buf, size_t len, int flags); (define nn-send (nanomsg-func int "nn_send" int '* size_t int)) (define (send s msg) (let* ((len (bytevector-length msg)) (bytes (nn-send s (bytevector->pointer msg) len 0))) (if (>= bytes 0) bytes #f))) (define (send-string s msg) (send s (string->utf8 msg))) ; int nn_recv (int s, void *buf, size_t len, int flags); (define nn-recv (nanomsg-func int "nn_recv" int '* ssize_t int)) ; int nn_freemsg (void *msg); (define nn-freemsg (nanomsg-func int "nn_freemsg" '*)) (define (recv s) (let* ((msg-ptr (make-null-pointer)) (bytes (nn-recv s msg-ptr NN_MSG 0))) (if (>= bytes 0) (pointer->bytevector (dereference-pointer msg-ptr) bytes) #f))) (define (freemsg msg) (nn-freemsg (bytevector->pointer msg))) ;;; int nn_errno (void); (define nn-errno (nanomsg-func int "nn_errno")) (define errno nn-errno) (define (eagain?) (let ((err (errno))) (or (= err EAGAIN) (= err ETIMEDOUT))))
false
a3aa4ae0841025b4f87523bf7449f5de73372ce9
d074b9a2169d667227f0642c76d332c6d517f1ba
/sicp/ch_5/exercise.5.41.scm
5f95ba5ebe1e9f95802db779ca7adb26f2e2d8bb
[]
no_license
zenspider/schemers
4d0390553dda5f46bd486d146ad5eac0ba74cbb4
2939ca553ac79013a4c3aaaec812c1bad3933b16
refs/heads/master
2020-12-02T18:27:37.261206
2019-07-14T15:27:42
2019-07-14T15:27:42
26,163,837
7
0
null
null
null
null
UTF-8
Scheme
false
false
1,149
scm
exercise.5.41.scm
#!/usr/bin/env csi -s (require rackunit) (use srfi-1) ;;; Exercise 5.41 ;; Write a procedure `find-variable' that takes as arguments a ;; variable and a compile-time environment and returns the lexical ;; address of the variable with respect to that environment. For ;; example, in the program fragment that is shown above, the ;; compile-time environment during the compilation of expression <E1> ;; is `((y z) (a b c d e) (x y))'. `Find-variable' should produce ;; ;; (find-variable 'c '((y z) (a b c d e) (x y))) ;; (1 2) ;; ;; (find-variable 'x '((y z) (a b c d e) (x y))) ;; (2 0) ;; ;; (find-variable 'w '((y z) (a b c d e) (x y))) ;; not-found ;; Sucks because there is no way to get obj + index via a findy function (define (find-variable var env) (let ((y (list-index (lambda (l) (member var l)) env))) (if y (list y (list-index (lambda (x) (eq? var x)) (list-ref env y))) 'not-found))) (let ((env '((y z) (a b c d e) (x y)))) (test '(1 2) (find-variable 'c env)) (test '(2 0) (find-variable 'x env)) (test 'not-found (find-variable 'w env)))
false
d950360cd6e61887804b8e035a616d3740f4f5a0
d7a69a0e464473bf2699b8370682080c18c6ff93
/test/runtests.scm
e8331d3d73f3d71786e7df9bfcf966086c5d5e09
[ "MIT" ]
permissive
leftmike/foment
08ecd44cd5327f00d0fc32d197e0903dd3d2f123
6089c3c9e762875f619ef382d27943819bbe002b
refs/heads/master
2022-09-19T00:53:49.568819
2022-09-07T04:46:36
2022-09-07T04:46:36
52,575,413
72
9
MIT
2022-08-28T15:33:02
2016-02-26T03:21:58
C++
UTF-8
Scheme
false
false
3,115
scm
runtests.scm
;; ;; A program to run the tests. ;; ;; foment runtests.scm <test> ... ;; (import (foment base)) (define pass-count 0) (define fail-count 0) (define (run-tests lst) (define (fail obj ret) (set! fail-count (+ fail-count 1)) (display "failed: ") (write obj) (display ": ") (write ret) (newline)) (let ((env (interaction-environment '(scheme base)))) (define (check-equal? a b) (if (equal? a b) #t (if (and (number? a) (inexact? a) (number? b) (inexact? b)) (equal? (number->string a) (number->string b)) #f))) (define (test-check-equal obj) (let ((ret (eval (caddr obj) env))) (if (check-equal? (unsyntax (cadr obj)) ret) (set! pass-count (+ pass-count 1)) (fail obj ret)))) (define (test-check-error obj) (guard (exc ((error-object? exc) (let ((want (unsyntax (cadr obj)))) (if (or (not (equal? (car want) (error-object-type exc))) (and (pair? (cdr want)) (not (equal? (cadr want) (error-object-who exc))))) (fail obj exc) (set! pass-count (+ pass-count 1))))) (else (fail obj exc))) (eval (caddr obj) env) (fail obj "no exception raised"))) (define (test-when obj) (define (test-list lst) (when (pair? lst) (test-expr (car lst)) (test-list (cdr lst)))) (if (eval (cadr obj) env) (test-list (cddr obj)))) (define (test-expr obj) (cond ((and (pair? obj) (eq? (unsyntax (car obj)) 'check-equal)) (test-check-equal obj)) ((and (pair? obj) (eq? (unsyntax (car obj)) 'check-error)) (test-check-error obj)) ((and (pair? obj) (eq? (unsyntax (car obj)) 'check-syntax)) (test-check-error obj)) ((and (pair? obj) (eq? (unsyntax (car obj)) 'test-when)) (test-when obj)) (else (eval obj env)))) (define (test port) (let ((obj (read port))) (when (not (eof-object? obj)) (test-expr obj) (test port)))) (define (run name) (let ((port (open-input-file name))) (want-identifiers port #t) (call-with-port port test))) (if (not (null? lst)) (begin (display (car lst)) (newline) (run (car lst)) (run-tests (cdr lst)))))) (run-tests (cdr (command-line))) (when (> fail-count 0) (newline) (write (features)) (newline) (write (config)) (newline)) (display "pass: ") (display pass-count) (display " fail: ") (display fail-count) (newline)
false
25437dc138f18f69a0e282fb2d3cd53b5a3dcc10
4b5dddfd00099e79cff58fcc05465b2243161094
/chapter_3/exercise_3_22.scm
64371d5b22d6dcd31c327b4cd0bf8e65e2789a43
[ "MIT" ]
permissive
hjcapple/reading-sicp
c9b4ef99d75cc85b3758c269b246328122964edc
f54d54e4fc1448a8c52f0e4e07a7ff7356fc0bf0
refs/heads/master
2023-05-27T08:34:05.882703
2023-05-14T04:33:04
2023-05-14T04:33:04
198,552,668
269
41
MIT
2022-12-20T10:08:59
2019-07-24T03:37:47
Scheme
UTF-8
Scheme
false
false
1,974
scm
exercise_3_22.scm
#lang sicp ;; P183 - [练习 3.22] (define (make-queue) (let ((front-ptr '()) (rear-ptr '())) (define (set-front-ptr! item) (set! front-ptr item)) (define (set-rear-ptr! item) (set! rear-ptr item)) (define (empty-queue?) (null? front-ptr)) (define (front-queue) (if (empty-queue?) (error "FRONT called with an empty queue" dispatch) (car front-ptr))) (define (insert-queue! item) (let ((new-pair (cons item '()))) (cond ((empty-queue?) (set-front-ptr! new-pair) (set-rear-ptr! new-pair) dispatch) (else (set-cdr! rear-ptr new-pair) (set-rear-ptr! new-pair) dispatch)))) (define (delete-queue!) (cond ((empty-queue?) (error "DELETE! called with an empty queue" dispatch)) (else (set-front-ptr! (cdr front-ptr)) dispatch))) (define (print-queue) (display front-ptr) (newline)) (define (dispatch m) (cond ((eq? m 'front-ptr) front-ptr) ((eq? m 'insert-queue!) insert-queue!) ((eq? m 'delete-queue!) delete-queue!) ((eq? m 'print-queue) print-queue) (else (error "Undefined operation -- MAKE-QUEUE" m)))) dispatch)) (define (front-queue queue) ((queue 'front-queue))) (define (insert-queue! queue item) ((queue 'insert-queue!) item)) (define (delete-queue! queue) ((queue 'delete-queue!))) (define (print-queue queue) ((queue 'print-queue))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define q1 (make-queue)) (insert-queue! (insert-queue! (insert-queue! q1 'a) 'b) 'c) (print-queue q1) ; (a b c) (insert-queue! q1 'd) (print-queue q1) ; (a b c d) (delete-queue! q1) (print-queue q1) ; (b c d) (delete-queue! q1) (print-queue q1) ; (c d) (delete-queue! (delete-queue! q1)) (print-queue q1) ; ()
false
58d0b9580525eedfb80902bf6a7a2ee22520406f
4b480cab3426c89e3e49554d05d1b36aad8aeef4
/misc/debug-display-sample.scm
0641ca23c31bd1c00c23b52b6de1d3699cb37cc6
[]
no_license
tuestudy/study-sicp
a5dc423719ca30a30ae685e1686534a2c9183b31
a2d5d65e711ac5fee3914e45be7d5c2a62bfc20f
refs/heads/master
2021-01-12T13:37:56.874455
2016-10-04T12:26:45
2016-10-04T12:26:45
69,962,129
0
0
null
null
null
null
UTF-8
Scheme
false
false
326
scm
debug-display-sample.scm
(load "../misc/debug-display.scm") (define (fact n) (define (fact-iter x result) (debug-display (list "fact-iter" "x =" x "result =" result)) (if (= x 0) result (fact-iter (- x 1) (* result x)))) (fact-iter n 1)) (set-enable-debug-display #t) (fact 10) (set-enable-debug-display #f) (fact 5)
false
baf8342e1a3a769a697884558316d3e61bfc1e86
923209816d56305004079b706d042d2fe5636b5a
/sitelib/http/header-field/accept.scm
9e42c457044bd47e7d9842227087a1ad725bc048
[ "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
1,021
scm
accept.scm
(library (http header-field accept) (export Accept accept-params) (import (rnrs (6)) (http abnf) (only (http basic-rule) quoted-string token) (http media-type) (http parameter) (http quality-value)) ;;; 14.1 Accept (define accept-extension (seq (char->rule #\;) token (opt (seq (char->rule #\=) (bar token quoted-string))))) (define accept-params (seq (char->rule #\;) *LWS ; implied *LWS (char->rule #\q) (char->rule #\=) qvalue (rep* accept-extension))) (define media-range (let ((/ (char->rule #\/)) (* (char->rule #\*))) (seq (bar (string->rule "*/*") (seq type / *) (seq type / subtype)) (rep* (seq (char->rule #\;) parameter))))) (define Accept (seq (string->rule "Accept") (char->rule #\:) (num* (seq media-range (opt accept-params))))) )
false
e65c64c02952805a546471f467f44e6f98f76cd8
6b961ef37ff7018c8449d3fa05c04ffbda56582b
/bbn_cl/mach/zcomp/rtlopt/ralloc.scm
6629742ef905cedd0e1e90bc9a0d3cbf8a1eb057
[]
no_license
tinysun212/bbn_cl
7589c5ac901fbec1b8a13f2bd60510b4b8a20263
89d88095fc2a71254e04e57cf499ae86abf98898
refs/heads/master
2021-01-10T02:35:18.357279
2015-05-26T02:44:00
2015-05-26T02:44:00
36,267,589
4
3
null
null
null
null
UTF-8
Scheme
false
false
5,232
scm
ralloc.scm
#| -*-Scheme-*- $Header: ralloc.scm,v 1.2 88/08/31 10:43:36 jinx Exp $ $MIT-Header: ralloc.scm,v 1.13 87/10/05 20:21:30 GMT jinx Exp $ Copyright (c) 1987 Massachusetts Institute of Technology This material was developed by the Scheme project at the Massachusetts Institute of Technology, Department of Electrical Engineering and Computer Science. Permission to copy this software, to redistribute it, and to use it for any purpose is granted, subject to the following restrictions and understandings. 1. Any copy made of this software must include this copyright notice in full. 2. Users of this software agree to make their best efforts (a) to return to the MIT Scheme project any improvements or extensions that they make, so that these may be included in future releases; and (b) to inform MIT of noteworthy uses of this software. 3. All materials developed as a consequence of the use of this software shall duly acknowledge such use, in accordance with the usual standards of acknowledging credit in academic research. 4. MIT has made no warrantee or representation that the operation of this software will be error-free, and MIT is under no obligation to provide any services, by way of maintenance, update, or otherwise. 5. In conjunction with products arising from the use of this material, there shall be no use of the name of the Massachusetts Institute of Technology nor of any adaptation thereof in any advertising, promotional, or sales literature without prior written consent from MIT in each case. |# ;;;; Register Allocation ;;; Based on the GNU C Compiler (declare (usual-integrations)) (package (register-allocation) (define (register-allocation rgraphs) (for-each walk-rgraph rgraphs)) (define (walk-rgraph rgraph) (let ((n-registers (rgraph-n-registers rgraph))) (set-rgraph-register-renumber! rgraph (make-vector n-registers false)) (fluid-let ((*current-rgraph* rgraph)) (walk-bblocks n-registers (let ((bblocks (rgraph-bblocks rgraph))) (set-rgraph-bblocks! rgraph false) bblocks))))) (define (walk-bblocks n-registers bblocks) ;; First, renumber all the registers remaining to be allocated. (let ((next-renumber 0) (register->renumber (make-vector n-registers false))) (define (renumbered-registers n) (if (< n n-registers) (if (vector-ref register->renumber n) (cons n (renumbered-registers (1+ n))) (renumbered-registers (1+ n))) '())) (for-each-pseudo-register (lambda (register) (if (positive? (register-n-refs register)) (begin (vector-set! register->renumber register next-renumber) (set! next-renumber (1+ next-renumber)))))) ;; Now create a conflict matrix for those registers and fill it. (let ((conflict-matrix (make-initialized-vector next-renumber (lambda (i) (make-regset next-renumber))))) (for-each (lambda (bblock) (let ((live (make-regset next-renumber))) (for-each-regset-member (bblock-live-at-entry bblock) (lambda (register) (let ((renumber (vector-ref register->renumber register))) (if renumber (regset-adjoin! live renumber))))) (bblock-walk-forward bblock (lambda (rinst) (for-each-regset-member live (lambda (renumber) (regset-union! (vector-ref conflict-matrix renumber) live))) (for-each (lambda (register) (let ((renumber (vector-ref register->renumber register))) (if renumber (regset-delete! live renumber)))) (rinst-dead-registers rinst)) (mark-births! live (rinst-rtl rinst) register->renumber))))) bblocks) ;; Finally, sort the renumbered registers into an allocation ;; order, and then allocate them into registers one at a time. ;; Return the number of required real registers as a value. (let ((next-allocation 0) (allocated (make-vector next-renumber 0))) (for-each (lambda (register) (let ((renumber (vector-ref register->renumber register))) (define (loop allocation) (if (< allocation next-allocation) (if (regset-disjoint? (vector-ref conflict-matrix renumber) (vector-ref allocated allocation)) allocation (loop (1+ allocation))) (let ((allocation next-allocation)) (set! next-allocation (1+ next-allocation)) (vector-set! allocated allocation (make-regset next-renumber)) allocation))) (let ((allocation (loop 0))) (set-register-renumber! register allocation) (regset-adjoin! (vector-ref allocated allocation) renumber)))) (sort (renumbered-registers number-of-machine-registers) allocate<?)) next-allocation)))) (define (allocate<? x y) (< (/ (register-n-refs x) (register-live-length x)) (/ (register-n-refs y) (register-live-length y)))) (define (mark-births! live rtl register->renumber) (if (rtl:assign? rtl) (let ((address (rtl:assign-address rtl))) (if (rtl:register? address) (let ((register (rtl:register-number address))) (if (pseudo-register? register) (regset-adjoin! live (vector-ref register->renumber register)))))))) )
false
600a8268badc085472b69cd562f6f5d0f8301daa
bcfa2397f02d5afa93f4f53c0b0a98c204caafc1
/scheme/lib/scheme_init.sch
843aea580c55f92ce702d519423b07bd200edf9f
[]
no_license
rahulkumar96/sicp-study
ec4aa6e1076b46c47dbc7a678ac88e757191c209
4dcd1e1eb607aa1e32277e1c232a321c5de9c0f0
refs/heads/master
2020-12-03T00:37:39.576611
2017-07-05T12:58:48
2017-07-05T12:58:48
96,050,670
0
0
null
2017-07-02T21:46:09
2017-07-02T21:46:09
null
UTF-8
Scheme
false
false
494
sch
scheme_init.sch
;; -*- scheme-mode -*- ;; I have a symlink from ~/.scheme.init to this file. MIT Scheme will ;; load this file automatically when it is starts up. (set-environment-variable! "TESTING_SCM" "/Users/jim/pgm/sicp/jimweirich/scheme/lib/testing.scm") ;; Load the testing tools. (define (testing) (load (get-environment-variable "TESTING_SCM"))) ;; Short cut for running tests. (define (t) (tests)) ;; Short cut for aborting after failures. (define (r) (restart 1))
false
2f417295e7816dc46f56c3a24b4e35c717d2a85b
37245ece3c767e9434a93a01c2137106e2d58b2a
/tests/test-program.scm
91107155e7dd47d8cc2d6d80cac10b855f4d5041
[ "MIT" ]
permissive
mnieper/unsyntax
7ef93a1fff30f20a2c3341156c719f6313341216
144772eeef4a812dd79515b67010d33ad2e7e890
refs/heads/master
2023-07-22T19:13:48.602312
2021-09-01T11:15:54
2021-09-01T11:15:54
296,947,908
12
0
null
null
null
null
UTF-8
Scheme
false
false
2,859
scm
test-program.scm
;; Copyright © Marc Nieper-Wißkirchen (2020). ;; This file is part of unsyntax. ;; 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 (including the ;; next paragraph) 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. (import (scheme base) (scheme eval) (srfi 64) (srfi 211 syntax-case) (srfi 213) (example library) (example library-import-only) (for (example r6rs-library ((<= 6))) run expand (meta -1)) (rename (unsyntax) (import import-module))) (import (rename (scheme base) (define import))) (import quux 'import) (test-begin "Compiler Test") (test-equal 'import quux) (test-assert (memq 'test (features))) (test-equal 42 foo) (test-equal 'bar (bar)) (test-equal 42 (eval 'foo (environment '(example library)))) (test-equal 'bar (eval '(bar) (environment '(example library)))) (test-equal "the-answer" (let-syntax ((get-the-answer (lambda (stx) (lambda (lookup) #`'#,(datum->syntax #'* (lookup #'foo #'*)))))) (get-the-answer))) (test-equal "the-answer" (eval '(let-syntax ((get-the-answer (lambda (stx) (lambda (lookup) #`'#,(datum->syntax #'* (lookup #'foo #'*)))))) (get-the-answer)) (environment '(scheme base) '(example library) '(srfi 211 syntax-case)))) (test-equal 42 (let-syntax ((foo (lambda (stx) meta-foo))) foo)) (test-equal 'apple (let () (define-apple apple) apple)) (test-equal 'pear (let () (import-module fruits) pear)) (test-equal 'after-barrier barrier-x) (test-equal 3 (let* () (import-module (rename (library (scheme base)) (+ plus))) (plus 1 2))) (test-equal 9 (let* () (import-module (example library-local)) (sq 3))) (test-end)
false
bdba425fdb8644c725c1060bd8f8f19edc18e63c
abc7bd420c9cc4dba4512b382baad54ba4d07aa8
/src/old/plt/regmodule.ss
ee66c94e26cfa82b29db0b660bc5f30edb37b52d
[ "BSD-3-Clause" ]
permissive
rrnewton/WaveScript
2f008f76bf63707761b9f7c95a68bd3e6b9c32ca
1c9eff60970aefd2177d53723383b533ce370a6e
refs/heads/master
2021-01-19T05:53:23.252626
2014-10-08T15:00:41
2014-10-08T15:00:41
1,297,872
10
2
null
null
null
null
UTF-8
Scheme
false
false
306
ss
regmodule.ss
(module regmodule mzscheme (require) (provide chezimports chezprovide) ;; These stubs allow our common module syntax to work. (define-syntax chezimports (syntax-rules () [(_ e ...) (begin)])) (define-syntax chezprovide (syntax-rules () [(_ e ...) (begin)])) )
true
9d3e06d7b23c1f202a4b4dfa58b2f1a7f44f3422
5927f3720f733d01d4b339b17945485bd3b08910
/hato-prob.scm
86d13ea242517d05e0ca427ada63d8f9d49c5ccf
[]
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
26,416
scm
hato-prob.scm
;;;; hato-prob.scm -- classifier probability library ;; ;; Copyright (c) 2005-2009 Alex Shinn. All rights reserved. ;; BSD-style license: http://synthcode.com/license.txt ;; This is where we build up chains of tokens into "features" of the ;; text and compute the combined probability. The main entry point ;; FEATURE-FOLD takes a huge amount of options in the form of DSSSL ;; keywords, which change at a fast enough rate that I won't bother ;; documenting them yet. ;; There's a lot of premature optimization in the form of fast paths (we ;; don't keep features in memory if we can at all avoid it), usually ;; added while waiting for the comparison results to finish their ;; overnight runs. Sorry about that. (require-library posix srfi-69 hato-i3db hato-mime html-parser posix hato-token) (module hato-prob ( ;; primary api feature-fold ;; utilities deleet i3db-file-name ;; mail record make-mstats mstats? mstats-words set-mstats-words! mstats-urls set-mstats-urls! mstats-ips set-mstats-ips! mstats-emails set-mstats-emails! mstats-features set-mstats-features! mstats-score set-mstats-score! mstats-count set-mstats-count! mstats-prob set-mstats-prob! ) (import scheme chicken extras data-structures ports posix srfi-69) (import html-parser hato-i3db hato-mime hato-token) (include "write-number.scm") (define (set-file-position! fd where . o) (set! (file-position fd) (if (pair? o) (cons where o) where))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; compile with "-feature debug" for more debugging info (cond-expand (debug (define-syntax debug (syntax-rules () ((debug fmt args ...) (fprintf (current-error-port) fmt args ...))))) (else (define-syntax debug (syntax-rules () ((debug fmt args ...) #t))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; list utils (define (fold kons knil ls) (let lp ((ls ls) (acc knil)) (if (null? ls) acc (lp (cdr ls) (kons (car ls) acc))))) (define (filter pred ls) (let lp ((ls ls) (res '())) (if (null? ls) (reverse res) (lp (cdr ls) (if (pred (car ls)) (cons (car ls) res) res))))) (define (unique ls . o) (let-optionals* o ((eq equal?) (key identity)) (map cdr (hash-table->alist (alist->hash-table (map (lambda (x) (cons (key x) x)) ls) eq))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; string utils (define (pad s i) (let* ((s (->string s)) (diff (fx- i (string-length s)))) (if (positive? diff) (string-append (make-string diff #\space) s) s))) (define (pad-right s i) (let* ((s (->string s)) (diff (fx- i (string-length s)))) (if (positive? diff) (string-append s (make-string diff #\space)) s))) (define (string-count s ch) (let lp ((i (fx- (string-length s) 1)) (sum 0)) (cond ((fx< i 0) sum) ((eq? ch (string-ref s i)) (lp (fx- i 1) (fx+ sum 1))) (else (lp (fx- i 1) sum))))) (define (string-downcase s . o) (let-optionals* o ((start 0) (end (string-length s))) (let* ((len (fx- end start)) (s2 (make-string len))) (let lp ((i start) (j 0)) (if (fx>= i end) s2 (begin (string-set! s2 j (char-downcase (string-ref s i))) (lp (fx+ i 1) (fx+ j 1)))))))) ;; translate 1337-speak (define (deleet str start end) (with-output-to-string (lambda () (let ((len (string-length str))) (let lp ((i start)) (when (fx< i end) (let ((c (string-ref str i))) (if (char-alphabetic? c) (display (char-downcase c)) (case c ((#\4 #\@ #\^) (display #\a)) ((#\8) (display #\b)) ((#\[ #\< #\() (display #\c)) ((#\3 #\&) (display #\e)) ((#\6 #\,) (display #\g)) ((#\#) (display #\h)) ((#\!) (display #\i)) ((#\1 #\|) (display #\l)) ((#\0) (display #\o)) ((#\9) (display #\p)) ((#\5) (display #\s)) ((#\+ #\7) (display #\t)) ((#\%) (display #\y)) ((#\2) (display #\z)) (else #f)))) (lp (fx+ i 1)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; record for holding mail information and statistics (define-record-type <mstats> (%make-mstats words urls ips emails features score inverse-score count prob) mstats? (words mstats-words set-mstats-words!) (urls mstats-urls set-mstats-urls!) (ips mstats-ips set-mstats-ips!) (emails mstats-emails set-mstats-emails!) (features mstats-features set-mstats-features!) (score mstats-score set-mstats-score!) (inverse-score mstats-inverse-score set-mstats-inverse-score!) (count mstats-count set-mstats-count!) (prob mstats-prob set-mstats-prob!) ) (define (make-mstats . o) (let-optionals* o ((words '()) (urls '()) (ips '()) (emails '()) (features '()) (score 0.0) (inverse-score 0.0) (count 0) (prob 0.0)) (%make-mstats words urls ips emails features score inverse-score count prob))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; probability utils (define (chi^2 chi df) (debug "chi^2 ~S ~S\n" chi df) (if (> df 1000) (let ((scale (/ 1000 df))) (chi^2 (* chi scale) (* df scale))) (let* ((m (/ chi 2.0)) (e^-m (exp (- m))) (limit (quotient df 2))) (let lp ((i 1) (term e^-m) (sum e^-m)) (if (> i limit) (min sum 1.0) (let ((term (* term (/ m i)))) (lp (+ i 1) term (+ sum term)))))))) (define (chi^2-combined-prob ls) (let lp ((ls ls) (p 1.0) (p-sum '()) (n 0)) (if (null? ls) (chi^2 (* -2 (fold + (log p) p-sum)) (* n 2)) (let ((p2 (* p (min 0.99 (max 0.01 (car ls)))))) (if (< p2 1e-200) (lp (cdr ls) 1.0 (cons (log p2) p-sum) (+ n 1)) (lp (cdr ls) p2 p-sum (+ n 1))))))) (define (chi^2-balanced-prob ls) (let ((H (chi^2-combined-prob ls)) (S (chi^2-combined-prob (map (cut - 1.0 <>) ls)))) (/ (+ 1 (- H S)) 2))) (define (mstats-feature-probability a num-significant epsilon naive-bayes?) (let ((words (sort (if (positive? epsilon) (filter (lambda (a) (>= (abs (- 0.5 (car a))) epsilon)) (mstats-features a)) (mstats-features a)) (lambda (a b) (> (abs (- 0.5 (car a))) (abs (- 0.5 (car b)))))))) (let ((sig-words ; take num-significant, plus any words of the same value (if (positive? num-significant) (let lp ((ls words) (i 0)) (cond ((null? ls) words) ((fx= i num-significant) (let ((diff (abs (- 0.5 (caar ls))))) (let lp ((ls ls)) (cond ((null? (cdr ls)) words) ((= (abs (- 0.5 (caadr ls)))) (lp (cdr ls))) (else (set-cdr! ls '()) words))))) (else (lp (cdr ls) (+ i 1))))) words))) ;;(debug "sig-words: ~S\n" sig-words) (if (null? sig-words) 0.5 (if naive-bayes? ((lambda (x) (/ (car x) (max 1 (cdr x)))) (fold (lambda (w a) (let ((weight (cadr w))) (cons (+ (* weight (car w)) (car a)) (fx+ weight (cdr a))))) (cons 0.0 0) sig-words)) (chi^2-balanced-prob (map car sig-words))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; chains of tokens form features (define (token-chain! db chains folders s i j) (for-each (lambda (vec folder) (let* ((s2 (folder s i j)) (len (string-length s2))) (let lp ((k (fx- (vector-length vec) 1))) (if (zero? k) (vector-set! vec 0 (i3db-hash db s2 0 len (i3db-salt db))) (let* ((prev (fx- k 1)) (init (i3db-hash db " " 0 1 (vector-ref vec prev)))) (vector-set! vec k (i3db-hash db s2 0 len init)) (lp prev)))))) chains folders)) (define (token-chain-identity! db vec s i j) (let lp ((k (fx- (vector-length vec) 1))) (if (zero? k) (vector-set! vec 0 (i3db-hash db s i j (i3db-salt db))) (let* ((prev (fx- k 1)) (init (i3db-hash db " " 0 1 (vector-ref vec prev)))) (vector-set! vec k (i3db-hash db s i j init)) (lp prev))))) (define (token-chain-with-words! db chains words folders s i j) (for-each (lambda (vec word-vec folder) (let* ((s2 (folder s i j)) (len (string-length s2))) (let lp ((k (fx- (vector-length vec) 1))) (cond ((zero? k) (vector-set! vec 0 (i3db-hash db s2 0 len (i3db-salt db))) (vector-set! word-vec 0 s2)) (else (let* ((prev (fx- k 1)) (init (i3db-hash db " " 0 1 (vector-ref vec prev))) (prev-word (vector-ref word-vec prev))) (vector-set! vec k (i3db-hash db s2 0 len init)) (vector-set! word-vec k (string-append prev-word " " s2)) (lp prev))))))) chains words folders)) (define (chain-score-bayes db chains weight-factor epsilon feature-prob) (let lp1 ((ls chains) (score 0.0) (count 0)) (if (null? ls) (values score 0 count) ; 0 place-holder for unused inverse (let* ((vec (car ls)) (len (vector-length vec))) (let lp2 ((i 0) (w 1) (score score) (count count)) (if (fx= i len) (lp1 (cdr ls) score count) (receive (s h) (i3db-ref db (vector-ref vec i)) (let ((ps (feature-prob s h))) (if (>= (abs (- ps 0.5)) epsilon) (lp2 (fx+ i 1) (fxshl w weight-factor) (+ score (* w ps)) (fx+ count w)) (lp2 (fx+ i 1) (fxshl w weight-factor) score count)))))))))) (define (chain-score-chi db chains weight-factor epsilon feature-prob) (let lp1 ((ls chains) (s 1.0) (h 1.0) (s-sum '()) (h-sum '()) (count 0)) (if (null? ls) (values (* -2 (fold + (log s) s-sum)) (* -2 (fold + (log h) h-sum)) count) (let* ((vec (car ls)) (len (vector-length vec))) (let lp2 ((i 0) (s s) (h h) (s-sum s-sum) (h-sum h-sum) (count count)) ;;(debug "lp2 ~S ~S ~S ~S\n" s h s-sum h-sum) (if (fx= i len) (lp1 (cdr ls) s h s-sum h-sum count) (receive (num-s num-h) (i3db-ref db (vector-ref vec i)) (let* ((ps (feature-prob num-s num-h)) (ph (- 1.0 ps))) (if (>= (abs (- ps 0.5)) epsilon) (let* ((s2 (* s (min 0.99 (max 0.01 ps)))) (s3 (if (< s2 1e-200) 1.0 s2)) (s-sum2 (if (< s2 1e-200) (cons (log s2) s-sum) s-sum)) (h2 (* h (min 0.99 (max 0.01 ph)))) (h3 (if (< h2 1e-200) 1.0 h2)) (h-sum2 (if (< h2 1e-200) (cons (log h2) h-sum) h-sum))) ;;(debug "s2: ~S s3: ~S h2: ~S h3: ~S\n" s2 s3 h2 h3) (lp2 (fx+ i 1) s3 h3 s-sum2 h-sum2 (fx+ count 1))) (lp2 (fx+ i 1) s h s-sum h-sum count)))))))))) (define (chain-word-score-list db chains words weight-factor feature-prob) (let ((last-pair (list #f))) (let lp1 ((ls chains) (ls2 words) (res last-pair)) (if (null? ls) (begin (set-car! last-pair (car res)) (cons (cdr res) last-pair)) (let* ((vec (car ls)) (word-vec (car ls2)) (len (vector-length vec))) (let lp2 ((i 0) (w 1) (res res)) (if (fx= i len) (lp1 (cdr ls) (cdr ls2) res) (let ((key (vector-ref vec i))) (receive (s h) (i3db-ref db key) (let ((ps (feature-prob s h))) (lp2 (fx+ i 1) (fxshl w weight-factor) (cons (list ps w (vector-ref word-vec i) s h key) res) ))))))))))) (define (chain-update! db chains spam-offset ham-offset) (let lp1 ((ls chains)) (unless (null? ls) (let* ((vec (car ls)) (len (vector-length vec))) (let lp2 ((i 0)) (if (fx= i len) (lp1 (cdr ls)) (begin (i3db-update! db (vector-ref vec i) spam-offset ham-offset) (lp2 (fx+ i 1))))))))) (define (report-features a) (define (same-tok? x y) (equal? (caddr x) (caddr y))) (let* ((tokens (mstats-features a)) (spam-tok (map caddr (filter (lambda (x) (= 1.0 (car x))) tokens))) (ham-tok (map caddr (filter (lambda (x) (= 0.0 (car x))) tokens))) (unknown-tok (map caddr (filter (lambda (x) (and (zero? (cadddr x)) (zero? (car (cddddr x))))) tokens)))) (printf "\nPure Spam ~S ~S:\n" (length spam-tok) (map (lambda (i) (length (filter (lambda (s) (= i (string-count s #\space))) spam-tok))) '(0 1 2 3 4))) (for-each (cut printf " ~S\n" <>) (unique spam-tok)) (newline) (printf "Pure Ham ~S ~S:\n" (length ham-tok) (map (lambda (i) (length (filter (lambda (s) (= i (string-count s #\space))) ham-tok))) '(0 1 2 3 4))) (for-each (cut printf " ~S\n" <>) (unique ham-tok)) (newline) (printf "Unknown: ~S ~S:\n" (length unknown-tok) (map (lambda (i) (length (filter (lambda (s) (= i (string-count s #\space))) unknown-tok))) '(0 1 2 3 4))) (for-each (lambda (x) (printf "~A x ~A (~A,~A) ~A ~S\n" (pad (cadr x) 4) (number->string* (car x) 10 8) (pad (cadddr x) 3) (pad (car (cddddr x)) 3) (pad-right (cadr (cddddr x)) 8) (caddr x))) (sort (unique (filter (lambda (x) (and (< 0.0 (car x) 1.0) (not (= 0.5 (car x))))) tokens) same-tok?) (lambda (x y) (< (car x) (car y))))) (printf "\nchi^2: ~S\n" (chi^2-balanced-prob (map car tokens))))) (define (i3db-file-name key-size value-size) (sprintf "~A/.hato/spam-k~A-v~A.db" (or (get-environment-variable "HOME") ".") (or key-size "0") value-size)) (define (feature-fold sources #!key (ham? #f) (spam? #f) (insert-header? #f) (print-result? #f) (literal? #f) (case-insensitive? #f) (deleet? #f) (auto-learn? #f) (verbose? #f) (delete-database? #f) (refile? #f) (no-update-count? #f) (mime? #f) (html? #f) (proportional-probability? #f) (naive-bayes? #f) (robinson? #f) (db-file #f) (offset 1) (key-size 2) (value-size 2) (min-length 1) (num-significant 0) (chain-length 1) (threshold 0.6) ; bias to reduce false-positives (weight-factor 2) (epsilon 0.0) ;; robinson constants (strength 1.0) (spam-first 0.5) ) (let* ((write? (or ham? spam? auto-learn?)) (folders (append (if case-insensitive? (list string-downcase) '()) (if deleet? (list deleet) '()) (if (or literal? (not (or case-insensitive? deleet?))) (list substring) '()))) (db-file (or db-file (i3db-file-name key-size value-size))) (db (i3db-open db-file key-size value-size write?)) (num-spam (i3db-spam db)) (num-ham (i3db-ham db)) (s% 0.0) (h% 0.0) (chains (map (lambda (x) (make-vector chain-length 0)) folders)) (tokens (map (lambda (x) (make-vector chain-length "")) folders)) (spam-offset (if spam? offset 0)) (ham-offset (if ham? offset 0))) (letrec ((make-knil (if naive-bayes? make-mstats (lambda () (let ((a (make-mstats))) (set-mstats-score! a 1.0) (set-mstats-inverse-score! a 1.0) a)))) (reset-percentages (lambda () (set! s% (if (zero? num-ham) 0.99 (/ num-spam num-ham))) (set! h% (if (zero? s%) 0.99 (/ 1.0 s%))))) (feature-prob1 (cond (proportional-probability? (lambda (s h) (let* ((s-p (* s s%)) (h-p (* h h%)) (divisor (+ s-p h-p))) (if (zero? divisor) 0.5 (/ s-p divisor))))) (else (lambda (s h) (let ((divisor (+ s h))) (if (zero? divisor) 0.5 (/ s divisor))))))) (feature-prob (if robinson? (lambda (s h) (/ (+ (* strength spam-first) (* (+ s h) (feature-prob1 s h))) (+ strength s h))) feature-prob1)) (chain-score (if naive-bayes? chain-score-bayes chain-score-chi)) (kons1 (cond ((and (or spam? ham?) (not verbose?) (not (positive? num-significant))) (debug "update all\n") (if (and (null? (cdr folders)) (eq? (car folders) substring)) (lambda (s i j a) (token-chain-identity! db (car chains) s i j) (chain-update! db chains spam-offset ham-offset) a) (lambda (s i j a) (token-chain! db chains folders s i j) (chain-update! db chains spam-offset ham-offset) a))) ((or verbose? ham? spam? auto-learn? (positive? num-significant)) (debug "using words: verbose? => ~S spam? => ~S ham? => ~S num-significant => ~S\n" verbose? spam? ham? num-significant) (lambda (s i j a) (token-chain-with-words! db chains tokens folders s i j) (let* ((res (chain-word-score-list db chains tokens weight-factor feature-prob)) (new (car res)) (last-pair (cdr res))) (let ((old (mstats-features a))) (set-cdr! last-pair old) (set-mstats-features! a new)) a))) (else (if (and (null? (cdr folders)) (eq? (car folders) substring)) (lambda (s i j a) (token-chain-identity! db (car chains) s i j) (receive (ps ph count) (chain-score db chains weight-factor epsilon feature-prob) (set-mstats-score! a (+ (mstats-score a) ps)) (set-mstats-inverse-score! a (+ (mstats-inverse-score a) ph)) (set-mstats-count! a (fx+ (mstats-count a) count))) a) (lambda (s i j a) (token-chain! db chains folders s i j) (receive (ps ph count) (chain-score db chains weight-factor epsilon feature-prob) (set-mstats-score! a (+ (mstats-score a) ps)) (set-mstats-inverse-score! a (+ (mstats-inverse-score a) ph)) (set-mstats-count! a (fx+ (mstats-count a) count))) a))))) (kons (if (positive? min-length) (lambda (s i j a) (if (fx> (fx- j i) min-length) (kons1 s i j a) a)) kons1)) (compute-spam-probability (cond ((and (or spam? ham?) (not verbose?) (not (positive? num-significant))) (lambda (a) (if spam? 1.0 0.0))) ((or verbose? spam? ham? auto-learn? (positive? num-significant)) (lambda (a) (mstats-feature-probability a num-significant epsilon naive-bayes?))) (naive-bayes? (lambda (a) (/ (mstats-score a) (max 1 (mstats-count a))))) (else (lambda (a) (let* ((count (mstats-count a)) (S (chi^2 (mstats-score a) (* 2 count))) (H (chi^2 (mstats-inverse-score a) (* 2 count)))) (debug "S: ~S, H: ~S\n" S H) (/ (+ 1 (- S H)) 2)))))) (final1 (cond ((or ham? spam?) (lambda (a) (if ham? (set! num-ham (fx+ num-ham 1)) (set! num-spam (fx+ num-spam 1))) (if (or print-result? (not auto-learn?)) (let ((PS (compute-spam-probability a))) (set-mstats-prob! a PS) (when (if ham? (> PS threshold) (<= PS threshold)) (for-each ; false pos/neg, train (lambda (tok) (i3db-update! db (cadr (cddddr tok)) spam-offset ham-offset)) (mstats-features a))) (if print-result? (print (if (> PS threshold) "spam " "ham ") PS))) a))) (else (lambda (a) (let ((PS (compute-spam-probability a))) (set-mstats-prob! a PS) (cond ((> PS threshold) (set! num-spam (fx+ num-spam 1)) (if refile? (set! num-ham (fx- num-ham 1))) (if print-result? (print "spam " PS))) (else (set! num-ham (fx+ num-ham 1)) (if refile? (set! num-spam (fx- num-spam 1))) (if print-result? (print "ham " PS)))) a))))) (final (lambda (a) (if verbose? (report-features a)) (final1 a))) (run1 (if insert-header? (cut feature-run-filter reset-percentages threshold kons <>) (cut feature-run-non-filter reset-percentages threshold kons <>))) (run (cond ((or mime? html?) (lambda () (final (mime-message-fold (current-input-port) (mime-headers->list) (lambda (headers str acc) (with-input-from-string (if (and html? (equal? "text/html" (caar (mime-parse-content-type (mime-ref headers "Content-Type" "text/plain"))))) (html-strip str) str) (lambda () (run1 acc)))) (make-knil))))) (else (lambda () (final (run1 (make-knil)))))))) ;; run (when verbose? (printf "spam?: ~S ham?: ~S auto-learn?: ~S verbose?: ~S\n" spam? ham? auto-learn? verbose?) (printf "num-spam: ~S num-ham: ~S\n" num-spam num-ham)) (let ((res (if (null? sources) (run) (let lp ((ls sources) (a (make-knil))) (if (null? ls) a (let ((file (car ls))) (if (directory? file) (let ((r1 (cddr (directory file)))) (let ((r2 (map (cut string-append file "/" <>) r1))) (lp (append ls r2) a))) (lp (cdr ls) (with-input-from-file file run))))))))) ;; close (when db (i3db-close db) (if (and write? (not no-update-count?)) (and-let* ((fd (file-open db-file open/rdwr))) (set-file-position! fd (* 2 4)) (write-binary-uint32 num-spam fd) (write-binary-uint32 num-ham fd) (file-close fd)))) res)))) (define (make-list-update-kons kons ref set) (lambda (s i j a) (set a (cons (substring s i j) (ref a))) (kons s i j a))) (define (feature-run-filter reset threshold kons acc) (let ((kons-url (make-list-update-kons kons mstats-urls set-mstats-urls!)) (kons-ip (make-list-update-kons kons mstats-ips set-mstats-ips!)) (kons-email (make-list-update-kons kons mstats-emails set-mstats-emails!))) (reset) (let lp ((res '())) (let ((line (read-line))) (cond ((eof-object? line) acc (let lp ((ls (reverse res))) (unless (null? ls) (cond ((string=? "" (car ls)) (print "X-Spam-Classification: " (if (> (mstats-prob acc) threshold) "SPAM " "HAM ")) (print "X-Spam-Probability: " (mstats-prob acc)) (newline) (for-each print (cdr ls))) (else (print (car ls)) (lp (cdr ls))))))) (else (token-fold line acc kons kons kons-url kons-ip kons-email) (lp (cons line res)))))))) (define (feature-run-non-filter reset threshold kons acc) (let ((kons-url (make-list-update-kons kons mstats-urls set-mstats-urls!)) (kons-ip (make-list-update-kons kons mstats-ips set-mstats-ips!)) (kons-email (make-list-update-kons kons mstats-emails set-mstats-emails!))) (reset) (let lp () (let ((line (read-line))) (cond ((eof-object? line) acc) (else (token-fold line acc kons kons kons-url kons-ip kons-email) (lp))))))) )
true
3209a2f0f85d7d8f6cb4904760a93b760095a164
4bd59493b25febc53ac9e62c259383fba410ec0e
/Scripts/Task/greatest-subsequential-sum/scheme/greatest-subsequential-sum.ss
e42244588b31e8501392cac49c7685c87668022d
[]
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
445
ss
greatest-subsequential-sum.ss
(define (maxsubseq in) (let loop ((_sum 0) (_seq (list)) (maxsum 0) (maxseq (list)) (l in)) (if (null? l) (cons maxsum (reverse maxseq)) (let* ((x (car l)) (sum (+ _sum x)) (seq (cons x _seq))) (if (> sum 0) (if (> sum maxsum) (loop sum seq sum seq (cdr l)) (loop sum seq maxsum maxseq (cdr l))) (loop 0 (list) maxsum maxseq (cdr l)))))))
false
b7e36b18803673a002dbc831208ba38c608e7e34
4bd59493b25febc53ac9e62c259383fba410ec0e
/Scripts/Task/factorial/scheme/factorial-2.ss
065b3725252cfbd6ea7accd642d9426613a85d1e
[]
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
133
ss
factorial-2.ss
(define (factorial n) (let loop ((i 1) (accum 1)) (if (> i n) accum (loop (+ i 1) (* accum i)))))
false
bf1624f5f31084de76f44a239499f08b1668127b
2fb1484c67bb67ece9d8417f659d7f1fe429a223
/forcible.meta
c905c9bdee528e73816b992de6045d44ae860c8c
[ "MIT" ]
permissive
0-8-15/forcible
7595f8bfe79afa1044cf4eeba5311628ddce2214
bb9d5b61c4da39b8afa2780d684600d52c1b86f7
refs/heads/master
2020-04-03T13:18:38.164102
2019-05-06T21:19:15
2019-05-06T21:19:15
155,281,007
0
1
null
2019-05-06T19:45:30
2018-10-29T21:03:01
Scheme
UTF-8
Scheme
false
false
308
meta
forcible.meta
;; -*- mode: Scheme; -*- ((category hell) (license "BSD") (author "Jörg F. Wittenberger") (synopsis "Thread- and exception aware, lazy-looking synchronization with timeouts - extending srfi-45") (doc-from-wiki) (needs pigeon-hole simple-timer) (files "forcible.meta" "forcible.setup" "forcible.scm"))
false
343295c8deff5dc7e183984833c42057b113545d
951b7005abfe3026bf5b3bd755501443bddaae61
/same-parity.scm
4ac675c572799bd515081750af69230907da4d6f
[]
no_license
WingT/scheme-sicp
d8fd5a71afb1d8f78183a5f6e4096a6d4b6a6c61
a255f3e43b46f89976d8ca2ed871057cbcbb8eb9
refs/heads/master
2020-05-21T20:12:17.221412
2016-09-24T14:56:49
2016-09-24T14:56:49
63,522,759
2
0
null
null
null
null
UTF-8
Scheme
false
false
1,152
scm
same-parity.scm
(define g (lambda w (define (add-iter tmp ans) (if (null? tmp) ans (add-iter (cdr tmp) (+ (car tmp) ans)))) (add-iter w 0))) (define (g1 . w) (define (add-iter tmp ans) (if (null? tmp) ans (add-iter (cdr tmp) (+ (car tmp) ans)))) (add-iter w 0)) (define f (lambda (x y . z) (define (add-iter tmp ans) (if (null? tmp) ans (add-iter (cdr tmp) (+ (car tmp) ans)))) (+ x y (add-iter z 0)))) (define (f1 x y . z) (define (add-iter tmp ans) (if (null? tmp) ans (add-iter (cdr tmp) (+ (car tmp) ans)))) (+ x y (add-iter z 0))) (g 1 2 3 4 5) (g1 1 2 3 4 5) (f 1 2 3 4 5) (f1 1 2 3 4 5) (define (same-parity . w) (define (same-parity-rec tmp) (define (next-list l) (if (or (null? (cdr l)) (= (remainder (cadr l) 2) (remainder (car tmp) 2))) (cdr l) (next-list (cdr l)))) (if (null? tmp) (list) (cons (car tmp) (same-parity-rec (next-list tmp))))) (same-parity-rec w)) (same-parity 1 2 3 4 5 6 7) (same-parity 2 3 4 5 6 7) (restart 1)
false
b4e1a713b6172532ae5fd528d0d6bbcfcc6f498f
afc3bd22ea6bfe0e60396a84a837c82a0d836ea2
/Informatics Basics/Module 1/02-day.scm
513a0e0af51c2c590abd403025906e6e028973b7
[]
no_license
BuDashka/BMSTU
c128c2b13065a25ec027c68bcc3bac119163a53f
069551c25bd11ea81e823b2195851f8563271b01
refs/heads/master
2021-04-15T15:22:12.324529
2017-10-19T00:59:25
2017-10-19T00:59:25
126,348,611
1
1
null
2018-03-22T14:35:04
2018-03-22T14:35:04
null
UTF-8
Scheme
false
false
428
scm
02-day.scm
(define (day-of-week dd mm year) (define v (quotient year 400)) (define v1 (quotient year 100)) (define v2 (quotient year 4)) (if (or (< mm 2) (= mm 2)) (begin (let* ((year (- year 1)) (dd (+ dd 3))) (remainder (remainder (+ dd year v2 (- v1) v (quotient (+ (* 31 mm) 10) 12)) 7) 7))) (remainder (+ (remainder (+ dd year v2 (- v1) v (quotient (+ (* 31 mm) 10) 12)) 7) 1) 7)))
false
5a7a14d060921e047c635f66e7cca54a903725dd
c6478f646c59c8ad7ee57c77523d205d67b7cd56
/experimental/scheme/anaphora.scm
bb50cc42352a6a5c69554e0b241b12ca09a23954
[]
no_license
hefeix/common
6a03c7e69e2024bc9ad60c67ca1662c86e337c03
1075697af2f00affd7d59311151a7840babfda2f
refs/heads/master
2016-09-05T11:19:59.365074
2014-10-26T14:42:30
2014-10-26T14:42:30
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
18,855
scm
anaphora.scm
; Author: Juergen Lorenz ; ju (at) jugilo (dot) de ; ; Copyright (c) 2011-2013, Juergen Lorenz ; 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 author 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 ; HOLDERS 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. ; ; Last update: Dec 11, 2013 ; #|[ ;Inspired by Paul Graham's classic "On Lisp" this module introduces ;anaphoric macros, which are unhygienic by design. Hence they can not be ;implemented with syntax-rules! In fact, they introduce new identifiers ;behind the scene, mostly named it, which can be referenced in the body ;without being declared. Please note, that this identifier is not ;renamed! ]|# (module anaphora (export anaphora aif nif alambda nlambda awhen nwhen acond ncond awhile nwhile aand nand define-anaphor define-properties alist-recurser atree-recurser tree-recurser list-recurser) (import scheme (only chicken case-lambda gensym print)) ;;; (aif test consequent [alternative]) ;;; ----------------------------------- ;;; anaphoric if, where consequent and alternative can refer to result ;;; of test named it (define-syntax aif (ir-macro-transformer (lambda (form inject compare?) (let ((it (inject 'it))) (let ( (test (cadr form)) (consequent (caddr form)) (alternative (cdddr form)) ) (if (null? alternative) `(let ((,it ,test)) (if ,it ,consequent)) `(let ((,it ,test)) (if ,it ,consequent ,(car alternative))))))))) ;;; (nif name test consequent [alternative]) ;;; ---------------------------------------- ;;; named if, where consequent and alternative can refer to result ;;; of test named name (define-syntax nif (syntax-rules () ((_ name test consequent) (let ((name test)) (if name consequent))) ((_ name test consequent alternative) (let ((name test)) (if name consequent alternative))))) ;;; (awhen test xpr . xprs) ;;; ----------------------- ;;; anaphoric when, where xpr ... can refer to result of test ;;; named it (define-syntax awhen (ir-macro-transformer (lambda (form inject compare?) (let ((it (inject 'it))) (let ( (test (cadr form)) (xpr (caddr form)) (xprs (cdddr form)) ) `(let ((,it ,test)) (if ,it (begin ,xpr ,@xprs)))))))) ;;; (nwhen name test xpr . xprs) ;;; ---------------------------- ;;; named when, where xpr ... can refer to result of test ;;; named name (define-syntax nwhen (syntax-rules () ((_ name test xpr . xprs) (let ((name test)) (if name (begin xpr . xprs)))))) ;;; (acond (test xpr ...) ... [(else ypr ...)]) ;;; ------------------------------------------- ;;; anaphoric cond, where each test is bound to it and else to #t. (define-syntax acond (ir-macro-transformer (lambda (form inject compare?) (let ((it (inject 'it))) (let ((clauses (cdr form))) (let loop ((clauses clauses)) (if (null? clauses) #f (let* ( (clause (car clauses)) (cnd (car clause)) ) `(let ((sym ,(if (compare? cnd 'else) #t cnd))) (if sym (let ((,it sym)) ,@(cdr clause)) ,(loop (cdr clauses)))))))))))) ;;; (ncond name (test xpr ...) ... [(else ypr ...)]) ;;; ------------------------------------------------ ;;; anaphoric cond, where each test is bound to name and else to #t. (define-syntax ncond (syntax-rules (else) ((_ name) #f) ((_ name (else xpr . xprs) . clauses) (let ((sym #t)) (if sym (let ((name sym)) xpr . xprs) #f))) ((_ name (test xpr . xprs) . clauses) (let ((sym test)) (if sym (let ((name sym)) xpr . xprs) (ncond name . clauses)))))) ;;; (awhile test xpr . xprs) ;;; ------------------------ ;;; anaphoric while, where each xpr ... can refer to the result of ;;; the successive test, named it (define-syntax awhile (ir-macro-transformer (lambda (form inject compare?) (let ((it (inject 'it))) (let ( (test (cadr form)) (xpr (caddr form)) (xprs (cdddr form)) ) `(let loop ((,it ,test)) (when ,it ,xpr ,@xprs (loop ,test)))))))) ;;; (nwhile name test xpr . xprs) ;;; ----------------------------- ;;; named while, where each xpr ... can refer to the result of ;;; the successive test, named name (define-syntax nwhile (syntax-rules () ((_ name test xpr . xprs) (let loop ((name test)) (when name (begin xpr . xprs) (loop test)))))) ;;; (aand . args) ;;; ------------- ;;; anaphoric and, where each successive argument can refer to the ;;; result of the previous argument, named it. (define-syntax aand (ir-macro-transformer (lambda (form inject compare?) (let ((it (inject 'it))) (let ((args (cdr form))) (let loop ((args args)) (cond ((null? args) #t) ((null? (cdr args)) (car args)) (else `(let ((,it ,(car args))) (if ,it ,(loop (cdr args)) #f)))))))))) ;;; (nand name . args) ;;; ------------------ ;;; named and, where each successive argument can refer to the ;;; result of the previous argument, named name. (define-syntax nand (syntax-rules () ((_ name) #t) ((_ name arg) arg) ((_ name arg0 arg1 ...) (let ((name arg0)) (if name (nand name arg1 ...)))))) ;;; (alambda args xpr . xprs) ;;; ------------------------- ;;; anaphoric lambda, where the body xpr ... can refer to self, so that ;;; recursion is possible (define-syntax alambda (ir-macro-transformer (lambda (form inject compare?) (let ((self (inject 'self))) (let ((args (cadr form)) (body (cddr form))) `(letrec ((,self (lambda ,args ,@body))) ,self)))))) ;;; (nlambda name args xpr . xprs) ;;; ------------------------------ ;;; named lambda, where the body xpr ... can refer to name, so that ;;; recursion is possible (define-syntax nlambda (syntax-rules () ((_ name args xpr . xprs) (letrec ((name (lambda args xpr . xprs))) name)))) #|[ Most of the anaphoric macros above could be generated automatically by means of the following macro, define-anaphor, which generates another macro defining it. It accepts three arguments, the name of the new macro to be defined, the name of the procedure or macro on which the anaphoric macro is patterned and a rule transforming the latter into the former, presently one of the procedures cascade-it and first-it. cascade-it produces a cascade of variables named it, storing the values of the previous arguments as in aand above, where first-it stores only the first argument as variable it to be used in any of the following arguments as in awhen above. So we could have defined them as (define-anaphor aand and cascade-it) (define-anaphor awhen when first-it) and used as follows (aand '(1 2 3) (cdr it) (cdr it)) ; -> '(3) (awhen (! 5) it (* 2 it)) ; -> 240 where ! is the factorial. But note, that define-anaphor could be used for any function as well, for example (define-anaphor a* * cascade-it) (a* 10 (* 2 it) (+ 5 it)) ; -> 35 ]|# ;;; (define-anaphor name from rule) ;;; ------------------------------- ;;; defines an anaphoric macro, name, patterned after the fuction or ;;; macro from and transformed according to rule, one of the symbols ;;; cascade or first. ;;; Note, that this macro is hygienic, but it creates an anaphoric one. (define-syntax define-anaphor (syntax-rules () ((_ name from rule) (define-syntax name (er-macro-transformer (lambda (form rename compare?) (let ((%let (rename 'let)) (%let* (rename 'let*))) (letrec ( (cascade-it (lambda (op args) (let loop ((args args) (xpr `(,op))) (if (null? args) xpr (let ((sym (gensym))) `(,%let* ((,sym ,(car args)) (it ,sym)) ,(loop (cdr args) (append xpr (list sym))))))))) (first-it (lambda (op args) `(,%let ((it ,(car args))) (,op it ,@(cdr args))))) ) (case rule ((#:cascade) (cascade-it 'from (cdr form))) ((#:first) (first-it 'from (cdr form))) (else (error 'define-anaphor "rule must be one of #:cascade or #:first"))))))))))) ;(define-syntax define-anaphor ; (syntax-rules () ; ((_ name from rule) ; (define-syntax name ; (er-macro-transformer ; (lambda (form rename compare?) ; (rule 'from (cdr form) rename))))))) ; ;(define (first-it op args rename) ; (let ((%let (rename 'let))) ; `(,%let ((it ,(car args))) ; (,op it ,@(cdr args))))) ; ;(define (cascade-it op args rename) ; (let ((%let* (rename 'let*))) ; (let loop ((args args) (xpr `(,op))) ; (if (null? args) ; xpr ; (let ((sym (gensym))) ; `(,%let* ((,sym ,(car args)) (it ,sym)) ; ,(loop (cdr args) (append xpr (list sym))))))))) #|[ The following macro defines new macros masking property-accessors and -mutators get and put! For each supplied identifier, prop, another identifier, prop!, is constructed behind the scene. The former will be the accessor, the latter the mutator. So (prop sym) is expands into (get sym 'prop) and (prop! sym val) into (put! sym 'prop val) Note how the new names with the ! suffix are generated at compile time, i.e. within an unquote. Note also the use of the injection argument, i, for the property-name, prop, and the suffixed name, prop!, within that unquote. ]|# ;;; (define-properties . names) ;;; --------------------------- ;;; defines, for each name, property-accessors and -mutators ;;; name and name! (define-syntax define-properties (ir-macro-transformer (lambda (f i c?) `(begin ,@(map (lambda (prop) `(begin (define-syntax ,prop (ir-macro-transformer (lambda (form inject compare?) `(get ,(cadr form) ',',prop)))) (define-syntax ,(i (string->symbol (string-append (symbol->string (i prop)) "!"))) (ir-macro-transformer (lambda (form inject compare?) `(put! ,(cadr form) ',',prop ,(caddr form))))))) (cdr f)))))) #|[ The following two macros and two procedures represent recursion an lists and trees respectively. They are, again, inspired by Graham. The procedures are defined with alambda, the anaphoric version of lambda with injected symbol self. These procedures, list-recurser and tree-recurser, accept a recurser and a base as arguments, the recurser being itself procedures accepting the actual list or tree as argument, as well as one or two thunks representing recursion along the cdr or the car and the cdr respectively. The macros, alist-recurser and atree-recurser, are anaphoric versions of the procedures list-recurser and tree-recurser. They both inject the symbol it behind the scene, representing the actual list or tree respectively, as well as symbols go-on or go-left and go-right respectively representing the recurser arguments of the functions. The relations between the procedures and the anaphoric macros are shown in the following exaples: (define lcopy (list-recurser (lambda (lst th) (cons (car lst) (th))) '())) (define alcopy (alist-recurser (cons (car it) (go-on)) '())) (define tcopy (tree-recurser (lambda (tree left right) (cons (left) (or (right) '()))) identity)) (define atcopy (atree-recurser (cons (go-left) (or (go-right) '())) it)) ]|# ;;; (alist-recurser recurser base) ;;; ------------------------------ ;;; wrapping list-recurser into an anaphoric macro with injected symbols it and go-on ;;; where it is the list itself and go-on the recurser-thunk (define-syntax alist-recurser (ir-macro-transformer (lambda (form inject compare?) (let ((it (inject 'it)) (go-on (inject 'go-on))) `(list-recurser (lambda (,it thunk) (letrec ((,go-on thunk)) ,(cadr form))) ,@(cddr form)))))) ;;; (atree-recurser recurser base) ;;; ------------------------------ ;;; wrapping tree-recurser into an anaphoric macro with injected symbols ;;; it, go-left and go-right representing the actual tree and recursers ;;; along the car and the cdr respectively. (define-syntax atree-recurser (ir-macro-transformer (lambda (form inject compare?) (let ((recurser (cadr form)) (base (caddr form)) (it (inject 'it)) (go-left (inject 'go-left)) (go-right (inject 'go-right))) `(tree-recurser (lambda (,it left right) (letrec ((,go-left left) (,go-right right)) ,recurser)) (lambda (,it) ,base)))))) ;;; (list-recurser recurser base) ;;; ----------------------------- ;;; recurser is a procedure of a list and a thunk processing the cdr (define (list-recurser recurser base) (alambda (lst) (if (null? lst) (if (procedure? base) (base) base) (recurser lst (lambda () (self (cdr lst))))))) ;;; (tree-recurser recurser base) ;;; ----------------------------- ;;; recurser is a procedure of a tree and two thunks processing the car ;;; and the cdr (define (tree-recurser recurser base) (alambda (tree) (cond ((pair? tree) (recurser tree (lambda () (self (car tree))) (lambda () (if (null? (cdr tree)) #f (self (cdr tree)))))) (else ; atom (if (procedure? base) (base tree) base))))) ;;; documentation dispatcher (define anaphora (let ( (alist '( (aif (macro (aif test consequent alternative ..) "anaphoric if where result of test is named it")) (nif (macro (nif name test consequent alternative ..) "named if where result of test is named name")) (awhen (macro (awhen test xpr . xprs) "anaphoric when where result of test is named it")) (nwhen (macro (nwhen name test xpr . xprs) "named when where result of test is named name")) (acond (macro (acond (test xpr . xprs) ... (else xpr . xprs) ..) "anaphoric cond, where each test except else is named it")) (ncond (macro (ncond name (test xpr . xprs) ... (else xpr . xprs) ..) "named cond, where each test except else is named name")) (awhile (macro (awhile test xpr . xprs) "anaphoric while, where each successive test is named it")) (nwhile (macro (nwhile name test xpr . xprs) "named while, where each successive test is named name")) (aand (macro (aand . args) "anaporic and, where each arg can refer to the previous arg named it")) (nand (macro (nand name . args) "named and, where each arg can refer to the previous arg named name")) (alambda (macro (alambda args . body) "anaphoric lambda, where body can refer to self")) (nlambda (macro (nlambda name args . body) "named lambda, where body can refer to name")) (define-anaphor (macro (define-anaphor name from rule) "define an anaphoric macro from a routine with implicit it and rule cascade: or first:")) (define-properties (macro (define-properties name ...) "abstracting away get and put! Defines properties name and name! ...")) (alist-recurser (macro (alist-recurser recur-xpr base-xpr) "creates unary procedure from macro-arguments with implicit it and go-on thunk")) (atree-recurser (macro (alist-recurser recur-xpr base-xpr) "creates unary procedure from macro-arguments with implicit it, go-left and go-right thunks")) (list-recurser (procedure (list-recurser recurser base) "creates procedure which traverses on cdrs of its only argument")) (tree-recurser (procedure (tree-recurser recurser base) "creates procedure which traverses on cars and cdrs of its only argument")) ))) (case-lambda (() (map car alist)) ((sym) (let ((pair (assq sym alist))) (if pair (for-each print (cadr pair)) (print "Choose one of " (map car alist)))))))) ) ; module anaphora
true
b783bffb931867b2c444fd327210831cc32da81d
b43e36967e36167adcb4cc94f2f8adfb7281dbf1
/scheme/swl1.3/src/swl/canvasitem.ss
da1c746755778169274e280163a620a5d618c758
[ "SWL", "TCL" ]
permissive
ktosiu/snippets
79c58416117fa646ae06a8fd590193c9dd89f414
08e0655361695ed90e1b901d75f184c52bb72f35
refs/heads/master
2021-01-17T08:13:34.067768
2016-01-29T15:42:14
2016-01-29T15:42:14
53,054,819
1
0
null
2016-03-03T14:06:53
2016-03-03T14:06:53
null
UTF-8
Scheme
false
false
32,066
ss
canvasitem.ss
;; Copyright (c) 1996 Oscar Waddell ;; ;; See the file "Notice" for information on usage and redistribution ;; of this file, and for a DISCLAIMER OF ALL WARRANTIES. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Canvas Item ;; ;; NOTE: go back and abstract <markup> and <canvas-item> ;; event-handling code ;; move all tag functionality into <group> class ;; make sure parent is a canvas ;; * maybe should have parent eval function for talking to parent ;; this guy can check that the parent exists... ;; on the other hand, checking to see that the parent is live ;; may be more efficient because we can check once for several calls ;; Implementation alternatives: ;; put the handle and making of it down below ;; do everything by calling protected method on the ;; instance that gets redefined to use handle down below ;; (could simply have protected method for getting handle ;; and define the protected method in all lower classes) ;; or ;; require them to use an init method, and blow up otherwise ;; not so bad since we're going to end up needing to call init ;; method anyway for most other widgets ;; ;; It's mighty tempting to go with the former just to show it could be ;; done, but the latter will likely be more efficient so that's the way. ;; ;; This means the create macro will have some positional and some ;; optional arguments (parent will prob'ly be positional). To work ;; with the other classes, we'll have ;; (create <foo> parent pos-arg1 ... pos-argn (option: opval) ...) ;; expand into: ;; (let ((inst (make <foo> parent))) ;; (send inst init pos-arg1 ... pos-argn) ;; (send inst set-option: opval) ... ;; inst) ;; ;; Analysis should show that we don't need the vector? checks, but of course ;; when we go to ultra-cool representation OW_1 even that doesn't matter. (define-swl-class (<canvas-item> canvas) (<tk-prewidget2> #f) ;* An abstract class of figures that can be drawn on a canvas. ;* Unlike other widgets which are not visible until shown, ;* canvas items are visible at the time they are created. ;* The various mouse events appear to register only when the mouse is ;* on some visible part of the object (for example, they do not register ;* when the mouse is over a transparently filled part of the object). (ivars (parent canvas)) (inherited handle) (inheritable handle parent) (private) (protected [set-color! (which val who) (set-tk-option which (if (eq? val 'transparent) "" val) (lambda (x) (or (eq? x "") (swl:color? val))) who)] [get-color (which who) (get-tk-option which (lambda (x) (if (string=? x "") 'transparent (tk->color x))) who)] [coords-error (mname ls) (assertion-violationf mname (apply string-append "coordinates must be fixnums or flonums " (map (lambda (x) (format "~s" x)) ls)))] [post-init () (swl:safety-check (unless (swl:oknum? handle) (assertion-violationf 'create "attempt to create ~s may have failed" (class-name self)))) (send parent adopt handle self)] [set-tk-option (tclname value err-check name) (swl:safety-check (unless (err-check value) (assertion-violationf name "bad value ~s" value))) (swl:tcl-eval parent 'itemconfig handle tclname value) (#3%void)] [get-tk-option (tclname conversion name) (conversion (swl:tcl-eval parent 'itemcget handle tclname))] [tk-destroy () ; commented out this garbage ' (unless (tk-destroyed?) ;; already checked to see if parent is live ;; we're in a critical section (see below) so we should be ok (swl:tcl-eval parent 'delete handle))] [tk-destroyed? () ; commented out this garbage ' (or (not parent) (string=? "0" (swl:tcl-eval 'winfo 'exists parent)) (string=? "0" (swl:tcl-eval parent 'find 'withtag handle)))]) (public [destroy () ;* \ret{unspecified} ;* destroys the canvas figure ;; put this here because it's almost sure to be called ? (critical-section (when handle (send parent disown handle self) (tk-destroy) (set! parent #f) (set! handle #f)))] [move (xamt yamt) ;* \ret{unspecified} ;* move the figure by the specified x and y amounts ;* (positive or negative). (swl:safety-check (unless (and (swl:oknum? xamt) (swl:oknum? yamt)) (assertion-violationf 'move "args must be numeric: ~s ~s~n" xamt yamt))) (swl:tcl-eval parent 'move handle xamt yamt) (void)] [get-coords () ;* \ret{list} ;* Returns a list of the coordinates defining the canvas figure. (swl:tcl->scheme (swl:tcl-eval parent 'coords handle))] [scheme->tcl (op) ;% \ret{unspecified} (display handle op)] [set-parent! (p) ;* \ret{unspecified} ;* (currently unimplemented) (assertion-violationf 'implementation "have to do set-parent! still")] [get-parent () ;* \ret{see below} ;* Returns the canvas on which the figure is drawn. parent] [show () ;* \ret{unspecified} ;* Makes the canvas item visible again after it has been hidden. (let ((coords (prop-ref 'coords))) (when coords (send-apply self set-coords! coords))) (void)] [hide () ;* \ret{unspecified} ;* Makes the canvas item invisible. ;; total hack (prop-set! 'coords (send self get-coords)) (swl:tcl-eval parent 'move handle -999999 -999999) (void)] [raise () ;* \ret{unspecified} ;* Raises this figure in the display list of the canvas. (swl:tcl-eval parent 'raise handle) (void)] [raise (above-this) ;* \ret{unspecified} ;* Raises this figure above the given figure ;* in the display list of the canvas. (swl:safety-check (unless (isa-canvas-item? above-this) (assertion-violationf 'raise "~s is not a canvas figure" above-this))) (swl:tcl-eval parent 'raise handle above-this) (void)] [lower () ;* \ret{unspecified} ;* Lowers this figure in the display list of the canvas. (swl:tcl-eval parent 'lower handle) (void)] [lower (below-this) ;* \ret{unspecified} ;* Lowers this figure above the given figure ;* in the display list of the canvas. (swl:safety-check (unless (isa-canvas-item? below-this) (assertion-violationf 'lower "~s is not a canvas figure" below-this))) (swl:tcl-eval parent 'lower handle below-this) (void)] ; [scale (xorigin yorigin xscale yscale) ; ;* Rescales the figure. xorigin and yorigin identify the ; ;* origin for the scaling operation and xscale and yscale ; ;* identify the scale factors for x- and y- coordinates, ; ;* respectively (a scale factor of 1.0 implies no change to ; ;* that coordinate). For each of the points defining the ; ;* item, the x-coordinate is adjusted to change the distance ; ;* from xorigin by a factor of xscale. Similarly, each ; ;* y-coordinate is adjusted to change the distance from ; ;* yorigin by a factor of yscale. ; (swl:safety-check ; (unless handle (dead-error self 'scale)) ; (unless (and (swl:oknum? xorigin) (swl:oknum? yorigin) ; (swl:oknum? xscale) (swl:oknum? yscale)) ; (assertion-violationf 'scale "bad value(s) ~s ~s ~s ~s" ; xorigin yorigin xscale yscale))) ; (swl:tcl-eval parent 'scale handle xorigin yorigin xscale yscale) ; (void)] [bounding-box () ;* \ret{list} ;* Returns a list of the coordinates giving the bounding box of this ;* figure on the canvas. (swl:tcl->scheme (swl:tcl-eval parent 'bbox handle))])) ;; Note: here "width:" is truly in screen-distance units ;; this is one thing we might be able to improve by moving to a setter/getter ;; model. (define-swl-class (<2pt-figure> canvas x1 y1 x2 y2) (<canvas-item> canvas) ;* An abstract class for canvas items whose geometry is defined by ;* two points. (ivars) (inherited parent handle) (inheritable parent handle) (private) (protected [tcl-name () 'ERROR]) (public [init (p x1 y1 x2 y2) ;* \ret{unspecified} ;* When creating an instance of this class four numbers ;* must be given defining the top-left and bottom-right ;* coordinates of a rectangular region enclosing the figure. (swl:safety-check (unless (and (swl:oknum? x1) (swl:oknum? y1) (swl:oknum? x2) (swl:oknum? y2)) (coords-error 'create (list x1 y1 x2 y2)))) (set! handle (string->number (swl:tcl-eval parent 'create (tcl-name) x1 y1 x2 y2))) (post-init)] [set-coords! (x1 y1 x2 y2) ;* \ret{unspecified} ;* Sets the coordinates defining the figure to ;* \var{x1}, \var{y1}, \var{x2}, \var{y2}. (swl:safety-check (unless (and (swl:oknum? x1) (swl:oknum? y1) (swl:oknum? x2) (swl:oknum? y2)) (coords-error 'set-coords! (list x1 y1 x2 y2)))) (swl:tcl-eval parent 'coords handle x1 y1 x2 y2) (void)] [set-fill-color! (val) ;* \ret{unspecified} ;* Sets the color with which the interior of the figure is filled. ;* \var{val} is either the symbol \mytt{transparent}, a symbol naming a ;* color in \mytt{rgb.txt}, or ;* an instance of \scheme{<rgb>}. (set-color! '-fill val 'set-fill-color!)] [get-fill-color () ;* \ret{see below} ;* Returns the color with which the interior of the figure is filled. ;* The value returned is either the symbol \mytt{transparent}, a symbol ;* naming a color in \mytt{rgb.txt}, or ;* an instance of \scheme{<rgb>}. (get-color '-fill 'get-fill-color)] [set-outline-color! (val) ;* \ret{unspecified} ;* Sets the color in which the outline of the figure is drawn. ;* \var{val} is either a symbol naming a color in \mytt{rgb.txt} or ;* an instance of \scheme{<rgb>}. (set-color! '-outline val 'set-outline-color!)] [get-outline-color () ;* \ret{see below} ;* Returns the color in which the outline of the figure is drawn. ;* The value returned is either a symbol naming a color in \mytt{rgb.txt} or ;* an instance of \scheme{<rgb>}. (get-color '-outline 'get-outline-color)] [set-line-thickness! (val) ;* \ret{unspecified} ;* Sets the thickness in pixels of the outline drawn around the figure. (set-tk-option '-width val swl:distance-unit? 'set-line-thickness!)] [get-line-thickness () ;* \ret{see below} ;* Returns the thickness in pixels of the outline drawn around the figure. (get-tk-option '-width string->number 'get-line-thickness)] [set-stipple! (val) ;* \ret{unspecified} ;* (currently unimplemented) (set-tk-option '-stipple val swl:bitmap? 'set-stipple!)] [get-stipple () ;* \ret{see below} ;* (currently unimplemented) (get-tk-option '-stipple tk->bitmap 'get-stipple)])) (swl:api-class (<arc> canvas x1 y1 x2 y2) (<2pt-figure> canvas x1 y1 x2 y2) ;% \swlapi{class}{<arc>}{(create <arc> canvas x1 y1 x2 y2)} ;* \ret{instance} ;* An arc is a section of an ;* oval delimited by two angles (see \scheme{set-start!} and \scheme{set-end!}). ;* The arc is inscribed within the rectangular region defined by ;* \var{x1}, \var{y1}, \var{x2}, \var{y2}. ;* An arc can be displayed as a pieslice, chord, or arc ;* (see \scheme{set-style!}) and can be filled with a color or have an ;* outline or both. The thickness and color of the outline ;* can be specified as well. (ivars) (inherited parent handle) (inheritable) (private) (protected [tcl-name () 'arc]) (public [set-style! (val) ;* \ret{unspecified} ;* Determines how the arc is displayed. \var{val} is either ;* \scheme{arc}, \scheme{chord}, or \scheme{pieslice}. (set-tk-option '-style val (lambda (x) (memq x '(arc chord pieslice))) 'set-style!)] [get-style() ;* \ret{see below} ;* Returns a symbol describing how the arc is displayed. ;* The value returns is either \scheme{arc}, \scheme{chord}, or \scheme{pieslice}. (get-tk-option '-style string->symbol 'get-style)] [set-start! (val) ;* \ret{unspecified} ;* Sets the position in degrees where the arc begins. (set-tk-option '-start val swl:oknum? 'set-start!)] [get-start() ;* \ret{see below} ;* Returns the position in degrees where the arc begins. (get-tk-option '-start string->number 'get-start)] [set-extent! (val) ;* \ret{unspecified} ;* Sets the extent in degrees of the arc. (set-tk-option '-extent val swl:oknum? 'set-extent!)] [get-extent() ;* \ret{see below} ;* Returns the extent in degrees of the arc. (get-tk-option '-extent string->number 'get-extent)])) (swl:api-class (<oval> canvas x1 y1 x2 y2) (<2pt-figure> canvas x1 y1 x2 y2) ;% \swlapi{class}{<oval>}{(create <oval> canvas x1 y1 x2 y2)} ;* \ret{instance} ;* An oval appears as a circle or oval on the canvas that ;* may be filled with a color, or have an outline, or both. ;* The oval is inscribed within the rectangular region defined by ;* \var{x1}, \var{y1}, \var{x2}, \var{y2}. ;* The thickness and color of the oval's outline ;* can be specified as well. (ivars) (inherited) (inheritable) (private) (protected [tcl-name () 'oval]) (public)) (swl:api-class (<rectangle> canvas x1 y1 x2 y2) (<2pt-figure> canvas x1 y1 x2 y2) ;% \swlapi{class}{<rectangle>}{(create <rectangle> canvas x1 y1 x2 y2)} ;* \ret{instance} ;* A rectangle appears as a rectangular region on the canvas and may be ;* filled, have an outline or both. ;* The region covered by the rectangle is defined by ;* \var{x1}, \var{y1}, \var{x2}, \var{y2}. ;* The thickness and color of the outline ;* can be specified as well. (ivars) (inherited) (inheritable) (private) (protected [tcl-name () 'rectangle]) (public)) (define-swl-class (<multi-pt-figure> canvas) (<canvas-item> canvas) ;* An abstract class for figures that can be defined by several ;* points (lines and polygons). (ivars) (inherited parent handle) (inheritable parent handle) (private) (protected) (public [set-fill-color! (val) ;* \ret{unspecified} ;* Sets the color with which the interior of the figure is filled. ;* \var{val} is either the symbol \mytt{transparent}, a symbol naming a ;* color in \mytt{rgb.txt}, or ;* an instance of \scheme{<rgb>}. (set-color! '-fill val 'set-fill-color!)] [get-fill-color () ;* \ret{see below} ;* Returns the color with which the interior of the figure is filled. ;* The value returned is either the symbol \mytt{transparent}, a symbol ;* naming a color in \mytt{rgb.txt}, or ;* an instance of \scheme{<rgb>}. (get-color '-fill 'get-fill-color)] [set-line-thickness! (val) ;* \ret{unspecified} ;; could get via inheritance, not worth it? ;* Sets the thickness in pixels of the outline drawn around the figure. (set-tk-option '-width val swl:distance-unit? 'set-line-thickness!)] [get-line-thickness () ;* \ret{see below} ;; could get via inheritance, not worth it? ;* Returns the thickness in pixels of the outline drawn around the figure. (get-tk-option '-width string->number 'get-line-thickness)] [set-stipple! (val) ;* \ret{unspecified} ;* (currently unimplemented) (set-tk-option '-stipple val swl:bitmap? 'set-stipple!)] [get-stipple () ;* \ret{see below} ;* (currently unimplemented) (get-tk-option '-stipple tk->bitmap 'get-stipple)] [set-draw-spline! (val) ;* \ret{unspecified} ;* \var{val} is a boolean that determines whether or not the outline ;* of the figure is drawn as a spline. (set-tk-option '-smooth val boolean? 'set-draw-spline!)] [get-draw-spline () ;* \ret{boolean} ;* Returns a boolean that indicates whether or not the outline ;* of the figure is drawn as a spline. (get-tk-option '-smooth tk->boolean 'get-draw-spline)] [set-spline-steps! (val) ;* \ret{unspecified} ;* Sets the number of steps to use when drawing the spline. ;* If zero the figure is not drawn as a spline otherwise ;* a spline is drawn for every pair of line segments ;* using \var{val} segments for every pair (set-tk-option '-splinesteps val (lambda (x) (and (fixnum? x) (fxpositive? x))) 'set-spline-steps!) (set-tk-option '-smooth (not (fxzero? val)) boolean? #f)] [get-spline-steps () ;* \ret{integer} ;* Returns the number of steps to be used when drawing the spline. ;* If zero the figure is not drawn as a spline. (if (get-tk-option '-smooth tk->boolean 'get-spline-steps) (get-tk-option '-splinesteps string->number 'get-spline-steps) 0)])) (swl:api-class (<line> canvas x1 y1 x2 y2 . more) (<multi-pt-figure> canvas) ;% \swlapi{class}{<line>}{(create <line> canvas x1 y1 x2 y2 \dots)} ;* \ret{instance} ;* Lines are displayed as one or more connected line segments or ;* curves. The \scheme{init} method requires coordinates for a series of ;* two or more end-points of a series of connected line segments (or ;* curves). Lines can have arrow heads at either or both ends, and the ;* shape of the arrowhead can be adjusted. The end-points of a ;* line can drawn rounded, projecting, etc. The joints between line ;* segments (or curves) can be drawn beveled, mitered, or rounded. ;* The line can be smoothed as a spline, and the degree of ;* smoothness can be specified. Width can also be specified. (ivars) (inherited parent handle) (inheritable) (private) (protected) (public ;; could use cool object system dispatch to determine if we have rest args [init (p x1 y1 x2 y2 . more) ;* \ret{unspecified} ;* When creating a line, at least four numbers ;* must be given defining the endpoints of the line. ;* Additional coordinates specify endpoints of connecting ;* line segments. (swl:safety-check (unless (and (swl:oknum? x1) (swl:oknum? y1) (swl:oknum? x2) (swl:oknum? y2) (andmap swl:oknum? more) (fxeven? (length more))) (coords-error 'create (list* x1 y1 x2 y2 more)))) (set! handle (string->number (if (null? more) (swl:tcl-eval parent 'create 'line x1 y1 x2 y2) (apply swl:tcl-eval parent 'create 'line x1 y1 x2 y2 more)))) (post-init)] [set-coords! (x1 y1 x2 y2 . more) ;* \ret{unspecified} ;* Sets the coordinates for the line to ;* \var{x1}, \var{y1}, \var{x2}, \var{y2}, etc. (swl:safety-check (unless (and (swl:oknum? x1) (swl:oknum? y1) (swl:oknum? x2) (swl:oknum? y2) (andmap swl:oknum? more) (fxeven? (length more))) (coords-error 'set-coords! (list* x1 y1 x2 y2 more)))) (if (null? more) (swl:tcl-eval parent 'coords handle x1 y1 x2 y2) (apply swl:tcl-eval parent 'coords handle x1 y1 x2 y2 more)) (void)] [set-arrow-shape! (inner-length outer-length flair) ;* \ret{unspecified} ;* Sets the shape of the arrowheads drawn on the line. ;* \var{inner-length} gives the distance along the line ;* from the tip of the arrow head to its neck, ;* \var{outer-length} gives the distance along the line ;* to which the wide part of the arrowhead should extend, ;* and \var{flair} describes how far out from the line the ;* wide part of the arrowhead should extend. (swl:safety-check (unless (and (swl:distance-unit? inner-length) (swl:distance-unit? outer-length) (swl:distance-unit? flair)) (assertion-violationf 'set-arrow-shape! "bad value(s) ~s ~s ~s" inner-length outer-length flair))) (set-tk-option '-arrowshape (list inner-length outer-length flair) (lambda (x) x) 'set-arrow-shape!)] [get-arrow-shape () ;* \ret{see below} ;* Returns a list of three numbers describing the shape of the arrowhead ;* see \scheme{set-arrow-shape!} for details. (get-tk-option '-arrowshape swl:tcl->scheme 'get-arrow-shape)] [set-arrow-style! (val) ;* \ret{unspecified} ;* Determines where the arrowheads are drawn. \var{val} is either ;* \scheme{none}, \scheme{first}, \scheme{last}, or \scheme{both}. (set-tk-option '-arrow val (lambda (x) (memq x '(none first last both))) 'set-arrow-style!)] [get-arrow-style () ;* \ret{see below} ;* Returns a symbol describing where on the line the arrowheads ;* should be drawn. (get-tk-option '-arrow string->symbol 'get-arrow-style)] [set-join-style! (val) ;* \ret{unspecified} ;* Determines how the articulations between line segments are ;* drawn. \var{val} is either \scheme{bevel}, \scheme{miter}, or \scheme{round}. ;* The difference is only appreciable for thick lines. (set-tk-option '-joinstyle val (lambda (x) (memq x '(bevel miter round))) 'set-join-style!)] [get-join-style () ;* \ret{see below} ;* Returns a symbol describing how the joints between line segments are ;* drawn. (get-tk-option '-joinstyle string->symbol 'get-join-style)] [set-cap-style! (val) ;* \ret{unspecified} ;* Determines how caps are drawn at the endpoints of the line. ;* \var{val} is either \scheme{butt}, \scheme{projecting}, or \scheme{round}. (set-tk-option '-capstyle val (lambda (x) (memq x '(butt projecting round))) 'set-cap-style!)] [get-cap-style () ;* \ret{see below} ;* Returns a symbol describing ;* how caps are drawn at the endpoints of the line. (get-tk-option '-capstyle string->symbol 'get-cap-style)])) (swl:api-class (<polygon> canvas x1 y1 x2 y2 x3 y3 . more) (<multi-pt-figure> canvas) ;% \swlapi{class}{<polygon>}{(create <polygon> canvas x1 y1 x2 y2 x3 y3 \dots)} ;* \ret{instance} ;* A polygon is a closed figure with three or more points ;* and may be filled or drawn with an outline. (ivars) (inherited parent handle) (inheritable) (private) (protected) (public ;; could use cool object system dispatch to determine if we have rest args [init (p x1 y1 x2 y2 x3 y3 . more) ;* \ret{unspecified} ;* When creating a polygon, at least six numbers ;* must be given defining the vertices of the polygon. ;* Additional coordinates specify additional vertices. (swl:safety-check (unless (and (swl:oknum? x1) (swl:oknum? y1) (swl:oknum? x2) (swl:oknum? y2) (swl:oknum? x3) (swl:oknum? y3) (andmap swl:oknum? more) (fxeven? (length more))) (coords-error 'create (list* x1 y1 x2 y2 x3 y3 more)))) (set! handle (string->number (if (null? more) (swl:tcl-eval parent 'create 'polygon x1 y1 x2 y2 x3 y3) (apply swl:tcl-eval parent 'create 'polygon x1 y1 x2 y2 x3 y3 more)))) (post-init)] [set-coords! (x1 y1 x2 y2 x3 y3 . more) ;* \ret{unspecified} ;* Sets the coordinates of the polygon to ;* \var{x1}, \var{y1}, \var{x2}, \var{y2}, ;* \var{x3}, \var{y3}, etc. (swl:safety-check (unless (and (swl:oknum? x1) (swl:oknum? y1) (swl:oknum? x2) (swl:oknum? y2) (swl:oknum? x3) (swl:oknum? y3) (andmap swl:oknum? more) (fxeven? (length more))) (coords-error 'set-coords! (list* x1 y1 x2 y2 x3 y3 more)))) (if (null? more) (swl:tcl-eval parent 'coords handle x1 y1 x2 y2 x3 y3) (apply swl:tcl-eval parent 'coords handle x1 y1 x2 y2 x3 y3 more)) (void)] [set-outline-color! (val) ;* \ret{unspecified} ;* Sets the color in which the outline of the figure is drawn. ;* \var{val} is either a symbol naming a color in \mytt{rgb.txt} or ;* an instance of \scheme{<rgb>}. (set-tk-option '-outline val swl:color? 'set-outline-color!)] [get-outline-color () ;* \ret{see below} ;* Returns the color in which the outline of the figure is drawn. ;* The value returned is either a symbol naming a color in \mytt{rgb.txt} or ;* an instance of \scheme{<rgb>}. (get-tk-option '-outline tk->color 'get-outline-color)])) (define-swl-class (<1pt-figure> canvas x1 y1) (<canvas-item> canvas) ;* An abstract class for figures whose position on the canvas ;* is defined by a single point that anchors the figure. (ivars) (inherited parent handle) (inheritable parent handle) (private) (protected [tcl-name () 'ERROR]) (public [init (p x1 y1) ;* \ret{unspecified} ;* Two numbers must be given when creating an instance of this class. (swl:safety-check (unless (and (swl:oknum? x1) (swl:oknum? y1)) (coords-error 'create (list x1 y1)))) (set! handle (string->number (swl:tcl-eval parent 'create (tcl-name) x1 y1))) (post-init)] [set-coords! (x1 y1) ;* \ret{unspecified} ;* Sets the coordinates of the anchor for this figure to \var{x1}, \var{y1}. (swl:safety-check (unless (and (swl:oknum? x1) (swl:oknum? y1)) (coords-error 'set-coords! (list x1 y1)))) (swl:tcl-eval parent 'coords handle x1 y1) (void)] [set-anchor! (val) ;* \ret{unspecified} ;* Determines where the figure is displayed relative to its ;* coordinates. ;* Legal values are \scheme{n}, \scheme{s}, \scheme{e}, \scheme{w}, \scheme{ne}, \scheme{se}, ;* \scheme{sw}, \scheme{nw}, and \scheme{center}. (set-tk-option '-anchor val swl:anchor? 'set-anchor!)] [get-anchor () ;* \ret{symbol} ;* Returns a symbol describing where the figure is displayed ;* relative to its coordinates. (get-tk-option '-anchor string->symbol 'get-anchor)])) (swl:api-class (<canvas-image> canvas x1 y1) (<1pt-figure> canvas x1 y1) ;% \swlapi{class}{<canvas-image>}{(create <canvas-image> canvas x y)} ;* \ret{instance} ;* Images can display bitmaps, and images in GIF, or PPM, and PGM format. ;* They are not yet finished. (ivars (img #f)) (inherited parent handle) (inheritable) (private) (protected [tcl-name () 'image]) (public [set-image! (val) ;* \ret{unspecified} ;* Sets the image to display in this canvas item to \var{val} which ;* should be an instance of \scheme{<bitmap>} or \scheme{<photo>}. (set! img val) (set-tk-option '-image val isa-image? 'set-image!)] [get-image() ;* \ret{see below} ;* Returns the image to displayed by this canvas item. (get-tk-option '-image (lambda (x) (swl:lookup-widget (string->symbol x))) 'get-image)])) (swl:api-class (<canvas-text> canvas x1 y1) (<1pt-figure> canvas x1 y1) ;% \swlapi{class}{<canvas-text>}{(create <canvas-text> canvas x y)} ;* \ret{instance} ;* A canvas-text displays a string of characters in a canvas window. ;* The main differences between this and a \scheme{<text>} widget are that ;* \scheme{<canvas-text>} is a graphics object (so other figures can show ;* through or partially occlude the displayed string), and this ;* class lacks some of the fancier text-manipulation ability of ;* \scheme{<text>}. (ivars) (inherited parent handle) (inheritable) (private) (protected [tcl-name () 'text]) (public [set-title! (val) ;* \ret{unspecified} ;* Sets the string displayed by the figure. (set-tk-option '-text val string? 'set-title!)] [get-title () ;* \ret{see below} ;* Returns the string displayed by the figure. (get-tk-option '-text (lambda (x) x) 'get-title)] [set-fill-color! (val) ;* \ret{unspecified} ;* Sets the color with which the interior of the figure is filled. ;* \var{val} is either the symbol \mytt{transparent}, a symbol naming a ;* color in \mytt{rgb.txt}, or ;* an instance of \scheme{<rgb>}. (set-color! '-fill val 'set-fill-color!)] [get-fill-color () ;* \ret{see below} ;* Returns the color with which the interior of the figure is filled. ;* The value returned is either the symbol \mytt{transparent}, a symbol ;* naming a color in \mytt{rgb.txt}, or ;* an instance of \scheme{<rgb>}. (get-color '-fill 'get-fill-color)] [set-font! (val) ;* \ret{unspecified} ;* Sets the font for the text displayed. ;* \var{val} is an instance of \scheme{<font>} (see the description ;* of the \scheme{make-font} macro). (set-tk-option '-font val swl:font? 'set-font!)] [get-font () ;* \ret{see below} ;* Returns an instance of \scheme{<font>} describing the font ;* for text displayed by the figure. (get-tk-option '-font tk->font 'get-font)] [set-stipple! (val) ;* \ret{unspecified} ;* (unimplemented) (set-tk-option '-stipple val swl:bitmap? 'set-stipple!)] [get-stipple () ;* \ret{see below} ;* (unimplemented) (get-tk-option '-stipple tk->bitmap 'get-stipple)] [set-justify! (val) ;* \ret{unspecified} ;* Determines how lines are to be justified when multiple lines ;* are displayed. Legal values are \scheme{left}, \scheme{right}, and \scheme{center}. (set-tk-option '-justify val swl:justify? 'set-justify!)] [get-justify () ;* \ret{symbol} ;* Returns a symbol describing how lines are to be justified when ;* multiple lines ;* are displayed. (get-tk-option '-justify string->symbol 'get-justify)] [set-width! (val) ;* \ret{unspecified} ;* Lines longer than \var{val} characters will be wrapped onto the ;* next line. If zero, lines break only where there are ;* newline characters in the displayed string. (set-tk-option '-width val swl:distance-unit? 'set-width!)] [get-width () ;* \ret{integer} ;* Returns the width of the canvas text used in line breaking. (get-tk-option '-width string->number 'get-width)])) ;; Eventually ;; want to use this to make it all transparent so that people can ;; create buttons, etc. and just specify that they want to put it on ;; a canvas at x,y and bang, it happens. (swl:api-class (<canvas-sub-window> canvas x1 y1) (<1pt-figure> canvas x1 y1) ;% \swlapi{class}{<canvas-sub-window>}{(create <canvas-sub-window> canvas x y)} ;* \ret{instance} ;* A canvas-sub-window allows other widgets to be placed on a canvas ;* anchored at a particular point. We hope to make this process ;* transparent soon. (ivars) (inherited parent handle) (inheritable) (private) (protected [tcl-name () 'window]) (public [set-window! (val) ;* \ret{unspecified} ;* \var{val} is a widget to be placed on the canvas. (prop-set! 'window val) (set-tk-option '-window val isa-tk-widget? 'set-window!)] [get-window () ;* \ret{see below} ;* Returns the widget placed on the canvas in this sub-window. (prop-ref 'window)] [set-height! (val) ;* \ret{unspecified} ;* Sets the height in pixels of the sub-window. (set-tk-option '-height val swl:distance-unit? 'set-height!)] [get-height () ;* \ret{integer} ;* Returns the height in pixels of the sub-window. (get-tk-option '-height string->number 'get-height)] [set-width! (val) ;* \ret{unspecified} ;* Sets the width in pixels of the sub-window. (set-tk-option '-width val swl:distance-unit? 'set-width!)] [get-width () ;* \ret{integer} ;* Returns the width in pixels of the sub-window. (get-tk-option '-width string->number 'get-width)])) (define isa-canvas-item? (lambda (x) (send x isa? <canvas-item>)))
false
6f1e146a46b0028ebba16bfd84274f6fc28cd3c0
880304b2bb68f758f7fa5896f9dc4fb907030998
/8.ss
fdfdf6d1eff3010b633cf3390e7a1227848689c6
[]
no_license
chapmacl/PLC
e51c7c424880a191cd5ec0972621159421cdaa4b
fcb39f801fa066424dcae8eb80351a199ddf4b3d
refs/heads/master
2021-07-16T17:43:38.186406
2017-10-19T21:13:53
2017-10-19T21:13:53
107,576,768
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,240
ss
8.ss
;Clay Chapman ;Assignment 8 ;Problem 1 (define (slist-map proc slist) (let slist-map ([slist slist]) (cond [(null? slist) '()] [(symbol? (car slist)) (cons (proc (car slist)) (slist-map (cdr slist)))] [else (cons (slist-map (car slist)) (slist-map (cdr slist)))]))) (define (slist-reverse slist) (let slist-reverse ([slist slist]) (cond [(null? slist) '()] [(list? (car slist)) (append (slist-reverse (cdr slist)) (list (slist-reverse (car slist))))] [else (append (slist-reverse (cdr slist)) (list (car slist)))]))) (define (slist-depth slist) (let notate ([slist slist] [depth 0]) (cond [(null? slist) (+ 1 depth)] [(symbol? (car slist)) (max depth (notate (cdr slist) depth))] [else (max (notate (car slist) (+ 1 depth)) (notate (cdr slist) depth))]))) (define (slist-paren-count slist) (let notate ([slist slist]) (cond [(null? slist) 2] [(symbol? (car slist)) (notate (cdr slist))] [else (+ (notate (car slist)) (notate (cdr slist)))]))) (define (slist-symbols-at-depth slist d) (let notate ([slist slist] [depth 1]) (cond [(null? slist) '()] [(and (symbol? (car slist)) (equal? depth d)) (cons (car slist) (notate (cdr slist) depth))] [(symbol? (car slist)) (notate (cdr slist) depth)] [else (append (notate (car slist) (+ 1 depth)) (notate (cdr slist) depth))]))) ;Problem 2 (define group-by-two (lambda (lst) (cond [(null? lst) '()] [(null? (cdr lst)) (list (list (car lst)))] [else (cons (list (car lst) (cadr lst)) (group-by-two (cddr lst)))] ))) ;Problem 3 (define group-by-n (letrec ([helper (lambda (lst n) (cond [(or (null? lst) (zero? n)) '()] [else (cons (car lst) (helper (cdr lst) (- n 1)))] ))]) (lambda (lst n) (cond [(null? lst) '()] [(< (length lst) n) (list lst)] [else (cons (helper lst n) (group-by-n (list-at-n lst n) n))] )))) ;Helper to return a list at index n (define list-at-n (letrec ([loop (lambda (lst n) (cond [(null? lst) '()] [(not (zero? n)) (loop (cdr lst) (- n 1))] [else lst] ))]) (lambda (lst n) (if (< (length lst) n) '() (loop lst n))))) ;Problem 4 (define (subst-leftmost new old slist equality-pred?) (car (let loop ([slist slist]) (cond [(null? slist) (list '() #f)] [(and (symbol? (car slist)) (equality-pred? old (car slist))) (list (cons new (cdr slist)) #t)] [(symbol? (car slist)) (let ([result (loop (cdr slist))]) (list (cons (car slist) (car result)) (cadr result)))] [else (let ([result (loop (car slist))]) (cond [(cadr result) (list (cons (car result) (cdr slist)) #t)] [else (let ([result (loop (cdr slist))]) (list (cons (car slist) (car result)) (cadr result)))]))] ))))
false
d2ca6a6b38907e891b9379ca736d7113f51e69f7
710bd922d612840b3dc64bd7c64d4eefe62d50f0
/scheme/tool-sdoc/sdoc.scm
a5c88b29ba45604f7c19dba05bb77ed8f623f422
[ "MIT" ]
permissive
prefics/scheme
66c74b93852f2dfafd4a95e04cf5ec6b06057e16
ae615dffa7646c75eaa644258225913e567ff4fb
refs/heads/master
2023-08-23T07:27:02.254472
2023-08-12T06:47:59
2023-08-12T06:47:59
149,110,586
0
0
null
null
null
null
UTF-8
Scheme
false
false
8,387
scm
sdoc.scm
;;; -*- library: sdoc-core ; coding: iso-8859-1 -*- ;;; ;; = SDoc ;; ;; SDoc is a source code document system for the Scheme programming ;; language. ;;; ;; A file is parsed into either a comment-block or a code-block. A ;; comment-block contains the list of profils (i.e names that are ;; documented) and a documentation (the stuff contained in the ;; comment) ;; Here is the comment block abstract data type (define (make-comment-block doc) (list 'comment #f doc)) (define (comment-block? block) (and (pair? block) (eq? 'comment (car block)))) (define comment-block-profils cadr) (define comment-block-doc caddr) (define (add-comment-profil! comment profil) (set-car! (cdr comment) (cons profil (or (cadr comment) '())))) ;; Here is the code block abstract data type (define (make-code-block exp) (list 'code exp)) (define (code-block? block) (and (pair? block) (eq? 'code (car block)))) (define code-block-exp cadr) ;;; ;; Read from `port` as long as blanks are read and return the first ;; non blank character. ;; (define (skip-blanks port) (let ((ch (peek-char port))) (cond ((eof-object? ch) ch) ((char-whitespace? ch) (read-char port) (skip-blanks port)) (else ch)))) ;;; ;; Read (meaning parsing) of a source from `port` and return the ;; parsed representation (define (read-file port) (read-file-with-last-comment port #f)) (define (read-file-with-last-comment port current-comment-block) (let ((ch (skip-blanks port))) (cond ((eof-object? ch) '()) ((char=? ch #\;) (let* ((comment (read-comment-block port)) (block (make-comment-block comment))) (cons block (read-file-with-last-comment port block)))) (else (let* ((exp (read port)) (profil (exp->profil exp))) (if (and profil current-comment-block) (add-comment-profil! current-comment-block profil)) (cons (make-code-block exp) (read-file port))))))) (define (exp->profil exp) (if (pair? exp) (let ((head (car exp))) (if (eq? head 'define) (if (pair? (cadr exp)) (cadr exp) (if (and (pair? (caddr exp)) (eq? 'lambda (car (caddr exp)))) (cons (cadr exp) (cdr (caddr exp))) (cadr exp))) #f)) #f)) ;; Read a comment block (define (read-comment-block port) (let ((line (read-line port))) (let ((ch (peek-char port))) (cond ((eof-object? ch) line) ((char=? #\; ch) (string-append line "\n" (read-comment-block port))) (else line))))) ;;; ;; == Processing of a parsed file ;;; ;; Process a representation, that is the representation of a file or ;; parse file. (define (process-result representation) (for-each process-one representation)) (define (process-one representation) (cond ((code-block? representation) (process-code representation)) ((comment-block? representation) (process-comment representation)) (else (error "Unknown parsed representation of file ~a" representation)))) (define (correct-file-name name) (let ((current-file-name (the-file-name))) (string-append (file-name-nondirectory current-file-name) name))) (define (process-code code) (if (and (pair? code) (eq? (car code) 'define-structure)) (for-each (lambda (directive) (if (and (pair? directive) (eq? 'files (car directive))) (add-files-to-queue! (map correct-file-name (cdr directive))))) (cdr code)))) (define (process-comment comment) (let ((text (comment-block-doc comment))) (if (documentation-comment? text) (render-comment-block comment)))) (define (documentation-comment? comment) (let ((first-line (with-input-from-string comment read-line))) (let lp ((i 0)) (if (< i (string-length first-line)) (let ((ch (string-ref first-line i))) (and (or (char-whitespace? ch) (char=? ch #\;)) (lp (+ i 1)))) #t)))) (define (strip-comment-char comment) (with-input-from-string comment (lambda () (with-output-to-string (lambda () (let strip ((line (read-line))) (if (eof-object? line) 'ok (begin (display (substring line (find-start-of-non-comment line) (string-length line))) (newline) (strip (read-line)))))))))) (define (find-start-of-non-comment string) (let lp ((i 0)) (if (< i (string-length string)) (let ((ch (string-ref string i))) (if (char=? ch #\;) (lp (+ i 1)) (if (char-whitespace? ch) (+ i 1) i))) i))) ;;; ;; == Rendering components ;; ;; Rendering of comment blocks and code blocks. For now only comment ;; blocks are kept in the generated document. Code blocks could be ;; used to as source viewing inside the produced documentation. Keep ;; it on the todo list for now. (define (write-safe-html string) (let lp ((i 0)) (if (< i (string-length string)) (let ((ch (string-ref string i))) (cond ((char=? ch #\<) (display "&lt;")) ((char=? ch #\>) (display "&gt;")) ((char=? ch #\&) (display "&amp;")) (else (display ch))) (lp (+ i 1)))))) ;; Rendering of profils (define (render-profils profils) (display "<div class=\"profils\">\n") (for-each (lambda (p) (write-safe-html (with-output-to-string (lambda () (write p))))) profils) (display "</div>\n")) ;; Rendering of comment blocks (define (render-comment-block block) (display "<div class=\"doc\">\n") (let ((profils (comment-block-profils block))) (if profils (render-profils profils)) (let* ((text (comment-block-doc block)) (markup (strip-comment-char text))) (markup->html (read-markup-from-string markup)) (display "</div>\n")))) ;; Rendering of parsed document (define (render-document representation) (display "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" >\n<head>\n <title>Scheme Documentation</title>\n <style>\n body { font-size: small ; font-family: Arial, Helvetica, sans-serif; line-height: 120% }\n .profils { background: #eef; font-family: \"Courier New\", Courier, monospace ; padding-top: 2px; padding-bottom: 2px ; margin: 0px ; border-top: 1px solid #ccf }\n .doc h1 { font-size: 160% }\n .doc h2 { font-size: 130% }\n .doc p { margin-top: 10px }\n .doc { line-height: 1.2em ; font-size: 12px ; font-family: Arial, Helvetica, sans-serif}\n .doc tt { background: #eee; border: 1px solid #ddd ; font-size: 110%; padding: 1px }\n </style>\n</head>\n<body>\n") (process-result representation) (display "\n</body>\n</html>\n")) ;;; ;; == Top level processing of files ;; ;; Top level interface for generating documentation is done by the ;; `sdoc-file` procedure. (define $file$ (make-fluid #f)) (define (the-file-name) (or (fluid $file$) (error "No current file name set"))) (define (with-file-name name proc) (let-fluid $file$ name proc)) (define $output-directory$ (make-fluid "./")) (define (the-output-directory) (fluid $output-directory$)) (define (with-output-directory name thunk) (let-fluid $output-directory$ name thunk)) (define (correct-output-file name) (string-append (the-output-directory) (replace-extension (file-name-nondirectory name) ".html"))) (define (sdoc-file file-name) (with-file-name file-name (lambda () (let ((repr (call-with-input-file file-name (lambda (port) (read-file port))))) (with-output-to-file (correct-output-file file-name) (lambda () (render-document repr))))))) (define *file-queue* '()) (define (add-files-to-queue! files) (set! *file-queue* (append *file-queue* files))) (define (file-queue-empty?) (null? *file-queue*)) (define (pop-file-from-queue!) (let ((front (car *file-queue*))) (set! *file-queue* (cdr *file-queue*)) front)) (define (process-file-queue) (if (not (file-queue-empty?)) (let ((file (pop-file-from-queue!))) (sdoc-file file) (process-file-queue)))) ;; Main entry point the script (define (main args) (let lp ((args args)) (if (not (null? args)) (let ((arg (car args))) (if (string=? arg "-o") (with-output-directory (cadr args) (lambda () (lp (cddr args)))) (begin (sdoc-file arg) (lp (cdr args))))))))
false
bc39d58239b031947817803711f6d457dd6f844e
f87e36a1ba00008d7e957c8595c86b5550af05b9
/ch4/ex4.73.scm
755eae9d5b07df01e85998699326d8de4dc5b02e
[]
no_license
kouheiszk/sicp
1b528898f825c0716acce6bdb36d378dcb04afec
eeb2f7d7634284faa7158c373a848b84084cc8cb
refs/heads/master
2020-04-16T07:00:43.135389
2014-06-16T11:57:43
2014-06-16T11:57:43
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
133
scm
ex4.73.scm
;;; ex4.73 ;; flatten-streamに渡るstreamが無限ストリームだった場合に ;; flatten-streamが無限ループに陥る
false
a06183a864bbd2ec1991350324f35bd43526fee5
3b74241704f1317aef4e54ce66494a4787b0b8c0
/AtCoder/typical90/001.scm
a99adff59d227870c3ce67b49ca26ad3658d3a7c
[ "CC0-1.0" ]
permissive
arlechann/atcoder
990a5c3367de23dd79359906fd5119496aad6eee
a62fa2324005201d518b800a5372e855903952de
refs/heads/master
2023-09-01T12:49:34.034329
2023-08-26T17:20:36
2023-08-26T17:20:36
211,708,577
0
0
CC0-1.0
2022-06-06T21:49:11
2019-09-29T18:37:00
Rust
UTF-8
Scheme
false
false
1,540
scm
001.scm
(define (id x) x) (define (inc n) (+ n 1)) (define (dec n) (- n 1)) (define (ceil-quotient a b) (quotient (dec (+ a b)) b)) (define (diff a b) (abs (- a b))) (define (read-times n) (let rec ((i 0) (ret '())) (if (= i n) (reverse! ret) (rec (inc i) (cons (read) ret))))) (define (sum ls) (reduce + 0 ls)) (define (maplist-1 proc ls) (if (null? ls) '() (cons (proc ls) (maplist-1 proc (cdr ls))))) ;; TODO (define (maplist proc ls) (maplist-1 proc ls)) (define (meguru-method ok ng pred) (let ((mid (quotient (+ ok ng) 2))) (cond ((< (diff ok ng) 2) ok) ((pred mid) (meguru-method mid ng pred)) (else (meguru-method ok mid pred))))) (define (main args) (let* ((n (read)) (l (read)) (k (read)) (a (read-times n))) (let ((result (solve n l k a))) (display result) (newline))) 0) (define (solve n l k a) (let ((a (append! a (list l)))) (meguru-method 0 1000000001 (lambda (min-length) (can-cut-yokan n k a min-length))))) (define (can-cut-yokan n k a min-length) (let ((yokan-count (count-yokan-piece 0 a min-length))) (> yokan-count k))) (define (count-yokan-piece init ls min-length) (cdr (fold (lambda (x acc) (let ((prev (car acc)) (count (cdr acc))) (let ((d (diff x prev))) (if (>= d min-length) (cons x (inc count)) acc)))) (cons init 0) ls)))
false
c1c346deb7fccbfde6514107aa9301d1eb2983e0
4b480cab3426c89e3e49554d05d1b36aad8aeef4
/chapter-04/ch4-myeval-for-lazy-comkid.scm
58ee135761a54be8a726d252c56e04abf7b0766c
[]
no_license
tuestudy/study-sicp
a5dc423719ca30a30ae685e1686534a2c9183b31
a2d5d65e711ac5fee3914e45be7d5c2a62bfc20f
refs/heads/master
2021-01-12T13:37:56.874455
2016-10-04T12:26:45
2016-10-04T12:26:45
69,962,129
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,176
scm
ch4-myeval-for-lazy-comkid.scm
(load "../misc/myeval-helper.scm") (define (actual-value exp env) (force-it (myeval exp env))) (define (thunk? obj) (tagged-list? obj 'thunk)) (define (thunk-exp thunk) (cadr thunk)) (define (thunk-env thunk) (caddr thunk)) (define (delay-it exp env) (list 'thunk exp env)) (define (list-of-arg-values exps env) (if (no-operands? exps) '() (cons (actual-value (first-operand exps) env) (list-of-arg-values (rest-operands exps) env)))) (define (list-of-delayed-args exps env) (if (no-operands? exps) '() (cons (delay-it (first-operand exps) env) (list-of-delayed-args (rest-operands exps) env)))) (define (myeval exp env) (cond ((self-evaluating? exp) exp) ((variable? exp) (lookup-variable-value exp env)) ((quoted? exp) (text-of-quotation exp)) ((assignment? exp) (eval-assignment exp env)) ((definition? exp) (eval-definition exp env)) ((if? exp) (eval-if exp env)) ((lambda? exp) (make-procedure (lambda-parameters exp) (lambda-body exp) env)) ((begin? exp) (eval-sequence (begin-actions exp) env)) ((cond? exp) (myeval (cond->if exp) env)) ((application? exp) (myapply ;(myeval (operator exp) env) -- for ex4.28 (actual-value (operator exp) env) (operands exp) env)) (else (error "Unknown expression type -- EVAL" exp)))) (define (myapply procedure arguments env) (cond ((primitive-procedure? procedure) (apply-primitive-procedure procedure (list-of-arg-values arguments env))) ((compound-procedure? procedure) (eval-sequence (procedure-body procedure) (extend-environment (procedure-parameters procedure) (list-of-delayed-args arguments env) (procedure-environment procedure)))) (else (display "Unknown procedure type -- APPLY") (display procedure) (newline)))) ;(load "../misc/myeval-test.scm")
false
306c084de60bd273e242dbf4cfd42c772bbba9be
5a68949704e96b638ca3afe335edcfb65790ca20
/kohlbecker/modern/kohl.scm
b6b6f8345af92d73dda4f37420262a6b2309fd23
[]
no_license
terryc321/lisp
2194f011f577d6b941a0f59d3c9152d24db167b2
36ca95c957eb598facc5fb4f94a79ff63757c9e5
refs/heads/master
2021-01-19T04:43:29.122838
2017-05-24T11:53:06
2017-05-24T11:53:06
84,439,281
2
0
null
null
null
null
UTF-8
Scheme
false
false
6,110
scm
kohl.scm
(define naive-expand (lambda (form) (if (not (pair? form)) form (case (car form) ((quote) form) ((lambda) `(lambda ,(cadr form) ,@(map naive-expand (cddr form)))) ((set!) `(set! ,(cadr form) ,(naive-expand (caddr form)))) ((if) `(if ,@(map naive-expand (cdr form)))) (else (if (macro-tag? (car form)) (naive-expand ((macro-transformer (car form)) form)) (map naive-expand form))))))) (define *macro-transformers* '()) (define macro-tag? (lambda (tag) (and (symbol? tag) (assq tag *macro-transformers*)))) (define macro-transformer (lambda (tag) (cdr (assq tag *macro-transformers*)))) (define macro-transformer-set! (lambda (tag transformer) (let ((pair (assq tag *macro-transformers*))) (if pair (set-cdr! pair transformer) (set! *macro-transformers* (cons (cons tag transformer) *macro-transformers*)))))) (macro-transformer-set! 'push ; (push a l) (lambda (form) ; ==> (set! l (cons a l)) `(set! ,(caddr form) (cons ,(cadr form) ,(caddr form))))) (macro-transformer-set! 'let ; (let ((var init) ...) (lambda (form) ; body ...) `((lambda ,(map car (cadr form)) ; ==> ((lambda (var ...) ,@(cddr form)) ; body ...) ,@(map cadr (cadr form))))) ; init ...) (macro-transformer-set! 'or (lambda (form) (cond ((null? (cdr form)) ; (or) '#f) ; ==> #f ((null? (cddr form)) ; (or e) (cadr form)) ; ==> e (else ; (or e1 e2 ...) `((lambda (temp) ; ==> ((lambda (temp) (if temp ; (if temp temp ; temp (or ,@(cddr form)))) ; (or e2 ...))) ,(cadr form)))))) ; e1) (macro-transformer-set! 'catch (lambda (form) `(call-with-current-continuation (lambda (,(capture 'throw)) ,(cadr form))))) ;;; kohlbecker algorithm ;; ftp://ftp.cs.indiana.edu/pub/scheme-repository/doc/misc/macros-02.txt (define *top-mark* #f) (define kohlbecker-expand (lambda (form) (set! *top-mark* (make-new-mark)) (unmark (alpha-convert (expand-marked (mark form *top-mark*)))))) (define capture (lambda (var) (make-identifier var *top-mark*))) ;; version without variable capture ;; (define kohlbecker-expand ;; (lambda (form) ;; (unmark ;; (alpha-convert ;; (expand-marked ;; (mark form (make-new-mark))))))) (define mark (lambda (s stamp-value) (cond ((or (identifier? s) (macro-tag? s) (reserved-word? s)) s) ((symbol? s) (make-identifier s stamp-value)) ((pair? s) (map (lambda (z) (mark z stamp-value)) s)) (else s)))) (define reserved-word? (lambda (x) (memq x '(quote lambda set! if)))) (define expand-marked (lambda (mform) (if (not (pair? mform)) mform (case (car mform) ((quote) mform) ((lambda) `(lambda ,(cadr mform) ,@(map expand-marked (cddr mform)))) ((set!) `(set! ,(cadr mform) ,(expand-marked (caddr mform)))) ((if) `(if ,@(map expand-marked (cdr mform)))) (else (if (macro-tag? (car mform)) (expand-marked (mark ((macro-transformer (car mform)) mform) (make-new-mark))) (map expand-marked mform))))))) (define alpha-convert (lambda (mform) (if (not (pair? mform)) mform (case (car mform) ((lambda) (alpha-convert-lambda (cadr mform) (map alpha-convert (cddr mform)))) ((quote) (unmark mform)) ((set!) `(set! ,(cadr mform) ,(alpha-convert (caddr mform)))) ((if) `(if ,@(map alpha-convert (cdr mform)))) (else (map alpha-convert mform)))))) (define alpha-convert-lambda (lambda (varlist body) (let ((substitutions (make-substitution-info varlist))) `(lambda ,(perform-substitutions substitutions varlist) ,@(perform-substitutions substitutions body))))) (define make-substitution-info (lambda (varlist) (map (lambda (id) (cons id (identifier->unique-symbol id))) varlist))) (define perform-substitutions (lambda (substitutions s) (cond ((identifier? s) (let ((entry (assoc-id s substitutions))) (if entry (cdr entry) s))) ((not (pair? s)) s) (else (cons (perform-substitutions substitutions (car s)) (perform-substitutions substitutions (cdr s))))))) (define unmark (lambda (s) (cond ((identifier? s) (identifier->symbol s)) ((pair? s) (map unmark s)) (else s)))) (define make-new-mark (let ((v 0)) (lambda () (begin (set! v (+ v 1)) v)))) (define mark=? =) (define make-identifier (lambda (name mark) (vector 'IDENTIFIER name mark))) (define identifier->symbol (lambda (x) (vector-ref x 1))) (define identifier-mark (lambda (x) (vector-ref x 2))) (define identifier? (lambda (x) (and (vector? x) (= (vector-length x) 3) (eq? (vector-ref x 0) 'IDENTIFIER)))) (define identifier=? (lambda (x y) (and (identifier? x) (identifier? y) (eq? (identifier->symbol x) (identifier->symbol y)) (mark=? (identifier-mark x) (identifier-mark y))))) (define assoc-id (lambda (id s) (cond ((null? s) #f) ((identifier=? id (caar s)) (car s)) (else (assoc-id id (cdr s)))))) (define identifier->unique-symbol (lambda (x) (gensym))) ;; comment out this identifier->unique-symbol -- its only for education purposes ;; it DOES NOT generate unique symbols !! ;; (define identifier->unique-symbol ;; (lambda (x) ;; (string->symbol ;; (string-append (symbol->string (identifier->symbol x)) ;; ":" ;; (number->string (identifier-mark x)))))) (define demo0 (kohlbecker-expand '(let ((temp 37.0)) (or (foo temp) temp)))) (define demo1 (kohlbecker-expand '(let ((cons '())) (push "ghengis" cons) (push "khubla" cons) cons)))
false
93014e8f03052751769bba8ae28f3479ab4742d3
84c9e7520891b609bff23c6fa3267a0f7f2b6c2e
/1.43.scm
c39b90d3213648e29e310a24bda77e731d2ad15a
[]
no_license
masaedw/sicp
047a4577cd137ec973dd9a7bb0d4f58d29ef9cb0
11a8adf49897465c4d8bddb7e1afef04876a805d
refs/heads/master
2020-12-24T18:04:01.909864
2014-01-23T11:10:11
2014-01-23T11:17:38
6,839,863
1
0
null
null
null
null
UTF-8
Scheme
false
false
212
scm
1.43.scm
(load "./misc.scm") (define (compose f g) (lambda (x) (f (g x)))) (define (repeated f n) (if (= n 1) f (compose f (repeated f (- n 1))))) (define (main args) (print ((repeated inc 6) 5)))
false
7ecea04b70bb074cf7b395ea516b94b4defbae84
bf1c9803ae38f9aad027fbe4569ccc6f85ba63ab
/chapter_4/4.4.Logic.Programming/ex_4.79.scm
f87b59bcca6dcb8658127648ea5d5bd71effd5cf
[]
no_license
mehese/sicp
7fec8750d3b971dd2383c240798dbed339d0345a
611b09280ab2f09cceb2479be98ccc5403428c6c
refs/heads/master
2021-06-12T04:43:27.049197
2021-04-04T22:22:47
2021-04-04T22:23:12
161,924,666
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,379
scm
ex_4.79.scm
;; Exercise 4.79: When we implemented the Lisp evaluator in 4.1, we saw how to use local environments ;; to avoid name conflicts between the parameters of procedures. For example, in evaluating ;; ;; (define (square x) ;; (* x x)) ;; ;; (define (sum-of-squares x y) ;; (+ (square x) (square y))) ;; ;; (sum-of-squares 3 4) ;; ;; there is no confusion between the x in square and the x in sum-of-squares, because we evaluate the body ;; of each procedure in an environment that is specially constructed to contain bindings for the local ;; variables. In the query system, we used a different strategy to avoid name conflicts in applying rules. ;; Each time we apply a rule we rename the variables with new names that are guaranteed to be unique. The ;; analogous strategy for the Lisp evaluator would be to do away with local environments and simply rename ;; the variables in the body of a procedure each time we apply the procedure. ;; ;; Implement for the query language a rule-application method that uses environments rather than renaming. ;; See if you can build on your environment structure to create constructs in the query language for dealing ;; with large systems, such as the rule analog of block-structured procedures. Can you relate any of this ;; to the problem of making deductions in a context (e.g., “If I supposed that P were true, then I would be ;; able to deduce A and B .”) as a method of problem solving? (This problem is open-ended. A good answer ;; is probably worth a Ph.D.) ;; Well, as it's a Ph.D. level problem (and open ended), I'll skip this problem, since I'll still probaly be ;; able to brag about "having done SICP" without doing this particular problem. In all fairness, probably the ;; Ph.D. level bit is not exactly limited at implementing a barebones env structure, as much as the ;; large-systems implementation. ;; ;; I found two attempts at solutions on Github ;; ;; https://github.com/skanev/playground/blob/master/scheme/sicp/04/79.scm ;; ;; https://github.com/soulomoon/SICP/blob/master/Chapter4/Exercise4.79.scm ;; ;; The second one is a bit unclear to me. The first solution seems to be using environments that have ;; special variables that indicate that their value is identical to that of the one in a parent frame. ;; If I was to implement this I would use the first solution as a reference.
false
18fb020d61bec7382cd53257c47ab91c6faaace5
60da79cf89177b72152d8aab846e21e4a5f4644f
/sicp2-1-4.scm
ec857f1b08b7fa983031f1b7942c3c8517862237
[]
no_license
deltam/sicp-reading
6dfa6a608f40085eba5821436a3eaef2d1024b6c
c05c3a97fb201da89890887e6bacef3a1abab41c
refs/heads/master
2021-01-19T14:56:05.349608
2014-05-18T17:56:47
2014-05-18T17:56:47
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,805
scm
sicp2-1-4.scm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; 2.1.4 拡張問題:区間算術演算 (define (add-interval x y) (make-interval (+ (lower-bound x) (lower-bound y)) (+ (upper-bound x) (upper-bound y)))) (define (mul-interval x y) (let ((p1 (* (lower-bound x) (lower-bound y))) (p2 (* (lower-bound x) (upper-bound y))) (p3 (* (upper-bound x) (lower-bound y))) (p4 (* (upper-bound x) (upper-bound y)))) (make-interval (min p1 p2 p3 p4) (max p1 p2 p3 p4)))) (define (div-interval x y) (mul-interval x (make-interval (/ 1.0 (upper-bound y)) (/ 1.0 (lower-bound y))))) ;;;; Q 2.7 区間演算の選択子を定義する (define (make-interval a b) (cons a b)) (define (upper-bound x) (cdr x)) (define (lower-bound x) (car x)) (define x (make-interval 10 14)) (upper-bound x) ;> 14 (lower-bound x) ;> 10 ;;;; Q 2.8 差の演算 ;;; マイナスの区間を加算する ;;; 区間のマイナスは、(ー下限,ー上限)とする (define (sub-interval x y) (add-interval x (make-interval (- (upper-bound y)) (- (lower-bound y))))) (define x (make-interval 1 2)) (define y (make-interval 4 5)) (add-interval x y) ;> (5 . 7) (sub-interval x y) ;> (-4 . -2) ;; 検算 (sub-interval (add-interval x y) y) ;> (0 . 3) ;; ??? (1 . 2)にならない? ;;;; Q 2.9 ?? ;;; いままで定義した演算について、計算結果の幅と計算前引数(x,yなど)の幅の関係について問うている? ;;; 計算結果の幅だけ欲しいならば、引数の区間の幅だけで計算できる ;;; 和と差の幅は、引数の幅だけで計算可能なことを示せばよいか。 ;;;; Q 2.10 0をまたがる区間 ;;; make-interval を書き換えたほうがいいような気がする (define x (make-interval 1 2)) (define y (make-interval -1 3)) (div-interval x y) (define (div-print y) (display (/ 1.0 (upper-bound y))) (newline) (display (/ 1.0 (lower-bound y)))) (div-print y) ;> 0.3333333333333333 ;-1.0#<undef> ;;; 区間の大小が逆転してる (define (div-interval2 x y) (let ((lower (/ 1.0 (upper-bound y))) (upper (/ 1.0 (lower-bound y)))) (if (> lower upper) (error "error!") (mul-interval x (make-interval lower upper))))) (define x (make-interval 1 2)) (define y (make-interval -1 3)) (div-interval2 x y) ;> *** ERROR: error! (define x (make-interval 1 2)) (define y (make-interval 1 3)) (div-interval2 x y) ;> (0.3333333333333333 . 2.0) (div-interval x y) ;> (0.3333333333333333 . 2.0) ;;; OK ;;;; Q 2.11 ;;; 区間の端がマイナス・ゼロ・プラスの場合か。3*3で9パターン
false
7ad4651a4e7b63c8c8b4db19a049c23d7003da15
bf6fad8f5227d0b0ef78598065c83b89b8f74bbc
/chapter03/ex3_3_3.ss
b765edc3a997f6f3e7c3d1c36d4f345bd900de90
[]
no_license
e5pe0n/tspl
931d1245611280457094bd000e20b1790c3e2499
bc76cac2307fe9c5a3be2cea36ead986ca94be43
refs/heads/main
2023-08-18T08:21:29.222335
2021-09-28T11:04:54
2021-09-28T11:04:54
393,668,056
0
0
null
null
null
null
UTF-8
Scheme
false
false
629
ss
ex3_3_3.ss
(define print (lambda (x) (for-each display `(,x "\n")) ) ) (define lwp-list `()) (define lwp (lambda (thunk) (set! lwp-list (append lwp-list (list thunk))) ) ) (define start (lambda () (call/cc (lambda (k) (set! quit-k k) (next) ) ) ) ) (define next (lambda () (let ([p (car lwp-list)]) (set! lwp-list (cdr lwp-list)) (p) ) ) ) (define pause (lambda () (call/cc (lambda (k) (lwp (lambda () (k #f))) (next) ) ) ) ) (define quit (lambda (v) (if (null? lwp-list) (quit-k v) (next) ) ) )
false
bd91bbbb1efa0f90b5d43574dee65230d3613282
958488bc7f3c2044206e0358e56d7690b6ae696c
/scheme/counter.scm
aae6fc6b4b8569fb1796eb440efc7fe9ceb37198
[]
no_license
possientis/Prog
a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4
d4b3debc37610a88e0dac3ac5914903604fd1d1f
refs/heads/master
2023-08-17T09:15:17.723600
2023-08-11T12:32:59
2023-08-11T12:32:59
40,361,602
3
0
null
2023-03-27T05:53:58
2015-08-07T13:24:19
Coq
UTF-8
Scheme
false
false
194
scm
counter.scm
(define (counter) (let ((n 0)) (lambda () (set! n (+ n 1)) n))) (define (counter2) (apply (lambda (n) (lambda () (set! n (+ n 1)) n)) '(0)))
false
7b21916612bf08cf01cb9893879d316701bc85e1
a19495f48bfa93002aaad09c6967d7f77fc31ea8
/src/kanren/kanren/mini/minikanrensupport.scm
2a6cc8af59117390f6835edb7ebb0e8673b61936
[ "Zlib" ]
permissive
alvatar/sphere-logic
4d4496270f00a45ce7a8cb163b5f282f5473197c
ccfbfd00057dc03ff33a0fd4f9d758fae68ec21e
refs/heads/master
2020-04-06T04:38:41.994107
2014-02-02T16:43:15
2014-02-02T16:43:15
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
8,331
scm
minikanrensupport.scm
'(define-syntax def-syntax (syntax-rules () ((_ (name . lhs) rhs) (define-syntax name (syntax-rules () ((_ . lhs) rhs)))))) (print-gensym #f) (define-syntax lambda@ (syntax-rules () ((_ () body0 body1 ...) (lambda () body0 body1 ...)) ((_ (formal) body0 body1 ...) (lambda (formal) body0 body1 ...)) ((_ (formal0 formal1 formal2 ...) body0 body1 ...) (lambda (formal0) (lambda@ (formal1 formal2 ...) body0 body1 ...))))) (define-syntax @ (syntax-rules () ((_ rator) (rator)) ((_ rator rand) (rator rand)) ((_ rator rand0 rand1 rand2 ...) (@ (rator rand0) rand1 rand2 ...)))) (define-syntax test-check (syntax-rules () ((_ title tested-expression expected-result) (begin (cout "Testing " title nl) (let* ((expected expected-result) (produced tested-expression)) (or (equal? expected produced) (errorf 'test-check "Failed: ~a~%Expected: ~a~%Computed: ~a~%" 'tested-expression expected produced))))))) (define nl (string #\newline)) (define (cout . args) (for-each (lambda (x) (if (procedure? x) (x) (display x))) args)) (define empty-s '()) (define var vector) ;;;;; (and needs explaining) (define var? vector?) (define ground? (lambda (v) (cond ((var? v) #f) ((pair? v) (and (ground? (car v)) (ground? (cdr v)))) (else #t)))) (define rhs cdr) (define lhs car) (define ext-s (lambda (x v s) (cons (cons x v) s))) ; Some terminology related to variables and substitutions ; ; A substitution subst is a finite map { xi -> ti ... } ; where xi is a logic variable. ; ti is a term ::= variable | Scheme-atom | (cons term term) ; A variable x is free in the substitution subst if x \not\in Dom(subst) ; ; Given a term t and a substitution subst, a weak reduction ; t -->w t' ; is defined as ; x -->w subst[x] if x is a var and x \in Dom(subst) ; t -->w t otherwise ; ; A strong reduction ; t -->s t' ; is defined as ; x -->s subst[x] if x is a var and x \in Dom(subst) ; (cons t1 t2) -->s (cons t1' t2') ; where t1 -->s t1' t2 -->s t2' ; t -->s t otherwise ; ; The notion of reduction can be extended to substitutions themselves: ; { xi -> ti ...} -->w { xi -> ti' } where ti -> ti' ; ditto for -->s. ; Let -->w* be a reflexive transitive closure of -->w, and ; let -->w! be a fixpoint of -->w. Ditto for -->s* and -->s! ; For acyclic substitutions, the fixpoints exist. ; ; The confluence of the reduction is guaranteed by the particular form ; of the substitution produced by the unifier (the unifier always ; deals with the weak normal forms of submitted terms). ; ; The similarity of the weak normalization with call-by-value and ; the strong normalization with the applicative-order reduction should ; be apparent. ; ; Variable x is called ultimately free if ; x -->w! x' and x' is free in the subtutution in question. ; ; Two ultimately free variables x and y belong to the same equivalence class ; if x -->w! u and y -->w! u ; The (free) variable u is the natural class representative. ; For the purpose of presentation, one may wish for a better representative. ; Given a set of equivalent variables xi -->w! u, ; a pretty representative is a member z of that set such that the ; string name of 'z' is lexicographically smaller than the string names ; of the other variables in that set. ; ; If a variable x is ultimately free in subst and x ->w! u, ; then there is a binding ; v1 -> v2 where both v1 and v2 are variables and v2 ->w! u. Furthermore, ; the set of all such v1 union {u} is the whole equivalence class of x. ; That property is guaranteed by the unifier. That property lets us ; build an inverse index to find the equivalence class of x. ; In this version (May 2005), the representation of substitutions differs ; from the one outlined above. ; Besides the proper mappings xi -> ti, the substitutions in minikanren ; may contain mappings xi -> xi. Such a mapping is to be considered ; not a part of substitution proper. Rather, that mapping is to be considered ; a ``birth record'' for a logical variable xi. A free variable is defined ; as the one that is ``bound to itself''. A substitution may now have ; several bindings for the same variable. Only the last one takes effect. ; The old invariant that the substitution has at most one binding for ; each variable no longer holds. We have a new invariant: each logical ; variable has at least one binding in the substitution list. ; Birth records give us a way to implement eigen safely, and once safely. ; Also, birth record may speed up unification. Before that, the only way ; to know if a variable is free is to scan the whole subtutution. ; Now we need to scan only to the birth record, which is quite close ; (oftentimes, really close -- most created logical variables are bound ; soon). (define unbound-binding? (lambda (binding) (eq? (lhs binding) (rhs binding)))) ; Compute the list of (free) variables of a term t, in the depth-first ; term-traversal order; we know that v^ has been walked-strongly. (define free-vars (lambda (v^) (reverse (fv v^ '())))) (define fv (lambda (v^ acc) (cond ((var? v^) (if (memq v^ acc) acc (cons v^ acc))) ((pair? v^) (fv (cdr v^) (fv (car v^) acc))) (else acc)))) ; Given a term v and a subst s, return v', the weak normal form of v: ; v -->w! v' with respect to s ; NB! This procedure is to be called only if 'x' has been tested ; as a variable! (define walk (lambda (x s) (cond ((assq x s) => (lambda (pr) (let ((v (rhs pr))) (cond ((unbound-binding? pr) v) ; pr is a birth record ((var? v) (walk v s)) (else v))))) (else x)))) ; Given a term v and a subst s, return v', the strong normal form of v: ; v -->s! v' with respect to s (define walk* (lambda (v s) (cond ((var? v) (let ((v (walk v s))) (cond ((var? v) v) (else (walk* v s))))) ((pair? v) (cons (walk* (car v) s) (walk* (cdr v) s))) (else v)))) (define reify (lambda (v s) (re (walk* v s)))) (define re (lambda (v^) (walk* v^ (name-s (free-vars v^))))) ; Given the list of free variables and the initial index, ; create a subst { v -> pretty-name-indexed } ; where pretty-name-indexed is the combination of "_" (indicating ; a free variable) and the index ".0", ".1", etc. (define name-s (lambda (fv) (ns fv 0))) (define ns (lambda (fv c) (cond ((null? fv) empty-s) (else (ext-s (car fv) (reify-id c) (ns (cdr fv) (+ c 1))))))) (define reify-id ;;;;; NEW (lambda (index) (string->symbol (string-append "_$_{_{" (number->string index) "}}$")))) (define reify-id ;;;; NEW (lambda (c) (string->symbol (string-append "_." (number->string c))))) (define unify (lambda (v w s) (let ((v (if (var? v) (walk v s) v)) (w (if (var? w) (walk w s) w))) (cond ((eq? v w) s) ((var? v) (ext-s v w s)) ((var? w) (ext-s w v s)) ((and (pair? v) (pair? w)) (cond ((unify (car v) (car w) s) => (lambda (s) (unify (cdr v) (cdr w) s))) (else #f))) ((equal? v w) s) (else #f))))) (define unify-check (lambda (v w s) (let ((v (if (var? v) (walk v s) v)) (w (if (var? w) (walk w s) w))) (cond ((eq? v w) s) ((var? v) (ext-s-check v w s)) ((var? w) (ext-s-check w v s)) ((and (pair? v) (pair? w)) (cond ((unify-check (car v) (car w) s) => (lambda (s) (unify-check (cdr v) (cdr w) s))) (else #f))) ((equal? v w) s) (else #f))))) (define ext-s-check (lambda (v w s) (cond ((occurs? v w s) #f) (else (ext-s v w s))))) (define occurs? (lambda (x v s) (cond ((var? v) (let ((v (walk v s))) (cond ((var? v) (eq? v x)) (else (occurs? x v s))))) ((pair? v) (or (occurs? x (car v) s) (occurs? x (cdr v) s))) (else #f))))
true
ce64a1155693a8e8e197a97151e21380d7417121
afc89799bda289c12d6d7153d7643379434e6a52
/nabs/targets.scm
3904b0682f4dc45c7cb7785324d4edc38bc53ff8
[ "MIT" ]
permissive
PlumpMath/nabs
b72763467de6ff076fb40efddc54f6432f35065f
9459fdfd316c862ec263525ecb2197a4afdd5a26
refs/heads/master
2021-01-18T22:15:27.314873
2014-05-21T14:52:47
2014-05-21T14:52:47
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,419
scm
targets.scm
(define-module (nabs targets) :use-module (nabs invoke) :use-module (ice-9 vlist) :use-module (ice-9 rdelim) :use-module (ice-9 regex) :use-module (rnrs io ports) :use-module (gnu make) ) (define (split-targets-and-prereqs line) (let* ((targets-and-prereqs (string-split line #\:)) (targets (string-tokenize (car targets-and-prereqs))) (prereqs (string-tokenize (cadr targets-and-prereqs)))) (list targets prereqs))) (define (find-all-rules-in lines) (let* ((re (make-regexp "^([^#.% \t][^%:= ]+ *)+:([^:=]|$)"))) (map split-targets-and-prereqs (filter (lambda (l) (regexp-exec re l)) lines)))) (define-public (find-all-rules makefile...) (if (null? makefile...) '() (append (find-all-rules-in (car makefile...)) (find-all-rules (cdr makefile...))))) (define-public (make-table all-rules... op) (define (fill-with-prereqs prereqs... table) (cond ((null? prereqs...) table) ((vhash-assoc (car prereqs...) table) (fill-with-prereqs (cdr prereqs...) table)) (#t (fill-with-prereqs (cdr prereqs...) (vhash-cons (car prereqs...) #t table))))) (define (fill-with-all-prereqs rules... table) (if (null? rules...) table (fill-with-all-prereqs (cdr rules...) (fill-with-prereqs (op rules...) table)))) (let* ((table vlist-null)) (fill-with-all-prereqs all-rules... table))) (define-public (make-prereqs-table all-rules...) (make-table all-rules... cadar)) (define-public (make-targets-table all-rules...) (make-table all-rules... caar)) (define-public (top-level-targets) (let* ((dont-run (gmk-expand "$(NABS_HELP_DONT_RECURSE)")) (makefiles (gmk-expand "$(MAKEFILE_LIST)")) (rules (if (not (equal? dont-run "")) '((() ())) (find-all-rules-in (command-output (gmk-expand "$(MAKE) -q -p -n -s $(MAKEFILE_LIST) NABS_HELP_DONT_RECURSE='#t'") "")))) (ttab (make-targets-table rules)) (ptab (make-prereqs-table rules))) (filter (lambda (x) (not (string-contains makefiles x))) (append (cadar rules) (vhash-fold (lambda (k v r) (if (vhash-assoc k ptab) r (cons k r))) '() ttab)))))
false
f1484b624712a523d9cfad33148492569a209f33
a9d1a0e915293c3e6101e598b3f8fc1d8b8647a9
/scheme/raytrace/canvas.sld
845b091b11ca744adc6f0a9cf3aa4041d80e2647
[]
no_license
mbillingr/raytracing
a3b5b988007536a7065e51ef2fc17e6b5ac44d43
9c786e5818080cba488d3795bc6777270c505e5e
refs/heads/master
2021-04-16T17:10:40.435285
2020-11-11T07:02:18
2020-11-11T07:02:18
249,372,261
2
4
null
null
null
null
UTF-8
Scheme
false
false
2,888
sld
canvas.sld
(define-library (raytrace canvas) (export canvas canvas-width canvas-height canvas-data canvas-clear! canvas->ppm pixel-set! pixel-get flat-index) (import (scheme base) (scheme write) (raytrace generic) (raytrace compare) (raytrace tuple)) (begin (define-record-type <canvas> (make-canvas w h data) canvas? (w canvas-width) (h canvas-height) (data canvas-data canvas-set-data!)) (define (canvas w h) (make-canvas w h (make-vector (* w h) (color 0 0 0)))) (define (canvas-clear! canvas color) (vector-fill! (canvas-data canvas) color) canvas) (define (canvas-almost-equal? a b) (and (eq? (canvas-width a) (canvas-width b)) (eq? (canvas-height a) (canvas-height b)) (let ((alleq #t)) (vector-for-each (lambda (x y) (set! alleq (and (almost-equal? x y) alleq))) (canvas-data a) (canvas-data b)) alleq))) (define (canvas-print obj) (display "<canvas ") (display (canvas-width obj)) (display " x ") (display (canvas-height obj)) (display ">")) (define (canvas-dispatch method . args) (cond ((eq? 'print method) (apply canvas-print args)) ((eq? 'almost-equal? method) (apply canvas-almost-equal? args)))) (register-type canvas? canvas-dispatch) (define (pixel-set! canvas x y color) (vector-set! (canvas-data canvas) (flat-index canvas x y) color)) (define (pixel-get canvas x y) (vector-ref (canvas-data canvas) (flat-index canvas x y))) (define (flat-index canvas x y) (+ x (* y (canvas-width canvas)))) (define (canvas->ppm canvas) (string-append (canvas->ppm-header canvas) (canvas->ppm-data canvas))) (define (canvas->ppm-header canvas) (string-append "P3\n" (number->string (canvas-width canvas)) " " (number->string (canvas-height canvas)) "\n" "255\n")) (define (canvas->ppm-data canvas) (let* ((data (canvas-data canvas)) (n (vector-length data)) (w (canvas-width canvas)) (out "") (current-line "")) (let loop ((i 0)) (if (= i n) out (let ((c (color->string (vector-ref data i)))) (set! out (string-append out c "\n")) (loop (+ i 1))))))) (define (color->string c) (let ((c (color-round (color-clip 0 255 (color-scale c 255))))) (string-append (number->string (color-red c)) " " (number->string (color-green c)) " " (number->string (color-blue c)))))))
false
9c33f8e568a5c31223cdb67284926d973795acf1
014610409106df01d31c5980d0ca435ba3870e8a
/opengl-glew.scm
73f6e370637e919cd53019e0f1c6770624186556
[ "BSD-2-Clause" ]
permissive
Jubjub/chicken-opengl-glew
94e59bf729f5300796fe4d64d260e6b0c782ea52
00dc1f9ff080341272d2147fd0698fc8a1e90f20
refs/heads/master
2021-01-17T23:16:43.023216
2014-05-24T15:02:01
2014-05-24T15:02:01
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
4,648
scm
opengl-glew.scm
(module opengl-glew * (import chicken scheme bind foreign srfi-4) #> #include <stdlib.h> #include <stdio.h> #include <GL/glew.h> static void showInfoLog(GLuint object){ GLint logLength; char *log; glGetShaderiv(object, GL_INFO_LOG_LENGTH, &logLength); log = malloc(logLength); glGetShaderInfoLog(object, logLength, NULL, log); fprintf(stderr, "%s\n", log); free(log); } <# (bind-rename/pattern "^glew" "") (bind-rename/pattern "^GL_([A-Z_].+)$" "+\\1+") (bind-rename/pattern "^gl" "") (bind-rename/pattern "^Is(.*)$" "\\1?") (bind-options default-renaming: "" export-constants: #t) (bind-file "gl.h") (bind* #<<END unsigned int makeShader(unsigned int type, const char *source){ GLuint shader; GLint shaderOk; shader = glCreateShader(type); glShaderSource(shader, 1, (const GLchar**)&source, NULL); glCompileShader(shader); glGetShaderiv(shader, GL_COMPILE_STATUS, &shaderOk); if (!shaderOk) { fprintf(stderr, "Failed to compile %s:\n", source); showInfoLog(shader); glDeleteShader(shader); return 0; } return shader; } END ) (bind* #<<END void checkError(){ switch (glGetError()){ case 0: return; case GL_INVALID_ENUM: fprintf(stderr, "GL error: Invalid enum\n"); break; case GL_INVALID_VALUE: fprintf(stderr, "GL error: Invalid value\n"); break; case GL_INVALID_OPERATION: fprintf(stderr, "GL error: Invalid operation\n"); break; case GL_STACK_OVERFLOW: fprintf(stderr, "GL error: Stack overflow\n"); break; case GL_STACK_UNDERFLOW: fprintf(stderr, "GL error: Stack underflow\n"); break; case GL_OUT_OF_MEMORY: fprintf(stderr, "GL error: Out of memory\n"); break; case GL_TABLE_TOO_LARGE: fprintf(stderr, "GL error: Table too large\n"); break; default: fprintf(stderr, "GL error: Unknown\n"); } } END ) (define (make-program shaders) (let ([program (create-program)]) (let loop ([shaders shaders]) (if (not (null? shaders)) (begin (attach-shader program (car shaders)) (loop (cdr shaders))))) (link-program program) ((foreign-lambda* unsigned-integer ((unsigned-integer program)) "GLint programOk; glGetProgramiv(program, GL_LINK_STATUS, &programOk); if (!programOk) { fprintf(stderr, \"Failed to link shader program:\\n\"); showInfoLog(program); glDeleteProgram(program); C_return(0); } C_return(program);") program))) (bind "bool glewIsSupported(char *name);") (bind* #<<END void init(){ glewExperimental = GL_TRUE; GLenum err = glewInit(); if (GLEW_OK != err){ fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); exit(1); } } END ) (define (gen-buffer) (let ([vec (make-u32vector 1)]) (gen-buffers 1 vec) (u32vector-ref vec 0))) (define (delete-buffer x) (let ([vec (u32vector x)]) (delete-buffers 1 vec))) (define (gen-framebuffer) (let ([vec (make-u32vector 1)]) (gen-framebuffers 1 vec) (u32vector-ref vec 0))) (define (delete-framebuffer x) (let ([vec (u32vector x)]) (delete-framebuffers 1 vec))) (define (gen-program-pipeline) (let ([vec (make-u32vector 1)]) (gen-program-pipelines 1 vec) (u32vector-ref vec 0))) (define (delete-program-pipeline x) (let ([vec (u32vector x)]) (delete-program-pipelines 1 vec))) (define (gen-query) (let ([vec (make-u32vector 1)]) (gen-queries 1 vec) (u32vector-ref vec 0))) (define (delete-query x) (let ([vec (u32vector x)]) (delete-queries 1 vec))) (define (gen-renderbuffer) (let ([vec (make-u32vector 1)]) (gen-renderbuffers 1 vec) (u32vector-ref vec 0))) (define (delete-renderbuffer x) (let ([vec (u32vector x)]) (delete-renderbuffers 1 vec))) (define (gen-sampler) (let ([vec (make-u32vector 1)]) (gen-samplers 1 vec) (u32vector-ref vec 0))) (define (delete-sampler x) (let ([vec (u32vector x)]) (delete-samplers 1 vec))) (define (gen-texture) (let ([vec (make-u32vector 1)]) (gen-textures 1 vec) (u32vector-ref vec 0))) (define (delete-texture x) (let ([vec (u32vector x)]) (delete-textures 1 vec))) (define (gen-transform-feedback) (let ([vec (make-u32vector 1)]) (gen-transform-feedbacks 1 vec) (u32vector-ref vec 0))) (define (delete-transform-feedback x) (let ([vec (u32vector x)]) (delete-transform-feedbacks 1 vec))) (define (gen-vertex-array) (let ([vec (make-u32vector 1)]) (gen-vertex-arrays 1 vec) (u32vector-ref vec 0))) (define (delete-vertex-array x) (let ([vec (u32vector x)]) (delete-vertex-arrays 1 vec))) (register-feature! #:opengl-glew) ) ; module end
false
fc7c85cfcaa2664a4cb27fc5641597465f900a19
6bd63be924173b3cf53a903f182e50a1150b60a8
/chapter_1/1.25.scm
3269cbffb24489974fb451e0ac393903dc3c6ebf
[]
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
1,367
scm
1.25.scm
(define (fast-expt b e) (cond ((= e 0) 1) ((even? e) (square (fast-expt b (/ e 2)))) (else (* b (fast-expt b (- e 1) ))) ) ) (define (expmod base e m) (remainder (fast-expt base e) m)) (define (fast-test n) (define (try-it a) (= (expmod a n n) a)) (try-it (+ 1 (random (- n 1))))) (define (fast-prime? n times) (cond ((= times 0) true) ((fast-test n) (fast-prime? n (- times 1))) (else false))) (define (timed-prime-test n) (newline) (display n) (start-prime-test n (runtime))) (define (start-prime-test n start-time) (if (fast-prime? n 10) (report-prime (- (runtime) start-time)))) (define (report-prime elapsed-time) (display " **** ") (display elapsed-time)) (define (even? n) (= (remainder n 2) 0)) (define (search-for-prime l r) (if (even? l) (search-for-prime (+ l 1) r) (cond ((< l r) (timed-prime-test l) (search-for-prime (+ l 2) r))))) (define (try) (display (search-for-prime 1000 1020)) (display (search-for-prime 10000 10020)) (display (search-for-prime 100000 100020)) (display (search-for-prime 10000000 10000020)) (display (search-for-prime 100000000 100000020)) (display (search-for-prime 1000000000 1000000020)) (display (search-for-prime 10000000000 10000000020)) (display (search-for-prime 100000000000 100000000020)) )
false
9aba7812ce81dbaf5cb97edfda398890aab43d83
1f48fb14898799bf9ee1118bf691586b430c5e9e
/269.scm
94039433f23fc82e1be93a4f3fb64f36ca9bc7bb
[]
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
439
scm
269.scm
(define (generate-huffman-tree pairs) (successive-merge (make-leaf-set pairs))) (define (successive-merge sets) (cond ((null? sets) '()) ((atom-in-list sets) (car sets)) (else (successive-merge (adjoin-set (make-code-tree (car sets) (cadr sets)) (cddr sets)))))) (define (atom-in-list set) (and (pair? set) (null? (cdr set))))
false
4e939f52c97920c57108a8e6d9f7af14954f7e4e
4f91474d728deb305748dcb7550b6b7f1990e81e
/Chapter2/2-midpoint-segment.scm
1f793b0a388c8b340a22a644169fce77a1d01e31
[]
no_license
CanftIn/sicp
e686c2c87647c372d7a6a0418a5cdb89e19a75aa
92cbd363c143dc0fbf52a90135218f9c2bf3602d
refs/heads/master
2021-06-08T22:29:40.683514
2020-04-20T13:23:59
2020-04-20T13:23:59
85,084,486
2
0
null
null
null
null
UTF-8
Scheme
false
false
436
scm
2-midpoint-segment.scm
;;; 2-midpoint-segment.scm (load "2-segment-selector.scm") (load "2-point-constructor.scm") (load "2-point-selector.scm") (define (midpoint-segment seg) (let ((start (start-segment seg)) (end (end-segment seg))) (make-point (average (x-point start) (x-point end)) (average (y-point start) (y-point end))))) (define (average x y) (/ (+ x y) 2.0))
false
bc9ef2667bdbaefac6709ea717b98abd96d9784b
53cb8287b8b44063adcfbd02f9736b109e54f001
/depend/dependency-analysis.scm
c8d259a4d1204e98d5e6ae486c6eb29e3b7f6b39
[]
no_license
fiddlerwoaroof/yale-haskell-reboot
72aa8fcd2ab7346a4990795621b258651c6d6c39
339b7d85e940db0b8cb81759e44abbb254c54aad
refs/heads/master
2021-06-22T10:32:25.076594
2020-10-30T00:00:31
2020-10-30T00:00:31
92,361,235
3
0
null
null
null
null
UTF-8
Scheme
false
false
5,094
scm
dependency-analysis.scm
;;; depend/depend.scm Author: John ;;; This performs dependency analysis. All module definitions are gathered ;;; into a single nested let/let*. (define-walker depend ast-td-depend-walker) ;;; This extracts the declarations out of the top level of the modules and ;;; creates a single let defining all values from the modules. (define (do-dependency-analysis modules) (let ((all-decls '())) (dolist (mod modules) (setf all-decls (append (module-decls mod) all-decls))) (analyze-dependency-top (**let all-decls (make void))))) (define *depend-fn-table* (make-table)) (define-syntax (var-depend-fn var) `(table-entry *depend-fn-table* ,var)) (define (analyze-dependency-top x) (dynamic-let ((*depend-fn-table* (make-table))) (analyze-dependency x))) ;;; This is the entry point to dependency analysis for an expression or decl (define (analyze-dependency x) (call-walker depend x)) (define (analyze-dependency/list l) (dolist (x l) (analyze-dependency x))) ;;; This makes default walkers for dependency analysis. Expressions are ;;; walked into; declaration lists must be sorted. (define-local-syntax (make-depend-code slot type) (let ((stype (sd-type slot)) (sname (sd-name slot)) (depend-exp-types '(exp alt qual single-fun-def guarded-rhs))) (cond ((and (symbol? stype) (memq stype depend-exp-types)) `(analyze-dependency (struct-slot ',type ',sname object))) ((and (pair? stype) (eq? (car stype) 'list) (symbol? (cadr stype)) (memq (cadr stype) depend-exp-types) `(analyze-dependency/list (struct-slot ',type ',sname object)))) ((equal? stype '(list decl)) `(setf (struct-slot ',type ',sname object) (restructure-decl-list (struct-slot ',type ',sname object)))) (else ; (format '#t "Depend: skipping slot ~A in ~A~%" ; (sd-name slot) ; type) '#f)))) (define-modify-walker-methods depend (lambda let if case alt exp-sign app con-ref integer-const float-const char-const string-const list-exp sequence sequence-then sequence-to sequence-then-to list-comp section-l section-r qual-generator qual-filter omitted-guard con-number sel is-constructor cast void single-fun-def guarded-rhs case-block return-from and-exp ) (object) make-depend-code) ;;; This sorts a list of decls. Recursive groups are placed in ;;; special structures: recursive-decl-group (define (restructure-decl-list decls) (let ((stack '()) (now 0) (sorted-decls '()) (edge-fn '())) (letrec ((visit (lambda (k) (let ((minval 0) (recursive? '#f) (old-edge-fn edge-fn)) (incf now) ; (format '#t "Visiting ~A: id = ~A~%" (valdef-lhs k) now) (setf (valdef-depend-val k) now) (setf minval now) (push k stack) (setf edge-fn (lambda (tv) ; (format '#t "Edge ~A -> ~A~%" (valdef-lhs k) ; (valdef-lhs tv)) (let ((val (valdef-depend-val tv))) (cond ((eq? tv k) (setf recursive? '#t)) ((eqv? val 0) (setf minval (min minval (funcall visit tv)))) (else (setf minval (min minval val)))) ; (format '#t "Min for ~A is ~A~%" ; (valdef-lhs k) minval) ))) (analyze-dependency/list (valdef-definitions k)) (setf edge-fn old-edge-fn) (when (eqv? minval (valdef-depend-val k)) (let ((defs '())) (do ((quit? '#f)) (quit?) (push (car stack) defs) (setf (valdef-depend-val (car stack)) 100000) (setf quit? (eq? (car stack) k)) (setf stack (cdr stack))) ; (format '#t "Popping stack: ~A~%" ; (map (lambda (x) (valdef-lhs x)) defs)) (if (and (null? (cdr defs)) (not recursive?)) (push k sorted-decls) (push (make recursive-decl-group (decls defs)) sorted-decls)))) minval)))) ;; for now assume all decl lists have only valdefs (dolist (d decls) (let ((decl d)) ; to force new binding for each closure (setf (valdef-depend-val decl) 0) (dolist (var (collect-pattern-vars (valdef-lhs decl))) (setf (var-depend-fn (var-ref-var var)) (lambda () (funcall edge-fn decl)))))) (dolist (decl decls) (when (eqv? (valdef-depend-val decl) 0) (funcall visit decl))) (dolist (decl decls) (dolist (var (collect-pattern-vars (valdef-lhs decl))) (setf (var-depend-fn (var-ref-var var)) '#f))) (nreverse sorted-decls)))) ;;; This is the only non-default walker needed. When a reference to a ;;; variable is encountered, the sort algorithm above is notified. (define-walker-method depend var-ref (object) (let ((fn (var-depend-fn (var-ref-var object)))) (when (not (eq? fn '#f)) (funcall fn)))) (define-walker-method depend overloaded-var-ref (object) (let ((fn (var-depend-fn (overloaded-var-ref-var object)))) (when (not (eq? fn '#f)) (funcall fn))))
true
adb7041a763e7d3e0f533906e411d2832a8fbbe1
8e15d5c1ed79e956f5f3a780daf64e57ba8fa0cb
/text/rss.scm
6b2e065d3d7234165acecdf20e163634a3c1b6bd
[ "Zlib" ]
permissive
pbui/omg
10602d73dab66cb69f4c24a543f3ffd91cb707e3
b7e9011643c301eb5eaae560b980ffe5b764e173
refs/heads/master
2020-07-06T06:10:16.247249
2016-11-17T18:34:38
2016-11-17T18:34:38
74,056,007
0
0
null
null
null
null
UTF-8
Scheme
false
false
4,332
scm
rss.scm
#!/usr/local/bin/gosh ;------------------------------------------------------------------------------- ; omg.text.rss : simple rss handling functions ;------------------------------------------------------------------------------- ; Copyright (c) 2006 Peter Bui. All Rights Reserved. ; This software is provided 'as-is', without any express or implied warranty. ; In no event will the authors be held liable for any damages arising from the ; use of this software. ; Permission is granted to anyone to use this software for any purpose, ; including commercial applications, and to alter it and redistribute it ; freely, subject to the following restrictions: ; 1. The origin of this software must not be misrepresented; you must not claim ; that you wrote the original software. If you use this software in a product, ; an acknowledgment in the product documentation would be appreciated but is ; not required. ; 2. Altered source versions must be plainly marked as such, and must not be ; misrepresented as being the original software. ; 3. This notice may not be removed or altered from any source distribution. ; Peter Bui <[email protected]> ;------------------------------------------------------------------------------- (define-module omg.text.rss (use omg.ds.record) (use omg.text.wrap) (use srfi-1) (export-all)) (select-module omg.text.rss) ;------------------------------------------------------------------------------- ; Item Data Structure ;------------------------------------------------------------------------------- (define-record <item> title author link description date) ;------------------------------------------------------------------------------- ; Parse Feed Function ;------------------------------------------------------------------------------- (define (parse-feed feed) (with-input-from-file feed (lambda () (parse-port (current-input-port) 'nonitem '())))) ;------------------------------------------------------------------------------- ; Parse Port Function ;------------------------------------------------------------------------------- (define (parse-port port state items) (let ((line (read-line port))) (if (eof-object? line) items (cond ((rxmatch #/<item>/i line) (parse-port port 'item (cons (make-item "" "" "" "" "") items))) ((rxmatch #/<item\s.*?>/i line) (parse-port port 'item (cons (make-item "" "" "" "" "") items))) ((and (eq? state 'item) (rxmatch #/<description>.*<\/description>/i line)) (let* ((tag (rxmatch #/<description>(.*)<\/description>/i line)) (body (rxmatch-substring tag 1))) (unless (null? items) (item-description! (car items) body)) (parse-port port 'item items))) ((and (eq? state 'item) (rxmatch #/<description>/i line)) (let* ((tag (rxmatch #/<description>(.*)/i line)) (body (rxmatch-substring tag 1))) (unless (null? items) (item-description! (car items) body)) (parse-port port 'description items))) ((and (eq? state 'description) (rxmatch #/.*?<\/description>/i line) (parse-port port 'item items))) ((rxmatch #/.*?<\/item>/i line) (parse-port port 'nonitem items)) (else (let* ((tag-matches (rxmatch #/<(.*?)>(.*?)<\/(.*?)>/i line)) (tag (rxmatch-substring tag-matches 1)) (body (rxmatch-substring tag-matches 2))) (cond ((and (eq? state 'item) tag-matches) (cond ((rxmatch #/author/i tag) (item-author! (car items) body)) ((rxmatch #/date/i tag) (item-date! (car items) body)) ((rxmatch #/description/i tag) (item-description! (car items) body)) ((rxmatch #/link/i tag) (item-link! (car items) body)) ((rxmatch #/title/i tag) (item-title! (car items) body)))) ((eq? state 'description) (unless (null? items) (item-description! (car items) (string-append (item-description (car items)) " " line)))))) (parse-port port state items)))))) ;------------------------------------------------------------------------------- (provide "omg/text/rss") ;------------------------------------------------------------------------------- ; vim: sts=2 sw=2 ts=8 ;-------------------------------------------------------------------------------
false
af0ad315d666102ad3078651b1ae0ecd1ae98999
648776d3a0d9a8ca036acaf6f2f7a60dcdb45877
/queries/vim/highlights.scm
c5bd2e947518160ff69d928d269065357d5c8847
[ "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
4,077
scm
highlights.scm
(identifier) @variable ((identifier) @constant (#lua-match? @constant "^[A-Z][A-Z_0-9]*$")) ;; Keywords [ "if" "else" "elseif" "endif" ] @conditional [ "try" "catch" "finally" "endtry" "throw" ] @exception [ "for" "endfor" "in" "while" "endwhile" "break" "continue" ] @repeat [ "function" "endfunction" ] @keyword.function ;; Function related (function_declaration name: (_) @function) (call_expression function: (identifier) @function.call) (call_expression function: (scoped_identifier (identifier) @function.call)) (parameters (identifier) @parameter) (default_parameter (identifier) @parameter) [ (bang) (spread) ] @punctuation.special [ (no_option) (inv_option) (default_option) (option_name) ] @variable.builtin [ (scope) "a:" "$" ] @namespace ;; Commands and user defined commands [ "let" "unlet" "const" "call" "execute" "normal" "set" "setfiletype" "setlocal" "silent" "echo" "echon" "echohl" "echomsg" "echoerr" "autocmd" "augroup" "return" "syntax" "filetype" "source" "lua" "ruby" "perl" "python" "highlight" "command" "delcommand" "comclear" "colorscheme" "startinsert" "stopinsert" "global" "runtime" "wincmd" "cnext" "cprevious" "cNext" "vertical" "leftabove" "aboveleft" "rightbelow" "belowright" "topleft" "botright" (unknown_command_name) "edit" "enew" "find" "ex" "visual" "view" "eval" "sign" ] @keyword (map_statement cmd: _ @keyword) (command_name) @function.macro ;; Filetype command (filetype_statement [ "detect" "plugin" "indent" "on" "off" ] @keyword) ;; Syntax command (syntax_statement (keyword) @string) (syntax_statement [ "enable" "on" "off" "reset" "case" "spell" "foldlevel" "iskeyword" "keyword" "match" "cluster" "region" "clear" "include" ] @keyword) (syntax_argument name: _ @keyword) [ "<buffer>" "<nowait>" "<silent>" "<script>" "<expr>" "<unique>" ] @constant.builtin (augroup_name) @namespace (au_event) @constant (normal_statement (commands) @constant) ;; Highlight command (hl_attribute key: _ @property val: _ @constant) (hl_group) @type (highlight_statement [ "default" "link" "clear" ] @keyword) ;; Command command (command) @string (command_attribute name: _ @property val: (behavior name: _ @constant val: (identifier)? @function)?) ;; Edit command (plus_plus_opt val: _? @constant) @property (plus_cmd "+" @property) @property ;; Runtime command (runtime_statement (where) @keyword.operator) ;; Colorscheme command (colorscheme_statement (name) @string) ;; Literals (string_literal) @string (integer_literal) @number (float_literal) @float (comment) @comment @spell (line_continuation_comment) @comment @spell (pattern) @string.special (pattern_multi) @string.regex (filename) @string (heredoc (body) @string) (heredoc (parameter) @keyword) [ (marker_definition) (endmarker) ] @label (literal_dictionary (literal_key) @label) ((scoped_identifier (scope) @_scope . (identifier) @boolean) (#eq? @_scope "v:") (#any-of? @boolean "true" "false")) ;; Operators [ "||" "&&" "&" "+" "-" "*" "/" "%" ".." "is" "isnot" "==" "!=" ">" ">=" "<" "<=" "=~" "!~" "=" "+=" "-=" "*=" "/=" "%=" ".=" "..=" "<<" "=<<" (match_case) ] @operator ; Some characters have different meanings based on the context (unary_operation "!" @operator) (binary_operation "." @operator) ;; Punctuation [ "(" ")" "{" "}" "[" "]" "#{" ] @punctuation.bracket (field_expression "." @punctuation.delimiter) [ "," ":" ] @punctuation.delimiter (ternary_expression ["?" ":"] @conditional.ternary) ; Options ((set_value) @number (#lua-match? @number "^[%d]+(%.[%d]+)?$")) (inv_option "!" @operator) (set_item "?" @operator) ((set_item option: (option_name) @_option value: (set_value) @function) (#any-of? @_option "tagfunc" "tfu" "completefunc" "cfu" "omnifunc" "ofu" "operatorfunc" "opfunc"))
false
0225f2b01b37ef7b76bfaec42717456d7502ce9a
ae0d7be8827e8983c926f48a5304c897dc32bbdc
/Gauche-tir/trunk/lib/tir04/dbm/util.scm
88835a7cf8a2996d4b6de7b0a22c6d6d89d57fd6
[ "MIT" ]
permissive
ayamada/copy-of-svn.tir.jp
96c2176a0295f60928d4911ce3daee0439d0e0f4
101cd00d595ee7bb96348df54f49707295e9e263
refs/heads/master
2020-04-04T01:03:07.637225
2015-05-28T07:00:18
2015-05-28T07:00:18
1,085,533
3
2
null
2015-05-28T07:00:18
2010-11-16T15:56:30
Scheme
EUC-JP
Scheme
false
false
1,051
scm
util.scm
;;; coding: euc-jp ;;; -*- scheme -*- ;;; vim:set ft=scheme ts=8 sts=2 sw=2 et: ;;; $Id$ ;;; dbmの為のユーティリティ手続き集。 ;;; あとでもう少し追加する。 (define-module tir04.dbm.util (use srfi-1) (use dbm) (export with-dbm-open )) (select-module tir04.dbm.util) ;; usage: ;; (with-dbm-open ;; <qdbm> ;; :path "/path/to/dbm.file" ;; :rw-mode :read ;; :key-convert #f ;; :value-convert #t ;; (lambda (dbm) ;; ;; dbmを使った操作を行う ;; ;; このprocの実行が完了すると、自動的にdbmは閉じられる ;; )) (define (with-dbm-open dbm-type . dbm-open-args&proc) (let ((dbm-open-args (drop-right dbm-open-args&proc 1)) (proc (car (last-pair dbm-open-args&proc)))) (let1 dbm #f (dynamic-wind (lambda () (set! dbm (apply dbm-open dbm-type dbm-open-args))) (lambda () (proc dbm)) (lambda () (dbm-close dbm) (set! dbm #f)))))) (provide "tir04/dbm/util")
false
feecc075fcf0d54f42e337dec45a00aefb82a8dd
b60cb8e39ec090137bef8c31ec9958a8b1c3e8a6
/test/R5RS/work.scm
d28b2d68f8fd49719cbe89beb1ed2d0096da2c6f
[]
no_license
acieroid/scala-am
eff387480d3baaa2f3238a378a6b330212a81042
13ef3befbfc664b77f31f56847c30d60f4ee7dfe
refs/heads/master
2021-01-17T02:21:41.692568
2021-01-15T07:51:20
2021-01-15T07:51:20
28,140,080
32
16
null
2020-04-14T08:53:20
2014-12-17T14:14:02
Scheme
UTF-8
Scheme
false
false
1,509
scm
work.scm
;; Taken from http://www.cs.cmu.edu/afs/cs/project/ai-repository/ai/lang/scheme/code/fun/ ; ; Putting Scheme to Work ; By Olivier Danvy ; Bigre special edition "Putting Scheme to Work" ; (define fix (let ((z (lambda (P) (lambda (u) (lambda (t) (lambda (t) (lambda (i) (lambda (n) (lambda (g) (lambda (S) (lambda (c) (lambda (h) (lambda (e) (lambda (m) (lambda (e) (lambda (t) (lambda (o) (lambda (W) (lambda (o) (lambda (r) (lambda (k) (lambda (!) (! (lambda (break) (((((((((((((((((((((W o) r) k) W) o) r) k) W) o) r) k) W) o) r) k) W) o) r) k) !) break))))))))))))))))))))))))) (let ((Z z)) (((((((((((((((((((z z) z) z) z) z) Z) Z) Z) Z) Z) Z) Z) z) z) z) z) z) z) z)))) ((fix (lambda (f) (lambda (n) (if (zero? n) 1 (* n (f (- n 1))))))) 9)
false
03367dc47bcede9246636c6cd4002abd63654108
e86c259361f8a400a0959d82009906da38e006cb
/test.scm
2a6ce3d1bdafb9d4a14bcb67f952c08f0b46f1dd
[ "BSD-3-Clause" ]
permissive
tabe/uri
86df02feb7104112af62f015a74c5c475ebddc95
5aa80f2353de1230bf9dd59d93a23c03e280059e
refs/heads/master
2020-05-04T19:30:10.482570
2009-08-27T09:25:58
2009-08-27T09:25:58
279,213
1
0
null
null
null
null
UTF-8
Scheme
false
false
2,386
scm
test.scm
#!r6rs (import (rnrs) (uri) (xunit)) (define-syntax assert-codec (syntax-rules () ((_ decoded encoded) (begin (assert-string=? decoded (decode-string encoded)) (assert-string-ci=? encoded (encode-string decoded)))))) (define-syntax assert-string->uri (syntax-rules () ((_ (scheme authority path query fragment) str) (let ((uri (string->uri str))) (assert-equal? scheme (uri-scheme uri)) (assert-equal? authority (uri-authority uri)) (assert-equal? path (uri-path uri)) (assert-equal? query (uri-query uri)) (assert-equal? fragment (uri-fragment uri)))))) (define-syntax assert-uri->string (syntax-rules () ((_ str (scheme authority path query fragment)) (assert-string=? str (uri->string (make-uri scheme authority path query fragment)))))) (define-syntax assert-string<->uri (syntax-rules () ((_ str (scheme authority path query fragment)) (begin (assert-uri->string str (scheme authority path query fragment)) (assert-string->uri (scheme authority path query fragment) str))))) (assert-codec " " "%20") (assert-codec "/path/example" "%2fpath%2fexample") (assert-codec "省メモリプログラミング" "%e7%9c%81%e3%83%a1%e3%83%a2%e3%83%aa%e3%83%97%e3%83%ad%e3%82%b0%e3%83%a9%e3%83%9f%e3%83%b3%e3%82%b0") (assert-codec "あいうえお" "%E3%81%82%E3%81%84%E3%81%86%E3%81%88%E3%81%8A") (assert-codec "foo+bar" "foo%2Bbar") (assert-string=? "foo bar" (decode-string "foo+bar" 'application/x-www-form-urlencoded)) (assert-string<->uri "http://example.com" ("http" "example.com" "" #f #f)) (assert-string<->uri "http://example.com/" ("http" "example.com" "/" #f #f)) (assert-string<->uri "http://example.com?foo" ("http" "example.com" "" "foo" #f)) (assert-string<->uri "http://example.com?foo#" ("http" "example.com" "" "foo" "")) (assert-string<->uri "http://example.com?#" ("http" "example.com" "" "" "")) (assert-string<->uri "http://example.com#bar" ("http" "example.com" "" #f "bar")) (assert-string<->uri "http://example.com/path/?foo" ("http" "example.com" "/path/" "foo" #f)) (assert-string<->uri "http://[email protected]:80/path/" ("http" "[email protected]:80" "/path/" #f #f)) (assert-string<->uri "file:///home/foo/bar" ("file" "" "/home/foo/bar" #f #f)) (assert-string<->uri "mailto:[email protected]" ("mailto" #f "[email protected]" #f #f)) (report)
true
7b2819d5f8a52b909452c56581ec287c282e6ef3
cb8cccd92c0832e056be608063bbec8fff4e4265
/chapter2/Exercises/2.03.scm
9bb4f2c7668f104801e959b796098c3c118219f8
[]
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,110
scm
2.03.scm
#lang scheme ; Ex 2.3 ; Point representation --------------------------------------- ; Constructor of a point as a pair of numbers (define (make-point x y) (cons x y)) ; Selector for the x- and y- components of a point (define (x-point p) (car p)) (define (y-point p) (cdr p)) ; Print point (define (print-point p) (newline) (display "(") (display (x-point p)) (display ",") (display (y-point p)) (display ")")) ; ------------------------------------------------------------ ; Representation for rectangles in a plane-------------------- ; Constructor of a rectanble with pair width-height (define (make-rectangle w h) (cons w h)) ; Selector for the width and height of a Rectangle (define (rect-width R) (car R)) (define (rect-height R) (cdr R)) ; Procedures for calculating the area and perimeter of a Rect (define (area-rect R) (* (rect-width R) (rect-height R))) (define (perim-rect R) (* 2 (+ (rect-width R) (rect-height R)))) ; ------------------------------------------------------------ ; Test code for rational numbers (define R1 (make-rectangle 3 5)) (area-rect R1) (perim-rect R1)
false
9ec781b6a172c92d936a5c5010bb3382beace6d4
c2e2ffee9e12a078bc59ed32dfe441e5d018807c
/toolbox/show-gl-version.scm
d6d14104cb71dc6672653cd5ffd3bf36e3565e2b
[ "BSD-2-Clause" ]
permissive
fujita-y/digamma
3fb3bdb8d24b05b6e809863c17cf2a3cb1aac53c
fbab05bdcb7019ff005ee84ed8f737ff3d44b38e
refs/heads/master
2022-06-03T01:29:22.084440
2022-03-15T03:30:35
2022-03-15T03:30:35
59,635,079
32
3
BSD-2-Clause
2020-02-10T23:40:16
2016-05-25T05:58:28
C++
UTF-8
Scheme
false
false
247
scm
show-gl-version.scm
(import (digamma gl) (digamma glut) (digamma c-types)) (glutInit (make-c-int (c-main-argc)) (c-main-argv)) (glutCreateWindow (string->utf8/nul "Digamma")) (format #t "~a~%~!" (utf8->string (make-bytevector-mapping (glGetString GL_VERSION) 1024)))
false
3ed4a174a537d39e8c6e46da9e598af83c7cbb3a
08b21a94e7d29f08ca6452b148fcc873d71e2bae
/src/scheme/repl.sld
4af18126e871f27da090e9cc6c09922e9b8d1d1f
[ "MIT" ]
permissive
rickbutton/loki
cbdd7ad13b27e275bb6e160e7380847d7fcf3b3a
7addd2985de5cee206010043aaf112c77e21f475
refs/heads/master
2021-12-23T09:05:06.552835
2021-06-13T08:38:23
2021-06-13T08:38:23
200,152,485
21
1
NOASSERTION
2020-07-16T06:51:33
2019-08-02T02:42:39
Scheme
UTF-8
Scheme
false
false
234
sld
repl.sld
(define-library (scheme repl) (import (except (loki core primitives) eval environment)) (import (scheme eval)) (export interaction-environment) (begin (define (interaction-environment) (environment '(scheme base)))))
false
1ce35018203130bc3051b1dc10e43906fc82f166
b862f6f4fd20066e3f25ea4ceb54a5fe22accd3f
/scheme/factorial-with-y.scm
4fd70667bfe282e8732903ff57acf6650ff36927
[]
no_license
okertanov/functional
4cbd67beebdd99cb2d82f4b87674e172928d9cf8
e191c6f8c123828efa86bf47f41348e15f37097c
refs/heads/master
2023-03-06T16:22:22.457201
2023-02-26T17:13:33
2023-02-26T17:13:33
1,440,909
0
0
null
null
null
null
UTF-8
Scheme
false
false
312
scm
factorial-with-y.scm
#lang scheme (define Y (lambda (f) ((lambda (x) (f (lambda (v) ((x x) v))) ) (lambda (x) (f (lambda (v) ((x x) v))) ) ) ) ) (define fact (Y (lambda (f) (lambda (n) (if (= n 0) 1 (* n (f (- n 1)))) ) ) ) ) (fact 5)
false
d814976c767ee0d5cde83296c398ee6ab0b8edbf
f62b93d76e3d66e6394dd8dac18837453ab4767c
/chapter6.ss
9bfaa30fbe62c91a4a6e8cbd6133099296b6c909
[]
no_license
rbarraud/lisp-in-small-pieces-1
f120b0a9bb904223f794a44425fc9404b2ed9d97
f3369aeb98c3ccb83155e91f85ba086a61f51af5
refs/heads/master
2021-01-15T16:14:59.073371
2014-02-16T12:50:46
2014-02-16T12:50:46
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
20,723
ss
chapter6.ss
;; In this interpreter, the static part of a program is explicitly ;; separated from the dynamic. Broadly speaking, the static are the ;; lexical environment and instructions, and the dynamic the ;; activation frames and continuation. ;; ;; Activation frames represent memory: they store values against ;; addresses. The environment maps names to those addresses, ;; abstractly -- that is, we determine which activation frame will ;; have the memory address while compiling, and look it up at ;; runtime. The only representations of memory kept in this ;; interpreter are the activation records and the memory for globals. (load "prelude.ss") (define (compiler-error . bobbins) (error bobbins)) (define (runtime-error . bobbins) (error bobbins)) (import type-system) (import generic-procedures) (import oo) ;; Environments and activation records. Both contain maps, and ;; activation records contain a link to the next record. Below we'll ;; actually use assoc lists for lexical environments, so having two ;; classes is overegging it, but it's what the book does. (define-generics :next :next! :args :args! :argument :argument!) (define-class (<environment>) (next :next :next!)) (define-class (<activation> <environment>) (args :args :args!)) (define-method (initialize (<activation> self) (<number> size)) (:args! self (make-vector size))) (define-method (:argument (<activation> frame) (<number> index)) (vector-ref (:args frame) index)) (define-method (:argument! (<activation> frame) (<number> index) (<value> value)) (vector-set! (:args frame) index value)) ;; Extend the activation frame (working memory) (define (sr-extend* sr v*) (:next! v* sr) v*) ;; Extend the environment. This works slightly differently to the ;; activation records -- it's just a list of assoc lists. (Why? ;; Because we only do lookups in the environment while pretreating ;; expressions, resulting in *references to locations* in activation ;; frames) (define (r-extend* r n*) (cons n* r)) ;; See if the given name is a local variable in the given environment (define (local-variable? r i n) (and (pair? r) (let scan ((names (car r)) (j 0)) (cond ((pair? names) (if (eq? n (car names)) `(local ,i . ,j) (scan (cdr names) (+ j 1)))) ((null? names) (local-variable? (cdr r) (+ i 1) n)) ;; Don't think I understand this clause -- why would ;; these be improper? A convenience perhaps ((eq? n names) `(local ,i . ,j)))))) ;; When we compile expressions, we replace variable references with ;; lookups into the activation records (that's i for the number of ;; frames up, and j for the slot). This is going to go retrieve the ;; values for us. (define (deep-fetch sr i j) (if (= i 0) (:argument sr j) (deep-fetch (:next sr) (- i 1) j))) ;; Likewise for set! (define (deep-update! sr i j value) (if (= i 0) (:argument! sr j value) (deep-update! (:next sr) (- i 1) j value))) ;; Global (top-level) variables: these are in two varieties, mutable ;; (defined by the program) and immutable (primitives). They can be ;; shadowed of course, and we know this at interpretation time, so we ;; can insert the correct lookup. ;; Global envs are just a list of (name (kind . addr)) i.e., an ;; assoc list. The addr is a vector index into our 'memory'. ;; Mutable globals (define g.current '()) ;; Predefined globals (define g.init '()) ;; And global memory is just a vector. (define sg.current (make-vector 100)) (define sg.init (make-vector 100)) (define (g.current-extend! n) (let ((level (length g.current))) (set! g.current (cons (cons n `(global . ,level)) g.current)) level)) (define (g.init-extend! n) (let ((level (length g.init))) (set! g.init (cons (cons n `(predefined . ,level)) g.init)) level)) (define (compute-kind r n) (or (local-variable? r 0 n) (global-variable? g.current n) (global-variable? g.init n))) (define (global-variable? g n) (let ((var (assq n g))) (and (pair? var) (cdr var)))) (define (global-fetch i) (vector-ref sg.current i)) (define (predef-fetch i) (vector-ref sg.init i)) (define (global-update! i v) (vector-set! sg.current i v)) ;; OK now for real stuff. ;; `meaning` is the compilation or (as per the book) pretreatment ;; step. The idea is to create a lambda that, given the store ;; (activation records) and the continuation, will execute the ;; program. While we're pretreating expressions, we maintain a lexical ;; environment so we know where to look to dereference variables. ;; I'm finally going to cede to the book way of naming variables, in ;; particular environments 'r'. (Presumably r for \rho from chapter 5) (define (meaning e r) (if (pair? e) (case (car e) ((quote) (meaning-quotation (cadr e) r)) ((lambda) (meaning-abstraction (cadr e) (cddr e) r)) ((if) (meaning-alternative (cadr e) (caddr e) (cadddr e) r)) ((begin) (meaning-sequence (cdr e) r)) ((set!) (meaning-assignment (cadr e) (caddr e) r)) (else (meaning-application (car e) (cdr e) r))) (if (symbol? e) (meaning-deref e r) (meaning-quotation e r)))) (define (meaning-quotation v r) (lambda (sr k) (k v))) (define (meaning-alternative e1 e2 e3 r) (let ((m1 (meaning e1 r)) (m2 (meaning e2 r)) (m3 (meaning e3 r))) (lambda (sr k) (m1 sr (lambda (v) ((if v m2 m3) sr k)))))) (define (meaning-sequence e+ r) (if (pair? e+) (if (pair? (cdr e+)) (meaning*-multiple-sequence (car e+) (cdr e+) r) (meaning*-single-sequence (car e+) r)) (compiler-error "Empty begin"))) (define (meaning*-multiple-sequence e1 e+ r) (let ((m1 (meaning e1)) (m+ (meaning-sequence e+ r))) (lambda (sr k) (m1 sr (lambda (v) (m+ sr k)))))) (define (meaning*-single-sequence e r) (meaning e r)) ;; First tricky one: application. This makes us determine how ;; procedures are represented. (As per book, I'll just use a closure). ;; NB the book has some static checks for native procedures in here; ;; I've moved these to meaning-primitive-application. (define (meaning-application e e* r) (cond ;; NB relies on the single-expression variety of cond clause ((and (symbol? e) (let ((kind (compute-kind r e))) (and (pair? kind) (eq? 'predefined (car kind))) ;; I've moved the arity checking into ;; meaning-primitive-application, since we already have to ;; do the description lookup there. (meaning-primitive-application e e* r)))) ((and (pair? e) (eq? 'lambda (car e))) (meaning-closed-application e e* r)) (else (meaning-regular-application e e* r)))) (define (meaning-regular-application e e* r) (let* ((m (meaning e r)) (m* (meaning* e* r (length e*)))) ;; pass length for size of ;; activation rec (lambda (sr k) (m sr (lambda (fn) (if (procedure? fn) ;; object-procedure = meta-procedure (m* sr (lambda (v*) (fn v* k))) (runtime-error "Not a function" fn))))))) ;; "left left lambda" (define (meaning-closed-application e ee* r) (let ((nn* (cadr e))) (let parse ((n* nn*) (e* ee*) (regular '())) (cond ((pair? n*) (if (pair? e*) (parse (cdr n*) (cdr e*) (cons (car n*) regular)) (compiler-error "Too few arguments: need" e "got" ee*))) ((null? n*) (if (null? e*) (meaning-fix-closed-application nn* (cddr e) ee* r) (compiler-error "Too many arguments: need" e "got" ee*))) (else ;; augh, rest args in a let-ish form .. (meaning-dotted-closed-application (reverse regular) n* (cddr e) ee* r)))))) (define (meaning-fix-closed-application n* body e* r) (let* ((m* (meaning* e* r (length e*))) (r2 (r-extend* r n*)) (m+ (meaning-sequence body r2))) (lambda (sr k) (m* sr (lambda (v*) (m+ (sr-extend* sr v*) k)))))) (define (meaning-dotted-closed-application n* n body e* r) (let* ((m* (meaning-dotted* e* r (length e*) (length n*))) (r2 (r-extend* r (append n* (list n)))) (m+ (meaning-sequence body r2))) (lambda (sr k) (m* sr (lambda (v*) (m+ (sr-extend* sr v*) k)))))) ;; As the book says, because we know the number of arguments being ;; supplied, we can build the rest list as we go; essentially a ;; transformation of the 'excess' argument expressions from ;; r1 .. r2 .. r3 to (cons r1 (cons r2 (cons r3 '()))) (define (meaning-dotted* e* r size arity) (if (pair? e*) (meaning-some-dotted-args (car e*) (cdr e*) r size arity) (meaning-no-dotted-arg r size arity))) (define (meaning-some-dotted-args e e* r size arity) (let ((m (meaning e r)) (m* (meaning-dotted* e* r size arity)) (rank (- size (length e*) 1))) (if (< rank arity) ;; if still in 'obligatory' arguments (lambda (sr k) (m sr (lambda (v) (m* sr (lambda (v*) (:argument! v* rank v) (k v*)))))) ;; else we're in rest args (lambda (sr k) (m sr (lambda (v) (m* sr (lambda (v*) (:argument! v* arity (cons v (:argument v* arity))) (k v*))))))))) (define (meaning-no-dotted-arg r size arity) (let ((arity+1 (+ arity 1))) (lambda (sr k) (let ((v* (make <activation> arity+1))) (:argument! v* arity '()) (k v*))))) ;; Compile (a fixed number of) arguments. The continuation gets the ;; activation frame. (define (meaning* e* r size) (if (pair? e*) (meaning-some-args (car e*) (cdr e*) r size) (meaning-no-args r size))) ;; Make an activation frame for each invocation (see book for ;; discussion) (define (meaning-no-args r size) (let ((size+1 (+ 1 size))) (lambda (sr k) (let ((v* (make <activation> size+1))) (k v*))))) (define (meaning-some-args e e* r size) (let ((m1 (meaning e r)) (m* (meaning* e* r size)) (index (- size (length e*) 1))) (lambda (sr k) (m1 sr (lambda (v) (m* sr (lambda (v*) (:argument! v* index v) (k v*)))))))) ;; All the environment stuff above is now useful for compiling -- I ;; mean pretreating -- variable references and assignment. (define (meaning-deref n r) (let ((kind (compute-kind r n))) (if kind (case (car kind) ((local) (let ((i (cadr kind)) (j (cddr kind))) (if (= i 0) (lambda (sr k) (k (:argument sr j))) (lambda (sr k) (k (deep-fetch sr i j)))))) ((global) (let ((i (cdr kind))) ;; This is of dubious utility -- only check later if it's ;; undefined now (if (eq? (global-fetch i) UNDEFINED) (lambda (sr k) (let ((value (global-fetch i))) (if (eq? value UNDEFINED) (runtime-error "variable not defined" n)))) (lambda (sr k) (k (global-fetch i)))))) ((predefined) (let* ((i (cdr kind)) (value (predef-fetch i))) (lambda (sr k) (k value))))) (compiler-error "No such variable:" n)))) (define (meaning-assignment n e r) (let ((m (meaning e r)) (kind (compute-kind r n))) (if kind (case (car kind) ((local) (let ((i (cadr kind)) (j (cddr kind))) (if (= i 0) (lambda (sr k) (m sr (lambda (val) (k (:argument! sr j val))))) (lambda (sr k) (m sr (lambda (val) (k (deep-update! sr i j val)))))))) ((global) (let ((i (cdr kind))) (lambda (sr k) (m sr (lambda (v) (k (global-update! i v))))))) ((predefined) (compiler-error "Assignment to immutable variable:" n))) (compiler-error "No such variable:" n)))) ;; Lambdas ;; arity+1, and size+1 above, because we may have to collect up extra ;; arguments into a list when we do the application. (define (meaning-fix-abstraction n* e+ r) (let* ((arity (length n*)) (arity+1 (+ 1 arity)) (r2 (r-extend* r n*)) (m+ (meaning-sequence e+ r2))) (lambda (sr k) (k (lambda (v* k1) (if (= (vector-length (:args v*)) arity+1) (m+ (sr-extend* sr v*) k1) (runtime-error "Incorrect arity:" arity "; expected:" (vector-length (:args v*))))))))) (define (meaning-dotted-abstraction n* n e+ r) (let* ((arity (length n*)) (arity+1 (+ 1 arity)) (r2 (r-extend* r (append n* (list n)))) (m+ (meaning-sequence e+ r2))) (lambda (sr k) (k (lambda (v* k1) (if (>= (vector-length (:args v*)) arity+1) (begin (listify! v* arity) (m+ (sr-extend* sr v*) k1)) (runtime-error "Insufficient args:" v* "; expected: " arity))))))) ;; Takes rest args, conses them into a list, and pops them into the ;; magical extra activation frame slot. Interesting point from Tony: ;; when `apply`ing a procedure, you don't want to be taking the list ;; or arguments apart just to put it back together, so it's worth ;; having a different entry point for `apply`. Extra for experts .. (define (listify! v* arity) (let loop ((index (- (:length v*) 1)) (result '())) (if (= arity index) (:argument! v* arity result) (loop (- index 1) (cons (:argument v* (- index 1)) result))))) (define (meaning-abstraction nn* e+ r) (let parse ((n* nn*) (regular '())) (cond ((pair? n*) (parse (cdr n*) (cons (car n*) regular))) ((null? n*) (meaning-fix-abstraction nn* e+ r)) (else (meaning-dotted-abstraction (reverse regular) n* e+ r))))) ;; === Now for the repl ;; Initial env (define r.init '()) ;; Initial memory (define sr.init (make <activation> 0)) ;; Redefine or initialise a global variable (either predef'd or user). ;; This ties the global environments earlier to our top-level ;; environment and store. (define UNDEFINED '(constant . undefined)) (define (g.current-init! name) ;; I don't know why r.init is here, since it doesn't contain ;; anything; possibly for generality, in case something does get ;; added to it? I guess something has to go in that argument ;; position, and if I change the representation of envs, r.init ;; will change with it. (let ((kind (compute-kind r.init name))) (if kind (case (car kind) ((global) (global-update! (cdr kind) UNDEFINED)) (else (compiler-error "Bad redefinition" name kind))) (let ((index (g.current-extend! name))) (global-update! index UNDEFINED)))) name) (define (g.init-init! name value) ;; As above, not sure why r.init is here (let ((kind (compute-kind r.init name))) (if kind (case (car kind) ((predefined) (vector-set! sg.init (cdr kind) value)) (else (compiler-error "Bad redefinition" name kind))) (let ((index (g.init-extend! name))) (vector-set! sg.init index value)))) name) ;; Primitives, definition of. The book has a separate environment for ;; the definitions of primitives, used only during pretreatment when ;; the name refers directly to the primitive (and so will I). (define desc.init '()) (define (description-extend! name description) (set! desc.init (cons (cons name description) desc.init)) name) (define (get-description name) (let ((d (assq name desc.init))) (and (pair? d) (cdr d)))) ;; I.e., a predefined. This isn't actually given in the book (define (define-initial name value) (g.init-init! name value)) ;; The book has here syntax, and below a (case ...) expression, ;; testing the arity or number of arguments given, with an else clause ;; resorting to regular application. This can only be an optimisation, ;; for when the procedure is named and applied in the same place. So: ;; the underlying procedure (just taking arguments) ends up in the ;; description for static application; while the behaviour (taking an ;; activation frame) ends up in the environment, for regular ;; application. Note that I don't record a list of variables, just the ;; arity. (define (define-primitive name underlying arity) ;; Nicked from http://srfi.schemers.org/srfi-1/srfi-1-reference.scm (define (take lis k) (let recur ((lis lis) (k k)) (if (zero? k) '() (cons (car lis) (recur (cdr lis) (- k 1)))))) (define-initial name ;; not sure why it's a letrec in the book (let* ((arity+1 (+ arity 1)) ;; behaviour is called with the activation record (behaviour (lambda (v* k) (let* ((args (:args v*)) (numargs (vector-length args))) (if (= arity+1 numargs) (k (apply underlying (take (vector->list args) arity))) (runtime-error "Wrong arity" arity numargs)))))) (description-extend! name `(function ,underlying ,arity)) behaviour))) ;; Here is where my laziness above wrt arity makes things tricky; ;; instead of having clauses for the different arities, I have to do a ;; kind of CPS fold over the expressions. I have moved some of the ;; checking of the description here from meaning-application, to avoid ;; getting the description twice. As in the book, if the expression is ;; statically known to be predefined (which is why we're here), but ;; the description is not present (um, why?), we fall through to ;; regular application. (define (meaning-primitive-application e e* r) (let ((desc (get-description e))) (and desc (eq? 'function (car desc)) (if (= (caddr desc) (length e*)) (let ((addr (cadr desc)) (m* (let loop ((m* '()) (e* e*)) (if (null? e*) (reverse m*) (loop (cons (meaning (car e*) r) m*) (cdr e*)))))) ;; Now I have all the meanings, that is procedures that ;; take an activation frame and a continuation, where ;; the continuation takes a value. I want to chain ;; them together, making the continuation of the first ;; call the second, and so on: ;; (m1 sr (lambda (v1) (m2 sr (lambda (v2) ...)))) (if (null? m*) (lambda (sr k) (k (addr))) (lambda (sr k) (let loop ((vs '()) (m* m*)) (let ((m (car m*)) (ms (cdr m*))) (if (null? ms) (m sr (lambda (v) (k (apply addr (reverse (cons v vs)))))) (m sr (lambda (v) (loop (cons v vs) ms))))))))) (compiler-error "Wrong arity for procedure" e "expected" (caddr desc) "given" (length e*)))))) (define (repl) (define (toplevel) (display "> ") ((meaning (read) r.init) sr.init display)(newline) (toplevel)) (toplevel)) ;; For the smoketest (define (eval-expr e) (call/cc (lambda (k) ((meaning e r.init) sr.init k)))) ;; Things to play with (define-primitive '+ + 2) (define-primitive '- - 2) ;; The book doesn't go on to detail apply and call/cc until §6.3, by ;; which time the interpreter has changed significantly. In the ;; interests of moving on, I'll leave them aside too.
false
da706f515a9c634eb2eb7396523046f1f6fa4c0f
00ed3dc269318dd060d64745fcf8c37d23db1745
/rc.scm
3f4420ec4b116b61240972745af99c0b2dc2f3c2
[ "MIT" ]
permissive
nv-vn/unbox
9370ed41959383da848ef93995787c03344237f6
ddb227edec5464fcc30c291e80725a8cdf0c1229
refs/heads/master
2021-01-16T18:36:27.717149
2015-12-27T13:50:37
2015-12-27T13:50:37
48,468,593
3
0
null
null
null
null
UTF-8
Scheme
false
false
5,277
scm
rc.scm
(rc (resistance (strength 10) (screen-edge-strength 20)) (focus (focus-new yes) (follow-mouse no) (focus-last yes) (under-mouse no) (focus-delay 200) (raise-on-focus no)) (placement monitor-primary ; This should be set, but the <primaryMonitor> tag is non-standard? (policy smart) (center yes)) (theme (name "THEME NAME HERE") (title-layout "NLIMC") (keep-border yes) (animate-iconify yes) (font-active-window (name "sans") (size 8) (weight bold) (slant normal)) (font-inactive-window (name "sans") (size 8) (weight bold) (slant normal)) (font-menu-header (name "sans") (size 9) (weight normal) (slant normal)) (font-menu-item (name "sans") (size 9) (weight normal) (slant normal))) ; Should be (in)activeonscreendisplay (desktops (number 4) (first-desk 1) (names "First" "Second" "Third" "Fourth") (popup-time 875)) (resize (draw-contents yes) (popup-show non-pixel) (popup-position centered) (popup-fixed-position (x 10) (y 10))) (make-margins 0 0 0 0) ; Top/Bottom/Left/Right (dock (position top-left) (floating-x 0) (floating-y 0) (no-strut no) (stacking above) (direction vertical) (autohide no) (hide-delay 300) (show-delay 300) (move-button middle)) (keyboard (chain-quit-key [C "g"]) (keybind [C [A left]] (go-to-desktop to-left (wrap no))) (keybind [C [A right]] (go-to-desktop to-right (wrap no))) (keybind [C [A up]] (go-to-desktop to-up (wrap no))) (keybind [C [A down]] (go-to-desktop to-down (wrap no))) (keybind [S [A left]] (send-to-desktop to-left (wrap no))) (keybind [S [A right]] (send-to-desktop to-right (wrap no))) (keybind [S [A up]] (send-to-desktop to-up (wrap no))) (keybind [S [A down]] (send-to-desktop to-up (wrap no))) (keybind [W "F1"] (go-to-desktop (to 1))) (keybind [W "F2"] (go-to-desktop (to 2))) (keybind [W "F3"] (go-to-desktop (to 3))) (keybind [W "F4"] (go-to-desktop (to 4))) (keybind [W "d"] (toggle-show-desktop)) ;; Key bindings for windows (keybind [A "F4"] (close)) (keybind [A "Escape"] (action-lower) (action-focus-to-bottom) (action-unfocus)) (keybind [A "space"] (show-menu (menu "client-menu"))) ;; Take a screenshot of the current window with scrot when Alt+Print are pressed (keybind [A "Print"] (execute "scrot -s")) ;; Keybindings for window switching (keybind [A "Tab"] (next-window (final-actions (action-focus) (action-raise) (unshade)))) (keybind [A [S "Tab"]] (previous-window (final-actions (action-focus) (action-raise) (unshade)))) (keybind [C [A "Tab"]] (next-window (panels yes) ;; (desktop yes) ;; FIXME! (final-actions (action-focus) (action-raise) (unshade)))) ;; Keybindings for window switching with the arrow keys (keybind [W [S right]] (directional-cycle-windows (direction right))) ;; FIXME? (keybind [W [S left]] (directional-cycle-windows (direction left))) ;; FIXME? (keybind [W [S up]] (directional-cycle-windows (direction up))) ;; FIXME? (keybind [W [S down]] (directional-cycle-windows (direction down))) ;; FIXME? ;; Keybindings for running applications (keybind [W "e"] (execute [(enabled true) (name "Konqueror")] "kfmclient openProfile filemanagement")) ;; Launch scrot when Print is pressed (keybind "Print" (execute "scrot"))) (mouse ;; (drag-threshold 1) ;; FIXME! ;; (double-click-time 500) ;; FIXME! ;; (screen-edge-warp-time 400) ;; FIXME! ;; (screen-edge-warp-mouse false) ;; FIXME! (context "Frame" (mousebind [A left] press (action-focus) (action-raise)) (mousebind [A left] click (unshade)) (mousebind [A left] drag (move)) (mousebind [A right] press (action-focus) (action-raise) (unshade)) (mousebind [A right] drag (action-resize)) (mousebind [A middle] press (action-lower) (action-focus-to-bottom) (action-unfocus)) (mousebind [A up] click (go-to-desktop to-previous)) (mousebind [A down] click (go-to-desktop to-next)) (mousebind [C [A up]] click (go-to-desktop to-previous)) (mousebind [C [A down]] click (go-to-desktop to-next)) (mousebind [A [S up]] click (send-to-desktop to-previous)) (mousebind [A [S down]] click (send-to-desktop to-next))) (context "Titlebar" (mousebind left drag (move)) (mousebind left double-click (toggle-maximize)) (mousebind up click (action-if [(shaded? no)] ;; FIXME! [(shade) (action-focus-to-bottom) (action-unfocus) (action-lower)])))))
false
df6827fb63cf2b0201d194aa8a6d3563b73b6c58
b60cb8e39ec090137bef8c31ec9958a8b1c3e8a6
/test/R5RS/scp1/family-budget.scm
b985d893b08fa786c86800a535ec9340c4071101
[]
no_license
acieroid/scala-am
eff387480d3baaa2f3238a378a6b330212a81042
13ef3befbfc664b77f31f56847c30d60f4ee7dfe
refs/heads/master
2021-01-17T02:21:41.692568
2021-01-15T07:51:20
2021-01-15T07:51:20
28,140,080
32
16
null
2020-04-14T08:53:20
2014-12-17T14:14:02
Scheme
UTF-8
Scheme
false
false
1,912
scm
family-budget.scm
(define familieboom '(jan (piet (frans (tom) (roel)) (mie)) (bram (inge (bert (ina) (ilse)) (bart)) (iris)) (joost (else (ilse))))) (define (familiehoofd fam) (car fam)) (define (kinderen fam) (cdr fam)) (define (laatste-nakomeling? fam) (null? (kinderen fam))) (define (verdeel-democratisch boom budget) (define (verdeel boom) (if (laatste-nakomeling? boom) 1 (+ 1 (verdeel-in (kinderen boom))))) (define (verdeel-in lst) (if (null? lst) 0 (+ (verdeel (car lst)) (verdeel-in (cdr lst))))) (/ budget (verdeel-in (kinderen boom)))) (define (budget boom budget-list) (define (budget-hulp boom budget-list) (+ (car budget-list) (budget-hulp-in (kinderen boom) (cdr budget-list)))) (define (budget-hulp-in bomen budget-list) (if (or (null? bomen)(null? budget-list)) 0 (+ (budget-hulp (car bomen) budget-list) (budget-hulp-in (cdr bomen) budget-list)))) (budget-hulp-in (kinderen boom) budget-list)) (define (verdeel boom budget) (cond ((laatste-nakomeling? boom) (list (list (familiehoofd boom) budget))) (else (let* ((rest (kinderen boom)) (new-budget (/ budget (length rest)))) (verdeel-in rest new-budget))))) (define (verdeel-in bomen budget) (if (null? bomen) '() (append (verdeel (car bomen) budget) (verdeel-in (cdr bomen) budget)))) (and (= (verdeel-democratisch familieboom 1500) 100) (= (budget familieboom '(100 50 20)) 650) (equal? (verdeel familieboom 3000) '((tom 250) (roel 250) (mie 500) (ina 125) (ilse 125) (bart 250) (iris 500) (ilse 1000))))
false
7fb4f6c6a4eec1bcabc53b2440047df090f12174
0011048749c119b688ec878ec47dad7cd8dd00ec
/src/042/solution.scm
04e6302d102bdacae79024629baa95619ab15062
[ "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
501
scm
solution.scm
(import (chicken io) (chicken string) (srfi 1)) (define (import-input) (let ((base (char->integer #\A))) (map (lambda (str) (apply + (map (lambda (char) (- (char->integer char) base -1)) (string->list str)))) (string-split (read-line) "\",")))) (define (triangle? n) (integer? (sqrt (+ (* 8 n) 1)))) (define (solve input) (count triangle? input)) (let ((_ (solve (import-input)))) (print _) (assert (= _ 162)))
false
9af9e79fb01bf148a713485e1b3e94fab6d66b96
b14c18fa7a4067706bd19df10f846fce5a24c169
/Chapter3/3.47.scm
32e4dab4ee3f39ca8b33f39bbede497f4c149a58
[]
no_license
silvesthu/LearningSICP
eceed6267c349ff143506b28cf27c8be07e28ee9
b5738f7a22c9e7967a1c8f0b1b9a180210051397
refs/heads/master
2021-01-17T00:30:29.035210
2016-11-29T17:57:16
2016-11-29T17:57:16
19,287,764
3
0
null
null
null
null
UTF-8
Scheme
false
false
719
scm
3.47.scm
#lang scheme ; pseudo code (define (make-semaphone max) (define counter-max max) (define counter 0) (define counter-lock (make-mutex)) (define lock (make-mutex)) (define (acquire-inner) (lock 'acquire) (counter-lock 'acquire) ) (define (acquire) (counter-lock 'acquire) (if (>= counter counter-max) (counter-lock 'release) (acquire-inner) ) (set! counter (+ counter 1)) (counter-lock 'release) ) (define (release) (lock 'release) (counter-lock 'acquire) (set! counter (- counter 1)) (counter-lock 'release) ) (define (the-semaphone s) (cond ((eq? m 'acquire) (acquire)) ((eq? m 'release) (release)) ) ) ) ; on test-and-set! ; just embed code of mutex in the book ?
false
83a100948c517068771ff92c3ef822c2d7afc802
454658b48dc3695aeffa16d6330a444e5a6cd30d
/utils/misc/asserts.ss
c91f9e3aebe970f5acfbdb5bb3ba9e132c21583e
[ "MIT" ]
permissive
Chream/chream-utils
2cd4cb31fc5f1876759d6a5f44a46e86b0401054
40320e5601cff0d26c9a37179fc8dc36de1adbef
refs/heads/master
2020-03-09T14:02:11.052386
2018-07-17T16:12:51
2018-07-17T16:12:51
128,825,406
1
0
null
null
null
null
UTF-8
Scheme
false
false
217
ss
asserts.ss
;;; -*- Gerbil -*- ;;; © Chream (import :std/format) (export #t) (def (check-type specifier? obj) (unless (specifier? obj) (error (format "Object ~S does not fulfill ~S" obj specifier?))))
false
2db749162f502640bf46210fa651a2026539fc80
ac2a3544b88444eabf12b68a9bce08941cd62581
/lib/_prim-char#.scm
3abf7b32d85e211470ef02c66f87731f4454ba72
[ "Apache-2.0", "LGPL-2.1-only" ]
permissive
tomelam/gambit
2fd664cf6ea68859d4549fdda62d31a25b2d6c6f
d60fdeb136b2ed89b75da5bfa8011aa334b29020
refs/heads/master
2020-11-27T06:39:26.718179
2019-12-15T16:56:31
2019-12-15T16:56:31
229,341,552
1
0
Apache-2.0
2019-12-20T21:52:26
2019-12-20T21:52:26
null
UTF-8
Scheme
false
false
447
scm
_prim-char#.scm
;;;============================================================================ ;;; File: "_prim-char#.scm" ;;; Copyright (c) 1994-2019 by Marc Feeley, All Rights Reserved. ;;;============================================================================ ;;; Character operations. (##include "~~lib/_prim-char-r4rs#.scm") (##include "~~lib/_prim-char-r7rs#.scm") ;;;============================================================================
false
fa3cc4b549eb29db6179f44d3abcc042903190c3
307481dbdfd91619aa5fd854c0a19cd592408f1b
/node_modules/biwascheme/,/58/a.scm
6fc239abf62f9529d1c9ac99727782e769c348e1
[ "MIT", "CC-BY-3.0" ]
permissive
yukarigohan/firstrepository
38ff2db62bb8baa85b21daf65b12765e10691d46
2bcdb91cbb6f01033e2e0a987a9dfee9d3a98ac7
refs/heads/master
2020-04-20T10:59:02.600980
2019-02-02T07:08:41
2019-02-02T07:08:41
168,803,970
0
0
null
null
null
null
UTF-8
Scheme
false
false
964
scm
a.scm
(import (scheme base) (scheme lazy) (scheme write)) (define stream-car car) (define stream-cdr (lambda (stm) (force (cdr stm)))) (define-syntax stream-cons (syntax-rules () ((_ head tail) (cons head (delay tail))))) (define make-stream (lambda (seed proc) (letrec ((stream-builder (lambda (n) (stream-cons n (stream-builder (proc n)))))) (stream-builder seed)))) (define stream-item (lambda (str k) (if (= k 0) (stream-car str) (stream-item (stream-cdr str) (- k 1))))) (define stream-map (lambda (f str) (stream-cons (f (stream-car str)) (stream-map f (stream-cdr str))))) (define print-stream (lambda (stm n) (cond ((<= n 0) (display "...")(newline)) (else (display (stream-car stm)) (display ", ") (print-stream (stream-cdr stm) (- n 1)))))) (define nat_zahlen (make-stream 0 (lambda (n) (+ n 1)))) (print-stream nat_zahlen 11)
true
0dea84b635b9614a7d42d14e88799af1c55c4c68
140a499a12332fa8b77fb738463ef58de56f6cb9
/worlds/core/verbcode/22/assoc-set-2.scm
374141253774b78ba5856c8ab9badd490bc0ca53
[ "MIT" ]
permissive
sid-code/nmoo
2a5546621ee8c247d4f2610f9aa04d115aa41c5b
cf504f28ab473fd70f2c60cda4d109c33b600727
refs/heads/master
2023-08-19T09:16:37.488546
2023-08-15T16:57:39
2023-08-15T16:57:39
31,146,820
10
0
null
null
null
null
UTF-8
Scheme
false
false
456
scm
assoc-set-2.scm
;;; (:assoc-set assoclist key new-value) ;;; If a `(key, any-value)` pair exists in `assoclist`, it is removed. ;;; Then, a `(key, new-value)` pair is added to `assoclist`. (let ((assoclist (get args 0)) (key (get args 1)) (new-value (get args 2)) (existing (self:assoc-pair assoclist key (list key new-value))) (new-existing (set existing 1 new-value))) (setadd (setremove assoclist existing) new-existing))
false
7da61b8eeba48ad26bf0e8c3b121004e83b4a10e
ee79125fc6e61b2f611d9b5724e56190fa8da53a
/library/la-library/cross-rotation.scm
789a80e620ebeb7a755c6f113de42b429e4e992c
[ "Apache-2.0" ]
permissive
cleoold/calculus-toolbox
b16dce4bea9d81beb824ee8570b12cb3ffe19a91
e5a6d3d9c5e85c94b335c48f235ba4c8fec7ed9f
refs/heads/master
2020-04-17T02:38:44.998990
2019-08-05T13:35:36
2019-08-05T13:35:36
166,145,959
1
0
null
null
null
null
UTF-8
Scheme
false
false
393
scm
cross-rotation.scm
#lang scheme/base (require scheme/math) (provide vec-cross r2) (define (vec-cross u v) (list (- (* (cadr u) (caddr v)) (* (caddr u) (cadr v))) (- (* (caddr u) (car v)) (* (car u) (caddr v))) (- (* (car u) (cadr v)) (* (cadr u) (car v))))) (define (r2 v a) (list (- (* (cos a) (car v)) (* (sin a) (cadr v))) (+ (* (sin a) (car v)) (* (cos a) (cadr v)))))
false
3b5308e147da1a7309ab11e0b997e5cefdddaac8
db0f911e83225f45e0bbc50fba9b2182f447ee09
/the-scheme-programming-language/2.9-assignment/examples/lazy.scm
8cc33b3d62cebc77fb39d6150fd124b5498d69eb
[]
no_license
ZhengHe-MD/learn-scheme
258941950302b4a55a1d5d04ca4e6090a9539a7b
761ad13e6ee4f880f3cd9c6183ab088ede1aed9d
refs/heads/master
2021-01-20T00:02:38.410640
2017-05-03T09:48:18
2017-05-03T09:48:18
89,069,898
0
0
null
null
null
null
UTF-8
Scheme
false
false
287
scm
lazy.scm
(define lazy (lambda (t) (let ([val #f] [flag #f]) (lambda () (if (not flag) (begin (set! val (t)) (set! flag #t)) val))))) (define p (lazy (lambda () (display "Ouch!") (newline) "got me")))
false
f486f21d867312e4d99693abdc392b237b1123d2
7301b8e6fbd4ac510d5e8cb1a3dfe5be61762107
/ex-3.61.scm
4408284ac47d6d7eb6746981449f2ec4395ea234
[]
no_license
jiakai0419/sicp-1
75ec0c6c8fe39038d6f2f3c4c6dd647a39be6216
974391622443c07259ea13ec0c19b80ac04b2760
refs/heads/master
2021-01-12T02:48:12.327718
2017-01-11T12:54:38
2017-01-11T12:54:38
78,108,302
0
0
null
2017-01-05T11:44:44
2017-01-05T11:44:44
null
UTF-8
Scheme
false
false
888
scm
ex-3.61.scm
;;; Exercise 3.61. Let S be a power series (exercise 3.59) whose constant term ;;; is 1. Suppose we want to find the power series 1/S, that is, the series ;;; X such that S · X = 1. Write S = 1 + S_R where S_R is the part of S after ;;; the constant term. Then we can solve for X as follows: ;;; ;;; S・X = 1 ;;; (1+S_R)・X = 1 ;;; X + S_R・X = 1 ;;; X = 1 - S_R・X ;;; ;;; In other words, X is the power series whose constant term is 1 and whose ;;; higher-order terms are given by the negative of S_R times X. Use this idea ;;; to write a procedure invert-unit-series that computes 1/S for a power ;;; series S with constant term 1. You will need to use mul-series from ;;; exercise 3.60. (define (invert-unit-series S) (define X (cons-stream 1 (mul-series (scale-stream (stream-cdr S) -1) X))) X)
false
6876cb955c5abbf977f3142097f0722f35fa71e6
9998f6f6940dc91a99e0e2acb4bc4e918f49eef0
/src/test/basic.ss
c719ce44d3164ca2a2aed4da8cfaac76565f582e
[]
no_license
JessamynT/wescheme-compiler2012
326d66df382f3d2acbc2bbf70fdc6b6549beb514
a8587f9d316b3cb66d8a01bab3cf16f415d039e5
refs/heads/master
2020-05-30T07:16:45.185272
2016-03-19T07:14:34
2016-03-19T07:14:34
70,086,162
0
0
null
2016-10-05T18:09:51
2016-10-05T18:09:51
null
UTF-8
Scheme
false
false
69,195
ss
basic.ss
#lang s-exp "../moby-lang.ss" ;; This is a set of basic tests. A lot of this is copy-and-pasted from PLT-Scheme's ;; test suite. #;(require "test-harness.ss") (define number-of-tests 0) (define number-of-skipped-tests 0) (define number-of-errors 0) (define error-messages empty) (define (add-error-message! msg) (set! error-messages (append error-messages (list msg)))) (define (test expect fun args) (begin (set! number-of-tests (add1 number-of-tests)) (let ([res (if (procedure? fun) (apply fun args) (car args))]) (let ([ok? (equal? expect res)]) (cond [(not ok?) (begin (add-error-message! (format "expected ~s, got ~s, on ~s" expect res (cons fun args))) (set! number-of-errors (add1 number-of-errors)) (list false expect fun args))] [else (list ok? expect fun args)]))))) ;; Just a note to myself about which tests need to be fixed. (define (skip f) (begin (set! number-of-skipped-tests (add1 number-of-skipped-tests)))) ;; test that all symbol characters are supported. '(+ - ... !.. $.+ %.- &.! *.: /:. :+. <-. =. >. ?. ~. _. ^.) (define disjoint-type-functions (list boolean? char? null? number? pair? procedure? string? symbol? vector?)) ;; Let tests, from syntax.ss ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (test 6 'let (list (let ((x 2) (y 3)) (* x y)))) (test 'second 'let (list (let ((x 2) (y 3)) (begin (* x y) 'second)))) (test 35 'let (list (let ((x 2) (y 3)) (let ((x 7) (z (+ x y))) (* z x))))) (test 70 'let* (list (let ((x 2) (y 3)) (let* ((x 7) (z (+ x y))) (* z x))))) (test #t 'letrec (list (letrec ((-even? (lambda (n) (if (zero? n) #t (-odd? (- n 1))))) (-odd? (lambda (n) (if (zero? n) #f (-even? (- n 1)))))) (-even? 88)))) (define x 34) ;; FIXME: ;; The tests involving internal defines have been changed to use local ;; for now. (test 5 'let (list (let ((x 3)) (local [(define x 5)] x)))) (test 5 'let (list (let ((x 3)) (local [(define x 5) (define w 8)] x)))) (test 34 'let (list x)) (test 6 'let (list (let () (local [(define x 6)] x)))) (test 34 'let (list x)) (test 7 'let* (list (let* ((x 3)) (local [(define x 7)] x)))) (test 34 'let* (list x)) (test 8 'let* (list (let* () (local [(define x 8)] x)))) (test 34 'let* (list x)) (test 9 'letrec (list (letrec () (local [(define x 9)] x)))) (test 34 'letrec (list x)) (test 10 'letrec (list (letrec ((x 3)) (local [(define x 10)] x)))) (test 34 'letrec (list x)) (test 3 'let (list (let ((y 'apple) (x 3) (z 'banana)) x))) (test 3 'let* (list (let* ((y 'apple) (x 3) (z 'banana)) x))) (test 3 'letrec (list (letrec ((y 'apple) (x 3) (z 'banana)) x))) (test 3 'let* (list (let* ((x 7) (y 'apple) (z (set! x 3))) x))) (test 3 'let* (list (let* ((x 7) (y 'apple) (z (if (not #f) (set! x 3) #f))) x))) (test 3 'let* (list (let* ((x 7) (y 'apple) (z (if (not #t) #t (set! x 3)))) x))) (let ([val 0]) (begin (let ([g (lambda () (letrec ([f (lambda (z x) (if (let ([w (even? 81)]) (if w w (let ([y x]) (begin (set! x 7) (set! val (+ y 5)) #t)))) 'yes 'no))]) (f 0 11)))]) (g)) (test 16 identity (list val)))) (let ([val 0]) (begin (let ([g (lambda () (letrec ([f (lambda (z x) (if (let ([w (even? 81)]) (if w w (let ([y x]) (begin (set! val (+ y 5)) #t)))) 'yes 'no))]) (f 0 11)))]) (g)) (test 16 identity (list val)))) (test #f not (list #t)) (test #f not (list 3)) (test #f not (list (list 3))) (test #t not (list #f)) (test #f not (list '())) (test #f not (list (list))) (test #f not (list 'nil)) (test #t boolean? (list #f)) (test #t boolean? (list #t)) (test #f boolean? (list 0)) (test #f boolean? (list '())) (test #t eqv? (list 'a 'a)) (test #f eqv? (list 'a 'b)) (test #t eqv? (list 2 2)) (test #f eqv? (list 2 (exact->inexact 2.0))) (test #t eqv? (list '() '())) (test #t eqv? (list '10000 '10000)) ;; These tests are commented out because Moby doesn't have bignums ;; yet. (skip (lambda () (test #t eqv? (list 10000000000000000000 10000000000000000000)))) (skip (lambda () (test #f eqv? (list 10000000000000000000 10000000000000000001)))) (skip (lambda () (test #f eqv? (list 10000000000000000000 20000000000000000000)))) ;; This test is commented out because cons only allows lists as a ;; second argument. (skip (lambda () (test #f eqv? (list (cons 1 2) (cons 1 2))))) (test #f eqv? (list (lambda () 1) (lambda () 2))) (test #f eqv? (list #f 'nil)) (let ((p (lambda (x) x))) (test #t eqv? (list p p))) (define gen-counter (lambda () (let ((n 0)) (lambda () (begin (set! n (+ n 1)) n))))) (let ((g (gen-counter))) (test #t eqv? (list g g))) (test #f eqv? (list (gen-counter) (gen-counter))) (letrec ((f (lambda () (if (eqv? f g) 'f 'both))) (g (lambda () (if (eqv? f g) 'g 'both)))) (test #f eqv? (list f g))) ;; Some tests with structures, from struct.ss (define-struct a (b c)) (define-struct aa ()) (define ai (make-a 1 2)) (define aai (make-aa)) ;;(test #t struct-type? struct:a) ;;(test #f struct-type? 5) (test #t procedure? (list a?)) (test #t a? (list ai)) (test #f a? (list 1)) (test #f aa? (list ai)) ;; We don't have struct inspectors, so this test should fail. ;;(test #f struct? (list ai)) (test 1 a-b (list ai)) (test 2 a-c (list ai)) (define ai2 (make-a 1 2)) (set-a-b! ai2 3) (set-a-c! ai2 4) (test 1 a-b (list ai)) (test 2 a-c (list ai)) (test 3 a-b (list ai2)) (test 4 a-c (list ai2)) ;; Commented out: we don't yet properly support redefinition of structures. #;(define-struct a (b c)) #;(test #f a? (list ai)) ;; Quasiquotation tests from syntax.ss. (test '(list 3 4) 'quasiquote (list `(list ,(+ 1 2) 4))) (test '(list a (quote a)) 'quasiquote (list (let ((name 'a)) `(list ,name ',name)))) (test '(a 3 4 5 6 b) 'quasiquote (list `(a ,(+ 1 2) ,@(map abs '(4 -5 6)) b))) ;; Test commented out: we shouldn't support dotted pairs. ;(test '((foo 7) . cons) ; 'quasiquote ; `((foo ,(- 10 3)) ,@(cdr '(c)) . ,(car '(cons)))) ;; Test commented out for now: we don't yet support this syntax for vectors. ;(test '#(10 5 2 4 3 8) 'quasiquote (list `#(10 5 ,(sqrt 4) ,@(map sqrt '(16 9)) 8))) (test 5 'quasiquote (list `,(+ 2 3))) ;; Test with foo commented out: we don't yet support the required let/cc form ;; needed to exercise this ;(test '(a `(b ,(+ 1 2) ,(foo 4 d) e) f) ; 'quasiquote (list `(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f))) (test '(a `(b ,x ,'y d) e) 'quasiquote (list (let ((name1 'x) (name2 'y)) `(a `(b ,,name1 ,',name2 d) e)))) (test '(list 3 4) 'quasiquote (list (quasiquote (list (unquote (+ 1 2)) 4)))) (test '`(list ,(+ 1 2) 4) 'quasiquote (list '(quasiquote (list (unquote (+ 1 2)) 4)))) (test '(()) 'qq (list `((,@'())))) (set! x 5) (test '(quasiquote (unquote x)) 'qq (list ``,x)) (test '(quasiquote (unquote 5)) 'qq (list ``,,x)) (test '(quasiquote (unquote-splicing x)) 'qq (list ``,@x)) (test '(quasiquote (unquote-splicing 5)) 'qq (list ``,@,x)) (test '(quasiquote (quasiquote (quasiquote (unquote (unquote (unquote x)))))) 'qq (list ````,,,x)) (test '(quasiquote (quasiquote (quasiquote (unquote (unquote (unquote 5)))))) 'qq (list ````,,,,x)) ;; Numbers.ss (test #f number? (list 'a)) (test #f complex? (list 'a)) (test #f real? (list 'a)) (test #f rational? (list 'a)) (test #f integer? (list 'a)) (test #t number? (list 3)) (test #t complex? (list 3)) (test #t real? (list 3)) (test #t rational? (list 3)) (test #t integer? (list 3)) (test #t number? (list 3.0)) (test #t complex? (list 3.0)) (test #t real? (list 3.0)) (test #t rational? (list 3.0)) (test #t integer? (list 3.0)) (test #t number? (list 3.1)) (test #t complex? (list 3.1)) (test #t real? (list 3.1)) (test #t rational? (list 3.1)) (test #f integer? (list 3.1)) (test #t number? (list 3/2)) (test #t complex? (list 3/2)) (test #t real? (list 3/2)) (test #t rational? (list 3/2)) (test #f integer? (list 3/2)) ;; Skipping the complex nubmers for now (test #t exact? (list 3)) (test #t exact? (list 3/4)) (test #f exact? (list (exact->inexact 3.0))) ;; Breaking: we don't have bignums! ;(test #t exact? (list (expt 2 100))) ;(test #t exact? 3+4i) ;(test #f exact? 3.0+4i) (test #f inexact? (list 3)) (test #f inexact? (list 3/4)) (test #t inexact? (list (exact->inexact 3.0))) ;; Breaking: we don't have bignums! ;(test #f inexact? (list (expt 2 100))) ;(test #f inexact? 3+4i) ;(test #t inexact? 3.0+4i) ;(test #t inexact? 0+4.0i) ;(test #t inexact? 4+0.i) ;(test #t complex? (list -4.242154731064108e-5-6.865001427422244e-5i)) ;(test #f exact? (list -4.242154731064108e-5-6.865001427422244e-5i)) ;(test #t inexact? (list -4.242154731064108e-5-6.865001427422244e-5i)) ;(test #t complex? (list -4.242154731064108f-5-6.865001427422244f-5i)) ;(test #f exact? (list -4.242154731064108f-5-6.865001427422244f-5i)) ;(test #t inexact? (list -4.242154731064108f-5-6.865001427422244f-5i)) (test #t number? (list +inf.0)) (test #t complex? (list +inf.0)) (test #t real? (list +inf.0)) (test #f rational? (list +inf.0)) (test #f integer? (list +inf.0)) (test #t number? (list -inf.0)) (test #t complex? (list -inf.0)) (test #t real? (list -inf.0)) (test #f rational? (list -inf.0)) (test #f integer? (list -inf.0)) (test "+inf.0" number->string (list +inf.0)) (test "-inf.0" number->string (list -inf.0)) ;; Currently broken: negative zero isn't properly supported yet. (skip (lambda () (test #t = (list 0.0 -0.0)))) (skip (lambda () (test #f eqv? (list 0.0 -0.0)))) (skip (lambda () (test #f equal? (list 0.0 -0.0)))) (skip (lambda () (test #f eqv? (list -0.0 0.0)))) (skip (lambda () (test #t eqv? (list 0.0 0.0)))) (skip (lambda () (test #t eqv? (list -0.0 -0.0)))) (define (test-nan.0 f args) (test +nan.0 f args)) (define (test-i-nan.0 f args) (test (make-rectangular +nan.0 +nan.0) f args)) (define (test-nan c) (begin (test #f < (list +nan.0 c)) (test #f > (list +nan.0 c)) (test #f = (list +nan.0 c)) (test #f <= (list +nan.0 c)) (test #f >= (list +nan.0 c)))) (test #t = (list 22 22 22)) (test #t = (list 22 22)) (test #f = (list 34 34 35)) (test #f = (list 34 35)) (test #t > (list 3 -6246)) (test #f > (list 9 9 -2424)) (test #t >= (list 3 -4 -6246)) (test #t >= (list 9 9)) (test #f >= (list 8 9)) (test #t < (list -1 2 3 4 5 6 7 8)) (test #f < (list -1 2 3 4 4 5 6 7)) (test #t <= (list -1 2 3 4 5 6 7 8)) (test #t <= (list -1 2 3 4 4 5 6 7)) (test #f < (list 1 3 2)) (test #f >= (list 1 3 2)) (define (test-compare lo m hi) ; all positive! (local [(define -lo (- lo)) (define -m (- m)) (define -hi (- hi)) (define (test-lh l h) (begin (test #f > (list l h)) (test #t < (list l h)) (test #f = (list l h)) (test #f >= (list l h)) (test #t <= (list l h)))) (define (test-hl h l) (begin (test #t > (list h l)) (test #f < (list h l)) (test #f = (list h l)) (test #t >= (list h l)) (test #f <= (list h l)))) (define (test-zero z) (begin (test-hl m z) (test-lh -m z) (test-hl z -m) (test-lh z m)))] (begin (test-lh m hi) (test-hl -m -hi) (test #f > (list m m)) (test #f < (list m m)) (test #t = (list m m)) (test #t >= (list m m)) (test #t <= (list m m)) (test-hl m -m) (test-lh -m m) (test-hl m lo) (test-lh -m -lo) (test-zero 0) (test-zero 0.0) (test-compare 0.5 1.2 2.3) (test-compare 2/5 1/2 2/3) (test-compare 1/4 1/3 1/2) ; same numerator (test-compare 3/10 7/10 9/10) ; same denominator ;(test-compare 2/500000000000000000000000000 1/200000000000000000000000000 2/300000000000000000000000000) ; bignums (test #t = (list 1/2 2/4)) (test #f = (list 2/3 2/5)) ;(test #f = 2/3 2/500000000000000000000000000) (test-compare 0.5 6/5 2.3) (test-compare 1 11922615739/10210200 3000) (test-compare 1.0 11922615739/10210200 3000.0) (test #t < (list 0.5 2/3)) (test #f < (list 2/3 0.5)) (test #t = (list 0.5 1/2)) ))) (test #t zero? (list 0)) (test #t zero? (list 0.0)) (test #t zero? (list 0/1)) (test #f zero? (list 1)) (test #f zero? (list -1)) (test #f zero? (list -100)) (test #f zero? (list 1.0)) (test #f zero? (list -1.0)) (test #f zero? (list 1/2)) (test #f zero? (list -1/2)) (test #f zero? (list -1/2+2i)) (test #f zero? (list +inf.0)) (test #f zero? (list -inf.0)) (test #f zero? (list (expt 2 37))) (test #f zero? (list (expt -2 37))) (test #t positive? (list 4)) (test #f positive? (list -4)) (test #f positive? (list 0)) (test #t positive? (list 4.0)) (test #f positive? (list -4.0)) (test #f positive? (list 0.0)) (test #t positive? (list 2/4)) (test #f positive? (list -2/4)) (test #f positive? (list 0/2)) (test #t positive? (list +inf.0)) (test #f positive? (list -inf.0)) (test #t positive? (list (expt 2 37))) (test #f positive? (list (expt -2 37))) (test #f negative? (list 4)) (test #t negative? (list -4)) (test #f negative? (list 0)) (test #f negative? (list 4.0)) (test #t negative? (list -4.0)) (test #f negative? (list 0.0)) (test #f negative? (list 2/4)) (test #t negative? (list -2/4)) (test #f negative? (list 0/4)) (test #f negative? (list (expt 2 37))) (test #t negative? (list (expt -2 37))) (test #f negative? (list +inf.0)) (test #t negative? (list -inf.0)) (test #t odd? (list 3)) (test #f odd? (list 2)) (test #f odd? (list -4)) (test #t odd? (list -1)) (test #f odd? (list (expt 2 37))) (test #f odd? (list (expt -2 37))) (test #t odd? (list (add1 (expt 2 37)))) (test #t odd? (list (sub1 (expt -2 37)))) (test #f even? (list 3)) (test #t even? (list 2)) (test #t even? (list -4)) (test #f even? (list -1)) (test #t even? (list (expt 2 37))) (test #t even? (list (expt -2 37))) (test #f even? (list (add1 (expt 2 37)))) (test #f even? (list (sub1 (expt -2 37)))) (test 5 max (list 5)) (test 5 min (list 5)) (test 38 max (list 34 5 7 38 6)) (test -24 min (list 3 5 5 330 4 -24)) (test 38.0 max (list 34 5.0 7 38 6)) (test -24.0 min (list 3 5 5 330 4 -24.0)) (test 2/3 max (list 1/2 2/3)) (test 2/3 max (list 2/3 1/2)) (test 2/3 max (list 2/3 -4/5)) (test 1/2 min (list 1/2 2/3)) (test 1/2 min (list 2/3 1/2)) (test -4/5 min (list 2/3 -4/5)) (test +inf.0 max (list +inf.0 0 -inf.0)) (test -inf.0 min (list +inf.0 0 -inf.0)) (test (expt 5 27) max (list 9 (expt 5 27))) (test (expt 5 29) max (list (expt 5 29) (expt 5 27))) (test (expt 5 29) max (list (expt 5 27) (expt 5 29))) (test (expt 5 27) max (list (expt 5 27) 9)) (test (expt 5 27) max (list (expt 5 27) (- (expt 5 29)))) (test (expt 5 27) max (list (- (expt 5 29)) (expt 5 27))) (test (- (expt 5 27)) max (list (- (expt 5 27)) (- (expt 5 29)))) (test (- (expt 5 27)) max (list (- (expt 5 29)) (- (expt 5 27)))) (test 9 min (list 9 (expt 5 27))) (test (expt 5 27) min (list (expt 5 29) (expt 5 27))) (test (expt 5 27) min (list (expt 5 27) (expt 5 29))) (test 9 min (list (expt 5 27) 9)) (test (- (expt 5 29)) min (list (expt 5 27) (- (expt 5 29)))) (test (- (expt 5 29)) min (list (- (expt 5 29)) (expt 5 27))) (test (- (expt 5 29)) min (list (- (expt 5 27)) (- (expt 5 29)))) (test (- (expt 5 29)) min (list (- (expt 5 29)) (- (expt 5 27)))) (test 0 + (list)) (test 7 + (list 3 4)) (test 6 + (list 1 2 3)) (test 7.0 + (list 3 4.0)) (test 6.0 + (list 1 2.0 3)) (test 19/12 + (list 1/4 1/3 1)) ;(test +i + (list +i)) ;(test 3/2+1i + (list 1 2+2i -i -3/2)) (test 3 + (list 3)) (test 0 + (list)) (test 4 * (list 4)) (test 16.0 * (list 4 4.0)) (test 1 * (list)) (test 6/25 * (list 3/5 1/5 2)) ;(test #i+6/25 * (list 3/5 1/5 2.0) ;(test +6/25i * (list 3/5 1/5 2 +i)) ;(test (make-rectangular 0 #i+6/25) * (list 3/5 1/5 2.0 +i)) ;(test 1073741874 + (list (- (expt 2 30) 50) 100)) ; fixnum -> bignum for 32 bits ;(test -1073741874 - (list (- 50 (expt 2 30)) 100)) ; fixnum -> bignum for 32 bits ;(test 10.0+0.0i + (list 9.0+0.0i 1)) ;(test 10.0+0.0i + (list 9.0+0.0i 1-0.0i)) ;(test 9.0+0.0i * (list 9.0+0.0i 1)) ;(test 10.0-1.0i + (list 9.0+0.0i 1-1.0i)) (test 0 * (list 0 10.0)) (test 0 * (list 0 +inf.0)) ;(test 0 * (list 0 +nan.0)) ;(test 0 / (list 0 0.0)) (test 0 / (list 0 +inf.0)) (test 0 / (list 0 -inf.0)) ;(test 0 / (list 0 +nan.0)) (test -0.0 + (list 0 -0.0)) (test -0.0 + (list -0.0 0)) (test -0.0 - (list -0.0 0)) (test -0.0 - (list 0.0)) (test 0.0 - (list -0.0)) (test -0.0 - (list 0 0.0)) (test 0.0 - (list 0 -0.0)) (test 2 add1 (list 1)) (test 0 add1 (list -1)) (test 2.0 add1 (list 1.0)) (test 0.0 add1 (list -1.0)) (test 3/2 add1 (list 1/2)) (test 1/2 add1 (list -1/2)) (test 1 sub1 (list 2)) (test -2 sub1 (list -1)) (test 1.0 sub1 (list 2.0)) (test -2.0 sub1 (list -1.0)) (test -1/2 sub1 (list 1/2)) (test -3/2 sub1 (list -1/2)) (test 1024 expt (list 2 10)) (test 1/1024 expt (list 2 -10)) (test 1/1024 expt (list 1/2 10)) (test (/ 1 (expt 2 10000)) expt (list 1/2 10000)) (test 2 expt (list 4 1/2)) (test 2.0 expt (list 4 0.5)) (test (sqrt 5) expt (list 5 1/2)) (test 31525197391593472 inexact->exact (list 31525197391593473.0)) (test 31525197391593476 inexact->exact (list 31525197391593476.0)) (test 31525197391593476 inexact->exact (list 31525197391593476.0)) (test #t positive? (list (inexact->exact 0.1))) (test #t negative? (list (inexact->exact -0.1))) (test 0 + (list (inexact->exact -0.1) (inexact->exact 0.1))) (define (test-inf-plus-times v) (local [(define (test+ +) (begin (test +inf.0 + (list v (+ +inf.0))) (test -inf.0 + (list v (+ -inf.0))) (test +inf.0 + (list (- v) (+ +inf.0))) (test -inf.0 + (list (- v) (+ -inf.0))) (test +inf.0 + (list +inf.0 v)) (test -inf.0 + (list -inf.0 v)) (test +inf.0 + (list +inf.0 (- v))) (test -inf.0 + (list -inf.0 (- v))) #;(test-nan.0 + +nan.0 v) #;(test-nan.0 + v +nan.0)))] (begin (test+ +) (test+ -) (test +inf.0 * (list +inf.0 v)) (test -inf.0 * (list -inf.0 v)) (test -inf.0 * (list +inf.0 (- v))) (test +inf.0 * (list -inf.0 (- v))) (test +inf.0 * (list v +inf.0)) (test -inf.0 * (list v -inf.0)) (test -inf.0 * (list (- v) +inf.0)) (test +inf.0 * (list (- v) -inf.0))))) ;(test-nan.0 * +nan.0 v) ;(test-nan.0 * v +nan.0) (test-inf-plus-times 1) (test-inf-plus-times 1.0) (test-inf-plus-times (expt 2 100)) (test -inf.0 - (list +inf.0)) (test +inf.0 - (list -inf.0)) (test +inf.0 + (list +inf.0 +inf.0)) (test -inf.0 + (list -inf.0 -inf.0)) (test +inf.0 * (list +inf.0 +inf.0)) (test -inf.0 * (list +inf.0 -inf.0)) (test 0 * (list +inf.0 0)) (test 1/2 / (list 1 2)) (test -1/3 / (list -1 3)) (test -1/3 / (list 1 -3)) (test 1/2 / (list 1/4 1/2)) (test 0.5 / (list 1 2.0)) (test 0.5 / (list 1.0 2)) ;(test 1/2+3/2i / 1+3i 2) ;(test 1/5-3/5i / 2 1+3i) ;(test 0.5+0.0i / 1+0.0i 2) ;(test 0.25-0.0i / 1 4+0.0i) ;(test 0.25+0.0i / 1+0.0i 4+0.0i) ;(test 0 / 0 4+3i) ;(test 0.25+0.0i / 1e300+1e300i (* 4 1e300+1e300i)) ;(test 0.25+0.0i / 1e-300+1e-300i (* 4 1e-300+1e-300i)) ;(test 1/2-1/2i / 1+1i) ;(test 1/2+1/2i / 1-1i) ;(test 1/5-2/5i / 1+2i) ;(test 1/5+2/5i / 1-2i) ;(test 2/5-1/5i / 2+1i) ;(test 2/5+1/5i / 2-1i) ;(test 0.5-0.5i / 1.0+1.0i) ;(test 0.5+0.5i / 1.0-1.0i) ;(test 0.2-0.4i / 1.0+2.0i) ;(test 0.2+0.4i / 1.0-2.0i) ;(test 0.4-0.2i / 2.0+1.0i) ;(test 0.4+0.2i / 2.0-1.0i) (test 3 / (list 1 1/3)) (test -3 / (list 1 -1/3)) (test -3 / (list -1 1/3)) (test 3 / (list -1 -1/3)) (test 1/3 / (list 1 3)) (test -1/3 / (list 1 -3)) (test -1/3 / (list -1 3)) (test 1/3 / (list -1 -3)) (test 3/2 / (list 1 2/3)) (test -3/2 / (list 1 -2/3)) (test -3/2 / (list -1 2/3)) (test 3/2 / (list -1 -2/3)) (test (expt 3 50) / (list 1 (/ 1 (expt 3 50)))) (test (- (expt 3 50)) / (list 1 (- (/ 1 (expt 3 50))))) (test (- (expt 3 50)) / (list -1 (/ 1 (expt 3 50)))) (test (expt 3 50) / (list -1 (- (/ 1 (expt 3 50))))) (test (/ 1 (expt 3 50)) / (list 1 (expt 3 50))) (test (- (/ 1 (expt 3 50))) / (list 1 (- (expt 3 50)))) (test (- (/ 1 (expt 3 50))) / (list -1 (expt 3 50))) (test (/ 1 (expt 3 50)) / (list -1 (- (expt 3 50)))) (test (/ (expt 3 50) (expt 2 70)) / (list 1 (/ (expt 2 70) (expt 3 50)))) (test (- (/ (expt 3 50) (expt 2 70))) / (list 1 (- (/ (expt 2 70) (expt 3 50))))) (test (- (/ (expt 3 50) (expt 2 70))) / (list -1 (/ (expt 2 70) (expt 3 50)))) (test (/ (expt 3 50) (expt 2 70)) / (list -1 (/ (- (expt 2 70)) (expt 3 50)))) (test (- (expt 2 30)) / (list (- (expt 2 30)) 1)) (test (expt 2 30) / (list (- (expt 2 30)) -1)) (test (expt 2 29) / (list (- (expt 2 30)) -2)) (test -1/1073741824 / (list (- (expt 2 30)))) (skip (lambda () (test +inf.0 / (list 1.0 0.0)))) (skip (lambda () (test -inf.0 / (list -1.0 0.0)))) (skip (lambda () (test +inf.0 / (list -1.0 -0.0)))) (skip (lambda () (test -inf.0 / (list 1.0 -0.0)))) (skip (lambda () (test 0.0 identity (list (exact->inexact (/ (expt 2 5000) (add1 (expt 2 5000000)))))))) (skip (lambda () (test -0.0 identity (list (exact->inexact (/ (- (expt 2 5000)) (add1 (expt 2 5000000)))))))) (skip (lambda () (test #t positive? (list (exact->inexact (* 5 (expt 10 -324))))))) (skip (lambda () (test #t negative? (list (exact->inexact (* -5 (expt 10 -324))))))) (test #t zero? (list (exact->inexact (* 5 (expt 10 -325))))) (skip (lambda () (test #t positive? (list (exact->inexact (* 45 (expt 10 -325))))))) (test -1 - (list 3 4)) (test -3 - (list 3)) (test -1.0 - (list 3.0 4)) (test -3.0 - (list 3.0)) (test 7 abs (list -7)) (test (expt 7 100) abs (list (- (expt 7 100)))) (test (expt 7 100) abs (list (expt 7 100))) (test 7.0 abs (list -7.0)) (test 7 abs (list 7)) (test 0 abs (list 0)) (test 1/2 abs (list 1/2)) (test 1/2 abs (list -1/2)) (test +inf.0 abs (list +inf.0)) (test +inf.0 abs (list -inf.0)) (test 1073741823 abs (list -1073741823)) (test 1073741823 abs (list 1073741823)) (test 1073741824 abs (list -1073741824)) (test 1073741824 abs (list 1073741824)) (test 1073741825 abs (list -1073741825)) (test 1073741825 abs (list 1073741825)) (test 5 quotient (list 35 7)) (test 5.0 quotient (list 35 7.0)) (test 5.0 quotient (list 36 7.0)) (test 5.0 quotient (list 36.0 7)) (test -5 quotient (list -35 7)) (test -5.0 quotient (list -35 7.0)) (test -5 quotient (list 35 -7)) (test -5.0 quotient (list 35 -7.0)) (test 5 quotient (list -35 -7)) (test 5.0 quotient (list -35 -7.0)) (test -5.0 quotient (list -36 7.0)) (test -5.0 quotient (list 36.0 -7)) (test 0 quotient (list 0 5.0)) (test 0 quotient (list 0 -5.0)) (test 1 modulo (list 13 4)) (test 1 remainder (list 13 4)) (test 1.0 modulo (list 13 4.0)) (test 1.0 remainder (list 13 4.0)) (test 3 modulo (list -13 4)) (test -1 remainder (list -13 4)) (test 3.0 modulo (list -13 4.0)) (test -1.0 remainder (list -13 4.0)) (test -3 modulo (list 13 -4)) (test 1 remainder (list 13 -4)) (test -3.0 modulo (list 13.0 -4)) (test 1.0 remainder (list 13.0 -4)) (test -1 modulo (list -13 -4)) (test -1 remainder (list -13 -4)) (test -1.0 modulo (list -13 -4.0)) (test -1.0 remainder (list -13 -4.0)) (test -2 remainder (list -3333333332 -3)) (test -2 modulo (list -3333333332 -3)) (test 2 remainder (list 3333333332 -3)) (test -1 modulo (list 3333333332 -3)) (test 0 modulo (list 4 2)) (test 0 modulo (list -4 2)) (test 0 modulo (list 4 -2)) (test 0 modulo (list -4 -2)) (test 0.0 modulo (list 4.0 2)) (test 0.0 modulo (list -4.0 2)) (test 0.0 modulo (list 4.0 -2)) (test 0.0 modulo (list -4.0 -2)) (test 0 remainder (list 4 2)) (test 0 remainder (list -4 2)) (test 0 remainder (list 4 -2)) (test 0 remainder (list -4 -2)) (test 0.0 remainder (list 4.0 2)) (test 0.0 remainder (list -4.0 2)) (test 0.0 remainder (list 4.0 -2)) (test 0.0 remainder (list -4.0 -2)) (test 0 modulo (list 0 5.0)) (test 0 modulo (list 0 -5.0)) (test 0 remainder (list 0 5.0)) (test 0 remainder (list 0 -5.0)) (define (divtest n1 n2) (= n1 (+ (* n2 (quotient n1 n2)) (remainder n1 n2)))) (test #t divtest (list 238 9)) (test #t divtest (list -238 9)) (test #t divtest (list 238 -9)) (test #t divtest (list -238 -9)) (test 13.0 quotient (list 1324.0 100)) ;; Check 0.0 combinations (test -0.0 quotient (list -0.0 2.0)) (test 0.0 quotient (list -0.0 -2.0)) (test 0.0 quotient (list 0.0 2.0)) (test -0.0 quotient (list 0.0 -2.0)) (test 0.0 modulo (list -0.0 2.0)) (test 0.0 modulo (list -0.0 -2.0)) (test 0.0 modulo (list 0.0 2.0)) (test 0.0 modulo (list 0.0 -2.0)) (test 0.0 remainder (list -0.0 2.0)) (test 0.0 remainder (list -0.0 -2.0)) (test 0.0 remainder (list 0.0 2.0)) (test 0.0 remainder (list 0.0 -2.0)) (test 4 gcd (list 0 4)) (test 4 gcd (list -4 0)) #;(test 4 gcd (list 4)) #;(test 4 gcd (list -4)) (test 4 gcd (list 32 -36)) (test 2 gcd (list 6 10 14)) #;(test 0 gcd (list)) (test 5 gcd (list 5)) (test 5.0 gcd (list 5.0 10)) (test 5.0 gcd (list -5.0 10)) (test 5.0 gcd (list 5.0 -10)) (test 5.0 gcd (list 5.0)) (test 5.0 gcd (list -5.0)) (test 3 gcd (list 0 0 3 0)) (test 3.0 gcd (list 0.0 0 3 0)) (test 0 gcd (list 0 0 0)) (test (expt 3 37) gcd (list (expt 9 35) (expt 6 37))) (test (expt 3 37) gcd (list (- (expt 9 35)) (expt 6 37))) (test (expt 3 37) gcd (list (expt 9 35) (- (expt 6 37)))) (test (expt 3 75) gcd (list (expt 3 75))) (test (expt 3 75) gcd (list (- (expt 3 75)))) (test 201 gcd (list (* 67 (expt 3 20)) (* 67 3))) (test 201 gcd (list (* 67 3) (* 67 (expt 3 20)))) (test 6 gcd (list (* 3 (expt 2 100)) 66)) (test 6 gcd (list 66 (* 3 (expt 2 100)))) (test 201.0 gcd (list (* 67 (expt 3 20)) (* 67. 3))) (test 201.0 gcd (list (* 67. 3) (* 67 (expt 3 20)))) (test (expt 9 35) gcd (list (expt 9 35) 0)) (test (expt 9 35) gcd (list 0 (expt 9 35))) (test 288 lcm (list 32 -36)) (test 12 lcm (list 2 3 4)) #;(test 1 lcm (list)) (test 5 lcm (list 5)) (test 5 lcm (list -5)) (test 0 lcm (list 123 0)) (test 0 lcm (list 0 0)) (test 0.0 lcm (list 0 0.0)) (test 0.0 lcm (list 0.0 0)) (test 30.0 lcm (list 5 6.0)) (test 6.0 lcm (list 6.0)) (test 6.0 lcm (list -6.0)) (test 0.0 lcm (list 123 0.0)) (test 0.0 lcm (list 123 -0.0)) (test (* (expt 2 37) (expt 9 35)) lcm (list (expt 9 35) (expt 6 37))) (test (* (expt 2 37) (expt 9 35)) lcm (list (- (expt 9 35)) (expt 6 37))) (test (* (expt 2 37) (expt 9 35)) lcm (list (expt 9 35) (- (expt 6 37)))) (test 2 floor (list 5/2)) (test 3 ceiling (list 5/2)) (test 2 round (list 5/2)) #;(test 2 truncate (list 5/2)) (test -3 floor (list -5/2)) (test -2 ceiling (list -5/2)) (test -2 round (list -5/2)) #;(test -2 truncate (list -5/2)) (test 1 floor (list 4/3)) (test 2 ceiling (list 4/3)) (test 1 round (list 4/3)) #;(test 1 truncate (list 4/3)) (test -2 floor (list -4/3)) (test -1 ceiling (list -4/3)) (test -1 round (list -4/3)) #;(test -1 truncate (list -4/3)) (test 1 floor (list 5/3)) (test 2 ceiling (list 5/3)) (test 2 round (list 5/3)) #;(test 1 truncate (list 5/3)) (test -2 floor (list -5/3)) (test -1 ceiling (list -5/3)) (test -2 round (list -5/3)) #;(test -1 truncate (list -5/3)) (test 2 floor (list 11/4)) (test 3 ceiling (list 11/4)) (test 3 round (list 11/4)) #;(test 2 truncate (list 11/4)) (test -3 floor (list -11/4)) (test -2 ceiling (list -11/4)) (test -3 round (list -11/4)) #;(test -2 truncate (list -11/4)) (test 2 floor (list 9/4)) (test 3 ceiling (list 9/4)) (test 2 round (list 9/4)) #;(test 2 truncate (list 9/4)) (test -3 floor (list -9/4)) (test -2 ceiling (list -9/4)) (test -2 round (list -9/4)) #;(test -2 truncate (list -9/4)) (test 2.0 floor (list 2.4)) (test 3.0 ceiling (list 2.4)) (test 2.0 round (list 2.4)) #;(test 2.0 truncate (list 2.4)) (test -3.0 floor (list -2.4)) (test -2.0 ceiling (list -2.4)) (test -2.0 round (list -2.4)) #;(test -2.0 truncate (list -2.4)) (test 2.0 floor (list 2.6)) (test 3.0 ceiling (list 2.6)) (test 3.0 round (list 2.6)) #;(test 2.0 truncate (list 2.6)) (test -3.0 floor (list -2.6)) (test -2.0 ceiling (list -2.6)) (test -3.0 round (list -2.6)) #;(test -2.0 truncate (list -2.6)) (test 2.0 round (list 2.5)) (test -2.0 round (list -2.5)) (test 4.0 round (list 3.5)) (test -4.0 round (list -3.5)) (define (test-zero-ident f) (begin (test 0.0 f (list 0.0)) (test -0.0 f (list -0.0)))) (test-zero-ident round) (test-zero-ident floor) (test-zero-ident ceiling) #;(test-zero-ident truncate) (test +inf.0 floor (list +inf.0)) (test +inf.0 ceiling (list +inf.0)) (test +inf.0 round (list +inf.0)) #;(test +inf.0 truncate (list +inf.0)) (test -inf.0 floor (list -inf.0)) (test -inf.0 ceiling (list -inf.0)) (test -inf.0 round (list -inf.0)) #;(test -inf.0 truncate (list -inf.0)) #;(test +nan.0 floor +nan.0) #;(test +nan.0 ceiling +nan.0) #;(test +nan.0 round +nan.0) #;(test +nan.0 truncate +nan.0) (define (test-fcrt-int v) (begin (test v floor (list v)) (test v ceiling (list v)) (test v round (list v)) #;(test v truncate (list v)))) (test-fcrt-int 2) (test-fcrt-int 2.0) (test-fcrt-int (expt 2 100)) (test 5 numerator (list 5)) (test 5000000000000 numerator (list 5000000000000)) (test 5.0 numerator (list 5.0)) (test 1 denominator (list 5)) (test 1 denominator (list 5000000000000)) (test 1.0 denominator (list 5.0)) (test 2 numerator (list 2/3)) (test 3 denominator (list 2/3)) (test 1000.0 round (list (* 10000.0 (/ (numerator 0.1) (denominator 0.1))))) (define (test-on-reals f filter) (begin (test (filter 5) f (list 5)) (test (filter 5.0) f (list 5.0)) (test (filter 1/5) f (list 1/5)) (test (filter (expt 2 100)) f (list (expt 2 100))))) (test 1+2i make-rectangular (list 1 2)) (test 1.0+2.0i make-rectangular (list 1.0 2)) #;(test-nan.0 real-part (make-rectangular +nan.0 1)) #;(test 1.0 imag-part (list (make-rectangular +nan.0 1))) #;(test-nan.0 imag-part (make-rectangular 1 +nan.0)) #;(test 1.0 real-part (make-rectangular 1 +nan.0)) (test +inf.0 real-part (list (make-rectangular +inf.0 -inf.0))) (test -inf.0 imag-part (list (make-rectangular +inf.0 -inf.0))) (test (make-rectangular +inf.0 -inf.0) * (list 1. (make-rectangular +inf.0 -inf.0))) (test (make-rectangular +inf.0 +inf.0) * (list +1.0i (make-rectangular +inf.0 -inf.0))) (test (make-rectangular -inf.0 +inf.0) * (list -3. (make-rectangular +inf.0 -inf.0))) (test (make-rectangular +inf.0 -inf.0) * (list (make-rectangular +inf.0 -inf.0) 1.)) (test (make-rectangular +inf.0 +inf.0) * (list (make-rectangular +inf.0 -inf.0) +1.0i)) (test (make-rectangular -inf.0 +inf.0) * (list (make-rectangular +inf.0 -inf.0) -3.)) (test (make-rectangular +inf.0 -inf.0) / (list (make-rectangular +inf.0 -inf.0) 1.)) (test (make-rectangular -inf.0 -inf.0) / (list (make-rectangular +inf.0 -inf.0) +1.0i)) (test (make-rectangular -inf.0 +inf.0) / (list (make-rectangular +inf.0 -inf.0) -3.)) ;; Test division with exact zeros in demoniator where ;; the exact zero gets polluted to an inexact zero unless ;; it's special-cased (test 0-0.0i / (list 0+1.0i -inf.0)) (test -0.0-0.0i / (list 1.0+1.0i -inf.0)) (test -0.0 / (list 0+1.0i 0-inf.0i)) (test -0.0+0.0i / (list 1.0+1.0i 0-inf.0i)) #;(test-i-nan.0 * 1.+0.i (make-rectangular +inf.0 -inf.0)) #;(test-i-nan.0 * 0.+1.0i (make-rectangular +inf.0 -inf.0)) #;(test-i-nan.0 * -3.+0.i (make-rectangular +inf.0 -inf.0)) #;(test-i-nan.0 * (make-rectangular +inf.0 -inf.0) 1.+0.i) #;(test-i-nan.0 * (make-rectangular +inf.0 -inf.0) 0.+1.0i) #;(test-i-nan.0 * (make-rectangular +inf.0 -inf.0) -3.+0.i) #;(test-i-nan.0 / (make-rectangular +inf.0 -inf.0) 1.+0.i) #;(test-i-nan.0 / (make-rectangular +inf.0 -inf.0) 0.+1.0i) #;(test-i-nan.0 / (make-rectangular +inf.0 -inf.0) -3.+0.i) (test 1 magnitude (list 1)) (test 1 magnitude (list -1)) (test 1.0 magnitude (list 1.0)) (test 1.0 magnitude (list -1.0)) #;(test big-num magnitude (list big-num)) #;(test big-num magnitude (list (- big-num))) (test 3/4 magnitude (list 3/4)) (test 3/4 magnitude (list -3/4)) (test 10.0 magnitude (list 10.0+0.0i)) (test 10.0 magnitude (list -10.0+0.0i)) (test 10.0 magnitude (list 0+10.0i)) (test 10 magnitude (list 0+10i)) #;(test 141421.0 round (list (* 1e-295 (magnitude 1e300+1e300i)))) #;(test 141421.0 round (list (* 1e+305 (magnitude 1e-300+1e-300i)))) #;(test +inf.0 magnitude (list +inf.0+inf.0i)) #;(test +inf.0 magnitude (list -inf.0-inf.0i)) #;(test +inf.0 magnitude (list 1+inf.0i)) #;(test +inf.0 magnitude (list +inf.0+1i)) #;(test +inf.0 magnitude (list +inf.0+0.0i)) #;(test +inf.0 magnitude (list 0.0+inf.0i)) #;(test +nan.0 magnitude (list +nan.0+inf.0i)) #;(test +nan.0 magnitude (list +inf.0+nan.0i)) (test 0 angle (list 1)) (test 0 angle (list 1.0)) (test 0 angle (list 0.0)) #;(test 0 angle (list big-num)) (test 0 angle (list 3/4)) (test 0.0 angle (list 3+0.0i)) (let ([pi (atan 0 -1)]) (begin (test pi angle (list -1)) (test pi angle (list -1.0)) (test pi angle (list -0.0)) #;(test pi angle (list (- big-num))) (test pi angle (list -3/4)) (test pi angle (list -3+0.0i)))) (test -inf.0 atan (list 0+i)) (test -inf.0 atan (list 0-i)) (test 1 real-part (list 1+2i)) (test 1.0 real-part (list 1+2.0i)) (test 1.0 real-part (list 1+0.0i)) (test 1/5 real-part (list 1/5+2i)) (test-on-reals real-part (lambda (x) x)) (test 2.0 imag-part (list 1+2.0i)) (test 0.0 imag-part (list 1+0.0i)) (test -0.0 imag-part (list 1-0.0i)) (test 1/5 imag-part (list 1+1/5i)) (test-on-reals imag-part (lambda (x) 0)) #;(test-nan.0 real-part +nan.0 (list)) #;(test 6@1 (lambda (x) x) [email protected]) #;(test 324.0 floor (* 100 (real-part 6@1))) #;(test 50488.0 floor (* 10000 (imag-part 6@1))) (test 1 make-polar (list 1 0)) (test 1.0+0.0i make-polar (list 1 0.0)) (test 1.0 make-polar (list 1.0 0)) (test 1.0+0.0i make-polar (list 1.0 0.0)) #;(err/rt-test (make-polar 1.0 0.0+0.0i)) #;(err/rt-test (make-polar 1.0+0.0i 0.0)) (let ([v (make-polar 1 1)]) (begin (test 5403.0 floor (list (* 10000 (real-part v)))) (test 84147.0 floor (list (* 100000 (imag-part v)))) (test 10000.0 round (list (* 10000.0 (magnitude v)))))) (let ([v (make-polar 1 2)]) (begin (test -416.0 ceiling (list (* 1000 (real-part v)))) (test 909.0 floor (list (* 1000 (imag-part v)))) (test 1.0 magnitude (list v)) (test 2.0 angle (list v)))) #;(test-nan.0 make-polar +nan.0 0) #;(test-i-nan.0 make-polar +nan.0 1) #;(test-i-nan.0 make-polar 1 +nan.0) #;(test-i-nan.0 make-polar 1 +inf.0) #;(test-i-nan.0 make-polar 1 -inf.0) (test +inf.0 make-polar (list +inf.0 0)) (test -inf.0 make-polar (list -inf.0 0)) (test (make-rectangular +inf.0 +inf.0) make-polar (list +inf.0 (atan 1 1))) (test (make-rectangular -inf.0 +inf.0) make-polar (list +inf.0 (atan 1 -1))) (test (make-rectangular +inf.0 -inf.0) make-polar (list +inf.0 (atan -1 1))) (test 785.0 floor (list (* 1000 (angle (make-rectangular 1 1))))) (test 14142.0 floor (list (* 10000 (magnitude (make-rectangular 1 1))))) (define (z-round c) (make-rectangular (round (real-part c)) (round (imag-part c)))) (test -1 * (list +i +i)) (test 1 * (list +i -i)) (test 2 * (list 1+i 1-i)) (test +2i * (list 1+i 1+i)) (test -3+4i - (list 3-4i)) (test 0.5+0.0i - (list (+ 0.5 +i) +i)) (test 1/2 - (list (+ 1/2 +i) +i)) (test 1.0+0.0i - (list (+ 1 +0.5i) +1/2i)) (test 1 sqrt (list 1)) (test 1.0 sqrt (list 1.0)) (test 25 sqrt (list 625)) (test 3/7 sqrt (list 9/49)) (test 0.5 sqrt (list 0.25)) (test +1i sqrt (list -1)) (test +2/3i sqrt (list -4/9)) (test +1.0i sqrt (list -1.0)) (test 1+1i sqrt (list +2i)) (test 2+1i sqrt (list 3+4i)) (test 2.0+0.0i sqrt (list 4+0.0i)) (test +inf.0 sqrt (list +inf.0)) (test (make-rectangular 0 +inf.0) sqrt (list -inf.0)) #;(test-nan.0 sqrt +nan.0 (list)) ;; Complex `sqrt' cases where both z and (magnitude z) are exact: (test 1414.0 round (list (* 1000 (real-part (sqrt +4i))))) (test +1414.0 round (list (* 1000 (imag-part (sqrt +4i))))) (test 1414.0 round (list (* 1000 (real-part (sqrt -4i))))) (test -1414.0 round (list (* 1000 (imag-part (sqrt -4i))))) (test 1155.0 round (list (* 1000 (real-part (sqrt 1+4/3i))))) (test +577.0 round (list (* 1000 (imag-part (sqrt 1+4/3i))))) (test 1155.0 round (list (* 1000 (real-part (sqrt 1-4/3i))))) (test -577.0 round (list (* 1000 (imag-part (sqrt 1-4/3i))))) (test (expt 5 13) sqrt (list (expt 5 26))) (test 545915034.0 round (list (sqrt (expt 5 25)))) (test (make-rectangular 0 (expt 5 13)) sqrt (list (- (expt 5 26)))) (test (make-rectangular 0 545915034.0) z-round (list (sqrt (- (expt 5 25))))) #;(err/rt-test (sqrt "a")) #;(arity-test sqrt 1 1) (test 3 integer-sqrt (list 10)) (test 420 integer-sqrt (list (expt 3 11))) (test 97184015999 integer-sqrt (list (expt 2 73))) (skip (lambda () (test 0+3i integer-sqrt (list -10)))) (skip (lambda () (test 0+420i integer-sqrt (list (expt -3 11))))) (skip (lambda () (test 0+97184015999i integer-sqrt (list (expt -2 73))))) #;(test 2.0 integer-sqrt (list 5.0)) #;(test 0+2.0i integer-sqrt (list -5.0)) #;(err/rt-test (integer-sqrt 5.0+0.0i)) #;(err/rt-test (integer-sqrt -5.0+0.0i)) #;(err/rt-test (integer-sqrt "a")) #;(err/rt-test (integer-sqrt 1.1)) #;(err/rt-test (integer-sqrt 1+1i)) #;(arity-test integer-sqrt 1 1) (test -13/64-21/16i expt (list -3/4+7/8i 2)) (let ([v (expt -3/4+7/8i 2+3i)]) (begin (printf "I see v as ~s~n" v) (test 3826.0 floor (list (* 10000000 (real-part v)))) (test -137.0 ceiling (list (* 100000 (imag-part v)))))) (test 49.0+0.0i expt (list 7 2+0.0i)) (test 49.0 floor (list (* 10 (expt 2 2.3)))) (test 189.0 floor (list (* 1000 (expt 2.3 -2)))) (test 1/4 expt (list 2 -2)) (test 1/1125899906842624 expt (list 2 -50)) (test 1/1024 expt (list 1/2 10)) (test 1024 expt (list 1/2 -10)) (test 707.0 floor (list (* 1000 (expt 1/2 1/2)))) (test 707.0 floor (list (* 1000 (expt 1/2 0.5)))) (test 707.0 floor (list (* 1000 (expt 0.5 1/2)))) (test 100.0+173.0i z-round (list (* 100 (expt -8 1/3)))) (test 100.0+173.0i z-round (list (* 100 (expt -8.0 1/3)))) (test 101.0+171.0i z-round (list (* 100 (expt -8 0.33)))) (test 101.0+171.0i z-round (list (* 100 (expt -8.0 0.33)))) (test 108.0+29.0i z-round (list (* 100 (expt 1+i 1/3)))) (test 25.0-43.0i z-round (list (* 100 (expt -8 -1/3)))) ;; This choice doesn't make sense to me, but it fits ;; with other standards and implementations: (define INF-POWER-OF_NEGATIVE +inf.0) (test +inf.0 expt (list 2 +inf.0)) (test +inf.0 expt (list +inf.0 10)) (test 0.0 expt (list +inf.0 -2)) (test 1 expt (list +inf.0 0)) (test 1.0 expt (list +inf.0 0.)) (test +inf.0 expt (list +inf.0 +inf.0)) (test INF-POWER-OF_NEGATIVE expt (list -2 +inf.0)) (test INF-POWER-OF_NEGATIVE expt (list -inf.0 +inf.0)) (test 0.0 expt (list 2 -inf.0)) (test -inf.0 expt (list -inf.0 11)) (test +inf.0 expt (list -inf.0 10)) (test 0.0 expt (list -inf.0 -2)) (test -0.0 expt (list -inf.0 -3)) (test 1 expt (list -inf.0 0)) (test 1.0 expt (list -inf.0 0.0)) (test 0.0 expt (list +inf.0 -inf.0)) (test 0.0 expt (list -2 -inf.0)) (test 0.0 expt (list -inf.0 -inf.0)) (test 1 expt (list +nan.0 0)) (test 0 expt (list 0 10)) (test 0 expt (list 0 10.0)) (test 0 expt (list 0 +inf.0)) #;(test-nan.0 expt 0 (list +nan.0)) (test 1 expt (list 1 +inf.0)) (test 1 expt (list 1 -inf.0)) (test 1 expt (list 1 -nan.0)) (test 0.0 expt (list 0.0 10)) (test 0.0 expt (list 0.0 +inf.0)) (test +inf.0 expt (list 0.0 -5)) (test -inf.0 expt (list -0.0 -5)) (test +inf.0 expt (list 0.0 -4)) (test +inf.0 expt (list -0.0 -4)) (test +inf.0 expt (list 0.0 -4.3)) (test +inf.0 expt (list -0.0 -4.3)) (test +inf.0 expt (list 0.0 -inf.0)) #;(test-nan.0 expt 0.0 (list +nan.0)) (test 1 expt (list 0 0)) (test 1.0 expt (list 0 0.0)) ; to match (expt 0 0) (test 1.0 expt (list 0 -0.0)) (test 1.0 expt (list 0.0 0.0)) (test 1.0 expt (list 0.0 0.0)) (test 1 expt (list 0.0 0)) (test 1 expt (list -0.0 0)) (test -0.0 expt (list -0.0 1)) #;(test-nan.0 expt +nan.0 (list 10)) #;(test-nan.0 expt 2 (list +nan.0)) (test 0 expt (list 0 1+i)) (test 0 expt (list 0 1-i)) #;(test-nan.0 expt 1.0 +inf.0) #;(test-nan.0 expt 1.0 -inf.0) #;(test-nan.0 expt 1.0 +nan.0) (test 0.0 expt (list 0.0 5)) (test -0.0 expt (list -0.0 5)) (test 0.0 expt (list 0.0 4)) (test 0.0 expt (list -0.0 4)) (test 0.0 expt (list 0.0 4.3)) (test 0.0 expt (list -0.0 4.3)) (test 0.0 expt (list 0.5 +inf.0)) (test +inf.0 expt (list 0.5 -inf.0)) (test INF-POWER-OF_NEGATIVE expt (list -0.5 -inf.0)) (test +inf.0 expt (list 1.5 +inf.0)) (test 0.0 expt (list 1.5 -inf.0)) (test 0.0 expt (list -0.5 +inf.0)) (test +inf.0 expt (list -0.5 -inf.0)) (test INF-POWER-OF_NEGATIVE expt (list -1.5 +inf.0)) (test 0.0 expt (list -1.5 -inf.0)) ;;;;From: [email protected] (Fred J Kaudel) ;;; Modified by jaffer. (define f3.9 (string->number "3.9")) (define f4.0 (string->number "4.0")) (define f-3.25 (string->number "-3.25")) (define f.25 (string->number ".25")) (define f4.5 (string->number "4.5")) (define f3.5 (string->number "3.5")) (define f0.0 (string->number "0.0")) (define f0.8 (string->number "0.8")) (define f1.0 (string->number "1.0")) #;(newline) #;(display ";testing inexact numbers; ") #;(newline) (test #t inexact? (list f3.9)) (test #f exact? (list f3.9)) (test #t 'inexact? (list (inexact? (max f3.9 4)))) (test f4.0 'max (list (max f3.9 4))) (test f4.0 'exact->inexact (list (exact->inexact 4))) ; Should at least be close... (test 4.0 round (list (log (exp 4.0)))) (test 125.0 round (list (* 1000 (asin (sin 0.125))))) (test 125.0d0 round (list (* 1000 (magnitude (asin (sin 0.125+0.0d0i)))))) (test 125.0 round (list (* 1000 (asin (sin 1/8))))) (test 125.0 round (list (* 1000 (acos (cos 0.125))))) (test 125.0d0-0.0i z-round (list (* 1000 (acos (cos 0.125+0.0d0i))))) (test 125.0 round (list (* 1000 (acos (cos 1/8))))) (test 785.0 round (list (* 1000 (atan 1 1)))) (test 785.0 round (list (* 1000 (atan 1.0 1.0)))) #;(err/rt-test (atan 1.0 1.0+0.0i)) #;(err/rt-test (atan 1.0+0.0i 1.0)) (test 2356.0 round (list (* 1000 (atan 1 -1)))) (test -785.0 round (list (* 1000 (atan -1 1)))) (test 785.0 round (list (* 1000 (atan 1)))) (test 100.0 round (list (* 100 (tan (atan 1))))) (test 100.0-0.0i z-round (list (* 100 (tan (+ +0.0i (atan 1)))))) (test 0.0 atan (list 0.0 0)) #;(err/rt-test (atan 0 0) exn:fail:contract:divide-by-zero?) (test 1024.0 round (list (expt 2.0 10.0))) (test 1024.0 round (list (expt -2.0 10.0))) (test -512.0 round (list (expt -2.0 9.0))) (test 32.0 round (list (sqrt 1024.0))) (test 32.0+0.0i z-round (list (sqrt 1024.0+0.0i))) (test 1.0+1.5e-10i sqrt (list 1+3e-10i)) (test 1 exp (list 0)) (test 1.0 exp (list 0.0)) (test 1.0 exp (list -0.0)) (test 272.0 round (list (* 100 (exp 1)))) (test 0 log (list 1)) (test 0.0 log (list 1.0)) (test -inf.0 log (list 0.0)) (test -inf.0 log (list -0.0)) (test +inf.0 log (list +inf.0)) (test +inf.0 real-part (list (log -inf.0))) (test +3142.0 round (list (* 1000 (imag-part (log -inf.0))))) (test +nan.0 log (list +nan.0)) #;(err/rt-test (log 0) exn:fail:contract:divide-by-zero?) (test 1 cos (list 0)) (test 1.0 cos (list 0.0)) (test 0 sin (list 0)) (test 0.0 sin (list 0.0)) (test -0.0 sin (list -0.0)) (test 0 tan (list 0)) (test 0.0 tan (list 0.0)) (test -0.0 tan (list -0.0)) (test #t >= (list 1 (sin 12345678901234567890123))) (test #t >= (list 1 (cos 12345678901234567890123))) (test #t <= (list -inf.0 (tan 12345678901234567890123) +inf.0)) (test 0 atan (list 0)) (test 0.0 atan (list 0.0)) (test -0.0 atan (list -0.0)) (test 314.0 round (list (* 400 (atan 1)))) (test 314.0 round (list (* 400 (atan 1.0)))) (test 0 asin (list 0)) (test 0.0 asin (list 0.0)) (test -0.0 asin (list -0.0)) (test 314.0 round (list (* 200 (asin 1)))) (test 314.0 round (list (* 200 (asin 1.0)))) (test 0 acos (list 1)) (test 0.0 acos (list 1.0)) (test 314.0 round (list (* 200 (acos 0)))) (test 314.0 round (list (* 200 (acos 0.0)))) (test 314.0 round (list (* 200 (acos -0.0)))) (test (/ 314.0 2) round (list (* 100 (atan +inf.0)))) (test (/ -314.0 2) round (list (* 100 (atan -inf.0)))) (skip (lambda () (test 71034.0 round (list (* 100 (log 312918491891666147403524564598095080760332972643192197862041633988540637438735086398143104076897116667450730097183397289314559387355872839339937813881411504027225774279272518360586167057501686099965513263132778526566297754301647311975918380842568054630540214544682491386730004162058539391336047825248736472519)))))) (test 71117.0 round (list (* 100 (log (expt 2 1026))))) (test 71048.0 round (list (* 100 (log (expt 2 1025))))) (test 70978.0 round (list (* 100 (log (expt 2 1024))))) (test 70909.0 round (list (* 100 (log (expt 2 1023))))) (test 35420.0 round (list (* 100 (log (expt 2 511))))) (test 35489.0 round (list (* 100 (log (expt 2 512))))) (test 35558.0 round (list (* 100 (log (expt 2 513))))) (test 141887.0 round (list (* 100 (log (expt 2 2047))))) (test 141957.0 round (list (* 100 (log (expt 2 2048))))) (test 142026.0 round (list (* 100 (log (expt 2 2049))))) (test 23026.0 round (list (log (expt 10 10000)))) (test 23026.0 round (list (real-part (log (- (expt 10 10000)))))) (test 3.0 round (list (imag-part (log (- (expt 10 10000)))))) (define (test-inf-bad f) (begin (test-nan.0 f (list +inf.0)) (test-nan.0 f (list -inf.0)) (test-nan.0 f (list +nan.0)))) (test-inf-bad tan) (test-inf-bad sin) (test-inf-bad cos) (test-inf-bad asin) (test-inf-bad acos) #;(test 11/7 rationalize (list (inexact->exact (atan +inf.0 1)) 1/100)) #;(skip (lambda () (test -11/7 rationalize (list (inexact->exact (atan -inf.0 1)) 1/100)))) (test 0.0 atan (list 1 +inf.0)) #;(skip (lambda () (test 22/7 rationalize (list (inexact->exact (atan 1 -inf.0)) 1/100)))) ; Note on the following tests with atan and inf.0: ; The IEEE standard makes this decision. I think it's a bad one, ; since (limit (atan (g x) (f x))) as x -> +inf.0 is not necessarily ; (atan 1 1) when (limit (f x)) and (limit (g x)) are +inf.0. ; Perhaps IEEE makes this choice because it's easiest to compute. #;(test 7/9 rationalize (list (inexact->exact (atan +inf.0 +inf.0)) 1/100)) #;(test 26/11 rationalize (list (inexact->exact (atan +inf.0 -inf.0)) 1/100)) #;(test -7/9 rationalize (list (inexact->exact (atan -inf.0 +inf.0)) 1/100)) (test-nan.0 atan (list +nan.0)) (test-nan.0 atan (list 1 +nan.0)) (test-nan.0 atan (list +nan.0 1)) (test -1178.+173.i z-round (list (* 1000 (atan -2+1i)))) #;(map (lambda (f) (err/rt-test (f "a")) (arity-test f 1 1)) (list log exp asin acos tan)) #;(err/rt-test (atan "a" 1)) #;(err/rt-test (atan 2+i 1)) #;(err/rt-test (atan "a")) #;(err/rt-test (atan 1 "a")) #;(err/rt-test (atan 1 2+i)) #;(arity-test atan 1 2) (test 3166.+1960.i z-round (list (* 1000 (sin 1+2i)))) (test -3166.-1960.i z-round (list (* 1000 (sin -1-2i)))) (test 0+1175.i z-round (list (* 1000 (sin 0+i)))) (test -642.-1069.i z-round (list (* 1000 (cos 2+i)))) (test -642.-1069.i z-round (list (* 1000 (cos -2-i)))) (test 1543. z-round (list (* 1000 (cos 0+i)))) (test 272-1084.i z-round (list (* 1000 (tan 1-i)))) (test -272+1084.i z-round (list (* 1000 (tan -1+i)))) (test 693.+3142.i z-round (list (* 1000 (log -2)))) (test 1571.-1317.i z-round (list (* 1000 (asin 2)))) (test -1571.+1317.i z-round (list (* 1000 (asin -2)))) (test 0+3688.i z-round (list (* 1000 (acos 20)))) (test 3142.-3688.i z-round (list (* 1000 (acos -20)))) (define (cs2 c) (+ (* (cos c) (cos c)) (* (sin c) (sin c)))) (test 0.0 imag-part (list (cs2 2+3i))) (test 1000.0 round (list (* 1000 (real-part (cs2 2+3i))))) (test 0.0 imag-part (list (cs2 -2+3i))) (test 1000.0 round (list (* 1000 (real-part (cs2 -2+3i))))) (test 0.0 imag-part (list (cs2 2-3i))) (test 1000.0 round (list (* 1000 (real-part (cs2 2-3i))))) (test #t positive? (list (real-part (sqrt (- 1 (* 2+3i 2+3i)))))) (test (- f4.0) round (list (- f4.5))) (test (- f4.0) round (list (- f3.5))) (test (- f4.0) round (list (- f3.9))) (test f0.0 round (list f0.0)) (test f0.0 round (list f.25)) (test f1.0 round (list f0.8)) (test f4.0 round (list f3.5)) (test f4.0 round (list f4.5)) (let ((x (string->number "4195835.0")) (y (string->number "3145727.0"))) (test #t 'pentium-fdiv-bug (list (> f1.0 (- x (* (/ x y) y)))))) #;(test (exact->inexact 1/3) rationalize (list .3 1/10)) #;(test 1/3 rationalize (list 3/10 1/10)) #;(test (exact->inexact 1/3) rationalize (list .3 -1/10)) #;(test 1/3 rationalize (list 3/10 -1/10)) #;(test 0 rationalize (list 3/10 4/10)) #;(test 0.0 rationalize (list .3 4/10)) #;(err/rt-test (rationalize .3+0.0i 4/10)) #;(err/rt-test (rationalize .3+0.0i 1/10)) #;(define (test-rat-inf v) (local [(define zero (if (exact? v) 0 0.0))] (test +inf.0 rationalize +inf.0 v) (test -inf.0 rationalize -inf.0 v) (test-nan.0 rationalize +nan.0 v) (test zero rationalize v +inf.0) (test zero rationalize v -inf.0) (test-nan.0 rationalize v +nan.0))) #;(let loop ([i 100]) (unless (= i -100) (test (/ i 100) rationalize (inexact->exact (/ i 100.0)) 1/100000) (loop (sub1 i)))) #;(arity-test rationalize 2 2) (define tb (lambda (n1 n2) (= n1 (+ (* n2 (quotient n1 n2)) (remainder n1 n2))))) (test -2147483648 - (list 2147483648)) (test 2147483648 - (list -2147483648)) (test #f = (list -2147483648 2147483648)) (test #t = (list -2147483648 -2147483648)) (test #t = (list 2147483648 2147483648)) (test 2147483647 sub1 (list 2147483648)) (test 2147483648 add1 (list 2147483647)) (test 2147483648 * (list 1 2147483648)) (test 437893890380859375 expt (list 15 15)) (test 0 modulo (list -2177452800 86400)) (test 0 modulo (list 2177452800 -86400)) (test 0 modulo (list 2177452800 86400)) (test 0 modulo (list -2177452800 -86400)) (test 86399 modulo (list -2177452801 86400)) (test -1 modulo (list 2177452799 -86400)) (test 1 modulo (list 2177452801 86400)) (test -86399 modulo (list -2177452799 -86400)) (test #t 'remainder (list (tb 281474976710655 65535))) (test #t 'remainder (list (tb 281474976710654 65535))) (test 281474976710655 string->number (list "281474976710655")) (test "281474976710655" number->string (list 281474976710655)) (skip (lambda () (test "-4" number->string (list -4 16)))) (skip (lambda () (test "-e" number->string (list -14 16)))) (skip (lambda () (test "0" number->string (list 0 16)))) ;;(test "30000000" number->string (list #x30000000 16)) (test "0" number->string (list 0)) (test "100" number->string (list 100)) (skip (lambda () (test "100" number->string (list 256 16)))) (skip (lambda () (test 256 string->number (list "100" 16)))) (skip (lambda () (test 15 string->number (list "#o17")))) (skip (lambda () (test 15 string->number (list "#o17" 10)))) (test #t = (list 0 0)) (test #f = (list 0 (expt 2 32))) (test #f = (list (expt 2 32) 0)) (test #f = (list (- (expt 2 32)) (expt 2 32))) (test #f = (list (expt 2 32) (- (expt 2 32)))) (test #t = (list 1234567890987654321 1234567890987654321)) (test #f < (list 0 0)) (test #t < (list 0 (expt 2 32))) (test #f < (list (expt 2 32) 0)) (test #t < (list (- (expt 2 32)) 0)) (test #f < (list 0 (- (expt 2 32)))) (test #f < (list 1234567890987654321 1234567890987654321)) (test #t < (list (- (expt 3 64)) (- (expt 2 13)))) (test #f < (list (- (expt 2 13)) (- (expt 3 64)))) (test #t < (list (- 123456789876543200) 123456789876543200)) (test #f < (list 123456789876543200 (- 123456789876543200))) (test 1234567890987654321 + (list 1234567890987654321 0)) (test 1234567890987654321 + (list 0 1234567890987654321)) (test 1234567890987654321 - (list 1234567890987654321 0)) (test -1234567890987654321 - (list 0 1234567890987654321)) (test (expt 2 33) + (list (expt 2 32) (expt 2 32))) (test 0 - (list (expt 2 32) (expt 2 32))) (test (expt 2 31) - (list (expt 2 32) (expt 2 31))) (test (- (expt 2 31)) - (list (expt 2 31) (expt 2 32))) (test 18446744073709551621 + (list 18446744073709551615 6)) (test 18446744073709551621 + (list 6 18446744073709551615)) ;(test 0 - (list #xfffffffffffffffff #xfffffffffffffffff)) ;(test -1 - (list #xffffffffffffffffe #xfffffffffffffffff)) ;(test 1 - (list #xfffffffffffffffff #xffffffffffffffffe)) ;(test #x1000000000000000000000000 + (list #xffffffffffffffffffffffff 1)) (test 0 * (list 1234567890987654321 0)) (test 0 * (list 0 1234567890987654321)) ;(test #x100000000000000000000 * #x100000000000 #x1000000000) ;(test #x-100000000000000000000 * #x100000000000 #x-1000000000) ;(test #x100000000000000000000 * #x-100000000000 #x-1000000000) ;(test #x-100000000000000000000 * #x-100000000000 #x1000000000) ;(test #x100000000000000000000 * #x1000000000 #x100000000000) ;(test #x-100000000000000000000 * #x1000000000 #x-100000000000) ;(test #x100000000000000000000 * #x-1000000000 #x-100000000000) ;(test #x-100000000000000000000 * #x-1000000000 #x100000000000) ;(test 4521191813415169 * #x100000000001 #x101) ;(test 4521191813415169 * #x101 #x100000000001) (test (expt 2 35) * (list (expt 2 32) 8)) (test (- (expt 2 35)) * (list (- (expt 2 32)) 8)) (test (- (expt 2 35)) * (list (expt 2 32) -8)) (test (expt 2 35) * (list (- (expt 2 32)) -8)) (test (- (add1 (expt 2 128)) (expt 2 65)) * (list (sub1 (expt 2 64)) (sub1 (expt 2 64)))) (test 4294967296 expt (list 2 32)) (test 3433683820292512484657849089281 expt (list 3 64)) (test 8192 expt (list 2 13)) (test 8589934592 expt (list 2 33)) (test 2147483648 expt (list 2 31)) (test 34359738368 expt (list 2 35)) (test 36893488147419103232 expt (list 2 65)) (test 18446744073709551616 expt (list 2 64)) (test 340282366920938463463374607431768211456 expt (list 2 128)) (test 340282366920938463463374607431768211456 expt (list -2 128)) (test 174449211009120179071170507 expt (list 3 55)) (test -174449211009120179071170507 expt (list -3 55)) (test 59768263894155949306790119265585619217025149412430681649 expt (list 7 66)) (test 1 expt (list 1234567890987654321 0)) (test 0 expt (list 0 1234567890987654321)) (test 1 expt (list 1 1234567890987654321)) (test 1234567890987654321 expt (list 1234567890987654321 1)) (test 828179745220145502584084235957368498016122811853894435464201864103254919330121223037770283296858019385573376 expt (list 953962166440690129601298432 4)) (test "0" number->string (list 0)) (test "1" number->string (list 1)) (test "-1" number->string (list -1)) (test "7284132478923046920834523467890234589203467590267382904573942345703" number->string (list 7284132478923046920834523467890234589203467590267382904573942345703)) (test "-7284132478923046920834523467890234589203467590267382904573942345703" number->string (list -7284132478923046920834523467890234589203467590267382904573942345703)) ;(test "1000101001010101011111011000101001011011100111110001111111010101000100010110001001011011101111011001111101000100110100010101111001111001001011111001000100111000011111110010101010110110001011011111101110000001010111111100111" number->string 7284132478923046920834523467890234589203467590267382904573942345703 2) ;(test "-1000101001010101011111011000101001011011100111110001111111010101000100010110001001011011101111011001111101000100110100010101111001111001001011111001000100111000011111110010101010110110001011011111101110000001010111111100111" number->string -7284132478923046920834523467890234589203467590267382904573942345703 2) ;(test "105125373051334761772504261133573175046425717113710470376252661337560127747" number->string 7284132478923046920834523467890234589203467590267382904573942345703 8) ;(test "-105125373051334761772504261133573175046425717113710470376252661337560127747" number->string -7284132478923046920834523467890234589203467590267382904573942345703 8) ;(test "452abec52dcf8fea88b12ddecfa268af3c97c89c3f955b16fdc0afe7" number->string 7284132478923046920834523467890234589203467590267382904573942345703 16) ;(test "-452abec52dcf8fea88b12ddecfa268af3c97c89c3f955b16fdc0afe7" number->string -7284132478923046920834523467890234589203467590267382904573942345703 16) ;(test "115792089237316195423570985008687907853269984665640564039457584007913129639936" number->string (expt 2 256)) ;(test "115792089237316195423570985008687907853269984665640564039457584007913129639935" number->string (sub1 (expt 2 256))) ;(test "10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" number->string (expt 2 256) 2) ;(test "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111" number->string (sub1 (expt 2 256)) 2) ;(test "20000000000000000000000000000000000000000000000000000000000000000000000000000000000000" number->string (expt 2 256) 8) ;(test "17777777777777777777777777777777777777777777777777777777777777777777777777777777777777" number->string (sub1 (expt 2 256)) 8) ;(test "10000000000000000000000000000000000000000000000000000000000000000" number->string (expt 2 256) 16) ;(test "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" number->string (sub1 (expt 2 256)) 16) ;(test "-115792089237316195423570985008687907853269984665640564039457584007913129639936" number->string (- (expt 2 256))) ;(test "-115792089237316195423570985008687907853269984665640564039457584007913129639935" number->string (- (sub1 (expt 2 256)))) ;(test "-10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" number->string (- (expt 2 256)) 2) ;(test "-1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111" number->string (- (sub1 (expt 2 256))) 2) ;(test "-20000000000000000000000000000000000000000000000000000000000000000000000000000000000000" number->string (- (expt 2 256)) 8) ;(test "-17777777777777777777777777777777777777777777777777777777777777777777777777777777777777" number->string (- (sub1 (expt 2 256))) 8) ;(test "-10000000000000000000000000000000000000000000000000000000000000000" number->string (- (expt 2 256)) 16) ;(test "-ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" number->string (- (sub1 (expt 2 256))) 16) (test 0 string->number (list "0")) (test 1 string->number (list "1")) (test -1 string->number (list "-1")) (test 7284132478923046920834523467890234589203467590267382904573942345703 string->number (list "7284132478923046920834523467890234589203467590267382904573942345703")) (test -7284132478923046920834523467890234589203467590267382904573942345703 string->number (list "-7284132478923046920834523467890234589203467590267382904573942345703")) ;(test 7284132478923046920834523467890234589203467590267382904573942345703 string->number "1000101001010101011111011000101001011011100111110001111111010101000100010110001001011011101111011001111101000100110100010101111001111001001011111001000100111000011111110010101010110110001011011111101110000001010111111100111" 2) ;(test -7284132478923046920834523467890234589203467590267382904573942345703 string->number "-1000101001010101011111011000101001011011100111110001111111010101000100010110001001011011101111011001111101000100110100010101111001111001001011111001000100111000011111110010101010110110001011011111101110000001010111111100111" 2) ;(test 7284132478923046920834523467890234589203467590267382904573942345703 string->number "105125373051334761772504261133573175046425717113710470376252661337560127747" 8) ;(test -7284132478923046920834523467890234589203467590267382904573942345703 string->number "-105125373051334761772504261133573175046425717113710470376252661337560127747" 8) ;(test 7284132478923046920834523467890234589203467590267382904573942345703 string->number "452abec52dcf8fea88b12ddecfa268af3c97c89c3f955b16fdc0afe7" 16) ;(test -7284132478923046920834523467890234589203467590267382904573942345703 string->number "-452abec52dcf8fea88b12ddecfa268af3c97c89c3f955b16fdc0afe7" 16) ;(test (expt 2 256) string->number "115792089237316195423570985008687907853269984665640564039457584007913129639936") ;(test (sub1 (expt 2 256)) string->number "115792089237316195423570985008687907853269984665640564039457584007913129639935") ;(test (expt 2 256) string->number "10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" 2) ;(test (sub1 (expt 2 256)) string->number "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111" 2) ;(test (expt 2 256) string->number "20000000000000000000000000000000000000000000000000000000000000000000000000000000000000" 8) ;(test (sub1 (expt 2 256)) string->number "17777777777777777777777777777777777777777777777777777777777777777777777777777777777777" 8) ;(test (expt 2 256) string->number "10000000000000000000000000000000000000000000000000000000000000000" 16) ;(test (sub1 (expt 2 256)) string->number "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" 16) ;(test (- (expt 2 256)) string->number "-115792089237316195423570985008687907853269984665640564039457584007913129639936") ;(test (- (sub1 (expt 2 256))) string->number "-115792089237316195423570985008687907853269984665640564039457584007913129639935") ;(test (- (expt 2 256)) string->number "-10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" 2) ;(test (- (sub1 (expt 2 256))) string->number "-1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111" 2) ;(test (- (expt 2 256)) string->number "-20000000000000000000000000000000000000000000000000000000000000000000000000000000000000" 8) ;(test (- (sub1 (expt 2 256))) string->number "-17777777777777777777777777777777777777777777777777777777777777777777777777777777777777" 8) ;(test (- (expt 2 256)) string->number "-10000000000000000000000000000000000000000000000000000000000000000" 16) ;(test (- (sub1 (expt 2 256))) string->number "-ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" 16) ;(test #f string->number "144r" 10) ;(err/rt-test (string->number "10" 30)) (define (q-test quotient) (begin (test 0 quotient (list 0 12345678909876532341)) (test 0 quotient (list 0 -1235782934075829307)) (test 2374865902374859023745 quotient (list 2374865902374859023745 1)) (test -2374865902374859023745 quotient (list -2374865902374859023745 1)) (test 0 quotient (list 1 13748910785903278450)) (test 1 quotient (list 13748910785903278450 13748910785903278449)) (test 0 quotient (list 13748910785903278450 13748910785903278451)) (test -1 quotient (list -13748910785903278450 13748910785903278449)) (test 0 quotient (list -13748910785903278450 13748910785903278451)) (test -1 quotient (list 13748910785903278450 -13748910785903278449)) (test 0 quotient (list 13748910785903278450 -13748910785903278451)) (test 1 quotient (list -13748910785903278450 -13748910785903278449)) (test 0 quotient (list -13748910785903278450 -13748910785903278451)) (test 1 quotient (list 13748910785903278450 13748910785903278450)) (test -1 quotient (list -13748910785903278450 13748910785903278450)) (test -1 quotient (list 13748910785903278450 -13748910785903278450)) (test 1 quotient (list -13748910785903278450 -13748910785903278450)) (test (expt 5 64) quotient (list (expt 5 256) (expt 5 192))) (test 0 quotient (list (expt 5 192) (expt 5 256))) (test 8636168555094444625386351862800399571116000364436281385023703470168591803162427057971507503472288226560547293946149 quotient (list (expt 5 192) (expt 2 64))))) (q-test quotient) #;(q-test (lambda (n1 n2) (let-values ([(q r) (quotient/remainder n1 n2)]) q))) (define (r-test remainder) (begin (test 0 remainder (list 0 12345678909876532341)) (test 0 remainder (list 0 -1235782934075829307)) (test 0 remainder (list 2374865902374859023745 1)) (test 0 remainder (list -2374865902374859023745 1)) (test 1 remainder (list 1 13748910785903278450)) (test 1 remainder (list 13748910785903278450 13748910785903278449)) (test 13748910785903278450 remainder (list 13748910785903278450 13748910785903278451)) (test -1 remainder (list -13748910785903278450 13748910785903278449)) (test -13748910785903278450 remainder (list -13748910785903278450 13748910785903278451)) (test 1 remainder (list 13748910785903278450 -13748910785903278449)) (test 13748910785903278450 remainder (list 13748910785903278450 -13748910785903278451)) (test -1 remainder (list -13748910785903278450 -13748910785903278449)) (test -13748910785903278450 remainder (list -13748910785903278450 -13748910785903278451)) (test 0 remainder (list 13748910785903278450 13748910785903278450)) (test 0 remainder (list -13748910785903278450 13748910785903278450)) (test 0 remainder (list 13748910785903278450 -13748910785903278450)) (test 0 remainder (list -13748910785903278450 -13748910785903278450)) (test 0 remainder (list (expt 5 256) (expt 5 192))) (test (expt 5 192) remainder (list (expt 5 192) (expt 5 256))) (test 12241203936672963841 remainder (list (expt 5 192) (expt 2 64))))) (r-test remainder) ;(r-test (lambda (n1 n2) (let-values ([(q r) (quotient/remainder n1 n2)]) r))) (define (s-test sqrt) (begin (test 0 sqrt (list 0)) (test 1 sqrt (list 1)) (test 2 sqrt (list 4)) (test 3 sqrt (list 9)) (test (expt 2 64) sqrt (list (* (expt 2 64) (expt 2 64)))) (test (expt 13 70) sqrt (list (* (expt 13 70) (expt 13 70)))) (test (sub1 (expt 2 200)) sqrt (list (* (sub1 (expt 2 200)) (sub1 (expt 2 200))))) (test (expt 2 25) sqrt (list (expt 2 50))) (test 1 sqrt (list 3)) (test #xffffffff sqrt (list (sub1 (expt 2 64)))) (test 2876265888493261300027370452880859375 sqrt (list (expt 15 62))) (test #x8f0767e50d4d0c07563bd81f530d36 sqrt (list (expt 15 61))))) (s-test integer-sqrt) ;(s-test (lambda (a) (let-values ([(root rem) (integer-sqrt/remainder a)]) root))) (define (sr-test sqrt) (begin (test 0 sqrt (list 0)) (test 0 sqrt (list 1)) (test 0 sqrt (list 4)) (test 0 sqrt (list 9)) (test 0 sqrt (list (* (expt 2 64) (expt 2 64)))) (test 0 sqrt (list (* (expt 13 70) (expt 13 70)))) (test 0 sqrt (list (* (sub1 (expt 2 200)) (sub1 (expt 2 200))))) (test 0 sqrt (list (expt 2 50))) (test 2 sqrt (list 3)) (test 8589934590 sqrt (list (sub1 (expt 2 64)))) (test 0 sqrt (list (expt 15 62))) (test 1306106749204831357295958563982718571 sqrt (list (expt 15 61))))) ;(sr-test (lambda (a) (let-values ([(root rem) (integer-sqrt/remainder a)]) rem))) (test 1.7320508075688772 sqrt (list 3)) (test 4294967296.0 sqrt (list (sub1 (expt 2 64)))) (test 2876265888493261300027370452880859375 sqrt (list (expt 15 62))) (test 7.426486590265921e+35 sqrt (list (expt 15 61))) (test 5.515270307539953e+71 exact->inexact (list (expt 15 61))) (test -5.515270307539953e+71 exact->inexact (list (- (expt 15 61)))) (test 1.8446744073709552e+19 exact->inexact (list (expt 2 64))) (test 1.157920892373162e+77 exact->inexact (list (expt 2 256))) (test 1.157920892373162e+77 exact->inexact (list (sub1 (expt 2 256)))) (test 551527030753995340375346347667240734743269800540264151034260072897183744 inexact->exact (list 5.515270307539953d+71)) (test (expt 2 64) inexact->exact (list 1.8446744073709552e+19)) (test (- (expt 2 64)) inexact->exact (list -1.8446744073709552e+19)) (test (expt 2 256) inexact->exact (list 1.157920892373162d+77)) (test 115792089237316195423570985008687907853269984665640564039457584007913129639936 inexact->exact (list 1.157920892373162d+77)) ;(test (integer-bytes->integer #"\1\2" #f) integer-bytes->integer #"\1\2" #f (system-big-endian?)) (js-big-bang #f (on-draw (lambda (w) `(,(js-div) ,(list (js-text (format "~a tests run. ~a tests broke. ~a tests skipped." number-of-tests number-of-errors number-of-skipped-tests))) ,@(map (lambda (msg) (list (js-div) (list (js-text (format "~a" msg))))) error-messages))) (lambda (w) '())))
false
13452229e75779b3ee544b26cf23beec44ac37cc
f6c954bac9db8e566fdd24249a4970dd759455eb
/PT-1300012785-1.33.scm
554c929374b3f09447a4532c02b5968eae028861
[]
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
1,527
scm
PT-1300012785-1.33.scm
(define (filtered-accumulate combiner null-value filter term a next b) (define (iter result a) (let ((value (term a))) (cond ((> a b) result) ((filter value) (iter (combiner result value) (next a))) (else (iter result (next a)))))) (iter null-value a)) ; sum from 1 to 100 (filtered-accumulate + 0 (lambda (x) #t) (lambda (x) x) 1 (lambda (x) (+ x 1)) 100) (define (sum-primes-between a b) (filtered-accumulate + 0 (lambda (x) (miller-rabin x 20)) (lambda (x) x) a (lambda (x) (+ x 1)) b)) (define (product-relative-prime n) (filtered-accumulate * 1 (lambda (x) (= (gcd x n) 1)) (lambda (x) x) 1 (lambda (x) (+ x 1)) (- n 1))) ;greatest-common-divisor function (define (gcd a b) (if (= b 0) a (gcd b (remainder a b)))) ;prime test function from ex1.29 (define (miller-rabin n times) (define (mr-exp-mod base expt) (if (= expt 0) 1 (let* ((half (mr-exp-mod base (quotient expt 2))) (squared-half (remainder (* half half) n))) (cond ((and (= squared-half 1) (not (= half 1)) (not (= half (- n 1)))) 0) ((even? expt) squared-half) (else (remainder (* base squared-half) n)))))) (define (test) (define (try-it a) (= (mr-exp-mod a (- n 1)) 1)) (try-it (+ 1 (random (- n 1))))) (cond ((< n 2) #f) ((= times 0) #t) (else (and (test) (miller-rabin n (- times 1))))))
false
4748c12a4d49ab5dbcabcc02d2f83cd6bdf448a2
ac2a3544b88444eabf12b68a9bce08941cd62581
/doc/m7.scm
230d8231e3bc9f81bb18149c5c39fb57ffa9d01c
[ "Apache-2.0", "LGPL-2.1-only" ]
permissive
tomelam/gambit
2fd664cf6ea68859d4549fdda62d31a25b2d6c6f
d60fdeb136b2ed89b75da5bfa8011aa334b29020
refs/heads/master
2020-11-27T06:39:26.718179
2019-12-15T16:56:31
2019-12-15T16:56:31
229,341,552
1
0
Apache-2.0
2019-12-20T21:52:26
2019-12-20T21:52:26
null
UTF-8
Scheme
false
false
23
scm
m7.scm
(define (g y) (+ n y))
false
9183dd59a86bbe96de469122ff1be46c5c3bad23
4f91474d728deb305748dcb7550b6b7f1990e81e
/Chapter2/ex2.39.scm
c04390d06d26b214638b731a9af877c279604099
[]
no_license
CanftIn/sicp
e686c2c87647c372d7a6a0418a5cdb89e19a75aa
92cbd363c143dc0fbf52a90135218f9c2bf3602d
refs/heads/master
2021-06-08T22:29:40.683514
2020-04-20T13:23:59
2020-04-20T13:23:59
85,084,486
2
0
null
null
null
null
UTF-8
Scheme
false
false
247
scm
ex2.39.scm
(define (fold-right op initial sequence) (if (null? sequence) initial (op (car sequence) (fold-right op initial (cdr sequence))))) (define (reverse sequence) (fold-right (lambda (x y) (append y (list x))) '() sequence))
false
ee284211d160f77f84940c59ee66e4f0baa92c61
4b480cab3426c89e3e49554d05d1b36aad8aeef4
/chapter-04/ex4.16.c-comkid-test.scm
2d9380fefaf649121b01c44b9a44557cd75e3622
[]
no_license
tuestudy/study-sicp
a5dc423719ca30a30ae685e1686534a2c9183b31
a2d5d65e711ac5fee3914e45be7d5c2a62bfc20f
refs/heads/master
2021-01-12T13:37:56.874455
2016-10-04T12:26:45
2016-10-04T12:26:45
69,962,129
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,109
scm
ex4.16.c-comkid-test.scm
(load "ch4-myeval-pkg-comkid.scm") (load "ex4.11-comkid.scm") (load "ex4.12-comkid.scm") (load "ex4.13-comkid.scm") (load "ex4.16.a-comkid.scm") (load "ex4.16.b-comkid.scm") (load "ex4.16.c-comkid.scm") (load "../misc/scheme-test-r5rs.scm") (define the-global-environment (setup-environment)) (myeval '(define (f x) (define (square a) (* a a)) (define b 3) (+ b (square x))) the-global-environment) (myeval '(define (double x) (* x 2)) the-global-environment) (display "[ex4.17.c - Tests]\n") (run (make-testcase '(assert-equal? 7 (myeval '((lambda (x) (define (square a) (* a a)) (define b 3) (+ b (square x))) 2) the-global-environment)) '(assert-equal? 30 (myeval '((lambda (x) (define a 10) (define b 20) (+ a b)) 3) the-global-environment)) '(assert-equal? 16 (myeval '(double 8) the-global-environment)) ))
false
a417a7c71f3985eaa29ebf803d4badefc3a4b563
370ebaf71b077579ebfc4d97309ce879f97335f7
/sicp/ch2/intervals.scm
009af85280b2bcdfc4ca964e737c506018a6574a
[]
no_license
jgonis/sicp
7f14beb5b65890a86892a05ba9e7c59fc8bceb80
fd46c80b98c408e3fd18589072f02ba444d35f53
refs/heads/master
2023-08-17T11:52:23.344606
2023-08-13T22:20:42
2023-08-13T22:20:42
376,708,557
0
0
null
null
null
null
UTF-8
Scheme
false
false
598
scm
intervals.scm
(define-library (ch2 intervals) (export make-interval make-interval-center-width make-interval-center-percent lower-bound upper-bound) (import (scheme base) (scheme write) (scheme case-lambda)) (begin (define (make-interval lower upper) (cond ((> lower upper) ;; (error "interval can't be constructed with lower bound > upper bound" ;; lower ;; upper)) (cons upper lower)) (else (cons lower upper)))) (define (lower-bound interval) (car interval)) (define (upper-bound interval) (cdr interval))))
false
7df02c34b1d71bbbbe746e05b4ae9e8aca8e5c78
18e69f3b8697cebeccdcd7585fcfc50a57671e21
/scheme/test.scm
4f10283494f8ea8e14efdeddf378c3dd1e3f5d21
[]
no_license
ashikawa/scripts
694528ccfd0b84edaa980d6cde156cfe394fe98a
c54463b736c6c01781a0bfe00472acd32f668550
refs/heads/master
2021-01-25T04:01:34.073018
2013-12-02T03:33:29
2013-12-02T03:33:29
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
306
scm
test.scm
(define ex (cons 1 (cons 2 (cons 3 (cons 4 (cons 5 '())))))) (display ex) (newline) (define ex2 (list 1 2 3 4 5)) (display ex2) (newline) (display (car ex2)) (newline) (display (cdr ex2)) (newline) (display (cddr ex2)) (newline) (display (cadr ex2)) (newline) (display (caddr ex2)) (newline)
false
1d890a3dd4e95b1b3e4a0319410ae4ea4cb91bc1
c754c7467be397790a95c677a9ef649519be59fa
/src/chap4/puzzles.scm
4fffd60aca3c2f204561559131488e1755b5ee72
[ "MIT" ]
permissive
Pagliacii/my-sicp-solutions
8117530185040aa8254f355e0ce78217d3e4b63b
7a0ffa0e60126d3fddf506e4801dde37f586c52b
refs/heads/main
2023-06-24T21:44:38.768363
2021-07-26T15:03:37
2021-07-26T15:03:37
388,704,426
0
0
null
null
null
null
UTF-8
Scheme
false
false
5,635
scm
puzzles.scm
(load "amb-utils.scm") (define (distinct? items) (cond ((null? items) true) ((null? (cdr items)) true) ((member (car items) (cdr items)) false) (else (distinct? (cdr items))))) (define (multiple-dwelling) (let ((baker (amb 1 2 3 4 5)) (cooper (amb 1 2 3 4 5)) (fletcher (amb 1 2 3 4 5)) (miller (amb 1 2 3 4 5)) (smith (amb 1 2 3 4 5))) (require (distinct? (list baker cooper fletcher miller smith))) (require (not (= baker 5))) (require (not (= cooper 1))) (require (not (= fletcher 5))) (require (not (= fletcher 1))) (require (> miller cooper)) (require (not (= (abs (- smith fletcher)) 1))) (require (not (= (abs (- fletcher cooper)) 1))) (list (list 'baker baker) (list 'cooper cooper) (list 'fletcher fletcher) (list 'miller miller) (list 'smith smith)))) (define (efficient-multiple-dwelling) (let ((cooper (amb 2 3 4 5)) (miller (amb 3 4 5))) (require (> miller cooper)) (let ((fletcher (amb 2 3 4))) (require (not (= (abs (- fletcher cooper)) 1))) (let ((smith (amb 1 2 3 4 5))) (require (not (= (abs (- smith fletcher)) 1))) (let ((baker (amb 1 2 3 4))) (require (distinct? (list baker cooper fletcher miller smith))) (list (list 'baker baker) (list 'cooper cooper) (list 'fletcher fletcher) (list 'miller miller) (list 'smith smith))))))) (define (liars-puzzle) (define (xor p q) (if p (not q) q)) (let ((betty (amb 1 2 3 4 5)) (kitty (amb 1 2 3 4 5)) (ethel (amb 1 2 3 4 5)) (joan (amb 1 2 3 4 5)) (mary (amb 1 2 3 4 5))) (require (distinct? (list betty kitty ethel joan mary))) (require (xor (= kitty 2) (= betty 3))) (require (xor (= ethel 1) (= joan 2))) (require (xor (= ethel 5) (= joan 3))) (require (xor (= kitty 2) (= mary 4))) (require (xor (= betty 1) (= mary 4))) (list (list 'betty betty) (list 'kitty kitty) (list 'ethel ethel) (list 'joan joan) (list 'mary mary)))) (define (father-puzzle) (define father first) (define daughter second) (define yacht third) (let ((moore (list 'moore 'mary-ann 'lorna)) (hood (list 'hood (amb 'lorna 'rosalind 'melissa) 'gabrielle))) (let ((hall (list 'hall (amb 'gabrielle 'lorna 'melissa) 'rosalind))) (require (not (eq? (daughter hall) (daughter hood)))) (let ((downing (list 'downing (amb 'gabrielle 'lorna 'rosalind) 'melissa))) (require (eq? (daughter hood) 'melissa)) (require (not (eq? (daughter hall) 'melissa))) (require (not (eq? (daughter downing) (daughter hood)))) (require (not (eq? (daughter downing) (daughter hall)))) (let ((parker (list 'parker (amb 'lorna 'rosalind) 'mary-ann)) (gabrielle-father (amb hall downing))) (require (not (eq? (daughter parker) (daughter hood)))) (require (not (eq? (daughter parker) (daughter hall)))) (require (not (eq? (daughter parker) (daughter downing)))) (require (eq? (daughter gabrielle-father) 'gabrielle)) (require (eq? (daughter parker) (yacht gabrielle-father))) (list hood moore downing hall parker)))))) (define (father-puzzle-variation) (define father first) (define daughter second) (define yacht third) (let ((moore (list 'moore (amb 'mary-ann 'rosalind 'melissa 'gabrielle) 'lorna)) (hood (list 'hood (amb 'mary-ann 'lorna 'rosalind 'melissa) 'gabrielle))) (require (not (eq? (daughter moore) (daughter hood)))) (let ((hall (list 'hall (amb 'mary-ann 'gabrielle 'lorna 'melissa) 'rosalind))) (require (not (eq? (daughter hall) (daughter moore)))) (require (not (eq? (daughter hall) (daughter hood)))) (let ((downing (list 'downing (amb 'mary-ann 'gabrielle 'lorna 'rosalind) 'melissa))) (require (eq? (daughter hood) 'melissa)) (require (not (eq? (daughter moore) 'melissa))) (require (not (eq? (daughter hall) 'melissa))) (require (not (eq? (daughter downing) (daughter moore)))) (require (not (eq? (daughter downing) (daughter hood)))) (require (not (eq? (daughter downing) (daughter hall)))) (let ((parker (list 'parker (amb 'gabrielle 'lorna 'rosalind) 'mary-ann)) (gabrielle-father (amb moore hall downing))) (require (not (eq? (daughter parker) (daughter moore)))) (require (not (eq? (daughter parker) (daughter hood)))) (require (not (eq? (daughter parker) (daughter hall)))) (require (not (eq? (daughter parker) (daughter downing)))) (require (eq? (daughter gabrielle-father) 'gabrielle)) (require (eq? (daughter parker) (yacht gabrielle-father))) (list hood moore downing hall parker)))))) (define (queens n) (define (new-queen rest-queens) (define (check-and-append row column old-column) (if (= old-column -1) (append rest-queens (list row)) (let ((old-row (list-ref rest-queens old-column))) (require (not (= row old-row))) (require (not (= (+ row column) (+ old-row old-column)))) (require (not (= (- row column) (- old-row old-column)))) (check-and-append row column (- old-column 1))))) (let ((new-column (length rest-queens)) (q (an-integer-between 1 8))) (check-and-append q new-column (- new-column 1)))) (define (iter result) (if (= (length result) n) result (iter (new-queen result)))) (iter '()))
false
f1eecff3660e8d0e3c4617dc6ad1b09457e838fb
de5d387aa834f85a1df3bd47bc324b01130f21fb
/ps9/code/load.scm
4eb718bc29c236a1dd9e64c302435b8474724e43
[]
no_license
chuchao333/6.945
5ae15980a952bed5c868be03d1a71b1878ddd53d
c50bb28aadf0c3fcda3c8e56b4a61b9a2d582552
refs/heads/master
2020-05-30T20:23:23.501175
2013-05-05T19:59:53
2013-05-05T19:59:53
24,237,118
5
0
null
null
null
null
UTF-8
Scheme
false
false
718
scm
load.scm
(set! (access user-initial-environment system-global-environment) (extend-top-level-environment system-global-environment)) (environment-define system-global-environment 'generic-evaluation-environment (extend-top-level-environment user-initial-environment)) (load "utils" user-initial-environment) (load "time-share" user-initial-environment) (load "schedule" user-initial-environment) (load "ghelper" user-initial-environment) (load "syntax" user-initial-environment) (load "rtdata" user-initial-environment) (load "interp-actor" generic-evaluation-environment) (load "repl" generic-evaluation-environment) ;;(load "promises" user-initial-environment) ;; (ge generic-evaluation-environment)
false
2d1cad3bbb182c4ae21876f5c04b3066f91d3854
6b961ef37ff7018c8449d3fa05c04ffbda56582b
/bbn_cl/mach/demo/simp.scm
9a20b0b9b7ebea330ea3a37eb7112ab2cc7dd776
[]
no_license
tinysun212/bbn_cl
7589c5ac901fbec1b8a13f2bd60510b4b8a20263
89d88095fc2a71254e04e57cf499ae86abf98898
refs/heads/master
2021-01-10T02:35:18.357279
2015-05-26T02:44:00
2015-05-26T02:44:00
36,267,589
4
3
null
null
null
null
UTF-8
Scheme
false
false
3,009
scm
simp.scm
;;; ******** ;;; ;;; Copyright 1992 by BBN Systems and Technologies, A division of Bolt, ;;; Beranek and Newman Inc. ;;; ;;; Permission to use, copy, modify and distribute this software and its ;;; documentation is hereby granted without fee, provided that the above ;;; copyright notice and this permission appear in all copies and in ;;; supporting documentation, and that the name Bolt, Beranek and Newman ;;; Inc. not be used in advertising or publicity pertaining to distribution ;;; of the software without specific, written prior permission. In ;;; addition, BBN makes no respresentation about the suitability of this ;;; software for any purposes. It is provided "AS IS" without express or ;;; implied warranties including (but not limited to) all implied warranties ;;; of merchantability and fitness. In no event shall BBN be liable for any ;;; special, indirect or consequential damages whatsoever resulting from ;;; loss of use, data or profits, whether in an action of contract, ;;; negligence or other tortuous action, arising out of or in connection ;;; with the use or performance of this software. ;;; ;;; ******** ;;; ;;;; Simplification works by canonicalizing the polynomial and ; then sorting it by the powers of its factors. A final merge ; step combines terms with the same coefficients. (declare (usual-integrations)) ; Sort a polynomial using the vector sort utility below. (define (sort-poly poly) (make-poly (poly-variables poly) (list->bag (sort-poly-terms poly)))) (define (sort-poly-terms poly) (let ((newpoly (weight-poly poly))) (bag-reduce merge-terms (lambda (tlist) (collect-terms (sort-terms tlist))) (poly-terms newpoly)))) ; Sort the terms assuming that they have been weighted. (define (sort-terms tlist) (sort tlist term-greater?)) (define (term-greater? x y) (> (term-weight x) (term-weight y))) ; Merge two term lists by comparing their weights. This will merge ; terms if necessary. (define (merge-terms trma trmb) (cond ((null? trma) trmb) ((null? trmb) trma) ((= (term-weight (car trma)) (term-weight (car trmb))) (cons (make-weighted-term (+ (term-coeff (car trma)) (term-coeff (car trmb))) (term-weight (car trma)) (term-factors (car trma))) (merge-terms (cdr trma) (cdr trmb)))) ((> (term-weight (car trma)) (term-weight (car trmb))) (cons (car trma) (merge-terms (cdr trma) trmb))) (else (cons (car trmb) (merge-terms trma (cdr trmb)))))) ; Merge adjacent terms with the same weight by adding their coefficients. (define (collect-terms terms) (cond ((null? terms) ()) ((null? (cdr terms)) terms) ((= (term-weight (car terms)) (term-weight (cadr terms))) (collect-terms (cons (make-weighted-term (+ (term-coeff (car terms)) (term-coeff (cadr terms))) (term-weight (car terms)) (term-factors (car terms))) (cddr terms)))) (else (cons (car terms) (collect-terms (cdr terms))))))
false
92d9397007dc18e30e74f458207d03131c6ab86c
bf9529ad04524a002b49f5a730d0396128545c54
/src/paxos/misc/coroutines.scm
95d3ae11e4731e4537c7242a170e3d774470b556
[]
no_license
z7198185/guile-paxos
0bdac6a254dfaa3d29965712c6c31d94cefcf328
b38af35146af98f10b1fa4e45d23aa8e7db66a53
refs/heads/master
2021-01-11T12:09:24.850538
2014-05-19T18:04:51
2014-05-19T18:04:51
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
810
scm
coroutines.scm
#!r6rs (library (paxos misc coroutines) (export call-with-yield with-yield) (import (rnrs) (ice-9 control)) (define (call-with-yield proc) (let ((tag (make-prompt-tag))) (define (handler k . args) (define (resume . args) (call-with-prompt tag (lambda () (apply k args)) handler)) (apply values resume args)) (call-with-prompt tag (lambda () (let ((yield (lambda args (apply abort-to-prompt tag args)))) (proc yield))) handler))) (define-syntax with-yield (syntax-rules () ((_ yield exp exp* ...) (call-with-yield (lambda (yield) exp exp* ...))))))
true
ccbef36afab66dd966860cc1dc0c742194e16488
defeada37d39bca09ef76f66f38683754c0a6aa0
/System/system/net/ftp-data-stream.sls
7acf21144149b818040e3908a107791d8ffcf361
[]
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,556
sls
ftp-data-stream.sls
(library (system net ftp-data-stream) (export is? ftp-data-stream? read end-write write begin-write set-length end-read begin-read seek flush close can-read? can-write? can-seek? length position-get position-set! position-update!) (import (ironscheme-clr-port)) (define (is? a) (clr-is System.Net.FtpDataStream a)) (define (ftp-data-stream? a) (clr-is System.Net.FtpDataStream a)) (define-method-port read System.Net.FtpDataStream Read (System.Int32 System.Byte[] System.Int32 System.Int32)) (define-method-port end-write System.Net.FtpDataStream EndWrite (System.Void System.IAsyncResult)) (define-method-port write System.Net.FtpDataStream Write (System.Void System.Byte[] System.Int32 System.Int32)) (define-method-port begin-write System.Net.FtpDataStream BeginWrite (System.IAsyncResult System.Byte[] System.Int32 System.Int32 System.AsyncCallback System.Object)) (define-method-port set-length System.Net.FtpDataStream SetLength (System.Void System.Int64)) (define-method-port end-read System.Net.FtpDataStream EndRead (System.Int32 System.IAsyncResult)) (define-method-port begin-read System.Net.FtpDataStream BeginRead (System.IAsyncResult System.Byte[] System.Int32 System.Int32 System.AsyncCallback System.Object)) (define-method-port seek System.Net.FtpDataStream Seek (System.Int64 System.Int64 System.IO.SeekOrigin)) (define-method-port flush System.Net.FtpDataStream Flush (System.Void)) (define-method-port close System.Net.FtpDataStream Close (System.Void)) (define-field-port can-read? #f #f (property:) System.Net.FtpDataStream CanRead System.Boolean) (define-field-port can-write? #f #f (property:) System.Net.FtpDataStream CanWrite System.Boolean) (define-field-port can-seek? #f #f (property:) System.Net.FtpDataStream CanSeek System.Boolean) (define-field-port length #f #f (property:) System.Net.FtpDataStream Length System.Int64) (define-field-port position-get position-set! position-update! (property:) System.Net.FtpDataStream Position System.Int64))
false
398b2d80fbddf3a39f9e7e4def0dc2250d0ab9dc
069111ccfe6585670fb7bc2047ff968c3d1ba86f
/sample/dom.scm
e1bcd77e66f37a9d6a448e884e85c128f4e3ddc4
[ "MIT" ]
permissive
SaitoAtsushi/Gauche-OLE
431eb9c2116592f2ccf1e71dbf09ffe10b45028b
10ad8c54faaa7c0368eb0295cd99de3e0ebc7a8e
refs/heads/master
2020-05-19T10:26:46.881876
2019-05-05T03:10:12
2019-05-05T03:10:12
184,971,684
0
0
null
null
null
null
UTF-8
Scheme
false
false
356
scm
dom.scm
#!/usr/bin/env gosh (use win.ole) (use gauche.collection) (define IE (make-ole "InternetExplorer.Application")) (set! (~ IE 'Visible) #t) (while (~ IE 'busy) (sys-sleep 1)) (IE 'Navigate "http://example.com/") (while (~ IE 'busy) (sys-sleep 1)) (display (? IE 'Document ! 'getElementsByTagName "div" ! 'item 0 ? 'innerText)) (ole-release!)
false
766907316aedae264ee402dd975f7c14fe50d838
2e126f712dc32c77a8281a78bbe4705643d7898d
/samples/isd.scm
e5d91da5a296d60a09b30200f1a6b419e7fa5ffa
[]
no_license
ktakashi/sagittarius-smart-card
f35cadc5340b7ac0c225f46eb293dee9d0da0fda
bd2785cc41d161f06a8ea9f81491bfc5a84d039e
refs/heads/master
2020-05-07T17:38:31.459826
2014-09-29T08:52:02
2014-09-29T08:52:02
7,689,155
1
0
null
null
null
null
UTF-8
Scheme
false
false
877
scm
isd.scm
(import (rnrs) (pcsc operations gp) (pcsc operations control) (pcsc shell commands)) ;; set your key here (define key #x10101010101010101010101010101010) (establish-context) (card-connect) (trace-on) (select) ;; get card status (for nothing) (print (invoke-command card-status)) ;; open secure channel (channel :security *security-level-mac* :option #x55 :key-version #x20 :enc-key key :mac-key key :dek-key key) ;; application get status of ISD ;; if the command is not the most top-level then ;; invoke-command must be used to run commands (print (bytevector->hex-string (invoke-command get-status issuer))) (print (bytevector->hex-string (invoke-command get-status applications))) (print (bytevector->hex-string (invoke-command get-status loadfiles))) (print (bytevector->hex-string (invoke-command get-status modules))) (card-disconnect) (release-context)
false
20f80da7443fd270c7e623fa8ac08d071ceb7fff
defeada37d39bca09ef76f66f38683754c0a6aa0
/System/system/net/ipv6-address.sls
f49ba93f4a20d8a52120f1aa82356d3c46cf1e8f
[]
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,643
sls
ipv6-address.sls
(library (system net ipv6-address) (export new is? ipv6-address? get-hash-code is-ipv4-compatible? parse equals? try-parse? is-ipv4-mapped? to-string is-loopback? loopback unspecified address prefix-length scope-id-get scope-id-set! scope-id-update! item address-family) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Net.IPv6Address a ...))))) (define (is? a) (clr-is System.Net.IPv6Address a)) (define (ipv6-address? a) (clr-is System.Net.IPv6Address a)) (define-method-port get-hash-code System.Net.IPv6Address GetHashCode (System.Int32)) (define-method-port is-ipv4-compatible? System.Net.IPv6Address IsIPv4Compatible (System.Boolean)) (define-method-port parse System.Net.IPv6Address Parse (static: System.Net.IPv6Address System.String)) (define-method-port equals? System.Net.IPv6Address Equals (System.Boolean System.Object)) (define-method-port try-parse? System.Net.IPv6Address TryParse (static: System.Boolean System.String System.Net.IPv6Address&)) (define-method-port is-ipv4-mapped? System.Net.IPv6Address IsIPv4Mapped (System.Boolean)) (define-method-port to-string System.Net.IPv6Address ToString (System.String System.Boolean) (System.String)) (define-method-port is-loopback? System.Net.IPv6Address IsLoopback (static: System.Boolean System.Net.IPv6Address)) (define-field-port loopback #f #f (static:) System.Net.IPv6Address Loopback System.Net.IPv6Address) (define-field-port unspecified #f #f (static:) System.Net.IPv6Address Unspecified System.Net.IPv6Address) (define-field-port address #f #f (property:) System.Net.IPv6Address Address System.UInt16[]) (define-field-port prefix-length #f #f (property:) System.Net.IPv6Address PrefixLength System.Int32) (define-field-port scope-id-get scope-id-set! scope-id-update! (property:) System.Net.IPv6Address ScopeId System.Int64) (define-field-port item #f #f (property:) System.Net.IPv6Address Item System.UInt16) (define-field-port address-family #f #f (property:) System.Net.IPv6Address AddressFamily System.Net.Sockets.AddressFamily))
true
d5b3a0b9e445bef30a17ac9a6f0e87a137888a9c
ae4938300d7eea07cbcb32ea4a7b0ead9ac18e82
/utils/tester.ss
c42e56fdd6319d85db50195eefff2ded99ed82ed
[]
no_license
keenbug/imi-libs
05eb294190be6f612d5020d510e194392e268421
b78a238f03f31e10420ea27c3ea67c077ea951bc
refs/heads/master
2021-01-01T19:19:45.036035
2012-03-04T21:46:28
2012-03-04T21:46:28
1,900,111
0
1
null
null
null
null
UTF-8
Scheme
false
false
599
ss
tester.ss
#!r6rs (library (imi utils tester) (export tester tester* testq testqv test char-in) (import (rnrs) (imi sugar cut)) (define (tester test eq? ls) (lambda (x) (test (cut eq? x <>) ls))) (define (tester* test eq? . ls) (tester test eq? ls)) (define (testq test . ls) (tester test eq? ls)) (define (testqv test . ls) (tester test eqv? ls)) (define (test proc . ls) (tester proc equal? ls)) (define (char-in chars) (tester exists char=? (string->list chars))) )
false
6aa4fa85a212e28add87bd452cf065c45f28540e
eef5f68873f7d5658c7c500846ce7752a6f45f69
/spheres/net/sack-server.scm
04a96aceaecab78a6bb95fc3fa9622579d66e96b
[ "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
84,010
scm
sack-server.scm
;; Sack HTTP server middleware ;; ;; Copyright (C) 2008-2009 Per Eckerdal, 2010-2013 Mikael More, 2005-2007 Marc Feeley. ;; All Rights Reserved. ;; MIT license. ;; ;; Fundementally Sack delivers core HTTP server functionality only, without also providing any ;; abstractions that the HTTP protocol does not imply. Thus for example, Sack does not provide ;; functionality to read static files from a harddrive as to deliver in a path on the HTTP server. ;; ;; Sack is inspired by Ruby's Rack, http://rack.github.io/ as introduced on ;; http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html , which in turn was inspired ;; by PEP333: Python Web Server Gateway Interface, http://www.python.org/dev/peps/pep-0333/ . ;; ;; ## General description of use ;; The basic use goes like this: ;; ;; * A Sack server is started using |sack-start!|. It takes the Sack app thunk as first argument, ;; which is the procedure that Sack invokes for each HTTP request received. Remaining arguments ;; are configuration options for what TCP port to use etc. ;; ;; * The Sack app thunk takes one argument, being |env|. |env| is a procedure that contains the ;; Sack app's "environment", as in, information about URI, headers, HTTP request body contents ;; etc. ;; ;; For the default |env| provided by Sack, see |make-environment|. ;; ;; * Sack provides extensibility through easy implementation of "adapters", that form a layer ;; between Sack and the Sack app, and that overlaps the |env| procedure as to provide additional ;; functionality. ;; ;; An example of such an extension is cookies support, provided by the cookies module. ;; ;; * The Sack app procedure should return a structure (values http-code headers data-thunk) . ;; ;; http-code = HTTP response statatus code as an integer e.g. 200 ;; headers = HTTP response headers as an a-list e.g. ;; '(("Content-Type" . "text/html; charset=utf-8")) ;; data-thunk = HTTP response body data provider thunk. Procedure taking no arguments and that ;; returns either an u8vector containing the next chunk of body data to be sent to ;; the client, or #f meaning that all data to be output has been provided and the ;; provision of HTTP response thus is done now. ;; ;; * On return of the sack-app, Sack sends to the client the HTTP response status and headers, and ;; then invokes data-thunk all until it returns #f. ;; ;; ## Simple use example ;; Opens a HTTP server on port 8000, available to connect to from any peer. For each HTTP request, ;; responds with HTTP status 200 (= HTTP OK), no headers, and with the text "Hello world!\n\nURI: " ;; followed by a copy of the particular URI this visit is for, with domain name, path and query i.e. ;; HTTP GET arguments. ;; ;; (sack-start! (lambda (env) ;; (define (r) (with-output-to-u8vector '() (lambda () ;; (print "Hello world!\n" ;; "\n" ;; "URI: " (env 'sack:uri))))) ;; (values 200 '() (let ((f #t)) (lambda () (and f (begin (set! f #f) (r))))))) ;; server-address: "*" port-number: 8000) ;; ;; ## Error handling ;; Sack needs to have error handling that is automatic and transparent on the one hand, and that is ;; configurable and hookable on the other hand, as to satisfy any general development and error ;; reporting use case. ;; ;; # Connection error handling ;; Connections that shut down before having received HTTP request line and HTTP headers, are ;; disconnected transparently. ;; ;; Disconnection while reading the HTTP request body (through the 'sack:body environment parameter) ;; or while sending the HTTP response body (through ;; ;; # sack-app exception handling ;; By default on sack-app exception, Sack catches the exception and current continuation and prints ;; them out fully. ;; ;; While this works well as a default behavior, in a particular use of Sack, the user may want: ;; ;; * Exceptions not to be caught. ;; Also it would be imaginable that the user would want only the exception to be caught. ;; And, ;; ;; * Printouts not to be made, or made but of the exception only and not of the continuation. ;; ;; Adjusting these is done through the |on-exception-catch| and |print-caught-exception?| key ;; arguments, see their definition site below for the possible settings. ;; ;; Last, we also want an on exception callback for exception monitoring and reporting purposes. ;; ;; For its definition, see its definition site below. ;; ;; ## Note on keepalives and TCP protocol logics ;; Note that the keep-alive logics are written in such a way that the client web browser is pushed ;; to make some of the close:s. This is good as close:s are medium-expensive - at the level of the ;; TCP stack, for each TCP connection, the party that initiates the close needs to keep a structure ;; must in RAM for ~2mins and during this time not more than ~32000 connections including those ;; closed ones can exist between the two IP:s. ;; ;; ## Primitives for server overload protection ;; As fundamentally Sack's action when in multithreaded mode is to launch a thread with the sack-app ;; for each received connection, there is a possibility that the server becomes overloaded in terms ;; of RAM, CPU or other use, and could go out of order. ;; ;; There are two points in Sack that are regarded by overloading: ;; ;; a) The acceptance of new TCP connections ;; (Regulates the number of TCP connections being processed) ;; ;; An incoming TCP connection starts taking any resources at all in the Gambit process, at first ;; when it has been (read) from the TCP server port. ;; ;; For this reason, together with that as long as we haven't (read) a connection the peer will ;; get a proper failure value in their TCP stack, we implement the overload protection as a ;; limiting mechanism on the (read):ing of new connections. ;; ;; b) The keeping of idling keepalive connections ;; (Regulates the number of TCP connections being processed) ;; ;; As we relate within these primitives to the number of TCP connections open as the basic ;; metric for basing overload protection mechanisms on, then in a situation of overload, based ;; on the max allowed number of TCP connections having been reached, no more TCP connections ;; will be allowed. ;; ;; Apart from that each TCP connection generally brings with it sack-app execution, it also ;; importantly occupies an OS socket and possibly a SSL channel, which are both expensive ;; resources. ;; ;; If the max TCP connection limit is reached, it's remedial to close TCP connections that very ;; probably are idling forever anyhow. ;; ;; These two points provide of course a limitation in that the overload mechanism this way not gives ;; any consideration to the amount of connections that are waiting to get accepted, whatever many or ;; few it may be. This though, is not an issue, as the goal is to deliver as much as we can but ;; safely, and how much we can deliver is a function of server-internal factors only and is not ;; affected by the amount of waiting connections. ;; ;; A third point for the acceptance of HTTP requests within a TCP connection to regulate the load ;; put on internal processing and sack-app execution was considered, though as the overhead of HTTP ;; request reading before sack-app launch is small and because it wouldn't make sense to put such a ;; point before any SSL channel negotiation has been done as the goal right after accepting a new ;; TCP connection is to get it ready to receive HTTP requests on and both TCP handshake and SSL ;; negotiations are quick processes, it was chosen that such a point should not be included. ;; ;; Please note that overload protection regarding the execution of the sack-app itself is not in the ;; scope of these overload protection primitives; that is to be implemented at the sack-app side, ;; for instance as an overload wrapper; ;; ;; These overload protection primitives are for providing overload protection logics that cannot be ;; implemented at the level of sack-app, solely. ;; ;; Primitives for regulating these three points are provided by the following optional arguments: ;; ;; accept-block = A procedure that takes no argument and returns nothing, that is invoked ;; before Sack will start (read):ing a new connection. This way the Sack user can ;; choose the timing of and rate for acceptance of new TCP connections. ;; ;; Do not let the accept-block procedure block forever, as closure of the Sack ;; server is done synchronously with accept-block only. ;; on-connection = A procedure that takes the arguments (connection is-connect?) and returns ;; nothing. ;; ;; connection = A closure unique to the connection opened. Takes the arguments (operation) and ;; returns the corresponding value or a closure that performs the respective operation: ;; ;; ('on-connection-idle-set!) => procedure (on-connection-idle) => #!void ;; = Allows the Sack user to set a |on-connection-idle| closure for the TCP ;; connection. This can be done *only during* the |on-connection| callback. ;; ;; on-connect-idle is a closure that takes the arguments (into-idle?) and returns ;; nothing. Sack will invoke it when the TCP connection will invoke it when it goes ;; into and out of reading the request line for a new HTTP request on a TCP connection, ;; which coincides with HTTP's idling connection state, that lasts for up to the duration ;; of the keepalive timeout. ;; ;; Thanks to this closure, the overload protection can keep track of how long respective ;; TCP connections have idled, and if needing to zero keepalives due to proximity to or ;; actual overload of number of concurrent TCP connections. ;; ;; ('keepalive-zero!) => procedure (only-if-idle-now?) => boolean ;; = Set the keepalive timeout for this connection to zero. This will make the ;; TCP connection close right away when it's not in use, which is of use for ;; an overload mechanism for decreasing the number of TCP connections quickly, ;; as to minimize the time close to or in a situation of TCP connection overload. I.e., ;; close to or when a Sack user's TCP connections roof is reached, it can ;; 'keepalive-zero! present connections as to free up connection slots faster. ;; ;; only-if-idle-now? = boolean, if #t the zeroing of the keepalive will be done ;; only if Sack is currently idling. ;; ;; Returns boolean for if the keepalive was actually zeroed, #t unless if ;; only-if-idle-now? was set and the connection was not idling now. ;; ;; is-connect? = A boolean that is #t if the call regards the opening of a TCP connection, ;; and #f if the call regards the closing of a TCP connection. ;; ;; This allows for the Sack user to track the number of active connections, and to manage the number of idling ;; keepalive connections. ;; ;; ## History ;; 2011-02-01: Added level to selected force-output calls to ensure that data is actually ;; transmitted to the client immediately on chunk write. ;; 2012-02-18: Updated the calling convention of sack:body to a more effective and functional one. ;; See the comments inside handle-sack-response for more info. ;; 2013-03-06: Structured and commented code. Implemented the 'sack:client-ip/u8v and ;; 'sack:client-ip environment methods. ;; 2013-05-10: Added primitives for overload handling. ;; ;; ## TODO ;; * Replace current body reading code with one that's implemented in a straight way. ;; * To specify to the server that the response is already chunk-encoded, you have to specify a ;; header like ("Transfer-Encoding" . "chunked"), that is, the value must not contain any ;; whitespace, commas or any other values (for instance "chunked" or "identity, chunked"). ;; Otherwise it will not understand it. To specify more than one encoding, use several header ;; field definitions. (?) ;; * Implement maximal chunk size on chunked encoding. [how to do that?] ;; * Implement conditional gets (?) ;; * Implement partial gets (?) ;; * Implement IP serialization for IPv6 IP:s ;; * Make the sack quit closure set the timeout on the server port to -inf as to ;; return the (read) for a new connection ASAP. ;; * Make the keepalive timeout applied *only* to the reading of the request line and request ;; headers, and not as currently also apply to the course of the request output IO work, ;; which should not be subject to any timeout, or, at least subject to another timeout value, ;; separate from the timeout. ;; (declare (standard-bindings) (extended-bindings) (block)) (define filter (lambda (p s) (cond ((null? s) '()) ((p (car s)) (cons (car s) (filter p (cdr s)))) (else (filter p (cdr s)))))) ;; ## Configuration settings ;; The mutations below are to work around the (declare (block)) for the respective values. ; ;; How many HTTP requests it's the most effective thing for a web browser to pipeline in a single ;; TCP connection, we let up to the web browser to decide. Due to the quite significant time it can ;; take to establish a TCP connection (including a SSL handshake, for example), it's not our ;; job to impose anything that could be related to as limits in this regard. (define default-http-connection-requests-roof #f) (set! default-http-connection-requests-roof 50) ;; # Debug output settings ;; The code contains outputs for debug logging. Since it's extremely rare that Sack would need to be debugged, ;; we provide the toggle for it by the user commenting our or not commenting out the actual code for it in here. (define sack-verbose #f) (define sack-verbose-about-gc-time-finalization? #f) ; #f = No debug output on GC-time sack-app thread finalization ; #t = Print output on GC-time sack-app thread finalization ; 'all = Print output on any sack-app thread finalization (set! sack-verbose #f) (set! sack-verbose-about-gc-time-finalization? #f) ;; # Default exception reporting settings (define sack-exception-on-exception-catch #f) (define sack-exception-print-caught-exception? #f) (define sack-exception-print-max-head #f) (define sack-exception-print-max-tail #f) (define sack-exception-on-exception-hook #f) (set! sack-exception-on-exception-catch 'exception&continuation) (set! sack-exception-print-caught-exception? #t ) (set! sack-exception-print-max-head 100 ) (set! sack-exception-print-max-tail 100 ) (set! sack-exception-on-exception-hook #f ) (define sack-version '(0 2)) (define-macro (sack-dbg . a) `(begin (if sack-verbose (begin (print port: console-output-port "sack: " (apply dumps (list ,@a)) "\n") (force-output console-output-port 1))))) (define-macro (sack-dbg-warn . a) `(begin (print port: console-output-port " XX sack warning: " (apply dumps (list ,@a)) "\n") (force-output console-output-port 1))) ;; Utilities. ;; For making debug output (define console-output-port (current-output-port)) ;; The parameter name is assumed to be lowercase. (define (has-header? headers name) (let loop ((lst headers)) (cond ((null? lst) #f) ((equal? name (string-downcase (caar lst))) #t) (else (loop (cdr lst)))))) ;; The parameter name is assumed to be lowercase. Note that this ;; function does not understand comma-separated lists of in header ;; values. (define (has-header-with-value? headers name value) (let loop ((lst headers)) (cond ((null? lst) #f) ((and (equal? name (string-downcase (caar lst))) (equal? value (cdar lst))) #t) (else (loop (cdr lst)))))) ;;============================================================================== ;; HTTP server. (define* (sack-start! sack-application ;; The Sack application thunk to be invoked for every received HTTP request. ;; #f = Accept connections from localhost only (default set to this, for security). ;; "*" = Accept connections from anywhere ;; A local IP address can be specified e.g. "1.2.3.4" = Listen to connections made to that IP only. ;; This is of value on servers that have several IP:s ;; and you want to provide different servers on different IP:s. (server-address: #f) ;; = TCP port to listen on, integer. Note that the ports < 1024 generally require ;; administrator privileges to listen on. (port-number: 80) ;; #f = Use Gambit's default value (which is 128). (max-waiting-connections: #f) ;; #t = Create a Gambit thread for each HTTP connection, so that several HTTP requests can ;; be handled concurrently. ;; #f = Process only one HTTP connection at a time, in the HTTP server's thread. ;; Note that you need to disable keepalives completely for this to deliver. (threaded?: #t) ;; Integer, seconds that Sack waits for another HTTP request on a HTTP connection before considering ;; the HTTP connection to be inactive and closing it. (keep-alive-timeout: 15) ;; Upper limit of number of HTTP requests to process on one (keep-alive: default-http-connection-requests-roof) ;; HTTP connection. ;; IO timeout - if an IO operation takes longer than this, close HTTP connection. (timeout: 300) ;; Procedure invoked on IO error. (io-error-callback: (lambda (e error-specific-to-a-connection?) #f)) ;; Name passed to make-thread for HTTP server thread. ;; 'auto = Autogenerate a suitable name. (thread-name: 'auto) ;; "http" or "https". Use this scheme value in URI objects created. (uri-scheme: "http") ;; We accept #f as meaning |with-standard-primitives|, just not ;; to require any user of this lib that might want to pass this ;; value, to import io-primitives too. (use-io-primitives: #f) ;; Please see the "Primitives for server overload protection" (accept-block: #f) ;; header comments section for more info on these two. (on-connection: #f) ;; The time the server thread should sleep in case of an ECONNABORTED error etc. ;; The purpose with the sleep is to not cause an infinite loop in the exotic ;; case that we would get unending errors from the OS. We never saw this happen ;; in practice though. ;; ;; # sack-app exception handling related options ;; For these three variables, if set to 'default, the respective of the global variables ;; |sack-exception-on-exception-catch| ;; |sack-exception-print-caught-exception?| |sack-exception-print-max-head| |sack-exception-print-max-tail| ;; |sack-exception-on-exception-hook| ;; should be used instead, on the handling of the respective HTTP request. (tcp-server-read-error-sleep: 0.025) ;; = Either of: ;; #f = Don't catch exceptions, but let them ;; go to the thread system/REPL ;; 'exception = Catch exceptions ;; 'exception&continuation = Catch exceptions and continuations (on-exception-catch: 'default) ;; = Either of: ;; #t = Print out the full exception/&continuation/ caught. ;; 'only-exception = Print out the exception caught. ;; #f = Don't do a printout on exception (print-caught-exception?: 'default) (print-max-head: 'default) (print-max-tail: 'default) ;; = #f = no on exception hook, or ;; thunk taking the arguments (exception/continuation exception continuation). ;; thunk is only invoked if on-exception-catch above is set. ;; |exception/continuation| |continuation| are only set if |on-exception-catch| ;; is set to 'exception&continuation , otherwise they are #f. (on-exception-hook: 'default) ;; # Debugging related options ;; Create a will object to finalize connections, as a means to guarantee that |on-connection| ;; is invoked properly even if the sack-app aborts due to exception? ;; ;; That this function is disabable through this option gives the user the opportunity to ;; evaluate whether the will object in any way would happen to contribute to a bug such as ;; a memory leak or alike. ;; ;; This option is given only because use of |make-will| is so rare - in practice its use ;; has been working perfectly all the time and this option has not been needed at any point. (create-finalizer-will?: #t)) (let* ((server-port (open-tcp-server `(server-address: ,(or server-address "") port-number: ,port-number ,@(if max-waiting-connections `(backlog: ,max-waiting-connections) '()) ;; reuse-address: #t - this is the default setting, no need mention. ;; server-address: '#u8(127 0 0 1) ; on localhost interface only ;; The reason we use this encoding is because all header data is communicated ;; in this encoding anyhow. As for HTTP body content of the request or response, ;; those are passed in u8vector format anyhow. ;; ;; We use ISO-8859-1 to guarantee symmetry of |with-standard-primitives| of io-primitives ;; with any other io-primitives implementation such as that for HTTPS, which is to follow ;; io-primitives' convention of usign ISO-8859-1 also. char-encoding: ISO-8859-1))) (serve/perform (lambda (gambit-port) (sack-dbg "Got a connection, creating IO primitives instance.") (if use-io-primitives (io-primitives#with-io-primitives gambit-port keep-alive-timeout (lambda (io-primitives) ;; (monitor-for-memory-leakage io-primitives) ;; (set-timeout! connection keep-alive-timeout io-primitives) (sack-dbg "IO primitives created, going into serve-connection .") (serve-connection sack-application timeout io-primitives threaded? port-number uri-scheme keep-alive gambit-port on-exception-catch print-caught-exception? print-max-head print-max-tail on-exception-hook))) (with-standard-primitives gambit-port keep-alive-timeout (lambda (io-primitives) ;; (monitor-for-memory-leakage io-primitives) ;; (set-timeout! connection keep-alive-timeout io-primitives) (sack-dbg "IO primitives created, going into serve-connection .") (serve-connection sack-application timeout io-primitives threaded? port-number uri-scheme keep-alive gambit-port on-exception-catch print-caught-exception? print-max-head print-max-tail on-exception-hook)))) ;; = Thread result value 'terminated-normally)) (serve (lambda (gambit-port) ;; (with-exception/continuation-catcher ;; (lambda (e) ;; (io-error-callback e #t) ;; (list 'terminated-by-exception e)) ; Leaves thread termination message ;; (lambda () (serve/perform connection)) (serve/perform gambit-port))) ;; We put the central logics for the main thread's handling of an individual incoming HTTP connection ;; in a separate procedure, as to minimize the risk surface for bugs such as memory leaks. (deliver (lambda (connection) (define finalized-at-first-at-gc? #t) (define (finalize/do) (if sack-verbose-about-gc-time-finalization? (cond (finalized-at-first-at-gc? (sack-dbg-warn "XXX Connection " connection " finalized at first at GC time. (Thread " (current-thread) ".) XXX")) ((eq? sack-verbose-about-gc-time-finalization? 'all) (sack-dbg-warn "Connection " connection " finalized per the ordinary route. (Thread " (current-thread) ")")) ;; (else (sack-dbg-warn "debug: finalize/do invoked for connection " connection ". (Thread " (current-thread) ")")) ; Mere debug )) ;; (Currently the presence of on-connection is a condition for the creation ;; of this will and therefore no checking for that it's set is needed.) (on-connection monitoring-closure #f)) ; is-connect? = #f ;; We now have a newly accepted TCP connection |connection| to process. ;; ;; As processing |connection| may be (and generally is) done in a multithreaded fashion, ;; and we immediately after starting the processing thread get into an |accept-block| run if ;; it's specified and after it to accepting a new connection, then in order for the overload ;; protection primitives to work with integrity, we need to do any |on-connect| call here as ;; for it to be synchronous with the following |accept-block| call, so that it will block ;; or not in proper consideration of this new connection. ;; ;; Therefore: (define monitoring-closure (and on-connection ; Create it only if monitoring is actually going on. (lambda (operation) (case operation ((timeout-zero!) (error "timeout-zero! not implemented")) ;; Apart from providing a tap for debugging purposes, this procedure ;; enforces uniqueness of the closure - ;; If the closure closes over no variables post the compiler's optimization, ;; it returns one and the same closure always. ;; This one should be fixed by using a Gambit-provided best practice such as a (declare). ((connection) connection) ;; This would just add to our memory leak drama, let's save ourselves of that. ;; ; Debug tap of the finalization will. Could be used to check the finalization and GC:ing ;; ; status of a connection. ;; ((finalize-will) finalize-will) (else (error "Unknown operation" operation)))))) ;; Finalization work for the handling of this TCP connection must be done as for our app ;; not to get into an undefined state. For this purpose, we create a will that trigs on GC, ;; just in case this sack thread would fail to the REPL and be shut down in such a way that ;; it does not execute up to its ordinary termination point. ;; ;; In ordinary cases however, the will is finalized already below, by the |finalize| call - ;; this is done by direct finalization of this will. ;; ;; Create the will for finalizing the sack-app execution ;; only if the will have anything of relevance to do. (define finalize-will (and on-connection create-finalizer-will? ;; We set the TCP connection port (named gambit-port in other places) as ;; testator; its garbage collection is indeed a perfect indicator that ;; Sack's handling of the TCP connection it contains is indeed over. (make-will connection ;; action: (lambda (testator) ; = |connection| (finalize/do))))) (define (finalize) ;; Ordinary code path for finalization of TCP connection handling. ;; If finalize-will was created, finalize it, i.e. invoke the on-connect overload protection primitive ;; to tell it that this connection is now closed. ;; ;; It won't happen ever but just for reference, subsequent |will-execute!| invocations are noop:s. (if on-connection (begin (set! finalized-at-first-at-gc? #f) (if create-finalizer-will? (begin ;; (sack-dbg-warn "finalize: Doing (will-execute! finalize-will) to trig will finalization of finalize-will.") (will-execute! finalize-will)) (begin ;; (sack-dbg-warn "finalize: We have no will, so running finalize/do right away.") (finalize/do)))) ;; (sack-dbg-warn "finalize: on-connection not set, nothing to do.") )) ;; Remove when Gambit's make-will + will-execute! bug has been resolved. (if finalize-will (sack-dbg-warn "Will #" (object->serial-number finalize-will) " was created with " connection " as testator.")) ;; (monitor-for-memory-leakage connection) (if (not (port? connection)) (error "Internal inconsistency - connection not a port!" connection)) (if finalize-will (if (not (port? (will-testator finalize-will))) (error "Internal inconsistency - finalize-will's testator not a port!" finalize-will))) ;; (if finalize-will (monitor-for-memory-leakage finalize-will)) ;; If the on-connect overload protection primitive has been provided by the ;; Sack user, invoke it. (if on-connection (begin ;; (monitor-for-memory-leakage monitoring-closure) (on-connection monitoring-closure #t))) ; is-connect? = #t (if threaded? ;; Multithreaded mode. (let ((thread (make-thread (lambda () (let ((dummy-port (open-dummy))) (parameterize ((current-input-port dummy-port) (current-output-port dummy-port)) (sack-dbg "Got connection.") (let ((r (serve connection))) (finalize) r)))) '(http-server connection-handler-thread)))) ;; (monitor-for-memory-leakage thread) (thread-start! thread)) ;; Single-threaded mode. (begin (sack-dbg "Got connection.") (serve connection) (finalize))))) ;; A mutex that is unlocked when the server should quit. (quit-mutex (make-mutex))) (mutex-lock! quit-mutex) (thread-start! (let ((thunk (lambda () (let loop () ;; If the accept-block overload protection primitive has been provided by the ;; Sack user, invoke it. (if accept-block (accept-block)) ;; Read a new TCP connection from the server port. (let* ((connection ;; If it was not for the possibility of ECONNABORTED Software caused connection abort , ;; we could just read straight here, i.e. (read server-port) . ;; ;; Now that that may happen though, we need a failsafe method. ;; ;; As I got it, ECONNABORTED happens on certain systems such as OpenBSD because (let loop () (with-exception-catcher (lambda (e) (sack-dbg-warn "Reading from the HTTP server port gave exception, ignoring and resuming: " e) (thread-sleep! tcp-server-read-error-sleep) (loop)) (lambda () (let ((r (read server-port))) ;; One reason we check the type here, is that the connection is used as testator in ;; wills later, and if that testator is #f then the will never executes and thus ;; we'd get a memory leak. (if (not (port? r)) (error "Didn't get a port" r)) r)))))) ;; Do all the delivery work regarding this connection. (deliver connection) ;; Proceed with next connection, or terminate if server shutdown has been initiated. ;; ;; If the mutex is not locked, it means that we should quit. (if (not (mutex-lock! quit-mutex 0)) (loop)))))) (thread-name (if (eq? thread-name 'auto) `(http-server connection-listener-thread port: ,port-number) thread-name))) (if thread-name (make-thread thunk thread-name) (make-thread thunk)))) (lambda () (if (mutex-lock! quit-mutex 0) (error "Server has already quit (or is quitting)") (begin (mutex-unlock! quit-mutex) (close-port server-port)))))) ;;============================================================================== ;;!! Error functions. (define (show-error code str io-primitives) (display-crlf io-primitives "HTTP/1.1 " code " " (http-status-code code)) (display-header io-primitives `("Content-Length" . ,(string-length str))) (display-header io-primitives `("Content-Type" . "text/html; char-encoding=UTF-8")) (display-crlf io-primitives) ((io-primitives-display io-primitives) str) ((io-primitives-close-port io-primitives))) (define (method-not-implemented-error io-primitives) (show-error 501 "<html><head><title>501 Method Not Implemented</title></head>\n<body><h1>Method Not Implemented</h1></body></html>" io-primitives)) (define (internal-server-error io-primitives) (show-error 500 "<html><head><title>500 Internal Server Error</title></head>\n<body><h1>Internal Server Error</h1></body></html>" io-primitives)) (define (bad-request-error io-primitives) (show-error 400 "<html><head><title>400 Bad Request</title></head>\n<body><h1>Bad Request</h1></body></html>" io-primitives)) ;;------------------------------------------------------------------------------ ;; Sack functions. (define (make-environment threaded? uri request-method ;; Attributes is an alist of lowercase ;; header names and their values attributes gambit-port takeover-connection-thunk-set!) (sack-dbg "(make-environment): Invoked. attributes " attributes) (let* ((peer-socket-info (let ((d #f)) (lambda () (or d (begin (set! d (tcp-client-peer-socket-info gambit-port)) ;; If d is #f, it means that the HTTP TCP connection is closed. ;; ;; This is nothing unexpected and therefore we do not relate to it as an error state like ;; (if (not d) (error "tcp-client-peer-socket-info returned #f" gambit-port)) d))))) (client-ip/u8v (let ((d-retrieved? #f) (d #f)) (lambda () (if d-retrieved? d (let ((peer-socket-info (peer-socket-info))) (set! d (and peer-socket-info (socket-info-address peer-socket-info))) (set! d-retrieved? #t) d))))) (client-ip (let ((d-retrieved? #f) (d #f)) (lambda () ; Used to be (tcp-client-port-ip-string gambit-port) of (std net/tcpip) , ; Gambit provides this itself though. (if d-retrieved? d (let ((u (client-ip/u8v))) (define (join between args) (cond ((null? args) '()) ((null? (cdr args)) (list (car args))) (else `(,(car args) ,between ,@(join between (cdr args)))))) (set! d (and u (case (u8vector-length u) ((4) (append-strings (join "." (map number->string (u8vector->list u))))) (else (error "IP string serialization not implemented for IP type" u))))) (set! d-retrieved? #t) d)) ))) (headers (lambda* (name (only-first? #f)) (if (procedure? name) (for-each (lambda (pair) (name (car pair) (cdr pair))) attributes) (let ((r (map cdr (filter (lambda (pair) (equal? (car pair) name)) attributes)))) (if only-first? (and (not (null? r)) (car r)) r))))) (sack:body #f)) (lambda (name) (case name ;; Sack settings ((sack:version) sack-version) ((sack:single-thread?) (not threaded?)) ((sack:root) "") ; ??? Remove? ;; HTTP request information: ;; * HTTP connection peer information ((sack:peer-socket-info) (peer-socket-info)) ((sack:client-ip/u8v) (client-ip/u8v)) ((sack:client-ip) (client-ip)) ;; ;; * Request and header contents ((sack:request-method) request-method) ((sack:uri) uri) ((sack:headers) headers) ;; ;; * Body contents ;; The first call to sack:body is made by the internal |handle-sack-response| procedure. ;; It sets the sack:body variable to the right handler procedure, which is subsequently ;; returned on each call to 'sack:body . I.e., this code here is only like a trampoline ;; for the provision of that procedure. ((sack:body) (or sack:body (lambda (sack:body-to-set) (set! sack:body sack:body-to-set)))) ;; Other ((sack:takeover-connection-thunk-set!) takeover-connection-thunk-set!) (else #f))))) (define (handle-sack-response-headers io-primitives version code headers chunked-encoding? close-connection? has-close-header?) ;; Display headers (display-crlf io-primitives version " " code " " (http-status-code code)) (if (not (has-header? headers "date")) (display-header io-primitives `("Date" . ,(time->string (current-time))))) (if (and close-connection? (not has-close-header?)) (display-header io-primitives `("Connection" . "close"))) (display-headers io-primitives headers) ;; It's important that this header is sent after the other headers, ;; because they might contain other transfer encodings, and chunked ;; should always be the last one. (if chunked-encoding? (display-header io-primitives `("Transfer-Encoding" . "chunked"))) (display-crlf io-primitives) ((io-primitives-force-output io-primitives))) ;; HTTP request body reader procedure. ;; Invoked by |handle-sack-response|. ;; ;; The reading work is done in units of the read buffer or the HTTP chunk size, whichever is ;; smallest. The mechanism is structured in such a way that it can be invoked over and over. Here's ;; the convention: ;; ;; (make-sack-request-body-handler environment connection) ;; => ret ;; ;; ret = #f = nothing was read and there's nothing more to read ;; reader-thunk w args (data-thunk copying?), that when invoked, returns another ret. ;; (box reader-thunk) = same as the previos option, except, the data-thunk returned #f. ;; Note that |reader-thunk|:s are single-use. ;; ;; (This procedure was initially written in a format as to accomodate providing the reader user ;; with the newly read data as the return value of a procedure, this is why this procedure is ;; written as it is.) (define (make-sack-request-body-handler environment io-primitives) ;; Read incoming HTTP request body ;; (with-output-to-port console-output-port (lambda () (print "attributes=") (pp attributes))) (let* ( ;; (data-thunk ((environment 'sack:body))) (sack:headers (environment 'sack:headers)) (content-length (let ((v (sack:headers "content-length"))) ;; (with-output-to-port console-output-port (lambda () (print "Sack: v=") (write v) (print "\n"))) (and (not (null? v)) (string->number (car v))))) (chunked-encoding (let ((v (sack:headers "transfer-encoding"))) ;; (with-output-to-port console-output-port (lambda () (print "Sack: v=") (write v) (print "\n"))) (and (not (null? v)) (string-prefix? "chunked" (string-downcase (car v)))))) (buf-size 4096) (buf #f)) (define (init-buf!) (set! buf (make-u8vector buf-size))) (define (make-read-bytes bytes-left*) (lambda (data-thunk copying?) (let loop ((bytes-left bytes-left*) (data-thunk data-thunk) (copying? copying?)) (if (< 0 bytes-left) (let* ((bytes-to-read (min buf-size bytes-left)) (_tmp (sack-dbg "(make-sack-request-body-handler): Going into read " bytes-to-read " bytes.")) (bytes-read ((io-primitives-read-subu8vector io-primitives) buf 0 bytes-to-read bytes-to-read))) (sack-dbg "(make-sack-request-body-handler): Read " bytes-read " bytes.") (if (and bytes-read (< 0 bytes-read)) (begin (sack-dbg "(make-sack-request-body-handler): Read " bytes-read " bytes.") (let* ((false-response? (if data-thunk (not (if copying? (data-thunk (subu8vector buf 0 bytes-read)) (data-thunk buf bytes-read))) #f)) (continue (lambda (data-thunk copying?) (loop (- bytes-left bytes-read) data-thunk copying?)))) (if false-response? (box continue) continue))) #f)) #f)))) (sack-dbg "(make-sack-request-body-handler): Now into assigning handlers for reading request contents body." " chunked-encoding=" chunked-encoding ", content-length=" content-length) (cond ;; HTTP request has chunked encoding ;; (End of body is denoted by a zero-length chunk.) (chunked-encoding (sack-dbg "(make-sack-request-body-handler): Entered. Using chunked encoding so returning routine for reading that out.") (lambda (data-thunk copying?) (define read-line-until-crlf ((io-primitives-read-line-until-crlf io-primitives) #t)) ; return-partial-string? = #t ;; This makes it returns the string up to the point of EOF, if EOF is reached. (sack-dbg "(make-sack-request-body-handler): Decoding chunked encoding.") (init-buf!) (let loop ((data-thunk data-thunk) (copying? copying?)) (let* ((len-str (read-line-until-crlf)) (len (chunked-coding-read-hex len-str))) (if (and len ; If we got an invalid or empty len-str, treat this the same way as if the len value is zero, ; namely by going to the block below which returns #f. (not (zero? len))) (let ((read-bytes (make-read-bytes len))) (let read-bytes-loop ((data-thunk data-thunk) (copying? copying?) ) (sack-dbg "(make-sack-request-body-handler): Reading " len " bytes http chunk") (let ((k (read-bytes data-thunk copying?))) (if k (let ((boxed? (box? k))) (set! read-bytes (if boxed? (unbox k) k)) (if boxed? (box read-bytes-loop) read-bytes-loop)) ; (We return read-bytes-loop) (begin (read-line-until-crlf io-primitives) ; To read the CRLF that every chunk ends with. (loop data-thunk copying?)))))) (begin (sack-dbg "(make-sack-request-body-handler): Read all chunks, ending.") #f)))))) ;; HTTP request has Content-Length set (content-length (sack-dbg "(make-sack-request-body-handler): Entered. We know the content length, so returning routine for reading that out.") (if (not (zero? content-length)) ; No need to allocate buffer and do read op if length is zero (lambda (data-thunk copying?) (init-buf!) (sack-dbg "(make-sack-request-body-handler): Content-Length set to " content-length ", processing.") ((make-read-bytes content-length) data-thunk copying?)) #f)) ;; HTTP request has no Content-Length, but has Connection: Close ;; HTTP request has neither Content-Length nor Connection: Close ;; In this case we presume that there is no request body. (Presumably this is in accordance with the HTTP RFC?) (else (sack-dbg "(make-sack-request-body-handler): Entered. There's neither Content-Length nor Connection: Close nor " "Transfer-Encoding: Chunked, so presuming there's no request body, returning no handler.") #f) ;; There could be some HTTP 1.0 or 0.9 client we'd be missing form data from, that just send it after the headers ;; and then close the connection, without specifying Connection: Close or Content-Length. ) ;; Please note that the following code was written for this procedure when it had done all reading work already ;; up to here. Now it's rather event-based. So the following code could not be taken in use straight off now. ;; (let ((b1 (read-u8 connection)) (b2 (read-u8 connection))) ;; (if (not (and (memq b1 '(#\return #!eof)) (memq b2 '(#\newline #!eof)))) ;; (begin ;; (with-output-to-port console-output-port (lambda () (print "Sack: Invalid end of request, expected chars 0D 0A. ") ;; (write b1) (print " ") (write b2) (print "\n"))) ;; (error "Invalid end of " b1 b2)))) ;; ^ I think this is commented out because the error never happened again. In case it would though ;; and it's because of erratic behavior from the client, ; ;; (with-output-to-port console-output-port (lambda () (print "Sack: Finished any request contents processing for connection.\n"))) )) ;; This procedure handles a HTTP request within a HTTP connection. ;; It is invoked by |handle-request| of |serve-connection|. ;; ;; => keep-connection-alive? (define (handle-sack-response ;; The server's keep-alive setting, an integer saying how many more HTTP requests we allow to be ;; processed over this HTTP connection. keep-alive ;; Sack application thunk to invoke sack-application ;; Environment closure for HTTP request (generally used under the name |env| in Sack app thunks). environment ;; io-primitives for doing IO on the HTTP connection io-primitives ;; HTTP version symbol: 'HTTP/1.1 etc. version takeover-connection-thunk-get gambit-port) ;; We get here from handle-request of serve-connection . At this point, the HTTP request line and the request ;; headers have been read in full, and none of the body has been read. The process now is to invoke the Sack ;; application and get the response HTTP headers in full from it, and then output the headers and ;; the HTTP body based on the |response-thunk|'s return values, and by that the handling of this HTTP ;; request is done, with the exception for reading the HTTP request body. ;; This is done by invocation to the 'sack:body environment parameter. The sack application may ;; do this as for it to get the HTTP request body's contents. After all execution of the sack app ;; for this request, we also run 'sack:body from here to ensure complete drainage from the HTTP ;; connection port of the body, so that the connection is reset correctly for handling of any ;; subsequent HTTP request in the same connection. ;; At the end of the handling of this request i.e. at the bottom of this procedure, 'sack:body ;; for this request is blocked from any subsequent reading, so that just in case it'd be called ;; by the sack app after the processing of this request has finished (by another thread etc.) it ;; won't interfere with the handling of subsequent HTTP requests using the same connection. (define http-request-body-read (make-sack-request-body-handler environment io-primitives)) ;; sack:body for the sack-application works as follows: ;; ((environment 'sack:body) data-thunk #!key (copying? #t)) => reached-eof-wo-data-thunk-cancelling-by-returning-false? ;; If copying? is #t: data-thunk is a procedure that takes the arguments (u8v), where u8v is an ;; u8vector containing the most recently read block/chunk of data. Sack makes no further use of u8v. ;; If copying? is #f: data-thunk is a procedure that takes the arguments (u8v len), where u8v ;; is an u8vector whose len first bytes contain the most recently read block/chunk of data. The ;; data is guaranteed to be there up to and only up to that data-thunk returns. ;; ;; The read operation with sack:body per above returns when data-thunk returned #f or when the ;; request body has been fully read. ;; ;; sack:body returns #f if data-thunk returned #f, otherwise #t. (Other than this, its return value ;; is not affected by whether any data was actually read.) ;; ;; sack:body may be re-run at any time. If its previous return was because of end of data, ;; the new run will just return #f . If the previous return was because data-thunk returned #f, ;; the new sack:body run will continue reading right after the point the previous reading ended. (define sack:body (lambda* (data-thunk (copying?: #t)) (let loop () ;; If we reached the end already on the previous iteration, (if (not http-request-body-read) ;; Return #t to signal EOF. #t ;; Otherwise, ;; ;; (If http-request-body-read returned a box on the last iteration, then it was also unboxed ;; on the last iteration and we have it in procedure form ready to invoke here now.) ;; ;; Do another read operation, (and (let* ((n (http-request-body-read data-thunk copying?)) (boxed? (box? n))) (set! http-request-body-read (if boxed? (unbox n) n)) (not boxed?)) ; And if we reached EOF (reported as n = #f, which leads to boxed? = #f), or ;; we have more data to process (reported as n = a procedure, which leads to ;; boxed? = #f too) return #t, meaning that we should continue iterating. ;; ;; Otherwise (the only case left is:), the data-thunk returned #f (reported ;; as n = a box, which leads to boxed? = #t), return #f, meaning that the ;; iteration process is ended here and this #f becomes |sack:body|'s return value. (loop)))))) ((environment 'sack:body) sack:body) (sack-dbg "Into handle-sack-response. (version=" version ")") ;; Invoke handler (i.e. page generator) (call-with-values (lambda () (sack-application environment)) (lambda (code headers response-thunk) ;; code = integer = send this HTTP response ;; #f = close connection immediately ;; ;; headers = alist ;; ;; response-thunk = thunk = response data generator ;; #f = no response data (let* ((write-subu8vector (io-primitives-write-subu8vector io-primitives)) (write-response-body-verbatim (lambda () (let loop () (let ((chunk (and response-thunk (response-thunk)))) (if chunk (http-util#chunk-return-value->u8v&u8v-length chunk (write-subu8vector u8v 0 u8v-length) (loop))))))) (chunked-encoding? (and (not (has-header? headers "content-length")) (not (has-header-with-value? headers "transfer-encoding" "chunked")) ;; It seems that for web browsers to properly understand 304 Not Modified, we must not tell HTTP ;; response has chunked encoding because this is received as that new content is coming in. ;; ;; Due to the great similarity with 303 See Other and probably all 3xx status codes, ;; we treat all of them with this rule. ;; ;; (We add a first check here to see if code is set at all; if it's not we'll close the connection ;; right away and the chunked-encoding? value won't have any effect anyhow.) code (not (fx<= 300 code 399)))) (has-close-header? (has-header-with-value? headers "connection" "close")) (close-connection? (or (not code) (not (eq? 'HTTP/1.1 version)) (member "close" ((environment 'sack:headers) "connection")) has-close-header? (<= keep-alive 1)))) (if code ; code = #f means, don't write any data but just close the connection. (case version ((HTTP/1.1 HTTP/1.0) ;; Write HTTP response headers (handle-sack-response-headers io-primitives version code headers chunked-encoding? close-connection? has-close-header?) ;; Write HTTP response body (if (and (not (equal? "head" (environment 'sack:request-method))) (not (eq? 304 code))) (if chunked-encoding? (http-write-with-chunked-encoding io-primitives (and response-thunk (response-thunk)) ; first-chunk response-thunk) ; get-chunk (write-response-body-verbatim))) ;; If this is a keepalive connection then ensure that all HTTP request body contents available ;; have been read out. This is to ensure that on the start of processing of the next HTTP request ;; on the HTTP connection, we will start reading the HTTP request line at the correct place. (if (not close-connection?) (sack:body (lambda (u8v len) (void)) copying?: #f))) ;; HTTP 0.9, just dump the HTTP response body as one data block. (else (write-response-body-verbatim)))) (let ((keep-connection-alive? (not close-connection?))) ;; Takeover connection handling must be done here which is before the connection may be closed. ;; ;; Invoke |takeover-connection!-thunk|, if set (let ((takeover-connection-thunk (takeover-connection-thunk-get))) (if takeover-connection-thunk (begin ;; Set connection's timeout to indefinite - when here otherwise in the current implementaiton we have keep-alive or alike ;; set to timeout. This works as a solution for now. (input-port-timeout-set! gambit-port +inf.0 (lambda () ((io-primitives-close-port io-primitives)) #f)) (output-port-timeout-set! gambit-port +inf.0 (lambda () ((io-primitives-close-port io-primitives)) #f)) (if (not (takeover-connection-thunk io-primitives)) (set! keep-connection-alive? #f))))) ;; Was: ;; (if close-connection? ;; (close-port conn) ;; (force-output conn)) ;; ;; Just to ensure completely that the data is sent (I believe this is superfluous but let's keep it for now): ((io-primitives-force-output io-primitives)) (if close-connection? ((io-primitives-close-port io-primitives))) keep-connection-alive?))))) ;;------------------------------------------------------------------------------ ;;!! Low-level serving functions. (define version-table (make-token-table ("HTTP/1.0" 'HTTP/1.0) ("HTTP/1.1" 'HTTP/1.1))) ;; This procedure sets IO timeouts at the level of Gambit TCP port. ;; It's invoked by the HTTP TCP connection bootstrap code in |sack-start!|. ;; ;; ** Note: Currently this one overlaps timeout handlers already set by the io-primitives module. (define (set-timeout! connection timeout io-primitives) ;; Configure the connection with the client so that if we can't read ;; the request after [timeout] seconds, the read/write operation ;; will fail (and the thread will terminate). (input-port-timeout-set! connection timeout (lambda () (sack-dbg "Port timed out as there was no new data within the timeout period of " timeout " seconds, so closing connection now.") ; (close-port connection) ((io-primitives-close-port io-primitives)) #f)) ; Signals to Gambit that the operation that timed out should be cancelled. (output-port-timeout-set! connection timeout (lambda () (sack-dbg "Port timed out as no new data could be written within the timeout period of " timeout " seconds, so closing connection now.") ; (close-port connection) ((io-primitives-close-port io-primitives)) #f))) ; Signals to Gambit that the operation that timed out should be cancelled. (define (serve-connection sack-application timeout io-primitives threaded? port-number uri-scheme keep-alive gambit-port ; In here we pass it to |make-environment| only, for resolving client IP. on-exception-catch print-caught-exception? print-max-head print-max-tail on-exception-hook) (let reuse-connection ((keep-alive keep-alive)) (let ((req (((io-primitives-read-line-until-crlf io-primitives) #f)))) ; = return-partial-string? (sack-dbg "Got request: " req) (if (not req) ;; If HTTP connection closed before sending us any data, then just close the connection. ;; This happens for instance when a Keepalive connection is closed. #!void (begin ;; (with-output-to-port console-output-port (lambda () (print "Got HTTP req line: ") (write req) (print ".\n"))) ;; (set-timeout! connection timeout) - done by the connection bootstrack code in |sack-start!| now. ;; |set-timeout!| is specific to Gambit's IO system, that's the reason for keeping it out of |serve-connection|. (let* ((end (let loop ((i 0)) (cond ((= i (string-length req)) #f) ((char=? (string-ref req i) #\space) i) (else (loop (+ i 1)))))) (method-name (let ((m (and end (substring req 0 end)))) (if m (string-downcase! m)) ; (If there's no space in the method, m is #f.) ;; We don't reuse |req| anywhere so mutating it is fine, saves us of an object allocation. m))) (define takeover-connection-thunk #f) (define (takeover-connection-thunk-set! thunk) (set! takeover-connection-thunk thunk)) (define (takeover-connection-thunk-get) takeover-connection-thunk) ;; Invoked by |handle-version| below only. ;; Presuming that it finds the HTTP request satisfactorily correct, it invokes |handle-sack-response| defined in ;; the global namespace above for proceeding with handling the HTTP request. ;; ;; This procedure performs any ;; ;; => keep-connection-alive? (define (handle-request version attributes uri) ;; This procedure performs the actual operation of this procedure; below it is ;; its context code for doing this with the proper exception handling. (define (handle-request-do) ;; Add some more info to the uri object. This is ;; useful for the sack environment object. (let* ((host/port (let ((ret (assoc "host" attributes))) (and ret (cdr ret)))) (host+port (string-split-char #\: (or host/port "0.0.0.0")))) ; TODO: Mutate URI object port slots instead. (set! uri (uri-port-set uri (or (and (pair? (cdr host+port)) (string->number (cadr host+port))) port-number))) (set! uri (uri-host-set uri (car host+port))) (set! uri (uri-scheme-set uri uri-scheme))) ;; (with-output-to-port console-output-port (lambda () (print "Sack: Handles request " uri ".\n"))) ;; Create an environment closure. It is the core handling block for each HTTP request. ;; ;; It is passed on verbatim onto the Sack app thunk. ;; ;; Normally within a Sack app thunk, the environment goes under the variable name |env|. (let* ((environment (make-environment threaded? uri method-name attributes gambit-port takeover-connection-thunk-set!))) ;; Proceed with handling the HTTP request. (handle-sack-response keep-alive sack-application environment io-primitives version takeover-connection-thunk-get gambit-port))) ;; What exception handling and reporting behavior to apply here is directed by the following variables. (let* ((on-exception-catch (if (eq? on-exception-catch 'default) sack-exception-on-exception-catch on-exception-catch )) (print-caught-exception? (if (eq? print-caught-exception? 'default) sack-exception-print-caught-exception? print-caught-exception?)) (print-max-head (if (eq? print-max-head 'default) sack-exception-print-max-head print-max-head )) (print-max-tail (if (eq? print-max-tail 'default) sack-exception-print-max-tail print-max-tail )) (on-exception-hook (if (eq? on-exception-hook 'default) sack-exception-on-exception-hook on-exception-hook ))) ;; This procedure is invoked when there's been an exception during sack application execution. (define (handle-exception exception/continuation exception continuation) ;; # Print exception to console, if applicable (if print-caught-exception? ;; Gambit's IO primitives are now set not to throw any exceptions for the HTTP connection port, ;; so we should never get any exceptions related to it here. ;; ;; (if (and (os-exception? exception) ;; (let ((v (os-exception-arguments exception))) ;; (and (list? v) (>= (length v) 1) ;; (port? (car v)) ;; ; (eq? connection (car v)) - Now this new check is a bit arbitrary. Best would be if we ;; ; could make the Gambit IO routines not throw any exceptions. ;; ))) ;; ;; ; Typically this is a "Broken pipe" exception. Don't know exactly how ;; ; to typecheck for it though. ;; (print port: console-output-port ;; " #### Sack application crashed, most probably IO error from connection failure. " e "\n") (print port: console-output-port "\n\n #### Sack application crashed in thread " (current-thread) " with exception:\n" (if (and exception/continuation (eq? #t print-caught-exception?)) (exception/continuation->string exception/continuation #f ; = for-console #t ; = display-environment print-max-head print-max-tail) exception))) ;; # Send internal server error to connection ;; If we get an exception while doing that, ignore it. (with-exception-catcher (lambda (e) #t) (lambda () (internal-server-error io-primitives))) ;; # Call exception handling hook, if applicable ;; We sent the error message on the connection above just in case the hook invocation here would take time. ;; ;; We invoke the hook here *within the same execution scope* as the sack-app is ordinarily executed. ;; (And for instance, we don't start a separate thread for invoking the hook.) ;; The reason we do it like this, is that the hook invocation potentially can be expensive; it may ;; involves contacting a third party such as sending an email. Thus this way we save the hooks from needing ;; to have their own overload code, and from such overload logics from becoming overloaded. ;; This behavior makes perfect sense when put in relation with that exceptions should be extremely rare ;; anyhow. (if on-exception-hook (on-exception-hook exception/continuation exception continuation)) ;; # Close HTTP connection #f) ; keep-connection-alive? = #f ;; Do any exception catching at all? (case on-exception-catch ;; Yes, do exception & continuation catching ((exception&continuation) (with-exception/continuation-catcher (lambda (exception/continuation) (handle-exception exception/continuation (exception/continuation-exception exception/continuation) (exception/continuation-continuation exception/continuation))) handle-request-do)) ;; Yes, do exception catching ((exception) (with-exception-catcher (lambda (exception) (handle-exception #f ; exception/continuation exception #f)) ; continuation handle-request-do)) ;; Don't do any exception catching, ((#f) (handle-request-do)) (else (error "Invalid on-exception-catch value" on-exception-catch))))) ;; Invoked by request handling code below this define only. ;; On success, invokes |handle-request| defined above for proceeding with handling the HTTP request. ;; ;; Procedure to proceed with the handling of a HTTP request, given knowledge of the HTTP protocol ;; version number specified in the HTTP request. ;; ;; => keep-connection-alive? (define (handle-version version uri) (sack-dbg "Request uses HTTP version " version) (case version ;; HTTP 1.0 or 1.1 request ((HTTP/1.0 HTTP/1.1) (sack-dbg "Request is HTTP 1.0 or 1.1.") (let ((attributes (read-headers io-primitives))) ; Read headers. (sack-dbg "Loaded headers " attributes) (cond ;; If failed to read headers, fail. ((not attributes) (sack-dbg "Request contained no attributes, aborting.") (bad-request-error io-primitives) #f) ;; If is HTTP 1.1 request and has no Host: header, fail. ;; (It is essential for any HTTP 1.1 request to have a Host: header.) ((and (eq? 'HTTP/1.1 version) (not (has-header? attributes "host"))) (sack-dbg "Request is for HTTP/1.1 but has no \"host\" attribute, aborting.") (bad-request-error io-primitives) #f) ;; Proceed with handling request. (else (sack-dbg "Going into |handle-request|.") (handle-request version attributes uri))))) ;; HTTP 0.9 request ((#f) (sack-dbg "Treating HTTP request as being for HTTP/0.9, now going into |handle-request|.") (handle-request 'HTTP/0.9 '() ; headers - HTTP 0.9 does not support nor headers nor keepalives. ; Here thusly we specify an empty list of headers. uri)) ;; Invalid HTTP version specified, fail. (else (sack-dbg "HTTP version is " version ", unknown, aborting.") (bad-request-error io-primitives) #f))) (if method-name ;; So we got past parsing out the method field. Now, end + 1 is the string position at which the URL should start. ;; We ask |parse-uri| of the uri module to parse it out, and call us back with the URI object loaded and with the ;; index in the req string that the URI ended, as for us to know at what index + 1 the HTTP version description starts. (parse-uri req ; = str (+ end 1) ; = start (string-length req) ; = end #t ; = decode? (lambda (uri uri-end-at-string-index) (sack-dbg "Got URI object " uri ", uri-end-at-string-index=" uri-end-at-string-index) ;; Handle connection i.e. process the HTTP request fully and provide HTTP response fully. (let* ((keep-connection-alive? (cond ;; If no URI was provided in HTTP request (or was so extremely misformatted that parse-uri ;; wouldn't accept it), fail. ((not uri) (sack-dbg "parse-uri gave us #f for uri, must have been very broken.") (bad-request-error io-primitives) #f) ;; If the HTTP request lacks HTTP version, then it's a HTTP 0.9 request. ;; (For more info see http://stackoverflow.com/questions/6686261/what-at-the-bare-minimum-is-required-for-an-http-request ;; and the HTTP 1.0 RFC, 1945. ;; ;; HTTP 0.9 connections do not support nor headers nor keepalives. ((not (< uri-end-at-string-index (string-length req))) (handle-version #f ; version (#f = 0.9) uri)) ;; If the URI is not followed by a whitespace, fail. ((not (char=? (string-ref req uri-end-at-string-index) #\space)) (sack-dbg "No space after GET/POST+space+PATH part of HTTP request.") (bad-request-error io-primitives) #f) ;; A HTTP version was specified. This is the general usecase. (else (let ((version-index (token-table-lookup-substring version-table req (+ uri-end-at-string-index 1) (string-length req)))) (if version-index ;; Valid HTTP version specified, proceed with handling request. (let ((http-protocol-version-sy (vector-ref version-table (+ version-index 1)))) ; 'HTTP/1.1 etc. (handle-version http-protocol-version-sy uri)) ;; Invalid HTTP version specified, fail. (begin (sack-dbg "Bad HTTP version, tried to parse it out from " (string->list (substring req (+ uri-end-at-string-index 1) (string-length req))) ". (=index " (+ uri-end-at-string-index 1) " up to the end of the string, whose length is " (string-length req)) (bad-request-error io-primitives) #f))))))) ;; If this connection is to be kept alive, then simply reiterate this HTTP request handling procedure. ;; ;; (Subroutines determine if this is the case - essentially if the request is with HTTP 1.1 and does ;; not have a Connection: Close header set, then it will be kept alive.) (if keep-connection-alive? (reuse-connection (- keep-alive 1)))))) ;; Request line contained no method. This means it was a bad HTTP request. ;; At least for now, we always send a full HTTP response here, if not else then as to make clear ;; to the requestor that this is a web server. ;; (method-not-implemented-error io-primitives) (bad-request-error io-primitives))))))))
false
692a52b9bd566d0f9daae8833bb37fa085fa54e4
fb9a1b8f80516373ac709e2328dd50621b18aa1a
/ch3/3_Modularity_Objects_and_State.scm
505879f69440768188e23b1fdef57db7499aa906
[]
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
7,681
scm
3_Modularity_Objects_and_State.scm
;3章 標準部品 ;3.1 代入と局所状態 (define balance 100) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define new-withdraw (let ((balance 100)) (lambda (amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")))) ; (define (make-withdraw balance) (lambda (amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds"))) (define W1 (make-withdraw 100)) (define W2 (make-withdraw 100)) (W1 50) (W2 70) (W2 40) (W1 40) ; (define (make-account balance) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (begin (set! balance (+ balance amount)) balance)) (define (dispatch m) (cond ((eq? m 'withdraw) withdraw) ((eq? m 'deposit) deposit) (else (error "Unknown request -- MAKE-ACCOUNT" m)))) dispatch) (define acc (make-account 100)) ((acc 'withdraw) 50) ((acc 'withdraw) 60) ((acc 'deposit) 40) ((acc 'withdraw) 60) (define acc2 (make-account 100)) ;3.1.2 代入を取り入れた利点 ;乱数生成について ;http://sicp.g.hatena.ne.jp/hyuki/20060505/random (define (rand-update x) (define A 1103515245) (define B 12345) (define M 2147483647) (mod (+ (* A x) B) M)) (define random-init 8) (define rand (let ((x random-init)) (lambda () (set! x (rand-update x)) x))) (rand) (define (estimate-pi trials) (sqrt (/ 6 (monte-carlo trials cesaro-test)))) (define (cesaro-test) (= (gcd (rand) (rand)) 1)) (define (monte-carlo trials experiment) (define (iter trials-remaining trials-passed) (cond ((= trials-remaining 0) (/ trials-passed trials)) ((experiment) (iter (- trials-remaining 1) (+ trials-passed 1))) (else (iter (- trials-remaining 1) trials-passed)))) (iter trials 0)) (estimate-pi 10000) (define (estimate-pi trials) (sqrt (/ 6 (random-gcd-test trials random-init)))) (define (random-gcd-test trials initial-x) (define (iter trials-remaining trials-passed x) (let ((x1 (rand-update x))) (let ((x2 (rand-update x1))) (cond ((= trials-remaining 0) (/ trials-passed trials)) ((= (gcd x1 x2) 1) (iter (- trials-remaining 1) (+ trials-passed 1) x2)) (else (iter (- trials-remaining 1) trials-passed x2)))))) (iter trials 0 initial-x)) ;========== ;3.1.3 代入を取り入れた代償 ;; set!により、局所状態を持ったオブジェクトがモデル化できた。 ;; ただし、その代償として、手続きの置き換えモデルを使った解釈を失った。 ;; また、参照透明であることも失い、オブジェクトが同一かそうでないかの判断が難しくなった。 ;2章でやったような代入を伴わないプログラミングは関数型プログラミングという ;代入が話を難しくしている例 3.1.1のmake-withdraw手続きの簡易版 (define (make-simplified-withdraw balance) (lambda (amount) (set! balance (- balance amount)) balance)) (define W (make-simplified-withdraw 25)) (W 20) (W 10) ;setを使わないmake-decrementer手続き(をmake-withdrawと比べる) (define (make-decrementer balance) (lambda (amount) (- balance amount))) (define D (make-decrementer 25)) (D 20) ;; 5 (D 10) ;; 15 ;置き換えモデルを使ったmake-decrementerの働きの説明 ((make-decrementer 25) 20) ((lambda (amount) (- 25 amount)) 20) (- 25 20) ;同様にmake-simpified-withdrawを置き換えモデルにしてみる ((make-simplified-withdraw 25) 20) ;make-simplified-withdraw中のbalanceを25に置き換える ((lambda (amount) (set! balance (- 25 amount)) 25) 20) ;lambda式中のamountを20で置き換える (set! balance (- 25 20)) 25 ;balanceに5をセットしたあとに25を返す? ;今までの考え方では、変数とは値に対する名前であった。 ;変数の値は変わりうる、という考えを取り入れると変数は単なる値の名前ではなくなる。 ;変数は値が格納される場所を指す。その場所に格納される値は変わりうる。 ;========== ;同一と変化 ;; 2つのものは「同じ」であるということについて考える (define D1 (make-decrementer 25)) (define D2 (make-decrementer 25)) ;D1とD2は同じ ;; W1とW2は同じ? (define W1 (make-simplified-withdraw 25)) (define W2 (make-simplified-withdraw 25)) (W1 20) (W1 20) (W2 20) ;任意の式でW1をW2で置き換えることはできない ;(W1 20)と(W2 20)で結果が違う。 ;W1とW2は別物である ;"式の評価結果を変えずに、式中のものをそれと等しいもので置き換えることができる"言語は ;参照透明(referentially transparent)である ;他のスレッドが値を書き換えることがある(3.4 ;参照透明を捨てたとき、"同じ"とはどういう意味なのだろうか ;同じように見える2つのオブジェクトについて、一方を変えてみてもう一方も同じように変わるかを見て決める。 ;変化を観測しないことには同一性を確かめることはできない ;p130 (define peter-acc (make-account 100)) (define paul-acc (make-account 100)) ((paul-acc 'withdraw) 60) ((peter-acc 'withdraw) 60) (define peter-acc (make-account 100)) (define paul-acc peter-acc) ((paul-acc 'withdraw) 60) ((peter-acc 'withdraw) 60) ;上の例ではpeter-accとpaul-accは別もの ;下の例では両者は同じもの ;このような状況は計算モデルの構築に混乱をもたらす。 ;paul-accが変えられている場所を探すには、peter-accが変えられている場所も探さなくてはいけない ;オブジェクトに状態の概念を取り入れることで、話は複雑になる。 ;払い出しをして残高が変わる同じ銀行口座 ;同じ状態の異なる2つの銀行口座 ;========== ;命令形プログラムの落とし穴 ;代入を多用するプログラミングは命令形プログラミングという ;計算モデルの複雑性を高める上に、命令形の流儀で書いたプログラムには、関数型プログラムには起こりえぬ虫を入れ易い ;1.2.1節の反復的な階乗プログラム (define (factorial n) (define (iter product counter) (if (> counter n) product (iter (* counter product) (+ counter 1)))) (iter 1 1)) (factorial 5) ;代入を使って書きなおしたfactorial (define (factorial n) (let ((product 1) (counter 1)) (define (iter) (if (> counter n) product (begin (set! counter (+ counter 1)) (set! product (* counter product)) ; (begin (set! product (* counter product)) ; (set! counter (+ counter 1)) (iter)))) (iter))) (factorial 5) ;うっかり順番を間違えると大変なことになる ;こういうことは関数型プログラミングにはない ;「この変数の設定をあの前にすべきか、あとにすべきか」という問題は、初心者プログラマの負担になっている ;複数のプロセスが並列に走る状況を考えるともっと大変なことになる(3.4節)
false
284aed1ae944e9f7ef5ecf60771c4a3443b6f9d9
a189a23c6841ac05c4f729484bea5f33abe238ab
/student/lang/church.scm
4a81749cf3f673d2527b26ee65804aa44120dfbb
[]
no_license
langmartin/hackrec
5129ede644b3eedd76f54350d9df87c241c1c0db
7ba3dd05bc54c42a9e3bdb6e86745c7b9f96a610
refs/heads/master
2020-05-21T13:10:03.274157
2012-04-05T15:14:38
2012-04-05T15:14:38
2,925,866
0
0
null
null
null
null
UTF-8
Scheme
false
false
892
scm
church.scm
(define zero (lambda (f) (lambda (x) x))) (define (add1 n) (lambda (f) (lambda (x) (f ((n f) x))))) (define one (lambda (f) (lambda (x) (f (((lambda (f) (lambda (x) x)) f) x))))) (define one (lambda (f) (lambda (x) (f x)))) (define two (lambda (f) (lambda (x) (f (((lambda (f) (lambda (x) (f x))) f) x))))) (define two (lambda (f) (lambda (x) (f (f x))))) (define (plus n n2) (lambda (f) (lambda (x) ((n f) ((n2 f) x))))) (define (mult n n2) (lambda (f) (lambda (x) ((n (lambda (f) (lambda (x) (mult n (minus n2 one))))) x)))) (define (square x) (* x x)) (define (dot x) (display ".")) ((two dot) '()) (newline) (((plus one two) dot) '()) (newline) ((one square) 2) ((two square) 2) (((plus two one) square) 2)
false
161fce6642f874c60e860efa3800c6c0201fa32d
8a35b05e66cb6a326198efb1336bc05d583e4406
/Sources/LispKit/Resources/Libraries/lispkit/test.sld
53eb8a7b2ea27781b53cb7720a01a7d8babc688a
[ "Apache-2.0" ]
permissive
QuantumGhost/swift-lispkit
0c0bcbb4c88f757686263ed6744160453a99012f
bb8e680882e2011212c4129a54a250fa7c5af1c4
refs/heads/master
2020-03-16T14:20:16.751370
2018-05-05T23:03:41
2018-05-05T23:03:41
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
7,739
sld
test.sld
;;; LISPKIT TEST ;;; ;;; Simple framework for implementing and running simple test suites. This is derived from ;;; similar, but much more sophisticated facilities from Chicken and Chibi scheme. ;;; ;;; Some of this code was originally implemented by Alex Shinn for his matching library. ;;; Copyright © 2010-2014 Alex Shinn. All rights reserved. ;;; BSD-style license: http://synthcode.com/license.txt ;;; ;;; Author: Matthias Zenger ;;; Copyright © 2018 Matthias Zenger. All rights reserved. ;;; ;;; Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file ;;; except in compliance with the License. You may obtain a copy of the License at ;;; ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; ;;; Unless required by applicable law or agreed to in writing, software distributed under the ;;; License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, ;;; either express or implied. See the License for the specific language governing permissions ;;; and limitations under the License. (define-library (lispkit test) (export test-begin test-end test-failures test test-equal test-assert test-error test-group approx-equal?) (import (lispkit base)) (begin (define tests-passed 0) (define tests-failed 0) (define tests-start-time 0) (define internal-fail-token (gensym)) (define (test-begin) (set! tests-passed 0) (set! tests-failed 0) (set! tests-start-time (current-second))) (define (test-end) (let ((end (current-second)) (total (+ tests-passed tests-failed))) (newline) (display "║ ") (display total) (display " tests completed in ") (display (format-float (inexact (/ (- end tests-start-time) 1000)) 3)) (display " seconds") (newline) (display "║ ") (display tests-passed) (display " (") (display (format-percent tests-passed total)) (display "%) tests passed") (newline) (display "║ ") (display tests-failed) (display " (") (display (format-percent tests-failed total)) (display "%) tests failed") (newline))) (define (test-failures) tests-failed) (define (format-result spec name expect result) (do ((ls spec (cdr ls))) ((null? ls) (newline)) (cond ((eq? (car ls) 'expect) (write expect)) ((eq? (car ls) 'result) (write result)) ((eq? (car ls) 'name) (if name (begin (display #\space) (display name)))) (else (display (car ls)))))) (define (format-float n prec) (let* ((str (number->string n)) (len (string-length str))) (let lp ((i (- len 1))) (cond ((negative? i) (string-append str "." (make-string prec #\0))) ((eqv? #\. (string-ref str i)) (let ((diff (+ 1 (- prec (- len i))))) (cond ((positive? diff) (string-append str (make-string diff #\0))) ((negative? diff) (substring str 0 (+ i prec 1))) (else str)))) (else (lp (- i 1))))))) (define (format-percent num denom) (let ((x (if (zero? denom) num (inexact (/ num denom))))) (format-float (* 100 x) 2))) (define (run-test name thunk expect eq pass-msg fail-msg) (let ((result (thunk))) (cond ((eq expect result) (set! tests-passed (+ tests-passed 1)) (format-result pass-msg name expect result)) (else (set! tests-failed (+ tests-failed 1)) (format-result fail-msg name expect result))))) (define (run-equal name thunk expect eq) (run-test name thunk expect eq '("[PASS]" name) (if (eq? expect #t) '("[FAIL]" name ": received " result) '("[FAIL]" name ": expected " expect " but received " result)))) (define-syntax test (syntax-rules (quote) ((_ expect expr) (test (write-to-string 'expr) expect expr)) ((_ name expect (expr ...)) (test-equal name expect (expr ...) equal?)) ((_ name (quote expect) expr) (test-equal name (quote expect) expr equal?)) ((_ name (expect ...) expr) (syntax-error "the test expression should come last: (test <expected> (<expr> ...))" '(test name (expect ...) expr))) ((_ name expect expr) (test-equal name expect expr equal?)) ((_ a ...) (syntax-error "a test requires 2 or 3 arguments" '(test a ...))))) (define-syntax test-equal (syntax-rules () ((_ name value expr eq) (run-equal name (lambda () expr) value eq)) ((_ name value expr) (run-equal name (lambda () expr) value equal?)) ((_ value expr) (test-equal (write-to-string 'expr) value expr)))) (define-syntax test-assert (syntax-rules () ((_ name expr) (run-equal name (lambda () (if expr #t #f)) #t eq?)) ((_ expr) (test-assert (write-to-string 'expr) expr)))) (define-syntax test-error (syntax-rules () ((_ name expr) (run-equal name (lambda () (guard (e (#t internal-fail-token)) expr)) internal-fail-token eq?)) ((_ expr) (test-error (write-to-string 'expr) expr)))) (define-syntax test-group (syntax-rules () ((_ name body ...) (begin (newline) (display name) (display ":") (newline) body ...)))) (define (approx-equal? a b epsilon) (cond ((> (abs a) (abs b)) (approx-equal? b a epsilon)) ((zero? a) (< (abs b) epsilon)) (else (< (abs (/ (- a b) b)) epsilon)))) (define (call-with-output-string proc) (let ((out (open-output-string))) (proc out) (get-output-string out))) (define (write-to-string x) (call-with-output-string (lambda (out) (let wr ((x x)) (if (pair? x) (cond ((and (symbol? (car x)) (pair? (cdr x)) (null? (cddr x)) (assq (car x) '((quote . "'") (quasiquote . "`") (unquote . ",") (unquote-splicing . ",@")))) => (lambda (s) (display (cdr s) out) (wr (cadr x)))) (else (display "(" out) (wr (car x)) (let lp ((ls (cdr x))) (cond ((pair? ls) (display " " out) (wr (car ls)) (lp (cdr ls))) ((not (null? ls)) (display " . " out) (write ls out)))) (display ")" out))) (write x out)))))) (define (display-to-string x) (if (string? x) x (call-with-output-string (lambda (out) (display x out))))) ) )
true
ac57e80dd0c04e018a4f28eb1b33886d587989af
52b0b749db0b7fb7a4ec1a8b78c5b6a0208bf1b5
/spiffy-request-vars.release-info
48b871e41aba95d3074b8670694a23f09c97bd86
[]
no_license
mario-goulart/spiffy-request-vars
9802c50847d391f1a1d79cbda012c4b6d5962ff7
659b7536f7f5ed3ead0e7c6e8b73926f7ad8afb5
refs/heads/master
2021-01-19T08:12:22.368118
2018-08-24T19:30:05
2018-08-24T19:30:05
9,183,358
1
0
null
null
null
null
UTF-8
Scheme
false
false
615
spiffy-request-vars.release-info
;; -*- scheme -*- (repo git "git://github.com/mario-goulart/{egg-name}.git") (uri targz "https://github.com/mario-goulart/{egg-name}/tarball/{egg-release}") (uri files-list "http://code.call-cc.org/files-list?egg={egg-name};egg-release={egg-release}" old-uri) (release "0.5" old-uri) (release "0.6" old-uri) (release "0.7" old-uri) (release "0.8" old-uri) (release "0.9" old-uri) (release "0.10" old-uri) (release "0.11" old-uri) (release "0.12" old-uri) (release "0.13" old-uri) (release "0.14" old-uri) (release "0.15" old-uri) (release "0.16" old-uri) (release "0.17" old-uri) (release "0.18") (release "0.19")
false
2cdd72139fe8c4c67b3f93189846e65d8e5df5c9
edffd423fdbef93bc8d44cdd7ae285a3558ef6de
/tests/learning-test.scm
3c806a02851e4a712f9f84c8278022570f0e4d60
[ "MIT" ]
permissive
massimo-nocentini/on-scheme
7983c219f5a9f82c2bda20f71c83ef4a2366dd4a
ebf590978c9ec8f34c9d4be9ce99ff406d72de44
refs/heads/master
2021-01-17T12:53:18.806547
2019-01-30T08:52:59
2019-01-30T08:52:59
58,215,388
0
0
null
null
null
null
UTF-8
Scheme
false
false
11,923
scm
learning-test.scm
(import scheme (chicken base) (chicken port) (chicken sort)) (import srfi-1 srfi-13 srfi-69) (import test matchable) (import commons) (test-group "DELAY-FORCE" (test-assert (promise? (delay (+ 3 4)))) (test-assert (promise? (delay-force (+ 3 4)))) (letrec ((stream-filter/tailcall (lambda (p? s) (delay-force (let ((s-mature (force s))) (if (null? s-mature) (delay '()) (let-values (((h t) (car+cdr s-mature))) (if (p? h) (delay (cons h (stream-filter/tailcall p? t))) (stream-filter/tailcall p? t)))))))) (stream-filter/stackfull (lambda (p? s) ; very inefficient version that uses unbounded memory because of (delay (force ...)) (delay (force (let ((s-mature (force s))) (if (null? s-mature) (delay '()) (let-values (((h t) (car+cdr s-mature))) (if (p? h) (delay (cons h (stream-filter/stackfull p? t))) (stream-filter/stackfull p? t))))))))) (from (lambda (n) (delay-force (cons n (from (+ n 1)))))) (large-number 10000)) (test large-number (car (force (stream-filter/tailcall (lambda (n) (= n large-number)) (from 0)))))) (test-assert (procedure? (force (λ () 3)))) (test '3 (force (make-promise 3))) ) (test-group "BOOLEANS" (test 'fail (if #f 'succeed 'fail)) (test 'succeed (if '() 'succeed 'fail)) (test 'succeed (if `(,#f ,#f) 'succeed 'fail)) (test 'else (cond ((and #t #f) => (lambda (y) #t)) (else 'else))) ) (test-group "HASH TABLE" (let ((H (make-hash-table))) (hash-table-set! H 'hello 'world) (test #t (hash-table-exists? H 'hello))) (let ((H (make-hash-table))) (hash-table-set! H 'hello 'world) (hash-table-set! H 'hello 'new-world) (test 'new-world (hash-table-ref H 'hello))) (test '(3 4 5) (sort (hash-table-fold (alist->hash-table '((a . 3) (b . 4) (c . 5))) (lambda (k v acc) (cons v acc)) '()) <)) ) (test-group "MATCHABLE" (test "multiple matches" 10 (match '(1 2 2 2 2 2 3) ((1 x ... 3) (apply + x)))) (test "multiple matches, literal" 2 (match '(1 1 1 1 1 2 3) ((1 ... x 3) x))) (test "match inside a string" 8 (match '(1 2 3) ((1 x 3) (* x x x)))) (test "declarative" 8 (let ((x 3)) (match '(1 3 2 3) ((1 x y 3) (* y y y))))) (test "declarative SHOULD RISE AN ERROR" 8 (let ((x 4)) (match '(1 3 2 3) ((1 x y 3) (* y y y))))) (test "matching with a quote in pattern" 'a-match (match '(1 x 3) ((1 'x 3) 'a-match))) (test "matching a quoted symbol" 'x (match '(1 x 3) ((1 y 3) y))) (test '(b c) (match '(a b c) (('a x ...) x))) (test 'else (match '(a b c) (('b x ...) x) (else 'else))) (test '(λ (b c) d) (let₁ (l '(a (b c) d)) (match l (('a (x ...) y) `(λ (,@x) ,y))))) ) (test-group "OUTPUT PORTS" (let* ((str-port (open-output-string)) (result (with-output-to-port str-port (lambda () (display "hello world") "succeed")))) (test "hello world" (get-output-string str-port)) (test "succeed" result)) (call+stdout (lambda () (display "hello world") ; to be redirected into a collecting string '(hello world)) ; to be used as return value (lambda (r s) (test-assert (and (equal? '(hello world) r) (equal? "hello world" s))))) (test "succeed" (with-output-to-string (lambda () (display 'succeed) #t))) ; `with-output-to-string` discards the return value (test "hello-world" (call-with-output-string (lambda (port) (display 'hello-world port) #t))) ; `call-with-output-string` discards the return value ) (test-group "MAPPING" (test '(hello world) (call-with-values (λ () (values 'hello 'world)) identity*)) (test 'succeed (values 'succeed)) (test 'fail (values 'fail 'succeed)) (test '(1 2 3) (map (lambda (i) (values (add1 i) i)) '(0 1 2))) ; this produces a warning: "expected a single result in argument #1 of procedure call `(cons (g2272 (##sys#slot g2278 0)) (quote ()))', but received 2 results" (test '(1 2 3) ((map/call-with-values (lambda (i) (values (add1 i) i)) (lambda (more less) more)) '(0 1 2))) (test '((1 1) (3 3)) ((map/values (lambda (p) (values (add1 (car p)) (cadr p)))) '((0 1) (2 3)))) (test #t ((tuple/pred? <) '(1 2) '(2 3) '(3 4))) (test #f ((tuple/pred? <) '(1 5) '(2 3) '(3 4))) (test #f ((tuple/pred? <) '(1 5) '(2) '(3 4))) (test '(a b c d e) (remove-duplicates (reverse '(a b c d e)))) (test '(e c d a b) (remove-duplicates '(a b a a c d c e e))) ) (test-group "TABLING" (define F (lambda (i) (cond ((< i 2) i) (else (+ (F (- i 1)) (F (- i 2))))))) (test 0 (F 0)) (test 1 (F 1)) (test '(0 1 1 2 3 5 8 13 21) (map F (iota 9))) (time (test 1346269 (F 31))) ; 0.574s CPU time, 0.007s GC time (major), 17/6 mutations (total/tracked), 14/5606 GCs (major/minor), maximum live heap: 377.59 KiB (define-tabled F₀ (lambda (i) (cond ((zero? i) 0) ((one? i) 1) (else (+ (F₀ (- i 1)) (F₀ (- i 2))))))) (test 0 (F₀ 0)) (test 1 (F₀ 1)) (test '(0 1 1 2 3 5 8 13 21) (map F₀ (iota 9))) (time (test 1346269 (F₀ 31))) ; 0s CPU time, 40/29 mutations (total/tracked), maximum live heap: 381.21 KiB (define fibonacci (letrec ((F (lambda (i) (cond ((< i 2) i) (else (+ (F (- i 1)) (F (- i 2)))))))) (memoize F))) (time (test 354224848179261915075 (fibonacci 100))) ; 0.001s CPU time, 117/106 mutations (total/tracked), 0/1 GCs (major/minor), maximum live heap: 391.37 KiB (define F₁ (memoize (lambda (i) (cond ((< i 2) i) (else (+ (F₁ (- i 1)) (F₁ (- i 2)))))))) (time (test 1346269 (F₁ 31))) ; 0.574s CPU time, 0.011s GC time (major), 17/6 mutations (total/tracked), 15/5605 GCs (major/minor), maximum live heap: 392.62 KiB (define-tabled pascal (lambda (n k) (cond ((and (zero? n) (zero? k)) 1) ((zero? n) 0) ((zero? k) (pascal (sub1 n) 0)) (else (+ (pascal (sub1 n) (sub1 k)) (pascal (sub1 n) k)))))) (test 1 (pascal 0 0)) (test 2 (pascal 2 1)) (test 1 (pascal 2 2)) (test 3 (pascal 3 2)) (test 100891344545564193334812497256 (pascal 100 50)) (define-tabled catalan (lambda (n k) (cond ((and (zero? n) (zero? k)) 1) ((zero? n) 0) ((zero? k) (apply + (map (lambda (j) (catalan (sub1 n) j)) (iota n)))) (else (apply + (map (lambda (j) (catalan (sub1 n) j)) (iota n (sub1 k)))))))) (define Riordan-array (lambda (recurrence) (lambda (m) (map (lambda (n) (append-map (lambda (k) (list (recurrence n k))) (iota (add1 n)))) (iota m))))) (test '((1) (1 1) (1 2 1) (1 3 3 1) (1 4 6 4 1) (1 5 10 10 5 1) (1 6 15 20 15 6 1) (1 7 21 35 35 21 7 1) (1 8 28 56 70 56 28 8 1) (1 9 36 84 126 126 84 36 9 1) (1 10 45 120 210 252 210 120 45 10 1) (1 11 55 165 330 462 462 330 165 55 11 1) (1 12 66 220 495 792 924 792 495 220 66 12 1) (1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1) (1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1) (1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1) (1 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 1) (1 17 136 680 2380 6188 12376 19448 24310 24310 19448 12376 6188 2380 680 136 17 1) (1 18 153 816 3060 8568 18564 31824 43758 48620 43758 31824 18564 8568 3060 816 153 18 1) (1 19 171 969 3876 11628 27132 50388 75582 92378 92378 75582 50388 27132 11628 3876 969 171 19 1)) ((Riordan-array pascal) 20)) (test '((1) (1 1) (2 2 1) (5 5 3 1) (14 14 9 4 1) (42 42 28 14 5 1) (132 132 90 48 20 6 1) (429 429 297 165 75 27 7 1) (1430 1430 1001 572 275 110 35 8 1) (4862 4862 3432 2002 1001 429 154 44 9 1) (16796 16796 11934 7072 3640 1638 637 208 54 10 1) (58786 58786 41990 25194 13260 6188 2548 910 273 65 11 1) (208012 208012 149226 90440 48450 23256 9996 3808 1260 350 77 12 1) (742900 742900 534888 326876 177650 87210 38760 15504 5508 1700 440 90 13 1) (2674440 2674440 1931540 1188640 653752 326876 149226 62016 23256 7752 2244 544 104 14 1) (9694845 9694845 7020405 4345965 2414425 1225785 572033 245157 95931 33915 10659 2907 663 119 15 1) (35357670 35357670 25662825 15967980 8947575 4601610 2187185 961400 389367 144210 48279 14364 3705 798 135 16 1) (129644790 129644790 94287120 58929450 33266625 17298645 8351070 3749460 1562275 600875 211508 67298 19019 4655 950 152 17 1) (477638700 477638700 347993910 218349120 124062000 65132550 31865925 14567280 6216210 2466750 904475 303600 92092 24794 5775 1120 170 18 1) (1767263190 1767263190 1289624490 811985790 463991880 245642760 121580760 56448210 24582285 10015005 3798795 1332045 427570 123970 31878 7084 1309 189 19 1)) ((Riordan-array catalan) 20)) (define-tabled ackermann (lambda (m n) (cond ((zero? m) (add1 n)) ((zero? n) (ackermann (sub1 m) 1)) (else (ackermann (sub1 m) (ackermann m (sub1 n))))))) (test 7 (ackermann 2 2)) (test 125 (ackermann 3 4)) ) (define-syntax add-key-args (syntax-rules () ((_ name) (define name (lambda (#!key (hello 0)) (add1 hello)))))) (add-key-args f) (define g (lambda (#!key (hello 0)) (add1 hello))) (test 1 (f)) (test 4 (f hello: 3)) (test 1 (f hello₁: 3)) (test-error (identity 0 hello: 3)) (test 1 (g)) (test 4 (g hello: 3)) (test 1 (g hello₁: 3)) #;(define-syntax d/τ (syntax-rules () ((d/τ name) (display 'name)))) #;(define-syntax define/τ (syntax-rules () ((define/τ name) (begin-for-syntax (let* ((name/1 (symbol-append 'name '/1)) (name/H (symbol-append 'name '/H))) (define-values (name/1 name/H) (values 1 2))))))) #;(d/τ hello) #;(define/τ my) #;(format #t "~a ~a" (my/1 4) (my/h)) (let₁ (x 4) (test-error (eval 'x))) (test-exit)
true
6ca28bbd8471b62b255a5249010773439d303e31
bcfa2397f02d5afa93f4f53c0b0a98c204caafc1
/scheme/chapter2/ex2_06_test.scm
96d6dce2de7efd921573e3a2793a015c83cac653
[]
no_license
rahulkumar96/sicp-study
ec4aa6e1076b46c47dbc7a678ac88e757191c209
4dcd1e1eb607aa1e32277e1c232a321c5de9c0f0
refs/heads/master
2020-12-03T00:37:39.576611
2017-07-05T12:58:48
2017-07-05T12:58:48
96,050,670
0
0
null
2017-07-02T21:46:09
2017-07-02T21:46:09
null
UTF-8
Scheme
false
false
389
scm
ex2_06_test.scm
;; SICP 2.6 tests (test-case "Ex 2.6 numbers" (let ((inc (lambda (n) (+ 1 n)))) (assert-equal 0 ((zero inc) 0)) (assert-equal 1 ((one inc) 0)) (assert-equal 2 ((two inc) 0)))) (test-case "Ex 2.6 Addition" (let ((inc (lambda (n) (+ 1 n))) (three (add one two))) (assert-equal 3 ((three inc) 0))))
false
1ba11dea5e65dd6aafbdc1b0ddc254fe7a4b08a2
37245ece3c767e9434a93a01c2137106e2d58b2a
/src/scheme/r5rs.scm
755a6e1e87f3ae0c878bafe6e3fe24406831aa82
[ "MIT" ]
permissive
mnieper/unsyntax
7ef93a1fff30f20a2c3341156c719f6313341216
144772eeef4a812dd79515b67010d33ad2e7e890
refs/heads/master
2023-07-22T19:13:48.602312
2021-09-01T11:15:54
2021-09-01T11:15:54
296,947,908
12
0
null
null
null
null
UTF-8
Scheme
false
false
2,038
scm
r5rs.scm
;; Copyright © Marc Nieper-Wißkirchen (2020). ;; This file is part of unsyntax. ;; 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 (including the ;; next paragraph) 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. (define (null-environment version) (unless (and (exact-integer? version) (= 5 version)) (raise-error 'null-environment "unsupported null environment version ‘~a’" version)) (environment '(only (scheme base) ... => _ and begin case cond define define-syntax do else if lambda let let* let-syntax letrec letrec-syntax or quasiquote quote set! syntax-rules) '(only (scheme lazy) delay))) (define (scheme-report-environment version) (unless (and (exact-integer? version) (= 5 version)) (raise-error 'scheme-report-environment "unsupported Scheme report environment version ‘~a’" version)) (environment '(scheme r5rs)))
true
1bea58a3fdbabf2a7f588cd7985c60068c56b581
140a499a12332fa8b77fb738463ef58de56f6cb9
/worlds/core/verbcode/137/render-partial-0.scm
fa2fc0ddee31eda813cfcf8dcbde6c7010bbc31e
[ "MIT" ]
permissive
sid-code/nmoo
2a5546621ee8c247d4f2610f9aa04d115aa41c5b
cf504f28ab473fd70f2c60cda4d109c33b600727
refs/heads/master
2023-08-19T09:16:37.488546
2023-08-15T16:57:39
2023-08-15T16:57:39
31,146,820
10
0
null
null
null
null
UTF-8
Scheme
false
false
460
scm
render-partial-0.scm
(define instruction-to-html (lambda (instruction) (cat ($webutils:html-fragment-for-data instruction) "<br>"))) (define bytecode-to-html (lambda (bytecode) (call cat (map instruction-to-html bytecode)))) (call (lambda (method path headers body pargs) (let ((obj (get pargs 0)) (verb-num (get pargs 1)) (bytecode (getverbbytecode obj verb-num))) (bytecode-to-html bytecode))) args)
false
c87e9149b073105a353e19eb6734851d4152af3d
72e555d63b0514768a8d905c3761c54e76e13429
/mark_wutka+scheme/select-parser.scm
296b856a2f1a1684d0e254abacd2d7b3be96af45
[ "MIT" ]
permissive
chaughawout/rdbms
d40c6ba591b5d4f1453923b0dcbe621c086de698
94228ce2f2a11f40a69ad612ecf99bc71858fefc
refs/heads/master
2020-04-28T13:08:37.560231
2019-03-13T01:19:14
2019-03-13T01:19:14
175,299,130
0
0
NOASSERTION
2019-03-12T21:29:51
2019-03-12T21:29:49
null
UTF-8
Scheme
false
false
1,927
scm
select-parser.scm
(include "prcc-maw.scm") (use prcc-maw) (define where (<r> "[Ww][Hh][Ee][Rr][Ee] ")) (define order (<r> "[Oo][Rr][Dd][Ee][Rr] ")) (define by (<r> "[Bb][Yy] ")) (define (keyword-check k) (or (string-ci= k "where") (string-ci= k "order") (string-ci= k "by"))) (define identifier (regexp-parser-with-check "[A-Za-z_][A-Za-z0-9_]*" keyword-check)) (define table-qualifier (seq_ identifier (<c> #\.))) (define table-qualifier? (<?> table-qualifier)) (define select-column (<or> (seq_ table-qualifier (<c> #\*)) (seq_ table-qualifier? identifier))) (define select-columns (<or> (<c> #\*) (<@> (<r> "[Cc][Oo][Uu][Nn][Tt] *[(] *[*] *[)]") (lambda (x) "count(*)")) (join+_ select-column (<c> #\,)))) (define table (seq_ identifier (<?> identifier))) (define tables (join+_ table (<c> #\,))) (define column (seq_ table-qualifier? identifier)) (define columns (join+_ column (<c> #\,))) (define constant (<or> (<r> "'[^']*'") (<r> "[0-9][0-9]*[.]?[0-9]*"))) (define expr (<or> column constant)) (define comp (<or> (<s> "=") (<s> "!=") (<@> (<s> "<>") (lambda (x) "!=")) (<s> ">=") (<s> "<=") (<s> ">") (<s> "<"))) (define comparison (seq_ expr (<or> (<@> (<r> "[Ii][Ss] *[Nn][Uu][Ll][Ll]") (lambda (x) "isnull")) (seq_ comp expr)))) (define where-expr (<or> comparison (seq_ (<c> #\() (lazy where-or-exprs) (<c> #\))))) (define where-and-exprs (join+_ where-expr (<@> (<r> "[Aa][Nn][Dd] ") (lambda (x) "and ")))) (define where-or-exprs (join+_ where-and-exprs (<@> (<r> "[Oo][Rr] ") (lambda (x) "or ")))) (define where-clause where-or-exprs) (define sql-parser (seq_ (<r> "[Ss][Ee][Ll][Ee][Cc][Tt] ") select-columns (<r> "[Ff][Rr][Oo][Mm] ") tables (<?> (seq_ where where-clause)) (<?> (seq_ order by columns)) skip: (<or> (<s*>) (eof))))
false
ea603c7b176834b48ab0712a1d61b236d23b38ad
941c7c0396ac5e0555ace55a047aada9c5614af9
/hex.scm
f66a8a8f5853b9f7d095cc1c4278329a9fafae26
[]
no_license
euccastro/hexgrid
be31d382abac779bee66bb3e4afc7542c8f7ff99
146457b14be8ddc0ca377e46cb2f4e472ac91563
refs/heads/master
2016-09-06T08:50:30.759388
2013-07-15T11:22:43
2013-07-15T11:22:43
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
12,830
scm
hex.scm
; hexgrid ; ======= ; ; This module defines utility functions to work with hexagonal grids, such as ; those used in some wargames. ; ; The grid is stored as a flat vector, where the 0,0 cell is at the lowest ; left corner and width-1,height-1 is at the upper right. The grid represents ; a roughly rectangular region in world/screen space. For example, ; (make-grid-vector '(3 4)) would return a representation of the following ; grid: ; ; 0,3 1,3 2,3 ; ; 0,2 1,2 2,2 ; ; 0,1 1,1 2,1 ; ; (0,0) 1,0 2,0 ; ; Where indices may optionally wrap around horizontally or vertically, so ; coords -1,4 in the above grid refer to the same cell as 2,0. Thus, the above ; grid also represents the following map (where an instance of the original ; grid has been highlighted): ; ; ... ; ; ... 1,1 2,1 0,1 1,1 2,1 0,1 1,1 ... ; ; ... 1,0 2,0 0,0 1,0 2,0 0,0 1,0 ... ; +-----------------+ ; ... 1,3 2,3 / 0,3 1,3 2,3 / 0,3 1,3 ... ; / / ; ... 1,2 2,2 | 0,2 1,2 2,2 | 0,2 1,2 ... ; \ \ ; ... 1,1 2,1 | 0,1 1,1 2,1 | 0,1 1,1 ... ; / / ; ... 1,0 2,0 /(0,0) 1,0 2,0 / 0,0 1,0 ... ; +-----------------+ ; ... 1,3 2,3 0,3 1,3 2,3 0,3 1,3 ... ; ; ... 1,2 2,2 0,2 1,2 2,2 0,2 1,2 ... ; ; ... ; ; If this wrapping doesn't make sense for your application, just check indices ; at the appropriate places with ((within-bounds? grid-size) cell). ; ; Warning: if you want your grid to wrap around vertically, make sure it has ; an even height (number of rows). ; ; Vector indices ; -------------- ; ; We store grid cells in a flat vector, where the order is determined by ; cell coordinates, first x and then y, both ascending. Thus, the grid ; described above would be represented as ; ; #(0,0 1,0 2,0 3,0 0,1 1,1 2,1 3,1 0,2 1,2 2,2 3,2) ; ; Where i,j are the contents at cell in row j and column i. These are ; basically whatever you set. This module initializes them to #f and ; doesn't otherwise bother itself with them. ; ; Coordinate format ; ----------------- ; ; Functions normally take and return sequences of size two to represent cell ; coordinates or points in world/screen space. This is done so they compose ; more seamlessly. ; ; Currying ; -------- ; ; Functions that take data that will typically not change much during a ; program come curried like this: ((fn permanent args) volatile args), to ; make it more convenient to avoid clutter and verbosity. ; ; License (BSD) ; ------------- ; ; Copyright (C) 2013, Estevo U. C. Castro <[email protected]> ; ; 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 author 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 HOLDERS 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. (use bindings) ; Internal helper to destructure 2-sequences. (define-syntax def2 (syntax-rules () ((_ (f i j seq2) body ...) (define (f seq2) (bind (i j) seq2 body ...))))) (def2 (make-grid-vector width height size) (assert (positive-integers? width height)) (make-vector (* width height) #f)) (def2 (indexer width height size) (assert (positive-integers? width height)) (lambda (cell) (assert ((within-bounds? size) cell)) (bind (i j) cell (+ i (* j width))))) (define (horizontal-wrapper width) (assert (positive-integers? width)) (lambda (cell) (bind (i j) cell (list (modulo i width) j)))) (define (vertical-wrapper height) (assert (and (positive-integers? height) (even? height))) (lambda (cell) (bind (i j) cell (list i (modulo j height))))) (define ((within-bounds? grid-size) cell) (bind-let (((grid-width grid-height) grid-size) ((i j) cell)) (assert (positive-integers? grid-width grid-height)) (and (<= 0 i) (< i grid-width) (<= 0 j) (< j grid-height)))) ; Copied for reference. ; ... 1,1 2,1 0,1 1,1 2,1 0,1 1,1 ... ; ... 1,0 2,0 0,0 1,0 2,0 0,0 1,0 ... ; ... 1,3 2,3 0,3 1,3 2,3 0,3 1,3 ... ; ... 1,2 2,2 0,2 1,2 2,2 0,2 1,2 ... ; ... 1,1 2,1 0,1 1,1 2,1 0,1 1,1 ... ; ... 1,0 2,0 (0,0) 1,0 2,0 0,0 1,0 ... ; ... 1,3 2,3 0,3 1,3 2,3 0,3 1,3 ... ; ... 1,2 2,2 0,2 1,2 2,2 0,2 1,2 ... (def2 (east i j cell) (list (+ i 1) j)) (def2 (northeast i j cell) (list (+ i (diagonal-offset 'east j)) (+ j 1))) (def2 (northwest i j cell) (list (+ i (diagonal-offset 'west j)) (+ j 1))) (def2 (west i j cell) (list (- i 1) j)) (def2 (southwest i j cell) (list (+ i (diagonal-offset 'west j)) (- j 1))) (def2 (southeast i j cell) (list (+ i (diagonal-offset 'east j)) (- j 1))) ; Utility. (define (diagonal-offset h-direction j) (cond ((and (eqv? h-direction 'west) (even? j)) -1) ((and (eqv? h-direction 'east) (odd? j)) +1) (else 0))) (define directions (list east northeast northwest west southwest southeast)) ; Vertical distance between centers of hexagons in two adjacent rows, in outer ; radii. (define row-height (/ 3 2)) ; In outer radii. This is also the horizontal distance between adjacent ; hexagons in adjacent rows, or half the distance between adjacent hexagons in ; the same row. (define inner-radius (/ (sqrt 3) 2)) ; Return the world coordinates of the center of the `cell`, if cells have an ; outer radius of `radius` and the center of the cell at grid position 0,0 is ; at `origin` in world/screen coordinates. (define ((grid->world origin radius) cell) (bind-let (((ox oy) origin) ((i j) cell)) (assert (> radius 0)) (list (+ ox (* (+ (* 2 i) (if (odd? j) 1 0)) inner-radius radius)) (+ oy (* j row-height radius))))) ; Return the (non-wrapped) grid coordinates of the cell that contains the ; `point`, if cells have an outer radius of `radius` and the center of the ; cell at grid position (0,0) is at `origin` in world/screen coordinates. (define ((world->grid origin radius) point) ; We begin by finding the position of the point in a rectangular grid where ; the center of every hexagon defines a new row and column. The point is ; closest to the corners of the rectangle it is in than to any other hexagon ; center. Each of these rectangles has two hexagon centers at opposite ; corners. The point is inside the hexagon with the closest center. (bind-let* (((ox oy) origin) ((x y) point) ((rect-width rect-height i% j% x%% y%%) (world->rect% ox oy radius x y)) ((x% y% di0 dj0 x1 y1 di1 dj1) ; What corners of the rectangle correspond to hex centers is arranged ; in a checkerboard pattern. (if (eq? (even? i%) (even? j%)) ; We have translated our space so the lower left corner is at the ; center of the 0,0 hexagon, so all rectangles congruent to 0,0 ; checkerboard-wise will have hexagon centers in their lower left ; and upper right corners. (list 0 0 0 0 rect-width rect-height 1 1) ; Thus, the others have hexagon centers in the lower right and upper ; left corners. (list rect-width 0 1 0 0 rect-height 0 1))) ; Check which one is closest and obtain index offset. ((di dj) (if (< (squared-distance x%% y%% x% y%) (squared-distance x%% y%% x1 y1)) (list di0 dj0) (list di1 dj1)))) (let ((j (+ dj j%))) ; Horizontally offset odd rows, divide by 2 because a rectangle is half ; an hexagon. (list (quotient (+ i% di (if (odd? j) -1 0)) 2) j)))) ; Factored out for debugging. (define (world->rect% ox oy radius x y) (let* ((rect-width (* inner-radius radius)) (rect-height (* row-height radius)) (x% (- x ox)) (y% (- y oy)) ; The lower left corner of the rectangle where this point is. (i% (inexact->exact (floor (/ x% rect-width)))) (j% (inexact->exact (floor (/ y% rect-height)))) ; The position of the point relative to the bottom left corner of the ; i%,j% rectangle. We'll use this to find the closest hexagon center ; and thus obtain a <column>,<row> offset from i%,j%. (x%% (- x% (* rect-width i%))) (y%% (- y% (* rect-height j%)))) (list rect-width rect-height i% j% x%% y%%))) ; In counter-clockwise order, assuming center at 0,0 and radius 1. (define normalized-hex-verts (let ((ir inner-radius)) `((,ir -1/2) (,ir 1/2) (0 1) (,(- ir) 1/2) (,(- ir) -1/2) (0 -1)))) (define (hex-verts origin hex-radius) (let ((g->w (grid->world origin hex-radius))) (lambda (cell) (bind (x y) (g->w cell) (map (lambda (v) (bind (vx vy) v (list (+ x (* vx hex-radius)) (+ y (* vy hex-radius))))) normalized-hex-verts))))) (def2 (distance grid-width grid-height grid-size) (lambda (cell other) (bind-let (((i0 j0) cell) ((i1 j1) other)) (let* ((i0 (+ i0 (if (odd? j0) 0.5 0))) (i1 (+ i1 (if (odd? j1) 0.5 0))) (nwdi (abs (- i1 i0))) (nwdj (abs (- j1 j0))) (di (if grid-width (min nwdi (- grid-width nwdi)) nwdi)) (dj (if grid-height (min nwdj (- grid-height nwdj)) nwdj))) (+ dj (max 0 (inexact->exact (- (ceiling di) (ceiling (/ dj 2)))))))))) (define distance-nowrap (distance '(#f #f))) ; The contrived name highlights that these are world coordinates. (define (grid-world-size grid-size radius) (bind (grid-width grid-height) grid-size (list (* (+ (* grid-width 2) ; Offset for odd rows, if any. (if (> grid-height 1) 1 0)) inner-radius radius) (* (+ 1/2 ; bottom half of first row. (* row-height grid-height)) radius)))) ; Calculate largest radius for which our grid will still fit in ; `container-size`, with `margin` units left at both sides in the most ; constrained direction. (define (radius-to-fit grid-size container-size margin) (let* ((world-1 (grid-world-size grid-size 1)) (canvas-size (map (lambda (x) (- x (* 2 margin))) container-size))) (apply min (map / canvas-size world-1)))) ; Calculate world/screen coordinates for the 0,0 hexagon, such that the grid ; will be centered in `container-size`. (define (origin-to-center grid-size hex-radius container-size) ; We choose the contrived name grid-world-(width|height) to highlight that ; these are screen/world coordinates. (bind-let (((grid-world-width grid-world-height) (grid-world-size grid-size hex-radius)) ((container-width container-height) container-size)) (list (+ (/ (- container-width grid-world-width) 2) (* inner-radius hex-radius)) (+ (/ (- container-height grid-world-height) 2) hex-radius)))) ; Utility. (define (squared-distance x0 y0 x1 y1) (+ (square (- x1 x0)) (square (- y1 y0)))) (define (square x) (* x x)) (define (positive-integers? . l) (every (lambda (x) (and integer? x) (> x 0)) l))
true
c9dcadd911ba978603428ca33fc5984746e5ada2
0011048749c119b688ec878ec47dad7cd8dd00ec
/src/spoilers/169/solution.scm
ffcd8b3ef1d8b353fc13434a775e49244e85bed8
[ "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
519
scm
solution.scm
(import (srfi 69)) (define (_solve n) (let* ((a (quotient n 2)) (b (- a 1))) (if (even? n) (+ (solve a) (solve b)) (solve a)))) (define solve (let ((cache (make-hash-table))) (hash-table-set! cache 0 1) (hash-table-set! cache 1 1) (lambda (n) (if (hash-table-exists? cache n) (hash-table-ref cache n) (let ((acc (_solve n))) (hash-table-set! cache n acc) acc))))) (let ((_ (solve #e1e25))) (print _) (assert (= _ 178653872807)))
false
5cb20757fc5fed2e96228c5903a15c8f65e335f1
15b3f9425594407e43dd57411a458daae76d56f6
/bin/test/listtest.scm
48edc53bb04f7ba56f85f97e599f0390c24d93c5
[]
no_license
aa10000/scheme
ecc2d50b9d5500257ace9ebbbae44dfcc0a16917
47633d7fc4d82d739a62ceec75c111f6549b1650
refs/heads/master
2021-05-30T06:06:32.004446
2015-02-12T23:42:25
2015-02-12T23:42:25
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,014
scm
listtest.scm
(define q (make-deque)) (define a (cons 'a 1)) (define b (cons 'b 1)) (define c (cons 'c 1)) (define d (cons 'd 1)) (front-insert-deque! q a) (front-insert-deque! q b) (front-insert-deque! q c) (front-insert-deque! q d) (print-deque q) (define (f value) (lambda (v) (eq? (car v) value))) (define n (find-deque q (f 'b))) (delete-deque! q n) (print-deque q) (define n (find-deque q (f 'd))) (delete-deque! q n) (print-deque q) (define n (find-deque q (f 'a))) (delete-deque! q n) (print-deque q) (define n (find-deque q (f 'c))) (delete-deque! q n) (print-deque q) (define n (find-deque q (f 'c))) (delete-deque! q n) (print-deque q) ;(define ht (make-hashtable)) ;(display "foo") (newline) ;(lookup-hashtable ht 'a #t 1) ;(lookup-hashtable ht 'b #t 2) ;(lookup-hashtable ht 'c #t 3) ;(lookup-hashtable ht 'd #t 4) ;(lookup-hashtable ht 'e #t 5) ;(display "bar") (newline) ;(define z (lookup-hashtable ht 'c #f 0)) ;(display "baz") (newline) ;(remove-hashtable ht 'c) ;(display "foobar") (newline)
false
4bbd9e73b64626bdd904de58dd394120fada5c34
e5a6f30aa5fb44e919bc423cfd05c3ddb8eab9f5
/libmdal/utils/md-note-table.scm
b5565fef1cdcf54e8d8c48ed74aa441a392ec97f
[ "MIT" ]
permissive
nyanpasu64/bintracker
46c55c9912fd04fa94832cb6cd816f21a66059c3
ebcc1677f701cee857d0dccfd3abeb574e32cc41
refs/heads/master
2022-09-24T20:46:11.448291
2020-06-04T14:17:08
2020-06-04T14:17:08
269,378,487
0
0
MIT
2020-06-04T14:15:44
2020-06-04T14:15:43
null
UTF-8
Scheme
false
false
6,927
scm
md-note-table.scm
;; This file is part of the libmdal library. ;; Copyright (c) utz/irrlicht project 2018-2020 ;; See LICENSE for license details. ;;; Generate note to frequency divider/lookup value mappings (module md-note-table (make-counters make-dividers-range make-inverse-dividers-range make-dividers make-inverse-dividers highest-note lowest-note note-table-range) (import scheme (chicken base) srfi-69) (define note-names (vector "c" "c#" "d" "d#" "e" "f" "f#" "g" "g#" "a" "a#" "b")) ;; fn = f0 * (2^(1/12))^n ;; using c-9 as base note (f0) (define (offset->freq offset) (* 8372.018 (expt (expt 2 (/ 1 12)) (- (- 108 offset))))) (define (freq->divider freq cycles bits cpu-speed) (inexact->exact (round (* (/ (* freq cycles) cpu-speed) (expt 2 bits))))) (define (freq->inverse-divider freq cycles cpu-speed) (inexact->exact (round (/ (/ cpu-speed cycles) freq)))) (define (offset->divider offset cycles bits cpu-speed) (freq->divider (offset->freq offset) cycles bits cpu-speed)) (define (offset->inverse-divider offset cycles cpu-speed) (freq->inverse-divider (offset->freq offset) cycles cpu-speed)) (define (offset->octave offset) (quotient offset 12)) ;; lower bound defined as: the offset in half-tones from C-0 that will ;; produce a divider value that is 1) > 0, and 2) distinct from the divider ;; value produced by (+ offset 1) (define (get-lower-bound cycles bits cpu-speed) (do ((offs 0 (+ offs 1))) ((and (> (offset->divider offs cycles bits cpu-speed) 0) (not (= (offset->divider offs cycles bits cpu-speed) (offset->divider (+ offs 1) cycles bits cpu-speed))) (not (= (offset->divider (+ offs 1) cycles bits cpu-speed) (offset->divider (+ offs 2) cycles bits cpu-speed)))) offs))) ;; upper bound defined as: the offset in half-tones from C-0 that will ;; produce a divider value that is 1) > 0, and 2) distinct from the divider ;; value produced by (+ offset 1) (define (get-upper-bound-inverse cycles bits cpu-speed) (do ((offs (get-lower-bound-inverse cycles bits cpu-speed) (+ offs 1))) ((or (<= (offset->inverse-divider offs cycles cpu-speed) 0) (= (offset->inverse-divider offs cycles cpu-speed) (offset->inverse-divider (+ offs 1) cycles cpu-speed)) (= (offset->inverse-divider (+ offs 1) cycles cpu-speed) (offset->inverse-divider (+ offs 2) cycles cpu-speed))) offs))) ;; lower bound defined as: the offset in half-tones from C-0 that will ;; produce a divider value that is larger than the max integer value ;; representable in <bits> (define (get-lower-bound-inverse cycles bits cpu-speed) (do ((offs 0 (+ offs 1))) ((< (offset->inverse-divider offs cycles cpu-speed) (expt 2 bits)) offs))) ;; upper bound defined as: the offset in half-tones from C-0 that will ;; produce a divider value that is larger than the max integer value ;; representable in <bits> (define (get-upper-bound cycles bits cpu-speed) (do ((offs 0 (+ offs 1))) ((>= (offset->divider offs cycles bits cpu-speed) (expt 2 bits)) offs))) (define (offset->note-name offset) (string->symbol (string-append (vector-ref note-names (modulo offset 12)) (number->string (offset->octave offset))))) ;;; (define (make-dividers-range cycles beg end rest bits cpu-speed) (if (> beg end) (list (cons 'rest rest)) (cons (cons (offset->note-name beg) (offset->divider beg cycles bits cpu-speed)) (make-dividers-range cycles (+ 1 beg) end rest bits cpu-speed)))) ;;; (define (make-inverse-dividers-range cycles beg end rest cpu-speed) (if (> beg end) (list (cons 'rest rest)) (cons (cons (offset->note-name beg) (offset->inverse-divider beg cycles cpu-speed)) (make-inverse-dividers-range cycles (+ 1 beg) end rest cpu-speed)))) ;;; generate a note table with divider->note-name mappings ;;; wrapper func for make-dividers-range that will auto-deduce optimal range ;;; parameters: cycles - number of cycles in sound generation loop ;;; bits - size of the dividers, as number of bits ;;; rest - the value that represents a rest/note-off ;;; [shift] - number of octaves to shift the table (define (make-dividers cpu-speed cycles bits rest . shift) (let* ((prescaler (if (null? shift) 1 (expt 2 (- (car shift))))) (prescaled-cycles (* cycles prescaler))) (alist->hash-table (make-dividers-range prescaled-cycles (get-lower-bound prescaled-cycles bits cpu-speed) (get-upper-bound prescaled-cycles bits cpu-speed) rest bits cpu-speed)))) ;;; generate a note table with inverse divider->node-name mappings ;;; ie. dividers are countdown values ;;; see `make-dividers` for further documentation (define (make-inverse-dividers cpu-speed cycles bits rest . shift) (let* ((prescaler (if (null? shift) 1 (expt 2 (- (car shift))))) (prescaled-cycles (* cycles prescaler))) (alist->hash-table (make-inverse-dividers-range prescaled-cycles (get-lower-bound-inverse prescaled-cycles bits cpu-speed) (get-upper-bound-inverse prescaled-cycles bits cpu-speed) rest cpu-speed)))) ;;; Generate a note table with simple note-name->index mappings. ;;; ;;; BEG - lowest note, as offset from c-0 ;;; ;;; END - highest note, as offset from c-0 ;;; ;;; FIRST-INDEX - index of the lowest note ;;; ;;; REST-INDEX - index of the rest/note-off (define (make-counters beg end first-index rest-index) (letrec ((mkcounters (lambda (beg end first rest) (if (> beg end) (list (cons 'rest rest)) (cons (cons (offset->note-name beg) first) (mkcounters (+ 1 beg) end (+ 1 first) rest)))))) (alist->hash-table (mkcounters beg end first-index rest-index)))) ;;; Returns the lowest note in the given note table. (define (lowest-note table) (letrec ((try-lower (lambda (offset tbl) (if (hash-table-ref/default tbl (offset->note-name offset) #f) (offset->note-name offset) (try-lower (+ offset 1) tbl))))) (try-lower 0 table))) ;;; Returns the highest note in the given note table. (define (highest-note table) (letrec ((try-upper (lambda (offset tbl) (if (hash-table-ref/default tbl (offset->note-name offset) #f) (offset->note-name offset) (try-upper (- offset 1) tbl))))) (try-upper 131 table))) ;;; Returns (lowest highest) notes in the given note table. (define (note-table-range table) (list (lowest-note table) (highest-note table))) ) ;; end module md-note-tables
false
21e66c131ec22182f2ba35a98dde0a12612b2b96
3323fb4391e76b853464a9b2fa478cd7429e9592
/exercise-2.70.ss
414d1e46dd3b6ae820786fef3715d6ba1e39ad7b
[]
no_license
simpleliangsl/hello-scheme
ceb203933fb056523f5288ce716569096a71ad97
31434fb810475ee0e8ec2e6816995a0041c47f44
refs/heads/master
2023-06-16T12:07:28.744188
2021-07-15T06:39:32
2021-07-15T06:39:32
386,197,304
0
0
null
null
null
null
UTF-8
Scheme
false
false
661
ss
exercise-2.70.ss
(top-level-program (import (chezscheme) (huffman)) (define pairs '((A 2) (NA 16) (BOOM 1) (SHA 3) (GET 2) (YIP 9) (JOB 2) (WAH 1)) ) (define huffman-tree (generate-huffman-tree pairs)) (define message '( GET A JOB SHA NA NA NA NA NA NA NA NA GET A JOB SHA NA NA NA NA NA NA NA NA WAH YIP YIP YIP YIP YIP YIP YIP YIP YIP SHA BOOM )) (define codes (encode message huffman-tree)) (display codes) (newline) (display (format "length of codes: ~a" (length codes))) (newline) (display (format "length of fixed codes: ~a" (* (log (length pairs) 2) (length message)))) )
false
9354e20580e8e000db2a53261e236426bfa7188f
defeada37d39bca09ef76f66f38683754c0a6aa0
/mscorlib/system/reflection/default-member-attribute.sls
62018c03d86ffdb9abc3e2d10935cf2abfb68e78
[]
no_license
futsuki/ironscheme-port
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
4e7a81b0fbeac9a47440464988e53fb118286c54
refs/heads/master
2016-09-06T17:13:11.462593
2015-09-26T18:20:40
2015-09-26T18:20:40
42,757,369
0
0
null
null
null
null
UTF-8
Scheme
false
false
611
sls
default-member-attribute.sls
(library (system reflection default-member-attribute) (export new is? default-member-attribute? member-name) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Reflection.DefaultMemberAttribute a ...))))) (define (is? a) (clr-is System.Reflection.DefaultMemberAttribute a)) (define (default-member-attribute? a) (clr-is System.Reflection.DefaultMemberAttribute a)) (define-field-port member-name #f #f (property:) System.Reflection.DefaultMemberAttribute MemberName System.String))
true
71b3e491817e09cf08077dd969527c39cf63b64f
0ffe5235b0cdac3846e15237c2232d8b44995421
/src/scheme/Section_2.2/2.18.scm
d44ae44b3c07ad661c5d3da3b79643cab021a8a9
[]
no_license
dawiedotcom/SICP
4d05014ac2b075b7de5906ff9a846e42298fa425
fa6ccac0dad8bdad0645aa01197098c296c470e0
refs/heads/master
2020-06-05T12:36:41.098263
2013-05-16T19:41:38
2013-05-16T19:41:38
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
839
scm
2.18.scm
; SICP Exercise 2.18 ; Dawie de Klerk ; 2012-08-20 (load "../utils.scm") (define (reverse1 lst) ;; Reverse the order of lst (define (iter acc l) (if (zero? (length l)) acc (iter (cons (car l) acc) (cdr l)))) (iter '() lst)) (define (reverse2 lst) ;; Reverse the order of list using fold (fold (lambda (elem acc) (cons elem acc)) '() lst)) ;;; TEST (define (test-reverse) (println "last-pair (23 72 149 34):" (reverse1 (list 23 72 149 34))) (println "last-pair (1 2 3 4 5 6 7):" (reverse1 (list 1 2 3 4 5 6 7))) (println "last-pair (7):" (reverse1 (list 7)))) (define (test-reverse2) (println "last-pair (23 72 149 34):" (reverse2 (list 23 72 149 34))) (println "last-pair (1 2 3 4 5 6 7):" (reverse2 (list 1 2 3 4 5 6 7))) (println "last-pair (7):" (reverse2 (list 7))))
false
ed5d0257abe12078b0f3c124d59c137169580899
5fe14ef1ced9caa3b7d1fc3248ba86155e9628f5
/tests/srfi-98.scm
46c8df224f8274e9b653a3729006cf9597f1483a
[]
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
656
scm
srfi-98.scm
; Test suite for SRFI 98 ; ; $Id: srfi-98-test.sch 6183 2009-04-10 21:03:12Z will $ ;(cond-expand (srfi-98)) (use posix srfi-1) (define for-all every) (define (writeln . xs) (for-each display xs) (newline)) (define (fail token . more) (writeln "Error: test failed: " token) #f) (or (string? (get-environment-variable "PATH")) (fail 'PATH)) (or (eq? #f (get-environment-variable "Unlikely To Be Any Such Thing")) (fail 'Unlikely)) (or (let ((alist (get-environment-variables))) (and (list? alist) (for-all pair? alist) (assoc "PATH" alist))) (fail 'get-environment-variables)) (writeln "Done.") ; eof
false
28971303df72ecf754414dee55ba6f1f5c636735
63a1f38e64b0604377fbfa0d10d48545c609cc86
/two-state/cmt-prop.ss
696e3fc4d6d627c112c20baf43d6a20e9b14a699
[]
no_license
jeapostrophe/redex
d02b96b441f27e3afa1ef92726741ec026160944
8e5810e452878a4ab5153d19725cfc4cf2b0bf46
refs/heads/master
2016-09-06T00:55:02.265152
2013-10-31T01:24:11
2013-10-31T01:24:11
618,062
2
1
null
null
null
null
UTF-8
Scheme
false
false
5,911
ss
cmt-prop.ss
#lang scheme (require redex/reduction-semantics tests/eli-tester "common.ss" "sl.ss" "tl.ss" "cmt.ss") (define cmt-decompose? (term-match/single sl-grammar+cmt [a #t] [(in-hole EE r) #t])) (redex-check sl-grammar e (cmt-decompose? (term e))) (printf "Done with decompose~n") (define-language reasonable-sl-programs [se sa (sw ... se) (letrec ([sigma sv] ...) se) (match sw sl ...) (call/cc sw)] [sl [(K x ...) => se] [else => se]] [sa sw (K sa ...)] [sw sv x] [sv (! sigma) ; XXX not good (λ (x ...) se) (unsafe-λ (x ...) ue) (K sv ...) (cont (hide-hole E))] [ue ua (uw ... ue) (letrec ([sigma uv] ...) ue) (match uw ul ...)] [ul [(K x ...) => ue] [else => ue]] [ua uw (K ua ...)] [uw uv x] [uv (! sigma) ; XXX not good (λ (x ...) ue) (K uv ...)] [x variable-not-otherwise-mentioned] [K string] [sigma (side-condition (name t string) (not (member (term t) '("resume" "call/cc" "=" "+" "-" "*" "if" "unsafe-map" "all-safe?"))))] [Sigma mt (snoc Sigma [sigma -> sv])] [e* (/ Sigma e)] [E hole (sv ... E)] [TE (/ Sigma E)]) (test (redex-match reasonable-sl-programs se (term (call/cc (unsafe-λ (mt) q)))) => #f (redex-match reasonable-sl-programs se (term (letrec (("call/cc" (λ (n x) (call/cc d)))) (call/cc (cont hole))))) => #f) (define remove-letrec_rel (reduction-relation tl-grammar (--> (in-hole E_1 (letrec ([sigma v] ...) e)) (in-hole E_1 e)))) (define (remove-letrec e) (first (apply-reduction-relation* remove-letrec_rel e))) (define (alpha-equal? t1 t2) (define t1->t2 (make-hash)) (define matchit (match-lambda* [(list `(λ (,id1 ...) . ,rest1) `(λ (,id2 ...) . ,rest2)) (define old (map (λ (i) (hash-ref t1->t2 i #f)) id1)) (for-each (curry hash-set! t1->t2) id1 id2) (begin0 (matchit rest1 rest2) (for-each (λ (i old) (if old (hash-set! t1->t2 i old) (hash-remove! t1->t2 i))) id1 old))] [(list (cons t1_f t1_r) (cons t2_f t2_r)) (and (matchit t1_f t2_f) (matchit t1_r t2_r))] [(list (? string? s1) (? string? s2)) (string=? s1 s2)] [(list (? symbol? s1) (? symbol? s2)) (symbol=? (hash-ref! t1->t2 s1 s2) s2)] [(list (list) (list)) #t] [else #f])) (matchit t1 t2)) (test (alpha-equal? (term (λ (x) (abort ((! "resume") ("cons" ("marks" ("some" (λ (x) (x)))) ("nil")) x)))) (term (λ (x1) (abort ((! "resume") ("cons" ("marks" ("some" (λ (x) (x)))) ("nil")) x1)))))) (define value? (redex-match sl-grammar v)) (define ((make-cmt-correct? cmt-compatible?) sl) (define sl-answers (apply-reduction-relation* -->_sl (term (/ mt ,(with-safe sl))))) (define tl (CMT sl 'safe)) (define tl-answers (apply-reduction-relation* -->_tl (term (/ mt ,tl)))) (andmap (lambda (sl-ans tl-ans) (match-let ([`(/ ,sl-store ,sl-val) sl-ans] [`(/ ,tl-store ,tl-val) tl-ans]) (cmt-compatible? sl-val tl-val))) sl-answers tl-answers)) ;;;;;;;;;;; (define-language pure-sl-programs [se sa (sw ... se) (letrec ([sigma sv] ...) se) (match sw sl ...) (call/cc sw)] [sl [(K x ...) => se] [else => se]] [sa sw (K sa ...)] [sw sv x] [sv (! sigma) ; XXX not good (λ (x ...) se) (K sv ...) (cont (hide-hole E))] [x variable-not-otherwise-mentioned] [K string] [sigma (side-condition (name t string) (not (member (term t) '("resume" "call/cc" "=" "+" "-" "*" "if" "unsafe-map" "all-safe?"))))] [Sigma mt (snoc Sigma [sigma -> sv])] [e* (/ Sigma e)] [E hole (sv ... E)] [TE (/ Sigma E)]) (define (pure-cmt-compatible? sl-val tl-val-ext) (define tl-val-int (remove-letrec (CMT sl-val 'safe))) (define ans (or (not (value? sl-val)) (alpha-equal? tl-val-int tl-val-ext))) (unless ans (printf "SL:~n~S~nTL int:~n~S~nTL ext:~n~S~n" sl-val tl-val-int tl-val-ext)) ans) (define pure-cmt-correct? (make-cmt-correct? pure-cmt-compatible?)) (redex-check pure-sl-programs se (pure-cmt-correct? (term se))) ;;;;;;;;;;; (define (reasonable-cmt-compatible? sl-val tl-val-ext) (define tl-val-int (remove-letrec (CMT sl-val 'safe))) (define ans (or (not (value? sl-val)) (alpha-equal? tl-val-int tl-val-ext) (equal? tl-val-ext '("unsafe context")))) (unless ans (printf "SL:~n~S~nTL int:~n~S~nTL ext:~n~S~n" sl-val tl-val-int tl-val-ext)) ans) (define reasonable-cmt-correct? (make-cmt-correct? reasonable-cmt-compatible?)) (test (reasonable-cmt-correct? (term ((unsafe-λ (f) ,(:let 'x `(f ,(num 2)) `((! "+") x ,(num 1)))) (λ (y) (call/cc (λ (k) (k ,(num 3)))))))) (reasonable-cmt-correct? (term ((! "We") (cont hole) (unsafe-λ () W) (cont hole) (unsafe-λ (w oB h) R) (λ (DC I IB d O) (call/cc v)) (! "yNYOXg") ("letrec" L I)))) (reasonable-cmt-correct? (term ((call/cc (cont hole))))) (reasonable-cmt-correct? (term (letrec (("" (cont ((cont hole) (cont hole) (! "f") (cont hole) (cont hole) hole))) ("rquQ" (! "λ")) ("BskzdU" (cont ((! "match") hole))) ("oiOv" (cont (hole))) ("" (unsafe-λ (B) G)) ("oBVASDiJI" (λ () (Y u r (call/cc ZK)))) ("EBVcnxCKqOe" ("AIqpVLp" (! "i")))) (P y (cont hole) x))))) (redex-check reasonable-sl-programs se (reasonable-cmt-correct? (term se)))
false
02dea78adbb76fc8857dd7819603d32b2849188e
0f9909b1ea2b247aa9dec923d58e4d0975b618e6
/tests/fft.scm
aff36bb0cf9c3a31ab5437bb0f0a38b5554049e7
[]
no_license
suranap/sausage
9898ad418e2bdbb7e7a1ac798b52f17c589a4cb4
9a03ff3c52cd69278ea75733491e95362cc8765d
refs/heads/master
2016-09-10T19:31:11.990203
2013-05-01T14:48:50
2013-05-01T14:48:50
9,792,997
1
0
null
null
null
null
UTF-8
Scheme
false
false
2,923
scm
fft.scm
;; ,open floatnums ;; for some reason, scheme48 doesn't have make-polar! (define pi 3.14159265358979323846) (define (make-polar m a) (make-rectangular (* m (cos a)) (* m (sin a)))) (define (make-nth-root len) (make-polar 1 (/ (* 2 pi) len))) (define (unity-root n k) (expt (make-nth-root n) k)) (define (my-fft sequence) (let ((unshuffle (lambda (seq) (let loop ((rest seq) (evens '()) (odds '())) (if (null? rest) (cons (reverse evens) (reverse odds)) (loop (cddr rest) (cons (car rest) evens) (cons (cadr rest) odds))))))) (let ((len (length sequence))) (if (= len 1) sequence (let ((nth-root (make-nth-root len)) ; principal len-th root of unity (half-len (quotient len 2)) (packs (unshuffle sequence))) (let loop ((step 0) (root 1) (evens (my-fft (car packs))) (odds (my-fft (cdr packs))) (front '()) (rear '())) (if (= step half-len) (append (reverse front) (reverse rear)) (loop (+ step 1) (* root nth-root) (cdr evens) (cdr odds) (cons (+ (car evens) (* root (car odds))) front) (cons (- (car evens) (* root (car odds))) rear))))))))) ;; i+t = ((index . temp) ...) (define (print . args) (for-each display args) (newline)) (define *count* 0) (define (new-temp i) (set! *count* (+ *count* 1)) (string->symbol (string-append "t" (number->string *count*)))) (define (unshuffle lst) (letrec ((odd (lambda (lst) (if (null? lst) (values '() '()) (receive (evens odds) (even (cdr lst)) (values evens (cons (car lst) odds)))))) (even (lambda (lst) (if (null? lst) (values '() '()) (receive (evens odds) (odd (cdr lst)) (values (cons (car lst) evens) odds)))))) (if (even? (length lst)) (even lst) (odd lst)))) (define (comp w yk ykn y0 y1 k stmts) (cons* `(set! ,yk (+ ,y0 (* ,(w k) ,y1))) `(set! ,ykn (- ,y0 (* ,(w k) ,y1))) stmts)) (define (merge temps even odd) (let ((k (length even)) (make-w (lambda (k) `(unity-root ,(length temps) ,k)))) (receive (lhs0 lhs1) (split-at temps k) (fold-right (cut comp make-w <> <> <> <> <> <>) '() lhs0 lhs1 even odd (iota k))))) (define (gen indices) (print (length indices)) (let ((temps (map new-temp indices))) (if (= (length indices) 1) (values temps `((set! ,(car temps) (input ,(car indices)))) ) (receive (even odd) (unshuffle indices) (let*-values (((even-temps even-code) (gen even)) ((odd-temps odd-code) (gen odd))) (values temps (append even-code odd-code (merge temps even-temps odd-temps)))))))) (define (fftgen n) (set! *count* 0) (gen (iota n))) (define (fft-data) (list->vector (let ((x (/ (* 2 pi 5) 16))) (map (lambda (a) (make-rectangular (cos (* x a)) (- (sin (* x a))))) (l:iota 16)))))
false
7f08072de217d57bf3dc90defe46390613740664
df0ba5a0dea3929f29358805fe8dcf4f97d89969
/exercises/informatics-2/05-lists/append.scm
c0e267b8fc314eeb8b0a3c9873763cb43cb3bbd5
[ "MIT" ]
permissive
triffon/fp-2019-20
1c397e4f0bf521bf5397f465bd1cc532011e8cf1
a74dcde683538be031186cf18367993e70dc1a1c
refs/heads/master
2021-12-15T00:32:28.583751
2021-12-03T13:57:04
2021-12-03T13:57:04
210,043,805
14
31
MIT
2019-12-23T23:39:09
2019-09-21T19:41:41
Racket
UTF-8
Scheme
false
false
532
scm
append.scm
(require rackunit rackunit/text-ui) (define append-tests (test-suite "Tests for append" (check-equal? (append '() '()) '()) (check-equal? (append '() '(42)) '(42)) (check-equal? (append '(42) '()) '(42)) (check-equal? (append '(42) '(1)) '(42 1)) (check-equal? (append '(1 2 3 4) '(5 6)) '(1 2 3 4 5 6)) (check-equal? (append '(1 2 3 4) '(4 4 4)) '(1 2 3 4 4 4 4)) (check-equal? (append '(8 4 92 82 8 13) '(42 666 83)) '(8 4 92 82 8 13 42 666 83)))) (run-tests append-tests)
false
2b3fa36679c09e2c7bd247b8af7e674d84937bbe
f08220a13ec5095557a3132d563a152e718c412f
/logrotate/skel/usr/share/guile/2.0/srfi/srfi-18.scm
01550c310c65e67a905cdcac0a817c9dbfc06c2f
[ "Apache-2.0" ]
permissive
sroettger/35c3ctf_chals
f9808c060da8bf2731e98b559babd4bf698244ac
3d64486e6adddb3a3f3d2c041242b88b50abdb8d
refs/heads/master
2020-04-16T07:02:50.739155
2020-01-15T13:50:29
2020-01-15T13:50:29
165,371,623
15
5
Apache-2.0
2020-01-18T11:19:05
2019-01-12T09:47:33
Python
UTF-8
Scheme
false
false
12,198
scm
srfi-18.scm
;;; srfi-18.scm --- Multithreading support ;; Copyright (C) 2008, 2009, 2010, 2014 Free Software Foundation, Inc. ;; ;; This library is free software; you can redistribute it and/or ;; modify it under the terms of the GNU Lesser General Public ;; License as published by the Free Software Foundation; either ;; version 3 of the License, or (at your option) any later version. ;; ;; This library is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;; Lesser General Public License for more details. ;; ;; You should have received a copy of the GNU Lesser General Public ;; License along with this library; if not, write to the Free Software ;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ;;; Author: Julian Graham <[email protected]> ;;; Date: 2008-04-11 ;;; Commentary: ;; This is an implementation of SRFI-18 (Multithreading support). ;; ;; All procedures defined in SRFI-18, which are not already defined in ;; the Guile core library, are exported. ;; ;; This module is fully documented in the Guile Reference Manual. ;;; Code: (define-module (srfi srfi-18) :use-module (srfi srfi-34) :export ( ;;; Threads ;; current-thread <= in the core ;; thread? <= in the core make-thread thread-name thread-specific thread-specific-set! thread-start! thread-yield! thread-sleep! thread-terminate! thread-join! ;;; Mutexes ;; mutex? <= in the core make-mutex mutex-name mutex-specific mutex-specific-set! mutex-state mutex-lock! mutex-unlock! ;;; Condition variables ;; condition-variable? <= in the core make-condition-variable condition-variable-name condition-variable-specific condition-variable-specific-set! condition-variable-signal! condition-variable-broadcast! condition-variable-wait! ;;; Time current-time time? time->seconds seconds->time current-exception-handler with-exception-handler raise join-timeout-exception? abandoned-mutex-exception? terminated-thread-exception? uncaught-exception? uncaught-exception-reason ) :re-export (current-thread thread? mutex? condition-variable?) :replace (current-time make-thread make-mutex make-condition-variable raise)) (if (not (provided? 'threads)) (error "SRFI-18 requires Guile with threads support")) (cond-expand-provide (current-module) '(srfi-18)) (define (check-arg-type pred arg caller) (if (pred arg) arg (scm-error 'wrong-type-arg caller "Wrong type argument: ~S" (list arg) '()))) (define abandoned-mutex-exception (list 'abandoned-mutex-exception)) (define join-timeout-exception (list 'join-timeout-exception)) (define terminated-thread-exception (list 'terminated-thread-exception)) (define uncaught-exception (list 'uncaught-exception)) (define object-names (make-weak-key-hash-table)) (define object-specifics (make-weak-key-hash-table)) (define thread-start-conds (make-weak-key-hash-table)) (define thread-exception-handlers (make-weak-key-hash-table)) ;; EXCEPTIONS (define raise (@ (srfi srfi-34) raise)) (define (initial-handler obj) (srfi-18-exception-preserver (cons uncaught-exception obj))) (define thread->exception (make-object-property)) (define (srfi-18-exception-preserver obj) (if (or (terminated-thread-exception? obj) (uncaught-exception? obj)) (set! (thread->exception (current-thread)) obj))) (define (srfi-18-exception-handler key . args) ;; SRFI 34 exceptions continue to bubble up no matter who handles them, so ;; if one is caught at this level, it has already been taken care of by ;; `initial-handler'. (and (not (eq? key 'srfi-34)) (srfi-18-exception-preserver (if (null? args) (cons uncaught-exception key) (cons* uncaught-exception key args))))) (define (current-handler-stack) (let ((ct (current-thread))) (or (hashq-ref thread-exception-handlers ct) (hashq-set! thread-exception-handlers ct (list initial-handler))))) (define (with-exception-handler handler thunk) (let ((ct (current-thread)) (hl (current-handler-stack))) (check-arg-type procedure? handler "with-exception-handler") (check-arg-type thunk? thunk "with-exception-handler") (hashq-set! thread-exception-handlers ct (cons handler hl)) (apply (@ (srfi srfi-34) with-exception-handler) (list (lambda (obj) (hashq-set! thread-exception-handlers ct hl) (handler obj)) (lambda () (call-with-values thunk (lambda res (hashq-set! thread-exception-handlers ct hl) (apply values res)))))))) (define (current-exception-handler) (car (current-handler-stack))) (define (join-timeout-exception? obj) (eq? obj join-timeout-exception)) (define (abandoned-mutex-exception? obj) (eq? obj abandoned-mutex-exception)) (define (uncaught-exception? obj) (and (pair? obj) (eq? (car obj) uncaught-exception))) (define (uncaught-exception-reason exc) (cdr (check-arg-type uncaught-exception? exc "uncaught-exception-reason"))) (define (terminated-thread-exception? obj) (eq? obj terminated-thread-exception)) ;; THREADS ;; Create a new thread and prevent it from starting using a condition variable. ;; Once started, install a top-level exception handler that rethrows any ;; exceptions wrapped in an uncaught-exception wrapper. (define make-thread (let ((make-cond-wrapper (lambda (thunk lcond lmutex scond smutex) (lambda () (lock-mutex lmutex) (signal-condition-variable lcond) (lock-mutex smutex) (unlock-mutex lmutex) (wait-condition-variable scond smutex) (unlock-mutex smutex) (with-exception-handler initial-handler thunk))))) (lambda (thunk . name) (let ((n (and (pair? name) (car name))) (lm (make-mutex 'launch-mutex)) (lc (make-condition-variable 'launch-condition-variable)) (sm (make-mutex 'start-mutex)) (sc (make-condition-variable 'start-condition-variable))) (lock-mutex lm) (let ((t (call-with-new-thread (make-cond-wrapper thunk lc lm sc sm) srfi-18-exception-handler))) (hashq-set! thread-start-conds t (cons sm sc)) (and n (hashq-set! object-names t n)) (wait-condition-variable lc lm) (unlock-mutex lm) t))))) (define (thread-name thread) (hashq-ref object-names (check-arg-type thread? thread "thread-name"))) (define (thread-specific thread) (hashq-ref object-specifics (check-arg-type thread? thread "thread-specific"))) (define (thread-specific-set! thread obj) (hashq-set! object-specifics (check-arg-type thread? thread "thread-specific-set!") obj) *unspecified*) (define (thread-start! thread) (let ((x (hashq-ref thread-start-conds (check-arg-type thread? thread "thread-start!")))) (and x (let ((smutex (car x)) (scond (cdr x))) (hashq-remove! thread-start-conds thread) (lock-mutex smutex) (signal-condition-variable scond) (unlock-mutex smutex))) thread)) (define (thread-yield!) (yield) *unspecified*) (define (thread-sleep! timeout) (let* ((ct (time->seconds (current-time))) (t (cond ((time? timeout) (- (time->seconds timeout) ct)) ((number? timeout) (- timeout ct)) (else (scm-error 'wrong-type-arg "thread-sleep!" "Wrong type argument: ~S" (list timeout) '())))) (secs (inexact->exact (truncate t))) (usecs (inexact->exact (truncate (* (- t secs) 1000000))))) (and (> secs 0) (sleep secs)) (and (> usecs 0) (usleep usecs)) *unspecified*)) ;; A convenience function for installing exception handlers on SRFI-18 ;; primitives that resume the calling continuation after the handler is ;; invoked -- this resolves a behavioral incompatibility with Guile's ;; implementation of SRFI-34, which uses lazy-catch and rethrows handled ;; exceptions. (SRFI-18, "Primitives and exceptions") (define (wrap thunk) (lambda (continuation) (with-exception-handler (lambda (obj) ((current-exception-handler) obj) (continuation)) thunk))) ;; A pass-thru to cancel-thread that first installs a handler that throws ;; terminated-thread exception, as per SRFI-18, (define (thread-terminate! thread) (define (thread-terminate-inner!) (let ((current-handler (thread-cleanup thread))) (if (thunk? current-handler) (set-thread-cleanup! thread (lambda () (with-exception-handler initial-handler current-handler) (srfi-18-exception-preserver terminated-thread-exception))) (set-thread-cleanup! thread (lambda () (srfi-18-exception-preserver terminated-thread-exception)))) (cancel-thread thread) *unspecified*)) (thread-terminate-inner!)) (define (thread-join! thread . args) (define thread-join-inner! (wrap (lambda () (let ((v (apply join-thread (cons thread args))) (e (thread->exception thread))) (if (and (= (length args) 1) (not v)) (raise join-timeout-exception)) (if e (raise e)) v)))) (call/cc thread-join-inner!)) ;; MUTEXES ;; These functions are all pass-thrus to the existing Guile implementations. (define make-mutex (lambda name (let ((n (and (pair? name) (car name))) (m ((@ (guile) make-mutex) 'unchecked-unlock 'allow-external-unlock 'recursive))) (and n (hashq-set! object-names m n)) m))) (define (mutex-name mutex) (hashq-ref object-names (check-arg-type mutex? mutex "mutex-name"))) (define (mutex-specific mutex) (hashq-ref object-specifics (check-arg-type mutex? mutex "mutex-specific"))) (define (mutex-specific-set! mutex obj) (hashq-set! object-specifics (check-arg-type mutex? mutex "mutex-specific-set!") obj) *unspecified*) (define (mutex-state mutex) (let ((owner (mutex-owner mutex))) (if owner (if (thread-exited? owner) 'abandoned owner) (if (> (mutex-level mutex) 0) 'not-owned 'not-abandoned)))) (define (mutex-lock! mutex . args) (define mutex-lock-inner! (wrap (lambda () (catch 'abandoned-mutex-error (lambda () (apply lock-mutex (cons mutex args))) (lambda (key . args) (raise abandoned-mutex-exception)))))) (call/cc mutex-lock-inner!)) (define (mutex-unlock! mutex . args) (apply unlock-mutex (cons mutex args))) ;; CONDITION VARIABLES ;; These functions are all pass-thrus to the existing Guile implementations. (define make-condition-variable (lambda name (let ((n (and (pair? name) (car name))) (m ((@ (guile) make-condition-variable)))) (and n (hashq-set! object-names m n)) m))) (define (condition-variable-name condition-variable) (hashq-ref object-names (check-arg-type condition-variable? condition-variable "condition-variable-name"))) (define (condition-variable-specific condition-variable) (hashq-ref object-specifics (check-arg-type condition-variable? condition-variable "condition-variable-specific"))) (define (condition-variable-specific-set! condition-variable obj) (hashq-set! object-specifics (check-arg-type condition-variable? condition-variable "condition-variable-specific-set!") obj) *unspecified*) (define (condition-variable-signal! cond) (signal-condition-variable cond) *unspecified*) (define (condition-variable-broadcast! cond) (broadcast-condition-variable cond) *unspecified*) ;; TIME (define current-time gettimeofday) (define (time? obj) (and (pair? obj) (let ((co (car obj))) (and (integer? co) (>= co 0))) (let ((co (cdr obj))) (and (integer? co) (>= co 0))))) (define (time->seconds time) (and (check-arg-type time? time "time->seconds") (+ (car time) (/ (cdr time) 1000000)))) (define (seconds->time x) (and (check-arg-type number? x "seconds->time") (let ((fx (truncate x))) (cons (inexact->exact fx) (inexact->exact (truncate (* (- x fx) 1000000))))))) ;; srfi-18.scm ends here
false
255a60536396e8567652987e2c9864cab5b0d321
a5d31dc29c25d1f2c0dab633459de05f5996679a
/benchmark-verification/intro3.sch
edb827546c562ca11eee11e3258102b032a786b9
[]
no_license
jebcat1982/soft-contract
250461a231b150b803df9275f33ee150de043f00
4df509a75475843a2caeb7e235301f277446e06c
refs/heads/master
2021-01-21T22:06:10.092109
2014-05-26T11:51:00
2014-05-26T11:51:00
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
350
sch
intro3.sch
(module f (provide [f (int? (int? . -> . any) . -> . any)]) (define (f x g) (g (+ x 1)))) (module h (provide [h ([z : int?] . -> . ((and/c int? (>/c z)) . -> . any))]) (define (h z) (λ (y) 'unit))) (module main (provide [main (int? . -> . any)]) (require f h) (define (main n) (if (>= n 0) (f n (h n)) 'unit))) (require main) (main •)
false
01f9685450aa6b68fe6bc9dc82dbb262f959031c
5f5bf90e51b59929b5e27a12657fade4a8b7f9cd
/src/training_routines/network_trainer.scm
1029f4f662ab145f938a3733e016460faf568a2c
[]
no_license
ashton314/NN_Chess
9ddd8ebc4a3594fcfe0b127ddd7309000eaa6594
f6c8295a622483641cdf883642723ee8e6e84e76
refs/heads/master
2020-04-25T04:16:00.493978
2014-01-01T22:24:01
2014-01-01T22:24:01
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,783
scm
network_trainer.scm
;;; AI Training Routines ;;; Ashton Wiersdorf ;;; Part of the NN_Chess project (load-option 'format) ;; (load "engine.scm") ;; (load "feature_detector.scm") (write-string "Comments: ") (define *comments* (read-line)) ;; Load neural network ; backup current network (copy-file "DATA/NN_DATA/network.scm" (let ((now (local-decoded-time))) (format #f "DATA/NN_DATA/~A~A~A~A~A~A.scm" (decoded-time/year now) (decoded-time/month now) (decoded-time/day now) (decoded-time/hour now) (decoded-time/minute now) (decoded-time/second now)))) ; load network (define *network-stream* (open-input-file "DATA/NN_DATA/network.scm")) (define *learning-rate* .7) (define *input-nodes* (read *network-stream*)) (define *output-nodes* (read *network-stream*)) (define *hidden-layer* (read *network-stream*)) (close-port *network-stream*) ;; NOTES: #| INPUTS: 13 - side (1 => white, 0 => black) - pawn-compare - king-compare - white-advancement-potential - black-advancement-potential - white-moves - black-moves - white-endangered-pieces - black-endangered-pieces - longest-jump-white - longest-jump-black - black-blocking-white (pieces-ahead-of board 'white) - white-blocking-black (ditto) OUTPUTS: 5 - evil - bad - meh - good - amazing |# (define *training-data* '()) (call-with-input-file "DATA/TRAINING_DATA/data_set02.scm" (lambda (fh) (do ((line (read fh) (read fh))) ((eof-object? line) #f) (push! (cons (car line) (cadr line)) *training-data*)))) (bkpt "check *training-data*") (define *start-string* (let ((now (local-decoded-time))) (format #f "~A ~A ~A ~A:~A:~A" (decoded-time/year now) (decoded-time/month now) (decoded-time/day now) (decoded-time/hour now) (decoded-time/minute now) (decoded-time/second now)))) (define *network* (define-ffn *learning-rate* *input-nodes* *output-nodes* *hidden-layer*)) (train-network *network* *training-data* #t 10 .01 .95 #t #t) (define *end-string* (let ((now (local-decoded-time))) (format #f "~A ~A ~A ~A:~A:~A" (decoded-time/year now) (decoded-time/month now) (decoded-time/day now) (decoded-time/hour now) (decoded-time/minute now) (decoded-time/second now)))) ;; Save network (set! *network-stream* (open-output-file "DATA/NN_DATA/network.scm")) (format *network-stream* ";; COMMENTS: ~A\n" *comments*) (format *network-stream* ";; START: ~A\n" *start-string*) (format *network-stream* ";; FINISHED: ~A\n" *end-string*) (write-line *input-nodes* *network-stream*) (let ((data (*network* 'debug-get-layers))) (write-line (cadr data) *network-stream*) (write-line (caar data) *network-stream*)) (close-port *network-stream*)
false
c083d374d5929b475af09d9469576c98a5211e46
140a499a12332fa8b77fb738463ef58de56f6cb9
/worlds/core/verbcode/0/eval-0.scm
8f046784201e90b208ed812a205cca106a973d44
[ "MIT" ]
permissive
sid-code/nmoo
2a5546621ee8c247d4f2610f9aa04d115aa41c5b
cf504f28ab473fd70f2c60cda4d109c33b600727
refs/heads/master
2023-08-19T09:16:37.488546
2023-08-15T16:57:39
2023-08-15T16:57:39
31,146,820
10
0
null
null
null
null
UTF-8
Scheme
false
false
27
scm
eval-0.scm
(echo "=> " (eval argstr))
false
7830210d71ffe84fe9e031eec1c32e8f818b219b
1a64a1cff5ce40644dc27c2d951cd0ce6fcb6442
/src/operation/lst-renderers-to-scene.scm
595b86371a5fdfd2ab97b23408c4780a86bb4f8b
[]
no_license
skchoe/2007.rviz-objects
bd56135b6d02387e024713a9f4a8a7e46c6e354b
03c7e05e85682d43ab72713bdd811ad1bbb9f6a8
refs/heads/master
2021-01-15T23:01:58.789250
2014-05-26T17:35:32
2014-05-26T17:35:32
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,432
scm
lst-renderers-to-scene.scm
(module lst-renderers-to-scene scheme (require (lib "class.ss") "../view-env/viz-class.scm" "../render/pick.scm" "../operation/convert-utils.scm" "../operation/scene-node-ops.scm") (provide lst-renderers->scene-node% generate-scene-graph-from-lst-renderers) ;; ------------------------------------------------ ;; ;; --------- scene-tree w/ renderers ----------- ;; ; parent class for mixin (define lst-renderers->scene-node% (class* object% (convert-to-scene-graph<%>) (super-new) (define/public object->renderer (lambda (object) object)) (define/public convert-to-scene-graph (lambda (lst-renderers) (lst-renderers->scene-node lst-renderers))))) ; child mixin class ; input: structure of tree ; use global(in this module) for conversion: tree-node->scene-node% (define generate-scene-graph-from-lst-renderers (lambda (lst-renderers) (object-mixin->scene-graph (convert-to-scene-graph-mixin lst-renderers->scene-node%) lst-renderers))) ;;;;;;; ;; helpers ;; direct conversion to scene-node struct (define lst-renderers->scene-node (lambda (lst) (let ((new-node (initialize-scene-leaf-node lst #:p (generate-pick-id pick-id-table)))) new-node))) ; leaf node )
false