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
994d8606acfa03ddc91207200c4881fc738d8aa0
9ff2abf87c905f4056e769fd3fc0a392904ac9e8
/Sample_Exams/Exam-1/Exam1-202010/E1-test-code.ss
a92528d13eed92fcaf323a0110e1866929a63c3b
[]
no_license
hernanre/csse304-1
b3cbc605aa4720bed1c16cab6da2385be6305d9b
4ae64ccd9858ead8a94245d4e20c4149fb4275f1
refs/heads/main
2023-08-30T04:03:02.067571
2021-10-23T21:55:01
2021-10-23T21:55:01
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
7,094
ss
E1-test-code.ss
;; Test code (define (test-string-index) (let ([correct '( 2 0 4 -1 -1 )] [answers (list (string-index #\h "ether") (string-index #\e "ether") (string-index #\r "ether") (string-index #\m "ether") (string-index #\m "") )]) (display-results correct answers equal?))) (define (test-merge-2-sorted-lists) (let ([correct '( (1 3) (1 2 3 4 5 6 7 8) (3 4 5 6) (1 2 3 4 5 6) (1 1 2 3 4 5 6 6) )] [answers (list (merge-2-sorted-lists '() '(1 3)) (merge-2-sorted-lists '(1 4 5 7 8) '(2 3 6)) (merge-2-sorted-lists '(5 6) '(3 4)) (merge-2-sorted-lists '(1 3 5) '(2 4 6)) (merge-2-sorted-lists '(1 2 4 6) '(1 3 5 6)) )]) (display-results correct answers equal?))) (define (test-slist-equal?) (let ([correct '(#f #t #f #t #f #t #f #t #t #f #t #f #t #f )] [answers (list (slist-equal? '() '(a)) (slist-equal? '() '()) (slist-equal? '(a) '(b)) (slist-equal? '(a) '(a)) (slist-equal? '(a) '(() a)) (slist-equal? '((a b)) '((a b))) (slist-equal? '((a a) a) '((a a))) (slist-equal? '((a ((b) (c) ())) d) '((a ((b) (c) ())) d)) (slist-equal? '(() (()) (()((a)))) '(() (()) (()((a))))) (slist-equal? '((a ((b) (c) ())) d) '((a ((b) (e) ())) d)) (slist-equal? '(a b c () d e) '(a b c () d e)) (slist-equal? '((a ((b) (c e) ())) d) '((a ((b) (c) ())) d)) (slist-equal? '(((()))) '(((())))) (slist-equal? '((a ((b) (c) ())) d) '((a ((b) (c) ())) f)))]) (display-results correct answers equal?))) (define (test-make-queue) (let ([correct '( 1 (#t #f) (1 2) (1 2) (3 1) (0 1 2 3 4 9 8 7 6 5) )] [answers (list (let ([q1 (make-queue)] [q2 (make-queue)]) (q1 'enqueue 1) (q1 'dequeue)) (let ([q1 (make-queue)] [q2 (make-queue)]) (q1 'enqueue 1) (q2 'enqueue 2) (q1 'dequeue) (list (q1 'empty?) (q2 'empty?))) (let ([q1 (make-queue)] [q2 (make-queue)]) (q1 'enqueue 1) (q2 'enqueue 2) (list (q1 'dequeue) (q2 'dequeue))) (let ([q1 (make-queue)] [q2 (make-queue)]) (q1 'enqueue 1) (q2 'enqueue 2) (q1 'enqueue (q2 'dequeue)) (let ([val (q1 'dequeue)]) (cons val (list (q1 'dequeue))))) (let ([q1 (make-queue)] [q2 (make-queue)]) (q1 'enqueue 1) (q2 'enqueue 2) (q1 'enqueue (q2 'dequeue)) (q2 'enqueue 3) (list (q2 'dequeue) (q1 'dequeue))) (let ([q1 (make-queue)] [q2 (make-queue)]) (let loop ([a 4] [b 5]) (q1 'enqueue a) (q2 'enqueue b) (if (positive? a) (loop (sub1 a) (add1 b)))) (let loop2 () (if (not (q1 'empty?)) (begin (q2 'enqueue (q1 'dequeue)) (loop2)))) (let loop3 ([result '()]) (if (q2 'empty?) result (loop3 (cons (q2 'dequeue) result))))) )]) (display-results correct answers equal?))) (define (test-) (let ([correct '( )] [answers (list )]) (display-results correct answers equal?))) (define (test-) (let ([correct '( )] [answers (list )]) (display-results correct answers equal?))) (define (test-) (let ([correct '( )] [answers (list )]) (display-results correct answers equal?))) (define (test-) (let ([correct '( )] [answers (list )]) (display-results correct answers equal?))) ;----------------------------------------------- (define display-results (lambda (correct results test-procedure?) (display ": ") (pretty-print (if (andmap test-procedure? correct results) 'All-correct `(correct: ,correct yours: ,results))))) (define sequal?-grading (lambda (l1 l2) (cond ((null? l1) (null? l2)) ((null? l2) (null? l1)) ((or (not (set?-grading l1)) (not (set?-grading l2))) #f) ((member (car l1) l2) (sequal?-grading (cdr l1) (rember-grading (car l1) l2))) (else #f)))) (define set?-grading (lambda (s) (cond [(null? s) #t] [(not (list? s)) #f] [(member (car s) (cdr s)) #f] [else (set?-grading (cdr s))]))) (define rember-grading (lambda (a ls) (cond ((null? ls) ls) ((equal? a (car ls)) (cdr ls)) (else (cons (car ls) (rember-grading a (cdr ls))))))) (define set-equals? sequal?-grading) (define find-edges ; e know that this node is in the graph before we do the call (lambda (graph node) (let loop ([graph graph]) (if (eq? (caar graph) node) (cadar graph) (loop (cdr graph)))))) ;; Problem 8 graph? (define set? ;; Is this list a set? If not, it is not a graph. (lambda (list) (if (null? list) ;; it's an empty set. #t (if (member (car list) (cdr list)) #f (set? (cdr list)))))) (define graph? (lambda (obj) (and (list? obj) (let ([syms (map car obj)]) (and (set? syms) (andmap symbol? syms) (andmap (lambda (x) (andmap (lambda (y) (member y (remove (car x) syms))) (cadr x))) obj)))))) (define graph-equal? (lambda (a b) (and (graph? a) (graph? b) (let ([a-nodes (map car a)] [b-nodes (map car b)]) (and (set-equals? a-nodes b-nodes) ; Now See if the edges from each node are equivalent in the two graphs. (let loop ([a-nodes a-nodes]) (if (null? a-nodes) #t (let ([a-edges (find-edges a (car a-nodes))] [b-edges (find-edges b (car a-nodes))]) (and (set-equals? a-edges b-edges) (loop (cdr a-nodes))))))))))) (define (test-graph-equal) (list (graph-equal? '((a (b)) (b (a))) '((b (a)) (a (b)))) (graph-equal? '((a (b c d)) (b (a c d)) (c (a b d)) (d (a b c))) '((b (a c d)) (c (a b d)) (a (b d c)) (d (b a c)))) (graph-equal? '((a ())) '((a ()))) (graph-equal? '((a (b c)) (b (a c)) (c (a b))) '((a (b c)) (b (a c)) (c (a b)))) (graph-equal? '() '()) )) (define g test-graph-equal) ;You can run the tests individually, or run them all ;#by loading this file (and your solution) and typing (r) (define (run-all) (display 'string-index) (test-string-index) (display 'merge-2-sorted-lists) (test-merge-2-sorted-lists) (display 'slist-equal?) (test-slist-equal?) (display 'make-queue) (test-make-queue) ) (define r run-all)
false
1deb7803fee248d1dca241a325c861d9eda9ae4e
3629e5c33ebbc3acbaa660fb324c26357098147c
/examples/glbook/example4-1.scm
ad5c51cd051d103b5e32381a6bd7149f096d8e55
[ "MIT", "LicenseRef-scancode-x11-sg" ]
permissive
shirok/Gauche-gl
f31a62ce4c2d91795f972b668861a77626b02cb5
a569e3009314f81bc513827064e05869220c6a9d
refs/heads/master
2023-06-07T15:56:17.514969
2023-06-01T06:56:48
2023-06-01T06:56:48
9,487,174
4
5
MIT
2018-09-24T21:39:18
2013-04-17T02:13:32
C
UTF-8
Scheme
false
false
1,118
scm
example4-1.scm
;; Example 4-1 Drawing a Smooth-Shaded Triangle (use gl) (use gl.glut) (define (init) (gl-clear-color 0.0 0.0 0.0 0.0) (gl-shade-model GL_SMOOTH)) (define (triangle) (gl-begin GL_TRIANGLES) (gl-color '#f32(1.0 0.0 0.0)) (gl-vertex '#f32(5.0 5.0)) (gl-color '#f32(0.0 1.0 0.0)) (gl-vertex '#f32(25.0 5.0)) (gl-color '#f32(0.0 0.0 1.0)) (gl-vertex '#f32(5.0 25.0)) (gl-end)) (define (disp) (gl-clear GL_COLOR_BUFFER_BIT) (triangle) (gl-flush) ) (define (reshape w h) (gl-viewport 0 0 w h) (gl-matrix-mode GL_PROJECTION) (gl-load-identity) (if (<= w h) (glu-ortho-2d 0.0 30.0 0.0 (* 30.0 (/ h w))) (glu-ortho-2d 0.0 (* 30.0 (/ w h)) 0.0 30.0)) (gl-matrix-mode GL_MODELVIEW) ) (define (keyboard key x y) (when (= key 27) (exit 0))) (define (main args) (glut-init args) (glut-init-display-mode (logior GLUT_SINGLE GLUT_RGB)) (glut-init-window-size 500 500) (glut-init-window-position 100 100) (glut-create-window *program-name*) (init) (glut-display-func disp) (glut-reshape-func reshape) (glut-keyboard-func keyboard) (glut-main-loop) 0)
false
7f5a00dc4c526b984f3892e92938db5a85b5601b
5bf673b5bd8de5c1a943b739b9c2e0426da85d7c
/tests/db-sql-de-lite.scm
220f126d751f235388c421a4c43eb92fe559f180
[ "BSD-2-Clause" ]
permissive
mario-goulart/awful
dfe44157865d5b9b94004efc30ddb1dc4bf0e441
739f7b4c6b808db3d4c05bf43aa095dd6543252e
refs/heads/master
2023-04-14T08:34:19.377592
2023-04-10T09:17:29
2023-04-10T09:17:29
4,197,893
68
5
NOASSERTION
2023-02-12T09:18:16
2012-05-02T00:02:50
Scheme
UTF-8
Scheme
false
false
964
scm
db-sql-de-lite.scm
(use awful awful-sql-de-lite sql-de-lite) (define db-file "sqlite-test.db") (db-credentials db-file) (enable-db 'sql-de-lite) (when (file-exists? db-file) (delete-file db-file)) (let* ((conn (open-database (db-credentials))) (db-query (lambda (q) (query (map-rows (lambda args args)) (sql conn q))))) (db-query "create table users (name varchar(50), address varchar(50) );") (db-query "insert into users (name, address) values ('mario', 'here')") (db-query "insert into users (name, address) values ('foo', 'bar')") (close-database conn)) (define-page (main-page-path) (lambda () `((pre ,(with-output-to-string (lambda () (pp ($db "select * from users"))))) (table ,@(map (lambda (row) `(tr ,@(map (lambda (i) `(td ,i)) row))) ($db "select * from users"))))))
false
0b3d3894f011c3620cb4cf5996a685a483b87e6c
defeada37d39bca09ef76f66f38683754c0a6aa0
/UnityEngine.UI/unity-engine/ui/mask.sls
77c80aa51a7724080c6fa7f0947c3163a5f42c06
[]
no_license
futsuki/ironscheme-port
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
4e7a81b0fbeac9a47440464988e53fb118286c54
refs/heads/master
2016-09-06T17:13:11.462593
2015-09-26T18:20:40
2015-09-26T18:20:40
42,757,369
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,350
sls
mask.sls
(library (unity-engine ui mask) (export is? mask? mask-enabled? get-modified-material on-sibling-graphic-enabled-disabled is-raycast-location-valid? show-mask-graphic?-get show-mask-graphic?-set! show-mask-graphic?-update! rect-transform) (import (ironscheme-clr-port)) (define (is? a) (clr-is UnityEngine.UI.Mask a)) (define (mask? a) (clr-is UnityEngine.UI.Mask a)) (define-method-port mask-enabled? UnityEngine.UI.Mask MaskEnabled (System.Boolean)) (define-method-port get-modified-material UnityEngine.UI.Mask GetModifiedMaterial (UnityEngine.Material UnityEngine.Material)) (define-method-port on-sibling-graphic-enabled-disabled UnityEngine.UI.Mask OnSiblingGraphicEnabledDisabled (System.Void)) (define-method-port is-raycast-location-valid? UnityEngine.UI.Mask IsRaycastLocationValid (System.Boolean UnityEngine.Vector2 UnityEngine.Camera)) (define-field-port show-mask-graphic?-get show-mask-graphic?-set! show-mask-graphic?-update! (property:) UnityEngine.UI.Mask showMaskGraphic System.Boolean) (define-field-port rect-transform #f #f (property:) UnityEngine.UI.Mask rectTransform UnityEngine.RectTransform))
false
f9427e94012ef2bc8d98e57eb72e5c428aa2f90b
3351f39dbc591ff445c0c90b946c4ccf302ef008
/project-3/code/interp.scm
df1211a63d6574908f860a497587d6833740f91f
[]
no_license
nmutlu98/comp301-projects
6cba3c930c0d6a838553c171011446f562e7cda2
aabe1dd5fdc95a18b55701269b5ece88d3d3cecb
refs/heads/master
2023-02-10T12:15:29.611337
2021-01-07T22:40:02
2021-01-07T22:40:02
307,976,435
0
0
null
null
null
null
UTF-8
Scheme
false
false
11,724
scm
interp.scm
(module interp (lib "eopl.ss" "eopl") ;; interpreter for the EXPLICIT-REFS language (require "drscheme-init.scm") (require "lang.scm") (require "data-structures.scm") (require "environments.scm") (require "store.scm") (provide value-of-program value-of instrument-let instrument-newref) ;;;;;;;;;;;;;;;; switches for instrument-let ;;;;;;;;;;;;;;;; (define instrument-let (make-parameter #f)) ;; say (instrument-let #t) to turn instrumentation on. ;; (instrument-let #f) to turn it off again. ;;;;;;;;;;;;;;;; the interpreter ;;;;;;;;;;;;;;;; ;; value-of-program : Program -> ExpVal ;; Page: 110 (define value-of-program (lambda (pgm) (initialize-store!) ; new for explicit refs. (cases program pgm (a-program (exp1) (value-of exp1 (init-env)))))) ;; value-of : Exp * Env -> ExpVal ;; Page: 113 (define value-of (lambda (exp env) (cases expression exp ;\commentbox{ (value-of (const-exp \n{}) \r) = \n{}} (const-exp (num) (num-val num)) ;\commentbox{ (value-of (var-exp \x{}) \r) = (apply-env \r \x{})} (var-exp (var) (apply-env env var)) ;\commentbox{\diffspec} (diff-exp (exp1 exp2) (let ((val1 (value-of exp1 env)) (val2 (value-of exp2 env))) (let ((num1 (expval->num val1)) (num2 (expval->num val2))) (num-val (- num1 num2))))) ;\commentbox{\zerotestspec} (zero?-exp (exp1) (let ((val1 (value-of exp1 env))) (let ((num1 (expval->num val1))) (if (zero? num1) (bool-val #t) (bool-val #f))))) ;\commentbox{\ma{\theifspec}} (if-exp (exp1 exp2 exp3) (let ((val1 (value-of exp1 env))) (if (expval->bool val1) (value-of exp2 env) (value-of exp3 env)))) ;\commentbox{\ma{\theletspecsplit}} (let-exp (var exp1 body) (let ((val1 (value-of exp1 env))) (value-of body (extend-env var val1 env)))) (proc-exp (var body) (proc-val (procedure var body env))) (call-exp (rator rand) (let ((proc (expval->proc (value-of rator env))) (arg (value-of rand env))) (apply-procedure proc arg))) (letrec-exp (p-names b-vars p-bodies letrec-body) (value-of letrec-body (extend-env-rec* p-names b-vars p-bodies env))) (begin-exp (exp1 exps) (letrec ((value-of-begins (lambda (e1 es) (let ((v1 (value-of e1 env))) (if (null? es) v1 (value-of-begins (car es) (cdr es))))))) (value-of-begins exp1 exps))) (newref-exp (exp1) (let ((v1 (value-of exp1 env))) (ref-val (newref v1)))) (deref-exp (exp1) (let ((v1 (value-of exp1 env))) (let ((ref1 (expval->ref v1))) (deref ref1)))) (setref-exp (exp1 exp2) (let ((ref (expval->ref (value-of exp1 env)))) (let ((v2 (value-of exp2 env))) (begin (setref! ref v2) (num-val 23))))) (newarray-exp (num1 num2) (arr-val (helper-new-array num1 (num-val num2)))) (update-array-exp (array num1 exp1) (let ((val (value-of exp1 env)) (sc-array (expval->arr (value-of array env)))) (helper-update-array sc-array num1 val) (num-val 23))) (read-array-exp (array num1) (let ((arr (expval->arr (value-of array env)))) (helper-read-array arr num1))) (newqueue-exp () (value-of (newarray-exp 1001 -1) env)) (queue-push-exp (q exp) (let ((queue (value-of q env))) (let ((val (value-of exp env)) (empty-index (first-empty-index-in-array (expval->arr queue)))) (helper-update-array (expval->arr queue) empty-index val)))) (empty-queue?-exp (q) (if (helper-empty-array (expval->arr (value-of q env))) (bool-val #t) (bool-val #f) )) (queue-pop-exp (q) (let ((queue (expval->arr (value-of q env)))) (if (helper-empty-array queue) (num-val -1) (let ((firstval (deref (expval->ref (car queue))))) (helper-pop-queue queue) firstval)))) (queue-top-exp (q) (let ((queue (expval->arr (value-of q env)))) (if (helper-empty-array queue) (num-val -1) (let ((firstval (deref (expval->ref (car queue))))) firstval)))) (queue-size-exp (q) (let ((queue (expval->arr (value-of q env)))) (num-val (array-size queue)))) (print-queue-exp (q) (let ((queue (expval->arr (value-of q env)))) (helper-print-array queue))) (newstack-exp () (value-of (newarray-exp 1001 -1) env)) (stack-push-exp (s exp1) (let ((stack (expval->arr (value-of s env)))) (let ((val (value-of exp1 env)) (empty-index (first-empty-index-in-array stack))) (helper-update-array stack empty-index val)))) (stack-pop-exp (s) (let ((stack (expval->arr (value-of s env)))) (let ((size (array-size stack))) (let ((pop-val (helper-read-array stack (- size 1)))) (helper-update-array stack (- size 1) (num-val -1)) pop-val)))) (stack-top-exp (s) (let ((stack (expval->arr (value-of s env)))) (let ((size (array-size stack))) (let ((top-val (helper-read-array stack (- size 1)))) top-val)))) (stack-size-exp (s) (let ((stack (expval->arr (value-of s env)))) (num-val (array-size stack)))) (empty-stack?-exp (s) (let ((stack (expval->arr (value-of s env)))) (if (eq? (array-size stack) 0) (bool-val #t) (bool-val #f)))) (print-stack-exp (s) (let ((stack (expval->arr (value-of s env)))) (helper-print-array stack))) ))) ; helper-new-array: integer * expval -> (list-of ref-val) ; usage: used to create a new array with num1 elements where each element's value is num2 (define helper-new-array (lambda (num1 num2) (if (eq? num1 0) '() (cons (ref-val (newref num2)) (helper-new-array (- num1 1) num2))))) ; helper-update-array: (list-of ref-val) * integer * expval -> returns nothing ; usage: used to update the value in the indexth element of the given array. The new value stored in the indexth element becomes value. (define helper-update-array (lambda (array index value) (if (eq? index 0) (setref! (expval->ref (car array)) value) (helper-update-array (cdr array) (- index 1) value)))) ; helper-read-array: (list-of ref-val) * integer -> expval ; usage: used to get the value stored in the given index of the array (define helper-read-array (lambda (arr index) (if (eq? index 0) (deref (expval->ref (car arr))) (helper-read-array (cdr arr) (- index 1))))) ; array-size: (list-of ref-val) -> integer ; usage: used to get the number of elements in the queue (define array-size (lambda (arr) (if (helper-empty-array arr) 0 (+ 1 (array-size (cdr arr)))))) ; first-empty-index-in-array: (list-of ref-val) -> integer ; usage: used to get the index of the first empty cell in the queue (define first-empty-index-in-array (lambda (arr) (if (eq? (expval->num (deref (expval->ref (car arr)))) -1) 0 (+ 1 (first-empty-index-in-array (cdr arr)))))) ; helper-pop-queue: (list-of ref-val) -> returns nothing ; usage: used to slide all the elements to the left after an element is popped from the queue (define helper-pop-queue (lambda (arr) (define helper (lambda (current-index size) (if (eq? current-index (- size 1)) (helper-update-array arr current-index (num-val -1)) (begin (helper-update-array arr current-index (deref (expval->ref (list-ref arr (+ current-index 1))))) (helper (+ current-index 1) size))))) (let ((size (array-size arr))) (helper 0 size)))) ; helper-print-array: (list-of ref-val) -> returns nothing ; usage: used to traverse all the elements in the queue and make a string from those elements seperated by spaces. Then prints the string with display. (define helper-print-array (lambda (arr) (define helper (lambda (lst remaining-arr) (if (helper-empty-array remaining-arr) (map number->string lst) (helper (append lst (list (expval->num (deref (expval->ref (car remaining-arr)))))) (cdr remaining-arr))))) (display (helper '() arr)))) ; helper-empty-array: (list-of ref-val) -> returns boolean ; usage: used to check whether an array has empty cells or not. returns true if it has, returns false otherwise. (define helper-empty-array (lambda (arr) (cond ((null? arr) #t) ((eq? (expval->num (deref (expval->ref (car arr)))) -1) (helper-empty-array (cdr arr))) ((> (expval->num (deref (expval->ref (car arr)))) 0) #f)))) ;; apply-procedure : Proc * ExpVal -> ExpVal ;; ;; uninstrumented version ;; (define apply-procedure ;; (lambda (proc1 arg) ;; (cases proc proc1 ;; (procedure (bvar body saved-env) ;; (value-of body (extend-env bvar arg saved-env)))))) ;; instrumented version (define apply-procedure (lambda (proc1 arg) (cases proc proc1 (procedure (var body saved-env) (let ((r arg)) (let ((new-env (extend-env var r saved-env))) (when (instrument-let) (begin (eopl:printf "entering body of proc ~s with env =~%" var) (pretty-print (env->list new-env)) (eopl:printf "store =~%") (pretty-print (store->readable (get-store-as-list))) (eopl:printf "~%"))) (value-of body new-env))))))) ;; store->readable : Listof(List(Ref,Expval)) ;; -> Listof(List(Ref,Something-Readable)) (define store->readable (lambda (l) (map (lambda (p) (cons (car p) (expval->printable (cadr p)))) l))) )
false
1fe9211797db1a9a20602e86c41324268a97744f
8c460fc27ece8523af9be0c8b6c48461ff072e94
/compiler.scm
0b6c66abbcc893cc70076f3012d1102ba2c031ac
[]
no_license
ssbr/dcpu16-scheme
f1bc69821a13c6cb37ffbd7c51a1b63218233b0e
f17fcab6573a6a31b39a21b76585c66cb63a079c
refs/heads/master
2020-04-07T16:11:27.452424
2012-04-07T15:11:07
2012-04-07T15:11:07
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,516
scm
compiler.scm
(define (raise-error . params) (error #f (apply format #f params))) (define fixnum-tag #b00) (define fixnum-tag-mask #b11) (define char-tag #b01) (define special-tag #b10) (define (make-tagger tag shift) (lambda (n) (bitwise-ior (bitwise-arithmetic-shift-left n shift) tag))) (define tag-fixnum (make-tagger fixnum-tag 2)) (define tag-special (make-tagger special-tag 4)) (define tag-char (make-tagger char-tag 2)) (define special/false (tag-special 0)) (define special/true (tag-special 1)) (define special/empty-list (tag-special 2)) (define (primcall? expr) (and (list? expr) (not (null? expr)) (primitive? (car expr)))) (define *primitives* (make-hash-table)) (define-syntax define-primitive (syntax-rules () ((_ (prim-name si arg* ...) b b* ...) (begin (hashtable-set! *primitives* 'prim-name (make-primitive 'prim-name (length '(arg* ...)) (lambda (si arg* ...) b b* ...))))))) (define (make-primitive name args emitter) (list '*primitive* name args emitter)) (define (primitive-emitter prim) (list-ref (hashtable-ref *primitives* prim #f) 3)) (define-primitive (fxadd1 si env arg) (emit-expr si env arg) (emit `(add a ,(immediate-rep 1)))) (define-primitive (fx+ si env arg1 arg2) (emit-expr si env arg1) (emit '(push a)) (emit-expr si env arg2) (emit '(add a pop))) (define-primitive (fx- si env arg1 arg2) (emit-expr si env arg1) (emit '(push a)) (emit-expr si env arg2) (emit '(sub a pop))) (define-primitive (fx< si env arg1 arg2) (emit-expr si env arg2) (emit `(push a)) (emit-expr si env arg1) (emit `(pop b)) (emit `(set c ,special/true)) (emit `(ife a b)) (emit `(set c ,special/false)) (emit `(ifg a b)) (emit `(set c ,special/false)) (emit `(set a c))) (define (primitive? x) (and (symbol? x) (hashtable-ref *primitives* x #f))) (define (emit-primcall si env expr) (let ((prim (car expr)) (args (cdr expr))) (apply (primitive-emitter prim) si env args))) (define (emit-expr si env expr) (cond ((immediate? expr) (emit-immediate expr)) ((primcall? expr) (emit-primcall si env expr)) ((if? expr) (emit-if si env expr)) (else (raise-error "unknown expression: ~a" expr)))) (define (compile-program form) (set! *result* '()) (emit-expr 0 #f form) (reverse *result*)) (define (if? expr) (and (list? expr) (eq? (car expr) 'if))) (define unique-label (let ((count 0)) (lambda () (set! count (+ count 1)) (string->symbol (string-append "label-" (number->string count)))))) (define (emit-if si env expr) (let ((alt-label (unique-label)) (end-label (unique-label))) (emit-expr si env (if-test expr)) (emit `(ife a ,special/false)) (emit `(jf ,alt-label)) (emit-expr si env (if-conseq expr)) (emit `(jf ,end-label)) (emit alt-label) (emit-expr si env (if-altern expr)) (emit end-label) )) (define (if-test expr) (list-ref expr 1)) (define (if-conseq expr) (list-ref expr 2)) (define (if-altern expr) (list-ref expr 3)) (define (immediate? x) (or (number? x) (boolean? x) (null? x) (char? x))) (define (emit-immediate expr) (emit `(set a ,(immediate-rep expr)))) (define *result* '()) (define (emit form) (set! *result* (cons form *result*))) (define (immediate-rep x) (cond ((integer? x) (tag-fixnum x)) ((boolean? x) (if x special/true special/false)) ((null? x) special/empty-list) ((char? x) (tag-char (char->integer x))) (else (raise-error "unknown immediate: ~a" x))))
true
1b343468b116a6c468d901902454a6e4f0564c6a
6cf2e78840970768168f583716e8826b1902dafa
/learning-functional/work-in-university/home-practice/scheme-practice/part-2-recursion/solutions/product_digits.scm
ece4e793ea252f3c5d3b54d363862deca70d2952
[]
no_license
dianvaltodorov/learning-code
e4b3e5034c68cdf9d1e38f8b6a12af1d51d2e167
a92605345829e051c0b2420de6f3dfc1fe5eb65a
refs/heads/master
2021-01-17T12:24:58.618311
2016-02-02T17:48:55
2018-06-21T06:53:16
49,488,021
2
0
null
null
null
null
UTF-8
Scheme
false
false
495
scm
product_digits.scm
(load "../../lib/unit.scm") (define (product-digits-rec n) (if(< n 10) n (* (remainder n 10) (product-digits-rec (quotient n 10))))) (define (product-digits-iter n) (define (helper n result) (if( <= n 9 ) (* n result) (helper (quotient n 10) (* result (remainder n 10))))) (helper n 1)) (define (product-digits-iter2 n) (define (helper n result) (if( = n 0 ) result (helper (quotient n 10) (* result (remainder n 10))))) (helper n 1))
false
6b39d64b6332f9a74b8ac13b37da2f96813c3d5b
5d5da19f36a1a200b2273e6da4f309e3ec0e3a82
/points.scm
8f0378fff609b0d42bf8ecda5952403bbd32f4eb
[ "MIT" ]
permissive
soma-arc/scheme-raytrace
84f0688b95899b8ca1c081aac9dd8ad5c0dff35b
c5802c6fdeb268b1df50b4c13d55f43c348f0120
refs/heads/master
2021-01-21T04:50:21.094182
2016-06-21T12:29:21
2016-06-21T12:29:21
54,718,758
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,720
scm
points.scm
(define-module points (use vec :prefix v:) (use srfi-13) (use bezier :prefix b:) (use gauche.collection) (export-all)) (select-module points) (define (load-points file-name magnitude) (let ((points '())) (with-input-from-file file-name (lambda () (port-for-each (lambda (line) (push! points (apply v:vec3 (map (lambda (p) (* magnitude (string->number p))) (string-split line ","))))) read-line))) (list->vector (reverse! points)))) ;;tightness = 0.5 (define (calc-bezier-cp pt p1 p2 p3) (let ((d1 (v:scale (v:diff p2 pt) (/ 1 6))) (d2 (v:scale (v:diff p3 p1) (/ 1 6)))) (list p1 (v:sum p1 d1) (v:diff p2 d2) p2))) (define (points->bezier points) (letrec ((last (- (vector-length points) 2)) (bezier-list '()) (loop (lambda (i) (cond ((< i last) (push! bezier-list (calc-bezier-cp (ref points (- i 1)) (ref points i) (ref points (+ i 1)) (ref points (+ i 2)))) (loop (inc! i))) (else bezier-list))))) (reverse! (loop 1)))) (define (bezier->objs beziers width material) (map (lambda (bez) (b:make-bezier (ref bez 0) (ref bez 1) (ref bez 2) (ref bez 3) width material)) beziers))
false
cd79ba751b0382fc9c78589a43d07c4edcde9e8f
6f7df1f0361204fb0ca039ccbff8f26335a45cd2
/examples/grammar-induction/stats/grammar-to-church.ss
a718cf11ae3d9d1afdd5253ba6e12d7789b88548
[]
no_license
LFY/bpm
f63c050d8a2080793cf270b03e6cf5661bf3599e
a3bce19d6258ad42dce6ffd4746570f0644a51b9
refs/heads/master
2021-01-18T13:04:03.191094
2012-09-25T10:31:25
2012-09-25T10:31:25
2,099,550
2
0
null
null
null
null
UTF-8
Scheme
false
false
2,972
ss
grammar-to-church.ss
(import (printing) (util) (_srfi :1)) (define (rewrite-choose expr) (let* ([choices (cdr expr)] [delayed-choices (map (lambda (c) `(lambda () ,c)) choices)]) `(discrete-sample ,@delayed-choices))) (define (rewrite-body body) (if (equal? 'choose (car body)) (rewrite-choose body) body)) (define (rewrite-nonterminal nt) (let* ([name (cadr nt)] [expr (cadddr nt)]) `(define ,name (lambda () ,(rewrite-body expr))))) (define (rewrite-grammar gr) (let* ([nonterminals (cadr gr)] [start (caddr gr)] [start-body (rewrite-body (caddr start))] [rewritten-nonterminals (map rewrite-nonterminal nonterminals)]) `( (define (contact . xs) (cons 'contact xs)) (define (footer . xs) (cons 'footer xs)) (define (text_link . xs) (cons 'text_link xs)) (define (fine_print . xs) (cons 'fine_print xs)) (define (text . xs) (cons 'text xs)) (define (image . xs) (cons 'image xs)) (define (heading . xs) (cons 'heading xs)) (define (container . xs) (cons 'container xs)) (define (threeColumn . xs) (cons 'threeColumn xs)) (define (headline . xs) (cons 'headline xs)) (define (hero_image . xs) (cons 'hero_image xs)) (define (navigation_element . xs) (cons 'navigation_element xs)) (define (logo . xs) (cons 'logo xs)) (define (navigation . xs) (cons 'navigation xs)) (define (page_root . xs) (cons 'page_root xs)) (define (copyright . xs) (cons 'copyright xs)) (define (twoColumn . xs) (cons 'twoColumn xs)) (define (header . xs) (cons 'header xs)) (define (auxiliary_navigation . xs) (cons 'auxiliary_navigation xs)) (define (social_media . xs) (cons 'social_media xs)) (define (subheading . xs) (cons 'subheading xs)) (define (search . xs) (cons 'search xs)) (define (login . xs) (cons 'login xs)) (define (region . xs) (cons 'region xs)) (define (image_link . xs) (cons 'image_link xs)) (define (fourColumn . xs) (cons 'fourColumn xs)) (define (form . xs) (cons 'form xs)) (define (shopping_links . xs) (cons 'shopping_links xs)) (define (sitemap . xs) (cons 'sitemap xs)) (define (transaction_icons . xs) (cons 'transaction_icons xs)) (define (auxiliary_navigtion . xs) (cons 'auxiliary_navigtion xs)) (define (pagination . xs) (cons 'pagination xs)) (define (uniform-select xs) (let* ([idx (sample-integer (length xs))]) (list-ref xs idx))) (define (discrete-sample . choices) (let* ([which-choice (uniform-select choices)]) (if (procedure? which-choice) (which-choice) which-choice))) ,@rewritten-nonterminals (define sample-grammar (lambda () ,start-body))))) (define gr-filename (cadr (command-line))) (load gr-filename) (for-each pretty-print (rewrite-grammar grammar))
false
1c8f5fb0ed181a03eef746b25dedb4efe8ca4cca
46244bb6af145cb393846505f37bf576a8396aa0
/sicp/5_31.scm
9ee20dfee961568f495503d339c08658f9e67258
[]
no_license
aoeuidht/homework
c4fabfb5f45dbef0874e9732c7d026a7f00e13dc
49fb2a2f8a78227589da3e5ec82ea7844b36e0e7
refs/heads/master
2022-10-28T06:42:04.343618
2022-10-15T15:52:06
2022-10-15T15:52:06
18,726,877
4
3
null
null
null
null
UTF-8
Scheme
false
false
1,498
scm
5_31.scm
#lang racket #| Exercise 5.31. In evaluating a procedure application, the explicit-control evaluator always saves and restores the env register around the evaluation of the operator, saves and restores env around the evaluation of each operand (except the final one), saves and restores argl around the evaluation of each operand, and saves and restores proc around the evaluation of the operand sequence. For each of the following combinations, say which of these save and restore operations are superfluous and thus could be eliminated by the compiler's preserving mechanism: (f 'x 'y) ((f) 'x 'y) (f (g 'x) y) (f (g 'x) 'y) ; answer Here is how ev-application works: ev-appl-did-operator (restore unev) ; the operands (restore env) (assign argl (op empty-arglist)) (assign proc (reg val)) ; the operator (test (op no-operands?) (reg unev)) (branch (label apply-dispatch)) (save proc) env holds the environment, proc holds operands, so(I got some hint from http://community.schemewiki.org/?sicp-ex-5.31) (f 'x 'y) needs to save nothing, becaule all operands are quoted, so env doesn't change and no other proc necessary ((f) 'x 'y) all operands are quoted, so env needn't; (f (g 'x) y) the 1st operand is a compound-procedure, so saving for proc, argl are needed; also env, because we have to read y from env (f (g 'x) 'y) the 1st operand is a compound-procedure, so saving for proc, argl are needed; env is not, because y is quoted |#
false
a16c22df2db27397e1bffac661b0025768b5c23c
d074b9a2169d667227f0642c76d332c6d517f1ba
/sicp/ch_4/exercise.4.14.scm
77f0c398b03faa83acdbc31640d56ecef8acfb5c
[]
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
749
scm
exercise.4.14.scm
#!/usr/bin/env csi -s (require rackunit) (require-library eval) (import eval) ;;; Exercise 4.14 ;; Eva Lu Ator and Louis Reasoner are each experimenting with the ;; metacircular evaluator. Eva types in the definition of `map', and ;; runs some test programs that use it. They work fine. Louis, in ;; contrast, has installed the system version of `map' as a primitive ;; for the metacircular evaluator. When he tries it, things go ;; terribly wrong. Explain why Louis's `map' fails even though Eva's ;; works. ;; A: make-define creates a list to be used as a proc in the ;; evaluator, not a real scheme proc. Installing the scheme map ;; means that the evaluator needs to produce real scheme procs, not ;; internalized versions of procs.
false
2d0b134e23ee5865077e100cbae5df2d9be79816
a8216d80b80e4cb429086f0f9ac62f91e09498d3
/lib/chibi/snow/commands.scm
ef613f459a94a0dfc2dc211ccaca44a37c8e292c
[ "BSD-3-Clause" ]
permissive
ashinn/chibi-scheme
3e03ee86c0af611f081a38edb12902e4245fb102
67fdb283b667c8f340a5dc7259eaf44825bc90bc
refs/heads/master
2023-08-24T11:16:42.175821
2023-06-20T13:19:19
2023-06-20T13:19:19
32,322,244
1,290
223
NOASSERTION
2023-08-29T11:54:14
2015-03-16T12:05:57
Scheme
UTF-8
Scheme
false
false
102,365
scm
commands.scm
;; commands.scm -- snow commands ;; ;; This code was written by Alex Shinn in 2014 and placed in the ;; Public Domain. All warranties are disclaimed. (define (impl-available? cfg spec confirm?) (if (find-in-path (cadr spec)) (or (null? (cddr spec)) (not (third spec)) (conf-get cfg 'skip-version-checks?) (let ((version (impl->version (car spec) (third spec)))) (or (and version (version>=? version (fourth spec))) (let ((msg (string-append "Implementation " (symbol->string (car spec)) (if (string? version) (string-append " is an unsupported version, " version) " is an unknown version") ", but at least " (fourth spec) " is required."))) (cond (confirm? (yes-or-no? cfg msg " Install anyway?")) (else (warn msg) #f)))))) (and confirm? (yes-or-no? cfg "Implementation " (car spec) " does not " " seem to be available, install anyway?")))) (define (conf-selected-implementations cfg) (let ((requested (conf-get-list cfg 'implementations '(chibi)))) (let lp ((ls (if (memq 'all requested) (append (map car known-implementations) (delete 'all requested)) requested)) (res '())) (cond ((null? ls) (if (null? res) (warn "no implementations available")) (reverse res)) ((memq (car ls) res) (lp (cdr ls) res)) ((assq (car ls) known-implementations) => (lambda (x) (cond ((or (cond-expand (chibi (eq? 'chibi (car ls))) (else #f)) (impl-available? cfg x #t)) (lp (cdr ls) (cons (car ls) res))) (else (warn "ignoring unavailable implementation" (car ls)) (lp (cdr ls) res))))) ((yes-or-no? cfg "Unknown implementation: " (car ls) " - try to install anyway?") (lp (cdr ls) (cons (car ls) res))) (else (warn "ignoring unknown implementation: " (car ls)) (lp (cdr ls) res)))))) (define (conf-program-implementation? impl cfg) (cond ((conf-get cfg 'program-implementation) => (lambda (x) (eq? impl x))) (else (let ((ls (conf-selected-implementations cfg))) (or (null? ls) (eq? impl (car ls))))))) (define (conf-for-implementation cfg impl) (conf-specialize cfg 'implementation impl)) ;; Hack to evaluate an expression in a separate process with a larger ;; default heap. The expression and result must be serializable with ;; write, and imports should be an argument list for environment. ;; Currently only used when generating keys and signing. (define (fast-eval expr imports . o) (let* ((heap-size (if (pair? o) (car o) 500)) (cmd `("chibi-scheme" ,(string-append "-h" (number->string heap-size) "M") ,@(map (lambda (i) (string-append "-m" (string-join (map write-to-string i) "."))) imports) "-p" ,(write-to-string expr)))) (let ((res (process->sexp cmd))) (if (eof-object? res) ; process error (eval expr (apply environment imports)) res)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Package - generate a package from one or more libraries. (define (x->string x) (cond ((string? x) x) ((symbol? x) (symbol->string x)) ((number? x) (number->string x)) (else (error "not a valid path component" x)))) (define (library-path-base file name) (let lp ((ls (cdr (reverse name))) (dir (path-directory file))) (cond ((null? ls) dir) ((equal? (x->string (car ls)) (path-strip-directory dir)) (lp (cdr ls) (path-directory dir))) (else dir)))) (define (path-relative file dir) (let ((file (path-normalize file)) (dir (string-trim-right (path-normalize dir) #\/))) (string-trim-left (if (string-prefix? dir file) (substring file (string-length dir)) file) #\/))) ;; remove import qualifiers (define (import-name import) (cond ((and (pair? import) (memq (car import) '(only except prefix drop-prefix rename)) (pair? (cadr import))) (import-name (cadr import))) (else import))) (define (extract-library cfg file) (let ((lib (read-from-file file))) (match lib (('define-library (name ...) declarations ...) (let* ((dir (library-path-base file name)) (lib-file (path-relative file dir)) (lib-dir (path-directory lib-file))) (define (resolve file) (let ((dest-path (if (equal? lib-dir ".") file (make-path lib-dir file)))) (list 'rename (make-path dir dest-path) dest-path))) (define (ffi-file-includes file) (let lp ((forms (guard (exn (else '())) (call-with-input-file file port->sexp-list))) (res '())) (cond ((null? forms) (reverse res)) ((and (pair? (car forms)) (eq? 'c-include-verbatim (caar forms))) (lp (cdr forms) (append (cdar forms) res))) (else (lp (cdr forms) res))))) (define (ffi-files base) (let* ((path (path-resolve base (path-directory file))) (stub-file (string-append path ".stub")) (c-file (string-append path ".c"))) (cond ((file-exists? stub-file) (cons (string-append base ".stub") (ffi-file-includes stub-file))) ((file-exists? c-file) (list c-file)) (else (warn "couldn't find ffi stub or c source" base) '())))) (let lp ((ls declarations) (info `(,@(cond ((conf-get cfg '(command package author)) => (lambda (x) (list (list 'author x)))) (else '())) (path ,lib-file) (name ,name) library)) (deps '()) (files `((rename ,file ,lib-file))) (chibi-ffi? #f)) (cond ((null? ls) ;; Force a fake dependency on (chibi) if the chibi ffi is ;; used so this isn't available to other implementations. (let* ((deps (if (and chibi-ffi? (not (member '(chibi) deps))) (cons '(chibi) deps) deps)) (info (reverse (cons `(depends ,@deps) info)))) (cons info files))) (else (match (car ls) (((or 'include 'include-ci) includes ...) (lp (cdr ls) info deps (append (map resolve includes) files) chibi-ffi?)) (('include-library-declarations includes ...) (lp (append (append-map (lambda (inc) (file->sexp-list (path-resolve inc (path-directory file)))) includes) (cdr ls)) info deps (append (map resolve includes) files) chibi-ffi?)) (('include-shared includes ...) (lp (cdr ls) info deps (append (map resolve (append-map ffi-files includes)) files) #t)) (('import libs ...) (lp (cdr ls) info (append (map import-name libs) deps) files chibi-ffi?)) (('cond-expand clauses ...) (let ((libs+files (map (lambda (c) (lp c '() '() '() #f)) clauses))) (lp (cdr ls) (cons (cons 'cond-expand (map cons (map car clauses) (map car libs+files))) info) deps (append files (append-map cdr libs+files)) chibi-ffi?))) (else (lp (cdr ls) info deps files chibi-ffi?)))))))) (else (die 2 "not a valid library declaration " lib " in file " file))))) (define (extract-program-dependencies file . o) (let ((depends (or (and (pair? o) (car o)) 'depends))) (let lp ((ls (guard (exn (else '())) (if (and (pair? file) (eq? 'inline (car file))) (port->sexp-list (open-input-string (cadr file))) (file->sexp-list file)))) (deps '()) (cond-deps '())) (cond ((and (pair? ls) (pair? (car ls)) (eq? 'import (caar ls))) (lp (cdr ls) (append (reverse (map import-name (cdar ls))) deps) cond-deps)) ((and (pair? ls) (pair? (car ls)) (eq? 'cond-expand (caar ls))) ;; flatten all imports, but maintain cond-expand's separately (let ((res (filter-map (lambda (clause) (let ((imps (lp (cdar ls) '() '()))) ;; TODO: support nested cond-expand's (and (pair? imps) (pair? (car imps)) (eq? depends (caar imps)) (list (car clause) (car imps))))) (cdar ls)))) (if (pair? res) (lp (cdr ls) deps `((cond-expand ,@res) ,@cond-deps)) (lp (cdr ls) deps cond-deps)))) (else (append (if (pair? deps) (list (cons depends (reverse deps))) '()) (if (pair? cond-deps) (reverse cond-deps) '()))))))) (define (make-package-name cfg pkg libs . o) (let ((name (or (assoc-get pkg 'name) (any (lambda (x) (or (library-name x) (program-name x))) libs))) (version (and (pair? o) (car o)))) (cond ((not (and (pair? name) (list? name))) (die 2 "Invalid library name: " name)) ((not name) (die 2 "Couldn't determine package name from libs: " libs)) (else (let lp ((ls (if version (append name (list version)) name)) (res '())) (if (null? ls) (string-join (reverse (cons ".tgz" res))) (lp (cdr ls) (cons (x->string (car ls)) (if (null? res) res (cons "-" res)))))))))) (define (check-overwrite cfg file type-pred type-name) (let ((mode (conf-get cfg '(command package overwrite) 'same-type))) (cond ((eq? mode 'always)) ((file-exists? file) (case mode ((never) (die 2 "Destination " file " already exists, not overwriting")) ((same-type) (if (and (not (type-pred file)) (not (yes-or-no? cfg "Destination " file " doesn't look like a " type-name ", overwrite?"))) (die 2 "Not overwriting " file))) ((confirm) (if (not (yes-or-no? cfg "Overwrite existing " file "?")) (die 2 "Not overwriting " file)))))))) ;; Simplistic pretty printing for package/repository/config declarations. (define (write-simple-pretty pkg out) (let wr ((ls pkg) (indent 0) (tails 0)) (cond ((and (pair? ls) (pair? (cdr ls)) (pair? (cadr ls))) (display (make-string indent #\space) out) (write-char #\( out) (write (car ls) out) (newline out) (for-each (lambda (x) (wr x (+ indent 2) 0)) (drop-right (cdr ls) 1)) (wr (last ls) (+ indent 2) (+ tails 1))) (else (display (make-string indent #\space) out) (write ls out) (display (make-string tails #\)) out) (newline out))))) ;; We want to automatically bundle (foo bar *) when packaging (foo bar) ;; if it's already in the same directory. (define (submodule->path cfg base file lib dep) (and base (> (length dep) (length base)) (equal? base (take dep (length base))) ;; TODO: find-library(-relative) (let* ((dir (library-path-base file lib)) (dep-file (make-path dir (string-append (library-name->path cfg dep) ".sld")))) (and (file-exists? dep-file) dep-file)))) (define (package-docs cfg spec libs lib-dirs) (guard (exn (else (warn "package-docs failed" exn) '())) (cond ((conf-get cfg '(command package doc)) => list) ((conf-get cfg '(command package doc-from-scribble)) (filter-map (lambda (lib) (let ((lib-name (library-file-name lib)) (docs (extract-module-file-docs lib #f))) (and (pair? docs) (not (and (= 1 (length docs)) (pair? (car docs)) (eq? 'subsection (caar docs)))) `(inline ,(string-append (library-name->path cfg lib-name) ".html") ,(call-with-output-string (lambda (out) (sxml-display-as-html (generate-docs `((title ,(write-to-string lib-name)) ,docs) (guard (exn (else (make-default-doc-env))) (make-module-doc-env lib-name))) out))))))) libs)) (else '())))) (define package-description (let ((sent-re (regexp '(: "<p>" (* "\n") (* space) ($ (* (or (: "<" (* (~ (">"))) ">") (~ ("<.")))) ".")))) (space-re (regexp '(or (: (* space) "\n" (* space)) (>= 2 space)))) (tag-re (regexp '(: "<" (? "/") (* (~ ("<>"))) ">")))) (lambda (cfg spec libs docs) (cond ((conf-get cfg '(command package description))) ((conf-get cfg '(command upload description))) ;; Crazy hack, make this more robust, probably opt-in. ((and (pair? docs) (pair? (car docs)) (eq? 'inline (caar docs)) (regexp-search sent-re (third (car docs)))) => (lambda (m) (let ((s (regexp-match-submatch m 1))) (and s (string-trim (regexp-replace-all space-re (regexp-replace-all tag-re s "") " ")))))) (else #f))))) (define (package-test cfg) (conf-get cfg '(command package test))) (define (package-license cfg) (conf-get cfg '(command package license))) (define (read-version-file cfg file lib-files) (let ((file (or (find file-exists? (map (lambda (f) (make-path (path-directory f) file)) lib-files)) file))) (call-with-input-file file read-line))) (define (package-output-version cfg lib-files) (cond ((conf-get cfg '(command package version))) ((conf-get cfg '(command upload version))) ((conf-get cfg '(command package version-file)) => (lambda (file) (read-version-file cfg file lib-files))) ((conf-get cfg '(command upload version-file)) => (lambda (file) (read-version-file cfg file lib-files))) (else #f))) (define (package-output-path cfg package-spec libs) (or (conf-get cfg '(command package output)) (make-path (conf-get cfg '(command package output-dir) ".") (make-package-name cfg package-spec (filter (lambda (x) (and (pair? x) (memq (car x) '(library program)))) package-spec) (package-output-version cfg libs))))) (define (replace-library-pattern pat base-lib) (case (and (pair? pat) (car pat)) ((append-to-last) (append (drop-right base-lib 1) (list (string->symbol (string-append (x->string (last base-lib)) (x->string (cadr pat))))))) ((append) (append base-lib (cdr pat))) ((quote) (cadr pat)) (else pat))) (define (find-library-from-pattern cfg pat lib . o) (cond ((not pat) #f) ((and (pair? pat) (eq? 'or (car pat))) (any (lambda (pat) (find-library-from-pattern pat lib)) (cdr pat))) (else (let ((lib-name (replace-library-pattern pat lib))) (apply find-library-file cfg lib-name o))))) (define (tests-from-libraries cfg libs lib-dirs) (let ((pat (conf-get cfg '(command package test-library)))) (cond ((string? pat) (list pat)) ((symbol? pat) (list (symbol->string pat))) (else (filter-map (lambda (lib) (find-library-from-pattern cfg pat lib lib-dirs)) libs))))) (define (test-program-from-libraries lib-files) (call-with-output-string (lambda (out) (let* ((lib-names (filter-map library-file-name lib-files)) (run-names (map (lambda (lib) (string->symbol (string-append "run-" (string-join (map x->string lib) "-") "-tests"))) lib-names))) (for-each (lambda (lib run) (write `(import (rename ,lib (run-tests ,run))) out) (newline out)) lib-names run-names) (newline out) (for-each (lambda (run) (write `(,run) out) (newline out)) run-names))))) (define (package-spec+files cfg spec libs) (define (symbols->strings x) (cond ((symbol? x) (symbol->string x)) ((pair? x) (cons (symbols->strings (car x)) (symbols->strings (cdr x)))) (else x))) (let* ((recursive? (conf-get cfg '(command package recursive?))) (programs (conf-get-list cfg '(command package programs))) (data-files (symbols->strings (conf-get-list cfg '(command package data-files)))) (name (conf-get cfg '(command package name))) (authors (conf-get-list cfg '(command package authors))) (test (package-test cfg)) (version (package-output-version cfg libs)) (maintainers (conf-get-list cfg '(command package maintainers))) (license (package-license cfg))) (let lp ((ls (map (lambda (x) (list x #f)) libs)) (progs programs) (res `(,@(if license `((license ,license)) '()) ,@(if version `((version ,version)) '()) ,@(if (pair? authors) `((authors ,@authors)) '()) ,@(if (pair? maintainers) `((maintainers ,@maintainers)) '()) ,@(if name `((name ,name)) '()))) (files '()) (lib-dirs '()) (test test) (extracted-tests? #f) (seen '())) (cond ((and (pair? ls) (member (caar ls) seen)) (lp (cdr ls) progs res files lib-dirs test extracted-tests? seen)) ((pair? ls) (let* ((lib+files (extract-library cfg (caar ls))) (lib (car lib+files)) (name (library-name lib)) (base (or (second (car ls)) name)) (use-for-test? (and (pair? (cddr (car ls))) (third (car ls)))) (lib (if use-for-test? (append lib '((use-for test))) lib)) (subdeps (if recursive? (filter-map (lambda (x) (submodule->path cfg base (caar ls) name x)) (cond ((assq 'depends (cdr lib)) => cdr) (else '()))) '()))) (lp (append (map (lambda (x) (list x base use-for-test?)) subdeps) (cdr ls)) progs (cons lib res) (append (reverse (cdr lib+files)) files) (delete-duplicates (cons (library-path-base (caar ls) name) lib-dirs)) test extracted-tests? (cons (caar ls) seen)))) ((pair? progs) (lp ls (cdr progs) (cons `(program (path ,(path-strip-leading-parents (car progs))) ,@(extract-program-dependencies (car progs))) res) (cons (car progs) files) lib-dirs test extracted-tests? seen)) ((null? res) (die 2 "No packages generated")) ((and (not test) (not extracted-tests?) (tests-from-libraries cfg (filter-map (lambda (x) (and (library? x) (library-name x))) res) lib-dirs)) => (lambda (tests-from-libraries) (if (pair? tests-from-libraries) (lp (append ls (map (lambda (x) (list x #f #t)) tests-from-libraries)) progs res files lib-dirs `(inline "run-tests.scm" ,(test-program-from-libraries tests-from-libraries)) #t seen) (lp ls progs res files lib-dirs test #t seen)))) (else (let* ((docs (package-docs cfg spec libs lib-dirs)) (desc (package-description cfg spec libs docs)) (test-depends (if test (extract-program-dependencies test 'test-depends) '())) ;; cleanup - package data-files relative to the lib-dir (src-data-files (map (lambda (x) (if (pair? x) (cadr x) x)) data-files)) (rel-data-files (if (= 1 (length lib-dirs)) (map (lambda (f) (path-relative-to f (car lib-dirs))) data-files) src-data-files)) (tar-data-files (map (lambda (src rel) `(rename ,src ,rel)) src-data-files rel-data-files)) (pkg-data-files (if (= 1 (length lib-dirs)) (map (lambda (file rel) (if (pair? file) `(rename ,rel ,(third file)) rel)) data-files rel-data-files) data-files)) (tar-files (reverse (append (cond ((pair? test) (list test)) (test `((rename ,test ,(path-strip-leading-parents test)))) (else '())) (remove (lambda (x) (and (string? x) (or (string-prefix? "http://" x) (string-prefix? "https://" x)))) docs) tar-data-files files)))) (cons `(package ,@(reverse res) ,@(if (pair? data-files) `((data-files ,@pkg-data-files)) '()) ,@(if (pair? docs) `((manual ,@(map (lambda (x) (path-strip-leading-parents (if (pair? x) (cadr x) x))) docs))) '()) ,@(if desc `((description ,desc)) '()) ,@(if test `((test ,(path-strip-leading-parents (if (pair? test) (cadr test) test)))) '()) ,@test-depends) tar-files))))))) (define (create-package spec files path) (gzip (tar-create #f `(,@files (inline "package.scm" ,(call-with-output-string (lambda (out) (write-simple-pretty spec out))))) (let ((dir (path-strip-extension (path-strip-directory path)))) (lambda (f) (make-path dir f))) #t))) (define (command/package cfg spec . libs) (let* ((spec+files (package-spec+files cfg spec libs)) (output (package-output-path cfg (car spec+files) libs)) (tarball (create-package (car spec+files) (cdr spec+files) output))) (check-overwrite cfg output package-file? "package") (let ((out (open-binary-output-file output))) (write-bytevector tarball out) (close-output-port out)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Index - add packages to a local repository file. (define (command/index cfg spec repo-path . pkg-files) (let* ((dir (path-directory repo-path)) (pkgs (filter-map (lambda (pkg-file) (let ((pkg (package-file-meta pkg-file))) (and pkg `(,(car pkg) (url ,(path-relative-to pkg-file dir)) ,@(cdr pkg))))) (if (pair? pkg-files) pkg-files (filter package-file? (map (lambda (f) (make-path dir f)) (directory-files dir)))))) (repo (fold (lambda (pkg repo) (let ((name (package-name pkg))) `(,(car repo) ,pkg ,@(remove (lambda (x) (equal? name (package-name x))) (cdr repo))))) (guard (exn (else (list 'repository))) (car (file->sexp-list repo-path))) pkgs))) (call-with-output-file repo-path (lambda (out) (write-simple-pretty repo out))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Gen-key - generate a new RSA key pair. (define (conf-get-snow-dir cfg) (or (conf-get cfg 'snow-dir) (string-append (get-environment-variable "HOME") "/.snow"))) (define (rsa-key->sexp key name email . o) (let ((password (and (pair? o) (not (equal? "" (car o))) (car o)))) (cond (key `((name ,name) (email ,email) (bits ,(rsa-key-bits key)) ,@(cond (password `((password ,password))) (else '())) ,@(cond ((rsa-key-e key) => (lambda (e) `((public-key (modulus ,(integer->hex-string (rsa-key-n key))) (exponent ,e))))) (else '())) ,@(cond ((rsa-key-d key) => (lambda (d) `((private-key (modulus ,(integer->hex-string (rsa-key-n key))) (exponent ,d))))) (else '())))) (password `((name ,name) (email ,email) (password ,password))) (else (error "neither key nor password provided" email))))) (define (conf-gen-key cfg bits) (show #t "Generating a new key, this may take quite a while...\n") (if (conf-get cfg '(command gen-key gen-key-in-process?)) (rsa-key-gen bits) (let* ((lo (max 3 (expt 2 (- bits 1)))) (hi (expt 2 bits)) (p (fast-eval `(random-prime ,lo ,hi) '((chibi math prime)))) (q (fast-eval `(random-prime-distinct-from ,lo ,hi ,p) '((chibi math prime))))) (rsa-key-gen-from-primes bits p q)))) (define (command/gen-key cfg spec) (show #t "Generate a new key for uploading packages.\n" "We need a descriptive name, and an email address to " "uniquely identify the key.\n") (let* ((name (input cfg '(gen-key name) "Name: ")) (email (input cfg '(gen-key email) "Email: ")) (passwd (input-password cfg '(gen-key password) "Password for upload: " "Password (confirmation): ")) (bits (if (conf-get cfg '(command gen-key gen-rsa-key?)) (input-number cfg '(gen-key bits) "RSA key size in bits: " 0 256 2048) 0)) (key (and (>= bits 256) (conf-gen-key cfg bits))) (snow-dir (conf-get-snow-dir cfg)) (key-file (or (conf-get cfg 'key-file) (string-append snow-dir "/priv-key.scm"))) (old-keys (guard (exn (else '())) (call-with-input-file key-file read))) (new-keys (cons (rsa-key->sexp key name email passwd) ;; TODO: confirm overwrite, preserve old keys (remove (rsa-identity=? email) old-keys)))) (if (not (file-directory? snow-dir)) (create-directory snow-dir)) (let* ((fd (open key-file (bitwise-ior open/write open/create) #o600)) (out (open-output-file-descriptor fd))) (show out "(" (joined (lambda (x) (if (pair? x) (each "(" (joined written x "\n ") ")") (written x))) new-keys "\n ") ")" nl) (close-output-port out) (show #t "Saved key to " key-file ".\n")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Reg-key - register an RSA key pair with a repository. (define (remote-uri cfg name path) (or (conf-get cfg name) (make-path (or (conf-get cfg 'host) "http://snow-fort.org") path))) ;; a subset of http-post functionality that can shell out to curl ;; depending on config (define (snow-post cfg uri params) (cond ((conf-get cfg 'use-curl?) (let ((cmd `(curl --silent ,@(append-map (lambda (x) (cond ((and (pair? (cdr x)) (assq 'value (cdr x))) => (lambda (y) `("-F" ,(string-append (display-to-string (car x)) "=" (write-to-string (display-to-string (cdr y))) "\"")))) ((and (pair? (cdr x)) (assq 'file (cdr x))) => (lambda (y) `("-F" ,(string-append (display-to-string (car x)) "=@" (display-to-string (cdr y)))))) (else `("-F" ,(string-append (display-to-string (car x)) "=" (write-to-string (display-to-string (cdr x)))))))) params) ,(uri->string uri)))) (open-input-bytevector (process->bytevector cmd)))) ((not (conf-get cfg 'non-blocking-io)) (http-post uri params '((blocking . #t)))) (else (http-post uri params)))) (define (remote-command cfg name path params) (let ((uri (remote-uri cfg name path))) (sxml-display-as-text (read (snow-post cfg uri (cons '(fmt . "sexp") params)))) (newline))) (define (command/reg-key cfg spec) (let* ((keys (call-with-input-file (or (conf-get cfg 'key-file) (string-append (conf-get-snow-dir cfg) "/priv-key.scm")) read)) (email (or (conf-get cfg 'email) (assoc-get (car keys) 'email))) (rsa-key-sexp (or (find (rsa-identity=? email) keys) (and (not email) (car keys)))) (name (assoc-get rsa-key-sexp 'name)) ;; Register the sha-256 sum of email and password - we'll ;; never send the password itself over the network. ;; TODO: encrypt this (password (cond ((assoc-get rsa-key-sexp 'password) => (lambda (pw) (sha-256 (string-append email pw)))) (else #f))) (rsa-pub-key (extract-rsa-public-key rsa-key-sexp)) (rsa-pub-key-str (write-to-string (rsa-key->sexp rsa-pub-key name email password)))) (remote-command cfg '(command reg-key uri) "/pkg/reg" `((u (file . "pub-key.scm") (value . ,rsa-pub-key-str)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Sign - sign a package. (define (generate-signature cfg package) (let* ((digest-name (conf-get cfg 'digest 'sha-256)) (digest-func (lookup-digest digest-name)) (raw-data (if (string? package) (call-with-input-file package port->bytevector) package)) (snowball (maybe-gunzip raw-data)) (digest (delay (digest-func snowball))) (keys (call-with-input-file (or (conf-get cfg 'key-file) (string-append (conf-get-snow-dir cfg) "/priv-key.scm")) read)) (email (or (conf-get cfg 'email) (assoc-get (car keys) 'email))) (rsa-key-sexp (find (rsa-identity=? email) keys)) (rsa-key (extract-rsa-private-key rsa-key-sexp)) (use-rsa? (and rsa-key (conf-get cfg 'sign-uploads?)))) (append `(signature (email ,email)) (if (or use-rsa? (not (conf-get cfg 'skip-digest?))) `((digest ,digest-name) (,digest-name ,(force digest))) '()) (if use-rsa? (let* ((sig (fast-eval `(rsa-sign (make-rsa-key ,(rsa-key-bits rsa-key) ,(rsa-key-n rsa-key) #f ,(rsa-key-d rsa-key)) ;;,(hex-string->integer digest) ,(hex-string->bytevector (force digest))) '((chibi crypto rsa)))) (hex-sig (if (bytevector? sig) (bytevector->hex-string sig) (integer->hex-string sig)))) `((rsa ,hex-sig))) '())))) (define (command/sign cfg spec package) (let* ((dst (or (conf-get cfg 'output) (path-replace-extension package "sig"))) (sig (generate-signature cfg package))) (call-with-output-file dst (lambda (out) (write sig out))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Verify - verify a signature. (define (command/verify cfg spec sig) (let* ((sig-spec (cdr (call-with-input-file sig read))) (keys (call-with-input-file (or (conf-get cfg 'key-file) (string-append (conf-get-snow-dir cfg) "/priv-key.scm")) read)) (email (assoc-get sig-spec 'email)) (digest-name (assoc-get sig-spec 'digest #f 'sha-256)) (digest (assoc-get sig-spec digest-name)) (sig (assoc-get sig-spec 'rsa)) (rsa-key-sexp (or (and (string? email) (find (rsa-identity=? email) keys)) (car keys)))) (cond ((not email) (show #t "invalid signature - no email: " sig-spec)) ((not sig) (show #t "no rsa signature in key for: " email)) ((not rsa-key-sexp) (show #t "couldn't find public key in repo for: " email)) (else (let* ((rsa-key (extract-rsa-public-key rsa-key-sexp)) (cipher (rsa-verify rsa-key (hex-string->bytevector sig))) (digest-bv (hex-string->bytevector digest))) (if (equal? cipher digest-bv) (show #t "signature valid " nl) (show #t "signature invalid " cipher " != " digest-bv nl))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Upload - upload a package. (define (get-password cfg package) (and (not (conf-get cfg 'upload-without-password?)) (let* ((keys (call-with-input-file (or (conf-get cfg 'key-file) (string-append (conf-get-snow-dir cfg) "/priv-key.scm")) read)) (email (or (conf-get cfg 'email) (assoc-get (car keys) 'email))) (rsa-key-sexp (find (rsa-identity=? email) keys)) (raw-password (assoc-get rsa-key-sexp 'password))) (and raw-password (sha-256 (string-append email raw-password)))))) (define (upload-package cfg spec package . o) (let ((password `(pw (value . ,(get-password cfg package)))) (pkg (if (string? package) `(u (file . ,package)) `(u (file . ,(if (pair? o) (car o) "package.tgz")) (value . ,package)))) (sig (cond ((conf-get cfg 'sig-file) => (lambda (sig-file) `(sig (file . ,sig-file)))) (else (let ((sig (generate-signature cfg package))) `(sig (file . "package.sig") (value . ,(write-to-string sig)))))))) (remote-command cfg '(command package uri) "/pkg/put" (list password pkg sig)))) (define (command/upload cfg spec . o) (define (non-homogeneous) (die 1 "upload arguments must all be packages or all be libraries, " "but got " o)) (cond ((null? o) (die 1 "upload requires at least one input argument")) ((package-file? (car o)) (if (not (every package-file? (cdr o))) (non-homogeneous)) ;; TODO: include a summary (version, file size, etc.) (if (yes-or-no? cfg "Upload " o " to " (remote-uri cfg '(command package uri) "/?")) (for-each (lambda (package) (upload-package cfg spec package)) o))) (else (if (any package-file? (cdr o)) (non-homogeneous)) (let* ((spec+files (package-spec+files cfg spec o)) (package-file (package-output-path cfg (car spec+files) o)) (package (create-package (car spec+files) (cdr spec+files) package-file))) ;; TODO: include a summary (version, file size, etc.) (if (yes-or-no? cfg "Upload " o " to " (remote-uri cfg '(command package uri) "/?")) (upload-package cfg spec package package-file)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Remove - removes the listed libraries. ;; ;; Provides a summary of the libraries to remove along with any ;; dependencies they have which were not explicitly installed. (define (remove-with-sudo? cfg path) (case (or (conf-get cfg '(command remove use-sudo?)) (conf-get cfg '(command upgrade use-sudo?))) ((always) #t) ((never) #f) (else (not (file-is-writable? (path-directory path)))))) (define (remove-file cfg file) (if (remove-with-sudo? cfg file) (system "sudo" "rm" file) (delete-file file))) (define (remove-directory cfg dir) (if (remove-with-sudo? cfg dir) (system "sudo" "rmdir" dir) (delete-directory dir))) (define (warn-delete-file cfg file) (guard (exn (else (warn "couldn't delete file: " file))) (remove-file cfg file))) (define (delete-library-files impl cfg pkg lib-name) (for-each (lambda (f) (warn-delete-file cfg f)) (package-installed-files pkg)) (warn-delete-file cfg (make-path (get-install-source-dir impl cfg) (get-package-meta-file cfg pkg))) (cond ((package->path cfg pkg) => (lambda (path) (let ((dir (make-path (get-install-source-dir impl cfg) path))) (if (and (file-directory? dir) (= 2 (length (directory-files dir)))) (remove-directory cfg dir))) (when (eq? impl 'guile) (let ((go-file (string-append (make-path (get-install-library-dir impl cfg) path) ".go"))) (warn-delete-file cfg go-file))))))) (define (command/remove cfg spec . args) (let* ((impls (conf-selected-implementations cfg)) (impl-cfgs (map (lambda (impl) (conf-for-implementation cfg impl)) impls)) (lib-names (map parse-library-name args))) (for-each (lambda (impl impl-cfg) (for-each (lambda (pkg lib-name) (delete-library-files impl impl-cfg (cdr pkg) lib-name)) (lookup-installed-libraries impl impl-cfg lib-names) lib-names)) impls impl-cfgs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Search - search for libraries matching keywords. ;; ;; Prints a list of libraries whose meta-info contain any of the given ;; keywords. Returns in sorted order for how well the package matches. (define (summarize-libraries cfg lib-names+pkgs) (for-each (lambda (name pkg) (describe-library cfg name pkg)) (map car lib-names+pkgs) (map cdr lib-names+pkgs))) (define (string-count-word str word) (let lp ((sc (string-cursor-start str)) (count 0)) (let ((sc2 (string-contains str word sc))) (if sc2 (lp (string-cursor-next str sc2) (+ count 1)) count)))) (define (count-in-sexp x keywords) (let ((s (string-downcase (write-to-string x)))) (fold (lambda (k sum) (+ sum (string-count-word s k))) 0 (map string-downcase keywords)))) (define (extract-matching-libraries cfg repo keywords) (define (library-score lib) (+ (* 10 (count-in-sexp (library-name lib) keywords)) (count-in-sexp lib keywords) (let ((use-for (assq 'use-for (cdr lib)))) (apply max 0 (map (lambda (x) (case x ((test) 0) ((build) 10) (else 100))) (if (pair? use-for) (cdr use-for) (list use-for))))))) (append-map (lambda (x) (cond ((not (package? x)) '()) (else (let ((pkg-score (count-in-sexp x keywords)) (libs (package-libraries x))) (if (or (zero? pkg-score) (null? libs)) '() (let lp ((libs (cdr libs)) (best-score (library-score (car libs))) (best-lib (car libs))) (cond ((null? libs) (list (cons (+ best-score pkg-score) (cons (library-name best-lib) x)))) (else (let ((score (library-score (car libs)))) (if (> score best-score) (lp (cdr libs) score (car libs)) (lp (cdr libs) best-score best-lib))))))))))) repo)) (define (extract-sorted-packages cfg repo keywords) (let ((ls (extract-matching-libraries cfg repo keywords))) (map cdr (sort ls > car)))) (define (command/search cfg spec . keywords) (let* ((repo (current-repositories cfg)) (lib-names+pkgs (extract-sorted-packages cfg repo keywords)) (sexp? (conf-get cfg 'sexp?))) (cond ((or (pair? lib-names+pkgs) sexp?) (if sexp? (display "(")) (summarize-libraries cfg lib-names+pkgs) (if sexp? (display ")\n"))) (else (display "No libraries matched your query.\n"))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Show - show detailed information for the given libraries ;; ;; The typical pattern is to use search to find the names of libraries ;; of interest, and show to see detailed information to decide whether ;; or not to install them. (define (describe-library cfg library-name pkg) (let ((sexp? (conf-get cfg 'sexp?))) (if sexp? (display "(")) (display library-name) (display (if sexp? " " "\t")) ((if sexp? write display) (package-version pkg)) (if sexp? (display ")")) (newline))) (define (command/show cfg spec . args) (current-repositories cfg) (let* ((impls (conf-selected-implementations cfg)) (impl-cfgs (map (lambda (impl) (conf-for-implementation cfg impl)) impls)) (lib-names (map parse-library-name args))) (for-each (lambda (impl impl-cfg) (for-each (lambda (name pkg) (describe-library impl-cfg name pkg)) (lookup-installed-libraries impl impl-cfg lib-names) lib-names)) impls impl-cfgs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Update - update the repository. (define (valid-repository? repo) (and (pair? repo) (list? repo) (eq? 'repository (car repo)))) (define (repository-dir cfg) (cond ((zero? (current-user-id)) (or (conf-get cfg 'local-root-repository) "/usr/local/share/snow/repo")) (else (or (conf-get cfg 'local-user-repository) (make-path (conf-get-snow-dir cfg) "repo"))))) (define (repository-local-path cfg repo-uri) (let* ((repo-id (substring (sha-224 (string->utf8 repo-uri)) 0 32)) (local-dir (repository-dir cfg)) (local-base (string-append "repo-" repo-id ".scm"))) (make-path local-dir local-base))) (define (update-repository cfg repo-uri) (let* ((local-path (repository-local-path cfg repo-uri)) (local-dir (path-directory local-path)) (local-tmp (string-append local-path ".tmp." (number->string (current-second)) "-" (number->string (current-process-id)))) (repo-str (utf8->string (resource->bytevector cfg repo-uri))) (repo (guard (exn (else #f)) (let ((repo (read (open-input-string repo-str)))) `(,(car repo) (url ,repo-uri) ,@(cdr repo)))))) (cond ((not (valid-repository? repo)) (warn "not a valid repository" repo-uri repo)) ((not (create-directory* local-dir)) (warn "can't create directory" local-dir)) (else (guard (exn (else (die 2 "couldn't write repository"))) (call-with-output-file local-tmp (lambda (out) (write repo out))) (if (file-exists? local-path) (rename-file local-path (string-append local-path ".bak"))) (rename-file local-tmp local-path) repo))))) (define (repository-stale? cfg repo-uri) (let ((local-path (repository-local-path cfg repo-uri))) (guard (exn (else #t)) (> (current-second) (+ (file-modification-time local-path) ;; by default update once every 3 hours (conf-get cfg 'update-refresh (* 3 60 60))))))) (define (should-update-repository? cfg repo-uri) (case (conf-get cfg 'update-strategy 'cache) ((always) #t) ((never) #f) ((cache) (repository-stale? cfg repo-uri)) ((confirm) (and (repository-stale? cfg repo-uri) (yes-or-no? cfg "Update repository info?"))) (else (warn "unknown update-stategy: " (conf-get cfg 'update-strategy)) #f))) ;; returns the single repo as a sexp, updated as needed (define (maybe-update-repository cfg repo-uri) (or (guard (exn (else (warn "error updating remote repository: " repo-uri " error: " exn) #f)) (and (should-update-repository? cfg repo-uri) (update-repository cfg repo-uri))) (guard (exn (else (warn "error reading local repository: " exn) '(repository))) (call-with-input-file (repository-local-path cfg repo-uri) read)))) (define (get-repository-list cfg) (let ((ls (conf-get-list cfg 'repository-uri))) (if (pair? ls) ls (list (remote-uri cfg 'default-repository "/s/repo.scm"))))) ;; returns all repos merged as a sexp, updated as needed ;; not to be confused with the current-repo util in (chibi snow fort) ;; which returns the single host (define (current-repositories cfg) (define (make-loc uri trust depth) (vector uri trust depth)) (define (loc-uri loc) (vector-ref loc 0)) (define (loc-trust loc) (vector-ref loc 1)) (define (loc-depth loc) (vector-ref loc 2)) (define (adjust-package-urls ls uri) (map (lambda (x) (cond ((and (pair? x) (eq? 'package (car x)) (assq 'url (cdr x))) => (lambda (y) (set-car! (cdr y) (uri-resolve (cadr y) (string->path-uri 'http uri)))))) x) (remove (lambda (x) (and (pair? x) (eq? 'url (car x)))) ls))) (let lp ((ls (map (lambda (x) (make-loc x 1.0 0)) (get-repository-list cfg))) (seen '()) (res '())) (cond ((null? ls) (cons 'repository (reverse res))) ((> (loc-depth (car ls)) (conf-get cfg 'sibling-depth-limit 1000)) (warn "skipping sibling repo at max depth: " (loc-uri (car ls)) (loc-depth (car ls))) (lp (cdr ls))) ((< (loc-trust (car ls)) (conf-get cfg 'sibling-min-trust 0.0)) (warn "skipping sibling repo with low trust: " (loc-uri (car ls)) (loc-trust (car ls)) ) (lp (cdr ls))) (else (let ((uri (uri-normalize (loc-uri (car ls))))) (if (member uri seen) (lp (cdr ls) seen res) (let* ((repo (maybe-update-repository cfg uri)) (siblings (if (and (valid-repository? repo) (conf-get cfg 'follow-siblings? #t)) (let ((uri-base (if (string-suffix? "/" uri) uri (uri-directory uri)))) (filter-map (lambda (x) (and (pair? x) (eq? 'sibling (car x)) (assoc-get (cdr x) 'url) (make-loc (uri-resolve (assoc-get (cdr x) 'url) uri-base) (* (loc-trust (car ls)) (or (assoc-get (cdr x) 'trust) 1.0)) (+ (loc-depth (car ls)) 1)))) (cdr repo))) '())) (res (if (valid-repository? repo) (let ((multi? (or (pair? res) (pair? siblings) (pair? (cdr ls))))) (append (reverse (if multi? (adjust-package-urls (cdr repo) uri) (cdr repo))) res)) (begin (if repo (warn "invalid repository for uri: " uri)) res)))) (lp (append siblings (cdr ls)) (cons uri seen) res)))))))) (define (command/update cfg spec) (current-repositories (conf-extend cfg '((update-strategy . always))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Install - install one or more libraries. ;; ;; Installs the listed libraries along with their transitive closure ;; of dependencies. For each library to install we confirm the ;; current status (skipping if already installed), the signature and ;; trust (optionally updating the trust level), and the default tests. ;; If multiple implementations are targeted, we install separately but ;; use the same confirmations for each. (define (get-chicken-binary-version cfg) (or (conf-get cfg 'chicken-binary-version) (string->number (process->string '(csi -p "(##sys#fudge 42)"))) 8)) (define (get-chicken-repo-path) (let ((release (string-trim (process->string '(csi -release)) char-whitespace?))) (string-trim (if (string-prefix? "4." release) (process->string '(csi -p "(repository-path)")) (process->string '(csi -R chicken.platform -p "(car (repository-path))"))) char-whitespace?))) (define (get-guile-site-dir) (process->string '(guile -c "(display (%site-dir))"))) (define (get-guile-site-ccache-dir) (process->string '(guile -c "(display (%site-ccache-dir))"))) (define (get-install-dirs impl cfg) (define (guile-eval expr) (guard (exn (else #f)) (process->sexp `(guile -c ,(write-to-string `(write ,expr)))))) (case impl ((chibi) (let* ((dirs (reverse (cond-expand (chibi (eval '(current-module-path) (environment '(chibi)))) (else (process->sexp '(chibi-scheme -q -p "(current-module-path)")))))) (share-dir (find (lambda (d) (string-contains d "/share/")) dirs))) (if share-dir (cons share-dir (delete share-dir dirs)) dirs))) ((chicken) (let ((dir (get-chicken-repo-path))) (list (if (file-exists? dir) ; repository-path should always exist dir (make-path (or (conf-get cfg 'install-prefix)) "lib" impl (get-chicken-binary-version cfg)))))) ((cyclone) (let ((dir (let ((lib-path (get-environment-variable "CYCLONE_LIBRARY_PATH"))) (if lib-path (car (string-split lib-path #\:)) ; searches only in the first path set (string-trim (process->string '(icyc -p "(Cyc-installation-dir 'sld)")) char-whitespace?))))) (list (or dir "/usr/local/share/cyclone/")))) ((gauche) (list (let ((dir (string-trim (process->string '(gauche-config "--sitelibdir")) char-whitespace?))) (or (and (string? dir) (> (string-length dir) 0) (eqv? #\/ (string-ref dir 0)) dir) "/usr/local/share/gauche/")))) ((guile) (let ((path (guile-eval '(string-append (cdr (assq 'pkgdatadir %guile-build-info)) (string (integer->char 47)) (effective-version))))) (list (if (string? path) path "/usr/local/share/guile/")))) ((larceny) (list (make-path (string-trim (process->string '(larceny -quiet -nobanner -- -e "(begin (display (getenv \"LARCENY_ROOT\")) (exit))")) char-whitespace?) "lib/Snow"))) (else (list (make-path (or (conf-get cfg 'install-prefix) "/usr/local") "share/snow" impl))))) (define (get-install-library-dirs impl cfg) (case impl ((chibi) (let* ((dirs (reverse (cond-expand (chibi (eval '(current-module-path) (environment '(chibi)))) (else (process->sexp '(chibi-scheme -q -p "(current-module-path)")))))) (lib-dir (find (lambda (d) (and (equal? (string-ref d 0) #\/) (string-contains d "/lib"))) dirs))) (if lib-dir (cons lib-dir (delete lib-dir dirs)) dirs))) (else (list (make-path (or (conf-get cfg 'install-prefix) "/usr/local") "lib" impl))))) (define (scheme-script-command impl cfg) (or (and (eq? impl 'chibi) (conf-get cfg 'chibi-path)) (let* ((prog (cond ((conf-get cfg 'scheme-script)) ((assq impl known-implementations) => cadr) (else "scheme-script"))) (path (or (find-in-path prog) prog)) (arg (case impl ((chicken) "-s") ((cyclone) "-s") ((gauche) "-b") ((larceny) "-program") (else #f)))) (if (and path arg) (string-append path " " arg) path)))) (define (scheme-program-command impl cfg file . o) (cond ((conf-get cfg 'scheme-program-command) => string-split) (else (let ((lib-path (and (pair? o) (car o))) (install-dir (get-install-source-dir impl cfg))) (case impl ((chibi) (let ((chibi (string-split (conf-get cfg 'chibi-path "chibi-scheme")))) (if lib-path `(,@chibi -A ,install-dir -A ,lib-path ,file) `(,@chibi -A ,install-dir ,file)))) ((chicken) (if lib-path `(csi -R r7rs -I ,install-dir -I ,lib-path -s ,file) `(csi -R r7rs -I ,install-dir -s ,file))) ((cyclone) (if lib-path `(icyc -A ,install-dir -A ,lib-path -s ,file) `(icyc -A ,install-dir -s ,file))) ((foment) (if lib-path `(foment -A ,install-dir -A ,lib-path ,file) `(foment -A ,install-dir ,file))) ((gauche) (if lib-path `(gosh -A ,install-dir -A ,lib-path ,file) `(gosh -A ,install-dir ,file))) ((guile) (if lib-path `(guile -L ,install-dir -L ,lib-path ,file) `(guile -L ,install-dir ,file))) ((kawa) (let ((install-dir (path-resolve install-dir (current-directory)))) (if lib-path `(kawa ,(string-append "-Dkawa.import.path=" install-dir ":" (path-resolve lib-path (current-directory))) --r7rs --script ,file) `(kawa ,(string-append "-Dkawa.import.path=" install-dir) --r7rs --script ,file)))) ((larceny) (if lib-path `(larceny -r7rs -path ,(string-append install-dir ":" lib-path) -program ,file) `(larceny -r7rs -path ,install-dir -program ,file))) (else #f)))))) (define (get-install-search-dirs impl cfg) (let ((install-dir (get-install-source-dir impl cfg)) (other-dirs (get-install-dirs impl cfg))) (cons install-dir (delete install-dir other-dirs)))) (define (find-library-meta impl cfg name) (let ((dirs (get-install-search-dirs impl cfg))) (let lp ((subname name)) (or (find-sexp-in-path (package-name->meta-file cfg subname) dirs (lambda (x) (and (package? x) (or (equal? name (package-name x)) (any (lambda (y) (equal? name (library-name y))) (package-libraries x)) (any (lambda (y) (equal? name (program-name y))) (package-programs x)))))) (and (pair? (cdr subname)) (lp (drop-right subname 1))))))) ;; test the package locally built in dir (define (test-package impl cfg pkg dir) (let* ((test-file (cond ((assoc-get pkg 'test) => (lambda (f) (path-resolve f dir))) (else #f))) (command (scheme-program-command impl cfg test-file dir))) (cond ((and test-file command (not (or (conf-get cfg '(command install skip-tests?)) (conf-get cfg '(command upgrade skip-tests?))))) ;; install any data files locally in the dir (let ((true-install-dir (get-install-data-dir impl cfg)) (test-install-dir (make-path dir (string-append "tmp-data-" (number->string (current-process-id))))) (data-files (package-data-files pkg))) (for-each (lambda (file) (let* ((src (make-path dir (if (pair? file) (cadr file) file))) (dest0 (if (pair? file) (third file) file)) (dest (make-path test-install-dir (if (path-absolute? dest0) (path-relative-to dest0 true-install-dir) dest0)))) (create-directory* (path-directory dest)) (install-file cfg src dest))) (package-data-files pkg)) (setenv "SNOW_TEST_DATA_DIR" test-install-dir)) ;; Run the tests from within the temp directory. This reduces ;; stray output in the pwd, can be useful for accessing data ;; files during testing, and is needed for chicken (see chicken ;; trac #736). ;; For chibi we run from the current directory anyway for the ;; sake of running snow-tests from an uninstalled chibi-scheme. (or (match ((if (eq? impl 'chibi) (lambda (dir f) (f)) with-directory) dir (lambda () (process->output+error+status command))) ((output error status) (cond ((or (not (zero? status)) (string-contains output "FAIL") (string-contains error "FAIL") (string-contains output "ERROR") (string-contains error "ERROR")) (call-with-output-file (make-path dir "test-out.txt") (lambda (out) (display output out))) (call-with-output-file (make-path dir "test-err.txt") (lambda (err) (display error err))) (display output) (display error) #f) (else (info "All tests passed.") (cond ((or (conf-get cfg '(command install show-tests?)) (conf-get cfg '(command upgrade show-tests?))) (display output) (display error))) #t))) (other (warn "Test error: " other) #f)) (yes-or-no? cfg "Tests failed: " test-file " (details in " dir "/test-{out,err}.txt)\n" "Proceed anyway?"))) (else #t)))) (define (lookup-installed-libraries impl cfg names) (map (lambda (name) (cons name (or (find-library-meta impl cfg name) `(not-installed ,name)))) names)) (define (installed-libraries impl cfg) (delete-duplicates (append-map (lambda (dir) (directory-fold-tree dir #f #f (lambda (file acc) (cond ((and (equal? "meta" (path-extension file)) (guard (exn (else (warn "read meta failed" exn) #f)) (let ((pkg (call-with-input-file file read))) (and (package? pkg) (every file-exists? (package-installed-files pkg)) pkg)))) => (lambda (pkg) (append (map (lambda (lib) (cons (library-name lib) pkg)) (package-libraries pkg)) acc))) (else acc))) '())) (get-install-search-dirs impl cfg)) (lambda (a b) (equal? (car a) (car b))))) (define r7rs-small-libraries '(base case-lambda char complex cxr eval file inexact lazy load process-context r5rs read repl time write)) ;; chibi is not included because chibi is already installed with full ;; package information for each builtin library (define native-srfi-support '((foment 60) (gauche 0 1 4 5 7 9 11 13 14 19 26 27 29 31 37 42 43 55) (guile 0 1 2 4 6 8 9 10 11 13 14 16 17 18 19 23 26 27 28 30 31 34 35 37 38 39 41 42 43 45 46 55 60 61 62 64 67 69 71 87 88 98 105 111 171) (kawa 1 2 13 14 34 37 60 69 95) (larceny 0 1 2 4 5 6 7 8 9 11 13 14 16 17 19 22 23 25 26 27 28 29 30 31 37 38 39 41 42 43 45 48 51 54 56 59 60 61 62 63 64 66 67 69 71 74 78 86 87 95 96 98))) (define native-self-support '((kawa base expressions hashtable quaternions reflect regex rotations string-cursors) (gauche array auxsys cgen charconv collection common-macros condutil config defvalues dictionary fileutil hashutil hook interactive interpolate let-opt libutil listener logger logical macroutil modutil net numerical package parameter parseopt portutil procedure process redefutil regexp reload selector sequence serializer signal singleton sortutil stringutil syslog termios test threads time treeutil uvector validator version vport) )) ;; Currently we make assumptions about default installed libraries of ;; the form (scheme *), (srfi *) and (<impl> *), but don't make any ;; particular effort to analyze other libraries installed outside of ;; the snow-chibi command. When adding support for versioning we can ;; keep in mind that srfi's are a fixed version, scheme is for the ;; forseeable future tied to the current standard (R7RS), and all core ;; <impl> libraries will be tied to the installed implementation ;; version, although in all cases the actual installed library may ;; have its own version due to improvements and bugfixes. (define (implementation-supports-natively? impl cfg lib-name) (and (pair? lib-name) (or (and (eq? 'scheme (car lib-name)) (= 2 (length lib-name)) (memq (cadr lib-name) r7rs-small-libraries)) (and (eq? 'srfi (car lib-name)) (= 2 (length lib-name)) (cond ((assq impl native-srfi-support) => (lambda (x) (memq (cadr lib-name) (cdr x)))) ((eq? impl 'chicken) (file-exists? (make-path (get-install-library-dir impl cfg) (string-append "srfi-" (number->string (cadr lib-name)) ".import.so")))) (else #f))) (equal? lib-name (list impl)) (and (eq? impl (car lib-name)) (= 2 (length lib-name)) (cond ((assq impl native-self-support) => (lambda (x) (memq (cadr lib-name) (cdr x)))) (else #f))) ))) (define (get-install-source-dir impl cfg) (cond ((eq? impl 'chicken) (get-install-library-dir impl cfg)) ((eq? impl 'cyclone) (get-install-library-dir impl cfg)) ((eq? impl 'guile) (get-guile-site-dir)) ((conf-get cfg 'install-source-dir)) ((conf-get cfg 'install-prefix) => (lambda (prefix) (make-path prefix "share/snow" impl))) (else snow-module-directory))) (define (get-install-data-dir impl cfg) (cond ((eq? impl 'chicken) (get-install-library-dir impl cfg)) ((eq? impl 'cyclone) (get-install-library-dir impl cfg)) ((conf-get cfg 'install-data-dir)) ((conf-get cfg 'install-prefix) => (lambda (prefix) (make-path prefix "share/snow" impl))) (else snow-module-directory))) (define (get-install-library-dir impl cfg) (cond ((conf-get cfg 'install-library-dir)) ((eq? impl 'chicken) (cond ((conf-get cfg 'install-prefix) => (lambda (prefix) (make-path prefix "lib" impl (get-chicken-binary-version cfg)))) (else (car (get-install-dirs impl cfg))))) ((eq? impl 'cyclone) (car (get-install-dirs impl cfg))) ((eq? impl 'guile) (get-guile-site-ccache-dir)) ((conf-get cfg 'install-prefix) => (lambda (prefix) (make-path prefix "lib" impl))) (else snow-binary-module-directory))) (define (get-install-binary-dir impl cfg) (cond ((conf-get cfg 'install-binary-dir)) ((conf-get cfg 'install-prefix) => (lambda (prefix) (make-path prefix "bin"))) (else "/usr/local/bin"))) (define (get-library-extension impl cfg) (or (conf-get cfg 'library-extension) (case impl ((gauche kawa) "scm") (else "sld")))) (define (install-with-sudo? cfg path) (case (or (conf-get cfg '(command install use-sudo?)) (conf-get cfg '(command upgrade use-sudo?))) ((always) #t) ((never) #f) (else (let lp ((path path)) (let ((dir (path-directory path))) (and (not (file-is-writable? path)) (or (file-exists? path) (lp dir)))))))) (define (install-file cfg source dest) (if (not (equal? source dest)) (if (install-with-sudo? cfg dest) (system "sudo" "cp" source dest) (system "cp" source dest)))) (define (install-sexp-file cfg obj dest) (if (install-with-sudo? cfg dest) (call-with-temp-file "sexp" (lambda (tmp-path out preserve) (write-simple-pretty obj out) (close-output-port out) (system "sudo" "cp" tmp-path dest) (system "sudo" "chmod" "644" dest))) (call-with-output-file dest (lambda (out) (write-simple-pretty obj out))))) (define (install-symbolic-link cfg source dest) (if (install-with-sudo? cfg dest) (system "sudo" "ln" "-s" source dest) (symbolic-link-file source dest))) (define (install-directory cfg dir) (cond ((file-directory? dir)) ((install-with-sudo? cfg dir) (system "sudo" "mkdir" "-p" dir)) (else (create-directory* dir)))) (define (should-install-library? impl cfg lib) (let ((use-for (assq 'use-for (cdr lib)))) (or (not (and (pair? use-for) (not (or (memq 'build use-for) (memq 'final use-for))))) (conf-get cfg '(command install install-tests?)) (conf-get cfg '(command upgrade install-tests?))))) (define (install-package-meta-info impl cfg pkg) (let* ((meta-file (get-package-meta-file cfg pkg)) (install-dir (get-install-source-dir impl cfg)) (path (make-path install-dir meta-file))) ;; write the package name (install-sexp-file cfg pkg path) ;; symlink utility libraries for which the package can't be inferred (let ((pkg-name (package-name pkg))) (for-each (lambda (lib) (let ((lib-name (library-name lib))) (if (and (not (equal? pkg-name (take lib-name (length pkg-name)))) (should-install-library? impl cfg lib)) (let* ((lib-meta (make-path install-dir (get-library-meta-file cfg lib))) (rel-path (path-relative-to path (path-directory lib-meta)))) (install-symbolic-link cfg rel-path lib-meta))))) (package-libraries pkg))))) ;; The default installer just copies the library file and any included ;; source files to the installation directory. ;; Returns a list of installed files. (define (default-installer impl cfg library dir) (let* ((library-file (get-library-file cfg library)) (ext (get-library-extension impl cfg)) (dest-library-file (string-append (library->path cfg library) "." ext)) (include-files (library-include-files impl cfg (make-path dir library-file))) (install-dir (get-install-source-dir impl cfg)) (install-lib-dir (get-install-library-dir impl cfg))) ;; install the library file (let ((path (make-path install-dir dest-library-file))) (install-directory cfg (path-directory path)) (install-file cfg (make-path dir library-file) path) ;; install any includes (cons path (append (map (lambda (x) (let ((dest-file (make-path install-dir (path-relative x dir)))) (install-directory cfg (path-directory dest-file)) (install-file cfg x dest-file) dest-file)) include-files) (map (lambda (x) (let* ((so-file (string-append x (cond-expand (macosx ".dylib") (else ".so")))) (dest-file (make-path install-lib-dir (path-relative so-file dir)))) (install-directory cfg (path-directory dest-file)) (install-file cfg so-file dest-file) dest-file)) (library-shared-include-files impl cfg (make-path dir library-file)))))))) (define (chicken-library-base name) (if (and (= 2 (length name)) (eq? 'srfi (car name)) (integer? (cadr name))) (string-append "srfi-" (number->string (cadr name))) (string-join (map x->string name) "."))) (define (chicken-installer impl cfg library dir) (let* ((library-file (get-library-file cfg library)) (name (library-name library)) (library-base (chicken-library-base name)) (install-dir (get-install-library-dir impl cfg)) (so-path (string-append library-base ".so")) (imp-path (string-append library-base ".import.scm")) (dest-so-path (make-path install-dir so-path)) (dest-imp-path (make-path install-dir imp-path))) (install-directory cfg install-dir) (let ((meta-dir (string-join (map x->string (drop-right (library-name library) 1)) "/"))) (install-directory cfg (make-path install-dir meta-dir))) (install-file cfg (make-path dir so-path) dest-so-path) (install-file cfg (make-path dir imp-path) dest-imp-path) (list dest-so-path dest-imp-path))) (define (cyclone-installer impl cfg library dir) (let* ((library-file (get-library-file cfg library)) (install-dir (get-install-library-dir impl cfg)) (so-path (string-append (path-strip-extension library-file) ".so")) (dest-so-path (make-path install-dir so-path)) (o-path (string-append (path-strip-extension library-file) ".o")) (dest-o-path (make-path install-dir o-path))) (install-directory cfg (path-directory dest-so-path)) (install-file cfg (make-path dir so-path) dest-so-path) (install-file cfg (make-path dir o-path) dest-o-path) (cons dest-o-path (cons dest-so-path (default-installer impl cfg library dir))))) (define (guile-installer impl cfg library dir) (let* ((source-scm-file (get-library-file cfg library)) (source-go-file (string-append (library->path cfg library) ".go")) (dest-scm-file (string-append (library->path cfg library) ".scm")) (dest-go-file (string-append (library->path cfg library) ".go")) (include-files (library-include-files impl cfg (make-path dir source-scm-file))) (install-dir (get-install-source-dir impl cfg)) (install-lib-dir (get-install-library-dir impl cfg))) (let ((scm-path (make-path install-dir dest-scm-file)) (go-path (make-path install-lib-dir dest-go-file))) (install-directory cfg (path-directory scm-path)) (install-directory cfg (path-directory go-path)) (install-file cfg (make-path dir source-scm-file) scm-path) (install-file cfg (make-path dir source-go-file) go-path) ;; install any includes (cons scm-path (append (map (lambda (x) (let ((dest-file (make-path install-dir (path-relative x dir)))) (install-directory cfg (path-directory dest-file)) (install-file cfg x dest-file) dest-file)) include-files) (map (lambda (x) (let* ((so-file (string-append x (cond-expand (macosx ".dylib") (else ".so")))) (dest-file (make-path install-lib-dir (path-relative so-file dir)))) (install-directory cfg (path-directory dest-file)) (install-file cfg so-file dest-file) dest-file)) (library-shared-include-files impl cfg (make-path dir source-scm-file)))))))) ;; installers should return the list of installed files (define (lookup-installer installer) (case installer ((chicken) chicken-installer) ((cyclone) cyclone-installer) ((guile) guile-installer) (else default-installer))) (define (installer-for-implementation impl cfg) (case impl ((chicken) 'chicken) ((cyclone) 'cyclone) ((guile) 'guile) (else 'default))) (define (install-library impl cfg library dir) (if (should-install-library? impl cfg library) (let ((installer (lookup-installer (or (conf-get cfg 'installer) (installer-for-implementation impl cfg))))) (installer impl cfg library dir)))) ;; The default builder just renames files per implementation. ;; Returns a new library object with any renames. (define (default-builder impl cfg library dir) (let* ((library-file (get-library-file cfg library)) (ext (get-library-extension impl cfg)) (src-library-file (make-path dir library-file)) (library-dir (path-directory src-library-file)) (dest-library-file (string-append (library->path cfg library) "." ext)) (dest-dir (path-directory (make-path dir dest-library-file))) (include-files (library-include-files impl cfg (make-path dir library-file))) (rewrite-include-files ;; Rewrite if any include has the same path as the library ;; declaration file after extension renaming. ;; TODO: Also rewrite for implementations which require certain ;; characters to be escaped. ;; TODO: Also rewrite if multiple libs use same file names? ;; For now we assume libraries with the same prefix cooperate. (filter-map (lambda (x) (and (equal? x (make-path dir dest-library-file)) (list x (string-append x ".renamed.scm")))) include-files)) (relative-rewrite-include-files (map (lambda (x) (list (path-relative-to (car x) library-dir) (path-relative-to (cadr x) library-dir))) rewrite-include-files))) ;; ensure the build directory exists (create-directory* dest-dir) ;; rename or copy includes (for-each (lambda (x) (rename-file (car x) (cadr x))) rewrite-include-files) (for-each (lambda (x) (let ((dest-file (make-path dest-dir (path-relative x library-dir)))) (install-directory cfg (path-directory dest-file)) (install-file cfg x dest-file) dest-file)) (filter (lambda (f) (not (equal? f dest-library-file))) include-files)) ;; install the library declaration file (cond ((pair? rewrite-include-files) ;; If we needed to rename an include file, we also need to rewrite ;; the library declaration itself to point to the new location. ;; TODO: rewrite with a structural editor to preserve formatting (let ((library (library-rewrite-includes (car (file->sexp-list src-library-file)) relative-rewrite-include-files))) (install-sexp-file cfg library (make-path dir dest-library-file)) (if (not (equal? library-file dest-library-file)) (delete-file src-library-file)))) ((not (equal? library-file dest-library-file)) (rename-file src-library-file (make-path dir dest-library-file)))) ;; return the rewritten library (library-rewrite-includes library (append relative-rewrite-include-files (if (equal? library-file dest-library-file) '() (list (list library-file dest-library-file))))))) ;; first call the default builder to fix paths, then compile any ffi files (define (chibi-builder impl cfg library dir) (let* ((library (default-builder impl cfg library dir)) (library-file (make-path dir (get-library-file cfg library))) (shared-includes (library-shared-include-files impl cfg library-file)) (local-test? (file-exists? "tools/chibi-ffi")) (chibi-ffi (if local-test? (scheme-program-command impl cfg "tools/chibi-ffi") '("chibi-ffi"))) (cc (string-split (or (conf-get cfg 'cc) (get-environment-variable "CC") "cc"))) (cflags (string-split (or (conf-get cfg 'cflags) (get-environment-variable "CFLAGS") "")))) (let lp ((ls shared-includes)) (if (null? ls) library (let* ((base (car ls)) (stub-file (string-append base ".stub")) (c-file (string-append base ".c")) (so-file (string-append base (cond-expand (macosx ".dylib") (else ".so")))) (so-flags (cond-expand (macosx '("-dynamiclib" "-Oz")) (else '("-fPIC" "-shared" "-Os")))) (lib-flags (map (lambda (lib) (string-append "-l" lib)) (library-foreign-dependencies impl cfg library))) (ffi-cmd `(,@chibi-ffi "-c" "-cc" ,(car cc) "-f" ,(string-join cflags " ") "-f" ,(string-join lib-flags " ") ,@(if local-test? '("-f" "-Iinclude -L.") '()) ,@(if (pair? (cdr cc)) (list "-f" (string-join (cdr cc) " ")) '()) ,stub-file)) (cc-cmd `(,@cc ,@cflags ,@so-flags ,@(if local-test? '("-Iinclude" "-L.") '()) "-o" ,so-file ,c-file "-lchibi-scheme" ,@lib-flags))) (when (or (and (file-exists? c-file) (or (system? cc-cmd) (yes-or-no? cfg "couldn't compile chibi ffi c code: " c-file " - install anyway?"))) (and (file-exists? stub-file) (or (system? ffi-cmd) (yes-or-no? cfg "couldn't compile stub: " stub-file " - install anyway?"))) (yes-or-no? cfg "can't find ffi stub or c source for: " base " - install anyway?")) (lp (cdr ls)))))))) (define (chicken-builder impl cfg library dir) (let* ((library-file (make-path dir (get-library-file cfg library))) (library-base (chicken-library-base (library-name library))) (so-path (make-path dir (string-append library-base ".so"))) (imp-path (string-append library-base ".import.scm"))) (with-directory dir (lambda () (let ((res (system 'csc '-R 'r7rs '-X 'r7rs '-s '-J '-o so-path '-I (path-directory library-file) library-file))) (and (or (and (pair? res) (zero? (cadr res))) (yes-or-no? cfg "chicken failed to build: " (library-name library-name) " - install anyway?")) library)))))) (define (cyclone-builder impl cfg library dir) (let* ((library-file (make-path dir (get-library-file cfg library))) (so-path (make-path dir (string-append (path-strip-extension library-file) ".so")))) (with-directory dir (lambda () (let ((res (system 'cyclone '-o so-path '-A (path-directory library-file) library-file))) (and (or (and (pair? res) (zero? (cadr res))) (yes-or-no? cfg "cyclone failed to build: " (library-name library) " - install anyway?")) library)))))) (define (guile-builder impl cfg library dir) (let* ((library-file (get-library-file cfg library)) (src-library-file (make-path dir library-file)) (library-dir (path-directory src-library-file)) (dest-library-file (string-append (library->path cfg library) ".go")) (dest-dir (path-directory (make-path dir dest-library-file)))) ;; ensure the build directory exists (create-directory* dest-dir) (with-directory dir (lambda () (and (system 'guild 'compile '-O0 '--r7rs '-o dest-library-file src-library-file) library))))) (define (lookup-builder builder) (case builder ((chibi) chibi-builder) ((chicken) chicken-builder) ((cyclone) cyclone-builder) ((guile) guile-builder) (else default-builder))) (define (builder-for-implementation impl cfg) (case impl ((chibi chicken cyclone guile) impl) (else 'default))) (define (build-library impl cfg library dir) (let ((builder (lookup-builder (or (conf-get cfg 'builder) (builder-for-implementation impl cfg))))) (builder impl cfg library dir))) ;; strip extension, add #! if needed, copy and chmod (define (default-program-builder impl cfg prog dir) (let* ((path (make-path dir (get-program-file cfg prog))) (dest (path-strip-extension path)) (src-lines (call-with-input-file path port->string-list)) (script (scheme-script-command impl cfg))) (if (equal? path dest) (system "cp" path (string-append path ".bak"))) (call-with-output-file dest (lambda (out) (when script (display "#! " out) (display script out) (newline out)) (for-each (lambda (line) (display line out) (newline out)) (if (and (pair? src-lines) (string-prefix? "#!" (car src-lines))) (cdr src-lines) src-lines)))) (chmod dest #o755) prog)) (define (chicken-program-builder impl cfg prog dir) (let ((path (get-program-file cfg prog))) (with-directory dir (lambda () (let ((res (system 'csc '-R 'r7rs '-X 'r7rs '-I (path-directory path) path))) (and (or (and (pair? res) (zero? (cadr res))) (yes-or-no? cfg "chicken failed to build: " path " - install anyway?")) prog)))))) (define (cyclone-program-builder impl cfg prog dir) (let ((path (get-program-file cfg prog))) (with-directory dir (lambda () (let ((res (system 'cyclone '-A (path-directory path) path))) (and (or (and (pair? res) (zero? (cadr res))) (yes-or-no? cfg "cyclone failed to build: " path " - install anyway?")) prog)))))) (define (lookup-program-builder builder) (case builder ((chicken) chicken-program-builder) ((cyclone) cyclone-program-builder) (else default-program-builder))) (define (program-builder-for-implementation impl cfg) (case impl ((chicken) 'chicken) ((cyclone) 'cyclone) (else 'default))) (define (build-program impl cfg prog dir) (let ((builder (lookup-program-builder (or (conf-get cfg 'program-builder) (program-builder-for-implementation impl cfg))))) (builder impl cfg prog dir))) (define (default-program-installer impl cfg prog dir) (let* ((program-file (path-strip-extension (get-program-file cfg prog))) (dest-program-file (program-install-name prog)) (install-dir (get-install-binary-dir impl cfg))) (let ((path (make-path install-dir dest-program-file))) (install-directory cfg (path-directory path)) (install-file cfg (make-path dir program-file) path) (list path)))) (define (lookup-program-installer installer) (case installer (else default-program-installer))) (define (install-program impl cfg prog dir) (let ((installer (lookup-program-installer (conf-get cfg 'program-installer)))) (installer impl cfg prog dir))) (define (install-data-file impl cfg file dir) (let* ((src (if (pair? file) (cadr file) file)) (dest0 (if (pair? file) (third file) file)) (install-dir (get-install-data-dir impl cfg)) (dest (path-resolve dest0 install-dir))) (create-directory* (path-directory dest)) (install-file cfg (make-path dir src) dest) dest)) (define (fetch-package cfg url) (resource->bytevector cfg url)) (define (path-strip-top file) (let ((pos (string-find file #\/))) (if (string-cursor<? pos (string-cursor-end file)) (substring-cursor file (string-cursor-next file pos)) file))) (define (maybe-invalid-package-reason impl cfg pkg) (let ((res (invalid-package-reason pkg))) (and res (not (yes-or-no? cfg "Package invalid: " res "\nProceed anyway?")) res))) (define (package-maybe-digest-mismatches impl cfg pkg raw) (and (not (conf-get cfg 'ignore-digests?)) (let ((res (package-digest-mismatches cfg pkg raw))) (and res (not (yes-or-no? cfg "Package checksum mismatches: " res "\nProceed anyway?")) res)))) (define (package-maybe-signature-mismatches repo impl cfg pkg raw) (cond ((conf-get cfg 'ignore-signature? #t) #f) ((not (cond ((assq 'signature (cdr pkg)) => (lambda (x) (assoc-get (cdr x) 'rsa))) (else #f))) (and (conf-get cfg 'require-signature?) (not (yes-or-no? cfg "Package signature missing.\nProceed anyway?")) '(package-signature-missing))) (else (let ((res (package-signature-mismatches repo cfg pkg raw))) (and res (not (yes-or-no? cfg "Package signature mismatches: " res "\nProceed anyway?")) res))))) ;; install from a raw, unzipped snowball as an in-memory bytevector (define (install-package-from-snowball repo impl cfg pkg snowball) (cond ((not (tar-safe? snowball)) (die 2 "package tarball should contain a single relative directory: " (tar-files snowball))) ((package-maybe-digest-mismatches impl cfg pkg snowball) => (lambda (x) (die 2 "package checksum didn't match: " x))) ((package-maybe-signature-mismatches repo impl cfg pkg snowball) => (lambda (x) (die 2 "package signature didn't match: " x))) (else (call-with-temp-dir "pkg" (lambda (dir preserve) (tar-extract snowball (lambda (f) (make-path dir (path-strip-top f)))) (let* ((ordered-lib-names (reverse (topological-sort (map (lambda (lib) (cons (library-name lib) (library-dependencies impl cfg lib))) (package-libraries pkg))))) (ordered-libs (filter-map (lambda (lib-name) (find (lambda (x) (equal? lib-name (library-name x))) (package-libraries pkg))) ordered-lib-names)) (libs (filter-map (lambda (lib) (build-library impl cfg lib dir)) ordered-libs))) (if (test-package impl cfg pkg dir) (let* ((data-files (append-map (lambda (file) (install-data-file impl cfg file dir)) (package-data-files pkg))) (lib-files (append-map (lambda (lib) (install-library impl cfg lib dir)) libs)) (prog-files (if (conf-program-implementation? impl cfg) (append-map (lambda (prog) (build-program impl cfg prog dir) (install-program impl cfg prog dir)) (package-programs pkg)) '())) (installed-files (append data-files lib-files prog-files))) (if (pair? installed-files) (install-package-meta-info impl cfg `(,@(remove (lambda (x) (and (pair? x) (eq? 'installed-files (car x)))) pkg) (installed-files ,@installed-files))))) (preserve)))))))) (define (install-package-from-file repo impl cfg file) (let ((pkg (package-file-meta file)) (snowball (maybe-gunzip (file->bytevector file)))) (install-package-from-snowball repo impl cfg pkg snowball))) (define (install-package repo impl cfg pkg) (cond ((maybe-invalid-package-reason impl cfg pkg) => (lambda (x) (die 2 "package invalid: " x))) ((package-url repo pkg) => (lambda (url) (let* ((raw (fetch-package cfg url)) (snowball (maybe-gunzip raw))) (install-package-from-snowball repo impl cfg pkg snowball)))) (else (die 2 "package missing url: " (package-name pkg))))) (define (install-for-implementation repo impl cfg pkgs) (for-each (lambda (pkg) (install-package repo impl cfg pkg)) pkgs)) ;; --always-yes implies first candidate, --always-no implies none (define (select-best-candidate impl cfg repo candidates) (cond ((or (null? (cdr candidates)) (conf-get cfg 'always-yes?)) (car candidates)) ((conf-get cfg 'always-no?) #f) (else (display "Select a package:\n") (let lp ((ls candidates) (i 1)) (if (pair? ls) (let ((pkg (car ls))) (display " ") (display i) (display " ") (display (package-name pkg)) (display " ") (display (package-version pkg)) (display " (") (display (package-author repo pkg #t)) (display ")\n") (lp (cdr ls) (+ i 1))))) (let ((n (input-number cfg 'candidate-number "Candidate number: " 1 1 (length candidates)))) (list-ref candidates (- n 1)))))) ;; Choose packages for the corresponding libraries, and recursively ;; select uninstalled packages. (define (expand-package-dependencies repo impl cfg lib-names) (let ((current (installed-libraries impl cfg)) (auto-upgrade-dependencies? (conf-get cfg '(command install auto-upgrade-dependencies?)))) (let lp ((ls lib-names) (res '()) (ignored '())) (cond ((null? ls) res) ((find (lambda (pkg) (package-provides? pkg (car ls))) res) (lp (cdr ls) res ignored)) (else (let* ((current-version (cond ((assoc (car ls) current) => (lambda (x) (package-version (cdr x)))) (else #f))) (providers (filter (lambda (pkg) (package-provides? pkg (car ls))) (cdr repo))) (candidates (filter (lambda (pkg) (or (not current-version) (and (or auto-upgrade-dependencies? (member (car ls) lib-names)) (version>? (package-version pkg) current-version)))) providers))) (cond ((member (car ls) ignored) (lp (cdr ls) res ignored)) ((and (null? candidates) (assoc (car ls) current)) (if (member (car ls) lib-names) (warn "skipping already installed library: " (car ls))) (lp (cdr ls) res (cons (car ls) ignored))) ((and (null? candidates) (not (assoc (car ls) current)) (pair? (car ls)) (implementation-supports-natively? impl cfg (car ls))) ;; assume certain core libraries already installed ;; (info "assuming core library installed: " (car ls)) (lp (cdr ls) res (cons (car ls) ignored))) ((and (null? candidates) (member (car ls) lib-names)) (die 2 "Can't find package: " (car ls))) ((null? candidates) (cond ((yes-or-no? cfg "Can't find package: " (car ls) ". Proceed anyway?") (lp (cdr ls) res (cons (car ls) ignored))) (else (die 2 "No candidates, not installing: " (car ls))))) ((select-best-candidate impl cfg repo candidates) => (lambda (pkg) (lp (append (package-dependencies impl cfg pkg) (package-test-dependencies impl cfg pkg) (cdr ls)) (cons pkg res) ignored))) (else (warn "no candidate selected") (lp (cdr ls) res ignored))))))))) ;; First lookup dependencies for all implementations so we can ;; download in a single batch. Then perform the installations a ;; single implementation at a time. (define (command/install cfg spec . args) (let*-values (((repo) (current-repositories cfg)) ((impls) (conf-selected-implementations cfg)) ((impl-cfgs) (map (lambda (impl) (conf-for-implementation cfg impl)) impls)) ((package-files lib-names) (partition package-file? args)) ((lib-names) (map parse-library-name lib-names)) ((impl-pkgs) (map (lambda (impl cfg) (expand-package-dependencies repo impl cfg lib-names)) impls impl-cfgs))) (for-each (lambda (impl cfg pkgs) (when (conf-get cfg 'verbose?) (if (pair? pkgs) (info `(installing packages: ,(map package-name pkgs) for ,impl))) (if (pair? package-files) (info `(installing files: ,package-files for ,impl)))) ;; install by name and dependency (install-for-implementation repo impl cfg pkgs) ;; install by file (for-each (lambda (pkg-file) (install-package-from-file repo impl cfg pkg-file)) package-files)) impls impl-cfgs impl-pkgs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Upgrade - upgrade installed packages. ;; With explicit packages same as install, but by default upgrade all ;; available packages. (define (command/upgrade cfg spec . args) (if (pair? args) (apply command/install cfg spec args) (let* ((repo (current-repositories cfg)) (impls (conf-selected-implementations cfg)) (impl-cfgs (map (lambda (impl) (conf-extend (conf-for-implementation cfg impl) '((command install auto-upgrade-dependencies?) . #t))) impls))) (for-each (lambda (impl cfg) (let ((pkgs (map cdr (installed-libraries impl cfg)))) (install-for-implementation repo impl cfg pkgs))) impls impl-cfgs)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Status - show the status of installed libraries. (define (command/status cfg spec . args) (let* ((impls (conf-selected-implementations cfg)) (impl-cfgs (map (lambda (impl) (conf-for-implementation cfg impl)) impls)) (sexp? (conf-get cfg 'sexp?))) (if sexp? (display "(")) (for-each (lambda (impl impl-cfg) (if sexp? (display "(")) (cond ((or sexp? (pair? (cdr impls))) (if (not (eq? impl (car impls))) (display "\n")) (display impl) (if (not sexp?) (display ":")) (display "\n"))) (summarize-libraries impl-cfg (if (pair? args) (lookup-installed-libraries impl impl-cfg (map parse-library-name args)) (installed-libraries impl impl-cfg))) (if sexp? (display ")\n"))) impls impl-cfgs) (if sexp? (display ")\n")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Implementations - show the currently available implementations. (define (command/implementations cfg spec . args) (for-each (lambda (impl) (write (car impl)) (newline)) (filter (lambda (x) (impl-available? cfg x #f)) known-implementations)))
false
17fddb6e1827880f7b5bd3b40e2fdba94051992a
2bcf33718a53f5a938fd82bd0d484a423ff308d3
/programming/sicp/ch2/ex-2.38.scm
bfaec9ae702e84b34a41fcbd51177ed30e901e36
[]
no_license
prurph/teach-yourself-cs
50e598a0c781d79ff294434db0430f7f2c12ff53
4ce98ebab5a905ea1808b8785949ecb52eee0736
refs/heads/main
2023-08-30T06:28:22.247659
2021-10-17T18:27:26
2021-10-17T18:27:26
345,412,092
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,221
scm
ex-2.38.scm
#lang scheme ;; https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-15.html#%_thm_2.38 ;; fold-right and fold-left reproduced for reference (define (fold-right op initial sequence) (if (null? sequence) initial (op (car sequence) (fold-right op initial (cdr sequence))))) (define (fold-left op initial sequence) (define (iter result rest) (if (null? rest) result (iter (op result (car rest)) (cdr rest)))) (iter initial sequence)) ;; What are the values of: (fold-right / 1 (list 1 2 3)) ;; Start with 3, it becomes divisor for thing to the right (move from right to left) >(fold-right / 1 '(1 2 3)) > (fold-right / 1 '(2 3)) > >(fold-right / 1 '(3)) > > (fold-right / 1 '()) < < 1 < <3 < 2/3 <3/2 3/2 ;; Start with 1, divide by thing to the right (move from left to right) (fold-left / 1 (list 1 2 3)) 1/6 (fold-right list '() (list 1 2 3)) '(1 (2 (3 ()))) (fold-left list '() (list 1 2 3)) (((() 1) 2) 3) ;; Give a property that `op` should satisfy to guarantee that fold-right and ;; fold-left will produce the same values for any sequence. ;; To produce the same values `op` should be commutative: (equal? (op a b) (op b a))
false
869ef0380362ac82f52dbca35e3269e0582c8a25
54819d742ff4fa8055a335a674640992f8c166d8
/sxml.scm
a775532667fae8fd8845f645be499f243c3ec130
[]
no_license
h8gi/sxml
092e454045e3dbfb98afed593f5a2527d81edecf
b60a081e330cc61ee28ee724a2e88e7ac20448e7
refs/heads/master
2016-09-11T03:11:06.345104
2015-08-31T04:06:51
2015-08-31T04:06:51
41,655,154
0
0
null
null
null
null
UTF-8
Scheme
false
false
103
scm
sxml.scm
;;; sxml (module sxml * (import scheme chicken extras posix srfi-13 ports) (include "main.scm"))
false
005c2fd2568d8b229ded45467d5e620fe3115891
b16702c79458d126ecdd5d297bba86a743610b25
/Assignment-6/asst-6/a6-nil.ss
3b5fdbd2cc769351af6dc7bc0ddce7208c31a2d2
[]
no_license
yangchenyun/Grad-School-Code
d5353d001ce6e9ba454580c1daa68c964843d6e6
5fe2e5d9d01886c4998762061dc7d22ab2264cf7
refs/heads/master
2021-01-24T22:36:45.453167
2017-03-20T08:34:11
2017-03-20T08:34:11
34,314,124
1
1
null
2015-04-21T08:24:36
2015-04-21T08:24:36
null
UTF-8
Scheme
false
false
14,249
ss
a6-nil.ss
;;; Andy Keep, Kent Dybvig, Nilesh Mahajan ;;; P523 ;;; Spring 2009 ;;; verify-scheme accepts a signle value and verifies that the value ;;; is a valid program in the grammar of the sixth assignment. ;;; ;;; Grammar for verify-scheme (assignment 6): ;;; ;;; Program --> (letrec ([<label> (lambda (<uvar>*) <Body>)]*) <Body>) ;;; Body --> (locals (<uvar>*) <Tail>) ;;; Tail --> <Triv> ;;; | (binop <Value> <Value>) ;;; | (<Value> <Value>*) ;;; | (if <Pred> <Tail> <Tail>) ;;; | (begin <Effect>* <Tail>) ;;; Pred --> (true) ;;; | (false) ;;; | (<predop> <Value> <Value>) ;;; | (if <Pred> <Pred> <Pred>) ;;; | (begin <Effect>* <Pred>) ;;; Effect --> (nop) ;;; | (set! <uvar> <Value>) ;;; | (if <Pred> <Effect> <Effect>) ;;; | (begin <Effect>* <Effect>) ;;; Value --> <Triv> ;;; | (<binop> <Value> <Value>) ;;; | (if <Pred> <Value> <Value>) ;;; | (begin <Effect>* <Value>) ;;; Triv --> <uvar> | <int64> | <label> ;;; ;;; Where uvar is symbol.n where (n >= 0) ;;; label is symbol$n where (n >= 0) ;;; binop is +, -, *, logand, logor, or sra ;;; predop is <, >, <=, >=, = ;;; ;;; We still have a couple constraints based on our machine and ;;; testing framework. Namely, we expect calls target values to ;;; evaluate to uvars or labels, and we expect computations to be ;;; done with uvars or integers. ;;; ;;; Note that we also expect the sra binop to have a uint6 in the ;;; second argument. ;;; (define-who verify-scheme (define verify-x-list (lambda (x* x? what) (let loop ([x* x*] [idx* '()]) (unless (null? x*) (let ([x (car x*)] [x* (cdr x*)]) (unless (x? x) (error who "invalid ~s ~s found" what x)) (let ([idx (extract-suffix x)]) (when (member idx idx*) (error who "non-unique ~s suffix ~s found" what idx)) (loop x* (cons idx idx*)))))))) (define Triv (lambda (label* uvar*) (lambda (t) (unless (or (label? t) (uvar? t) (and (integer? t) (exact? t))) (error who "invalid Triv ~s" t)) (when (and (integer? t) (exact? t)) (unless (int64? t) (error who "integer out of 64-bit range ~s" t))) (when (uvar? t) (unless (memq t uvar*) (error who "reference to unbound uvar ~s" t))) (when (label? t) (unless (memq t label*) (error who "unbound label ~s" t))) t))) (define Value (lambda (label* uvar*) (lambda (val) (match val [(if ,[(Pred label* uvar*) -> test] ,[conseq] ,[altern]) (void)] [(begin ,[(Effect label* uvar*) -> ef*] ... ,[val]) (void)] [(sra ,[(Value label* uvar*) -> x] ,y) (unless (uint6? y) (error who "invalid sra operand ~s" y))] [(,binop ,[(Value label* uvar*) -> x] ,[(Value label* uvar*) -> y]) (guard (memq binop '(+ - * logand logor sra))) (void)] [,[(Triv label* uvar*) -> tr] (void)])))) (define Effect (lambda (label* uvar*) (lambda (ef) (match ef [(nop) (void)] [(if ,[(Pred label* uvar*) -> test] ,[conseq] ,[altern]) (void)] [(begin ,[ef*] ... ,[ef]) (void)] [(set! ,var ,[(Value label* uvar*) -> val]) (unless (memq var uvar*) (error who "assignment to unbound var ~s" var))] [,ef (error who "invalid Effect ~s" ef)])))) (define Pred (lambda (label* uvar*) (lambda (pr) (match pr [(true) (void)] [(false) (void)] [(if ,[test] ,[conseq] ,[altern]) (void)] [(begin ,[(Effect label* uvar*) -> ef*] ... ,[pr]) (void)] [(,predop ,[(Value label* uvar*) -> x] ,[(Value label* uvar*) -> y]) (unless (memq predop '(< > <= >= =)) (error who "invalid predicate operator ~s" predop))] [,pr (error who "invalid Pred ~s" pr)])))) (define Tail (lambda (tail label* uvar*) (match tail [(if ,[(Pred label* uvar*) -> test] ,[conseq] ,[altern]) (void)] [(begin ,[(Effect label* uvar*) -> ef*] ... ,[tail]) (void)] [(sra ,[(Value label* uvar*) -> x] ,y) (unless (uint6? y) (error who "invalid sra operand ~s" y))] [(,binop ,[(Value label* uvar*) -> x] ,[(Value label* uvar*) -> y]) (guard (memq binop '(+ - * logand logor sra))) (void)] [(,[(Value label* uvar*) -> rator] ,[(Value label* uvar*) -> rand*] ...) (void)] [,[(Triv label* uvar*) -> triv] (void)]))) (define Body (lambda (label*) (lambda (bd fml*) (match bd [(locals (,local* ...) ,tail) (let ([uvar* `(,fml* ... ,local* ...)]) (verify-x-list uvar* uvar? 'uvar) (Tail tail label* uvar*))] [,bd (error who "invalid Body ~s" bd)])))) (lambda (x) (match x [(letrec ([,label* (lambda (,fml** ...) ,bd*)] ...) ,bd) (verify-x-list label* label? 'label) (map (lambda (fml*) (verify-x-list fml* uvar? 'formal)) fml**) (for-each (Body label*) bd* fml**) ((Body label*) bd '())] [,x (error who "invalid Program ~s" x)]) x)) ;;; Program --> (letrec ([label (lambda (uvar*) Body)]*) Body) ;;; Body --> (locals (uvar*) Tail) ;;; Tail --> Triv ;;; | (binop Value Value) ;;; | (Value Value*) ;;; | (if Pred Tail Tail) ;;; | (begin Effect* Tail) ;;; Pred --> (true) ;;; | (false) ;;; | (relop Value Value) ;;; | (if Pred Pred Pred) ;;; | (begin Effect* Pred) ;;; Effect --> (nop) ;;; | (set! uvar Value) ;;; | (if Pred Effect Effect) ;;; | (begin Effect* Effect) ;;; Value --> Triv ;;; | (binop Value Value) ;;; | (if Pred Value Value) ;;; | (begin Effect* Value) ;;; Triv --> uvar | int | label (define-who remove-complex-opera* (define (Body bd) (define new-local* '()) (define (new-t) (let ([t (unique-name 't)]) (set! new-local* (cons t new-local*)) t)) ;;; returns true if the input val is not a Triv (define nontrivial? (lambda (x) (not (or (uvar? x) (label? x) (integer? x))))) ;;; handles the common code for binop, predop (define (binop-handler binop x y) (cond ((and (nontrivial? x) (nontrivial? y)) (let ([t1 (new-t)] [t2 (new-t)]) (make-begin `((set! ,t1 ,x) (set! ,t2 ,y) (,binop ,t1 ,t2))))) ((nontrivial? x) (let ([t (new-t)]) (make-begin `((set! ,t ,x) (,binop ,t ,y))))) ((nontrivial? y) (let ([t (new-t)]) (make-begin `((set! ,t ,y) (,binop ,x ,t))))) (else `(,binop ,x ,y)))) (define (Value val) (match val [(if ,[Pred -> test] ,[conseq] ,[altern]) `(if ,test ,conseq ,altern)] [(begin ,[Effect -> ef*] ... ,[val]) `(begin ,ef* ... ,val)] [(,binop ,[x] ,[y]) (binop-handler binop x y)] [,tr tr])) (define (Effect ef) (match ef [(nop) `(nop)] [(if ,[Pred -> test] ,[conseq] ,[altern]) `(if ,test ,conseq ,altern)] [(begin ,[ef*] ...) `(begin ,ef* ...)] [(set! ,var ,[Value -> val]) `(set! ,var ,val)] [,ef (error who "invalid Effect ~s" ef)])) (define (Pred pr) (match pr [(true) `(true)] [(false) `(false)] [(if ,[test] ,[conseq] ,[altern]) `(if ,test ,conseq ,altern)] [(begin ,[Effect -> ef*] ... ,[pr]) `(begin ,ef* ... ,pr)] [(,predop ,[Value -> x] ,[Value -> y]) (binop-handler predop x y)] [,pr (error who "invalid Pred ~s" pr)])) (define (handle-value x) (cond ((nontrivial? x) (let ([t (new-t)]) (make-begin `((set! ,t ,x) ,t)))) (else x))) (define (Tail tail) (match tail [(if ,[Pred -> test] ,[conseq] ,[altern]) `(if ,test ,conseq ,altern)] [(begin ,[Effect -> ef*] ... ,[tail]) `(begin ,ef* ... ,tail)] [(,binop ,[Value -> x] ,[Value -> y]) (binop-handler binop x y)] [(,[Value -> rator] ,[Value -> rand*] ...) (append `(,(handle-value rator)) (map handle-value rand*))] [,triv triv])) (match bd [(locals (,local* ...) ,[Tail -> tail]) `(locals (,local* ... ,new-local* ...) ,tail)] [,bd (error who "invalid Body ~s" bd)])) (lambda (x) (match x [(letrec ([,label* (lambda (,fml** ...) ,[Body -> bd*])] ...) ,[Body -> bd]) `(letrec ([,label* (lambda (,fml** ...) ,bd*)] ...) ,bd)] [,x (error who "invalid Program ~s" x)]))) (define-who flatten-set! #;(define (Triv t) ---) #;(define (Value val) ---) (define (propagate-set! expr var) (match expr [(if ,[Pred -> test] ,[conseq] ,[altern]) `(if ,test ,conseq ,altern)] [(begin ,[Effect -> ef*] ... ,[val]) `(begin ,ef* ... ,val)] [(,binop ,x ,y) `(set! ,var (,binop ,x ,y))] [,tr `(set! ,var ,tr)])) (define (Effect ef) (match ef [(nop) `(nop)] [(if ,[Pred -> test] ,[conseq] ,[altern]) `(if ,test ,conseq ,altern)] [(begin ,[ef*] ...) (make-begin ef*)] [(set! ,var ,val) (propagate-set! val var)] [,ef (error who "invalid Effect ~s" ef)])) (define (Pred pr) (match pr [(true) `(true)] [(false) `(false)] [(if ,[test] ,[conseq] ,[altern]) `(if ,test ,conseq ,altern)] [(begin ,[Effect -> ef*] ... ,[pr]) (make-begin `(,ef* ... ,pr))] [(,predop ,x ,y) `(,predop ,x ,y)] [,pr (error who "invalid Pred ~s" pr)])) (define (Tail tail) (match tail [(if ,[Pred -> test] ,[conseq] ,[altern]) `(if ,test ,conseq ,altern)] [(begin ,[Effect -> ef*] ... ,[tail]) (make-begin `(,ef* ... ,tail))] [(,binop ,x ,y) `(,binop ,x ,y)] [(,rator ,rand* ...) `(,rator ,rand* ...)] [,triv triv])) (define (Body bd) (match bd [(locals (,uvar* ...) ,[Tail -> tail]) `(locals (,uvar* ...) ,tail)] [,bd (error who "invalid Body ~s" bd)])) (lambda (x) (match x [(letrec ([,label* (lambda (,fml** ...) ,[Body -> bd*])] ...) ,[Body -> bd]) `(letrec ([,label* (lambda (,fml** ...) ,bd*)] ...) ,bd)] [,x (error who "invalid Program ~s" x)]))) ;;; Program --> (letrec ([label (lambda (uvar*) Body)]*) Body) ;;; Body --> (locals (uvar*) Tail) ;;; Tail --> Triv ;;; | (binop Triv Triv) ;;; | (Triv Triv*) ;;; | (if Pred Tail Tail) ;;; | (begin Effect* Tail) ;;; Pred --> (true) ;;; | (false) ;;; | (relop Triv Triv) ;;; | (if Pred Pred Pred) ;;; | (begin Effect* Pred) ;;; Effect --> (nop) ;;; | (set! uvar Triv) ;;; | (set! uvar (binop Triv Triv)) ;;; | (if Pred Effect Effect) ;;; | (begin Effect* Effect) ;;; Triv --> uvar | int | label (define-who impose-calling-conventions #;(define (Triv t) ---) (define (Effect ef) (match ef [(nop) `(nop)] [(if ,[Pred -> test] ,[conseq] ,[altern]) `(if ,test ,conseq ,altern)] [(begin ,[ef*] ...) `(begin ,ef* ...)] [(set! ,var ,val) `(set! ,var ,val)] [,ef (error who "invalid Effect ~s" ef)])) (define (Pred pr) (match pr [(true) `(true)] [(false) `(false)] [(if ,[test] ,[conseq] ,[altern]) `(if ,test ,conseq ,altern)] [(begin ,[Effect -> ef*] ... ,[pr]) `(begin ,ef* ... ,pr)] [(,predop ,x ,y) `(,predop ,x ,y)] [,pr (error who "invalid Pred ~s" pr)])) (define (generate-set! dest src) `(set! ,dest ,src)) (define (generate-frame-var-list count) (if (= count 0) `() (let ([newcount (- count 1)]) (cons (index->frame-var newcount) (generate-frame-var-list newcount))))) (define (Tail tail rp) (match tail [(if ,[Pred -> test] ,[conseq] ,[altern]) `(if ,test ,conseq ,altern)] [(begin ,[Effect -> ef*] ... ,[tail]) `(begin ,ef* ... ,tail)] [(,proc ,args* ...) (make-begin (append (append (if (> (length args*) (length parameter-registers)) (let ([argstail (list-tail args* (length parameter-registers))]) (map generate-set! (generate-frame-var-list (length argstail)) argstail)) '()) (let ([reg* (if (< (length args*) (length parameter-registers)) (list-head parameter-registers (length args*)) parameter-registers)]) (map generate-set! reg* (list-head args* (length reg*))))) `((set! ,return-value-register ,rp)) `((,proc ,frame-pointer-register ,return-value-register ,args*))))] [(,binop ,x ,y) `(begin (set! ,return-value-register (,binop ,x ,y)) (,rp ,frame-pointer-register ,return-value-register))] [,triv `(begin (set! ,return-value-register ,triv) (,rp ,frame-pointer-register ,return-value-register))])) (define (Body bd fml*) (match bd [(locals (,locals* ...) ,tail) (let ([rp (unique-name 'rp)] [newlocals* (append locals* fml*)]) `(locals (,newlocals* ,rp) ,(make-begin (append `((set! ,rp ,return-address-register)) (append (let ([reg* (if (< (length newlocals*) (length parameter-registers)) (list-head parameter-registers (length newlocals*)) parameter-registers)]) (map generate-set! (list-head newlocals* (length reg*)) reg*)) (if (> (length newlocals*) (length parameter-registers)) (let ([newlocalstail (list-tail newlocals* (length parameter-registers))]) (map generate-set! newlocalstail (generate-frame-var-list (length newlocalstail)))) '())) (Tail tail rp)))))] [,bd (error who "invalid Body ~s" bd)])) (lambda (x) (match x [(letrec ([,label* (lambda (,fml** ...) ,bd*)] ...) ,bd) (let ([bd* (map Body bd* fml**)] [bd (Body bd '())]) `(letrec ([,label* (lambda () ,bd*)] ...) ,bd))] [,x (error who "invalid Program ~s" x)])))
false
243c88675d8aa59c5fb3439823f0c262e92b6c6c
4b480cab3426c89e3e49554d05d1b36aad8aeef4
/chapter-02/ex2.58-falsetru-test.scm
588c78a4e1f33572e2bd1664dca22491251f43ad
[]
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
844
scm
ex2.58-falsetru-test.scm
(require (planet schematics/schemeunit:3)) (require (planet schematics/schemeunit:3/text-ui)) (load "ex2.58-falsetru.scm") (define ex2.58-falsetru-tests (test-suite "Test for ex2.58-falsetru" ; a (check-equal? (deriv '(x + (3 * (x + (y + 2)))) 'x) 4) (check-equal? (deriv '(x + (3 * (x + (y + 2)))) 'y) 3) (check-equal? (deriv '(x + (3 * (x + (y + 2)))) 'z) 0) (check-equal? (deriv '(x ** 3) 'x) '(3 * (x ** 2))) (check-equal? (deriv '((x ** 2) + x) 'x) '((2 * x) + 1)) ; b (check-equal? (deriv '(x + 3 * (x + y + 2)) 'x) 4) (check-equal? (addend '(x + y + z)) '(y + z)) (check-equal? (addend '(x + (y + z))) '(y + z)) )) (exit (cond ((= (run-tests ex2.58-falsetru-tests) 0)) (else 1)))
false
1b442e22d4888c05cdee06e3551bf4c38863accb
09e309c8c7dd86d201f965a12f4f174fd2bf8cf5
/scheme/bin2dec.scm
f3cf9833f5967b596766682154e9253575d1b464
[]
no_license
googol-lab/lang
f21076846b2364ee08875530ab7a6680de61f55c
38cae455f85464a7f918d1a5a481a577ed5549fe
refs/heads/master
2020-03-29T13:32:29.159544
2010-05-24T03:09:54
2010-05-24T03:09:54
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
197
scm
bin2dec.scm
(define (bin2dec xs) (define (iter msb remain accum) (let ((ans (+ msb (* 2 accum)))) (if (null? remain) ans (iter (car remain) (cdr remain) ans)))) (iter (car xs) (cdr xs) 0))
false
1205250fa74e53fab41d24d9a1b40516da70d828
bdcc255b5af12d070214fb288112c48bf343c7f6
/r7b-impl/division.sls
74aac7029f368cd6294ccd2bc2fc9287e2b32c52
[]
no_license
xaengceilbiths/chez-lib
089af4ab1d7580ed86fc224af137f24d91d81fa4
b7c825f18b9ada589ce52bf5b5c7c42ac7009872
refs/heads/master
2021-08-14T10:36:51.315630
2017-11-15T11:43:57
2017-11-15T11:43:57
109,713,952
5
1
null
null
null
null
UTF-8
Scheme
false
false
1,479
sls
division.sls
#!chezscheme (library (r7b-impl division) (export ;; from R7RS draft 4 ceiling-quotient ceiling-remainder ceiling/ centered-quotient centered-remainder centered/ euclidean-quotient euclidean-remainder euclidean/ floor-quotient floor-remainder floor/ round-quotient round-remainder round/ truncate-quotient truncate-remainder truncate/ ) (import (rnrs) (rnrs r5rs)) ;; ???: Inexact integers are allowed?? (define truncate-quotient quotient) (define truncate-remainder remainder) (define (truncate/ x y) (values (truncate-quotient x y) (truncate-remainder x y))) ;; FIXME: accepts inexacts (define euclidean-quotient div) (define euclidean-remainder mod) (define euclidean/ div-and-mod) ;; FIXME: accepts inexacts (define centered-quotient div0) (define centered-remainder mod0) (define centered/ div0-and-mod0) (define-syntax %define-division (syntax-rules () ((_ fix quo rem q+r) (begin (define (quo x y) (exact (fix (/ x y)))) (define (rem x y) (- x (* (quo x y) y))) (define (q+r x y) (let ((q (quo x y))) (values q (- x (* q y))))))))) (%define-division ceiling ceiling-quotient ceiling-remainder ceiling/) (%define-division round round-quotient round-remainder round/) (%define-division floor floor-quotient floor-remainder0 ;; Most implementation has native modulo floor/) (define floor-remainder modulo) )
true
d8d2644ed744991239767924cef7d59d2ec10452
ebc5db754946092d65c73d0b55649c50d0536bd9
/2017/day06.scm
1cb10dc5305ad216d0823aed3d24d08851bf6cc6
[]
no_license
shawnw/adventofcode
6456affda0d7423442d0365a2ddfb7b704c0aa91
f0ecba80168289305d438c56f3632d8ca89c54a9
refs/heads/master
2022-12-07T22:54:04.957724
2022-12-02T07:26:06
2022-12-02T07:26:06
225,129,064
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,609
scm
day06.scm
(import (srfi 126) (io-utils)) (define (max-index vec) (let ((len (vector-length vec))) (let loop ((i 1) (maxi 0) (maxv (vector-ref vec 0))) (if (= i len) maxi (let ((thisv (vector-ref vec i))) (if (> thisv maxv) (loop (+ i 1) i thisv) (loop (+ i 1) maxi maxv))))))) (define (vector-add! vec n) (do ((i (- (vector-length vec) 1) (- i 1))) ((< i 0)) (vector-set! vec i (+ (vector-ref vec i) n)))) (define (distribute! vec i) (let* ((val (vector-ref vec i)) (len (vector-length vec)) (modincr (lambda (n) (mod (+ n 1) len)))) (vector-set! vec i 0) (let loop ((n (modincr i)) (val val)) (cond ((= val 0)) ((>= val len) (vector-add! vec 1) (loop n (- val len))) (else (vector-set! vec n (+ (vector-ref vec n) 1)) (loop (modincr n) (- val 1))))))) (define (count-cycles vec) (let ((seen (make-hashtable equal-hash equal?)) (vec (vector-copy vec))) (hashtable-set! seen vec 0) (let loop ((cycles 1)) (distribute! vec (max-index vec)) (let-values (((occurred found) (hashtable-lookup seen vec))) (if found (values cycles (- cycles occurred)) (begin (hashtable-set! seen (vector-copy vec) cycles) (loop (+ cycles 1)))))))) (define input (list->vector (read-numbers))) (define test-input (vector 0 2 7 0)) (format #t "Test 1: ~A~%" (count-cycles test-input)) (format #t "Part 1 & 2: ~A~%" (count-cycles input))
false
c373e4159573110d395ea04c1cdb0a6ed43d534b
e1fc47ba76cfc1881a5d096dc3d59ffe10d07be6
/ch4/4.40.scm
7f45ca41b8cb503d841f364a89873f20e04f6d21
[]
no_license
lythesia/sicp-sol
e30918e1ebd799e479bae7e2a9bd4b4ed32ac075
169394cf3c3996d1865242a2a2773682f6f00a14
refs/heads/master
2021-01-18T14:31:34.469130
2019-10-08T03:34:36
2019-10-08T03:34:36
27,224,763
2
0
null
null
null
null
UTF-8
Scheme
false
false
595
scm
4.40.scm
(define (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 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) (list 'cooper) (list 'fletcher) (list 'miller) (list 'smith) ) ) ) ) ) )
false
63c02d1595ff38906802422ed4fc76ec0c349981
c94361855ba29e0190df993d10856a0a2d53e687
/library/feature-optional.ss
bfa3166c4f62680c70f564c03c888bf24744b187
[ "MIT" ]
permissive
kghost/Yume
f886431eaa7600192fcd8b0ad04896caf4f96b31
6ec307279fe0036437a9047d49032f4ee6eb286b
refs/heads/master
2023-08-16T11:49:40.270078
2019-04-18T14:02:33
2019-04-18T14:02:33
3,162,103
4
0
null
null
null
null
UTF-8
Scheme
false
false
82
ss
feature-optional.ss
(define (:optional args default) (if (pair? args) (car args) default))
false
5cbc1f0812af97359ce006076387a66ac71584df
cf0088c48b127311069a183d90ca0d179bd83ba6
/srfi/148.sld
9bfba24be897ecf946d15d374e2ffe68f4fa9576
[ "MIT" ]
permissive
scheme-requests-for-implementation/srfi-148
63d9e1edc39fe4caa5c21b3b08944b2530d56323
255c94f569b4b0f8680c35243c398e0039a271ad
refs/heads/master
2022-11-29T06:19:08.691501
2022-11-15T21:15:20
2022-11-15T21:15:20
77,763,467
1
2
MIT
2022-11-15T21:15:21
2017-01-01T02:42:55
Scheme
UTF-8
Scheme
false
false
3,458
sld
148.sld
;; Copyright (C) Marc Nieper-Wißkirchen (2016). All Rights Reserved. ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation ;; files (the "Software"), to deal in the Software without ;; restriction, including without limitation the rights to use, copy, ;; modify, merge, publish, distribute, sublicense, and/or sell copies ;; of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; The above copyright notice and this permission notice shall be ;; included in all copies or substantial portions of the Software. ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS ;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN ;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. (define-library (srfi 148) (export em-syntax-rules ;; General em em-cut em-cute em-constant em-quote em-eval em-apply em-call em-error em-gensym em-generate-temporaries ;; Boolean logic em-if em-not em-or em-and em-null? em-pair? em-list? em-boolean? em-vector? em-symbol? em-bound-identifier=? em-free-identifier=? em-equal? ;; Constructors em-cons em-cons* em-list em-make-list ;; Selectors em-car em-cdr em-caar em-cadr em-cdar em-cddr em-first em-second em-third em-fourth em-fifth em-sixth em-seventh em-eighth em-ninth em-tenth em-list-tail em-list-ref em-take em-drop em-take-right em-drop-right em-last em-last-pair ;; Miscellaneous em-append em-reverse ;; Folding, unfolding, and mapping em-fold em-fold-right em-unfold em-unfold-right em-map em-append-map ;; Filtering em-filter em-remove ;; Searching em-find em-find-tail em-take-while em-drop-while em-any em-every em-member ;; Association lists em-assoc em-alist-delete ;; Set operationse em-set<= em-set= em-set-adjoin em-set-union em-set-intersection em-set-difference em-set-xor ;; Vector processing em-vector em-list->vector em-vector->list em-vector-map em-vector-ref ;; Combinatorics em-0 em-1 em-2 em-3 em-4 em-5 em-6 em-7 em-8 em-9 em-10 em= em< em<= em> em>= em-zero? em-even? em-odd? em+ em- em* em-quotient em-remainder em-fact em-binom ;; Auxiliary syntax => <> ...) (include-library-declarations "../custom-macro-transformers.scm") (import (srfi 26)) (cond-expand (chibi (import (scheme cxr)) (import (srfi 147 er-macro-transformer)) (include "148.er-macro-transformer.scm")) (else (include "148.identifier.scm"))) (include "148.scm" "148.macros.scm")) ;; Local Variables: ;; eval: (put 'em-syntax-rules 'scheme-indent-function 'defun) ;; eval: (font-lock-add-keywords 'scheme-mode ;; '(("(\\(em-syntax-rules\\)\\>" 1 font-lock-keyword-face))) ;; End:
false
16a58885ebab9cb7fb69e7afbb7497648a62430d
6b961ef37ff7018c8449d3fa05c04ffbda56582b
/bbn_cl/mach/sf/tables.scm
4e86912c11ac4ffbc5369ca62c4cfd2b6109a713
[]
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,075
scm
tables.scm
#| -*-Scheme-*- 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. |# ;;;; SCode Optimizer: Tables (declare (usual-integrations)) ;;;; Operations (define (operations/make) (cons '() '())) (define (operations/lookup operations variable if-found if-not) (let ((entry (assq variable (car operations))) (finish (lambda (entry) (if-found (vector-ref (cdr entry) 1) (vector-ref (cdr entry) 2))))) (if entry (if (cdr entry) (finish entry) (if-not)) (let ((entry (assq (variable/name variable) (cdr operations)))) (if entry (finish entry) (if-not)))))) (define (operations/shadow operations variables) (cons (map* (car operations) (lambda (variable) (cons variable false)) variables) (cdr operations))) (define (operations/bind-global operations operation export? names values) (cons (car operations) (map* (cdr operations) (lambda (name value) (cons name (vector export? operation value))) names values))) (define (operations/bind operations operation export? names values) (cons (let ((make-binding (lambda (name value) (cons name (vector export? operation value))))) (if (eq? values 'NO-VALUES) (map* (car operations) (lambda (name) (make-binding name false)) names) (map* (car operations) make-binding names values))) (cdr operations))) (define (operations/extract-external operations procedure) (let loop ((elements (car operations))) (if (null? elements) '() (let ((value (cdar elements)) (rest (loop (cdr elements)))) (if (and value (vector-ref value 0)) (procedure (caar elements) (vector-ref value 1) (vector-ref value 2) (lambda (value) (cons value rest)) (lambda () rest)) rest)))))
false
737829b82d28f278fdf5b5cb1a1a96fbd7f58859
defeada37d39bca09ef76f66f38683754c0a6aa0
/System/system/diagnostics/event-type-filter.sls
e85e9487355696ba602005bc055c14bd0eeee730
[]
no_license
futsuki/ironscheme-port
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
4e7a81b0fbeac9a47440464988e53fb118286c54
refs/heads/master
2016-09-06T17:13:11.462593
2015-09-26T18:20:40
2015-09-26T18:20:40
42,757,369
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,049
sls
event-type-filter.sls
(library (system diagnostics event-type-filter) (export new is? event-type-filter? should-trace? event-type-get event-type-set! event-type-update!) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Diagnostics.EventTypeFilter a ...))))) (define (is? a) (clr-is System.Diagnostics.EventTypeFilter a)) (define (event-type-filter? a) (clr-is System.Diagnostics.EventTypeFilter a)) (define-method-port should-trace? System.Diagnostics.EventTypeFilter ShouldTrace (System.Boolean System.Diagnostics.TraceEventCache System.String System.Diagnostics.TraceEventType System.Int32 System.String System.Object[] System.Object System.Object[])) (define-field-port event-type-get event-type-set! event-type-update! (property:) System.Diagnostics.EventTypeFilter EventType System.Diagnostics.SourceLevels))
true
4c5117a40cf0153648609d9ddac611e1619d6851
a74932f6308722180c9b89c35fda4139333703b8
/edwin48/srfi-89.scm
a5514749f21c98e52ca76e3a2d5ea6c31d7449a6
[]
no_license
scheme/edwin48
16b5d865492db5e406085e8e78330dd029f1c269
fbe3c7ca14f1418eafddebd35f78ad12e42ea851
refs/heads/master
2021-01-19T17:59:16.986415
2014-12-21T17:50:27
2014-12-21T17:50:27
1,035,285
39
10
null
2022-02-15T23:21:14
2010-10-29T16:08:55
Scheme
UTF-8
Scheme
false
false
1,028
scm
srfi-89.scm
;;; -*- Mode: Scheme; scheme48-package: srfi-89 -*- ;;; (open scheme srfi-1 let-opt) ;;; (for-syntax (open scheme let-opt (subset signals (syntax-error)) srfi-1)) (define-syntax define* (lambda (form rename compare) (let* ((signature (cadr form)) (body (cddr form)) (name (car signature)) (arguments (cdr signature)) (required (lambda (args) (take-while symbol? args))) (optional (lambda (args) (drop-while symbol? args))) (required-args (required arguments)) (optional-args (optional arguments)) (args (rename 'args)) (%define (rename 'define)) (%let-optionals (rename 'let-optionals))) (cond ((null? optional-args) `(,%define (,name ,@required-args) ,@body)) ((not (every pair? optional-args)) (syntax-error "all required arguments must come before optional arguments")) (else `(,%define (,name ,@required-args . ,args) (,%let-optionals ,args ,optional-args ,@body)))))))
true
2895aef2ee28df898ffeff6e8263803503cdb220
5355071004ad420028a218457c14cb8f7aa52fe4
/2.2/e-2.32.scm
bdcbb3b1d6da8f93c377f704ce1091ebd3738980
[]
no_license
ivanjovanovic/sicp
edc8f114f9269a13298a76a544219d0188e3ad43
2694f5666c6a47300dadece631a9a21e6bc57496
refs/heads/master
2022-02-13T22:38:38.595205
2022-02-11T22:11:18
2022-02-11T22:11:18
2,471,121
376
90
null
2022-02-11T22:11:19
2011-09-27T22:11:25
Scheme
UTF-8
Scheme
false
false
1,145
scm
e-2.32.scm
; Exercise 2.32. ; ; We can represent a set as a list of distinct elements, and we can ; represent the set of all subsets of the set as a list of lists. ; For example, if the set is (1 2 3), then the set of all subsets is ; (() (3) (2) (2 3) (1) (1 3) (1 2) (1 2 3)). Complete the following ; definition of a procedure that generates the set of subsets of a set ; and give a clear explanation of why it works: (load "../helpers.scm") (load "../common.scm") (define (subsets s) (if (null? s) (list nil) (let ((rest (subsets (cdr s)))) (append rest (map (lambda (x) (cons (car s) x)) rest))))) ; gives expected result (() (3) (2) (2 3) (1) (1 3) (1 2) (1 2 3)) (output (subsets (list 1 2 3))) ; The recursive algorithm that is implemented here can be explained in ; following way suitable for recursive implementation: ; ; To list all the subsets of the definite set you need ; 1. All the subsets of a given set without a certain element ; 2. You have to add to this all the subsets from point 1 ; but with that element added to the sets. ; ; More on this is written: http://en.wikipedia.org/wiki/Power_set#Algorithms
false
be24f835e9c2d68ea00b9ed808f758bc60133d57
d3e9eecbf7fa7e015ab8b9c357882763bf6d6556
/practices/assignments/10.generic-arithmetic/types.scm
3d1c7be1e46ad8251467f689c1b2f1425bc673ac
[]
no_license
yangchenyun/learning-sicp
37d43f18836055274f78755ff93eb20fba63d383
99a19a06eddc282e0eb364536e297f27c32a9145
refs/heads/master
2021-01-19T02:15:15.634140
2017-02-13T22:26:58
2017-02-13T22:26:58
5,344,488
17
3
null
null
null
null
UTF-8
Scheme
false
false
798
scm
types.scm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; This is the file types.scm ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; The bottom level typing system (define attach-tag cons) (define (type-tag datum) (if (pair? datum) (car datum) (error "Bad typed datum -- TYPE-TAG" datum))) (define (contents datum) (if (pair? datum) (cdr datum) (error "Bad typed datum -- CONTENTS" datum))) ;;; The apply-generic mechanism. ;;; Note that we don't deal with coercion here. (define (apply-generic op . args) (let ((type-tags (map type-tag args))) (let ((proc (get op type-tags))) (if proc (apply proc (map contents args)) (error "No method for the given types -- APPLY-GENERIC" (list op type-tags))))))
false
8172605edab0faac998f6969443f139462fa20d3
ae4938300d7eea07cbcb32ea4a7b0ead9ac18e82
/labs/playground/webshop/comp.ss
70741c61b7a01ac460f7945cfe46f6633c263e17
[]
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
23,560
ss
comp.ss
(import (imi list processing) (imi string format) (imi sugar cut) (imi sugar receive) ) (define (fold-right* proc ls . seeds) (if (null? ls) (apply values seeds) (receive seeds (apply fold-right* proc (cdr ls) seeds) (apply proc (car ls) seeds)))) (define SEQUENCE 0) (define RET 1) (define WITHCONT 2) (define (compile e r pos) (if (atom? e) (if (symbol? e) (compile-reference e r pos) (compile-quotation e r pos)) (case (car e) [(quote) (compile-quotation (cadr e) r pos)] [(begin) (compile-sequence (cdr e) r pos)] [(if) (compile-alternative (cadr e) (caddr e) (cadddr e) r pos)] [(set!) (compile-set (cadr e) (caddr e) r pos)] [(let) (compile-let (cadr e) (cddr e) r pos)] [(lambda) (compile-abstraction (cadr e) (cddr e) r pos)] [(define) (compile-definition (cadr e) (cddr e) r pos)] [else (compile-application (car e) (cdr e) r pos)]))) (define (atom? e) (not (pair? e))) (define (compile-reference n r pos) (let* ([bind (lookup-variable r n)] [var (extract-variable bind)]) (cond [(not bind) (error 'compile-reference "unbound variable" n r)] [(local? bind) (values (RETURN pos (car var)) '() '())] [(and (global? var) (not (local? bind))) (values (RETURN pos (car var)) (if (function? var) '() (list n)) '())] [else (values (RETURN pos (car var)) '() (add-free-ref n bind '()))]))) (define (compile-quotation e r pos) (if (atom? e) (values (cond [(char? e) (RETURN pos (string #\" e #\"))] [(string? e) (RETURN pos (string-append "'" e "'"))] [(symbol? e) (RETURN pos (string-append "\"" (string-process-specials (symbol->string e)) "\""))] [(number? e) (RETURN pos (number->string e))] [(boolean? e) (RETURN pos (if e "true" "false"))] [(null? e) (RETURN pos "NULL")] [else (error 'compile-quotation "invalid quotation" e)]) '() '()) (compile-list-quotation e r pos))) (define (compile-list-quotation e* r pos) (receive (c* global* free*) (map-compile compile-quotation e* r) (values (list "array " (ARGUMENTS c*)) global* free*))) (define (compile-sequence e* r pos) (when (= pos WITHCONT) (error 'compile-sequence "a sequence can not be an argument" e*)) (let ([e* (flatten-begin e*)]) (receive (c* global* free*) (compile-sequence-list e* r pos) (values (list 'lines "{" (cons* 'indent 'lines c*) "}") global* free*)))) (define (compile-sequence-list e* r pos) (fold-right* (lambda (e c* global* free*) (receive (c g* f*) (compile e r (if (null? c*) ; do we have the last element? pos SEQUENCE)) (values (cons (list c ";") c*) (append g* global*) (append f* free*)))) e* '() '() '())) (define (flatten-begin e*) (fold-right (lambda (e e*) (if (and (pair? e) (eq? 'begin (car e))) (append (flatten-begin (cdr e)) e*) (cons e e*))) '() e*)) (define (compile-alternative ec et ef r pos) (if (= pos WITHCONT) (let-values ([(cc g0* f0*) (compile ec r WITHCONT)] [(ct g1* f1*) (compile et r WITHCONT)] [(cf g2* f2*) (compile ef r WITHCONT)]) (values (list "(" cc " ? " ct " : " cf ")") (append g2* g1* g0*) (append f2* f1* f0*))) (let-values ([(cc g0* f0*) (compile ec r WITHCONT)] [(ct g1* f1*) (compile-sequence (list et) r pos)] [(cf g2* f2*) (compile-sequence (list ef) r pos)]) (values (list 'lines (list "if (" cc ")") ct "else" cf) (append g2* g1* g0*) (append f2* f1* f0*))))) (define (compile-set n e r pos) (receive (ce global* free*) (compile e r WITHCONT) (let ([bind (or (lookup-variable r n) (error 'compile-set "unbound variable" n))]) (values (SET (car (extract-variable bind)) ce) (if (and (global? bind) (not (local? bind))) (cons n global*) global*) (if (and (not (global? bind)) (not (local? bind))) (add-free-set n local free*) free*))))) (define (compile-let b* e* r pos) (cond [(= pos WITHCONT) (error 'compile-let "let cannot be with continuation (yet)" b* e*)] [(list? b*) (compile-simple-let b* e* r pos)] [else (compile-advanced-let b* (car e*) (cdr e*) r pos)])) (define (compile-simple-let b* e* r pos) (let* ([n* (map car b*)] [v* (map cadr b*)] [r.local (extend-local* r n*)]) (receive (c* global* free*) (compile-sequence-list e* r.local pos) (receive (ca global0* free0*) (compile-let-assignment n* v* r r.local) (values (cons* 'lines ca c*) (append global0* global*) (append free0* (remp (lambda (f) (memq (cadr f) n*)) free*))))))) (define (compile-advanced-let n b* e* r pos) (error 'compile-advanced-let "not yet implemented")) (define (compile-let-assignment n* e* r r.local) (receive (c* global* free*) (map-compile compile e* r) (values (list (if (null? (cdr n*)) (list (lookup-variable r.local (car n*)) " = " (car c*)) (list "list (" (list-intersperse ", " (map (lambda (n) (lookup-local r.local n)) n*)) ") = array (" (list-intersperse ", " c*) ")")) ";") global* free*))) (define (compile-abstraction n* e* r pos) (receive (c global* free*) (compile-abstraction-root n* e* r) (values (FUNCTION c pos) global* free*))) (define (compile-definition n* e* r pos) (if (list? n*) (compile-function-definition (car n*) (cdr n*) e* r pos) (compile-variable-definition n* (car e*) r pos))) (define (compile-function-definition n n* e* r pos) (if (not (= pos SEQUENCE)) (error 'compile-function-definition "definition can only be in a sequence" n n* e* pos) (receive (c global* free*) (compile-abstraction-root n* e* (extend-local r (funbind n))) (values (DEFFUNCTION n c) global* free*)))) (define (compile-abstraction-root n* e* r) (receive (vars rest) (parse-vars n*) (receive (c* global* free*) (let* ([e* (flatten-begin e*)] [r.func (extend-frame r (if rest (cons rest n*) n*))] [r.body (analyse/env e* r.func)]) (compile-sequence-list e* r.body RET)) (values (ABSTRACTION vars rest c* free* global*) '() (map (lambda (f) (list (car f) (cadr f) (car (caddr f)))) (remp (lambda (f) (local? (car (caddr f)))) free*)))))) (define (compile-variable-definition n e r pos) (receive (c global* free*) (compile-set n e (extend-local r (varbind n r)) pos) (values (list c ";") global* free*))) (define (compile-application e e* r pos) (let* ([bind (lookup-application r e)] [var (extract-variable bind)]) (if (and var (procedure? (car var))) ((car var) e* r pos) (receive (c* global* free*) (map-compile compile e* r) (values (APPLICATION (or var (list (symbol->function e) 'global 'function)) c* pos) (if (and var (global? var) (not (local? var))) (cons e global*) global*) (if (and var (not (global? var)) (not (local? var))) (add-free-ref e bind free*) free*)))))) (define (APPLICATION bind c* pos) (RETURN pos (list (car bind) " " (ARGUMENTS c*)))) (define (FUNCTION c pos) (RETURN pos (cons "function " c))) (define (DEFFUNCTION n c) (cons* "function " (symbol->function n) " " c)) (define (ABSTRACTION vars rest c* free* global*) (list (ARGUMENTS (map symbol->variable vars)) (collect-closure free*) " " (with-globals global* (if rest (cons (list (symbol->variable rest) " = array_slice (func_get_vars (), " (length vars) ")") c*) c*)))) (define (SET var val pos) (let ([c (list var " = " val)]) (if (= pos WITHCONT) (parantheses c) (RETURN pos c)))) (define (ARGUMENTS als) (parantheses (list-intersperse ", " als))) (define (RETURN pos c) (if (= pos RET) (list "return " c) c)) (define (analyse/env e* r) (cond [(null? e*) r] [(pair? e*) (case (car e*) [(define) (analyse/env (cdr e*) (extend-local r ((if (list? (cadr e*)) funbind varbind) (car e*))))] [else (analyse/env (cdr e*) r)])] [else (analyse/env (cdr e*) r)])) (define (parse-vars n*) (let loop ([vars '()] [n* n*]) (cond [(null? n*) (values (reverse vars) #f)] [(pair? n*) (loop (cons (car n*) vars) (cdr n*))] [else (values (reverse vars) n*)]))) (define (collect-closure free*) (if (null? free*) "" (list " use " (parantheses (list-intersperse ", " (map (lambda (f) (case (car f) [(set) (string-append "&" (car (caddr f)))] [(ref) (car (caddr f))] [else (error 'collect-closure "invalid free variable" f)])) (merge-free free*))))))) (define (merge-free free*) (fold-left (lambda (merged free) (let ([thisfree? (lambda (f) (eq? (cadr f) (cadr free)))]) (cond [(find thisfree? merged) => (lambda (f) (cond [(eq? 'set (car f)) merged] [(eq? 'set (car free)) (cons free (remp thisfree? merged))] [else merged]))] [else (cons free merged)]))) '() free*)) (define (with-globals global* c*) (let ([globals (list-merge-unique equal? global*)]) (list 'lines "{" (cons* 'indent 'lines (if (null? globals) c* (cons (list "global " (list-intersperse ", " (map cdr globals)) ";") c*))) "}"))) (define (map-compile comp e* r) (fold-right* (lambda (e c* global* free*) (receive (c g* f*) (comp e r WITHCONT) (values (cons c c*) (append g* global*) (append f* free*)))) e* '() '() '())) (define (parantheses ls) (append '("(") ls '(")"))) (define (symbol->variable sym) (string-append "$" (string-process-specials (symbol->string sym)))) (define (symbol->function sym) (string-process-specials (symbol->string sym))) (define (string-process-specials str) (list->string (fold-right (lambda (c ls) (let ([special (assq c *special-table*)]) (if special (append (string->list (cadr special)) ls) (cons c ls)))) '() (string->list str)))) (define *special-table* '((#\+ "_plus_") (#\- "_") (#\* "_times_") (#\/ "_div_") (#\% "_mod_") (#\$ "_") (#\? "_is") )) (define (varbind n r) (cond [(lookup-variable r n) => (lambda (bind) `(,n (variable ,(shadow-variable (car (extract-variable bind))))))] [else `(,n (variable ,(symbol->variable n)))])) (define (funbind n) `(,n (function ,(symbol->function n)) (variable ,(asstring n)))) (define (shadow-variable varstr) (string-append "$_" (list->string (cdr (string->list varstr))))) (define (asstring n) (string-append "'" (symbol->string n) "'")) (define (extend-local r bind) (cons (car r) (cons (if (null? (car r)) (cons* (car bind) '(global) (cdr bind)) bind) (cdr r)))) (define (extend-local* r bind*) (let loop ([r.new r] [bind* bind*]) (if (null? bind*) r.new (loop (extend-local r.new (varbind (car bind*) r)) (cdr bind*))))) (define (extend-frame r n*) (cons r (map (cut varbind <> '()) n*))) (define (lookup r n proc) (cond [(null? r) #f] [(assq n (cdr r)) => (lambda (ref) (proc (cdr ref)))] [(lookup (car r) n proc) => list] [else #f])) (define (lookup-variable r n) (lookup r n (lambda (ref) (cond [(assq 'variable ref) => (lambda (var) (process-special (cadr var) ref))] [else (error 'lookup-variable "no mode for variable defined" ref n r)])))) (define (lookup-application r n) (lookup r n (lambda (ref) (cond [(assq 'function ref) => (lambda (func) (process-special (cadr func) ref))] [(assq 'variable ref) => (lambda (var) (process-special (cadr var) ref))] [else (error 'lookup-application "no mode for application defined" ref n r)])))) (define (process-special var special) (cons var (filter (lambda (s) (assq s special)) '(global function)))) (define (extract-variable bind) (if (or (not bind) (local? bind)) bind (extract-variable (car bind)))) (define (global-env? r) (null? (car r))) (define (local? bind) (not (list? (car bind)))) (define (global? var) (memq 'global (cdr var))) (define (function? var) (memq 'function (cdr var))) (define (add-free-ref n bind free*) (cons (list 'ref n bind) free*)) (define (add-free-set n bind free*) (cons (list 'set n bind) free*)) (define gensym (let ([counter 0]) (lambda (sym) (set! counter (+ 1 counter)) (string->symbol (string-append (symbol->string sym) "-gensym-" (number->string counter)))))) (define (check-args who args len) (unless (= len (length args)) (error who "invalid number of arguments" args))) (define php-fold "function ($func, $init, $arr) { return array_reduce ($ls, $proc, $init); }") (define (php-fold-proc args r pos) (check-args 'fold args 3) (let ([proc (car args)] [init (cadr args)] [ls (caddr args)]) (receive (c* global* free*) (map-compile compile (list ls proc init) r) (values (RETURN pos (list "array_reduce (" (list-intersperse ", " c*) ")")) global* free*)))) (define php-for-each "function ($func, $arr) { foreach ($arr as $v) { $func ($arr); } }") (define (php-for-each-proc args r pos) (unless (= pos SEQUENCE) (error 'for-each "can only be in sequence" args pos)) (check-args 'for-each args 2) (let ([proc (car args)] [ls (cadr args)]) (cond [(not (symbol? ls)) (let ([lsid (gensym 'list)]) (compile `(let ([,lsid ,ls]) (for-each ,proc ,lsid)) r pos))] [(and (pair? proc) (eq? 'lambda (car proc))) (let ([largs (cadr proc)] [lbody (cddr proc)]) (unless (= 1 (length largs)) (error 'for-each "proc's arity must be 1" proc)) (let* ([newvar (varbind (car largs) r)] [r.body (extend-local r newvar)]) (let-values ([(c g0* f0*) (compile ls r WITHCONT)] [(c* g1* f1*) (compile-sequence lbody r.body pos)]) (values (list "foreach " (parantheses (list c " as " (car (lookup-variable r.body (car largs))))) c*) (append g1* g0*) (append f1* f0*)))))] [(not (symbol? proc)) (let ([procid (gensym 'func)]) (compile `(let ([,procid ,proc]) (for-each ,procid ,ls)) r pos))] [else (let ([valueid (gensym 'v)]) (values (list "foreach " (parantheses (symbol->variable ls) " as " (symbol->variable valueid)) " " (list 'lines "{" (list 'indent (symbol->variable proc) " (" valueid ");") "}")) '() '()))]))) (define php-list "function () { return func_get_args(); }") (define php-cons "function ($elem, $arr) { return array_unshift ($arr, $elem); }") (define (php-cons-proc e* r pos) (check-args 'cons e* 2) (receive (c* global* free*) (map-compile compile e* r) (values (RETURN pos (list "array_unshift " (ARGUMENTS (list (cadr c*) (car c*))))) global* free*))) (define php-car "function ($arr) { return $arr[0]; }") (define (php-car-proc e* r pos) (check-args 'car e* 1) (receive (c global* free*) (compile (car e*) r WITHCONT) (values (RETURN pos (list c "[0]")) global* free*))) (define php-cdr "function ($arr) { return array_slice ($arr, 1); }") (define (php-cdr-proc e* r pos) (check-args 'cdr e* 1) (receive (c global* free*) (compile (car e*) r WITHCONT) (values (RETURN pos (list "array_slice " (ARGUMENTS (list c "1")))) global* free*))) (define (operator op) (lambda (e* r pos) (receive (c* global* free*) (map-compile compile e* r) (values (RETURN pos (parantheses (list-intersperse (string-append " " op " ") c*))) global* free*)))) (define (comparator cmp) (lambda (e* r pos) (receive (c* global* free*) (map-compile compile e* r) (values (RETURN pos (parantheses (list-intersperse " and " (let ([strcomp (string-append " " cmp " ")]) (intermap 2 (lambda (a b) (list a strcomp b)) c*))))) global* free*)))) (define *r.global* `(() (list (global) (function "array") (variable ,php-list)) (cons (global) (function ,php-cons-proc) (variable ,php-cons)) (car (global) (function ,php-car-proc) (variable ,php-car)) (cdr (global) (function ,php-cdr-proc) (variable ,php-cdr)) (length (global) (function "count")) (map (global) (function "array_map")) (for-each (global) (function ,php-for-each-proc) (variable ,php-for-each)) (filter (global) (function "array_filter")) (reverse (global) (function "array_reverse")) (fold (global) (function ,php-fold-proc) (variable ,php-fold)) (echo (global) (function "echo")) (+ (global) (function ,(operator "+"))) (- (global) (function ,(operator "-"))) (* (global) (function ,(operator "*"))) (/ (global) (function ,(operator "/"))) (mod (global) (function ,(operator "%"))) (eq? (global) (function ,(comparator "==="))) (= (global) (function ,(comparator "=="))) (< (global) (function ,(comparator "<"))) (> (global) (function ,(comparator ">"))) (<= (global) (function ,(comparator "<="))) (>= (global) (function ,(comparator ">="))) (and (global) (function ,(operator "and"))) (or (global) (function ,(operator "or"))) (string-append (global) (function ,(operator "."))) )) (define (indent n) (display (make-string (* 2 n) #\space))) (define (write-compilation c ind) (cond [(list? c) (case (and (pair? c) (car c)) [(lines) (unless (null? (cdr c)) (write-compilation (cadr c) ind) (for-each (lambda (c) (newline) (indent ind) (write-compilation c ind)) (cddr c)))] [(indent) (indent 1) (write-compilation (cdr c) (+ 1 ind))] [else (for-each (cut write-compilation <> ind) c)])] [(string? c) (display c)] [else (error 'write-compilation "can't write compilation" c)])) (define (warn-free free*) (define warning "Warning: free identifiers: ") (define whitespace " ") (unless (null? free*) (display warning) (display (car free*)) (newline) (for-each (lambda (free) (display whitespace) (display free) (newline)) (cdr free*)) (newline))) (define (scomp e) (receive (c global* free*) (compile e *r.global* SEQUENCE) (warn-free free*) (write-compilation c 0) (newline)))
false
a22c3d11745249db39280bfb5af9d349d3dd55a4
ae76253c0b7fadf8065777111d3aa6b57383d01b
/chap2/exec-2.20.ss
ccfd0409749e3ce1143d35baa7d18c586b36d5fa
[]
no_license
cacaegg/sicp-solution
176995237ad1feac39355f0684ee660f693b7989
5bc7df644c4634adc06355eefa1637c303cf6b9e
refs/heads/master
2021-01-23T12:25:25.380872
2014-04-06T09:35:15
2014-04-06T09:35:15
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
543
ss
exec-2.20.ss
(define (same-parity pivot . ls) (define (make-check) (if (even? pivot) even? odd?)) (define (processor remain result same?) (if (null? remain) result (let ((item (car remain))) (if (same? item) (processor (cdr remain) (append result (list item)) same?) (processor (cdr remain) result same?))))) (processor ls (list pivot) (make-check))) (same-parity 1 2 3 4 5 6 7) (same-parity 2 3 4 5 6 7)
false
34259224291a818a7812ffb918d55065b98c0930
2e50e13dddf57917018ab042f3410a4256b02dcf
/contrib/50.option/option.scm
5bd84a2de3bcb7b9a259a6ffed94ac6680ce0ecd
[ "MIT" ]
permissive
koba-e964/picrin
c0ca2596b98a96bcad4da9ec77cf52ce04870482
0f17caae6c112de763f4e18c0aebaa73a958d4f6
refs/heads/master
2021-01-22T12:44:29.137052
2016-07-10T16:12:36
2016-07-10T16:12:36
17,021,900
0
0
MIT
2019-05-17T03:46:41
2014-02-20T13:55:33
Scheme
UTF-8
Scheme
false
false
395
scm
option.scm
(define-library (picrin control option) (import (scheme base) (picrin control) (picrin procedure)) (define unit identity) (define (bind m f) (and m (f m))) (define-syntax reify (syntax-rules () ((_ expr) (reset (unit expr))))) (define (reflect m) (shift k (bind m k))) (export unit bind reify reflect))
true
ab46aba0d791439f711017b8ddc48d06fdd47480
7b49e5e3aec855d322c1179d4fb288b76307fa4a
/bin/insert-exif-date.scm
d49d4a27a7d206f4c070edef98c4d4586f4a36d4
[]
no_license
mario-goulart/awful-picman
db7fb456e551a0796d67187d8bea90692056c48a
3a38e1265ff770e1292c45aa44df8edadaa22028
refs/heads/master
2022-12-22T10:13:21.786573
2022-12-11T19:41:17
2022-12-11T19:41:23
11,710,823
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,792
scm
insert-exif-date.scm
#!/bin/sh #| -*- scheme -*- exec csi -s $0 "$@" |# ;; This script inserts dates for pics based on their exif data. It ;; gets the path to pictures from the database and try to get exif ;; dates from those files (it doesn't scan picture files that are not ;; in the database). (use data-structures extras files posix) (use exif sql-de-lite) (use awful-picman-db awful-picman-params awful-picman-utils) (define (usage #!optional exit-code) (let ((port (if (and exit-code (not (zero? exit-code))) (current-error-port) (current-output-port))) (this (pathname-strip-directory (program-name)))) (fprintf port "Usage: ~a [<directory>]\n" this) (when exit-code (exit exit-code)))) (define (insert-exif-date! db-file) (define limit 10) (call-with-database db-file (lambda (db) (let loop ((offset 0)) (let* ((raw-pics (db-query db (string-append "select pic_id, dir, filename, descr, decade, year, month, day " "from pics order by pic_id limit ? offset ?") values: (list limit offset))) (pics (map (lambda (raw-pic) (apply make-db-pic (append raw-pic (list '() '())))) raw-pics)) (null-date? (lambda (d) (or (null? d) (equal? d ""))))) (for-each (lambda (pic) (when (and (null-date? (db-pic-decade pic)) (null-date? (db-pic-year pic)) (null-date? (db-pic-month pic)) (null-date? (db-pic-day pic))) (let ((exif-date (get-exif-date-from-file (db-pic-path pic)))) (when exif-date (info "~a (~a) -> ~a-~a-~a" (db-pic-path pic) (db-pic-id pic) (+ (car exif-date) (cadr exif-date)) (caddr exif-date) (cadddr exif-date)) (db-query db "update pics set decade=?, year=?, month=?, day=? where pic_id=?" values: (append exif-date (list (db-pic-id pic)))))))) pics) (unless (null? pics) (loop (- (+ offset limit) 1)))))))) (let ((args (command-line-arguments))) (when (or (member "-h" args) (member "-help" args) (member "--help" args)) (usage 0)) (unless (null? args) (change-directory (car args))) (let ((db-file (make-pathname metadata-dir db-filename))) (unless (file-exists? db-file) (info-error "Could not find database file (~a). Aborting." db-file) (exit 1)) (insert-exif-date! db-file)))
false
0fa8c85e4d07c0574d92adfdbb2d3b752982a62a
be32518c6f54b0ab1eaf33f53405ac1d2e1023c2
/np/lang/macros/test/codegen/test-codegen-nonterminals.ss
539164b3bdcfc26556cff6217f12647531f15ff0
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
ilammy/np
7990302bc30fe7802a7f4fc33d8fa7449ef8b011
0e3cbdea0eb2583f9b272d97bc408011af6a7947
refs/heads/master
2016-09-05T17:11:03.893011
2015-06-13T16:37:39
2015-06-13T16:37:39
23,740,287
1
0
null
2015-06-13T16:39:43
2014-09-06T17:19:46
Scheme
UTF-8
Scheme
false
false
10,238
ss
test-codegen-nonterminals.ss
(import (scheme base) (only (srfi 1) every first second) (np lang macros codegen) (np lang descriptions definitions) (sr ck) (sr ck kernel) (te base) (te conditions assertions) (te utils verify-test-case)) ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; (define-test-case (nonterminals:standalone "Code generation for standalone nonterminal forms") (define-syntax for (syntax-rules () ((_ defs normalized-forms . body) (let ((defs ($ ($generate-standalone-nonterminal-definitions normalized-forms)))) . body )) ) ) (define (assert-list-of n list) (assert-true (list? list)) (assert-= n (length list)) (assert-true (every nonterminal-definition? list)) ) (define (assert-def def name meta-variables production-definitions) (assert-eq name (nonterminal-name def)) (assert-equal meta-variables (nonterminal-meta-variables def)) (assert-equal production-definitions (nonterminal-production-definitions def)) ) (define-test ("Empty list") (for defs '() (assert-list-of 0 defs) ) ) (define-test ("Smoke test 1") (for defs '((Number #f (Num) (n))) (assert-list-of 1 defs) (assert-def (first defs) 'Number '(Num) '(n)) ) ) (define-test ("Smoke test 2") (for defs '((Number #(Number?) (Num) (n))) (assert-list-of 1 defs) (assert-def (first defs) 'Number '(Num) '(n)) ) ) (define-test ("Does not change meta-variable order") (for defs '((Number #f (Num Number) (n))) (assert-list-of 1 defs) (assert-def (first defs) 'Number '(Num Number) '(n)) ) ) (define-test ("Does not change production order") (for defs '((Number #(Number?) (Num) (n (n n)))) (assert-list-of 1 defs) (assert-def (first defs) 'Number '(Num) '(n (n n))) ) ) (define-test ("Can handle several nonterminals and does not change their order") (for defs '((Number #f (Num) (n)) (Pair #f (Pair) ((e e)))) (assert-list-of 2 defs) (assert-def (first defs) 'Number '(Num) '(n)) (assert-def (second defs) 'Pair '(Pair) '((e e))) ) ) ) (verify-test-case! nonterminals:standalone) ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; (define-test-case (nonterminals:extension-addition "Code generation for extension addition nonterminal forms") (define-syntax for (syntax-rules () ((_ defs normalized-forms . body) (let ((defs ($ ($generate-extension-nonterminal-additions normalized-forms)))) . body )) ) ) (define (assert-list-of n list) (assert-true (list? list)) (assert-= n (length list)) (assert-true (every nonterminal-definition? list)) ) (define (assert-def def name meta-variables production-definitions) (assert-eq name (nonterminal-name def)) (assert-equal meta-variables (nonterminal-meta-variables def)) (assert-equal production-definitions (nonterminal-production-definitions def)) ) (define-test ("Empty list") (for defs '() (assert-list-of 0 defs) ) ) (define-test ("Smoke test 1") (for defs '((Number #f (Num) (n))) (assert-list-of 1 defs) (assert-def (first defs) 'Number '(Num) '(n)) ) ) (define-test ("Smoke test 2") (for defs '((Number Number? (Num) (n))) (assert-list-of 1 defs) (assert-def (first defs) 'Number '(Num) '(n)) ) ) (define-test ("Does not change meta-variable order") (for defs '((Number #f (Num Number) (n))) (assert-list-of 1 defs) (assert-def (first defs) 'Number '(Num Number) '(n)) ) ) (define-test ("Does not change production order") (for defs '((Number Number? (Num) (n (n n)))) (assert-list-of 1 defs) (assert-def (first defs) 'Number '(Num) '(n (n n))) ) ) (define-test ("Can handle several nonterminals and does not change their order") (for defs '((Number #f (Num) (n)) (Pair Pair? (Pair) ((e e)))) (assert-list-of 2 defs) (assert-def (first defs) 'Number '(Num) '(n)) (assert-def (second defs) 'Pair '(Pair) '((e e))) ) ) ) (verify-test-case! nonterminals:extension-addition) ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; (define-test-case (nonterminals:extension-removal "Code generation for extension removal nonterminal forms") (define-syntax for (syntax-rules () ((_ rems normalized-forms . body) (let ((rems ($ ($generate-extension-nonterminal-removals normalized-forms)))) . body )) ) ) (define (assert-list-of n list) (assert-true (list? list)) (assert-= n (length list)) (assert-true (every symbol? list)) ) (define (assert-rem removed name) (assert-eq name removed) ) (define-test ("Empty list") (for rems '() (assert-list-of 0 rems) ) ) (define-test ("Smoke test") (for rems '(Number) (assert-list-of 1 rems) (assert-rem (first rems) 'Number) ) ) (define-test ("Does not change removed nonterminal order") (for rems '(Number Pair) (assert-list-of 2 rems) (assert-rem (first rems) 'Number) (assert-rem (second rems) 'Pair) ) ) ) (verify-test-case! nonterminals:extension-removal) ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; (define-test-case (nonterminals:extension-modification "Code generation for extension modification nonterminal forms") (define-syntax for (syntax-rules () ((_ mods normalized-forms . body) (let ((mods ($ ($generate-extension-nonterminal-modifications normalized-forms)))) . body )) ) ) (define (assert-list-of n list) (assert-true (list? list)) (assert-= n (length list)) (assert-true (every nonterminal-modification? list)) ) (define (assert-mod modified name added-meta-vars removed-meta-vars added-production-definitions removed-production-definitions) (assert-eq name (modified-nonterminal-name modified)) (assert-equal added-meta-vars (modified-nonterminal-added-meta-variables modified)) (assert-equal removed-meta-vars (modified-nonterminal-removed-meta-variables modified)) (assert-equal added-production-definitions (modified-nonterminal-added-production-definitions modified)) (assert-equal removed-production-definitions (modified-nonterminal-removed-production-definitions modified)) ) (define-test ("Empty list") (for mods '() (assert-list-of 0 mods) ) ) (define-test ("Smoke test") (for mods '((Number #f () () () ())) (assert-list-of 1 mods) (assert-mod (first mods) 'Number '() '() '() '()) ) ) (define-test ("Does not change meta-variable order") (for mods '((Number #f (a b) (c d e) () ())) (assert-list-of 1 mods) (assert-mod (first mods) 'Number '(a b) '(c d e) '() '()) ) ) (define-test ("Does not change production order") (for mods '((Number #f () () (a b) (c d e))) (assert-list-of 1 mods) (assert-mod (first mods) 'Number '() '() '(a b) '(c d e)) ) ) (define-test ("Does not change nonterminal order") (for mods '((Number #f (a b c) (d) (e f) (g h i)) (Pair #f (j) () () (k))) (assert-list-of 2 mods) (assert-mod (first mods) 'Number '(a b c) '(d) '(e f) '(g h i)) (assert-mod (second mods) 'Pair '(j) '() '() '(k)) ) ) ) (verify-test-case! nonterminals:extension-modification) ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; (define-test-case (nonterminals:predicate-definitions:standalone "Definition generators for standalone nonterminal predicates") (define lang #f) ; expected to fail when define-language is implemented (define-syntax for (syntax-rules () ((_ normalized-forms . body) (begin ($ ($generate-standalone-nonterminal-predicate-definitions 'lang normalized-forms)) . body )) ) ) (define (assert-defined procedure) (assert-true (procedure? procedure)) ) ; This should be syntactically valid (define-test ("Empty list") (for '() #t ) ) ; This should be syntactically valid (define-test ("Effectively empty list") (for '((Number #f (Num) (n)) (Pair #f (Cons) ((a d)))) #t ) ) (define-test ("Example definitions") (for '((Number Number? (Num) (n)) (Pair Pair? (Cons) ((a d)))) (assert-defined Number?) (assert-defined Pair?) ) ) ; These are allowed, but they are the user's problem (define-test ("Duplicate definitions are allowed") (for '((Number Number? (Num) (n)) (Pair Number? (Cons) ((a d)))) (assert-defined Number?) ) ) ) (verify-test-case! nonterminals:predicate-definitions:standalone) ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; (define-test-case (nonterminals:predicate-definitions:extension "Definition generators for extension nonterminal predicates") (define lang #f) ; expected to fail when define-language is implemented (define-syntax for (syntax-rules () ((_ normalized-forms . body) (begin ($ ($generate-extension-nonterminal-predicate-definitions 'lang normalized-forms)) . body )) ) ) (define (assert-defined procedure) (assert-true (procedure? procedure)) ) ; This should be syntactically valid (define-test ("Empty list") (for '() #t ) ) ; This should be syntactically valid (define-test ("Effectively empty list") (for '((Number #f (Num) (n)) (Pair #f (Cons) ((a d))) (Triple #f (Tri) () () ((t t t))) (Void #f () () () ())) #t ) ) (define-test ("Example definitions") (for '((Number Number? (Num) (n)) (Pair Pair? (Cons) ((a d))) (Triple Tri? (Tri) () () ((t t t))) (Void Void? () () () ())) (assert-defined Number?) (assert-defined Pair?) (assert-defined Tri?) (assert-defined Void?) ) ) ; These are allowed, but they are the user's problem (define-test ("Duplicate definitions are allowed") (for '((Number Number? (Num) (n)) (Pair Number? (Cons) ((a d))) (Void Number? () () () ())) (assert-defined Number?) ) ) ) (verify-test-case! nonterminals:predicate-definitions:extension)
true
c541d5c5062ae68894604e2f176d07872f2189ee
ed81f401dcd2ce0399cec3a99b6e5851e62e74ca
/data/github.com/mwand/eopl3/2648675ca8e8ee804701a31f6198838d2c7a04f5/chapter4/call-by-need/drscheme-init.scm
bc39938a6ad9dc86c9618a8c617ec7fb4743e35e
[ "MIT" ]
permissive
smola/language-dataset
9e2a35340d48b497cd9820fa2673bb5d482a13f7
4d1827d1018b922e03a48a5de5cb921a6762dda3
refs/heads/master
2023-03-10T12:42:04.396308
2022-07-15T18:05:05
2022-07-15T18:05:05
143,737,125
18
3
MIT
2023-03-06T05:01:14
2018-08-06T14:05:52
Python
UTF-8
Scheme
false
false
4,286
scm
drscheme-init.scm
;; drscheme-init.scm - compatibility file for DrScheme ;; usage: (require "drscheme-init.scm") ;;; makes structs printable, and provides basic functionality for ;;; testing. This includes pretty-printing and tracing. (module drscheme-init mzscheme ;; show the contents of define-datatype values (print-struct #t) (require (lib "pretty.ss")) (provide (all-from (lib "pretty.ss"))) (require (lib "trace.ss")) (provide (all-from (lib "trace.ss"))) (provide make-parameter) (provide run-experiment run-tests! stop-after-first-error run-quietly ) ;; safely apply procedure fn to a list of args. ;; if successful, return (cons #t val) ;; if eopl:error is invoked, returns (cons #f string), where string is the ;; format string generated by eopl:error. If somebody manages to raise a ;; value other than an exception, then the raised value is reported. (define apply-safely (lambda (proc args) (with-handlers ([(lambda (exn) #t) ; catch any error (lambda (exn) ; evaluate to a failed test result (cons #f (if (exn? exn) (exn-message exn) exn)))]) (let ([actual (apply proc args)]) (cons #t actual))))) ;; run-experiment : ;; ((a ...) -> b) * (a ...) * b * (b * b -> bool) ;; -> (cons bool b) ;; usage: (run-experiment fn args correct-answer equal-answer?) ;; Applies fn to args. Compares the result to correct-answer. ;; Returns (cons bool b) where bool indicates whether the ;; answer is correct. (define run-experiment (lambda (fn args correct-answer equal-answer?) (let* ((result (apply-safely fn args)) ;; ans is either the answer or the args to eopl:error (error-thrown? (not (car result))) (ans (cdr result))) (cons (if (eqv? correct-answer 'error) error-thrown? (equal-answer? ans correct-answer)) ans)))) (define stop-after-first-error (make-parameter #f)) (define run-quietly (make-parameter #t)) ;; run-tests! : (arg -> outcome) * (any * any -> bool) * (list-of test) ;; -> unspecified ;; where: ;; test ::= (name arg outcome) ;; outcome ::= ERROR | any ;; usage: (run-tests! run-fn equal-answer? tests) ;; for each item in tests, apply run-fn to the arg. Check to see if ;; the outcome is right, comparing values using equal-answer?. ;; print a log of the tests. ;; at the end, print either "no bugs found" or the list of tests ;; failed. ;; Normally, run-tests! will recover from any error and continue to ;; the end of the test suite. This behavior can be altered by ;; setting (stop-after-first-error #t). (define (run-tests! run-fn equal-answer? tests) (let ((tests-failed '())) (for-each (lambda (test-item) (let ((name (car test-item)) (pgm (cadr test-item)) (correct-answer (caddr test-item))) (printf "test: ~a~%" name) (let* ((result (run-experiment run-fn (list pgm) correct-answer equal-answer?)) (correct? (car result)) (actual-answer (cdr result))) (if (or (not correct?) (not (run-quietly))) (begin (printf "~a~%" pgm) (printf "correct outcome: ~a~%" correct-answer) (printf "actual outcome: ") (pretty-display actual-answer))) (if correct? (printf "correct~%~%") (begin (printf "incorrect~%~%") ;; stop on first error if stop-after-first? is set: (if (stop-after-first-error) (error name "incorrect outcome detected")) (set! tests-failed (cons name tests-failed))))))) tests) (if (null? tests-failed) (printf "no bugs found~%") (printf "incorrect answers on tests: ~a~%" (reverse tests-failed))))) )
false
6f8a3c138812f6fc4ca4f908139c89caffe84e96
21d1502c108ff87379f29ce70146a9ee21492297
/tests/thread-test.scm
088cf0187a1be4eeee0890a37188103adb35dcee
[]
no_license
ThomasHintz/mda
d3358c433361d732f593dde1442eda5dba7fc221
27d304066c534337e28d8d06163c592f0ccfbc2e
refs/heads/master
2020-05-20T01:08:50.866407
2013-01-02T13:08:44
2013-01-02T13:08:44
2,335,455
0
0
null
null
null
null
UTF-8
Scheme
false
false
809
scm
thread-test.scm
(use mda-client srfi-18 ports) (define (test-proc) (db:store "v" "k") (db:read "k")) (define (do-times num proc) (letrec ((_ (lambda (i num proc) (if (> i num) #t (begin (proc) (_ (+ i 1) num proc)))))) (_ 0 num proc))) (define (do-test) (do-times 1000 test-proc)) (define (range from/to . to) (let ((f (if (= (length to) 0) -1 (- from/to 1))) (t (if (> (length to) 0) (first to) from/to))) (do ((i (- t 1) (- i 1)) (l '() (cons i l))) ((= i f) l)))) (map (lambda (thread) (thread-join! thread)) (map (lambda (arg-not-used) (let ((t (make-thread do-test))) (thread-start! t) t)) (range 1000))) (print "success")
false
f5d8598ed952b2c4286cc3d6b3fe89b62bf907c0
e1fc47ba76cfc1881a5d096dc3d59ffe10d07be6
/ch5/5.03.scm
7dfb6ddb03906dbe0321bedda1dad01d9c564cd7
[]
no_license
lythesia/sicp-sol
e30918e1ebd799e479bae7e2a9bd4b4ed32ac075
169394cf3c3996d1865242a2a2773682f6f00a14
refs/heads/master
2021-01-18T14:31:34.469130
2019-10-08T03:34:36
2019-10-08T03:34:36
27,224,763
2
0
null
null
null
null
UTF-8
Scheme
false
false
676
scm
5.03.scm
; simple (controller (assign x (op read)) (assign guess (const 1.0)) test-guess (test (op good-enough?) (reg guess)) (branch (label sqrt-done)) (assign guess (op improve) (reg guess)) (goto (label test-guess)) sqrt-done ) ; full (controller ; init (assign x (op read)) (assign guess (const 1.0)) test-guess ; good-enough? (assign t (op square) (reg guess)) (assign t (op -) (reg t) (reg x)) (assign t (op abs) (reg t)) (test (op <) (reg t) (const 0.001)) (branch (label sqrt-done)) ; improve (assign t (op /) (reg x) (reg guess)) (assign guess (op average) (reg guess) (reg t)) ; average assumed (goto (label test-guess)) sqrt-done )
false
e4ddca0fc83f9b269ecabf6ac3271ddff2aea439
beac83b9c75b88060f4af609498541cf84437fd3
/site/content/centralized-people/carl-eastlund.ss
49803c3c6cdac1e0df8ff7f6e829a5d435900e55
[]
no_license
nuprl/prl-website
272ce3b9edd5b3ada23798a694f6cb7c6d510776
31a321f629a62f945968c3e4c59d180de0f656f6
refs/heads/master
2021-05-16T02:06:38.847789
2016-09-16T14:41:22
2016-09-16T14:41:22
412,044
1
0
null
null
null
null
UTF-8
Scheme
false
false
490
ss
carl-eastlund.ss
#lang scheme (provide me)(define me (quote (person "Carl Eastlund" (group "Alumni") (picture "gallery/Carl_Eastlund.jpg") (homepage "http://www.ccs.neu.edu/home/cce/") (bio " A third-year student in the languages group, I graduated with a CS degree from CMU in '01 and worked a couple years in industry before coming here. My interests lie mostly in static analysis and functional software design. Outside school, I enjoy kung fu, card games and board games, and geeky fiction genres."))))
false
dc413fab0bb003efd442d873eb5dfaa5f4ce670e
957ca548c81c2c047ef82cdbf11b7b2b77a3130b
/04LAB/04_lab_3.scm
953a822661f80917f99d44182a4d33a3a9bd1150
[]
no_license
emrzvv/Scheme
943d4a55c5703f0e1318ae65aec24d0cb57e3372
e6ae1ed19104f46d22eee2afabea5459f7031a22
refs/heads/master
2023-02-19T08:55:29.470491
2021-01-18T12:56:26
2021-01-18T12:56:26
318,609,955
4
0
null
null
null
null
UTF-8
Scheme
false
false
1,112
scm
04_lab_3.scm
#|(define-syntax lazy-cons (syntax-rules () ((lazy-cons a b) (cons a (delay b))))) (define lazy-car car) (define (lazy-cdr ls) (force (cdr ls))) (define (lazy-ref lst n) (if (zero? n) (lazy-car lst) (lazy-ref (lazy-cdr lst) (- n 1)))) (define (trib-gen a b c) (lazy-cons a (trib-gen b c (+ a b c)))) (define (lazy-trib n) (lazy-ref (trib-gen 0 0 1) n))|# (define (default-trib n) (cond ((<= n 1) 0) ((= n 2) 1) (else (+ (default-trib (- n 1)) (default-trib (- n 2)) (default-trib (- n 3)))))) (define memoized-trib (let ((memory '())) (lambda (n) (let ((memoized (assq n memory))) (if (not (equal? memoized #f)) (cadr memoized) (let ((next-value (cond ((<= n 1) 0) ((= n 2) 1) (else (+ (memoized-trib (- n 3)) (memoized-trib (- n 2)) (memoized-trib (- n 1))))))) (set! memory (cons (list n next-value) memory)) next-value)))))) (default-trib 30) (display #\newline) (memoized-trib 100)
true
8bf7e575bf709f868d1a8976aa8fd91113fb6c2a
961ccc58c2ed4ed1d84a78614bedf0d57a2f2174
/scheme/socket-repl-server.scm
867b37d27d4c4b2c03b37ff7d92837d574d1c3e5
[]
no_license
huangjs/mostly-lisp-code
96483b566b8fa72ab0b73bf0e21f48cdb80dab0d
9fe862dbb64f2a28be62bb1bd996238de018f549
refs/heads/master
2021-01-10T10:11:50.121705
2015-11-01T08:53:22
2015-11-01T08:53:22
45,328,850
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,020
scm
socket-repl-server.scm
(module socket-repl (main main)) (define s1 (make-server-socket)) (define s2 #unspecified) (define (main argv) (dynamic-wind ;; Init: Launch an xterm with telnet running ;; on the s listening port and connect (lambda () (run-process "/usr/X11R6/bin/xterm" "-display" ":0" "-e" "telnet" "localhost" (number->string (socket-port-number s1))) (set! s2 (socket-accept s1)) (display #"\nWelcome on the socket REPL.\n\n> " (socket-output s2)) (flush-output-port (socket-output s2))) ;; Action: A toplevel like loop (lambda () (let loop () (let ((obj (eval (read (socket-input s2))))) (fprint (socket-output s2) "; Result: " obj) (display "> " (socket-output s2)) (flush-output-port (socket-output s2)) (loop)))) ;; Termination: We go here when ;; -a: an error occurs ;; -b: connection is closed (lambda () (print #"Shutdown ......\n") (socket-close s2) (socket-shutdown s1))))
false
28f1fdef0f8c956df3c1881261a8145ccf54ecdf
fb9a1b8f80516373ac709e2328dd50621b18aa1a
/ch1/1-2-5_Greatest_Common_Divisor.scm
204d1cb8dd08a5f219602f57cb5fafb7952fee27
[]
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
270
scm
1-2-5_Greatest_Common_Divisor.scm
;; 1.2.5 最大公約数 ;; Euclidのアルゴリズム (define (gcd a b) (if (= b 0) a (gcd b (remainder a b)))) ;; 問題 1.20 (define remainder-old remainder) (define (remainder a b) (print "remainder " a " " b) (remainder-old a b)) (gcd 206 40)
false
847a1852e547989f804bf4fbdb488d91cc8d949d
4a01cc0d02f7bc90a2fad16a3784faf0cdfedaba
/tests/run.scm
9c29af2bd5ff278009d94e531ea7888d631c4790
[]
no_license
lbeckman314/sicp-chicken
cdc04046632a783e4df6875f11e81f58d8136162
0f65de82acb06ae6abcff655dc1aea115cfdc142
refs/heads/master
2020-09-01T21:19:52.593955
2016-08-30T20:28:37
2016-08-30T20:28:37
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,743
scm
run.scm
(use sicp sicp-eval sicp-eval-anal sicp-streams test) (test "Draw-painter-as-svg" "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" height=\"256\" width=\"256\"><g stroke=\"black\"><line x1=\"0.0\" y1=\"256.0\" x2=\"256.0\" y2=\"0.0\"></line></g></svg>" (with-output-to-string (lambda () (draw-painter-as-svg (segments->painter (list (make-segment (make-vect 0.0 1.0) (make-vect 1.0 0.0)))))))) (test "Draw-painter-as-svg: beside" "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" height=\"256\" width=\"256\"><g stroke=\"black\"><line x1=\"128.0\" y1=\"256.0\" x2=\"256.0\" y2=\"0.0\"></line><line x1=\"0.0\" y1=\"256.0\" x2=\"128.0\" y2=\"0.0\"></line></g></svg>" (with-output-to-string (lambda () (let ((painter (segments->painter (list (make-segment (make-vect 0.0 1.0) (make-vect 1.0 0.0)))))) (draw-painter-as-svg (beside painter painter)))))) (test "Draw-painter-as-svg: image" "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" height=\"256\" width=\"256\"><g stroke=\"black\"><g transform=\"matrix(128.0, 0.0, 0.0, 256.0, 128.0, 0.0)\"><image xlink:href=\"lena.png\" width=\"1\" height=\"1\"></image></g><g transform=\"matrix(128.0, 0.0, 0, 256, 0, 0)\"><image xlink:href=\"lena.png\" width=\"1\" height=\"1\"></image></g></g></svg>" (with-output-to-string (lambda () (let ((painter (image->painter "lena.png"))) (draw-painter-as-svg (beside painter painter)))))) (test "Numerical derivation" 1 (deriv '(+ x 3) 'x)) (test "Symbolic derivation" 'y (deriv '(* x y) 'x)) (test "Stream->list with all" '(1 2 3) (stream->list (cons-stream 1 (cons-stream 2 (cons-stream 3 stream-null))))) (test "Stream->list with 2" '(1 2) (stream->list (cons-stream 1 (cons-stream 2 (cons-stream 3 stream-null))) 2)) (test "List->string" '(1 2 3) (stream->list (list->stream '(1 2 3)))) (test "The evaluator evaluates" 5 (parameterize ((primitive-procedures (cons (list '+ +) (primitive-procedures)))) (eval* '(+ 2 3) (setup-environment)))) (call-with-values (lambda () (time+values (+ 2 2))) (lambda (time value) (test-assert "Time returns a number" (number? time)) (test "Values returns the value" 4 value))) (test "The analyzing evaluator analyzes and evaluates" 5 (parameterize ((primitive-procedures (cons (list '+ +) (primitive-procedures)))) (anal-eval* '(+ 2 3) (setup-environment)))) (use sicp-eval-lazy) (with-primitive-procedures `((+ ,+) (values ,values)) (lambda (env) (eval* '(define count 0) env) (eval* '(define (id x) (set! count (+ count 1)) x) env) (eval* '(define w (id (id 10))) env) (test "Id has been called once." 1 (eval* 'count env)) (test "W is 10." 10 (eval* '(values w) env)) (test "Id has been called twice." 2 (eval* 'count env)))) (use sicp-eval-amb) (with-require `((+ ,+) (prime? ,prime?) (list ,list)) (lambda (env) (ambeval* '(define (prime-sum-pair list1 list2) (let ((a (an-element-of list1)) (b (an-element-of list2))) (require (prime? (+ a b))) (list a b))) env) (test "Ambeval with prime-sum-pair" '(3 20) (ambeval-n '(prime-sum-pair '(1 3 5 8) '(20 35 110)) env 1)))) (test-exit)
false
e306ee25d9f5bf07d40b63d1c71f1a23a8603eaf
7301b8e6fbd4ac510d5e8cb1a3dfe5be61762107
/ex-4.5.scm
2659728f52427d1e66639872f8737db16d06335d
[]
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
1,436
scm
ex-4.5.scm
;;; Exercise 4.5. Scheme allows an additional syntax for cond clauses, (<test> ;;; => <recipient>). If <test> evaluates to a true value, then <recipient> is ;;; evaluated. Its value must be a procedure of one argument; this procedure is ;;; then invoked on the value of the <test>, and the result is returned as the ;;; value of the cond expression. For example ;;; ;;; (cond ((assoc 'b '((a 1) (b 2))) => cadr) ;;; (else false)) ;;; ;;; returns 2. Modify the handling of cond so that it supports this extended ;;; syntax. (define (expand-clauses clauses) (if (null? clauses) 'false ; no else clause (let ((first (car clauses)) (rest (cdr clauses))) (cond [(cond-else-clause? first) (if (null? rest) (sequence->exp (cond-actions first)) (error "ELSE clause isn't last -- COND->IF" clauses))] [(cond-extended-clause? first) `(let ((result ,(cond-predicate first))) (if result (,(cond-recipient first) result) ,(expand-clauses rest)))] [else (make-if (cond-predicate first) (sequence->exp (cond-actions first)) (expand-clauses rest))])))) (define (cond-extended-clause? clause) (tagged-list? (cdr clause) '=>)) (define (cond-recipient clause) (caddr clause))
false
54d4a2d34718839a839dd1030dbb560e1545741c
d881dacf2327ecd474f11318ea8e2b9536fe3e73
/srfi-tools/core.sld
c30d0b3822cf456020efee84dd9eeb6d8a062ec3
[ "MIT" ]
permissive
scheme-requests-for-implementation/srfi-common
a84c7eaa6a40a4d1b80ef723759c2d3aed480177
78b45ab8028cfbd462fb1231cafec4ff4c5c5d30
refs/heads/master
2023-07-19T23:14:26.615668
2023-07-14T18:03:06
2023-07-14T18:03:06
37,961,335
31
7
MIT
2023-05-11T13:57:14
2015-06-24T04:00:50
HTML
UTF-8
Scheme
false
false
1,169
sld
core.sld
(define-library (srfi-tools core) (export srfi-num-stem srfi-num-ext try-parse-srfi-number parse-srfi-number write-string-about-srfi write-line-about-srfi srfi-default-command srfi-default-number-command) (import (scheme base)) (begin (define (srfi-num-stem num) (string-append "srfi-" (number->string num))) (define (srfi-num-ext num ext) (string-append (srfi-num-stem num) ext)) ;; (define (try-parse-srfi-number string) (let ((num (string->number string))) (and (integer? num) (>= num 0) num))) (define (parse-srfi-number string) (or (try-parse-srfi-number string) (error "Not a valid SRFI number" string))) ;; (define (write-string-about-srfi what-about num) (let ((num (parse-srfi-number num))) (write-string (what-about num)))) (define (write-line-about-srfi what-about num) (write-string-about-srfi what-about num) (newline)) ;; (define srfi-default-command (make-parameter "list")) (define srfi-default-number-command (make-parameter "browse"))))
false
a7fa080069bd751446639d489c0b5e427945ce4b
defeada37d39bca09ef76f66f38683754c0a6aa0
/System.Data/system/data/common/db-data-reader.sls
cf20c3912409ac9673de06999645498359296e29
[]
no_license
futsuki/ironscheme-port
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
4e7a81b0fbeac9a47440464988e53fb118286c54
refs/heads/master
2016-09-06T17:13:11.462593
2015-09-26T18:20:40
2015-09-26T18:20:40
42,757,369
0
0
null
null
null
null
UTF-8
Scheme
false
false
6,186
sls
db-data-reader.sls
(library (system data common db-data-reader) (export is? db-data-reader? get-values is-dbnull? read? get-chars get-data-type-name get-decimal get-guid get-boolean? get-data get-name get-schema-table get-int16 get-string get-bytes get-char get-double get-provider-specific-value get-enumerator get-int64 next-result? get-date-time get-ordinal get-value get-float get-byte get-provider-specific-values get-provider-specific-field-type get-field-type dispose get-int32 close depth field-count has-rows? is-closed? item item records-affected visible-field-count) (import (ironscheme-clr-port)) (define (is? a) (clr-is System.Data.Common.DbDataReader a)) (define (db-data-reader? a) (clr-is System.Data.Common.DbDataReader a)) (define-method-port get-values System.Data.Common.DbDataReader GetValues (System.Int32 System.Object[])) (define-method-port is-dbnull? System.Data.Common.DbDataReader IsDBNull (System.Boolean System.Int32)) (define-method-port read? System.Data.Common.DbDataReader Read (System.Boolean)) (define-method-port get-chars System.Data.Common.DbDataReader GetChars (System.Int64 System.Int32 System.Int64 System.Char[] System.Int32 System.Int32)) (define-method-port get-data-type-name System.Data.Common.DbDataReader GetDataTypeName (System.String System.Int32)) (define-method-port get-decimal System.Data.Common.DbDataReader GetDecimal (System.Decimal System.Int32)) (define-method-port get-guid System.Data.Common.DbDataReader GetGuid (System.Guid System.Int32)) (define-method-port get-boolean? System.Data.Common.DbDataReader GetBoolean (System.Boolean System.Int32)) (define-method-port get-data System.Data.Common.DbDataReader GetData (System.Data.Common.DbDataReader System.Int32)) (define-method-port get-name System.Data.Common.DbDataReader GetName (System.String System.Int32)) (define-method-port get-schema-table System.Data.Common.DbDataReader GetSchemaTable (System.Data.DataTable)) (define-method-port get-int16 System.Data.Common.DbDataReader GetInt16 (System.Int16 System.Int32)) (define-method-port get-string System.Data.Common.DbDataReader GetString (System.String System.Int32)) (define-method-port get-bytes System.Data.Common.DbDataReader GetBytes (System.Int64 System.Int32 System.Int64 System.Byte[] System.Int32 System.Int32)) (define-method-port get-char System.Data.Common.DbDataReader GetChar (System.Char System.Int32)) (define-method-port get-double System.Data.Common.DbDataReader GetDouble (System.Double System.Int32)) (define-method-port get-provider-specific-value System.Data.Common.DbDataReader GetProviderSpecificValue (System.Object System.Int32)) (define-method-port get-enumerator System.Data.Common.DbDataReader GetEnumerator (System.Collections.IEnumerator)) (define-method-port get-int64 System.Data.Common.DbDataReader GetInt64 (System.Int64 System.Int32)) (define-method-port next-result? System.Data.Common.DbDataReader NextResult (System.Boolean)) (define-method-port get-date-time System.Data.Common.DbDataReader GetDateTime (System.DateTime System.Int32)) (define-method-port get-ordinal System.Data.Common.DbDataReader GetOrdinal (System.Int32 System.String)) (define-method-port get-value System.Data.Common.DbDataReader GetValue (System.Object System.Int32)) (define-method-port get-float System.Data.Common.DbDataReader GetFloat (System.Single System.Int32)) (define-method-port get-byte System.Data.Common.DbDataReader GetByte (System.Byte System.Int32)) (define-method-port get-provider-specific-values System.Data.Common.DbDataReader GetProviderSpecificValues (System.Int32 System.Object[])) (define-method-port get-provider-specific-field-type System.Data.Common.DbDataReader GetProviderSpecificFieldType (System.Type System.Int32)) (define-method-port get-field-type System.Data.Common.DbDataReader GetFieldType (System.Type System.Int32)) (define-method-port dispose System.Data.Common.DbDataReader Dispose (System.Void)) (define-method-port get-int32 System.Data.Common.DbDataReader GetInt32 (System.Int32 System.Int32)) (define-method-port close System.Data.Common.DbDataReader Close (System.Void)) (define-field-port depth #f #f (property:) System.Data.Common.DbDataReader Depth System.Int32) (define-field-port field-count #f #f (property:) System.Data.Common.DbDataReader FieldCount System.Int32) (define-field-port has-rows? #f #f (property:) System.Data.Common.DbDataReader HasRows System.Boolean) (define-field-port is-closed? #f #f (property:) System.Data.Common.DbDataReader IsClosed System.Boolean) (define-field-port item #f #f (property:) System.Data.Common.DbDataReader Item System.Object) (define-field-port item #f #f (property:) System.Data.Common.DbDataReader Item System.Object) (define-field-port records-affected #f #f (property:) System.Data.Common.DbDataReader RecordsAffected System.Int32) (define-field-port visible-field-count #f #f (property:) System.Data.Common.DbDataReader VisibleFieldCount System.Int32))
false
2311bf9f48391c9fc0506433ff2ca782e6630157
4b480cab3426c89e3e49554d05d1b36aad8aeef4
/misc/facetdata_test.scm
090ac491627ef652e8e3d0d01890fc05dedc59a8
[]
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,096
scm
facetdata_test.scm
; data (define facetrst (list (list "main/-/sub1" 1) (list "main/-/sub1/-/ssub1" 1) (list "main/-/sub1/-/ssub2" 3) (list "main/-/sub2/-/ssub1" 2) (list "main/-/sub2/-/ssub2" 1) (list "main/-/sub2/-/ssub3" 1) (list "main/-/sub3" 2) (list "main/-/sub3/-/ssub1" 1) (list "main/-/unspecified" 10))) (define facetrst2 (list (list "main/-/sub1" 1) (list "main/-/sub1/-/ssub1" 1) (list "main/-/sub1/-/ssub2" 3) (list "main/-/sub2/-/ssub1" 2) (list "main/-/sub2/-/ssub2" 1) (list "main/-/sub2/-/ssub3" 1) (list "main/-/sub3" 2) (list "main/-/sub3/-/ssub1" 1) (list "main/-/unspecified" 10) (list "main/-/unspecified/-/unknown1" 10) (list "main/-/unspecified/-/unknown2" 10) (list "main/-/unspecified/-/unknown3" 10))) ; expected result (define expectedrst '("main" (("sub1" (("ssub1" () 1) ("ssub2" () 3)) 5) ("sub2" (("ssub1" () 2) ("ssub2" () 1) ("ssub3" () 1)) 4) ("sub3" (("ssub1" () 1)) 3) ("unspecified" () 10)) 22))
false
725987e24734bd52948533b1ce8875e91caeb12f
140a499a12332fa8b77fb738463ef58de56f6cb9
/worlds/core/verbcode/119/escape-html-4.scm
f0ee3107d0336cc0ebb019529dadfd1dec6ffdae
[ "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
163
scm
escape-html-4.scm
(let ((html (get args 0)) (escape-quotes (get args 1 0))) ;; TODO: implement quote escaping (gsub (gsub (gsub html "&" "&amp;") "<" "&lt;") ">" "&gt;"))
false
1ed7e9d9db38b736c60b54958faaf07e19fe617a
296dfef11631624a5b2f59601bc7656e499425a4
/snow/snow/random/test-chicken.scm
fefe743f941a2c8f19f2bce3143780146d9efb96
[]
no_license
sethalves/snow2-packages
f4dc7d746cbf06eb22c69c8521ec38791ae32235
4cc1a33d994bfeeb26c49f8a02c76bc99dc5dcda
refs/heads/master
2021-01-22T16:37:51.427423
2019-06-10T01:51:42
2019-06-10T01:51:42
17,272,935
1
1
null
null
null
null
UTF-8
Scheme
false
false
299
scm
test-chicken.scm
#! /bin/sh #| -*- scheme -*- exec csi -s $0 "$@" |# (use r7rs) (import-for-syntax r7rs) (include "snow/bytevector.sld") (include "snow/binio.sld") (include "snow/bignum.sld") (include "snow/random.sld") (include "snow/random/tests.sld") (import (snow random tests)) (display (run-tests)) (newline)
false
61c2b6ef172f6a3176cbf7f18804bfda10431a12
382770f6aec95f307497cc958d4a5f24439988e6
/projecteuler/073/073-imp2.scm
1f0f61a5c8195bc3891cd4819fa449313ff2d623
[ "Unlicense" ]
permissive
include-yy/awesome-scheme
602a16bed2a1c94acbd4ade90729aecb04a8b656
ebdf3786e54c5654166f841ba0248b3bc72a7c80
refs/heads/master
2023-07-12T19:04:48.879227
2021-08-24T04:31:46
2021-08-24T04:31:46
227,835,211
1
0
null
null
null
null
UTF-8
Scheme
false
false
948
scm
073-imp2.scm
(define countSB (lambda (limit leftN leftD rightN rightD) (let ([medN (+ leftN rightN)] [medD (+ leftD rightD)]) (if (> medD limit) 0 (let ([count 1]) (+ count (countSB limit leftN leftD medN medD) (countSB limit medN medD rightN rightD))))))) (countSB 10000 1 3 1 2) #| (time (countSB 10000 ...)) no collections 0.046875000s elapsed cpu time 0.056046120s elapsed real time 768 bytes allocated 5066251 |# (define limit 10000) (define stack (make-vector (/ limit 2) 0)) (let pro ([left 3] [right 2] [top 0] [count 0]) (let ([med (+ left right)]) (if (> med limit) (if (> top 0) (pro right (vector-ref stack (- top 1)) (- top 1) count) count) (begin (vector-set! stack top right) (pro left med (+ top 1) (+ count 1)))))) #| (time (let pro ...)) no collections 0.046875000s elapsed cpu time 0.051878736s elapsed real time 0 bytes allocated 5066251 |#
false
3287fb45221644015e7b36e1db3e2c2f87e14dbd
4b2aeafb5610b008009b9f4037d42c6e98f8ea73
/6.5/priority-queue.scm
e8402f23b77e102863f59d6c1e75c3282558436e
[]
no_license
mrinalabrol/clrs
cd461d1a04e6278291f6555273d709f48e48de9c
f85a8f0036f0946c9e64dde3259a19acc62b74a1
refs/heads/master
2021-01-17T23:47:45.261326
2010-09-29T00:43:32
2010-09-29T00:43:32
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,425
scm
priority-queue.scm
(define (heap-maximum heap) (heap-ref heap 0)) (define (heap-minimum heap) (heap-ref heap 0)) (define (heap-extract-max heap) (heap-extract heap heap-maximum max-heapify)) (define (heap-extract-min heap) (heap-extract heap heap-minimum min-heapify)) (define (heap-extract heap extremum heapify) (if (negative? (heap-size heap)) (error "Heap underflow -- HEAP-EXTRACT-MAX" (heap-size heap)) (let ((max (extremum heap)) (heap-size (- (heap-size heap) 1))) (heap-set! heap 0 (heap-ref heap heap-size)) (heap-drop-right! heap 1) (set-heap-size! heap heap-size) (heapify heap 0) max))) (define (heap-increase-key heap index key) (heap-crease-key heap index key <)) (define (heap-decrease-key heap index key) (heap-crease-key heap index key >)) (define (heap-crease-key heap index key comparator) (if (comparator key (heap-ref heap index)) (error "New key incomparate -- HEAP-CREASE-KEY" key) (begin (heap-set! heap index key) (let iter ((index index) (parent-index (parent index))) (if (not (and (positive? index) (< index (heap-size heap)) (< parent-index (heap-size heap)) (comparator (heap-ref heap parent-index) (heap-ref heap index)))) heap (begin (heap-swap! heap index parent-index) (iter parent-index (parent parent-index)))))))) (define (max-heap-insert heap key) (heap-insert heap key -inf.0 heap-increase-key)) (define (min-heap-insert heap key) (heap-insert heap key +inf.0 heap-decrease-key)) (define (heap-insert heap key infimum creasor) (let ((heap-size (+ (heap-size heap) 1))) (set-heap-size! heap heap-size) (if (heap-null? heap) (set-heap-data! heap (list infimum)) (heap-append! heap infimum)) (creasor heap (- heap-size 1) key) heap)) (define (max-heap-delete heap index) (heap-delete heap index max-heapify)) (define (min-heap-delete heap index) (heap-delete heap index min-heapify)) (define (heap-delete heap index heapify) (let ((heap-size (- (heap-size heap) 1))) (heap-set! heap index (heap-ref heap heap-size)) (heap-drop-right! heap 1) (set-heap-size! heap heap-size) (heapify heap index) heap)) (define (min-heap-merge . sorted-lists) (heap-merge sorted-lists min-heap-insert heapsort)) (define (max-heap-merge . sorted-lists) (heap-merge sorted-lists max-heap-insert heapsort-decreasing)) (define (heap-merge sorted-lists heap-insert heapsort) (let ((heap (make-heap '() 0))) (let iter ((sorted-lists sorted-lists)) (if (any null? sorted-lists) (heapsort (heap-data heap)) (let ((tuple (map car sorted-lists))) (for-each (cut heap-insert heap <>) tuple) (iter (map cdr sorted-lists))))))) (define (min-heap-merge-append . sorted-lists) (heap-merge-append sorted-lists min-heap-insert heapsort)) (define (max-heap-merge-append . sorted-lists) (heap-merge-append sorted-lists max-heap-insert heapsort-decreasing)) (define (heap-merge-append sorted-lists heap-insert heapsort) (let ((heap (make-heap '() 0))) (for-each (cut heap-insert heap <>) (apply append sorted-lists)) (heapsort (heap-data heap))))
false
25f696f5d7abb1ab13e737897d6632652208f645
86c001154e57121157873d0f1348c540ecea6675
/command/invoke.ss
fcbca70502562ea18d7410900cd08b203fd17444
[]
no_license
Memorytaco/melt-core
d9d3cd2d38cf4154bd9544a87a02ee0c3d6f765a
e6cf20ae881b33523f17959019d66499ae74c667
refs/heads/master
2020-04-30T02:00:16.058976
2019-04-18T13:24:50
2019-04-18T13:24:50
176,546,164
1
0
null
null
null
null
UTF-8
Scheme
false
false
1,548
ss
invoke.ss
(library (melt command invoke) (export invoke-cli) (import (scheme) (melt invoke) (melt lib console) (melt lib file) (melt command) (melt utils)) ;; display the build command usage (define (invoke-cli-help) (gemd:info (string-append (gem:text "[37;1m" "melt") (gem:text "[38;5;67m" " invoke") (gem:text "[38;5;253m" " <main-execute-file>\n") " If the" (gem:text "[38;5;253m" " <main-execute-file> ") "is not provided, use" (gem:text "[38;5;190m" " melt.scm ") "instead."))) (define (invoke-cli global-invocation) (create-command 'invoke "melt command to execute one list actions, mostly build the site." (lambda args (cond [(eq? 1 (length args)) (let ((main-ex-file (car args))) (if (file-exists? main-ex-file) (begin (load main-ex-file) (invoke global-invocation)) (begin (gemd:error "Coundn't find config file !!") (gemd:error (string-append "expect " (basename main-ex-file) " but the file doesn't exist!")))))] [else (gemd:warn "please give me the melt.scm!") (invoke-cli-help)])))) )
false
772047d44b39a69344ed46862cd0f21c17902984
03de0e9f261e97d98f70145045116d7d1a664345
/parscheme/lazy.scm
31c588a789c57b6aebe36bfe64ab5014bb770460
[ "LicenseRef-scancode-public-domain" ]
permissive
arcfide/riastradh
4929cf4428307b926e4c16e85bc39e5897c14447
9714b5c8b642f2d6fdd94d655ec5d92aa9b59750
refs/heads/master
2020-05-26T06:38:54.107723
2010-10-18T16:52:23
2010-10-18T16:52:23
3,235,881
2
1
null
null
null
null
UTF-8
Scheme
false
false
1,385
scm
lazy.scm
;;; -*- Mode: Scheme; scheme48-package: laziness -*- ;;;; Laziness Primitives ;;;; (Substitutes for R5RS's DELAY & FORCE) ;;; This code is written by Taylor R. Campbell and placed in the Public ;;; Domain. All warranties are disclaimed. (define (eager value) (make-promise #t value)) (define-syntax lazy (syntax-rules () ((LAZY expression) (MAKE-PROMISE #F (LAMBDA () expression))))) (define-syntax delay (syntax-rules () ((DELAY expression) (LAZY (EAGER expression))))) (define (force promise) (if (promise-forced? promise) (promise-value promise) (let ((promise* ((promise-thunk promise)))) (if (not (promise-forced? promise)) (clobber-promise! promise promise*)) (force promise)))) (define (clobber-promise! promise promise*) (let ((pair (promise-pair promise)) (pair* (promise-pair promise*))) (set-car! pair (car pair*)) (set-cdr! pair (cdr pair*)) (set-promise-pair! promise* pair))) (define-record-type <promise> (%make-promise pair) promise? (pair promise-pair set-promise-pair!)) (define (make-promise forced? value-then-thunk) (%make-promise (cons forced? value-then-thunk))) (define (promise-forced? promise) (car (promise-pair promise))) (define (promise-thunk promise) (cdr (promise-pair promise))) (define (promise-value promise) (cdr (promise-pair promise)))
true
7acc04401852f09f7d299990682337bb35f13807
c95b424d826780d088a1e797db26717c8b335669
/popupmenu.scm
7c8c8fa4894fded71a747ab7f54a1b1bacf587f7
[]
no_license
kdltr/ezd
c6bb38ef25c22030f09dc4be9bc2bdec2a575242
2e372a159903d674d29b5b3f32e560d35fcac397
refs/heads/master
2021-01-13T17:02:40.005029
2020-01-26T11:09:23
2020-01-26T11:11:28
76,651,078
7
1
null
null
null
null
UTF-8
Scheme
false
false
12,382
scm
popupmenu.scm
;;; ezd - easy drawing for X11 displays. ;;; ;;; The procedures in this module implement popup menus. ;* Copyright 1990-1993 Digital Equipment Corporation ;* All Rights Reserved ;* ;* Permission to use, copy, and modify this software and its documentation is ;* hereby granted only under the following terms and conditions. Both the ;* above copyright notice and this permission notice must appear in all copies ;* of the software, derivative works or modified versions, and any portions ;* thereof, and both notices must appear in supporting documentation. ;* ;* Users of this software agree to the terms and conditions set forth herein, ;* and hereby grant back to Digital a non-exclusive, unrestricted, royalty-free ;* right and license under any changes, enhancements or extensions made to the ;* core functions of the software, including but not limited to those affording ;* compatibility with other hardware or software environments, but excluding ;* applications which incorporate this software. Users further agree to use ;* their best efforts to return to Digital any such changes, enhancements or ;* extensions that they make and inform Digital of noteworthy uses of this ;* software. Correspondence should be provided to Digital at: ;* ;* Director of Licensing ;* Western Research Laboratory ;* Digital Equipment Corporation ;* 250 University Avenue ;* Palo Alto, California 94301 ;* ;* This software may be distributed (but not offered for sale or transferred ;* for compensation) to third parties, provided such third parties agree to ;* abide by the terms and conditions of this notice. ;* ;* THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL ;* WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF ;* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT ;* CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL ;* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR ;* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ;* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS ;* SOFTWARE. ;;; The procedure DEFINE-POPUP defines a procedure that implements a popup ;;; menu. The user supplies a procedure name, a list of menu entries and ;;; actions and optionally a font. Each menu entry/action is a list of either ;;; a string, a procedure, or an expression that evaluates to a string and an ;;; action procedure or expression to be evaluated. ;;; ;;; The menu is attached to some object by using a WHEN command to associate ;;; the evaluation of the popup procedure with a button press. When the button ;;; is pressed, the menu will come up under the button. When the button comes ;;; up, the action associated with the menu entry is executed. Moving the ;;; mouse outside the menu without releasing the button will cause the menu to ;;; disappear. ;;; ;;; The popup menu object has the following attributes. Address them in the ;;; drawing "popup-name", object POPUP. ;;; ;;; ENTRIES ;;; REPLACE-NAME ;;; REPLACE-ACTION ;;; FOREGROUND ;;; BACKGROUND ;;; FONT ;;; ;;; DELETE-OBJECT ;;; ATTRIBUTES (define (define-popup popup-name name-action-list colors font) (define foreground (if colors (car colors) 'black)) (define background (if colors (cadr colors) 'white)) (define window #f) (define visible #f) (define menu-x #f) (define menu-y #f) (define menu-width 0) (define menu-height 0) (define menu-length (length name-action-list)) (define popped-window #f) (define popped-drawing #f) (define popped-object #f) (define popped-object-x #f) (define popped-object-y #f) (define (any-button?) (or *mouse-button1* *mouse-button2* *mouse-button3* *mouse-button4* *mouse-button5*)) ;;; Compute the size of a menu entry text string. (define (compute-menu-width-and-height text) (let ((height-width (text->height-width (string-append " " text " ") font))) (set! menu-height (max menu-height (* 2 (car height-width)))) (set! menu-width (max menu-width (cadr height-width))))) ;;; Service procedure to make the window invisible. (define (make-invisible) (when visible (set! visible #f) (ezd `(delete-view ,popup-name ,popup-name)))) ;;; When the window is initially poped up, the following procedure is ;;; called to verify that the mouse is still in the window. (define (drop-when-not-there) (if (and visible (or (< *mouse-x* menu-x) (> *mouse-x* (+ menu-x menu-width)) (< *mouse-y* menu-y) (> *mouse-y* (* menu-length (+ menu-y menu-height))) (not (any-button?)))) (make-invisible))) ;;; When the button event occurs, the following procedure is called to ;;; display the popup menu in its own window. (define (popitup) (set! menu-x (max 0 (- *mouse-x* (quotient menu-width 2)))) (set! menu-y (max 0 (- *mouse-y* (quotient menu-height 2)))) (set! popped-window *user-event-window*) (set! popped-drawing *user-event-drawing*) (set! popped-object *user-event-object*) (set! popped-object-x *user-event-x*) (set! popped-object-y *user-event-y*) (if window (xmovewindow *dpy* (window-xwindow window) menu-x menu-y) (begin (ezd `(window ,popup-name ,menu-x ,menu-y ,menu-width ,(* menu-length menu-height))) (set! window (name->window popup-name)) (let-temporary ((x (make-xsetwindowattributes) free-xsetwindowattributes)) (set-xsetwindowattributes-save_under! x 1) (set-xsetwindowattributes-override_redirect! x 1) (xchangewindowattributes *dpy* (window-xwindow window) (bit-or CWSAVEUNDER CWOVERRIDEREDIRECT) x)))) (set! visible #t) (ezd `(overlay ,popup-name ,popup-name))) ;;; Procedures to draw a menu entry as either high or low lighted. (define (highlight object y text) (draw-text object y text background foreground #f)) (define (lowlight object y text) (draw-text object y text foreground background #f)) (define (draw-text object y text forecolor backcolor stipple) (ezd `(set-drawing ,popup-name) `(object ,object (fill-rectangle 0 ,y ,menu-width ,menu-height ,backcolor) (text 0 ,y ,menu-width ,menu-height center center ,(menu-text text) ,forecolor ,@(if stipple (list stipple) '()) ,@(if font (list font) '()))))) ;;; Compute the actual text string. (define (menu-text menu-name) (cond ((string? menu-name) menu-name) ((procedure? menu-name) (menu-name)) (else (eval menu-name)))) ;;; The following procedure "configures" the drawing representing the ;;; popup menu. It is called (define (configure-popup) (if window (ezd `(delete-window ,popup-name))) (set! window #f) (set! visible #f) (set! menu-width 0) (set! menu-height 0) (set! menu-length (length name-action-list)) ;;; 1. Compute size of the menu. (for-each (lambda (name-action) (compute-menu-width-and-height (menu-text (car name-action)))) name-action-list) ;;; 2. Draw the entries in the menu and arm their event handlers. (ezd '(save-drawing) `(set-drawing ,popup-name) '(object popup) `(when popup get-attributes ,get-attributes) `(when popup set-attributes ,set-attributes)) (let loop ((y 0) (args name-action-list)) (if (pair? args) (let* ((name-action (car args)) (object (string->symbol (format "~s-~s" popup-name y))) (text (car name-action)) (action (cadr name-action))) (define (enter-obj) (if (any-button?) (if action (highlight object y text)) (make-invisible))) (define (exit-obj) (if action (lowlight object y text)) (unless (and *mouse-window* (eq? (window-name *mouse-window*) popup-name) *mouse-object*) (make-invisible))) (define (execute-obj) (lowlight object y text) (make-invisible) (set! *user-event-type* 'popup) (set! *user-event-window* popped-window) (set! *user-event-drawing* popped-drawing) (set! *user-event-object* popped-object) (set! *user-event-x* popped-object-x) (set! *user-event-y* popped-object-y) (set! *user-event-misc* (list popup-name (menu-text text))) (ezd `(set-drawing *user-event-drawing*) '(draw-now)) (if (procedure? action) (action) (eval action))) (draw-text object y text foreground background (if action #f 's8)) (if action (ezd `(when ,object button1up ,execute-obj) `(when ,object button2up ,execute-obj) `(when ,object button3up ,execute-obj) `(when ,object button4up ,execute-obj) `(when ,object button5up ,execute-obj)) (ezd `(when ,object * #f))) (ezd `(when ,object enter ,enter-obj) `(when ,object exit ,exit-obj)) (loop (+ y menu-height) (cdr args))))) (ezd `(when * expose ,drop-when-not-there) '(restore-drawing))) ;;; Attributes are accessed via the following procedure. (define (get-attributes) (map (lambda (a) (case a ((entries) (flatten name-action-list)) ((foreground) foreground) ((background) background) ((font) font) ((attributes) '(entries replace-name replace-action foreground background font delete-object attributes)) (else (ezd-error 'check-button "Illegal attribute: ~s" a)))) *user-event-misc*)) ;;; List conversion functions ((a b) (c d)) <--> (a b c d) (define (flatten x) (if (pair? x) (cons* (caar x) (cadar x) (flatten (cdr x))) '())) (define (pair-up x) (if (pair? x) (cons (list (car x) (cadr x)) (pair-up (cddr x))) '())) ;;; Attribute argument parsers. (define (name-action-list? x) (or (null? x) (and (pair? x) (popup-entry-name? (car x)) (pair? (cdr x)) (popup-entry-action? (cadr x)) (name-action-list? (cddr x))))) (define (entry-index? x) (and (exact? x) (<= 0 x) (< x (length name-action-list)))) ;;; Attributes are changed via the following procedure. (define (set-attributes) (let ((delete #f)) (for-each (lambda (a) (cond ((and (pair? a) (eq? (car a) 'entries) (name-action-list? (cdr a))) (set! name-action-list (pair-up (cdr a)))) ((match? (replace-name entry-index? popup-entry-name?) a) (set-car! (list-ref name-action-list (cadr a)) (caddr a))) ((match? (replace-action entry-index? popup-entry-action?) a) (set-car! (cdr (list-ref name-action-list (cadr a))) (caddr a))) ((match? (foreground color?) a) (set! foreground (cadr a))) ((match? (background color?) a) (set! background (cadr a))) ((match? (font string?) a) (set! font (cadr a))) ((equal? '(delete-object) a) (set! delete #t)) (else (ezd-error 'slider "Illegal attribute: ~s" a)))) *user-event-misc*) (if delete (ezd `(delete-window ,popup-name) '(save-drawing) `(set-drawing ,popup-name) '(clear) '(restore-drawing)) (begin (if visible (make-invisible)) (configure-popup))))) ;;; Install POPITUP as the top-level value of the value of POPUP-NAME. (configure-popup) ;; TODO less ugly hack (block-set! popup-name 0 popitup)) ;;; Booleans for command and attribute parsing. (define (popup-entry-name? x) (or (string? x) (procedure? x) (pair? x))) (define (popup-entry-action? x) (or (pair? x) (procedure? x) (eq? x #f))) (define-ezd-command `(define-popup ,symbol? (repeat ,popup-entry-name? ,popup-entry-action?) (optional ,color? ,color?) (optional ,string?)) "(define-popup popup-name item-action-list [foreground background] [\"font\"])" define-popup)
false
ae6526e1ee3e5c9fcd35ee4de766731213732ea0
dd4cc30a2e4368c0d350ced7218295819e102fba
/vendored_parsers/vendor/highlights/c-sharp.scm
d63ae12ada786bc2471ba0416b9564ed59b3eb00
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "Apache-2.0" ]
permissive
Wilfred/difftastic
49c87b4feea6ef1b5ab97abdfa823aff6aa7f354
a4ee2cf99e760562c3ffbd016a996ff50ef99442
refs/heads/master
2023-08-28T17:28:55.097192
2023-08-27T04:41:41
2023-08-27T04:41:41
162,276,894
14,748
287
MIT
2023-08-26T15:44:44
2018-12-18T11:19:45
Rust
UTF-8
Scheme
false
false
45
scm
c-sharp.scm
../tree-sitter-c-sharp/queries/highlights.scm
false
3c6be23146533ee5706e4394f5db682e418c52f2
cc6a300f6d5414a5e7173968c7a6be1f8a8425dc
/speme/scmTree.scm
641e9f7d339e59602c53c292463c66e12e70ba21
[ "Artistic-2.0" ]
permissive
hdijkema/speme
2b4058164c8d59df721a7f54fa4f6c805e7e5621
e5d72c54d07af81e98f0f5e059f7180e36ff4f4a
refs/heads/master
2020-05-17T21:41:34.617879
2013-07-24T08:04:51
2013-07-24T08:04:51
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,219
scm
scmTree.scm
(package scmTree 0.1 (tree-new tree-put tree-get tree-remove tree-exists? tree-traverse) (define (tree-new less eq) (list 'tree less eq 'nil)) ; value left right ;;;;;;;;; put (define (tree-put tree val) (begin (set-car! (cdddr tree) (i-tree-put (cadr tree) (caddr tree) val (cadddr tree))) tree)) (define (i-tree-put less eq val node) (if (list? node) ;(begin ;(println "i-tree-put: " node (eq val (car node)) (less val (car node))) (if (equal? (car node) 'nil) (list val (cadr node) (caddr node)) (if (less val (car node)) (list (car node) (i-tree-put less eq val (cadr node)) (caddr node)) (if (eq val (car node)) (list val (cadr node) (caddr node)) (list (car node) (cadr node) (i-tree-put less eq val (caddr node)))))) ;) (list val 'nil 'nil))) ;;;;;;;;;; get (define (tree-get tree key) (i-tree-get (cadr tree) (caddr tree) key (cadddr tree))) (define (i-tree-get less eq key node) (if (list? node) (if (equal? (car node) 'nil) 'nil (if (less key (car node)) (i-tree-get less eq key (cadr node)) (if (eq key (car node)) (car node) (i-tree-get less eq key (caddr node))))) 'nil)) ;;;;;;;;; exists (define (tree-exists? tree key) (i-tree-exists (cadr tree) (caddr tree) key (cadddr tree))) (define (i-tree-exists less eq key node) (if (list? node) (if (equal? (car node) 'nil) #f (if (less key (car node)) (i-tree-exists less eq key (cadr node)) (if (eq key (car node)) #t (i-tree-exists less eq key (caddr node))))) #f)) ;;;;;;;;; remove (define (tree-remove tree key) (begin (set-car! (cdddr tree) (i-tree-remove (cadr tree) (caddr tree) key (cadddr tree))) tree)) (define (i-tree-remove less eq key node) (if (list? node) (if (equal? (car node) 'nil) node (if (less key (car node)) (list (car node) (i-tree-remove less eq key (cadr node)) (caddr node)) (if (eq key (car node)) (let ((left (cadr node)) (right (caddr node))) (if (equal? left 'nil) (if (equal? right 'nil) 'nil right) (if (equal? right 'nil) left (list (car left) (cadr left) (i-tree-put-part less (caddr left) right))))) (list (car node) (cadr node) (i-tree-remove less eq key (caddr node)))))) node)) (define (i-tree-put-part less node part) (if (list? node) (if (equal? (car node) 'nil) part (if (less (car part) (car node)) (list (car node) (i-tree-put-part less (cadr node) part) (caddr node)) (list (car node) (cadr node) (i-tree-put-part less (caddr node) part)))) part)) ;;;;;;;;;; traverse (define (tree-traverse tree f) (i-tree-traverse (cadddr tree) f)) (define (i-tree-traverse node f) (if (list? node) (begin (i-tree-traverse (cadr node) f) (f (car node)) (i-tree-traverse (caddr node) f)) 'nil)) )
false
880ecd52e7c731bf0898ef0171dd1df581a10c92
648776d3a0d9a8ca036acaf6f2f7a60dcdb45877
/queries/pony/indents.scm
c9b3e7a252b3918c11d327144e94eb013162ec06
[ "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
897
scm
indents.scm
[ (use_statement) (actor_definition) (class_definition) (primitive_definition) (interface_definition) (trait_definition) (struct_definition) (constructor) (method) (behavior) (parameters) (if_block) (then_block) (elseif_block) (else_block) (iftype_statement) (elseiftype_block) (do_block) (match_statement) (parenthesized_expression) (tuple_expression) (array_literal) (object_literal) ] @indent.begin (try_statement (block) @indent.begin) (repeat_statement (block) @indent.begin) (recover_statement (block) @indent.begin) (return_statement (block) @indent.begin) (continue_statement (block) @indent.begin) (break_statement (block) @indent.begin) [ "}" "]" ")" ] @indent.end [ "{" "}" ] @indent.branch [ "[" "]" ] @indent.branch [ "(" ")" ] @indent.branch [ (ERROR) (string) (line_comment) (block_comment) ] @indent.auto
false
b9b96dfda8489db36a3843adaf455212c24a9c32
37245ece3c767e9434a93a01c2137106e2d58b2a
/tests/srfi-46-tests.sch
10c4edb407aa9ccdda756de34536f653c64095df
[ "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
1,736
sch
srfi-46-tests.sch
;; 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) (srfi 64)) (test-begin "SRFI 46") (test-group "Examples" (test-equal '((1) 2 (3) (4)) (let-syntax ((f (syntax-rules () ((f ?e) (let-syntax ((g (syntax-rules ::: () ((g (??x ?e) (??y :::)) '((??x) ?e (??y) :::))))) (g (1 2) (3 4))))))) (f :::))) (test-equal '(1 (2 3 4) 5) (let-syntax ((foo (syntax-rules () ((foo ?x ?y ... ?z) (list ?x (list ?y ...) ?z))))) (foo 1 2 3 4 5)))) (test-end)
false
0bab9b561b8bc6d1df33da880f6ddb76ce22129c
74d2f4ec77852839450ab8563971a5e0f615c019
/chapter_02/exercise_2_35.scm
134c60662f5c30241303817b3c62571e26509d0b
[]
no_license
wangoasis/sicp
b56960a0c3202ce987f176507b1043ed632ed6b3
07eaf8d46f7b8eae5a46d338a4608d8e993d4568
refs/heads/master
2021-01-21T13:03:11.520829
2016-04-22T13:52:15
2016-04-22T13:52:15
53,835,426
0
0
null
null
null
null
UTF-8
Scheme
false
false
394
scm
exercise_2_35.scm
( define ( accumulate op initial sequence ) ( if ( null? sequence ) initial ( op ( car sequence ) ( accumulate op initial ( cdr sequence ) ) ) ) ) ( define ( count-leaves tree ) ( accumulate + 0 ( map ( lambda ( x ) ( if ( pair? x ) ( count-leaves x ) 1 ) ) tree ) ) ) ( define x ( list ( list 1 2 ) ( list ( list 2 3 ) ( list 6 7 ) ) ) )
false
77101dcde80cf9d598757a8e7cf9343f32bbecbd
defeada37d39bca09ef76f66f38683754c0a6aa0
/UnityEngine/unity-engine/context-menu-item-attribute.sls
230b3ec387423d926b39a7714c35813b38a6ff9f
[]
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
707
sls
context-menu-item-attribute.sls
(library (unity-engine context-menu-item-attribute) (export new is? context-menu-item-attribute? name function) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new UnityEngine.ContextMenuItemAttribute a ...))))) (define (is? a) (clr-is UnityEngine.ContextMenuItemAttribute a)) (define (context-menu-item-attribute? a) (clr-is UnityEngine.ContextMenuItemAttribute a)) (define-field-port name #f #f () UnityEngine.ContextMenuItemAttribute name System.String) (define-field-port function #f #f () UnityEngine.ContextMenuItemAttribute function System.String))
true
0ffa9cf6aa7e6d1a55755cd9108a3caa564ecbc3
5927f3720f733d01d4b339b17945485bd3b08910
/tests/roots/02-filter/init-home/leo/.hato/filter
c109f964bc00d87370376763fd834fd0a3809c3c
[]
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
100
filter
; -*- scheme -*- (cond ((To? "[email protected]") "work-list/.")) ;; (cond ;; ((auto-list)))
false
9fb8910060bda45f6330f745a3a5754ce2cd1db9
d6121a780f97ae1f3afb265812e9296d23574f78
/primenocturne/scheme/D-14.scm
6fcc6bd1723c5d72f343b2533618058eafcc6ba7
[]
no_license
phasetr/mathcodes
6ac2efd6bffe719c1edf5eabc4b14487f3ad600a
e97261641d203ff3cca54742fd4a77390940eddb
refs/heads/master
2022-10-19T13:24:26.473230
2022-10-05T12:05:26
2022-10-05T12:05:26
65,594,078
13
0
null
2021-06-02T12:01:59
2016-08-13T02:00:46
Jupyter Notebook
UTF-8
Scheme
false
false
5,440
scm
D-14.scm
(load "./lib") "P.748" "D.14 モンテカルロ法" "D.14.1 面積を求める" (define (mc-method pred k) (let loop ((i 0) (hits 0)) (if (= i k) hits (loop (++ i) (+ hits (if (pred (random-real) (random-real)) 1 0)))))) "P.749" (define (eq-pi x y) (<= (+ (** x 2) (** y 2)) 1)) (output (map (lambda (x) (let* ((hitnum (mc-method eq-pi x)) (app-pi (/ (* 4 hitnum) x))) (list hitnum app-pi))) '(10 100 1000 10000 100000 1000000))) (save->data 'P750-random-2d.dat (rand2d 4000)) "P.750" "アステロイドの面積を求める" "P.751" (define (eq-ast x y) ;;; 0^{2/3} がエラーになるのでそれを除外 (let ((x0 (if (< x m-eps) m-eps x)) (y0 (if (< y m-eps) m-eps y))) (<= (+ (** x0 (/ 2 3)) (** y0 (/ 2 3))) 1))) (output (map (lambda (x) (let* ((hitnum (mc-method eq-ast x)) (app-ast (* 1.0 (/ hitnum x)))) (list hitnum app-ast))) '(10 100 1000 10000))) (/ (* 3 (* 4 (atan 1))) 32) (save->data 'P751-random-2d.dat (mc-method eq-ast 1000)) "P.753" (define (eq-lem x y) (<= (- (** (+ (** x 2) (** y 2)) 2) (- (** x 2) (** y 2))) 0)) (output (map (lambda (x) (let* ((hitnum (mc-method eq-lem x)) (app-lem (* 1.0 (/ hitnum x)))) (list hitnum app-lem))) '(10 100 1000 10000 100000))) "D.14.2 三次元への拡張" "P.754" (define (rand3d k) (map (lambda (x) (list (random-real) (random-real) (random-real))) (iota k))) (save->data 'P754-random-3d.dat (rand3d 4000)) (define (mc-method3 pred k) (let loop ((i 0) (hits 0)) (if (= i k) hits (loop (++ i) (+ hits (if (pred (random-real) (random-real) (random-real)) 1 0)))))) (define (eq-pi3 x y z) (<= (+ (** x 2) (** y 2) (** z 2)) 1)) "P.755" (output (map (lambda (x) (let* ((hitnum (mc-method3 eq-pi3 x)) (apprx (* 1.0 (/ hitnum x)))) (list hitnum apprx))) '(10 100 1000 10000 100000 1000000))) "P.756" "D.14.3 ピタゴラス数を求める" "述語を定める" "P.757" (define (Pythagorean? x y z) "全体が定数倍になっている自明な組は除くようにしてある: gcd=1? の部分" (and (< x y) (gcd=1? x y z) (= (+ (** x 2) (** y 2)) (** z 2)))) (Pythagorean? 3 4 5) (Pythagorean? 6 8 10) (define (gcd=1? x y z) (if (= (gcd x y z) 1) #t #f)) (gcd=1? 6 8 10) (gcd=1? 3 4 5) (define (diff? x lst) (not (member x lst))) "境界上の疑似乱数" (define (mc-xyz pred z) (let loop ((i 0) (tmp '())) (let ((x (random+ z)) (y (random+ z))) (cond ((< (* z z) i) tmp) ((and (pred x y z) (diff? (list x y z) tmp)) (loop (++ i) (cons (list x y z) tmp))) (else (loop (++ i) tmp)))))) "P.758" (define (mc-all pred max) (let loop ((i max) (tmp '())) (cond ((= 3 i) tmp) ((null? (mc-xyz pred i)) (loop (-- i) tmp)) (else (loop (-- i) (append (mc-xyz pred i) tmp)))))) (mc-all Pythagorean? 100) "実験結果" "P.759" "リストによる方法" (define (sqn-car? lst) (sqn? (car lst))) (filter sqn-car? (triple 15)) (define (sqrt-car lst) (cons (inexact->exact (sqrt (car lst))) (cdr lst))) (map sqrt-car (filter sqn-car? (triple 15))) (define (gcd-xyz? lst) (if (= (gcd (car lst) (cadr lst) (cadr lst)) 1) #t #f)) (filter gcd-xyz? (map sqrt-car (filter sqn-car? (triple 15)))) "P.760" (define (triple-xyz n) (reverse (reverse-all (filter gcd-xyz? (map sqrt-car (filter sqn-car? (triple n))))))) (triple-xyz 15) "D.14.4 ガウス素数の抽出" (define (prime-car? n) (prime? (car n))) (filter prime-car? (triple 5)) (define (p4n1? n) (if (and (prime? n) (= (/@ n 4) 1)) #t #f)) (define (p4n3? n) (if (and (prime? n) (= (/@ n 4) 3)) #t #f)) (filter p4n1? (iota 99)) (filter p4n3? (iota 99)) "P.761" (define (sqsum-p lst) (remove null? (map (lambda (x) (if (prime-car? x) (cdr x) '())) lst))) (sqsum-p (triple 5)) (define (quad1 lst) "quadruple" (let ((ones '((1 1) (1 -1) (-1 1) (-1 -1)))) (map (lambda (x) (map * lst x)) ones))) (define (quad2 lst) "quadruple" (let ((ones '((1 0) (-1 0) (0 1) (0 -1)))) (map (lambda (x) (map * lst x)) ones))) (quad1 '(2 3)) (quad2 '(2 3)) (define (gauss-p1 lst) (let* ((ex (lambda (l) (list (cadr l) (car l))))) (append (quad1 lst) (quad1 (ex lst))))) (flat-in (map gauss-p1 (sqsum-p (triple 5)))) "P.762" (define (gauss-p2 n) (let ((lst (list n n))) (quad2 lst))) (flat-in (map gauss-p2 (filter p4n3? (iota 25)))) (define gauss-p3 (quad1 '(1 1))) ;;;(define gauss-p0 (gauss-p2-test 1)) (define gauss-p0 (gauss-p2 1)) (define (gauss-p n) (flat-in (append (list gauss-p0 '(()) gauss-p3) (map gauss-p1 (sqsum-p (triple n))) (map gauss-p2 (filter p4n3? (iota n)))))) (define (diskcut k) (filter list? (map (lambda (x) (cond ((equal? x '()) '()) ((<= (sq+ (car x) (cadr x)) (** k 2)) x) (else 'del-term))) (gauss-p k)))) "P.763" (save->data 'P763-gauss50.dat (diskcut 50))
false
e8e01be762548849d3021c4f7cb34ea4ea65a76e
a416300cfff2efcf5749349330566b7db70cf4a6
/positive-tests/testLowerInt.scm
8a34dbe518b0211fe8636f44b34e710ca57b68f3
[]
no_license
lukaspj/LaBSec-Project
c4e24ba395a990c8facd24d8a4cb5780bfa69e20
47f37726f7531080b14f4039276968e942b34c02
refs/heads/master
2020-04-02T03:07:49.662099
2016-06-13T10:04:41
2016-06-13T10:04:41
58,653,567
0
0
null
2016-06-12T11:54:08
2016-05-12T15:26:05
Scheme
UTF-8
Scheme
false
false
180
scm
testLowerInt.scm
(load "framework.scm") (define lowintconf (label-expression '(label () ()) 10)) (define lowinthighconf (label-expression '(label (integrity . 0) ()) lowintconf))
false
38b86325813ac1890bcb4c1b336ba244dd9ce120
f4f3fa828c89a435dfde7f814964e79926850e23
/immutable/deque-impl.scm
67a76f6b7940f03ad84aebb5543f3fa636e831a8
[ "BSD-2-Clause" ]
permissive
kevinwortman/Scheme-immutable-data-structures
36ab692912bed18616b132420fa49e1503d85e8f
861327ef70638508a9f2024949e7ef2dba9c081e
refs/heads/master
2021-01-23T21:42:43.876475
2020-09-14T17:12:53
2020-09-14T17:12:53
11,671,684
12
2
BSD-2-Clause
2020-09-14T17:12:54
2013-07-25T21:39:26
Scheme
UTF-8
Scheme
false
false
6,687
scm
deque-impl.scm
;;;; missing from the SRFI 121 reference implementation #| (define (list->generator list) (let ((list list)) (lambda () (if (null? list) (eof-object) (let ((obj (car list))) (set! list (cdr list)) obj))))) |# ;;;; (define *deque-measure* (make-measure (lambda (elt) 1) +)) (define *mzero* 0) (define-record-type <ideque> (make-ideque length tree) ideque? (length ideque-length) (tree ideque-tree)) (define (length+tree deque) (values (ideque-length deque) (ideque-tree deque))) (define underflow-error (cute error "ideque underflow")) (define (check-length deque n) (when (> n (ideque-length deque)) (underflow-error))) (define check-nonempty (cute check-length <> 1)) (define (length+generator->ideque length gen) (make-ideque length (generator->finger-tree madd mget gen))) (define (ideque . elements) (list->ideque elements)) (define (ideque-tabulate n proc) (length+generator->ideque n (make-tabulation-generator n proc))) (define (ideque-unfold stop? mapper successor seed) (generator->ideque (make-unfold-generator stop? mapper successor seed))) (define (ideque-unfold-right stop? mapper successor seed) (ideque-reverse (ideque-unfold stop? mapper successor seed))) (define (ideque-empty? deque) (finger-tree-empty? (ideque-tree deque))) (define (ideque-front deque) (finger-tree-front (ideque-tree deque))) (define (ideque-back deque) (finger-tree-back (ideque-tree deque))) (define (ideque-remove-front deque) (check-nonempty deque) (receive (l t) (length+tree deque) (make-ideque (- l 1) (finger-tree-remove-front t)))) (define (ideque-remove-back deque) (check-nonempty deque) (receive (l t) (length+tree deque) (make-ideque (- l 1) (finger-tree-remove-back t)))) (define (ideque-add-front deque obj) (receive (l t) (length+tree deque) (make-ideque (+ 1 l) (finger-tree-add-front madd mget t obj)))) (define (ideque-add-back deque obj) (receive (l t) (length+tree deque) (make-ideque (+ 1 l) (finger-tree-add-back madd mget t obj)))) (define (ideque-take deque n) (receive (pre suf) (ideque-split-at deque n) pre)) (define (ideque-drop deque n) (receive (pre suf) (ideque-split-at deque n) suf)) (define (split-right deque n) (if (zero? n) (values deque (ideque)) (ideque-split-at deque (- (ideque-length deque) n)))) (define (ideque-take-right deque n) (receive (pre suf) (split-right deque n) suf)) (define (ideque-drop-right deque n) (receive (pre suf) (split-right deque n) pre)) (define (ideque-split-at deque n) (check-length deque n) (finger-tree-scan/context madd mget (cute > <> n) mseed (ideque-tree deque) (lambda (pre e suf) (values (make-ideque n pre) (make-ideque (- (ideque-length deque) n) (finger-tree-add-front madd mget suf e)))) underflow-error)) (define (ideque-append first . rest) (let ((deques (cons first rest))) (make-ideque (apply + (map ideque-length deques)) (apply finger-tree-append madd mget (map ideque-tree deques))))) (define (ideque-concatenate list-of-deques) (fold (lambda (right left) (ideque-append left right)) (ideque) list-of-deques)) (define (ideque-reverse deque) (receive (l t) (length+tree deque) (length+generator->ideque l (reverse-finger-tree->generator t)))) (define (ideque-count pred deque) (generator-count pred (ideque->generator deque))) ;; TODO ideque-zip ;; TODO: for some reason gmap is not visible here... (define (gmap proc generator) (lambda () (let ((value (generator))) (if (eof-object? value) value (proc value))))) (define (ideque-map proc first . rest) (generator->ideque (apply gmap proc (map! ideque->generator (cons first rest))))) (define (ideque-for-each proc first . rest) (apply generator-for-each proc (map! ideque->generator (cons first rest)))) (define (ideque-fold proc nil first . rest) (apply generator-fold proc nil (map! ideque->generator (cons first rest)))) (define (ideque-fold-right proc nil first . rest) (apply generator-fold proc nil (map! reverse-ideque->generator (cons first rest)))) ;; TODO ideque-append-map (define (ideque-filter pred deque) (generator->ideque (gfilter pred (ideque->generator deque)))) (define (ideque-remove pred deque) (ideque-filter (lambda (obj) (not (pred obj))) deque)) (define (ideque-partition pred deque) (values (ideque-filter pred deque) (ideque-remove pred deque))) (define (generator-find/failure pred gen failure) (call/cc (lambda (return) (generator-for-each (lambda (obj) (when (pred obj) (return obj))) gen) (failure)))) (define (ideque-find pred deque failure) (generator-find/failure pred (ideque->generator deque) failure)) (define (ideque-find-right pred deque failure) (generator-find/failure pred (reverse-ideque->generator deque) failure)) (define (ideque-take-while pred deque) (generator->ideque (gtake-while pred (ideque->generator deque)))) (define (ideque-take-while-right pred deque) (ideque-reverse (generator->ideque (gtake-while pred (reverse-ideque->generator deque))))) (define (drop-while get drop pred deque) (do ((deque deque (drop deque))) ((or (ideque-empty? deque) (not (pred (get deque)))) deque))) (define ideque-drop-while (cute drop-while ideque-front ideque-remove-front <> <>)) (define ideque-drop-while-right (cute drop-while ideque-back ideque-remove-back <> <>)) (define (ideque-span pred deque) (values (ideque-take-while pred deque) (ideque-drop-while pred deque))) (define (ideque-break pred deque) (receive (which-do which-dont) (ideque-span deque) (values which-dont which-do))) (define (ideque-any pred deque) (generator-any pred (ideque->generator deque))) (define (ideque-every pred deque) (generator-every pred (ideque->generator deque))) (define (list->ideque list) (generator->ideque (list->generator list))) (define (ideque->list deque) (generator->list (ideque->generator deque))) (define (generator->ideque gen) (let ((tree (generator->finger-tree madd mget gen))) (make-ideque (finger-tree-length tree) tree))) (define (ideque->generator deque) (finger-tree->generator (ideque-tree deque))) (define (reverse-ideque->generator deque) (reverse-finger-tree->generator (ideque-tree deque))) (define (make-ideque-comparator comparator) (make-list-comparator ideque? comparator ideque-empty? ideque-front ideque-remove-front)) (define ideque-comparator (make-ideque-comparator default-comparator))
false
22c7c4a28421fe279bbb623fc55185c1f2b09e42
b60cb8e39ec090137bef8c31ec9958a8b1c3e8a6
/test/R5RS/scp1/parking-counter.scm
dd85bbfa50ef47b2bfd9d835486189b7426dbf5e
[]
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
3,393
scm
parking-counter.scm
(define (create-counter initial) (define (increase) (set! initial (+ initial 1))) (define (decrease) (set! initial (- initial 1))) (define (read) initial) (define (dispatch m) (cond ((eq? m 'increase) (increase)) ((eq? m 'decrease) (decrease)) ((eq? m 'read) (read)) (else (display "wrong message")))) dispatch) (define (create-parking . capaciteiten) (let ((verdieping-ctrs (map create-counter capaciteiten)) (nr-verdiepingen (length capaciteiten)) (nbr-cars 0)) (define (total-capacity) (apply + capaciteiten)) (define (full?) (= nbr-cars (total-capacity))) (define (empty?) (= nbr-cars 0)) (define (max-reached-level level idx) (>= (level 'read) (list-ref capaciteiten (- idx 1)))) (define (level-current) (define (loop lst index) (cond ((null? lst) #f) (else (let* ((level (car lst)) (capacity (level 'read))) (if (> capacity 0) index (loop (cdr lst) (+ index 1))))))) (loop verdieping-ctrs 1)) (define (level-to-leave) (define (loop lst index) (cond ((null? lst) #f) (else (let* ((level (car lst)) (capacity (level 'read))) (if (and (not (max-reached-level level index)) (>= capacity 0)) index (loop (cdr lst) (- index 1))))))) (loop (reverse verdieping-ctrs) nr-verdiepingen)) (define (car-enters) (let ((level (level-current))) (if level (let ((verdieping-ctr (list-ref verdieping-ctrs (- level 1)))) (set! nbr-cars (+ nbr-cars 1)) (verdieping-ctr 'decrease)) #f))) (define (car-leaves) (let ((level (level-to-leave))) (if level (let ((verdieping-ctr (list-ref verdieping-ctrs (- level 1)))) (set! nbr-cars (- nbr-cars 1)) (verdieping-ctr 'increase)) (let ((verdieping-ctr (list-ref verdieping-ctrs(- nr-verdiepingen 1)))) (set! nbr-cars (- nbr-cars 1)) (verdieping-ctr 'increase))))) (define (dispatch msg) (cond ((eq? msg 'full?) (full?)) ((eq? msg 'empty?) (empty?)) ((eq? msg 'level) (level-current)) ((eq? msg 'car-enters) (car-enters)) ((eq? msg 'lst) verdieping-ctrs) ((eq? msg 'car-leaves) (car-leaves)) (else (error "wrong message")))) dispatch)) (define parking (create-parking 3 5 2)) (and (= (parking 'level) 1) (not (parking 'full?)) (= (begin (parking 'car-enters) (parking 'car-enters) (parking 'car-enters) (parking 'car-enters) (parking 'level)) 2) (not (parking 'empty?)) (begin (parking 'car-enters) (parking 'car-enters) (parking 'car-enters) (parking 'car-enters) (parking 'car-enters) (parking 'car-enters) (parking 'full?)) (not (parking 'car-enters)) (= (begin (parking 'car-leaves) (parking 'car-leaves) (parking 'car-leaves) (parking 'level)) 2))
false
3ce10e754bc6a0b502318af998d22e4b97039694
d6121a780f97ae1f3afb265812e9296d23574f78
/primenocturne/scheme/C-01.scm
db0c8ae6d57faf81d41d75734e3250b620013da0
[]
no_license
phasetr/mathcodes
6ac2efd6bffe719c1edf5eabc4b14487f3ad600a
e97261641d203ff3cca54742fd4a77390940eddb
refs/heads/master
2022-10-19T13:24:26.473230
2022-10-05T12:05:26
2022-10-05T12:05:26
65,594,078
13
0
null
2021-06-02T12:01:59
2016-08-13T02:00:46
Jupyter Notebook
UTF-8
Scheme
false
false
5,326
scm
C-01.scm
"P.469" "付録 C プログラミング言語の拡張" (define non (lambda (x) 'non)) (map (compose print non) '(1 2 3)) (define id (lambda (x) x)) (map (compose print id) '(1 2 3)) (define add1 (lambda (n) (+ n 1))) (map (compose print add1) '(1 2 3)) (define sub1 (lambda (n) (- n 1))) (map (compose print sub1) '(1 2 3)) "P.470" "C.1 関数を作る" (define ++ (lambda (i) (+ i 1))) (map (compose print ++) '(1 2 3)) (define -- (lambda (i) (- i 1))) (map (compose print --) '(1 2 3)) "組み込み関数の再定義" (define ** (lambda (a b) (expt a b))) (define ^ (lambda (a b) (expt a b))) (** 2 3) (^ 2 3) (define // (lambda (a b) (quotient a b))) (// 9 3) (// 8 2) (define /@ (lambda (a b) (remainder a b))) (/@ 9 4) (define /: (lambda (a b) (modulo a b))) (/: 9 3) (/: 9 5) "P.471" "偶奇性" (define make-even (lambda (n) (* 2 n))) (define make-odd (lambda (n) (+ (* 2 n) 1))) (map (compose print make-even) '(0 1 2 3)) (map (compose print make-odd) '(0 1 2 3)) (define parity-of (lambda (p) (if (odd? p) -1 1))) (map (compose print parity-of) '(0 1 2 3 4 5)) "swap" (define swap-test (lambda (a b) (** a b))) "P.472" (swap-test 2 3) (define swap-test (lambda (a b) (let* ((dummy a) (a b) (b dummy)) (** a b)))) (swap-test 2 3) "誤差の修正" "rpund: 偶数丸め・偶捨奇入" (round 1.5) (round 3/2) (round 2.5) (round 5/2) "P.473" (define adjust-of (lambda (x) (let ((digit 1000) (slide (if (positive? x) 1/2 -1/2))) (/ (truncate (+ slide (* digit x))) digit)))) (map (compose print adjust-of) '(0.2994 -0.2994)) (define adjust-of2 (lambda (x digit) (let ((slide (if (positive? x) 1/2 -1/2))) (/ (truncate (+ slide (* digit x))) digit)))) (adjust-of2 0.2994 100) (adjust-of2 0.2994 1000) (adjust-of2 -0.2994 100) (adjust-of2 -0.2994 1000) "C.1.1 数のリスト" "P.474" (define iota (lambda (min max) (if (> min max) '() (cons min (iota (+ min 1) max))))) (equal? (iota 0 3) '(0 1 2 3)) (equal? (iota 1 4) '(1 2 3 4)) "P.475" (iota 1 9) (iota -5 5) (define iota-reverse (lambda (min max) (if (> min max) '() (cons max (iota-reverse min (- max 1)))))) (iota-reverse -5 5) "named let" (define iota (lambda (min max) (let iota-loop ((i max) (tmp '())) (if (< i min) tmp (iota-loop (- i 1) (cons i tmp)))))) (iota 2 9) (define iota-reverse (lambda (min max) (let iota-loop ((i min) (tmp '())) (if (> i max) tmp (iota-loop (+ i 1) (cons i tmp)))))) (iota-reverse 0 3) (iota-reverse -5 5) "P.477" "生成されたリストによる判断" (equal? (and #t #t) #t) (equal? (and #t #f) #f) (equal? (and #f #t) #f) (equal? (and #f #f) #f) (define iota-reverse (lambda (min max) (let iota-loop ((i min) (tmp '())) (if (and (not (null? tmp)) (= (car tmp) max)) tmp (iota-loop (+ i 1) (cons i tmp)))))) (iota-reverse 0 3) (iota-reverse -5 5) "P.478" "C.1.2 選択肢のあるiota" (define iota (lambda (max . opt) (let* ((min (if (null? opt) 1 (car opt))) (step (if (or (null? opt) (null? (cdr opt))) 1 (cadr opt))) (dummy max) (max (if (null? opt) max min)) (min (if (null? opt) min dummy))) (let loop ((i (- min step)) (tmp '())) (if (< (- max step) i) (reverse tmp) (loop (+ i step) (cons (adjust-of (+ i step)) tmp))))))) "P.480" (equal? (iota 9) '(1 2 3 4 5 6 7 8 9)) (equal? (iota 4 9) '(4 5 6 7 8 9)) (equal? (iota 2 9 3) '(2 5 8)) (define iota (lambda lst (let* ((x (length lst)) (max (if (= 1 x) (car lst) (cadr lst))) (min (if (< 1 x) (car lst) 1)) (step (if (= 3 x) (caddr lst) 1))) (let loop ((i (- min step)) (tmp '())) (if (< (- max step) i) (reverse tmp) (loop (+ i step) (cons (adjust-of (+ i step)) tmp))))))) (equal? (iota 9) '(1 2 3 4 5 6 7 8 9)) (equal? (iota 4 9) '(4 5 6 7 8 9)) (equal? (iota 2 9 3) '(2 5 8)) "P.481" "C.1.3 再帰による可算・乗算" (define succ (lambda (list) (cons 1 list))) (define pred (lambda (list) (cdr list))) "P.482" (equal? (succ '(1 1 1)) '(1 1 1 1)) (equal? (pred '(1 1 1 1)) '(1 1 1)) "加算 plus" (define plus (lambda (x y) (if (null? y) x (succ (plus x (pred y)))))) "P.483" (equal? (plus '(1 1) '(1 1 1)) '(1 1 1 1 1)) (define plus-num (lambda (x y) (if (zero? y) x (add1 (plus-num x (sub1 y)))))) (equal? (plus-num 2 3) 5) "乗算 mult" (define mult (lambda (x y) (if (null? y) '() (plus x (mult x (pred y)))))) "P.484" (equal? (mult '(1 1) '(1 1 3)) '(1 1 1 1 1 1)) (equal? (mult '(1) '(1 1)) '(1 1)) "累乗 pows" (define pows (lambda (x y) (if (null? y) '(1) (mult x (pows x (pred y)))))) (equal? (pows '(1 1) '(1 1 1)) '(1 1 1 1 1 1 1 1)) "無限集合との関係" (define kakko (lambda (i) (if (zero? i) (list) (append (list (kakko (-- i))) (kakko (-- i)))))) "P.485" (equal? (kakko 0) '()) (equal? (kakko 1) '(())) (equal? (kakko 2) '((()) ())) (equal? (kakko 3) '(((()) ()) (()) ())) (add1 0) (add1 (add1 0)) (add1 (add1 (add1 0))) ((compose add1 add1 add1) 0)
false
a668d7554aba618df5486fbcf2cc8e7f416cffed
6f86602ac19983fcdfcb2710de6e95b60bfb0e02
/input/exercises/word-count/test.ss
a9c2010bfbac3680e87f923911d4ff273f78f377
[ "MIT", "CC-BY-SA-3.0" ]
permissive
exercism/scheme
a28bf9451b8c070d309be9be76f832110f2969a7
d22a0f187cd3719d071240b1d5a5471e739fed81
refs/heads/main
2023-07-20T13:35:56.639056
2023-07-18T08:38:59
2023-07-18T08:38:59
30,056,632
34
37
MIT
2023-09-04T21:08:27
2015-01-30T04:46:03
Scheme
UTF-8
Scheme
false
false
1,551
ss
test.ss
(define (parse-test test) `(test-success ,(lookup 'description test) (lambda (result expected) (let ((get-count (if (hashtable? result) (lambda (word) (hashtable-ref result word 0)) (lambda (word) (cond ((assoc word result) => cdr) (else 0)))))) (and (= (length expected) (hashtable-size result)) (fold-left (lambda (count-agrees w.c) (and count-agrees (= (cdr w.c) (get-count (car w.c))))) #t expected)))) word-count '(,(cdar (lookup 'input test))) '(,@(map (lambda (expected) (cons (symbol->string (car expected)) (cdr expected))) (lookup 'expected test))))) (let ((spec (get-test-specification 'word-count))) (put-problem! 'word-count `((test . ,(map parse-test (lookup 'cases spec))) (stubs word-count) (version . ,(lookup 'version spec)) (skeleton . "word-count.scm") (solution . "example.scm") (markdown . ,(splice-exercism 'word-count)))))
false
08e24ac77979c23c2ac7ce350e13faa05175fedd
404799b4b2d5f83ee5304392826a69defc25da77
/ex3-62.scm
53456624dee678f44cd3a26ddb15496c6f97fc5d
[]
no_license
WuzhangFang/SICP-exercise
38ae650c63e74bb7c6639bf984285e06743db925
d9977009ec3e32a74edb13b4f13f6ebbbc44ab32
refs/heads/master
2020-04-16T16:01:18.058287
2019-10-01T21:52:40
2019-10-01T21:52:40
165,722,260
0
0
null
null
null
null
UTF-8
Scheme
false
false
492
scm
ex3-62.scm
;; Exercise 3.62 (load "3.5.scm") (load "ex3-59.scm") (load "ex3-60.scm") (load "ex3-61.scm") (define (div-series s1 s2) (if (zero? (stream-car s2)) (error "denominator is zero") (mul-series s1 (invert-unit-series s2)))) (define tan-series (div-series sine-series cosine-series)) ; test (stream-ref tan-series 0) (stream-ref tan-series 1) (stream-ref tan-series 2) (stream-ref tan-series 3) (stream-ref tan-series 4) (stream-ref tan-series 5) ;; tanx = x + 1/3x^3 + 2/15x^5 + ...
false
450e1ad6548cc2dff6471fd79ac3964fe46d0258
3604661d960fac0f108f260525b90b0afc57ce55
/SICP-solutions/2/2.97-reduce-terms.scm
81d3e0c98dbdf35267c28b768880b3a242b0304b
[]
no_license
rythmE/SICP-solutions
b58a789f9cc90f10681183c8807fcc6a09837138
7386aa8188b51b3d28a663958b807dfaf4ee0c92
refs/heads/master
2021-01-13T08:09:23.217285
2016-09-27T11:33:11
2016-09-27T11:33:11
69,350,592
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,351
scm
2.97-reduce-terms.scm
(load "terms.scm") (define (reduce-terms n d) (define (gcd-coeff L) (if (null? (rest-terms L)) (coeff (first-term L)) (gcd (coeff (first-term L)) (gcd-coeff L)))) (let ((g (gcd (gcd-coeff n) (gcd-coeff d)))) (let ((numer (div-terms n (make-polynomial 0 g))) (denom (div-terms d (make-polynomial 0 g)))) (list n d)))) ;;representation of terms and term lists for poly-package (define (reduce-poly p1 p2) (if (same-variable? (variable p1) (variable p2)) (make-poly (variable p1) (reduce-terms (term-list p1) (term-list p2))) (error "Polys not in same var -- REDUCE-POLY" (list p1 p2)))) ;;interface to rest of the system for poly-package (put 'reduce '(polynomial polynomial) (lambda (p1 p2) (tag (reduce-poly p1 p2)))) ;;representation of terms and term lists for scheme-number-package (define (reduce-integers n d) (let ((g (gcd n d))) (list (/ n g) (/ d g)))) ;;interface to rest of the system for scheme-number-package (put 'reduce '(scheme-number scheme-number) (lambda (x y) (tag (reduce-integers x y)))) ;; for apply-generic.scm (define (reduce x y) (apply-generic 'reduce x y)) ;;internal procedures for raational-package ; (load "apply-generic.scm") (define (make-rat n d) (let ((g (reduce n d))) (cons (car g) (cadr g))))
false
89f0e38ef6b2d98577a0d243da85a03b8b87a7e5
4f91474d728deb305748dcb7550b6b7f1990e81e
/Chapter2/ex2.28.scm
677b60b866e89ce14734e2b0642963d4cf07efe8
[]
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
323
scm
ex2.28.scm
(define (fringe items) (cond ((null? items) '()) ((pair? (car items)) (append (fringe (car items)) (fringe (cdr items)))) (else (cons (car items) (fringe (cdr items)))))) (define x (list (list 1 2) (list 3 4))) (define y (fringe x)) (define z (fringe (list x x)))
false
431595c220374ec3d3d53c3067f739f48e5d8d20
917429e3eb6bcf2db8c71197f88b979d998b1b7e
/conf/srfi-13.scm
b9ad1bd2caa2931117d1c9702581ec8d6da311ae
[]
no_license
mario-goulart/chicken-benchmarks
554ca8421631211a891cc497f84dfe62b8f9c8e5
ea00fe51ec33496de7c9b07fa0ec481fe59989fa
refs/heads/master
2021-11-20T21:40:55.198252
2021-10-09T18:52:48
2021-10-09T18:52:48
4,427,587
1
5
null
2019-01-27T07:59:38
2012-05-24T01:59:23
Scheme
UTF-8
Scheme
false
false
30
scm
srfi-13.scm
(programs-dir "progs/srfi-13")
false
6beca716d977e10826d60392194d230543fb3076
3323fb4391e76b853464a9b2fa478cd7429e9592
/exercise-2.69.ss
41a80cd1617b71e37cc681ffd3b856692c677523
[]
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
409
ss
exercise-2.69.ss
(top-level-program (import (rnrs) (huffman)) (define huffman-tree (generate-huffman-tree '((A 4) (B 2) (D 1) (C 1)))) (define sample-message '(A D A B B C A)) (display (encode sample-message huffman-tree)) ; (0 1 1 0 0 1 0 1 0 1 1 1 0) (newline) (define sample-codes '(0 1 1 0 0 1 0 1 0 1 1 1 0)) (display (decode sample-codes huffman-tree)) ; (A D A B B C A) (newline) )
false
e2d14fcde9fdae8116b8da041c495145283049d2
0021f53aa702f11464522ed4dff16b0f1292576e
/scm/p85.scm
ce53619d9a7936ae3d3b5954010dd1f52a5bc553
[]
no_license
mtsuyugu/euler
fe40dffbab1e45a4a2a297c34b729fb567b2dbf2
4b17df3916f1368eff44d6bc36202de4dea3baf7
refs/heads/master
2021-01-18T14:10:49.908612
2016-10-07T15:35:45
2016-10-07T15:35:45
3,059,459
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,471
scm
p85.scm
(define (p85) (letrec ((max-num 2000000) (dummy (list 0 0 0 0 max-num)) (count (lambda (c r col row) (* (+ (- col c) 1) (+ (- row r) 1)))) (count-all (lambda (c r col row) (let loop ((c 1) (r 1) (n 0)) (cond ((> c col) n) ((> r row) (loop (+ c 1) 1 n)) (else (loop c (+ r 1) (+ n (count c r col row)))))))) (diff (lambda (n) (abs (- n max-num)))) (choice-lower-diff (lambda (a b) (if (< (ref a 4) (ref b 4)) a b))) (iter (lambda (col row result tmp end) (if (and (> end 0) (> row end)) result (let* ((n (count-all 1 1 col row)) (diff-n (diff n)) (record (list col row (* col row) n diff-n))) (cond ((< n max-num) (iter (+ col 1) row result record end)) (else (let ((nearest (if (< (ref tmp 4) diff-n) tmp record))) ; (print nearest) (iter 1 (+ row 1) (choice-lower-diff nearest result) dummy (if (= end 0) col end)))))))))) (iter 1 1 dummy '() 0) )) (print (p85))
false
a9ff7af5446a09ab0051aa36761852eaa820eaf7
0964d931c7146fbdd1eb72fba2c0bcc492ca526b
/ports/prescheme/runtime-types.scm
7c07952b2fdd54a22b3eabe183b7728afa16d95a
[]
no_license
kaveman-/schemeray
b30f67f0b0d3f8285b70d23266c13a34b6e96f7e
0ea0f1596cbafa05e541131fd64d482c79dd4173
refs/heads/master
2021-05-27T03:29:43.126547
2009-03-26T03:56:42
2009-03-26T03:56:42
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,517
scm
runtime-types.scm
(define-syntax define-field (lambda (f r c) (let ((name (cadr f)) (type (caddr f))) (table-set! *type-field-table* name type)) '(begin))) (define-syntax define-object (lambda (f r c) (define (get-field-type name) (table-ref *type-field-table* name)) (define (construct-type-field type-name field-name type) `(,field-name ,type ,(symbol-append type-name "-" field-name))) (let* ((name (cadr f)) (type-desc (caddr f)) (fields (cdddr f)) (bare-fields (map (lambda (f) (if (pair? f) (car f) f)) fields)) (id *last-record-type-id*) (constructor (symbol-append "really-make-" name)) (maker (symbol-append "make-" name)) (predicator (symbol-append name "?")) (typifier (symbol-append "object->" name)) (untypifier (symbol-append name "->object"))) (set! *last-record-type-id* (+ *last-record-type-id* 1)) `(begin (define-record-type ,name ,type-desc (,constructor ,@(cons 'type bare-fields)) ,(construct-type-field name 'type 'integer) ,@(map (lambda (field) (let ((field-name (if (pair? field) (car field) field)) (field-type (if (pair? field) (cadr field) (get-field-type field)))) (construct-type-field name field-name field-type))) fields)) (define (,maker ,@bare-fields) ;; Cast it to the generic type before releasing ;; it to the wild (,untypifier (,constructor ,@(cons id bare-fields)))) (define (,predicator o) ;; Note that we can only test generic objects, ;; but if it's already typed we would know it (= (object-type o) ,id)) (define ,untypifier (external "(struct object*)" (=> (,name) object) (lambda (o) (,(r 'change-record-type) o :object)))) (define ,typifier (external ,(string-append "(struct " (symbol->string name) "*)") (=> (object) ,name) (lambda (o) (,(r 'change-record-type) o ,type-desc))))))))
true
effd34a079428f21cc507f3041d1ed54bfdde3fc
e26e24bec846e848630bf97512f8158d8040689c
/lib/chibi/pathname.sld
8f7aaaf843e241c6bbb36bc62ddea26b3e3f470a
[ "BSD-3-Clause" ]
permissive
traviscross/chibi-scheme
f989df49cb76512dc59f807aeb2426bd6fe1c553
97b81d31300945948bfafad8b8a7dbffdcd61ee3
refs/heads/master
2023-09-05T16:57:14.338631
2014-04-01T22:02:02
2014-04-01T22:02:02
18,473,315
2
0
null
null
null
null
UTF-8
Scheme
false
false
331
sld
pathname.sld
(define-library (chibi pathname) (export path-strip-directory path-directory path-extension path-strip-extension path-replace-extension path-absolute? path-relative? path-strip-leading-parents path-relative-to path-normalize make-path) (import (chibi) (chibi string)) (include "pathname.scm"))
false
8a13c95ecbc84eb726b56dddb8bed987cdebbbb2
b780251bb60ae41f158cff824973c5dba9f3288d
/lambda-operations.scm
705e0f7a7eed058b98557921135d57009d21f043
[]
no_license
drewt/Church
2bb742bf37cbe4c95e1386b87dcfe197d5fe4d9d
90b32d12bf65684665b4d87f744ee4ded63418e6
refs/heads/master
2020-06-02T09:08:06.236411
2014-04-19T00:58:40
2014-04-19T01:10:03
18,859,972
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,749
scm
lambda-operations.scm
(declare (unit lambda-operations) (uses lambda-ast) (export lambda-apply lambda-equal? lambda-freevars lambda-reduce lambda-substitute)) (require-extension srfi-14) (include "ast-case.scm") (define (lambda-equal? a b) (ast-case a ((var: name type) (and (variable? b) (char=? name (variable-name b)))) ((fun: var body) (and (abstraction? b) (lambda-equal? var (abstraction-variable b)) (lambda-equal? body (abstraction-body b)))) ((app: fun arg) (and (application? b) (lambda-equal? fun (application-function b)) (lambda-equal? arg (application-argument b)))))) (define (lambda-substitute ast v expr) (ast-case ast ((var: name type) (if (lambda-equal? ast v) expr ast)) ((fun: var body) (if (lambda-equal? var v) ast (make-fun var (lambda-substitute body v expr)))) ((app: fun arg) (make-app (lambda-substitute fun v expr) (lambda-substitute arg v expr))))) (define (lambda-apply fun arg) (assert (abstraction? fun)) (let ((fixed-fun (alpha-fixup fun arg))) (lambda-substitute (abstraction-body fixed-fun) (abstraction-variable fun) arg))) (define (lambda-reduce ast) (nor ast)) ;; "call by name" reduction strategy (define (cbn ast) (ast-case ast ((var: n t) ast) ((fun: v b) ast) ((app: app-fun arg) (let ((fun (cbn app-fun))) (if (abstraction? fun) (cbn (lambda-apply fun arg)) (make-app fun arg)))))) ;; normal order reduction strategy (define (nor ast) (ast-case ast ((var: name type) ast) ((fun: var body) (make-fun var (nor body))) ((app: app-fun arg) (let ((fun (cbn app-fun))) (if (abstraction? fun) (nor (lambda-apply fun arg)) (make-app (nor fun) (nor arg))))))) (define (lambda-freevars ast) (define (visit ast bound) (ast-case ast ((var: name type) (if (member name bound) '() (list ast))) ((fun: var body) (visit body (cons (variable-name var) bound))) ((app: fun arg) (append (visit fun bound) (visit arg bound))))) (visit ast '())) (define (lambda-vars ast) (ast-case ast ((var: name type) (list ast)) ((fun: var body) (cons var (lambda-vars body))) ((app: fun arg) (append (lambda-vars fun) (lambda-vars arg))))) (define var-names (string->char-set "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")) (define (unused-var ast) (let ((used (lambda-vars ast))) (let loop ((cursor (char-set-cursor var-names))) (cond ((end-of-char-set? cursor) #f) ((in-set? (make-var (char-set-ref var-names cursor)) used) (loop (char-set-cursor-next var-names cursor))) (else (make-var (char-set-ref var-names cursor))))))) (define (in-set? ast set) (cond ((null? set) #f) ((lambda-equal? ast (car set)) #t) (else (in-set? ast (cdr set))))) (define (alpha-fixup fun arg) (let ((free (lambda-freevars arg))) (define (fixup ast) (ast-case ast ((var: name type) ast) ;; -- if fun-var free in arg, rename ((fun: var body) (if (in-set? var free) (let* ((new-var (unused-var ast)) (new-body (lambda-substitute body var new-var))) (make-fun new-var (fixup new-body))) (make-fun var (fixup body)))) ((app: fun arg) (make-app (fixup fun) (fixup arg))))) (make-fun (abstraction-variable fun) (fixup (abstraction-body fun)))))
false
5a81abeb2d16d6c9622f6d4db91b79a635298baf
ff40f278d948cfea9911ee5db3c5cbb3cb41b09e
/spock/syntax.scm
6b786d641d0833120b6c2febaa2fea8116ef1d3d
[]
no_license
mario-goulart/spock
a1da32448b4ff2bf04c2ac4f63d67659f548ad0c
b88f08f8bc689babc433ad8288559ce5c28c52d5
refs/heads/master
2020-05-29T13:49:25.874909
2013-05-30T12:48:49
2013-05-30T12:48:49
12,936,406
4
0
null
null
null
null
UTF-8
Scheme
false
false
2,708
scm
syntax.scm
;;;; syntax.scm - various useful macros (define-syntax define-syntax-rule (syntax-rules ___ () ((_ (name args ___) rule) (define-syntax name (syntax-rules () ((_ args ___) rule)))))) (define-syntax-rule (when x y z ...) (if x (begin y z ...))) (define-syntax-rule (unless x y z ...) (if (not x) (begin y z ...))) (define-syntax cut (syntax-rules (<> <...>) ;; construct fixed- or variable-arity procedure: ((_ "1" (slot-name ...) (proc arg ...)) (lambda (slot-name ...) (proc arg ...))) ((_ "1" (slot-name ...) (proc arg ...) <...>) (lambda (slot-name ... . rest-slot) (apply proc arg ... rest-slot))) ;; process one slot-or-expr ((_ "1" (slot-name ...) (position ...) <> . se) (cut "1" (slot-name ... x) (position ... x) . se)) ((_ "1" (slot-name ...) (position ...) nse . se) (cut "1" (slot-name ...) (position ... nse) . se)) ((_ . slots-or-exprs) (cut "1" () () . slots-or-exprs))) ) (define-syntax fluid-let (syntax-rules () ((_ ((v1 e1) ...) b1 b2 ...) (fluid-let "temps" () ((v1 e1) ...) b1 b2 ...)) ((_ "temps" (t ...) ((v1 e1) x ...) b1 b2 ...) (let ((temp e1)) (fluid-let "temps" ((temp e1 v1) t ...) (x ...) b1 b2 ...))) ((_ "temps" ((t e v) ...) () b1 b2 ...) (let-syntax ((swap! (syntax-rules () ((swap! a b) (let ((tmp a)) (set! a b) (set! b tmp)))))) (dynamic-wind (lambda () (swap! t v) ...) (lambda () b1 b2 ...) (lambda () (swap! t v) ...)))))) (define-syntax-rule (begin1 x1 x2 ...) (%call-with-saved-values (lambda () x1) (lambda () (begin x2 ...)))) (define-syntax-rule (syntax-error msg arg ...) (%syntax-error msg arg ...)) (define-syntax-rule (new class arg ...) (%new class arg ...)) (define-syntax define-entry-point (syntax-rules () ((_ (name . llist) body ...) (define-entry-point name (lambda llist body ...))) ((_ name x) (begin (define name x) (define (%host-set! 'name (callback name))))))) (define-syntax-rule (define-native name ...) (begin (define-syntax name (native (%host-ref 'name))) ...)) (define-syntax-rule (define-native-method name ...) (begin (define-syntax name (native-method (%host-ref 'name))) ...)) (define-syntax set! (let-syntax ((primitive-set! set!)) (syntax-rules () ((_ (prop x) y) (%property-set! 'prop x y)) ((_ var x) (primitive-set! var x))))) (define-syntax-rule (optional x y) (if (pair? x) (car x) y))
true
8f43c646a28e5ad0620a1237d4c443a2e4778203
defeada37d39bca09ef76f66f38683754c0a6aa0
/System.Data/system/data/odbc/odbc-permission-attribute.sls
d22e95374b6d8a71b22561ca615158f6a726e6a3
[]
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
618
sls
odbc-permission-attribute.sls
(library (system data odbc odbc-permission-attribute) (export new is? odbc-permission-attribute? create-permission) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Data.Odbc.OdbcPermissionAttribute a ...))))) (define (is? a) (clr-is System.Data.Odbc.OdbcPermissionAttribute a)) (define (odbc-permission-attribute? a) (clr-is System.Data.Odbc.OdbcPermissionAttribute a)) (define-method-port create-permission System.Data.Odbc.OdbcPermissionAttribute CreatePermission (System.Security.IPermission)))
true
8f4443aaf9fea5c5e739012c14b22b7d17f691af
defeada37d39bca09ef76f66f38683754c0a6aa0
/mscorlib/system/threading/event-wait-handle.sls
9d5687f7cfb573d1f7c72640041cdfec8818ed4c
[]
no_license
futsuki/ironscheme-port
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
4e7a81b0fbeac9a47440464988e53fb118286c54
refs/heads/master
2016-09-06T17:13:11.462593
2015-09-26T18:20:40
2015-09-26T18:20:40
42,757,369
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,368
sls
event-wait-handle.sls
(library (system threading event-wait-handle) (export new is? event-wait-handle? set? set-access-control open-existing reset? get-access-control) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Threading.EventWaitHandle a ...))))) (define (is? a) (clr-is System.Threading.EventWaitHandle a)) (define (event-wait-handle? a) (clr-is System.Threading.EventWaitHandle a)) (define-method-port set? System.Threading.EventWaitHandle Set (System.Boolean)) (define-method-port set-access-control System.Threading.EventWaitHandle SetAccessControl (System.Void System.Security.AccessControl.EventWaitHandleSecurity)) (define-method-port open-existing System.Threading.EventWaitHandle OpenExisting (static: System.Threading.EventWaitHandle System.String System.Security.AccessControl.EventWaitHandleRights) (static: System.Threading.EventWaitHandle System.String)) (define-method-port reset? System.Threading.EventWaitHandle Reset (System.Boolean)) (define-method-port get-access-control System.Threading.EventWaitHandle GetAccessControl (System.Security.AccessControl.EventWaitHandleSecurity)))
true
5692807338329f29fb448d05a215c41cfa16b88e
222b42ba803bfecd4ec31166dd2be107a840f2bd
/undone/unsorted/src/src/stringsearch.scm
8ebec0813af549b44b4bbb085425bda397d23951
[]
no_license
ab3250/ablib
83512c2c2cadd0eb49ad534548c058e3ed119d4c
887c8661ce99e8edfe89bcf707400e55c3943dd4
refs/heads/master
2023-06-12T13:36:49.487467
2021-07-11T13:29:45
2021-07-11T13:29:45
384,955,137
0
0
null
null
null
null
UTF-8
Scheme
false
false
928
scm
stringsearch.scm
;;;; ;;;; Brute force string searching. ;;;; The program really searches a sublist from a list of ;;;; characters, but the algorithm is exactly the same. ;;;; ;;;; Copyright Pertti Kellom\"aki, [email protected], 1992 ;;;; This file may be freely distributed. ;;;; (define (brutesearch pattern string) (define (matches? pattern string) (let loop ((pattern pattern) (string string)) (cond ((null? pattern) #t) ((null? string) #f) (else (and (equal? (car pattern) (car string)) (matches? (cdr pattern) (cdr string))))))) ;; try each prefix of the string (let loop ((string string) (position 0)) (cond ((null? string) #f) ((matches? pattern string) position) (else (loop (cdr string) (+ position 1))))))
false
1f283cfcedfbeb1ca70ec13febe1607fa24bc598
defeada37d39bca09ef76f66f38683754c0a6aa0
/System/system/component-model/component-info.sls
bfbe15813caa0cde11855606445ec8acaffa3fe7
[]
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
955
sls
component-info.sls
(library (system component-model component-info) (export new is? component-info? get-properties get-attributes get-events) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.ComponentModel.ComponentInfo a ...))))) (define (is? a) (clr-is System.ComponentModel.ComponentInfo a)) (define (component-info? a) (clr-is System.ComponentModel.ComponentInfo a)) (define-method-port get-properties System.ComponentModel.ComponentInfo GetProperties (System.ComponentModel.PropertyDescriptorCollection)) (define-method-port get-attributes System.ComponentModel.ComponentInfo GetAttributes (System.ComponentModel.AttributeCollection)) (define-method-port get-events System.ComponentModel.ComponentInfo GetEvents (System.ComponentModel.EventDescriptorCollection)))
true
ee1424d83fb43d5c21699fc5562df31f2139af9c
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
/ext/crypto/sagittarius/crypto/digests.scm
c6e0aec09bf38a0aae85b34ff070c68847667fd2
[ "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "MIT", "BSD-2-Clause" ]
permissive
ktakashi/sagittarius-scheme
0a6d23a9004e8775792ebe27a395366457daba81
285e84f7c48b65d6594ff4fbbe47a1b499c9fec0
refs/heads/master
2023-09-01T23:45:52.702741
2023-08-31T10:36:08
2023-08-31T10:36:08
41,153,733
48
7
NOASSERTION
2022-07-13T18:04:42
2015-08-21T12:07:54
Scheme
UTF-8
Scheme
false
false
5,837
scm
digests.scm
;;; -*- mode:scheme; coding:utf-8; -*- ;;; ;;; sagittarius/crypto/digests.scm - Digests calculator ;;; ;;; Copyright (c) 2022 Takashi Kato <[email protected]> ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; #!nounbound (library (sagittarius crypto digests) (export message-digest? make-message-digest digest-message digest-message! message-digest-init! message-digest-process! message-digest-done! message-digest-done message-digest-descriptor message-digest-digest-size digest-descriptor? <digest-descriptor> make-digest-descriptor digest-descriptor-name digest-descriptor-digest-size digest-descriptor-block-size digest-descriptor-oid *digest:whirlpool* *digest:ripemd-128* *digest:ripemd-160* *digest:ripemd-256* *digest:ripemd-320* *digest:sha-1* *digest:sha-224* *digest:sha-256* *digest:sha-384* *digest:sha-512* *digest:sha-512/224* *digest:sha-512/256* *digest:sha3-224* *digest:sha3-256* *digest:sha3-384* *digest:sha3-512* *digest:keccak-224* *digest:keccak-256* *digest:keccak-384* *digest:keccak-512* *digest:tiger-192* *digest:md5* *digest:md4* *digest:md2* *digest:blake2s-128* *digest:blake2s-160* *digest:blake2s-224* *digest:blake2s-256* *digest:blake2b-160* *digest:blake2b-256* *digest:blake2b-384* *digest:blake2b-512* *digest:shake-128* *digest:shake-256* *digest:cshake-128* *digest:cshake-256* oid->digest-descriptor ) (import (rnrs) (clos user) (sagittarius) (sagittarius mop immutable) (sagittarius crypto digests descriptors) (sagittarius crypto digests cshake) (sagittarius crypto digests oid-map)) (define-class <message-digest> (<immutable>) ((state :reader message-digest-state :writer message-digest-state-set! :init-value #f :mutable #t) (descriptor :reader message-digest-descriptor :init-keyword :descriptor))) (define (message-digest? o) (is-a? o <message-digest>)) (define (make-message-digest descriptor) (unless (digest-descriptor? descriptor) (assertion-violation 'make-message-digest "Digest descriptor is required")) (make <message-digest> :descriptor descriptor)) (define (message-digest-digest-size md) (digest-descriptor-digest-size (message-digest-descriptor md))) (define (digest-message md msg :optional (length #f)) (define desc (message-digest-descriptor md)) (let ((len (or (digest-descriptor-digest-size desc) length))) (unless len (assertion-violation 'digest-message "Digest length must be specified for this digest" (digest-descriptor-name desc))) (let ((out (make-bytevector len))) (digest-message! md msg out 0 len)))) (define (digest-message! md msg out :optional (start 0) (length #f)) (message-digest-done! (message-digest-process! (message-digest-init! md) msg) out start (or length (bytevector-length out))) out) (define (message-digest-init! (md message-digest?) . opts) (define desc (message-digest-descriptor md)) (message-digest-state-set! md (apply make-digest-state desc opts)) md) (define (message-digest-process! (md message-digest?) (bv bytevector?) :optional (start 0) (length (- (bytevector-length bv) start))) (digest-state-process! (message-digest-state md) bv start length) md) (define (message-digest-done! (md message-digest?) (out bytevector?) :optional (start 0) ;; length may not be used (length (- (bytevector-length out) start))) (digest-state-done! (message-digest-state md) out start length)) (define (message-digest-done md :optional (length #f)) (define desc (message-digest-descriptor md)) (let ((len (or (digest-descriptor-digest-size desc) length))) (unless len (assertion-violation 'message-digest-done "Digest length must be specified for this digest" (digest-descriptor-name desc))) (let ((out (make-bytevector len))) (message-digest-done! md out) out))) (define-record-type digest-state (fields descriptor state) (protocol (lambda (p) (lambda (desc . opts) (p desc (apply (digest-descriptor-init desc) opts)))))) (define (digest-state-process! ds bv start length) ((digest-descriptor-process (digest-state-descriptor ds)) (digest-state-state ds) bv start length)) (define (digest-state-done! ds out start length) ((digest-descriptor-done (digest-state-descriptor ds)) (digest-state-state ds) out start length)) )
false
160c4adcdefbe887433bfdec546357d8f2544d80
0768e217ef0b48b149e5c9b87f41d772cd9917f1
/sitelib/srfi/35.scm
7f90efb552e95235704b9202beb2e7c65ec19395
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
fujita-y/ypsilon
e45c897436e333cf1a1009e13bfef72c3fb3cbe9
62e73643a4fe87458ae100e170bf4721d7a6dd16
refs/heads/master
2023-09-05T00:06:06.525714
2023-01-25T03:56:13
2023-01-25T04:02:59
41,003,666
45
7
BSD-2-Clause
2022-06-25T05:44:49
2015-08-19T00:05:35
Scheme
UTF-8
Scheme
false
false
7,061
scm
35.scm
#!nobacktrace #| Copyright (C) Richard Kelsey, Michael Sperber (2002). All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |# (define-library (srfi 35) (import (except (scheme base) define-record-type) (srfi 1) (srfi 9) (srfi 23)) (export make-condition-type condition-type? make-condition condition? condition-has-type? condition-ref make-compound-condition extract-condition define-condition-type condition &condition &message message-condition? condition-message &serious serious-condition? &error error?) (begin (define-record-type :condition-type (really-make-condition-type name supertype fields all-fields) condition-type? (name condition-type-name) (supertype condition-type-supertype) (fields condition-type-fields) (all-fields condition-type-all-fields)) (define (make-condition-type name supertype fields) (if (not (symbol? name)) (error "make-condition-type: name is not a symbol" name)) (if (not (condition-type? supertype)) (error "make-condition-type: supertype is not a condition type" supertype)) (if (not (null? (lset-intersection eq? (condition-type-all-fields supertype) fields))) (error "duplicate field name")) (really-make-condition-type name supertype fields (append (condition-type-all-fields supertype) fields))) (define-syntax define-condition-type (syntax-rules () ((define-condition-type ?name ?supertype ?predicate (?field1 ?accessor1) ...) (begin (define ?name (make-condition-type '?name ?supertype '(?field1 ...))) (define (?predicate thing) (and (condition? thing) (condition-has-type? thing ?name))) (define (?accessor1 condition) (condition-ref (extract-condition condition ?name) '?field1)) ...)))) (define (condition-subtype? subtype supertype) (let recur ((subtype subtype)) (cond ((not subtype) #f) ((eq? subtype supertype) #t) (else (recur (condition-type-supertype subtype)))))) (define (condition-type-field-supertype condition-type field) (let loop ((condition-type condition-type)) (cond ((not condition-type) #f) ((memq field (condition-type-fields condition-type)) condition-type) (else (loop (condition-type-supertype condition-type)))))) (define-record-type :condition (really-make-condition type-field-alist) condition? (type-field-alist condition-type-field-alist)) (define (make-condition type . field-plist) (let ((alist (let label ((plist field-plist)) (if (null? plist) '() (cons (cons (car plist) (cadr plist)) (label (cddr plist))))))) (if (not (lset= eq? (condition-type-all-fields type) (map car alist))) (error "condition fields don't match condition type")) (really-make-condition (list (cons type alist))))) (define (condition-has-type? condition type) (any (lambda (has-type) (condition-subtype? has-type type)) (condition-types condition))) (define (condition-ref condition field) (type-field-alist-ref (condition-type-field-alist condition) field)) (define (type-field-alist-ref type-field-alist field) (let loop ((type-field-alist type-field-alist)) (cond ((null? type-field-alist) (error "type-field-alist-ref: field not found" type-field-alist field)) ((assq field (cdr (car type-field-alist))) => cdr) (else (loop (cdr type-field-alist)))))) (define (make-compound-condition condition-1 . conditions) (really-make-condition (apply append (map condition-type-field-alist (cons condition-1 conditions))))) (define (extract-condition condition type) (let ((entry (find (lambda (entry) (condition-subtype? (car entry) type)) (condition-type-field-alist condition)))) (if (not entry) (error "extract-condition: invalid condition type" condition type)) (really-make-condition (list (cons type (map (lambda (field) (assq field (cdr entry))) (condition-type-all-fields type))))))) (define-syntax condition (syntax-rules () ((condition (?type1 (?field1 ?value1) ...) ...) (type-field-alist->condition (list (cons ?type1 (list (cons '?field1 ?value1) ...)) ...))))) (define (type-field-alist->condition type-field-alist) (really-make-condition (map (lambda (entry) (cons (car entry) (map (lambda (field) (or (assq field (cdr entry)) (cons field (type-field-alist-ref type-field-alist field)))) (condition-type-all-fields (car entry))))) type-field-alist))) (define (condition-types condition) (map car (condition-type-field-alist condition))) (define (check-condition-type-field-alist the-type-field-alist) (let loop ((type-field-alist the-type-field-alist)) (if (not (null? type-field-alist)) (let* ((entry (car type-field-alist)) (type (car entry)) (field-alist (cdr entry)) (fields (map car field-alist)) (all-fields (condition-type-all-fields type))) (for-each (lambda (missing-field) (let ((supertype (condition-type-field-supertype type missing-field))) (if (not (any (lambda (entry) (let ((type (car entry))) (condition-subtype? type supertype))) the-type-field-alist)) (error "missing field in condition construction" type missing-field)))) (lset-difference eq? all-fields fields)) (loop (cdr type-field-alist)))))) (define &condition (really-make-condition-type '&condition #f '() '())) (define-condition-type &message &condition message-condition? (message condition-message)) (define-condition-type &serious &condition serious-condition?) (define-condition-type &error &serious error?)))
true
d894b7e9e141ad4b8faae62e4f9ce5b8c35d3d67
7b49e5e3aec855d322c1179d4fb288b76307fa4a
/src/renderers/ajax-handlers.scm
954df003d0c298617df58dc8e420dca8ef61b510
[]
no_license
mario-goulart/awful-picman
db7fb456e551a0796d67187d8bea90692056c48a
3a38e1265ff770e1292c45aa44df8edadaa22028
refs/heads/master
2022-12-22T10:13:21.786573
2022-12-11T19:41:17
2022-12-11T19:41:23
11,710,823
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,714
scm
ajax-handlers.scm
(define (json-array->list-wo-nulls json-array) (remove (lambda (item) (equal? item "")) (with-input-from-string json-array json-read))) (define (update-pic-info!) (with-request-variables (id path descr (tags (nonempty as-string)) (albums (nonempty as-string)) (decade (nonempty as-string)) (year (nonempty as-string)) (month (nonempty as-string)) (day (nonempty as-string))) (let ((tags (json-array->list-wo-nulls tags)) (albums (json-array->list-wo-nulls albums))) (debug 2 "update-pic-info!: Form data:") (debug 2 " path=~a" path) (debug 2 " date=~a ~a ~a ~a" decade year month day) (debug 2 " descr=~S" descr) (debug 2 " tags=~S" tags) (debug 2 " albums=~S" albums) (insert/update-pic! path descr: descr tags: tags albums: albums decade: decade year: year month: month day: day) (render-modal-pic-form/ro (get-pic-from-db path) id)))) (define (update-album-info!) (with-request-variables (album-id title descr (remove? (nonempty as-boolean))) (if remove? (db-remove-album! album-id) (db-update-album! album-id title descr)))) (define (batch-update-pic-info!) (with-request-variables (pics template-data) (assert pics) (assert template-data) (and-let* ((pics (chop (with-input-from-string pics json-read) 2)) (template-data (vector->list (with-input-from-string template-data json-read))) (tags (json-array->list-wo-nulls (alist-ref "tags" template-data equal?))) (albums (json-array->list-wo-nulls (alist-ref "albums" template-data equal?)))) (debug 2 "batch-update-pic-info!:") (debug 2 " pics: ~S" pics) (debug 2 " template-data: ~S" template-data) (debug 2 " tags: ~S" tags) (debug 2 " albums: ~S" albums) (for-each (lambda (pic-id/path) ;; pic-path is actually the thumbnail path, so it ;; contains (thumbnails-web-dir) and the thumbnail ;; dimension, which have to be removed. (let* ((pic-id (car pic-id/path)) (path (cadr pic-id/path)) (get-field (lambda (i) (alist-ref i template-data equal?)))) ;; FIXME: a single insert would be enough (insert/update-pic! path descr: (get-field "descr") tags: tags albums: albums decade: (get-field "decade") year: (get-field "year") month: (get-field "month") day: (get-field "day")))) pics)))) (define (update-tag!) (with-request-variables (tag-id original-tag new-tag (remove? (nonempty as-boolean))) (if (or (equal? new-tag "") remove?) (db-remove-tag! original-tag) (db-update-tag! original-tag new-tag)))) (define (ajax/run-ocr) (with-request-variables (pic-id filename language) (run-ocr filename language)))
false
698f35d6595194f63705104a192c86059de1e11f
f5f5bf46a162365eb5f5955d185cfa9380376fa8
/test/hello-test.scm
0614db354c9b1eaf9c9190dfdf650e3f86a5c6d1
[]
no_license
fthibault1969/srfi-204
60ebad1fc5de79a25cde5827b766cca8123ad4ae
add561acc23002165ac864bd7fa443dae9d4b01a
refs/heads/master
2023-08-17T11:06:13.522151
2021-10-10T18:36:21
2021-10-10T18:36:21
280,735,657
0
0
null
2021-07-13T03:39:32
2020-07-18T20:38:52
Scheme
UTF-8
Scheme
false
false
2,469
scm
hello-test.scm
;; Copyright (C) Felix Thibault (2020). All Rights Reserved. ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation ;; files (the "Software"), to deal in the Software without ;; restriction, including without limitation the rights to use, copy, ;; modify, merge, publish, distribute, sublicense, and/or sell copies ;; of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; The above copyright notice and this permission notice (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. (cond-expand (guile (define test-name "guile-hello-test" ) (define scheme-version-name (string-append "guile-" (version))) (import (srfi srfi-9) (srfi srfi-64)) (include-from-path "./test/hello-common.scm")) (gauche (import (only (gauche base) gauche-version) (scheme base) (srfi-64)) (define test-name "gauche-hello-test") (define scheme-version-name (string-append "gauche-" (gauche-version))) (include "hello-common.scm")) (larceny ;;NOTE run like: ;; $rlwrap larceny -r7rs -I .. ;; > (include "test/hello-test.scm") (import (scheme base) (srfi 64) (srfi 115)) (define (is-version sym) (regexp-matches '(seq "larceny-" (one-or-more (or numeric "."))) (symbol->string sym))) (define test-name "larceny-hello-test") (define scheme-version-name (let lp ((has (features))) (cond ((null? has) "larceny-???") ((and (symbol? (car has)) (is-version (car has))) => (lambda (match) (regexp-match-submatch match 0))) (else (lp (cdr has)))))) (include "test/hello-common.scm")) (unsyntax (import (scheme base) (srfi :64)) (define test-name "unsyntax-hello-test") (define scheme-version-name (symbol->string (car (features)))) (include "hello-common.scm")) )
false
ada3d5c4db512c615c88279105b73e02a102f495
a19495f48bfa93002aaad09c6967d7f77fc31ea8
/src/kanren/kanren/benchmarks/query-mini.scm
9241ada7326cbce4893499cb5ba797457f99c53c
[ "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
5,011
scm
query-mini.scm
; Benchmark query, in mini-kanren ; ; David H. D. Warren ; ; query population and area database to find countries ; of approximately equal population density ; $Id: query-mini.scm,v 1.1 2006/01/31 01:32:02 oleg Exp $ ; ; SWI-Prolog, (Version 5.0.10), Pentium IV, 2GHz: ; ?- time(dobench(10000)). ; 35,020,001 inferences in 36.78 seconds (952116 Lips) (load "../mini/mk.scm") (load "../mini/mkextraforms.scm") (define benchmark_count 100) (define-syntax test-check (syntax-rules () ((_ title tested-expression expected-result) (begin (display "Testing") (display title) (newline) (let* ((expected expected-result) (produced tested-expression)) (or (equal? expected produced) (errorf 'test-check "Failed: ~a~%Expected: ~a~%Computed: ~a~%" 'tested-expression expected produced))))))) ; query(quad(C1, D1, C2, D2)) :- ; density(C1, D1), ; density(C2, D2), ; D1 > D2, ; T1 is 20 * D1, ; T2 is 21 * D2, ; T1 < T2. ; density(C, D) :- ; pop(C, P), ; area(C, A), ; D is P * 100 // A. (define benchmark (letrec ((bquery (lambda (out) (fresh (c1 d1 c2 d2) (== `(quad ,c1 ,d1 ,c2 ,d2) out) (density c1 d1) (density c2 d2) (project (d1 d2) (== (and (> d1 d2) (let ((t1 (* 20 d1)) (t2 (* 21 d2))) (< t1 t2))) #t))))) (choose2 (lambda (l a b) ; l must be instantiated (fresh () (== #t (pair? l)) (conde ((== (car l) (cons a b))) (else (choose2 (cdr l) a b)))))) (density (lambda (c d) (fresh (p) (choose2 population c p) (project (c p) (== d (let ((a (cdr (assoc c area-lst)))) (* p (/ 100.0 a))))))))) bquery)) ; populations in 100000s (define population '(("china" . 8250) ("india" . 5863) ("ussr" . 2521) ("usa" . 2119) ("indonesia" . 1276) ("japan" . 1097) ("brazil" . 1042) ("bangladesh" . 750) ("pakistan" . 682) ("w_germany" . 620) ("nigeria" . 613) ("mexico" . 581) ("uk" . 559) ("italy" . 554) ("france" . 525) ("philippines" . 415) ("thailand" . 410) ("turkey" . 383) ("egypt" . 364) ("spain" . 352) ("poland" . 337) ("s_korea" . 335) ("iran" . 320) ("ethiopia" . 272) ("argentina" . 251))) ; areas in 1000s of square miles (define area-lst '(("china" . 3380) ("india" . 1139) ("ussr" . 8708) ("usa" . 3609) ("indonesia" . 570) ("japan" . 148) ("brazil" . 3288) ("bangladesh" . 55) ("pakistan" . 311) ("w_germany" . 96) ("nigeria" . 373) ("mexico" . 764) ("uk" . 86) ("italy" . 116) ("france" . 213) ("philippines" . 90) ("thailand" . 200) ("turkey" . 296) ("egypt" . 386) ("spain" . 190) ("poland" . 121) ("s_korea" . 37) ("iran" . 628) ("ethiopia" . 350) ("argentina" . 1080))) (test-check 'query-benchmark (run 5 (out) (benchmark out)) '((quad "indonesia" 223.859649122807 "pakistan" 219.2926045016077) (quad "uk" 650.0 "w_germany" 645.8333333333334) (quad "italy" 477.5862068965517 "philippines" 461.11111111111114) (quad "france" 246.4788732394366 "china" 244.08284023668637) (quad "ethiopia" 77.71428571428571 "mexico" 76.04712041884817))) (display "Timing per iterations: ") (display benchmark_count) (newline) (time (do ((i 0 (+ 1 i))) ((>= i benchmark_count)) (run 5 (out) (benchmark out)))) ; mk.scm, v1.2 (corresponds to the book) ; (time (do ((...)) ...)) ; 62 collections ; 1230 ms elapsed cpu time, including 5 ms collecting ; 1251 ms elapsed real time, including 6 ms collecting ; 66764800 bytes allocated, including 67106536 bytes reclaimed ; kanren.ss version 3.45 ; (time (do ((...)) ...)) ; 52 collections ; 1275 ms elapsed cpu time, including 9 ms collecting ; 1312 ms elapsed real time, including 7 ms collecting ; 57261352 bytes allocated, including 56455376 bytes reclaimed ; ; kanren.ss version 4.0 ; 39 collections ; 904 ms elapsed cpu time, including 7 ms collecting ; 914 ms elapsed real time, including 6 ms collecting ; 41670216 bytes allocated, including 42439072 bytes reclaimed ; ; kanren.ss version 4.17 ; 38 collections ; 895 ms elapsed cpu time, including 5 ms collecting ; 946 ms elapsed real time, including 11 ms collecting ; 41320888 bytes allocated, including 41172536 bytes reclaimed ; ; kanren.ss version 4.50 ; 30 collections ; 874 ms elapsed cpu time, including 6 ms collecting ; 882 ms elapsed real time, including 7 ms collecting ; 31748608 bytes allocated, including 32641448 bytes reclaimed ; dobench(Count) :- ; data(Data), ; repeat(Count), ; benchmark(Data, _Result), ; fail. ; dobench(_).
true
58677d4bc541b1c7f064d6f42f1d1208cc0b83ba
074200eeaf6a79a72dd17651fdb471b7c7fbf1b5
/framework/sparql-logic.scm
4337b514a21d430c8e9e05b3f2a6669254ec006c
[ "MIT" ]
permissive
big-data-europe/mu-query-rewriter
4b687636e39c3eeb12b45c1ababc6b6d331c7289
31da5b908d3c43179fc56c8be3c6d17e406faaa7
refs/heads/master
2018-06-29T12:19:42.584292
2018-05-31T13:31:03
2018-05-31T13:31:03
108,171,918
2
0
null
null
null
null
UTF-8
Scheme
false
false
2,788
scm
sparql-logic.scm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Solving and Simplifying (define (replace-variables exp substitutions) (let rec ((exp exp)) (if (null? exp) '() (let ((e (car exp)) (rest (rec (cdr exp)))) (if (pair? e) (cons (rec e) rest) (cons (or (alist-ref e substitutions) e) rest)))))) (define (simplify-values vars vals bindings) (let ((vars (if (pair? vars) vars (list vars))) (vals (if (pair? (car vals)) vals (map list vals)))) (call/cc (lambda (out) (let loop ((vars vars) (new-vars '()) (vals vals) (new-vals (make-list (length vals) '()))) (cond ((null? vars) (if (null? new-vars) '() `(VALUES ,(reverse new-vars) ,@(map reverse new-vals)))) ((pair? vars) (cond ((sparql-variable? (car vars)) (loop (cdr vars) (cons (car vars) new-vars) (map cdr vals) (map cons (map car vals) new-vals))) (else (let ((matches (map (cut rdf-equal? <> (car vars)) (map car vals)))) (if (null? (filter values matches)) (out #f) (loop (cdr vars) new-vars (filter values (map (lambda (match? val) (and match? val)) matches vals)) (filter values (map (lambda (match? val) (and match? val)) matches new-vals)))))))) (else (cond ((sparql-variable? vars) `(VALUES ,vars ,@vals)) (else (if (null? (filter not (map (cut rdf-equal? <> vars) vals))) '() (out #f))))))))))) (define (validate-filter statement bindings) (let ((check (validate-constraint (second statement) bindings))) (case check ((#t) (values '() bindings)) ((?) (values (list statement) bindings)) ((#f) (values (list #f) bindings)) (else (abort (format "Validate filter error: ~A" statement)))))) (define (validate-constraint constraint bindings) (match constraint ((`= a b) (unify a b bindings)) ((`!= a b) (disunify a b bindings)) ((`IN a bs) (constraint-member a bs bindings)) ((`|NOT IN| a b) (constraint-not-member a b bindings)) (else '?))) (define (unify a b bindings) (if (or (sparql-variable? a) (sparql-variable? b)) '? (rdf-equal? a b))) (define (disunify a b bindings) (if (or (sparql-variable? a) (sparql-variable? b)) '? (not (rdf-equal? a b)))) (define (constraint-member a bs bindings) (let ((possible? (lambda (x) (or (sparql-variable? x) (rdf-equal? a x))))) (cond ((sparql-variable? a) '?) ((not (null? (filter possible? bs))) #t) ((null? (filter sparql-variable? bs)) #f) (else '?)))) (define (constraint-not-member a b bindings) (cond ((sparql-variable? a) '?) ((member a b) #f) ((null? (filter sparql-variable? b)) #t) (else '?)))
false
0b63c332fefedc9a2e251ce7a8adcd62e7b35404
97c107938d7a7b80d319442337316604200fc0ae
/engine/obj.ss
3e75cbecdb30d5042f912dbd1a163f9c18983810
[]
no_license
jeapostrophe/rl
ddb131563cb37da80905c5de2debd01ec6c371d6
865f2a68e075bb5cc91754839181a35b03e08cb9
refs/heads/master
2021-01-19T03:10:04.613667
2013-10-31T01:24:57
2013-10-31T01:24:57
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
651
ss
obj.ss
#lang scheme (define obj<%> (interface () short-desc render)) (define obj% (class* object% (obj<%>) (define/public (short-desc) (error 'short-desc "No short description")) (define/public (render) (error 'render "No rendering")) (super-new))) (define paren% (class* obj% (obj<%>) (init-field color orient) (define/override (short-desc) (format "~a ~a paren" color orient)) (define/override (render) (string->symbol (format "~a-~a-paren" color orient))) (super-new))) (provide/contract [obj% (implementation?/c obj<%>)] [paren% (implementation?/c obj<%>)])
false
56de0b62c3f7358233fbf7b2cb82483ef4edeff3
a2d8b4843847507b02085bb8adabd818f57dd09f
/scheme/sicp/ch_3/chapter_03.scm
7bcbd80b409be0bc6f8e13461421baaaa0bcf75c
[]
no_license
tcharding/self_learning
df911b018fc86bd5f918394b79d2456bf51f35a8
f6bb5c6f74092177aa1b71da2ce87ca1bfc5ef3c
refs/heads/master
2022-05-13T05:09:32.284093
2022-05-02T08:25:18
2022-05-02T08:25:18
41,029,057
13
2
null
null
null
null
UTF-8
Scheme
false
false
5,790
scm
chapter_03.scm
;;;; Various exercises from chapter 3 ;;;; (load "lib.scm") ;;;; Exercise 3.1 (define (make-accumulator initial-value) (lambda (n) (set! initial-value (+ initial-value n)) initial-value)) ;;;; Exercise 3.2 (define make-monitored (let ((count 0)) (lambda (fn) (lambda (x) (cond ((eq? x 'how-many-calls) count) ((eq? x 'reset) (set! count 0)) (else (set! count (inc count)) (fn x))))))) ;;;; Exercise 3.3 (define (make-account acc-password balance) (let ((incorrect-password-attempts 0)) (define %allowed-attempts 3) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount)) balance) (define (incorrect-password ignored-amount) (set! incorrect-password-attempts (inc incorrect-password-attempts)) (if (>= incorrect-password-attempts %allowed-attempts) "Too many incorrect password attempts, please contact your local overlord" "Incorrect password")) (define (dispatch password message) (if (eq? password acc-password) (begin (set! incorrect-password-attempts 0) (cond ((eq? message 'withdraw) withdraw) ((eq? message 'deposit) deposit) (else (error "Unknown request -- MAKE-ACCOUNT" m)))) incorrect-password)) dispatch)) ;;;; Exercise 3.6 (define rand-max 1000) (define rand-init 0) (define rand (let ((x rand-init)) (lambda (m) (cond ((eq? m 'generate) (let ((tmp x)) (set! x (rand-update x)) tmp)) ((eq? m 'reset) (lambda (seed) (set! x seed))) (else (error "Unknown request -- RAND" m)))))) ;; appropriately chosen integers (define a 1103515245) (define b 12345) (define m (expt 2 32)) (define (rand-update x) (mod (+ (* a x) b) m)) ;;;; (define (rng seed) "random number generator with seed" (let ((x seed)) (lambda () (let ((tmp x)) (set! x (rand-update x)) tmp)))) ;;;; Exercise 3.7 (define (make-account acc-password balance) (let ((incorrect-password-attempts 0) (passwords (list acc-password))) (define %allowed-attempts 3) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount)) balance) (define (incorrect-password ignored-amount) (set! incorrect-password-attempts (inc incorrect-password-attempts)) (if (>= incorrect-password-attempts %allowed-attempts) "Too many incorrect password attempts, please contact your local overlord" "Incorrect password")) (define (add-password extra-password) (set-cdr! passwords (list extra-password))) (define (dispatch password message) (if (member? password passwords) (begin (set! incorrect-password-attempts 0) (cond ((eq? message 'withdraw) withdraw) ((eq? message 'deposit) deposit) ((eq? message 'add-password) add-password) (else (error "Unknown request -- MAKE-ACCOUNT" m)))) incorrect-password)) dispatch)) (define (make-joint account acc-password extra-password) ((account acc-password 'add-password) extra-password) account) ;;;; Exercise 3.8 (define f-global 0) (define (f n) (let ((tmp f-global)) (set! f-global n) tmp)) ;;;; Exercise 3.14 (define (mystery x) (define (loop x y) (if (null? x) y (let ((temp (cdr x))) (set-cdr! x y) (loop temp x)))) (loop x '())) ;;;; count number of pairs in an s-exp ; http://codereview.stackexchange.com/questions/2497/correctly-count-the-number-of-pairs-in-an-irregular-list-structure (define (count-pairs x) (define (iter x sum already-counted) (if (or (not (pair? x)) (member x already-counted)) (list sum already-counted) (let ((car-result (iter (car x) (+ sum 1) (cons x already-counted)))) (iter (cdr x) (car car-result) (cadr car-result))))) (car (iter x 0 '()))) ;;;; Exercise 3.18 (define (cycle? x) (define (iter x already-seen) (cond ((null? x) #f) ((atom? (car x)) (or (member? x already-seen) (iter (cdr x) (cons x already-seen)))) (else (or (cycle? (car x)) (cycle? (cdr x)))))) (iter x '())) #! ;;; Exercise 3.50 (define (stream-map proc . argstreams) (if ((stream-null? argstreams)) the-empty-stream (cons-stream (apply proc (map stream-car argstreams)) (apply stream-map (cons proc (map stream-cdr argstreams)))))) !# ;;; Exercise 3.51 (define (show x) (dnl x) x) (define (stream-enumerate-interval low high) (if (> low high) '() (stream-cons low (stream-enumerate-interval (inc low) high)))) (define x (stream-map show (stream-enumerate-interval 1 10))) ;;;; Exercise 3.52 (define sum 0) (define (accum x) (set! sum (+ x sum)) sum) (define seq (stream-map accum (stream-enumerate-interval 1 20))) (define y (stream-filter even? seq)) (define z (stream-filter (lambda (x) (= (remainder x 5) 0)) seq)) ;;;; Exercise 3.59 (define exp-series (cons-stream 1 (integrate-series exp-series))) (define cosine-series (cons-stream 1) (integrate-series (scale-stream sine-series -1))) (define sine-series (cons-stream 0 (integrate-series cosine-series)))
false
84cde1274dcb22f2f0cbbd539825f447472a9e30
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
/test/r7rs-tests/tests/r7rs/write.scm
468fb95fe4c76ba67b7da7cc6315f3aa527902ac
[ "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "MIT", "BSD-2-Clause" ]
permissive
ktakashi/sagittarius-scheme
0a6d23a9004e8775792ebe27a395366457daba81
285e84f7c48b65d6594ff4fbbe47a1b499c9fec0
refs/heads/master
2023-09-01T23:45:52.702741
2023-08-31T10:36:08
2023-08-31T10:36:08
41,153,733
48
7
NOASSERTION
2022-07-13T18:04:42
2015-08-21T12:07:54
Scheme
UTF-8
Scheme
false
false
1,934
scm
write.scm
;; -*- mode:scheme; coding:utf-8; -*- #!r7rs (define-library (tests r7rs write) (import (scheme base) (scheme write) (tests r7rs test)) (export run-r7rs-write-tests) (begin (define-syntax test-io-unspecified (syntax-rules () ((_ expect test) (test-equal expect (let ((p (open-output-string))) (parameterize ((current-output-port p)) test) (get-output-string p)))))) (define-syntax test-io-value (syntax-rules () ((_ v str test) (test-equal str (let ((p (open-output-string))) (parameterize ((current-output-port p)) (test-equal v test)) (get-output-string p)))))) (define (run-r7rs-write-tests) (test-unspecified (unless (= 1 1.0) (display "1") (display "2"))) (test-io-unspecified "12" (when (= 1 1.0) (display "1") (display "2"))) (test-io-unspecified "" (unless (= 1 1.0) (display "1") (display "2"))) (test-io-unspecified "4 plus 1 equals 5" (begin (display "4 plus 1 equals ") (display (+ 4 1)))) (test-io-value 65 "should be a number" (with-exception-handler (lambda (con) (cond ((string? con) (display con)) (else (display "a warning has been issued"))) 42) (lambda () (+ (raise-continuable "should be a number") 23)))) ;; 6.11 (test-io-value 'exception "condition: an-error\n" (call-with-current-continuation (lambda (k) (with-exception-handler (lambda (x) (display "condition: ") (write x) (newline) (k 'exception)) (lambda () (+ 1 (raise 'an-error))))))) ;; 6.13 (test-equal "piece by piece by piece.\n" (parameterize ((current-output-port (open-output-string))) (display "piece") (display " by piece ") (display "by piece.") (newline) (get-output-string (current-output-port)))) ) ) )
true
11f995482c564142cd87fa8e840fe623b83f5b92
f782cd9c608a6aaac795d6a0758681e5caf08e11
/git.sm
85678d7d7f18e8d638a85c1e12adcc31bccd85db
[]
no_license
plesner/scsh
7d4d6ab632da4188e8c4ab0c9123878e5711d1c5
f4f2e7f7f9c73737f0acb2b19e7f7f3e78218f25
refs/heads/master
2016-09-05T09:47:12.069802
2015-05-31T10:07:44
2015-05-31T10:07:44
18,053,607
6
0
null
null
null
null
UTF-8
Scheme
false
false
2,481
sm
git.sm
; -*- mode: scheme -*- ; ; Helper functions for interacting with git. ; Returns the list of branches in the current workspace. The head of ; the list will be the current branch, followed by the other ; workspaces in the order in which they were returned from 'git branch'. (define (git-list-branches) (define (process-branch str) (cond ((starts-with str "* ") (list #t (substring str 2 (string-length str)))) ((starts-with str " ") (list #f (substring str 2 (string-length str)))) (else '()))) (define (is-active e) (car e)) (define (is-inactive e) (not (is-active e))) (glog "Listing branches") (let* ((output (run/strings (git branch))) (parts (map process-branch output))) (if (eq? parts '()) (fail "Error running 'git branch' in '" (cwd) "'.")) (let ((current (cadr (find is-active parts))) (others (map cadr (filter is-inactive parts)))) (cons current others)))) ; Returns the string name of the current git branch. (define (git-current-branch) (car (git-list-branches))) ; Returns true iff there are outstanding changes to files in the current ; workspace. Untracked files are ignored. (define (git-has-outstanding-changes?) (define (is-modified? line) (not (starts-with line "??"))) (let* ((output (run/strings (git status -s))) (any-modified (any is-modified? output))) any-modified)) ; Returns the name of the config that tracks whether a pull request exists for ; the given branch. (define (git-pull-request-config-name branch) (string-append "branch." branch ".pull-request")) ; Returns #t if a pull request has been successfully created for the given ; branch. (define (git-has-pull-request? branch) (let* ((config (git-pull-request-config-name branch)) (value (run/strings (git config --local --get ,config)))) (not (null? value)))) ; Creates a marker in the given git branch that causes git-has-pull-request? ; to return #t in the future. (define (git-mark-has-pull-request branch) (let ((config (git-pull-request-config-name branch))) (run (git config --local --add ,config yes)))) ; Creates a location that represents the git branch with the given name. (define (@git-branch target) (let ((origin (git-current-branch))) (define (do-before) (run (git checkout ,target))) (define (run-thunk thunk) (thunk)) (define (do-after) (run (git checkout ,origin))) (list do-before run-thunk do-after)))
false
52dab19caf875989ed1df9b944f3f1ad79cc8d1d
defeada37d39bca09ef76f66f38683754c0a6aa0
/System.Data/system/data/common/db-provider-factories-configuration-handler.sls
eef813c1b777ba0764c21a9dbad8f8b2c88c9c6b
[]
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
844
sls
db-provider-factories-configuration-handler.sls
(library (system data common db-provider-factories-configuration-handler) (export new is? db-provider-factories-configuration-handler? create) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Data.Common.DbProviderFactoriesConfigurationHandler a ...))))) (define (is? a) (clr-is System.Data.Common.DbProviderFactoriesConfigurationHandler a)) (define (db-provider-factories-configuration-handler? a) (clr-is System.Data.Common.DbProviderFactoriesConfigurationHandler a)) (define-method-port create System.Data.Common.DbProviderFactoriesConfigurationHandler Create (System.Object System.Object System.Object System.Xml.XmlNode)))
true
b9481860c9d9649f680c952dcdc8c4507511db95
665da87f9fefd8678b0635e31df3f3ff28a1d48c
/srfi/test-2.scm
8d7bb537ef0ab70521c01e80ada2612d12499da8
[ "MIT" ]
permissive
justinethier/cyclone
eeb782c20a38f916138ac9a988dc53817eb56e79
cc24c6be6d2b7cc16d5e0ee91f0823d7a90a3273
refs/heads/master
2023-08-30T15:30:09.209833
2023-08-22T02:11:59
2023-08-22T02:11:59
31,150,535
862
64
MIT
2023-03-04T15:15:37
2015-02-22T03:08:21
Scheme
UTF-8
Scheme
false
false
205
scm
test-2.scm
(import (scheme base) (scheme write) (scheme cyclone pretty-print) (2)) (pretty-print `( ,(and-let* ((x 1) (y 2)) (+ x y)) ,(and-let* ((x 1) (y 2) (#f)) (+ x y)) ))
false
c7a67af22c2bd48ae61eab48114f3c00a9f29361
a74932f6308722180c9b89c35fda4139333703b8
/edwin48/notify.scm
d9bd7e2502e921b12604b6ffb65791d6b34aa036
[]
no_license
scheme/edwin48
16b5d865492db5e406085e8e78330dd029f1c269
fbe3c7ca14f1418eafddebd35f78ad12e42ea851
refs/heads/master
2021-01-19T17:59:16.986415
2014-12-21T17:50:27
2014-12-21T17:50:27
1,035,285
39
10
null
2022-02-15T23:21:14
2010-10-29T16:08:55
Scheme
UTF-8
Scheme
false
false
6,754
scm
notify.scm
#| -*-Scheme-*- $Id: notify.scm,v 1.27 2008/01/30 20:02:04 cph Exp $ Copyright (C) 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Massachusetts Institute of Technology This file is part of MIT/GNU Scheme. MIT/GNU Scheme is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. MIT/GNU Scheme is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MIT/GNU Scheme; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. |# ;;;; Mode-line notifications (e.g. presence of mail, load average) (define-variable notify-show-time "If true, the notifier displays the current time." #t boolean?) (define (notifier:time) (let ((time (get-decoded-time))) (let ((hour (decoded-time/hour time)) (minute (decoded-time/minute time))) (string-append (write-to-string (cond ((zero? hour) 12) ((< hour 13) hour) (else (- hour 12)))) (if (< minute 10) ":0" ":") (write-to-string minute) (if (< hour 12) "am" "pm"))))) (define-variable notify-show-date "If true, the notifier displays the current date." #f boolean?) (define (notifier:date) (let ((time (get-decoded-time))) (string-append (vector-ref '#("Mon" "Tue" "Wed" "Thu" "Fri" "Sat" "Sun") (decoded-time/day-of-week time)) (vector-ref '#("??" " Jan " " Feb " " Mar " " Apr " " May " " Jun " " Jul " " Aug " " Sep " " Oct " " Nov " " Dec ") (decoded-time/month time)) (write-to-string (decoded-time/day time))))) (define-variable notify-show-load "If true, the notifier displays the load average." #f boolean?) (define (notifier:load-average) (let ((temporary-buffer (temporary-buffer "*uptime*"))) (let ((start (buffer-start temporary-buffer))) (shell-command #f start #f #f "uptime") (let ((result (if (re-search-forward ".*load average:[ ]*\\([0-9.]*\\)," start (buffer-end temporary-buffer)) (extract-string (re-match-start 1) (re-match-end 1)) ""))) (kill-buffer temporary-buffer) result)))) (define-variable notify-show-mail "If true, the notifier displays your mail status." #t boolean?) (define-variable notify-mail-present "A string to be displayed in the modeline when mail is present. Ignored if notify-show-mail is false." "Mail" string?) (define-variable notify-mail-not-present "A string to be displayed in the modeline when mail is not present. Ignored if notify-show-mail is false." "" string?) (define-variable mail-notify-directory "Directory in which MAIL-NOTIFY checks for mail." #f (lambda (object) (or (not object) (file-directory? object)))) (define (notifier:mail-present) (if (not (ref-variable mail-notify-directory)) (begin (guarantee-rmail-variables-initialized) (set-variable! mail-notify-directory rmail-spool-directory))) (if (let ((pathname (merge-pathnames (ref-variable mail-notify-directory) (current-user-name)))) (and (file-exists? pathname) (> (file-length pathname) 0))) (ref-variable notify-mail-present) (ref-variable notify-mail-not-present))) (define (notifier:set-mail-string! string) ;; STRING is either #F, meaning use the internal mail notifier, or a ;; string. A null string means no mail, and a non-null string means ;; new mail is available. (without-interrupts (lambda () (set! override-notifier-mail-string string) (if (not notifier-thread-registration) (set-variable! global-mode-string string #f)) (global-window-modeline-event!)))) (define-variable notify-interval "How often the notifier updates the modeline, in seconds." 60 exact-nonnegative-integer?) (define notifier-elements (list (cons (ref-variable-object notify-show-date) notifier:date) (cons (ref-variable-object notify-show-time) notifier:time) (cons (ref-variable-object notify-show-load) notifier:load-average))) (define (notifier:get-string window) window (string-append-separated notifier-element-string (if override-notifier-mail-string (if (string-null? override-notifier-mail-string) (ref-variable notify-mail-not-present) (ref-variable notify-mail-present)) notifier-mail-string))) (define (update-notifier-strings! element mail) (set! notifier-element-string element) (set! notifier-mail-string mail) (global-window-modeline-event!)) (define notifier-element-string "") (define notifier-mail-string "") (define override-notifier-mail-string #f) (define mail-notify-hook-installed? #f) (define notifier-thread-registration #f) (define-command run-notifier "Run the notifier. The notifier maintains a simple display in the modeline, which can show various things including time, load average, and mail status." () (lambda () (if (and (not mail-notify-hook-installed?) (command-defined? rmail)) (begin (add-event-receiver! (ref-variable rmail-new-mail-hook) (lambda () (update-notifier-strings! notifier-element-string (if (ref-variable notify-show-mail) (ref-variable notify-mail-not-present) "")))) (set! mail-notify-hook-installed? #t) unspecific)) ((ref-command kill-notifier)) (set-variable! global-mode-string `("" ,notifier:get-string)) (set! notifier-thread-registration (start-standard-polling-thread (* (ref-variable notify-interval #f) 1000) notifier)) unspecific)) (define (notifier) (update-notifier-strings! (reduce-right string-append-separated "" (map (lambda (element) (if (and (car element) (variable-value (car element))) ((cdr element)) "")) notifier-elements)) (if (and mail-notify-hook-installed? (ref-variable notify-show-mail)) (notifier:mail-present) "")) #t) (define-command kill-notifier "Kill the current notifier, if any." () (lambda () (without-interrupts (lambda () (if notifier-thread-registration (begin (stop-standard-polling-thread notifier-thread-registration) (set! notifier-thread-registration #f) unspecific)))) (update-notifier-strings! "" "") (set-variable! global-mode-string override-notifier-mail-string #f)))
false
aab0a30e61d99cdfea5386a368cfa5635cfddc40
abc7bd420c9cc4dba4512b382baad54ba4d07aa8
/src/parser/wavescript/lang/reader.ss
0f478de97880d753374784517aa219f4e8667d7c
[ "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
1,693
ss
reader.ss
(module reader syntax/module-reader wavescript #:read ws-read #:read-syntax ws-read-syntax #:whole-body-readers? #t (require "../../regiment_parser.ss") ;(require "main.sls") ;(require (scheme pretty)) (require scheme/pretty) (define (ws-read-syntax file port) (source-position-tracking #t) (let ((expr `((require (except-in rnrs error + - * / or and) "../ws/sim/wavescript_sim_library_push.sls" "../ws/util/streams.sls" scheme/pretty (for-syntax ;"../ws/sim/wavescript_sim_library_push.sls" scheme/pretty) ;(for-meta 2 "../ws/sim/wavescript_sim_library_push.sls") ) (let () (begin ;(printf "Executing module code. And got sim binding: ~a ~a\n" wsequal? (wscase #f)) (reset-wssim-state!) (for-each print (car (values->list (stream-take 10 ;browse-stream ;wsint:direct-stream (run-stream-query (WSCOMPILE_MACRO ,(ws-parse-port port file))))))) (void)))))) (if (file-exists? "DEBUG.ss") (delete-file "DEBUG.ss") (void)) (with-output-to-file "DEBUG.ss" (lambda () (pretty-print expr))) (datum->syntax #f expr) ) ) (define (ws-read port) (syntax->datum (ws-read-syntax "UNKNOWN_FILE" port))) ) ;;[p ',(ws-parse-port port file)] #| ;; Make all the pairs mutable: (define (gross-hack sexp) (cond [(pair? sexp) (mcons (gross-hack (car sexp)) (gross-hack (cdr sexp)))] [(vector? sexp) (vector-map gross-hack sexp)] [else sexp])) (pretty-print (gross-hack p)) (for-each pretty-print (mlist->list (mcar (values->list (stream-take 10 (wsint (gross-hack p) '())))))) |#
false
f86936b8ffcbcce3bf6a0b4f7292aaae5e60763a
4fd95c081ccef6afc8845c94fedbe19699b115b6
/chapter_3/3.6.scm
67a25eef690e6b0c2e66e85cbc88680a713257fa
[ "MIT" ]
permissive
ceoro9/sicp
61ff130e655e705bafb39b4d336057bd3996195d
7c0000f4ec4adc713f399dc12a0596c770bd2783
refs/heads/master
2020-05-03T09:41:04.531521
2019-08-08T12:14:35
2019-08-08T12:14:35
178,560,765
1
0
null
null
null
null
UTF-8
Scheme
false
false
1,129
scm
3.6.scm
(define (rand-update x) (define random-values (list 4 7 6 8 9 5 1 2 3)) (define (find-next-value c-values) (cond ((null? c-values) (error "Randomizer does not support such number")) ((and (= (car c-values) x) (null? (cdr c-values))) (car random-values)) ((= (car c-values) x) (cadr c-values)) (else (find-next-value (cdr c-values))))) (find-next-value random-values)) (define rand (let ((rand-value 4)) (lambda (op) (cond ((eq? op 'generate) (begin (set! rand-value (rand-update rand-value)) rand-value)) ((eq? op 'reset) (lambda (new-value) (set! rand-value new-value))))))) (display (rand 'generate)) (newline) (display (rand 'generate)) (newline) (display (rand 'generate)) ((rand 'reset) 5) (newline) (newline) (newline) (display (rand 'generate)) (newline) (display (rand 'generate)) (newline) (display (rand 'generate))
false
d081671da15495f50fb4fd9c143756fbb548f307
ffd6cdc49ba0aa09366cf3091d2a657461d388cf
/2.ss
e6702bd3eec4b428af1bb768a7c727275fa9c8bb
[]
no_license
hernanre/csse304-ProgrammingLanguageConcept
cba83977be2eff7dbf39da8eec483801ce939930
14cbbd604cd7cdb421d39741e96a7fd003b2579b
refs/heads/master
2022-01-26T13:20:51.590843
2018-10-02T23:04:35
2018-10-02T23:04:35
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,668
ss
2.ss
;Linjie Zha A02 ;Problem1 (define fact (lambda (n) (cond [(zero? n) 1] [else (* n (fact (- n 1)))]))) (define choose (lambda (n k) (/ (fact n) (* (fact k) (fact (- n k)))))) ;Problem2 (define range (lambda (m n) (cond [(<= n m) '()] [else (cons m (range (+ m 1) n))]))) ;Problem3 (define set? (lambda (ls) (cond [(null? ls) #t] [(member (car ls) (cdr ls)) #f] [else (set? (cdr ls))]))) ;Problem4 (define sum-of-squares (lambda (lon) (cond [(null? lon) 0] [else (+ (* (car lon) (car lon)) (sum-of-squares (cdr lon)))]))) ;Problem5 (define make-vec-from-points (lambda (p1 p2) (cond [(null? p1) '()] [else (cons (- (car p2) (car p1)) (make-vec-from-points (cdr p1) (cdr p2)))]))) ;Problem6 (define dot-product (lambda (v1 v2) (cond [(null? v1) 0] [else (+ (* (car v1) (car v2)) (dot-product (cdr v1) (cdr v2)))]))) ;Problem7 (define vec-length (lambda (v) (sqrt (sum-of-squares v)))) ;Problem8 (define distance (lambda (p1 p2) (vec-length (make-vec-from-points p1 p2)))) ;Problem9 (define cross-product (lambda (v1 v2) (list (- (* (cadr v1) (caddr v2)) (* (caddr v1) (cadr v2))) (- (* (caddr v1) (car v2)) (* (car v1) (caddr v2))) (- (* (car v1) (cadr v2)) (* (cadr v1) (car v2)))))) ;Problem10 (define parallel? (lambda (v1 v2) (equal? '(0 0 0) (cross-product v1 v2)))) ;Problem11 (define collinear? (lambda (p1 p2 p3) (equal? 0 (vec-length (cross-product (make-vec-from-points p1 p2) (make-vec-from-points p1 p3))))))
false
255a307091974cb13acde6e91294a6b5bb304d6b
defeada37d39bca09ef76f66f38683754c0a6aa0
/System.Data/system/data/common/dbcomparer-factory.sls
137d5cba398dea5e1377592c1963dffd7a066a08
[]
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
604
sls
dbcomparer-factory.sls
(library (system data common dbcomparer-factory) (export new is? dbcomparer-factory? get-comparer) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Data.Common.DBComparerFactory a ...))))) (define (is? a) (clr-is System.Data.Common.DBComparerFactory a)) (define (dbcomparer-factory? a) (clr-is System.Data.Common.DBComparerFactory a)) (define-method-port get-comparer System.Data.Common.DBComparerFactory GetComparer (static: System.Collections.IComparer System.Type System.Boolean)))
true
f760a795ee9559f78eceb317f325aeef26053711
309e1d67d6ad76d213811bf1c99b5f82fa2f4ee2
/A06.ss
2aa102805331133921d1653be13240287a707925
[]
no_license
lix4/CSSE304-Programming-Language-Concept-Code
d8c14c18a1baa61ab5d3df0b1ac650bdebc59526
dd94262865d880a357e85f6def697661e11c8e7a
refs/heads/master
2020-08-06T02:50:53.307301
2016-11-12T03:03:56
2016-11-12T03:03:56
73,528,000
1
1
null
null
null
null
UTF-8
Scheme
false
false
2,448
ss
A06.ss
;;Xiwen Li ;;Assignment 06 ;;1 (define curry2 (lambda (x) (lambda (y) (lambda (z) (x y z))))) ;;2 (define curried-compose (lambda (proc1) (lambda (proc2) (lambda (obj) (proc1 (proc2 obj)))))) ;;3 (define compose (lambda list-of-functions (lambda (obj) (compose-rec (reverse list-of-functions) obj)))) (define compose-rec (lambda (functions obj) (if (null? (cdr functions)) ((car functions) obj) (compose-rec (cdr functions) ((car functions) obj))))) ;;4 (define make-list-c (lambda (n) (lambda (element) (let in-list ([index 0]) (if (= index n) '() (cons element (in-list (+ index 1)))))))) ;;5 (define let->application (lambda (ls) (let ([para (map car (cadr ls))] [body (caddr ls)] [vals (map cadr (cadr ls))]) (cons (list 'lambda para body) vals)))) ;;6 (define let*->let (lambda (ls) (let ([vars (map car (cadr ls))] [body (caddr ls)] [vals (map cadr (cadr ls))]) (let*->let-rec vars vals body)))) (define let*->let-rec (lambda (vars vals body) (if (null? vars) body (list 'let (list (list (car vars) (car vals))) (let*->let-rec (cdr vars) (cdr vals) body))))) ;;7 (define filter-in (lambda (pred? lst) (cond [(null? lst) '()] [(pred? (car lst)) (cons (car lst) (filter-in pred? (cdr lst)))] [else (filter-in pred? (cdr lst))]))) (define filter-out (lambda (pred? lst) (cond [(null? lst) '()] [(pred? (car lst)) (filter-out pred? (cdr lst))] [else (cons (car lst) (filter-out pred? (cdr lst)))]))) (define sort-list-of-symbols (lambda (ls) (map string->symbol (sort string<? (map symbol->string ls))))) (define invert (lambda (ls) (if (null? ls) '() (cons (reverse (car ls)) (invert (cdr ls)))))) (define vector-index (lambda (pred vector) (vector-index-rec pred (vector->list vector) 0))) (define vector-index-rec (lambda (pred ls index) (cond [(null? ls) #f] [(pred (car ls)) index] [else (vector-index-rec pred (cdr ls) (+ index 1))]))) (define ribassoc (lambda (s los v fail-value) (cond [(null? los) fail-value] [(list-index s los 0) (vector-ref v (list-index s los 0))] [else (ribassoc s (cdr los) v fail-value)]))) (define list-index (lambda (tar ls index) (cond [(null? ls) #f] [(equal? tar (car ls)) index] [else (list-index tar (cdr ls) (+ index 1))])))
false
4bbf3538f662d9c656797a89965f8149d4b63e89
174072a16ff2cb2cd60a91153376eec6fe98e9d2
/chap2-5/2-93-94-test.scm
d8f37ac3c06454754f0fbaf57d7c868a0eac61fa
[]
no_license
Wang-Yann/sicp
0026d506ec192ac240c94a871e28ace7570b5196
245e48fc3ac7bfc00e586f4e928dd0d0c6c982ed
refs/heads/master
2021-01-01T03:50:36.708313
2016-10-11T10:46:37
2016-10-11T10:46:37
57,060,897
1
0
null
null
null
null
UTF-8
Scheme
false
false
906
scm
2-93-94-test.scm
(load "raw-apply-generic-2.scm") (load "polynomial-package.scm") (install-polynomial-package) (load "coercion-package.scm") (install-coercion-package) (define (negate x) (apply-generic 'negate x)) (define (add x y) (apply-generic 'add x y)) (define (sub x y) (apply-generic 'sub x y)) (define (mul x y) (apply-generic 'mul x y)) (define (div x y) (apply-generic 'div x y)) (define (=zero? x) (apply-generic '=zero? x )) (define (greatest-common-divisor a b) (apply-generic 'greatest-common-divisor a b)) ;;2-93+++ (define A (make-polynomial 'x (list (list 10 20) (list 3 2) (list 2 1)))) (define B (make-polynomial 'x '((9 2) (4 1) (0 6)))) (define C (make-polynomial 'x '((9 3) (4 3) (0 4)))) (define p1 (make-polynomial 'x '((4 1) (3 -1) (2 -2) (1 2)))) (define p2 (make-polynomial 'x '((3 1) (1 -1)))) (define g-c-d (greatest-common-divisor p1 p2)) (define g-c-d2 (greatest-common-divisor B C))
false
5099823f78906150ca0c933e4d2424edc9b7dddc
b7ec5209446e33ec4b524c66c4d52ff852e46ae4
/Ressources/interface.scm
6f19e438f3702104c9f3576191a054b5d4ba5059
[]
no_license
antjacquemin/physics
a2751f69ee0a54bbb17e46c6bbb2d3b478776136
fd0444c838d097c795fdb1af3a8f3507e810fae5
refs/heads/master
2023-03-31T23:58:49.022201
2020-07-13T09:33:35
2020-07-13T09:33:35
279,257,815
1
0
null
null
null
null
UTF-8
Scheme
false
false
159,327
scm
interface.scm
;***************************************************** ; PROJET PHYSICS ; ANNEE 2008 ; PROGRAMMEURS : F. CORLAIS & A. JACQUEMIN ; MAJ : 27.04.2008 ;***************************************************** ;***************************************************** ; "interface.scm" ;ce fichier gère toute l'interface graphique du soft ;***************************************************** ;***************************************************** ; LIBRAIRIES NECESSAIRES ;***************************************************** (require (lib "texpict.ss" "texpict") ; pour les images (lib "sendurl.ss" "net") (lib "process.ss")) ; pour le lien Internet ;***************************************************** ; FICHIERS A CHARGER ;***************************************************** (load (build-path (current-directory) "Ressources" "collisions.scm")) (load (build-path (current-directory) "Ressources" "objet.scm")) ;***************************************************** ; METHODES PRIVEES ;***************************************************** ; change-fils : area-container% x list (of subwindows%) -> void ; Remplace les fils courants du père conteneur par la nouvelle liste de fils (define (change-fils father Lchildren) (for-each (lambda (child) (send father delete-child child)) (send father get-children)) (for-each (lambda (child) (send father add-child child)) Lchildren)) ; couleur : string -> color% ; Crée une couleur (define (couleur str) (make-object color% str)) ;***************************************************** ; VARIABLES PRIVEES ;***************************************************** (define PI/2 (/ pi 2)) ;; Pour le dessin (define POLYGONE (polygone-nul)) ; Polygone pour le dessin (define AFFICHE_EC #f) ; Indicateur de l'affichage de l'enveloppe convexe (define AFFICHE_CM #f) ; Indicateur de l'affichage du centre de masse (define COLOR_POLY (couleur "black")) ; Couleur du polygone (define COLOR_EC (couleur "blue")) ; Couleur de l'enveloppe convexe (define COLOR_CM (couleur "red")) ; Couleur du centre de masse (define COLOR_BACK (couleur "azure")) ; Couleur de fond du canvas (define IND_CLIC #f) ; Indicateur de clic enfoncé dans le canvas (define COMPT 0) ; Compteur de points (modulo 2) pour le tracé (define IND_ACTION #f) ; Indicateur d'animation (via le bouton d'activation) ;; Pour les exemples (define POLYGONE_EXS (polygone-nul)) ; Polygone pour les exemples (define ANGLE PI/2) ; Angle de l'exemple en radians (define LONG_BAR 150) ; Longueur de la barre (define TAILLE_INF 4) ; Taille de la boucle infinie (define TAILLE_ELL 100) ; Taille de l'ellipse (define TORSADE_ESC 8) ; Torsade de l'escargot (define NB_BRAN_STAR 12) ; Nombre de branches de l'étoile (define TAILLE_HALT 3) ; Taille de la boule du bas de l'haltère (define NB_COTES_POLYREG 5) ; Nombre de côtés du polygone régulier (define COURB_QUA 50) ; Courbure du quadrillage (define CART_X "(expt (sin t) 3)") ; Paramétrisation cartésienne selon x en t (define CART_Y "(- (cos t) (expt (cos t) 4))") ; Paramétrisation cartésienne selon y en t (define CART_INF "(- pi)") ; Borne inférieure de la paramétrisation cartésienne (define CART_SUP "pi") ; Borne supérieure de la paramétrisation cartésienne (define POL_RHO "(+ (- (exp (cos t)) (* 2 (cos (* 4 t)))) (expt (sin (/ t 12)) 5))") ; Paramétrisation polaire selon rho en t (define POL_INF "(- pi)") ; Borne inférieure de la paramétrisation polaire (define POL_SUP "pi") ; Borne supérieure de la paramétrisation polaire ;; Pour les objets (define AFFICHE_OBJ_CM #f) ; Indicateur de l'affichage du centre de masse (define COLOR_OBJ_BACK (make-object color% 194 116 31)) ; Couleur de fond du canvas objet (define M1_2B 1) ; Masse de la première boule dans Deux boules (define M2_2B 1) ; Masse de la seconde boule dans Deux boules (define V1_2B (make-vect -5 0)) ; Vitesse de la première boule dans Deux boules (define V2_2B (make-vect 0 0)) ; Vitesse de la seconde boule dans Deux boules (define R1_2B 60) ; Rayon de la première boule dans Deux boules (define R2_2B 60) ; Rayon de la seconde boule dans Deux boules (define NB_BAL 20) ; Nombre de boules dans Boules multiples (define M_GRAV 1) ; Masse de la boule dans Gravite (define V_GRAV (make-vect -1 0)) ; Vitesse de la boule dans Gravite (define R_GRAV 50) ; Rayon de la boule dans Gravite (define NB_PEND 5) ; Nombre de boules dans Pendule ;***************************************************** ; STRUCTURE DE L'INTERFACE GRAPHIQUE ;***************************************************** ; Fenêtre principale (define FRAME1 (new frame% (label "PHYSICS") (style '(metal)))) ; affichage métallisé (seulement sur MAC OS X) ;(stretchable-height #f))) ; Panneau horizontal (define HPANEL1 (new horizontal-panel% (parent FRAME1))) ; Panneau vertical contenant les règlages (define VPANEL1 (new vertical-panel% (parent HPANEL1) (alignment '(center center)))) ; Panneau vertical contenant le canvas (define VPANEL2 (new vertical-panel% (parent HPANEL1) (alignment '(center center)))) ;***************************************************** ; GESTION DES MENUS ;***************************************************** ;;;; Barre des menus (define BARRE_MENU (new menu-bar% (parent FRAME1))) ;;; Menus ;;; Menu Fichier (define MENU_FICH (new menu% (label "Fichier") (parent BARRE_MENU) (help-string "Lance une démo"))) ;;; Menu Affichage (define MENU_AFF (new menu% (label "Affichage") (parent BARRE_MENU))) ;;; Menu Aide (define MENU_AIDE (new menu% (label "Aide") (parent BARRE_MENU))) ;; Sous-menus du menu Fichier ;; Sous-menu Menu (define FICH_MENU (new menu-item% (label "Menu") (parent MENU_FICH) (shortcut #\m) (callback (lambda (item evt) (send BITMAP-DC set-background COLOR_BACK) (set! IND_ACTION #f) (send AFF_TRA enable #t) (send AFF_CM enable #t) (send AFF_EC enable #t) (send AFF_FOND set-label "Changer la couleur de fond pour les sections Dessin et Exemples") (change-fils VPANEL1 (list GPANEL_INIT_SELECT GPANEL_INIT_DOC)) (change-fils VPANEL2 (list CANVAS_INIT)))) (help-string "Retourne au menu"))) ;; Sous-menu Dessin (define FICH_DRAW (new menu-item% (label "Dessin") (parent MENU_FICH) (shortcut #\d) (callback (lambda (item evt) (send BITMAP-DC set-background COLOR_BACK) (set! GRAVITE (make-vect 0 0.01)) (send SLIDER_DRAW_G set-value 100) (set! E 0.95) (send SLIDER_DRAW_E set-value 95) (set! POLYGONE (polygone-nul)) (set! AFFICHE_EC #f) (send CBOX_DRAW_EC set-value #f) (set! AFFICHE_CM #f) (send CBOX_DRAW_CM set-value #f) (set! COMPT 0) (set! IND_ACTION #f) (send BUTTON_DRAW_ACTION set-label "Go") (send CANVAS_DRAW on-paint) (send AFF_TRA enable #t) (send AFF_CM enable #t) (send AFF_EC enable #t) (send AFF_FOND set-label "Changer la couleur de fond pour les sections Dessin et Exemples") (change-fils VPANEL1 (list GPANEL_DRAW_VISU GPANEL_DRAW_REG VPANEL_DRAW_BUTS)) (change-fils VPANEL2 (list CANVAS_DRAW)))) (help-string "Dessine ta propre figure et regarde la réagir!"))) ;; Sous-menu Exemples (define FICH_EXS (new menu% (label "Exemples") (parent MENU_FICH) (help-string "Observe différents exemples déjà préparés"))) ; Sous-menus du menu Exemples ; Sous-menu Barre (define EXS_BAR (new menu-item% (label "Barre") (parent FICH_EXS) (shortcut #\e) (callback (lambda (item evt) (send BITMAP-DC set-background COLOR_BACK) (set! GRAVITE (make-vect 0 0.01)) (send SLIDER_EXS_G set-value 100) (set! E 0.95) (send SLIDER_EXS_E set-value 95) (set! ANGLE PI/2) (send SLIDER_EXS_ANGLE set-value 90) (set! LONG_BAR 150) (send SLIDER_EXS_BAR_LONG set-value 150) (set! AFFICHE_EC #f) (send CBOX_EXS_EC set-value #f) (set! AFFICHE_CM #f) (send CBOX_EXS_CM set-value #f) (set! IND_ACTION #f) (send BUTTON_EXS_ACTION set-label "Go") (send LBOX_EXS set-selection 0) (send RBOX_EXS_GRAV set-selection 0) (load (build-path "Exemples" "Barre.scm")) (send CANVAS_EXS on-paint) (send AFF_TRA enable #t) (send AFF_CM enable #t) (send AFF_EC enable #t) (send AFF_FOND set-label "Changer la couleur de fond pour les sections Dessin et Exemples") (send BUTTON_EXS_ACTION enable #t) (change-fils GPANEL_EXS_SELECT (list LBOX_EXS RBOX_EXS_GRAV)) (send SLIDER_EXS_BAR_LONG enable #t) (send SLIDER_EXS_ANGLE enable #t) (change-fils GPANEL_EXS_REG (list SLIDER_EXS_G SLIDER_EXS_E SLIDER_EXS_ANGLE SLIDER_EXS_BAR_LONG)) (change-fils VPANEL1 (list GPANEL_EXS_SELECT GPANEL_EXS_VISU GPANEL_EXS_REG VPANEL_EXS_BUTS)) (change-fils VPANEL2 (list CANVAS_EXS)))))) ; Sous-menu Boucle infinie (define EXS_INF (new menu-item% (label "Boucle infinie") (parent FICH_EXS) (callback (lambda (item evt) (send BITMAP-DC set-background COLOR_BACK) (set! GRAVITE (make-vect 0 0.01)) (send SLIDER_EXS_G set-value 100) (set! E 0.95) (send SLIDER_EXS_E set-value 95) (set! ANGLE PI/2) (send SLIDER_EXS_ANGLE set-value 90) (set! TAILLE_INF 4) (send SLIDER_EXS_INF_TAILLE set-value 4) (set! AFFICHE_EC #f) (send CBOX_EXS_EC set-value #f) (set! AFFICHE_CM #f) (send CBOX_EXS_CM set-value #f) (set! IND_ACTION #f) (send BUTTON_EXS_ACTION set-label "Go") (send LBOX_EXS set-selection 0) (send RBOX_EXS_GRAV set-selection 1) (load (build-path "Exemples" "Boucle infinie.scm")) (send CANVAS_EXS on-paint) (send AFF_TRA enable #t) (send AFF_CM enable #t) (send AFF_EC enable #t) (send AFF_FOND set-label "Changer la couleur de fond pour les sections Dessin et Exemples") (send BUTTON_EXS_ACTION enable #t) (change-fils GPANEL_EXS_SELECT (list LBOX_EXS RBOX_EXS_GRAV)) (send SLIDER_EXS_INF_TAILLE enable #t) (send SLIDER_EXS_ANGLE enable #t) (change-fils GPANEL_EXS_REG (list SLIDER_EXS_G SLIDER_EXS_E SLIDER_EXS_ANGLE SLIDER_EXS_INF_TAILLE)) (change-fils VPANEL1 (list GPANEL_EXS_SELECT GPANEL_EXS_VISU GPANEL_EXS_REG VPANEL_EXS_BUTS)) (change-fils VPANEL2 (list CANVAS_EXS)))))) ; Sous-menu Ellipse (define EXS_ELL (new menu-item% (label "Ellipse") (parent FICH_EXS) (callback (lambda (item evt) (send BITMAP-DC set-background COLOR_BACK) (set! GRAVITE (make-vect 0 0.01)) (send SLIDER_EXS_G set-value 100) (set! E 0.95) (send SLIDER_EXS_E set-value 95) (set! ANGLE PI/2) (send SLIDER_EXS_ANGLE set-value 90) (set! TAILLE_ELL 100) (send SLIDER_EXS_ELL_TAILLE set-value 100) (set! AFFICHE_EC #f) (send CBOX_EXS_EC set-value #f) (set! AFFICHE_CM #f) (send CBOX_EXS_CM set-value #f) (set! IND_ACTION #f) (send BUTTON_EXS_ACTION set-label "Go") (send LBOX_EXS set-selection 0) (send RBOX_EXS_GRAV set-selection 2) (load (build-path "Exemples" "Ellipse.scm")) (send CANVAS_EXS on-paint) (send AFF_TRA enable #t) (send AFF_CM enable #t) (send AFF_EC enable #t) (send AFF_FOND set-label "Changer la couleur de fond pour les sections Dessin et Exemples") (send BUTTON_EXS_ACTION enable #t) (change-fils GPANEL_EXS_SELECT (list LBOX_EXS RBOX_EXS_GRAV)) (send SLIDER_EXS_ELL_TAILLE enable #t) (send SLIDER_EXS_ANGLE enable #t) (change-fils GPANEL_EXS_REG (list SLIDER_EXS_G SLIDER_EXS_E SLIDER_EXS_ANGLE SLIDER_EXS_ELL_TAILLE)) (change-fils VPANEL1 (list GPANEL_EXS_SELECT GPANEL_EXS_VISU GPANEL_EXS_REG VPANEL_EXS_BUTS)) (change-fils VPANEL2 (list CANVAS_EXS)))))) ; Sous-menu Escargot (define EXS_ESC (new menu-item% (label "Escargot") (parent FICH_EXS) (callback (lambda (item evt) (send BITMAP-DC set-background COLOR_BACK) (set! GRAVITE (make-vect 0 0.01)) (send SLIDER_EXS_G set-value 100) (set! E 0.95) (send SLIDER_EXS_E set-value 95) (set! ANGLE PI/2) (send SLIDER_EXS_ANGLE set-value 90) (set! TORSADE_ESC 8) (send SLIDER_EXS_ESC_TORSADE set-value 8) (set! AFFICHE_EC #f) (send CBOX_EXS_EC set-value #f) (set! AFFICHE_CM #f) (send CBOX_EXS_CM set-value #f) (set! IND_ACTION #f) (send BUTTON_EXS_ACTION set-label "Go") (send LBOX_EXS set-selection 0) (send RBOX_EXS_GRAV set-selection 3) (load (build-path "Exemples" "Escargot.scm")) (send CANVAS_EXS on-paint) (send AFF_TRA enable #t) (send AFF_CM enable #t) (send AFF_EC enable #t) (send AFF_FOND set-label "Changer la couleur de fond pour les sections Dessin et Exemples") (send BUTTON_EXS_ACTION enable #t) (change-fils GPANEL_EXS_SELECT (list LBOX_EXS RBOX_EXS_GRAV)) (send SLIDER_EXS_ESC_TORSADE enable #t) (send SLIDER_EXS_ANGLE enable #t) (change-fils GPANEL_EXS_REG (list SLIDER_EXS_G SLIDER_EXS_E SLIDER_EXS_ANGLE SLIDER_EXS_ESC_TORSADE)) (change-fils VPANEL1 (list GPANEL_EXS_SELECT GPANEL_EXS_VISU GPANEL_EXS_REG VPANEL_EXS_BUTS)) (change-fils VPANEL2 (list CANVAS_EXS)))))) ; Sous-menu Etoile (define EXS_STAR (new menu-item% (label "Etoile") (parent FICH_EXS) (callback (lambda (item evt) (send BITMAP-DC set-background COLOR_BACK) (set! GRAVITE (make-vect 0 0.01)) (send SLIDER_EXS_G set-value 100) (set! E 0.95) (send SLIDER_EXS_E set-value 95) (set! ANGLE PI/2) (send SLIDER_EXS_ANGLE set-value 90) (set! NB_BRAN_STAR 12) (send SLIDER_EXS_STAR_NB_BRAN set-value 6) (set! AFFICHE_EC #f) (send CBOX_EXS_EC set-value #f) (set! AFFICHE_CM #f) (send CBOX_EXS_CM set-value #f) (set! IND_ACTION #f) (send BUTTON_EXS_ACTION set-label "Go") (send LBOX_EXS set-selection 0) (send RBOX_EXS_GRAV set-selection 4) (load (build-path "Exemples" "Etoile.scm")) (send CANVAS_EXS on-paint) (send AFF_TRA enable #t) (send AFF_CM enable #t) (send AFF_EC enable #t) (send AFF_FOND set-label "Changer la couleur de fond pour les sections Dessin et Exemples") (send BUTTON_EXS_ACTION enable #t) (change-fils GPANEL_EXS_SELECT (list LBOX_EXS RBOX_EXS_GRAV)) (send SLIDER_EXS_STAR_NB_BRAN enable #t) (send SLIDER_EXS_ANGLE enable #t) (change-fils GPANEL_EXS_REG (list SLIDER_EXS_G SLIDER_EXS_E SLIDER_EXS_ANGLE SLIDER_EXS_STAR_NB_BRAN)) (change-fils VPANEL1 (list GPANEL_EXS_SELECT GPANEL_EXS_VISU GPANEL_EXS_REG VPANEL_EXS_BUTS)) (change-fils VPANEL2 (list CANVAS_EXS)))))) ; Sous-menu Fleur (define EXS_FLO (new menu-item% (label "Fleur") (parent FICH_EXS) (callback (lambda (item evt) (send BITMAP-DC set-background COLOR_BACK) (set! GRAVITE (make-vect 0 0.01)) (send SLIDER_EXS_G set-value 100) (set! E 0.95) (send SLIDER_EXS_E set-value 95) (set! ANGLE PI/2) (send SLIDER_EXS_ANGLE set-value 90) (set! AFFICHE_EC #f) (send CBOX_EXS_EC set-value #f) (set! AFFICHE_CM #f) (send CBOX_EXS_CM set-value #f) (set! IND_ACTION #f) (send BUTTON_EXS_ACTION set-label "Go") (send LBOX_EXS set-selection 0) (send RBOX_EXS_GRAV set-selection 5) (load (build-path "Exemples" "Fleur.scm")) (send CANVAS_EXS on-paint) (send AFF_TRA enable #t) (send AFF_CM enable #t) (send AFF_EC enable #t) (send AFF_FOND set-label "Changer la couleur de fond pour les sections Dessin et Exemples") (send BUTTON_EXS_ACTION enable #t) (change-fils GPANEL_EXS_SELECT (list LBOX_EXS RBOX_EXS_GRAV)) (send SLIDER_EXS_ANGLE enable #t) (change-fils GPANEL_EXS_REG (list SLIDER_EXS_G SLIDER_EXS_E SLIDER_EXS_ANGLE)) (change-fils VPANEL1 (list GPANEL_EXS_SELECT GPANEL_EXS_VISU GPANEL_EXS_REG VPANEL_EXS_BUTS)) (change-fils VPANEL2 (list CANVAS_EXS)))))) ; Sous-menu Haltere (define EXS_HALT (new menu-item% (label "Haltere") (parent FICH_EXS) (callback (lambda (item evt) (send BITMAP-DC set-background COLOR_BACK) (set! GRAVITE (make-vect 0 0.01)) (send SLIDER_EXS_G set-value 100) (set! E 0.95) (send SLIDER_EXS_E set-value 95) (set! ANGLE PI/2) (send SLIDER_EXS_ANGLE set-value 90) (set! TAILLE_HALT 3) (send SLIDER_EXS_HALT_TAILLE set-value 3) (set! AFFICHE_EC #f) (send CBOX_EXS_EC set-value #f) (set! AFFICHE_CM #f) (send CBOX_EXS_CM set-value #f) (set! IND_ACTION #f) (send BUTTON_EXS_ACTION set-label "Go") (send LBOX_EXS set-selection 0) (send RBOX_EXS_GRAV set-selection 6) (load (build-path "Exemples" "Haltere.scm")) (send CANVAS_EXS on-paint) (send AFF_TRA enable #t) (send AFF_CM enable #t) (send AFF_EC enable #t) (send AFF_FOND set-label "Changer la couleur de fond pour les sections Dessin et Exemples") (send BUTTON_EXS_ACTION enable #t) (change-fils GPANEL_EXS_SELECT (list LBOX_EXS RBOX_EXS_GRAV)) (send SLIDER_EXS_ANGLE enable #t) (send SLIDER_EXS_HALT_TAILLE enable #t) (change-fils GPANEL_EXS_REG (list SLIDER_EXS_G SLIDER_EXS_E SLIDER_EXS_ANGLE SLIDER_EXS_HALT_TAILLE)) (change-fils VPANEL1 (list GPANEL_EXS_SELECT GPANEL_EXS_VISU GPANEL_EXS_REG VPANEL_EXS_BUTS)) (change-fils VPANEL2 (list CANVAS_EXS)))))) ; Sous-menu Polygone régulier (define EXS_POLYREG (new menu-item% (label "Polygone regulier") (parent FICH_EXS) (callback (lambda (item evt) (send BITMAP-DC set-background COLOR_BACK) (set! GRAVITE (make-vect 0 0.01)) (send SLIDER_EXS_G set-value 100) (set! E 0.95) (send SLIDER_EXS_E set-value 95) (set! ANGLE PI/2) (send SLIDER_EXS_ANGLE set-value 90) (set! NB_COTES_POLYREG 5) (send SLIDER_EXS_POLYREG_NB_COTES set-value 5) (set! AFFICHE_EC #f) (send CBOX_EXS_EC set-value #f) (set! AFFICHE_CM #f) (send CBOX_EXS_CM set-value #f) (set! IND_ACTION #f) (send BUTTON_EXS_ACTION set-label "Go") (send LBOX_EXS set-selection 0) (send RBOX_EXS_GRAV set-selection 7) (load (build-path "Exemples" "Polygone regulier.scm")) (send CANVAS_EXS on-paint) (send AFF_TRA enable #t) (send AFF_CM enable #t) (send AFF_EC enable #t) (send AFF_FOND set-label "Changer la couleur de fond pour les sections Dessin et Exemples") (send BUTTON_EXS_ACTION enable #t) (change-fils GPANEL_EXS_SELECT (list LBOX_EXS RBOX_EXS_GRAV)) (send SLIDER_EXS_POLYREG_NB_COTES enable #t) (send SLIDER_EXS_ANGLE enable #t) (change-fils GPANEL_EXS_REG (list SLIDER_EXS_G SLIDER_EXS_E SLIDER_EXS_ANGLE SLIDER_EXS_POLYREG_NB_COTES)) (change-fils VPANEL1 (list GPANEL_EXS_SELECT GPANEL_EXS_VISU GPANEL_EXS_REG VPANEL_EXS_BUTS)) (change-fils VPANEL2 (list CANVAS_EXS)))))) ; Sous-menu Quadrillage (define EXS_QUA (new menu-item% (label "Quadrillage") (parent FICH_EXS) (callback (lambda (item evt) (send BITMAP-DC set-background COLOR_BACK) (set! GRAVITE (make-vect 0 0.01)) (send SLIDER_EXS_G set-value 100) (set! E 0.95) (send SLIDER_EXS_E set-value 95) (set! ANGLE PI/2) (send SLIDER_EXS_ANGLE set-value 90) (set! COURB_QUA 50) (send SLIDER_EXS_QUA_COURB set-value 50) (set! AFFICHE_EC #f) (send CBOX_EXS_EC set-value #f) (set! AFFICHE_CM #f) (send CBOX_EXS_CM set-value #f) (set! IND_ACTION #f) (send BUTTON_EXS_ACTION set-label "Go") (send LBOX_EXS set-selection 0) (send RBOX_EXS_GRAV set-selection 8) (load (build-path "Exemples" "Quadrillage.scm")) (send CANVAS_EXS on-paint) (send AFF_TRA enable #t) (send AFF_CM enable #t) (send AFF_EC enable #t) (send AFF_FOND set-label "Changer la couleur de fond pour les sections Dessin et Exemples") (send BUTTON_EXS_ACTION enable #t) (change-fils GPANEL_EXS_SELECT (list LBOX_EXS RBOX_EXS_GRAV)) (send SLIDER_EXS_QUA_COURB enable #t) (send SLIDER_EXS_ANGLE enable #t) (change-fils GPANEL_EXS_REG (list SLIDER_EXS_G SLIDER_EXS_E SLIDER_EXS_ANGLE SLIDER_EXS_QUA_COURB)) (change-fils VPANEL1 (list GPANEL_EXS_SELECT GPANEL_EXS_VISU GPANEL_EXS_REG VPANEL_EXS_BUTS)) (change-fils VPANEL2 (list CANVAS_EXS)))))) ; Séparateur entre les sous-menus relevant de la gravitation et ceux relevant des chocs (define SEPARATOR_EXS (new separator-menu-item% (parent FICH_EXS))) ; Sous-menu Cercle et ellipse (define EXS_CERELL (new menu-item% (label "Cercle et ellipse") (parent FICH_EXS) (callback (lambda (item evt) (send BITMAP-DC set-background COLOR_BACK) (set! GRAVITE (make-vect 0 0)) (set! E 0.95) (send SLIDER_EXS_E set-value 95) (set! AFFICHE_EC #f) (send CBOX_EXS_EC set-value #f) (set! AFFICHE_CM #f) (send CBOX_EXS_CM set-value #f) (set! IND_ACTION #f) (send BUTTON_EXS_ACTION set-label "Go") (send LBOX_EXS set-selection 1) (send RBOX_EXS_CHOC set-selection 0) (load (build-path "Exemples" "Cercle et ellipse.scm")) (send CANVAS_EXS on-paint) (send AFF_TRA enable #t) (send AFF_CM enable #t) (send AFF_EC enable #t) (send AFF_FOND set-label "Changer la couleur de fond pour les sections Dessin et Exemples") (send BUTTON_EXS_ACTION enable #t) (change-fils GPANEL_EXS_SELECT (list LBOX_EXS RBOX_EXS_CHOC)) (change-fils GPANEL_EXS_REG (list SLIDER_EXS_E)) (change-fils VPANEL1 (list GPANEL_EXS_SELECT GPANEL_EXS_VISU GPANEL_EXS_REG VPANEL_EXS_BUTS)) (change-fils VPANEL2 (list CANVAS_EXS)))))) ; Sous-menu Formes diverses (define EXS_FORMDIV (new menu-item% (label "Formes diverses") (parent FICH_EXS) (callback (lambda (item evt) (send BITMAP-DC set-background COLOR_BACK) (set! GRAVITE (make-vect 0 0)) (set! E 0.95) (send SLIDER_EXS_E set-value 95) (set! AFFICHE_EC #f) (send CBOX_EXS_EC set-value #f) (set! AFFICHE_CM #f) (send CBOX_EXS_CM set-value #f) (set! IND_ACTION #f) (send BUTTON_EXS_ACTION set-label "Go") (send LBOX_EXS set-selection 1) (send RBOX_EXS_CHOC set-selection 1) (load (build-path "Exemples" "Formes diverses.scm")) (send CANVAS_EXS on-paint) (send AFF_TRA enable #t) (send AFF_CM enable #t) (send AFF_EC enable #t) (send AFF_FOND set-label "Changer la couleur de fond pour les sections Dessin et Exemples") (send BUTTON_EXS_ACTION enable #t) (change-fils GPANEL_EXS_SELECT (list LBOX_EXS RBOX_EXS_CHOC)) (change-fils GPANEL_EXS_REG (list SLIDER_EXS_E)) (change-fils VPANEL1 (list GPANEL_EXS_SELECT GPANEL_EXS_VISU GPANEL_EXS_REG VPANEL_EXS_BUTS)) (change-fils VPANEL2 (list CANVAS_EXS)))))) ; Sous-menu Oeil de hibou (define EXS_HIB (new menu-item% (label "Oeil de hibou") (parent FICH_EXS) (callback (lambda (item evt) (send BITMAP-DC set-background COLOR_BACK) (set! GRAVITE (make-vect 0 0)) (set! E 0.95) (send SLIDER_EXS_E set-value 95) (set! AFFICHE_EC #f) (send CBOX_EXS_EC set-value #f) (set! AFFICHE_CM #f) (send CBOX_EXS_CM set-value #f) (set! IND_ACTION #f) (send BUTTON_EXS_ACTION set-label "Go") (send LBOX_EXS set-selection 1) (send RBOX_EXS_CHOC set-selection 2) (load (build-path "Exemples" "Oeil de hibou.scm")) (send CANVAS_EXS on-paint) (send AFF_TRA enable #t) (send AFF_CM enable #t) (send AFF_EC enable #t) (send AFF_FOND set-label "Changer la couleur de fond pour les sections Dessin et Exemples") (send BUTTON_EXS_ACTION enable #t) (change-fils GPANEL_EXS_SELECT (list LBOX_EXS RBOX_EXS_CHOC)) (change-fils GPANEL_EXS_REG (list SLIDER_EXS_E)) (change-fils VPANEL1 (list GPANEL_EXS_SELECT GPANEL_EXS_VISU GPANEL_EXS_REG VPANEL_EXS_BUTS)) (change-fils VPANEL2 (list CANVAS_EXS)))))) ; Sous-menu Oeil de Sauron (define EXS_SAURON (new menu-item% (label "Oeil de Sauron") (parent FICH_EXS) (callback (lambda (item evt) (send BITMAP-DC set-background COLOR_BACK) (set! GRAVITE (make-vect 0 0)) (set! E 0.95) (send SLIDER_EXS_E set-value 95) (set! AFFICHE_EC #f) (send CBOX_EXS_EC set-value #f) (set! AFFICHE_CM #f) (send CBOX_EXS_CM set-value #f) (set! IND_ACTION #f) (send BUTTON_EXS_ACTION set-label "Go") (send LBOX_EXS set-selection 1) (send RBOX_EXS_CHOC set-selection 3) (load (build-path "Exemples" "Oeil de Sauron.scm")) (send CANVAS_EXS on-paint) (send AFF_TRA enable #t) (send AFF_CM enable #t) (send AFF_EC enable #t) (send AFF_FOND set-label "Changer la couleur de fond pour les sections Dessin et Exemples") (send BUTTON_EXS_ACTION enable #t) (change-fils GPANEL_EXS_SELECT (list LBOX_EXS RBOX_EXS_CHOC)) (change-fils GPANEL_EXS_REG (list SLIDER_EXS_E)) (change-fils VPANEL1 (list GPANEL_EXS_SELECT GPANEL_EXS_VISU GPANEL_EXS_REG VPANEL_EXS_BUTS)) (change-fils VPANEL2 (list CANVAS_EXS)))))) ; Sous-menu Polygones imbriques (define EXS_POLYIMB (new menu-item% (label "Polygones imbriques") (parent FICH_EXS) (callback (lambda (item evt) (send BITMAP-DC set-background COLOR_BACK) (set! GRAVITE (make-vect 0 0)) (set! E 0.95) (send SLIDER_EXS_E set-value 95) (set! AFFICHE_EC #f) (send CBOX_EXS_EC set-value #f) (set! AFFICHE_CM #f) (send CBOX_EXS_CM set-value #f) (set! IND_ACTION #f) (send BUTTON_EXS_ACTION set-label "Go") (send LBOX_EXS set-selection 1) (send RBOX_EXS_CHOC set-selection 4) (load (build-path "Exemples" "Polygones imbriques.scm")) (send CANVAS_EXS on-paint) (send AFF_TRA enable #t) (send AFF_CM enable #t) (send AFF_EC enable #t) (send AFF_FOND set-label "Changer la couleur de fond pour les sections Dessin et Exemples") (send BUTTON_EXS_ACTION enable #t) (change-fils GPANEL_EXS_SELECT (list LBOX_EXS RBOX_EXS_CHOC)) (change-fils GPANEL_EXS_REG (list SLIDER_EXS_E)) (change-fils VPANEL1 (list GPANEL_EXS_SELECT GPANEL_EXS_VISU GPANEL_EXS_REG VPANEL_EXS_BUTS)) (change-fils VPANEL2 (list CANVAS_EXS)))))) ; Sous-menu Triangles (define EXS_TRIS (new menu-item% (label "Triangles") (parent FICH_EXS) (callback (lambda (item evt) (send BITMAP-DC set-background COLOR_BACK) (set! GRAVITE (make-vect 0 0)) (set! E 0.95) (send SLIDER_EXS_E set-value 95) (set! AFFICHE_EC #f) (send CBOX_EXS_EC set-value #f) (set! AFFICHE_CM #f) (send CBOX_EXS_CM set-value #f) (set! IND_ACTION #f) (send BUTTON_EXS_ACTION set-label "Go") (send LBOX_EXS set-selection 1) (send RBOX_EXS_CHOC set-selection 5) (load (build-path "Exemples" "Triangles.scm")) (send CANVAS_EXS on-paint) (send AFF_TRA enable #t) (send AFF_CM enable #t) (send AFF_EC enable #t) (send AFF_FOND set-label "Changer la couleur de fond pour les sections Dessin et Exemples") (send BUTTON_EXS_ACTION enable #t) (change-fils GPANEL_EXS_SELECT (list LBOX_EXS RBOX_EXS_CHOC)) (change-fils GPANEL_EXS_REG (list SLIDER_EXS_E)) (change-fils VPANEL1 (list GPANEL_EXS_SELECT GPANEL_EXS_VISU GPANEL_EXS_REG VPANEL_EXS_BUTS)) (change-fils VPANEL2 (list CANVAS_EXS)))))) ; Sous-menu Triangles necklace (ou Collier de triangles) (define EXS_TRINECK (new menu-item% (label "Triangles necklace") (parent FICH_EXS) (callback (lambda (item evt) (send BITMAP-DC set-background COLOR_BACK) (set! GRAVITE (make-vect 0 0)) (set! E 0.95) (send SLIDER_EXS_E set-value 95) (set! AFFICHE_EC #f) (send CBOX_EXS_EC set-value #f) (set! AFFICHE_CM #f) (send CBOX_EXS_CM set-value #f) (set! IND_ACTION #f) (send BUTTON_EXS_ACTION set-label "Go") (send LBOX_EXS set-selection 1) (send RBOX_EXS_CHOC set-selection 6) (load (build-path "Exemples" "Triangles necklace.scm")) (send CANVAS_EXS on-paint) (send AFF_TRA enable #t) (send AFF_CM enable #t) (send AFF_EC enable #t) (send AFF_FOND set-label "Changer la couleur de fond pour les sections Dessin et Exemples") (send BUTTON_EXS_ACTION enable #t) (change-fils GPANEL_EXS_SELECT (list LBOX_EXS RBOX_EXS_CHOC)) (change-fils GPANEL_EXS_REG (list SLIDER_EXS_E)) (change-fils VPANEL1 (list GPANEL_EXS_SELECT GPANEL_EXS_VISU GPANEL_EXS_REG VPANEL_EXS_BUTS)) (change-fils VPANEL2 (list CANVAS_EXS)))))) ; Séparateur entre les sous-menus relevant des chocs et ceux relevant des parametrisations (define SEPARATOR_EXS2 (new separator-menu-item% (parent FICH_EXS))) ; Sous-menu Courbe cartesienne (define EXS_CART (new menu-item% (label "Courbe cartesienne") (parent FICH_EXS) (callback (lambda (item evt) (send BITMAP-DC set-background COLOR_BACK) (set! POLYGONE_EXS (polygone-nul)) (set! GRAVITE (make-vect 0 0.01)) (send SLIDER_EXS_G set-value 100) (set! E 0.95) (send SLIDER_EXS_E set-value 95) (set! ANGLE 0) (send SLIDER_EXS_ANGLE set-value 0) (set! AFFICHE_EC #f) (send CBOX_EXS_EC set-value #f) (set! AFFICHE_CM #f) (send CBOX_EXS_CM set-value #f) (set! CART_X "(expt (sin t) 3)") (send TFIELD_EXS_CART_X set-value "(expt (sin t) 3)") (set! CART_Y "(- (cos t) (expt (cos t) 4))") (send TFIELD_EXS_CART_Y set-value "(- (cos t) (expt (cos t) 4))") (set! CART_INF "(- pi)") (send TFIELD_EXS_CART_INF set-value "(- pi)") (set! CART_SUP "pi") (send TFIELD_EXS_CART_SUP set-value "pi") (send MSG_EXS_CART set-label "") (set! IND_ACTION #f) (send BUTTON_EXS_ACTION set-label "Go") (send LBOX_EXS set-selection 2) (send RBOX_EXS_CHOC set-selection 0) (load (build-path "Exemples" "Courbe cartesienne.scm")) (send CANVAS_EXS on-paint) (send AFF_TRA enable #t) (send AFF_CM enable #t) (send AFF_EC enable #t) (send AFF_FOND set-label "Changer la couleur de fond pour les sections Dessin et Exemples") (send BUTTON_EXS_ACTION enable #t) (send MSG_EXS_CART set-label "") (change-fils GPANEL_EXS_SELECT (list LBOX_EXS RBOX_EXS_PARAM)) (send TFIELD_EXS_CART_X enable #t) (send TFIELD_EXS_CART_Y enable #t) (send TFIELD_EXS_CART_INF enable #t) (send TFIELD_EXS_CART_SUP enable #t) (send BUTTON_EXS_CART enable #t) (send SLIDER_EXS_ANGLE enable #t) (change-fils GPANEL_EXS_REG (list TFIELD_EXS_CART_X TFIELD_EXS_CART_Y TFIELD_EXS_CART_INF TFIELD_EXS_CART_SUP MSG_EXS_CART BUTTON_EXS_CART SLIDER_EXS_G SLIDER_EXS_E SLIDER_EXS_ANGLE)) (change-fils VPANEL1 (list GPANEL_EXS_SELECT GPANEL_EXS_VISU GPANEL_EXS_REG VPANEL_EXS_BUTS)) (change-fils VPANEL2 (list CANVAS_EXS)))))) ; Sous-menu Courbe polaire (define EXS_POL (new menu-item% (label "Courbe polaire") (parent FICH_EXS) (callback (lambda (item evt) (send BITMAP-DC set-background COLOR_BACK) (set! POLYGONE_EXS (polygone-nul)) (set! GRAVITE (make-vect 0 0.01)) (send SLIDER_EXS_G set-value 100) (set! E 0.95) (send SLIDER_EXS_E set-value 95) (set! ANGLE 0) (send SLIDER_EXS_ANGLE set-value 0) (set! AFFICHE_EC #f) (send CBOX_EXS_EC set-value #f) (set! AFFICHE_CM #f) (send CBOX_EXS_CM set-value #f) (set! POL_RHO "(+ (- (exp (cos t)) (* 2 (cos (* 4 t)))) (expt (sin (/ t 12)) 5))") (send TFIELD_EXS_POL_RHO set-value "(+ (- (exp (cos t)) (* 2 (cos (* 4 t)))) (expt (sin (/ t 12)) 5))") (set! POL_INF "(- pi)") (send TFIELD_EXS_POL_INF set-value "(- pi)") (set! POL_SUP "pi") (send TFIELD_EXS_POL_SUP set-value "pi") (send MSG_EXS_POL set-label "") (set! IND_ACTION #f) (send BUTTON_EXS_ACTION set-label "Go") (send LBOX_EXS set-selection 2) (send RBOX_EXS_CHOC set-selection 1) (load (build-path "Exemples" "Courbe polaire.scm")) (send CANVAS_EXS on-paint) (send AFF_TRA enable #t) (send AFF_CM enable #t) (send AFF_EC enable #t) (send AFF_FOND set-label "Changer la couleur de fond pour les sections Dessin et Exemples") (send BUTTON_EXS_ACTION enable #t) (send MSG_EXS_POL set-label "") (change-fils GPANEL_EXS_SELECT (list LBOX_EXS RBOX_EXS_PARAM)) (send TFIELD_EXS_POL_RHO enable #t) (send TFIELD_EXS_POL_INF enable #t) (send TFIELD_EXS_POL_SUP enable #t) (send SLIDER_EXS_ANGLE enable #t) (send BUTTON_EXS_POL enable #t) (change-fils GPANEL_EXS_REG (list TFIELD_EXS_POL_RHO TFIELD_EXS_POL_INF TFIELD_EXS_POL_SUP MSG_EXS_POL BUTTON_EXS_POL SLIDER_EXS_G SLIDER_EXS_E SLIDER_EXS_ANGLE)) (change-fils VPANEL1 (list GPANEL_EXS_SELECT GPANEL_EXS_VISU GPANEL_EXS_REG VPANEL_EXS_BUTS)) (change-fils VPANEL2 (list CANVAS_EXS)))))) ;; Sous-menu Objets (define FICH_OBJ (new menu% (label "Objets") (parent MENU_FICH) (help-string "Observe différents exemples et modifie certains paramètres"))) ; Sous-menus du menu Objets ; Sous-menu Deux boules (define OBJ_2BAL (new menu-item% (label "Deux boules") (parent FICH_OBJ) (shortcut #\o) (callback (lambda (item evt) (send BITMAP-DC set-background COLOR_OBJ_BACK) (init-objet) (set! AFFICHE_OBJ_CM #f) (send CBOX_OBJ_CM set-value #f) (set! IND_ACTION #f) (send BUTTON_OBJ_ACTION set-label "Go") (send RBOX_OBJ set-selection 0) (set! M1_2B 1) (send SLIDER_OBJ_2B_M1 set-value 1) (send SLIDER_OBJ_2B_M1 enable #t) (set! M2_2B 1) (send SLIDER_OBJ_2B_M2 set-value 1) (send SLIDER_OBJ_2B_M2 enable #t) (set! V1_2B (make-vect -5 0)) (send SLIDER_OBJ_2B_V1 set-value -5) (send SLIDER_OBJ_2B_V1 enable #t) (set! V2_2B (make-vect 0 0)) (send SLIDER_OBJ_2B_V2 set-value 0) (send SLIDER_OBJ_2B_V2 enable #t) (set! R1_2B 60) (send SLIDER_OBJ_2B_R1 set-value 60) (send SLIDER_OBJ_2B_R1 enable #t) (set! R2_2B 60) (send SLIDER_OBJ_2B_R2 set-value 60) (send SLIDER_OBJ_2B_R2 enable #t) (load (build-path "Objets" "Deux boules.scm")) (send CANVAS_OBJ on-paint) (send AFF_TRA enable #f) (send AFF_CM enable #f) (send AFF_EC enable #f) (send AFF_FOND set-label "Changer la couleur de fond pour la section Objets") (change-fils GPANEL_OBJ_REG (list SLIDER_OBJ_2B_M1 SLIDER_OBJ_2B_M2 SLIDER_OBJ_2B_R1 SLIDER_OBJ_2B_R2 SLIDER_OBJ_2B_V1 SLIDER_OBJ_2B_V2)) (change-fils VPANEL1 (list GPANEL_OBJ_SELECT GPANEL_OBJ_VISU GPANEL_OBJ_REG VPANEL_OBJ_BUTS)) (change-fils VPANEL2 (list CANVAS_OBJ)))))) ; Sous-menu Boules multiples (define OBJ_BAL (new menu-item% (label "Boules multiples") (parent FICH_OBJ) (callback (lambda (item evt) (send BITMAP-DC set-background COLOR_OBJ_BACK) (init-objet) (set! AFFICHE_OBJ_CM #f) (send CBOX_OBJ_CM set-value #f) (set! IND_ACTION #f) (send BUTTON_OBJ_ACTION set-label "Go") (send RBOX_OBJ set-selection 1) (set! NB_BAL 20) (send SLIDER_OBJ_BAL_NB set-value 20) (send SLIDER_OBJ_BAL_NB enable #t) (load (build-path "Objets" "Boules multiples.scm")) (send CANVAS_OBJ on-paint) (send AFF_TRA enable #f) (send AFF_CM enable #f) (send AFF_EC enable #f) (send AFF_FOND set-label "Changer la couleur de fond pour la section Objets") (change-fils GPANEL_OBJ_REG (list SLIDER_OBJ_BAL_NB)) (change-fils VPANEL1 (list GPANEL_OBJ_SELECT GPANEL_OBJ_VISU GPANEL_OBJ_REG VPANEL_OBJ_BUTS)) (change-fils VPANEL2 (list CANVAS_OBJ)))))) ; Sous-menu Gravite (define OBJ_GRA (new menu-item% (label "Gravite") (parent FICH_OBJ) (callback (lambda (item evt) (send BITMAP-DC set-background COLOR_OBJ_BACK) (init-objet) (set! AFFICHE_OBJ_CM #f) (send CBOX_OBJ_CM set-value #f) (set! IND_ACTION #f) (send BUTTON_OBJ_ACTION set-label "Go") (send RBOX_OBJ set-selection 2) (set! GRAVITE 0.1) (send SLIDER_OBJ_GRAV_G set-value 10) (send SLIDER_OBJ_GRAV_G enable #t) (set! M_GRAV 1) (send SLIDER_OBJ_GRAV_M set-value 1) (send SLIDER_OBJ_GRAV_M enable #t) (set! V_GRAV (make-vect -1 0)) (send SLIDER_OBJ_GRAV_V set-value -1) (send SLIDER_OBJ_GRAV_V enable #t) (set! R_GRAV 50) (send SLIDER_OBJ_GRAV_R set-value 50) (send SLIDER_OBJ_GRAV_R enable #t) (load (build-path "Objets" "Gravite.scm")) (send CANVAS_OBJ on-paint) (send AFF_TRA enable #f) (send AFF_CM enable #f) (send AFF_EC enable #f) (send AFF_FOND set-label "Changer la couleur de fond pour la section Objets") (change-fils GPANEL_OBJ_REG (list SLIDER_OBJ_GRAV_G SLIDER_OBJ_GRAV_M SLIDER_OBJ_GRAV_R SLIDER_OBJ_GRAV_V)) (change-fils VPANEL1 (list GPANEL_OBJ_SELECT GPANEL_OBJ_VISU GPANEL_OBJ_REG VPANEL_OBJ_BUTS)) (change-fils VPANEL2 (list CANVAS_OBJ)))))) ; Sous-menu Pendule (define OBJ_PEN (new menu-item% (label "Pendule") (parent FICH_OBJ) (callback (lambda (item evt) (send BITMAP-DC set-background COLOR_OBJ_BACK) (init-objet) (set! AFFICHE_OBJ_CM #f) (send CBOX_OBJ_CM set-value #f) (set! IND_ACTION #f) (send BUTTON_OBJ_ACTION set-label "Go") (send RBOX_OBJ set-selection 3) (set! NB_PEND 5) (send SLIDER_OBJ_PEND_NB set-value 5) (send SLIDER_OBJ_PEND_NB enable #t) (load (build-path "Objets" "Pendule.scm")) (send CANVAS_OBJ on-paint) (send AFF_TRA enable #f) (send AFF_CM enable #f) (send AFF_EC enable #f) (send AFF_FOND set-label "Changer la couleur de fond pour la section Objets") (change-fils GPANEL_OBJ_REG (list SLIDER_OBJ_PEND_NB)) (change-fils VPANEL1 (list GPANEL_OBJ_SELECT GPANEL_OBJ_VISU GPANEL_OBJ_REG VPANEL_OBJ_BUTS)) (change-fils VPANEL2 (list CANVAS_OBJ)))))) ;; Sous-menus du menu Affichage ;; Sous-menu Couleur du fond (define AFF_FOND (new menu-item% (label "Changer la couleur de fond pour les sections Dessin et Exemples") (parent MENU_AFF) (callback (lambda (item evt) (let ((current-dc (car (send VPANEL2 get-children))) (color (get-color-from-user))) (if color ; au cas où l'utilisateur aurait fermé la fenêtre de choix ou appuyé sur annuler (begin (if (equal? current-dc CANVAS_OBJ) (set! COLOR_OBJ_BACK color) (set! COLOR_BACK color)) (send BITMAP-DC set-background color) (send current-dc on-paint)))))))) ;; Sous-menu Couleur du tracé (define AFF_TRA (new menu-item% (label "Changer la couleur du tracé") (parent MENU_AFF) (callback (lambda (item evt) (let ((current-dc (first (send VPANEL2 get-children))) (color (get-color-from-user))) (if color (set! COLOR_POLY color)) (send current-dc on-paint)))))) ;; Sous-menu Couleur du centre de masse (define AFF_CM (new menu-item% (label "Changer la couleur du centre de masse") (parent MENU_AFF) (callback (lambda (item evt) (let ((current-dc (first (send VPANEL2 get-children))) (color (get-color-from-user))) (if color (set! COLOR_CM color)) (send current-dc on-paint)))))) ;; Sous-menu Couleur de l'enveloppe convexe (define AFF_EC (new menu-item% (label "Changer la couleur de l'enveloppe convexe") (parent MENU_AFF) (callback (lambda (item evt) (let ((current-dc (first (send VPANEL2 get-children))) (color (get-color-from-user))) (if color (set! COLOR_EC color)) (send current-dc on-paint)))))) ;; Sous-menus du menu Aide ;; Sous-menu A props du projet (define AIDE_PROPOS (new menu-item% (label "A propos du Projet") (parent MENU_AIDE) (shortcut #\s) (callback (lambda (item evt) (if (equal? (system-type 'os) 'windows) (system (path->string (build-path (current-directory) "slideshow.scm"))) (system (string-append "open " (path->string (build-path (current-directory) "slideshow.scm"))))))))) ;; Sous-menu Documentation technique (define AIDE_DOCTEC (new menu-item% (label "Documentation technique") (parent MENU_AIDE) (shortcut #\t) (callback (lambda (item evt) (if (equal? (system-type 'os) 'windows) (system (path->string (build-path (current-directory) "documentation_technique.pdf"))) (system (string-append "open " (path->string (build-path (current-directory) "documentation_technique.pdf"))))))))) ;; Sous-menu Aide en ligne (define AIDE_SITE (new menu-item% (label "Aide en ligne") (parent MENU_AIDE) (shortcut #\?) (callback (lambda (item evt) (send-url "http://projetphysics.teria.org"))))) ;***************************************************** ; GESTION DES PANEAUX DE REGLAGES ;***************************************************** ;;;; Panneau initial ;;; Panneau de sélection de la section (define GPANEL_INIT_SELECT (new group-box-panel% (label "Sélection") (parent VPANEL1) (vert-margin 5) (horiz-margin 10) (spacing 30) (border 5) (alignment '(center center)))) ;; Bouton Dessin (define BUTTON_DRAW (new button% (label (make-object bitmap% (build-path 'same "Images" "Icones" "dessin.png") 'png #f)) (parent GPANEL_INIT_SELECT) (callback (lambda (b evt) (set! GRAVITE (make-vect 0 0.01)) (send SLIDER_DRAW_G set-value 100) (set! E 0.95) (send SLIDER_DRAW_E set-value 95) (set! POLYGONE (polygone-nul)) (set! AFFICHE_EC #f) (send CBOX_DRAW_EC set-value #f) (set! AFFICHE_CM #f) (send CBOX_DRAW_CM set-value #f) (set! COMPT 0) (set! IND_ACTION #f) (send BUTTON_DRAW_ACTION set-label "Go") (send CANVAS_DRAW on-paint) (change-fils VPANEL1 (list GPANEL_DRAW_VISU GPANEL_DRAW_REG VPANEL_DRAW_BUTS)) (change-fils VPANEL2 (list CANVAS_DRAW)))))) ;; Panneau horizontal contenant les boutons Exemples et Objets (define HPANEL_BUTS1 (new horizontal-panel% (parent GPANEL_INIT_SELECT) (spacing 50) (alignment '(center center)))) ; Bouton Exemples (define BUTTON_EXS (new button% (label (make-object bitmap% (build-path 'same "Images" "Icones" "dossier.png") 'png #f)) (parent HPANEL_BUTS1) (callback (lambda (b evt) (set! GRAVITE (make-vect 0 0.01)) (send SLIDER_EXS_G set-value 100) (set! E 0.95) (send SLIDER_EXS_E set-value 95) (set! ANGLE PI/2) (send SLIDER_EXS_ANGLE set-value 90) (set! LONG_BAR 150) (send SLIDER_EXS_BAR_LONG set-value 150) (set! AFFICHE_EC #f) (send CBOX_EXS_EC set-value #f) (set! AFFICHE_CM #f) (send CBOX_EXS_CM set-value #f) (set! IND_ACTION #f) (send BUTTON_EXS_ACTION set-label "Go") (send LBOX_EXS set-selection 0) (send RBOX_EXS_GRAV set-selection 0) (load (build-path "Exemples" "Barre.scm")) (send CANVAS_EXS on-paint) (change-fils GPANEL_EXS_SELECT (list LBOX_EXS RBOX_EXS_GRAV)) (send SLIDER_EXS_BAR_LONG enable #t) (send SLIDER_EXS_ANGLE enable #t) (send BUTTON_EXS_ACTION enable #t) (change-fils GPANEL_EXS_REG (list SLIDER_EXS_G SLIDER_EXS_E SLIDER_EXS_ANGLE SLIDER_EXS_BAR_LONG)) (change-fils VPANEL1 (list GPANEL_EXS_SELECT GPANEL_EXS_VISU GPANEL_EXS_REG VPANEL_EXS_BUTS)) (change-fils VPANEL2 (list CANVAS_EXS)))))) ; Bouton Objets (define BUTTON_OBJ (new button% (label (make-object bitmap% (build-path 'same "Images" "Icones" "panier.png") 'png #f)) (parent HPANEL_BUTS1) (callback (lambda (b evt) (send BITMAP-DC set-background COLOR_OBJ_BACK) (init-objet) (set! AFFICHE_OBJ_CM #f) (send CBOX_OBJ_CM set-value #f) (set! IND_ACTION #f) (send BUTTON_OBJ_ACTION set-label "Go") (send RBOX_OBJ set-selection 0) (set! M1_2B 1) (send SLIDER_OBJ_2B_M1 set-value 1) (send SLIDER_OBJ_2B_M1 enable #t) (set! M2_2B 1) (send SLIDER_OBJ_2B_M2 set-value 1) (send SLIDER_OBJ_2B_M2 enable #t) (set! V1_2B (make-vect -5 0)) (send SLIDER_OBJ_2B_V1 set-value -5) (send SLIDER_OBJ_2B_V1 enable #t) (set! V2_2B (make-vect 0 0)) (send SLIDER_OBJ_2B_V2 set-value 0) (send SLIDER_OBJ_2B_V2 enable #t) (set! R1_2B 60) (send SLIDER_OBJ_2B_R1 set-value 60) (send SLIDER_OBJ_2B_R1 enable #t) (set! R2_2B 60) (send SLIDER_OBJ_2B_R2 set-value 60) (send SLIDER_OBJ_2B_R2 enable #t) (load (build-path "Objets" "Deux boules.scm")) (send CANVAS_OBJ on-paint) (send AFF_TRA enable #f) (send AFF_CM enable #f) (send AFF_EC enable #f) (send AFF_FOND set-label "Changer la couleur de fond pour la section Objets") (change-fils GPANEL_OBJ_REG (list SLIDER_OBJ_2B_M1 SLIDER_OBJ_2B_M2 SLIDER_OBJ_2B_R1 SLIDER_OBJ_2B_R2 SLIDER_OBJ_2B_V1 SLIDER_OBJ_2B_V2)) (change-fils VPANEL1 (list GPANEL_OBJ_SELECT GPANEL_OBJ_VISU GPANEL_OBJ_REG VPANEL_OBJ_BUTS)) (change-fils VPANEL2 (list CANVAS_OBJ)))))) ;;; Panneau de sélection de la documentation (define GPANEL_INIT_DOC (new group-box-panel% (label "Documentation") (parent VPANEL1) (vert-margin 5) (horiz-margin 10) (spacing 30) (border 5))) ;; Panneau horizontal contenant les boutons Slide et Lien (define HPANEL_BUTS2 (new horizontal-panel% (parent GPANEL_INIT_DOC) (spacing 50) (alignment '(center center)))) ; Bouton Slide (define BUTTON_SLIDE (new button% (label (make-object bitmap% (build-path 'same "Images" "Icones" "boussole.png") 'png #f)) (parent HPANEL_BUTS2) (callback (lambda (item evt) (if (equal? (system-type 'os) 'windows) (system (path->string (build-path (current-directory) "slideshow.scm"))) (system (string-append "open " (path->string (build-path (current-directory) "slideshow.scm"))))))))) ; Bouton Lien (define BUTTON_LINK (new button% (label (make-object bitmap% (build-path 'same "Images" "Icones" "lien.png") 'png #f)) (parent HPANEL_BUTS2) (callback (lambda (b evt) (send-url "http://projetphysics.teria.org"))))) ;;;; Panneaux pour le dessin ;;; Panneau de visualisation pour le dessin (define GPANEL_DRAW_VISU (new group-box-panel% (label "Visualisation") (parent VPANEL1) (style '(deleted)) (vert-margin 5) (horiz-margin 10) (spacing 10) (border 5) (alignment '(center center)))) ;; Case à cocher pour l'enveloppe convexe (define CBOX_DRAW_EC (new check-box% (label "Enveloppe convexe") (parent GPANEL_DRAW_VISU) (callback (lambda (c evt) (case AFFICHE_EC ((#t) (set! AFFICHE_EC #f) (send CANVAS_DRAW on-paint)) (else (set! AFFICHE_EC #t) (send CANVAS_DRAW on-paint))))))) ;; Case à cocher pour le centre de masse (define CBOX_DRAW_CM (new check-box% (label "Centre de masse") (parent GPANEL_DRAW_VISU) (callback (lambda (c evt) (case AFFICHE_CM ((#t) (set! AFFICHE_CM #f) (send CANVAS_DRAW on-paint)) (else (set! AFFICHE_CM #t) (send CANVAS_DRAW on-paint))))))) ;;; Panneau de réglages pour le dessin (define GPANEL_DRAW_REG (new group-box-panel% (label "Réglages") (parent VPANEL1) (style '(deleted)) (vert-margin 5) (horiz-margin 10) (spacing 10) (border 5) (alignment '(center center)))) ;; Slider pour régler l'effet de la gravité (pourcentage) (define SLIDER_DRAW_G (new slider% (label "Coefficient de gravitation (%)") (min-value 0) (max-value 100) (init-value 100) (parent GPANEL_DRAW_REG) (callback (lambda (sl evt) (set! GRAVITE (make-vect 0 (/ (send sl get-value) 10000))))))) ;; Slider pour régler le coefficient d'elasticite (pourcentage) (define SLIDER_DRAW_E (new slider% (label "Coefficient d'élasticité (%)") (min-value 50) (max-value 100) (init-value 100) (parent GPANEL_DRAW_REG) (callback (lambda (sl evt) (set! E (/ (send sl get-value) 100)))))) ;;; Panneau de boutons pour le dessin (define VPANEL_DRAW_BUTS (new vertical-panel% (parent VPANEL1) (style '(deleted)) (vert-margin 5) (horiz-margin 10) (spacing 10) (border 5) (alignment '(center center)) (stretchable-height #f))) ;; Bouton pour effacer le dessin (define BUTTON_DRAW_CLEAR (new button% (label "Clear") (parent VPANEL_DRAW_BUTS) (callback (lambda (b evt) (set! IND_ACTION #f) (send BUTTON_DRAW_ACTION set-label "Go") (set! POLYGONE (polygone-nul)) (send CANVAS_DRAW on-paint))))) ;; Bouton pour enclencher l'animation (define BUTTON_DRAW_ACTION (new button% (label "Go") (parent VPANEL_DRAW_BUTS) (callback (lambda (b evt) (case IND_ACTION ((#t) (set! IND_ACTION #f) (send BUTTON_DRAW_ACTION set-label "Go") (send CANVAS_DRAW on-paint)) (else (set! IND_ACTION #t) (send BUTTON_DRAW_ACTION set-label "Stop") (send CANVAS_DRAW on-paint))))))) ;; Bouton de retour au menu initial (define BUTTON_DRAW_MENU (new button% (label "Menu") (parent VPANEL_DRAW_BUTS) (callback (lambda (b evt) (set! IND_ACTION #f) (change-fils VPANEL1 (list GPANEL_INIT_SELECT GPANEL_INIT_DOC)) (change-fils VPANEL2 (list CANVAS_INIT)))))) ;;;; Panneaux pour les exemples ;;; Panneau de sélection des exemples (define GPANEL_EXS_SELECT (new group-box-panel% (label "Exemples") (parent VPANEL1) (style '(deleted)) (horiz-margin 10) (alignment '(center center)) (stretchable-height #f))) ;; Label-box pour choisir parmi les deux radio-box (define LBOX_EXS (new list-box% (label "Catégorie") (choices (list "Gravitation" "Chocs" "Parametrisation")) (parent GPANEL_EXS_SELECT) (callback (lambda (lb evt) (set! E 0.95) (send SLIDER_EXS_E set-value 95) (set! IND_ACTION #f) (send BUTTON_EXS_ACTION set-label "Go") (send BUTTON_EXS_ACTION enable #t) (case (first (send lb get-selections)) ((0) (send RBOX_EXS_GRAV set-selection 0) (set! GRAVITE (make-vect 0 0.01)) (send SLIDER_EXS_G set-value 100) (set! ANGLE PI/2) (send SLIDER_EXS_ANGLE set-value 90) (set! LONG_BAR 150) (send SLIDER_EXS_BAR_LONG set-value 150) (send RBOX_EXS_GRAV set-selection 0) (load (build-path "Exemples" "Barre.scm")) (send CANVAS_EXS on-paint) (change-fils GPANEL_EXS_SELECT (list LBOX_EXS RBOX_EXS_GRAV)) (send SLIDER_EXS_BAR_LONG enable #t) (send SLIDER_EXS_ANGLE enable #t) (change-fils GPANEL_EXS_REG (list SLIDER_EXS_G SLIDER_EXS_E SLIDER_EXS_ANGLE SLIDER_EXS_BAR_LONG))) ((1) (set! GRAVITE (make-vect 0 0)) (send RBOX_EXS_CHOC set-selection 0) (load (build-path "Exemples" "Cercle et ellipse.scm")) (send CANVAS_EXS on-paint) (change-fils GPANEL_EXS_SELECT (list LBOX_EXS RBOX_EXS_CHOC)) (change-fils GPANEL_EXS_REG (list SLIDER_EXS_E))) ((2) ;; ¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡ ATTENTION !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ;; En passant de la paramétrisation a une autre section de la catégorie ;; exemple, la fenêtre s'agrandit alors que celle de paramétrisation est la plus grande ;; L'utilisateur doit alors la redimensionner (set! POLYGONE_EXS (polygone-nul)) (send RBOX_EXS_PARAM set-selection 0) (set! GRAVITE (make-vect 0 0.01)) (send SLIDER_EXS_G set-value 100) (set! ANGLE 0) (send SLIDER_EXS_ANGLE set-value 0) (set! CART_X "(expt (sin t) 3)") (send TFIELD_EXS_CART_X set-value "(expt (sin t) 3)") (set! CART_Y "(- (cos t) (expt (cos t) 4))") (send TFIELD_EXS_CART_Y set-value "(- (cos t) (expt (cos t) 4))") (set! CART_INF "(- pi)") (send TFIELD_EXS_CART_INF set-value "(- pi)") (set! CART_SUP "pi") (send TFIELD_EXS_CART_SUP set-value "pi") (send MSG_EXS_CART set-label "") (send RBOX_EXS_CHOC set-selection 0) (load (build-path "Exemples" "Courbe cartesienne.scm")) (send CANVAS_EXS on-paint) (change-fils GPANEL_EXS_SELECT (list LBOX_EXS RBOX_EXS_PARAM)) (send TFIELD_EXS_CART_X enable #t) (send TFIELD_EXS_CART_Y enable #t) (send TFIELD_EXS_CART_INF enable #t) (send TFIELD_EXS_CART_SUP enable #t) (send SLIDER_EXS_ANGLE enable #t) (send BUTTON_EXS_CART enable #t) (change-fils GPANEL_EXS_REG (list TFIELD_EXS_CART_X TFIELD_EXS_CART_Y TFIELD_EXS_CART_INF TFIELD_EXS_CART_SUP MSG_EXS_CART BUTTON_EXS_CART SLIDER_EXS_G SLIDER_EXS_E SLIDER_EXS_ANGLE)))))) (style '(single vertical-label)))) ;; Définition d'une nouvelle classe radio-box dotée d'une nouvelle méthode get-label-item (define my-radio-box% (class radio-box% (define/public (get-label-item str) ; retourne la position du bouton de label str (do ((i 0 (+ i 1))) ((equal? (send this get-item-label i) str) i))) (super-new))) ;; Radio-box pour les exemples de gravitation (define RBOX_EXS_GRAV (new my-radio-box% (label "Gravitation") (choices (list "Barre" "Boucle infinie" "Ellipse" "Escargot" "Etoile" "Fleur" "Haltere" "Polygone regulier" "Quadrillage")) (parent GPANEL_EXS_SELECT) (callback (lambda (rb evt) (let ((str (send rb get-item-label (send rb get-selection)))) (set! GRAVITE (make-vect 0 0.01)) (send SLIDER_EXS_G set-value 100) (set! E 0.95) (send SLIDER_EXS_E set-value 95) (set! ANGLE PI/2) (send SLIDER_EXS_ANGLE set-value 90) (set! IND_ACTION #f) (send BUTTON_EXS_ACTION set-label "Go") (change-fils GPANEL_EXS_REG (list SLIDER_EXS_G SLIDER_EXS_E SLIDER_EXS_ANGLE)) (send SLIDER_EXS_ANGLE enable #t) (cond ((string=? str "Barre") (set! LONG_BAR 150) (send SLIDER_EXS_BAR_LONG set-value 150) (send SLIDER_EXS_BAR_LONG enable #t) (send GPANEL_EXS_REG add-child SLIDER_EXS_BAR_LONG)) ((string=? str "Boucle infinie") (set! TAILLE_INF 4) (send SLIDER_EXS_INF_TAILLE set-value 4) (send SLIDER_EXS_INF_TAILLE enable #t) (send GPANEL_EXS_REG add-child SLIDER_EXS_INF_TAILLE)) ((string=? str "Ellipse") (set! TAILLE_ELL 100) (send SLIDER_EXS_ELL_TAILLE set-value 100) (send SLIDER_EXS_ELL_TAILLE enable #t) (send GPANEL_EXS_REG add-child SLIDER_EXS_ELL_TAILLE)) ((string=? str "Escargot") (set! TORSADE_ESC 8) (send SLIDER_EXS_ESC_TORSADE set-value 8) (send SLIDER_EXS_ESC_TORSADE enable #t) (send GPANEL_EXS_REG add-child SLIDER_EXS_ESC_TORSADE)) ((string=? str "Etoile") (set! NB_BRAN_STAR 12) (send SLIDER_EXS_STAR_NB_BRAN set-value 6) (send SLIDER_EXS_STAR_NB_BRAN enable #t) (send GPANEL_EXS_REG add-child SLIDER_EXS_STAR_NB_BRAN)) ((string=? str "Haltere") (set! TAILLE_HALT 3) (send SLIDER_EXS_HALT_TAILLE set-value 3) (send SLIDER_EXS_HALT_TAILLE enable #t) (send GPANEL_EXS_REG add-child SLIDER_EXS_HALT_TAILLE)) ((string=? str "Polygone regulier") (set! NB_COTES_POLYREG 5) (send SLIDER_EXS_POLYREG_NB_COTES set-value 5) (send SLIDER_EXS_POLYREG_NB_COTES enable #t) (send GPANEL_EXS_REG add-child SLIDER_EXS_POLYREG_NB_COTES)) ((string=? str "Quadrillage") (set! COURB_QUA 50) (send SLIDER_EXS_QUA_COURB set-value 50) (send SLIDER_EXS_QUA_COURB enable #t) (send GPANEL_EXS_REG add-child SLIDER_EXS_QUA_COURB))) (load (build-path "Exemples" (string-append str ".scm"))) (send CANVAS_EXS on-paint)))) (style '(vertical vertical-label)))) ;; Radio-box pour les exemples de chocs (define RBOX_EXS_CHOC (new my-radio-box% (label "Chocs") (choices (list "Cercle et ellipse" "Formes diverses" "Oeil de hibou" "Oeil de Sauron" "Polygones imbriques" "Triangles" "Triangles necklace")) (parent GPANEL_EXS_SELECT) (callback (lambda (rb evt) (set! GRAVITE (make-vect 0 0)) (set! E 0.95) (send SLIDER_EXS_E set-value 95) (set! IND_ACTION #f) (send BUTTON_EXS_ACTION set-label "Go") (load (build-path "Exemples" (string-append (send rb get-item-label (send rb get-selection)) ".scm"))) (send CANVAS_EXS on-paint))) (style '(vertical vertical-label deleted)))) ;; Radio-box pour les exemples de paramétrisation (define RBOX_EXS_PARAM (new my-radio-box% (label "Parametrisation") (choices (list "Courbe cartesienne" "Courbe polaire")) (parent GPANEL_EXS_SELECT) (callback (lambda (rb evt) (set! POLYGONE_EXS (polygone-nul)) (set! GRAVITE (make-vect 0 0.01)) (send SLIDER_EXS_G set-value 100) (set! E 0.95) (send SLIDER_EXS_E set-value 95) (set! ANGLE 0) (send SLIDER_EXS_ANGLE set-value 0) (set! IND_ACTION #f) (send BUTTON_EXS_ACTION set-label "Go") (send BUTTON_EXS_ACTION enable #t) (send SLIDER_EXS_ANGLE enable #t) (if (string=? (send rb get-item-label (send rb get-selection)) "Courbe cartesienne") (begin (set! CART_X "(expt (sin t) 3)") (send TFIELD_EXS_CART_X set-value "(expt (sin t) 3)") (send TFIELD_EXS_CART_X enable #t) (set! CART_Y "(- (cos t) (expt (cos t) 4))") (send TFIELD_EXS_CART_Y set-value "(- (cos t) (expt (cos t) 4))") (send TFIELD_EXS_CART_Y enable #t) (set! CART_INF "(- pi)") (send TFIELD_EXS_CART_INF set-value "(- pi)") (send TFIELD_EXS_CART_INF enable #t) (set! CART_SUP "pi") (send TFIELD_EXS_CART_SUP set-value "pi") (send TFIELD_EXS_CART_SUP enable #t) (send MSG_EXS_CART set-label "") (send BUTTON_EXS_CART enable #t) (change-fils GPANEL_EXS_REG (list TFIELD_EXS_CART_X TFIELD_EXS_CART_Y TFIELD_EXS_CART_INF TFIELD_EXS_CART_SUP MSG_EXS_CART BUTTON_EXS_CART SLIDER_EXS_G SLIDER_EXS_E SLIDER_EXS_ANGLE)) (load (build-path "Exemples" "Courbe cartesienne.scm"))) (begin (set! POL_RHO "(+ (- (exp (cos t)) (* 2 (cos (* 4 t)))) (expt (sin (/ t 12)) 5))") (send TFIELD_EXS_POL_RHO set-value "(+ (- (exp (cos t)) (* 2 (cos (* 4 t)))) (expt (sin (/ t 12)) 5))") (send TFIELD_EXS_POL_RHO enable #t) (set! POL_INF "(- pi)") (send TFIELD_EXS_POL_INF set-value "(- pi)") (send TFIELD_EXS_POL_INF enable #t) (set! POL_SUP "pi") (send TFIELD_EXS_POL_SUP set-value "pi") (send TFIELD_EXS_POL_SUP enable #t) (send MSG_EXS_POL set-label "") (send BUTTON_EXS_POL enable #t) (change-fils GPANEL_EXS_REG (list TFIELD_EXS_POL_RHO TFIELD_EXS_POL_INF TFIELD_EXS_POL_SUP MSG_EXS_POL BUTTON_EXS_POL SLIDER_EXS_G SLIDER_EXS_E SLIDER_EXS_ANGLE)) (load (build-path "Exemples" "Courbe polaire.scm")))) (send CANVAS_EXS on-paint))) (style '(vertical vertical-label deleted)))) ;;; Panneau de visualisation pour les exemples (define GPANEL_EXS_VISU (new group-box-panel% (label "Visualisation") (parent VPANEL1) (style '(deleted)) (horiz-margin 10) (border 5) (alignment '(center center)))) ;; Case à cocher pour l'enveloppe convexe (define CBOX_EXS_EC (new check-box% (label "Enveloppe convexe") (parent GPANEL_EXS_VISU) (callback (lambda (c evt) (case AFFICHE_EC ((#t) (set! AFFICHE_EC #f) (send CANVAS_EXS on-paint)) (else (set! AFFICHE_EC #t) (send CANVAS_EXS on-paint))))))) ;; Case à cocher pour le centre de masse (define CBOX_EXS_CM (new check-box% (label "Centre de masse") (parent GPANEL_EXS_VISU) (callback (lambda (c evt) (case AFFICHE_CM ((#t) (set! AFFICHE_CM #f) (send CANVAS_EXS on-paint)) (else (set! AFFICHE_CM #t) (send CANVAS_EXS on-paint))))))) ;;; Panneau de réglages des exemples (define GPANEL_EXS_REG (new group-box-panel% (label "Réglages") (parent VPANEL1) (style '(deleted)) (horiz-margin 10) (alignment '(center center)) (stretchable-height #f))) ;; Slider pour régler l'effet de la gravité (pourcentage) pour les parties Gravitation et Parametrisation (define SLIDER_EXS_G (new slider% (label "Coefficient de gravitation (%)") (min-value 0) (max-value 100) (init-value 100) (parent GPANEL_EXS_REG) (callback (lambda (sl evt) (set! GRAVITE (make-vect 0 (/ (send sl get-value) 10000))))) (style '(horizontal vertical-label)))) ;; Slider pour régler le coefficient d'elasticite (pourcentage) pour tous les exemples (define SLIDER_EXS_E (new slider% (label "Coefficient d'élasticité (%)") (min-value 50) (max-value 100) (init-value 100) (parent GPANEL_EXS_REG) (callback (lambda (sl evt) (set! E (/ (send sl get-value) 100)))) (style '(horizontal vertical-label)))) ;; Slider pour régler l'angle de l'exemple dans Gravitation et Parametrisation (define SLIDER_EXS_ANGLE (new slider% (label "Angle (en degré)") (min-value 0) (max-value 360) (init-value 90) (parent GPANEL_EXS_REG) (callback (lambda (sl evt) (let ((rbox (cadr (send GPANEL_EXS_SELECT get-children)))) (set! ANGLE (/ (* pi (send sl get-value)) 180)) (load (build-path "Exemples" (string-append (send rbox get-item-label (send rbox get-selection)) ".scm"))) (send CANVAS_EXS on-paint)))) (style '(horizontal vertical-label)))) ;; Sliders pour la partie Chocs ;; Slider pour régler la longueur de la barre (define SLIDER_EXS_BAR_LONG (new slider% (label "Longueur") (min-value 50) (max-value 250) (init-value 150) (parent GPANEL_EXS_REG) (callback (lambda (sl evt) (set! LONG_BAR (send sl get-value)) (load (build-path "Exemples" "Barre.scm")) (send CANVAS_EXS on-paint))) (style '(horizontal vertical-label)))) ;; Slider pour régler la taille de la boucle infinie (define SLIDER_EXS_INF_TAILLE (new slider% (label "Taille") (min-value 1) (max-value 8) (init-value 4) (parent GPANEL_EXS_REG) (callback (lambda (sl evt) (set! TAILLE_INF (send sl get-value)) (load (build-path "Exemples" "Boucle infinie.scm")) (send CANVAS_EXS on-paint))) (style '(horizontal vertical-label deleted)))) ;; Slider pour régler la taille de l'ellipse (define SLIDER_EXS_ELL_TAILLE (new slider% (label "Taille") (min-value 50) (max-value 150) (init-value 100) (parent GPANEL_EXS_REG) (callback (lambda (sl evt) (set! TAILLE_ELL (send sl get-value)) (load (build-path "Exemples" "Ellipse.scm")) (send CANVAS_EXS on-paint))) (style '(horizontal vertical-label deleted)))) ;; Slider pour régler la torsade de l'escargot (define SLIDER_EXS_ESC_TORSADE (new slider% (label "Torsade") (min-value 1) (max-value 10) (init-value 8) (parent GPANEL_EXS_REG) (callback (lambda (sl evt) (set! TORSADE_ESC (send sl get-value)) (load (build-path "Exemples" "Escargot.scm")) (send CANVAS_EXS on-paint))) (style '(horizontal vertical-label deleted)))) ;; Slider pour régler le nombre de branches de l'étoile (define SLIDER_EXS_STAR_NB_BRAN (new slider% (label "Nombre de branches") (min-value 2) (max-value 25) (init-value 6) (parent GPANEL_EXS_REG) (callback (lambda (sl evt) (set! NB_BRAN_STAR (* (send sl get-value) 2)) (load (build-path "Exemples" "Etoile.scm")) (send CANVAS_EXS on-paint))) (style '(horizontal vertical-label deleted)))) ;; Slider pour régler le nombre de branches de l'étoile (define SLIDER_EXS_HALT_TAILLE (new slider% (label "Taille de la boule du bas") (min-value 1) (max-value 6) (init-value 3) (parent GPANEL_EXS_REG) (callback (lambda (sl evt) (set! TAILLE_HALT (send sl get-value)) (load (build-path "Exemples" "Haltere.scm")) (send CANVAS_EXS on-paint))) (style '(horizontal vertical-label deleted)))) ;; Slider pour régler le nombre de côtés du polygone régulier (define SLIDER_EXS_POLYREG_NB_COTES (new slider% (label "Nombre de côtés") (min-value 3) (max-value 10) (init-value 5) (parent GPANEL_EXS_REG) (callback (lambda (sl evt) (set! NB_COTES_POLYREG (send sl get-value)) (load (build-path "Exemples" "Polygone regulier.scm")) (send CANVAS_EXS on-paint))) (style '(horizontal vertical-label deleted)))) ;; Slider pour régler la courbure du quadrillage (define SLIDER_EXS_QUA_COURB (new slider% (label "Courbure") (min-value 1) (max-value 100) (init-value 50) (parent GPANEL_EXS_REG) (callback (lambda (sl evt) (set! COURB_QUA (send sl get-value)) (load (build-path "Exemples" "Quadrillage.scm")) (send CANVAS_EXS on-paint))) (style '(horizontal vertical-label deleted)))) ;; Zones de texte, boutons et messages pour la partie Parametrisation ;; ¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡ ATTENTION !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ;;les zones de texte lorsqu'elles sont rendues inactives ne sont plus éditables sur Windows mais le sont sur MAC OS X ;; Zone de texte pour déterminer x en fonction de t dans la paramétrisation cartésienne (define TFIELD_EXS_CART_X (new text-field% (label "x(t) = ") (parent GPANEL_EXS_REG) (callback (lambda (tf evt) (if (equal? (send evt get-event-type) 'text-field-enter) (begin (set! POLYGONE_EXS (polygone-nul)) (send MSG_EXS_CART set-label "") (set! CART_X (send tf get-value)) (set! CART_Y (send TFIELD_EXS_CART_Y get-value)) (set! CART_INF (send TFIELD_EXS_CART_INF get-value)) (set! CART_SUP (send TFIELD_EXS_CART_SUP get-value)) (load (build-path "Exemples" "Courbe cartesienne.scm")) (when (not (polygone-nul? POLYGONE_EXS)) (send CANVAS_EXS on-paint) (send SLIDER_EXS_ANGLE enable #t) (send BUTTON_EXS_ACTION enable #t))) (begin (send BUTTON_EXS_ACTION enable #f) (send SLIDER_EXS_ANGLE enable #f))))) (style '(single vertical-label deleted)))) ;; Zone de texte pour déterminer y en fonction de t dans la paramétrisation cartésienne (define TFIELD_EXS_CART_Y (new text-field% (label "y(t) = ") (parent GPANEL_EXS_REG) (callback (lambda (tf evt) (if (equal? (send evt get-event-type) 'text-field-enter) (begin (set! POLYGONE_EXS (polygone-nul)) (send MSG_EXS_CART set-label "") (set! CART_X (send TFIELD_EXS_CART_X get-value)) (set! CART_Y (send tf get-value)) (set! CART_INF (send TFIELD_EXS_CART_INF get-value)) (set! CART_SUP (send TFIELD_EXS_CART_SUP get-value)) (load (build-path "Exemples" "Courbe cartesienne.scm")) (when (not (polygone-nul? POLYGONE_EXS)) (send CANVAS_EXS on-paint) (send SLIDER_EXS_ANGLE enable #t) (send BUTTON_EXS_ACTION enable #t))) (begin (send BUTTON_EXS_ACTION enable #f) (send SLIDER_EXS_ANGLE enable #f))))) (style '(single vertical-label deleted)))) ;; Zone de texte pour déterminer la borne inférieure dans la paramétrisation cartésienne (define TFIELD_EXS_CART_INF (new text-field% (label "Borne inférieure = ") (parent GPANEL_EXS_REG) (callback (lambda (tf evt) (if (equal? (send evt get-event-type) 'text-field-enter) (begin (set! POLYGONE_EXS (polygone-nul)) (send MSG_EXS_CART set-label "") (set! CART_X (send TFIELD_EXS_CART_X get-value)) (set! CART_Y (send TFIELD_EXS_CART_Y get-value)) (set! CART_INF (send tf get-value)) (set! CART_SUP (send TFIELD_EXS_CART_SUP get-value)) (load (build-path "Exemples" "Courbe cartesienne.scm")) (when (not (polygone-nul? POLYGONE_EXS)) (send CANVAS_EXS on-paint) (send SLIDER_EXS_ANGLE enable #t) (send BUTTON_EXS_ACTION enable #t))) (begin (send BUTTON_EXS_ACTION enable #f) (send SLIDER_EXS_ANGLE enable #f))))) (style '(single vertical-label deleted)))) ;; Zone de texte pour déterminer la borne supérieure dans la paramétrisation cartésienne (define TFIELD_EXS_CART_SUP (new text-field% (label "Borne supérieure = ") (parent GPANEL_EXS_REG) (callback (lambda (tf evt) (if (equal? (send evt get-event-type) 'text-field-enter) (begin (set! POLYGONE_EXS (polygone-nul)) (send MSG_EXS_CART set-label "") (set! CART_X (send TFIELD_EXS_CART_X get-value)) (set! CART_Y (send TFIELD_EXS_CART_Y get-value)) (set! CART_INF (send TFIELD_EXS_CART_INF get-value)) (set! CART_SUP (send tf get-value)) (load (build-path "Exemples" "Courbe cartesienne.scm")) (when (not (polygone-nul? POLYGONE_EXS)) (send CANVAS_EXS on-paint) (send SLIDER_EXS_ANGLE enable #t) (send BUTTON_EXS_ACTION enable #t))) (begin (send BUTTON_EXS_ACTION enable #f) (send SLIDER_EXS_ANGLE enable #f))))) (style '(single vertical-label deleted)))) ;; Bouton pour créer le polygone selon la paramétrisation cartésienne donnée au-dessus (define BUTTON_EXS_CART (new button% (label "Créer") (parent GPANEL_EXS_REG) (callback (lambda (obj evt) (set! POLYGONE_EXS (polygone-nul)) (send MSG_EXS_CART set-label "") (set! CART_X (send TFIELD_EXS_CART_X get-value)) (set! CART_Y (send TFIELD_EXS_CART_Y get-value)) (set! CART_INF (send TFIELD_EXS_CART_INF get-value)) (set! CART_SUP (send TFIELD_EXS_CART_SUP get-value)) (load (build-path "Exemples" "Courbe cartesienne.scm")) (when (not (polygone-nul? POLYGONE_EXS)) (send CANVAS_EXS on-paint) (send SLIDER_EXS_ANGLE enable #t) (send BUTTON_EXS_ACTION enable #t)))) (style '(deleted)))) ;; Zone de message pour signaler les erreurs de la paramétrisation cartésienne de l'utilisateur (define MSG_EXS_CART (new message% (label " ") ; Les espaces dans le label ci-desus permettent de contenir les (éventuels) messages d'erreur (parent GPANEL_EXS_REG) (style '(deleted)))) ;; Zone de texte pour déterminer rho en fonction de t dans la paramétrisation polaire (define TFIELD_EXS_POL_RHO (new text-field% (label "\u03c1(t) = ") (parent GPANEL_EXS_REG) (callback (lambda (tf evt) (if (equal? (send evt get-event-type) 'text-field-enter) (begin (set! POLYGONE_EXS (polygone-nul)) (send MSG_EXS_POL set-label "") (set! POL_RHO (send tf get-value)) (set! POL_INF (send TFIELD_EXS_POL_INF get-value)) (set! POL_SUP (send TFIELD_EXS_POL_SUP get-value)) (load (build-path "Exemples" "Courbe polaire.scm")) (when (not (polygone-nul? POLYGONE_EXS)) (send CANVAS_EXS on-paint) (send SLIDER_EXS_ANGLE enable #t) (send BUTTON_EXS_ACTION enable #t))) (begin (send BUTTON_EXS_ACTION enable #f) (send SLIDER_EXS_ANGLE enable #f))))) (style '(single vertical-label deleted)))) ;; Zone de texte pour déterminer la borne inférieure dans la paramétrisation polaire (define TFIELD_EXS_POL_INF (new text-field% (label "Borne inférieure = ") (parent GPANEL_EXS_REG) (callback (lambda (tf evt) (if (equal? (send evt get-event-type) 'text-field-enter) (begin (set! POLYGONE_EXS (polygone-nul)) (send MSG_EXS_POL set-label "") (set! POL_RHO (send TFIELD_EXS_POL_RHO get-value)) (set! POL_INF (send tf get-value)) (set! POL_SUP (send TFIELD_EXS_POL_SUP get-value)) (load (build-path "Exemples" "Courbe polaire.scm")) (when (not (polygone-nul? POLYGONE_EXS)) (send CANVAS_EXS on-paint) (send SLIDER_EXS_ANGLE enable #t) (send BUTTON_EXS_ACTION enable #t))) (begin (send BUTTON_EXS_ACTION enable #f) (send SLIDER_EXS_ANGLE enable #f))))) (style '(single vertical-label deleted)))) ;; Zone de texte pour déterminer la borne supérieure dans la paramétrisation polaire (define TFIELD_EXS_POL_SUP (new text-field% (label "Borne supérieure = ") (parent GPANEL_EXS_REG) (callback (lambda (tf evt) (if (equal? (send evt get-event-type) 'text-field-enter) (begin (set! POLYGONE_EXS (polygone-nul)) (send MSG_EXS_POL set-label "") (set! POL_RHO (send TFIELD_EXS_POL_RHO get-value)) (set! POL_INF (send TFIELD_EXS_POL_INF get-value)) (set! POL_SUP (send tf get-value)) (load (build-path "Exemples" "Courbe polaire.scm")) (when (not (polygone-nul? POLYGONE_EXS)) (send CANVAS_EXS on-paint) (send SLIDER_EXS_ANGLE enable #t) (send BUTTON_EXS_ACTION enable #t))) (begin (send BUTTON_EXS_ACTION enable #f) (send SLIDER_EXS_ANGLE enable #f))))) (style '(single vertical-label deleted)))) ;; Bouton pour créer le polygone selon la paramétrisation polaire donnée au-dessus (define BUTTON_EXS_POL (new button% (label "Créer") (parent GPANEL_EXS_REG) (callback (lambda (obj evt) (set! POLYGONE_EXS (polygone-nul)) (send MSG_EXS_POL set-label "") (set! POL_RHO (send TFIELD_EXS_POL_RHO get-value)) (set! POL_INF (send TFIELD_EXS_POL_INF get-value)) (set! POL_SUP (send TFIELD_EXS_POL_SUP get-value)) (load (build-path "Exemples" "Courbe polaire.scm")) (when (not (polygone-nul? POLYGONE_EXS)) (send CANVAS_EXS on-paint) (send SLIDER_EXS_ANGLE enable #t) (send BUTTON_EXS_ACTION enable #t)))) (style '(deleted)))) ;; Zone de message pour signaler les erreurs de la paramétrisation polaire de l'utilisateur (define MSG_EXS_POL (new message% (label " ") (parent GPANEL_EXS_REG) (style '(deleted)))) ;;; Panneau de boutons (define VPANEL_EXS_BUTS (new vertical-panel% (parent VPANEL1) (style '(deleted)) (horiz-margin 10) (border 5) (alignment '(center center)) (stretchable-height #f))) ;; Bouton pour enclencher l'animation (define BUTTON_EXS_ACTION (new button% (label "Go") (parent VPANEL_EXS_BUTS) (callback (lambda (b evt) (case IND_ACTION ((#t) (set! IND_ACTION #f) (send BUTTON_EXS_ACTION set-label "Go") (case (car (send LBOX_EXS get-selections)) ((0) (send SLIDER_EXS_ANGLE enable #t) (let ((str (send RBOX_EXS_GRAV get-item-label (send RBOX_EXS_GRAV get-selection)))) (cond ((string=? str "Barre") (send SLIDER_EXS_BAR_LONG enable #t)) ((string=? str "Boucle infinie") (send SLIDER_EXS_INF_TAILLE enable #t)) ((string=? str "Ellipse") (send SLIDER_EXS_ELL_TAILLE enable #t)) ((string=? str "Escargot") (send SLIDER_EXS_ESC_TORSADE enable #t)) ((string=? str "Etoile") (send SLIDER_EXS_STAR_NB_BRAN enable #t)) ((string=? str "Haltere") (send SLIDER_EXS_HALT_TAILLE enable #t)) ((string=? str "Polygone regulier") (send SLIDER_EXS_POLYREG_NB_COTES enable #t)) ((string=? str "Quadrillage") (send SLIDER_EXS_QUA_COURB enable #t))))) ((1) ()) ((2) (send SLIDER_EXS_ANGLE enable #t) (if (string=? (send RBOX_EXS_PARAM get-item-label (send RBOX_EXS_PARAM get-selection)) "Courbe cartesienne") (begin (send TFIELD_EXS_CART_X enable #t) (send TFIELD_EXS_CART_Y enable #t) (send TFIELD_EXS_CART_INF enable #t) (send TFIELD_EXS_CART_SUP enable #t) (send BUTTON_EXS_CART enable #t)) (begin (send TFIELD_EXS_POL_RHO enable #t) (send TFIELD_EXS_POL_INF enable #t) (send TFIELD_EXS_POL_SUP enable #t) (send BUTTON_EXS_POL enable #t))))) (send CANVAS_EXS on-paint)) (else (set! IND_ACTION #t) (send BUTTON_EXS_ACTION set-label "Stop") (case (car (send LBOX_EXS get-selections)) ((0) (send SLIDER_EXS_ANGLE enable #f) (let ((str (send RBOX_EXS_GRAV get-item-label (send RBOX_EXS_GRAV get-selection)))) (cond ((string=? str "Barre") (send SLIDER_EXS_BAR_LONG enable #f)) ((string=? str "Boucle infinie") (send SLIDER_EXS_INF_TAILLE enable #f)) ((string=? str "Ellipse") (send SLIDER_EXS_ELL_TAILLE enable #f)) ((string=? str "Escargot") (send SLIDER_EXS_ESC_TORSADE enable #f)) ((string=? str "Etoile") (send SLIDER_EXS_STAR_NB_BRAN enable #f)) ((string=? str "Haltere") (send SLIDER_EXS_HALT_TAILLE enable #f)) ((string=? str "Polygone regulier") (send SLIDER_EXS_POLYREG_NB_COTES enable #f)) ((string=? str "Quadrillage") (send SLIDER_EXS_QUA_COURB enable #f))))) ((1) ()) ((2) (send SLIDER_EXS_ANGLE enable #f) (if (string=? (send RBOX_EXS_PARAM get-item-label (send RBOX_EXS_PARAM get-selection)) "Courbe cartesienne") (begin (send TFIELD_EXS_CART_X enable #f) (send TFIELD_EXS_CART_Y enable #f) (send TFIELD_EXS_CART_INF enable #f) (send TFIELD_EXS_CART_SUP enable #f) (send BUTTON_EXS_CART enable #f)) (begin (send TFIELD_EXS_POL_RHO enable #f) (send TFIELD_EXS_POL_INF enable #f) (send TFIELD_EXS_POL_SUP enable #f) (send BUTTON_EXS_POL enable #f))))) (send CANVAS_EXS on-paint))))))) ;; Bouton de retour au menu initial (define BUTTON_EXS_MENU (new button% (label "Menu") (parent VPANEL_EXS_BUTS) (callback (lambda (b evt) (set! IND_ACTION #f) (change-fils VPANEL1 (list GPANEL_INIT_SELECT GPANEL_INIT_DOC)) (change-fils VPANEL2 (list CANVAS_INIT)))))) ;;;; Panneaux pour la partie objet ;;; Panneau de sélection des exemples objet (define GPANEL_OBJ_SELECT (new group-box-panel% (label "Exemples Objet") (parent VPANEL1) (style '(deleted)) (vert-margin 5) (horiz-margin 10) (spacing 10) (border 5) (alignment '(center center)) (stretchable-height #f))) ;; Radio-box pour les phénomènes physiques (define RBOX_OBJ (new my-radio-box% (label "Phénomènes physiques") (choices (list "Deux boules" "Boules multiples" "Gravite" "Pendule")) (parent GPANEL_OBJ_SELECT) (callback (lambda (rb evt) (let ((str (send rb get-item-label (send rb get-selection)))) (init-objet) (set! IND_ACTION #f) (send BUTTON_OBJ_ACTION set-label "Go") (cond ((string=? str "Deux boules") (set! M1_2B 1) (send SLIDER_OBJ_2B_M1 set-value 1) (send SLIDER_OBJ_2B_M1 enable #t) (set! M2_2B 1) (send SLIDER_OBJ_2B_M2 set-value 1) (send SLIDER_OBJ_2B_M2 enable #t) (set! V1_2B (make-vect -5 0)) (send SLIDER_OBJ_2B_V1 set-value -5) (send SLIDER_OBJ_2B_V1 enable #t) (set! V2_2B (make-vect 0 0)) (send SLIDER_OBJ_2B_V2 set-value 0) (send SLIDER_OBJ_2B_V2 enable #t) (set! R1_2B 60) (send SLIDER_OBJ_2B_R1 set-value 60) (send SLIDER_OBJ_2B_R1 enable #t) (set! R2_2B 60) (send SLIDER_OBJ_2B_R2 set-value 60) (send SLIDER_OBJ_2B_R2 enable #t) (change-fils GPANEL_OBJ_REG (list SLIDER_OBJ_2B_M1 SLIDER_OBJ_2B_M2 SLIDER_OBJ_2B_R1 SLIDER_OBJ_2B_R2 SLIDER_OBJ_2B_V1 SLIDER_OBJ_2B_V2))) ((string=? str "Boules multiples") (set! NB_BAL 20) (send SLIDER_OBJ_BAL_NB set-value 20) (send SLIDER_OBJ_BAL_NB enable #t) (change-fils GPANEL_OBJ_REG (list SLIDER_OBJ_BAL_NB))) ((string=? str "Gravite") (set! GRAVITE 0.1) (send SLIDER_OBJ_GRAV_G set-value 10) (send SLIDER_OBJ_GRAV_G enable #t) (set! M_GRAV 1) (send SLIDER_OBJ_GRAV_M set-value 1) (send SLIDER_OBJ_GRAV_M enable #t) (set! V_GRAV (make-vect -1 0)) (send SLIDER_OBJ_GRAV_V set-value -1) (send SLIDER_OBJ_GRAV_V enable #t) (set! R_GRAV 50) (send SLIDER_OBJ_GRAV_R set-value 50) (send SLIDER_OBJ_GRAV_R enable #t) (change-fils GPANEL_OBJ_REG (list SLIDER_OBJ_GRAV_G SLIDER_OBJ_GRAV_M SLIDER_OBJ_GRAV_R SLIDER_OBJ_GRAV_V))) ((string=? str "Pendule") (set! NB_PEND 5) (send SLIDER_OBJ_PEND_NB set-value 5) (send SLIDER_OBJ_PEND_NB enable #t) (change-fils GPANEL_OBJ_REG (list SLIDER_OBJ_PEND_NB)))) (load (build-path "Objets" (string-append (send rb get-item-label (send rb get-selection)) ".scm"))) (send CANVAS_OBJ on-paint)))) (style '(vertical vertical-label)))) ;;; Panneau de visualisation des exemples objet (define GPANEL_OBJ_VISU (new group-box-panel% (label "Visualisation") (parent VPANEL1) (style '(deleted)) (vert-margin 5) (horiz-margin 10) (spacing 10) (border 5) (alignment '(center center)))) ;; Case à cocher pour le centre de masse (define CBOX_OBJ_CM (new check-box% (label "Centre de masse du système") (parent GPANEL_OBJ_VISU) (callback (lambda (c evt) (case AFFICHE_OBJ_CM ((#t) (set! AFFICHE_OBJ_CM #f) (send CANVAS_OBJ on-paint)) (else (set! AFFICHE_OBJ_CM #t) (send CANVAS_OBJ on-paint))))) )) ;;; Panneau de réglages des exemples objet (define GPANEL_OBJ_REG (new group-box-panel% (label "Réglages") (parent VPANEL1) (style '(deleted)) (vert-margin 5) (horiz-margin 10) (spacing 10) (border 5) (alignment '(center center)) (stretchable-height #f))) ;; Slider pour régler la masse de la première boule dans Deux Boules (define SLIDER_OBJ_2B_M1 (new slider% (label "Masse de la 1ère boule") (min-value 1) (max-value 7) (init-value 1) (parent GPANEL_OBJ_REG) (callback (lambda (sl evt) (init-objet) (set! M1_2B (send sl get-value)) (load (build-path "Objets" "Deux boules.scm")) (send CANVAS_OBJ on-paint))) (style '(horizontal vertical-label)))) ;; Slider pour régler la masse de la deuxième boule dans Deux Boules (define SLIDER_OBJ_2B_M2 (new slider% (label "Masse de la 2ème boule") (min-value 1) (max-value 7) (init-value 1) (parent GPANEL_OBJ_REG) (callback (lambda (sl evt) (init-objet) (set! M2_2B (send sl get-value)) (load (build-path "Objets" "Deux boules.scm")) (send CANVAS_OBJ on-paint))) (style '(horizontal vertical-label)))) ;; Slider pour régler le rayon de la première boule dans Deux Boules (define SLIDER_OBJ_2B_R1 (new slider% (label "Rayon de la 1ère boule") (min-value 10) (max-value 100) (init-value 60) (parent GPANEL_OBJ_REG) (callback (lambda (sl evt) (init-objet) (set! R1_2B (send sl get-value)) (load (build-path "Objets" "Deux boules.scm")) (send CANVAS_OBJ on-paint))) (style '(horizontal vertical-label)))) ;; Slider pour régler le rayon de la deuxième boule dans Deux Boules (define SLIDER_OBJ_2B_R2 (new slider% (label "Rayon de la 2éme boule") (min-value 10) (max-value 100) (init-value 60) (parent GPANEL_OBJ_REG) (callback (lambda (sl evt) (init-objet) (set! R2_2B (send sl get-value)) (load (build-path "Objets" "Deux boules.scm")) (send CANVAS_OBJ on-paint))) (style '(horizontal vertical-label)))) ;; Slider pour régler la vitesse de la première boule dans Deux Boules (define SLIDER_OBJ_2B_V1 (new slider% (label "Vitesse de la 1ère boule") (min-value -5) (max-value 5) (init-value 0) (parent GPANEL_OBJ_REG) (callback (lambda (sl evt) (init-objet) (set! V1_2B (make-vect (send sl get-value) 0)) (load (build-path "Objets" "Deux boules.scm")) (send CANVAS_OBJ on-paint))) (style '(horizontal vertical-label)))) ;; Slider pour régler la vitesse de la deuxième boule dans Deux Boules (define SLIDER_OBJ_2B_V2 (new slider% (label "Vitesse de la 2éme boule") (min-value -5) (max-value 5) (init-value -5) (parent GPANEL_OBJ_REG) (callback (lambda (sl evt) (init-objet) (set! V2_2B (make-vect (send sl get-value) 0)) (load (build-path "Objets" "Deux boules.scm")) (send CANVAS_OBJ on-paint))) (style '(horizontal vertical-label)))) ;; Slider pour régler le nombre de boules dans Boules Multiples (define SLIDER_OBJ_BAL_NB (new slider% (label "Nombre de boules") (min-value 10) (max-value 30) (init-value 20) (parent GPANEL_OBJ_REG) (callback (lambda (sl evt) (init-objet) (set! NB_BAL (send sl get-value)) (actualiser_nombre) (send CANVAS_OBJ on-paint))) (style '(horizontal vertical-label deleted)))) ;; Slider pour régler la gravitation dans Gravité (define SLIDER_OBJ_GRAV_G (new slider% (label "Coefficient de gravitation (%)") (min-value 0) (max-value 100) (init-value 10) (parent GPANEL_OBJ_REG) (callback (lambda (sl evt) (if (not IND_ACTION) (begin (init-objet) (load (build-path "Objets" "Gravite.scm")))) (set! GRAVITE (/ (send sl get-value) 100)) (send CANVAS_OBJ on-paint))) (style '(horizontal vertical-label deleted)))) ;; Slider pour régler la masse dans Gravité (define SLIDER_OBJ_GRAV_M (new slider% (label "Masse") (min-value 1) (max-value 7) (init-value 1) (parent GPANEL_OBJ_REG) (callback (lambda (sl evt) (init-objet) (set! GRAVITE (/ (send SLIDER_OBJ_GRAV_G get-value) 100)) (set! M_GRAV (send sl get-value)) (load (build-path "Objets" "Gravite.scm")) (send CANVAS_OBJ on-paint))) (style '(horizontal vertical-label deleted)))) ;; Slider pour régler le rayon dans Gravité (define SLIDER_OBJ_GRAV_R (new slider% (label "Rayon") (min-value 10) (max-value 100) (init-value 50) (parent GPANEL_OBJ_REG) (callback (lambda (sl evt) (init-objet) (set! GRAVITE (/ (send SLIDER_OBJ_GRAV_G get-value) 100)) (set! R_GRAV (send sl get-value)) (load (build-path "Objets" "Gravite.scm")) (send CANVAS_OBJ on-paint))) (style '(horizontal vertical-label)))) ;; Slider pour régler la vitesse dans Gravité (define SLIDER_OBJ_GRAV_V (new slider% (label "Vitesse") (min-value -10) (max-value 10) (init-value -1) (parent GPANEL_OBJ_REG) (callback (lambda (sl evt) (init-objet) (set! GRAVITE (/ (send SLIDER_OBJ_GRAV_G get-value) 100)) (set! V_GRAV (make-vect (send sl get-value) 0)) (load (build-path "Objets" "Gravite.scm")) (send CANVAS_OBJ on-paint))) (style '(horizontal vertical-label)))) ;; Slider pour régler le nombre de boules dans Pendule (define SLIDER_OBJ_PEND_NB (new slider% (label "Nombre de boules") (min-value 3) (max-value 7) (init-value 5) (parent GPANEL_OBJ_REG) (callback (lambda (sl evt) (init-objet) (set! NB_PEND (send sl get-value)) (load (build-path "Objets" "Pendule.scm")) (send CANVAS_OBJ on-paint))) (style '(horizontal vertical-label deleted)))) ;;; Panneau de boutons (define VPANEL_OBJ_BUTS (new vertical-panel% (parent VPANEL1) (style '(deleted)) (vert-margin 5) (horiz-margin 10) (spacing 10) (border 5) (alignment '(center center)) (stretchable-height #f))) ;; Bouton pour enclencher l'animation (define BUTTON_OBJ_ACTION (new button% (label "Go") (parent VPANEL_OBJ_BUTS) (callback (lambda (b evt) (let ((str (send RBOX_OBJ get-item-label (send RBOX_OBJ get-selection)))) (case IND_ACTION ((#t) (set! IND_ACTION #f) (send BUTTON_OBJ_ACTION set-label "Go") (cond ((string=? str "Deux boules") (send SLIDER_OBJ_2B_M1 enable #t) (send SLIDER_OBJ_2B_M2 enable #t) (send SLIDER_OBJ_2B_R1 enable #t) (send SLIDER_OBJ_2B_R2 enable #t) (send SLIDER_OBJ_2B_V1 enable #t) (send SLIDER_OBJ_2B_V2 enable #t)) ((string=? str "Boules multiples") (void)) ((string=? str "Gravite") (send SLIDER_OBJ_GRAV_M enable #t) (send SLIDER_OBJ_GRAV_R enable #t) (send SLIDER_OBJ_GRAV_V enable #t)) ((string=? str "Pendule") (send SLIDER_OBJ_PEND_NB enable #t))) (send CANVAS_OBJ on-paint)) (else (set! IND_ACTION #t) (send BUTTON_OBJ_ACTION set-label "Stop") (cond ((string=? str "Deux boules") (send SLIDER_OBJ_2B_M1 enable #f) (send SLIDER_OBJ_2B_M2 enable #f) (send SLIDER_OBJ_2B_R1 enable #f) (send SLIDER_OBJ_2B_R2 enable #f) (send SLIDER_OBJ_2B_V1 enable #f) (send SLIDER_OBJ_2B_V2 enable #f)) ((string=? str "Boules multiples") (send SLIDER_OBJ_BAL_NB enable #f)) ((string=? str "Gravite") (send SLIDER_OBJ_GRAV_M enable #f) (send SLIDER_OBJ_GRAV_R enable #f) (send SLIDER_OBJ_GRAV_V enable #f)) ((string=? str "Pendule") (send SLIDER_OBJ_PEND_NB enable #f))) (send CANVAS_OBJ on-paint)))))))) ;; Bouton de retour au menu initial (define BUTTON_OBJ_MENU (new button% (label "Menu") (parent VPANEL_OBJ_BUTS) (callback (lambda (b evt) (send BITMAP-DC set-background COLOR_BACK) (set! IND_ACTION #f) (send AFF_TRA enable #t) (send AFF_CM enable #t) (send AFF_EC enable #t) (send AFF_FOND set-label "Changer la couleur de fond pour les sections Dessin et Exemples") (change-fils VPANEL1 (list GPANEL_INIT_SELECT GPANEL_INIT_DOC)) (change-fils VPANEL2 (list CANVAS_INIT)))))) ;***************************************************** ; GESTION DES CANVAS ;***************************************************** ;;;; Bitmap-dc associé à un bitmap pour le double-buffer utilisés pour tous les canvas (define BITMAP (make-object bitmap% 500 500)) (define BITMAP-DC (new bitmap-dc% (bitmap BITMAP))) (send BITMAP-DC set-background (make-object color% "azure")) ;;;; Canvas initial (define CANVAS_INIT (new canvas% (parent VPANEL2) (min-width 615) (min-height 460) (paint-callback (lambda (c dc) (send dc draw-bitmap (make-object bitmap% (build-path 'same "Images" "Icones" "sommaire.jpg") 'jpeg #f) 0 0 'solid))) (stretchable-width #f) (stretchable-height #f))) ;;;; Canvas pour le dessin ;; Méthodes privées (define (affiche poly dc type_polygone) ; aussi utilisée pour les exemples (send dc clear) (when (vector? poly) (let ((Lpoly (vector->list poly))) (map (lambda (x) (affiche-polygone x dc COLOR_POLY 'exemples) (affiche-polygone x dc COLOR_POLY 'exemples)) Lpoly) (when AFFICHE_EC (map (lambda (x) (affiche-ev x dc COLOR_EC)) Lpoly)) (when AFFICHE_CM (map (lambda (x) (affiche-centre x dc COLOR_CM)) Lpoly)))) (when (not (vector? poly)) (if (equal? 'exemples type_polygone) (affiche-polygone poly dc COLOR_POLY 'exemples) (affiche-polygone poly dc COLOR_POLY 'ligne_polygonale)) (when AFFICHE_EC (affiche-ev poly dc COLOR_EC)) (when AFFICHE_CM (affiche-centre poly dc COLOR_CM)))) (define (action poly) ; aussi utilisée pour les exemples (when (vector? poly) (for i from 0 to (- (vector-length poly) 1) (for j from (add1 i) to (- (vector-length poly) 1) (when (<= (norme (-vect (masse-r (polygone-cm (vector-ref poly i))) (masse-r (polygone-cm (vector-ref poly j))))) (+ (polygone-rayon (vector-ref poly i)) (polygone-rayon (vector-ref poly j)))) (let ((inter (intersection (vector-ref poly i) (vector-ref poly j) 0.5))) (when inter (evolution inter)))))) (map (lambda (x) (next x E)) (vector->list poly))) (when (not (vector? poly)) (next poly E))) (define (rajout dc evt) (let ((x (max 10 (min 490 (send evt get-x)))) (y (max 10 (min 490 (send evt get-y))))) (ajouter-point x y) ; Considération du point (affiche-liste L dc COLOR_POLY))) ; Affichage des points ; Définition d'une nouvelle classe Canvas pour le dessin (define canvas-draw% (class canvas% (init-field (evolution (make-vect 0 0))) (define/override (on-event evt) (if (polygone-nul? POLYGONE) ; Le canvas est vierge, le dessin n'a pas été tracé (case (send evt get-event-type) ((left-down) (rajout (send this get-dc) evt) (set! IND_CLIC #t) (set! IND_ACTION #f) (send BUTTON_DRAW_ACTION set-label "Go") (send this on-paint)) ((left-up) (set! IND_CLIC #f) ; Création du polygone (creer-poly) (send this on-paint)) (else (when IND_CLIC ; Si le clic gauche est enfoncé (set! COMPT (modulo (add1 COMPT) 2)) ; Pour ne prendre qu'un point sur deux (when (zero? COMPT) (rajout (send this get-dc) evt))))) ; Le dessin a déjà été tracé (case (send evt get-event-type) ((left-down) (when ;pour pouvoir saisir l'objet par le centre de masse, il faut que la boule enveloppante ;soit à une distance minimale des bords de la fenêtre de 25px ;et que le curseur soit à 15px du centre de masse (and (<= (norme (-vect (make-vect (send evt get-x) (send evt get-y)) (masse-r (polygone-cm POLYGONE)))) 15) (<= (+ (polygone-rayon POLYGONE) (send evt get-x)) 475) (<= (+ (polygone-rayon POLYGONE) (send evt get-y)) 475) (>= (- (send evt get-x) (polygone-rayon POLYGONE)) 25) (>= (- (send evt get-y) (polygone-rayon POLYGONE)) 25)) ;si tel est le cas, on change de curseur (send this set-cursor (make-object cursor% 'hand)) ;on active le témoin de clic (set! IND_CLIC #t) ;on stoppe l'évolution (set! IND_ACTION #f) (send BUTTON_DRAW_ACTION set-label "Stop") (send this on-paint))) ((left-up) ;quand on relache le clic (when IND_CLIC ;on désactive le témoin de clic (set! IND_CLIC #f) ;on met la figure en mouvement (set! IND_ACTION #t) ;on lui communique en vitesse de translation la dernière vitesse transmise à main levée ;minorée si besoin (pour éviter des vitesses trop élevées) (set-polygone-vtrans! POLYGONE (let* ((evol (*vect 0.1 evolution)) (n (norme evol))) (if (<= n 2) evol (*vect 2 (*vect (/ 1 n) evol))))) (set! evolution (make-vect 0 0)) (send this set-cursor (make-object cursor% 'cross)) (send this on-paint))) (else ;lorsque l'on survole le canvas (if ;si le clic est enfoncé IND_CLIC (if ;et si la boule enveloppante est dans la fenêtre (and (<= (+ (polygone-rayon POLYGONE) (send evt get-x)) 500) (<= (+ (polygone-rayon POLYGONE) (send evt get-y)) 500) (>= (- (send evt get-x) (polygone-rayon POLYGONE)) 0) (>= (- (send evt get-y) (polygone-rayon POLYGONE)) 0)) ;on actualise le vecteur déplacement evolution (begin (set! evolution (-vect (make-vect (send evt get-x) (send evt get-y)) (masse-r (polygone-cm POLYGONE)))) ;on translate tous les points du polygone (for i from 0 to (- (polygone-size POLYGONE) 1) (set-masse-r! (vector-ref (polygone-poly POLYGONE) i) (+vect (masse-r (vector-ref (polygone-poly POLYGONE) i)) evolution))) ;ainsi que son centre de masse (set-masse-r! (polygone-cm POLYGONE) (+vect (masse-r (polygone-cm POLYGONE)) evolution)) ;et le curseur reste une main (send this set-cursor (make-object cursor% 'hand)) (send this on-paint)) ;sinon, le curseur redevient une croix (send this set-cursor (make-object cursor% 'cross))) ;si le clic n'est pas enfoncé (if ;on affiche la main si la boule enveloppante ;est à une distance minimale des bords de la fenêtre de 25px ;et que le curseur est à 15px du centre de masse (and (<= (norme (-vect (make-vect (send evt get-x) (send evt get-y)) (masse-r (polygone-cm POLYGONE)))) 15) (<= (+ (polygone-rayon POLYGONE) (send evt get-x)) 475) (<= (+ (polygone-rayon POLYGONE) (send evt get-y)) 475) (>= (- (send evt get-x) (polygone-rayon POLYGONE)) 25) (>= (- (send evt get-y) (polygone-rayon POLYGONE)) 25)) (send this set-cursor (make-object cursor% 'hand)) (send this set-cursor (make-object cursor% 'cross)))))))) (super-new))) ;;;; Canvas pour le dessin à main levée (define CANVAS_DRAW (new canvas-draw% (parent VPANEL2) (min-width 500) (min-height 500) (style '(deleted)) (paint-callback (lambda (c dc) (do () ((not IND_ACTION) ) (action POLYGONE) (affiche POLYGONE BITMAP-DC 'ligne_polygonale) (send dc draw-bitmap BITMAP 0 0 'solid) (next POLYGONE E) (sleep/yield (/ 1 100.))) (affiche POLYGONE BITMAP-DC 'ligne_polygonale) (send dc draw-bitmap BITMAP 0 0 'solid))) (stretchable-width #f) (stretchable-height #f))) ; Affichage d'un curseur en forme de croix au-dessus de la fenêtre du canvas du dessin (send CANVAS_DRAW set-cursor (make-object cursor% 'cross)) ;;;; Canvas pour les exemples (define CANVAS_EXS (new canvas% (parent VPANEL2) (min-width 500) (min-height 500) (style '(deleted)) (paint-callback (lambda (c dc) (do () ((not IND_ACTION) ) (action POLYGONE_EXS) (if (equal? "Parametrisation" (send LBOX_EXS get-string-selection)) (affiche POLYGONE_EXS BITMAP-DC 'ligne-polygonale) (affiche POLYGONE_EXS BITMAP-DC 'exemples)) (send dc draw-bitmap BITMAP 0 0 'solid) (sleep/yield (/ 1 100.))) (if (equal? "Parametrisation" (send LBOX_EXS get-string-selection)) (affiche POLYGONE_EXS BITMAP-DC 'ligne-polygonale) (affiche POLYGONE_EXS BITMAP-DC 'exemples)) (send dc draw-bitmap BITMAP 0 0 'solid))) (stretchable-width #f) (stretchable-height #f))) ;;;; Canvas pour la partie objet (define CANVAS_OBJ (new canvas% (parent VPANEL2) (min-width 500) (min-height 500) (style '(deleted)) (paint-callback (lambda (c dc) (do () ((not IND_ACTION) ) (send BITMAP-DC clear) (action-obj BITMAP-DC) (affiche-obj BITMAP-DC) (send dc draw-bitmap BITMAP 0 0 'solid) (sleep/yield (/ 1 24.))) (send BITMAP-DC clear) (affiche-obj BITMAP-DC) (send dc draw-bitmap BITMAP 0 0 'solid))) (stretchable-width #f) (stretchable-height #f))) ; Centrage de la fenêtre seulement horizontalement (du fait de sa hauteur) (send FRAME1 center 'horizontal) ; Affichage de l'icône en haut à gauche de la fenêtre, dans la barre des tâches (non valable sur Mac OS X) et dans la barre ouverte avec Atl-Tab (seulement sur Windows) (send FRAME1 set-icon (make-object bitmap% (build-path (current-directory) "Images" "Icones" "phi.jpg") 'jpeg #f)) ; Affichage de la fenêtre (send FRAME1 show #t)
false
56bc946bbe7bf038696554977a0737efc4f6278c
d11ad5e19d63d2cf6ca69f12ecae02a9b9871ad3
/ml/ml-reader.ss
782ed20f86a3227591ff4849a7415d94b2dd908c
[ "Apache-2.0" ]
permissive
willfaught/sham1
3e708368a02ce8af204dbf26cc94f01e75ea39a8
371e9a6fd810628f8e9a79868b9f457bfcf8dc29
refs/heads/master
2022-08-28T20:46:09.904927
2022-08-18T22:04:51
2022-08-18T22:04:51
151,862
1
0
null
null
null
null
UTF-8
Scheme
false
false
18,313
ss
ml-reader.ss
; This file contains a reader for a subset of OCaml that is able to share higher-order, polymorphic functions with mzscheme, while preserving parametricity ; By David Kinghorn ;; now by me too! (JBC, 2007-06-19) ; TODO: get tuples and nested tuples to work properly ; TODO: do lots of testing ; TODO: Add units and variants to the language. (module ml-reader mzscheme (require (lib "lex.ss" "parser-tools") (prefix : (lib "lex-sre.ss" "parser-tools")) (lib "yacc.ss" "parser-tools") (lib "readerr.ss" "syntax") (lib "list.ss") "stack.ss" "ml-expander.ss" "ml-typechecker.ss" scheme/pretty) (require (planet "test.ss" ("schematics" "schemeunit.plt" 2)) (only (lib "list.ss" "srfi" "1") lset=)) (provide ml-read-syntax unification-test-suite) (define-tokens regular (ID LITNUM TYVAR FILENAME LITSTRING CAPID)) (define-empty-tokens keywords (EQUALS IN LET REC SEMICOLON COLON-G LUMP INT STRING ARROW IF THEN ELSE PLUS MINUS STAR LPAREN RPAREN DIVIDE FILE HASH-SCHEME TRUE FALSE BOOL AND OR NOT NE GE GT LE LT MODULE INCLUDE MOD FUN FUNCTION COMMA TYPE PIPE OF EOF)) (define-lex-abbrevs (lower-letter (:/ "a" "z")) (upper-letter (:/ #\A #\Z)) (litnum-start (:or "+" "-" digit)) (digit (:/ "0" "9")) (id-cont (:or lower-letter upper-letter digit "_" "-")) (file-cont (:or lower-letter upper-letter digit "_" "-" ".")) (comment-start "(*") (comment-end "*)")) (define simple-lexer (lexer-src-pos [whitespace (return-without-pos (simple-lexer input-port))] [comment-start (return-without-pos ((comment-lexer 1) input-port))] ;; TODO: signal a read error here: [comment-end (error 'simple-lexer "End of comment outside of comment block.")] ["=" (token-EQUALS)] [";" (token-SEMICOLON)] [":G" (token-COLON-G)] ["->" (token-ARROW)] ["+" (token-PLUS)] ["-" (token-MINUS)] ["*" (token-STAR)] ["/" (token-DIVIDE)] ["(" (token-LPAREN)] [")" (token-RPAREN)] ["<>" (token-NE)] [">=" (token-GE)] [">" (token-GT)] ["<=" (token-LE)] ["<" (token-LT)] ["&" (token-AND)] ["," (token-COMMA)] ["|" (token-PIPE)] ["#include" (token-INCLUDE)] ["#module" (token-MODULE)] [(:: lower-letter (:* id-cont)) (keyword-filter lexeme)] [(:: upper-letter (:* id-cont)) (token-CAPID lexeme)] [(:: "'" (:or lower-letter upper-letter) (:* id-cont)) (token-TYVAR lexeme)] [(:: litnum-start (:* digit)) (token-LITNUM lexeme)] ;; disallow strings with embedded double-quotes, for now. [(:: #\" (:* (:~ #\")) #\") (token-LITSTRING (substring lexeme 1 (- (string-length lexeme) 1)))] [(eof) (token-EOF)])) ; Enable nested comments (define (comment-lexer level) (lexer [comment-start ((comment-lexer (+ level 1)) input-port)] [comment-end (if (= level 1) (simple-lexer input-port) ((comment-lexer (- level 1)) input-port))] [(:or (:~ whitespace) whitespace) ((comment-lexer level) input-port)] [(eof) (error 'comment-lexer "End of file occured inside a comment.")])) ;; keyword-filter : string -> token (define (keyword-filter str) (let ([maybe-kwd (assoc str keyword-list)]) (if maybe-kwd ((cadr maybe-kwd)) (token-ID str)))) (define keyword-list `(("let" ,token-LET) ("in" ,token-IN) ("if" ,token-IF) ("then" ,token-THEN) ("else" ,token-ELSE) ("lump" ,token-LUMP) ("int" ,token-INT) ("string" ,token-STRING) ("rec" ,token-REC) ("file" ,token-FILE) ("true" ,token-TRUE) ("false" ,token-FALSE) ("bool" ,token-BOOL) ("not" ,token-NOT) ("or" ,token-OR) ("mod" ,token-MOD) ("fun" ,token-FUN) ("function" ,token-FUNCTION) ("type" ,token-TYPE) ("of" ,token-OF))) (print-struct #t) (define stx-for-original-property (read-syntax #f (open-input-string "original"))) (define-syntax (build-so stx) (syntax-case stx () ((_ value start end) (with-syntax ((start-pos (datum->syntax-object (syntax end) (string->symbol (format "$~a-start-pos" (syntax-object->datum (syntax start)))))) (end-pos (datum->syntax-object (syntax end) (string->symbol (format "$~a-end-pos" (syntax-object->datum (syntax end)))))) (source (datum->syntax-object (syntax end) 'source-name))) (syntax (datum->syntax-object #f value (list source (position-line start-pos) (position-col start-pos) (position-offset start-pos) (- (position-offset end-pos) (position-offset start-pos))) stx-for-original-property)))))) (define (ml-parser source-name) (parser (src-pos) (start program) (end EOF) (tokens regular keywords) (error (lambda (a name val start end) (raise-read-error "parse error" source-name (position-line start) (position-col start) (position-offset start) (- (position-offset end) (position-offset start))))) (grammar (program [(module includes defs) (make-program (build-so $1 1 3) $1 $2 $3)]) (module [(MODULE LPAREN LITSTRING RPAREN) (string->symbol $3)]) (includes [(INCLUDE LPAREN files RPAREN) $3]) (files [(file files) (cons $1 $2)] [() null]) (file [(LITSTRING) $1]) (defs [(defn defs) (cons $1 $2)] [() null]) (defn [(LET REC id params EQUALS exp SEMICOLON SEMICOLON) (make-let-def (build-so $3 1 7) $3 $4 $6 #t)] [(LET id params EQUALS exp SEMICOLON SEMICOLON) (make-let-def (build-so $2 1 6) $2 $3 $5 #f)] [(TYPE id EQUALS constr-decls SEMICOLON SEMICOLON) (make-typedef (build-so $2 1 4) $2 $4)]) (constr-decls [(constr-decl PIPE constr-decls) (cons $1 $3)] [(constr-decl) (list $1)]) (constr-decl [(CAPID) (make-constr-decl/0ary (build-so $1 1 1) $1)] [(CAPID OF type) (make-constr-decl (build-so $1 1 3) $1 $3)]) (params [(param params) (cons $1 $2)] [() null]) (param [(param-tuple-list) (if (null? (cdr $1)) (car $1) (make-tuple (build-so $1 1 1) $1))]) (param-tuple-list [(simple-param COMMA param-tuple-list) (cons $1 $3)] [(simple-param) (list $1)]) (simple-param [(id) $1] [(LPAREN param RPAREN) $2]) (exp [(LET REC id params EQUALS exp IN exp) (make-let-exp (build-so $3 1 8) $3 $4 $6 $8 #t)] [(LET id params EQUALS exp IN exp) (make-let-exp (build-so $2 1 7) $2 $3 $5 $7 #f)] [(FUNCTION param ARROW exp) (make-anonymous-function (build-so $2 1 4) (list $2) $4)] [(FUN param ARROW exp) (make-anonymous-function (build-so $2 1 4) (list $2) $4)] [(IF exp THEN exp ELSE exp) (make-if-exp (build-so $2 1 6) $2 $4 $6)] [(id COLON-G type) (make-ms (build-so $1 1 3) $1 (replace-unbound-tyvars-with-fresh-tyvars $3))] [(tuple-exp) $1]) (tuple-exp [(tuple-list) (if (null? (cdr $1)) (car $1) (make-tuple (build-so $1 1 1) $1))]) (tuple-list [(logical-exp COMMA tuple-list) (cons $1 $3)] [(logical-exp) (list $1)]) (logical-exp [(NOT comparison-exp) (make-app (build-so $2 1 2) (anon-ms (anon-id 'not) (anon-arrow anon-bool anon-bool)) (list $2))] ; And and Or need to be short circuited, so they are converted to conditional expressions rather than Scheme Imports [(comparison-exp OR comparison-exp) (make-if-exp (build-so $1 1 3) $1 (make-bool #f #t) $3)] [(comparison-exp AND comparison-exp) (make-if-exp (build-so $1 1 3) $1 $3 (make-bool #f #f))] [(comparison-exp) $1]) (comparison-exp ; I would like to do the following, but I can't because the import hides the actual arguments from Scheme ; Create an import that doesn't do any checking? I can't just change the type of the arguments because I want ML's typechecker run on the two arguments first ; [(mul-exp EQUALS mul-exp) (make-app (build-so $1 1 3) (anon-ms (anon-id 'ml-equals) (anon-arrow (anon-tyvar 'a) (anon-tyvar 'a) anon-bool)) (list $1 $3))] ; [(mul-exp NE mul-exp) (make-app (build-so $1 1 3) (anon-ms (anon-id 'ml-ne) (anon-arrow (anon-tyvar 'a) (anon-tyvar 'a) anon-bool)) (list $1 $3))] ;; JBC: okay, I introduced a prim term to handle this. [(mul-exp EQUALS mul-exp) (make-app (build-so $1 1 3) (make-prim #f 'equals) (list $1 $3))] [(mul-exp NE mul-exp) (make-app (build-so $1 1 3) (anon-ms (anon-id 'ml-ne) (anon-arrow anon-int anon-int anon-bool)) (list $1 $3))] [(mul-exp GE mul-exp) (make-app (build-so $1 1 3) (anon-ms (anon-id 'ml-ge) (anon-arrow anon-int anon-int anon-bool)) (list $1 $3))] [(mul-exp GT mul-exp) (make-app (build-so $1 1 3) (anon-ms (anon-id 'ml-gt) (anon-arrow anon-int anon-int anon-bool)) (list $1 $3))] [(mul-exp LE mul-exp) (make-app (build-so $1 1 3) (anon-ms (anon-id 'ml-le) (anon-arrow anon-int anon-int anon-bool)) (list $1 $3))] [(mul-exp LT mul-exp) (make-app (build-so $1 1 3) (anon-ms (anon-id 'ml-lt) (anon-arrow anon-int anon-int anon-bool)) (list $1 $3))] [(mul-exp) $1]) (mul-exp [(add-exp STAR add-exp) (make-app (build-so $1 1 3) (anon-ms (anon-id 'ml-times) (anon-arrow anon-int anon-int anon-int)) (list $1 $3))] [(add-exp DIVIDE add-exp) (make-app (build-so $1 1 3) (anon-ms (anon-id 'ml-divide) (anon-arrow anon-int anon-int anon-int)) (list $1 $3))] [(add-exp MOD add-exp) (make-app (build-so $1 1 3) (anon-ms (anon-id 'ml-modulo) (anon-arrow anon-int anon-int anon-int)) (list $1 $3))] [(add-exp) $1]) (add-exp [(app-exp PLUS app-exp) (make-app (build-so $1 1 3) (anon-ms (anon-id 'ml-plus) (anon-arrow anon-int anon-int anon-int)) (list $1 $3))] [(app-exp MINUS app-exp) (make-app (build-so $1 1 3) (anon-ms (anon-id 'ml-minus) (anon-arrow anon-int anon-int anon-int)) (list $1 $3))] [(MINUS app-exp) (make-app (build-so $2 1 2) (anon-ms '- (anon-arrow anon-int anon-int)) (list $2))] [(app-exp) $1]) (app-exp [(simple-exp simple-exp args) (make-app (build-so $1 1 3) $1 (cons $2 $3))] [(simple-exp) $1]) (args [(simple-exp args) (cons $1 $2)] [() null]) (simple-exp [(id) $1] [(CAPID) (make-constr (build-so $1 1 1) $1)] [(LITNUM) (make-litnum (build-so $1 1 1) (string->number $1))] [(TRUE) (make-bool #f #t)] [(FALSE) (make-bool #f #f)] [(LPAREN RPAREN) anon-unit-term] [(LPAREN exp RPAREN) $2] [(LITSTRING) (make-litstr (build-so $1 1 1) $1)]) (id [(ID) (make-id (build-so $1 1 1) (string->symbol $1))]) (type [(tuple-type-list) (if (null? (cdr $1)) (car $1) (make-tuple-type (build-so $1 1 1) $1))]) (tuple-type-list [(arrow-type STAR tuple-type-list) (cons $1 $3)] [(arrow-type) (list $1)]) (arrow-type [(simple-type ARROW arrow-type) (make-arrow-type (build-so $1 1 3) $1 $3)] ; Right associative [(simple-type) $1]) (simple-type [(INT) (make-int-type #f)] [(STRING) (make-str-type #f)] [(BOOL) (make-bool-type #f)] [(LUMP) (make-lump-type #f)] [(TYVAR) (make-tyvar (build-so $1 1 1) (string->symbol $1))] [(LPAREN type RPAREN) $2] [(LPAREN RPAREN) anon-unit-type] [(ID) (make-user-type (build-so $1 1 1) $1)])))) ;; ;; READ ;; (define (ml-read-syntax source-name input-port) (port-count-lines! input-port) (let ([program ((ml-parser source-name) (lambda () (simple-lexer input-port)))]) (let* ([defs (program-defs program)] [typemap (make-hash-table)] [usertypes (filter typedef? defs)] [let-defs (filter not-typedef? defs)]) (collision-check usertypes) (let ([types (map (lambda (def) (let ([css (new-stack)]) (stack-push! css (new-stack)) (let ([type ((typecheck usertypes) def typemap css)]) (let ([replacements (unify (stack-peek css) (make-hash-table))]) (hash-table-for-each replacements (lambda (tyvar new-type) (set! type (tyrep type tyvar new-type)))) (hash-table-put! typemap (id-val (let-def-id def)) type) type)))) let-defs)]) (let ([code (let ([defn (map emit-code let-defs types)]) #`(module #,(program-module program) mzscheme (require (lib "contract.ss") (lib "ml-primitives.ss" "sham" "ml") #,@(map (lambda (include) (list 'file include)) (program-includes program))) (provide (all-defined)) #,@defn))]) ;; display the module source: (pretty-print (syntax-object->datum code)) code))))) (define (not-typedef? x) (not (typedef? x))) ;;; TESTING ;; UNIFICATION TESTS (define (ut . constraint-list) (let ([ht (make-hash-table)]) (unify (list->stack (map (lambda (x) (apply make-constraint x)) constraint-list)) ht) (hash-table-map ht list))) ;; my test function. (define (ls= x y) (lset= equal? x (map (lambda (pr) (list (tyvar-val (car pr)) (cadr pr))) y))) ;; I'm suspicious about the lack of anon-tuple (define (anon-tuple . types) (make-tuple-type #f types)) (define int1 (make-int-type 34)) (define int2 (make-int-type 37)) (define bool1 (make-bool-type 2987)) (define bool2 (make-bool-type 223)) (define (arr1 t1 t2) (make-arrow-type 327 t1 t2)) (define (arr2 t1 t2) (make-arrow-type 272987 t1 t2)) (define (tup1 . ts) (make-tuple-type 232 ts)) (define (tup2 . ts) (make-tuple-type 2132 ts)) (define tv1a (make-tyvar 23 79)) (define tv1b (make-tyvar 124 79)) (define tv2 (make-tyvar 234 81)) (define tv3 (make-tyvar 12 2)) (define unification-test-suite (test-suite "unification tests" ;; single constraint: ;; simple types (test-check "trivial" ls= (ut) '()) (test-check "success1" ls= (ut (list int1 int2)) '()) (test-check "success2" ls= (ut (list bool2 bool1)) '()) (test-exn "simple-fail" exn:fail? (lambda () (ut (list bool1 int1)))) ;; arrows (test-check "success3" ls= (ut (list (arr1 int1 int2) (arr2 int2 int1))) '()) (test-exn "fail2" exn:fail? (lambda () (ut (list (anon-arrow anon-bool anon-int) (anon-arrow anon-int anon-int))))) (test-exn "fail3" exn:fail? (lambda () (ut (list (anon-arrow anon-bool anon-int) (anon-arrow anon-bool anon-bool))))) ;; tuples (test-check "tuple1" ls= (ut (list (anon-tuple) (anon-tuple))) '()) (test-check "tuple2" ls= (ut (list (anon-tuple anon-int anon-bool) (anon-tuple anon-int (make-bool-type 2387)))) '()) (test-exn "tuple-fail" exn:fail? (lambda () (ut (list (anon-tuple anon-int) (tup1 bool2))))) (test-exn "tuple-fail2" exn:fail? (lambda () (ut (list (tup1 bool1 bool2 int2) (tup2 bool2 int1 int2))))) ;; live vars, now: ;; top level (test-check "var1" ls= (ut (list tv1a int2)) `((,tv1a ,int2))) (test-check "var2" ls= (ut (list int2 tv1a)) `((,tv1a ,int2))) (test-check "var3" ls= (ut (list tv1a tv1b)) '()) ;; arrows (test-check "var4" ls= (ut (list (arr1 tv2 bool1) (arr2 int2 tv3))) `((,tv2 ,int2) (,tv3 ,bool1))) (test-check "var4" ls= (ut (list (arr1 tv2 tv1a) (arr2 int2 tv3))) `((,tv2 ,int2) (,tv1a ,tv3))) ;; could go either way ;; tuples (test-check "vartup" ls= (ut (list (tup1 int1 tv2 bool1) (tup2 tv1a (arr2 int2 tv3) tv3))) `((,tv1a ,int1) (,tv2 ,(arr2 int2 bool1)) (,tv3 ,bool1))) (test-check "tpair" ls= (ut (list (arr1 tv2 tv3) (arr2 tv3 tv2))) `((,tv3 ,tv2))) (test-exn "trecursive" exn:fail? (lambda () (ut (list tv1a (arr1 int1 tv1a))))) )) )
true
f442e721b9727008aa3d9b49308e29d4f73d1adf
4f17c70ae149426a60a9278c132d5be187329422
/scheme/r6rs/r5rs.ss
bce34d05ecff28655370f19212fb4246d37f5826
[]
no_license
okuoku/yuni-core
8da5e60b2538c79ae0f9d3836740c54d904e0da4
c709d7967bcf856bdbfa637f771652feb1d92625
refs/heads/master
2020-04-05T23:41:09.435685
2011-01-12T15:54:23
2011-01-12T15:54:23
889,749
2
0
null
null
null
null
UTF-8
Scheme
false
false
223
ss
r5rs.ss
(library (yuni scheme r6rs r5rs) (export null-environment scheme-report-environment delay force exact->inexact inexact->exact quotient remainder modulo) (import (rnrs r5rs)) ) ; rnrs r5rs
false