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
16e13b55cc025c55969ca7f8f31c211b19b65719
e82d67e647096e56cb6bf1daef08552429284737
/data-directed-programming/scheme-numbers.scm
d866701d69bd5e8f41450306e3aa5a7855ab1c17
[]
no_license
ashishmax31/sicp-exercises
97dfe101dd5c91208763dcc4eaac2c17977d1dc1
097f76a5637ccb1fba055839d389541a1a103e0f
refs/heads/master
2020-03-28T11:16:28.197294
2019-06-30T20:25:18
2019-06-30T20:25:18
148,195,859
6
0
null
null
null
null
UTF-8
Scheme
false
false
1,094
scm
scheme-numbers.scm
(define (install-scheme-numbers) (define (tag contents) (attach-tag 'scheme-number contents)) (define (raise-to-rational number) (make-rational-number number 1)) (put 'add '(scheme-number scheme-number) (lambda (a b) (tag (+ a b)))) (put 'sub '(scheme-number scheme-number) (lambda (a b) (tag (- a b)))) (put 'mul '(scheme-number scheme-number) (lambda (a b) (tag (* a b)))) (put 'div '(scheme-number scheme-number) (lambda (a b) (tag (/ a b)))) (put 'make 'scheme-number (lambda (num) (tag num))) (put-coercion 'scheme-number 'complex (lambda (n) (make-from-real-imag (contents n) 0))) (put-coercion 'rational 'scheme-number (lambda (rational-num) (tag (/ (car (contents rational-num)) (cdr (contents rational-num)))))) (put 'raise '(scheme-number) (lambda(integer) (raise-to-rational integer))) (display "Installed scheme numbers...") (newline))
false
6e734171c8a7d47621bcb1158a32b717b05eb7e6
a2bc20ee91471c8116985e0eb6da1d19ab61f6b0
/exercise_14_1/main.scm
05c54d3de44c4bc20a0058ed9068964add443c7e
[]
no_license
cthulhu-irl/my-scheme-practices
6209d01aa1497971a5b970ab8aa976bb3481e9c9
98867870b0cb0306bdeb209d076bdc80e2e0e8cc
refs/heads/master
2022-09-22T15:19:48.798783
2020-06-06T14:16:07
2020-06-06T14:16:07
265,855,102
0
0
null
null
null
null
UTF-8
Scheme
false
false
847
scm
main.scm
(define (vec-inner-prod vec1 vec2) (let ((rvec (make-vector (if (< (vector-length vec1) (vector-length vec2)) (vector-length vec1) (vector-length vec2))))) (let loop((k (- (vector-length rvec) 1))) (if (< k 0) rvec (begin (vector-set! rvec k (* (vector-ref vec1 k) (vector-ref vec2 k))) (loop (- k 1))))))) (display "\n") (format #t "(vec-inner-prod #() #(2 3 4 5)): ~a\n" (vec-inner-prod #() #(2 3 4 5))) (format #t "(vec-inner-prod #(1 2 3 4) #(2 3 4 5)): ~a\n" (vec-inner-prod #(1 2 3 4) #(2 3 4 5))) (format #t "(vec-inner-prod #(1 2 3 4) #(2 3)): ~a\n" (vec-inner-prod #(1 2 3 4) #(2 3)))
false
f9f5e49fd769e94c5631d3115cea72bb43ea4ece
7e15b782f874bcc4192c668a12db901081a9248e
/ty-scheme/ch03/procedures.scm
71b34055504174d326595f5a6215653bc419ac63
[]
no_license
Javran/Thinking-dumps
5e392fe4a5c0580dc9b0c40ab9e5a09dad381863
bfb0639c81078602e4b57d9dd89abd17fce0491f
refs/heads/master
2021-05-22T11:29:02.579363
2021-04-20T18:04:20
2021-04-20T18:04:20
7,418,999
19
4
null
null
null
null
UTF-8
Scheme
false
false
502
scm
procedures.scm
(load "../common/utils.scm") (out (lambda (x) (+ x 2))) ; procedure (out ((lambda (x) (+ x 2)) 5)) ; 7 (define add2 (lambda (x) (+ x 2))) (out (add2 4)) ; 6 (out (add2 9)) ; 11 (define area-1 (lambda (length breadth) (* length breadth))) (define area-2 *) (out (area-1 10 20)) (out (area-2 10 20)) ; 200 ; test variable arguments (define test-arg (lambda (a b . c) (begin (out a) (out b) (out c)))) (test-arg 1 2 3) ; 1 2 (3) (test-arg 1 2 3 4 5) ; 1 2 (3 4 5)
false
b46b0c607f79aabe66bd91733a16ba4b7177b603
5add38e6841ff4ec253b32140178c425b319ef09
/%3a214.sls
1a192bc5c518d4a2ccb33abfee1d580e9bcdefd4
[ "X11-distribute-modifications-variant" ]
permissive
arcfide/chez-srfi
8ca82bfed96ee1b7f102a4dcac96719de56ff53b
e056421dcf75d30e8638c8ce9bc6b23a54679a93
refs/heads/master
2023-03-09T00:46:09.220953
2023-02-22T06:18:26
2023-02-22T06:18:26
3,235,886
106
42
NOASSERTION
2023-02-22T06:18:27
2012-01-21T20:21:20
Scheme
UTF-8
Scheme
false
false
2,003
sls
%3a214.sls
#!r6rs ;; This is an R6RS adaptation of the R7RS implementation by the SRFI-214 author, ;; taken from [here](https://github.com/scheme-requests-for-implementation/srfi-214/tree/master/implementation) (library (srfi :214) (export ;; Constructors make-flexvector flexvector flexvector-unfold flexvector-unfold-right flexvector-copy flexvector-reverse-copy flexvector-append flexvector-concatenate flexvector-append-subvectors ;; Predicates flexvector? flexvector-empty? flexvector=? ;; Selectors flexvector-ref flexvector-front flexvector-back flexvector-length ;; Mutators flexvector-add! flexvector-add-front! flexvector-add-back! flexvector-remove! flexvector-remove-front! flexvector-remove-back! flexvector-add-all! flexvector-remove-range! flexvector-clear! flexvector-set! flexvector-swap! flexvector-fill! flexvector-reverse! flexvector-copy! flexvector-reverse-copy! flexvector-append! ;; Iteration flexvector-fold flexvector-fold-right flexvector-map flexvector-map! flexvector-map/index flexvector-map/index! flexvector-append-map flexvector-append-map/index flexvector-filter flexvector-filter! flexvector-filter/index flexvector-filter/index! flexvector-for-each flexvector-for-each/index flexvector-count flexvector-cumulate ;; Searching flexvector-index flexvector-index-right flexvector-skip flexvector-skip-right flexvector-binary-search flexvector-any flexvector-every flexvector-partition ;; Conversion flexvector->vector flexvector->list flexvector->string vector->flexvector list->flexvector string->flexvector reverse-flexvector->list reverse-list->flexvector generator->flexvector flexvector->generator) (import (srfi :214 impl)))
false
0d827c1e446ada23274ca0b2ea3812c5cf62b0b4
1a64a1cff5ce40644dc27c2d951cd0ce6fcb6442
/object-renderers/init-lst-renderers.scm
f1337cd29e39d713b54f9209e221b3d88c6ac120
[]
no_license
skchoe/2007.rviz-objects
bd56135b6d02387e024713a9f4a8a7e46c6e354b
03c7e05e85682d43ab72713bdd811ad1bbb9f6a8
refs/heads/master
2021-01-15T23:01:58.789250
2014-05-26T17:35:32
2014-05-26T17:35:32
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
5,213
scm
init-lst-renderers.scm
(module init-lst-renderers scheme (require (lib "mred.ss" "mred") (lib "list.ss") (lib "class.ss") (lib "graphics.ss" "graphics") (lib "etc.ss") "../src/math/def.scm" "../src/math/calc.scm" "../src/render/render.scm" "../src/render/primitives.scm" "../src/operation/renderer-ops.scm") (provide construct-lst-renderers gen-renderer) (define construct-lst-renderers (lambda () (let* ((cubes (gen-lst-renderers 'cube 50)) (cylinders (gen-lst-renderers 'cylinder 30)) (disks (gen-lst-renderers 'disk 20)) (quads (gen-lst-renderers 'quad 20)) (spheres (gen-lst-renderers 'sphere 30)) (triangles (gen-lst-renderers 'triangle 10))) (append cubes cylinders disks quads spheres triangles)))) (define gen-lst-renderers (lambda (geo-kind num) (for/fold([lst empty]) ([i (in-range 1 num)]) (cons (gen-renderer geo-kind #t empty) lst)))) (define gen-renderer (lambda (geo-kind random? lst) (let* ([prim (if (empty? lst) (match geo-kind ['cube (make-cube .5 .5 .5)] ['cylinder (make-cylinder .3 .3 1)] ['disk (make-disk .2 .5)] ['quad (gen-unit-quad)] ['sphere (make-sphere .5)] ['triangle (gen-unit-triangle)] ['line (gen-unit-line)] [_ null]) (match geo-kind ['cube (make-cube (list-ref lst 0) (list-ref lst 1) (list-ref lst 2))] ['cylinder (make-cylinder (list-ref lst 0) (list-ref lst 1) (list-ref lst 2))] ['disk (make-disk (list-ref lst 0) (list-ref lst 1))] ['quad (make-quad (list-ref lst 0) (list-ref lst 1) (list-ref lst 2) (list-ref lst 3))] ['sphere (make-sphere (list-ref lst 0))] ['triangle (make-triangle (list-ref lst 0) (list-ref lst 1) (list-ref lst 2))] ['line (make-line (list-ref lst 0) (list-ref lst 1))] [_ null]))] [mat (if random? (random-material) (default-material))] [xfm (if random? (random-pos-xform 100) (default-transform))]) (unless (null? prim) (initialize-renderer prim mat xfm))))) (define random-material (lambda () (make-material (make-point4 (random) (random) (random) 1.0) (make-point4 (random) (random) (random) 1.0) (make-point4 0.0 0.0 0.0 1.0) 0.0 empty))) (define random-pos-xform (lambda (r) (let* ([rx (- (random r) (/ r 2.0))] [ry (- (random r) (/ r 2.0))] [rz (- (random r) (/ r 2.0))]) (vector 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 rx ry rz 1.0)))) (define gen-unit-quad (lambda () (let* ([vtx0 (make-vertex (make-point3 1 -1 0) (make-point3 0 0 1) (make-point2 1 1) (make-point4 1 0 0 1))] [vtx1 (make-vertex (make-point3 1 1 0) (make-point3 0 0 1) (make-point2 1 0) (make-point4 0 1 0 1))] [vtx2 (make-vertex (make-point3 -1 1 0) (make-point3 0 0 1) (make-point2 0 0) (make-point4 0 0 1 1))] [vtx3 (make-vertex (make-point3 -1 -1 0) (make-point3 0 0 1) (make-point2 0 1) (make-point4 1 1 1 1))]) (make-quad vtx0 vtx1 vtx2 vtx3)))) (define gen-line (lambda (p0 p1) (make-line p0 p1))) (define gen-unit-line (lambda () (make-line (make-point3 1 0 0) (make-point3 -1 0 0)))) (define gen-unit-triangle (lambda () (let* ([vtx0 (make-vertex (make-point3 1 0 0) (make-point3 0 0 1) (make-point2 1 1) (make-point4 1 0 0 1))] [vtx1 (make-vertex (make-point3 -1 0 0) (make-point3 0 0 1) (make-point2 1 0) (make-point4 0 1 0 1))] [vtx2 (make-vertex (make-point3 0 1 0) (make-point3 0 0 1) (make-point2 0 0) (make-point4 0 0 1 1))]) (make-triangle vtx0 vtx1 vtx2)))) )
false
b318824e42c285d3f6f5b7601efd38efb336d267
1de3d2f5aea84e4d19825c290980a3b4f7815f32
/monarchy/prototyping/agents/procter.import.scm
3885f4b73894acfad92dfe0c880a9c9f42d7c96c
[]
no_license
certainty/lisp-misc
37798607ca0275552c39683bad3080a42ba931fe
d5ee799f3ab0f2cc74bf3b2a83604dace160a649
refs/heads/master
2017-12-30T03:02:25.789701
2016-11-12T09:27:43
2016-11-12T09:27:43
69,743,925
0
0
null
null
null
null
UTF-8
Scheme
false
false
964
scm
procter.import.scm
;;;; procter.import.scm - GENERATED BY CHICKEN 4.7.0.3-st -*- Scheme -*- (eval '(import chicken scheme ports extras srfi-1 irregex)) (##sys#register-compiled-module 'procter (list) '((with-property-headers . procter#with-property-headers) (with-vertical-headers . procter#with-vertical-headers) (with-horizontal-headers . procter#with-horizontal-headers) (columnize . procter#columnize) (make-table-line-reader . procter#make-table-line-reader) (make-property-table-reader . procter#make-property-table-reader) (make-table-reader . procter#make-table-reader) (port-map* . procter#port-map*) (make-reader . procter#make-reader) (make-fully-qualified-reader . procter#make-fully-qualified-reader) (make-procter-error-condition . procter#make-procter-error-condition) (make-procter-condition . procter#make-procter-condition) (make-exn-condition . procter#make-exn-condition)) (list) (list)) ;; END OF FILE
false
18dfe6620929a864a98c51c046b563848c0e1d1c
e36ebbeea1e910ed85a73ea91fd891e45cf7fe84
/Fractal.scm
4edcaa32dd7b689736fb2f940b07b0cafc1e7c7a
[]
no_license
w453908766/other
2850cf98af1c2870b94e75ca31193c961b927446
a76f21b7d62d5ec1043e78f018cf93c72b7775f0
refs/heads/master
2020-04-10T09:11:02.847625
2018-12-08T10:40:46
2018-12-08T10:40:46
160,929,142
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,451
scm
Fractal.scm
#lang racket (define (acc func . lst) (_acc func lst)) (define (_acc func lst) (if (eq? '() (cdr lst)) (car lst) (func (car lst) (_acc func (cdr lst))) )) (require (planet "sicp.ss" ("soegaard" "sicp.plt" 2 1))) (define origin (make-vect 0 0)) (define space-painter (segments->painter '())) (define vert-line (segments->painter (list (make-segment origin (make-vect 0 1))))) (define hor-line (segments->painter (list (make-segment origin (make-vect 1 0))))) (define (shrink k painter) ((transform-painter origin (make-vect k 0) (make-vect 0 k)) painter)) (define (rotate rad painter) (let ((sinrad (sin rad)) (cosrad (cos rad))) ((transform-painter origin (make-vect cosrad sinrad) (make-vect (- sinrad) cosrad)) painter))) (define rad60 (/ pi.f 3)) (define -rad60 (/ pi.f -3)) (define (move x y painter) ((transform-painter (make-vect x y) (make-vect (+ x 1) y) (make-vect x (+ 1 y))) painter)) (define (paint-mid painter) (paint (move 0.5 0.5 painter))) (define (snow-comb n snow-edge) (-snow-comb n (/ (* 2 pi.f) n) snow-edge)) (define (-snow-comb n rad snow-edge) (if (= n 0) space-painter (superpose snow-edge (rotate rad (-snow-comb (- n 1) rad snow-edge))) )) (define (paint-snow snow k) (paint-mid (shrink 0.5 (snow-comb 6 (stream-ref snow k))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (snow-splay s) (let ((s/2 (shrink 1/2 s)) (s/4 (shrink 1/3 s))) (superpose s/2 (move 0 1/2 (acc superpose s/2 (rotate rad60 s/4) (rotate -rad60 s/4))) ))) (define snow0 (stream-cons vert-line (stream-map snow-splay snow0))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (koch s) (let ((shr ((shrink 1/3) s))) (let ((left (superpose shr ((move 1/3 0) (rotate rad60 shr))))) (superpose left (flip-horiz left))))) (define snow (stream-cons hor-line (stream-map koch snow))) (define snow-snow (stream-map snow-comb snow)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (kk s) (let ((s/2 (shrink 1/2 s)) (s/4 (shrink 1/4 s))) (move 0 0.5 (acc superpose s/2 (rotate pi.f s/2) (rotate (* 1 rad60) s/4) (rotate (* 2 rad60) s/4) (rotate (* 4 rad60) s/4) (rotate (* 5 rad60) s/4)) ))) (define ss (stream-cons vert-line (stream-map kk ss))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
false
bc5cc2f9fed2463279325b54e365bab374685227
c42881403649d482457c3629e8473ca575e9b27b
/src/kahua/xml-template.scm
79332c1042a324d0ac9874d1b7c2071c625a0f64
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
kahua/Kahua
9bb11e93effc5e3b6f696fff12079044239f5c26
7ed95a4f64d1b98564a6148d2ee1758dbfa4f309
refs/heads/master
2022-09-29T11:45:11.787420
2022-08-26T06:30:15
2022-08-26T06:30:15
4,110,786
19
5
null
2015-02-22T00:23:06
2012-04-23T08:02:03
Scheme
UTF-8
Scheme
false
false
7,256
scm
xml-template.scm
;; -*- mode: scheme; coding: utf-8 -*- ;; ;; kahua.template - Page Template Engine ;; ;; Copyright (c) 2006-2007 Kahua Project, All rights reserved. ;; See COPYING for terms and conditions of using this software. ;; (define-module kahua.xml-template (use srfi-1) (use srfi-13) (use text.parse) (use sxml.ssax) (use sxml.tools) (use gauche.parameter) (use kahua.util) (use kahua.elem) (export kahua:make-xml-parser <kahua:xml-template> kahua:make-xml-template kahua:xml-template->sxml kahua:xml-template->node/ )) (select-module kahua.xml-template) (define-condition-type <kahua-xml-template-error> <kahua-error> #f) (define (kahua-xml-template-error fmt . args) (apply errorf <kahua-xml-template-error> fmt args)) ;; FIXME!! It should use the DOCTYPE declaration itself. (define-constant *doctype-table* `(("http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" . "-//W3C//DTD XHTML 1.0 Strict//EN") ("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" . "-//W3C//DTD XHTML 1.0 Transitional//EN") ("http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd" . "-//W3C//DTD XHTML 1.0 Frameset//EN") ("http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd" . "-//W3C//DTD XHTML 1.1//EN") )) (define (public-identifier uri) (and-let* ((id (assoc uri *doctype-table*))) (cdr id))) (define-class <kahua:xml-template> () ((sxml :init-keyword :sxml) (parser :init-keyword :parser) (path :init-keyword :path))) (define (kahua:make-xml-template path . maybe-ns-alist) (let* ((ns-alist (get-optional maybe-ns-alist '((#f . "http://www.w3.org/1999/xhtml")))) (parser (kahua:make-xml-parser ns-alist)) (sxml (call-with-input-file path (cut parser <> '()) :encoding 'UTF-8))) ; FIXME!! (make <kahua:xml-template> :sxml sxml :parser parser :path path))) (define (keyword-list->alist klist) (define keyword->symbol (compose string->symbol keyword->string)) (let loop ((klist klist) (alist '())) (if (null? klist) (reverse! alist) (loop (cddr klist) (acons (keyword->symbol (car klist)) (cadr klist) alist))))) (define-method kahua:xml-template->sxml ((tmpl <kahua:xml-template>) . args) (let1 elem-alist (keyword-list->alist args) (define (xml-template->sxml-internal node accum) (cond ((and-let* ((id (sxml:attr node 'id)) (p (assq (string->symbol id) elem-alist))) (cdr p)) => (lambda (node) (let1 node (cond ((procedure? node) (rev-nodes (exec '() node))) ((or (null? node) (not node)) '()) ((pair? node) (let1 n (car node) (cond ((eq? n 'node-set) (cdr node)) ((symbol? n) (list node)) (else node)))) (else (kahua-xml-template-error "invalid node: ~s" node))) (fold cons accum node)))) ((list? node) (cons (reverse (fold xml-template->sxml-internal '() node)) accum)) (else (cons node accum)))) (list (reverse (fold xml-template->sxml-internal '() (slot-ref tmpl 'sxml)))))) (define-method kahua:xml-template->node/ ((tmpl <kahua:xml-template>) . args) (let1 sxml (apply kahua:xml-template->sxml tmpl args) (if (null? sxml) empty (update (cut cons (car (rev-nodes sxml)) <>))))) ;; ;; The parser take input port and seed(maybe a nil) ;; FIXME!! This cannot handle namespace and DOCTYPE properly. ;; (define (kahua:make-xml-parser ns-alist) (define (res-name->sxml res-name) (if (symbol? res-name) res-name (string->symbol #`",(car res-name):,(cdr res-name)"))) (let ((namespaces (map (lambda (el) (list* #f (car el) (ssax:uri-string->symbol (cdr el)))) (or ns-alist '())))) (define (%new-level-seed elem-gi attributes namespaces expected-content seed) '()) (define (%finish-element elem-gi attributes namespaces parent-seed seed) (receive (attrs id) (let loop ((attrs (attlist->alist attributes)) (accum '()) (id #f)) (if (null? attrs) (values accum id) (let* ((attr (car attrs)) (name (res-name->sxml (car attr))) (value (cdr attr)) (n+v (list name value))) (if (eq? name 'id) (loop (cdr attrs) (cons n+v accum) (string->symbol value)) (loop (cdr attrs) (cons n+v accum) #f))))) (let* ((seed (ssax:reverse-collect-str-drop-ws seed)) (node (cons (res-name->sxml elem-gi) (if (null? attrs) seed (cons (cons '@ attrs) seed))))) (cons node parent-seed)))) (define (%char-data-handler string1 string2 seed) (if (string-null? string2) (cons string1 seed) (list* string2 string1 seed))) (define (%doctype port docname systemid internal-subset? seed) (when internal-subset? (ssax:warn port "Internal DTD subset is not currently handled ") (ssax:skip-internal-dtd port)) (let1 publicid (public-identifier systemid) (values #f '() namespaces (if publicid (cons (list '*DOCTYPE* docname publicid systemid) seed) seed)))) (define (%undecl-root elem-gi seed) (values #f '() namespaces seed)) (define (%decl-root elem-gi seed) seed) (define (%default-pi-handler port pi-tag seed) (cons (list '*PI* pi-tag (ssax:read-pi-body-as-string port)) seed)) ;; main (let1 base-parser (ssax:make-parser DOCTYPE %doctype DECL-ROOT %decl-root UNDECL-ROOT %undecl-root NEW-LEVEL-SEED %new-level-seed FINISH-ELEMENT %finish-element CHAR-DATA-HANDLER %char-data-handler PI ((*DEFAULT* . %default-pi-handler))) (lambda (port seed) (let1 result (reverse (base-parser port seed)) (cond (ns-alist (cons '*TOP* (if (null? ns-alist) result (cons (list '@@ (cons '*NAMESPACES* (map (lambda (ns) (list (car ns) (cdr ns))) ns-alist))) result)))) ((and (pair? result) (pair? (car result))) (car result)) (else result))))))) (provide "kahua/xml-template")
false
c1cb68547c562b74d73a07d0a925433d9375b27a
eef5f68873f7d5658c7c500846ce7752a6f45f69
/spheres/net/debug-repl/rdi.scm
5b42a9e153467d6e03b17c987da41762d71d1e02
[ "MIT" ]
permissive
alvatar/spheres
c0601a157ddce270c06b7b58473b20b7417a08d9
568836f234a469ef70c69f4a2d9b56d41c3fc5bd
refs/heads/master
2021-06-01T15:59:32.277602
2021-03-18T21:21:43
2021-03-18T21:21:43
25,094,121
13
3
null
null
null
null
UTF-8
Scheme
false
false
7,064
scm
rdi.scm
(define default-remote-debugger-address "192.168.1.162") (define default-remote-debugger-port-num 20000) (define (rdi-set-host! address) (set! default-remote-debugger-address address)) (define *rdi-function* (lambda (x) x)) (define (rdi-set-rdi-function! f) (set! *rdi-function* f)) (define (split-address str) (call-with-input-string str (lambda (port) (let* ((x (read-all port (lambda (port) (read-line port #\:)))) (len (length x))) (cond ((<= len 1) (cons (if (= len 1) (car x) default-remote-debugger-address) default-remote-debugger-port-num)) ((= len 2) (let ((address (car x)) (port-num (string->number (cadr x) 10))) (if (and port-num (exact? port-num) (integer? port-num) (>= port-num 1) (<= port-num 65535)) (cons (if (string=? address "") default-remote-debugger-address address) port-num) #f))) (else #f)))))) (define-type rdi address port-num seq-num call-table connection writer-thread) (define (rdi-create-client remote-debugger-address) (and remote-debugger-address (let ((x (split-address remote-debugger-address))) (if (not x) (error "invalid remote debugger address") (let* ((address (car x)) (port-num (cdr x)) (rdi (make-rdi address port-num 0 (make-table) #f #f)) (writer-thread (rdi-create-writer-thread rdi))) (rdi-writer-thread-set! rdi writer-thread) (thread-start! writer-thread) rdi))))) (define (rdi-create-server remote-debugger-port-num) (let* ((address #f) (port-num (or remote-debugger-port-num default-remote-debugger-port-num)) (rdi (make-rdi address port-num 0 (make-table) #f #f)) (writer-thread (rdi-create-writer-thread rdi))) (rdi-writer-thread-set! rdi writer-thread) (thread-start! writer-thread) rdi)) (define (rdi-force-connection rdi) (or (rdi-connection rdi) (if (rdi-address rdi) (rdi-open-client rdi) (rdi-open-server rdi)))) (define rdi-version1 '());(gambit-debuggee-version 0)) (define rdi-version2 '());(gambit-debugger-version 0)) (define (rdi-open-client rdi) (let ((connection (open-tcp-client (list server-address: (rdi-address rdi) port-number: (rdi-port-num rdi))))) (write rdi-version1 connection) (force-output connection) (let ((response (read connection))) (if (not (equal? response rdi-version2)) (error "unexpected debugger version: " response) (let ((reader-thread (rdi-create-reader-thread rdi connection))) (rdi-connection-set! rdi connection) (thread-start! reader-thread) connection))))) (define (rdi-open-server rdi) (let ((listen-port (open-tcp-server (list server-address: (string-append "*:" (number->string (rdi-port-num rdi))) reuse-address: #t)))) (let loop () (let ((connection (read listen-port))) (let ((request (read connection))) (if (not (equal? request rdi-version1)) (error "unexpected debuggee version: " request) (begin (write rdi-version2 connection) (force-output connection) (let ((reader-thread (rdi-create-reader-thread rdi connection))) (rdi-connection-set! rdi connection) (thread-start! reader-thread) (loop))))))))) (define (rdi-create-reader-thread rdi connection) (make-thread (lambda () (let loop () (let ((msg (read connection))) (if (not (eof-object? msg)) (begin (thread-send (rdi-writer-thread rdi) msg) (loop))))) (thread-send (rdi-writer-thread rdi) '(reader-thread-terminated))))) (define (rdi-create-writer-thread rdi) (make-thread (lambda () (let loop () (let ((msg (thread-receive))) (and (rdi-handle-message rdi msg) (loop))))))) (define (rdi-new-seqnum rdi) (let ((seq-num (+ (rdi-seq-num rdi) 1))) (rdi-seq-num-set! rdi seq-num) seq-num)) (define (rdi-handle-message rdi msg) (if (pair? msg) (case (car msg) ((reader-thread-terminated) ;; (pretty-print ;; '(rdi reader-thread is terminating) ;; ##stdout-port) #t) ((terminate) ;; (pretty-print ;; '(rdi writer-thread is terminating) ;; ##stdout-port) #f) ((call) (let* ((seq-num (cadr msg)) (call (caddr msg)) (result (apply (*rdi-function* (car call)) (cdr call)))) (rdi-send rdi (list 'return seq-num result)) #t)) ((remote-call) (let* ((result-mutex (cadr msg)) (call (caddr msg)) (seq-num (rdi-new-seqnum rdi))) (rdi-send rdi (list 'call seq-num call)) (table-set! (rdi-call-table rdi) seq-num result-mutex) #t)) ((return) (let* ((seq-num (cadr msg)) (result (caddr msg)) (call-table (rdi-call-table rdi)) (result-mutex (table-ref call-table seq-num #f))) (if (not result-mutex) (error "invalid call sequence number") (begin (table-set! call-table seq-num) (mutex-specific-set! result-mutex result) (mutex-unlock! result-mutex) #t)))) (else (pretty-print (list 'unhandled-message msg) ##stdout-port) #t)) #f)) (define (rdi-send rdi msg) (let ((connection (rdi-connection rdi))) (write msg connection) (force-output connection))) (define (rdi-remote-call rdi fn . args) (rdi-force-connection rdi) (let ((result-mutex (make-mutex 'remote-call))) (mutex-lock! result-mutex) ;; result not ready yet... (thread-send (rdi-writer-thread rdi) (list 'remote-call result-mutex (cons fn args))) (mutex-lock! result-mutex) ;; wait until result is ready (mutex-specific result-mutex)))
false
832b214636422bae120d706b45cce7540a9a7893
957ca548c81c2c047ef82cdbf11b7b2b77a3130b
/03LAB/03_lab_3.scm
ff1091ded02db3bd9c55bc62c6c6208b19d77166
[]
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
3,547
scm
03_lab_3.scm
(load "debug.scm") (define (ref object idx . val) (cond ((= 0 (length val)) (cond ((list? object) (if (and (integer? idx) (>= idx 0) (< idx (length object))) (let loop ((i idx) (obj object)) (if (= 0 i) (car obj) (loop (- i 1) (cdr obj)))) #f )) ((string? object) (if (and (integer? idx) (>= idx 0) (< idx (string-length object))) (string-ref object idx) #f )) ((vector? object) (if (and (integer? idx) (>= idx 0) (< idx (vector-length object))) (vector-ref object idx) #f )) (else #f) )) ((= 1 (length val)) (cond ((list? object) (if (and (integer? idx) (>= idx 0) (<= idx (length object))) (let loop ((i 0) (ix idx) (obj object) (x (car val))) (if (null? obj) (if (= ix i) (list x) '() ) (if (= ix i) (cons x (loop (+ i 1) ix obj x)) (cons (car obj) (loop (+ i 1) ix (cdr obj) x)) ) ) ) #f)) ((vector? object) (if (and (integer? idx) (>= idx 0) (<= idx (vector-length object))) (begin (let loop ((i 0) (obj object) (nv (make-vector (+ (vector-length object) 1))) (x (car val))) (cond ((= i (+ 1 (vector-length object))) nv) ((= i idx) (begin (vector-set! nv i x) (loop (+ i 1) obj nv x))) ((< i idx) (begin (vector-set! nv i (vector-ref obj i)) (loop (+ i 1) obj nv x))) ((> i idx) (begin (vector-set! nv i (vector-ref obj (- i 1))) (loop (+ i 1) obj nv x))) (else #f) )) ) ) ) ((string? object) (if (and (integer? idx) (>= idx 0) (<= idx (string-length object)) (char? (car val))) (string-append (substring object 0 idx) (make-string 1 (car val)) (substring object idx (string-length object))) #f )) )) (else #f))) (define main-tests (list (test (ref '(1 2 3) 1) 2) (test (ref #(1 2 3) 1) 2) (test (ref "123" 1) #\2) (test (ref "123" 3) #f) (test (ref '(1 2 3) 99) #f) (test (ref '(2 3 4) -99) #f) (test (ref "123" 99) #f) (test (ref "124543" -1) #f) (test (ref '('(1 2 3) 2 3) 1 0) '(1 0 2 3)) (test (ref #(1 2 3) 1 0) #(1 0 2 3)) (test (ref #(1 2 3) 1 #\0) #(1 #\0 2 3)) (test (ref "123" 1 #\0) "1023") (test (ref "123" 1 0) #f) (test (ref "123" 3 #\4) "1234") (test (ref "123" 5 #\4) #f)))
false
bf9978d9901dbb085a4abc6200166c621373aa69
314ebaed53c58ca25553493222fec30942d08803
/chapter5/5.4.ss
8c1f1c5c2e39f788ee3b0a3ec70b625136f5dd5e
[]
no_license
Cltsu/SICP
45dc6a003e6977e6b7e339f7ff71a00638a28279
92402f2e6f06be5c967d60590c7bf13b070f0a5e
refs/heads/master
2021-02-08T08:31:30.491089
2020-06-17T13:32:37
2020-06-17T13:32:37
244,130,747
0
0
null
null
null
null
UTF-8
Scheme
false
false
52,471
ss
5.4.ss
(define (eval exp env) (cond ((self-evaluating? exp) exp) ((variable? exp) (lookup-variable-value exp env)) ((quoted? exp) (text-of-quotation exp)) ((assignment? exp) (eval-assignment exp env)) ((definition? exp) (eval-definition exp env)) ((let? exp) (eval (let-combination exp) env)); ((if? exp) (eval-if exp env)) ((lambda? exp) (make-procedure (lambda-parameters exp) (lambda-body exp) env)) ((begin? exp) (eval-sequence (begin-actions exp) env)) ((cond? exp) (eval (cond->if exp) env)) ((application? exp) (apply-moto (eval (operator exp) env) (list-of-values (operands exp) env))) (else (error "unkown expression type -- EVAL" exp)))) (define (apply-moto procedure arguments) (cond ((primitive-procedure? procedure) (apply-primitive-procedure procedure arguments)) ((compound-procedure? procedure) (eval-sequence (procedure-body procedure) (extend-environment (procedure-parameters procedure) arguments (procedure-environment procedure)))) (else (error "unkown procedure type -- APPLY" procedure)))) (define (eval-if exp env) (if (true? (eval (if-predicate exp) env)) (eval (if-consequent exp) env) (eval (if-alternative exp) env))) (define (eval-sequence exps env) (cond ((last-exp? exps) (eval (first-exp exps) env)) (else (eval (first-exp exps) env) (eval-sequence (rest-exps exps) env)))) (define (eval-assignment exp env) (set-variable-value! (assignment-variable exp) (eval (assignment-value exp) env) env) 'ok) (define (eval-definition exp env) (define-variable! (definition-variable exp) (eval (definition-value exp) env) env) 'ok) (define (list-of-values exps env) (if (no-operands? exps) '() (cons (eval (first-operand exps) env) (list-of-values (rest-operands exps) env)))) (define (self-evaluating? exp) (cond ((number? exp) #t) ((string? exp) #t) (else #f))) (define (variable? exp) (symbol? exp)) (define (quoted? exp) (tagged-list? exp 'quote)) (define (text-of-quotation exp ) (cadr exp)) (define (tagged-list? exp tag) (if (pair? exp) (eq? (car exp) tag) #f)) ;assignment (define (assignment? exp) (tagged-list? exp 'set!)) (define (assignment-variable exp) (cadr exp)) (define (assignment-value exp) (caddr exp)) ;definition (define (definition? exp) (tagged-list? exp 'define)) (define (definition-variable exp) (if (symbol? (cadr exp)) (cadr exp) (caadr exp))) (define (definition-value exp) (if (symbol? (cadr exp)) (caddr exp) (make-lambda (cdadr exp) (cddr exp)))) ;lambda (define (lambda? exp) (tagged-list? exp 'lambda)) (define (lambda-parameters exp) (cadr exp)) (define (lambda-body exp) (cddr exp)) (define (make-lambda parameters body) (cons 'lambda (cons parameters body))) ;if (define (if? exp) (tagged-list? exp 'if)) (define (if-predicate exp) (cadr exp)) (define (if-consequent exp) (caddr exp)) (define (if-alternative exp) (if (not (null? (cdddr exp))) (cadddr exp) '#f)) (define (make-if predicate consequent alternative) (list 'if predicate consequent alternative)) ;begin (define (begin? exp) (tagged-list? exp 'begin)) (define (begin-actions exp) (cdr exp)) (define (last-exp? seq) (null? (cdr seq))) (define (first-exp seq) (car seq)) (define (rest-exps seq) (cdr seq)) (define (sequence->exp seq) (cond ((null? seq) seq) ((last-exp? seq) (first-exp seq)) (else (make-begin seq)))) (define (make-begin seq) (cons 'begin seq)) ;application (define (application? exp) (pair? exp)) (define (operator exp) (car exp)) (define (operands exp) (cdr exp)) (define (no-operands? ops) (null? ops)) (define (first-operand ops) (car ops)) (define (rest-operands ops) (cdr ops)) ;cond (define (cond? exp) (tagged-list? exp 'cond)) (define (cond-clauses exp) (cdr exp)) (define (cond-else-clause? clause) (eq? (cond-predicate clause) 'else)) (define (cond-predicate clause) (car clause)) (define (cond-actions clause) (cdr clause)) (define (cond->if exp) (expand-clauses (cond-clauses exp))) (define (expand-clauses clauses) (if (null? clauses) '#f (let ((first (car clauses)) (rest (cdr clauses))) (if (cond-else-clause? first) (if (null? rest) (sequence->exp (cond-actions first)) (error "ELSE clause isn't last -- COND->IF" rest)) (make-if (cond-predicate first) (sequence->exp (cond-actions first)) (expand-clauses rest)))))) ;谓词检测 (define (true? x) (not (eq? x '#f))) (define (false? x) (eq? x '#f)) ;过程的表示 (define (make-procedure parameters body env) (list 'procedure parameters body env)) (define (compound-procedure? p) (tagged-list? p 'procedure)) (define (procedure-parameters p) (cadr p)) (define (procedure-body p) (caddr p)) (define (procedure-environment p) (cadddr p)) ;环境 作为frame的表 (define (enclosing-environment env) (cdr env)) (define (first-frame env) (car env)) (define the-empty-environment '()) ;frame 表示一个单独的环境 (define (make-frame variable values) (cons variable values)) (define (frame-variables frame) (car frame)) (define (frame-values frame) (cdr frame)) (define (add-binding-to-frame! var val frame) (set-car! frame (cons var (car frame))) (set-cdr! frame (cons val (cdr frame)))) (define (extend-environment vars vals base-env) (if (= (length vars) (length vals)) (cons (make-frame vars vals) base-env) (error "can't match vals and vars" vars vals))) (define (lookup-variable-value var env) (define (env-loop env) (define (scan vars vals) (cond ((null? vars) (env-loop (enclosing-environment env))) ((eq? var (car vars)) (car vals)) (else (scan (cdr vars) (cdr vals))))) (if (eq? env the-empty-environment) (error "can't find var" var) (let ((frame (first-frame env))) (scan (frame-variables frame) (frame-values frame))))) (env-loop env)) (define (set-variable-value! var val env) (define (env-loop env) (define (scan vars vals) (cond ((null? vars) (env-loop (enclosing-environment env))) ((eq? var (car vars)) (set-car! vals val)) (else (scan (cdr vars) (cdr vals))))) (if (eq? env the-empty-environment) (error "unbound var" var) (let ((frame (first-frame env))) (scan (frame-variables frame) (frame-values frame))))) (env-loop env)) (define (define-variable! var val env) (let ((frame (first-frame env))) (define (scan vars vals) (cond ((null? vars) (add-binding-to-frame! var val frame)) ((eq? var (car vars)) (set-car! vals val)) (else (scan (cdr vars) (cdr vals))))) (scan (frame-variables frame) (frame-values frame)))) ;primitive过程 (define (primitive-procedure? proc) (tagged-list? proc 'primitive)) (define (primitive-implementation proc) (cadr proc)) (define primitive-procedures (list (list 'car car) (list 'cdr cdr) (list 'cons cons) (list 'null? null?) (list '+ +) (list '= =) (list '* *) (list '- -) (list 'null? null?) (list '() '()) (list 'list list) )) (define (primitive-procedure-names) (map car primitive-procedures)) (define (primitive-procedure-objects) (map (lambda (proc) (list 'primitive (cadr proc))) primitive-procedures)) (define (apply-primitive-procedure proc args) (apply (primitive-implementation proc) args)) (define input-prompt "M-Eval input:") (define output-prompt "M-Eval output:") (define (driver-loop) (prompt-for-input input-prompt) (let ((input (read))) (let ((output (eval input the-global-environment))) (announce-output output-prompt) (user-print output))) (driver-loop)) (define (prompt-for-input string) (newline) (newline) (display string) (newline)) (define (announce-output string) (newline) (display string) (newline)) (define (user-print object) (if (compound-procedure? object) (display (list 'compound-procedure (procedure-parameters object) (procedure-body object))) (display object))) ;全局环境 (define (setup-environment) (let ((initial-env (extend-environment (primitive-procedure-names) (primitive-procedure-objects) the-empty-environment))) (define-variable! '#t #t initial-env) (define-variable! '#f #f initial-env) initial-env)) (define the-global-environment (setup-environment)) ;let (define (let? exp) (tagged-list? exp 'let)) (define (let-defn exp) (cadr exp)) (define (let-body exp) (cddr exp)) (define (let-combination exp) (let ((defn (let-defn exp)) (body (let-body exp))) (let ((vars (map car defn)) (exps (map cadr defn))) (cons (make-lambda vars body) exps)))) ; (driver-loop) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (make-machine register-names ops controller-text) (let ((machine (make-new-machine))) (for-each (lambda (register-name) ((machine 'allocate-register) register-name)) register-names) ((machine 'install-operations) ops) (let ((inst-label (assemble controller-text machine))) ((machine 'install-instruction-sequence) (car inst-label)) ((machine 'install-labels) (cdr inst-label)) machine))) ;register (define (make-register name) (let ((contents '*unassigned*) (trace #f));;; (define (set-register value) (if trace (begin (newline) (display name) (display ":") (display contents) (display " -> ") (display value) (set! contents value)) (set! contents value))) (define (dispatch message) (cond ((eq? message 'get) contents) ((eq? message 'set) set-register) ((eq? message 'trace-on) (set! trace #t)) ((eq? message 'trace-off) (set! trace #f)) (else (error "register" "unknown request" message)))) dispatch)) (define (get-contents register) (register 'get)) (define (set-contents! register value) ((register 'set) value)) (define (set-register-trace! machine reg-name on-off);;; ((machine 'reg-trace) reg-name on-off)) ;stack (define (make-stack) (let ((s '()) (number-pushes 0) (max-depth 0) (current-depth 0)) (define (push x) (set! s (cons x s)) (set! number-pushes (+ 1 number-pushes)) (set! current-depth (+ 1 current-depth)) (set! max-depth (max current-depth max-depth))) (define (pop) (if (null? s) (error "pop" "Empty stack" x)) (let ((top (car s))) (set! s (cdr s)) (set! current-depth (- current-depth 1)) top)) (define (initialize) (print-statistics) (set! s '()) (set! number-pushes 0) (set! current-depth 0) (set! max-depth 0) 'done) (define (print-statistics) (newline) (display (list 'total-pushes '= number-pushes 'maximum-depth '= max-depth))) (define (dispatch message) (cond ((eq? message 'push) push) ((eq? message 'pop) (pop)) ((eq? message 'initialize) (initialize)) ((eq? message 'print-statistics) (print-statistics)) (else (error "stack" "unknown request" message)))) dispatch)) (define (pop stack) (stack 'pop)) (define (push stack value) ((stack 'push) value)) ;initial-machine (define (make-new-machine) (let ((pc (make-register 'pc)) (flag (make-register 'flag)) (stack (make-stack)) (the-instruction-sequence '()) (labels '())) (let ((the-ops (list (list 'initialize-stack (lambda () (stack 'initialize))) (list 'print-stack-statistics (lambda () (stack 'print-statistics))))) (register-table (list (list 'pc pc) (list 'flag flag))) (bp-table '()) (inst-counter 0) (trace #f)) (define (allocate-register name) (if (assoc name register-table) (error "allocate-register" "Multiply define register:" name) (set! register-table (cons (list name (make-register name)) register-table))) 'register-allocated) (define (lookup-register name) (let ((val (assoc name register-table))) (if val (cadr val) (error "lookup-register" "Unknown register" name)))) (define (lookup-label name) (let ((label (assoc name labels))) (if label (cdr label) (error "lookup-label" "Unknown label" label)))) (define (execute) (let ((insts (get-contents pc))) (if (null? insts) 'done (if (breakpoint? (car insts)) (begin (display "breakpoint: ") (display (breakpoint-label (car insts))) (display " ") (display (breakpoint-diff (car insts))) (advance-pc pc)) (begin ((instruction-execution-proc (car insts))) (set! inst-counter (+ 1 inst-counter)) (if trace (begin (newline) (display (instruction-text (car insts))))) (execute)))))) (define (set-breakpoint label-name n) (let ((label (lookup-label label-name))) (define (aim-inst insts diff) (cond ((<= diff 0) (error "set-breakpoint" "n can't be less than 1" label)) ((null? insts) (error "set-breakpoint" "breakpoint can't be set since the porc finished" label)) ((= diff 1) (let ((temp (car insts)) (bp (list 'breakpoint label-name n))) (set-car! insts bp) (set-cdr! insts (cons temp (cdr insts))) (set! bp-table (cons (cons bp insts) bp-table)))) (else (aim-inst (cdr insts) (- diff 1))))) (aim-inst label n))) (define (delete-one-breakpoint bp) (let ((inst (cdr (car bp)))) (set-car! inst (cadr inst)) (set-cdr! inst (cddr inst))) (if (null? (cdr bp)) (set! bp '()) (begin (set-car! bp (cadr bp)) (set-cdr! bp (cddr bp))))) (define (cancel-breakpoint label-name n) (define (lookup-breakpoint breakpoint table) (cond ((null? table) (error "lookup breakpoint" "not such breakpoint" label-name)) ((equal? breakpoint (car (car table))) table) (else (lookup-breakpoint breakpoint (cdr table))))) (let ((bp (lookup-breakpoint (list 'breakpoint label-name n) bp-table))) (delete-one-breakpoint bp))) (define (cancel-all-breakpoint) (if (not (null? bp-table)) (begin (delte-one-breakpoint bp-table) (cancel-all-breakpoint)))) (define (dispatch message) (cond ((eq? message 'start) (set-contents! pc the-instruction-sequence) (execute)) ((eq? message 'proceed-machine) (execute)) ((eq? message 'install-instruction-sequence) (lambda (seq) (set! the-instruction-sequence seq))) ((eq? message 'install-labels);;; (lambda (lab) (set! labels lab))) ((eq? message 'get-label) lookup-label) ((eq? message 'allocate-register) allocate-register) ((eq? message 'get-register) lookup-register) ((eq? message 'install-operations) (lambda (ops) (set! the-ops (append the-ops ops)))) ((eq? message 'stack) stack) ((eq? message 'operations) the-ops) ((eq? message 'trace-on) (set! trace #t));;; ((eq? message 'trace-off) (set! trace #f));;; ((eq? message 'inst-number);;; (let ((temp inst-counter)) (set! inst-counter 0) temp)) ((eq? message 'reg-trace);;; (lambda (reg-name switch) ((lookup-register reg-name) switch))) ((eq? message 'set-breakpoint) set-breakpoint) ((eq? message 'cancel-breakpoint) cancel-breakpoint) ((eq? message 'cancel-all-breakpoint) (cancel-all-breakpoint)) (else (error "machine" "Unknown request" message)))) dispatch))) (define (start machine) (machine 'start)) (define (get-register machine reg-name) ((machine 'get-register) reg-name)) (define (get-register-contents machine register-name) (get-contents (get-register machine register-name))) (define (set-register-contents! machine register-name value) (set-contents! (get-register machine register-name) value) 'done) ; (define (assemble controller-text machine) (extract-labels controller-text (lambda (insts labels) (update-insts! insts labels machine) (cons insts labels)))) (define (extract-labels text receive) (if (null? text) (receive '() '()) (extract-labels (cdr text) (lambda (insts labels) (let ((next-inst (car text))) (if (symbol? next-inst) (receive insts (cons (make-label-entry next-inst insts) labels)) (receive (cons (make-instruction next-inst) insts) labels))))))) (define (update-insts! insts labels machine) (let ((pc (get-register machine 'pc)) (flag (get-register machine 'flag)) (stack (machine 'stack)) (ops (machine 'operations))) (for-each (lambda (inst) (set-instruction-execution-proc! inst (make-execution-procedure (instruction-text inst) labels machine pc flag stack ops))) insts))) (define (make-instruction text) (cons text '())) (define (instruction-text inst) (car inst)) (define (instruction-execution-proc inst) (cdr inst)) (define (set-instruction-execution-proc! inst proc) (set-cdr! inst proc)) (define (make-label-entry label-name insts) (cons label-name insts)) (define (lookup-label labels label-name) (let ((val (assoc label-name labels))) (if val (cdr val) (error "assemble" "Undefined label" label-name)))) (define (make-execution-procedure inst labels machine pc flag stack ops) (cond ((eq? (car inst) 'assign) (make-assign inst machine labels ops pc)) ((eq? (car inst) 'test) (make-test inst machine labels ops flag pc)) ((eq? (car inst) 'branch) (make-branch inst machine labels flag pc)) ((eq? (car inst) 'goto) (make-goto inst machine labels pc)) ((eq? (car inst) 'save) (make-save inst machine stack pc)) ((eq? (car inst) 'restore) (make-restore inst machine stack pc)) ((eq? (car inst) 'perform) (make-perform inst machine labels ops pc)) (else (error "ASSEMBLE" "Unknown instruction type" inst)))) ;assign (define (make-assign inst machine labels operations pc) (let ((target (get-register machine (assign-reg-name inst))) (value-exp (assign-value-exp inst))) (let ((value-proc (if (operation-exp? value-exp) (make-operation-exp value-exp machine labels operations) (make-primitive-exp (car value-exp) machine labels)))) (lambda () (set-contents! target (value-proc)) (advance-pc pc))))) (define (assign-reg-name assign-instruction) (cadr assign-instruction)) (define (assign-value-exp assign-instruction) (cddr assign-instruction)) (define (advance-pc pc) (set-contents! pc (cdr (get-contents pc)))) ;跳转 (define (make-test inst machine labels operations flag pc) (let ((condition (test-condition inst))) (if (operation-exp? condition) (let ((condition-proc (make-operation-exp condition machine labels operations))) (lambda () (set-contents! flag (condition-proc)) (advance-pc pc))) (error "ASSEMBLE" "Bad test" inst)))) (define (test-condition test-instruction) (cdr test-instruction)) ; (define (make-branch inst machine labels flag pc) (let ((dest (branch-dest inst))) (if (label-exp? dest) (let ((insts (lookup-label labels (label-exp-label dest)))) (lambda () (if (get-contents flag) (set-contents! pc insts) (advance-pc pc)))) (error "ASSEMBLE" "Bad branch" inst)))) (define (branch-dest branch-instruction) (cadr branch-instruction)) (define (make-goto inst machine labels pc) (let ((dest (goto-dest inst))) (cond ((label-exp? dest) (let ((insts (lookup-label labels (label-exp-label dest)))) (lambda () (set-contents! pc insts)))) ((register-exp? dest) (let ((reg (get-register machine (register-exp-reg dest)))) (lambda () (set-contents! pc (get-contents reg))))) (else (error "ASSEMBLE" "Bad GOTO" isnt))))) (define (goto-dest goto-instruction) (cadr goto-instruction)) ;stak and perform (define (make-save inst machine stack pc) (let ((reg (get-register machine (stack-inst-reg-name inst)))) (lambda () (push stack (get-contents reg)) (advance-pc pc)))) (define (make-restore inst machine stack pc) (let ((reg (get-register machine (stack-inst-reg-name inst)))) (lambda () (set-contents! reg (pop stack)) (advance-pc pc)))) (define (stack-inst-reg-name stack-instruction) (cadr stack-instruction)) (define (make-perform inst machine labels operations pc) (let ((action (preform-action inst))) (if (operation-exp? action) (let ((action-proc (make-operation-exp action machine labels operations))) (lambda () (action-proc) (advance-pc pc))) (error "ASSEMBLE" "bad perform" inst)))) (define (preform-action inst) (cdr inst)) ;构造执行 (define (make-primitive-exp exp machine labels) (cond ((constant-exp? exp) (let ((c (constant-exp-value exp))) (lambda () c))) ((label-exp? exp) (let ((insts (lookup-label labels (label-exp-label exp)))) (lambda () insts))) ((register-exp? exp) (let ((reg (get-register machine (register-exp-reg exp)))) (lambda () (get-contents reg)))) (else (error "ASSEMBLE" "Unknown expression typr" exp)))) (define (register-exp? exp) (tagged-list? exp 'reg)) (define (register-exp-reg exp) (cadr exp)) (define (constant-exp? exp) (tagged-list? exp 'const)) (define (constant-exp-value exp) (cadr exp)) (define (label-exp? exp) (tagged-list? exp 'label)) (define (label-exp-label exp) (cadr exp)) ; (define (make-operation-exp exp machine labels operations) (let ((op (lookup-prim (operation-exp-op exp) operations)) (aprocs (map (lambda (e) (make-primitive-exp e machine labels)) (operation-exp-operands exp)))) (lambda () (apply op (map (lambda (p) (p)) aprocs))))) (define (operation-exp? exp) (and (pair? exp) (tagged-list? (car exp) 'op))) (define (operation-exp-op exp) (cadar exp)) (define (operation-exp-operands exp) (cdr exp)) (define (lookup-prim symbol operations) (let ((val (assoc symbol operations))) (if val (cadr val) (error "ASSEMBLE" "Unknown operation" symbol)))) (define (tagged-list? exp tag) (if (pair? exp) (eq? (car exp) tag) #f)) (define (empty-arglist) '()) (define (adjoin-arg arg arglist) (append arglist (list arg))) (define (last-operand? ops) (null? (cdr ops))) (define (no-more-exps? seq) (null? seq)) (define (get-global-environment) the-global-environment) (define (breakpoint? exp) (tagged-list? exp 'breakpoint)) (define (breakpoint-label bp) (cadr bp)) (define (breakpoint-diff bp) (caddr bp)) (define (get-machine-label machine label-name) ((machine 'get-label) label-name)) (define (set-machine-breakpoint machine label-name n) ((machine 'set-breakpoint) label-name n)) (define (cancel-machine-breakpoint machine label-name n) ((machine 'cancel-breakpoint) label-name n)) (define (cancel-machine-all-breakpoint machine) (machine 'cancel-all-breakpoint)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define eceval-operations (list (list 'self-evaluating? self-evaluating?) (list 'variable? variable?) (list 'quoted? quoted?) (list 'assignment? assignment?) (list 'definition? definition?) (list 'if? if?) (list 'lambda? lambda?) (list 'begin? begin?) (list 'application? application?) (list 'lookup-variable-value lookup-variable-value) (list 'text-of-quotation text-of-quotation) (list 'lambda-parameters lambda-parameters) (list 'lambda-body lambda-body) (list 'make-procedure make-procedure) (list 'operands operands) (list 'announce-output announce-output) (list 'user-print user-print) (list 'read read) (list 'get-global-environment get-global-environment) (list 'prompt-for-input prompt-for-input) (list 'definition-value definition-value) (list 'define-variable! define-variable!) (list 'set-variable-value! set-variable-value!) (list 'definition-variable definition-variable) (list 'assignment-variable assignment-variable) (list 'assignment-value assignment-value) (list 'if-alternative if-alternative) (list 'if-consequent if-consequent) (list 'if-predicate if-predicate) (list 'true? true?) (list 'last-exp? last-exp?) (list 'rest-exps rest-exps) (list 'begin-actions begin-actions) (list 'first-exp first-exp) (list 'extend-environment extend-environment) (list 'procedure-body procedure-body) (list 'procedure-parameters procedure-parameters) (list 'procedure-environment procedure-environment) (list 'compound-procedure? compound-procedure?) (list 'apply-primitive-procedure apply-primitive-procedure) (list 'rest-operands rest-operands) (list 'primitive-procedure? primitive-procedure?) (list 'last-operand? last-operand?) (list 'adjoin-arg adjoin-arg) (list 'no-operands? no-operands?) (list 'first-operand first-operand) (list 'operator operator) (list 'empty-arglist empty-arglist))) (define eceval (make-machine '(exp env val proc argl continue unev) eceval-operations '( read-eval-print-loop (perform (op initialize-stack)) (perform (op prompt-for-input) (const ";;; EC-Eval input:")) (assign exp (op read)) (assign env (op get-global-environment)) (assign continue (label print-result)) (goto (label eval-dispatch)) print-result (perform (op announce-output) (const ";;; EC-Eval value:")) (perform (op user-print) (reg val)) (goto (label read-eval-print-loop)) unknown-expression-type (assign val (const unknown-expression-type-error)) (goto (label signal-error)) unknown-procedure-type ; clean up stack (from apply-dispatch): (restore continue) (assign val (const unknown-procedure-type-error)) (goto (label signal-error)) signal-error (perform (op user-print) (reg val)) (goto (label read-eval-print-loop)) eval-dispatch (test (op self-evaluating?) (reg exp)) (branch (label ev-self-eval)) (test (op variable?) (reg exp)) (branch (label ev-variable)) (test (op quoted?) (reg exp)) (branch (label ev-quoted)) (test (op assignment?) (reg exp)) (branch (label ev-assignment)) (test (op definition?) (reg exp)) (branch (label ev-definition)) (test (op if?) (reg exp)) (branch (label ev-if)) (test (op lambda?) (reg exp)) (branch (label ev-lambda)) (test (op begin?) (reg exp)) (branch (label ev-begin)) (test (op application?) (reg exp)) (branch (label ev-application)) (goto (label unknown-expression-type)) ev-self-eval (assign val (reg exp)) (goto (reg continue)) ev-variable (assign val (op lookup-variable-value) (reg exp) (reg env)) (goto (reg continue)) ev-quoted (assign val (op text-of-quotation) (reg exp)) (goto (reg continue)) ev-lambda (assign unev (op lambda-parameters) (reg exp)) (assign exp (op lambda-body) (reg exp)) (assign val (op make-procedure) (reg unev) (reg exp) (reg env)) (goto (reg continue)) ev-application (save continue) (save env) (assign unev (op operands) (reg exp)) (save unev) (assign exp (op operator) (reg exp)) (assign continue (label ev-appl-did-operator)) (goto (label eval-dispatch)) 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) ev-appl-operand-loop (save argl) (assign exp (op first-operand) (reg unev)) (test (op last-operand?) (reg unev)) (branch (label ev-appl-last-arg)) (save env) (save unev) (assign continue (label ev-appl-accumulate-arg)) (goto (label eval-dispatch)) ev-appl-accumulate-arg (restore unev) (restore env) (restore argl) (assign argl (op adjoin-arg) (reg val) (reg argl)) (assign unev (op rest-operands) (reg unev)) (goto (label ev-appl-operand-loop)) ev-appl-last-arg (assign continue (label ev-appl-accum-last-arg)) (goto (label eval-dispatch)) ev-appl-accum-last-arg (restore argl) (assign argl (op adjoin-arg) (reg val) (reg argl)) (restore proc) (goto (label apply-dispatch)) apply-dispatch (test (op primitive-procedure?) (reg proc)) (branch (label primitive-apply)) (test (op compound-procedure?) (reg proc)) (branch (label compound-apply)) (goto (label unknown-procedure-type)) primitive-apply (assign val (op apply-primitive-procedure) (reg proc) (reg argl)) (restore continue) (goto (reg continue)) compound-apply (assign unev (op procedure-parameters) (reg proc)) (assign env (op procedure-environment) (reg proc)) (assign env (op extend-environment) (reg unev) (reg argl) (reg env)) (assign unev (op procedure-body) (reg proc)) (goto (label ev-sequence)) ev-begin (assign unev (op begin-actions) (reg exp)) (save continue) (goto (label ev-sequence)) ev-sequence (assign exp (op first-exp) (reg unev)) (test (op last-exp?) (reg unev)) (branch (label ev-sequence-last-exp)) (save unev) (save env) (assign continue (label ev-sequence-continue)) (goto (label eval-dispatch)) ev-sequence-continue (restore env) (restore unev) (assign unev (op rest-exps) (reg unev)) (goto (label ev-sequence)) ev-sequence-last-exp (restore continue) (goto (label eval-dispatch)) ev-if (save exp) ; save expression for later (save env) (save continue) (assign continue (label ev-if-decide)) (assign exp (op if-predicate) (reg exp)) ; evaluate the predicate: (goto (label eval-dispatch)) ev-if-decide (restore continue) (restore env) (restore exp) (test (op true?) (reg val)) (branch (label ev-if-consequent)) ev-if-alternative (assign exp (op if-alternative) (reg exp)) (goto (label eval-dispatch)) ev-if-consequent (assign exp (op if-consequent) (reg exp)) (goto (label eval-dispatch)) ev-assignment (assign unev (op assignment-variable) (reg exp)) (save unev) ; save variable for later (assign exp (op assignment-value) (reg exp)) (save env) (save continue) (assign continue (label ev-assignment-1)) ; evaluate the assignment value: (goto (label eval-dispatch)) ev-assignment-1 (restore continue) (restore env) (restore unev) (perform (op set-variable-value!) (reg unev) (reg val) (reg env)) (assign val (const ok)) (goto (reg continue)) ev-definition (assign unev (op definition-variable) (reg exp)) (save unev) ; save variable for later (assign exp (op definition-value) (reg exp)) (save env) (save continue) (assign continue (label ev-definition-1)) ; evaluate the definition value: (goto (label eval-dispatch)) ev-definition-1 (restore continue) (restore env) (restore unev) (perform (op define-variable!) (reg unev) (reg val) (reg env)) (assign val (const ok)) (goto (reg continue)) ))) ; (start eceval) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (compile exp target linkage) (cond ((self-evaluating? exp) (compile-self-evaluating exp target linkage)) ((quoted? exp) (compile-quoted exp target linkage)) ((variable? exp) (compile-variable exp target linkage)) ((assignment? exp) (compile-assignment exp target linkage)) ((definition? exp) (compile-definition exp target linkage)) ((if? exp) (compile-if exp target linkage)) ((lambda? exp) (compile-lambda exp target linkage)) ((begin? exp) (compile-sequence (begin-actions exp) target linkage)) ((cond? exp) (compile (cond->if exp) target linkage)) ((application? exp) (compile-application exp target linkage)) (else (error "Unknown expression type: COMPILE" exp)))) (define (make-instruction-sequence needs modifies statements) (list needs modifies statements)) (define (empty-instruction-sequence) (make-instruction-sequence '() '() '())) (define (compile-linkage linkage) (cond ((eq? linkage 'return) (make-instruction-sequence '(continue) '() '((goto (reg continue))))) ((eq? linkage 'next) (empty-instruction-sequence)) (else (make-instruction-sequence '() '() `((goto (label ,linkage))))))) (define (end-with-linkage linkage instruction-sequence) (preserving '(continue) instruction-sequence (compile-linkage linkage))) (define (compile-self-evaluating exp target linkage) (end-with-linkage linkage (make-instruction-sequence '() (list target) `((assign ,target (const ,exp)))))) (define (compile-quoted exp target linkage) (end-with-linkage linkage (make-instruction-sequence '() (list target) `((assign ,target (const ,(text-of-quotation exp))))))) (define (compile-variable exp target linkage) (end-with-linkage linkage (make-instruction-sequence '(env) (list target) `((assign ,target (op lookup-variable-value) (const ,exp) (reg env)))))) (define (compile-assignment exp target linkage) (let ((var (assignment-variable exp)) (get-value-code (compile (assignment-value exp) 'val 'next))) (end-with-linkage linkage (preserving '(env) get-value-code (make-instruction-sequence '(env val) (list target) `((perform (op set-variable-value!) (const ,var) (reg val) (reg env)) (assign ,target (const ok)))))))) (define (compile-definition exp target linkage) (let ((var (definition-variable exp)) (get-value-code (compile (definition-value exp) 'val 'next))) (end-with-linkage linkage (preserving '(env) get-value-code (make-instruction-sequence '(env val) (list target) `((perform (op define-variable!) (const ,var) (reg val) (reg env)) (assign ,target (const ok)))))))) (define (compile-if exp target linkage) (let ((t-branch (make-label 'true-branch)) (f-branch (make-label 'false-branch)) (after-if (make-label 'after-if))) (let ((consequent-linkage (if (eq? linkage 'next) after-if linkage))) (let ((p-code (compile (if-predicate exp) 'val 'next)) (c-code (compile (if-consequent exp) target consequent-linkage)) (a-code (compile (if-alternative exp) target linkage))) (preserving '(env continue) p-code (append-instruction-sequences (make-instruction-sequence '(val) '() `((test (op false?) (reg val)) (branch (label ,f-branch)))) (parallel-instruction-sequences (append-instruction-sequences t-branch c-code) (append-instruction-sequences f-branch a-code)) after-if)))))) (define (compile-sequence seq target linkage) (if (last-exp? seq) (compile (first-exp seq) target linkage) (preserving '(env continue) (compile (first-exp seq) target 'next) (compile-sequence (rest-exps seq) target linkage)))) (define (compile-lambda exp target linkage) (let ((proc-entry (make-label 'entry)) (after-lambda (make-label 'after-lambda))) (let ((lambda-linkage (if (eq? linkage 'next) after-lambda linkage))) (append-instruction-sequences (tack-on-instruction-sequence (end-with-linkage lambda-linkage (make-instruction-sequence '(env) (list target) `((assign ,target (op make-compiled-procedure) (label ,proc-entry) (reg env))))) (compile-lambda-body exp proc-entry)) after-lambda)))) (define (compile-lambda-body exp proc-entry) (let ((formals (lambda-parameters exp))) (append-instruction-sequences (make-instruction-sequence '(env proc argl) '(env) `(,proc-entry (assign env (op compiled-procedure-env) (reg proc)) (assign env (op extend-environment) (const ,formals) (reg argl) (reg env)))) (compile-sequence (lambda-body exp) 'val 'return)))) (define (compile-application exp target linkage) (let ((proc-code (compile (operator exp) 'proc 'next)) (operand-codes (map (lambda (operand) (compile operand 'val 'next)) (operands exp)))) (preserving '(env continue) proc-code (preserving '(proc continue) (construct-arglist operand-codes) (compile-procedure-call target linkage))))) (define (construct-arglist operand-codes) (let ((operand-codes (reverse operand-codes))) (if (null? operand-codes) (make-instruction-sequence '() '(argl) '((assign argl (const ())))) (let ((code-to-get-last-arg (append-instruction-sequences (car operand-codes) (make-instruction-sequence '(val) '(argl) '((assign argl (op list) (reg val))))))) (if (null? (cdr operand-codes)) code-to-get-last-arg (preserving '(env) code-to-get-last-arg (code-to-get-rest-args (cdr operand-codes)))))))) (define (code-to-get-rest-args operand-codes) (let ((code-for-next-arg (preserving '(argl) (car operand-codes) (make-instruction-sequence '(val argl) '(argl) '((assign argl (op cons) (reg val) (reg argl))))))) (if (null? (cdr operand-codes)) code-for-next-arg (preserving '(env) code-for-next-arg (code-to-get-rest-args (cdr operand-codes)))))) (define (compile-procedure-call target linkage) (let ((primitive-branch (make-label 'primitive-branch)) (compiled-branch (make-label 'compiled-branch)) (after-call (make-label 'after-call))) (let ((compiled-linkage (if (eq? linkage 'next) after-call linkage))) (append-instruction-sequences (make-instruction-sequence '(proc) '() `((test (op primitive-procedure?) (reg proc)) (branch (label ,primitive-branch)))) (parallel-instruction-sequences (append-instruction-sequences compiled-branch (compile-proc-appl target compiled-linkage)) (append-instruction-sequences primitive-branch (end-with-linkage linkage (make-instruction-sequence '(proc argl) (list target) `((assign ,target (op apply-primitive-procedure) (reg proc) (reg argl))))))) after-call)))) (define (compile-proc-appl target linkage) (cond ((and (eq? target 'val) (not (eq? linkage 'return))) (make-instruction-sequence '(proc) all-regs `((assign continue (label ,linkage)) (assign val (op compiled-procedure-entry) (reg proc)) (goto (reg val))))) ((and (not (eq? target 'val)) (not (eq? linkage 'return))) (let ((proc-return (make-label 'proc-return))) (make-instruction-sequence '(proc) all-regs `((assign continue (label ,proc-return)) (assign val (op compiled-procedure-entry) (reg proc)) (goto (reg val)) ,proc-return (assign ,target (reg val)) (goto (label ,linkage)))))) ((and (eq? target 'val) (eq? linkage 'return)) (make-instruction-sequence '(proc continue) all-regs '((assign val (op compiled-procedure-entry) (reg proc)) (goto (reg val))))) ((and (not (eq? target 'val)) (eq? linkage 'return)) (error "return linkage, target not val: COMPILE" target)))) (define (registers-needed s) (if (symbol? s) '() (car s))) (define (registers-modified s) (if (symbol? s) '() (cadr s))) (define (statements s) (if (symbol? s) (list s) (caddr s))) (define (needs-register? seq reg) (memq reg (registers-needed seq))) (define (modifies-register? seq reg) (memq reg (registers-modified seq))) (define (append-instruction-sequences . seqs) (define (append-2-sequences seq1 seq2) (make-instruction-sequence (list-union (registers-needed seq1) (list-difference (registers-needed seq2) (registers-modified seq1))) (list-union (registers-modified seq1) (registers-modified seq2)) (append (statements seq1) (statements seq2)))) (define (append-seq-list seqs) (if (null? seqs) (empty-instruction-sequence) (append-2-sequences (car seqs) (append-seq-list (cdr seqs))))) (append-seq-list seqs)) (define (list-union s1 s2) (cond ((null? s1) s2) ((memq (car s1) s2) (list-union (cdr s1) s2)) (else (cons (car s1) (list-union (cdr s1) s2))))) (define (list-difference s1 s2) (cond ((null? s1) '()) ((memq (car s1) s2) (list-difference (cdr s1) s2)) (else (cons (car s1) (list-difference (cdr s1) s2))))) (define (preserving regs seq1 seq2) (if (null? regs) (append-instruction-sequences seq1 seq2) (let ((first-reg (car regs))) (if (and (needs-register? seq2 first-reg) (modifies-register? seq1 first-reg)) (preserving (cdr regs) (make-instruction-sequence (list-union (list first-reg) (registers-needed seq1)) (list-difference (registers-modified seq1) (list first-reg)) (append `((save ,first-reg)) (statements seq1) `((restore ,first-reg)))) seq2) (preserving (cdr regs) seq1 seq2))))) (define (tack-on-instruction-sequence seq body-seq) (make-instruction-sequence (registers-needed seq) (registers-modified seq) (append (statements seq) (statements body-seq)))) (define (parallel-instruction-sequences seq1 seq2) (make-instruction-sequence (list-union (registers-needed seq1) (registers-needed seq2)) (list-union (registers-modified seq1) (registers-modified seq2)) (append (statements seq1) (statements seq2)))) (define (make-compiled-procedure entry env) (list 'compiled-procedure entry env)) (define (compiled-procedure? proc) (tagged-list? proc 'compiled-precedure)) (define (compiled-procedure-entry c-proc) (cadr c-proc)) (define (compiled-procedure-env c-proc) (caddr c-proc)) (define label-counter 0) (define (new-label-number) (set! label-counter (+ 1 label-counter)) label-counter) (define (make-label name) (string->symbol (string-append (symbol->string name) (number->string (new-label-number))))) (define all-regs '(env proc val argl continue)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; (map (lambda (x) (newline) (display x)) ; (reverse (caddr ; (compile ; '(define (factorial n) ; (if (= n 1) ; 1 ; (* (factorial (- n 1)) n))) ; 'val ; 'next) ; ))) ; (exit) ;5.33 ;(* n (fac (- n 1)))需要save env ;(* (fac (- n 1)) n)需要save argl ;5.34 ;汇编程序不会为最后调用的函数保留after-return,所以尾递归优化不止是为尾递归函数优化,实际上它在优化所以函数。 ;只是尾递归函数能得到每一层的优化 ;5.35 ;wtm ;5.36 ;参数求值顺序 右->左 ;construct-arglist函数控制 ;会影响一点? ;5.37
false
990634036a6d6ed4246675dfa177ac038ab37c7f
eb4c9cc6036c985065fec67e3116115be1d7fc12
/lisp/tests/begin.scm
4ae7f042ecb76930cf8a0631bd733729829f7da7
[ "MIT" ]
permissive
jorendorff/cell-gc
31d751a1d854248bb894a43c4d10a951e203cd6a
1d73457069b93b6af1adbfeb390ba1fbae8a291a
refs/heads/master
2021-07-12T10:24:19.880104
2017-12-13T16:11:33
2017-12-13T16:11:33
49,678,729
62
5
null
2017-11-14T19:35:38
2016-01-14T22:12:58
Pascal
UTF-8
Scheme
false
false
339
scm
begin.scm
(define x 0) (assert (eq? (begin (set! x 5) (+ x 1)) 6)) (assert (eq? x 5)) ;; At toplevel, `begin` forms are splicing, and definitions can be interleaved ;; with expressions. (begin (define y 2) (set! x (+ y 100)) (define z 3)) (assert (eq? y 2)) (assert (eq? x 102)) (assert (eq? z 3))
false
bebf6ad432ff1af44ecd94cad9a8b03d50a3f1dc
03e4064a7a55b5d00937e74cddb587ab09cf7af9
/nscheme/old/old-5/lib/base.scm
670abb83f17910336ac6e5976765f618d08d34c9
[ "BSD-2-Clause" ]
permissive
gregr/ina
29f28396cd47aa443319147ecde5235d11e1c3d1
16188050caa510899ae22ff303a67897985b1c3b
refs/heads/master
2023-08-25T13:31:44.131598
2023-08-14T16:46:48
2023-08-14T16:46:48
40,606,975
17
0
null
null
null
null
UTF-8
Scheme
false
false
9,072
scm
base.scm
((provide language:empty language:initial language:primitive language:base-primitive language:base module:base-primitive module:base) (require ast:var ast:prim ast:lambda ast:let ast:list primitive-op-descriptions primitive-op-type-signature parse env:empty env:initial env:primitive language module)) (define language:empty (language '() '() '() '() env:empty)) (define language:initial (language '() '() '() '() env:initial)) (define language:primitive (language '() '() '() '() env:primitive)) (define names:prim (cons 'apply (map car primitive-op-descriptions))) (define language:base-primitive (language names:prim '() names:prim '() env:initial)) (define module:base-primitive (let* ((lam:apply (parse env:primitive '(lambda (f arg . args) (define (cons* x xs) (if (null? xs) x (cons x (cons* (car xs) (cdr xs))))) (apply f (cons* arg args))))) (lams:prim (map (lambda (po-desc) (define (x i) (vector-ref '#(x0 x1 x2 x3 x4) i)) (define type-sig (primitive-op-type-signature po-desc)) (define p* (map x (range (length (car type-sig))))) (ast:lambda p* (ast:prim (car po-desc) (map ast:var p*)))) primitive-op-descriptions)) (ast (ast:lambda '() (ast:let names:prim (cons lam:apply lams:prim) (apply ast:list (map ast:var names:prim)))))) (module '() names:prim ast '() '()))) (define defs:base '((error (lambda args ('error args))) (not (lambda (b) (if b #f #t))) (caar (lambda (v) (car (car v)))) (cadr (lambda (v) (car (cdr v)))) (cddr (lambda (v) (cdr (cdr v)))) (cdar (lambda (v) (cdr (car v)))) (caaar (lambda (v) (car (caar v)))) (caadr (lambda (v) (car (cadr v)))) (cadar (lambda (v) (car (cdar v)))) (caddr (lambda (v) (car (cddr v)))) (cdaar (lambda (v) (cdr (caar v)))) (cdadr (lambda (v) (cdr (cadr v)))) (cddar (lambda (v) (cdr (cdar v)))) (cdddr (lambda (v) (cdr (cddr v)))) (list-tail (lambda (xs i) (if (= 0 i) xs (list-tail (cdr xs) (- i 1))))) (list-ref (lambda (xs i) (car (list-tail xs i)))) (list->vector (lambda (xs) (define result (make-mvector (length xs) #t)) (foldl (lambda (x i) (mvector-set! result i x) (+ i 1)) 0 xs) (mvector->vector result))) (vector->list (lambda (v) (let loop ((i (- (vector-length v) 1)) (xs '())) (if (< i 0) xs (loop (- i 1) (cons (vector-ref v i) xs)))))) (string->list (lambda (s) (vector->list (string->vector s)))) (list->string (lambda (cs) (vector->string (list->vector cs)))) (equal? (lambda (a b) (cond ((pair? a) (and (pair? b) (equal? (car a) (car b)) (equal? (cdr a) (cdr b)))) ((vector? a) (and (vector? b) (equal? (vector->list a) (vector->list b)))) ((boolean? a) (and (boolean? b) (boolean=? a b))) ((string? a) (and (string? b) (string=? a b))) ((number? a) (and (number? b) (number=? a b))) ((mvector? a) (and (mvector? b) (mvector=? a b))) ((procedure? a) (and (procedure? b) (procedure=? a b))) ((null? a) (null? b))))) (vector (lambda xs (list->vector xs))) (vector-set (lambda (v i x) (define result (make-mvector (vector-length v) #t)) (foldl (lambda (x i) (mvector-set! result i x) (+ i 1)) 0 (vector->list v)) (mvector-set! result i x) (mvector->vector result))) (list? (lambda (v) (or (and (pair? v) (list? (cdr v))) (null? v)))) (list (lambda xs xs)) (list* (lambda (x . xs) (if (null? xs) x (cons x (apply list* xs))))) ;; TODO: n-ary versions of foldl, foldr. (foldl (lambda (f acc xs) (if (null? xs) acc (foldl f (f (car xs) acc) (cdr xs))))) (foldr (lambda (f acc xs) (if (null? xs) acc (f (car xs) (foldr f acc (cdr xs)))))) (map (lambda (f xs . xss) (define (map1 f xs) (if (null? xs) '() (cons (f (car xs)) (map1 f (cdr xs))))) (cond ((null? xs) '()) (#t (cons (apply f (car xs) (map1 car xss)) (apply map f (cdr xs) (map1 cdr xss))))))) (for-each (lambda args (apply map args) #t)) (andmap (lambda (f xs . xss) (let loop ((last #t) (xs xs) (xss xss)) (and last (if (null? xs) last (loop (apply f (car xs) (map car xss)) (cdr xs) (map cdr xss))))))) (ormap (lambda (f xs . xss) (cond ((null? xs) #f) (#t (let ((? (apply f (car xs) (map car xss)))) (if ? ? (apply ormap f (cdr xs) (map cdr xss)))))))) (filter (lambda (p? xs) (cond ((null? xs) '()) ((p? (car xs)) (cons (car xs) (filter p? (cdr xs)))) (#t (filter p? (cdr xs)))))) (filter-not (lambda (p? xs) (filter (lambda (x) (not (p? x))) xs))) (remf (lambda (p? xs) (cond ((null? xs) '()) ((p? (car xs)) (cdr xs)) (#t (cons (car xs) (remf p? (cdr xs))))))) (remove (lambda (v xs) (remf (lambda (x) (equal? x v)) xs))) (length (lambda (xs) (foldl (lambda (_ l) (+ 1 l)) 0 xs))) (append (lambda xss (foldr (lambda (xs yss) (foldr cons yss xs)) '() xss))) (reverse-append (lambda (xs ys) (foldl cons ys xs))) (reverse (lambda (xs) (reverse-append xs '()))) (range (lambda (n) (let loop ((i 0)) (if (= i n) '() (cons i (loop (+ i 1))))))) (split (lambda (xs n) (let loop ((xs xs) (n n) (rprefix '())) (if (= 0 n) (cons rprefix xs) (loop (cdr xs) (- n 1) (cons (car xs) rprefix)))))) (take (lambda (xs n) (reverse (car (split xs n))))) (drop (lambda (xs n) (cdr (split xs n)))) (memf (lambda (? xs) (cond ((null? xs) #f) ((? (car xs)) xs) (#t (memf ? (cdr xs)))))) (member (lambda (v xs) (memf (lambda (x) (equal? x v)) xs))) (assoc (lambda (k xs) (cond ((null? xs) #f) ((equal? k (caar xs)) (car xs)) (#t (assoc k (cdr xs)))))) (alist-get (lambda (rs key default) (let ((rib (assoc key rs))) (if rib (cdr rib) default)))) (alist-ref (lambda (alist k) (cdr (or (assoc k alist) (error '"alist-ref of non-existent key:" k alist))))) (alist-ref* (lambda (alist k*) (map (lambda (k) (alist-ref alist k)) k*))) (alist-remove* (lambda (rs keys) (filter (lambda (rib) (not (member (car rib) keys))) rs))) (string-append (lambda ss (define css (map vector->list (map string->vector ss))) (vector->string (list->vector (apply append css))))) (string-split (lambda (str sep) (define (rseg->str s) (list->string (reverse s))) (define sepv (string->vector sep)) (define sepcs (vector->list sepv)) (define len (vector-length sepv)) (define v (string->vector str)) (let loop ((cs (vector->list v)) (clen (vector-length v)) (rseg '()) (rs '())) (cond ((null? cs) (map rseg->str (reverse (if (pair? rseg) (cons rseg rs) rs)))) ((< clen len) (loop '() 0 (append cs rseg) rs)) ((equal? (take cs len) sepcs) (loop (drop cs len) (- clen len) '() (cons rseg rs))) (#t (loop (cdr cs) (- clen 1) (cons (car cs) rseg) rs)))))) (string-join (lambda (strs sep) (let ((rstrs (reverse strs)) (sepcs (string->list sep))) (list->string (foldl (lambda (s cs) (append (string->list s) (append sepcs cs))) (string->list (car rstrs)) (cdr rstrs)))))) )) (define names:base (map car defs:base)) (define names:prim&base (append names:prim names:base)) (define language:base (language names:prim&base '() names:prim&base '() env:initial)) (define module:base (let ((ast (parse env:initial (list 'lambda names:prim (list 'letrec defs:base (cons '(lambda xs xs) names:base)))))) (module names:prim names:base ast '() '())))
false
84fa0370ffd71967377bc77de96eecb6a9fb224d
0855447c3321a493efa9861b3713209e37c03a4c
/sicp/chapter02_1.ss
8ccb81695b4da9af6db83157c4f2579c9eccdf30
[]
no_license
dasheng523/sicp
d04f30c50076f36928728ad2fe0da392dd0ae414
1c40c01e16853ad83b8b82130c2c95a5533875fe
refs/heads/master
2021-06-16T20:15:08.281249
2021-04-02T04:09:01
2021-04-02T04:09:01
190,505,284
0
0
null
null
null
null
UTF-8
Scheme
false
false
6,385
ss
chapter02_1.ss
;;(define wave2 ;; (beside wave (flip-vert wave))) ;;(define wave4 ;; (below wave2 wave2)) ;; 画家在有关语言组合方式下是封闭的。 (define (flipped-pairs painter) (let ((painter2 (beside painter (flip-vert painter)))) (below painter2 painter2))) (define wave4 (flipped-pairs wave)) (define (right-split painter n) (if (= n 0) painter (let ((smaller (right-split painter (- n 1)))) (beside painter (below smaller smaller))))) (define (corner-split painter n) (if (= n 0) painter (let ((up (up-split painter (- n 1))) (right (right-split painter (- n 1)))) (let ((top-left (beside up up)) (bottom-right (below right right)) (corner (corner-split painter (- n 1)))) (beside (below painter top-left) (below bottom-right corner)))))) (define (square-limit painter n) (let ((quarter (corner-split painter n))) (let ((half (beside (flip-horiz quarter) quarter))) (below (flip-vert half) half)))) ;; 2.44 (define (up-split painter n) (if (= n 0) painter (let ((up (up-split painter (- n 1)))) (below painter (beside up up))))) ;; 抽象的基础在于观察。 ;; 比如flipped-pairs和square-limit两者的区别就很相近,都将画家复制并放入四个正方形模式里。 (define (square-of-four tl tr bl br) (lambda (painter) (let ((top (beside (tl painter) (tr painter))) (bottom (beside (bl painter) (br painter)))) (below bottom top)))) (define (flipped-pairs painter) (let ((combine4 (square-of-four identity flip-vert identity flip-vert))) (combine4 painter))) (define (square-limit painter n) (let ((combine4 (square-of-four flip-horiz identity rotate180 flip-vert))) (combine4 (corner-split painter n)))) ;; 2.45 (define (split p1 p2) (define (split-fn painter n) (if (= n 0) painter (let ((smaller (split-fn painter (- n 1)))) (p1 painter (p2 smaller smaller))))) split-fn) (define right-split (split beside below)) (define (up-split (split below beside))) (define (frame-coord-map frame) (lambda (v) (add-vect (origin-frame frame) (add-vect (scale-vect (xcor-vect v) (edge1-frame frame)) (scale-vect (ycor-vect v) (edge2-frame frame)))))) ;; 2.46 (define (make-vect x y) (cons x y)) (define (xcor-vect v) (car v)) (define (ycor-vect v) (cdr v)) (define (add-vect v1 v2) (make-vect (+ (xcor-vect v1) (xcor-vect v2)) (+ (ycor-vect v1) (ycor-vect v2)))) (define (sub-vect v1 v2) (make-vect (- (xcor-vect v1) (xcor-vect v2)) (- (ycor-vect v1) (ycor-vect v2)))) (define (scale-vect s v) (make-vect (* s (xcor-vect v)) (* s (ycor-vect v)))) ;; 2.47 (define (make-frame origin edge1 edge2) (list origin edge1 edge2)) (define (origin-frame f) (car f)) (define (edge1-frame f) (car (cdr f))) (define (edge2-frame f) (car (cdr (cdr f)))) (define (make-frame origin edge1 edge2) (cons origin (cons edge1 edge2))) (define (origin-frame f) (car f)) (define (edge1-frame f) (car (cdr f))) (define (edge2-frame f) (cdr (cdr f))) (define (draw-line v1 v2) (display v1) (display "\n") (display v2)) (draw-line (cons 1 2) (cons 3 4)) (define (segments->painter segment-list) (lambda (frame) (for-each (lambda (segment) (draw-line ((frame-coord-map frame) (start-segment segment)) ((frame-coord-map frame) (end-segment segment)))) segment-list))) ;; 2.48 (define (make-segment v1 v2) (cons v1 v2)) (define (start-segment v) (car v)) (define (end-segment v) (cdr v)) ;; 2.49 (define (frame-painter frame) ((segments->painter (list (make-segment (make-vect 0 0) (make-vect 0 1)) (make-segment (make-vect 0 1) (make-vect 1 1)) (make-segment (make-vect 1 1) (make-vect 1 0)) (make-segment (make-vect 1 0) (make-vect 0 0)))) frame)) (define (frame-cross frame) ((segments->painter (list (make-segment (make-vect 0 0) (make-vect 1 1)) (make-segment (make-vect 1 0) (make-vect 0 1)))) frame)) (define (frame-diamond frame) ((segments->painter (list (make-segment (make-vect 0 0.5) (make-vect 0.5 1)) (make-segment (make-vect 0.5 1) (make-vect 1 0.5)) (make-segment (make-vect 1 0.5) (make-vect 0.5 0)) (make-segment (make-vect 0.5 0) (make-vect 0 0.5)))) frame)) (define (transform-painter painter origin corner1 corner2) (lambda (frame) (let ((m (frame-coord-map frame))) (let ((new-origin (m origin))) (painter (make-frame new-origin (sub-vect (m corner1) new-origin) (sub-vect (m corner2) new-origin))))))) (define (flip-vert painter) (transform-painter painter (make-vect 0.0 1.0) (make-vect 1.0 1.0) (make-vect 0.0 0.0))) (define (shrink-to-upper-right painter) (transform-painter painter (make-vect 0.5 0.5) (make-vect 1.0 0.5) (make-vect 0.5 1.0))) (define (rotate180 painter) (transform-painter painter (make-vect 1.0 0.0) (make-vect 1.0 1.0) (make-vect 0.0 0.0))) (define (squash-inwards painter) (transform-painter painter (make-vect 0.0 0.0) (make-vect 0.65 0.35) (make-vect 0.35 0.65))) (define (beside painter1 painter2) (let ((split-point (make-vect 0.5 0.0))) (let ((paint-left (transform-painter painter1 (make-vect 0.0 0.0) split-point (make-vect 0.0 1.0))) (paint-right (transform-painter painter2 split-point (make-vect 1.0 0.0) (make-vect 0.5 1.0)))) (lambda (frame) (paint-left frame) (paint-right frame)))))
false
444117cbf1bc231928322f7def5a866c2f7044a5
3c9983e012653583841b51ddfd82879fe82706fb
/experiments/a-normal-form/anf.scm
25c4dfe36812086ce434d5cbfe5d54a0e9708231
[]
no_license
spdegabrielle/smalltalk-tng
3c3d4cffa09541b75524fb1f102c7c543a84a807
545343190f556edd659f6050b98036266a270763
refs/heads/master
2020-04-16T17:06:51.884611
2018-08-07T16:18:20
2018-08-07T16:18:20
165,763,183
1
0
null
null
null
null
UTF-8
Scheme
false
false
8,182
scm
anf.scm
;; Conversion of a core-scheme-like language to ANF ;; after Flanagan et al. 1993, "The Essence of Compiling with Continuations" ;; A-Normal Form, from Wikipedia: ;; EXP ::= VAL VAL ;; | let VAR = EXP in EXP ;; VAL ::= lambda VAR . EXP ;; | VAR ;; We'll extend the core calculus with a lazy construct, which plays ;; the role of scheme's letrec. We replace simple let with a ;; pattern-matching construct, which covers both let and if. We keep ;; the single-argument restriction for now. ;; ;; In terms of data, we keep closures, and extend the language with ;; tuples and integer and symbol literals. (require (lib "1.ss" "srfi") ;; lists (lib "8.ss" "srfi") ;; receive (lib "9.ss" "srfi") ;; records (lib "pretty.ss") "justlazy.scm" (lib "packrat.ss" "json-scheme")) (load "node.scm") (load "parse-etng.scm") (define *debug-mode* '(sequence-phases)) (define a-normal-form-languages `( (core-exp (%or (core-send (receiver core-exp) (message core-exp)) (core-case (value core-exp) (clauses (%list-of core-case-clause))) (core-lazy (bindings (%list-of core-lazy-binding)) (body core-exp)) (core-object (methods (%list-of core-method))) (core-sequence (exps (%list-of core-exp))) (core-let (pattern data-pattern) (value core-exp)) (core-ref (name ,symbol?)) (core-tuple (elements (%list-of core-exp))) (core-lit (value #t)) )) (core-case-clause (core-case-clause (pattern data-pattern) (body core-exp))) (core-method (%or (core-constant (pattern data-pattern) (body core-exp)) (core-method (pattern data-pattern) (body core-exp)) )) (core-lazy-binding (core-lazy-binding (name ,symbol?) (value core-exp))) (anf-exp (%or (anf-send (receiver anf-value) (message anf-value)) (anf-case (value anf-exp) (clauses (%list-of anf-case-clause))) (anf-lazy (bindings (%list-of anf-lazy-binding)) (body anf-exp)) (anf-tuple (elements (%list-of anf-value))) anf-value )) (anf-case-clause (anf-case-clause (pattern data-pattern) (body anf-exp))) (anf-lazy-binding (anf-lazy-binding (name ,symbol?) (value anf-exp))) (anf-value (%or (anf-lambda (formal ,symbol?) (body anf-exp)) (anf-ref (name ,symbol?)) (anf-lit (value #t)) )) (data-pattern (%or (pat-discard) (pat-binding (name ,symbol?)) (pat-tuple (elements (%list-of data-pattern))) (pat-lit (value #t)))) )) (define (anf-value? a) (check-language a 'anf-value a-normal-form-languages #f)) (define core->anf (let () (define (gentemp) (gensym 'anftmp)) (define (make-anf-let pattern value body) (make-node 'anf-case 'value value 'clauses (list (make-node 'anf-case-clause 'pattern pattern 'body body)))) (define (normalize-term exp) (normalize exp values)) (define (normalize-name exp k) (normalize exp (lambda (a) (if (anf-value? a) (k a) (let ((t (gentemp))) (make-anf-let (make-node 'pat-binding 'name t) a (k (make-node 'anf-ref 'name t)))))))) (define (normalize-name* exps k) (if (null? exps) (k '()) (normalize-name (car exps) (lambda (e) (normalize-name* (cdr exps) (lambda (es) (k (cons e es)))))))) (define (remake-constant-method constant constant-body) (make-node 'anf-case-clause 'pattern (node-get constant 'core-constant 'pattern) 'body constant-body)) (define (remake-normal-method method) (make-node 'anf-case-clause 'pattern (node-get method 'core-method 'pattern) 'body (normalize-term (node-get method 'core-method 'body)))) (define (normalize exp k) (node-match exp ((core-send receiver message) (normalize-name receiver (lambda (r) (normalize-name message (lambda (m) (k (make-node 'anf-send 'receiver r 'message m))))))) ((core-case value clauses) (normalize value (lambda (v) (k (make-node 'anf-case 'value v 'clauses (map (lambda (clause) (node-match clause ((core-case-clause pattern body) (make-node 'anf-case-clause 'pattern pattern 'body (normalize-term body))))) clauses)))))) ((core-lazy bindings body) (k (make-node 'anf-lazy 'bindings (map (lambda (binding) (node-match binding ((core-lazy-binding name value) (make-node 'anf-lazy-binding 'name name 'value (normalize-term value))))) bindings) 'body (normalize-term body)))) ((core-object methods) (receive (constants methods) (partition (lambda (n) (node-kind? n 'core-constant)) methods) (normalize-name* (map (node-getter 'core-constant 'body) constants) (lambda (constant-bodies) (let ((formal (gentemp)) (method-clauses (append (map remake-constant-method constants constant-bodies) (map remake-normal-method methods)))) (k (make-node 'anf-lambda 'formal formal 'body (make-node 'anf-case 'value (make-node 'anf-ref 'name formal) 'clauses method-clauses)))))))) ((core-sequence exps) (let loop ((exps exps)) (cond ((null? exps) (error "Need value in sequence")) ((null? (cdr exps)) (normalize (car exps) k)) (else (let ((exp (car exps))) (node-match exp ((core-let pattern value) (normalize value (lambda (v) (make-anf-let pattern v (loop (cdr exps)))))) (else (normalize-name exp (lambda (dont-care) (loop (cdr exps))))))))))) ((core-let pattern value) (error "core-let in invalid position" (node->list exp))) ((core-ref name) (k (make-node 'anf-ref 'name name))) ((core-tuple elements) (normalize-name* elements (lambda (es) (k (make-node 'anf-tuple 'elements es))))) ((core-lit value) (k (make-node 'anf-lit 'value value))))) normalize-term)) (define (stdin-results) (packrat-port-results "<stdin>" (current-input-port))) (define (debug-mode=? what) (and (memq what *debug-mode*) #t)) (define (node-type-error node type) (error "Language match error" (node->list node) type)) (define (sequence-phases datum phase-alist) (if (null? phase-alist) (begin (when (debug-mode=? 'sequence-phases) (display ";; Final phase result is ") (write (node->list datum)) (newline)) datum) (let* ((entry (car phase-alist)) (phase-name (car entry)) (phase-prelanguage (cadr entry)) (phase-body (caddr entry)) (phase-postlanguage (cadddr entry)) (rest (cdr phase-alist))) (when (debug-mode=? 'sequence-phases) (display ";;--------------------------------------------------") (newline) (display ";; Applying phase \"") (display phase-name) (display "\" to ") (write (node->list datum)) (newline)) (unless (check-language datum phase-prelanguage a-normal-form-languages #f) (error (string-append "Failed precondition for phase \"" phase-name "\"") (node->list datum))) (let ((new-datum (phase-body datum))) (unless (check-language new-datum phase-postlanguage a-normal-form-languages #f) (error (string-append "Failed postcondition for phase \"" phase-name "\"") (node->list new-datum))) (sequence-phases new-datum rest))))) (define (compiler-front-end-phases exp) (sequence-phases exp `(("expansion and a-normalization" core-exp ,core->anf anf-exp)))) (define (etng-repl) (let loop () (display ">>ETNG>> ") (flush-output) (let ((results (stdin-results))) (parse-etng results (lambda (ast next) (if (node? ast) (pretty-print (node->list (compiler-front-end-phases ast))) (begin (newline) (display ";; No parse result") (newline))) (when (and next (not (eq? next results))) (loop))) (lambda (error-description) (pretty-print error-description) (loop)))))) ;;; Local Variables: ;;; eval: (put 'node-match 'scheme-indent-function 1) ;;; End:
false
2ca8f9dde5af7dcaaf50cd3db1730ce11328f375
b0c1935baa1e3a0b29d1ff52a4676cda482d790e
/tests/t-closure.scm
51bd3f972b3849f1c8742ecbfd19129624012f2b
[ "MIT" ]
permissive
justinethier/husk-scheme
35ceb8f763a10fbf986340cb9b641cfb7c110509
1bf5880b2686731e0870e82eb60529a8dadfead1
refs/heads/master
2023-08-23T14:45:42.338605
2023-05-17T00:30:56
2023-05-17T00:30:56
687,620
239
28
MIT
2023-05-17T00:30:07
2010-05-26T17:02:56
Haskell
UTF-8
Scheme
false
false
446
scm
t-closure.scm
;; ;; husk-scheme ;; http://github.com/justinethier/husk-scheme ;; ;; Written by Justin Ethier ;; ;; Test cases for closures ;; From: http://stackoverflow.com/questions/36636/what-is-a-closure ;; (unit-test-start "closures") (define (make-counter) (let ((count 0)) (lambda () (set! count (+ count 1)) count))) (define x (make-counter)) (assert/equal (x) 1) (assert/equal (x) 2) (unit-test-handler-results)
false
5895ffe42dec8c48bbadc5eda43a8f63abb95215
212b2592f429ab706aa4a6f9de9323d0e4e47132
/3imp_sample/chap4.3-stack-model.scm
2f1ec72c3513419e1a500f1779f48d7dbd2cf64d
[ "MIT" ]
permissive
bobuhiro11/myscheme
36f9135001cbfe51a06e30d143cc8406c221a633
af91ab98125a604d574fe4467ace6bd7d340bae5
refs/heads/master
2021-12-21T22:39:45.182376
2021-12-15T00:26:26
2021-12-15T00:26:26
17,799,023
0
0
MIT
2021-12-15T00:26:27
2014-03-16T12:41:05
Scheme
UTF-8
Scheme
false
false
6,887
scm
chap4.3-stack-model.scm
;;; Chap 4.3 Stack Base Scheme Interpreter ;; (rec sum (lambda (x) (if (= x 0) 0 (+ x (sum (- x 1)))))) (define-syntax rec (syntax-rules () ((_ a b) (let ((a '())) (set! a b))))) ;; (recur count ((x '(a b c d e))) (if (null? x) 0 (+ (count (cdr x)) 1))) (define-syntax recur (syntax-rules () ((_ f ((v i) ...) e ...) ((rec f (lambda (v ...) e ...)) i ...)))) ;; (record (x y z) '(1 2 3) (+ x y z)) (define-syntax record (syntax-rules () ((_ (var ...) val exp ...) (apply (lambda (var ...) exp ...) val)))) ;; (record-case '(hello 1 2 3) ;; (hello (x y z) ;; (+ x y z)) ;; (bye (x y z) ;; (- x y z))) (define-syntax record-case (syntax-rules (else) ((_ exp1 (else exp3 ...)) (begin exp3 ...)) ((_ exp1 (key vars exp2 ...)) (if (eq? (car exp1) 'key) (record vars (cdr exp1) exp2 ...))) ((_ exp1 (key vars exp2 ...) c ...) (if (eq? (car exp1) 'key) (record vars (cdr exp1) exp2 ...) (record-case exp1 c ...))))) ;; (compile-lookup ;; 'c ;; '((x y z) (a b c) (u v)) ;; (lambda (n m) (cons n m)) ; n...rib, m...elt ;; ) ;; => (1. 2) (define compile-lookup (lambda (var e return) (recur nxtrib ((e e) (rib 0)) (recur nxtelt ((vars (car e)) (elt 0)) (cond ((null? vars) (nxtrib (cdr e) (+ rib 1))) ; next rib ((eq? (car vars) var) (return rib elt)) ; discover (else (nxtelt (cdr vars) (+ elt 1)))))))) ; next elt ;; (extend ;; '((a b c) (u v)) ;; '(x y z)) ;; ;; => ((x y z) (a b c) (u v)) (define extend (lambda (env rib) (cons rib env))) ;; (closure '(cons x y) '(1 2 3)) ;; => ((cons x y) (1 2 3)) (define closure (lambda (body e) (list body e))) (define continuation (lambda (s) (closure (list 'refer 0 0 (list 'nuate (save-stack s) '(return 0))) '()))) (define compile (lambda (x e next) (cond ((symbol? x) (compile-lookup x e (lambda (n m) (list 'refer n m next)))) ((pair? x) (record-case x (quote (obj) (list 'constant obj next)) (lambda (vars body) (list 'close (compile body (extend e vars) (list 'return (+ (length vars) 1))) next)) (if (test then else) (let ((thenc (compile then e next)) (elsec (compile else e next))) (compile test e (list 'test thenc elsec)))) (call/cc (x) (list 'frame next (list 'conti (list 'argument (compile x e '(apply)))))) (else (recur loop ((args (cdr x)) (c (compile (car x) e '(apply)))) (if (null? args) (list 'frame next c) (loop (cdr args) (compile (car args) e (list 'argument c)))))))) (else (list 'constant x next))))) (define *stack* (make-vector 100)) ;; (set! s (push 1 s)) (define push (lambda (x s) (vector-set! *stack* s x) (+ s 1))) ;; (index s 0) (define index (lambda (s i) (vector-ref *stack* (- (- s i) 1)))) ;; (index-set! s 0 99) (define index-set! (lambda (s i v) (vector-set! *stack* (- (- s i) 1) v))) (define find-link (lambda (n e) (if (= n 0) e (find-link (- n 1) (index e -1))))) (define save-stack (lambda (s) (let ((v (make-vector s))) (recur copy ((i 0)) (unless (= i s) (vector-set! v i (vector-ref *stack* i)) (copy (+ i 1)))) v))) (define restore-stack (lambda (v) (let ((s (vector-length v))) (recur copy ((i 0)) (unless (= i s) (vector-set! *stack* i (vector-ref v i)) (copy (+ i 1)))) s))) (define display-stack (lambda () (display "---bottom---\n") (map (lambda (x) (if (undefined? x) '() (begin (display x) (newline)))) (vector->list *stack*)) (display "--- top ----\n"))) (define VM (lambda (a x e s) ;(display-stack) ;(display x) (newline) (newline) (record-case x (halt () a) (refer (n m x) (VM (index (find-link n e) m) x e s)) (constant (obj x) (VM obj x e s)) (close (body x) (VM (closure body e) x e s)) (test (then else) (VM a (if a then else) e s)) (conti (x) (VM (continuation s) x e s)) (nuate (stack x) (VM a x e (restore-stack stack))) (frame (ret x) (VM a x e (push ret (push e s)))) (argument (x) (VM a x e (push a s))) (apply () (record (body link) a (VM a body s (push link s)))) (return (n) (let ((s (- s n))) (VM a (index s 0) (index s 1) (- s 2))))))) ;(display (compile '((lambda (x y) x) 1 2) ; '((x y z) (a b c) (u v)) ; '(halt))) (define evaluate (lambda (x) (VM '() (compile x '() '(halt)) 0 0))) (display (evaluate '(if #t 1 2) )) (newline) (display (evaluate '(quote (1 2 3)) )) (newline) (display (evaluate '((lambda (x y) y) 19 29) )) (newline) ;(display (compile ; '((lambda (x y) (x y)) ; (lambda (x) (if x 10 20)) ; #f) ; '() ; '(halt) ; )) ; (display (evaluate '((lambda (x y) (x y)) (lambda (x) (if x 10 20)) #f) )) (newline) (display (evaluate '(call/cc (lambda (k) (if (k #f) 10 20)))))
true
5630d5bfa0225be420318f53cfa4a08b42f1989a
a74932f6308722180c9b89c35fda4139333703b8
/edwin48/scsh/errors.scm
5ae40065788351976ede7063b3588f5c7c287b67
[]
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
790
scm
errors.scm
;;; -*- Mode: Scheme; scheme48-package: s48-errors -*- (define (error:bad-range-argument datum operator) (error "bad range argument" `(,datum) `(is out of range for ,operator))) (define (error:datum-out-of-range datum) (error "out of range" datum)) (define (error:file-operation filename verb noun reason operator operands) (error "file operation" `(,filename) `(unable to ,verb ,noun because ,reason))) (define (error:wrong-type-argument datum type operator) (error "wrong type argument" `(,operator) `(expects ,datum) `(to be type ,type))) (define (error:not-list datum operator) (error "not a list" `(,datum) `(,operator))) (define (error:not-weak-list datum operator) (error "not a weak list" `(,datum) `(,operator)))
false
599579a4ee1c046b865be87e6675d9e3902c8538
120324bbbf63c54de0b7f1ca48d5dcbbc5cfb193
/packages/slib/uri.scm
7a9f78a57fca71c22a089af4918ca0033e6cfb01
[ "MIT" ]
permissive
evilbinary/scheme-lib
a6d42c7c4f37e684c123bff574816544132cb957
690352c118748413f9730838b001a03be9a6f18e
refs/heads/master
2022-06-22T06:16:56.203827
2022-06-16T05:54:54
2022-06-16T05:54:54
76,329,726
609
71
MIT
2022-06-16T05:54:55
2016-12-13T06:27:36
Scheme
UTF-8
Scheme
false
false
15,099
scm
uri.scm
;;; "uri.scm" Construct and decode Uniform Resource Identifiers. -*-scheme-*- ; Copyright 1997, 1998, 2000, 2001 Aubrey Jaffer ; ;Permission to copy this software, to modify it, to redistribute it, ;to distribute modified versions, 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. I have made no warranty or representation that the operation of ;this software will be error-free, and I am under no obligation to ;provide any services, by way of maintenance, update, or otherwise. ; ;3. In conjunction with products arising from the use of this ;material, there shall be no use of my name in any advertising, ;promotional, or sales literature without prior written consent in ;each case. (require 'scanf) (require 'printf) (require 'coerce) (require 'string-case) (require 'string-search) (require 'common-list-functions) (require-if 'compiling 'directory) ; path->uri uses current-directory ;;@code{(require 'uri)} ;;@ftindex uri ;; ;;@noindent Implements @dfn{Uniform Resource Identifiers} (URI) as ;;described in RFC 2396. ;;@args ;;@args fragment ;;@args query fragment ;;@args path query fragment ;;@args authority path query fragment ;;@args scheme authority path query fragment ;; ;;Returns a Uniform Resource Identifier string from component arguments. (define (make-uri . args) (define nargs (length args)) (set! args (reverse args)) (let ((fragment (if (>= nargs 1) (car args) #f)) (query (if (>= nargs 2) (cadr args) #f)) (path (if (>= nargs 3) (caddr args) #f)) (authority (if (>= nargs 4) (cadddr args) #f)) (scheme (if (>= nargs 5) (list-ref args 4) #f))) (string-append (if scheme (sprintf #f "%s:" scheme) "") (cond ((string? authority) (sprintf #f "//%s" (uric:encode authority "$,;:@&=+"))) ((list? authority) (apply (lambda (userinfo host port) (cond ((and userinfo port) (sprintf #f "//%s@%s:%d" (uric:encode userinfo "$,;:&=+") host port)) (userinfo (sprintf #f "//%s@%s" (uric:encode userinfo "$,;:&=+") host)) (port (sprintf #f "//%s:%d" host port)) (else host))) authority)) (else (or authority ""))) (cond ((string? path) (uric:encode path "/$,;:@&=+")) ((null? path) "") ((list? path) (uri:make-path path)) (else (or path ""))) (if query (sprintf #f "?%s" (uric:encode query "?/$,;:@&=+")) "") (if fragment (sprintf #f "#%s" (uric:encode fragment "?/$,;:@&=+")) "")))) ;;@body ;;Returns a URI string combining the components of list @1. (define (uri:make-path path) (apply string-append (cons (uric:encode (car path) "$,;:@&=+") (map (lambda (pth) (string-append "/" (uric:encode pth "$,;:@&=+"))) (cdr path))))) ;;@body Returns a string which defines this location in the (HTML) file ;;as @1. The hypertext @samp{<A HREF="#@1">} will link to this point. ;; ;;@example ;;(html:anchor "(section 7)") ;;@result{} ;;"<A NAME=\"(section%207)\"></A>" ;;@end example (define (html:anchor name) (sprintf #f "<A NAME=\"%s\"></A>" (uric:encode name "#?/:@;="))) ;;@body Returns a string which links the @2 text to @1. ;; ;;@example ;;(html:link (make-uri "(section 7)") "section 7") ;;@result{} ;;"<A HREF=\"#(section%207)\">section 7</A>" ;;@end example (define (html:link uri highlighted) (sprintf #f "<A HREF=\"%s\">%s</A>" uri highlighted)) ;;@body Returns a string specifying the @dfn{base} @1 of a document, for ;;inclusion in the HEAD of the document (@pxref{HTML, head}). (define (html:base uri) (sprintf #f "<BASE HREF=\"%s\">" uri)) ;;@body Returns a string specifying the search @1 of a document, for ;;inclusion in the HEAD of the document (@pxref{HTML, head}). (define (html:isindex prompt) (sprintf #f "<ISINDEX PROMPT=\"%s\">" prompt)) (define (uri:scheme? str) (let ((lst (scanf-read-list "%[-+.a-zA-Z0-9] %s" str))) (and (list? lst) (eqv? 1 (length lst)) (char-alphabetic? (string-ref str 0))))) ;;@args uri-reference base-tree ;;@args uri-reference ;; ;;Returns a list of 5 elements corresponding to the parts ;;(@var{scheme} @var{authority} @var{path} @var{query} @var{fragment}) ;;of string @1. Elements corresponding to absent parts are #f. ;; ;;The @var{path} is a list of strings. If the first string is empty, ;;then the path is absolute; otherwise relative. The optional @2 is a ;;tree as returned by @0; and is used as the base address for relative ;;URIs. ;; ;;If the @var{authority} component is a ;;@dfn{Server-based Naming Authority}, then it is a list of the ;;@var{userinfo}, @var{host}, and @var{port} strings (or #f). For other ;;types of @var{authority} components the @var{authority} will be a ;;string. ;; ;;@example ;;(uri->tree "http://www.ics.uci.edu/pub/ietf/uri/#Related") ;;@result{} ;;(http "www.ics.uci.edu" ("" "pub" "ietf" "uri" "") #f "Related") ;;@end example (define (uri->tree uri-reference . base-tree) (define split (uri:split uri-reference)) (apply (lambda (b-scheme b-authority b-path b-query b-fragment) (apply (lambda (scheme authority path query fragment) (define uri-empty? (and (equal? "" path) (not scheme) (not authority) (not query))) (list (if (and scheme (uri:scheme? scheme)) (string-ci->symbol scheme) (cond ((not scheme) b-scheme) (else (slib:warn 'uri->tree 'bad 'scheme scheme) b-scheme))) (if authority (uri:decode-authority authority) b-authority) (if uri-empty? (or b-path '("")) (uri:decode-path (map uric:decode (uri:split-fields path #\/)) (and (not authority) (not scheme) b-path))) (if uri-empty? b-query query) (or (and fragment (uric:decode fragment)) (and uri-empty? b-fragment)))) split)) (if (or (car split) (null? base-tree)) '(#f #f #f #f #f) (car base-tree)))) (define (uri:decode-path path-list base-path) (cond ((and (equal? "" (car path-list)) (not (equal? '("") path-list))) path-list) (base-path (let* ((cpath0 (append (butlast base-path 1) path-list)) (cpath1 (let remove ((l cpath0) (result '())) (cond ((null? l) (reverse result)) ((not (equal? "." (car l))) (remove (cdr l) (cons (car l) result))) ((null? (cdr l)) (reverse (cons "" result))) (else (remove (cdr l) result))))) (cpath2 (let remove ((l cpath1) (result '())) (cond ((null? l) (reverse result)) ((not (equal? ".." (car l))) (remove (cdr l) (cons (car l) result))) ((or (null? result) (equal? "" (car result))) (slib:warn 'uri:decode-path cpath1) (append (reverse result) l)) ((null? (cdr l)) (reverse (cons "" (cdr result)))) (else (remove (cdr l) (cdr result))))))) cpath2)) (else path-list))) (define (uri:decode-authority authority) (define idx-at (string-index authority #\@)) (let* ((userinfo (and idx-at (uric:decode (substring authority 0 idx-at)))) (hostport (if idx-at (substring authority (+ 1 idx-at) (string-length authority)) authority)) (cdx (string-index hostport #\:)) (host (if cdx (substring hostport 0 cdx) hostport)) (port (and cdx (substring hostport (+ 1 cdx) (string-length hostport))))) (if (or userinfo port) (list userinfo host (or (string->number port) port)) host))) ;;@args txt chr ;;Returns a list of @1 split at each occurrence of @2. @2 does not ;;appear in the returned list of strings. (define uri:split-fields (let ((cr (integer->char #xd))) (lambda (txt chr) (define idx (string-index txt chr)) (if idx (cons (substring txt 0 (if (and (positive? idx) (char=? cr (string-ref txt (+ -1 idx)))) (+ -1 idx) idx)) (uri:split-fields (substring txt (+ 1 idx) (string-length txt)) chr)) (list txt))))) ;;@body Converts a @dfn{URI} encoded @1 to a query-alist. (define (uri:decode-query query-string) (set! query-string (string-subst query-string " " "" "+" " ")) (do ((lst '()) (edx (string-index query-string #\=) (string-index query-string #\=))) ((not edx) lst) (let* ((rxt (substring query-string (+ 1 edx) (string-length query-string))) (adx (string-index rxt #\&)) (urid (uric:decode (substring rxt 0 (or adx (string-length rxt))))) (name (string-ci->symbol (uric:decode (substring query-string 0 edx))))) (if (not (equal? "" urid)) (set! lst (cons (list name urid) lst)) ;; (set! lst (append lst (map (lambda (value) (list name value)) ;; (uri:split-fields urid #\newline)))) ) (set! query-string (if adx (substring rxt (+ 1 adx) (string-length rxt)) ""))))) (define (uri:split uri-reference) (define len (string-length uri-reference)) (define idx-sharp (string-index uri-reference #\#)) (let ((fragment (and idx-sharp (substring uri-reference (+ 1 idx-sharp) len))) (uri (if idx-sharp (and (not (zero? idx-sharp)) (substring uri-reference 0 idx-sharp)) uri-reference))) (if uri (let* ((len (string-length uri)) (idx-? (string-index uri #\?)) (query (and idx-? (substring uri (+ 1 idx-?) len))) (front (if idx-? (and (not (zero? idx-?)) (substring uri 0 idx-?)) uri))) (if front (let* ((len (string-length front)) (cdx (string-index front #\:)) (scheme (and cdx (substring front 0 cdx))) (path (if cdx (substring front (+ 1 cdx) len) front))) (cond ((eqv? 0 (substring? "//" path)) (set! len (string-length path)) (set! path (substring path 2 len)) (set! len (+ -2 len)) (let* ((idx-/ (string-index path #\/)) (authority (substring path 0 (or idx-/ len))) (path (if idx-/ (substring path idx-/ len) ""))) (list scheme authority path query fragment))) (else (list scheme #f path query fragment)))) (list #f #f "" query fragment))) (list #f #f "" #f fragment)))) ;;@ ;;@noindent @code{uric:} prefixes indicate procedures dealing with ;;URI-components. ;;@body Returns a copy of the string @1 in which all @dfn{unsafe} octets ;;(as defined in RFC 2396) have been @samp{%} @dfn{escaped}. ;;@code{uric:decode} decodes strings encoded by @0. (define (uric:encode uri-component allows) (set! uri-component (sprintf #f "%a" uri-component)) (apply string-append (map (lambda (chr) (if (or (char-alphabetic? chr) (char-numeric? chr) (string-index "-_.!~*'()" chr) (string-index allows chr)) (string chr) (let ((code (char->integer chr))) (sprintf #f "%%%02x" code)))) (string->list uri-component)))) ;;@body Returns a copy of the string @1 in which each @samp{%} escaped ;;characters in @1 is replaced with the character it encodes. This ;;routine is useful for showing URI contents on error pages. (define (uric:decode uri-component) (define len (string-length uri-component)) (define (sub uri) (cond ((string-index uri #\%) => (lambda (idx) (if (and (< (+ 2 idx) len) (string->number (substring uri (+ 1 idx) (+ 2 idx)) 16) (string->number (substring uri (+ 2 idx) (+ 3 idx)) 16)) (string-append (substring uri 0 idx) (printf (string (integer->char (string->number (substring uri (+ 1 idx) (+ 3 idx)) 16)))) (sub (substring uri (+ 3 idx) (string-length uri))))))) (else uri))) (sub uri-component)) ;;@body @1 is a path-list as returned by @code{uri:split-fields}. @0 ;;returns a list of items returned by @code{uri:decode-path}, coerced ;;to types @2. (define (uri:path->keys path-list ptypes) (and (not (null? path-list)) (not (equal? '("") path-list)) (let ((path (uri:decode-path (map uric:decode path-list) #f))) (and (= (length path) (length ptypes)) (map coerce path ptypes))))) ;;@subheading File-system Locators and Predicates ;;@body Returns a URI-string for @1 on the local host. (define (path->uri path) (require 'directory) (if (absolute-path? path) (sprintf #f "file:%s" path) (sprintf #f "file:%s/%s" (current-directory) path))) ;;@body Returns #t if @1 is an absolute-URI as indicated by a ;;syntactically valid (per RFC 2396) @dfn{scheme}; otherwise returns ;;#f. (define (absolute-uri? str) (let ((lst (scanf-read-list "%[-+.a-zA-Z0-9]:%s" str))) (and (list? lst) (eqv? 2 (length lst)) (char-alphabetic? (string-ref str 0))))) ;;@body Returns #t if @1 is a fully specified pathname (does not ;;depend on the current working directory); otherwise returns #f. (define (absolute-path? file-name) (and (string? file-name) (positive? (string-length file-name)) (memv (string-ref file-name 0) '(#\\ #\/)))) ;;@body Returns #t if changing directory to @1 would leave the current ;;directory unchanged; otherwise returns #f. (define (null-directory? str) (member str '("" "." "./" ".\\"))) ;;@body Returns #t if the string @1 contains characters used for ;;specifying glob patterns, namely @samp{*}, @samp{?}, or @samp{[}. (define (glob-pattern? str) (let loop ((idx (+ -1 (string-length str)))) (if (negative? idx) #f (case (string-ref str idx) ((#\* #\[ #\?) #t) (else (loop (+ -1 idx))))))) ;;@noindent ;;Before RFC 2396, the @dfn{File Transfer Protocol} (FTP) served a ;;similar purpose. ;;@body ;;Returns a list of the decoded FTP @1; or #f if indecipherable. FTP ;;@dfn{Uniform Resource Locator}, @dfn{ange-ftp}, and @dfn{getit} ;;formats are handled. The returned list has four elements which are ;;strings or #f: ;; ;;@enumerate 0 ;;@item ;;username ;;@item ;;password ;;@item ;;remote-site ;;@item ;;remote-directory ;;@end enumerate (define (parse-ftp-address uri) (let ((length? (lambda (len lst) (and (eqv? len (length lst)) lst)))) (cond ((not uri) #f) ((length? 1 (scanf-read-list " ftp://%s %s" uri)) => (lambda (host) (let ((login #f) (path #f) (dross #f)) (sscanf (car host) "%[^/]/%[^@]%s" login path dross) (and login (append (cond ((length? 2 (scanf-read-list "%[^@]@%[^@]%s" login)) => (lambda (userpass@hostport) (append (cond ((length? 2 (scanf-read-list "%[^:]:%[^@/]%s" (car userpass@hostport)))) (else (list (car userpass@hostport) #f))) (cdr userpass@hostport)))) (else (list "anonymous" #f login))) (list path)))))) (else (let ((user@site #f) (colon #f) (path #f) (dross #f)) (case (sscanf uri " %[^:]%[:]%[^@] %s" user@site colon path dross) ((2 3) (let ((user #f) (site #f)) (cond ((or (eqv? 2 (sscanf user@site "/%[^@/]@%[^@]%s" user site dross)) (eqv? 2 (sscanf user@site "%[^@/]@%[^@]%s" user site dross))) (list user #f site path)) ((eqv? 1 (sscanf user@site "@%[^@]%s" site dross)) (list #f #f site path)) (else (list #f #f user@site path))))) (else (let ((site (scanf-read-list " %[^@/] %s" uri))) (and (length? 1 site) (list #f #f (car site) #f))))))))))
false
d974b3143618534116ec4d1d5c591a61f01acad7
de21ee2b90a109c443485ed2e25f84daf4327af3
/exercise/section3/3.8.scm
bc32e3be9755a845440b4ed92df7eb5ef83a3963
[]
no_license
s-tajima/SICP
ab82518bdc0551bb4c99447ecd9551f8d3a2ea1d
9ceff8757269adab850d01f238225d871748d5dc
refs/heads/master
2020-12-18T08:56:31.032661
2016-11-10T11:37:52
2016-11-10T11:37:52
18,719,524
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,032
scm
3.8.scm
;= Question ============================================================================= ; ; 問題3.7 ; ; 1.1.3節で評価モデルを定義した時, 式の評価の第一歩はその部分式を評価することだといった. ; しかし部分式を評価する順(例えば左から右か右から左か) は規定しなかった. ; 代入を取り入れると, 手続きへの引数が評価される順は結果に違いを生じるかも知れない. ; 単純な手続きfを定義し, (+ (f 0) (f 1))が, ; +の引数を左から右へ評価すると0を返し, 右から左へ評価すると1を返すようにせよ. ; ;= Prepared ============================================================================= ;= Answer =============================================================================== (define f (let ((y 1)) (lambda (x) (begin (set! y (* y x)) y)))) ;(print (+ (f 0) (f 1))) (print (+ (f 1) (f 0))) ;= Test =================================================================================
false
5a3d3d87c66fc16836104d32b745b43d94a90997
b8034221175e02a02307ef3efef129badecda527
/tests/tut2.scm
01e5a3a4493dfb4abe02a8af7ecf394403e51f6b
[]
no_license
nobody246/xlsxWriterScm
ded2410db122dfbe8bbb5e9059239704ee9a5b32
d02ed10c3e8c514cc1b6a9eaf793a2cde34c4c47
refs/heads/master
2022-04-27T23:29:45.258892
2022-04-15T22:04:02
2022-04-15T22:04:02
153,357,109
0
1
null
null
null
null
UTF-8
Scheme
false
false
1,031
scm
tut2.scm
(use xlsxwriterscm) (define expenses '((Rent . 1000) (Gas . 100) (Food . 300) (Gym . 50))) (define row 0) (define col 0) (create-workbook "tut2.xlsx") (add-worksheet "") (init-formats 2) (create-format) (set-bold) (create-format) (set-cell-num-format "$#,##0") (set-format-index 0) (worksheet-write-string "Item") (set-col (add1 col)) (worksheet-write-string "Cost") (set! row (add1 row)) (set-format-index 1) (define (write-expenses e) (set-pos row col) (if (not (null? e)) (let* ((curr-row (car e)) (curr-str (symbol->string (car curr-row))) (curr-num (cdr curr-row))) (worksheet-write-string curr-str) (set-col (add1 col)) (worksheet-write-number curr-num) (set! row (add1 row)) (write-expenses (cdr e))) (begin (worksheet-write-string "TOTAL") (set-col (add1 col)) (worksheet-write-formula "=SUM(B1:B4)")))) (write-expenses expenses) (close-workbook) (exit)
false
37fcfaf9a39f9dd0ec38f7eef8dc11d7122c0e35
43612e5ed60c14068da312fd9d7081c1b2b7220d
/unit-tests/IFT3065/1/etape1-let4.scm
2c1cfdae0683afee1700458e11c317a84f44d732
[ "BSD-3-Clause" ]
permissive
bsaleil/lc
b1794065183b8f5fca018d3ece2dffabda6dd9a8
ee7867fd2bdbbe88924300e10b14ea717ee6434b
refs/heads/master
2021-03-19T09:44:18.905063
2019-05-11T01:36:38
2019-05-11T01:36:38
41,703,251
27
1
BSD-3-Clause
2018-08-29T19:13:33
2015-08-31T22:13:05
Scheme
UTF-8
Scheme
false
false
124
scm
etape1-let4.scm
(let ((x 11)) (let ((x (+ x x))) (let ((y (let ((x 2200)) (+ x x)))) (println (+ x y))))) ;4422
false
ba10e24a980d2530da1a63b7a470c19119039675
4890b89d4e190ad152c26f5f1565d1157c0972e7
/Compiler/convert-complex-datum.ss
0f9d3e39318dc1087a9d1e4b78706c18f0cfdbed
[]
no_license
haskellstudio/p-423-Compiler
e2791bae1b966cd1650575e39eef10b4c7205ca1
36be558647ecd5786b02df42865d0ffa2a57fa2f
refs/heads/master
2021-01-25T13:11:49.825526
2017-11-09T03:48:00
2017-11-09T03:48:00
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,718
ss
convert-complex-datum.ss
(library (Compiler convert-complex-datum) (export convert-complex-datum) (import (chezscheme) (Framework match) (Framework helpers)) (define-who convert-complex-datum (define primitives '(+ - * <= < = >= > boolean? car cdr cons eq? fixnum? make-vector null? pair? procedure? set-car! set-cdr! vector? vector-length vector-ref vector-set! void)) (define constant? (lambda (x) (or (memq x '(#t #f ())) (and (and (integer? x) (exact? x)) (or (fixnum-range? x) (error who "integer ~s is out of fixnum range" x)))))) (define Program (lambda (x) (define let-datum '()) (define Set-Vector (lambda (x count tmp) (if (null? x) '() (cons `(vector-set! ,tmp (quote ,count) ,(car x)) (Set-Vector (cdr x) (add1 count) tmp))))) (define Process-Datum (lambda (x) (match x [#(,[Process-Datum -> x*] ...) (let* ([tmp (unique-name 'tmp)] [set-vects (Set-Vector x* 0 tmp)]) `(let ([,tmp (make-vector (quote ,(length x*)))]) ,(make-begin `(,set-vects ... ,tmp))))] [(,[Process-Datum -> x] . ,[Process-Datum -> y]) `(cons ,x ,y)] [,x (guard (constant? x)) `(quote ,x)] [,x (error who "invalid Datum ~s" x)]))) (define Expr (lambda (x) (match x [,uvar (guard (uvar? uvar)) uvar] [(quote ,x) (if (constant? x) `(quote ,x) (let* ([nuvar (unique-name 't)] [set-datum (Process-Datum x)]) (set! let-datum (cons `(,nuvar ,set-datum) let-datum)) nuvar))] [(if ,[test] ,[conseq] ,[altern]) `(if ,test ,conseq ,altern)] [(begin ,[eff*] ... ,[eff]) `(begin ,eff* ... ,eff)] [(lambda (,uvar* ...) ,[exp]) `(lambda (,uvar* ...) ,exp)] [(let ([,uvar* ,[exp*]] ...) ,[exp]) `(let ([,uvar* ,exp*] ...) ,exp)] [(letrec ([,uvar* ,[exp*]] ...) ,[exp]) `(letrec ([,uvar* ,exp*] ...) ,exp)] [(set! ,uvar ,[exp]) `(set! ,uvar ,exp)] [(,prim ,[x*] ...) (guard (memq prim primitives)) `(,prim ,x* ...)] [(,[rator] ,[rand*] ...) `(,rator ,rand* ...)] [,x (error who "invalid Expr ~s" x)]))) (let ([exp (Expr x)]) (if (null? let-datum) exp `(let ,let-datum ,exp))))) (lambda (x) (Program x))) )
false
28281ddcc976c63fd83f9737ed302f18f634597d
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
/lib/sagittarius/comparators.scm
07ae1149eba42ee17f362adf28663cfe92eadd21
[ "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
4,573
scm
comparators.scm
;;; -*- mode:scheme; coding:utf-8 -*- ;;; ;;; comparators.scm: Comparators ;;; ;;; Copyright (c) 2014 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. ;;; (library (sagittarius comparators) (export <comparator> comparator? make-comparator comparator-comparison-procedure? comparator-hash-function? comparator-type-test-procedure comparator-equality-predicate comparator-comparison-procedure comparator-hash-function comparator-test-type comparator-check-type comparator-equal? comparator-compare comparator-hash ;; built-in comparatorss eq-comparator eqv-comparator equal-comparator string-comparator ;; others make-comparison< make-comparison> make-comparison<= make-comparison>= make-comparison=/< make-comparison=/> ;; non SRFI procedure object-type ;; hook method disjoint-order ) (import (rnrs) (sagittarius) (core inline) (clos user)) (define (make-comparator type-test equality comparison hash :optional (name #f)) ;; TODO parameter check (let ((eq (if (eq? equality #t) (lambda (x y) (eqv? (comparison x y) 0)) equality))) (%make-comparator type-test eq comparison hash name))) (define eq-comparator (%eq-comparator)) (define eqv-comparator (%eqv-comparator)) (define equal-comparator (%equal-comparator)) (define string-comparator (%string-comparator)) ;; This is a bit tricky. ;; we want the order rather static value. (Well as long as we use ;; method then it won't be totally static though). However the ;; reference implementation way is rather dynamic so that the ;; evaluation order matters and we don't want it. maybe we should ;; provide more proper procedure such as taking 2 argument, like ;; comparator and index order. But for now. ;; ;; Default value is taken from reference implementation (define-generic disjoint-order) (define-method disjoint-order (obj) 32767) ;; compare and equal-hash are extensible. (define (object-type obj) (cond ((null? obj) 0) ((pair? obj) 1) ((boolean? obj) 2) ((char? obj) 3) ((string? obj) 4) ((symbol? obj) 5) ((number? obj) 6) ((vector? obj) 7) ((bytevector? obj) 8) (else (disjoint-order obj)))) (define-syntax define-comparison (syntax-rules () ((_ (name . formals) expr) (begin (define (name . formals) expr) (define-inliner name (sagittarius comparators) ((_ . formals) expr)))))) (define-comparison (make-comparison< <) (lambda (a b) (cond ((< a b) -1) ((< b a) 1) (else 0)))) (define-comparison (make-comparison> >) (lambda (a b) (cond ((> a b) -1) ((> b a) 1) (else 0)))) (define-comparison (make-comparison<= <=) (lambda (a b) (if (<= a b) (if (<= b a) 0 -1) 1))) (define-comparison (make-comparison>= >=) (lambda (a b) (if (>= a b) (if (>= b a) 0 1) -1))) (define-comparison (make-comparison=/< = <) (lambda (a b) (cond ((= a b) 0) ((< a b) -1) (else 1)))) (define-comparison (make-comparison=/> = >) (lambda (a b) (cond ((= a b) 0) ((> b a) 1) (else -1)))) )
true
7f8ef091b842b15bffb60b5aaeadd9e797662575
8c44b6c3cc638a03f1ae4f1c3338396e6c777364
/chicken-egg/bxml/bxml.scm
48d229711c37f311d752db40f3cc69ad96164faa
[]
no_license
kristianlm/chicken-apk
abad750ac24f2d51a9437fcb98a98fc2c9874a79
1bd08038e9b6fd8fca8346314efba8163722a6ff
refs/heads/master
2020-09-11T01:08:21.611491
2019-11-15T09:24:16
2019-11-15T11:29:09
221,889,587
0
0
null
null
null
null
UTF-8
Scheme
false
false
18,173
scm
bxml.scm
;;; android binary xml parsing ;;; ;;; parsing an undocumented binary format is non-trivial, so this is ;;; done in two stages: blob -> ibax -> sxml ;;; ;;; think of blob => machine code ;;; ibax => assembly (intermediate binary android xml) ;;; sxml => some programming language ;;; ;;; ibax typically looks like this: ;;; ;;; ((string-pool utf16 ("label" "icon" "name" "debuggable" "minSdkVersion" "…")) ;;; (resource-map (16844147 16844146 16844076)) ;; don't know what this is ;;; (<ns> (str 17) (str 22)) ;; prefix url ;;; (<element> (str #f) (str 24) (((str 5) 1) ((str 11) 28))) ;; ns tag (attributes) ;;; (<element> (str #f) (str 30)) ;; always of type (str x) ;;; (</element> (str #f) (str 30)) ;;; (</element> (str #f) (str 24)) ;;; (</ns> (str 17) (str 22))) ;;; ;;; where (str n) points to the nth element in the string-pool. we ;;; assume string-pool declarations come before references to them ;;; (seems to be the case in the binary output I've seen). ;;; ;;; sxml typically looks like this: ;;; ;;; (@ns (android "http://schemas.android.com/apk/res/android") ;;; (manifest ;;; (@ (android versionCode 1) ;;; (android versionName "1.0") ;;; (android compileSdkVersion 28) ;;; (android compileSdkVersionCodename "9") ;;; (package "org.call_cc.template.sotest") ;;; (platformBuildVersionCode 28) ;;; (platformBuildVersionName 9)) ;;; (uses-sdk (@ (minSdkVersion 21) (targetSdkVersion 28))) ;;; (application ;;; (@ (label (ref 2131099648)) ;;; (icon (ref 2131034112)) ;;; (debuggable #t) ;;; (allowBackup #t) ;;; (supportsRtl #t) ;;; (roundIcon (ref 2131034113))) ;;; (activity ;;; (@ (android name "org.call_cc.template.sotest.MainActivity")) ;;; (intent-filter ;;; (action (@ (android name "android.intent.action.MAIN"))) ;;; (category (@ (android name "android.intent.category.LAUNCHER")))))))) (import (only chicken.string conc) (only chicken.io read-string) (only matchable match match-lambda) (only srfi-1 unfold filter)) ;; OBS: we need buffer.scm and friends (import (only (chicken pretty-print) pp)) (begin (define type/null #x0000) (define type/string-pool #x0001) (define type/first-chunk #x0100) (define type/start-namespace #x0100) (define type/end-namespace #x0101) (define type/start-element #x0102) (define type/end-element #x0103) (define type/cdata #x0104) (define type/last-chunk #x017f) (define type/resource-map #x0180) (define att/reference #x01) (define att/string #x03) (define att/dec #x10) ;; number as decimal string (define att/hex #x11) ;; number as hex string (define att/bool #x12) ) (define (decode-value value type) (cond ((= type att/string) `(str ,value)) ((= type att/dec) value) ((= type att/hex) `(hex ,value)) ((= type att/reference) `(ref ,value)) ((= type att/bool) (if (= value #xffffffff) #t #f)) (else `(¿ type value)))) ;; I'm tierd of seeing (str 4294967295) (define (str index) `(str ,(if (= index #xffffffff) #f index))) ;; bxml is a string representation of android's binary xml (define (bxml->ibax bxml) (define p (make-seekable-port bxml)) (parameterize ((current-input-port (p #:port))) (define (seek byte-offset) (p byte-offset)) ;; ==================== /io ==================== (seek 0) (expect #x00080003 (read-uint32) "bad header: ") (define len (read-uint32)) (prn "len " len) (let loop ((tree '())) (define type (read-uint16)) (prn "type " type) (cond ((eof-object? type) (prn "well done everyone") (reverse tree)) ((= type type/string-pool) (loop (cons (parse-string-pool (lambda () (p #:pos)) seek) tree))) ((= type type/resource-map) (let () (expect 8 (read-uint16) "header size ≠ 8") (define size (read-uint32)) (define len (quotient (- size 8) 4)) ;; what is going on? (prn "resource size " size ", len " len) (define mapping (unfold (lambda (x) (>= x len)) (lambda (x) (read-uint32)) add1 0)) (loop (cons `(resource-map ,mapping) tree)))) ((= type type/start-namespace) (let () (expect #x10 (read-uint16) " expecting ns header #x10") (expect #x18 (read-uint32) " expecting chunk header 24") (define line (read-uint32)) (prn " line# " line) (define comment (read-uint32)) (prn " comment " comment) (define prefix (read-uint32)) (prn " prefix «" prefix "»") (define uri (read-uint32)) (prn " uri «" uri "»") (loop (cons `(<ns> ,(str prefix) ,(str uri)) tree)))) ((= type type/end-namespace) (let () (expect #x10 (read-uint16) "/namespace header ≠ #x10") (expect #x18 (read-uint32) "/namespace header chunk ≠ #x18") (define line (read-uint32)) (define comment (read-uint32)) (define prefix (read-uint32)) (define uri (read-uint32)) (loop (cons `(</ns> ,(str prefix) ,(str uri)) tree)))) ((= type type/start-element) (let () (expect #x10 (read-uint16) " element header size ≠ #x10") (define chunk-size (read-uint32)) (prn " chunk-size " chunk-size) (define line (read-uint32)) (prn " line# " line) (define comment (read-uint32)) (prn " comment " comment) (define ns (read-uint32)) (prn " ns: " ns) (define tag (read-uint32)) (prn " tag: " tag) (expect #x14 (read-uint16) "ns-name sttribute start ≠ #x14") (expect #x14 (read-uint16) "ns-name attribute size ≠ #x14") (define att-count (read-uint16)) (prn " att-count " att-count) (define id-index (read-uint16)) (prn " id-index: " id-index) (define class-index (read-uint16)) (prn " class-index: " class-index) (define style-index (read-uint16)) (prn " style-index: " style-index) (define element `(<element> ,(str ns) ,(str tag) (@ ,@(unfold (lambda (x) (>= x att-count)) (lambda (i) (prn " ===== " i) (define att-ns (read-uint32)) (prn " att-ns " att-ns) (define att-name (read-uint32)) (prn " att-name " att-name) (define att-raw-value (read-uint32)) (prn " att-raw " att-raw-value) (expect #x08 (read-uint16) "attribute value size ≠ #x08") (expect 0 (read-byte) "res0 ≠ 0") (define att-type (read-byte)) (prn " att-type " att-type) (define att-value (decode-value (read-uint32) att-type)) (prn " att value" att-value) `(,(str att-ns) ,(str att-name) ,att-value)) add1 0)))) (loop (cons element tree)))) ((= type type/end-element) (let () (expect #x10 (read-uint16) " element header size ≠ #x10") (expect #x18 (read-uint32) " header chunk ≠ #x18") (define line (read-uint32)) (prn " line# " line) (define comment (read-uint32)) (prn " comment " comment) (define ns (read-uint32)) (prn " ns: " ns) (define tag (read-uint32)) (prn " tag: " tag) (loop (cons `(</element> ,(str ns) ,(str tag)) tree)))) (else (prn " error; don't know how to handle type " type) (pp tree)))))) (define (write-ibax ibax) (write-uint32 #x00080003) ;; header (define len (write-uint32 0)) (let loop ((ibax ibax)) (if (pair? ibax) (match (car ibax) (('string-pool 'utf8 (strings ...)) (error "utf8 unparsing not implemented")) (('string-pool 'utf16 (strings ...)) (write-uint16 type/string-pool) ;; string-pool type (unparse-string-pool strings) (loop (cdr ibax))) (('resource-map (mapping ...)) (write-uint16 type/resource-map) (write-uint16 #x08) ;; header size (write-uint32 (+ 8 (* 4 (length mapping)))) ;; mystery counting technique (for-each write-uint32 mapping) (loop (cdr ibax))) (('<ns> ('str prefix) ('str url)) (let () (write-uint16 type/start-namespace) (write-uint16 #x10) ;; header element size (define here (current-buffer-pos)) (define chunk-size (write-uint32 0)) ;; fixed later (write-uint32 0) ;; line (write-uint32 #xffffffff) ;; comment (write-uint32 (or prefix #xffffffff)) (write-uint32 (or url #xffffffff)) (chunk-size (+ 4 (- (current-buffer-pos) here))) (loop (cdr ibax)))) (('</ns> ('str prefix) ('str url)) (let () (write-uint16 type/end-namespace) (write-uint16 #x10) ;; header element size (define here (current-buffer-pos)) (define chunk-size (write-uint32 0)) ;; fixed later (write-uint32 0) ;; line (write-uint32 #xffffffff) ;; comment (write-uint32 (or prefix #xffffffff)) (write-uint32 (or url #xffffffff)) (chunk-size (+ 4 (- (current-buffer-pos) here))) (loop (cdr ibax)))) (('<element> ('str ns) ('str tag) ('@ attributes ...)) (let () (write-uint16 type/start-element) (write-uint16 #x10) ;; element header size (define here (current-buffer-pos)) (define chunk-size (write-uint32 #x00)) (write-uint32 #xffffffff) ;; line (write-uint32 #xffffffff) ;; comment (write-uint32 (or ns #xffffffff)) ;; element ns (write-uint32 (or tag #xffffffff)) ;; tag (write-uint16 #x14) ;; start? (write-uint16 #x14) ;; stop? (write-uint16 (length attributes)) ;; att-count (write-uint16 0) ;; id-index (write-uint16 0) ;; class-index (write-uint16 0) ;; style-index (for-each (match-lambda ( (('str ns) ('str key) val) (receive (val type) (match val (#t (values #xffffffff att/bool)) (#f (values #x00000000 att/bool)) (('str val) (values val att/string)) (('ref val) (values val att/reference)) ((? number? val) (values val att/dec)) (else (error "unknown attribute value type " val))) (write-uint32 (or ns #xffffffff)) ;; attribute ns (write-uint32 key) ;; name ;; guesswork of the week: (write-uint32 (if (eq? type att/string) val #xffffffff)) ;; raw-value (write-uint16 #x08) ;; value size (write-uint8 #x00) ;; res0 (write-uint8 type) ;; type (write-uint32 val) ;; value )) (else (error "no matching patt" else))) attributes) (chunk-size (+ 4 (- (current-buffer-pos) here))) (loop (cdr ibax)))) (('</element> ('str ns) ('str tag)) (let () (write-uint16 type/end-element) (write-uint16 #x10) ;; element header size (define here (current-buffer-pos)) (define chunk-size (write-uint32 #x00)) (write-uint32 #xffffffff) ;; line (write-uint32 #xffffffff) ;; comment (write-uint32 (or ns #xffffffff)) ;; ns (write-uint32 (or tag #xffffffff)) ;; tag (chunk-size (+ 4 (- (current-buffer-pos) here))) (loop (cdr ibax)))) ((')) (else (error "unknown: " else) (loop (cdr ibax)))))) (len (current-buffer-pos))) (define (ibax->bxml ibax) (wotb (lambda () (write-ibax ibax)))) ;; turn ibax into nested sxml (define (ibax->sxml ibax) (let loop ((ibax ibax) (sp #f) (rm #f) (ns '()) ;; alist ((prefix "http://..") ...) (tree '(()))) (define (push element) (cons (reverse element) tree)) (define (pop) (cons (cons (reverse (car tree)) (cadr tree)) (cddr tree))) (define (decode value) (cond ((boolean? value) value) ((number? value) value) (else (match value (('str x) (if (eq? x #f) #f (list-ref sp x))) (('hex x) x) ;; ok to loose this was stored as hex? (('ref x) value) ;; don't know how to resolve refs to resources.arsc (else (error "unknown value" value)))))) (define (ns-find uri) ;; uri is string (cond ((assoc uri ns) => cadr) (else (error "namespace not found" uri ns)))) (if (pair? ibax) (match (car ibax) (('string-pool encoding strings) (loop (cdr ibax) strings rm ns tree)) (('resource-map rm) (loop (cdr ibax) sp rm ns tree)) (('<ns> prefix uri) (loop (cdr ibax) sp rm (cons `(,(decode uri) ,(string->symbol (decode prefix))) ns) (push `(@ns (,(string->symbol (decode prefix)) ,(decode uri))) ))) (('</ns> prefix uri) (loop (cdr ibax) sp rm (filter (match-lambda ((pfx uri*) (equal? uri uri*)) (else (error "invalid namespace entry" else))) ns) (pop))) (('<element> element-ns tag ('@ attributes ...)) (loop (cdr ibax) sp rm ns (push `(,(string->symbol (decode tag)) (@ ,@(map (match-lambda ((nsuri an av) (let ((uri (decode nsuri))) (if uri (list (ns-find uri) (string->symbol (decode an)) (decode av)) (list (string->symbol (decode an)) (decode av)))))) attributes)))))) (('</element> element-ns tag) (loop (cdr ibax) sp rm ns (pop))) (else (prn " error; don't know how to handle ibax" (car ibax)) (pp tree))) ;; final result: (caar tree)))) (define (sxml->ibax sxml) (define sp '()) (define (str! str) ;; append to string pool (unless (string? str) (error "can not add non-string to sp" str)) (let ((index (length sp))) (set! sp (cons str sp)) `(str ,index))) (define ibax '()) (define (ins! ibax1) (set! ibax (cons ibax1 ibax))) (let loop ((sxmls (list sxml)) (ns '())) ;; alist ((prefix (str %uri)) ...) (not ordered like above) (if (pair? sxmls) (match (car sxmls) (('@ns (prefix uri) rest ...) (let ((prefix* (str! (symbol->string prefix))) (uri* (str! uri))) (ins! `(<ns> ,prefix* ,uri*)) (loop rest (cons `(,prefix ,uri*) ns)) (ins! `(</ns> ,prefix* ,uri*)) (loop (cdr sxmls) ns))) ;; typical attributes: ( (android label "hello" ) (package "com.example") ) ((element ('@ attributes ...) rest ...) (let () ;; add strings to sp, turn everything to uint32 (define (encode x) (cond ((string? x) (str! x)) ((symbol? x) (str! (symbol->string x))) (else x))) (define (ns-find pfx) ;; pfx is prefix symbol (cadr (assoc pfx ns))) (define atts (map (match-lambda ((ans key val) ;; attribute ns `(,(ns-find ans) ,(encode key) ,(encode val))) ((key val) ;; no attribute namespace `((str #f) ,(encode key) ,(encode val))) (else (error "invalid attibute pattern" else))) attributes)) (set! element (str! (symbol->string element))) (ins! `(<element> (str #f) ,element (@ ,@atts))) (loop rest ns) (ins! `(</element> (str #f) ,element)) (loop (cdr sxmls) ns))) ((element rest ...) (error "missing (@ attributes ...) in element" (list element rest))) (else (error "internal sxml-ibax error: no match" sxmls))) `((string-pool utf16 ,(reverse sp)) (resource-map ()) ,@(reverse ibax))))) (define sxml->bxml (o ibax->bxml sxml->ibax)) (define bxml->sxml (o ibax->sxml bxml->ibax))
false
4a80e06ca9221faa575638a2a102cc589202f2ba
b9eb119317d72a6742dce6db5be8c1f78c7275ad
/racket/web/flickr/lazy/update-nikkor-tags.ss
7d565b30f15712474ee527f1f54691cb06529d57
[]
no_license
offby1/doodles
be811b1004b262f69365d645a9ae837d87d7f707
316c4a0dedb8e4fde2da351a8de98a5725367901
refs/heads/master
2023-02-21T05:07:52.295903
2022-05-15T18:08:58
2022-05-15T18:08:58
512,608
2
1
null
2023-02-14T22:19:40
2010-02-11T04:24:52
Scheme
UTF-8
Scheme
false
false
5,233
ss
update-nikkor-tags.ss
#! /bin/sh #| Hey Emacs, this is -*-scheme-*- code! #$Id$ exec mzscheme -M errortrace --no-init-file --mute-banner --version --require "$0" |# (module update-nikkor-tags (lib "mz-without-promises.ss" "lazy") (require (lib "file.ss") (lib "cmdline.ss") (planet "xmlrpc.ss" ("schematics" "xmlrpc.plt" )) (only (lib "pretty.ss") pretty-display pretty-print) (lib "force.ss" "lazy") (only (planet "sxml.ss" ("lizorkin" "sxml.plt")) sxpath) (only (lib "13.ss" "srfi") string-tokenize ) (only (lib "14.ss" "srfi") char-set char-set-complement ) (lib "sendurl.ss" "net") "../flickr.ss" "lazy-photo-stream.ss") ;; for each of my flickr photos ;; if it was taken with my D200 ;; find the focal length and aperture ;; find a tag that describes that lens ;; add that tag to the picture (define (lens-data->string min-focal-length max-focal-length min-aperture max-aperture) ;; "30-70mmf/2.8-3.5", e.g. (format "~a~ammf/~a~a" min-focal-length (if (< min-focal-length max-focal-length ) (format "-~a" max-focal-length) "") (exact->inexact min-aperture) (if (< min-aperture max-aperture) (format "-~a" (exact->inexact max-aperture)) ""))) (file-stream-buffer-mode (current-output-port) 'line) (file-stream-buffer-mode (current-error-port) 'line) ;;(*verbose* #t) (define *the-auth-frob* (car ((sxpath '(frob *text*)) (flickr.auth.getFrob)))) (printf "Here dat frob, boss: ~s~%" *the-auth-frob*) (define *the-token* (get-preference 'flickr-token)) (when (not *the-token*) (let again () (with-handlers ([exn:xmlrpc:fault? (lambda (e) (define *login-url* (get-login-url *the-auth-frob* "write")) (printf "Handling ~s~%" e) (printf "Your web browser should open; tell it that it's OK to let this app mess with flickr!~%") (sleep 2) (send-url *login-url* #f) (sleep 10) (again))]) (set! *the-token* (car ((sxpath '(auth token *text*)) (flickr.auth.getToken 'frob *the-auth-frob*))))))) (printf "Here dat token, boss: ~s~%" *the-token*) (put-preferences (list 'flickr-token) (list *the-token*)) (fprintf (current-error-port) "Check-token says ~a~%" (flickr.auth.checkToken 'auth_token *the-token*)) (define *dry-run* (make-parameter #f)) (command-line "update-nikkor-tags" (current-command-line-arguments) (once-each (("-d" "--dry-run") "Just report what tags we'd add, instead of actually adding them" (*dry-run* #t)) ) ) (let loop ([i 0] [photo-stream (! (photo-stream *the-token*))]) (when (not (null? photo-stream)) (let ((p (! (car photo-stream)))) (let ((id (car ((sxpath '(@ id *text*)) p))) (title (car ((sxpath '(@ title *text*)) p)))) (printf "~s (~a) :" title id) (let ((exif (flickr.photos.getExif 'auth_token *the-token* 'photo_id id))) (let ((model-name ((sxpath '(photo (exif (@ (equal? (label "Model")))) raw *text*)) exif))) (let ((lens-data ((sxpath '(photo (exif (@ (equal? (label "Lens Min/Max Focal Length, Min/Max Aperture")))) raw *text*)) exif)) ) (when (not (null? lens-data)) (let* ((parsed-exact-numbers (map string->number (string-tokenize (car lens-data) (char-set-complement (char-set #\, #\newline)))))) ;; sometimes the four numbers come back as all 0 ;; ... no idea why (when (not (member 0 parsed-exact-numbers)) (let ((tag (apply lens-data->string parsed-exact-numbers))) ;; I don't know why, but flickr.photos.addTags ;; raises a -1 _when it succeeds_. So I ;; have to ignore that here. (Actually it's ;; ssax that's raising -1. How annoying) (with-handlers ([integer? (lambda (e) (fprintf (current-error-port) "Ignoring integer ~s~%" e))]) (when (not (*dry-run*)) (flickr.photos.addTags 'auth_token *the-token* 'photo_id id 'tags tag))) (printf " => ~s" tag))) ))) (printf "~%") )))) (loop (add1 i) (! (cdr photo-stream))))))
false
ea7d7c721f3e7dc7910781bbd207acf96171d84d
7cc8db8c11bf2401181f8803dab125d9343f5a41
/source/scheme/sph/sp/vectorise.scm
790fc3ba657151e308bd016d7b4bdf1e61d90ac5
[]
no_license
sph-mn/sph-sp-guile
9735fcfca7c29657536dc414f2af8159ba26bbc1
9ae56663332f4ec43b5ba025debb45b33b9fa4dd
refs/heads/master
2021-07-06T05:10:20.270511
2019-04-27T20:28:13
2019-04-27T20:28:13
150,976,986
1
0
null
null
null
null
UTF-8
Scheme
false
false
6,686
scm
vectorise.scm
(library (sph sp vectorise) (export sp-vectorise) (import (rnrs sorting) (sph) (sph list) (sph math) (sph sp) (sph vector) (only (guile) floor inexact->exact display) (only (srfi srfi-1) drop split-at)) ; todo: needs to be adjusted for the new version of sp-fft (define sph-sp-vectorise-description "experimental. convert a time/magnitude samples array to sines and noise parameters that can be used to approximately recreate the sound. uses a multiresolution fast fourier transform based analysis that balances time and frequency resolution based on amount of change and other weights") (define (sp-fft-bins-magnitudes a) (vector-map (l (b) (/ (magnitude b) (vector-length a))) a)) (define (sp-fft-drop-dc a) (list->vector (drop (vector->list a) 1))) (define* (sp-fft-threshold a #:optional (max-factor 1.0e-4)) "#(complex ...) real -> #(complex ...) remove all values with magnitudes smaller than (max / max-divisor). this is mainly to remove non-useful rounding error phase values that would lead to large angles" (let* ( (a-list (vector->list a)) (magnitudes (map magnitude a-list)) (threshold (* (apply max magnitudes) max-factor))) (apply vector (map (l (a b) (if (> threshold b) 0 a)) a-list magnitudes)))) (define (sp-frames-count data-size duration overlap-factor) "calculate how many frames with overlap can be taken from data-size" (- (/ data-size (* duration overlap-factor)) (- (/ 1 overlap-factor) 1))) (define (sp-vectorise-fft-series f input frame-size padded-frame-size . custom) "return the result for ffts on all frames of frame-size that fit into input with an overlap. fft input is zero padded so that results have the same size for different effective input durations" (let ( (overlap-factor 0.5) (input-threshold 0.001) (bin-magnitude-threshold 0.01) (window-f sp-samples-apply-hann-window)) (apply sp-fold-frames (l (input . custom) (apply f (sp-fft-threshold (sp-fft-drop-dc (sp-fftr (sp-samples-threshold (sp-samples-extract-padded (window-f input) (round (/ (- frame-size padded-frame-size) 2)) padded-frame-size) input-threshold))) bin-magnitude-threshold) custom)) input frame-size overlap-factor custom))) (define (debug-log-line a . b) (display-line (pair a b)) (display-line "") a) (define (sp-vectorise-series input duration scaled-duration) "samples integer integer -> ((vector:bins number:change integer:duration):series-element ...):series" (reverse (first (sp-vectorise-fft-series (l (bins result previous-bin-magnitudes . custom) (let* ( (bin-magnitudes (sp-fft-bins-magnitudes bins)) (change (if previous-bin-magnitudes (absolute-threshold (vector-relative-change-index/value previous-bin-magnitudes bin-magnitudes) 0.001) 0))) (pairs (pair (list bins change duration) result) bin-magnitudes custom))) input duration scaled-duration null #f)))) (define (combine-one a b a-change b-change duration-offset count-ratio) "receives the same number of bins for the same frequency ranges and combines them. this is the function that adds information from higher resolution fft results to lower resolution results" ; the weighting could be improved. the most useful feature is perhaps that it is or can be like an adaptive fft (let* ( (a-magnitudes (map magnitude a)) (a-imaginary (map imag-part a)) (a-mean (arithmetic-mean a-magnitudes)) (a-imaginary-mean (arithmetic-mean a-imaginary)) (b-magnitudes (map magnitude b)) (b-imaginary (map imag-part b))) (map complex-from-magnitude-and-imaginary (linearly-interpolate (/ 1 (+ 1 duration-offset)) a-magnitudes b-magnitudes) (linearly-interpolate (/ 1 (+ 1 duration-offset)) a-magnitudes b-magnitudes)))) (define (combine-series-one a b duration-offset count-ratio) "(series-element ...) (series-element) integer -> (series-element ...) adds information from series b to a. each element has the same bin count but effective input durations are different between series and are scaled to match in size" (map (l (a) (apply (l (a-bins a-change a-duration b-bins b-change b-duration) (let loop ((index count-ratio)) (if (< index (vector-length a-bins)) (let (values (map (l (bins) (map-integers count-ratio (l (c) (vector-ref bins (- index c))))) (list a-bins b-bins))) (each-with-index (l (c-index c-value) (vector-set! a-bins (- index c-index) c-value)) (combine-one (first values) (second values) a-change b-change duration-offset count-ratio)) (loop (+ count-ratio index))) (list a-bins b-change a-duration)))) (append a b))) a)) (define (combine-series a b duration-offset) "(series-element ...) (series-element ...) integer -> (series-element ...)" (let (count-ratio (inexact->exact (floor (/ (length a) (length b))))) (let loop ((a a) (b b) (result null)) (if (null? b) result (let (a (apply-values pair (split-at a count-ratio))) (loop (tail a) (tail b) (append result (combine-series-one (first a) (first b) duration-offset count-ratio)))))))) (define* (sp-vectorise input #:key duration) "samples [integer] -> (series-element ...) duration is an exponent for (2 ** exponent) result length is the length of the first series. result elements are (2**duration * overlap-factor) samples apart. analyses only parts of input that powers of two length frames fit into" (let* ( (max-exponent (inexact->exact (floor (log2 (sp-samples-length input))))) (max-duration (expt 2 max-exponent)) (min-exponent (or duration (round (/ max-exponent 2))))) (let loop ((exponent min-exponent) (result null)) (if (<= exponent max-exponent) (let (series (sp-vectorise-series input (expt 2 exponent) max-duration)) (loop (+ 1 exponent) (if (null? result) series (combine-series result series (- exponent min-exponent))))) result)))))
false
9716630c45232fec0ed65a9e4c8a8b950f62468a
62306098c265670b8cb1e6ad9fc056c8ff471b15
/c4.scm
75f5eb0e210fca7acc51baedcf1238e0416ac588
[]
no_license
naoyat/reading-3imp-ikoma
9953ef8a3d4b955fa6919a167ea4f0d6e7665e05
1f4d106e3504a2701bb1ce4a81afdc4bcfb94a2f
refs/heads/master
2016-09-06T00:19:58.518754
2009-04-15T12:34:37
2009-04-15T12:34:37
176,603
2
0
null
null
null
null
UTF-8
Scheme
false
false
11,397
scm
c4.scm
;;; ;;; 4.6 Tail Calls 末尾呼出し ;;; (require "./3imp") (require "./debug") (use srfi-1) ;; ;; Chapter 4.1 - Stack-Based Implementation of Block-Structured Languages ;; ; p.75 (define stack (make-vector 1000)) (define (push x s) (dbg :trace "(push x:~a s:~d)" x s) (vector-set! stack s x) (+ s 1)) (define (index s i) ;** (dbg :trace "(index s:~d i:~d) => stack[~d]" s i (- s i 1)) ; (vector-ref stack (- (- s i) 1))) (vector-ref stack (- s i 1))) (define (index-set! s i v) ;** (dbg :trace "(index-set! s:~d i:~d v:~a) => stack[~d] := ~a" s i v (- s i 1) v) ; (vector-set! stack (- (- s i) 1) v) (vector-set! stack (- s i 1) v)) (define (save-stack s) ;; v <== stack[0..s-1]; vを返すよ (dbg :trace "(save-stack s:~a)" s) (let1 v (make-vector s) (dotimes (i s) (vector-set! v i (vector-ref stack i))) v)) (define (restore-stack v) ;; stack <== v; 長さを返すよ (dbg :trace "(restore-stack v:~a)" v) (let1 s (vector-length v) (dotimes (i s) (vector-set! stack i (vector-ref v i))) s)) (define (head-of-stack) (let1 undef (if #f #f) (filter (lambda (x) (not (eq? undef x))) (take (vector->list stack) 20) ))) ;;; ;;; 4.4 Display Closures ディスプレイ・クロージャ ;;; ;; ;; 4.4.1 Displays. ディスプレイ ;; ;; ;; 4.4.2 Creating Display Closures. ディスプレイ・クロージャを作る ;; ;; ;; 4.4.3 Finding Free Variables. 自由変数を探す ;; ;; p.93 (define (set-member? x s) (dbg :trace "(set-member? x:~a s:~a)" x s) ; (cond [(null? s) '()] ; [(eq? x (car s)) 't] (cond [(null? s) #f] [(eq? x (car s)) #t] [else (set-member? x (cdr s))])) (define (set-cons x s) (dbg :trace "(set-cons x:~a s:~a)" x s) (if (set-member? x s) s (cons x s))) (define (set-union s1 s2) (dbg :trace "(set-union s1:~a s2:~a)" s1 s2) (if (null? s1) s2 (set-union (cdr s1) (set-cons (car s1) s2)))) (define (set-minus s1 s2) (dbg :trace "(set-minus s1:~a s2:~a)" s1 s2) (if (null? s1) '() (if (set-member? (car s1) s2) (set-minus (cdr s1) s2) (cons (car s1) (set-minus (cdr s1) s2))))) (define (set-intersect s1 s2) (dbg :trace "(set-intersect s1:~a s2:~a)" s1 s2) (if (null? s1) '() (if (set-member? (car s1) s2) (cons (car s1) (set-intersect (cdr s1) s2)) (set-intersect (cdr s1) s2)))) ;; ;; 4.4.4 Translation 翻訳 ;; ;; p.95 (define (collect-free vars e next) (dbg :trace "(collect-free vars:~a e:~a next:~a)" vars e next) (if (null? vars) next (collect-free (cdr vars) e (compile-refer (car vars) e (list 'argument next))))) (define (compile-refer x e next) (dbg :trace "(compile-refer x:~a e:~a next:~a)" x e next) (compile-lookup x e (lambda (n) (list 'refer-local n next)) (lambda (n) (list 'refer-free n next)))) (define (compile-lookup x e return-local return-free) (dbg :trace "(compile-lookup x:~a e:~a return-local:~a return-free:~a)" x e return-local return-free) (unless (null? e) (let next-local ([locals (car e)] [n 0]) (dbg :compile "COMPILE> (next-local locals:~a, n:~d)" locals n) (if (null? locals) (let next-free ([free (cdr e)] [n 0]) (dbg :compile "COMPILE> (next-free free:~a, n:~d)" free n) (if (eq? (car free) x) (return-free n) (next-free (cdr free) (+ n 1)))) (if (eq? (car locals) x) (return-local n) (next-local (cdr locals) (+ n 1))))) )) ;; ;; 4.4.5 Evaluation 評価 ;; (define (closure body n s) (dbg :trace "(closure body:~a n:~a s:~a)" body n s) (let1 v (make-vector (+ n 1)) (vector-set! v 0 body) ; (let f ([i 0]) ; (unless (= i n) ; (vector-set! v (+ i 1) (index s i)) ; (f (+ i 1)))) (dotimes (i n) (vector-set! v (+ i 1) (index s i))) v)) ;; p.98 (define (closure-body c) (dbg :trace "(closure-body c:~a)" c) (vector-ref c 0)) (define (index-closure c n) (dbg :trace "(index-closure c:~a n:~a)" c n) (vector-ref c (+ n 1))) ;;;;;;;;;;;;;;;;;;;;;;;45 ;;; ;;; 4.5 Supporting Assignments 代入のサポート ;;; ;; ;; 4.5.1 Translation. 翻訳 ;; (define (find-sets x v) (dbg :trace "(find-sets x:~a v:~a)" x v) (cond [(symbol? x) '()] [(pair? x) (record-case x [quote (obj) '()] [lambda (vars body) (find-sets body (set-minus v vars))] [if (test then else) (set-union (find-sets test v) (set-union (find-sets then v) (find-sets else v)))] [set! (var x) ; (set-union (if (set-member? var v) (list var) '()) ; (find-sets x v))] (if (set-member? var v) (set-cons var (find-sets x v)) (find-sets x v))] [call/cc (exp) (find-sets exp v)] [else (let next ([x x]) (if (null? x) '() (set-union (find-sets (car x) v) (next (cdr x)))))])] [else '()])) ;; p.102 (define (make-boxes sets vars next) (dbg :trace "(make-boxes sets:~a vars:~a next:~a)" sets vars next) (let f ([vars vars] [n 0]) (if (null? vars) next (if (set-member? (car vars) sets) (list 'box n (f (cdr vars) (+ n 1))) (f (cdr vars) (+ n 1)))))) ;; p.104 (define (find-free x b) (dbg :trace "(find-free x:~a b:~a)" x b) (cond [(symbol? x) (if (set-member? x b) '() (list x))] [(pair? x) (record-case x [quote (obj) '()] [lambda (vars body) (find-free body (set-union vars b))] [if (test then else) (set-union (find-free test b) (set-union (find-free then b) (find-free else b)))] [set! (var exp) ; (set-union (if (set-member? var b) '() (list var)) ; (find-free exp b))] (if (set-member? var b) (find-free exp b) (set-cons var (find-free exp b)))] [call/cc (exp) (find-free exp b)] [else (let next ([x x]) (if (null? x) '() (set-union (find-free (car x) b) (next (cdr x)))))])] [else '()])) ;; ;; 4.6 ;; ;; p.110 (define (compile x e s next) (dbg :compile "% COMPILE") (dbg :compile " X: ~a" x) (dbg :compile " ENV: ~a" e) (dbg :compile " S: ~a" s) (dbg :compile " NEXT: ~a\n" next) (cond [(symbol? x) (compile-refer x e (if (set-member? x s) (list 'indirect next) next))] [(pair? x) (record-case x [quote (obj) (list 'constant obj next)] [lambda (vars body) (let ([free (find-free body vars)] ;, f [sets (find-sets body vars)]) (collect-free free e (list 'close (length free) (make-boxes sets vars (compile body (cons vars free) (set-union sets (set-intersect s free)) (list 'return (length vars)))) next)))] [if (test then else) (let ([thenc (compile then e s next)] [elsec (compile else e s next)]) (compile test e s (list 'test thenc elsec)))] [set! (var x) (dbg :compile "COMPILE> set! var:~a x:~a" var x) (compile-lookup var e (lambda (n) (compile x e s (list 'assign-local n next))) (lambda (n) (compile x e s (list 'assign-free n next))))] [call/cc (x) (let1 c (list 'conti (if (tail? next) (cadr next) 0);;;;; (list 'argument (compile x e s (if (tail? next) (list 'shift 1 (cadr next) '(apply)) '(apply))))) (if (tail? next) c ; (list 'frame next c)))] (list 'frame c next)))] [else (let loop (;[func (car x)] [args (cdr x)] [c (compile (car x) e s (if (tail? next) (list 'shift (length (cdr x)) (cadr next) '(apply)) '(apply)))]) ; (list 'shift (length args) (cadr next) (list 'apply (length args))) ; (list 'apply (length args))))]) (if (null? args) (if (tail? next) c ; (list 'frame next c)) (list 'frame c next)) (loop ;(car args) (cdr args) (compile (car args) e s (list 'argument c)))))])] [else (list 'constant x next)])) ;; ;; 4.6.3 Evaluation. ;; (define (shift-args n m s) ;; STACK[s+(n-1..1)+m-1] = STACK[s-(n-1..1)-1] (dbg :trace "(shift-args n:~d m:~d s:~d)" n m s) (let next-arg ((i (- n 1))) (unless (< i 0) (index-set! s (+ i m) (index s i)) (next-arg (- i 1)))) ; (index-set! s (+ i m) (index s i)) ; (unless (< i 0) ; (next-arg (- i 1)))) (- s m)) ;; p.112 (define (VM a x f c s) (dbg :vm "% VM") (dbg :vm " ACCUM: ~a" a) (dbg :vm " NEXT: ~a" x) (dbg :vm " CURR-CALL-FRAME: ~a" f) ;; [eから改名] (環境は現在のフレームと現在のクロージャに分けて保存されるようになったので) (dbg :vm " CURR-CLOSURE: ~a" c) ;; [NEW]クロージャ外の自由変数を参照するときに使う (dbg :vm " STACK: ~d in ~a" s (head-of-stack)) (dbg :vm " INST: ~a\n" (car x)) (record-case x [halt () a] [refer-local (n x) (VM (index f n) x f c s)] [refer-free (n x) (VM (index-closure c n) x f c s)] ; index-closure c n = c[n+1] [indirect (x) (VM (unbox a) x f c s)] [constant (obj x) (VM obj x f c s)] [close (n body x) (VM (closure body n s) x f c (- s n))] [box (n x) (index-set! s n (box (index s n))) (VM a x f c s)] [test (then else) (VM a (if a then else) f c s)] [assign-local (n x) (set-box! (index f n) a) (VM a x f c s)] [assign-free (n x) (set-box! (index-closure c n) a); c[n+1].[0] = a (VM a x f c s)] ; [conti (x) ; (VM (continuation s) x f c s)] [conti (n x) (VM (continuation s n) x f c s)] [nuate (stack x) (VM a x f c (restore-stack stack))] ; [frame (ret x) ; (VM a x f c (push ret (push f (push c s))))] [frame (x ret) (VM a x f c (push ret (push f (push c s))))] [argument (x) (VM a x f c (push a s))] [shift (n m x) (VM a x f c (shift-args n m s))] [apply () (VM a (closure-body a) s a s)] ;; closure-body c = c[0] [return (n) (let1 s (- s n) (VM a (index s 0) (index s 1) (index s 2) (- s 3)))] [_ args (dbg :vm "?? ~a ~a" x args)] )) (define (tail? x) (dbg :trace "(tail? x:~a)" x) (eq? 'return (car x))) (define (box x) (dbg :trace "(box x:~a)" x) (list x)) (define (unbox x) (dbg :trace "(unbox x:~a)" x) (car x)) (define (set-box! b x) (dbg :trace "(set-box! b:~a x:~a)" b x) (set-car! b x)) (define (continuation s n) ;; 3引数のclosureを使う版continuationの定義がない ... biwaschemeから (dbg :trace "(continuation s:~a n:~a)" s n) (closure ; (list 'refer 0 0 (list 'nuate (save-stack s) '(return 0))) ;; body (list 'refer-local; 0 0 0;n? (list 'nuate (save-stack s) (list 'return n))) ; next? ;; n - number of frees 0 ;; s:x '() )) (define (evaluate x . args) (let-optionals* args ((env '())) (dbg :evaluate "% EVALUATE") (dbg :evaluate " X: ~a" x) (dbg :evaluate " ENV: ~a\n" env) (VM '() (compile x env '() '(halt)) 0 '() 0) ))
false
4b82e0c3dc013c6d78124093ea68f46b2b3a3262
fb9a1b8f80516373ac709e2328dd50621b18aa1a
/ch2/exercise2-79.scm
70f787f992a90f0db80287e9401c9f666a94815b
[]
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
949
scm
exercise2-79.scm
;; 問題2.79 ; 2つの数の等価をテストする等価述語equ?を定義して,汎用算術パッケージに設定せよ ; この演算は通常の数,有理数および複素数に対して働くものとする (load "./ch2/2-5_system_with_generic_operations.scm") ;;2.79 (define n1 (make-scheme-number 3)) (define n2 (make-scheme-number 3)) (define n3 (make-scheme-number 4)) (equ? n1 n2) (equ? n1 n3) (define ra1 (make-rational 3 4)) (define ra2 (make-rational 3 4)) (define ra3 (make-rational 1 5)) (equ? ra1 ra2) (equ? ra1 ra3) (define ri1 (make-complex-from-real-imag 1 1)) (define ri2 (make-complex-from-real-imag 1 1)) (define ri3 (make-complex-from-real-imag 2 1)) (equ? ri1 ri2) (equ? ri1 ri3) (define ma1 (make-complex-from-mag-ang 1 0)) (define ma2 (make-complex-from-mag-ang 1 0)) (define ma3 (make-complex-from-mag-ang 1 1)) (equ? ma1 ma2) (equ? ma1 ma3) (define ri4 (make-complex-from-real-imag 1 0)) (equ? ri4 ma1)
false
b8c62b8f1ac9c7b492fbe7c8274f9d32c9748f4a
0b90add00a39e266f63ee7868b4b6499d58bbb31
/combinators/linrec.sls
05529d245df0ecf35435ddc9977ec29337316c99
[]
no_license
okuoku/dharmalab
e295b7fb6fda704d73b9865841fb6dc6605e78a5
9ac64b8de3067a73c812f3534bd6710f6a7d3109
refs/heads/master
2021-01-16T20:01:25.538104
2010-07-04T08:58:54
2011-01-17T16:53:18
756,061
1
0
null
null
null
null
UTF-8
Scheme
false
false
219
sls
linrec.sls
(library (dharmalab combinators linrec) (export linrec) (import (rnrs)) (define (linrec f g h i) (define (fun x) (if (f x) (g x) (i x (fun (h x))))) fun) )
false
8e4d1fd876106d457a5544a7c40cfbff0cd017ca
1a64a1cff5ce40644dc27c2d951cd0ce6fcb6442
/testing/test-optional-arg.scm
886c14506a346e05452b1fb12d6317035ef215d7
[]
no_license
skchoe/2007.rviz-objects
bd56135b6d02387e024713a9f4a8a7e46c6e354b
03c7e05e85682d43ab72713bdd811ad1bbb9f6a8
refs/heads/master
2021-01-15T23:01:58.789250
2014-05-26T17:35:32
2014-05-26T17:35:32
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
25,208
scm
test-optional-arg.scm
#lang scheme ;file:///Users/Authenticated%20User/Desktop/PLT%20Scheme%20v3.99.0.22/doc/guide/Contracts_on_Functions_in_General.html#(part~20contracts-optional) (provide/contract ; pad the given str left and right with ; the (optional) char so that it is centered [string-pad-center (->* (string? natural-number/c) (char?) string?)]) (define (string-pad-center str width [pad #\space]) (define field-width (min width (string-length str))) (define rmargin (ceiling (/ (- width field-width) 2))) (define lmargin (floor (/ (- width field-width) 2))) (string-append (build-string lmargin (λ (x) pad)) str (build-string rmargin (λ (x) pad)))) (string-pad-center "test" 10 (lambda (x) x)) ;Guide: PLT Scheme ; ;1 Welcome to PLT Scheme ;2 Scheme Essentials ;3 Built-In Datatypes ;4 Expressions and Definitions ;5 Programmer-Defined Datatypes ;6 Modules ;7 Contracts ;8 Input and Output ;9 Regular Expressions ;10 Exceptions and Control ;11 Iterations and Comprehensions ;12 Pattern Matching ;13 Classes and Objects ;14 Units (Components) ;15 Threads ;16 Reflection and Dynamic Evaluation ;17 Macros ;18 Reader Extension ;19 Security ;20 Memory Management ;21 Performance ;22 Running and Creating Executables ;23 Configuration and Compilation ;24 More Libraries ; Bibliography ; Index ; ;On this page: ;7.3.1 Contract error messages that contain “...” ;7.3.2 Optional arguments ;7.3.3 Rest arguments ;7.3.4 Keyword arguments ;7.3.5 Optional keyword arguments ;7.3.6 When a function’s result depends on its arguments ;7.3.7 When contract arguments depend on each other ;7.3.8 Ensuring that a function properly modifies state ;7.3.9 Contracts for case-lambda ;7.3.10 Multiple result values ;7.3.11 Procedures of some fixed, but statically unknown arity ;Version: 3.99.0.23contents index ← prev up next → ; ;7.3 Contracts on Functions in General ;7.3.1 Contract error messages that contain “...” ;You wrote your module. You added contracts. You put them into the interface so that client programmers have all the information from interfaces. It’s a piece of art: ; ; #lang scheme ; ; ; ; (provide/contract ; ; [deposit (-> (lambda (x) ; ; (and (number? x) (integer? x) (>= x 0))) ; ; any)]) ; ; ; ; (define this 0) ; ; (define (deposit a) ...) ; ; ; ;Several clients used your module. Others used their modules in turn. And all of a sudden one of them sees this error message: ; ;bank-client broke the contract (-> ??? any) it had with myaccount on deposit; expected <???>, given: -10 ; ;Clearly, bank-client is a module that uses myaccount but what is the ??? doing there? Wouldn’t it be nice if we had a name for this class of data much like we have string, number, and so on? ; ;For this situation, PLT Scheme provides flat named contracts. The use of “contract” in this term shows that contracts are first-class values. The “flat” means that the collection of data is a subset of the built-in atomic classes of data; they are described by a predicate that consumes all Scheme values and produces a boolean. The “named” part says what we want to do, which is to name the contract so that error messages become intelligible: ; ; #lang scheme ; ; ; ; (define (amount? x) (and (number? x) (integer? x) (>= x 0))) ; ; (define amount (flat-named-contract 'amount amount?)) ; ; ; ; (provide/contract ; ; [deposit (amount . -> . any)]) ; ; ; ; (define this 0) ; ; (define (deposit a) ...) ; ; ; ;With this little change, the error message becomes all of the sudden quite readable: ; ;bank-client broke the contract (-> amount any) it had with myaccount on deposit; expected <amount>, given: -10 ; ;7.3.2 Optional arguments ;Take a look at this excerpt from a string-processing module, inspired by the Scheme cookbook: ; ; #lang scheme ; ; ; ; (provide/contract ; ; ; pad the given str left and right with ; ; ; the (optional) char so that it is centered ; ; [string-pad-center (->* (string? natural-number/c) ; ; (char?) ; ; string?)]) ; ; ; ; (define (string-pad-center str width [pad #\space]) ; ; (define field-width (min width (string-length str))) ; ; (define rmargin (ceiling (/ (- width field-width) 2))) ; ; (define lmargin (floor (/ (- width field-width) 2))) ; ; (string-append (build-string lmargin (λ (x) pad)) ; ; str ; ; (build-string rmargin (λ (x) pad)))) ; ; ; ;The module exports string-pad-center, a function that creates a string of a given width with the given string in the center. The default fill character is #\space; if the client module wishes to use a different character, it may call string-pad-center with a third argument, a char, overwriting the default. ; ;The function definition uses optional arguments, which is appropriate for this kind of functionality. The interesting point here is the formulation of the contract for the string-pad-center. ; ;The contract combinator ->*, demands several groups of contracts: ; ;The first one is a parenthesized group of contracts for all required arguments. In this example, we see two: string? and natural-number/c. ; ;The second one is a parenthesized group of contracts for all optional arguments: char?. ; ;The last one is a single contract: the result of the function. ; ;Note if a default value does not satisfy a contract, you won’t get a contract error for this interface. In contrast to type systems, we do trust you; if you can’t trust yourself, you need to communicate across boundaries for everything you write. ; ;7.3.3 Rest arguments ;We all know that + in Beginner Scheme is a function that consumes at least two numbers but, in principle, arbitraily many more. Defining the function is easy: ; ; (define (plus fst snd . rst) ; ; (foldr + (+ fst snd) rst)) ; ; ; ;Describing this function via a contract is difficult because of the rest argument (rst). ; ;Here is the contract: ; ; (provide/contract ; ; [plus (->* (number? number?) () #:rest (listof number?) number?)]) ; ; ; ;The ->* contract combinator empowers you to specify functions that consume a variable number of arguments or functions like plus, which consume “at least this number” of arguments but an arbitrary number of additional arguments. ; ;The contracts for the required arguments are enclosed in the first pair of parentheses: ; ; (number? number?) ; ;For plus they demand two numbers. The empty pair of parenthesis indicates that there are no optional arguments (not counting the rest arguments) and the contract for the rest argument follows #:rest ; ; (listof number?) ; ;Since the remainder of the actual arguments are collected in a list for a rest parameter such as rst, the contract demands a list of values; in this specific examples, these values must be number. ; ;7.3.4 Keyword arguments ;Sometimes, a function accepts many arguments and remembering their order can be a nightmare. To help with such functions, PLT Scheme has keyword arguments. ; ;For example, consider this function that creates a simple GUI and asks the user a yes-or-no question: ; ; #lang scheme/gui ; ; ; (define (ask-yes-or-no-question #:question question #:default answer #:title title #:width w #:height h) (define d (new dialog% [label title] [width w] [height h])) (define msg (new message% [label question] [parent d])) (define (yes) (set! answer #t) (send d show #f)) (define (no) (set! answer #f) (send d show #f)) (define yes-b (new button% [label "Yes"] [parent d] [callback (λ (x y) (yes))] [style (if answer '(border) '())])) (define no-b (new button% [label "No"] [parent d] [callback (λ (x y) (no))] [style (if answer '() '(border))])) (send d show #t) answer) ; (provide/contract ; ; [ask-yes-or-no-question ; ; (-> #:question string? ; ; #:default boolean? ; ; #:title string? ; ; #:width exact-integer? ; ; #:height exact-integer? ; ; boolean?)]) ; ; ;Note that if you really want to ask a yes-or-no question via a GUI, you should use message-box/custom (and generally speaking, avoiding the responses “yes” and “no” in your dialog is a good idea, too ...). ;The contract for ask-yes-or-no-question uses our old friend the -> contract combinator. Just like lambda (or define-based functions) use keywords for specifying keyword arguments, it uses keywords for specifying contracts on keyword arguments. In this case, it says that ask-yes-or-no-question must receive five keyword arguments, one for each of the keywords #:question, #:default, #:title, #:width, and #:height. Also, just like in a function definition, the keywords in the -> may appear in any order. ; ;7.3.5 Optional keyword arguments ;Of course, many of the parameters in ask-yes-or-no-question (from the previous question) have reasonable defaults, and should be made optional: ; ; (define (ask-yes-or-no-question #:question question ; ; #:default answer ; ; #:title [title "Yes or No?"] ; ; #:width [w 400] ; ; #:height [h 200]) ; ; ...) ; ; ; ;To specify this function’s contract, we need to use ->*. It too supports keywords just as you might expect, in both the optional and mandatory argument sections. In this case, we have mandatory keywords #:question and #:default, and optional keywords #:title, #:width, and #:height. So, we write the contract like this: ; ; (provide/contract ; ; [ask-yes-or-no-question ; ; (->* (#:question string? ; ; #:default boolean?) ; ; ; ; (#:title string? ; ; #:width exact-integer? ; ; #:height exact-integer?) ; ; ; ; boolean?)]) ; ; ; ;putting the mandatory keywords in the first section and the optional ones in the second section. ; ;7.3.6 When a function’s result depends on its arguments ;Here is an excerpt from an imaginary (pardon the pun) numerics module: ; ; #lang scheme ; ; (provide/contract ; ; [sqrt.v1 (->d ([argument (>=/c 1)]) ; ; () ; ; [result (<=/c argument)])]) ; ; ... ; ; ; ;The contract for the exported function sqrt.v1 uses the ->d rather than -> function contract. The “d” stands for dependent contract, meaning the contract for the function range depends on the value of the argument. ; ;In this particular case, the argument of sqrt.v1 is greater or equal to 1. Hence a very basic correctness check is that the result is smaller than the argument. (Naturally, if this function is critical, one could strengthen this check with additional clauses.) ; ;In general, a dependent function contract looks just like the more general ->* contract, but with names added that can be used elsewhere in the contract. ; ;Yes, there are many other contract combinators such as <=/c and >=/c, and it pays off to look them up in the contract section of the reference manual. They simplify contracts tremendously and make them more accessible to potential clients. ; ;7.3.7 When contract arguments depend on each other ;Eventually bank customers want their money back. Hence, a module that implements a bank account must include a method for withdrawing money. Of course, ordinary accounts don’t let customers withdraw an arbitrary amount of money but only as much as they have in the account. ; ;Suppose the account module provides the following two functions: ; ; balance : (-> account amount) ; ; withdraw : (-> account amount account) ; ; ; ;Then, informally, the proper precondition for withdraw is that “the balance of the given account is greater than or equal to the given (withdrawal) amount.” The postcondition is similar to the one for deposit: “the balance of the resulting account is larger than (or equal to) than the one of the given account.” You could of course also formulate a full-fledged correctness condition, namely, that the balance of the resulting account is equal to the balance of the given one, plus the given amount. ; ;The following module implements accounts imperatively and specifies the conditions we just discussed: ; ; #lang scheme ; ; ; ; ; section 1: the contract definitions ; ; (define-struct account (balance)) ; ; (define amount natural-number/c) ; ; ; ; (define msg> "account a with balance larger than ~a expected") ; ; (define msg< "account a with balance less than ~a expected") ; ; ; ; (define (mk-account-contract acc amt op msg) ; ; (define balance0 (balance acc)) ; ; (define (ctr a) ; ; (and (account? a) (op balance0 (balance a)))) ; ; (flat-named-contract (format msg balance0) ctr)) ; ; ; ; ; section 2: the exports ; ; (provide/contract ; ; [create (amount . -> . account?)] ; ; [balance (account? . -> . amount)] ; ; [withdraw (->d ([acc account?] ; ; [amt (and/c amount (<=/c (balance acc)))]) ; ; () ; ; [result (mk-account-contract acc amt > msg>)])] ; ; [deposit (->d ([acc account?] ; ; [amt amount]) ; ; () ; ; [result (mk-account-contract acc amt < msg<)])]) ; ; ; ; ; section 3: the function definitions ; ; (define balance account-balance) ; ; ; ; (define (create amt) (make-account amt)) ; ; ; ; (define (withdraw acc amt) ; ; (set-account-balance! acc (- (balance acc) amt)) ; ; acc) ; ; ; ; (define (deposit acc amt) ; ; (set-account-balance! acc (+ (balance acc) amt)) ; ; acc) ; ; ; ;The second section is the export interface: ; ;create consumes an initial deposit and produces an account. This kind of contract is just like a type in a statically typed language, except that statically typed languages usually don’t support the type “natural numbers” (as a full-fledged subtype of numbers). ; ;balance consumes an account and computes its current balance. ; ;withdraw consumes an account, named acc, and an amount, amt. In addition to being an amount, the latter must also be less than (balance acc), i.e., the balance of the given account. That is, the contract for amt depends on the value of acc, which is what the ->d contract combinator expresses. ; ;The result contract is formed on the fly: (mk-account-contract acc amt > msg>). It is an application of a contract-producing function that consumes an account, an amount, a comparison operator, and an error message (a format string). The result is a contract. ; ;deposit’s contract has been reformulated using the ->d combinator. ; ;The code in the first section defines all those pieces that are needed for the formulation of the export contracts: account?, amount, error messages (format strings), and mk-account-contract. The latter is a function that extracts the current balance from the given account and then returns a named contract, whose error message (contract name) is a string that refers to this balance. The resulting contract checks whether an account has a balance that is larger or smaller, depending on the given comparison operator, than the original balance. ; ;7.3.8 Ensuring that a function properly modifies state ;The ->d contract combinator can also ensure that a function only modifies state according to certain constraints. For example, consider this contract (it is a slightly simplified from the function preferences:add-panel in the framework): ; ; (->d ([parent (is-a?/c area-container-window<%>)]) ; ; () ; ; [_ ; ; (let ([old-children (send parent get-children)]) ; ; (λ (child) ; ; (andmap eq? ; ; (append old-children (list child)) ; ; (send parent get-children))))]) ; ; ; ;It says that the function accepts a single argument, named parent, and that parent must be an object matching the interface area-container-window<%>. ; ;The range contract ensures that the function only modifies the children of parent by adding a new child to the front of the list. It accomplishes this by using the _ instead of a normal identifier, which tells the contract library that the range contract does not depend on the values of any of the results, and thus the contract library evaluates the expression following the _ when the function is called, instead of when it returns. Therefore the call to the get-children method happens before the function under the contract is called. When the function under contract returns, its result is passed in as child, and the contract ensures that the children after the function return are the same as the children before the function called, but with one more child, at the front of the list. ; ;To see the difference in a toy example that focuses on this point, consider this program ; ; #lang scheme ; ; (define x '()) ; ; (define (get-x) x) ; ; (define (f) (set! x (cons 'f x))) ; ; (provide/contract ; ; [f (->d () () [_ (begin (set! x (cons 'ctc x)) any/c)])] ; ; [get-x (-> (listof symbol?))]) ; ; ; ;If you were to require this module, call f, then the result of get-x would be '(f ctc). In contrast, if the contract for f were ; ; (->d () () [res (begin (set! x (cons 'ctc x)) any/c)]) ; ;(only changing the underscore to res), then the result of get-x would be '(ctc f). ; ;7.3.9 Contracts for case-lambda ;Dybvig, in Chapter 5 of the Chez Scheme User’s Guide, explains the meaning and pragmatics of case-lambda with the following example (among others): ; ; (define substring1 ; ; (case-lambda ; ; [(s) (substring1 s 0 (string-length s))] ; ; [(s start) (substring1 s start (string-length s))] ; ; [(s start end) (substring s start end)])) ; ; ; ;This version of substring has one of the following signature: ; ;just a string, in which case it copies the string; ; ;a string and an index into the string, in which case it extracts the suffix of the string starting at the index; or ; ;a string a start index and an end index, in which case it extracts the fragment of the string between the two indices. ; ;The contract for such a function is formed with the case-> combinator, which combines as many functional contracts as needed: ; ; (provide/contract ; ; [substring1 ; ; (case-> ; ; (string? . -> . string?) ; ; (string? natural-number/c . -> . string?) ; ; (string? natural-number/c natural-number/c . -> . string?))]) ; ; ; ;As you can see, the contract for substring1 combines three function contracts, just as many clauses as the explanation of its functionality required. ; ;7.3.10 Multiple result values ;The function split consumes a list of chars and delivers the string that occurs before the first occurrence of #\newline (if any) and the rest of the list: ; ; (define (split l) ; ; (define (split l w) ; ; (cond ; ; [(null? l) (values (list->string (reverse w)) '())] ; ; [(char=? #\newline (car l)) ; ; (values (list->string (reverse w)) (cdr l))] ; ; [else (split (cdr l) (cons (car l) w))])) ; ; (split l '())) ; ; ; ;It is a typical multiple-value function, returning two values by traversing a single list. ; ;The contract for such a function can use the ordinary function arrow ->, since it treats values specially, when it appears as the last result: ; ; (provide/contract ; ; [split (-> (listof char?) ; ; (values string? (listof char?)))]) ; ; ; ;The contract for such a function can also be written using ->*, just like plus: ; ; (provide/contract ; ; [split (->* ((listof char?)) ; ; () ; ; (values string? (listof char?)))]) ; ; ; ;As before the contract for the argument is wrapped in an extra pair of parentheses (and must always be wrapped like that) and the empty pair of parentheses indicates that there are no optoinal arguments. The contracts for the results are inside values: a string and a list of characters. ; ;Now suppose we also want to ensure that the first result of split is a prefix of the given word in list format. In that case, we need to use the ->d contract combinator: ; ; (define (substring-of? s) ; ; (flat-named-contract ; ; (format "substring of ~s" s) ; ; (lambda (s2) ; ; (and (string? s2) ; ; (<= (string-length s2) s) ; ; (equal? (substring s 0 (string-length s2)) s2))))) ; ; ; ; (provide/contract ; ; [split (->d ([fl (listof char?)]) ; ; () ; ; (values [s (substring-of (list->string fl))] ; ; [c (listof char?)]))]) ; ; ; ;Like ->*, the ->d combinator uses a function over the argument to create the range contracts. Yes, it doesn’t just return one contract but as many as the function produces values: one contract per value. In this case, the second contract is the same as before, ensuring that the second result is a list of chars. In contrast, the first contract strengthens the old one so that the result is a prefix of the given word. ; ;This contract is expensive to check of course. Here is a slightly cheaper version: ; ; (provide/contract ; ; [split (->d ([fl (listof char?)]) ; ; () ; ; (values [s (string-len/c (length fl))] ; ; [c (listof char?)]))]) ; ; ; ;Click on string-len/c to see what it does. ; ;7.3.11 Procedures of some fixed, but statically unknown arity ;Imagine yourself writing a contract for a function that accepts some other function and a list of numbers that eventually applies the former to the latter. Unless the arity of the given function matches the length of the given list, your procedure is in trouble. ; ;Consider this n-step function: ; ; ; (number ... -> (union #f number?)) (listof number) -> void ; ; (define (n-step proc inits) ; ; (let ([inc (apply proc inits)]) ; ; (when inc ; ; (n-step proc (map (λ (x) (+ x inc)) inits))))) ; ; ; ;The argument of n-step is proc, a function proc whose results are either numbers or false, and a list. It then applies proc to the list inits. As long as proc returns a number, n-step treats that number as an increment for each of the numbers in inits and recurs. When proc returns false, the loop stops. ; ;Here are two uses: ; ; ; nat -> nat ; ; (define (f x) ; ; (printf "~s \n" x) ; ; (if (= x 0) #f -1)) ; ; (n-step f '(2)) ; ; ; ; ; nat nat -> nat ; ; (define (g x y) ; ; (define z (+ x y)) ; ; (printf "~s\n" (list x y z)) ; ; (if (= z 0) #f -1)) ; ; ; ; (n-step g '(1 1)) ; ; ; ;A contract for n-step must specify two aspects of proc’s behavior: its arity must include the number of elements in inits, and it must return either a number or #f. The latter is easy, the former is difficult. At first glance, this appears to suggest a contract that assigns a variable-arity to proc: ; ; (->* () ; ; (listof any/c) ; ; (or/c number? false/c)) ; ; ; ;This contract, however, says that the function must accept any number of arguments, not a specific but undetermined number. Thus, applying n-step to (lambda (x) x) and (list 1) breaks the contract because the given function accepts only one argument. ; ;The correct contract uses the unconstrained-domain-> combinator, which specifies only the range of a function, not its domain. It is then possible to combine this contract with an arity test to specify the correct n-step’s contract: ; ; (provide/contract ; ; [n-step ; ; (->d ([proc ; ; (and/c (unconstrained-domain-> ; ; (or/c false/c number?)) ; ; (λ (f) (procedure-arity-includes? ; ; f ; ; (length inits))))] ; ; [inits (listof number?)]) ; ; () ; ; any)]) ; ; ; ; ; ;contents index ← prev up next →
false
0880065c48c2e5c68ad02d79ae9ad4e5cafd890c
648776d3a0d9a8ca036acaf6f2f7a60dcdb45877
/queries/haskell_persistent/folds.scm
2bdffd1776812107294dd15b31fcc9e78b0f6412
[ "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
32
scm
folds.scm
[ (entity_definition) ] @fold
false
00302d6a7884b748ecefc27c2dd9110c76e5a45c
4b5dddfd00099e79cff58fcc05465b2243161094
/chapter_1/half_interval_method.scm
2e7786e2f2e3158d17fd31ba5051678b7c50a8c6
[ "MIT" ]
permissive
hjcapple/reading-sicp
c9b4ef99d75cc85b3758c269b246328122964edc
f54d54e4fc1448a8c52f0e4e07a7ff7356fc0bf0
refs/heads/master
2023-05-27T08:34:05.882703
2023-05-14T04:33:04
2023-05-14T04:33:04
198,552,668
269
41
MIT
2022-12-20T10:08:59
2019-07-24T03:37:47
Scheme
UTF-8
Scheme
false
false
1,067
scm
half_interval_method.scm
#lang racket ;; P44 - [通过区间折半寻找方程的根] (define (average x y) (/ (+ x y) 2)) (define (search f neg-point pos-point) (let ((midpoint (average neg-point pos-point))) (if (close-enough? neg-point pos-point) midpoint (let ((test-value (f midpoint))) (cond ((positive? test-value) (search f neg-point midpoint)) ((negative? test-value) (search f midpoint pos-point)) (else midpoint)))))) (define (close-enough? x y) (< (abs (- x y)) 0.001)) (define (half-interval-method f a b) (let ((a-value (f a)) (b-value (f b))) (cond ((and (negative? a-value) (positive? b-value)) (search f a b)) ((and (negative? b-value) (positive? a-value)) (search f b a)) (else (error "Values are not of opposite sign" a b))))) ;;;;;;;;;;;;;;;;;;;; (half-interval-method sin 2.0 4.0) (half-interval-method (lambda (x) (- (* x x x) (* 2 x) 3)) 1.0 2.0)
false
07b33ac271e7b3a16ce6a4d1d821113597153e70
c6b8d142caf06cccf400b8c6d0154050f7037bcf
/test/test-kernel.scm
63fe4793dea5fb4986961d68a7e3e8a8f0371673
[ "Zlib" ]
permissive
skilldown/sphere-geometry
ee9c138407d7c250f47953c6a18cb722030e3f48
817a6e4b7ca20c1ea80036683aabbf302f9b924f
refs/heads/master
2020-04-05T18:29:28.406919
2013-06-05T22:45:30
2013-06-05T22:45:30
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
4,671
scm
test-kernel.scm
;;; Copyright (c) 2010 by Álvaro Castro-Castilla, All Rights Reserved. ;;; Licensed under the GPLv3 license, see LICENSE file for full description. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Tests for geometry package ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (import (srfi 64-test) #(math exact-algebra) ../kernel) (define-syntax test-equal/= (syntax-rules () ((_ name =f expr result) (test-assert name (=f expr result))))) ;------------------------------------------------------------------------------- (test-begin "geometry") ;------------------------------------------------------------------------------- ;------------------------------------------------------------------------------- ; Construction ;------------------------------------------------------------------------------- (test-equal/= "segment->line horizontal line" line:= (segment->line (make-segment (make-point 2.2 -2.0) (make-point 2.2 3.0))) (make-line -1.0 0.0 2.2)) (test-equal/= "segment->line vertical line" line:= (segment->line (make-segment (make-point 1.0 1.0) (make-point 11.0 1.0))) (make-line 0.0 1.0 -1.0)) (test-equal/= "line:point" vect2:= (line:point (segment->line (make-segment (make-point 4.0 1.0) (make-point 3.0 1.0))) 0) (make-point 1.0 1.0)) ;------------------------------------------------------------------------------- ; Segment ;------------------------------------------------------------------------------- (test-equal "segment:point-relative-position" (segment:point->normalized-1d (make-segment (make-point 1.0 2.0) (make-point 3.0 2.0)) (make-point 2.0 2.0)) 0.5) ;------------------------------------------------------------------------------- ; pseq ;------------------------------------------------------------------------------- (test-equal/= "centroid" vect2:= (pseq:centroid (list (make-point 0.0 0.0) (make-point 2.0 0.0) (make-point 2.0 2.0) (make-point 0.0 2.0))) (make-point 1.0 1.0)) ;------------------------------------------------------------------------------- ; Translations ;------------------------------------------------------------------------------- (test-equal/= "translate.line" line:= (translate.line (segment->line (make-segment (make-point 0.0 0.0) (make-point 1.0 1.0))) (make-vect2 0.0 1.0)) (segment->line (make-segment (make-point 0.0 1.0) (make-point 1.0 2.0)))) (test-equal/= "translate.line" line:= (translate.line (segment->line (make-segment (make-point 0.0 0.0) (make-point 1.0 1.0))) (make-vect2 1.0 1.0)) (segment->line (make-segment (make-point 1.0 1.0) (make-point 2.0 2.0)))) ;------------------------------------------------------------------------------- ; Intersections ;------------------------------------------------------------------------------- (test-equal/= "intersection:line-line 2" vect2:= (intersect.line-line (segment->line (make-segment (make-point 0.0 0.0) (make-point 2.0 2.0))) (segment->line (make-segment (make-point 0.0 2.0) (make-point 2.0 0.0)))) (make-point 1.0 1.0)) (test-equal/= "intersection:line-line 2" vect2:= (intersect.line-line (segment->line (make-segment (make-point 0.0 0.0) (make-point 2.0 2.0))) (segment->line (make-segment (make-point -2.0 0.0) (make-point 0.0 -2.0)))) (make-point -1.0 -1.0)) ;------------------------------------------------------------------------------- (test-end "geometry") ;-------------------------------------------------------------------------------k
true
238f699c0a302d49840493b9de920a1a43e95d1b
a2bc20ee91471c8116985e0eb6da1d19ab61f6b0
/exercise_9_2/main.scm
b197f9e6d95ae7290cbd6cc7b57809dfded27fbc
[]
no_license
cthulhu-irl/my-scheme-practices
6209d01aa1497971a5b970ab8aa976bb3481e9c9
98867870b0cb0306bdeb209d076bdc80e2e0e8cc
refs/heads/master
2022-09-22T15:19:48.798783
2020-06-06T14:16:07
2020-06-06T14:16:07
265,855,102
0
0
null
null
null
null
UTF-8
Scheme
false
false
550
scm
main.scm
(define (my-copy-file filename1 filename2) (let ( (port1 (open-input-file filename1)) (port2 (open-output-file filename2))) (let loop((chr (read-char port1))) (if (eof-object? chr) (begin (close-input-port port1) (close-output-port port2) #t) (begin (write-char chr port2) (loop (read-char port1))))))) (my-copy-file "hello.txt" "copy.txt")
false
e8aaabdcf5cd6618bfa746429b65e8167a9f73c8
38bf86e526c4d667225531bb817237304f5339e6
/lib/gr2e/extractcontent.scm
27ad25efbb3e9f7e3d2ed92872ba8a7aadccd5a0
[]
no_license
SumiTomohiko/gauche-rss2email
c5aff808ca7cf9ece960d9cdf4030678f7307a4d
bec7faf44fcf81b13272ebdd768146fe32c17d23
refs/heads/master
2020-04-06T21:32:17.468515
2009-07-31T13:19:25
2009-07-31T13:19:25
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,087
scm
extractcontent.scm
;;; ;;; extractcontent ;;; (define-module gr2e.extractcontent (export extract-content)) (select-module gr2e.extractcontent) (define (extract-content html) (define (extract-google-ad-section html) (let ( (from (rxmatch-end (#/<!--\s*google_ad_section_start\s*-->/ html))) (to (rxmatch-start (#/<!--\s*google_ad_section_end\s*-->/ html)))) (substring html from to))) (if (#/<!--\s*google_ad_section_start\s*-->/ html) (extract-google-ad-section html) (let loop ( (max-score 0) (content "") (contents (string-split html #/<\/?(?:div|td)\s*[^>]*>/i))) (define (count-punctuations s) (length (string-split s #/[、。!?]/))) (if (null? contents) content (let ((score (count-punctuations (car contents)))) (when (< max-score score) (set! content (car contents)) (set! max-score score)) (loop max-score content (cdr contents))))))) ;; Epilogue (provide "gr2e/extractcontent") ;; vim: tabstop=2 shiftwidth=2 expandtab softtabstop=2 filetype=scheme
false
e42a2af0cf294f4f319c2c8a243743cbeca6678f
15b3f9425594407e43dd57411a458daae76d56f6
/bin/test/tmj.scm
aa1d0384f83cad8c7a632c991ff2fdb91a8ddee6
[]
no_license
aa10000/scheme
ecc2d50b9d5500257ace9ebbbae44dfcc0a16917
47633d7fc4d82d739a62ceec75c111f6549b1650
refs/heads/master
2021-05-30T06:06:32.004446
2015-02-12T23:42:25
2015-02-12T23:42:25
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
277
scm
tmj.scm
(load "ch5-compiler.scm") (define in2 (open-input-file "exp_com.scm")) (define expression-to-compile (read in2)) (close-input-port in2) (define out2 (open-output-file "t.txt")) (display (compile expression-to-compile 'val 'next) out2) (newline out2) (close-output-port out2)
false
7434c51fb4190ae3912a653c4b95468bf3338e7b
a19495f48bfa93002aaad09c6967d7f77fc31ea8
/src/kanren/kanren/mini/book-si.scm
aa71e96ced4ce99a96737fc1638925243d19a4ee
[ "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
13,171
scm
book-si.scm
(load "minikanrensupport.scm") ; Stream implementation, with incomplete ; data Ans a = Zero | Unit a | Choice a (() -> Ans a) ; | Incomplete (() -> Ans) ; In (Choice a f): a is the current answer; (f) will give further ; answers ; ; This version implements the equations from FBackTrack.hs ; ; $Id: book-si.scm,v 1.8 2006/01/10 05:08:54 oleg Exp $ ; Constructors (define-syntax mzero (syntax-rules () ((_) #f))) (define-syntax unit ; just the identity (syntax-rules () ((_ a) a))) (define-syntax choice (syntax-rules () ((_ a f) (cons a f)))) (define-syntax incomplete (syntax-rules () ((_ e) (lambdaf@ () e)))) (define-syntax incomplete-f ; if already a suspension (syntax-rules () ((_ f) f))) ; Deconstructor (define-syntax case-ans (syntax-rules () ((_ e on-zero ((a^) on-one) ((a f) on-choice) ((i) on-incomplete)) (let ((r e)) (cond ((not r) on-zero) ((procedure? r) (let ((i r)) on-incomplete)) ((and (pair? r) (procedure? (cdr r))) (let ((a (car r)) (f (cdr r))) on-choice)) (else (let ((a^ r)) on-one))))))) ; constructor of a suspension: () -> Ans a (define-syntax lambdaf@ (syntax-rules () ((_ () e) (lambda () e)))) ; constructor of a goal: Subst -> Ans a (define-syntax lambdag@ (syntax-rules () ((_ (s) e) (lambda (s) e)))) ; bind r k = case r of ; Zero -> Zero ; Unit a -> k a ; Choice a f -> mplus (k a) (\() -> bind (f ()) k) (define bind (lambda (r k) (case-ans r (mzero) ((a) (k a)) ((a f) (mplus (k a) (lambdaf@ () (bind (f) k)))) ((i) (incomplete (bind (i) k))) ))) ; mplus:: Ans a -> (() -> Ans a) -> Ans a ; mplus r f = ; case r of ; Zero -> Incomplete f ; Unit a -> Choice a f ; Choice a f' -> Choice a (\() -> mplus (f ()) f') ; mplus r@(Incomplete i) r' = ; case r' of ; Nil -> r ; One b -> Choice b i ; Choice b r' -> Choice b (mplus i r') ; -- Choice _ _ -> Incomplete (mplus r' i) ; Incomplete j -> Incomplete (mplus i j) '(define mplus (lambda (r f) (case-ans r (incomplete-f f) ((a) (choice a f)) ((a f^) (choice a (lambdaf@ () (mplus1 (f) f^)))) ((i) (case-ans (f) (incomplete-f i) ((b) (choice b i)) ; ((b f^^) (choice b (lambdaf@ () (mplus r f^^)))) ; ((b f^^) (incomplete (choice b (lambdaf@ () (mplus r f^^))))) ; ((b f^^) (incomplete (mplus1 (i) f))) ((b f^^) (choice b (lambdaf@ () (mplus1 (i) f^^)))) ; ((b f^^) (choice b (lambdaf@ () (mplus1 (f^^) i)))) ((j) (incomplete (mplus1 (i) j)))) )))) ; We bias towards depth-first: we try 5 steps in depth. If no solution ; is forthcoming, we explore other alternatives... (define mplus (lambda (r f) (mplus-aux 1 r f))) (define mplus-aux (lambda (n r f) (case-ans r (incomplete-f f) ((a) (choice a f)) ((a f^) (choice a (lambdaf@ () (mplus (f) f^)))) ((i) (if (positive? n) (incomplete (mplus-aux (- n 1) (i) f)) (incomplete (case-ans (f) (incomplete-f i) ((b) (choice b i)) ; ((b f^^) (choice b (lambdaf@ () (mplus r f^^)))) ; ((b f^^) (incomplete (choice b (lambdaf@ () (mplus r f^^))))) ((b f^^) (incomplete (mplus (choice b f^^) i))) ; ((b f^^) (choice b (lambdaf@ () (mplus1 (i) f^^)))) ; ((b f^^) (choice b (lambdaf@ () (mplus1 (f^^) i)))) ((j) (mplus (i) j))) )))))) ; (define mplus ; (lambda (r f) ; ;(cout "r:" (lambda () (write r))nl) ; (case-ans r ; (incomplete-f f) ; ((a) (choice a f)) ; ((a f^) (choice a ; (lambdaf@ () (mplus (f) f^)))) ; ((i) (incomplete (mplus (f) i)))))) ; (define mplus1 ; (lambda (r f) ; (case-ans r ; (incomplete-f f) ; ((a) (choice a f)) ; ((a f^) (choice a ; (lambdaf@ () (mplus1 (f) f^)))) ; ((i) (case-ans (f) ; (incomplete-f i) ; ((b) (choice b i)) ; ; ((b f^^) (choice b (lambdaf@ () (mplus1 r f^^)))) ; ; ((b f^^) (incomplete (choice b (lambdaf@ () (mplus1 r f^^))))) ; ((b f^^) (incomplete (mplus1 (choice b f^^) i))) ; ; ((b f^^) (incomplete (choice b (lambdaf@ () (mplus1 (i) f^^))))) ; ; ((b f^^) (choice b (lambdaf@ () (interleave (f^^) i)))) ; ((j) (incomplete (mplus1 (i) j)))) ; )))) (define interleave mplus) ; interleave :: Ans a -> (() -> Ans a) -> Ans a ; interleave r f = ; case r of ; Zero -> Incomplete f ; Unit a -> Choice a f ; Choice a f' -> Choice a (\() -> interleave (f ()) f') ; The last step is the rotation of the tree ; ; The algebra of incomplete: from SRIReif.hs ; compose_trees' HZero r = return $ Incomplete r ; compose_trees' (HOne a) r = return $ HChoice a r ; -- Note that we do interleave here! ; compose_trees' (HChoice a r') r = ; return $ HChoice a (compose_trees r r') ; -- t1 was incomplete. Now try t2 ; compose_trees' (Incomplete r) t2 = ; do { t2v <- t2; return $ compose_trees'' r t2v } ; compose_trees'' r HZero = Incomplete r ; compose_trees'' r (HOne a) = HChoice a r ; -- Note that we do interleave here! ; compose_trees'' r (HChoice a r') = HChoice a (compose_trees r' r) ; -- Both tree are incomplete. Suspend ; compose_trees'' r (Incomplete t2) = Incomplete (compose_trees r ; t2) ; aka interleave-reset ; (define interleave-reset ; (lambda (r f) ; (case-ans r ; (incomplete-f f) ; ((a) (choice a f)) ; ((a f^) (choice a ; (lambdaf@ () (interleave (f) f^)))) ; ((i) ; (case-ans (f) ; (incomplete-f i) ; ((b) (choice b i)) ; ; ((b f^^) (incomplete (interleave (i) f))) ; ; ((b f^^) ; ; (case-ans (i) ; ; (choice b f^^) ; ; ((a1) (choice a1 (lambdaf@ () ; ; (choice b f^^)))) ; ; ((a1 f^1) (choice a1 (lambdaf@ () ; ; (choice b ; ; (lambdaf@ () (interleave (f^1) f^^)))))) ; ; ((i1) (choice b (lambdaf@ () (interleave (i1) f^^)))))) ; ((b f^^) (choice b (lambdaf@ () (interleave (i) f^^)))) ; ; ((b f^^) (choice b (lambdaf@ () (interleave (f^^) i)))) ; ((j) (incomplete (interleave (i) j))))) ; ))) ; (define interleave ;-shift ; (lambda (r f) ; (case-ans r ; (incomplete-f f) ; ((a) (choice a f)) ; ((a f^) (choice a ; (lambdaf@ () (interleave (f) f^)))) ; ((i) ; (case-ans (f) ; (incomplete-f i) ; ((b) (choice b i)) ; ((b f^^) (incomplete (interleave (choice b f^^) i))) ; ((j) (incomplete (interleave (i) j))))) ; ))) ; Kanren implementation (define succeed (lambdag@ (s) (unit s))) (define fail (lambdag@ (s) (mzero))) (define-syntax run* (syntax-rules () ((_ (x) g0 g ...) (let ((x (var 'x))) (rn x (all g0 g ...) prefix*))))) (define rn (lambda (x g filter) (map (lambda (s) (reify x s)) (filter (g empty-s))))) (define-syntax run (syntax-rules () ((_ n^ (x) g0 g ...) (let ((x (var 'x)) (n n^)) (cond ((zero? n) (quote ())) (else (rn x (all g0 g ...) (prefix n)))))))) (define-syntax run-1 (syntax-rules () ((_ n^ depth (x) g0 g ...) (let ((x (var 'x)) (n n^)) (cond ((zero? n) (quote ())) (else (rn x (all g0 g ...) (prefix-1 depth n)))))))) ; Converting streams to lists (define prefix* (lambda (r) (case-ans r (quote ()) ((v) (cons v (quote ()))) ((v f) (cons v (prefix* (f)))) ((i) (prefix* (i))) ))) (define prefix (lambda (n) (lambda (r) (case-ans r (quote ()) ((s) (cons s (quote ()))) ((s f) (cons s (cond ((= n 1) (quote ())) (else ((prefix (- n 1)) (f)))))) ((i) ((prefix n) (i))) )))) ; depth-limited: essentially the engine (define prefix-1 (lambda (depth n) (lambda (r) (case-ans r (quote ()) ((s) (cons s (quote ()))) ((s f) (cons s (cond ((= n 1) (quote ())) (else ((prefix-1 depth (- n 1)) (f)))))) ((i) (if (positive? depth) ((prefix-1 (- depth 1) n) (i)) '())) ; out of depth... return something else? )))) ; Kanren combinators (define-syntax all (syntax-rules () ((_) succeed) ((_ g) g) ((_ g0 g ...) (let ((g^ g0)) (lambdag@ (s) (bind (g^ s) (lambdag@ (s) ((all g ...) s)))))))) (define == (lambda (v w) (lambdag@ (s) (cond ((unify v w s) => succeed) (else (fail s)))))) (define ==-check (lambda (v w) (lambdag@ (s) (cond ((unify-check v w s) => succeed) (else (fail s)))))) (define-syntax fresh (syntax-rules () ((_ (x ...) g0 g ...) (lambdag@ (s) (let ((x (var 'x)) ...) ((all g0 g ...) s)))))) (define-syntax project (syntax-rules () ((_ (x ...) g0 g ...) (lambdag@ (s) (let ((x (walk* x s)) ...) ((all g0 g ...) s)))))) (define-syntax conde (syntax-rules () ((_ c ...) (c@ mplus c ...)))) (define-syntax condi (syntax-rules () ((_ c ...) (c@ interleave c ...)))) (define-syntax c@ (syntax-rules (else) ((_ combine) fail) ((_ combine (else g ...)) (all g ...)) ((_ combine (g ...) c ...) (let ((g^ (all g ...))) (lambdag@ (s) (combine (g^ s) (lambdaf@ () ((c@ combine c ...) s)))))))) (define-syntax chop1 (syntax-rules () ((chop1 r s) (succeed s)))) (define-syntax condu (syntax-rules () ((_ c ...) (c1 chop1 c ...)))) (define-syntax chopo (syntax-rules () ((chopo r s) r))) (define-syntax conda (syntax-rules () ((_ c ...) (c1 chopo c ...)))) ; for committed choice, wait until incomplete is completed (define-syntax c1 (syntax-rules (else) ((_ chop) fail) ((_ chop (else g ...)) (all g ...)) ((_ chop (g0 g ...) c ...) (let ((g^ g0)) (lambdag@ (s) (let loop ((r (g^ s))) (case-ans r (incomplete ((c1 chop c ...) s)) ; g0 failed ((s) ((all g ...) s)) ; g0 is deterministic ((s f) ; at least one answer from g0 (bind (chop r s) (lambdag@ (s) ((all g ...) s)))) ((i) (incomplete (loop (i)))) ; need at least one asnwer... ))))))) (define-syntax alli (syntax-rules () ((_) succeed) ((_ g) g) ((_ g0 g ...) (let ((g^ g0)) (lambdag@ (s) (bindi (g^ s) (lambdag@ (s) ((alli g ...) s)))))))) ; (define-syntax alli1 ; (syntax-rules () ; ((_) succeed) ; ((_ g) g) ; ((_ g0 g ...) ; (let ((g^ g0)) ; (lambdag@ (s) (bindi1 (g^ s) (lambdag@ (s) ((alli1 g ...) ; s)))))))) (define bindi bind) ; '(define bindi ; (lambda (r k) ; (case-ans r ; (mzero) ; ((a) (k a)) ; ((a f) (interleave-reset (k a) ; (lambdaf@ () (bindi (f) k)))) ; ((i) (incomplete (bindi (i) k))) ; ))) ; (define bindi1 ; (lambda (r k) ; (case-ans r ; (mzero) ; ((a) (k a)) ; ((a f) (interleave (k a) ; (lambdaf@ () (bindi1 (f) k)))) ; ((i) (incomplete (bindi1 (i) k))) ; ))) ; Just the lambda... (define-syntax lambda-limited (syntax-rules () ((_ n formals g) (lambda formals g)))) ; (define-syntax allw ; (syntax-rules () ; ((_) succeed) ; ((_ g) g) ; ((_ g1 g2) (allw-1 g1 g2)) ; ((_ g0 g1 g2 ...) (allw (allw g0 g1) g2 ...)))) ; (define allw-1 ; (lambda (g1 g2) ; (fresh (choice failed) ; (all ; (oracle g1 g2 failed choice) ; (condu ; ((== #t failed) fail) ; ((== #t choice) (alli g1 g2)) ; ((== #f choice) (alli g2 g1))))))) ; ;;; If 'g' succeeds or fails, then (terminates failed g) succeeds, ; ;;; and in the process sets failed to #t if g fails and sets failed ; ;;; to #f if g succeeds, but without extending the substitution. ; ;;; If 'g' diverges, (terminates failed g) diverges. ; (define oracle ; (lambda (g1 g2 failed choice) ; (once ; (condi ; ((terminates failed (alli g1 g2)) (== #t choice)) ; ((terminates failed (alli g2 g1)) (== #f choice)))))) ; (define terminates ; (lambda (failed g) ; (condu ; ((succeeds ; (condu ; [g succeed] ; [else fail])) ; (== #f failed)) ; (else (== #t failed))))) ; (define succeeds ; (lambda (g) ; (fails (fails g)))) ; (define fails ; (lambda (g) ; (condu [g fail] [else succeed]))) (define once (lambda (g) (condu (g succeed) (else fail)))) (define (yield) #f)
true
e2f61b235ac434760f050a15cc26dd9d31f42436
2b96d7fcc558af35d4ab13cd9099a7d0c662773d
/sample/mandelbrot.scm
7458730130238ffe32695527f2585b8f688274b2
[]
no_license
xrk7j2/bmp
b93713b395cfc9de79ed19b51a3cdb231c9a7358
bfdc83eb6b143ad0863cad1b69f01b6805cfde39
refs/heads/master
2016-09-03T07:41:38.009450
2012-11-06T11:29:46
2012-11-06T11:29:46
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,648
scm
mandelbrot.scm
(include "../syntax.scm") (define (fl-square x) (fl* x x)) (define (offset dim min pixel-dim) (fl+ min (fl* (fl+ (exact->inexact dim) 0.5) pixel-dim))) (define (mandelbrot width height x-min x-max y-min y-max verbose?) (let ((image (make-image width height)) (delta-x (- x-max x-min)) (delta-y (- y-max y-min))) (let ((pixel-width (/ delta-x width 1.0)) (pixel-height (/ delta-y height 1.0))) (for h 0 (dec height) (when verbose? (cerr (inc h) "/" height return)) (for w 0 (dec width) (check-pixel! image w h x-min y-min pixel-width pixel-height)))) image)) (define make-gray-pixel (let ((tab (make-table))) (lambda (intensity) (or (table-ref tab intensity #f) (let ((pix (pixel intensity (* intensity 3) (* intensity 4)))) (table-set! tab intensity pix) pix))))) (define (check-pixel! image w h x-min y-min pixel-width pixel-height) (let ((cx (offset w x-min pixel-width)) (cy (offset h y-min pixel-height))) (let loop ((zx 0.) (zy 0.) (counter 0)) (if (fx> counter 63) (set-pixel! image w h black) (let ((zx (fl+ (fl- (fl-square zx) (fl-square zy)) cx)) (zy (fl+ (fl* 2. zx zy) cy))) (if (fl> (fl+ (fl-square zx) (fl-square zy)) 4.) (set-pixel! image w h (make-gray-pixel counter)) (loop zx zy (inc counter)))))))) (define (whole-mandelbrot w h) (mandelbrot w h -1.8 .7 -1.2 1.2))
false
4a36940773bcf6f7e642a95c7b9e87763f631e7f
3ecee09e72582189e8a4a48b3d85447c7927142f
/static/now/std__build-config.scm
942aac5eae2badbdb41da59449898af5dd5854ba
[ "MIT" ]
permissive
drewc/gx-quasar
6c745b9ec13c60ab6d1af8964a25ff14ceb4549b
17513967f611d46cc2d5a44999c90a7891e5d2d0
refs/heads/main
2023-02-02T17:01:12.011714
2020-12-18T22:18:19
2020-12-18T22:18:19
310,720,698
1
0
null
null
null
null
UTF-8
Scheme
false
false
434
scm
std__build-config.scm
(declare (block) (standard-bindings) (extended-bindings)) (begin (define std/build-config#config-enable-libxml '#f) (define std/build-config#config-enable-libyaml '#f) (define std/build-config#config-enable-zlib '#t) (define std/build-config#config-enable-sqlite '#t) (define std/build-config#config-enable-mysql '#f) (define std/build-config#config-enable-lmdb '#f) (define std/build-config#config-enable-leveldb '#f))
false
cf93fa3996734e8f8880b51f93b895afe931bdd7
4890b89d4e190ad152c26f5f1565d1157c0972e7
/Compiler/expose-basic-blocks.ss
6adff896dec4deb40ba24c353e66c32b4eb995e5
[]
no_license
haskellstudio/p-423-Compiler
e2791bae1b966cd1650575e39eef10b4c7205ca1
36be558647ecd5786b02df42865d0ffa2a57fa2f
refs/heads/master
2021-01-25T13:11:49.825526
2017-11-09T03:48:00
2017-11-09T03:48:00
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,459
ss
expose-basic-blocks.ss
(library (Compiler expose-basic-blocks) (export expose-basic-blocks) (import (chezscheme) (Framework helpers) (Framework match)) (define-who expose-basic-blocks (define Tail (lambda (x) (match x [(if ,pred ,[conseq cb*] ,[altern ab*]) (let ([clab (unique-label 'c)] [alab (unique-label 'a)]) (let-values ([(pred pb*) (Pred pred clab alab)]) (values pred `(,pb* ... [,clab (lambda () ,conseq)] ,cb* ... [,alab (lambda () ,altern)] ,ab* ...))))] [(begin ,effect* ... ,[tail tb*]) (let-values ([(x xb*) (Effect* effect* `(,tail))]) (values x `(,xb* ... ,tb* ...)))] [(,triv) (values `(,triv) '())] [,x (error who "invalid Tail ~s" x)]))) (define Pred (lambda (x tlab flab) (match x [(true) (values `(,tlab) '())] [(false) (values `(,flab) '())] [(if ,pred ,[conseq cb*] ,[altern ab*]) (let ([clab (unique-label 'c)] [alab (unique-label 'a)]) (let-values ([(pred pb*) (Pred pred clab alab)]) (values pred `(,pb* ... [,clab (lambda () ,conseq)] ,cb* ... [,alab (lambda () ,altern)] ,ab* ...))))] [(begin ,effect* ... ,[pred pb*]) (let-values ([(x xb*) (Effect* effect* `(,pred))]) (values x `(,xb* ... ,pb* ...)))] [(,relop ,triv1 ,triv2) (values `(if (,relop ,triv1 ,triv2) (,tlab) (,flab)) '())] [,x (error who "invalid Pred ~s" x)]))) (define Effect* (lambda (x* rest*) (match x* [() (values (make-begin rest*) '())] [(,x* ... ,x) (Effect x* x rest*)]))) (define Effect (lambda (x* x rest*) (match x [(nop) (Effect* x* rest*)] [(set! ,lhs ,rhs) (Effect* x* `((set! ,lhs ,rhs) ,rest* ...))] [(if ,pred ,conseq ,altern) (let ([clab (unique-label 'c)] [alab (unique-label 'a)] [jlab (unique-label 'j)]) (let-values ([(conseq cb*) (Effect '() conseq `((,jlab)))] [(altern ab*) (Effect '() altern `((,jlab)))] [(pred pb*) (Pred pred clab alab)]) (let-values ([(x xb*) (Effect* x* `(,pred))]) (values x `(,xb* ... ,pb* ... [,clab (lambda () ,conseq)] ,cb* ... [,alab (lambda () ,altern)] ,ab* ... [,jlab (lambda () ,(make-begin rest*))])))))] [(begin ,effect* ...) (Effect* `(,x* ... ,effect* ...) rest*)] [(return-point ,rp-label ,[Tail -> tail b*]) (let-values ([(eexpr ebinds) (Effect* x* `(,tail))]) (values eexpr `(,ebinds ... [,rp-label (lambda () ,(make-begin rest*))])))] [,x (error who "invalid Effect ~s" x)]))) (lambda (x) (match x [(letrec ([,label* (lambda () ,[Tail -> tail* b**])] ...) ,[Tail -> tail b*]) `(letrec ([,label* (lambda () ,tail*)] ... ,b** ... ... ,b* ...) ,tail)] [,x (error who "invalid Program ~s" x)]))) )
false
eb6b90013caa77c6f4d11a35575c06a7b20021ac
b30896ca57a43c4c788dbb89de6ffa32c5d29338
/web-support.scm
b7d62908ffa3597655f30f30a2a2a0463a0c67ce
[ "MIT" ]
permissive
alokthapa/leftparen
1820b543fe28a15bd649f228bf8c17d88e5f7f62
dd0ac601763bf80ab4e21b4951d152553d26e189
refs/heads/master
2021-01-09T05:36:02.280732
2009-01-12T16:51:04
2009-01-12T16:51:04
120,912
1
0
null
null
null
null
UTF-8
Scheme
false
false
9,159
scm
web-support.scm
#lang scheme/base ;; This differs from web-export.ss in that these are ones that we wrote and aren't ;; included in PLT libs. (require (file "util.scm") xml net/url scheme/serialize "web-export.ss" "contract-lp.ss" ) (provide request-all-bindings ;; final-prep-of-response (via contract) xexpr->de-grouped-xexprs wrap-each-in-list wrap-each-in-list-with-attrs redirect-to web-link img raw-str basic-response xexpr-if url+query url->string get-url bindings/string find-binding ;; list-response (via contract) response-promise? ;; single-response-promise-in-list (via contract) ;; single-response/full-in-list (via contract) ;; response-promise-to-redirect (via contract) ;; response-from-promise (via contract) ) ;; ;; list-response ;; (define (any-responses? lst) (any (lambda (elt) (or (response/full? elt) (response/incremental? elt) (response/basic? elt))) lst)) (provide/contract (list-response (->* ;; required ((not/c any-responses?)) ;; optional (#:type bytes? #:extras list?) ;; returns response?))) ;; (define (list-response content-lst #:type (type #"text/html") #:extras (extras '())) (basic-response (append-map (lambda (content) (map xexpr->string (xexpr->de-grouped-xexprs content))) content-lst) #:type type #:extras extras)) (define (basic-response content-lst #:type (type #"text/html") #:extras (extras '())) ;; right now we always no-cache. we'll probably eventually want something more ;; subtle. (let ((no-cache (make-header #"Cache-Control" (string->bytes/utf-8 "no-cache;")))) (make-response/full 200 "all good" (current-seconds) type (cons no-cache extras) content-lst))) (define-serializable-struct binding/string (id)) (define-serializable-struct (binding/string:form binding/string) (value)) (define-serializable-struct (binding/string:file binding/string) (filename content)) (provide/contract [struct binding/string ([id string?])] [struct (binding/string:form binding/string) ([id string?] [value string?])] [struct (binding/string:file binding/string) ([id string?] [filename string?] [content bytes?])]) (define (bindings/string req [localization-function bytes->string/utf-8]) (map (lambda (binding) (if (binding:form? binding) (make-binding/string:form (localization-function (binding-id binding)) (localization-function (binding:form-value binding))) (make-binding/string:file (localization-function (binding-id binding)) (localization-function (binding:file-filename binding)) (binding:file-content binding)))) (request-bindings/raw req))) (define (find-binding field bindings) ; strait from request-struct.ss (match bindings [(list) #f] [(list-rest (and b (struct binding/string (i))) bindings) (if (string=? field i) b (find-binding field bindings))])) ;; if you are doing a post, this gives you post and get vars. if a get, it's just reg. (define (request-all-bindings req) (append (request-bindings req) (if (request-post-data/raw req) ; there a better way to check if it's a post? (url-query (request-uri req)) '()))) (define (group-tag? xexpr) (match xexpr ((list-rest 'group children) #t) (else #f))) (define (xexpr->de-grouped-xexprs xexpr) (cond ((not xexpr) '()) ((not (list? xexpr)) (list xexpr)) ; non-xexpr response case ((group-tag? xexpr) (append-map xexpr->de-grouped-xexprs (rest xexpr))) (else (receive (tag attrs children) (xexpr->tag*attrs*children xexpr) (list (create-xexpr tag attrs (append-map xexpr->de-grouped-xexprs children))))))) (define (attrs? thing) (and (list? thing) (or (empty? thing) (not (symbol? (first thing)))))) (define (create-xexpr tag attrs children) (if (empty? attrs) `(,tag ,@children) `(,tag ,attrs ,@children))) (define (xexpr->tag*attrs*children xexpr) (let ((tag (first xexpr)) (but-tag (rest xexpr))) (if (empty? but-tag) (values tag '() '()) (let ((next (first but-tag))) (if (attrs? next) (values tag next (rest but-tag)) (values tag '() but-tag)))))) ;; the wrap-each-in* fns filter out #f values from elts: (define (wrap-each-in-list tag elts) (filter-map (lambda (e) (and e `(,tag ,e))) elts)) (define (wrap-each-in-list-with-attrs tag attrs elts) (filter-map (lambda (e) (and e `(,tag ,attrs ,e))) elts)) (define (web-link label url #:class (class #f) #:extra-attrs (extra-attrs '())) `(a ((href ,(if (string? url) url (url->string url))) ,@(append (if class `((class ,class)) '()) extra-attrs)) ,label)) ;; image-file is relative to /i/ (define (img image-file #:class (class #f)) `(img ((src ,(string-append "/i/" image-file)) (border "0") ,@(splice-if class `(class ,class))))) (define (raw-str str) (make-cdata #f #f str)) ;; ;; xexpr-if ;; ;; Use if you only want to create an xexpr if a condition is true. E.g., ;; (ul (li "Item 1") ,(xexpr-if (= 2 2) `(li "Item 2"))) ;; (define-syntax xexpr-if (syntax-rules () ((_ test) (or test "")) ((_ test body ...) (if test (begin body ...) "")))) ;; ;; url+query ;; ;; query-alist is ((key . str) ...) ;; given query strs should *not* be url encoded (this will be done by url+query). ;; (define (url+query url-str query-alist) (let ((tmp-url (string->url url-str))) (make-url (url-scheme tmp-url) (url-user tmp-url) (url-host tmp-url) (url-port tmp-url) (url-path-absolute? tmp-url) (url-path tmp-url) (append (url-query tmp-url) query-alist) (url-fragment tmp-url)))) ;; ;; get-url ;; ;; exn-handler: exn -> any ;; (define (get-url url port-handler #:exn-handler (exn-handler #f)) (let ((thunk (lambda () (call/input-url (if (url? url) url (string->url url)) get-pure-port port-handler)))) (if exn-handler (with-handlers ((exn:fail:network? exn-handler)) (thunk)) (thunk)))) (define-struct response-promise (fn)) ;; ;; response-promise-to-redirect ;; ;; A relatively low-level tool for "promising" to construct a redirect response. The issue ;; is that at the time we know we want to redirect, we don't necessarily know all the ;; headers that we might want to go into the redirect response. For example, a cookie ;; may need to be set on the client. Response promises can never make it to the top-level ;; (the web server), since they are a LeftParen concept only. Thus, the promises must ;; be "response-from-promise"'d before that happens. ;; (provide/contract (response-promise-to-redirect (-> string? response-promise?))) ;; (define (response-promise-to-redirect redirect-to-uri) (make-response-promise (lambda (#:headers (h '())) (redirect-to redirect-to-uri #:headers h)))) ;; ;; response-from-promise ;; (provide/contract (response-from-promise (->* (response-promise?) (#:headers (listof header?)) response?))) ;; (define (response-from-promise r-p #:headers (headers '())) ((response-promise-fn r-p) #:headers headers)) ;; ;; single-response-promise-in-list ;; (provide/contract (single-response-promise-in-list (-> (listof any/c) (or/c #f response-promise?)))) ;; (define (single-response-promise-in-list lst) (and-let* (((and (length= lst 1))) (elt (first lst)) ((response-promise? elt))) elt)) ;; ;; single-response/full-in-list ;; (provide/contract (single-response/full-in-list (-> (listof any/c) (or/c #f response/full?)))) ;; (define (single-response/full-in-list lst) (and-let* (((and (length= lst 1))) (elt (first lst)) ((response/full? elt))) elt)) ;; ;; final-prep-of-response ;; (provide/contract (final-prep-of-response (-> (or/c response? response-promise?) response?))) ;; (define (final-prep-of-response response-or-promise) (if (response-promise? response-or-promise) (response-from-promise response-or-promise) (let ((result (xexpr->de-grouped-xexprs response-or-promise))) (if (and (length= result 1) (response? (first result))) (first result) (list-response result)))))
true
4a1b0ad82341139da467898f9a6871b97b1ecaa5
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
/example/socket/echo.scm
0a6390080af3a6ac1a35b25146e2935c6394c093
[ "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "MIT", "BSD-2-Clause" ]
permissive
ktakashi/sagittarius-scheme
0a6d23a9004e8775792ebe27a395366457daba81
285e84f7c48b65d6594ff4fbbe47a1b499c9fec0
refs/heads/master
2023-09-01T23:45:52.702741
2023-08-31T10:36:08
2023-08-31T10:36:08
41,153,733
48
7
NOASSERTION
2022-07-13T18:04:42
2015-08-21T12:07:54
Scheme
UTF-8
Scheme
false
false
2,808
scm
echo.scm
;;; -*- scheme -*- ;;; ;;; echo.scm: simple echo server for sample ;;; ;;; Copyright (c) 2000-2011 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. ;;; ;; import socket library (import (sagittarius socket)) ;; creates echo server socket with port number 5000 (define echo-server-socket (make-server-socket "5000")) ;; addr is client socket (let loop ((addr (socket-accept echo-server-socket))) (call-with-socket addr (lambda (sock) ;; socket-port creates binary input/output port ;; make it transcoded port for convenience. (let ((p (transcoded-port (socket-port sock) ;; on Sagittarius Scheme native-transcoder ;; uses utf8 codec for ASCII compatibility. ;; For socket programming it might be better ;; to specify eol-style with crlf. ;; But this sample just shows how it goes. (native-transcoder)))) (call-with-port p (lambda (p) (put-string p "please type something\n\r") (put-string p "> ") ;; gets line from client. (let lp2 ((r (get-line p))) (unless (eof-object? r) (print "received: " r) ;; just returns message from client. ;; NB: If client type nothing, it'll throw assertion-violation. (put-string p r) (put-string p "\r\n> ") ;; waits for next input. (lp2 (get-line p))))))))) ;; echo server waits next connection. (loop (socket-accept echo-server-socket)))
false
1b879eeb3792ba3d0ceacc5c994fac1ca426c107
98fd12cbf428dda4c673987ff64ace5e558874c4
/sicp/v1/chapter-2.3/inaimathi-2.3.1.scm
c83920ba78706e4ffd361d2dab045d5b4f03faed
[ "Unlicense" ]
permissive
CompSciCabal/SMRTYPRTY
397645d909ff1c3d1517b44a1bb0173195b0616e
a8e2c5049199635fecce7b7f70a2225cda6558d8
refs/heads/master
2021-12-30T04:50:30.599471
2021-12-27T23:50:16
2021-12-27T23:50:16
13,666,108
66
11
Unlicense
2019-05-13T03:45:42
2013-10-18T01:26:44
Racket
UTF-8
Scheme
false
false
726
scm
inaimathi-2.3.1.scm
;;; 2.53 (list 'a 'b 'c) > (a b c) (list (list 'george)) > ((george)) (cdr '((x1 y1) (x2 y2))) > ((x2 y2)) (cadr '((x1 y1) (x2 y2))) > (x2 y2) (pair? (car '(a short list))) > #f (memq 'red '((red shoes) (blue socks))) > #f (memq 'red '(red shoes blue socks)) > #t ;;; 2.54 (define (my-equal? a b) (or (and (symbol? a) (symbol? b) (eq? a b)) (and (my-equal? (car a) (car b)) (my-equal? (cdr a) (cdr b))))) ;;; 2.55 (car ''abracadabra) ;; apply read macros (car (quote (quote abracadabra))) ;; apply special forms; the first quote supresses evaluation on the second, which becomes an element of a list. ;; basically (car ('quote 'abracadabra)) ;; finally, take the car of that two-element list quote
false
dcb72b8826524d83efcbce69bf982815821809ee
00466b7744f0fa2fb42e76658d04387f3aa839d8
/sicp/chapter2/2.5/generic-ops/tests/coerse-test.scm
dfca8c717303c8ba83f7a42266a1ba6adbefa9c3
[ "WTFPL" ]
permissive
najeex/stolzen
961da2b408bcead7850c922f675888b480f2df9d
bb13d0a7deea53b65253bb4b61aaf2abe4467f0d
refs/heads/master
2020-09-11T11:00:28.072686
2015-10-22T21:35:29
2015-10-22T21:35:29
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,666
scm
coerse-test.scm
#lang scheme (require rackunit) (require rackunit/text-ui) (require "../coerce.scm") (require "../generic-operations.scm") (require "../complex-numbers.scm") (require "../install-modules.scm") (require "../rational-numbers.scm") (define coerse-test-suite (test-suite "Coerse test suite" (check-equal? (get-index 'complex inheritance-indexes) 0 "Complex is the zeroth in the tower") (check-equal? (get-index 'rational inheritance-indexes) 1 "Rational is the first if the tower") (check-equal? (get-index 'scheme-number inheritance-indexes) 2 "Scheme-numer is the last in the tower") (check-equal? (get-type 0 inheritance-indexes) 'complex "zeroth element of the tower is complex") (check-equal? (get-type 1 inheritance-indexes) 'rational "First element of the tower is rational") (check-equal? (get-type 2 inheritance-indexes) 'scheme-number "Second element of the tower is scheme-numer") (check-equal? (find-superest-parent '(scheme-number scheme-number rational) inheritance-indexes) 'rational "in (scheme-number scheme-number rational) rational is superest") (check-equal? (find-superest-parent '(scheme-number scheme-number scheme-number) inheritance-indexes) 'scheme-number "in (scheme-number scheme-number scheme-number) scheme-number is superest") (check-equal? (find-superest-parent '(scheme-number complex rational) inheritance-indexes) 'complex "in (scheme-number complex rational) complex is the superest") (check-equal? (calc-distance 'complex 'complex inheritance-indexes) 0 "Distance between complex and complex is 0") (check-equal? (calc-distance 'complex 'rational inheritance-indexes) 1 "Distance between complex and rational is 1") (check-equal? (calc-distance 'complex 'scheme-number inheritance-indexes) 2 "Distance between complex and scheme-number is 2") (check-equal? (distances '(complex rational scheme-number) inheritance-indexes) '(0 1 2) "for (complex rational scheme-number) distances are (0 1 2)") (check-equal? (distances '(complex complex complex) inheritance-indexes) '(0 0 0) "for all complex numbers all distances are 0") (check-equal? (distances '(scheme-number scheme-number scheme-number) inheritance-indexes) '(0 0 0) "for all scheme-numbers all the distances are 0") (check-equal? (raise-times 1 0) 1 "Number raised 0 times still number") (check-equal? (raise-times 1 1) (make-rational 1 1) "Number raised 1 times is rational") (check-equal? (raise-times 1 2) (make-complex-from-real-imag (make-rational 1 1) 0) "Number raised 2 times is complex") (check-equal? (raise-seq (list 1 (make-complex-from-real-imag 2 2)) '(2 0)) (list (make-complex-from-real-imag (make-rational 1 1) 0) (make-complex-from-real-imag 2 2)) "Raising pairs") (check-equal? (coerce (list (make-complex-from-real-imag 1 2) (make-complex-from-real-imag 2 2)) inheritance-indexes) (list (make-complex-from-real-imag 1 2) (make-complex-from-real-imag 2 2)) "Coerse on same types yields same types") )) (run-tests coerse-test-suite)
false
c902b7e230713dac9c0593886e65644073b3d02a
df0ba5a0dea3929f29358805fe8dcf4f97d89969
/exercises/software-engineering/03/double.scm
2d476905e83a265d3eac3d236a7d8f8f4cd8440e
[ "MIT" ]
permissive
triffon/fp-2019-20
1c397e4f0bf521bf5397f465bd1cc532011e8cf1
a74dcde683538be031186cf18367993e70dc1a1c
refs/heads/master
2021-12-15T00:32:28.583751
2021-12-03T13:57:04
2021-12-03T13:57:04
210,043,805
14
31
MIT
2019-12-23T23:39:09
2019-09-21T19:41:41
Racket
UTF-8
Scheme
false
false
400
scm
double.scm
(define (double f) (lambda (x) (f (f x)))) (load "../testing/check.scm") (define (1+ x) (+ x 1)) (define (square x) (* x x)) (check ((double 1+) 0) => 2) (check ((double square) 2) => 16) (check ((double (double 1+)) 0) => 4) (check (((double double) 1+) 0) => 4) (check (((double (double double)) 1+) 0) => 16) (check (((double (double double)) 1+) 5) => 21) (check-report) (check-reset!)
false
1efc536d34a6dbc096e80d28647e78168b11eace
ce567bbf766df9d98dc6a5e710a77870753c7d29
/ch6/13.scm
b91ee93ff14731f933e38be1ef32bce2ffedd73b
[]
no_license
dott94/eopl
1cbe2d98c948689687f88e514579e66412236fc9
47fadf6f2aa6ca72c831d6e2e2eccbe673129113
refs/heads/master
2021-01-18T06:42:35.921839
2015-01-21T07:06:43
2015-01-21T07:06:43
30,055,972
1
0
null
2015-01-30T04:21:42
2015-01-30T04:21:42
null
UTF-8
Scheme
false
false
2,471
scm
13.scm
(load-relative "../libs/init.scm") (load-relative "./base/test.scm") (load-relative "./base/cps.scm") (load-relative "./base/data-structures.scm") (load-relative "./base/cps-lang.scm") (load-relative "./base/cps-cases.scm") ;; Translate each of these expressions in CPS-IN into continuation-passing ;; style using the CPS recipe on page 200 above. Test your transformed ;; programs by running them using the interpreter of figure 6.6. ;; Be sure that the original and transformed versions give the same answer ;; on each input. ;; finish this need to add some types into the interpreter, such as list, ;; cdr, null? number? etc, this will need too much work. ;; This exercise is one level? really? ;; Let me solve it in scheme as an example. (define removeall (lambda (n lst) (if (null? lst) lst ;; this is different with example (if (list? (car lst)) (cons (removeall n (car lst)) (removeall n (cdr lst))) (if (equal? n (car lst)) (removeall n (cdr lst)) (cons (car lst) (removeall n (cdr lst)))))))) ;; give some testcases (removeall 1 '(1)) ;; ==> () (removeall 1 '(1 2 3)) ;; ==> (2 3) (removeall 3 '(1 2 2)) ;; ==> (1 2 2) (removeall 3 '(1 3 3)) ;; ==> (1) ;; OK, write a tail form version (define removeall-tail (lambda (n lst) (remove-iter n lst (end-cont)))) (define end-cont (lambda () (lambda (val) (begin (print "end-cont return only one time") val)))) (define apply-cont (lambda (cont val) (cont val))) (define cons1-cont (lambda (elm lst cont) (lambda (val) (remove-iter elm lst (cons2-cont val cont))))) (define cons2-cont (lambda (val2 cont) (lambda (val1) (apply-cont cont (cons val1 val2))))) (define append-cont (lambda (store-val cont) (lambda (val) (apply-cont cont (append (list store-val) val))))) (define remove-iter (lambda (n lst cont) (if (null? lst) (apply-cont cont lst) (if (list? (car lst)) (remove-iter n (car lst) ;; new cont (cons1-cont n (cdr lst) cont)) (let ((now (car lst))) (if (equal? n now) (remove-iter n (cdr lst) cont) (remove-iter n (cdr lst) ;; new cont (append-cont now cont)))))))) (removeall-tail 1 '(1)) ;; ==> () (removeall-tail 1 '(1 2 3)) ;; ==> (2 3) (removeall-tail 3 '(1 2 2)) ;; ==> (1 2 2) (removeall-tail 3 '(1 3 3)) ;; ==> (1) (removeall-tail 0 '(1 2 3 4)) ;; ==> (1 2 3 4) ;; Others left unsolved, :)
false
9cd06c114339a360538d73cf8a2e0217911f6557
6b961ef37ff7018c8449d3fa05c04ffbda56582b
/bbn_cl/mach/cl/package-d.scm
be3a01143bcb2a1082ac61ef0573366bf908b503
[]
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
10,359
scm
package-d.scm
;;; ******** ;;; ;;; Copyright 1992 by BBN Systems and Technologies, A division of Bolt, ;;; Beranek and Newman Inc. ;;; ;;; Permission to use, copy, modify and distribute this software and its ;;; documentation is hereby granted without fee, provided that the above ;;; copyright notice and this permission appear in all copies and in ;;; supporting documentation, and that the name Bolt, Beranek and Newman ;;; Inc. not be used in advertising or publicity pertaining to distribution ;;; of the software without specific, written prior permission. In ;;; addition, BBN makes no respresentation about the suitability of this ;;; software for any purposes. It is provided "AS IS" without express or ;;; implied warranties including (but not limited to) all implied warranties ;;; of merchantability and fitness. In no event shall BBN be liable for any ;;; special, indirect or consequential damages whatsoever resulting from ;;; loss of use, data or profits, whether in an action of contract, ;;; negligence or other tortuous action, arising out of or in connection ;;; with the use or performance of this software. ;;; ;;; ******** ;;; ;;; (proclaim '(insert-touches nil)) (eval-when (compile) (load "package-common.bin") (load "package-a.bin")) ;;; Export -- Public ;;; ;;; (defun export (symbols &optional (package *package*)) "Exports Symbols from Package, checking that no name conflicts result." (let ((package (package-or-lose package)) (syms ())) ;; ;; Punt any symbols that are already external. (dolist (sym (symbol-listify symbols)) (multiple-value-bind (s w) (find-external-symbol (symbol-name sym) package) (declare (ignore s)) (unless (or w (member sym syms)) (push sym syms)))) ;; ;; Find symbols and packages with conflicts. (let ((used-by (package-used-by-list package)) (cpackages ()) (cset ())) (dolist (sym syms) (let ((name (symbol-name sym))) (dolist (p used-by) (multiple-value-bind (s w) (find-symbol name p) (when (and w (not (eq s sym)) (not (member s (package-shadowing-symbols p)))) (pushnew sym cset) (pushnew p cpackages)))))) (when cset (cerror "skip exporting these symbols or unintern all conflicting ones." "Exporting these symbols from the ~A package:~%~S~%~ results in name conflicts with these packages:~%~{~A ~}" (package-name package) cset (mapcar #'package-name cpackages)) (if (y-or-n-p "Unintern all conflicting symbols? ") (dolist (p cpackages) (dolist (sym cset) (moby-unintern sym p))) (setq syms (nset-difference syms cset))))) ;; ;; Check that all symbols are accessible. If not, ask to import them. (let ((missing ()) (imports ())) (dolist (sym syms) (multiple-value-bind (s w) (find-symbol (symbol-name sym) package) (cond ((not (and w (eq s sym))) (push sym missing)) ((eq w :inherited) (push sym imports))))) (when missing (cerror "Import these symbols into the ~A package." "These symbols are not accessible in the ~A package:~%~S" (package-name package) missing) (import missing package)) (import imports package)) ;; ;; And now, three pages later, we export the suckers. (let ((internal (package-internal-symbols package)) (external (package-external-symbols package))) (dolist (sym syms) (nuke-symbol internal (symbol-name sym)) (add-symbol external sym))) t)) ;;; Unexport -- Public ;;; ;;; Check that all symbols are accessible, then move from external to ;;; internal. ;;; (defun unexport (symbols &optional (package *package*)) "Makes Symbols no longer exported from Package." (let ((package (package-or-lose package)) (syms ())) (dolist (sym (symbol-listify symbols)) (multiple-value-bind (s w) (find-symbol (symbol-name sym) package) (cond ((or (not w) (not (eq s sym))) (error "~S is not accessible in the ~A package." sym (package-name package))) ((eq w :external) (pushnew sym syms))))) (let ((internal (package-internal-symbols package)) (external (package-external-symbols package))) (dolist (sym syms) (add-symbol internal sym) (nuke-symbol external (symbol-name sym)))) t)) ;;; Import -- Public ;;; ;;; Check for name conflic caused by the import and let the user ;;; shadowing-import if there is. ;;; (defun import (symbols &optional (package *package*)) "Make Symbols accessible as internal symbols in Package. If a symbol is already accessible then it has no effect. If a name conflict would result from the importation, then a correctable error is signalled." (let ((package (package-or-lose package)) (symbols (symbol-listify symbols)) (syms ()) (cset ())) (dolist (sym symbols) (multiple-value-bind (s w) (find-symbol (symbol-name sym) package) (cond ((not w) (let ((found (member sym syms :test #'string=))) (if found (when (not (eq (car found) sym)) (push sym cset)) (push sym syms)))) ((not (eq s sym)) (push sym cset)) ((eq w :inherited) (push sym syms))))) (when cset (cerror "Import these symbols with Shadowing-Import." "Importing these symbols into the ~A package causes a name conflict:~%~S" (package-name package) cset)) ;; ;; Add the new symbols to the internal hashtable. (let ((internal (package-internal-symbols package))) (dolist (sym syms) (add-symbol internal sym))) ;; ;; If any of the symbols are uninterned, make them be owned by Package. (dolist (sym symbols) (unless (symbol-package sym) (%set-symbol-package! sym package))) (shadowing-import cset package))) ;;; Shadowing-Import -- Public ;;; ;;; If a conflicting symbol is present, unintern it, otherwise just ;;; stick the symbol in. ;;; (defun shadowing-import (symbols &optional (package *package*)) "Import Symbols into package, disregarding any name conflict. If a symbol of the same name is present, then it is uninterned. The symbols are added to the Package-Shadowing-Symbols." (let* ((package (package-or-lose package)) (internal (package-internal-symbols package))) (dolist (sym (symbol-listify symbols)) (multiple-value-bind (s w) (find-symbol (symbol-name sym) package) (unless (and w (not (eq w :inherited)) (eq s sym)) (when (or (eq w :internal) (eq w :external)) ;; ;; If it was shadowed, we don't want Unintern to flame out... (setf (package-shadowing-symbols package) (delete s (the list (package-shadowing-symbols package)))) (unintern s package)) (add-symbol internal sym)) (pushnew sym (package-shadowing-symbols package))))) t) '$split-file ;;; Shadow -- Public ;;; ;;; (defun shadow (symbols &optional (package *package*)) "Make an internal symbol in Package with the same name as each of the specified symbols, adding the new symbols to the Package-Shadowing-Symbols. If a symbol with the given name is already present in Package, then the existing symbol is placed in the shadowing symbols list if it is not already present." (let* ((package (package-or-lose package)) (internal (package-internal-symbols package))) (dolist (sym (symbol-listify symbols)) (let ((name (symbol-name sym))) (multiple-value-bind (s w) (find-symbol name package) (when (or (not w) (eq w :inherited)) (setq s (make-symbol name)) (set-package s package) (add-symbol internal s)) (pushnew s (package-shadowing-symbols package)))))) t) ;;; Use-Package -- Public ;;; ;;; Do stuff to use a package, with all kinds of fun name-conflict ;;; checking. ;;; (defun use-package (packages-to-use &optional (package *package*)) "Add all the Package-To-Use to the use list for Package so that the external symbols of the used packages are accessible as internal symbols in Package." (let ((packages (package-listify packages-to-use)) (package (package-or-lose package))) ;; ;; Loop over each package, use-ing one at a time... (dolist (pkg packages) (unless (member pkg (package-use-list package)) (let ((cset ()) (shadowing-symbols (package-shadowing-symbols package)) (use-list (package-use-list package))) ;; ;; If the number of symbols already accessible is less than the ;; number to be inherited then it is faster to run the test the ;; other way. This is particularly valuable in the case of ;; a new package use-ing Lisp. ;; I deleted the special case code because our implementation ;; does not keep a symbol count - JP 6/23/87 ;; (do-external-symbols (sym pkg) (multiple-value-bind (s w) (find-symbol (symbol-name sym) package) (when (and w (not (eq s sym)) (not (member s shadowing-symbols))) (push s cset)))) (when cset (cerror "The symbols will be replaced by the symbols in ~A~%~ by uninterning the conflicting symbols in ~1*~A." "Use-package of package ~A results in name conflicts for these symbols:~%~S" (package-name pkg) cset (package-name package)) (dolist (s cset) (moby-unintern s package)))) (push pkg (package-use-list package)) (push (package-external-symbols pkg) (cdr (package-tables package))) (push package (package-used-by-list pkg))))) t) ;;; Unuse-Package -- Public ;;; ;;; (defun unuse-package (packages-to-unuse &optional (package *package*)) "Remove Packages-To-Unuse from the use list for Package." (let ((package (package-or-lose package))) (dolist (p (package-listify packages-to-unuse)) (setf (package-use-list package) (delete p (the list (package-use-list package)))) (setf (package-tables package) (delete (package-external-symbols p) (the list (package-tables package)))) (setf (package-used-by-list p) (delete package (the list (package-used-by-list p))))) t)) ;;; Find-All-Symbols -- Public ;;; ;;; (defun find-all-symbols (string-or-symbol) "Return a list of all symbols in the system having the specified name." (let ((string (string string-or-symbol)) (res ())) (mapc #'(lambda (package) (multiple-value-bind (s w) (find-symbol string package) (when w (pushnew s res)))) (list-all-packages)) res))
false
52051d0e94eebcae2fbe2fe07486630b3f4dccac
bec9f0c739a30427f472afb90bd667d56b5d8d0c
/hw/6.ss
1a0a52f70389796bc8b5e1422018f19cd11d5f40
[]
no_license
compuwizard123/CSSE304
d599c820f26476bcda7805a96191ea3b6dc8bf07
2a7bf7f080f99edc837e5193ce2abdb544cfa24d
refs/heads/master
2021-01-16T01:08:06.305879
2011-05-05T02:15:46
2011-05-05T02:15:46
615,614
0
2
null
null
null
null
UTF-8
Scheme
false
false
994
ss
6.ss
; Kevin Risden ; Assignment 6 ; ; #1 (define snlist-recur (lambda (base-value list-proc comb-proc) (letrec ((helper (lambda (ls) (cond [(null? ls) base-value] [(list? (car ls)) (list-proc (helper (car ls)) (helper (cdr ls)))] [else (comb-proc (car ls) (helper (cdr ls)))])))) helper))) ; a (define sn-list-sum (snlist-recur 0 + +)) ; b (define sn-list-map (lambda (f snlist) ((snlist-recur '() (lambda (x y) (cons x y)) (lambda (x y) (cons (f x) y))) snlist))) ; c (define paren-count (snlist-recur 2 + (lambda (x y) y))) ; d (define sn-list-reverse (snlist-recur '() (lambda (x y) (append y (list x))) (lambda (x y) (append y (list x))))) ; e (define sn-list-occur (lambda (s snlist) ((snlist-recur 0 + (lambda (x y) (if (equal? s x) (+ y 1) y))) snlist))) ; f (define depth (snlist-recur 1 (lambda (x y) (+ (max x (- y 1)) 1)) (lambda (x y) y)))
false
62511350464f48fb3260d16176ef5a04765f109d
ae4938300d7eea07cbcb32ea4a7b0ead9ac18e82
/array.ss
4348af211aeee95954552005010db0cc40002699
[]
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
1,751
ss
array.ss
#!r6rs (library (imi array) (export make-array array? array-pos array-ref array-set!) (import (rnrs)) (define (product ls) (fold-left * 1 ls)) ;;; multidimensional array (define-record-type array (fields dimensions contents) (protocol (lambda (new) ;;; dimensions - (listof/c (number>/c 0)) (lambda dimensions (new dimensions (make-vector (product dimensions))))))) ;;; calcs position of an element in a `(length dimensions)` ;;; dimensional matrix with sizes `dimensions` at position ;;; `specs` ;;; ;;; dimensions - (listof/c (number>/c 0)) ;;; position - (listof/c (number>=/c 0)) ;;; -> (number>=/c 0) (define (array-pos dimensions specs) (let calc-pos ([dims dimensions] [specs specs] [dim-size 1] [spec-pos 0]) (cond [(null? dims) spec-pos] [else (calc-pos (cdr dims) (cdr specs) (* dim-size (car dims)) (+ (* (car specs) dim-size) spec-pos))]))) ;;; get an element out of `array` at position `specs` ;;; ;;; array - array? ;;; specs - (listof (number>=/c 0)) ;;; -> any? (define (array-ref array . specs) (vector-ref (array-contents array) (array-pos (array-dimensions array) specs))) ;;; set an element in `array` at position `specs` to `val` ;;; ;;; array - array? ;;; val - any? ;;; specs - (listof (number>=/c 0)) ;;; -> void? (define (array-set! array val . specs) (vector-set! (array-contents array) (array-pos (array-dimensions array) specs) val)) )
false
4c26ba805e247391efce49262040cc23e90e444e
defeada37d39bca09ef76f66f38683754c0a6aa0
/System/system/component-model/design/designtime-license-context.sls
4b82b1df0647a3fa5056e7e7c99c707445d470e9
[]
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,203
sls
designtime-license-context.sls
(library (system component-model design designtime-license-context) (export new is? designtime-license-context? set-saved-license-key get-saved-license-key usage-mode) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.ComponentModel.Design.DesigntimeLicenseContext a ...))))) (define (is? a) (clr-is System.ComponentModel.Design.DesigntimeLicenseContext a)) (define (designtime-license-context? a) (clr-is System.ComponentModel.Design.DesigntimeLicenseContext a)) (define-method-port set-saved-license-key System.ComponentModel.Design.DesigntimeLicenseContext SetSavedLicenseKey (System.Void System.Type System.String)) (define-method-port get-saved-license-key System.ComponentModel.Design.DesigntimeLicenseContext GetSavedLicenseKey (System.String System.Type System.Reflection.Assembly)) (define-field-port usage-mode #f #f (property:) System.ComponentModel.Design.DesigntimeLicenseContext UsageMode System.ComponentModel.LicenseUsageMode))
true
8a7dc6ea63d9f590c6eca1d25857541909869e80
defeada37d39bca09ef76f66f38683754c0a6aa0
/System.Xml/system/xml/xml-entity.sls
c673f51ade5f8ac4f6b6e2ab41479d77c6ca816c
[]
no_license
futsuki/ironscheme-port
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
4e7a81b0fbeac9a47440464988e53fb118286c54
refs/heads/master
2016-09-06T17:13:11.462593
2015-09-26T18:20:40
2015-09-26T18:20:40
42,757,369
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,400
sls
xml-entity.sls
(library (system xml xml-entity) (export is? xml-entity? clone-node write-content-to write-to base-uri inner-text-get inner-text-set! inner-text-update! inner-xml-get inner-xml-set! inner-xml-update! is-read-only? local-name name node-type notation-name outer-xml public-id system-id) (import (ironscheme-clr-port)) (define (is? a) (clr-is System.Xml.XmlEntity a)) (define (xml-entity? a) (clr-is System.Xml.XmlEntity a)) (define-method-port clone-node System.Xml.XmlEntity CloneNode (System.Xml.XmlNode System.Boolean)) (define-method-port write-content-to System.Xml.XmlEntity WriteContentTo (System.Void System.Xml.XmlWriter)) (define-method-port write-to System.Xml.XmlEntity WriteTo (System.Void System.Xml.XmlWriter)) (define-field-port base-uri #f #f (property:) System.Xml.XmlEntity BaseURI System.String) (define-field-port inner-text-get inner-text-set! inner-text-update! (property:) System.Xml.XmlEntity InnerText System.String) (define-field-port inner-xml-get inner-xml-set! inner-xml-update! (property:) System.Xml.XmlEntity InnerXml System.String) (define-field-port is-read-only? #f #f (property:) System.Xml.XmlEntity IsReadOnly System.Boolean) (define-field-port local-name #f #f (property:) System.Xml.XmlEntity LocalName System.String) (define-field-port name #f #f (property:) System.Xml.XmlEntity Name System.String) (define-field-port node-type #f #f (property:) System.Xml.XmlEntity NodeType System.Xml.XmlNodeType) (define-field-port notation-name #f #f (property:) System.Xml.XmlEntity NotationName System.String) (define-field-port outer-xml #f #f (property:) System.Xml.XmlEntity OuterXml System.String) (define-field-port public-id #f #f (property:) System.Xml.XmlEntity PublicId System.String) (define-field-port system-id #f #f (property:) System.Xml.XmlEntity SystemId System.String))
false
383584b6efcafde51c0957b8eb9495928b849929
ae76253c0b7fadf8065777111d3aa6b57383d01b
/chap1/exec-1.32.ss
5a5fa9ded2fdeef47191cf8ae4352ae87a1b49ea
[]
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
731
ss
exec-1.32.ss
(define (accumulate-rec combiner null-value term a next b) (if (> a b) null-value (combiner (term a) (accumulate-rec combiner null-value term (next a) next b)))) (define (accumulate-iter combiner null-value term a next b) (define (iter cur result) (if (> cur b) result (iter (next cur) (combiner (term cur) result)))) (iter a null-value)) (define (identity x) x) (define (sum-rec a b) (accumulate-rec + 0 identity a 1+ b)) (define (product-rec a b) (accumulate-rec * 1 identity a 1+ b)) (sum-rec 1 10) (product-rec 1 10) (define (sum-iter a b) (accumulate-iter + 0 identity a 1+ b)) (define (product-iter a b) (accumulate-iter * 1 identity a 1+ b)) (sum-iter 1 10) (product-iter 1 10)
false
cf1350536229aedb1e88a51502d65abd761de7f1
9b2eb10c34176f47f7f490a4ce8412b7dd42cce7
/lib-r7c/r7c-io/port/buffers.sls
d43c89de6016db79ddcf012180ab6592408082bc
[ "LicenseRef-scancode-public-domain", "CC0-1.0" ]
permissive
okuoku/yuni
8be584a574c0597375f023c70b17a5a689fd6918
1859077a3c855f3a3912a71a5283e08488e76661
refs/heads/master
2023-07-21T11:30:14.824239
2023-06-11T13:16:01
2023-07-18T16:25:22
17,772,480
36
6
CC0-1.0
2020-03-29T08:16:00
2014-03-15T09:53:13
Scheme
UTF-8
Scheme
false
false
6,712
sls
buffers.sls
(library (r7c-io port buffers) (export open-input-string open-output-string get-output-string open-input-bytevector open-output-bytevector get-output-bytevector) (import (r7c-basic syntax define) (r7c-basic lib strings) (r7c-system core) (r7c heap fixnum) (r7c heap char) (r7c heap eof-object) (r7c syntax or) (r7c syntax and) (r7c syntax let) (r7c syntax case) (r7c-yunicore yuniport)) ;; (define (%find-newline str start end) ;; #f if the string teminated without NL (if ($fx= start end) #f (case (char->integer (string-ref str start)) ((10 13) ;; CR or LF start) (else (%find-newline str ($fx+ 1 start) end))))) (define (%skip-newline str start end) ;; #f if the string ends with newline (if ($fx= start end) #f (case (char->integer (string-ref str start)) ((13) ;; CR ;; Find lf if available (let ((n ($fx+ 1 start))) (cond (($fx= n end) ;; The string ends with LF #f) (else (if ($fx= 10 (char->integer (string-ref str n))) n ;; CR + LF start ;; CR ))))) ((10) ;; LF (let ((n ($fx+ 1 start))) (if ($fx= n end) #f n)) ) (else start)))) (define (open-input-string str) (define open? #t) (define ptr 0) (define len (string-length str)) (define (close) (set! open? #f)) (define (input-port-open?) open?) (define (peek-char) (if ($fx< ptr len) (string-ref str ptr) (eof-object))) (define (read-char) (if ($fx< ptr len) (let ((c (string-ref str ptr))) (set! ptr ($fx+ 1 ptr)) c) (eof-object))) (define (read-line) (if ($fx>= ptr len) (eof-object) (let ((start (%skip-newline str ptr len))) (cond (($fx= ptr start) (let ((end (%find-newline str ptr len))) (cond (end ;; Skip CRLF (let ((next (%skip-newline str end len))) (set! ptr (if next next len))) ;; Return string (substring str start end)) (else ;; String terminated (set! ptr len) ;; Return string (substring str start len))))) ((eqv? #f start) (set! ptr len) (make-string 0)) (else (set! ptr start) (make-string 0)))))) (define (read-string k) (if ($fx>= ptr len) (eof-object) (let ((end? ($fx+ k ptr))) (let ((start ptr) (next (if ($fx< end? len) end? len))) (set! ptr next) (substring str start next))))) (define (query sym) (case sym ((textual-port?) #t) ((buffer-port?) #t) ((input-port?) #t) ((input-port-open?) input-port-open?) ((close) close) ((close-input-port) close) ((read-char) read-char) ((peek-char) peek-char) ((read-line) read-line) ((read-string) read-string) (else #f))) (make-yuniport query)) (define (open-output-string) (define open? #t) (define buf "") (define (output-port-open?) open?) (define (close) (set! open? #f)) (define (get-buffer) (let ((r buf)) (set! buf "") r)) (define (write-char c) (set! buf (string-append buf (string c)))) (define (write-string str start end) (set! buf (string-append buf (substring str start end)))) (define (flush) ;; Do nothing #t) (define (query sym) (case sym ((textual-port?) #t) ((buffer-port?) #t) ((output-port?) #t) ((flush) flush) ((output-port-open?) output-port-open?) ((close) close) ((close-output-port) close) ((get-buffer) get-buffer) ((write-char) write-char) ((write-string) write-string) (else #f))) (make-yuniport query)) (define (open-input-bytevector bv) (define ptr 0) (define len (bytevector-length bv)) (define open? #t) (define (close) (set! open? #f)) (define (input-port-open?) open?) (define (peek-u8) (if ($fx= len ptr) (eof-object) (bytevector-u8-ref bv ptr))) (define (read-u8) (if ($fx= len ptr) (eof-object) (begin (let ((b (bytevector-u8-ref bv ptr))) (set! ptr ($fx+ 1 ptr)) b)))) (define (read-bytevector! out start end) (let ((copylen ($fx- end start))) (let ((term ($fx+ ptr copylen))) (cond (($fx< len term) ;; Short copy case (let ((copylen2 ($fx- len ptr))) (cond (($fx= 0 copylen2) (set! ptr len) (eof-object)) (else (bytevector-copy! out start bv ptr len) (set! ptr len) copylen2)))) (else (bytevector-copy! out start bv ptr term) (set! ptr term) copylen))))) (define (query sym) (case sym ((binary-port?) #t) ((buffer-port?) #t) ((input-port?) #t) ((input-port-open?) input-port-open?) ((close) close) ((close-input-port) close) ((read-u8) read-u8) ((peek-u8) peek-u8) ((read-bytevector!) read-bytevector!) (else #f))) (make-yuniport query)) (define (open-output-bytevector) (define open? #t) (define buf (make-bytevector 0)) (define (output-port-open?) open?) (define (close) (set! open? #f)) (define (get-buffer) (let ((r buf)) (set! buf (make-bytevector 0)) r)) (define (write-u8 b) (set! buf (bytevector-append buf (make-bytevector 1 b)))) (define (write-bytevector bv start end) (let ((len1 (bytevector-length buf)) (len2 ($fx- end start))) (let ((nextbuf (make-bytevector ($fx+ len1 len2)))) (bytevector-copy! nextbuf 0 buf 0 len1) (bytevector-copy! nextbuf len1 bv start end) (set! buf nextbuf)))) (define (flush) ;; Do nothing #t) (define (query sym) (case sym ((binary-port?) #t) ((buffer-port?) #t) ((output-port?) #t) ((flush) flush) ((output-port-open?) output-port-open?) ((close) close) ((close-output-port) close) ((get-buffer) get-buffer) ((write-u8) write-u8) ((write-bytevector) write-bytevector) (else #f))) (make-yuniport query)) (define get-output-string yuniport-get-buffer) (define get-output-bytevector yuniport-get-buffer) )
false
c6f73824786bab877f0a27ac20181a870c44da4e
2b540259d6a0b3195cb6b71a6f987447885328b2
/lib/derived/derived.scm
1f928758537212ab3152edb88ab93f7b47b89bab
[]
no_license
katsuya94/grime
fd3f2cf6ac4c561188350110d796a50c754c5427
b9f9760a920ff2f1f37cde2c04a46d2e5f6b1ea3
refs/heads/master
2021-06-21T13:14:19.544615
2019-05-05T04:18:14
2019-05-05T04:18:14
143,479,534
2
0
null
null
null
null
UTF-8
Scheme
false
false
5,642
scm
derived.scm
(library (derived) (export define when unless let* letrec* with-syntax let letrec and or list? fold-left for-all syntax-rules cond) (import (for (only (core) car cdr define-syntax error identifier? if lambda null? pair? proc? syntax syntax-case) run) (for (only (core) ... _ begin bound-identifier=? car cdr datum->syntax generate-temporaries identifier? if lambda list not null? quote set! syntax syntax-case ~define ~let) expand)) (define-syntax define (lambda (x) (syntax-case x () [(_ (name formals ...) body ...) #'(~define name (lambda (formals ...) body ...))] [(_ name value) #'(~define name value)]))) (define-syntax when (lambda (x) (syntax-case x () [(_ test body ...) #'(if test (begin body ...) #f)]))) (define-syntax unless (lambda (x) (syntax-case x () [(_ test body ...) #'(when (not test) body ...)]))) (define-syntax let* (lambda (x) (syntax-case x () [(_ () b1 b2 ...) #'(begin b1 b2 ...)] [(_ ((i1 e1) (i2 e2) ...) b1 b2 ...) #'(~let (i1 e1) (let* ((i2 e2) ...) b1 b2 ...))]))) (define-syntax letrec* (lambda (x) (syntax-case x () [(_ () b1 b2 ...) #'(begin b1 b2 ...)] [(_ ((i1 e1) (i2 e2) ...) b1 b2 ...) #'(~let (i1 #f) (set! i1 e1) (let* ((i2 e2) ...) b1 b2 ...))]))) (define-syntax with-syntax (lambda (x) (syntax-case x () [(_ ((p e0) ...) e1 e2 ...) #'(syntax-case (list e0 ...) () ((p ...) (begin e1 e2 ...)))]))) (define-syntax let (lambda (x) (define (unique-ids? ls) (define (notmem? x ls) (if (null? ls) #t (if (bound-identifier=? x (car ls)) #f (notmem? x (cdr ls))))) (if (null? ls) #t (if (notmem? (car ls) (cdr ls)) (unique-ids? (cdr ls)) #f))) (syntax-case x () [(_ v ((i e) ...) b1 b2 ...) (identifier? #'v) #'(letrec* ((v (lambda (i ...) b1 b2 ...))) (v e ...))] [(_ ((i e) ...) b1 b2 ...) (unique-ids? #'(i ...)) (with-syntax ([(t ...) (generate-temporaries #'(i ...))]) #'(let* ((t e) ...) (let* ((i t) ...) b1 b2 ...)))]))) ; TODO letrec should detect usages of variables before definition (define-syntax letrec (lambda (x) (define (unique-ids? ls) (define (notmem? x ls) (if (null? ls) #t (if (bound-identifier=? x (car ls)) #f (notmem? x (cdr ls))))) (if (null? ls) #t (if (notmem? (car ls) (cdr ls)) (unique-ids? (cdr ls)) #f))) (syntax-case x () [(_ ((i e) ...) b1 b2 ...) (unique-ids? #'(i ...)) (with-syntax ([(t ...) (generate-temporaries #'(i ...))]) #'(let* ((i #f) ...) (let* ((t e) ...) (set! i t) ... b1 b2 ...)))]))) (define-syntax and (lambda (x) (syntax-case x () [(_ ) #'#t] [(_ e) #'e] [(_ e1 e2 e3 ...) #'(let ([t e1]) (if t (and e2 e3 ...) t))]))) (define-syntax or (lambda (x) (syntax-case x () [(_ ) #'#f] [(_ e) #'e] [(_ e1 e2 e3 ...) #'(let ([t e1]) (if t t (or e2 e3 ...)))]))) (define (list? x) (or (null? x) (pair? x))) (define (fold-left combine nil lst) (unless (proc? combine) (error "fold-left: expected proc")) (unless (list? lst) (error "fold-left: expected list")) (if (null? lst) nil (fold-left combine (combine nil (car lst)) (cdr lst)))) (define (for-all proc lst) (fold-left (lambda (b x) (and b (proc x))) #t lst)) ; grime treats #'() and '() as discrete values making the default for-all ; incompatible with the syntax object (define (for-all-identifier ids) (syntax-case ids () [() #t] [(id . rest) (and (identifier? #'id) (for-all-identifier #'rest))])) (define-syntax syntax-rules (lambda (x) (syntax-case x () [(_ (lit ...) [(k . p) t] ...) (for-all-identifier #'(lit ... k ...)) #'(lambda (x) (syntax-case x (lit ...) [(_ . p) #'t] ...))]))) (define-syntax cond (lambda (x) (syntax-case x () [(_ c1 c2 ...) (let f ([c1 #'c1] [c2* #'(c2 ...)]) (syntax-case c2* () [() (syntax-case c1 (else =>) [(else e1 e2 ...) #'(begin e1 e2 ...)] [(e0) #'e0] [(e0 => e1) #'(let ([t e0]) (if t (e1 t)))] [(e0 e1 e2 ...) #'(if e0 (begin e1 e2 ...))])] [(c2 c3 ...) (with-syntax ([rest (f #'c2 #'(c3 ...))]) (syntax-case c1 (=>) [(e0) #'(let ([t e0]) (if t t rest))] [(e0 => e1) #'(let ([t e0]) (if t (e1 t) rest))] [(e0 e1 e2 ...) #'(if e0 (begin e1 e2 ...) rest)]))]))]))))
true
da6a3fa5e10644538d3c2fd7c88a6a61141dca13
cdab7b6efc54afca468ee90c1cd68fee67955caa
/chap1/exer1.1.scm
5706090946fedd00a79feffbcd2d2ff74fac5158
[]
no_license
natsutan/Lisp_in_Small_Pieces
2440e6a8b9b66cc80777c952dc33cbfadf4ac0b2
14904ce89657393fb3403727f4a4519c37d4e1b9
refs/heads/master
2021-01-18T15:21:41.241933
2018-09-17T00:13:25
2018-09-17T00:13:25
10,713,155
0
0
null
null
null
null
UTF-8
Scheme
false
false
296
scm
exer1.1.scm
(load "./chap1.scm") (chap1-scheme-bat '((+ 3 5))) (chap1-scheme-bat '((set! pow (lambda (x) (* x x))) (pow 5))) (trace-on) (trace 'fact) (chap1-scheme-bat '((set! fact (lambda (x) (if (= x 1) 1 (* (fact (- x 1)) x)))) (fact 5)))
false
79821784e802639211b5bc54acd3fac9d820f1e5
648776d3a0d9a8ca036acaf6f2f7a60dcdb45877
/queries/vala/folds.scm
86b731eeac07ba696c3b50f16e43745f42080888
[ "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
175
scm
folds.scm
[ (namespace_member) (enum_declaration) (class_declaration) (if_statement) (elseif_statement) (try_statement) (catch_clause) (block) (class_member) ] @fold
false
2d4a7f0f1db9d43e6ac9dd180367e86b05b53198
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
/sitelib/srfi/%3a142/bitwise.scm
b97879e8ece7e4ad340dbfe8d74f1691a12d1e98
[ "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "MIT", "BSD-2-Clause" ]
permissive
ktakashi/sagittarius-scheme
0a6d23a9004e8775792ebe27a395366457daba81
285e84f7c48b65d6594ff4fbbe47a1b499c9fec0
refs/heads/master
2023-09-01T23:45:52.702741
2023-08-31T10:36:08
2023-08-31T10:36:08
41,153,733
48
7
NOASSERTION
2022-07-13T18:04:42
2015-08-21T12:07:54
Scheme
UTF-8
Scheme
false
false
2,535
scm
bitwise.scm
;;; -*- mode:scheme; coding:utf-8; -*- ;;; ;;; srfi/%3a142/bitwise.scm - Bitwise Operations ;;; ;;; Copyright (c) 2017 Takashi Kato <[email protected]> ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; (library (srfi :142 bitwise) (export bitwise-not bitwise-and bitwise-ior bitwise-xor bitwise-eqv bitwise-nand bitwise-nor bitwise-andc1 bitwise-andc2 bitwise-orc1 bitwise-orc2 bit-count bitwise-if bit-set? copy-bit bit-swap any-bit-set? every-bit-set? bit-field-any? bit-field-every? bit-field-clear bit-field-set bit-field-replace bit-field-replace-same bit-field-rotate bits->list list->bits bits->vector vector->bits bits bitwise-fold bitwise-for-each bitwise-unfold make-bitwise-generator arithmetic-shift integer-length first-set-bit bit-field bit-field-reverse) (import (only (rnrs) define) (rename (srfi :151 bitwise) (bitwise-if srfi:bitwise-if))) ;; From the abstract of SRFI-151 ;; This SRFI differs from SRFI 142 in only one way: the bitwise-if ;; function has the argument ordering of SLIB, SRFI 60, and R6RS ;; rather than the ordering of SRFI 33. (define (bitwise-if mask i j) (srfi:bitwise-if mask j i)) )
false
83ecc577b292ac377ce00f5e84cfb61c5139c6de
ce292f2540ed48c5770021a74830da75a89cb89c
/sr/ck/kernel.sld
1342fade450c8966d96663b8097bd789d9222ab9
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
ilammy/sr
ba30453c560d130deb78f408b16d309da0561063
38c054260c6ee9c51b73ecb506b2bb5f1fcc9be6
refs/heads/master
2020-12-24T13:21:28.193042
2015-02-07T15:40:02
2015-02-07T18:07:00
22,486,031
1
1
null
null
null
null
UTF-8
Scheme
false
false
790
sld
kernel.sld
(define-library (sr ck kernel) (export $quote $eval $call $apply $if) (import (scheme base) (sr ck)) (begin (define-syntax $quote (syntax-rules (quote) ((_ s 'x) ($ s ''x)) ) ) (define-syntax $eval (syntax-rules (quote) ((_ s 'x) ($ s x)) ) ) (define-syntax $call (syntax-rules (quote) ; need to know the internals of $ ((_ s '(f ...) 'args ...) ($ s #f (f ... 'args ...))) ((_ s 'f 'args ...) ($ s ($call '(f) 'args ...))) ) ) (define-syntax $apply (syntax-rules (quote) ((_ s 'f '(args ...)) ($ s ($call 'f 'args ...))) ) ) (define-syntax $if (syntax-rules (quote) ((_ s '#t 't 'f) ($ s ($eval 't))) ((_ s '#f 't 'f) ($ s ($eval 'f))) ) ) ) )
true
3d7f17a7da249d273cfc9161b9bb005702311009
8a0660bd8d588f94aa429050bb8d32c9cd4290d5
/test/tests/srfi/%3a43.scm
f5e6ab59675f75ecd674c01cb4ccf6e9d38b0a9e
[ "BSD-2-Clause" ]
permissive
david135/sagittarius-scheme
dbec76f6b227f79713169985fc16ce763c889472
2fbd9d153c82e2aa342bfddd59ed54d43c5a7506
refs/heads/master
2016-09-02T02:44:31.668025
2013-12-21T07:24:08
2013-12-21T07:24:08
32,497,456
0
0
null
null
null
null
UTF-8
Scheme
false
false
23,084
scm
%3a43.scm
(import (rnrs) (srfi :43) (srfi :64)) (test-begin "SRFI-43 tests") (define-syntax assert-equal (syntax-rules () ((_ name expr expected) (test-equal name expected expr)))) (define-syntax assert-error (syntax-rules () ((_ name expr) (test-error name (lambda (e) e) expr)))) (define *extended-test* #t) ;; test cases are from ;; http://srfi.schemers.org/srfi-43/post-mail-archive/msg00010.html (assert-equal "make-vector 0" (vector-length (make-vector 5)) 5) (assert-equal "make-vector 1" (make-vector 0) '#()) (assert-error "make-vector 2" (make-vector -4)) (assert-equal "make-vector 3" (make-vector 5 3) '#(3 3 3 3 3)) (assert-equal "make-vector 4" (make-vector 0 3) '#()) (assert-error "make-vector 5" (make-vector -1 3)) (assert-equal "vector 0" (vector) '#()) (assert-equal "vector 1" (vector 1 2 3 4 5) '#(1 2 3 4 5)) (assert-equal "vector-unfold 0" (vector-unfold (lambda (i x) (values x (- x 1))) 10 0) '#(0 -1 -2 -3 -4 -5 -6 -7 -8 -9)) (assert-equal "vector-unfold 1" (vector-unfold values 10) '#(0 1 2 3 4 5 6 7 8 9)) (assert-equal "vector-unfold 2" (vector-unfold values 0) '#()) (assert-error "vector-unfold 3" (vector-unfold values -1)) (assert-equal "vector-unfold-right 0" (vector-unfold-right (lambda (i x) (values x (+ x 1))) 10 0) '#(9 8 7 6 5 4 3 2 1 0)) (assert-equal "vector-unfold-right 1" (let ((vector '#(a b c d e))) (vector-unfold-right (lambda (i x) (values (vector-ref vector x) (+ x 1))) (vector-length vector) 0)) '#(e d c b a)) (assert-equal "vector-unfold-right 2" (vector-unfold-right values 0) '#()) (assert-error "vector-unfold-right 3" (vector-unfold-right values -1)) (assert-equal "vector-copy 0" (vector-copy '#(a b c d e f g h i)) '#(a b c d e f g h i)) (assert-equal "vector-copy 1" (vector-copy '#(a b c d e f g h i) 6) '#(g h i)) (assert-equal "vector-copy 2" (vector-copy '#(a b c d e f g h i) 3 6) '#(d e f)) (assert-equal "vector-copy 3" (vector-copy '#(a b c d e f g h i) 6 12 'x) '#(g h i x x x)) (assert-equal "vector-copy 4" (vector-copy '#(a b c d e f g h i) 6 6) '#()) (assert-error "vector-copy 5" (vector-copy '#(a b c d e f g h i) 4 2)) (assert-equal "vector-reverse-copy 0" (vector-reverse-copy '#(a b c d e)) '#(e d c b a)) (assert-equal "vector-reverse-copy 1" (vector-reverse-copy '#(a b c d e) 1 4) '#(d c b)) (assert-equal "vector-reverse-copy 2" (vector-reverse-copy '#(a b c d e) 1 1) '#()) (assert-error "vector-reverse-copy 3" (vector-reverse-copy '#(a b c d e) 2 1)) (assert-equal "vector-append 0" (vector-append '#(x) '#(y)) '#(x y)) (assert-equal "vector-append 1" (let ((v '#(x y))) (vector-append v v v)) '#(x y x y x y)) (assert-equal "vector-append 2" (vector-append '#(x) '#() '#(y)) '#(x y)) (assert-equal "vector-append 3" (vector-append) '#()) (assert-error "vector-append 4" (vector-append '#() 'b 'c)) (assert-equal "vector-concatenate 0" (vector-concatenate '(#(a b) #(c d))) '#(a b c d)) (assert-equal "vector-concatenate 1" (vector-concatenate '()) '#()) (assert-error "vector-concatenate 2" (vector-concatenate '(#(a b) c))) ;;; ;;; Predicates ;;; (assert-equal "vector? 0" (vector? '#()) #t) (assert-equal "vector? 1" (vector? '#(a b)) #t) (assert-equal "vector? 2" (vector? '(a b)) #f) (assert-equal "vector? 3" (vector? 'a) #f) (assert-equal "vector-empty? 0" (vector-empty? '#()) #t) (assert-equal "vector-empty? 1" (vector-empty? '#(a)) #f) (assert-equal "vector= 0" (vector= eq? '#(a b c d) '#(a b c d)) #t) (assert-equal "vector= 1" (vector= eq? '#(a b c d) '#(a b c d) '#(a b c d)) #t) (assert-equal "vector= 2" (vector= eq? '#() '#()) #t) (assert-equal "vector= 3" (vector= eq?) #t) (assert-equal "vector= 4" (vector= eq? '#(a)) #t) (assert-equal "vector= 5" (vector= eq? '#(a b c d) '#(a b d c)) #f) (assert-equal "vector= 6" (vector= eq? '#(a b c d) '#(a b c d) '#(a b d c)) #f) (assert-equal "vector= 7" (vector= eq? '#(a b c) '#(a b d c)) #f) (assert-equal "vector= 8" (vector= eq? '#() '#(a b d c)) #f) (assert-equal "vector= 9" (vector= eq? '#(a b d c) '#()) #f) (assert-equal "vector= 10" (vector= equal? '#("a" "b" "c") '#("a" "b" "c")) #t) (assert-error "vector= 11" (vector= equal? '#("a" "b" "c") '("a" "b" "c"))) ;;; ;;; Selectors ;;; (assert-equal "vector-ref 0" (vector-ref '#(a b c) 0) 'a) (assert-equal "vector-ref 1" (vector-ref '#(a b c) 1) 'b) (assert-equal "vector-ref 2" (vector-ref '#(a b c) 2) 'c) (assert-error "vector-ref 3" (vector-ref '#(a b c) -1)) (assert-error "vector-ref 4" (vector-ref '#(a b c) 3)) (assert-error "vector-ref 5" (vector-ref '#() 0)) (assert-equal "vector-length 0" (vector-length '#()) 0) (assert-equal "vector-length 1" (vector-length '#(a b c)) 3) (assert-error "vector-length 2" (vector-length '(a b c))) ;;; ;;; Iteration ;;; (assert-equal "vector-fold 0" (vector-fold (lambda (i seed val) (+ seed val)) 0 '#(0 1 2 3 4)) 10) (assert-equal "vector-fold 1" (vector-fold (lambda (i seed val) (+ seed val)) 'a '#()) 'a) (assert-equal "vector-fold 2" (vector-fold (lambda (i seed val) (+ seed (* i val))) 0 '#(0 1 2 3 4)) 30) (assert-equal "vector-fold 3" (vector-fold (lambda (i seed x y) (cons (- x y) seed)) '() '#(6 1 2 3 4) '#(7 0 9 2)) '(1 -7 1 -1)) (assert-equal "vector-fold-right 0" (vector-fold-right (lambda (i seed val) (cons (cons i val) seed)) '() '#(a b c d e)) '((0 . a) (1 . b) (2 . c) (3 . d) (4 . e))) (assert-equal "vector-fold-right 1" (vector-fold-right (lambda (i seed x y) (cons (- x y) seed)) '() '#(6 1 2 3 7) '#(7 0 9 2)) '(-1 1 -7 1)) (assert-equal "vector-map 0" (vector-map cons '#(a b c d e)) '#((0 . a) (1 . b) (2 . c) (3 . d) (4 . e))) (assert-equal "vector-map 1" (vector-map cons '#()) '#()) (assert-equal "vector-map 2" (vector-map + '#(0 1 2 3 4) '#(5 6 7 8)) '#(5 8 11 14)) (assert-equal "vector-map! 0" (let ((v (vector 0 1 2 3 4))) (vector-map! * v) v) '#(0 1 4 9 16)) (assert-equal "vector-map! 1" (let ((v (vector))) (vector-map! * v) v) '#()) (assert-equal "vector-map! 2" (let ((v (vector 0 1 2 3 4))) (vector-map! + v '#(5 6 7 8)) v) '#(5 8 11 14 4)) (assert-equal "vector-for-each 0" (let ((sum 0)) (vector-for-each (lambda (i x) (set! sum (+ sum (* i x)))) '#(0 1 2 3 4)) sum) 30) (assert-equal "vector-for-each 1" (let ((sum 0)) (vector-for-each (lambda (i x) (set! sum (+ sum (* i x)))) '#()) sum) 0) (assert-equal "vector-count 0" (vector-count (lambda (i x) (even? x)) '#(0 1 2 3 4 5 6)) 4) (assert-equal "vector-count 1" (vector-count values '#()) 0) (assert-equal "vector-count 2" (vector-count (lambda (i x y) (< x y)) '#(8 2 7 4 9 1 0) '#(7 6 8 3 1 1 9)) 3) ;;; ;;; Searching ;;; (assert-equal "vector-index 0" (vector-index even? '#(3 1 4 1 5 9)) 2) (assert-equal "vector-index 1" (vector-index < '#(3 1 4 1 5 9 2 5 6) '#(2 7 1 8 2)) 1) (assert-equal "vector-index 2" (vector-index = '#(3 1 4 1 5 9 2 5 6) '#(2 7 1 8 2)) #f) (assert-equal "vector-index 3" (vector-index < '#() '#(2 7 1 8 2)) #f) (assert-equal "vector-index-right 0" (vector-index-right even? '#(3 1 4 1 5 9 2)) 6) (assert-equal "vector-index-right 1" (vector-index-right < '#(3 1 4 1 5) '#(2 7 1 8 2)) 3) (assert-equal "vector-index-right 2" (vector-index-right = '#(3 1 4 1 5) '#(2 7 1 8 2)) #f) (assert-equal "vector-index-right 3" (vector-index-right even? #()) #f) (assert-equal "vector-skip 0" (vector-skip odd? '#(3 1 4 1 5 9)) 2) (assert-equal "vector-skip 1" (vector-skip < '#(3 1 4 1 5 9 2 5 6) '#(4 9 5 0 2 4)) 3) (assert-equal "vector-skip 2" (vector-skip < '#(3 1 4 1 5 2 5 6) '#(4 9 5 9 9 9)) #f) (assert-equal "vector-skip 3" (vector-skip < '#() '#(4 9 5 9 9 9)) #f) (assert-equal "vector-skip-right 0" (vector-skip-right odd? '#(3 1 4 1 5 9 2 6 5 3)) 7) (assert-equal "vector-skip-right 1" (vector-skip-right < '#(8 3 7 3 1 0) '#(4 9 5 0 2 4)) 3) (assert-equal "vector-skip-right 2" (vector-skip-right < '#() '#(4 9 5 0 2 4)) #f) (define (char-cmp c1 c2) (cond ((char<? c1 c2) -1) ((char=? c1 c2) 0) (else 1))) (assert-equal "vector-binary-search 0" (vector-binary-search '#(#\a #\b #\c #\d #\e #\f #\g #\h) #\g char-cmp) 6) (assert-equal "vector-binary-search 1" (vector-binary-search '#(#\a #\b #\c #\d #\e #\f #\g) #\q char-cmp) #f) (assert-equal "vector-binary-search 2" (vector-binary-search '#(#\a) #\a char-cmp) 0) (assert-equal "vector-binary-search 3" (vector-binary-search '#() #\a char-cmp) #f) (assert-error "vector-binary-search 4" (vector-binary-search '(#\a #\b #\c) #\a char-cmp)) (cond (*extended-test* (assert-equal "vector-binary-search 5" (vector-binary-search '#(#\a #\b #\c #\d #\e #\f #\g #\h) #\d char-cmp 2 6) 3) (assert-equal "vector-binary-search 6" (vector-binary-search '#(#\a #\b #\c #\d #\e #\f #\g #\h) #\g char-cmp 2 6) #f) )) (assert-equal "vector-any 0" (vector-any even? '#(3 1 4 1 5 9 2)) #t) (assert-equal "vector-any 1" (vector-any even? '#(3 1 5 1 5 9 1)) #f) (assert-equal "vector-any 2" (vector-any even? '#(3 1 4 1 5 #f 2)) #t) (assert-equal "vector-any 3" (vector-any even? '#()) #f) (assert-equal "vector-any 4" (vector-any < '#(3 1 4 1 5 #f) '#(1 0 1 2 3)) #t) (assert-equal "vector-any 5" (vector-any < '#(3 1 4 1 5 #f) '#(1 0 1 0 3)) #f) (assert-equal "vector-every 0" (vector-every odd? '#(3 1 4 1 5 9 2)) #f) (assert-equal "vector-every 1" (vector-every odd? '#(3 1 5 1 5 9 1)) #t) (assert-equal "vector-every 2" (vector-every odd? '#(3 1 4 1 5 #f 2)) #f) (assert-equal "vector-every 3" (vector-every even? '#()) #t) (assert-equal "vector-every 4" (vector-every >= '#(3 1 4 1 5) '#(1 0 1 2 3 #f)) #f) (assert-equal "vector-every 5" (vector-every >= '#(3 1 4 1 5) '#(1 0 1 0 3 #f)) #t) ;;; ;;; Mutators ;;; (assert-equal "vector-set! 0" (let ((v (vector 0 1 2))) (vector-set! v 1 'a) v) '#(0 a 2)) (assert-error "vector-set! 1" (vector-set! (vector 0 1 2) 3 'a)) (assert-error "vector-set! 2" (vector-set! (vector 0 1 2) -1 'a)) (assert-error "vector-set! 3" (vector-set! (vector) 0 'a)) (assert-equal "vector-swap! 0" (let ((v (vector 'a 'b 'c))) (vector-swap! v 0 1) v) '#(b a c)) (assert-equal "vector-swap! 1" (let ((v (vector 'a 'b 'c))) (vector-swap! v 1 1) v) '#(a b c)) (assert-error "vector-swap! e0" (vector-swap! (vector 'a 'b 'c) 0 3)) (assert-error "vector-swap! e1" (vector-swap! (vector 'a 'b 'c) -1 1)) (assert-error "vector-swap! e2" (vector-swap! (vector) 0 0)) (assert-equal "vector-fill! 0" (let ((v (vector 'a 'b 'c 'd 'e))) (vector-fill! v 'z) v) '#(z z z z z)) (assert-equal "vector-fill! 1" (let ((v (vector 'a 'b 'c 'd 'e))) (vector-fill! v 'z 2) v) '#(a b z z z)) (assert-equal "vector-fill! 2" (let ((v (vector 'a 'b 'c 'd 'e))) (vector-fill! v 'z 1 3) v) '#(a z z d e)) (assert-equal "vector-fill! 3" (let ((v (vector 'a 'b 'c 'd 'e))) (vector-fill! v 'z 0 5) v) '#(z z z z z)) (assert-equal "vector-fill! 4" (let ((v (vector 'a 'b 'c 'd 'e))) (vector-fill! v 'z 2 2) v) '#(a b c d e)) (assert-error "vector-fill! e0" (vector-fill! (vector 'a 'b 'c) 'z 0 4)) (assert-error "vector-fill! e1" (vector-fill! (vector 'a 'b 'c) 'z 2 1)) (assert-error "vector-fill! e2" (vector-fill! (vector 'a 'b 'c) 'z -1 1)) ;;(assert-error "vector-fill! e3" (vector-fill! (vector) 'z 0 0)) (assert-equal "vector-reverse! 0" (let ((v (vector 'a 'b 'c 'd 'e))) (vector-reverse! v) v) '#(e d c b a)) (assert-equal "vector-reverse! 1" (let ((v (vector 'a 'b 'c 'd 'e 'f))) (vector-reverse! v 1 4) v) '#(a d c b e f)) (assert-equal "vector-reverse! 2" (let ((v (vector 'a 'b 'c 'd 'e 'f))) (vector-reverse! v 3 3) v) '#(a b c d e f)) (assert-equal "vector-reverse! 3" (let ((v (vector 'a 'b 'c 'd 'e 'f))) (vector-reverse! v 3 4) v) '#(a b c d e f)) (assert-equal "vector-reverse! 4" (let ((v (vector))) (vector-reverse! v) v) '#()) (assert-error "vector-reverse! e0" (vector-reverse! (vector 'a 'b) 0 3)) (assert-error "vector-reverse! e1" (vector-reverse! (vector 'a 'b) 2 1)) (assert-error "vector-reverse! e2" (vector-reverse! (vector 'a 'b) -1 1)) ;;(assert-error "vector-reverse! e3" (vector-reverse! (vector) 0 0)) (assert-equal "vector-copy! 0" (let ((v (vector 'a 'b 'c 'd 'e))) (vector-copy! v 0 '#(1 2 3)) v) '#(1 2 3 d e)) (assert-equal "vector-copy! 1" (let ((v (vector 'a 'b 'c 'd 'e))) (vector-copy! v 2 '#(1 2 3)) v) '#(a b 1 2 3)) (assert-equal "vector-copy! 2" (let ((v (vector 'a 'b 'c 'd 'e))) (vector-copy! v 2 '#(1 2 3) 1) v) '#(a b 2 3 e)) (assert-equal "vector-copy! 3" (let ((v (vector 'a 'b 'c 'd 'e))) (vector-copy! v 2 '#(1 2 3 4 5) 2 5) v) '#(a b 3 4 5)) (assert-equal "vector-copy! 4" (let ((v (vector 'a 'b 'c 'd 'e))) (vector-copy! v 2 '#(1 2 3) 1 1) v) '#(a b c d e)) (assert-equal "vector-copy! self0" (let ((v (vector 'a 'b 'c 'd 'e))) (vector-copy! v 0 v 1 3) v) '#(b c c d e)) (assert-equal "vector-copy! self1" (let ((v (vector 'a 'b 'c 'd 'e))) (vector-copy! v 2 v 1 4) v) '#(a b b c d)) (assert-equal "vector-copy! self2" (let ((v (vector 'a 'b 'c 'd 'e))) (vector-copy! v 0 v 0) v) '#(a b c d e)) (assert-error "vector-copy! e0" (vector-copy! (vector 1 2) 3 '#(1 2 3))) (assert-error "vector-copy! e1" (vector-copy! (vector 1 2) 0 '#(1 2 3))) (assert-error "vector-copy! e2" (vector-copy! (vector 1 2) 1 '#(1 2 3) 1)) (assert-equal "vector-reverse-copy! 0" (let ((v (vector 'a 'b 'c 'd 'e))) (vector-reverse-copy! v 0 '#(1 2 3)) v) '#(3 2 1 d e)) (assert-equal "vector-reverse-copy! 1" (let ((v (vector 'a 'b 'c 'd 'e))) (vector-reverse-copy! v 2 '#(1 2 3)) v) '#(a b 3 2 1)) (assert-equal "vector-reverse-copy! 2" (let ((v (vector 'a 'b 'c 'd 'e))) (vector-reverse-copy! v 2 '#(1 2 3) 1) v) '#(a b 3 2 e)) (assert-equal "vector-reverse-copy! 3" (let ((v (vector 'a 'b 'c 'd 'e))) (vector-reverse-copy! v 2 '#(1 2 3 4 5) 1 4) v) '#(a b 4 3 2)) (assert-equal "vector-reverse-copy! 4" (let ((v (vector 'a 'b 'c 'd 'e))) (vector-reverse-copy! v 2 '#(1 2 3 4 5) 2 2) v) '#(a b c d e)) (assert-equal "vector-reverse-copy! self0" (let ((v (vector 'a 'b 'c 'd 'e))) (vector-reverse-copy! v 0 v) v) '#(e d c b a)) (assert-equal "vector-reverse-copy! self1" (let ((v (vector 'a 'b 'c 'd 'e))) (vector-reverse-copy! v 0 v 0 2) v) '#(b a c d e)) (assert-error "vector-reverse-copy! e0" (vector-reverse-copy! (vector 'a 'b) 2 '#(a b))) (assert-error "vector-reverse-copy! e1" (vector-reverse-copy! (vector 'a 'b) -1 '#(a b))) (assert-error "vector-reverse-copy! e2" (vector-reverse-copy! (vector 'a 'b) 0 '#(a b c))) (assert-error "vector-reverse-copy! e3" (vector-reverse-copy! (vector 'a 'b) 0 '#(a b c) 1 4)) (assert-error "vector-reverse-copy! e4" (vector-reverse-copy! (vector 'a 'b) 0 '#(a b c) -1 2)) (assert-error "vector-reverse-copy! e5" (vector-reverse-copy! (vector 'a 'b) 0 '#(a b c) 2 1)) ;;; ;;; Conversion ;;; (assert-equal "vector->list 0" (vector->list '#(a b c)) '(a b c)) (assert-equal "vector->list 1" (vector->list '#(a b c) 1) '(b c)) (assert-equal "vector->list 2" (vector->list '#(a b c d e) 1 4) '(b c d)) (assert-equal "vector->list 3" (vector->list '#(a b c d e) 1 1) '()) (assert-equal "vector->list 4" (vector->list '#()) '()) (assert-error "vector->list e0" (vector->list '#(a b c) 1 6)) (assert-error "vector->list e1" (vector->list '#(a b c) -1 1)) (assert-error "vector->list e2" (vector->list '#(a b c) 2 1)) (assert-equal "reverse-vector->list 0" (reverse-vector->list '#(a b c)) '(c b a)) (assert-equal "reverse-vector->list 1" (reverse-vector->list '#(a b c) 1) '(c b)) (assert-equal "reverse-vector->list 2" (reverse-vector->list '#(a b c d e) 1 4) '(d c b)) (assert-equal "reverse-vector->list 3" (reverse-vector->list '#(a b c d e) 1 1) '()) (assert-equal "reverse-vector->list 4" (reverse-vector->list '#()) '()) (assert-error "reverse-vector->list e0" (reverse-vector->list '#(a b c) 1 6)) (assert-error "reverse-vector->list e1" (reverse-vector->list '#(a b c) -1 1)) (assert-error "reverse-vector->list e2" (reverse-vector->list '#(a b c) 2 1)) (assert-equal "list->vector 0" (list->vector '(a b c)) '#(a b c)) (assert-equal "list->vector 1" (list->vector '()) '#()) (cond (*extended-test* (assert-equal "list->vector 2" (list->vector '(0 1 2 3) 2) '#(2 3)) (assert-equal "list->vector 3" (list->vector '(0 1 2 3) 0 2) '#(0 1)) (assert-equal "list->vector 4" (list->vector '(0 1 2 3) 2 2) '#()) (assert-error "list->vector e0" (list->vector '(0 1 2 3) 0 5)) (assert-error "list->vector e1" (list->vector '(0 1 2 3) -1 1)) (assert-error "list->vector e2" (list->vector '(0 1 2 3) 2 1)) )) (assert-equal "reverse-list->vector 0" (reverse-list->vector '(a b c)) '#(c b a)) (assert-equal "reverse-list->vector 1" (reverse-list->vector '()) '#()) (cond (*extended-test* (assert-equal "reverse-list->vector 2" (reverse-list->vector '(0 1 2 3) 2) '#(3 2)) (assert-equal "reverse-list->vector 3" (reverse-list->vector '(0 1 2 3) 0 2) '#(1 0)) (assert-equal "reverse-list->vector 4" (reverse-list->vector '(0 1 2 3) 2 2) '#()) (assert-error "reverse-list->vector e0" (reverse-list->vector '(0 1 2 3) 0 5)) (assert-error "reverse-list->vector e1" (reverse-list->vector '(0 1 2 3) -1 1)) (assert-error "reverse-list->vector e2" (reverse-list->vector '(0 1 2 3) 2 1)) )) (test-end)
true
746f63c4dd0d6abcc25bfaa8f5767bc1fe23d0f8
5355071004ad420028a218457c14cb8f7aa52fe4
/3.5/e-3.52.scm
92bb871cc8995c61ce8d649622a175c6e442572e
[]
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,985
scm
e-3.52.scm
(load "../helpers.scm") (load "../common.scm") (load "3.5.scm") ; Exercise 3.52. Consider the sequence of expressions (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)) (stream-ref y 7) ; (display-stream z) ; What is the value of sum after each of the above expressions is evaluated? ; What is the printed response to evaluating the stream-ref and display-stream ; expressions? Would these responses differ if we had implemented (delay <exp>) ; simply as (lambda () <exp>) without using the optimization provided by ; memo-proc ? Explain. ; ------------------------------------------------------------ (define sum 0) ; here we define sequence that is potentially expandable to ; 1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190 210 (define seq (stream-map accum (stream-enumerate-interval 1 20))) (output sum) ; => 1 (first element of the sequence was evaluated) ; here we define sequence expandable to ; 6 10 28 36 66 78 120 136 190 210 (define y (stream-filter even? seq)) ; here we have filter that will look for the first element ; and then evaluate sums for 1 2 3 and produce 6 ; (output sum) ; => 6 (up to first element of sequence is evaluated) ; here we define sequence of the form ; 10 15 45 55 105 120 190 210 (define z (stream-filter (lambda (x) (= (remainder x 5) 0)) seq)) (output sum) ; => 10 (up to first element of sequence evaluated) (stream-ref y 7) (output sum) ; => 136 (up to 8th element evaluated because of zero base indexing in stream-ref) (display-stream z) ; => 10 15 45 55 105 120 190 210 ; These results would differ significantly if there was no memo implementation ; since procedure (accum) would be executed every time we need to ; get next element of the sequence and sum would turn out different.
false
54e5addc29082d65c0f18a4f4f809769549d6e13
cf8c6fe3a289f26b8c0cca1281cbf89a14985064
/racketwork/streamstuff.scm
6e967650091b72a58217a43a1f3a7d1a89e59877
[]
no_license
chetnashah/emacs-lisp-practice-work
3c9bf47eefe77ebd3b6511593ba1dea7d3732db3
ec6ec1cbe6516017d107f3d1f766bca76ec3680b
refs/heads/master
2020-12-27T12:13:35.757655
2020-09-02T04:55:15
2020-09-02T04:55:15
68,783,499
2
0
null
null
null
null
UTF-8
Scheme
false
false
4,237
scm
streamstuff.scm
;; -*- geiser-scheme-implementation: chicken -*- ;; ;; As a data abstraction, streams are same as lists. ;; With ordinary lists, both car and cdr are evaluated ;; at construction. ;; With steams, cdr is evaluated at selection time ;; implementation of streams will be based ;; on special form called 'delay' ;; Evaluating (delay <exp>) returns delayed object, ;; like a promise of exp evaluation result in future. ;; (delay <expr>) => promise ;; Companion of delay is force, ;; force takes a delayed object/promise and performs ;; evaluation, in effect forcing delay to fulfill the promise ;; (force <promise>) => value ;; (cons-stream a b) is equivalent to (cons a (delay b)) (define (stream-car stream) (car stream)) (define (stream-cdr stream) (force (cdr stream))) ;; stream-cdr selects cdr of the pair and evaluates ;; delayed expression found there to obtain rest of stream ;; DELAY and FORCE SEMANTICS ;; delay must be a macro to prevent eager eval of exp ;; delay puts expression in lambda with no-args to delay eval ;; (define (delay exp) ;; (lambda () exp)) ;; ;; force implementation will also usually memoize result ;; in addition to below ;; force calls promise with no arguments ;; (define (force promise) ;; (promise)) ;; delay and force are already present in scheme R5RS ;; implementation which are correct as desired and ;; hence we will use them. ;; e.g. try out ;; (define heyer (cons 1 (delay (display 'hey)))) ;; (force (cdr heyer)) ;; output => 'hey ;; cons-stream needs to be a macro; ;; Why ? ;; (define (cons-stream a b) ;; (cons a (delay b))) ;; because while calling itself ;; b is evaluated ;; e.g. (cons-stream 1 (display 'hi)) ;; will display hi instead of delaying its evaluation (define-syntax cons-stream (syntax-rules () [(_ a b) (cons a (delay b))] )) (define the-empty-stream '()) (define stream-null? null?) ;; define stream-for-each ;; run a procedure on each element of stream (define (stream-for-each proc stream) (if (stream-null? stream) 'done (begin (proc (stream-car stream)) (stream-for-each proc (stream-cdr stream))))) (define test-stream (cons-stream 2 (cons-stream 3 (cons-stream 4 '())))) ;; displays passed argument but with a newline (define (display-line x) (newline) (display x)) (define (display-stream stream) (stream-for-each display-line stream)) ;; stream map (define (stream-map proc stream) (if (stream-null? stream) the-empty-stream (cons-stream (proc (stream-car stream)) (stream-map proc (stream-cdr stream))))) (define (sqr x) (* x x)) ;; try ;; (define sqr-stream (stream-map sqr test-stream)) ;; (display-stream sqr-stream) ;; stream-filter is interesting (define (stream-filter pred stream) (cond [(stream-null? stream) the-empty-stream] [(pred (stream-car stream)) (cons-stream (stream-car stream) (stream-filter pred (stream-cdr stream)))] [#t (stream-filter pred (stream-cdr stream))] )) (define (stream-enumerate-interval low hi) (if (> low hi) '() (cons-stream low (stream-enumerate-interval (+ 1 low) hi)))) (define (shower x) (display-line x) x) ;; this works though (define yyy (stream-map sqr (stream-enumerate-interval 1 10))) ;; reason why below wont work? (define xxx (stream-map shower (stream-enumerate-interval 1 10))) (define (stream-ref stream n) (if (= n 0) (stream-car stream) (stream-ref (stream-cdr stream) (- n 1)))) ;; ex 3.52 (define sum 0) (define (accum x) (set! sum (+ x sum)) sum) ;; customary infinite sequences with cons-stream (define (integers-starting-from n) (cons-stream n (integers-starting-from (+ n 1)))) (define integers (integers-starting-from 1)) ;; try to do on repl ;; (display-stream integers) ;; we can get other subset of infinite streams (define even-integers (stream-filter even? integers)) (define (divisible? x y) (= 0 (remainder x y))) (define (not-div-by-7 x) (lambda (x) (not (divisible? x 7)))) (define no-sevens (stream-filter not-div-by-7 integers)) ;; generate some interesting infinite inductive streams ;; like fibonacci series ;; like seive of erastothenes
true
4f948467f66e45b3ea70b1cc26604c93b855e095
7e15b782f874bcc4192c668a12db901081a9248e
/ty-scheme/common/coroutines.scm
5122f6b15febd187e7d1d3a9d5dff49f86c91e32
[]
no_license
Javran/Thinking-dumps
5e392fe4a5c0580dc9b0c40ab9e5a09dad381863
bfb0639c81078602e4b57d9dd89abd17fce0491f
refs/heads/master
2021-05-22T11:29:02.579363
2021-04-20T18:04:20
2021-04-20T18:04:20
7,418,999
19
4
null
null
null
null
UTF-8
Scheme
false
false
655
scm
coroutines.scm
(define-syntax coroutine (rsc-macro-transformer (let ((xfmr ; x: initial argument (lambda (x . body) `(letrec ((+local-control-state (lambda (,x) ,@body)) (resume (lambda (c v) (call/cc (lambda (k) (set! +local-control-state k) ; what? (c v)))))) (lambda (v) (+local-control-state v)))))) (lambda (e r) (apply xfmr (cdr e))))))
true
ff9a799d236bf47c505fb1556cddc28ed97302a4
7ab12c8b00310a7176b53d32072762ecea154c65
/srfi/chez9.5/match-test.scm
a7ed6fb1b783550becd422129ec92e473a02a7c1
[]
no_license
krfantasy/srfi-204
6752f3629a5562c6b233b4df6e682244aa34fe8c
1d745c1eafc57450fe7ee0c232be7c2fdf29bfee
refs/heads/master
2022-11-26T06:27:24.527512
2020-08-10T17:17:59
2020-08-10T17:17:59
286,407,023
0
0
null
2020-08-10T07:30:59
2020-08-10T07:30:58
null
UTF-8
Scheme
false
false
180
scm
match-test.scm
(import (scheme) (srfi :0) (srfi :64) (srfi :9) (match)) (define test-name "chez-match-test") (define scheme-version-name (scheme-version)) (include "./match-chez-common.scm")
false
5747f522f62d264a888b6ebb4aaf4e24619e04d0
ece1c4300b543df96cd22f63f55c09143989549c
/Chapter2/Exercise 2.64.scm
e78c48ad015fd039849fc2834410fb06d42f8264
[]
no_license
candlc/SICP
e23a38359bdb9f43d30715345fca4cb83a545267
1c6cbf5ecf6397eaeb990738a938d48c193af1bb
refs/heads/master
2022-03-04T02:55:33.594888
2019-11-04T09:11:34
2019-11-04T09:11:34
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,062
scm
Exercise 2.64.scm
; Exercise 2.64: The following procedure list->tree converts an ordered list to a balanced binary tree. The helper procedure partial-tree takes as arguments an integer nn and list of at least nn elements and constructs a balanced tree containing the first nn elements of the list. The result returned by partial-tree is a pair (formed with cons) whose car is the constructed tree and whose cdr is the list of elements not included in the tree. (define (make-tree entry left right) (list entry left right)) (define (list->tree elements) (car (partial-tree elements (length elements)))) (define (partial-tree elts n) (if (= n 0) (cons '() elts) (let ((left-size (quotient (- n 1) 2))) (let ((left-result (partial-tree elts left-size))) (let ((left-tree (car left-result)) (non-left-elts (cdr left-result)) (right-size (- n (+ left-size 1)))) (let ((this-entry (car non-left-elts)) (right-result (partial-tree (cdr non-left-elts) right-size))) (let ((right-tree (car right-result)) (remaining-elts (cdr right-result))) (cons (make-tree this-entry left-tree right-tree) remaining-elts)))))))) (define a (list->tree (list 1 2 3 4 5 6 7 8))) (display a) ;1 Write a short paragraph explaining as clearly as you can how partial-tree works. Draw the tree produced by list->tree for the list (1 3 5 7 9 11). ; 1 set the size of left tree as (quotient (- n 1) 2)), always equal or smaller by one than the half of (- n 1), ; 2 then call (partial-tree elts left-size), and suppose it returns a (cons lefttree, rest of the eles), (implementation details on procedure on the last part). ; 3 separate the the above results and take away the first of the eles as entry of the current point. ; 4 set the size of the right tree as (- n (+ left-size 1)), (equation: right-size + left-size + 1(current-point) = n, and right -size is at best biggier than left size by one or equal) ; 5 same as step 2 ; 6 (cons (make-tree this-entry ; left-tree ; right-tree) ; remaining-elts) ; for remaining-eles, at the left most of the leave, it is full, that leave in step 2 take one away(left-size), then this entry get the second one, then the left get one too,it makes one sub blanced tree, and return as a (lefttree) with the (remaining-elts and proceed with the same procedure) ;2 What is the order of growth in the number of steps required by list->tree to convert a list of nn elements? ; 0(n) ; every elements is visit once, with (cons '() elts) at the leave or cdr in the rest entry to take a apart from the list
false
060c10411fbd6cc244dbfbc3275ef8e992e0536b
4b480cab3426c89e3e49554d05d1b36aad8aeef4
/chapter-04/ex4.29-comkid-test-for-memoization.scm
3b2d242bdb919b52962b7e5c79736077867270f9
[]
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
597
scm
ex4.29-comkid-test-for-memoization.scm
(load "ch4-myeval-for-lazy-comkid.scm") (load "ch4-force-it-with-memoization.scm") (load "../misc/scheme-test-r5rs.scm") (define the-global-environment (setup-environment)) (myeval '(define count 0) the-global-environment) (myeval '(define (id x) (set! count (+ count 1)) x) the-global-environment) (myeval '(define (square x) (* x x)) the-global-environment) (run-named-test "ex4.29 Test" (make-testcase '(assert-equal? 100 (myeval '(square (id 10)) the-global-environment)) '(assert-equal? 1 (myeval 'count the-global-environment)) ))
false
9e2d775e2715b6208b7a94f164b714184fca0129
d6cb5370b9502942b755e884ab953e94bc3f2e2a
/17_input_of_words.scm
9ecad84f4e72cc5efd19306b705626b46de3b984
[]
no_license
AsadiR/Scheme_tasks
7df4279f5e1749182f138f554fb40d96e6d4436a
f28927044a7a7e40b913126c8da44c551f35c4dc
refs/heads/master
2021-05-04T07:47:21.261738
2016-10-12T12:13:36
2016-10-12T12:13:36
70,696,735
0
0
null
null
null
null
UTF-8
Scheme
false
false
199
scm
17_input_of_words.scm
(define fname "17input.txt") (define fp (open-input-file fname)) (define (read-words) (define word (read)) (cond ((eof-object? word) '()) (else (cons word (read-words))))) (read-words)
false
3083af4fb4f8529d88c302f7b82fefc6269b1347
a1737280e5bde10cf78c3514c1b0713ec750d36b
/lang/scheme/learn-scheme/prac.scm
222c9d6ded143597b96847656e983bae63e7acfa
[]
no_license
kaiwk/playground
ee691f6a98f6870e9e53dcf901c85dddb2a9d0cc
cf982a8ba769a232bfc63fd68f36fe863ca7a4c5
refs/heads/master
2022-02-19T01:23:49.474229
2019-09-05T12:59:13
2019-09-05T12:59:13
56,390,601
3
0
null
null
null
null
UTF-8
Scheme
false
false
643
scm
prac.scm
;; loop 1-10 (define (looping) (let loop ((x 0)) (if (< x 10) (begin (display x) (newline) (loop (+ 1 x)))))) ;; fib (define (fib n) (if (or (= n 1) (= n 2) (= n 0)) 1 (+ (fib (- n 1)) (fib (- n 2))))) ;; fac (define (fac n) (if (= n 0) 1 (* n (fac (- n 1))))) ;; fac tail recursive (define (fac-h n res) (if (= n 0) res (fac-h (- n 1) (* n res)))) (define (fac-tail n) (fac-h n 1)) (define (fac-tail n init) (lambda (n product) (if (= n 0) product (fac-tail (- n 1) (* init n)))) n init)
false
231fe54f455425bf9aed264811eaf08e4ef9fe5b
18e69f3b8697cebeccdcd7585fcfc50a57671e21
/scheme/balance.scm
6c8375186d247ad0784f5f833afefb092a0667bd
[]
no_license
ashikawa/scripts
694528ccfd0b84edaa980d6cde156cfe394fe98a
c54463b736c6c01781a0bfe00472acd32f668550
refs/heads/master
2021-01-25T04:01:34.073018
2013-12-02T03:33:29
2013-12-02T03:33:29
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
869
scm
balance.scm
(load "./inc/std.scm") (define (make-account balance) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount)) balance) (define (dispatch m) (cond ((eq? m 'withdraw) withdraw) ((eq? m 'deposit) deposit) (else (error "Unknown request -- MAKE-ACCOUNT" m)))) dispatch) (define (make-account-with-secret password balance) (define acc (make-account balance)) (define (dispatch-secret p m) (if (eq? p password) (acc m) "Inncorrect password ")) dispatch-secret) (define acc (make-account-with-secret 'pass 100)) (display ((acc 'pass 'withdraw) 50)) (newline) (display ((acc 'pass 'withdraw) 60)) (newline) (display ((acc 'pass 'deposit) 40)) (newline) (display ((acc 'pass 'withdraw) 60)) (newline)
false
4c36dc58ae4efdd377f21d028b32c9b6ba6fb8f8
9b0c653f79bc8d0dc87526f05bdc7c9482a2e277
/1/1-33.ss
d3ca133e20a9784f6f6bbbff3dcd5bebc2d06331
[]
no_license
ndNovaDev/sicp-magic
798b0df3e1426feb24333658f2313730ae49fb11
9715a0d0bb1cc2215d3b0bb87c076e8cb30c4286
refs/heads/master
2021-05-18T00:36:57.434247
2020-06-04T13:19:34
2020-06-04T13:19:34
251,026,570
0
0
null
null
null
null
UTF-8
Scheme
false
false
514
ss
1-33.ss
(define (next n) (+ n 1)) (define (noneTerm n) n) (define (isEven n) (= 0 (remainder n 2))) (define (accumulate filter combiner null-value term a next b) (define (iter a result) (cond ((> a b) result) ((filter a) (iter (next a) (combiner (term a) result))) (else (iter (next a) result)))) (iter a null-value)) ; 偷懒,只计算了偶数相加,没有算素数和、互素乘积 (define (evenSum a b) (accumulate isEven + 0 noneTerm a next b)) (display (evenSum 1 8)) (exit)
false
5f77e48ba8868b8264348dcc89735ebbf7f9054c
67075ba6b854c2277e25283ec172242df2b41447
/compare/racket/racket_filtern.scm
0abc2d012a2043ed02a9806368c22363f3e6a69b
[]
no_license
shiplift/theseus-bench
4391abcd430317a51ffae17dce7a3cb6b881cfbd
3ec38fba7668fdf4318b112e759f5e6078e04822
refs/heads/master
2020-09-19T21:34:16.873956
2019-12-12T11:35:17
2019-12-12T11:36:03
224,303,592
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,463
scm
racket_filtern.scm
#lang racket/base (require (for-syntax racket/base)) (require (prefix-in r: racket/base)) (require "cons-emulation.rktl") (define-syntax time (lambda (stx) (syntax-case stx () [(_ expr1 expr ...) (syntax/loc stx (let-values ([(v cpu user gc) (time-apply (lambda () expr1 expr ...) null)]) (printf "0:RESULT-cpu:ms: ~a.0\n0:RESULT-total:ms: ~a.0\n0:RESULT-gc:ms: ~a.0\n" cpu user gc) (apply values v)))]))) (letrec ([e 17] [f 36] [head car] [tail cdr] [racket-filter (lambda (p l) (cond [(null? l) '()] [(p (head l)) (cons (head l) (racket-filter p (tail l)))] [else (racket-filter p (tail l))]))] [make-list (lambda (n) (letrec ((aux (lambda (m acc) (if (= 0 m) acc (aux (- m 1) (cons (if (odd? m) e f) acc)))))) (aux n '())))] [flt (lambda (x) (= x e))] [listnum (lambda (l) (let* ([pairish (r:pair? l)] [numberish (if pairish (string->number (r:car l)) pairish)]) (if numberish numberish 5000000)))] [num (listnum (vector->list (current-command-line-arguments)))] [l (make-list num)]) (time (void (racket-filter flt l))))
true
9dc42006df6758d12be320f476a32aa8af3423dd
8a0660bd8d588f94aa429050bb8d32c9cd4290d5
/ext/time/time_stub.stub
374784c9792e4bc952cf194efc32c065c14cccca
[ "BSD-2-Clause" ]
permissive
david135/sagittarius-scheme
dbec76f6b227f79713169985fc16ce763c889472
2fbd9d153c82e2aa342bfddd59ed54d43c5a7506
refs/heads/master
2016-09-02T02:44:31.668025
2013-12-21T07:24:08
2013-12-21T07:24:08
32,497,456
0
0
null
null
null
null
UTF-8
Scheme
false
false
4,016
stub
time_stub.stub
;; -*- scheme -*- #!compatible (decl-code (.include <sagittarius.h>) (.define "LIBSAGITTARIUS_EXT_BODY") (.include <sagittarius/extend.h> <sagittarius-time.h>)) (define-cise-stmt assertion-violation ((_ who msg) `(begin (Sg_AssertionViolation ,who (SG_MAKE_STRING ,msg) '()))) ((_ who msg irritants) `(begin (Sg_AssertionViolation ,who (SG_MAKE_STRING ,msg) ,irritants) ))) (define-cise-stmt wrong-type-of-argument-violation ((_ who msg got) `(begin (Sg_WrongTypeOfArgumentViolation ,who (SG_MAKE_STRING ,msg) ,got '()))) ((_ who msg got irritants) `(begin (Sg_WrongTypeOfArgumentViolation ,who (SG_MAKE_STRING ,msg) ,got ,irritants)))) (define-type <time> "SgTime*") (define-c-proc make-time (type::<symbol> nsec::<number> sec::<number>) (result (Sg_MakeTime type (Sg_GetIntegerS64Clamp sec SG_CLAMP_NONE NULL) (Sg_GetIntegerClamp nsec SG_CLAMP_NONE NULL)))) (define-c-proc time? (o) ::<boolean> (result (SG_TIMEP o))) (define-c-proc time-type (o::<time>) (result (-> (SG_TIME o) type))) (define-c-proc time-nanosecond (o::<time>) (result (Sg_MakeInteger (-> (SG_TIME o) nsec)))) (define-c-proc time-second (o::<time>) (result (Sg_MakeIntegerFromS64 (-> (SG_TIME o) sec)))) (define-c-proc set-time-type! (o type::<symbol>) ::<void> (set! (-> (SG_TIME o) type) type)) (define-c-proc set-time-nanosecond! (o nsec::<number>) (set! (-> (SG_TIME o) nsec) (Sg_GetIntegerClamp nsec SG_CLAMP_NONE NULL))) (define-c-proc set-time-second! (o sec::<number>) (set! (-> (SG_TIME o) sec) (Sg_GetIntegerS64Clamp sec SG_CLAMP_NONE NULL))) (define-c-proc copy-time (o::<time>) (result (Sg_MakeTime (-> (SG_TIME o) type) (-> (SG_TIME o) sec) (-> (SG_TIME o) nsec)))) (define-c-proc time-resolution (:optional (type::<symbol> 'time-utc)) ::<fixnum> (cond ((SG_EQ type 'time-tai) (result 10000)) ((SG_EQ type 'time-utc) (result 10000)) ((SG_EQ type 'time-monotonic) (result 10000)) ((SG_EQ type 'time-thread) (result 10000)) ((SG_EQ type 'time-process) (result 10000)) (else (assertion-violation 'time-resolution "invalid-clock-type" type)))) (define-c-proc current-time (:optional (type::<symbol> 'time-utc)) (result (Sg_CurrentTime type))) (define-c-proc time->seconds (o::<time>) (result (Sg_TimeToSeconds (SG_TIME o)))) (define-c-proc seconds->time (o::<number>) (result (Sg_SecondsToTime (Sg_GetIntegerS64Clamp o SG_CLAMP_NONE NULL)))) (define-c-proc time<=? (x::<time> y::<time>) ::<boolean> (let ((compare::SgClassCompareProc (-> (SG_CLASS_OF x) compare))) (result (<= (compare x y FALSE) 0)))) (define-c-proc time<? (x::<time> y::<time>) ::<boolean> (let ((compare::SgClassCompareProc (-> (SG_CLASS_OF x) compare))) (result (< (compare x y FALSE) 0)))) (define-c-proc time=? (x::<time> y::<time>) ::<boolean> (let ((compare::SgClassCompareProc (-> (SG_CLASS_OF x) compare))) (result (== (compare x y FALSE) 0)))) (define-c-proc time>=? (x::<time> y::<time>) ::<boolean> (let ((compare::SgClassCompareProc (-> (SG_CLASS_OF x) compare))) (result (>= (compare x y FALSE) 0)))) (define-c-proc time>? (x::<time> y::<time>) ::<boolean> (let ((compare::SgClassCompareProc (-> (SG_CLASS_OF x) compare))) (result (> (compare x y FALSE) 0)))) (define-c-proc time-difference (x::<time> y::<time>) (result (Sg_TimeDifference x y (SG_TIME (Sg_MakeTime #f 0 0))))) (define-c-proc time-difference! (x::<time> y::<time>) (result (Sg_TimeDifference x y x))) (define-c-proc add-duration (x::<time> y::<time>) (result (Sg_AddDuration x y (SG_TIME (Sg_MakeTime (-> (SG_TIME x) type) 0 0))))) (define-c-proc add-duration! (x::<time> y::<time>) (result (Sg_AddDuration x y x))) (define-c-proc subtract-duration (x::<time> y::<time>) (result (Sg_SubDuration x y (SG_TIME (Sg_MakeTime (-> (SG_TIME x) type) 0 0))))) (define-c-proc subtract-duration! (x::<time> y::<time>) (result (Sg_SubDuration x y x)))
false
45b16d12765ffcaecd75d1f7c56d5b57ff85992d
d1ef1938e1f388aee6b1343f334ea63732d4e251
/r5rs.scm
018ce0beb4a6492b6f3f6c66460a9034bb80cb38
[]
no_license
uberblah/goops-feqxprt
3aa56d0b218d98757bc0b0ec619464d0bf557b59
509fdb1f3f32224cc4ce9ea41b64d458ff4c9380
refs/heads/master
2021-01-10T02:03:32.200142
2015-12-30T08:28:06
2015-12-30T08:28:06
48,202,470
0
0
null
null
null
null
UTF-8
Scheme
false
false
7,986
scm
r5rs.scm
(include "feval.scm") ; TODO: Make modules (use-modules (srfi srfi-1) (srfi srfi-26) (djf fstruct) (oop goops) (ice-9 match) ;(feval) ) (define r5rs-proc-env (procs->env ; equivalence eqv? eq? equal? ; numbers number? complex? real? rational? integer? exact? inexact? = < > <= >= zero? positive? negative? odd? even? + - * quotient remainder modulo max min abs numerator denominator gcd lcm floor ceiling truncate round rationalize expt / exp log sin cos tan asin acos atan sqrt make-rectangular make-polar real-part imag-part magnitude angle exact->inexact inexact->exact number->string string->number ; booleans not boolean? ; pairs and lists pair? cons car cdr set-car! caar cadr cdar cddr caaar caadr cadar caddr cdaar cdadr cddar cdddr caaaar caaadr caadar caaddr cadaar cadadr caddar cadddr cdaaar cdaadr cdadar cdaddr cddaar cddadr cdddar cddddr null? list? list length append reverse list-tail list-ref memq memv member assq assv assoc ; symbols symbol? symbol->string string->symbol ; characters char? char=? char<? char>? char<=? char>=? char-ci=? char-ci<? char-ci<=? char-ci>=? char-alphabetic? char-numeric? char-whitespace? char-upper-case? char-lower-case? char->integer integer->char char-upcase char-downcase ; strings string? make-string string string-length string-ref string-set! string=? string>? string>? string<=? string>=? string-ci<? string-ci>? string-ci<=? string-ci>=? substring string-append string->list list->string string-copy string-fill! ; vectors vector? make-vector vector vector-length vector-ref vector-set! vector->list list->vector vector-fill! ; control features procedure? apply map for-each force call-with-current-continuation values call-with-values dynamic-wind ; eval eval #;scheme-report-environment #;null-environment interaction-environment ; ports call-with-input-file call-with-output-file input-port? output-port? current-input-port current-output-port with-input-from-file with-output-to-file open-input-file open-output-file close-input-port close-output-port ; input read read-char peek-char eof-object? char-ready? ; output write display newline write-char ; system interface load #;transcript-on #;transcript-off)) (define r5rs-base-env (append r5rs-proc-env lisp-base-env)) (define (r5rs-valid-definition? expr) (match expr (('define (f . args) . _) (fold-right (lambda (x y) (and y (symbol? x))) #t args)) (('define (? symbol? _) _) #t) (('begin . body) (every r5rs-valid-definition? body)) (_ #f))) (define (r5rs-definition? expr) (match expr (('define . _) #t) (('begin . body) (every r5rs-definition? body)) (_ #f))) (define (r5rs-transform-body body) (define (get-defs def prev-defs) (match def (('define (f . args) . body) `((,f (lambda ,args ,(r5rs-transform-body body))) . ,prev-defs)) (('define var val) `((,var ,val) . ,prev-defs)) (('begin . defs) (fold get-defs prev-defs defs)))) (define (rec defs body) (match body ((a . b) (cond ((r5rs-valid-definition? a) (rec (get-defs a defs) b)) ((r5rs-definition? a) (error "Invalid R5RS definition:" a)) ((null? defs) `(begin . ,body)) (else `(letrec ,(reverse defs) (begin . ,body))))))) (rec '() body)) #| ; halting work on syntax-rules, see notes/r5rs (define (sr-ell-form form) (and (pair? form) (pair? (cdr form)) (null? (cddr form)) (equal? (cadr form) '...))) (define (sr-check pattern template lits) (define (get-vars pattern) (cond ((member pattern lits) '()) ((symbol? pattern) (list pattern)) ((vector? pattern) (get-vars (vector->list pattern))) ((pair? pattern) (match pattern ((a (? (cut equal? <> '...) _)) (map (cut cons <> '...) (get-vars a))) ((a . b) (append (get-vars a) (get-vars b))))) (else '()))) (define (check-vars vars prev) (match vars (() #t) (((var . '...) . rest) (check-vars `(,var . ,rest) prev)) ((var . rest) (and (not (member var rest)) (check-vars rest (cons var prev)))) (_ #f))) (define (check-template template vvars evars ivars) (cond ((vector? template) (check-template (vector->list template) vvars evars ivars)) ((sr-ell-form template) => (cut check-template <> vvars (map car (filter pair? evars)) (append (filter (negate pair?) evars) ivars))) ((pair? template) (and (check-template (car template) vvars evars ivars) (check-template (cdr template) vvars evars ivars))) (else (or (member template vvars) (member template evars) (not (member template ivars)))))) (let ((vars (get-vars pattern))) (cond ((not (check-vars vars '())) (error "Duplicate variables in pattern" pattern)) ((check-template template (filter (negate pair?) vars) (filter pair? vars) ivars)) (else (error "Incompatible ellipsis between pattern and template" (cons pattern template)))))) (define (sr-matcher pattern lits) (define (ellipsis-matcher inner-pattern) (define (transpose l) (apply map list l)) (define l (sr-matcher inner-pattern)) (lambda (expr) (let ((m (map l expr))) (and (every identity m) (let ((vars (map (lambda (x) (cons (car x) '...)) m)) (vals (transpose (map cdr m)))) (map cons vars vals)))))) (cond ((member pattern lits) (const '())) ((symbol? pattern) (cut acons pattern <> '())) ((vector? pattern) (let ((l (sr-matcher (vector->list pattern) lits))) (lambda (x) (and (vector? x) (l (vector->list x)))))) ((sr-ell-form pattern) => ellipsis-matcher) ((pair? pattern) (let ((la (sr-matcher (car pattern) lits)) (lb (sr-matcher (cdr pattern) lits))) (lambda (x) (let ((va (la (car x))) (vb (lb (cdr x)))) (and va vb (append va vb)))))) (else (lambda (x) (and (equal? x pattern) '()))))) (define (sr-expander template binds) (define (ell? x) (equal? x '...)) (define (rec template vbinds ebinds einvalid) (cond ((symbol? template) (let ((a (assoc template vbinds))) (if a (cdr a) template))) ((vector? template) (list->vector (rec (vector->list template) vbinds ebinds))) ((sr-ell-form template) (rec template vbinds (map (lambda (x) (cons (caar x) (cdr x))) (filter (compose pair? car) ebinds)) (append (filter (compose (negate pair?) car) ebinds) vbinds))) ((pair? template) (cons (rec (car template) vbinds ebinds einvalid) (rec (cdr template) vbinds ebinds einvalid))))) (rec template vbinds ebinds '())) |# ; R5RS derived expressions: cond case and or let let* letrec begin do delay quasiquote #| (r5rs-transform-body '((begin (define a b)) (define (b) c) expr1 (expr2))) (r5rs-transform-body '(expr)) (syntax-rules-proc '(1 2 3) 5 '(syntax-rules () ((_ (a b))) ())) (syntax-rules-proc '(1 2 3) 5 '(syntax-rules () ((_ a ...) (list a ...)))) (syntax-rules-proc '(alist-alist 0 (1 2 3) (4 5 6) (7 8 9)) r5rs-base-env '(syntax-rules () ((_ beg (var val ...) ...) (list (list beg var val ...) ...)))) (define-syntax-rule (alist-alist beg (var val ...) ...) (list (list beg var val ...) ...)) (alist-alist 0 (1 2 3) (4 5 6) (7 8 9)) |#
true
23d2bec4b69d55ac09924d05e5706ca41d63f1f1
da2114279d57b3428cec5d43f191fac50aaa3053
/yast-cn/chapter 07/ex3.ss
c0b1282032718d4e32434a82b3eed84288f85d5a
[]
no_license
ntzyz/scheme-exercise
7ac05d6ac55f756376b272d817c21c1254a1d588
c845dd27c6fc0c93027ac1b7d62aa8f8204dd677
refs/heads/master
2020-04-09T07:51:08.212584
2019-03-11T09:21:45
2019-03-11T09:21:45
160,173,089
2
0
null
null
null
null
UTF-8
Scheme
false
false
1,791
ss
ex3.ss
; 一个分别接受一个表ls和一个对象x的函数,该函数返回从 ; ls中删除x后得到的表。 (define (remove-item ss target) (let loop((ss ss) (res '())) (if (null? ss) res (let ((head (car ss))) (loop (cdr ss) (if (= head target) res (cons head res))))))) ; 一个分别接受一个表ls和一个对象x的函数,该函数返回 ; x在ls中首次出现的位置。索引从0开始。如果x不在ls中, ; 函数返回#f。 (define (index-of ss target) (let loop((ss ss) (idx 0)) (if (null? ss) #f (if (= (car ss) target) idx (loop (cdr ss) (+ 1 idx)))))) ; 用于翻转表元素顺序的my-reverse函数。(reverse函数是预定义函数) (define (my-reverse ss) (let loop((ss ss) (res '())) (if (null? ss) res (loop (cdr ss) (cons (car ss) res))))) ; 求和由数构成的表。 (define (my-sum ss) (let loop((ss ss) (ans 0)) (if (null? ss) ans (loop (cdr ss) (+ (car ss) ans))))) ; 将一个代表正整数的字符串转化为对应整数。 ; 例如,"1232"会被转化为1232。不需要检查不合法的输入。 ; 提示,字符到整数的转化是通过将字符#\0……#\9的ASCII减去48, ; 可以使用函数char->integer来获得字符的ASCII码。 ; 函数string->list可以将字符串转化为由字符构成的表。 (define (atoi string) (let loop((ss (string->list string)) (res 0)) (if (null? ss) res (loop (cdr ss) (+ (* res 10) (char->integer (car ss)) -48))))) ; range函数:返回一个从0到n的表(但不包含n) (define (range n) (let loop((res '()) (current 0)) (if (= current n) res (loop (cons (- n current 1) res) (+ current 1)))))
false
c0dfa306411a45587984da9b7a0e10b48c40a741
bef204d0a01f4f918333ce8f55a9e8c369c26811
/src/tspl-6-Operations-on-Objects/6.7-Characters.ss
00cf0461c2501d378f9796d8425f91c5db2ce71d
[ "MIT" ]
permissive
ZRiemann/ChezSchemeNote
56afb20d9ba2dd5d5efb5bfe40410a5f7bb4e053
70b3dca5d084b5da8c7457033f1f0525fa6d41d0
refs/heads/master
2022-11-25T17:27:23.299427
2022-11-15T07:32:34
2022-11-15T07:32:34
118,701,405
5
0
null
null
null
null
UTF-8
Scheme
false
false
131
ss
6.7-Characters.ss
#!/usr/bin/scheme --script (display " ================================================================================ The End. ")
false
816e6d9f913db00a75ffe96b36c1dc838b856d09
23339417dc5af41ff46434d79f3d053d2780131c
/compile-all.ss
cfae53c2a8de2725209cfe3fc57f62bb8063462f
[]
no_license
fedeinthemix/chez-matchable
12f49dcf2ed763d6ebea434c2b126ecc9d0d63b6
73e46432ae70ec72eba6ef116bd84ad9ee38b2f2
refs/heads/master
2020-04-01T18:02:20.203909
2018-09-13T18:49:05
2018-09-13T18:49:05
61,033,123
9
0
null
null
null
null
UTF-8
Scheme
false
false
960
ss
compile-all.ss
#! /usr/bin/env scheme-script ;;; Copyright (c) 2016 Federico Beffa <[email protected]> ;;; ;;; Permission to use, copy, modify, and distribute this software for ;;; any purpose with or without fee is hereby granted, provided that the ;;; above copyright notice and this permission notice appear in all ;;; copies. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL ;;; WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE ;;; AUTHOR 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. (import (chezscheme)) (parameterize ((compile-imported-libraries #t)) (map compile-library '("matchable.sls")))
false
9cc9ff2a9393e418196bb1d91a06b46a45757d96
ebc5db754946092d65c73d0b55649c50d0536bd9
/2020/day15.scm
3e0dd7ec545a260348840404059b1ba3faf97fb6
[]
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
2,136
scm
day15.scm
#!/usr/local/bin/csi -s (import (chicken format) (srfi 1)) (declare (fixnum-arithmetic) (block)) (define (vector-grow-and-set! vec i val) (if (< i (vector-length vec)) (begin (vector-set! vec i val) vec) (let ((newvec (vector-resize vec (max (* (vector-length vec) 2) (+ i 1)) #f))) (vector-set! newvec i val) newvec))) (define (solve numbers last-turn) (let* ((history (make-vector 10000000 #f)) (turn (fold (lambda (num turn) (vector-set! history num turn) (+ turn 1)) 1 (drop-right numbers 1)))) (let loop ((turn turn) (num (last numbers)) (history history)) (cond ((= turn last-turn) num) ((and (< num (vector-length history)) (vector-ref history num)) => (lambda (last-said) (loop (+ turn 1) (- turn last-said) (vector-grow-and-set! history num turn)))) (else (loop (+ turn 1) 0 (vector-grow-and-set! history num turn))))))) (define (test inputs last-turn) (let loop ((inputs inputs)) (unless (null? inputs) (let* ((input (caar inputs)) (expected (cdar inputs)) (result (solve input last-turn))) (if (= expected result) (printf "~S => ~A PASS~%" input result) (printf "~S => ~A but got ~A FAIL~%" input expected result))) (loop (cdr inputs))))) (define (test1) (test '(((0 3 6) . 436) ((1 3 2) . 1) ((2 1 3) . 10) ((1 2 3) . 27) ((2 3 1) . 78) ((3 2 1) . 438) ((3 1 2) . 1836)) 2020)) (define (test2) (test '(((0 3 6) . 175594) ((1 3 2) . 2578) ((2 1 3) . 3544142) ((1 2 3) . 261214) ((2 3 1) . 6895259) ((3 2 1) . 18) ((3 1 2) . 362)) 30000000)) ;;;(test1) ;;; Slow! ;;;(test2) (define input '(0 14 6 20 1 4)) (printf "Part 1: ~A~%" (solve input 2020)) (printf "Part 2: ~A~%" (solve input 30000000))
false
cffe787780c65b83cd039ecda392fed40355332e
84c9e7520891b609bff23c6fa3267a0f7f2b6c2e
/2.71.scm
a0c95c574e9d852008f2e85840370dde777142a4
[]
no_license
masaedw/sicp
047a4577cd137ec973dd9a7bb0d4f58d29ef9cb0
11a8adf49897465c4d8bddb7e1afef04876a805d
refs/heads/master
2020-12-24T18:04:01.909864
2014-01-23T11:10:11
2014-01-23T11:17:38
6,839,863
1
0
null
null
null
null
UTF-8
Scheme
false
false
990
scm
2.71.scm
(load "./2.70.scm") (define sign5 '((A 1) (B 2) (C 4) (D 8) (E 16))) (define sign10 '((A 1) (B 2) (C 4) (D 8) (E 16) (F 32) (G 64) (H 128) (I 256) (J 512))) (define (main args) (let ((t5 (generate-huffman-tree sign5)) (t10 (generate-huffman-tree sign10))) (print "sign5") (print (encode '(A) t5)) (print (encode '(B) t5)) (print (encode '(C) t5)) (print (encode '(D) t5)) (print (encode '(E) t5)) (print "sign10") (print (encode '(A) t10)) (print (encode '(B) t10)) (print (encode '(C) t10)) (print (encode '(D) t10)) (print (encode '(E) t10)) (print (encode '(F) t10)) (print (encode '(G) t10)) (print (encode '(H) t10)) (print (encode '(I) t10)) (print (encode '(J) t10)))) ;; n 個の記号の出現頻度を 1, 2, ... , n-1 とした場合、 ;; 最高頻度の符号を表すのに必要なビット数は 1 であり、 ;; 最低頻度の符号を表すのに必要なビット数は n である。
false
f2528fd858eb8f37a6031f8f6a0ec52d882f0036
4b2aeafb5610b008009b9f4037d42c6e98f8ea73
/16/chapter.scm
62bf8acdb5b89e930c3b9707b966bea3880ede8a
[]
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
710
scm
chapter.scm
(require-extension syntax-case array-lib array-lib-hof foof-loop (srfi 1 9 26 31 69 95)) (require '../srfi/srfi-70) (require '../util/util) (require '../16.3/section) (module chapter-16 (greedy-change power-change dynamic-change make-change make-task non-preemptive-schedule preemptive-schedule task-id average-completion task-completion) (import* srfi-70 exact-floor) (import* util debug) (import* section-16.3 make-heap build-heap! heapsort! heap-insert! heap-empty? heap-union! heap-extremum heap-extract-extremum! heap-data) (include "../16/change.scm") (include "../16/schedule.scm"))
false
eaebc6cc7fc8f441847c7096ce6805fc793036d0
8981787979ca36cfb38070afec4c53a7dc7a3126
/15.ss
2a7a08fa63330a7cc11cda15d9d3705aecd92642
[]
no_license
hernanre/CSSE304
c52750004bb981b0bbbca20ba3341945b9dcb5e6
26e88a35f136aa4bb9c76539cb706958db1db0bb
refs/heads/master
2021-12-15T08:30:35.067405
2017-08-05T15:28:12
2017-08-05T15:28:12
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
5,408
ss
15.ss
;Han Wei Assignment15 ;#2 In this way, we do not need to consider the size of the variable we need. Therefore in this way, our function can work for other calculation too. (define apply-continuation (lambda (k v) (k v))) ;#1 ;(a) (define member?-cps (lambda (ele ls k) (cond [(null? ls) (apply-continuation k #f)] [(eq? ele (car ls)) (apply-continuation k #t)] [else (member?-cps ele (cdr ls) k)]))) ;(b) (define set?-cps (lambda (ls k) (cond [(null? ls) (apply-continuation k #t)] [(not (pair? ls)) (apply-continuation k #f)] [else (member?-cps (car ls) (cdr ls) (lambda (condi) (if condi (apply-continuation k #f) (set?-cps (cdr ls) k))))]))) (define 1st-cps (lambda (ls k) (apply-continuation k (car ls)))) (define set-of-cps (lambda (ls k) (cond [(null? ls) (apply-continuation k '())] [else (set-of-cps (cdr ls) (lambda (rls) (member?-cps (car ls) rls (lambda (condi) (if condi (apply-continuation k rls) (apply-continuation k (cons (car ls) rls)))))))]))) (define map-cps (lambda (proc ls k) (cond [(null? ls) (apply-continuation k '())] [else (map-cps proc (cdr ls) (lambda (rls) (proc (car ls) (lambda (result) (apply-continuation k (cons result rls))))))]))) (define domain-cps (lambda (rel k) (map-cps 1st-cps rel (lambda (result) (set-of-cps result k))))) ;(c) (define make-cps (lambda (proc) (lambda (x k) (apply-continuation k (proc x))))) ;(d) (define andmap-cps (lambda (proc ls k) (cond[(null? ls) (apply-continuation k #t)] [else (proc (car ls) (lambda (condi) (if condi (andmap-cps proc (cdr ls) k) (apply-continuation k #f))))]))) ;(e) (define cps-snlist-recur (lambda (seed item-proc list-proc) (letrec ([helper (lambda (ls k) (cond [(null? ls) (apply-continuation k seed)] [(let ([c (car ls)]) (if (or (pair? c) (null? c)) (helper c (lambda (cls) (helper (cdr ls) (lambda (rls) (list-proc cls rls k))))) (helper (cdr ls) (lambda (rls) (item-proc c rls k)))))]))]) helper))) (define +-cps (lambda (a b k) (apply-continuation k (+ a b)))) (define append-cps (lambda (ls1 ls2 k) (cond [(null? ls2) (apply-continuation k ls1)] [else (append-cps (reverse (cons (car ls2) (reverse ls1))) (cdr ls2) k)]))) (define sn-list-reverse-cps (cps-snlist-recur '() (lambda (ele1 ele2 k) (append-cps ele2 (list ele1) k)) (lambda (ele1 ele2 k) (append-cps ele2 (list ele1) k)))) (define sn-list-occur-cps (lambda (s sls k) ((cps-snlist-recur 0 (lambda (e count k) (if (eq? e s) (+-cps 1 count k) (apply-continuation k count))) +-cps) sls k))) (define max-cps (lambda (num1 num2 k) (apply-continuation k (max num1 num2)))) (define sn-list-depth-cps (cps-snlist-recur 1 (lambda (ele sls k) (apply-continuation k sls)) (lambda (sls1 sls2 k) (max-cps (+ 1 sls1) sls2 k)))) ;2 (define memoize (lambda (f hash eqp) (let ([htb (make-hashtable hash eqp)]) (lambda args (let ([check (hashtable-ref htb args #f)]) (if check check (let ([result (apply f args)]) (hashtable-set! htb args result) result))))))) ;3 (define subst-leftmost (letrec ([helper (lambda (new old slist eq-f) (cond [(null? slist) (values #f '())] [(symbol? (car slist)) (if (eq-f (car slist) old) (values #t (cons new (cdr slist))) (call-with-values (lambda () (helper new old (cdr slist) eq-f)) (lambda (bool body) (values bool (cons (car slist) body)))))] [else (call-with-values (lambda () (helper new old (car slist) eq-f)) (lambda (boolf bodyf) (if boolf (values #t (cons bodyf (cdr slist))) (call-with-values (lambda () (helper new old (cdr slist) eq-f)) (lambda (boolb bodyb) (values boolb (cons bodyf bodyb)))))))]))]) (lambda (new old slist eq-f) (call-with-values (lambda () (helper new old slist eq-f)) (lambda (a b) b)))))
false
15b7e08c736930c51e8ecf81ce08505b97ca92c5
82d771f9c7a77fc0c084f6c5fca5d5b7480aa883
/demo/regexp.ss
3751a4b8e235155a139e5865be11979e639c6b95
[]
no_license
localchart/not-a-box
d45725722c0bfa6d07cf37ef4c33a5358b1dd987
b6c1af4fb0eb877610a3a20b5265a8c8d2dd28e9
refs/heads/master
2021-01-20T10:10:14.034524
2017-05-04T21:54:41
2017-05-04T21:54:41
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
77
ss
regexp.ss
(import (core) (regexp) (port)) (include "demo/regexp.scm")
false
6a9bd161859f793d35e362e692b3f16f78ce1bdc
c1bd77e99e38cbd3e8f18399fd117aa6a1721177
/packages/keybase.scm
281cde0d317b906e3a9fe639250746ac65281b7d
[]
no_license
jkopanski/guix
b016a57d95968042644aa56a4d1dda876ad96ac8
a6be12a1af7b76793314c7c04881948ca947c059
refs/heads/master
2021-08-31T23:30:03.126909
2017-12-23T13:29:48
2017-12-23T13:29:48
104,381,903
2
0
null
null
null
null
UTF-8
Scheme
false
false
8,014
scm
keybase.scm
(define-module (nat guix packages keybase) #:use-module (gnu packages golang) #:use-module (gnu packages linux) #:use-module (guix build-system go) #:use-module (guix download) #:use-module (guix git-download) #:use-module (guix licenses) #:use-module (guix packages)) (define keybase-build (lambda* (#:key import-path #:allow-other-keys) "Build the package named by IMPORT-PATH." (or (zero? (system* "go" "install" "-v" ; print the name of packages as they are compiled "-x" ; print each command as it is invoked ;; Respectively, strip the symbol table and debug ;; information, and the DWARF symbol table. "-ldflags=-s -w" ;; Pass missing arguments "-tags" "production" import-path)) (begin (display (string-append "Building '" import-path "' failed.\n" "Here are the results of `go env`:\n")) (system* "go" "env") #f)))) (define-public keybase (package (name "keybase") (version "1.0.36") (source (origin (method url-fetch) (uri (string-append "https://github.com/keybase/client/archive/v" version ".tar.gz")) (sha256 (base32 "1yjib1axssfxm7c1y837zyydic1ja2fb6v14xwkipvp9l3bakffx")))) (build-system go-build-system) (arguments `(#:import-path "github.com/keybase/client/go/keybase" #:unpack-path "github.com/keybase/" #:install-source? #f #:phases (modify-phases %standard-phases (add-after 'unpack 'rename-sources (lambda _ ;; ERROR: In procedure string-append: Wrong-type (expected string) ;; (rename-file (string-append "src/github.com/keybase/client-" version) (rename-file "src/github.com/keybase/client-1.0.36" "src/github.com/keybase/client"))) (add-after 'setup-environment 'setup-bindir (lambda* (#:key outputs #:allow-other-keys) (let* ((out (assoc-ref outputs "out")) (bin (string-append out "/bin"))) (setenv "GOBIN" bin)))) (replace 'build (lambda* (#:key import-path #:allow-other-keys) "Build the package named by IMPORT-PATH." (or (zero? (system* "go" "install" "-v" ; print the name of packages as they are compiled "-x" ; print each command as it is invoked ;; Respectively, strip the symbol table and debug ;; information, and the DWARF symbol table. "-ldflags=-s -w" ;; Pass missing arguments "-tags" "production" import-path)) (begin (display (string-append "Building '" import-path "' failed.\n" "Here are the results of `go env`:\n")) (system* "go" "env") #f))))))) (home-page "https://keybase.io/") (synopsis "Keybase Go Library, Client, Service") (description "Keybase is a new and free security app for mobile phones and computers.") (license bsd-3))) (define-public go-github-com-keybase-kbfs-kbfsfuse (let ((commit "v1.0.36") (revision "0")) (package (name "go-github-com-keybase-kbfs-kbfsfuse") (version (git-version "0.0.0" revision commit)) (source (origin (method git-fetch) (uri (git-reference (url "https://github.com/keybase/kbfs") (commit commit))) (file-name (git-file-name name version)) (sha256 (base32 "1wj118mblyq2060ixhn90h0n9fk1phfcwjviy44kbj2swlq6xpis")))) (build-system go-build-system) (inputs `(("fuse" ,fuse) ("keybase" ,keybase))) (arguments `(#:import-path "github.com/keybase/kbfs/kbfsfuse" #:unpack-path "github.com/keybase/kbfs" #:install-source? #f #:phases (modify-phases %standard-phases (replace 'build (lambda* (#:key import-path #:allow-other-keys) "Build the package named by IMPORT-PATH." (or (zero? (system* "go" "install" "-v" ; print the name of packages as they are compiled "-x" ; print each command as it is invoked ;; Respectively, strip the symbol table and debug ;; information, and the DWARF symbol table. "-ldflags=-s -w" ;; Pass missing arguments "-tags" "production" import-path)) (begin (display (string-append "Building '" import-path "' failed.\n" "Here are the results of `go env`:\n")) (system* "go" "env") #f))))))) (synopsis "Keybase Filesystem") (description "Keybase filesystem fuse driver") (home-page "https://keybase.io/") (license bsd-3)))) (define-public go-github-com-keybase-kbfs-kbfsgit (let ((commit "v1.0.36") (revision "0")) (package (name "go-github-com-keybase-kbfs-kbfsgit") (version (git-version "0.0.0" revision commit)) (source (origin (method git-fetch) (uri (git-reference (url "https://github.com/keybase/kbfs") (commit commit))) (file-name (git-file-name name version)) (sha256 (base32 "1wj118mblyq2060ixhn90h0n9fk1phfcwjviy44kbj2swlq6xpis")))) (build-system go-build-system) (inputs `(("go-github-com-keybase-kbfs-kbfsfuse" ,go-github-com-keybase-kbfs-kbfsfuse))) (arguments `(#:import-path "github.com/keybase/kbfs/kbfsgit/git-remote-keybase" #:unpack-path "github.com/keybase/kbfs" #:install-source? #f #:phases (modify-phases %standard-phases (replace 'build (lambda* (#:key import-path #:allow-other-keys) "Build the package named by IMPORT-PATH." (or (zero? (system* "go" "install" "-v" ; print the name of packages as they are compiled "-x" ; print each command as it is invoked ;; Respectively, strip the symbol table and debug ;; information, and the DWARF symbol table. "-ldflags=-s -w" ;; Pass missing arguments "-tags" "production" import-path)) (begin (display (string-append "Building '" import-path "' failed.\n" "Here are the results of `go env`:\n")) (system* "go" "env") #f))))))) (synopsis "KBFS git remote") (description "Encrypted git repos over Keybase filesystem") (home-page "https://keybase.io/") (license bsd-3))))
false
cbb1a0b922cd9a52fd3c60f0d26db4b23c534a08
49ce71db04085d8a3ce90a9b3b8925fb36cc865d
/test-irregex-utf8.scm
c8deaa61a0e2e0d52b2b24fc4297bdc8315c5172
[]
no_license
fedeinthemix/chez-irregex
f3e0eb8cf85cef90dffd5a5484724038cd1b9826
0492ffefd660dea03401d013ad6d484eb3d7d8db
refs/heads/master
2021-01-09T20:11:13.163733
2016-06-13T12:32:55
2016-06-13T12:32:55
61,034,245
6
1
null
null
null
null
UTF-8
Scheme
false
false
1,760
scm
test-irregex-utf8.scm
#!/usr/local/bin/csi -script (import (rename (chezscheme) (format sprintf) (call-with-string-output-port call-with-output-string)) (rename (srfi :64) (test-equal test)) (test-utils) (irregex) (matchable)) ;; (use test extras utils irregex) (test-begin "test-irregex-utf8") (test-assert (irregex-search "(?u:<..>)" "<漢字>")) (test-assert (irregex-search "(?u:<.*>)" "<漢字>")) (test-assert (irregex-search "(?u:<.+>)" "<漢字>")) (test-assert (not (irregex-search "(?u:<.>)" "<漢字>"))) (test-assert (not (irregex-search "(?u:<...>)" "<漢>"))) (test-assert (irregex-search "(?u:<[^a-z]*>)" "<漢字>")) (test-assert (not (irregex-search "(?u:<[^a-z]*>)" "<漢m字>"))) (test-assert (irregex-search "(?u:<[^a-z][^a-z]>)" "<漢字>")) (test-assert (irregex-search "(?u:<あ*>)" "<あ>")) (test-assert (irregex-search "(?u:<あ*>)" "<ああ>")) (test-assert (not (irregex-search "(?u:<あ*>)" "<あxあ>"))) (test-assert (irregex-search "(?u:<[あ-ん]*>)" "<あん>")) (test-assert (irregex-search "(?u:<[あ-ん]*>)" "<ひらがな>")) (test-assert (not (irregex-search "(?u:<[あ-ん]*>)" "<ひらgがな>"))) (test-assert (not (irregex-search "(?u:<[^あ-ん語]*>)" "<語>"))) (test-assert (irregex-search "(?u:<[^あ-ん]*>)" "<abc>")) (test-assert (not (irregex-search "(?u:<[^あ-ん]*>)" "<あん>"))) (test-assert (not (irregex-search "(?u:<[^あ-ん]*>)" "<ひらがな>"))) (test-assert (irregex-search "(?u:<[^あ-ん語]*>)" "<abc>")) (test-assert (not (irregex-search "(?u:<[^あ-ん語]*>)" "<あん>"))) (test-assert (not (irregex-search "(?u:<[^あ-ん語]*>)" "<ひらがな>"))) (test-assert (not (irregex-search "(?u:<[^あ-ん語]*>)" "<語>"))) (test-end "test-irregex-utf8")
false
5e79103f640e67bba62be1d846f12d0160118058
ac2a3544b88444eabf12b68a9bce08941cd62581
/gsc/tests/14-keyword/key2str.scm
131c00913777bff3e00c62dffbbf867bafcdd8d6
[ "Apache-2.0", "LGPL-2.1-only" ]
permissive
tomelam/gambit
2fd664cf6ea68859d4549fdda62d31a25b2d6c6f
d60fdeb136b2ed89b75da5bfa8011aa334b29020
refs/heads/master
2020-11-27T06:39:26.718179
2019-12-15T16:56:31
2019-12-15T16:56:31
229,341,552
1
0
Apache-2.0
2019-12-20T21:52:26
2019-12-20T21:52:26
null
UTF-8
Scheme
false
false
251
scm
key2str.scm
(declare (extended-bindings) (not constant-fold) (not safe)) (define k1 'hello:) (define k2 '||:) (define k3 '|a b c|:) (define (test x) (let ((s (##keyword->string x))) (println s) (println (##string? s)))) (test k1) (test k2) (test k3)
false
91725f889388943450a018f705462aa81bc61890
84c9e7520891b609bff23c6fa3267a0f7f2b6c2e
/sicp/ddp.scm
ba8f151a931a91b99a0abd3d8fed9fbc1e04e6c4
[]
no_license
masaedw/sicp
047a4577cd137ec973dd9a7bb0d4f58d29ef9cb0
11a8adf49897465c4d8bddb7e1afef04876a805d
refs/heads/master
2020-12-24T18:04:01.909864
2014-01-23T11:10:11
2014-01-23T11:17:38
6,839,863
1
0
null
null
null
null
UTF-8
Scheme
false
false
20,789
scm
ddp.scm
(define-module sicp.ddp (use srfi-1) (use gauche.sequence) (use math.const) (export-all) ;; Data-Directed Programming package ;; SICP(J) P.99 ) (select-module sicp.ddp) (define (square x) (* x x)) (define *type-op-table* (make-hash-table 'equal?)) (define (put-method op type item) (hash-table-put! *type-op-table* (list op type) item)) (define (get-method op type) (if (hash-table-exists? *type-op-table* (list op type)) (hash-table-get *type-op-table* (list op type)) #f)) (define *coercion-table* (make-hash-table 'equal?)) (define (put-coercion from-type to-type proc) (hash-table-put! *coercion-table* (list from-type to-type) proc)) (define (get-coercion from-type to-type) (if (hash-table-exists? *coercion-table* (list from-type to-type)) (hash-table-get *coercion-table* (list from-type to-type)) #f)) (define (attach-tag type-tag contents) (if (number? contents) contents (cons type-tag contents))) (define (type-tag datum) (cond [(number? datum) 'scheme-number] [(pair? datum) (car datum)] [else (error "Bad tagged datum -- TYPE-TAG" datum)])) (define (is-a? datum type) (eq? (type-tag datum) type)) (define (contents datum) (cond [(number? datum) datum] [(pair? datum) (cdr datum)] [else (error "Bad tagged datum -- CONTENTS" datum)])) ;; 2.84 二つの型のいずれが塔の中で高いかをテストする方法 (define (higher t1 t2) (cond [(eq? t1 t2) #f] [(memq t2 (ancestors t1)) #t] [(memq t1 (ancestors t2)) #f] [else (error "Independent types" t1 t2)])) (define (ancestors type) (let loop ([a ()] [t type]) (let1 p (parent t) (if (not p) (reverse a) (loop (cons p a) p))))) (define *parent-table* (make-hash-table 'equal?)) (define (parent type) (if (hash-table-exists? *parent-table* type) (hash-table-get *parent-table* type) #f)) (define (inherit child parent) (hash-table-put! *parent-table* child parent)) ;; 可能な限り塔を押し下げる (define (drop-tower x) (or (and-let* ([proc (get-method 'project (type-tag x))] [projected (proc x)] [(equ? projected x)]) projected) x)) ;; 2.84 apply-generic を raise を用いて書き直したもの (define (apply-generic op . args) (define (highest types) (find-max types :compare higher)) (define (coerce-to type n) (if (is-a? n type) n (coerce-to type (raise n)))) (define (all-same xs) (every (^x (eq? x (car xs))) xs)) (cond [(null? args) (error "No given args")] [(= 1 (length args)) (let ([proc (get-method op (type-tag (car args)))]) (if proc (proc (contents (car args))) (error "No method for that type" (list op (type-tag (car args))))))] [(< 1 (length args)) (let ((type-tags (map type-tag args))) (let ((proc (get-method op type-tags))) (if proc (apply proc (map contents args)) (if (not (all-same type-tags)) (let* ([highest-type (highest type-tags)] [proc (get-method op (map (^x highest-type) type-tags))]) (apply proc (map (^x (contents (coerce-to highest-type x))) args))) (error "No method for these types" (list op type-tags))))))])) ;; ジェネリック関数の定義 (define (add x y) (apply-generic 'add x y)) (define (sub x y) (apply-generic 'sub x y)) (define (negate x) (apply-generic 'negate x)) (define (mul x y) (apply-generic 'mul x y)) (define (div x y) (apply-generic 'div x y)) (define (equ? x y) (apply-generic 'equ? x y)) (define (=zero? x) (apply-generic '=zero? x)) (define (exp x y) (apply-generic 'exp x y)) (define (raise x) (apply-generic 'raise x)) (define (project x) (apply-generic 'project x)) ;; 普通の数値パッケージ (define (install-scheme-number-package) (define (tag x) (attach-tag 'scheme-number x)) (define (scheme-number->complex n) (make-complex-from-real-imag (contents n) 0)) (define (scheme-number->scheme-number n) n) (define (scheme-number->rational n) (make-rational (contents n) 1)) (put-method 'add '(scheme-number scheme-number) (lambda (x y) (tag (+ x y)))) (put-method 'sub '(scheme-number scheme-number) (lambda (x y) (tag (- x y)))) (put-method 'negate 'scheme-number (^x (tag (- x)))) (put-method 'mul '(scheme-number scheme-number) (lambda (x y) (tag (* x y)))) (put-method 'div '(scheme-number scheme-number) (lambda (x y) (tag (/ x y)))) (put-method 'equ? '(scheme-number scheme-number) (lambda (x y) (= x y))) (put-method '=zero? 'scheme-number (lambda (x) (= x 0))) (put-method 'make 'scheme-number (lambda (x) (tag x))) (put-method 'exp '(scheme-number scheme-number) (lambda (x y) (tag (expt x y)))) (put-method 'raise 'scheme-number (^x (make-rational (contents x) 1))) (inherit 'scheme-number 'rational) (put-coercion 'scheme-number 'complex scheme-number->complex) (put-coercion 'scheme-number 'rational scheme-number->rational) (put-coercion 'scheme-number 'scheme-number scheme-number->scheme-number) 'done) (define (make-scheme-number n) ((get-method 'make 'scheme-number) n)) ;; 有理数パッケージ (define (install-rational-package) ;; 内部手続き (define (numer x) (car x)) (define (denom x) (cdr x)) (define (make-rat n d) (letrec ((g (gcd n d)) (h (if (< d 0) (- g) g))) (cons (/ n h) (/ d h)))) (define (add-rat x y) (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (sub-rat x y) (make-rat (- (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (mul-rat x y) (make-rat (* (numer x) (numer y)) (* (denom x) (denom y)))) (define (div-rat x y) (make-rat (* (numer x) (numer y)) (* (denom x) (numer y)))) (define (equ?-rat x y) (and (= (numer x) (numer y)) (= (denom x) (denom y)))) (define (=zero?-rat x) (= (numer x) 0)) (define (rational->complex n) (make-complex-from-real-imag (contents n) 0)) (define (rational->rational n) n) ;; システムの他の部分へのインターフェース (define (tag x) (attach-tag 'rational x)) (put-method 'add '(rational rational) (lambda (x y) (tag (add-rat x y)))) (put-method 'sub '(rational rational) (lambda (x y) (tag (sub-rat x y)))) (put-method 'negate 'rational (^x (tag (mul-rat (make-rat -1 1) x)))) (put-method 'mul '(rational rational) (lambda (x y) (tag (mul-rat x y)))) (put-method 'div '(rational rational) (lambda (x y) (tag (div-rat x y)))) (put-method 'equ? '(rational rational) equ?-rat) (put-method '=zero? 'rational =zero?-rat) (put-method 'make 'rational (lambda (n d) (tag (make-rat n d)))) (put-method 'numer 'rational (^x (numer (contents x)))) (put-method 'denom 'rational (^x (denom (contents x)))) (put-method 'raise 'rational (^x (make-complex-from-real-imag (/ (numer x) (denom x)) 0))) (inherit 'rational 'complex) (put-method 'project 'rational (^x (make-scheme-number (round (/ (numer x) (denom x)))))) (put-coercion 'rational 'complex rational->complex) (put-coercion 'rational 'rational rational->rational) 'done) (define (make-rational n d) ((get-method 'make 'rational) n d)) ;; 複素数パッケージ ;; 複素数の直交座標系による実装 (define (install-rectangular-package) ;; 内部手続き (define (real-part z) (car z)) (define (imag-part z) (cdr z)) (define (make-from-real-imag x y) (cons x y)) (define (magnitude z) (sqrt (+ (square (real-part z)) (square (imag-part z))))) (define (angle z) (atan (imag-part z) (real-part z))) (define (make-from-mag-ang r a) (cons (* r (cos a)) (* r (sin a)))) ;; システムの他の部分とのインターフェース (define (tag x) (attach-tag 'rectangular x)) (put-method 'real-part 'rectangular real-part) (put-method 'imag-part 'rectangular imag-part) (put-method 'magnitude 'rectangular magnitude) (put-method 'angle 'rectangular angle) (put-method 'make-from-real-imag 'rectangular (lambda (x y) (tag (make-from-real-imag x y)))) (put-method 'make-from-mag-ang 'rectangular (lambda (r a) (tag (make-from-mag-ang r a)))) 'done) ;; 複素数の極座標系による実装 (define (install-polar-packge) ;; 内部手続き (define (magnitude z) (car z)) (define (angle z) (cdr z)) (define (make-from-mag-ang r a) (cons r a)) (define (real-part z) (* (magnitude z) (cos (angle z)))) (define (imag-part z) (* (magnitude z) (sin (angle z)))) (define (make-from-real-imag x y) (cons (sqrt (+ (square x) (square y))) (atan y x))) ;; システムの他の部分とのインターフェイス (define (tag x) (attach-tag 'polar x)) (put-method 'real-part 'polar real-part) (put-method 'imag-part 'polar imag-part) (put-method 'magnitude 'polar magnitude) (put-method 'angle 'polar angle) (put-method 'make-from-real-imag 'polar (lambda (x y) (tag (make-from-real-imag x y)))) (put-method 'make-from-mag-ang 'polar (lambda (r a) (tag (make-from-mag-ang r a)))) 'done) (define (real-part z) (apply-generic 'real-part z)) (define (imag-part z) (apply-generic 'imag-part z)) (define (magnitude z) (apply-generic 'magnitude z)) (define (angle z) (apply-generic 'angle z)) (define (make-from-real-imag x y) ((get-method 'make-from-real-imag 'rectangular) x y)) (define (make-from-mag-ang r a) ((get-method 'make-from-mag-ang 'polar) r a)) (define (install-complex-package) ;; 直交座標と極座標パッケージから取り入れた手続き (define (make-from-real-imag x y) ((get-method 'make-from-real-imag 'rectangular) x y)) (define (make-from-mag-ang r a) ((get-method 'make-from-mag-ang 'polar) r a)) (define (normalize-angle a) (cond [(< pi a) (normalize-angle (- a 2pi))] [(< a (- pi)) (normalize-angle (+ a 2pi))] [else a])) ;; 内部手続き (define (add-complex z1 z2) (make-from-real-imag (+ (real-part z1) (real-part z2)) (+ (imag-part z1) (imag-part z2)))) (define (sub-complex z1 z2) (make-from-real-imag (- (real-part z1) (real-part z2)) (- (imag-part z1) (imag-part z2)))) (define (mul-complex z1 z2) (make-from-mag-ang (* (magnitude z1) (magnitude z2)) (normalize-angle (+ (angle z1) (angle z2))))) (define (add-complex z1 z2) (make-from-mag-ang (/ (magnitude z1) (magnitude z2)) (normalize-angle (- (angle z1) (angle z2))))) (define (equ?-complex z1 z2) (and (= (real-part z1) (real-part z2)) (= (imag-part z1) (imag-part z2)))) (define (=zero?-complex z) (and (= (real-part z) 0) (= (imag-part z) 0))) (define (complex->complex z) z) ;; システムの他の部分へのインターフェース (define (tag z) (attach-tag 'complex z)) (put-method 'add '(complex complex) (lambda (z1 z2) (tag (add-complex z1 z2)))) (put-method 'sub '(complex complex) (lambda (z1 z2) (tag (sub-complex z1 z2)))) (put-method 'negate 'complex (^x (tag (mul-complex x (make-complex-from-real-imag -1 0))))) (put-method 'mul '(complex complex) (lambda (z1 z2) (tag (mul-complex z1 z2)))) (put-method 'div '(complex complex) (lambda (z1 z2) (tag (div-complex z1 z2)))) (put-method 'equ? '(complex complex) equ?-complex) (put-method '=zero? 'complex =zero?-complex) (put-method 'make-from-real-imag 'complex (lambda (x y) (tag (make-from-real-imag x y)))) (put-method 'make-from-mag-ang 'complex (lambda (r a) (tag (make-from-mag-ang r a)))) (put-method 'real-part 'complex real-part) (put-method 'imag-part 'complex imag-part) (put-method 'magnitude 'complex magnitude) (put-method 'angle 'complex angle) (put-coercion 'complex 'complex complex->complex) (put-method 'project 'complex (^x (make-rational (real-part x) 1))) 'done) (define (make-complex-from-real-imag x y) ((get-method 'make-from-real-imag 'complex) x y)) (define (make-complex-from-mag-ang r a) ((get-method 'make-from-mag-ang 'complex) r a)) (install-scheme-number-package) (install-rational-package) (install-rectangular-package) (install-polar-packge) (install-complex-package) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 多項式パッケージ (define (variable? x) (symbol? x)) (define (same-variable? v1 v2) (and (variable? v1) (variable? v2) (eq? v1 v2))) (define (variable p) (apply-generic 'variable p)) (define (term-list p) (apply-generic 'term-list p)) (define (coeff-list p) (apply-generic 'coeff-list p)) (define (the-empty-term-list) ()) (define (empty-termlist? term-list) (null? term-list)) (define (adjoin-term term term-list) (if (=zero? (coeff term)) term-list (cons term term-list))) (define (first-term term-list) (car term-list)) (define (rest-terms term-list) (cdr term-list)) (define (make-term order coeff) (list order coeff)) (define (order term) (car term)) (define (coeff term) (cadr term)) (define (normalize-term-list term-list) (reverse (sort-by term-list car))) ;; 薄い多項式パッケージ (define (install-polynomial-sparse-package) (define (make-poly variable term-list) (cons variable (normalize-term-list term-list))) (define (variable p) (car p)) (define (term-list p) (cdr p)) (define (coeff-list p) (let loop [(cs ()) (ts (reverse (term-list p))) (i 0)] (if (empty-termlist? ts) cs (if (= i (order (first-term ts))) (loop (cons (coeff (first-term ts)) cs) (rest-terms ts) (+ i 1)) (loop (cons 0 cs) ts (+ i 1)))))) (define (negate-sparse p1) (make-poly (variable p1) (negate-terms (term-list p1)))) (define (negate-terms l1) (if (empty-termlist? l1) l1 (let ([t1 (first-term l1)]) (adjoin-term (make-term (order t1) (negate (coeff t1))) (negate-terms (rest-terms l1)))))) (define (=zero?-sparse p) (let loop ([terms (term-list p)]) (if (empty-termlist? terms) #t (and (=zero? (coeff (first-term terms))) (loop (rest-terms terms)))))) ;; システムの他の部分とのインターフェース (define (tag x) (attach-tag 'sparse x)) (put-method 'variable 'sparse variable) (put-method 'term-list 'sparse term-list) (put-method 'coeff-list 'sparse coeff-list) (put-method 'negate 'sparse (.$ tag negate-sparse)) (put-method '=zero? 'sparse =zero?-sparse) (put-method 'make-from-term-list 'sparse (.$ tag make-poly)) ) (install-polynomial-sparse-package) ;; 濃い多項式パッケージ (define (install-polynomial-dense-package) (define (make-poly variable coeff-list) (cons variable coeff-list)) (define (variable p) (car p)) (define (term-list p) (let loop [(ts (the-empty-term-list)) (cs (reverse (coeff-list p))) (i 0)] (if (null? cs) ts (loop (adjoin-term (make-term i (car cs)) ts) (cdr cs) (+ i 1))))) (define (coeff-list p) (cdr p)) (define (negate-dense p1) (make-poly (variable p1) (negate-coeffs (coeff-list p1)))) (define (negate-coeffs c1) (if (null? c1) c1 (map negate c1))) (define (=zero?-dense p) (let loop ([coeffs (coeff-list p)]) (if (null? coeffs) #t (and (=zero? (car coeffs)) (loop (cdr coeffs)))))) ;; システムの他の部分とのインターフェース (define (tag x) (attach-tag 'dense x)) (put-method 'variable 'dense variable) (put-method 'term-list 'dense term-list) (put-method 'coeff-list 'dense coeff-list) (put-method 'negate 'dense (.$ tag negate-dense)) (put-method '=zero? 'dense =zero?-dense) (put-method 'make-from-coeff-list 'dense (.$ tag make-poly)) ) (install-polynomial-dense-package) (define (install-polynomial-package) ;; 内部手続き ;; 多項式型の表現 (define (make-from-coeff-list var coeffs) ((get-method 'make-from-coeff-list 'dense) var coeffs)) (define (make-from-term-list var terms) ((get-method 'make-from-term-list 'sparse) var terms)) (define (sub-poly p1 p2) (add-poly p1 (negate p2))) (define (add-poly p1 p2) (if (same-variable? (variable p1) (variable p2)) (make-from-coeff-list (variable p1) (add-coeffs (coeff-list p1) (coeff-list p2))) (error "polys not in same var -- add-poly" (list p1 p2)))) (define (add-coeffs c1 c2) (let loop ([coeffs ()] [c1 (reverse c1)] [c2 (reverse c2)]) (if (and (null? c1) (null? c2)) coeffs (loop (cons (cond [(null? c1) (car c2)] [(null? c2) (car c1)] [else (add (car c1) (car c2))]) coeffs) (drop* c1 1) (drop* c2 1))))) (define (mul-poly p1 p2) (if (same-variable? (variable p1) (variable p2)) (make-from-term-list (variable p1) (mul-terms (term-list p1) (term-list p2))) (error "polys not in same var -- mul-poly" (list p1 p2)))) (define (add-terms l1 l2) (cond [(empty-termlist? l1) l2] [(empty-termlist? l2) l1] [else (let ([t1 (first-term l1)] [t2 (first-term l2)]) (cond [(> (order t1) (order t2)) (adjoin-term t1 (add-terms (rest-terms l1) l2))] [(< (order t1) (order t2)) (adjoin-term t2 (add-terms l1 (rest-terms l2)))] [else (adjoin-term (make-term (order t1) (add (coeff t1) (coeff t2))) (add-terms (rest-terms l1) (rest-terms l2)))]))])) (define (mul-terms L1 L2) (if (empty-termlist? L1) (the-empty-term-list) (add-terms (mul-term-by-all-terms (first-term L1) L2) (mul-terms (rest-terms L1) L2)))) (define (mul-term-by-all-terms t1 L) (if (empty-termlist? L) (the-empty-term-list) (let ([t2 (first-term L)]) (adjoin-term (make-term (+ (order t1) (order t2)) (mul (coeff t1) (coeff t2))) (mul-term-by-all-terms t1 (rest-terms L)))))) (define (equ?-poly l1 l2) (let loop ([t1 (term-list l1)] [t2 (term-list l2)]) (cond [(and (empty-termlist? t1) (empty-termlist? t2)) #t] [(and (= (order (first-term t1)) (order (first-term t2))) (equ? (coeff (first-term t1)) (coeff (first-term t2)))) (loop (rest-terms t1) (rest-terms t2))] [else #f]))) ;; システムの他の部分とのインターフェース (define (tag p) (attach-tag 'polynomial p)) (put-method 'add '(polynomial polynomial) (.$ tag add-poly)) (put-method 'sub '(polynomial polynomial) (.$ tag sub-poly)) (put-method 'mul '(polynomial polynomial) (.$ tag mul-poly)) (put-method 'equ? '(polynomial polynomial) equ?-poly) (put-method 'negate 'polynomial (.$ tag negate)) (put-method '=zero? 'polynomial =zero?) (put-method 'make-from-term-list 'polynomial (.$ tag make-from-term-list)) (put-method 'make-from-coeff-list 'polynomial (.$ tag make-from-coeff-list)) 'done) (install-polynomial-package) (define (make-from-term-list var terms) ((get-method 'make-from-term-list 'polynomial) var terms)) (define (make-from-coeff-list var coeffs) ((get-method 'make-from-coeff-list 'polynomial) var coeffs)) ;; 互換性のため (define make-polynomial make-from-term-list)
false
bda1db7ca70f721acc71054e91d9fee654e41374
dae624fc36a9d8f4df26f2f787ddce942b030139
/chapter-13/string.scm
28813f72b3e700af2ba5a5793c6c2b1e8741142c
[ "MIT" ]
permissive
hshiozawa/gauche-book
67dcd238c2edeeacb1032ce4b7345560b959b243
2f899be8a68aee64b6a9844f9cbe83eef324abb5
refs/heads/master
2020-05-30T20:58:40.752116
2019-10-01T08:11:59
2019-10-01T08:11:59
189,961,787
0
0
null
null
null
null
UTF-8
Scheme
false
false
967
scm
string.scm
"hello" (string? "hello") (string? 1) (string-length "hello") (string-ref "あいうえお" 0) (use srfi-13) (string-null? "abc") (string-null? "") (string #\あ #\い #\う) (string #\1 #\2 #\3) (string-concatenate '("Hello" " world")) (list->string '(#\a #\b #\c)) (write-to-string '(1 "abc" "\"" #\z)) (x->string '(1 "abc" "\"" #\z)) #`"The answer is ,(* 6 7)." (define *answer* 42) #`"The answer is ,|*answer*|." (define (hello) (print "Hello World!")) (with-output-to-string hello) (string->list "日月火水木金土") (string-append "foo" "bar" "buz") (string-join '("foo" "bar" "buz") "/") (string-join '("foo" "bar" "buz") "/" 'infix) (string-join '("foo" "bar" "buz") "/" 'prefix) (string-join '("foo" "bar" "buz") "/" 'suffix) (string-split "foo:bar:buz" #\:) (string-split "foo:::bar:buz" #/:+/) (substring "abcdefg" 2 5) (string-copy "hello") (string-copy "hello" 3) (string-scan "fkdjafkd" "dja") (string-scan "fkdjafkd" "djx")
false
85a57efdd47a959525160d46fa5c74af99e2dceb
3686e1a62c9668df4282e769220e2bb72e3f9902
/ex2.41.scm
e3b44800e048c4e0bf4586bf520b4fe8b281ebdd
[]
no_license
rasuldev/sicp
a4e4a79354495639ddfaa04ece3ddf42749276b5
71fe0554ea91994822db00521224b7e265235ff3
refs/heads/master
2020-05-21T17:43:00.967221
2017-05-02T20:32:06
2017-05-02T20:32:06
65,855,266
0
0
null
null
null
null
UTF-8
Scheme
false
false
767
scm
ex2.41.scm
(define nil '()) (define (enumerate-interval a b) (if (> a b) nil (cons a (enumerate-interval (+ a 1) b)) ) ) (enumerate-interval 1 3) (define (flatmap proc seq) (fold-right append nil (map proc seq)) ) (define (triples n s) (define (distinct-and-sum-is-s? triple) (let ((a (car triple)) (b (cadr triple)) (c (caddr triple))) (and (not (or (= a b) (= a c) (= b c))) (= (+ a b c) s)) ) ) (filter distinct-and-sum-is-s? (flatmap (lambda (i) (flatmap (lambda (j) (map (lambda (k) (list i j k) ) (enumerate-interval 1 n) ) ) (enumerate-interval 1 n) ) ) (enumerate-interval 1 n) ) ) ) (triples 3 6)
false
9f4b070db6f125e419bc3315ba9b628baebe2390
ae76253c0b7fadf8065777111d3aa6b57383d01b
/chap3/exec-3.20.ss
f08695c688a0b35233a4d97cec85c4698da3f211
[]
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
1,553
ss
exec-3.20.ss
(define (cons x y) (define (set-x! v) (set! x v)) (define (set-y! v) (set! y v)) (define (dispatch m) (cond ((eq? m 'car) x) ((eq? m 'cdr) y) ((eq? m 'set-car!) set-x!) ((eq? m 'set-cdr!) set-y!) (else (error 'cons "Undefiend operation -- CONS" m)))) dispatch) (define (car z) (z 'car)) (define (cdr z) (z 'cdr)) (define (set-car! z new-value) ((z 'set-car!) new-value) z) (define (set-cdr! z new-value) ((z 'set-cdr!) new-value) z) (define x (cons 1 2)) (define z (cons x x)) (set-car! (cdr z) 17) (car x) ; |-----------------------------------------------------| ; | cons:---| set-car!:... x:--| y:... | ; | car:.. | set-cdr!:... | | ; | cdr:.. | | | ; |_________|_______________^______________|____________| ; | | | ; v |----------| v ; O O |set-x!: | O O -------------------| |------| ; paramter: x y |set-y!: | parameter: m | |m:'car| ; |dispatch: | body: | |______| ; body: |x:1 y:2 | (cond ((eq? m 'car) x) | | ; |__________|<--| .... | | ; (define set-x!... ^ |__________________________| | ; (define set-y!... |_______________________________________| ; (define dispatch m ; dispatch
false
6a51b6ca1c1bd44ad3f7390dc707af348a5e801b
e82d67e647096e56cb6bf1daef08552429284737
/ex2-44.scm
d73d81494a113cb248d818b2fe6f1701831befe8
[]
no_license
ashishmax31/sicp-exercises
97dfe101dd5c91208763dcc4eaac2c17977d1dc1
097f76a5637ccb1fba055839d389541a1a103e0f
refs/heads/master
2020-03-28T11:16:28.197294
2019-06-30T20:25:18
2019-06-30T20:25:18
148,195,859
6
0
null
null
null
null
UTF-8
Scheme
false
false
378
scm
ex2-44.scm
#lang scheme (define (upsplit pict n) (if (zero? n) pict (let ((smaller (upsplit pict (-n 1)))) (below pict (beside smaller smaller))))) (define (square-of-four tl tr bl br) (lambda (painter) (let ((top (beside (tl painter) (tr painter))) (buttom (beside (bl painter) (br painter)))) (below top buttom))))
false
36ff9bcee601e62b9028f7c61f5ac580dcb9698d
4f97d3c6dfa30d6a4212165a320c301597a48d6d
/cocoa/Barliman/mk-and-rel-interp/interp-fancy.scm
0724c1c71cd2f2c9940b3020b48e5d090e6b04ac
[ "MIT", "LicenseRef-scancode-free-unknown" ]
permissive
michaelballantyne/Barliman
8c0b1ccbe5141347a304fe57dc9f85085aae9228
7a58671a85b82c05b364b60aa3a372313d71f8ca
refs/heads/master
2022-09-24T05:59:45.760663
2019-11-25T10:32:26
2019-11-25T10:32:26
268,399,942
0
0
MIT
2020-06-01T01:48:21
2020-06-01T01:48:20
null
UTF-8
Scheme
false
false
34,735
scm
interp-fancy.scm
;; The definition of 'letrec' is based based on Dan Friedman's code, ;; using the "half-closure" approach from Reynold's definitional ;; interpreters. (define closure-tag (gensym "#%closure")) (define prim-tag (gensym "#%primitive")) (define undefined-tag (gensym "#%undefined")) ;; TODO: defer conde fallbacks during eager evaluation. ;; TODO: fresh should push/pop deferred context for hierarchical binding. ;; TODO: reverse eval-listo queuing order once deferring works. (define (literal-expo expr env val) (== expr val)) (define (quote-primo expr env val) (fresh () (== `(quote ,val) expr) (absento closure-tag val) (absento prim-tag val) (not-in-envo 'quote env))) (define (lambda-primo expr env val) (fresh (x body) (== `(lambda ,x ,body) expr) (== `(,closure-tag (lambda ,x ,body) ,env) val) (paramso x) (not-in-envo 'lambda env))) (define (app-closure-variadico expr env val) (fresh (rator x rands body env^ a*) (== `(,rator . ,rands) expr) (eval-expo rator env `(,closure-tag (lambda ,x ,body) ,env^)) (ext-env1-evalo x a* env^ body val) (eval-listo rands env a*))) (define (app-closure-multi-argo expr env val) (fresh (rator x* rands body env^ a*) (== `(,rator . ,rands) expr) (eval-expo rator env `(,closure-tag (lambda ,x* ,body) ,env^)) (eval-listo rands env a*) (ext-env*-evalo x* rands a* env^ body val))) (define (app-primo expr env val) (fresh (rator rands a* prim-id) (== `(,rator . ,rands) expr) (eval-expo rator env `(,prim-tag . ,prim-id)) (eval-primo prim-id a* val) (eval-listo rands env a*))) (define (app-expo expr env val) (fresh (rator rand* op a*) (== `(,rator . ,rand*) expr) (let-deferred (rator-deferred (eval-expo rator env op)) (project0 (op) (cond ((var? op) ;; TODO: factor out eval-listo rands. (fresh () (eval-listo rand* env a*) (defer (conde ((fresh (x body env^) (== `(,closure-tag (lambda ,x ,body) ,env^) op) (ext-env1-evalo x a* env^ body val))) ((fresh (x* body env^) (== `(,closure-tag (lambda ,x* ,body) ,env^) op) (ext-env*-evalo x* rand* a* env^ body val))) ((fresh (x* rand* prim-id) (== `(,prim-tag . ,prim-id) op) (eval-primo prim-id a* val))))) (defer* rator-deferred))) ((pair? op) ;; Assume a procedure "pair" must have been immediately tagged. (cond ((eq? closure-tag (car op)) (fresh (params body env^) (== `((lambda ,params ,body) ,env^) (cdr op)) (eval-listo rand* env a*) (defer* rator-deferred) (project0 (params) (cond ((var? params) (conde ((ext-env1-evalo params a* env^ body val)) ((ext-env*-evalo params rand* a* env^ body val)))) ((pair? params) (ext-env*-evalo params rand* a* env^ body val)) (else (ext-env1-evalo params a* env^ body val)))))) ((eq? prim-tag (car op)) (fresh () (eval-primo (cdr op) a* val) (eval-listo rand* env a*) (defer* rator-deferred))) (else fail))) (else fail)))))) (define (begin-primo expr env val) (fresh (begin-body) (== `(begin . ,begin-body) expr) (not-in-envo 'begin env) (eval-begino '() begin-body env val))) (define (letrec-primo expr env val) (fresh (b* letrec-body) (== `(letrec ,b* ,letrec-body) expr) (not-in-envo 'letrec env) (eval-letreco b* letrec-body env val))) (define (let-primo expr env val) (fresh (b* body) ;; TODO: ensure bound names are all different (== `(let ,b* ,body) expr) (not-in-envo 'let env) (let loop ((b* b*) (p* '()) (rand* '())) (define (gnull) (fresh (a* res) (eval-listo rand* env a*) (ext-env*-evalo p* rand* a* env body val))) (define (gpair) (fresh (p rand b*-rest) (== `((,p ,rand) . ,b*-rest) b*) (symbolo p) (loop b*-rest (cons p p*) (cons rand rand*)))) (project0 (b*) (cond ((null? b*) (gnull)) ((pair? b*) (gpair)) (else (conde ((== '() b*) (gnull)) ((gpair))))))))) (define (let*-primo expr env val) (fresh (b* body) (== `(let* ,b* ,body) expr) (not-in-envo 'let env) (let loop ((b* b*) (env env)) (define (gpair) (fresh (p rand a b*-rest res) (== `((,p ,rand) . ,b*-rest) b*) (ext-env1o p a env res) (loop b*-rest res) (eval-expo rand env a))) (project0 (b*) (cond ((null? b*) (eval-expo body env val)) ((pair? b*) (gpair)) (else (conde ((== '() b*) (eval-expo body env val)) ((gpair))))))))) (define (quasiquote-primo expr env val) (fresh (qq-expr) (== (list 'quasiquote qq-expr) expr) (not-in-envo 'quasiquote env) (eval-qq-expo 0 qq-expr env val))) (define (case-bound-symbol-reco x b* env loop gk-unknown gk-unbound gk-else) (project0 (b*) (cond ((var? b*) (loop env gk-unknown)) ((null? b*) (loop env gk-unbound)) (else (fresh (p-name lam-expr b*-rest) (== `((,p-name . ,lam-expr) . ,b*-rest) b*) (project0 (p-name) (cond ((eq? p-name x) (gk-else)) ((var? p-name) (case-bound-symbol-reco x b*-rest env loop gk-unknown gk-unknown gk-else)) (else (case-bound-symbol-reco x b*-rest env loop gk-unknown gk-unbound gk-else))))))))) (define (case-bound-symbolo x env gk-unknown gk-unbound gk-else) (cond ((var? x) (gk-unknown)) ((not (symbol? x)) (gk-else)) (else (let loop ((env env) (gk-unbound gk-unbound)) (project0 (env) (cond ((var? env) (gk-unknown)) ((null? env) (gk-unbound)) (else (fresh (tag rib rest) (== `((,tag . ,rib) . ,rest) env) (project0 (tag) (cond ((var? tag) (loop rest gk-unknown)) ((eq? 'rec tag) (case-bound-symbol-reco x rib rest loop gk-unknown gk-unbound gk-else)) ((eq? 'val tag) (fresh (y b) (== `(,y . ,b) rib) (project0 (y) (cond ((var? y) (loop rest gk-unknown)) ((eq? y x) (gk-else)) (else (loop rest gk-unbound)))))) (else fail))))))))))) (define (evalo expr val) (eval-expo expr initial-env val)) (define (eval-expo expr env val) (define (gall) (lookupo-alt expr env val (conde ((quote-primo expr env val)) ((numbero expr) (literal-expo expr env val)) ((lambda-primo expr env val)) ((app-closure-variadico expr env val)) ((app-closure-multi-argo expr env val)) ((app-primo expr env val)) ((handle-matcho expr env val)) ((begin-primo expr env val)) ((letrec-primo expr env val)) ((let-primo expr env val)) ((let*-primo expr env val)) ((quasiquote-primo expr env val)) ((cond-primo expr env val)) ((boolean-primo expr env val)) ((and-primo expr env val)) ((or-primo expr env val)) ((if-primo expr env val))))) (define (gpair) (conde ((quote-primo expr env val)) ((lambda-primo expr env val)) ((app-closure-variadico expr env val)) ((app-closure-multi-argo expr env val)) ((app-primo expr env val)) ((handle-matcho expr env val)) ((begin-primo expr env val)) ((letrec-primo expr env val)) ((let-primo expr env val)) ((let*-primo expr env val)) ((quasiquote-primo expr env val)) ((cond-primo expr env val)) ((and-primo expr env val)) ((or-primo expr env val)) ((if-primo expr env val)))) (project0 (expr) (cond ((or (not expr) (eq? #t expr) (number? expr)) (literal-expo expr env val)) ((symbol? expr) (lookupo expr env val)) ((pair? expr) (let ((ea (car expr))) (project0 (ea) (case-bound-symbolo ea env gpair (lambda () (case ea ((quote) (quote-primo expr env val)) ((lambda) (lambda-primo expr env val)) ((if) (if-primo expr env val)) ((begin) (begin-primo expr env val)) ((letrec) (letrec-primo expr env val)) ((let) (let-primo expr env val)) ((let*) (let*-primo expr env val)) ((quasiquote) (quasiquote-primo expr env val)) ((cond) (cond-primo expr env val)) ((and) (and-primo expr env val)) ((or) (or-primo expr env val)) ((match) (handle-matcho expr env val)) (else fail))) (lambda () (app-expo expr env val)))))) ((var? expr) (gall)) (else fail)))) (define empty-env '()) (define (lookup-reco k renv x b* t) (define (gtest b*-rest p-name lam-expr) (conde ((== p-name x) (== `(,closure-tag ,lam-expr ,renv) t)) ((=/= p-name x) (lookup-reco k renv x b*-rest t)))) (define (gpair) (fresh (b*-rest p-name lam-expr) (== `((,p-name . ,lam-expr) . ,b*-rest) b*) (gtest b*-rest p-name lam-expr))) (project0 (b*) (cond ((null? b*) (k)) ((pair? b*) (fresh (b*-rest p-name lam-expr) (== `((,p-name . ,lam-expr) . ,b*-rest) b*) (project0 (x p-name) (if (and (symbol? x) (symbol? p-name)) (if (eq? x p-name) (== `(,closure-tag ,lam-expr ,renv) t) (lookup-reco k renv x b*-rest t)) (gtest b*-rest p-name lam-expr))))) ((var? b*) (conde ((== '() b*) (k)) ((gpair)))) (else fail)))) (define (lookupo-alt x env t galt) (define (gtest y b rest) (conde ((== x y) (== b t)) ((=/= x y) (lookupo-alt x rest t galt)))) (define (gval) (fresh (y b rest) (== `((val . (,y . ,b)) . ,rest) env) (gtest y b rest))) (define (grec) (fresh (b* rest) (== `((rec . ,b*) . ,rest) env) (lookup-reco (lambda () (lookupo-alt x rest t galt)) env x b* t))) (define (gdefault) (conde ((gval)) ((grec)) ((== '() env) galt))) (project0 (env) (cond ((pair? env) (let ((rib (car env))) (project0 (rib) (cond ((pair? rib) (let ((tag (car rib))) (project0 (tag) (if (var? tag) (gdefault) (case tag ((val) (fresh (y b rest) (== `((val . (,y . ,b)) . ,rest) env) (project0 (x y) (if (and (symbol? x) (symbol? y)) (if (eq? x y) (== b t) (lookupo-alt x rest t galt)) (gtest y b rest))))) ((rec) (grec)) (else fail)))))) (else (gdefault)))))) (else (gdefault))))) (define (lookupo x env t) (lookupo-alt x env t fail)) (define (not-in-envo x env) (define (gval) (fresh (y b rest) (== `((val . (,y . ,b)) . ,rest) env) (=/= x y) (not-in-envo x rest))) (define (grec) (fresh (b* rest) (== `((rec . ,b*) . ,rest) env) (not-in-env-reco x b* rest))) (project0 (env) (cond ((null? env) succeed) ((pair? env) (let ((rib (car env))) (project0 (rib) (cond ((pair? rib) (let ((tag (car rib))) (project0 (tag) (if (var? tag) (conde ((gval)) ((grec))) (case tag ((val) (gval)) ((rec) (grec)) (else fail)))))) (else (conde ((gval)) ((grec)))))))) ((var? env) (conde ((== empty-env env)) ((gval)) ((grec)))) (else fail)))) (define (not-in-env-reco x b* env) (define (gpair) (fresh (p-name lam-expr b*-rest) (== `((,p-name . ,lam-expr) . ,b*-rest) b*) (=/= p-name x) (not-in-env-reco x b*-rest env))) (project0 (b*) (cond ((null? b*) (not-in-envo x env)) ((pair? b*) (gpair)) ((var? b*) (conde ((== '() b*) (not-in-envo x env)) ((gpair)))) (else fail)))) (define (eval-letreco b* letrec-body env val) (let loop ((b* b*) (rb* '())) (define (gdefs) (fresh (p-name x body b*-rest) (== `((,p-name (lambda ,x ,body)) . ,b*-rest) b*) (symbolo p-name) (paramso x) (loop b*-rest `((,p-name . (lambda ,x ,body)) . ,rb*)))) (project0 (b*) (cond ((null? b*) (eval-expo letrec-body `((rec . ,rb*) . ,env) val)) ((pair? b*) (gdefs)) (else (conde ((== '() b*) (eval-expo letrec-body `((rec . ,rb*) . ,env) val)) ((gdefs)))))))) ;; NOTE: rec-defs is Scheme state, not a logic term! (define (eval-begino rec-defs begin-body env val) (define (gbody e) (if (null? rec-defs) (eval-expo e env val) (eval-letreco rec-defs e env val))) (define (gdefine e begin-rest) (fresh (name args body) (== `(define ,name (lambda ,args ,body)) e) (symbolo name) (eval-begino (cons `(,name (lambda ,args ,body)) rec-defs) begin-rest env val))) (fresh (e begin-rest) (== `(,e . ,begin-rest) begin-body) (project0 (begin-rest) (cond ((null? begin-rest) (gbody e)) ((pair? begin-rest) (gdefine e begin-rest)) (else (conde ((== '() begin-rest) (gbody e)) ((gdefine e begin-rest)))))))) ;; 'level' is non-relational. (define (eval-qq-expo level qq-expr env val) (define (guq) (fresh (expr) (== (list 'unquote expr) qq-expr) (if (= 0 level) (eval-expo expr env val) (fresh (sub-val) (== (list 'unquote sub-val) val) (eval-qq-expo (- level 1) expr env sub-val))))) (define (gqq) (fresh (expr sub-val) (== (list 'quasiquote expr) qq-expr) (== (list 'quasiquote sub-val) val) (eval-qq-expo (+ level 1) expr env sub-val))) (define (gpair) (fresh (qq-a qq-d va vd) (== `(,qq-a . ,qq-d) qq-expr) (== `(,va . ,vd) val) (=/= 'unquote qq-a) (=/= 'quasiquote qq-a) (=/= closure-tag qq-a) (=/= prim-tag qq-a) (eval-qq-expo level qq-a env va) (eval-qq-expo level qq-d env vd))) (project0 (qq-expr) (cond ((var? qq-expr) (conde ((guq)) ((gqq)) ((gpair)) ((== qq-expr val) (conde ((== '() val)) ((symbolo val)) ((== #f val)) ((== #t val)) ((numbero val)))))) ((pair? qq-expr) (fresh (qq-a qq-d) (== `(,qq-a . ,qq-d) qq-expr) (project0 (qq-a) (cond ((var? qq-a) (conde ((guq)) ((gqq)) ((gpair)))) ((eq? 'unquote qq-a) (guq)) ((eq? 'quasiquote qq-a) (gqq)) (else (gpair)))))) (else (== qq-expr val))))) (define (eval-listo expr env val) (define (gpair) (fresh (a d v-a v-d) (== `(,a . ,d) expr) (== `(,v-a . ,v-d) val) (eval-expo a env v-a) (eval-listo d env v-d))) (project0 (expr) (cond ((null? expr) (== '() val)) ((pair? expr) (gpair)) (else (conde ((== '() expr) (== '() val)) ((gpair))))))) (define (paramso params) (let loop ((params params) (seen '())) (define (not-seen name) (let seen-loop ((seen seen)) (if (null? seen) succeed (fresh () (=/= (car seen) name) (seen-loop (cdr seen)))))) (project0 (params) (cond ;; Don't bother deferring, env extension can handle the rest. ((or (null? params) (var? params)) succeed) ((symbol? params) (not-seen params)) ((pair? params) (fresh () (symbolo (car params)) (not-seen (car params)) (loop (cdr params) (cons (car params) seen)))) (else fail))))) (define (ext-env1o x a* env out) (fresh () (symbolo x) (== `((val . (,x . ,a*)) . ,env) out))) ;; TODO: ensure uniqueness of names here instead of in paramso. (define (ext-env*o-gps x* r* a* env out gk) (define (gnil) (fresh () (== '() x*) (== '() r*) (== '() a*) (== env out) gk)) (define (gpair) (fresh (x r a dx* dr* da* env2) (== `(,x . ,dx*) x*) (== `(,r . ,dr*) r*) (== `(,a . ,da*) a*) (== `((val . (,x . ,a)) . ,env) env2) (symbolo x) (ext-env*o-gps dx* dr* da* env2 out gk))) (project0 (x* r* a*) (cond ((or (null? x*) (null? r*) (null? a*)) (gnil)) ((or (pair? x*) (pair? r*) (pair? a*)) (gpair)) ((and (var? x*) (var? r*) (var? a*)) (conde ((gnil)) ((gpair)))) (else fail)))) (define (ext-env1-evalo param a* env body val) (fresh (res) (ext-env1o param a* env res) (eval-expo body res val))) (define (ext-env*-evalo params rand* a* env body val) (fresh (res) (ext-env*o-gps params rand* a* env res (eval-expo body res val)))) (define (eval-primo prim-id a* val) (define (gcons) (fresh (a d) (== `(,a ,d) a*) (== `(,a . ,d) val) (=/= closure-tag a) (=/= prim-tag a))) (define (gcar) (fresh (d) (== `((,val . ,d)) a*) (=/= closure-tag val) (=/= prim-tag val))) (define (gcdr) (fresh (a) (== `((,a . ,val)) a*) (=/= closure-tag a) (=/= prim-tag a))) (define (gnot) (fresh (b) (== `(,b) a*) (project0 (b) (cond ((var? b) (conde ((=/= #f b) (== #f val)) ((== #f b) (== #t val)))) ((not b) (== #t val)) (else (== #f val)))))) (define (gequal?) (fresh (v1 v2) (== `(,v1 ,v2) a*) (lambda (st) ((let ((st0 (state-with-scope st nonlocal-scope))) (let ((==? ((== v1 v2) st0)) (=/=? ((=/= v1 v2) st0))) (if ==? (if =/=? (conde ((== v1 v2) (== #t val)) ((=/= v1 v2) (== #f val))) (fresh () (== v1 v2) (== #t val))) (fresh () (=/= v1 v2) (== #f val))))) st)))) (define (gsymbol?) (fresh (v) (== `(,v) a*) (project0 (v) (cond ((var? v) (conde ((== #t val) (symbolo v)) ((== #f val) (conde ((== '() v)) ((== #f v)) ((== #t v)) ((numbero v)) ((fresh (a d) (== `(,a . ,d) v))))))) ((symbol? v) (== #t val)) (else (== #f val)))))) (define (gnumber?) (fresh (v) (== `(,v) a*) (project0 (v) (cond ((var? v) (conde ((== #t val) (numbero v)) ((== #f val) (conde ((== '() v)) ((== #f v)) ((== #t v)) ((symbolo v)) ((fresh (a d) (== `(,a . ,d) v))))))) ((number? v) (== #t val)) (else (== #f val)))))) (define (gnull?) (fresh (v) (== `(,v) a*) (project0 (v) (cond ((var? v) (conde ((== '() v) (== #t val)) ((=/= '() v) (== #f val)))) ((null? v) (== #t val)) (else (== #f val)))))) (define (gpair?) (fresh (v) (== `(,v) a*) (project0 (v) (cond ((var? v) (conde ((fresh (a d) (== #t val) (== `(,a . ,d) v) (=/= closure-tag a) (=/= prim-tag a))) ((== #f val) (conde ((== '() v)) ((symbolo v)) ((== #f v)) ((== #t v)) ((numbero v)) ((fresh (d) (== `(,closure-tag . ,d) v))) ((fresh (d) (== `(,prim-tag . ,d) v))))))) ((pair? v) (fresh (a d) (== `(,a . ,d) v) (project0 (a) (cond ((var? a) (conde ((fresh () (== #t val) (=/= closure-tag a) (=/= prim-tag a))) ((== #f val) (conde ((== `(,closure-tag . ,d) v)) ((== `(,prim-tag . ,d) v)))))) ((or (eq? closure-tag a) (eq? prim-tag a)) (== #f val)) (else (== #t val)))))) (else (== #f val)))))) (define (gprocedure?) (fresh (v) (== `(,v) a*) (project0 (v) (cond ((var? v) (conde ((== #t val) (conde ((fresh (d) (== `(,closure-tag . ,d) v))) ((fresh (d) (== `(,prim-tag . ,d) v))))) ((== #f val) (conde ((== '() v)) ((symbolo v)) ((== #f v)) ((== #t v)) ((numbero v)) ((fresh (a d) (== `(,a . ,d) v) (=/= closure-tag a) (=/= prim-tag a))))))) ((pair? v) (fresh (a d) (== `(,a . ,d) v) (project0 (a) (cond ((var? a) (conde ((== #t val) (conde ((== `(,closure-tag . ,d) v)) ((== `(,prim-tag . ,d) v)))) ((fresh () (== #f val) (=/= closure-tag a) (=/= prim-tag a))))) ((or (eq? closure-tag a) (eq? prim-tag a)) (== #t val)) (else (== #t val)))))) (else (== #f val)))))) (project0 (prim-id) (if (var? prim-id) (conde [(== prim-id 'cons) (gcons)] [(== prim-id 'car) (gcar)] [(== prim-id 'cdr) (gcdr)] [(== prim-id 'not) (gnot)] [(== prim-id 'equal?) (gequal?)] [(== prim-id 'symbol?) (gsymbol?)] [(== prim-id 'number?) (gnumber?)] [(== prim-id 'null?) (gnull?)] [(== prim-id 'pair?) (gpair?)] [(== prim-id 'procedure?) (gprocedure?)]) (case prim-id ((cons) (gcons)) ((car) (gcar)) ((cdr) (gcdr)) ((not) (gnot)) ((equal?) (gequal?)) ((symbol?) (gsymbol?)) ((number?) (gnumber?)) ((null?) (gnull?)) ((pair?) (gpair?)) ((procedure?) (gprocedure?)) (else fail))))) (define (boolean-primo expr env val) (conde ((== #t expr) (== #t val)) ((== #f expr) (== #f val)))) (define (and-primo expr env val) (fresh (e*) (== `(and . ,e*) expr) (not-in-envo 'and env) (ando e* env val))) (define (ando e* env val) (define (gmulti) (fresh (e1 e2 e-rest v) (== `(,e1 ,e2 . ,e-rest) e*) (eval-expo e1 env v) (project0 (v) (cond ((var? v) (conde ((== #f v) (== #f val)) ((=/= #f v) (ando `(,e2 . ,e-rest) env val)))) ((not v) (== #f val)) (else (ando `(,e2 . ,e-rest) env val)))))) (project0 (e*) (cond ((null? e*) (== #t val)) ((pair? e*) (fresh (ea ed) (== `(,ea . ,ed) e*) (project0 (ed) (cond ((null? ed) (eval-expo ea env val)) ((pair? ed) (gmulti)) (else (conde ((fresh (e) (== `(,e) e*) (eval-expo e env val))) ((gmulti)))))))) (else (conde ((== '() e*) (== #t val)) ((fresh (e) (== `(,e) e*) (eval-expo e env val))) ((gmulti))))))) (define (or-primo expr env val) (fresh (e*) (== `(or . ,e*) expr) (not-in-envo 'or env) (oro e* env val))) (define (oro e* env val) (define (gmulti) (fresh (e1 e2 e-rest v) (== `(,e1 ,e2 . ,e-rest) e*) (eval-expo e1 env v) (project0 (v) (cond ((var? v) (conde ((=/= #f v) (== v val)) ((== #f v) (oro `(,e2 . ,e-rest) env val)))) ((not v) (oro `(,e2 . ,e-rest) env val)) (else (== v val)))))) (project0 (e*) (cond ((null? e*) (== #f val)) ((pair? e*) (fresh (ea ed) (== `(,ea . ,ed) e*) (project0 (ed) (cond ((null? ed) (eval-expo ea env val)) ((pair? ed) (gmulti)) (else (conde ((fresh (e) (== `(,e) e*) (eval-expo e env val))) ((gmulti)))))))) (else (conde ((== '() e*) (== #f val)) ((fresh (e) (== `(,e) e*) (eval-expo e env val))) ((gmulti))))))) (define (if-primo expr env val) (fresh (e1 e2 e3 t) (== `(if ,e1 ,e2 ,e3) expr) (not-in-envo 'if env) (eval-expo e1 env t) (project0 (t) (cond ((var? t) (conde ((=/= #f t) (eval-expo e2 env val)) ((== #f t) (eval-expo e3 env val)))) ((not t) (eval-expo e3 env val)) (else (eval-expo e2 env val)))))) (define (cond-primo expr env val) (fresh (c c*) (== `(cond ,c . ,c*) expr) (not-in-envo 'cond env) (cond-clauseso `(,c . ,c*) env val))) (define (cond-clauseso c* env val) (define (gelse) (fresh (conseq) (== `((else ,conseq)) c*) (not-in-envo 'else env) (eval-expo conseq env val))) (define (gtest) (fresh (test conseq c*-rest) (== `((,test ,conseq) . ,c*-rest) c*) (fresh (v) (eval-expo test env v) (project0 (v) (cond ((var? v) (conde ((=/= #f v) (eval-expo conseq env val)) ((== #f v) (cond-clauseso c*-rest env val)))) ((not v) (cond-clauseso c*-rest env val)) (else (eval-expo conseq env val))))))) (project0 (c*) (cond ((null? c*) (== undefined-tag val)) ((pair? c*) (fresh (test conseq cd) (== `((,test ,conseq) . ,cd) c*) (project0 (cd) (cond ((null? cd) (project0 (test) (if (eq? 'else test) (case-bound-symbolo test env (lambda () (conde ((gelse)) ((gtest)))) (lambda () (eval-expo conseq env val)) (lambda () (gtest))) (gtest)))) ((pair? cd) (gtest)) (else (conde ((gelse)) ((gtest)))))))) (else (conde ((== '() c*) (== undefined-tag val)) ((gelse)) ((gtest))))))) (define initial-env `((val . (list . (,closure-tag (lambda x x) ,empty-env))) (val . (not . (,prim-tag . not))) (val . (equal? . (,prim-tag . equal?))) (val . (symbol? . (,prim-tag . symbol?))) (val . (number? . (,prim-tag . number?))) (val . (cons . (,prim-tag . cons))) (val . (null? . (,prim-tag . null?))) (val . (pair? . (,prim-tag . pair?))) (val . (car . (,prim-tag . car))) (val . (cdr . (,prim-tag . cdr))) (val . (procedure? . (,prim-tag . procedure?))) . ,empty-env)) ;; TODO: make these as eager as possible. (define handle-matcho (lambda (expr env val) (fresh (against-expr mval clause clauses) (== `(match ,against-expr ,clause . ,clauses) expr) (not-in-envo 'match env) (eval-expo against-expr env mval) (match-clauses mval `(,clause . ,clauses) env val)))) (define (not-symbolo t) (conde ((== #f t)) ((== #t t)) ((== '() t)) ((numbero t)) ((fresh (a d) (== `(,a . ,d) t))))) (define (not-numbero t) (conde ((== #f t)) ((== #t t)) ((== '() t)) ((symbolo t)) ((fresh (a d) (== `(,a . ,d) t))))) (define (self-eval-literalo t) (conde ((numbero t)) ((booleano t)))) (define (literalo t) (conde ((numbero t)) ((symbolo t) (=/= closure-tag t) (=/= prim-tag t)) ((booleano t)) ((== '() t)))) (define (booleano t) (conde ((== #f t)) ((== #t t)))) (define (regular-env-appendo env1 env2 env-out) (conde ((== empty-env env1) (== env2 env-out)) ((fresh (y v rest res) (== `((val . (,y . ,v)) . ,rest) env1) (== `((val . (,y . ,v)) . ,res) env-out) (regular-env-appendo rest env2 res))))) (define (match-clauses mval clauses env val) (fresh (p result-expr d) (== `((,p ,result-expr) . ,d) clauses) (p-clauseo p mval '() (lambda (_) (conde ((fresh (env^ penv) (p-match p mval '() penv) (regular-env-appendo penv env env^) (eval-expo result-expr env^ val))) ((fresh (penv) (p-no-match p mval '() penv) (match-clauses mval d env val))))) (lambda (penv) (fresh (env^) (regular-env-appendo penv env env^) (eval-expo result-expr env val))) (lambda (_) (match-clauses mval d env val))))) (define (p-clauseo p mval penv gk-unknown gk-match gk-no-match) (project0 (p mval) (cond ((or (var? p) (var? mval)) (gk-unknown penv)) ((or (number? p) (boolean? p)) (if (eqv? p mval) (gk-match penv) (gk-no-match penv))) ((symbol? p) (case-bound-symbolo x penv (lambda () (gk-unknown penv)) (lambda () (fresh (penv-out) (== `((val . (,var . ,mval)) . ,penv) penv-out) (gk-match penv-out))) (lambda () (fresh (val) (lookupo p penv val) (project0 (val) (if (var? val) (gk-unknown penv) ;; TODO: immediate equality check. (gk-unknown penv) ;(gk-match penv) ;(gk-no-match penv) )))))) ((pair? p) (fresh (pa pd) (== `(,pa . ,pd) p) (project0 (pa) (cond ((eq? 'quote pa) (fresh (datum) (== `(quote ,datum) p) (project0 (datum) (if (var? datum) (gk-unknown penv) ;; TODO: immediate equality check. (gk-unknown penv) ;(gk-match penv) ;(gk-no-match penv) )))) ;; TODO: predicate, quasiquote ;((eq? '? pa) ;) ;((eq? 'quasiquote pa) ;) (else (gk-unknown penv)))))) (else fail)))) (define (var-p-match var mval penv penv-out) (fresh (val) (symbolo var) (=/= closure-tag mval) (=/= prim-tag mval) (conde ((== mval val) (== penv penv-out) (lookupo var penv val)) ((== `((val . (,var . ,mval)) . ,penv) penv-out) (not-in-envo var penv))))) (define (var-p-no-match var mval penv penv-out) (fresh (val) (symbolo var) (=/= mval val) (== penv penv-out) (lookupo var penv val))) (define (p-match p mval penv penv-out) (conde ((self-eval-literalo p) (== p mval) (== penv penv-out)) ((var-p-match p mval penv penv-out)) ((fresh (datum) (== `(quote ,datum) p) (== datum mval) (== penv penv-out))) ((fresh (var pred val) (== `(? ,pred ,var) p) (conde ((== 'symbol? pred) (symbolo mval)) ((== 'number? pred) (numbero mval))) (var-p-match var mval penv penv-out))) ((fresh (quasi-p) (== (list 'quasiquote quasi-p) p) (quasi-p-match quasi-p mval penv penv-out))))) (define (p-no-match p mval penv penv-out) (conde ((self-eval-literalo p) (=/= p mval) (== penv penv-out)) ((var-p-no-match p mval penv penv-out)) ((fresh (datum) (== `(quote ,datum) p) (=/= datum mval) (== penv penv-out))) ((fresh (var pred val) (== `(? ,pred ,var) p) (== penv penv-out) (symbolo var) (conde ((== 'symbol? pred) (conde ((not-symbolo mval)) ((symbolo mval) (var-p-no-match var mval penv penv-out)))) ((== 'number? pred) (conde ((not-numbero mval)) ((numbero mval) (var-p-no-match var mval penv penv-out))))))) ((fresh (quasi-p) (== (list 'quasiquote quasi-p) p) (quasi-p-no-match quasi-p mval penv penv-out))))) (define (quasi-p-match quasi-p mval penv penv-out) (conde ((== quasi-p mval) (== penv penv-out) (literalo quasi-p)) ((fresh (p) (== (list 'unquote p) quasi-p) (p-match p mval penv penv-out))) ((fresh (a d v1 v2 penv^) (== `(,a . ,d) quasi-p) (== `(,v1 . ,v2) mval) (=/= 'unquote a) (quasi-p-match a v1 penv penv^) (quasi-p-match d v2 penv^ penv-out))))) (define (quasi-p-no-match quasi-p mval penv penv-out) (conde ((=/= quasi-p mval) (== penv penv-out) (literalo quasi-p)) ((fresh (p) (== (list 'unquote p) quasi-p) (=/= closure-tag mval) (=/= prim-tag mval) (p-no-match p mval penv penv-out))) ((fresh (a d) (== `(,a . ,d) quasi-p) (=/= 'unquote a) (== penv penv-out) (literalo mval))) ((fresh (a d v1 v2 penv^) (== `(,a . ,d) quasi-p) (=/= 'unquote a) (== `(,v1 . ,v2) mval) (conde ((quasi-p-no-match a v1 penv penv^)) ((quasi-p-match a v1 penv penv^) (quasi-p-no-match d v2 penv^ penv-out)))))))
false
2074704b784d0d3f8dec5f05325b8a5fd1755381
db442e9ba81eb899a2a1a289ce66311c0cce8021
/char-set/cyclone/char-set/base.sld
0fb2f4deb5765659c4a1b0197a065c44ba28be87
[ "BSD-3-Clause" ]
permissive
cyclone-scheme/cyclone-packages
b336aece25b3031ec03db179303e27703f3f88d0
16b41a22f2f55628078409b26f204b6b500834a2
refs/heads/master
2021-01-20T05:13:08.219700
2017-04-16T22:18:42
2017-04-16T22:18:42
83,856,503
0
2
null
2017-04-17T00:31:28
2017-03-04T01:37:13
Scheme
UTF-8
Scheme
false
false
421
sld
base.sld
(define-library (cyclone char-set base) (export (rename Integer-Set Char-Set) (rename iset? char-set?) immutable-char-set char-set-contains?) (import (scheme base) (cyclone iset base)) (begin (define-syntax immutable-char-set (syntax-rules () ((immutable-char-set cs) cs))) (define (char-set-contains? cset ch) (iset-contains? cset (char->integer ch)))))
true
6ebb22d7ac5567d079c64619c9c370a288a0b03e
57bfe431088678c31259140ea9ddfda9dea3f281
/lisp-in-small-pieces/chapter-3/continuation-coroutine.scm
f762eadd41b0ae30225cc7cfc81de476e0a2d26a
[]
no_license
ezy023/book-notes
c3b025fb4d8b3c230db9ee330cf14681ff28bb7f
f00f1418e2a346807c4cf9a417a0ce5f4bfc0124
refs/heads/master
2021-11-25T09:14:36.135115
2021-11-02T01:26:11
2021-11-02T01:26:11
161,814,039
0
0
null
2020-06-02T17:21:56
2018-12-14T16:43:19
TeX
UTF-8
Scheme
false
false
873
scm
continuation-coroutine.scm
;; The following procedures are coroutines that call each other as they iterate through the list of numbers, until no numbers remain (define numbers '(1 2 3 4 5 6 7 8 9)) (define c1 (lambda (kont) (if (pair? numbers) (let ((current (car numbers))) (set! numbers (cdr numbers)) ;; modify the global value of 'numbers' (format #t "c1 showing number ~s" current) (newline) (sleep 2) (c1 (call/cc kont)))) ;; calls (kont the-current-continuation), the-current-continuation in this case is just returning the symbol 'done 'done)) (define c2 (lambda (kont) (if (pair? numbers) (let ((current (car numbers))) (set! numbers (cdr numbers)) (format #t "c2 showing number ~s" current) (newline) (sleep 2) (c2 (call/cc kont)))) 'finish)) (c1 c2)
false
bcf83532486950f697f934b0a9b162467e39ce35
804e0b7ef83b4fd12899ba472efc823a286ca52d
/old/FeedReader/serf/network/http/response-v1.scm
5fa51e12ce49595cdea17c234afad3a3f4aecbb9
[ "Apache-2.0" ]
permissive
cha63506/CRESTaceans
6ec436d1bcb0256e17499ea9eccd5c034e9158bf
a0d24fd3e93fc39eaf25a0b5df90ce1c4a96ec9b
refs/heads/master
2017-05-06T16:59:57.189426
2013-10-17T15:22:35
2013-10-17T15:22:35
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
5,022
scm
response-v1.scm
;; Copyright 2009 Michael M. Gorlick ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; http://www.apache.org/licenses/LICENSE-2.0 ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; A Scheme wrapper around the Apache HTTP Components BasicHttpResponse. (define <http/response> (let () ; Hide the Java grit from view. (define-java-class <java-http-response> |org.apache.http.message.BasicHttpResponse|) (define-java-class <java-http-status-line> |org.apache.http.message.BasicStatusLine|) (define-generic-java-method get-status-line) ; StatusLine getStatusLine() for BasicHttpResponse (define-generic-java-method set-entity) ; void setEntity(HttpEntity) for BasicHttpResponse (define-generic-java-method set-header) ; void setHeader(String, String) for BasicHttpResponse (define-generic-java-method set-reason-phrase) ; void setReasonPhrase(String) for BasicHttpResponse (define-generic-java-method set-status-code) ; void setStatusCode(int) for BasicHttpResponse (define-generic-java-method get-reason-phrase) ; String getReasonPhrase for BasicStatusLine (define-generic-java-method get-status-code) ; int getStatusCode() for BasicStatusLine ; Set the headers in a BasicHttpResponse instance o. (define (to-java-headers o headers) (cond ((null? headers) o) (else (let ((header (car headers))) (set-header o (->jstring (car header)) (->jstring (cdr header)))) (to-java-headers o (cdr headers))))) ; Object constructor. (lambda () (let ((self (make-object)) (status #f) (reason #f) (headers #f) ; Content (length #f) ; Length in bytes. (type #f) ; MIME type. (encoding #f) ; Usually UTF-8. (entity #f) ; For now just a string if anything at all. (java #f)) ; The original Java object (if any). (make-method! self instantiate (lambda (self . arguments) (if (null? arguments) (set! headers '()) (instantiate/nonvirgin self (car arguments))))) (make-method! self instantiate/nonvirgin (lambda (self java-http-response) (set! java java-http-response) (set! headers (->list (get-all-headers java-http-request))) (translate-headers headers headers) (let ((line (get-status-line java-http-response))) (set! status (->int (get-status-code line))) (set! reason (->string (get-reason-phrase line)))) (let* ((e (get-entity java-http-response))) (cond ((not (java-null? e)) (set! entity (entity/string/extract e)) (let ((n (->number (get-content-length e)))) (set! length (and (> n 0) n))) (let ((h (get-content-type e))) (set! type (and (not (java-null? h)) (cdr (http/header/unwrap h))))) (let ((h (get-content-encoding e))) (set! encoding (and (not (java-null? h)) (cdr (http/header/unwrap h)))))) (else (set! entity #f) (set! length #f) (set! type #f) (set encoding #f)))))) (make-method! self http/response/header! (lambda (self header) (set! headers (cons header headers)))) (make-method! self http/response/headers (lambda (self) (if java headers (reverse headers)))) (make-method! self http/response/status (lambda (self) status)) (make-method! self http/response/reason (lambda (self) reason)) (make-method! self http/response/length (lambda (self) length)) (make-method! self http/response/type (lambda (self) type)) (make-method! self http/response/encoding (lambda (self) encoding)) (make-method! self http/response/entity (lambda (self) entity)) (make-method! self http/response/entity! (lambda (self e) (set! entity e))) ; For now must be a Scheme string. (make-method! self http/response/encoding! (lambda (self e) ; e: Scheme string giving value of Content-Encoding header. (set! encoding e))) (make-method! self http/response/type! (lambda (self m) ; m: Scheme string giving MIME type for Content-Type header. (set! type m))) (make-method! self http/response/java ; Construct a Java BasicHttpResponse object. (lambda (self o) ; o: BasicHttpResponse instance. (cond ((not java) (set-status-code o (->jint status)) (set-reason-phrase o (->jstring reason)) (if type (set! headers (cons '|Content-Type| . type))) (if encoding (set! headers (cons '|Content-Encoding| . encoding))) (to-java-headers o (reverse headers)) (if entity (set-entity o (entity/string/new entity))) o) (else #f)))) self))))
false
321f4be205578f27403a63d8fdaf66b4574a41d9
98fd12cbf428dda4c673987ff64ace5e558874c4
/sicp/v1/chapter-3.3/ndpar-3.3.scm
e9290b635da788e611776eaed3dabd4d1e2fab59
[ "Unlicense" ]
permissive
CompSciCabal/SMRTYPRTY
397645d909ff1c3d1517b44a1bb0173195b0616e
a8e2c5049199635fecce7b7f70a2225cda6558d8
refs/heads/master
2021-12-30T04:50:30.599471
2021-12-27T23:50:16
2021-12-27T23:50:16
13,666,108
66
11
Unlicense
2019-05-13T03:45:42
2013-10-18T01:26:44
Racket
UTF-8
Scheme
false
false
8,375
scm
ndpar-3.3.scm
#lang planet neil/sicp ;; ------------------------------------------------------------------- ;; Mutable Lists, p.252 ;; ------------------------------------------------------------------- ;; Exrcise 3.16, p.259 (define (count-pairs x) (if (not (pair? x)) 0 (+ (count-pairs (car x)) (count-pairs (cdr x)) 1))) ;; Tests (= 3 (count-pairs (cons 1 (cons 2 (cons 3 nil))))) (define x (cons 1 nil)) (= 4 (count-pairs (cons (cons 2 x) x))) (= 5 (count-pairs (cons (cons x x) x))) (define y (cons x x)) (= 7 (count-pairs (cons y y))) (define z (cons 3 4)) (define cycle (cons 1 (cons 2 z))) (set-cdr! z cycle) ;(= ∞ (count-pairs cycle)) ; Infinite loop ;; Exrcise 3.17, p.259 (define (cp x) (let ((visited nil)) (define (iter y) (if (memq y visited) 0 (begin (set! visited (cons y visited)) (if (not (pair? y)) 0 (+ (iter (car y)) (iter (cdr y)) 1))))) (iter x))) ;; Tests (= 3 (cp (cons 1 (cons 2 (cons 3 nil))))) (= 3 (cp (cons (cons 2 x) x))) (= 3 (cp (cons (cons x x) x))) (= 3 (cp (cons y y))) (= 3 (cp cycle)) ;; Exercise 3.18, p.260 (define (cycle? ls) (define (iter y visited) (cond ((memq y visited) #t) ((null? y) #f) (else (iter (cdr y) (cons y visited))))) (iter ls nil)) ;; Tests (not (cycle? '(1 2 3))) (cycle? cycle) ;; Exercise 3.19, p.260 (define (floyd-cycle? ls) (define (iter tortoise hare) (cond ((eq? tortoise hare) #t) ((null? hare) #f) ((null? (cdr hare)) #f) (else (iter (cdr tortoise) (cddr hare))))) (cond ((null? ls) #f) ((null? (cdr ls)) #f) (else (iter (cdr ls) (cddr ls))))) ;; Tests (not (floyd-cycle? nil)) (not (floyd-cycle? '(1))) (not (floyd-cycle? '(1 2))) (not (floyd-cycle? '(1 2 3))) (floyd-cycle? cycle) ;; ------------------------------------------------------------------- ;; Representing Queues, p.261 ;; ------------------------------------------------------------------- (define front-ptr car) (define rear-ptr cdr) (define set-front-ptr! set-car!) (define set-rear-ptr! set-cdr!) (define (make-queue) (cons nil nil)) (define (empty-queue? queue) (null? (front-ptr queue))) (define (front-queue queue) (if (empty-queue? queue) (error "FRONT called with an empty queue" queue) (car (front-ptr queue)))) (define (insert-queue! queue item) (let ((new-pair (cons item nil))) (cond ((empty-queue? queue) (set-front-ptr! queue new-pair) (set-rear-ptr! queue new-pair) queue) (else (set-cdr! (rear-ptr queue) new-pair) (set-rear-ptr! queue new-pair) queue)))) (define (delete-queue! queue) (cond ((empty-queue? queue) (error "DELETE! called with an empty queue" queue)) (else (set-front-ptr! queue (cdr (front-ptr queue))) queue))) ;; Exercise 3.21, p.265 (define (print-queue queue) (display (front-ptr queue)) (newline)) (define q1 (make-queue)) (print-queue (insert-queue! q1 'a)) (print-queue (insert-queue! q1 'b)) (print-queue (delete-queue! q1)) (print-queue (delete-queue! q1)) ;; Exercise 3.22, p.266 (define (make-q) (let ((front-ptr nil) (rear-ptr nil)) (define (empty-q?) (null? front-ptr)) (define (insert-q item) (let ((q (cons item nil))) (cond ((empty-q?) (set! front-ptr q) (set! rear-ptr q) front-ptr) (else (set-cdr! rear-ptr q) (set! rear-ptr q) front-ptr)))) (define (delete-q) (cond ((empty-q?) (error "DELETE! called with an empty queue" front-ptr)) (else (set! front-ptr (cdr front-ptr)) front-ptr))) (define (dispatch m) (cond ((eq? m 'insert-queue) insert-q) ((eq? m 'delete-queue) delete-q))) dispatch)) (define q2 (make-q)) ((q2 'insert-queue) 'a) ((q2 'insert-queue) 'b) ((q2 'delete-queue)) ((q2 'delete-queue)) ;; Exercise 3.23, p.266 (define (cell item) (cons item (cons nil nil))) (define (link! left-cell right-cell) (set-car! (cdr left-cell) right-cell) (set-cdr! (cdr right-cell) left-cell) left-cell) ; ┌─┬─┐ ; Deque │*│*┼────┐ ; └┼┴─┘ │ ; │ │ ; ┌┴┐ ┌┴┐ ; ┌─┤a│ ┌──┤b│ Cells ; │ ├─┤ │ ├─┤ ; │ │*│ │ │*│ ; │ └┼┘ │ └┼┘ ; │ ┌┴┐ │ ┌┴┐ ; │ │*┼──┘ │ │ ; │ ├─┤ ├─┤ ; │ │ │ ┌┼*│ ; │ └─┘ │└─┘ ; └────────┘ (define (make-deque) (cons nil nil)) (define (empty-deque? d) (null? (car d))) (define (front-deque d) (if (empty-deque? d) (error "FRONT called with an empty deque" d) (caar d))) (define (rear-deque d) (if (empty-deque? d) (error "REAR called with an empty deque" d) (cadr d))) (define (front-insert-deque! d item) (let ((n (cell item))) (cond ((empty-deque? d) (set-car! d n) (set-cdr! d n) d) (else (link! n (car d)) (set-car! d n) d)))) (define (rear-insert-deque! d item) (let ((n (cell item))) (cond ((empty-deque? d) (set-car! d n) (set-cdr! d n) d) (else (link! (cdr d) n) (set-cdr! d n) d)))) (define (front-delete-deque! d) (cond ((empty-deque? d) (error "FRONT-DELETE! called with an empty deque" d)) (else (set-car! d (cadar d)) (set-cdr! (cdar d) nil) d))) (define (rear-delete-deque! d) (cond ((empty-deque? d) (error "REAR-DELETE! called with an empty deque" d)) (else (set-cdr! d (cdddr d)) (set-car! (cddr d) nil) d))) (define (to-list d) (define (iter acc cells) (if (null? cells) (reverse acc) (iter (cons (car cells) acc) (cadr cells)))) (iter nil (car d))) ;; Tests (define d (make-deque)) (to-list (front-insert-deque! d 5)) (front-deque d) (rear-deque d) (to-list (front-insert-deque! d 4)) (front-deque d) (rear-deque d) (to-list (rear-insert-deque! d 6)) (front-deque d) (rear-deque d) (to-list (front-delete-deque! d)) (front-deque d) (rear-deque d) (to-list (rear-delete-deque! d)) (front-deque d) (rear-deque d) ;; ------------------------------------------------------------------- ;; Representing Tables, p.270 ;; ------------------------------------------------------------------- (define (assoc key records same-key?) (cond ((null? records) false) ((same-key? key (caar records)) (car records)) (else (assoc key (cdr records) same-key?)))) (define (make-table same-key?) (let ((local-table (list '*table*))) (define (lookup key-1 key-2) (let ((subtable (assoc key-1 (cdr local-table) same-key?))) (if subtable (let ((record (assoc key-2 (cdr subtable) same-key?))) (if record (cdr record) false)) false))) (define (insert! key-1 key-2 value) (let ((subtable (assoc key-1 (cdr local-table) same-key?))) (if subtable (let ((record (assoc key-2 (cdr subtable) same-key?))) (if record (set-cdr! record value) (set-cdr! subtable (cons (cons key-2 value) (cdr subtable))))) (set-cdr! local-table (cons (list key-1 (cons key-2 value)) (cdr local-table))))) 'ok) (define (dispatch m) (cond ((eq? m 'lookup-proc) lookup) ((eq? m 'insert-proc!) insert!) (else (error "Unknown operation -- TABLE" m)))) dispatch)) (define operation-table (make-table equal?)) (define get (operation-table 'lookup-proc)) (define put (operation-table 'insert-proc!)) ;; Tests (put 'a 'b 5) (get 'a 'b) (define test-table (make-table =)) ((test-table 'insert-proc!) 4 2 42) (= 42 ((test-table 'lookup-proc) 4.0 2.0))
false
0d272d6169e3d87191f2f18cb44349da390d30d0
951b7005abfe3026bf5b3bd755501443bddaae61
/astonish/stream/序对的无穷流.scm
47f9d9738de5893d06605bb50138ec9f4780c8cc
[]
no_license
WingT/scheme-sicp
d8fd5a71afb1d8f78183a5f6e4096a6d4b6a6c61
a255f3e43b46f89976d8ca2ed871057cbcbb8eb9
refs/heads/master
2020-05-21T20:12:17.221412
2016-09-24T14:56:49
2016-09-24T14:56:49
63,522,759
2
0
null
null
null
null
UTF-8
Scheme
false
false
6,320
scm
序对的无穷流.scm
(define (interleave s1 s2) (if (empty-stream? s1) s2 (cons-stream (stream-car s1) (interleave s2 (stream-cdr s1))))) (define (pairs s t) (cons-stream (list (stream-car s) (stream-car t)) (interleave (stream-map (lambda (x) (list (stream-car s) x)) (stream-cdr t)) (pairs (stream-cdr s) (stream-cdr t))))) (define the-pairs (pairs integers integers)) ;3.66 (define (pairs-2 s t) (cons-stream (list (stream-car s) (stream-car t)) (interleave (stream-map (lambda (x) (list (stream-car s) x)) (stream-cdr t)) (interleave (stream-map (lambda (x) (list x (stream-car t))) (stream-cdr s)) (pairs-2 (stream-cdr s) (stream-cdr t)))))) (define the-pairs-2 (pairs-2 integers integers)) (display-n the-pairs-2 20) ;3.69 (define (triples s t u) (cons-stream (list (stream-car s) (stream-car t) (stream-car u)) (interleave (triples (stream-cdr s) (stream-cdr t) (stream-cdr u)) (interleave (stream-map (lambda (k) (list (stream-car s) (stream-car t) k)) (stream-cdr u)) (stream-map (lambda (jk) (cons (stream-car s) jk)) (pairs (stream-cdr t) (stream-cdr u))))))) (define the-triples (triples integers integers integers)) (define pythagoras (stream-filter (lambda (ijk) (= (+ (square (car ijk)) (square (cadr ijk))) (square (caddr ijk)))) the-triples)) (display-n the-triples 10) (display-n pythagoras 4) ;;下面是来自schemewiki的版本,两者效率差不多,这样盲搜基本只能等到猴年马月,但是下面这个版本明显简洁很多 (define (triples-2 s t u) (cons-stream (list (stream-car s) (stream-car t) (stream-car u)) (interleave (stream-map (lambda (jk) (cons (stream-car s) jk)) (stream-cdr (pairs t u))) (triples-2 (stream-cdr s) (stream-cdr t) (stream-cdr u))))) (define the-triples-2 (triples-2 integers integers integers)) (define pythagoras-2 (stream-filter (lambda (ijk) (= (+ (square (car ijk)) (square (cadr ijk))) (square (caddr ijk)))) the-triples-2)) (display-n the-triples-2 10) (display-n pythagoras-2 4) ;3.70 (define (merge-weighted s1 s2 weight) (cond ((empty-stream? s1) s2) ((empty-stream? s2) s1) (else (let ((s1car (stream-car s1)) (s2car (stream-car s2))) (cond ((< (weight s1car) (weight s2car)) (cons-stream s1car (merge-weighted (stream-cdr s1) s2 weight))) (else (cons-stream s2car (merge-weighted s1 (stream-cdr s2) weight)))))))) (define (weighted-pairs s1 s2 weight) (let ((s1car (stream-car s1)) (s2car (stream-car s2))) (cons-stream (list s1car s2car) (merge-weighted (stream-map (lambda (j) (list s1car j)) (stream-cdr s2)) (weighted-pairs (stream-cdr s1) (stream-cdr s2) weight) weight)))) ;;a (define the-pairs-3 (weighted-pairs integers integers (lambda (ij) (+ (car ij) (cadr ij))))) (display-n the-pairs-3 10) ;;b (define the-pairs-4 (weighted-pairs integers integers (lambda (ij) (let ((i (car ij)) (j (cadr ij))) (+ (* 2 i) (* 3 j) (* 5 i j)))))) (display-n the-pairs-4 10) (display-n (stream-map (lambda (ij) (let ((i (car ij)) (j (cadr ij))) (+ (* 2 i) (* 3 j) (* 5 i j)))) the-pairs-4) 10) ;3.71 (define (ramanujan) (define (cube x) (* x x x)) (define the-weight (lambda (ij) (let ((i (car ij)) (j (cadr ij))) (+ (cube i) (cube j))))) (define the-pairs (weighted-pairs integers integers the-weight)) (define (iter pairs) (if (= (the-weight (stream-car pairs)) (the-weight (stream-car (stream-cdr pairs)))) (cons-stream (the-weight (stream-car pairs)) (iter (stream-cdr pairs))) (iter (stream-cdr pairs)))) (iter the-pairs)) (define the-ramanujan (ramanujan)) (display-n the-ramanujan 5) ;3.72 (define (square-sum-of-3-pairs) (define the-weight (lambda (ij) (let ((i (car ij)) (j (cadr ij))) (+ (square i) (square j))))) (define the-pairs (weighted-pairs integers integers the-weight)) (define (iter pairs) (let ((scar (stream-car pairs)) (scadr (stream-car (stream-cdr pairs))) (scaddr (stream-car (stream-cdr (stream-cdr pairs))))) (if (= (the-weight scar) (the-weight scadr) (the-weight scaddr)) (cons-stream (cons (the-weight scar) (list scar scadr scaddr)) (iter (stream-cdr pairs))) (iter (stream-cdr pairs))))) (iter the-pairs)) (define the-square-sum-of-3-pairs (square-sum-of-3-pairs)) (display-n the-square-sum-of-3-pairs 25)
false
4c056176d6efd827fe7e43451b8440bf44c1c23d
9998f6f6940dc91a99e0e2acb4bc4e918f49eef0
/src/template.ss
ce1f434a60c278c98af0bb17212e0ebbad09e9f8
[]
no_license
JessamynT/wescheme-compiler2012
326d66df382f3d2acbc2bbf70fdc6b6549beb514
a8587f9d316b3cb66d8a01bab3cf16f415d039e5
refs/heads/master
2020-05-30T07:16:45.185272
2016-03-19T07:14:34
2016-03-19T07:14:34
70,086,162
0
0
null
2016-10-05T18:09:51
2016-10-05T18:09:51
null
UTF-8
Scheme
false
false
3,456
ss
template.ss
#lang scheme/base (require (for-syntax scheme/base) scheme/file scheme/path scheme/contract) (provide/contract [fill-template (string? hash? . -> . string?)] [fill-template-port (input-port? output-port? hash? . -> . any)] [fill-template-file (path-string? path-string? hash? . -> . any)] [replace-template-file (path-string? path-string? hash? . -> . any)]) (provide build-mappings) ;; fill-template: string hashtable -> string ;; Given a template, fills in all of the holes in the template ;; with values from the mappings. Each hole is of the form ;; <<[-A-Z]>> ;; ;; Example: ;; ;; (fill-template "Hello <<name>>" #hash(("name" . "Danny"))) ;; ;; should produce "Hello Danny". (define (fill-template a-template mappings) (let ([pattern #px"\\<\\<([-A-Za-z]+)\\>\\>"]) (cond [(regexp-match pattern a-template) => (lambda (a-match) ;; I want to use regexp-replace*, but there's a bug in ;; Racket 5.0 that prevents me from doing so: the type ;; signature of regexp-replace* is incompatible with ;; previous versions of plt-scheme. (fill-template (regexp-replace pattern a-template (lambda (_ hole-name) (stringify (hash-ref mappings hole-name)))) mappings))] [else a-template]))) ;; stringify: X -> string ;; Just make sure we turn something into a string. (define (stringify thing) (cond [(string? thing) thing] [(path? thing) (path->string thing)] [else (format "~a" thing)])) ;; fill-template-port: input-port output-port hashtable -> void (define (fill-template-port inp outp mappings) (for ([line (in-lines inp)]) (display (fill-template line mappings) outp) (newline outp))) ;; fill-template-file: path path mappings -> void (define (fill-template-file a-path-in a-path-out mappings) (make-directory* (path-only a-path-out)) ;; fixme: validate that a-path-in and a-path-out are different. (call-with-output-file a-path-out (lambda (op) (call-with-input-file a-path-in (lambda (ip) (for ([line (in-lines ip)]) (display (fill-template line mappings) op) (newline op))))) #:exists 'replace)) (define (replace-template-file dest-dir a-path mappings) (fill-template-file (build-path dest-dir (string-append a-path ".template")) (build-path dest-dir a-path) mappings) (delete-file (build-path dest-dir (string-append a-path ".template")))) (define-syntax (build-mappings stx) (syntax-case stx () [(_ (k v) ...) (andmap identifier? (syntax->list #'(k ...))) (with-syntax ([(k ...) (map (lambda (s) (symbol->string (syntax-e s))) (syntax->list #'(k ...)))]) (syntax/loc stx (let ([ht (make-hash)]) (hash-set! ht k v) ... ht)))] [(_ (k v) ...) (not (andmap identifier? (syntax->list #'(k ...)))) (let ([bad-non-identifier-stx (findf (lambda (stx) (not (identifier? stx))) (syntax->list #'(k ...)))]) (raise-syntax-error #f "Not an identifier" stx bad-non-identifier-stx))]))
true
d476cc6858a96dac830db94330d1c2e8c7ed2d30
cfa60b41f70f07dcb6e2d4b637c71593779088ca
/tests/client.scm
752034b18fd31f41547ffe78b27d332dc80bc4e8
[]
no_license
hugoArregui/awful-blog
01b815ff2e898df271ed75781195900f40ef2aef
3ba5027ad22cd784208e6e6c5726077d4e5406c6
refs/heads/master
2021-03-12T19:21:36.522488
2016-08-28T23:35:24
2016-08-28T23:35:24
11,226,846
0
0
null
null
null
null
UTF-8
Scheme
false
false
858
scm
client.scm
(use posix setup-api) (use http-client test intarweb uri-common awful) (define server-uri "http://localhost:8080") (define (get path/vars) (let ((val (with-input-from-request (make-pathname server-uri path/vars) #f read-string))) (close-all-connections!) val)) (define (expect/text title content) (sprintf "\n<div class=\"page-header\">\n<h1>~a</h1></div>~a\n<br />\n<br />" title content)) (define (expect/markdown content) (sprintf "\n<p>~a</p>" content)) (define (expect/html content) (sprintf "\n<p>~a</p>\n" content)) (test-begin "awful-blog") (pp (get "/blog/")) (test (expect/text "foo" "this is foo") (get "/blog/foo")) (test (expect/markdown "this is bar") (get "/blog/bar")) (test (expect/html "this is hh") (get "/blog/hh")) (test-end "awful-blog")
false
0f7ee8c3353e054d6457f01e84e9fb7163d3f362
e1fc47ba76cfc1881a5d096dc3d59ffe10d07be6
/ch5/5.05.eceval-support.scm
3b88b89ea24d41b8c9b7f07a48441141c1d366d9
[]
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
5,447
scm
5.05.eceval-support.scm
(load "5.05.syntax.scm") ;; makeup for syntax ; cond (define cond-first-clause car) (define cond-first-clause-predicate caar) (define cond-first-clause-actions cdar) (define cond-rest-clauses cdr) (define cond-no-clauses? null?) ; apply (define (empty-arglist) '()) (define (adjoin-arg arg arglist) (append arglist (list arg))) (define (last-operand? ops) (null? (cdr ops))) ;; operation for machine use ;; from ch4/4.01.no-aly.scm (define (true? x) (not (eq? x #f)) ) (define (false? x) (eq? x #f) ) (define (make-procedure parameters body env) (list 'procedure parameters body env) ) (define (compound-procedure? p) (tagged-list? p 'procedure)) (define procedure-parameters cadr) (define procedure-body caddr) (define procedure-environment cadddr) (define (make-compiled-procedure entry env) (list 'compiled-procedure entry env) ) (define (compiled-procedure? proc) (tagged-list? proc 'compiled-procedure)) (define compiled-procedure-entry cadr) (define compiled-procedure-env caddr) ; def env ; (frame . outer-env) (define (enclosing-environment env) (cdr env)) ; outer (define (first-frame env) (car env)) (define the-empty-environment '()) ; list-struct: ; (var-1 var-2 ..) . (val-1 val-2 ..) (define (make-frame variables values) (cons variables values)) (define frame-variables car) (define frame-values cdr) (define (add-binding-to-frame! var val frame) (set-car! frame (cons var (car frame))) (set-cdr! frame (cons val (cdr frame))) ) (define (extend-environment vars vals base-env) (if (= (length vars) (length vals)) (cons (make-frame vars vals) base-env) (if (< (length vars) (length vals)) (error "Too many arguments supplied" vars vals) (error "Too few arguments supplied" vars vals) ) ) ) ; O(n) (define (lookup-variable-value var env) (define (env-loop env) (define (scan vars vals) (cond ; current env not found, goto outer ((null? vars) (env-loop (enclosing-environment env))) ; found ((eq? var (car vars)) (car vals)) ; iter (else (scan (cdr vars) (cdr vals))) ) ) (if (eq? env the-empty-environment) (error "Unbound variable" var) (let ((frame (first-frame env))) (scan (frame-variables frame) (frame-values frame)) ) ) ) (env-loop env) ) (define (set-variable-value! var val env) (define (env-loop env) (define (scan vars vals) (cond ((null? vars) (env-loop (enclosing-environment env))) ((eq? var (car vars)) (set-car! vals val)) (else (scan (cdr vars) (cdr vals))) ) ) (if (eq? env the-empty-environment) (error "Unbound variable -- SET" var) (let ((frame (first-frame env))) (scan (frame-variables frame) (frame-values frame)) ) ) ) (env-loop env) ) (define (define-variable! var val env) (let ((frame (first-frame env))) (define (scan vars vals) (cond ((null? vars) (add-binding-to-frame! var val frame)) ((eq? var (car vars)) (set-car! vals val)) (else (scan (cdr vars) (cdr vals))) ) ) (scan (frame-variables frame) (frame-values frame)) ) ) ;; ============ ;; init ; primitive-procedure: ; 'primitive (impl) (define (primitive-procedure? proc) (tagged-list? proc 'primitive) ) (define (primitive-implementation proc) (cadr proc) ) ; table: ; <name> <proc>(these procs are primitive, not written in scm) (define primitive-procedures (list ; (list 'car car) (list 'cdr cdr) (list 'cons cons) (list 'null? null?) (list '+ +) (list '- -) (list '* *) (list '/ /) (list '= =) (list '> >) (list '< <) (list '<= <=) (list '>= >=) (list 'not not) (list 'eq? eq?) (list 'remainder remainder) (list 'display display) (list 'newline newline) (list 'read read) (list 'write write) (list 'list list) (list 'length length) (list 'member member) ; .. other primitives ) ) (define (primitive-procedure-names) (map car primitive-procedures) ) (define (primitive-procedure-objects) (map (lambda (proc) (list 'primitive (cadr proc))) primitive-procedures) ) (define (apply-primitive-procedure proc args) (apply-in-underlying-scheme (primitive-implementation proc) args) ) ; using scheme self's `apply` (define apply-in-underlying-scheme apply) (define (setup-environment) ; need primitive-procedure, true and false (let ((initial-env (extend-environment (primitive-procedure-names) (primitive-procedure-objects) the-empty-environment))) (define-variable! 'true #t initial-env) (define-variable! 'false #f initial-env) initial-env ) ) ; (define the-global-environment (setup-environment)) ; (define (get-global-environment) the-global-environment) ; for repl (define (prompt-for-input string) (newline)(newline) (display string) (newline) ) (define (announce-output string) (newline) (display string) (newline) ) (define (user-print object) (cond ((compound-procedure? object) (display (list 'compound-procedure ; check 4.01.03 (procedure-parameters object) (procedure-body object) '<procedure-env> ) ) ) ((compiled-procedure? object) (display object)(newline) ; TODO ) ((not (or (null? object) (unspecified? object))) ; ordinary object (display object)(newline) ) ) )
false
6da8d5bdd201b9e7b2acc04f4e0a5191b4cdce4f
db0567d04297eb710cd4ffb7af094d82b2f66662
/scheme/ikarus.reader.ss
e101e60b10cb990269a1817bbcc1c246c52eec35
[]
no_license
xieyuheng/ikarus-linux
3899e99991fd192de53c485cf429bfd208e7506a
941b627e64f30af60a25530a943323ed5c78fe1b
refs/heads/master
2021-01-10T01:19:05.250392
2016-02-13T22:21:24
2016-02-13T22:21:24
51,668,773
0
0
null
null
null
null
UTF-8
Scheme
false
false
61,437
ss
ikarus.reader.ss
(library (ikarus.reader) (export read read-initial read-token comment-handler get-datum read-annotated read-script-annotated annotation? annotation-expression annotation-source annotation-stripped) (import (only (ikarus.string-to-number) define-string->number-parser) (ikarus system $chars) (ikarus system $fx) (ikarus system $pairs) (ikarus system $bytevectors) (only (ikarus.io) input-port-byte-position input-port-column-number) (except (ikarus) read-char read read-token comment-handler get-datum read-annotated read-script-annotated annotation? annotation-expression annotation-source annotation-stripped input-port-column-number)) (define (die/lex id pos who msg arg*) (raise (condition (make-lexical-violation) (make-message-condition msg) (if (null? arg*) (condition) (make-irritants-condition arg*)) (make-source-position-condition id pos)))) (define (die/pos p off who msg arg*) (die/lex (port-id p) (let ([pos (input-port-byte-position p)]) (and pos (+ pos off))) who msg arg*)) (define (die/p p who msg . arg*) (die/pos p 0 who msg arg*)) (define (die/p-1 p who msg . arg*) (die/pos p -1 who msg arg*)) (define (die/ann ann who msg . arg*) (let ([src (annotation-source ann)]) (die/lex (car src) (cdr src) who msg arg*))) (define (checked-integer->char n ac p) (define (valid-integer-char? n) (cond [(<= n #xD7FF) #t] [(< n #xE000) #f] [(<= n #x10FFFF) #t] [else #f])) (if (valid-integer-char? n) ($fixnum->char n) (die/p p 'tokenize "invalid numeric value for character" (list->string (reverse ac))))) (define-syntax read-char (syntax-rules () [(_ p) (get-char p)])) (define delimiter? (lambda (c) (or (char-whitespace? c) (memq c '(#\( #\) #\[ #\] #\" #\# #\; #\{ #\} #\|))))) (define digit? (lambda (c) (and ($char<= #\0 c) ($char<= c #\9)))) (define char->num (lambda (c) (fx- ($char->fixnum c) ($char->fixnum #\0)))) (define initial? (lambda (c) (cond [($char<= c ($fixnum->char 127)) (or (letter? c) (special-initial? c))] [else (unicode-printable-char? c)]))) (define letter? (lambda (c) (or (and ($char<= #\a c) ($char<= c #\z)) (and ($char<= #\A c) ($char<= c #\Z))))) (define special-initial? (lambda (c) (memq c '(#\! #\$ #\% #\& #\* #\/ #\: #\< #\= #\> #\? #\^ #\_ #\~)))) (define special-subsequent? (lambda (c) (memq c '(#\+ #\- #\. #\@)))) (define subsequent? (lambda (c) (cond [($char<= c ($fixnum->char 127)) (or (letter? c) (digit? c) (special-initial? c) (special-subsequent? c))] [else (or (unicode-printable-char? c) (memq (char-general-category c) '(Nd Mc Me)))]))) (define tokenize-identifier (lambda (ls p) (let ([c (peek-char p)]) (cond [(eof-object? c) ls] [(subsequent? c) (read-char p) (tokenize-identifier (cons c ls) p)] [(delimiter? c) ls] [(char=? c #\\) (read-char p) (tokenize-backslash ls p)] [(eq? (port-mode p) 'r6rs-mode) (die/p p 'tokenize "invalid identifier syntax" (list->string (reverse (cons c ls))))] [else ls])))) (define (tokenize-string ls p) (let ([c (read-char p)]) (cond [(eof-object? c) (die/p p 'tokenize "invalid eof inside string")] [else (tokenize-string-char ls p c)]))) (define LF1 '(#\xA #\x85 #\x2028)) ;;; these are considered newlines (define LF2 '(#\xA #\x85)) ;;; these are not newlines if they ;;; appear after CR (define (tokenize-string-char ls p c) (define (intraline-whitespace? c) (or (eqv? c #\x9) (eq? (char-general-category c) 'Zs))) (define (tokenize-string-continue ls p c) (cond [(eof-object? c) (die/p p 'tokenize "invalid eof inside string")] [(intraline-whitespace? c) (let f () (let ([c (read-char p)]) (cond [(eof-object? c) (die/p p 'tokenize "invalid eof inside string")] [(intraline-whitespace? c) (f)] [else (tokenize-string-char ls p c)])))] [else (tokenize-string-char ls p c)])) (cond [($char= #\" c) ls] [($char= #\\ c) (let ([c (read-char p)]) (cond [(eof-object? c) (die/p p 'tokenize "invalid eof after string escape")] [($char= #\a c) (tokenize-string (cons #\x7 ls) p)] [($char= #\b c) (tokenize-string (cons #\x8 ls) p)] [($char= #\t c) (tokenize-string (cons #\x9 ls) p)] [($char= #\n c) (tokenize-string (cons #\xA ls) p)] [($char= #\v c) (tokenize-string (cons #\xB ls) p)] [($char= #\f c) (tokenize-string (cons #\xC ls) p)] [($char= #\r c) (tokenize-string (cons #\xD ls) p)] [($char= #\" c) (tokenize-string (cons #\x22 ls) p)] [($char= #\\ c) (tokenize-string (cons #\x5C ls) p)] [($char= #\x c) ;;; unicode escape \xXXX; (let ([c (read-char p)]) (cond [(eof-object? c) (die/p p 'tokenize "invalid eof inside string")] [(hex c) => (lambda (n) (let f ([n n] [ac (cons c '(#\x))]) (let ([c (read-char p)]) (cond [(eof-object? n) (die/p p 'tokenize "invalid eof inside string")] [(hex c) => (lambda (v) (f (+ (* n 16) v) (cons c ac)))] [($char= c #\;) (tokenize-string (cons (checked-integer->char n ac p) ls) p)] [else (die/p-1 p 'tokenize "invalid char in escape sequence" (list->string (reverse (cons c ac))))]))))] [else (die/p-1 p 'tokenize "invalid char in escape sequence" c)]))] [(intraline-whitespace? c) (let f () (let ([c (read-char p)]) (cond [(eof-object? c) (die/p p 'tokenize "invalid eof inside string")] [(intraline-whitespace? c) (f)] [(memv c LF1) (tokenize-string-continue ls p (read-char p))] [(eqv? c #\return) (let ([c (read-char p)]) (cond [(memv c LF2) (tokenize-string-continue ls p (read-char p))] [else (tokenize-string-continue ls p c)]))] [else (die/p-1 p 'tokenize "non-whitespace character after escape")])))] [(memv c LF1) (tokenize-string-continue ls p (read-char p))] [(eqv? c #\return) (let ([c (read-char p)]) (cond [(memv c LF2) (tokenize-string-continue ls p (read-char p))] [else (tokenize-string-continue ls p c)]))] [else (die/p-1 p 'tokenize "invalid string escape" c)]))] [(memv c LF1) (tokenize-string (cons #\linefeed ls) p)] [(eqv? c #\return) (let ([c (peek-char p)]) (when (memv c LF2) (read-char p)) (tokenize-string (cons #\linefeed ls) p))] [else (tokenize-string (cons c ls) p)])) (define skip-comment (lambda (p) (let ([c (read-char p)]) (unless (or (eof-object? c) (memv c LF1) (eqv? c #\return)) (skip-comment p))))) (define tokenize-dot (lambda (p) (let ([c (peek-char p)]) (cond [(eof-object? c) 'dot] [(delimiter? c) 'dot] [($char= c #\.) ; this is second dot (read-char p) (let ([c (peek-char p)]) (cond [(eof-object? c) (die/p p 'tokenize "invalid syntax .. near end of file")] [($char= c #\.) ; this is the third (read-char p) (let ([c (peek-char p)]) (cond [(eof-object? c) '(datum . ...)] [(delimiter? c) '(datum . ...)] [else (die/p p 'tokenize "invalid syntax" (string-append "..." (string c)))]))] [else (die/p p 'tokenize "invalid syntax" (string-append ".." (string c)))]))] [else (cons 'datum (u:dot p '(#\.) 10 #f #f +1))])))) (define tokenize-char* (lambda (i str p d) (cond [(fx= i (string-length str)) (let ([c (peek-char p)]) (cond [(eof-object? c) d] [(delimiter? c) d] [else (die/p p 'tokenize "invalid character after sequence" (string-append str (string c)))]))] [else (let ([c (read-char p)]) (cond [(eof-object? c) (die/p p 'tokenize "invalid eof in the middle of expected sequence" str)] [($char= c (string-ref str i)) (tokenize-char* (fxadd1 i) str p d)] [else (die/p-1 p 'tokenize "invalid char while scanning string" c str)]))]))) (define tokenize-char-seq (lambda (p str d) (let ([c (peek-char p)]) (cond [(eof-object? c) (cons 'datum (string-ref str 0))] [(delimiter? c) (cons 'datum (string-ref str 0))] [($char= (string-ref str 1) c) (read-char p) (tokenize-char* 2 str p d)] [else (die/p p 'tokenize "invalid syntax" (string-ref str 0) c)])))) (define tokenize-char (lambda (p) (let ([c (read-char p)]) (cond [(eof-object? c) (die/p p 'tokenize "invalid #\\ near end of file")] [(eqv? #\n c) (let ([c (peek-char p)]) (cond [(eof-object? c) (read-char p) '(datum . #\n)] [(eqv? #\u c) (read-char p) (tokenize-char-seq p "ul" '(datum . #\x0))] [(eqv? #\e c) (read-char p) (tokenize-char-seq p "ewline" '(datum . #\xA))] [(delimiter? c) '(datum . #\n)] [else (die/p p 'tokenize "invalid syntax" (string #\# #\\ #\n c))]))] [(eqv? #\a c) (tokenize-char-seq p "alarm" '(datum . #\x7))] [(eqv? #\b c) (tokenize-char-seq p "backspace" '(datum . #\x8))] [(eqv? #\t c) (tokenize-char-seq p "tab" '(datum . #\x9))] [(eqv? #\l c) (tokenize-char-seq p "linefeed" '(datum . #\xA))] [(eqv? #\v c) (tokenize-char-seq p "vtab" '(datum . #\xB))] [(eqv? #\p c) (tokenize-char-seq p "page" '(datum . #\xC))] [(eqv? #\r c) (tokenize-char-seq p "return" '(datum . #\xD))] [(eqv? #\e c) (tokenize-char-seq p "esc" '(datum . #\x1B))] [(eqv? #\s c) (tokenize-char-seq p "space" '(datum . #\x20))] [(eqv? #\d c) (tokenize-char-seq p "delete" '(datum . #\x7F))] [(eqv? #\x c) (let ([n (peek-char p)]) (cond [(or (eof-object? n) (delimiter? n)) '(datum . #\x)] [(hex n) => (lambda (v) (read-char p) (let f ([v v] [ac (cons n '(#\x))]) (let ([c (peek-char p)]) (cond [(eof-object? c) (cons 'datum (checked-integer->char v ac p))] [(delimiter? c) (cons 'datum (checked-integer->char v ac p))] [(hex c) => (lambda (v0) (read-char p) (f (+ (* v 16) v0) (cons c ac)))] [else (die/p p 'tokenize "invalid character sequence" (list->string (reverse (cons c ac))))]))))] [else (die/p p 'tokenize "invalid character sequence" (string-append "#\\" (string n)))]))] [else (let ([n (peek-char p)]) (cond [(eof-object? n) (cons 'datum c)] [(delimiter? n) (cons 'datum c)] [else (die/p p 'tokenize "invalid syntax" (string-append "#\\" (string c n)))]))])))) (define (hex x) (cond [(and ($char<= #\0 x) ($char<= x #\9)) ($fx- ($char->fixnum x) ($char->fixnum #\0))] [(and ($char<= #\a x) ($char<= x #\f)) ($fx- ($char->fixnum x) ($fx- ($char->fixnum #\a) 10))] [(and ($char<= #\A x) ($char<= x #\F)) ($fx- ($char->fixnum x) ($fx- ($char->fixnum #\A) 10))] [else #f])) (define multiline-error (lambda (p) (die/p p 'tokenize "end of file encountered while inside a #|-style comment"))) (define apprev (lambda (str i ac) (cond [(fx= i (string-length str)) ac] [else (apprev str (fx+ i 1) (cons (string-ref str i) ac))]))) (define multiline-comment (lambda (p) (define f (lambda (p ac) (let ([c (read-char p)]) (cond [(eof-object? c) (multiline-error p)] [($char= #\| c) (let g ([c (read-char p)] [ac ac]) (cond [(eof-object? c) (multiline-error p)] [($char= #\# c) ac] [($char= #\| c) (g (read-char p) (cons c ac))] [else (f p (cons c ac))]))] [($char= #\# c) (let ([c (read-char p)]) (cond [(eof-object? c) (multiline-error p)] [($char= #\| c) (let ([v (multiline-comment p)]) (if (string? v) (f p (apprev v 0 ac)) (f p ac)))] [else (f p (cons c (cons #\# ac)))]))] [else (f p (cons c ac))])))) (let ([ac (f p '())]) ((comment-handler) (list->string (reverse ac)))))) (define tokenize-hash (lambda (p) (tokenize-hash/c (read-char p) p))) (define (skip-whitespace p caller) (let ([c (read-char p)]) (cond [(eof-object? c) (die/p p 'tokenize "invalid eof inside" caller)] [(char-whitespace? c) (skip-whitespace p caller)] [else c]))) (define tokenize-hash/c (lambda (c p) (cond [(eof-object? c) (die/p p 'tokenize "invalid # near end of file")] [(memq c '(#\t #\T)) (let ([c1 (peek-char p)]) (cond [(eof-object? c1) '(datum . #t)] [(delimiter? c1) '(datum . #t)] [else (die/p p 'tokenize (format "invalid syntax near #~a~a" c c1))]))] [(memq c '(#\f #\F)) (let ([c1 (peek-char p)]) (cond [(eof-object? c1) '(datum . #f)] [(delimiter? c1) '(datum . #f)] [else (die/p p 'tokenize (format "invalid syntax near #~a~a" c c1))]))] [($char= #\\ c) (tokenize-char p)] [($char= #\( c) 'vparen] [($char= #\' c) '(macro . syntax)] [($char= #\` c) '(macro . quasisyntax)] [($char= #\, c) (let ([c (peek-char p)]) (cond [(eqv? c #\@) (read-char p) '(macro . unsyntax-splicing)] [else '(macro . unsyntax)]))] [($char= #\! c) (let ([e (read-char p)]) (when (eof-object? e) (die/p p 'tokenize "invalid eof near #!")) (case e [(#\e) (when (eq? (port-mode p) 'r6rs-mode) (die/p-1 p 'tokenize "invalid syntax: #!e")) (read-char* p '(#\e) "of" "eof sequence" #f #f) (cons 'datum (eof-object))] [(#\r) (read-char* p '(#\r) "6rs" "#!r6rs comment" #f #f) (set-port-mode! p 'r6rs-mode) (tokenize/1 p)] [(#\i) (read-char* p '(#\i) "karus" "#!ikarus comment" #f #f) (set-port-mode! p 'ikarus-mode) (tokenize/1 p)] [else (die/p-1 p 'tokenize (format "invalid syntax near #!~a" e))]))] [(digit? c) (when (eq? (port-mode p) 'r6rs-mode) (die/p-1 p 'tokenize "graph syntax is invalid in #!r6rs mode" (format "#~a" c))) (tokenize-hashnum p (char->num c))] [($char= #\: c) (when (eq? (port-mode p) 'r6rs-mode) (die/p-1 p 'tokenize "gensym syntax is invalid in #!r6rs mode" (format "#~a" c))) (let* ([c (skip-whitespace p "gensym")] [id0 (cond [(initial? c) (list->string (reverse (tokenize-identifier (cons c '()) p)))] [($char= #\| c) (list->string (reverse (tokenize-bar p '())))] [else (die/p-1 p 'tokenize "invalid char inside gensym" c)])]) (cons 'datum (gensym id0)))] [($char= #\{ c) (when (eq? (port-mode p) 'r6rs-mode) (die/p-1 p 'tokenize "gensym syntax is invalid in #!r6rs mode" (format "#~a" c))) (let* ([c (skip-whitespace p "gensym")] [id0 (cond [(initial? c) (list->string (reverse (tokenize-identifier (cons c '()) p)))] [($char= #\| c) (list->string (reverse (tokenize-bar p '())))] [else (die/p-1 p 'tokenize "invalid char inside gensym" c)])] [c (skip-whitespace p "gensym")]) (cond [($char= #\} c) (cons 'datum (foreign-call "ikrt_strings_to_gensym" #f id0))] [else (let ([id1 (cond [(initial? c) (list->string (reverse (tokenize-identifier (cons c '()) p)))] [($char= #\| c) (list->string (reverse (tokenize-bar p '())))] [else (die/p-1 p 'tokenize "invalid char inside gensym" c)])]) (let ([c (skip-whitespace p "gensym")]) (cond [($char= #\} c) (cons 'datum (foreign-call "ikrt_strings_to_gensym" id0 id1))] [else (die/p-1 p 'tokenize "invalid char inside gensym" c)])))]))] [($char= #\v c) (let ([c (read-char p)]) (cond [($char= #\u c) (let ([c (read-char p)]) (cond [($char= c #\8) (let ([c (read-char p)]) (cond [($char= c #\() 'vu8] [(eof-object? c) (die/p p 'tokenize "invalid eof object after #vu8")] [else (die/p-1 p 'tokenize (format "invalid sequence #vu8~a" c))]))] [(eof-object? c) (die/p p 'tokenize "invalid eof object after #vu")] [else (die/p-1 p 'tokenize (format "invalid sequence #vu~a" c))]))] [(eof-object? c) (die/p p 'tokenize "invalid eof object after #v")] [else (die/p p 'tokenize (format "invalid sequence #v~a" c))]))] [(memq c '(#\e #\E)) (cons 'datum (parse-string p (list c #\#) 10 #f 'e))] [(memq c '(#\i #\I)) (cons 'datum (parse-string p (list c #\#) 10 #f 'i))] [(memq c '(#\b #\B)) (cons 'datum (parse-string p (list c #\#) 2 2 #f))] [(memq c '(#\x #\X)) (cons 'datum (parse-string p (list c #\#) 16 16 #f))] [(memq c '(#\o #\O)) (cons 'datum (parse-string p (list c #\#) 8 8 #f))] [(memq c '(#\d #\D)) (cons 'datum (parse-string p (list c #\#) 10 10 #f))] ;[($char= #\@ c) DEAD: Unfixable due to port encoding ; that does not allow mixing binary and ; textual data in the same port. ; Left here for historical value ; (when (eq? (port-mode p) 'r6rs-mode) ; (die/p-1 p 'tokenize "fasl syntax is invalid in #!r6rs mode" ; (format "#~a" c))) ; (die/p-1 p 'read "FIXME: fasl read disabled") ; '(cons 'datum ($fasl-read p))] [else (die/p-1 p 'tokenize (format "invalid syntax #~a" c))]))) (define (num-error p str ls) (die/p-1 p 'read str (list->string (reverse ls)))) (define-syntax port-config (syntax-rules (GEN-TEST GEN-ARGS FAIL EOF-ERROR GEN-DELIM-TEST) [(_ GEN-ARGS k . rest) (k (p ac) . rest)] [(_ FAIL (p ac)) (num-error p "invalid numeric sequence" ac)] [(_ FAIL (p ac) c) (num-error p "invalid numeric sequence" (cons c ac))] [(_ EOF-ERROR (p ac)) (num-error p "invalid eof while reading number" ac)] [(_ GEN-DELIM-TEST c sk fk) (if (delimiter? c) sk fk)] [(_ GEN-TEST var next fail (p ac) eof-case char-case) (let ([c (peek-char p)]) (if (eof-object? c) (let () (define-syntax fail (syntax-rules () [(_) (num-error p "invalid numeric sequence" ac)])) eof-case) (let ([var c]) (define-syntax fail (syntax-rules () [(_) (num-error p "invalid numeric sequence" (cons var ac))])) (define-syntax next (syntax-rules () [(_ who args (... ...)) (who p (cons (get-char p) ac) args (... ...))])) char-case)))])) (define-string->number-parser port-config (parse-string u:digit+ u:sign u:dot)) (define (read-char* p ls str who ci? delimited?) (let f ([i 0] [ls ls]) (cond [(fx= i (string-length str)) (when delimited? (let ([c (peek-char p)]) (when (and (not (eof-object? c)) (not (delimiter? c))) (die/p p 'tokenize (format "invalid ~a: ~s" who (list->string (reverse (cons c ls))))))))] [else (let ([c (read-char p)]) (cond [(eof-object? c) (die/p p 'tokenize (format "invalid eof inside ~a" who))] [(or (and (not ci?) (char=? c (string-ref str i))) (and ci? (char=? (char-downcase c) (string-ref str i)))) (f (add1 i) (cons c ls))] [else (die/p-1 p 'tokenize (format "invalid ~a: ~s" who (list->string (reverse (cons c ls)))))]))]))) (define (tokenize-hashnum p n) (let ([c (read-char p)]) (cond [(eof-object? c) (die/p p 'tokenize "invalid eof inside #n mark/ref")] [($char= #\= c) (cons 'mark n)] [($char= #\# c) (cons 'ref n)] [(digit? c) (tokenize-hashnum p (fx+ (fx* n 10) (char->num c)))] [else (die/p-1 p 'tokenize "invalid char while inside a #n mark/ref" c)]))) (define tokenize-bar (lambda (p ac) (let ([c (read-char p)]) (cond [(eof-object? c) (die/p p 'tokenize "unexpected eof while reading symbol")] [($char= #\\ c) (let ([c (read-char p)]) (cond [(eof-object? c) (die/p p 'tokenize "unexpected eof while reading symbol")] [else (tokenize-bar p (cons c ac))]))] [($char= #\| c) ac] [else (tokenize-bar p (cons c ac))])))) (define (tokenize-backslash main-ac p) (let ([c (read-char p)]) (cond [(eof-object? c) (die/p p 'tokenize "invalid eof after symbol escape")] [($char= #\x c) (let ([c (read-char p)]) (cond [(eof-object? c) (die/p p 'tokenize "invalid eof after \\x")] [(hex c) => (lambda (v) (let f ([v v] [ac `(,c #\x #\\)]) (let ([c (read-char p)]) (cond [(eof-object? c) (die/p p 'tokenize (format "invalid eof after ~a" (list->string (reverse ac))))] [($char= #\; c) (tokenize-identifier (cons (checked-integer->char v ac p) main-ac) p)] [(hex c) => (lambda (v0) (f (+ (* v 16) v0) (cons c ac)))] [else (die/p-1 p 'tokenize "invalid sequence" (list->string (cons c (reverse ac))))]))))] [else (die/p-1 p 'tokenize (format "invalid sequence \\x~a" c))]))] [else (die/p-1 p 'tokenize (format "invalid sequence \\~a" c))]))) (define tokenize/c (lambda (c p) (cond [(eof-object? c) (error 'tokenize/c "hmmmm eof") (eof-object)] [($char= #\( c) 'lparen] [($char= #\) c) 'rparen] [($char= #\[ c) 'lbrack] [($char= #\] c) 'rbrack] [($char= #\' c) '(macro . quote)] [($char= #\` c) '(macro . quasiquote)] [($char= #\, c) (let ([c (peek-char p)]) (cond [(eof-object? c) '(macro . unquote)] [($char= c #\@) (read-char p) '(macro . unquote-splicing)] [else '(macro . unquote)]))] [($char= #\# c) (tokenize-hash p)] [(char<=? #\0 c #\9) (let ([d (fx- (char->integer c) (char->integer #\0))]) (cons 'datum (u:digit+ p (list c) 10 #f #f +1 d)))] [(initial? c) (let ([ls (reverse (tokenize-identifier (cons c '()) p))]) (cons 'datum (string->symbol (list->string ls))))] [($char= #\" c) (let ([ls (tokenize-string '() p)]) (cons 'datum (list->string (reverse ls))))] [(memq c '(#\+)) (let ([c (peek-char p)]) (cond [(eof-object? c) '(datum . +)] [(delimiter? c) '(datum . +)] [else (cons 'datum (u:sign p '(#\+) 10 #f #f +1))]))] [(memq c '(#\-)) (let ([c (peek-char p)]) (cond [(eof-object? c) '(datum . -)] [(delimiter? c) '(datum . -)] [($char= c #\>) (read-char p) (let ([ls (tokenize-identifier '() p)]) (let ([str (list->string (cons* #\- #\> (reverse ls)))]) (cons 'datum (string->symbol str))))] [else (cons 'datum (u:sign p '(#\-) 10 #f #f -1))]))] [($char= #\. c) (tokenize-dot p)] [($char= #\| c) (when (eq? (port-mode p) 'r6rs-mode) (die/p p 'tokenize "|symbol| syntax is invalid in #!r6rs mode")) (let ([ls (reverse (tokenize-bar p '()))]) (cons 'datum (string->symbol (list->string ls))))] [($char= #\\ c) (cons 'datum (string->symbol (list->string (reverse (tokenize-backslash '() p)))))] ;[($char= #\{ c) 'lbrace] [($char= #\@ c) (when (eq? (port-mode p) 'r6rs-mode) (die/p p 'tokenize "@-expr syntax is invalid in #!r6rs mode")) 'at-expr] [else (die/p-1 p 'tokenize "invalid syntax" c)]))) (define tokenize/1 (lambda (p) (let ([c (read-char p)]) (cond [(eof-object? c) (eof-object)] [(eqv? c #\;) (skip-comment p) (tokenize/1 p)] [(eqv? c #\#) (let ([c (read-char p)]) (cond [(eof-object? c) (die/p p 'tokenize "invalid eof after #")] [(eqv? c #\;) (read-as-comment p) (tokenize/1 p)] [(eqv? c #\|) (multiline-comment p) (tokenize/1 p)] [else (tokenize-hash/c c p)]))] [(char-whitespace? c) (tokenize/1 p)] [else (tokenize/c c p)])))) (define tokenize/1+pos (lambda (p) (let ([pos (input-port-byte-position p)]) (let ([c (read-char p)]) (cond [(eof-object? c) (values (eof-object) pos)] [(eqv? c #\;) (skip-comment p) (tokenize/1+pos p)] [(eqv? c #\#) (let ([pos (input-port-byte-position p)]) (let ([c (read-char p)]) (cond [(eof-object? c) (die/p p 'tokenize "invalid eof after #")] [(eqv? c #\;) (read-as-comment p) (tokenize/1+pos p)] [(eqv? c #\|) (multiline-comment p) (tokenize/1+pos p)] [else (values (tokenize-hash/c c p) pos)])))] [(char-whitespace? c) (tokenize/1+pos p)] [else (values (tokenize/c c p) pos)]))))) (define tokenize-script-initial (lambda (p) (let ([c (read-char p)]) (cond [(eof-object? c) c] [(eqv? c #\;) (skip-comment p) (tokenize/1 p)] [(eqv? c #\#) (let ([c (read-char p)]) (cond [(eof-object? c) (die/p p 'tokenize "invalid eof after #")] [(eqv? c #\!) (skip-comment p) (tokenize/1 p)] [(eqv? c #\;) (read-as-comment p) (tokenize/1 p)] [(eqv? c #\|) (multiline-comment p) (tokenize/1 p)] [else (tokenize-hash/c c p)]))] [(char-whitespace? c) (tokenize/1 p)] [else (tokenize/c c p)])))) (define tokenize-script-initial+pos (lambda (p) (let ([pos (input-port-byte-position p)]) (let ([c (read-char p)]) (cond [(eof-object? c) (values (eof-object) pos)] [(eqv? c #\;) (skip-comment p) (tokenize/1+pos p)] [(eqv? c #\#) (let ([pos (input-port-byte-position p)]) (let ([c (read-char p)]) (cond [(eof-object? c) (die/p p 'tokenize "invalid eof after #")] [(eqv? c #\!) (skip-comment p) (tokenize/1+pos p)] [(eqv? c #\;) (read-as-comment p) (tokenize/1+pos p)] [(eqv? c #\|) (multiline-comment p) (tokenize/1+pos p)] [else (values (tokenize-hash/c c p) pos)])))] [(char-whitespace? c) (tokenize/1+pos p)] [else (values (tokenize/c c p) pos)]))))) (define-struct loc (value value^ set?)) ;;; this is reverse engineered from psyntax.ss (define-struct annotation (expression source stripped)) ;;; - source is a pair of file-name x char-position ;;; - stripped is an s-expression with no annotations ;;; - expression is a list/vector/id/whathaveyou that ;;; may contain further annotations. (module (read-expr read-expr-script-initial) (define-syntax tokenize/1 syntax-error) (define (annotate-simple datum pos p) (make-annotation datum (cons (port-id p) pos) datum)) (define (annotate stripped expression pos p) (make-annotation expression (cons (port-id p) pos) stripped)) (define read-list (lambda (p locs k end mis init?) (let-values ([(t pos) (tokenize/1+pos p)]) (cond [(eof-object? t) (die/p p 'read "end of file encountered while reading list")] [(eq? t end) (values '() '() locs k)] [(eq? t mis) (die/p-1 p 'read "paren mismatch")] [(eq? t 'dot) (when init? (die/p-1 p 'read "invalid dot while reading list")) (let-values ([(d d^ locs k) (read-expr p locs k)]) (let-values ([(t pos^) (tokenize/1+pos p)]) (cond [(eq? t end) (values d d^ locs k)] [(eq? t mis) (die/p-1 p 'read "paren mismatch")] [(eq? t 'dot) (die/p-1 p 'read "cannot have two dots in a list")] [else (die/p-1 p 'read (format "expecting ~a, got ~a" end t))])))] [else (let-values ([(a a^ locs k) (parse-token p locs k t pos)]) (let-values ([(d d^ locs k) (read-list p locs k end mis #f)]) (let ([x (cons a d)] [x^ (cons a^ d^)]) (values x x^ locs (extend-k-pair x x^ a d k)))))])))) (define extend-k-pair (lambda (x x^ a d k) (cond [(or (loc? a) (loc? d)) (lambda () (let ([a (car x)]) (when (loc? a) (set-car! x (loc-value a)) (set-car! x^ (loc-value^ a)))) (let ([d (cdr x)]) (when (loc? d) (set-cdr! x (loc-value d)) (set-cdr! x^ (loc-value^ d)))) (k))] [else k]))) (define vector-put (lambda (v v^ k i ls ls^) (cond [(null? ls) k] [else (let ([a (car ls)]) (vector-set! v i a) (vector-set! v^ i (car ls^)) (vector-put v v^ (if (loc? a) (lambda () (vector-set! v i (loc-value a)) (vector-set! v^ i (loc-value^ a)) (k)) k) (fxsub1 i) (cdr ls) (cdr ls^)))]))) (define read-vector (lambda (p locs k count ls ls^) (let-values ([(t pos) (tokenize/1+pos p)]) (cond [(eof-object? t) (die/p p 'read "end of file encountered while reading a vector")] [(eq? t 'rparen) (let ([v (make-vector count)] [v^ (make-vector count)]) (let ([k (vector-put v v^ k (fxsub1 count) ls ls^)]) (values v v^ locs k)))] [(eq? t 'rbrack) (die/p-1 p 'read "unexpected ] while reading a vector")] [(eq? t 'dot) (die/p-1 p 'read "unexpected . while reading a vector")] [else (let-values ([(a a^ locs k) (parse-token p locs k t pos)]) (read-vector p locs k (fxadd1 count) (cons a ls) (cons a^ ls^)))])))) (define read-bytevector (lambda (p locs k count ls) (let-values ([(t pos) (tokenize/1+pos p)]) (cond [(eof-object? t) (die/p p 'read "end of file encountered while reading a bytevector")] [(eq? t 'rparen) (let ([v (u8-list->bytevector (reverse ls))]) (values v v locs k))] [(eq? t 'rbrack) (die/p-1 p 'read "unexpected ] while reading a bytevector")] [(eq? t 'dot) (die/p-1 p 'read "unexpected . while reading a bytevector")] [else (let-values ([(a a^ locs k) (parse-token p locs k t pos)]) (unless (and (fixnum? a) (fx<= 0 a) (fx<= a 255)) (die/ann a^ 'read "invalid value in a bytevector" a)) (read-bytevector p locs k (fxadd1 count) (cons a ls)))])))) (define read-at-expr (lambda (p locs k at-pos) (define-struct nested (a a^)) (define-struct nested* (a* a*^)) (define (get-chars chars pos p a* a*^) (if (null? chars) (values a* a*^) (let ([str (list->string chars)]) (let ([str^ (annotate-simple str pos p)]) (values (cons str a*) (cons str^ a*^)))))) (define (return start-pos start-col c*** p) (let ([indent (apply min start-col (map (lambda (c**) (define (st00 c* c** n) (if (null? c*) (st0 c** n) (if (char=? (car c*) #\space) (st00 (cdr c*) c** (+ n 1)) n))) (define (st0 c** n) (if (null? c**) start-col (let ([c* (car c**)]) (if (or (nested? c*) (nested*? c*)) start-col (st00 (car c*) (cdr c**) n))))) (st0 c** 0)) (cdr c***)))]) (define (convert c*) (if (or (nested? c*) (nested*? c*)) c* (let ([str (list->string (car c*))]) (let ([str^ (annotate-simple str (cdr c*) p)]) (make-nested str str^))))) (define (trim/convert c**) (define (mk n pos) (let ([str (make-string (- n indent) #\space)]) (let ([str^ (annotate-simple str pos p)]) (make-nested str str^)))) (define (s1 c* pos c** n) (if (null? c*) (let ([c* (car c**)]) (if (or (nested? c*) (nested*? c*)) (cons (mk n pos) (map convert c**)) (s1 c* pos (cdr c**) n))) (if (char=? (car c*) #\space) (s1 (cdr c*) pos c** (+ n 1)) (cons* (mk n pos) (map convert (cons (cons c* pos) c**)))))) (define (s00 c* pos c** n) (if (null? c*) (s0 c** n) (if (char=? #\space (car c*)) (if (< n indent) (s00 (cdr c*) pos c** (+ n 1)) (s1 (cdr c*) pos c** (+ n 1))) (map convert (cons (cons c* pos) c**))))) (define (s0 c** n) (if (null? c**) '() (let ([c* (car c**)]) (if (or (nested? c*) (nested*? c*)) (map convert c**) (s00 (car c*) (cdr c*) (cdr c**) n))))) (s0 c** 0)) (define (cons-initial c** c***) (define (all-white? c**) (andmap (lambda (c*) (and (not (nested? c*)) (not (nested*? c*)) (andmap (lambda (c) (char=? c #\space)) (car c*)))) c**)) (define (nl) (let ([str "\n"]) (list (make-nested str str)))) (define (S1 c*** n) (if (null? c***) (make-list n (nl)) (let ([c** (car c***)] [c*** (cdr c***)]) (if (all-white? c**) (S1 c*** (+ n 1)) (append (make-list n (nl)) (cons (trim/convert c**) (S2 c*** 0 0))))))) (define (S2 c*** n m) (if (null? c***) (make-list (+ n m) (nl)) (let ([c** (car c***)] [c*** (cdr c***)]) (if (all-white? c**) (S2 c*** (+ n 1) -1) (append (make-list (+ n 1) (nl)) (cons (trim/convert c**) (S2 c*** 0 0))))))) (define (S0 c** c***) (if (all-white? c**) (S1 c*** 0) (cons (map convert c**) (S2 c*** 0 0)))) (S0 c** c***)) (let ([c** (cons-initial (car c***) (cdr c***))]) (let ([n* (apply append c**)]) (define (extract p p* ls) (let f ([ls ls]) (cond [(null? ls) '()] [(nested? (car ls)) (cons (p (car ls)) (f (cdr ls)))] [else (append (p* (car ls)) (f (cdr ls)))]))) (let ([c* (extract nested-a nested*-a* n*)] [c*^ (extract nested-a^ nested*-a*^ n*)]) (values c* (annotate c* c*^ start-pos p) locs k)))))) (define (read-text p locs k pref*) (let ([start-pos (port-position p)] [start-col (input-port-column-number p)]) (let f ([c* '()] [pos start-pos] [c** '()] [c*** '()] [depth 0] [locs locs] [k k]) (define (match-prefix c* pref*) (cond [(and (pair? c*) (pair? pref*)) (and (char=? (car c*) (car pref*)) (match-prefix (cdr c*) (cdr pref*)))] [else (and (null? pref*) c*)])) (let ([c (read-char p)]) (cond [(eof-object? c) (die/p p 'read "end of file while reading @-expr text")] [(char=? c #\}) (let g ([x* (cons #\} c*)] [p* pref*]) (if (null? p*) (if (= depth 0) (let ([c** (reverse (if (null? c*) c** (cons (cons (reverse c*) pos) c**)))]) (let ([c*** (reverse (cons c** c***))]) (return start-pos start-col c*** p))) (f x* pos c** c*** (- depth 1) locs k)) (let ([c (peek-char p)]) (cond [(eof-object? c) (die/p p 'read "invalid eof inside @-expression")] [(char=? c (rev-punc (car p*))) (read-char p) (g (cons c x*) (cdr p*))] [else (f x* pos c** c*** depth locs k)]))))] [(char=? c #\{) (f (cons c c*) pos c** c*** (if (match-prefix c* pref*) (+ depth 1) depth) locs k)] [(char=? c #\newline) (f '() (port-position p) '() (cons (reverse (if (null? c*) c** (cons (cons (reverse c*) pos) c**))) c***) depth locs k)] [(and (char=? c #\@) (match-prefix c* pref*)) => (lambda (c*) (let ([c (peek-char p)]) (cond [(eof-object? c) (die/p p 'read "invalid eof inside nested @-expr")] [(char=? c #\") (read-char p) (let ([c* (tokenize-string c* p)]) (f c* pos c** c*** depth locs k))] [else (let-values ([(a* a*^ locs k) (read-at-text-mode p locs k)]) (f '() (port-position p) (cons (make-nested* a* a*^) (if (null? c*) c** (cons (cons (reverse c*) pos) c**))) c*** depth locs k))])))] [else (f (cons c c*) pos c** c*** depth locs k)]))))) (define (read-brackets p locs k) (let-values ([(a* a*^ locs k) (read-list p locs k 'rbrack 'rparen #t)]) (unless (list? a*) (die/ann a*^ 'read "not a proper list")) (let ([c (peek-char p)]) (cond [(eof-object? c) ;;; @<cmd>[...] (values a* a*^ locs k)] [(char=? c #\{) (read-char p) (let-values ([(b* b*^ locs k) (read-text p locs k '())]) (values (append a* b*) (append a*^ b*^) locs k))] [(char=? c #\|) (read-char p) (let-values ([(b* b*^ locs k) (read-at-bar p locs k #t)]) (values (append a* b*) (append a*^ b*^) locs k))] [else (values a* a*^ locs k)])))) (define (left-punc? c) (define chars "([<!?~$%^&*-_+=:") (let f ([i 0]) (cond [(= i (string-length chars)) #f] [(char=? c (string-ref chars i)) #t] [else (f (+ i 1))]))) (define (rev-punc c) (cond [(char=? c #\() #\)] [(char=? c #\[) #\]] [(char=? c #\<) #\>] [else c])) (define (read-at-bar p locs k text-mode?) (let ([c (peek-char p)]) (cond [(eof-object? c) (die/p p 'read "eof inside @|-expression")] [(and (char=? c #\|) text-mode?) ;;; @|| (read-char p) (values '() '() locs k)] [(char=? c #\{) ;;; @|{ (read-char p) (read-text p locs k '(#\|))] [(left-punc? c) ;;; @|<({ (read-char p) (let ([pos (port-position p)]) (let f ([ls (list c)]) (let ([c (peek-char p)]) (cond [(eof-object? c) (die/p p 'read "eof inside @|< mode")] [(left-punc? c) (read-char p) (f (cons c ls))] [(char=? c #\{) (read-char p) (read-text p locs k (append ls '(#\|)))] [else (read-at-bar-others ls p locs k)]))))] [text-mode? ;;; @|5 6 7| (read-at-bar-datum p locs k)] [else (die/p p 'read "invalid char in @| mode" c)]))) (define (read-at-bar-others ls p locs k) (define (split ls) (cond [(null? ls) (values '() '())] [(initial? (car ls)) (let-values ([(a d) (split (cdr ls))]) (values (cons (car ls) a) d))] [else (values '() ls)])) (define (mksymbol ls) (let ([s (string->symbol (list->string (reverse ls)))]) (values s s))) (let-values ([(inits rest) (split ls)]) (let ([ls (tokenize-identifier inits p)]) (let-values ([(s s^) (mksymbol ls)]) (let g ([rest rest] [a* (list s)] [a*^ (list s^)] [locs locs] [k k]) (if (null? rest) (let-values ([(b* b*^ locs k) (read-at-bar-datum p locs k)]) (values (append a* b*) (append a*^ b*^) locs k)) (let ([x (car rest)]) (case x [(#\() #\) ;;; vim paren-matching sucks (let-values ([(b* b*^ locs k) (read-list p locs k 'rparen 'rbrack #t)]) (g (cdr rest) (list (append a* b*)) (list (append a*^ b*^)) locs k))] [(#\[) #\] ;;; vim paren-matching sucks (let-values ([(b* b*^ locs k) (read-list p locs k 'rbrack 'rparen #t)]) (g (cdr rest) (list (append a* b*)) (list (append a*^ b*^)) locs k))] [else (let-values ([(inits rest) (split rest)]) (let-values ([(s s^) (mksymbol inits)]) (g rest (cons s a*) (cons s^ a*^) locs k)))])))))))) (define (read-at-bar-datum p locs k) (let ([c (peek-char p)]) (cond [(eof-object? c) (die/p p 'read "eof inside @|datum mode")] [(char-whitespace? c) (read-char p) (read-at-bar-datum p locs k)] [(char=? c #\|) (read-char p) (values '() '() locs k)] [else (let-values ([(a a^ locs k) (read-expr p locs k)]) (let-values ([(a* a*^ locs k) (read-at-bar-datum p locs k)]) (values (cons a a*) (cons a^ a*^) locs k)))]))) (define (read-at-text-mode p locs k) (let ([c (peek-char p)]) (cond [(eof-object? c) (die/p p 'read "eof encountered inside @-expression")] [(char=? c #\|) (read-char p) (read-at-bar p locs k #t)] [else (let-values ([(a a^ locs k) (read-at-sexpr-mode p locs k)]) (values (list a) (list a^) locs k))]))) (define (read-at-sexpr-mode p locs k) (let ([c (peek-char p)]) (cond [(eof-object? c) (die/p p 'read "eof encountered inside @-expression")] [(eqv? c '#\[) ;;; @[ ... (read-char p) (read-brackets p locs k)] [(eqv? c #\{) ;;; @{ ... (read-char p) (read-text p locs k '())] [(char=? c #\|) (read-char p) (read-at-bar p locs k #f)] [else ;;; @<cmd> ... (let-values ([(a a^ locs k) (read-expr p locs k)]) (let ([c (peek-char p)]) (cond [(eof-object? c) ;;; @<cmd><eof> (values a a^ locs k)] [(eqv? c #\[) (read-char p) (let-values ([(a* a*^ locs k) (read-brackets p locs k)]) (let ([v (cons a a*)] [v^ (cons a^ a*^)]) (values v (annotate v v^ at-pos p) locs k)))] [(eqv? c #\{) ;;; @<cmd>{ ... (read-char p) (let-values ([(a* a*^ locs k) (read-text p locs k '())]) (let ([v (cons a a*)] [v^ (cons a^ a*^)]) (values v (annotate v v^ at-pos p) locs k)))] [(eqv? c #\|) ;;; @<cmd>| ... (read-char p) (let-values ([(a* a*^ locs k) (read-at-bar p locs k #f)]) (let ([v (cons a a*)] [v^ (cons a^ a*^)]) (values v (annotate v v^ at-pos p) locs k)))] [else (values a a^ locs k)])))]))) (read-at-sexpr-mode p locs k))) (define parse-token (lambda (p locs k t pos) (cond [(eof-object? t) (values (eof-object) (annotate-simple (eof-object) pos p) locs k)] [(eq? t 'lparen) (let-values ([(ls ls^ locs k) (read-list p locs k 'rparen 'rbrack #t)]) (values ls (annotate ls ls^ pos p) locs k))] [(eq? t 'lbrack) (let-values ([(ls ls^ locs k) (read-list p locs k 'rbrack 'rparen #t)]) (values ls (annotate ls ls^ pos p) locs k))] [(eq? t 'vparen) (let-values ([(v v^ locs k) (read-vector p locs k 0 '() '())]) (values v (annotate v v^ pos p) locs k))] [(eq? t 'vu8) (let-values ([(v v^ locs k) (read-bytevector p locs k 0 '())]) (values v (annotate v v^ pos p) locs k))] [(eq? t 'at-expr) (read-at-expr p locs k pos)] [(pair? t) (cond [(eq? (car t) 'datum) (values (cdr t) (annotate-simple (cdr t) pos p) locs k)] [(eq? (car t) 'macro) (let ([macro (cdr t)]) (define (read-macro) (let-values ([(t pos) (tokenize/1+pos p)]) (cond [(eof-object? t) (die/p p 'read (format "invalid eof after ~a read macro" macro))] [else (parse-token p locs k t pos)]))) (let-values ([(expr expr^ locs k) (read-macro)]) (let ([d (list expr)] [d^ (list expr^)]) (let ([x (cons macro d)] [x^ (cons (annotate-simple macro pos p) d^)]) (values x (annotate x x^ pos p) locs (extend-k-pair d d^ expr '() k))))))] [(eq? (car t) 'mark) (let ([n (cdr t)]) (let-values ([(expr expr^ locs k) (read-expr p locs k)]) (cond [(assq n locs) => (lambda (x) (let ([loc (cdr x)]) (when (loc-set? loc) ;;; FIXME: pos (die/p p 'read "duplicate mark" n)) (set-loc-value! loc expr) (set-loc-value^! loc expr^) (set-loc-set?! loc #t) (values expr expr^ locs k)))] [else (let ([loc (make-loc expr 'unused #t)]) (let ([locs (cons (cons n loc) locs)]) (values expr expr^ locs k)))])))] [(eq? (car t) 'ref) (let ([n (cdr t)]) (cond [(assq n locs) => (lambda (x) (values (cdr x) 'unused locs k))] [else (let ([loc (make-loc #f 'unused #f)]) (let ([locs (cons (cons n loc) locs)]) (values loc 'unused locs k)))]))] [else (die/p p 'read "invalid token" t)])] [else (die/p-1 p 'read (format "unexpected ~s found" t))]))) (define read-expr (lambda (p locs k) (let-values ([(t pos) (tokenize/1+pos p)]) (parse-token p locs k t pos)))) (define read-expr-script-initial (lambda (p locs k) (let-values ([(t pos) (tokenize-script-initial+pos p)]) (parse-token p locs k t pos))))) (define (reduce-loc! p) (lambda (x) (let ([loc (cdr x)]) (unless (loc-set? loc) (die/p p 'read "referenced mark is not set" (car x))) (when (loc? (loc-value loc)) (let f ([h loc] [t loc]) (if (loc? h) (let ([h1 (loc-value h)]) (if (loc? h1) (begin (when (eq? h1 t) (die/p p 'read "circular marks")) (let ([v (f (loc-value h1) (loc-value t))]) (set-loc-value! h1 v) (set-loc-value! h v) v)) (begin (set-loc-value! h h1) h1))) h)))))) (define (read-as-comment p) (begin (read-expr p '() void) (void))) (define (return-annotated x) (cond [(and (annotation? x) (eof-object? (annotation-expression x))) (eof-object)] [else x])) (define my-read (lambda (p) (let-values ([(expr expr^ locs k) (read-expr p '() void)]) (cond [(null? locs) expr] [else (for-each (reduce-loc! p) locs) (k) (if (loc? expr) (loc-value expr) expr)])))) (define read-initial (lambda (p) (let-values ([(expr expr^ locs k) (read-expr-script-initial p '() void)]) (cond [(null? locs) expr] [else (for-each (reduce-loc! p) locs) (k) (if (loc? expr) (loc-value expr) expr)])))) (define read-annotated (case-lambda [(p) (unless (input-port? p) (error 'read-annotated "not an input port" p)) (let-values ([(expr expr^ locs k) (read-expr p '() void)]) (cond [(null? locs) (return-annotated expr^)] [else (for-each (reduce-loc! p) locs) (k) (if (loc? expr) (loc-value^ expr) (return-annotated expr^))]))] [() (read-annotated (current-input-port))])) (define read-script-annotated (lambda (p) (let-values ([(expr expr^ locs k) (read-expr-script-initial p '() void)]) (cond [(null? locs) (return-annotated expr^)] [else (for-each (reduce-loc! p) locs) (k) (if (loc? expr) (loc-value^ expr) (return-annotated expr^))])))) (define read-token (case-lambda [() (tokenize/1 (current-input-port))] [(p) (if (input-port? p) (tokenize/1 p) (die 'read-token "not an input port" p))])) (define read (case-lambda [() (my-read (current-input-port))] [(p) (if (input-port? p) (my-read p) (die 'read "not an input port" p))])) (define (get-datum p) (unless (input-port? p) (die 'get-datum "not an input port")) (my-read p)) (define comment-handler ;;; this is stale, maybe delete (make-parameter (lambda (x) (void)) (lambda (x) (unless (procedure? x) (die 'comment-handler "not a procedure" x)) x))) )
true
d436a7a6f2206985eb2daeec6aa9d859ea468e26
dd4cc30a2e4368c0d350ced7218295819e102fba
/vendored_parsers/highlights/html.scm
0ea534ed5555f9806e3b2a6e7204d3e6ef8a58b0
[ "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
42
scm
html.scm
../tree-sitter-html/queries/highlights.scm
false