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
dc7c9a33a810fb62c88e59c0b74b54b7f9222da2
a8216d80b80e4cb429086f0f9ac62f91e09498d3
/lib/srfi/146/hash.sld
2f7fb9c9c86d67845ea71c819b3fd37ead343840
[ "BSD-3-Clause" ]
permissive
ashinn/chibi-scheme
3e03ee86c0af611f081a38edb12902e4245fb102
67fdb283b667c8f340a5dc7259eaf44825bc90bc
refs/heads/master
2023-08-24T11:16:42.175821
2023-06-20T13:19:19
2023-06-20T13:19:19
32,322,244
1,290
223
NOASSERTION
2023-08-29T11:54:14
2015-03-16T12:05:57
Scheme
UTF-8
Scheme
false
false
1,362
sld
hash.sld
(define-library (srfi 146 hash) (export hashmap hashmap-unfold hashmap? hashmap-contains? hashmap-empty? hashmap-disjoint? hashmap-ref hashmap-ref/default hashmap-key-comparator hashmap-adjoin hashmap-adjoin! hashmap-set hashmap-set! hashmap-replace hashmap-replace! hashmap-delete hashmap-delete! hashmap-delete-all hashmap-delete-all! hashmap-intern hashmap-intern! hashmap-update hashmap-update! hashmap-update/default hashmap-update!/default hashmap-pop hashmap-pop! hashmap-search hashmap-search! hashmap-size hashmap-find hashmap-count hashmap-any? hashmap-every? hashmap-keys hashmap-values hashmap-entries hashmap-map hashmap-map->list hashmap-for-each hashmap-fold hashmap-filter hashmap-filter! hashmap-remove hashmap-remove! hashmap-partition hashmap-partition! hashmap-copy hashmap->alist alist->hashmap alist->hashmap! hashmap=? hashmap<? hashmap>? hashmap<=? hashmap>=? hashmap-union hashmap-intersection hashmap-difference hashmap-xor hashmap-union! hashmap-intersection! hashmap-difference! hashmap-xor! make-hashmap-comparator hashmap-comparator comparator?) (import (scheme base) (scheme case-lambda) (srfi 1) (srfi 8) (srfi 121) (srfi 128) (srfi 145) (srfi 146 hamt-map)) (include "hash.scm"))
false
e32547cc3d11403f2e2bafac66535ec2e22d91fc
8ae29235445f56b8a96f3fa89fda4a1da4ff4b85
/tests.scm
ec4e8110d4d594643931d07f986cf1c4f5ce0652
[]
no_license
ThomasHintz/mongodb-chicken-scheme
837a69db71648c23609a6880c88599ae33992338
022c227dc3e315e9b054dea7be7dffad02fb11e4
refs/heads/master
2016-09-06T13:26:22.950999
2012-12-10T14:03:25
2012-12-10T14:03:25
6,641,888
1
0
null
null
null
null
UTF-8
Scheme
false
false
1,960
scm
tests.scm
(use test) (load "mongo-client.scm") (define (contains-oid json-result) (if (alist-ref 'oids json-result) #t #f)) (define test-resource "test") (test-begin "all") (test-group "connect" (test '((ok . 1) (server . "http://localhost:27017") (name . "default")) (mdb-connect server: "http://localhost:27017"))) (test-group "hello" (test '((ok . 1) (msg . "Uh, we had a slight weapons malfunction, but uh... everything's perfectly all right now. We're fine. We're all fine here now, thank you. How are you?")) (mdb-hello))) (test-group "insert" (mdb-connect server: "http://localhost:27017") (database "testdatabase") (test #t (contains-oid (mdb-insert test-resource '((name . "stuff")))))) (test-group "remove" (mdb-connect server: "http://localhost:27017") (database "testdatabase") (mdb-insert test-resource '((eat . "good"))) (test '((ok . 1)) (mdb-remove test-resource '()))) (test-group "find/query" (mdb-connect server: "http://localhost:27017") (database "testdatabase") (test-group "find empty" (mdb-remove test-resource '()) (let ((res (mdb-find test-resource))) (test 1 (alist-ref 'ok res)) (test '#() (alist-ref 'results res)))) (test-group "find one" (mdb-remove test-resource '()) (mdb-insert test-resource '((name . "joe"))) (let* ((res (mdb-find test-resource)) (items (alist-ref 'results res))) (test 1 (alist-ref 'ok res)) (test 1 (vector-length items)) (test "joe" (alist-ref 'name (vector-ref items 0))))) (test-group "find by criteria" (mdb-remove test-resource '()) (let ((oid (cdadar (mdb-insert test-resource '((name . "joe")))))) (mdb-insert test-resource '((name . "abel"))) (let* ((res (mdb-find test-resource criteria: '((name . "joe")))) (items (alist-ref 'results res))) (test 1 (alist-ref 'ok res)) (test 1 (vector-length items)) (test oid (alist-ref 'oid (vector-ref items 0))))))) (test-end "all")
false
75946ad164b1fac3f1fba964894a6526757914e1
b9eb119317d72a6742dce6db5be8c1f78c7275ad
/racket/flatten.rkt
04bb11a92c21101320581f7ac80c0e0d62b33c91
[]
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
1,288
rkt
flatten.rkt
#! /bin/sh #| Hey Emacs, this is -*-scheme-*- code! exec racket -l errortrace --require "$0" --main -- ${1+"$@"} |# #lang racket (require rackunit rackunit/text-ui) (provide (rename-out [my-flatten flatten])) (define (flatten-backwards thing) (let loop ([accumulator '()] [thing thing]) (cond ((null? thing) accumulator) ((empty? (car thing)) (loop accumulator (cdr thing))) ((pair? (car thing)) (loop (append (flatten-backwards (car thing)) accumulator) (cdr thing))) (else (loop (cons (car thing) accumulator) (cdr thing)))))) (define (my-flatten thing) (reverse (flatten-backwards thing))) (define (test-data [how-many 10]) (for/list ([i (in-range how-many)]) (let ([r (random)]) (cond ((< r .1) '()) ((< r .2) (test-data (/ how-many 2))) (else #\f))))) (define-test-suite flatten-tests (check-equal? (my-flatten '( #\s (#\r #\a #\b) #\space #\o #\o #\f)) '( #\s #\r #\a #\b #\space #\o #\o #\f)) (for ([trial (in-range 100)]) (let ([td (test-data 10)]) (check-equal? (my-flatten td) (flatten td))))) (define-test-suite all-tests flatten-tests) (provide main) (define (main . args) (exit (run-tests all-tests 'verbose)))
false
048e48aa5b0eb65946253fe78f6606d116b6a8a3
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
/test/tests/text/yaml/scanner.scm
60dbd55c6c267a482b81139d9991e1bd46896368
[ "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
9,212
scm
scanner.scm
(import (rnrs) (text yaml scanner) (text yaml tokens) (srfi :127) (srfi :64)) (define (find-index name vec) (do ((i 0 (+ i 1))) ((eq? name (vector-ref vec i)) i))) (define-syntax test-record (syntax-rules () ((_ "collect" msg rt o ((n v acc) ...) ()) (let* ((rtd (record-type-descriptor rt)) (fields (record-type-field-names rtd))) (define pred (record-predicate rtd)) (define acc (record-accessor rtd (find-index 'n fields))) ... ;; (begin (write (list 'n v (acc o))) (newline)) ... ;; (begin (display 'rt) (write o) (newline)) (test-assert '(msg predicate) (pred o)) (test-equal '(msg n v) v (acc o)) ...)) ((_ "collect" msg rt o ((n v acc) ...) ((slot val) rest ...)) (test-record "collect" msg rt o ((n v acc) ... (slot val tmp)) (rest ...))) ((_ record-type ((slot val) ...) value) (test-record record-type record-type ((slot val) ...) value)) ((_ message record-type ((slot val) ...) value) (test-record "collect" message record-type value () ((slot val) ...))))) (test-begin "YAML scanner") (define (string->scanner s) (port->yaml-scanner-lseq (open-string-input-port s))) (define-syntax test-scanner (syntax-rules () ((_ "emit" scanner) (begin)) ((_ "emit" scanner (rt (slot val) ...) e* ...) (begin (test-record rt ((slot val) ...) (lseq-car scanner)) (test-scanner "emit" (lseq-cdr scanner) e* ...))) ((_ input (rt (s v) ...) rest ...) (let ((scanner (string->scanner input))) (test-scanner "emit" scanner (<stream-start-token>) (rt (s v) ...) rest ...))))) (define-syntax test-scanner-error (syntax-rules () ((_ input) (let ((scanner (string->scanner input))) ;; skip stream-start (test-error input yaml-scanner-error? (lseq-realize scanner)))))) (test-scanner "plain" (<scalar-token> (value "plain") (plain? #t))) (test-scanner "plain #comment\nbar" (<scalar-token> (value "plain") (plain? #t)) (<scalar-token> (value "bar") (plain? #t))) (test-scanner "%YAML 1.0" (<directive-token> (value '(1 . 0)) (name "YAML"))) (test-scanner-error "% invalid") (test-scanner-error "%YAML 1.x") (test-scanner-error "%YAML 1-1") (test-scanner-error "%YAML 1.1x") ;; after a directive, there must be a line break (or EOF) (test-scanner-error "%YAML 1.1 boo") (test-scanner "%TAG !yaml! tag:yaml.org,2002:" (<directive-token> (value '("!yaml!" . "tag:yaml.org,2002:")) (name "TAG"))) (test-scanner "%TAG ! tag:yaml.org,2002:/" (<directive-token> (value '("!" . "tag:yaml.org,2002:/")) (name "TAG"))) (test-scanner "%TAG !! tag:yaml.org,2002:/" (<directive-token> (value '("!!" . "tag:yaml.org,2002:/")) (name "TAG"))) (test-scanner "%TAG !! tag:%20:with:%20:space" (<directive-token> (value '("!!" . "tag: :with: :space")) (name "TAG"))) (test-scanner-error "%TAG !") (test-scanner-error "%TAG ! !>") (test-scanner-error "%TAG ! ! !") (test-scanner-error "%TAG foo bar") (test-scanner-error "%TAG !! tag:%2") (test-scanner "---" (<document-start-token>)) (test-scanner "--- " (<document-start-token>)) (test-scanner "---\n" (<document-start-token>)) (test-scanner "-" (<block-sequence-start-token>) (<block-entry-token>)) (test-scanner "- --"(<block-sequence-start-token>) (<block-entry-token>)) (test-scanner "-\n--" (<block-sequence-start-token>) (<block-entry-token>)) (test-scanner "..." (<document-end-token>)) (test-scanner ". .." (<scalar-token>)) (test-scanner "[" (<flow-sequence-start-token>)) (test-scanner "]" (<flow-sequence-end-token>)) (test-scanner "{" (<flow-mapping-start-token>)) (test-scanner "}" (<flow-mapping-end-token>)) (test-scanner "," (<flow-entry-token>)) (test-scanner "?" (<block-mapping-start-token>) (<key-token>)) (test-scanner "[ ? ]" (<flow-sequence-start-token>) (<key-token>) (<flow-sequence-end-token>)) (test-scanner ":" (<block-mapping-start-token>) (<value-token>)) (test-scanner "[ :" (<flow-sequence-start-token>) (<value-token>)) (test-scanner "&value" (<anchor-token> (value "value"))) (test-scanner-error "& value") (test-scanner-error "&value$") (test-scanner "*value" (<alias-token> (value "value"))) (test-scanner-error "* value") (test-scanner-error "*value$") (test-scanner "!<tag:yaml.org,2002:str>" (<tag-token> (value '(#f . "tag:yaml.org,2002:str")))) (test-scanner "!" (<tag-token> (value '(#f . "!")))) (test-scanner "!!str" (<tag-token> (value '("!!" . "str")))) (test-scanner "!str" (<tag-token> (value '("!" . "str")))) (test-scanner "!foo!str" (<tag-token> (value '("!foo!" . "str")))) (test-scanner-error "!<tag:yaml.org,2002:str") (test-scanner-error "!<tag:yaml.org,2002:str>foo") (test-scanner "|\n block scalar\n next line" (<scalar-token> (value "block scalar\nnext line") (style #\|) (plain? #f))) (test-scanner "|\n \n \n literal\n \n \n text\n\n #comment" (<scalar-token> (value "\n\nliteral\n \n\ntext\n") (style #\|) (plain? #f))) (test-scanner "| # Empty header\n literal" (<scalar-token> (value "literal"))) (test-scanner "|+ # Chompoing indicator\n keep\n\n" (<scalar-token> (value "keep\n\n"))) (test-scanner "|1- # Both indicator\n strip\n\n" (<scalar-token> (value " strip"))) (test-scanner-error "| - # wrong indicator") (test-scanner-error "|0- # wrong indicator") (test-scanner-error "|10- # wrong indicator") (test-scanner ">1 # Indentation indicator\n folded\n" (<scalar-token> (value " folded\n") (style #\>) (plain? #f))) (test-scanner ">\n folded\n text\n\n" (<scalar-token> (value "folded text\n") (style #\>) (plain? #f))) (test-scanner ">\n\n folded\n line\n\n next\n line\n * bullet\n\n * list\n * lines\n\n last\n line\n\n# Comment" (<scalar-token> (value "\nfolded line\nnext line\n * bullet\n\n * list\n * lines\n\nlast line\n") (style #\>) (plain? #f))) (test-scanner "\"implicit block key\"" (<scalar-token> (value "implicit block key") (style #\") (plain? #f))) (test-scanner "\"folded \nto a space,\t\n \n to a line feed, or \t\\\n \\ \tnon-content\"" (<scalar-token> (value "folded to a space,\nto a line feed, or \t \tnon-content") (style #\"))) (test-scanner "\" 1st non-empty\n\n 2nd non-empty \n\t3rd non-empty \"" (<scalar-token> (value " 1st non-empty\n2nd non-empty 3rd non-empty "))) (test-scanner "\"\\0\\a\\b\\t\\ \\n\\v\\f\\r\\e\\ \\\"\\\\\\N\\_\\L\\P\"" (<scalar-token> (value "\x0;\x07;\x08;\x09;\x09;\x0a;\x0b;\x0c;\x0d;\x1b; \"\\\x85;\xa0;\x2028;\x2029;"))) (test-scanner "\"\\x20\\u0020\\U00000020\"" (<scalar-token> (value " "))) (test-scanner-error "\"foo") (test-scanner-error "\"\\x0\"") (test-scanner-error "\"\\u0\"") (test-scanner-error "\"\\U0\"") (test-scanner-error "\"\\xVV\"") (test-scanner-error "\"\\T\"") (test-scanner "'here''s to \"quotes\"'" (<scalar-token> (value "here's to \"quotes\"") (style #\') (plain? #f))) (test-scanner "'implicit block key'" (<scalar-token> (value "implicit block key") (style #\') (plain? #f))) (test-scanner "' 1st non-empty\n\n 2nd non-empty \n\t3rd non-empty '" (<scalar-token> (value " 1st non-empty\n2nd non-empty 3rd non-empty ") (style #\'))) (test-scanner "scalar\n..." (<scalar-token> (value "scalar")) (<document-end-token>)) (test-scanner "foo:\n- bar" (<block-mapping-start-token>) (<key-token>) (<scalar-token> (value "foo")) (<value-token>) (<block-entry-token>) (<scalar-token> (value "bar")) (<block-end-token>)) (test-scanner "- { foo:bar }" (<block-sequence-start-token>) (<block-entry-token>) (<flow-mapping-start-token>) (<scalar-token>) (<flow-mapping-end-token>) (<block-end-token>)) (test-scanner "foo:\n - bar\n - 1234\n - foo" (<block-mapping-start-token>) (<key-token>) (<scalar-token>) (<value-token>) (<block-sequence-start-token>) (<block-entry-token>) (<scalar-token>) (<block-entry-token>) (<scalar-token>) (<block-entry-token>) (<scalar-token>) (<block-end-token>) (<block-end-token>)) (test-scanner " - &alias1 1 - &alias2 2 - << : [ *alias1, *alias2 ] r: 10" (<block-sequence-start-token>) (<block-entry-token>) (<anchor-token> (value "alias1")) (<scalar-token> (value "1")) (<block-entry-token>) (<anchor-token> (value "alias2")) (<scalar-token> (value "2")) (<block-entry-token>) (<block-mapping-start-token>) (<key-token>) (<scalar-token> (value "<<")) (<value-token>) (<flow-sequence-start-token>) (<alias-token> (value "alias1")) (<flow-entry-token>) (<alias-token> (value "alias2")) (<flow-sequence-end-token>) (<key-token>) (<scalar-token> (value "r")) (<value-token>) (<scalar-token> (value "10")) (<block-end-token>)) (test-end)
true
577459dfaa68f91f8b3dd533c372ffb38f21d726
ca39b0bad8cf2fb9bc5699720c1ef86a34ab096a
/libskiwi/scm/core/symbol-table.scm
0dcf469102226523a0b08dd556219c92bd1d6bea
[ "MIT" ]
permissive
janm31415/skiwi
9f40c2120f14dd895cd875087ee941ec6a155b2d
8234d18fd95a971e947f28477b6173c3c7ef30da
refs/heads/master
2022-09-23T23:52:09.637174
2022-08-31T21:34:50
2022-08-31T21:34:50
252,686,866
4
0
null
null
null
null
UTF-8
Scheme
false
false
994
scm
symbol-table.scm
(define %symbol-table (make-vector 256 (list))) (define string->symbol (lambda (str) (let* ([i (string-hash str)] [b (vector-ref %symbol-table i)]) (let loop ([bucket b]) (cond [(##null? bucket) (let ([sym (%allocate-symbol str)]) (vector-set! %symbol-table i (##cons sym b)) sym ) ] [(%eqv? str (symbol->string (car bucket))) (car bucket)] [else (loop (cdr bucket))] )))))
false
06d3dcde075075d971eab9e6d36357806bbf17a9
ae0d7be8827e8983c926f48a5304c897dc32bbdc
/nekoie/bin/qdbm-dump
943232630ce21a4a112b6c0946f7d2065ccf0c16
[]
no_license
ayamada/copy-of-svn.tir.jp
96c2176a0295f60928d4911ce3daee0439d0e0f4
101cd00d595ee7bb96348df54f49707295e9e263
refs/heads/master
2020-04-04T01:03:07.637225
2015-05-28T07:00:18
2015-05-28T07:00:18
1,085,533
3
2
null
2015-05-28T07:00:18
2010-11-16T15:56:30
Scheme
UTF-8
Scheme
false
false
895
qdbm-dump
#!/usr/bin/env gosh ;;; coding: euc-jp ;;; -*- scheme -*- ;;; vim:set ft=scheme ts=8 sts=2 sw=2 et: ;;; $Id$ (use dbm.qdbm) ;;; ---- (define (qdbm-dump file) (let1 qdbm (make <qdbm> :path file :rw-mode :read ) (with-error-handler (lambda (e) #f) (lambda () (dynamic-wind (lambda () (dbm-open qdbm)) (lambda () (dbm-for-each qdbm (lambda (key value) (write key) (display " ") (write value) (newline) (flush) ))) (lambda () (dbm-close qdbm))))))) (define (main args) (if (= 1 (length args)) (begin (print "usage: qdbm-dump filename.qdbm") 1) (begin (map qdbm-dump (cdr args)) 0)))
false
8189c22a9b536355b9f8c87e774be81ca0df7803
88eaf472fcdbb4736ad95d52ede1d2d8c019774a
/scheme/System/nodebugger.scm
f2ca828f45b90358019254bd52e021f7cc0cbd43
[ "BSD-2-Clause", "BSD-2-Clause-Views" ]
permissive
blakemcbride/Dynace
8ca2ed1a1ba3c91cd4220543fce9880f2a089aa8
9cd122b3cd7977261cc093fae676a978fdb95ab2
refs/heads/master
2023-01-13T09:21:02.214780
2023-01-02T17:57:00
2023-01-02T17:57:00
16,148,303
86
10
null
null
null
null
UTF-8
Scheme
false
false
82
scm
nodebugger.scm
(define break (lambda tag null)) (define break-if (lambda args null))
false
ac12a9c0c01a78474f435bddddf5c4b94da03042
9b2eb10c34176f47f7f490a4ce8412b7dd42cce7
/lib-compat/chibi-scheme-yuni/compat/ffi/primitives.sls
d44a85405d72b7c88d12bafce7b19b80847e3c1c
[ "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
4,102
sls
primitives.sls
(library (chibi-scheme-yuni compat ffi primitives) (export yuniffi-nccc-call yuniffi-nccc-ptr->callable yuniffi-nccc-proc-register yuniffi-nccc-proc-release yuniffi-module-load yuniffi-module-lookup yuniffi-callback-helper ;; Memory OPs (pointers) ptr? ptr-read/w64ptr ptr-read/s8 ptr-read/u8 ptr-read/s16 ptr-read/u16 ptr-read/s32 ptr-read/u32 ptr-read/s64 ptr-read/u64 ptr-read/asciiz ptr-write/s8! ptr-write/u8! ptr-write/s16! ptr-write/u16! ptr-write/s32! ptr-write/u32! ptr-write/s64! ptr-write/u64! ptr-write/asciiz! bv-read/w64ptr bv-write/w64ptr! ) (import (yuni scheme) (yuni ffi runtime bootstraploader) (yuni ffi runtime simpleloader) (yuni ffi runtime simplestrings) (srfi 33) ;; FIXME: Undocumented? (only (chibi) current-module-path) ;; FIXME: Rename this? (yuniffi-runtime)) ;; ;; FIXME: Assumes little endian (define (ptr? x) (eq? 1 (yuniffi_pointerp x))) (define (integer->ptr x) (yuniffi_offset_ptr #f x)) (define (ptr-read/s8 p off) (yuniffi_fetch_s8 p off)) (define (ptr-read/u8 p off) (yuniffi_fetch_u8 p off)) (define (ptr-read/s16 p off) (yuniffi_fetch_s16 p off)) (define (ptr-read/u16 p off) (yuniffi_fetch_u16 p off)) (define (ptr-read/s32 p off) (yuniffi_fetch_s32 p off)) (define (ptr-read/u32 p off) (yuniffi_fetch_u32 p off)) (define (ptr-write/s8! p off v) (yuniffi_store_s8 p off v)) (define (ptr-write/u8! p off v) (yuniffi_store_u8 p off v)) (define (ptr-write/s16! p off v) (yuniffi_store_s16 p off v)) (define (ptr-write/u16! p off v) (yuniffi_store_u16 p off v)) (define (ptr-write/s32! p off v) (yuniffi_store_s32 p off v)) (define (ptr-write/u32! p off v) (yuniffi_store_u32 p off v)) (define-read-asciiz ptr-read/asciiz ptr-read/u8) (define-write-asciiz ptr-write/asciiz! ptr-write/u8!) (define (ptr-read/w64ptr p off) (yuniffi_fetch_p64 p off)) (define (ptr-write/s64ptr! p off v) (yuniffi_store_p64 p off v)) (define (bv-read/w64ptr bv off) (yuniffi_fetch_p64_bv bv off)) (define (bv-write/w64ptr! bv off v) (yuniffi_store_p64_bv bv off v)) ;; Implement 64bit variants (define (ptr-read/s64 p off) (let ((lo (ptr-read/s32 p off)) (hi (ptr-read/s32 p (+ 4 off)))) (bitwise-ior (arithmetic-shift hi 32) lo))) (define (ptr-read/u64 p off) (let ((lo (ptr-read/s32 p off)) (hi (ptr-read/s32 p (+ 4 off)))) (+ (arithmetic-shift hi 32) lo))) (define (ptr-write/s64! p off v) (let ((lo (bitwise-and #xffffffff v)) (hi (bitwise-and #xffffffff (arithmetic-shift v -32)))) (ptr-write/u32! p off lo) (ptr-write/u32! p (+ 4 off) hi))) (define ptr-write/u64! ptr-write/s64!) ;; (define (yuniffi-nccc-call func in in-offset in-size out out-offset out-size) (yuniffi_nccc_call func in in-offset in-size out out-offset out-size)) (define (yuniffi-nccc-proc-register proc) (yuniffi_nccc_proc_register proc)) (define (yuniffi-nccc-proc-release obj) (yuniffi_nccc_proc_release obj)) (define (yuniffi-callback-helper) (yuniffi_nccc_get_callback_bridge)) (define-values (dlopen dlsym) (make-bootstraploader yuniffi-nccc-call yuniffi_nccc_bootstrap ptr? bv-read/w64ptr bv-write/w64ptr! ptr-write/asciiz!)) (define (module-load path) (dlopen path)) (define (yuniffi-module-lookup handle str) (dlsym handle str)) (define (module-path) (current-module-path)) (define yuniffi-module-load (make-simpleloader module-path module-load)) (define (yuniffi-nccc-ptr->callable ptr) ptr) )
false
f0fc9558ebfd32feb778ebd4b623f821d045e786
f04768e1564b225dc8ffa58c37fe0213235efe5d
/Assignment7/7.ss
feb8b0781c5ef6abd91a34ba7bead40c6404ba88
[]
no_license
FrancisMengx/PLC
9b4e507092a94c636d784917ec5e994c322c9099
e3ca99cc25bd6d6ece85163705b321aa122f7305
refs/heads/master
2021-01-01T05:37:43.849357
2014-09-09T23:27:08
2014-09-09T23:27:08
23,853,636
1
0
null
null
null
null
UTF-8
Scheme
false
false
5,326
ss
7.ss
;Francis Meng Assignment 7 ;Question1 (define (invert list) (if (null? list) '() (cons (reverse (car list)) (invert (cdr list))))) ;Question2 (define (vector-index pred v) (let search ([pred pred] [vector v] [index 0]) (if (>= index (vector-length vector)) #f (if (pred (vector-ref vector index)) index (search pred vector (+ index 1)))))) ;Question3 (define (vector-append-list v lst) (if (null? lst) v (let append-list ([ls lst] [index 0] [result (make-vector (+ (vector-length v) (list-length lst)))]) (if (>= index (vector-length v)) (if (null? ls) result (vector-set! result index (car ls))) (vector-set! result index (vector-ref v index))) (if (>= index (vector-length v)) (if (null? ls) result (append-list (cdr ls) (+ 1 index) result)) (append-list ls (+ 1 index) result)))) ) (define (list-length ls) (if (null? ls) 0 (+ 1 (list-length (cdr ls))))) ;Question4 (define (qsort pred ls) (if (null? ls) '() (let ([filtered-ls (filter-list pred ls)]) (append (append (qsort pred (car (cdr filtered-ls))) (cons (car ls) '())) (qsort pred (car filtered-ls)))) ) ) (define (filter-list op ls) (let filter-single ([l (cdr ls)] [pos '()] [neg '()] [pivot (car ls)]) (if (null? l) (list pos neg) (if (op pivot (car l)) (filter-single (cdr l) (append pos (cons (car l) '())) neg pivot) (filter-single (cdr l) pos (append neg (cons (car l) '())) pivot)))) ) ;Question5 (define (connected? g) (cond ((null? g) #t) ((null? (cdr g)) #t) ((null? (cadr (car g))) #f) (else (let check-connectivity ([group (cons (append (append '() (cons (car (car g)) '())) (cadr (car g))) '())] [cur-g (cdr g)] ) (cond ((null? cur-g) (if (> (list-length group) 1) #f #t)) ((null? (cadr (car cur-g))) #f) (else (check-connectivity (intersect-union group (append (cons (car (car cur-g)) '()) (cadr (car cur-g)))) (cdr cur-g))) ) ) ) ) ) (define (add-set set e) (if (member e set) set (append set (cons e '())))) (define (intersect-union ls1 ls2) (if (null? ls2) ls1 (if (null? (cdr ls1)) (if (intersect? (car ls1) ls2) (cons (union (car ls1) ls2) '()) (cons (car ls1) (cons ls2 '()))) (if (intersect? (car ls1) ls2) (intersect-union (cons (union (car ls1) ls2) '()) (cadr ls1)) (cons (car ls1) (intersect-union (cdr ls1) ls2))))) ) (define (union ls1 ls2) (if (null? ls2) ls1 (if (member (car ls2) ls1) (union ls1 (cdr ls2)) (union (append ls1 (cons (car ls2) '())) (cdr ls2))))) (define (intersect? ls1 ls2) (if (null? (cdr ls1)) (if (member (car ls1) ls2) #t #f) (if (member (car ls1) ls2) #t (intersect? (cdr ls1) ls2)))) (define (intersection s1 s2) (if (equal? s1 '()) '() (if (member (car s1) s2) (cons (car s1) (intersection (cdr s1) s2)) (intersection (cdr s1) s2))) ) (define (in-list? ls el) (if (null? ls) #f (if (equal? (car ls) el) #t (in-list? (cdr ls) el))) ) ;Question6 (define (reverse-it ls) (cond ((null? ls) '()) ((null? (cdr ls)) ls) (else (append (reverse-it (cdr ls)) (cons (car ls) '()))) )) ;Question7 ;Question 7.1 (define (empty-BST) '() ) ;Question 7.2 (define (empty-BST? obj) (equal? obj (empty-BST))) ;Question 7.3 (define (BST-insert num bst) (if (null? bst) (cons num (list '() '())) (if (> num (car bst)) (list (car bst) (cadr bst) (BST-insert num (caddr bst))) (if (equal? num (car bst)) bst (list (car bst) (BST-insert num (cadr bst)) (caddr bst)))))) ;Question 7.4 (define (BST-inorder bst) (cond ((null? bst) '()) ;((and (null? (cadr bst)) (null? (caddr bst))) (cons (car bst) '())) (else (append (append (BST-inorder (cadr bst)) (cons (car bst) '())) (BST-inorder (caddr bst)))) ) ) ;Question 7.5 (define (BST? bst) (cond ((null? bst) #t) ((not (list? bst)) #f) ((null? (cdr bst)) #f) ((null? (cddr bst)) #f) ((not (list? (cadr bst))) #f) ((not (list? (caddr bst))) #f) ((not (number? (car bst))) #f) ((is-sorted? (BST-inorder bst)) #t) (else #f)) ) (define (is-sorted? ls) (if (null? (cdr ls)) #t (if (< (car ls) (cadr ls)) (is-sorted? (cdr ls)) #f))) ;Question 7.6 (define (BST-element tree) (car tree) ) (define (BST-left tree) (cadr tree)) (define (BST-right tree) (caddr tree)) ;Question 7.7 (define (BST-insert-nodes bst nums) (if (null? nums) bst (BST-insert-nodes (BST-insert (car nums) bst) (cdr nums)))) ;Question 7.8 (define (BST-contains? bst num) (if (null? bst) #f (if (equal? (car bst) num) #t (if (> num (car bst)) (BST-contains? (caddr bst) num) (BST-contains? (cadr bst) num))))) ;Question8 (define (map-by-position fn-list arg-list) (map (lambda (x y) (x y)) fn-list arg-list) )
false
a55ceee0794d02ad60534dd8eb9ca3d8171e5028
0bb7631745a274104b084f6684671c3ee9a7b804
/lib/_six/six-expand.scm
c03ba805cf475dd07d5759b04cbfe4678df58a27
[ "Apache-2.0", "LGPL-2.1-only", "LicenseRef-scancode-free-unknown", "GPL-3.0-or-later", "LicenseRef-scancode-autoconf-simple-exception" ]
permissive
feeley/gambit
f87fd33034403713ad8f6a16d3ef0290c57a77d5
7438e002c7a41a5b1de7f51e3254168b7d13e8ba
refs/heads/master
2023-03-17T06:19:15.652170
2022-09-05T14:31:53
2022-09-05T14:31:53
220,799,690
0
1
Apache-2.0
2019-11-10T15:09:28
2019-11-10T14:14:16
null
UTF-8
Scheme
false
false
22,665
scm
six-expand.scm
;;;============================================================================ ;;; File: "six-expand.scm" ;;; Copyright (c) 2020-2022 by Marc Feeley, All Rights Reserved. ;;; Copyright (c) 2022 by Marc-André Bélanger, All Rights Reserved. ;;;============================================================================ (##supply-module _six/six-expand) (##namespace ("_six/six-expand#")) ;; in _six/six-expand# (##include "~~lib/gambit/prim/prim#.scm") ;; map fx+ to ##fx+, etc (##include "~~lib/_gambit#.scm") ;; for macro-check-procedure, ;; macro-absent-obj, etc (##include "six-expand#.scm") (declare (extended-bindings)) ;; ##fx+ is bound to fixnum addition, etc (declare (not safe)) ;; claim code has no type errors (declare (block)) ;; claim no global is assigned ;;;---------------------------------------------------------------------------- (define-type conversion-ctx target operators parameters globals literal procedure unsupported incall) (define C-operators (list->table '( ;; _____precedence ;; / ____associativity (0=LR, 1=RL, 2=not assoc.) ;; / / ___operand count (-1 for postfix unary operator) ;; / / / __target operator ;; / / / / (quasiquote 0 0) (six.identifier 0 0) (six.literal 0 0) (six.index 1 0) (six.call 1 0) (six.dot 1 0) (six.arrow 1 0) (six.x++ 1 0 -1 "++") (six.x-- 1 0 -1 "--") (six.+x 2 1 1 "+") ;; note: RL associative (six.-x 2 1 1 "-") (six.!x 2 1 1 "!") (six.~x 2 1 1 "~") (six.*x 2 1 1 "*") (six.&x 2 1 1 "&") (six.++x 2 1 1 "++") (six.--x 2 1 1 "--") (six.x*y 3 0 2 "*") (six.x/y 3 0 2 "/") (six.x%y 3 0 2 "%") (six.x+y 4 0 2 "+") (six.x-y 4 0 2 "-") (six.x<<y 5 0 2 "<<") (six.x>>y 5 0 2 ">>") (six.x<y 6 0 2 "<") (six.x<=y 6 0 2 "<=") (six.x>y 6 0 2 ">") (six.x>=y 6 0 2 ">=") (six.x==y 7 0 2 "==") (six.x!=y 7 0 2 "!=") (six.x&y 8 0 2 "&") (six.x^y 9 0 2 "^") (|six.x\|y| 10 0 2 "|") (six.x&&y 11 0 2 "&&") (|six.x\|\|y| 12 0 2 "||") ;; (six.x?y:z 13 1) ;; note: RL associative (six.x=y 14 1 2 "=") ;; note: RL associative (six.x+=y 14 1 2 "+=") (six.x-=y 14 1 2 "-=") (six.x**=y 14 1 2 "**=") (six.x*=y 14 1 2 "*=") (six.x/=y 14 1 2 "/=") (six.x%=y 14 1 2 "%=") (six.x<<=y 14 1 2 "<<=") (six.x>>=y 14 1 2 ">>=") (six.x&=y 14 1 2 "&=") (six.x^=y 14 1 2 "^=") (|six.x\|=y| 14 1 2 "|=") (six.x&&=y 14 1 2 "&&=") (six.x||=y 14 1 2 "||=") ;; (six.x,=y 15 0 2 ",") ))) (define js-operators (list->table '( ;; _____precedence ;; / ____associativity (0=LR, 1=RL, 2=not assoc.) ;; / / ___operand count (-1 for postfix unary operator) ;; / / / __target operator ;; / / / / (quasiquote 0 0) (six.identifier 0 0) (six.literal 0 0) (six.list 0 0) (six.null 0 0) (six.asyncx 0 1 1 "async ") ;; note: RL associative (six.index 1 0) (six.call 1 0) (six.dot 1 0) (six.new 1 0) (six.x++ 3 0 -1 "++") (six.x-- 3 0 -1 "--") (six.+x 4 1 1 "+") ;; note: RL associative (six.-x 4 1 1 "-") (six.!x 4 1 1 "!") (six.~x 4 1 1 "~") (six.++x 4 1 1 "++") (six.--x 4 1 1 "--") (six.awaitx 4 1 1 "await ") (six.typeofx 4 1 1 "typeof ") (six.x**y 5 1 2 "**") ;; note: RL associative (six.x*y 6 0 2 "*") (six.x/y 6 0 2 "/") (six.x%y 6 0 2 "%") (six.x+y 7 0 2 "+") (six.x-y 7 0 2 "-") (six.x<<y 8 0 2 "<<") (six.x>>y 8 0 2 ">>") (six.x>>>y 8 0 2 ">>>") (six.x<y 9 0 2 "<") (six.x<=y 9 0 2 "<=") (six.x>y 9 0 2 ">") (six.x>=y 9 0 2 ">=") (six.xiny 9 0 2 " in ") (six.xinstanceofy 9 0 2 " instanceof ") (six.x==y 10 0 2 "==") (six.x!=y 10 0 2 "!=") (six.x===y 10 0 2 "===") (six.x!==y 10 0 2 "!==") (six.x&y 11 0 2 "&") (six.x^y 12 0 2 "^") (|six.x\|y| 13 0 2 "|") (six.x&&y 14 0 2 "&&") (|six.x\|\|y| 15 0 2 "||") ;; (six.x?y:z 17 1) ;; note: RL associative (six.x=y 18 1 2 "=") ;; note: RL associative (six.x+=y 18 1 2 "+=") (six.x-=y 18 1 2 "-=") (six.x**=y 18 1 2 "**=") (six.x*=y 18 1 2 "*=") (six.x/=y 18 1 2 "/=") (six.x%=y 18 1 2 "%=") (six.x<<=y 18 1 2 "<<=") (six.x>>=y 18 1 2 ">>=") (six.x>>>=y 18 1 2 ">>>=") (six.x&=y 18 1 2 "&=") (six.x^=y 18 1 2 "^=") (|six.x\|=y| 18 1 2 "|=") (six.x&&=y 18 1 2 "&&=") (six.x||=y 18 1 2 "||=") (six.yieldx 20 1 1 "yield ") ;; note: RL associative ;; (six.x,=y 21 0 2 ",") (six.procedure 99 0) ))) (define python-operators (list->table '( ;; _____precedence ;; / ____associativity (0=LR, 1=RL, 2=not assoc.) ;; / / ___operand count (-1 for postfix unary operator) ;; / / / __target operator ;; / / / / (quasiquote 0 0) (six.identifier 0 0) (six.literal 0 0) (six.list 0 0) (six.null 0 0) (six.index 1 0) (six.call 1 0) (six.dot 1 0) (six.xasy 1 1 2 " as ") (|six.x,y| 2 1 2 ", ") (six.x**y 3 1 2 "**") ;; note: RL associative (six.+x 4 1 1 "+") ;; note: RL associative (six.-x 4 1 1 "-") (six.~x 4 1 1 "~") (six.x*y 5 0 2 "*") (six.x@y 5 0 2 "@") (six.x/y 5 0 2 "/") (six.x//y 5 0 2 "//") (six.x%y 5 0 2 "%") (six.x+y 6 0 2 "+") (six.x-y 6 0 2 "-") (six.x<<y 7 0 2 "<<") (six.x>>y 7 0 2 ">>") (six.x&y 8 0 2 "&") (six.x^y 9 0 2 "^") (|six.x\|y| 10 0 2 "|") (six.x<y 11 2 2 "<") ;; note: not associative (six.x<=y 11 2 2 "<=") (six.x>y 11 2 2 ">") (six.x>=y 11 2 2 ">=") (six.x==y 11 2 2 "==") (six.x!=y 11 2 2 "!=") (six.xiny 11 2 2 " in ") (six.xisy 11 2 2 " is ") (six.notx 12 1 1 "not ") ;; note: RL associative (six.xandy 13 0 2 " and ") (six.xory 14 0 2 " or ") (six.x=y 15 1 2 "=") ;; note: RL associative (six.procedure 99 0) ))) (define (six->C ast-src) (define (convert-literal cctx src) (##deconstruct-call src 2 (lambda (val-src) (let ((val (##source-strip val-src))) (cond ((number? val) (number->string val)) ;; TODO: use C number syntax ((boolean? val) (if val "1" "0")) ((string? val) (object->string val)) ;; TODO: use C string syntax (else (unsupported cctx src))))))) (define (convert-procedure cctx ast-src params return-type stmts-src) (unsupported cctx ast-src)) (define (unsupported cctx src) (##raise-expression-parsing-exception 'ill-formed-expression src)) (define cctx (make-conversion-ctx 'C C-operators '() (make-table) convert-literal convert-procedure unsupported #f)) (let ((target-expr (six-expression-to-infix cctx ast-src))) (cons (flatten-string target-expr) (reverse (conversion-ctx-parameters cctx))))) (define (six->js ast-src) (define (convert-literal cctx src) (##deconstruct-call src 2 (lambda (val-src) (let ((val (##source-strip val-src))) (cond ((number? val) (number->string val)) ;; TODO: use JavaScript number syntax ((boolean? val) (if val "true" "false")) ((string? val) (object->string val)) ;; TODO: use JavaScript string syntax (else (unsupported cctx src))))))) (define (statement cctx ast-src) (let ((ast (##source-strip ast-src))) (if (not (pair? ast)) (unsupported ast-src) (let* ((head (##source-strip (car ast))) (rest (cdr ast))) (case head ((six.return) (list "return " (six-expression-to-infix cctx (car rest)) "; ")) (else (list (six-expression-to-infix cctx ast) "; "))))))) (define (convert-procedure cctx ast-src params return-type stmts-src) (list "function (" (comma-separated (map (lambda (param) (symbol->string (cadr (car param)))) params)) ") { " (map (lambda (stmt-src) (statement cctx stmt-src)) stmts-src) "}")) (define (unsupported cctx src) (##raise-expression-parsing-exception 'ill-formed-expression src)) (define cctx (make-conversion-ctx 'js js-operators '() (make-table) convert-literal convert-procedure unsupported #f)) (let ((target-expr (six-expression-to-infix cctx ast-src))) (cons (flatten-string target-expr) (reverse (conversion-ctx-parameters cctx))))) ;; Expand six.infix for JavaScript. (define (six.infix-js-expand src) (##deconstruct-call src 2 (lambda (ast-src) (let ((ast (##source-strip ast-src))) (if (and (pair? ast) (eq? 'six.import (##source-strip (car ast))) (pair? (cdr ast)) (null? (cddr ast))) (let ((ident (##source-strip (cadr ast)))) (if (and (pair? ident) (eq? 'six.identifier (##source-strip (car ident))) (pair? (cdr ident)) (null? (cddr ident))) `(begin (error "JavaScript import not implemented") (js-import ,(symbol->string (##source-strip (cadr ident)))) (void)) (error "invalid import"))) (let* ((x (six->js ast-src)) (body (car x)) (params (cdr x)) (def (string-append "(async function (" (flatten-string (comma-separated (map car params))) ") {" "\n return " body ";\n})"))) `((##host-function-memoized ',(box def)) ;; literal box ,@(map cdr params)))))))) (define (six->python ast-src) (define (convert-literal cctx src) (##deconstruct-call src 2 (lambda (val-src) (let ((val (##source-strip val-src))) (cond ((number? val) (number->string val)) ;; TODO: use Python number syntax ((boolean? val) (if val "True" "False")) ((string? val) (object->string val)) ;; TODO: use Python string syntax (else (unsupported cctx src))))))) ;; Unsupported in Python (define (convert-procedure cctx ast-src params return-type stmts-src) #!void) (define (statement cctx ast-src) #!void) (define (unsupported cctx src) (##raise-expression-parsing-exception 'ill-formed-expression src)) (define cctx (make-conversion-ctx 'python python-operators '() (make-table) convert-literal convert-procedure unsupported #f)) (let ((target-expr (six-expression-to-infix cctx ast-src))) (cons (flatten-string target-expr) (reverse (conversion-ctx-parameters cctx))))) ;; Expand six.infix for Python. (define (six.infix-python-expand src) (##deconstruct-call src 2 (lambda (ast-src) (let ((ast (##source-strip ast-src))) (cond ((and (pair? ast) (eq? 'six.from-import-* (##source-strip (car ast)))) (let ((stmt (string-concatenate `("from " ,@(six->python (##source-strip (cadr ast))) " import *")))) `(begin (python-exec ,stmt) (void)))) ((and (pair? ast) (eq? 'six.from-import (##source-strip (car ast)))) (let ((stmt (string-concatenate `("from " ,@(six->python (##source-strip (cadr ast))) " import " ,(flatten-string (comma-separated (map (lambda (e) (six->python e)) (##source-strip (cddr ast))))))))) `(begin (python-exec ,stmt) (void)))) ((and (pair? ast) (eq? 'six.import (##source-strip (car ast))) (pair? (cdr ast))) (let ((stmt `(string-concatenate (list "import " ,(flatten-string (comma-separated (map (lambda (e) (six->python e)) (##source-strip (cdr ast))))))))) `(begin (python-exec ,stmt) (void)))) (else (let* ((x (six->python ast-src)) (body (car x)) (params (cdr x)) (def (string-append "lambda " (flatten-string (comma-separated (map car params))) ": " body))) `((##py-function-memoized ',(box def)) ;; literal box ,@(map cdr params))))))))) (define (six->target ast-src target) (case target ((C) (six->C ast-src)) ((js) (six->js ast-src)) ((python) (six->python ast-src)) (else (error "unsupported target" target)))) (define (six-expression-to-infix cctx ast-src) (define (unsupported ast-src) ((conversion-ctx-unsupported cctx) cctx ast-src)) (define (precedence op) (car op)) (define (associativity op) (cadr op)) (define (parens-optional? pos inner-op outer-op) (let ((inner-prec (precedence inner-op)) (outer-prec (precedence outer-op))) (or (< inner-prec outer-prec) (and (= inner-prec outer-prec) (let ((inner-assoc (associativity inner-op))) (and (< inner-assoc 2) ;; 2 = non associative (= inner-assoc pos))))))) (define (infix ast-src pos outer-op) (let ((ast (##source-strip ast-src))) (if (not (pair? ast)) (unsupported ast-src) (let* ((head (##source-strip (car ast))) (rest (cdr ast)) (inner-op (table-ref (conversion-ctx-operators cctx) head #f))) (if (not inner-op) (unsupported ast-src) (let* ((x (cddr inner-op)) (expr (if (not (pair? x)) (infix* ast-src pos inner-op) (let ((operand-count (car x)) (target-op (cadr x))) (case (length rest) ((0) target-op) ((1) (list target-op (infix (car rest) 1 inner-op))) ((2) ;; Handle six.x=y assignments for Python (if (and (eq? (conversion-ctx-target cctx) 'python) (not (conversion-ctx-incall cctx)) (equal? target-op "=")) (let ((lhs (infix (car rest) 0 inner-op))) (list "set_global('" lhs "', " (infix (cadr rest) 1 inner-op) ")")) (list (infix (car rest) 0 inner-op) target-op (infix (cadr rest) 1 inner-op)))) ((3) ...) ;; TODO: ternary operator (else (unsupported ast))))))) (if (parens-optional? pos inner-op outer-op) expr (list "(" expr ")")))))))) (define (infix* ast-src pos inner-op) (let ((ast (##source-strip ast-src))) (case (##source-strip (car ast)) ((quasiquote) (##deconstruct-call ast-src 2 (lambda (expr-src) (let* ((params (conversion-ctx-parameters cctx)) (param-id (string-append "___" (number->string (+ 1 (length params)))))) (conversion-ctx-parameters-set! cctx (cons (cons param-id expr-src) params)) param-id)))) ((six.identifier) (##deconstruct-call ast-src 2 (lambda (ident-src) (let* ((ident-sym (##source-strip ident-src)) (ident (symbol->string ident-sym))) (table-set! (conversion-ctx-globals cctx) ident-sym ident) ident)))) ((six.literal) ((conversion-ctx-literal cctx) cctx ast-src)) ((six.list six.null) (let loop ((ast-src ast-src) (rev-elems '())) (let ((ast (##source-strip ast-src))) (case (##source-strip (car ast)) ((six.list) (##deconstruct-call ast-src 3 (lambda (head-src tail-src) (loop tail-src (cons (cvt head-src) rev-elems))))) ((six.null) (##deconstruct-call ast-src 0 (lambda () (list "[" (comma-separated (reverse rev-elems)) "]")))) (else (unsupported ast-src)))))) ((six.index) (##deconstruct-call ast-src 3 (lambda (obj-src index-src) (list (infix obj-src 0 inner-op) "[" (cvt index-src) "]")))) ((six.call) (##deconstruct-call ast-src -2 (lambda (fn-src . args-src) (conversion-ctx-incall-set! cctx #t) ;; Named/keyword argument handling (let loop ((args-src args-src) (args '())) (if (pair? args-src) (if (keyword? (car args-src)) (loop (cddr args-src) (cons (string-append (keyword->string (car args-src)) "=" (cvt (cadr args-srcs))) args)) (loop (cdr args-src) (cons (cvt (car args-src)) args))) (let ((res (list (infix fn-src 0 inner-op) "(" (comma-separated (reverse args)) ")"))) (conversion-ctx-incall-set! cctx #f) res)))))) ((six.new) (##deconstruct-call ast-src -2 (lambda (constructor-src . args-src) (let ((args (map cvt args-src))) (list "new " (infix constructor-src 0 inner-op) "(" (comma-separated args) ")"))))) ((six.dot) (##deconstruct-call ast-src 3 (lambda (obj-src attr-src) ;; TODO: check that attr-src is (six.identifier ...) (##deconstruct-call attr-src 2 (lambda (ident-src) (list (infix obj-src 0 inner-op) "." (symbol->string (##source-strip ident-src)))))))) ((six.procedure) (##deconstruct-call ast-src 4 (lambda (return-type-src params-src procedure-body-src) ;; TODO: check that procedure-body-src is correct (##deconstruct-call procedure-body-src -1 (lambda stmts-src ((conversion-ctx-procedure cctx) cctx ast-src (##desourcify params-src) (##desourcify return-type-src) stmts-src)))))) (else (unsupported ast-src))))) (define (cvt ast-src) ;; pretend wrapped in infinitely low precedence operator to prevent ;; outer level of parentheses (infix ast-src 0 '(9999 0))) (cvt ast-src)) (define (comma-separated lst) (if (pair? lst) (cons (car lst) (map (lambda (x) (list "," x)) (cdr lst))) "")) (define (flatten-string x) (call-with-output-string (lambda (p) (##print-aux x p)))) ;;;============================================================================
false
7f428585fa838c19360f63a09026fb3c976f1b1d
5355071004ad420028a218457c14cb8f7aa52fe4
/2.5/e-2.83.scm
a0861e3f88090e6f382de9de77f400d74d382148
[]
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,528
scm
e-2.83.scm
; Exercise 2.83. ; ; Suppose you are designing a generic arithmetic ; system for dealing with the tower of types shown in figure 2.25: ; integer, rational, real, complex. For each type (except ; complex), design a procedure that raises objects of that type ; one level in the tower. Show how to install a generic raise ; operation that will work for each type (except complex). ; ------------------------------------------------------------ (load "../helpers.scm") (load "2.5.scm") (load "e-2.78.scm") (define (raise-scheme-number n) (make-rational n 1)) ;; internal procedures (define (numer x) (car x)) (define (denom x) (cdr x)) (define (raise-rational n) (attach-tag 'real (/ (numer (content n)) (denom (content n))))) (define (raise-real n) (make-complex-from-mag-ang (content n) 0)) ; test procedures to how raise works ; (output (raise-scheme-number 5)) ; (output (raise-rational (make-rational 3 2))) ; (output (raise-real (raise-rational (make-rational 3 2)))) ; here we can define generic raise procedure for our ; arithmetic system and install it (define (update-scheme-number-package) (put 'raise '(scheme-number) raise-scheme-number)) (update-scheme-number-package) (define (raise-rational-to-complex n) (make-complex-from-real-imag (/ (numer n) (denom n)) 0)) ; since we dont work with real numbers yet (define (update-rational-package) (put 'raise '(rational) raise-rational-to-complex)) (update-rational-package) (define (raise n) (apply-generic 'raise n)) ; (output (raise 5))
false
194fff5c5b577225db7e4ceb3952fc62712184a2
923209816d56305004079b706d042d2fe5636b5a
/sitelib/http/header-field/content-length.scm
5cadaaa6a934ebd042c3adcdd5db2f4bfce75288
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
tabe/http
4144cb13451dc4d8b5790c42f285d5451c82f97a
ab01c6e9b4e17db9356161415263c5a8791444cf
refs/heads/master
2021-01-23T21:33:47.859949
2010-06-10T03:36:44
2010-06-10T03:36:44
674,308
1
0
null
null
null
null
UTF-8
Scheme
false
false
249
scm
content-length.scm
(library (http header-field content-length) (export Content-Length) (import (rnrs (6)) (http abnf)) ;;; 14.13 Content-Length (define Content-Length (seq (string->rule "Content-Length") (char->rule #\:) *LWS (rep+ DIGIT))) )
false
0436d3a2745134ed5dbccf59e9b6e6dade8ff278
2d868c9428b8f4772d2ede375a3492b3b6885e1d
/Henderson Escher Example/2.41.scm
932e532c6b52ab5f04a0bb6ca425c5bf80098881
[]
no_license
transducer/sicp
2428223945da87836fa2a82c02d965061717ae95
2cec377aa7805edfd7760c643c14127e344ee962
refs/heads/master
2021-06-06T20:06:47.156461
2016-09-16T22:05:02
2016-09-16T22:05:02
25,219,798
1
0
null
null
null
null
UTF-8
Scheme
false
false
1,491
scm
2.41.scm
#lang scheme ;; Write a procedure to find all ordered triples of distinct ;; positive integers i, j, and k less than or equal to a ;; given integer n that sum to a given integer s. ;; Define helpers: (define (filter predicate sequence) (cond ((null? sequence) nil) ((predicate (car sequence)) (cons (car sequence) (filter predicate (cdr sequence)))) (else (filter predicate (cdr sequence))))) (define (accumulate op initial sequence) (if (null? sequence) initial (op (car sequence) (accumulate op initial (cdr sequence))))) (define nil '()) (define (flatmap proc seq) (accumulate append nil (map proc seq))) (define (enumerate-interval low high) (if (> low high) nil (cons low (enumerate-interval (+ low 1) high)))) ;; Answer the question: ;; Use unique-pairs from previous and append each number ;; upto n to the front on every unique pair. (define (unique-triples n) (flatmap (lambda (a) (map (lambda (b) (cons a b)) (flatmap (lambda (i) (map (lambda (j) (list i j)) (enumerate-interval 1 (- i 1)))) (enumerate-interval 1 (- a 1))))) (enumerate-interval 1 n))) (define (find-ordered-triples n s) ;; only keep the triples that add up to 10: (filter (lambda (triple) (= (accumulate + 0 triple) s)) (unique-triples n))) ;; Testing: (find-ordered-triples 10 10) ;; => ((5 3 2) (5 4 1) (6 3 1) (7 2 1))
false
dbd380a611691a34247ff9c1ce5fea04bae780db
424b80e2c2a1829f8815378dd08ed6b6021310f7
/exercises/09/streams-idea-demo.scm
86d6dc2e5531b9362fd886f20c382f42ab91beb2
[ "MIT" ]
permissive
fmi-lab/fp-elective-2017
b8238b413f346f6e74a02af043293d27822c9ce2
e88d5c0319b6d03c0ecd8a12a2856fb1bf5dcbf3
refs/heads/master
2021-09-06T22:01:16.421169
2018-02-12T09:53:52
2018-02-12T09:53:52
106,176,573
7
3
MIT
2018-01-15T15:00:40
2017-10-08T13:02:09
Scheme
UTF-8
Scheme
false
false
364
scm
streams-idea-demo.scm
(define (from n) (cons n (lambda () (from (+ n 1))))) (define naturals (from 0)) (define (take n stream) (if (= n 0) '() (cons (car stream) (lambda () (take (- n 1) ((cdr stream))))))) (define (collect-stream stream) (if (null? stream) '() (cons (car stream) (collect-stream ((cdr stream)))))) (collect-stream (take 10 naturals))
false
4098b2e9079855264013c6ff7bcb27c83aa81f30
ab05b79ab17619f548d9762a46199dc9eed6b3e9
/sitelib/ypsilon/gdk/list.scm
5e03328daa3ff55d65dbc20494a5fe2ce7f26c82
[ "BSD-2-Clause" ]
permissive
lambdaconservatory/ypsilon
2dce9ff4b5a50453937340bc757697b9b4839dee
f154436db2b3c0629623eb2a53154ad3c50270a1
refs/heads/master
2021-02-28T17:44:05.571304
2017-12-17T12:29:00
2020-03-08T12:57:52
245,719,032
1
0
NOASSERTION
2020-03-07T23:08:26
2020-03-07T23:08:25
null
UTF-8
Scheme
false
false
937
scm
list.scm
#!nobacktrace ;;; Ypsilon Scheme System ;;; Copyright (c) 2004-2009 Y.FUJITA / LittleWing Company Limited. ;;; See license.txt for terms and conditions of use. (library (ypsilon gdk list) (export gdk_list_visuals) (import (rnrs) (ypsilon ffi)) (define lib-name (cond (on-linux "libgdk-x11-2.0.so.0") (on-sunos "libgdk-x11-2.0.so.0") (on-freebsd "libgdk-x11-2.0.so.0") (on-openbsd "libgdk-x11-2.0.so.0") (on-darwin "Gtk.framework/Gtk") (on-windows "libgdk-win32-2.0-0.dll") (else (assertion-violation #f "can not locate GDK library, unknown operating system")))) (define lib (load-shared-object lib-name)) (define-syntax define-function (syntax-rules () ((_ ret name args) (define name (c-function lib lib-name ret name args))))) ;; GList* gdk_list_visuals (void) (define-function void* gdk_list_visuals ()) ) ;[end]
true
8e257704149b4aa404c967521d78503c5cc05988
1db1ff7b9a9ac4ef2c04e64beec85952e7e12c6b
/pgy-tokens.sch
a9796097100f7f78ed19a04b3798fa758a6fd446
[]
no_license
pnkfelix/pgybs
c2a19db40287a2d0387d4fa00251be36ee4ff5ca
a34f70a65d26d2c5ad798a4bbf15eaf3acd1cced
refs/heads/master
2021-01-19T19:37:45.419606
2013-09-30T00:02:09
2013-09-30T00:02:09
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
995
sch
pgy-tokens.sch
(define pgy-tokens (let* ((char-range (lambda (char-a char-b) (let ((a (char->integer char-a)) (b (char->integer char-b))) (let loop ((i a)) (cond ((> i b) '()) (else (cons (integer->char i) (loop (+ i 1))))))))) (digit `(! ,@(char-range #\0 #\9))) (letter `(! ,@(char-range #\a #\z) ,@(char-range #\A #\Z)))) `((id-a (+ (! #\a))) (id-b (+ (! #\b))) ;; old token classes (goesto ( #\: #\: #\= )) (newline #\newline) (sharpsign #\#) (end ,(string->list "*end")) (productions ,(string->list "*productions")) (terminals ,(string->list "*terminals")) (id (,letter (* (! ,letter ,digit)))) (id (#\< ,letter (* (! ,letter ,digit)) #\>)) (number (+ ,digit)) )))
false
9683a4e95a8d1d05d9064f0902fdd6779bc6553d
93979d95c1bd6c56e1a2b13d4a29fb37a072fb72
/sha-1.scm
5a91fc6a966733672d0d3dbed7055f344aad04e9
[ "MIT" ]
permissive
theschemer/hashing
1b6abf391351a832225472f95fc294ad3ebae4bb
abdbaf7ce8324540e324acf1ecff670b170ae10d
refs/heads/master
2021-05-05T21:50:14.133424
2017-12-24T20:21:09
2017-12-24T20:50:40
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
11,693
scm
sha-1.scm
;; -*- mode: scheme; coding: utf-8 -*- ;; Copyright © 2009, 2010, 2012, 2017 Göran Weinholt <[email protected]> ;; SPDX-License-Identifier: MIT ;; Permission is hereby granted, free of charge, to any person obtaining a ;; copy of this software and associated documentation files (the "Software"), ;; to deal in the Software without restriction, including without limitation ;; the rights to use, copy, modify, merge, publish, distribute, sublicense, ;; and/or sell copies of the Software, and to permit persons to whom the ;; Software is furnished to do so, subject to the following conditions: ;; The above copyright notice and this permission notice shall be included in ;; all copies or substantial portions of the Software. ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ;; THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;; DEALINGS IN THE SOFTWARE. #!r6rs ;; Byte-oriented SHA-1 from FIPS 180-3 and RFC 3174. ;; The data being hashed will never be modified here. ;; TODO: give an error if more than 2^64 bits are processed? ;; TODO: Optimize. Should be simple enough with the help of a profiler. (library (hashing sha-1) (export make-sha-1 sha-1-update! sha-1-finish! sha-1-clear! sha-1 sha-1-copy sha-1-finish sha-1-transform! ;for interested parties only sha-1-length sha-1-copy-hash! sha-1-96-copy-hash! sha-1->bytevector sha-1->string sha-1-hash=? sha-1-96-hash=? hmac-sha-1) (import (rnrs)) (define (sha-1-length) 20) (define (vector-copy x) (vector-map (lambda (i) i) x)) (define (rol32 n count) (let ((field1 (bitwise-and #xffffffff (bitwise-arithmetic-shift-left n count))) (field2 (bitwise-arithmetic-shift-right n (- 32 count)))) (bitwise-ior field1 field2))) (define-record-type sha1state (fields (immutable H) ;Hash (immutable W) ;temporary data (immutable m) ;unprocessed data (mutable pending) ;length of unprocessed data (mutable processed))) ;length of processed data (define (make-sha-1) (let ((H (list->vector initial-hash)) (W (make-bytevector (* 4 80))) (m (make-bytevector (* 4 16)))) (make-sha1state H W m 0 0))) (define (sha-1-copy state) (let ((H (vector-copy (sha1state-H state))) (W (make-bytevector (* 4 80))) (m (bytevector-copy (sha1state-m state)))) (make-sha1state H W m (sha1state-pending state) (sha1state-processed state)))) (define (sha-1-clear! state) (for-each (lambda (i v) (vector-set! (sha1state-H state) i v)) '(0 1 2 3 4) initial-hash) (bytevector-fill! (sha1state-W state) 0) (bytevector-fill! (sha1state-m state) 0) (sha1state-pending-set! state 0) (sha1state-processed-set! state 0)) (define initial-hash '(#x67452301 #xefcdab89 #x98badcfe #x10325476 #xc3d2e1f0)) (define (Ch x y z) (bitwise-xor (bitwise-and x y) (bitwise-and (bitwise-not x) z))) (define Parity bitwise-xor) (define (Maj x y z) (bitwise-xor (bitwise-and x y) (bitwise-and x z) (bitwise-and y z))) (define k1 #x5a827999) (define k2 #x6ed9eba1) (define k3 #x8f1bbcdc) (define k4 #xca62c1d6) (define (f t B C D) ((cond ((<= 0 t 19) Ch) ((<= 20 t 39) Parity) ((<= 40 t 59) Maj) (else Parity)) B C D)) (define (K t) (cond ((<= 0 t 19) k1) ((<= 20 t 39) k2) ((<= 40 t 59) k3) (else k4))) ;; This function transforms a whole 512 bit block. (define (sha-1-transform! H W m offset) ;; Copy the message block (do ((t 0 (+ t 4))) ((= t (* 4 16))) (bytevector-u32-native-set! W t (bytevector-u32-ref m (+ t offset) (endianness big)))) ;; Initialize W[16..79] (do ((t (* 4 16) (+ t 4))) ((= t (* 4 80))) (bytevector-u32-native-set! W t (rol32 (bitwise-xor (bytevector-u32-native-ref W (- t (* 4 3))) (bytevector-u32-native-ref W (- t (* 4 8))) (bytevector-u32-native-ref W (- t (* 4 14))) (bytevector-u32-native-ref W (- t (* 4 16)))) 1))) ;; Do the hokey pokey (let lp ((A (vector-ref H 0)) (B (vector-ref H 1)) (C (vector-ref H 2)) (D (vector-ref H 3)) (E (vector-ref H 4)) (t 0)) (cond ((= t 80) (vector-set! H 0 (bitwise-and #xffffffff (+ A (vector-ref H 0)))) (vector-set! H 1 (bitwise-and #xffffffff (+ B (vector-ref H 1)))) (vector-set! H 2 (bitwise-and #xffffffff (+ C (vector-ref H 2)))) (vector-set! H 3 (bitwise-and #xffffffff (+ D (vector-ref H 3)))) (vector-set! H 4 (bitwise-and #xffffffff (+ E (vector-ref H 4))))) (else (lp (bitwise-and #xffffffff (+ (rol32 A 5) (f t B C D) E (bytevector-u32-native-ref W (* 4 t)) (K t))) A (rol32 B 30) C D (+ t 1)))))) ;; Add a bytevector to the state. Align your data to whole blocks if ;; you want this to go a little faster. (define sha-1-update! (case-lambda ((state data start end) (let ((m (sha1state-m state)) ;unprocessed data (H (sha1state-H state)) (W (sha1state-W state))) (let lp ((offset start)) (cond ((= (sha1state-pending state) 64) ;; A whole block is pending (sha-1-transform! H W m 0) (sha1state-pending-set! state 0) (sha1state-processed-set! state (+ 64 (sha1state-processed state))) (lp offset)) ((= offset end) (values)) ((or (> (sha1state-pending state) 0) (> (+ offset 64) end)) ;; Pending data exists or less than a block remains. ;; Add more pending data. (let ((added (min (- 64 (sha1state-pending state)) (- end offset)))) (bytevector-copy! data offset m (sha1state-pending state) added) (sha1state-pending-set! state (+ added (sha1state-pending state))) (lp (+ offset added)))) (else ;; Consume a whole block (sha-1-transform! H W data offset) (sha1state-processed-set! state (+ 64 (sha1state-processed state))) (lp (+ offset 64))))))) ((state data) (sha-1-update! state data 0 (bytevector-length data))))) (define zero-block (make-bytevector 64 0)) ;; Finish the state by adding a 1, zeros and the counter. (define (sha-1-finish! state) (let ((m (sha1state-m state)) (pending (+ (sha1state-pending state) 1))) (bytevector-u8-set! m (sha1state-pending state) #x80) (cond ((> pending 56) (bytevector-copy! zero-block 0 m pending (- 64 pending)) (sha-1-transform! (sha1state-H state) (sha1state-W state) m 0) (bytevector-fill! m 0)) (else (bytevector-copy! zero-block 0 m pending (- 64 pending)))) ;; Number of bits in the data (bytevector-u64-set! m 56 (* (+ (sha1state-processed state) (- pending 1)) 8) (endianness big)) (sha-1-transform! (sha1state-H state) (sha1state-W state) m 0))) (define (sha-1-finish state) (let ((copy (sha-1-copy state))) (sha-1-finish! copy) copy)) ;; Find the SHA-1 of the concatenation of the given bytevectors. (define (sha-1 . data) (let ((state (make-sha-1))) (for-each (lambda (d) (sha-1-update! state d)) data) (sha-1-finish! state) state)) (define (copy-hash! state bv off len) (do ((i 0 (+ i 1))) ((= i len)) (bytevector-u32-set! bv (+ off (* 4 i)) (vector-ref (sha1state-H state) i) (endianness big)))) (define (sha-1-copy-hash! state bv off) (copy-hash! state bv off 5)) (define (sha-1-96-copy-hash! state bv off) (copy-hash! state bv off 3)) (define (sha-1->bytevector state) (let ((ret (make-bytevector (* 4 5)))) (sha-1-copy-hash! state ret 0) ret)) (define (sha-1->string state) (apply string-append (map (lambda (x) (if (< x #x10) (string-append "0" (number->string x 16)) (number->string x 16))) (bytevector->u8-list (sha-1->bytevector state))))) ;; Compare an SHA-1 state with a bytevector. It is supposed to not ;; terminate early in order to not leak timing information. Assumes ;; that the bytevector's length is ok. (define (cmp state bv len) (do ((i 0 (fx+ i 1)) (diff 0 (+ diff (bitwise-xor (bytevector-u32-ref bv (* 4 i) (endianness big)) (vector-ref (sha1state-H state) i))))) ((fx=? i len) (zero? diff)))) (define (sha-1-hash=? state bv) (cmp state bv 5)) (define (sha-1-96-hash=? state bv) (cmp state bv 3)) ;;; HMAC-SHA-1. RFC 2104. ;; TODO: an API with make, update!, finish!, finish, clear!, copy, etc (define (hmac-sha-1 secret . data) ;; RFC 2104. (if (> (bytevector-length secret) 64) (apply hmac-sha-1 (sha-1->bytevector (sha-1 secret)) data) (let ((k-ipad (make-bytevector 64 0)) (k-opad (make-bytevector 64 0))) (bytevector-copy! secret 0 k-ipad 0 (bytevector-length secret)) (bytevector-copy! secret 0 k-opad 0 (bytevector-length secret)) (do ((i 0 (fx+ i 1))) ((fx=? i 64)) (bytevector-u8-set! k-ipad i (fxxor #x36 (bytevector-u8-ref k-ipad i))) (bytevector-u8-set! k-opad i (fxxor #x5c (bytevector-u8-ref k-opad i)))) (let ((state (make-sha-1))) (sha-1-update! state k-ipad) (for-each (lambda (d) (sha-1-update! state d)) data) (sha-1-finish! state) (let ((digest (sha-1->bytevector state))) (sha-1-clear! state) (sha-1-update! state k-opad) (sha-1-update! state digest) (sha-1-finish! state) state))))))
false
8387a947b5753edf81b684ab5ccf17999dc6d8b1
b58f908118cbb7f5ce309e2e28d666118370322d
/src/72.scm
21ead224bff99db598fda63eeb3039633e7eec15
[ "MIT" ]
permissive
arucil/L99
a9e1b7ad2634850db357f7cc292fa2871997d93d
8b9a3a8e7fb63efb2d13fab62cab2c1254a066d9
refs/heads/master
2021-09-01T08:18:39.029308
2017-12-26T00:37:55
2017-12-26T00:37:55
114,847,976
1
0
null
null
null
null
UTF-8
Scheme
false
false
511
scm
72.scm
;;; P72 (load "prelude.scm") (define (bottom-up t) (if (symbol? t) (list (list t)) (append (list (list (car t))) (map (lambda (x) (append x (list (car t)))) (apply append (map bottom-up (cdr t))))))) (test (bottom-up 'x) '((x))) (test (bottom-up '(f g)) '((f) (g f))) (test (bottom-up '(x (f g))) '((x) (f x) (g f x))) (test (bottom-up '(a (f g) c (b d e))) '((a) (f a) (g f a) (c a) (b a) (d b a) (e b a)))
false
7498d27181050e03babc8a0c04aa66a79ed7c394
abc7bd420c9cc4dba4512b382baad54ba4d07aa8
/src/ws/compiler_components/regiment_helpers.sls
d1d074d265289c2946651bd8273b883e21f8ec2b
[ "BSD-3-Clause" ]
permissive
rrnewton/WaveScript
2f008f76bf63707761b9f7c95a68bd3e6b9c32ca
1c9eff60970aefd2177d53723383b533ce370a6e
refs/heads/master
2021-01-19T05:53:23.252626
2014-10-08T15:00:41
2014-10-08T15:00:41
1,297,872
10
2
null
null
null
null
UTF-8
Scheme
false
false
38,291
sls
regiment_helpers.sls
#!r6rs ;;;; .title Regiment Helper Functions (regiment_helpers.ss) ;;;; <br> [2005.12.01] <br> ;;;; I'm going to start the (slow) process of seperating all the ;;;; Regiment-specific support utilities from my generic scheme ;;;; utilities. Previously all of this had resided in the bloated ;;;; helpers.ss file. (library (ws compiler_components regiment_helpers) (export reg:random-int reg:random-real reg:get-random-state reg:set-random-state! randomize-list randomize-vector! list-get-random vector-get-random sense-spatial-sine-wave sense-dist-from-origin sense-sine-wave sense-noisy-rising sense-random-1to100 ;sense-fast-sine-wave unique-name unique-name-counter extract-suffix make-begin make-nested-lets ;deep-reg:struct->list ;deep-reg:struct->list2 reg:very-deep-map strip-illegal deunique-name reunique-names get-formals ;; Hmm, not sure what meaning immediate has here... ;immediate? simple-constant? complex-constant? datum? qinteger? qinteger->integer formalexp? cast-formals fit-formals-to-args constant-expr? simple-expr? maybe-bind-tmp token-machine? token-machine->program ;token-machine-keyword? ;; Token names: token-name? new-token-name token-names get-names get-formation-name get-membership-name token->name token->subtok destructure-tokbind handler->tokname handler->formals handler->body handler->subtokid handler->stored project-metadata apply-to-program-body map-graph-exprs regiment-print-params test-regiment_helpers parse-readFile-modestring annotation? peel-annotations apply/annotations let-spine ) (import (except (rnrs (6)) error) (rnrs mutable-pairs (6)) (ws compat compat) (ws globals) (ws compiler_components prim_defs) (ws util hashtab) (ws util helpers) (ws util iu-match) (ws util reg_macros) ;(ws util rn-match) ;; TEMPTOGGLE ) ; ====================================================================== ;;; The various sensor-reading stubs. ;;; ;;; Used by SimAlpha. <br> ;;; These are all simple functions that compute fake sensor values. <br><br> ;;; ;;; Sensor-function constructors are thunks that allocate state for a ;;; simulated sensed-world and return a sensor function. <br><br> ;;; ;;; Sensor-functions are called regularly with the current time. They ;;; are also called when a sensor value needs to be read, in which ;;; case the node-id, x/y coords, and sensor type are all provided. <br><br> ;;; ;;; If we wanted the simulator to be less synchronous, we would need ;;; to have seperate sense objects for each node, each maintaining its ;;; own state according to its own clock. That gets a little tricky, ;;; because presumably you're measuring a phenomena defined globally. <br><br> ;;; ;;; All told, sensor-function constructors have a type like the following: ;;; <br> ;;; () --{Newsim}--> ;;; Time --{UpdateState}--> ;;; (type, id, x, y) --> ;;; SensorReading ;;; <br> ;;; ;;; Alternatively, these could be implemented as an object with a ;;; constructor and two methods AdvanceClock, and and ReadSensor. But ;;; this way ensures that AdvanceClock is called before ReadSensor. ;; This one changes amplitude across space and time. (define sense-spatial-sine-wave (let ([fun (lambda () (lambda (t) (lambda (type id x y) ;(printf "(sensing ~a ~a ~a ~a) " id x y t) ;(exact->inexact (exact (floor (let ((waveamp (+ 127.5 (* 127.5 (sin (* t (/ 3.14 1000)))))) (distorigin (sqrt (+ (* x x) (* y y)))) (maxdist (sqrt (+ (expt world-xbound 2) (expt world-ybound 2))))) (* waveamp (/ distorigin maxdist))))))))]) ;; This is the default sensing function right now, so we set the parameter. (simalpha-sense-function-constructor fun) fun)) ;; This globally defined functions decides the sensor values. ;; Here's a version that makes the sensor reading the distance from the origin: (define sense-dist-from-origin (lambda () (lambda (t) (lambda (type id x y) (sqrt (+ (expt x 2) (expt y 2))))))) (define sense-sine-wave (lambda () (lambda (t) (lambda (type id x y) ;(printf "(sensing ~a ~a ~a ~a) " id x y t) ;(exact->inexact (exact (floor (+ 127.5 (* 127.5 (sin (* t (/ 3.14 1000))))))))))) ;; TODO: add noise to this, store state per ID: curry inputs: (define sense-noisy-rising (lambda () (lambda (t) (lambda (type id x y) (/ t 100.))))) (define sense-random-1to100 (lambda () (lambda (t) (lambda (type id x y) (add1 (reg:random-int 100)))))) #; (define (sense-fast-sine-wave id x y t) (printf "(sensing ~a ~a ~a ~a) " id x y t) (exact (floor (+ 127.5 (* 127.5 (sin (* t (/ 3.14 1000)))))))) ;(include "prim_defs_OLD.ss") ;====================================================================== ;;; Some methods for handling Abstract Syntax. ;; create a "flattened" begin from list of expressions ;; e.g., (make-begin '(1 (begin 2) (begin 3 4) 5)) => (begin 1 2 3 4 5) ;; (define make-begin (lambda (expr*) (IFCHEZ (import rn-match) (begin)) (let ([initlst (match expr* [(begin ,x* ...) x*] [,ls ls])]) (match (let loop ([ls initlst]) (match ls [() '()] [((begin ,sub* ...) . ,[rest]) (append (loop sub*) rest)] [(,x) (list x)] [((tuple) . ,[rest]) rest] [('UNIT . ,[rest]) rest] [(,fst . ,[rest]) (cons fst rest)])) ;[() '(tuple)] [() ''UNIT] [(,x) x] [(,x ,x* ...) `(begin ,x ,@x*)])))) (define (make-nested-lets binds body) (if (null? binds) body `(let (,(car binds)) ,(make-nested-lets (cdr binds) body)))) ;; A little helper to project out a metadata-tag from a program form. ;; TODO: Move this somewhere else: (define (project-metadata tag prog) (match prog [(,lang '(program ,body ,meta ... ,ty)) (assq tag meta)] [(,lang '(graph ,body ,meta ...)) (assq tag meta)] [,else #f])) ;; Another little helper to avoid destructuring the program syntax all the time. (define (apply-to-program-body f prog) (match prog [(,lang '(program ,body ,meta ... ,ty)) `(,lang '(program ,(f body) ,@meta ,ty))] [,_ (error 'apply-to-program-body "bad program form: ~s" prog)])) ;; Apply a function to all the *Expressions* within an explicit graph ;; representation (resulting from explicit-stream-wiring). (define (map-graph-exprs fn graph) (match graph [(,lang '(graph (const (,cbv* ,cbty* ,[fn -> cbexp*]) ...) (init ,[fn -> init*] ...) (sources ((name ,nm) (output-type ,s_ty) (code ,[fn -> scode]) (outgoing ,down* ...)) ...) (operators (,op (name ,name) (output-type ,o_ty) (code ,[fn -> itercode]) (incoming ,o_up ...) (outgoing ,o_down* ...)) ...) (sink ,base ,basetype) ,meta* ...)) `(,lang '(graph (const (,cbv* ,cbty* ,cbexp*) ...) (init ,init* ...) (sources ((name ,nm) (output-type ,s_ty) (code ,scode) (outgoing ,down* ...)) ...) (operators (,op (name ,name) (output-type ,o_ty) (code ,itercode) (incoming ,o_up ...) (outgoing ,o_down* ...)) ...) (sink ,base ,basetype) ,meta* ...))] [,oth (inspect oth)] )) ;============================================================= ;;; Identifiers and Constants. ;;; ;;; These are the symbols I use for different types right now: <br>&nbsp;&nbsp; ;;; Bool Char Float64 Int32 List Object ;;; Number Pair Port String Symbol Vector Void ;; The subset of Scheme keywords we support. <br> ;; [2004.06.28] RRN: Removed 'let' (define base-keyword? (lambda (x) (and (memq x '(quote set! if begin letrec lambda)) #t))) (define (simple-expr? x) (IFCHEZ (import rn-match) (begin)) (match x ;; [2007.03.11] Making complex constants *NON* simple [(quote ,imm) (guard ;(not (null? imm)) (or (simple-constant? imm) (symbol? imm)) ;(not (pair? imm)) (not (vector? imm)) ) #t] [Array:null #t] ;; [2007.12.09] Adding... ;; Void value: [(tuple) #t] ;; [2007.03.19] Why had I commented this before? Using 'UNIT instead. [(empty-wsrecord) #t] ;; [2008.11.11] This should be treated the same as an empty tuple. [,var (guard (symbol? var) (not (regiment-constant? var))) #t] ;; Annotations can still be simple. [(,annot ,_ ,[x]) (guard (annotation? annot)) x] ;; [2007.10.16] This is now considered simple: [(deref ,var) (DEBUGASSERT symbol? var) #t] [,otherwise #f])) ;; This is a litlte helper that introduces a new binding ONLY if the ;; RHS in question is not simple. This avoids unnecessary aliasing ;; and code-bloat. ;; ;; We can use propagate-copies to get rid of spurious ;; temporary variables. But that's no reason to be particularly ;; sloppy about introducing them, if it's easy not to. (define (maybe-bind-tmp rhs ty k) (if (simple-expr? rhs) (k rhs) (let ([name (unique-name 'tmp)]) `(let ([,name ,ty ,rhs]) ,(k name))))) ;; This describes what can go inside a (quote _) expression ;; after the complex constants have been removed. (define simple-constant? (lambda (x) (or ;(fx-integer? x) ;(flonum? x) ;(bg-integer? x) ;(ratnum? x) (number? x) ;; replacing chez specific... (double? x) ;; a new, boxed, number type [2008.08.22] (null? x) ;; This means you can type () without a quote. (boolean? x) (char? x) (string? x) ;; [2008.01.04] Making this complex. (eq? x 'BOTTOM) (eq? x 'UNIT) #; (if (symbol? x) ;; Just for compiler internal stuff. (printf "TRUE FOR SYM: ~s\n" x) #f ) ))) ;; Is it an *expression* that always returns the same value. (define (constant-expr? xp) (match xp [',c (simple-constant? c)] [(,annot ,_ ,[x]) (guard (annotation? annot)) x] [,_ #f])) ;; Valid complex constants in Regiment. ;; (Includes simple constants as well.) (define complex-constant? (lambda (x) (or (simple-constant? x) (and (pair? x) (complex-constant? (car x)) (complex-constant? (cdr x))) (and (vector? x) (vector-andmap complex-constant? x)) (and (tuple? x) (andmap complex-constant? (tuple-fields x))) ;; This is only for nullseg, it's a bit sketchy. (and (sigseg? x) (fx= 0 (vector-length (sigseg-vec x)))) (string? x) ))) ;; A potentially quoted integer. (define (qinteger? n) (IFCHEZ (import rn-match) (begin)) (match n [,i (guard (integer? i)) #t] [',i (guard (integer? i)) #t] [,else #f])) ;; Get the value of a potentially quoted integer. (define (qinteger->integer n) (IFCHEZ (import rn-match) (begin)) (match n [,i (guard (integer? i)) i] [(quote ,i) (DEBUGASSERT (integer? i)) i] [else (error 'qinteger->integer "this is not a qinteger: ~a" n)])) ;; Datums include structured constants as well as atoms. (define datum? (lambda (x) (or (simple-constant? x) (null? x) (symbol? x) ;(string? x) (if (pair? x) (and (datum? (car x)) (datum? (cdr x))) (and (vector? x) (andmap datum? (vector->list x))))))) ;; [2006.03.01] ;;<br> Flatten out a whole struct (record) into a list. ;;<br> This handles cyclic structures. #; (define (deep-reg:struct->list x) (let ([touched (make-default-hash-table)]) (let loop ((x x)) (cond [(hashtab-get touched x) => (lambda (v) v)] [(pair? x) ;; Add the original cell to the touched list. (let ([newcell (cons #f #f)]) ;; Associate the old cell with the new cell. (hashtab-set! touched x newcell) (set-car! newcell (loop (car x))) (set-cdr! newcell (loop (cdr x))) newcell)] [(vector? x) (let ([newvec (make-vector (vector-length x) #f)]) (hashtab-set! touched x newvec) (for i = 0 to (sub1 (vector-length x)) (vector-set! newvec i (loop (vector-ref x i)))) newvec)] [(reg:struct? x) (let ([newlst (reg:struct->list x)]) (hashtab-set! touched x newlst) (let innerloop ([lst (cdr newlst)]) (unless (null? lst) (set-car! lst (loop (car lst))) (innerloop (cdr lst)))) newlst)] [(atom? x) x] [else (error 'deep-reg:struct->list "what on earth is this object? ~a" x)])))) ;============================================================================= ;;; Unique names. ;; Remove the numeric suffix. (define deunique-name (lambda (sym) (let* ([str (symbol->string sym)] [segments (string-split str #\_)]) (string->symbol (apply string-append (insert-between "_" (if (string->number (rac segments)) (rdc segments) segments))))))) ;; [2005.11.03] This is for comparing test outputs that differ only in unique names. ;; It goes through the structure in a fixed, deterministic order, and introduces ;; unique names that are platform independent. (define reunique-names (lambda (expr) (define table (make-default-hash-table)) (define (make-entry) (cons -1 (make-default-hash-table))) (define (process s) (let* ((basesym (deunique-name s)) (entry (hashtab-get table basesym))) (when (not entry) (set! entry (make-entry)) (hashtab-set! table basesym entry)) (when (not (hashtab-get (cdr entry) s)) ;; Increment our counter: (set-car! entry (add1 (car entry))) (hashtab-set! (cdr entry) s (string->symbol (if (zero? (car entry)) "" (format "_~s" (car entry)))))) (symbol-append basesym (hashtab-get (cdr entry) s)))) (let loop ((ls expr)) (cond [(null? ls) '()] [(or (simple-constant? (car ls)) (match (car ls) [(quote ,c) (guard (simple-constant? c)) #t] [,_ #f])) (cons (car ls) (loop (cdr ls)))] [(symbol? (car ls)) (let ((first (process (car ls)))) (cons first (loop (cdr ls))))] [(list? (car ls)) (let ((first (loop (car ls)))) (cons first (loop (cdr ls))))] [(vector? (car ls)) (cons (list->vector (loop (vector->list (car ls)))) (loop (cdr ls)))] [else (error 'reunique-names "bad subexpression: ~s" (car ls))])))) ;; unique-name produces a unique name derived the input name by ;; adding a unique suffix of the form _<digit>+ creating a unique ;; name from a unique name has the effect of replacing the old ;; unique suffix with a new one. ;; ;; extract-suffix returns the numeric portion of the unique suffix ;; of a unique name, or #f if passed a non unique name. ;; RRN [01.09.16] -- We need to phase out code-name... ;; ;; <br><br> ;; ;; [2004.06.28] I am replacing this with a version that uses ;; a hash-table to keep a counter per seed-name. (begin ;; This is a single counter that is incremented every time a fresh variable is coined. (define unique-name-counter (make-parameter 0 (lambda (x) (if (integer? x) x (error 'unique-name-counter "bad value: ~a" x))))) (define (unique-suffix ignored) (unique-name-counter (+ (unique-name-counter) 1)) (number->string (unique-name-counter))) (define extract-root (lambda (sym) (list->string (let ([chars (string->list (symbol->string sym))]) (define (s0 ls) (cond [(null? ls) chars] [(char-numeric? (car ls)) (s1 (cdr ls))] [else chars])) (define (s1 ls) (cond [(null? ls) chars] [(char-numeric? (car ls)) (s1 (cdr ls))] [(memv (car ls) '(#\. #\$ #\_ )) (reverse (cdr ls))] [else chars])) (s0 (reverse chars)))))) (define extract-suffix (lambda (sym) (let ([str (symbol->string sym)]) (let ([n (string-length str)] [m (string-length (extract-root sym))]) (and (not (= n m)) (substring str (+ m 1) n)))))) (define strip-illegal (lambda (str) (list->string ;; [2007.03.10] Changing it to insert underscores rather than just removing the character: (map (lambda (c) (if (or (char-alphabetic? c) (char-numeric? c)) c #\_)) (string->list str))))) #; (define illegal-chars '(#\! #\@ #\# #\$ #\% #\^ #\& #\* #\. #\-)) #; (define strip-illegal (lambda (str) (let loop ([ls illegal-chars] [chars (string->list str)]) (if (null? ls) (list->string chars) (loop (cdr ls) (remq (car ls) chars)))))) ;;Ok, this is designed so that it can extract the root from ;;either a (define unique-name (lambda args (let ((sym (if (null? args) 'gensym (car args)))) (let ((sym (cond [(string? sym) (string->symbol sym)] [(symbol? sym) sym] [else (error 'unique-name "invalid name root: ~a" sym)]))) ; (printf " Coining name, counter ~s\n" (unique-name-counter)) (string->symbol (string-append (strip-illegal ;;RRN - THIS IS STUPID, CHANGE ME (extract-root sym)) "_" (unique-suffix sym))))))) ) ;; [2004.06.28] NEW VERSION, counter per seed name: ;; Just overwriting definitions from above: ;; ;; [2008.03.30] Resurrecting this. I've probably just forgotten why I wasn't using it. ;; Well, seems to break something (type errors appear...) #; (begin (define name-counter-table (make-default-hash-table)) (define ____ (let ([old-param unique-name-counter]) (set! unique-name-counter (case-lambda [() name-counter-table] [(val) (if (eq? val 0) ;; Ok, here's a hack. We simulate the behavior of ;; the above version when the input is zero. (set! name-counter-table (make-default-hash-table)) ;; This had better be a hash table: (begin (ASSERT (not (number? val))) (set! name-counter-table val)))])) (set! unique-suffix (lambda (sym) (let ((entry (hashtab-get name-counter-table sym))) (number->string (if entry (begin (hashtab-set! name-counter-table sym (add1 entry)) entry) (begin (hashtab-set! name-counter-table sym 1) 0))))))))) ;=============================================================================== ;;; Manipulation of lambda-arguments (formals). ;;; ;;; TODO: Phase out! (define formalexp? (lambda (formalexp) (match formalexp [(,v* ...) (list-is-set? v*)] [,v (guard (symbol? v)) #t] [(,v* ... . ,extra) (list-is-set? (cons extra v*))] [,else #f]))) ;; [2004.04.24] We're not using most of these forms, but this is still ;; a valid procedure: (define get-formals (lambda (formalexp) (match formalexp [(,v* ...) v*] [,v (guard (symbol? v)) (list v)] [(,v* ... . ,extra) (append v* (list extra))] [,else (error 'get-formals "invalid formals expression: ~a" formalexp)]))) (define get-normal-formals (lambda (formalexp) (match formalexp [(,v* ...) v*] [,v (guard (symbol? v)) '()] [(,v* ... . ,extra) v*] [,else (error 'get-normal-formals "invalid formals expression: ~a" formalexp)]))) (define get-list-formals (lambda (formalexp) (match formalexp [(,v* ...) '()] [,v (guard (symbol? v)) (list v)] [(,v* ... . ,extra) (list extra)] [,else (error 'get-list-formals "invalid formals expression: ~a" formalexp)]))) (define cast-formals (lambda (formals formalexp) (match formalexp [,v (guard (symbol? v)) (car formals)] [(,v* ...) formals] [(,v* ... . ,extra) (match formals [(,v* ... ,last) `(,v* ... . ,last)])] [,else (error 'cast-formals "invalid formals expression: ~a" formalexp)]))) ;; [2005.11.28] (define fit-formals-to-args (lambda (formals args) (let loop ((f formals) (a args)) (cond [(and (null? f) (null? a)) '()] [(and (symbol? f) (null? a)) '()] [(and (pair? f) (pair? a)) (cons (car f) (loop (cdr f) (cdr a)))] [(and (symbol? f) (pair? a)) (cons f (loop f (cdr a)))] [else (error 'fit-formals-to-args "cannot fit formals ~a to args ~a" formals args)])))) ;====================================================================== ;;; Dealing with token-machines in sexp form ;; Predicate to test (define (token-machine? x) (match x [(,input-lang '(program (bindings ,nodebinds ...) (socpgm (bindings ,socbinds ...) ,socstmts ...) (nodepgm (tokens ,nodetoks ...) (startup ,starttoks ...)))) #t] [(quote (program (bindings ,nodebinds ...) (socpgm (bindings ,socbinds ...) ,socstmts ...) (nodepgm (tokens ,nodetoks ...) (startup ,starttoks ...)))) #t] [(program (bindings ,nodebinds ...) (socpgm (bindings ,socbinds ...) ,socstmts ...) (nodepgm (tokens ,nodetoks ...) (startup ,starttoks ...))) #t] [,else #f])) ;; Project out the program portion. Strip off the language-name wrapper. (define (token-machine->program x) (if (token-machine? x) (match x [(,input-lang ',x) x] [(quote ,x) x] [,x x]) (error 'token-machine->program "bad token machine: \n ~s\n" x))) ;;; Token Handler Bindings. ;; There are different syntactic ways to write down token handler bindings. ;; (Thanks to optional forms in the syntax.) This parses tokbinds. ;; (Note: I am no longer using handler-local constant "bindings", but ;; it doesn't hurt that this function handles them:) (define (destructure-tokbind tbind) (define (process-stored s) (match s [(,v ,e) `(,v ,e)] [,v (guard (symbol? v)) `(,v '#f)])) (define (process-bods x) (match x [((stored ,s ...) (bindings ,b ...) ,bods ...) (values (map process-stored s) b (make-begin `((begin ,bods ...))))] [((bindings ,b ...) (stored ,s ...) ,bod ,bods ...) (values (map process-stored s) b (make-begin `((begin ,bod ,bods ...))))] [((stored ,s ...) ,bod ,bods ...) (values (map process-stored s) '() (make-begin `((begin ,bod ,bods ...))))] [((bindings ,b ...) ,bod ,bods ...) (values '() b (make-begin `((begin ,bods ,bods ...))))] ;; This is missing an expression: [(,_ ... (,keyword ,s ...)) (guard (memq keyword '(stored bindings))) (error 'destructure-tokbind "Missing body from token handler declaration: ~a" x)] [,bods (values '() '() (make-begin `((begin ,bods ...))))])) (match tbind [(,t (,a ...) ,bds ...) (mvlet ([(stored bindings body) (process-bods bds)]) (values t DEFAULT_SUBTOK_VAR a stored bindings body))] [(,t ,i (,a ...) ,bds ...) (mvlet ([(stored bindings body) (process-bods bds)]) (values t i a stored bindings body))] [,other (error 'destructure-tokbind "bad tokbind: ~a" other)])) ;; tokname accessor (define (handler->tokname tb) ;; More efficient for now: (car tb) ;(mvlet ([(tok id args stored bindings body) (destructure-tokbind tb)]) ;tok)) ) ;; formals accessor (define (handler->formals tb) (mvlet ([(tok id args stored bindings body) (destructure-tokbind tb)]) args)) ;; body accessor (define (handler->body tb) (mvlet ([(tok id args stored bindings body) (destructure-tokbind tb)]) body)) ;; subtokid accessor (define (handler->subtokid tb) (mvlet ([(tok id args stored bindings body) (destructure-tokbind tb)]) id)) (define (handler->stored tb) (mvlet ([(tok id args stored bindings body) (destructure-tokbind tb)]) stored)) ;============================================================= ;;; Dealing with the names of Tokens. ;;; ;;; Sloppy interface right now. ;;; Used by the deglobalize pass. ;; [2004.06.13] Tokens will be more complex later. (define (token-name? t) (IFCHEZ (import rn-match) (begin)) ;(or (symbol? t) ;(and (pair? t) (symbol? (car t)) (integer? (cdr t)))) (match t [(tok ,name) #t] [(tok ,name ,num) #t] [,s (guard (symbol? s)) #t] [else #f])) (define (token->name t) (IFCHEZ (import rn-match) (begin)) (match t [(tok ,name) name] [(tok ,name ,num) name] ;[(,name . ,_) name] [,name (guard (symbol? name)) name] [,other (error 'token->name "bad token: ~a" other)])) (define (token->subtok t) (IFCHEZ (import rn-match) (begin)) (match t [(tok ,name) 0] [(tok ,name ,num) num] ;[(,_ . ,subtok) subtok] [,name (guard (symbol? name)) 0] [,other (error 'token->name "bad token: ~a" other)])) ;; Allocate a token name, possibly with a seed name. (define new-token-name (lambda args (if (null? args) (unique-name 'token) (unique-name (car args))))) (define token-names (case-lambda [() (let ((n (unique-name 'token))) (values (symbol-append 'f_ n) (symbol-append 'm_ n)))] [(sym) (if (symbol? sym) (values (symbol-append 'f_token_ sym) (symbol-append 'm_token_ sym)) (error 'deglobalize.token-names "takes a symbol argument not this: ~s" sym))])) ;; Get's the token name that corresponds with the edge of a ;; dataflow graph that corresponds with a variable name. ;; For the moment token-names is deterministic!! So we just do this: (define get-names (lambda (v) (token-names v))) ; (mvlet ([(f m) (token-names v)]) f))) ; (define get-membership-name ; (lambda (v) ; (mvlet ([(f m) (token-names v)]) m))) (define (get-formation-name v) (mvlet ([(f m) (token-names v)]) f)) (define (get-membership-name v) (mvlet ([(f m) (token-names v)]) m)) ;;; Regiment Random Number Interface. <br> ;;; ;;; These provide a simple random number generator interface for use ;;; within the Regiment codebase. <br> ;;; The simulator should only use this RNG interface to maintain ;;; determinism. (Currently this just uses the primitive Chez ;;; Scheme RNG, so there is no proper seperation which would be ;;; necessary for other concurrently running code to not ruin the ;;; simulators determininms.) ;;; ;;; <br><br> ;;; TODO: FIXME: [2006.03.01] ;;; I should overhall this. Really, what I want is a separate RNG for simulator-alpha. ;;; And then I'd like another seperate RNG for the sensor data-generator. ;; NOTE: This is currently unisolated anyways. So it's just a ;; common interface into Chez/PLT's RNG's. Need to go further than that. ;; A random integer. (define reg:random-int (case-lambda [() (random (greatest-fixnum))] [(k) (random k)])) ;; A random real number. #; (define (reg:random-real . _) (error 'reg:random-real "can't get random reals from all R6RS implementations yet") #; (case-lambda [() (random 1.0)] [(n) (random n)])) (define reg:random-real (case-lambda [() (reg:random-real 1.0)] [(k) (/ (* k (reg:random-int (greatest-fixnum))) (inexact (greatest-fixnum)))])) ;; THIS DOES NOTHING ATM: (define (reg:get-random-state) #f) (define (reg:set-random-state! s) (void)) #| ;; Get the state of the RNG. (define (reg:get-random-state) (random-seed)) ;; This doesn't work!!! [2005.10.05] ;; Set the state of the RNG. (define (reg:set-random-state! s) (random-seed s)) (define (reg:get-random-state) (pseudo-random-generator->vector (current-pseudo-random-generator))) (define (reg:set-random-state! s) (current-pseudo-random-generator (vector->pseudo-random-generator s))) |# ;; [2006.03.01] UNFINISHED #; (define (reg:very-deep-map f x) (let ([touched (make-default-hash-table)]) (let loop ((x x)) ;(printf "MAPPING DOWN: ~a\n" (reg:struct? x)) (cond ;; Function gets applied for each instance of a repeated object: [(hashtab-get touched x) => (lambda (v) ;(printf "HIT REPEAT\n") (f v))] [(pair? x) ;; Add the original cell to the touched list. (let ([newcell (cons #f #f)]) ;; Associate the old cell with the new cell. (hashtab-set! touched x newcell) (set-car! newcell (loop (car x))) (set-cdr! newcell (loop (cdr x))) (f newcell))] [(vector? x) (let ([newvec (make-vector (vector-length x) #f)]) (hashtab-set! touched x newvec) (for i = 0 to (sub1 (vector-length x)) (vector-set! newvec i (loop (vector-ref x i)))) (f newvec))] [(reg:struct? x) ;; Copy the structure: (let* ([lst (reg:struct->list x)] [type (record-type-descriptor x)] [new (reg:list->struct x (cdr lst))]) (hashtab-set! touched x new) ;; CHEZ SPECIFIC. ;; CURRENT BEHAVIOR IS THAT IMMUTABLE FIELDS ARE OPAQUE TO THIS MAP FUNCTION: (for-each (lambda (decls val) ;(printf "DECLS & val: ~s ~s\n" decls val) (unless (memq 'immutable decls) ((record-field-mutator type (caddr decls)) new (loop val)))) (record-type-field-decls type) (cdr lst)) (f new))] [(atom? x) (f x)] [else (error 'reg:very-deep-map "what on earth is this object? ~a" x)])))) ; (reg:very-deep-map (\\ x (if (integer? x) (add1 x) x)) ; (let ((x '#0=(1 2 #(3 #0#)))) (set-car! x (make-node 99 99)) x)) ; (deep-reg:struct->list2 (make-node 1 2)) ; (deep-reg:struct->list2 (make-node 1 (make-node 3 4))) ;; THIS DOESN'T WORK RIGHT NOW: ; (deep-reg:struct->list2 (let ((x (make-node 1 (make-node 3 4)))) (set-node-id! x x) x)) ;; DOESN'T WORK YET: #; (define (deep-reg:struct->list2 ob) (reg:very-deep-map (let ([touched (make-default-hash-table)]) (lambda (x) (cond [(not (reg:struct? x)) x] [(hashtab-get touched x) => (lambda (v) v)] [else (let ([ret (reg:struct->list x)]) (hashtab-set! touched x ret) ret)] ))) ob)) #; ;; UNFINISHED: ;; This is like generic-traverse, but for any list/vector/record data structure. ;; TODO: How to handle cyclic structures. (define (reg:very-deep-traverse driver fuser x) (let loop ((e x)) (driver e (lambda (x) (cond [(atom? x) (fuser x '() (lambda () x))] [(pair? x) (fuser x (list (loop (car x)) (loop (cdr x))) (lambda (a d) (cons a d)))] [(vector? x) (fuser x (map loop (vector->list x)) (lambda args (list->vector args)))] [(reg:struct? x) (fuser x (cdr (reg:struct->list x)) (lambda args (reg:list->struct x args)))] [else (error 'reg:very-deep-traverse "unknown object: ~s" otherwise)]))))) ;============================================================= ;;; A few utilities that depend on Regiment's isolated RNG. ;; [2004.06.15] Copying this from generic utils file. (define list-get-random (lambda (ls) (if (null? ls) (error 'list-get-random "cannot get random element from null list.") (list-ref ls (reg:random-int (length ls)))))) ;; This too: (define randomize-list (lambda (ls) (let* ([vec (list->vector ls)]) (vector->list (randomize-vector! vec))))) (define vector-get-random (lambda (vec) (let ([len (vector-length vec)]) (if (fxzero? len) (error 'list-get-random "cannot get random element from empty vector.") (vector-ref vec (reg:random-int len)) )))) (define (randomize-vector! vec) (let ([len (vector-length vec)]) (let ([swap (lambda (i j) (let ([temp (vector-ref vec i)]) (vector-set! vec i (vector-ref vec j)) (vector-set! vec j temp)))]) (do ([i 0 (add1 i)]) ((= i len)) ;; Swap with a later position: (swap i (+ i (reg:random-int (- len i))))) vec))) ; ====================================================================== ;;; Misc. ;; This prints the valus of the most important parameters. It is for ;; recording the state of the compiler/simulator. It's primarily for ;; good book-keeping while benchmarking. It only records parameters ;; relevent to the resulting data. (define (regiment-print-params prefix . port) (let ([port (if (null? port) (current-output-port) (car port))] [pad-width (if #f;(top-level-bound? 'pad-width) ;; [2006.02.27] FIXME (top-level-value 'pad-width) (lambda (_ x) (format "~a" x)))]) (for-each (lambda (param-name) (fprintf port "~a ~a = ~s\n" prefix (pad-width 30 param-name) ((top-level-value param-name)))) (filter (lambda (p) (not (memq p ;; This is an omit list: '(repl-stream-depth simalpha-label-sensorvals simalpha-label-msgcounts simulator-write-sims-to-disk simalpha-graphics-on simalpha-stream-result simalpha-realtime-mode simalpha-output-port default-unit-tester-retries reg:comment-code simulation-logger-count simulation-logger-level simulation-logger regiment-emit-debug regiment-verbosity )))) (regiment-parameters)) ))) ;; The utility used for parsing the modestring arguments to readFile. ;; Returns: a __readfile expression with its many fields. (define (parse-readFile-modestring annot str typ fn src) (ASSERT string? str) ;; Defaults: (let* ([mode "text"] [repeats 0] [winsize 1] ;; Another meaningless default. [skipbytes 0] [offset 0] [p (open-string-input-port str)] [params (let loop ([x (read p)]) (if (eof-object? x) '() (cons x (loop (read p)))))] [pairs (match params [() '()] [(,a ,b . ,[tl]) (cons (list a b) tl)] [,oth (error 'readFile "invalid parameter string to readFile primitive: ~s" str)])] [num (lambda (n) (if (integer? n) n (error 'readFile "expected numeric parameter, got: ~s" n)))] [types (match typ [#(,t* ...) t*] [(Array ,[t]) t] [(Sigseg ,[t]) t] [,t (list t)])]) (for-each (match-lambda ((,flag ,val)) (case flag [(mode:) (set! mode (case val [(text) "text"] [(binary) "binary"] [else (error 'readFile "unsupported mode: ~s" val)]))] [(repeats:) (set! repeats (num val))] [(skipbytes:) (set! skipbytes (num val))] [(offset:) (set! offset (num val))] [(window:) (set! winsize (num val))] [else (error 'readFile "unknown option flag \"~s\"\n Valid flags are: ~s\n" flag '(mode: repeats: skipbytes: offset: window:))]) ) pairs) (when (equal? mode "text") (unless (= offset 0) (error 'readFile "doesn't support 'offset:' option in conjunction with text mode")) (unless (= skipbytes 0) (error 'readFile "doesn't support 'skipbytes:' option in conjunction with text mode"))) ;; If we're not producing a sigseg, we must set the winsize to zero: (match typ [(Sigseg ,t) (void)] [(Array ,t) (void)] [,else (set! winsize 0)]) `(__readFile ,annot ,fn ,src ',mode ',repeats ',skipbytes ',offset ',winsize ',types) ) ) ;; This defines the set of "annotations" recognized by the compiler. (define (annotation? sym) (eq-any? sym 'assert-type 'src-pos 'data-rate)) ;; Takes off just the outer layer of annotations (define (peel-annotations e) (match e [(,ann ,_ ,[e]) (guard (annotation? ann)) e] [,e e])) (define (apply/annotations e fn) (let loop ([e e] [acc1 '()] [acc2 '()]) (match e [(,ann ,a ,rhs) (guard (annotation? ann)) (loop rhs (cons ann acc1) (cons a acc2))] [,e (fn e (lambda (x) (let unroll ([acc1 (reverse! acc1)] [acc2 (reverse! acc2)]) (if (null? acc1) x (list (car acc1) (car acc2) (unroll (cdr acc1) (cdr acc2))) ))))]))) ;; This variant returns all the annotations to you. ;; Not used yet: #; (define (peel/collect-annotations e) (match e [(,ann ,_ ,[e a*]) (guard (annotation? ann)) (values e (cons (list ann _) a*))] [,e (values e '())])) ;; This is a simple interactive debugging tool. It shows the binding ;; spine of the program. ;; ;; Levels: ;; (define let-spine (case-lambda [(arg) (if (number? arg) (lambda (e) (let-spine arg e)) (let-spine 0 arg))] [(level e) (match e [,v (guard (symbol? v)) v] [(,lett ([,lhs* ,ty* ,[rhs*]] ...) ,[bod]) (guard (memq lett '(let* let letrec lazy-letrec))) `(,lett ,(map (lambda (v rhs) (list v (if (>= level 1) rhs '_))) lhs* rhs*) ,bod)] [(begin ,[e*] ...) (if (>= level 3) `(begin ,@e*) '_)] [(lambda ,args ,ty ,[bod]) (if (>= level 2) `(lambda ,args ,bod) '_)] [(iterate ,annot ,[fun] ,[bod]) (if (>= level 3) (if (>= level 4) `(iterate ,annot ,fun ,bod) `(iterate ,annot _ ,bod)) '_)] [(assert-type ,_ ,[e]) e] [(src-pos ,_ ,[e]) e] [(using ,_ ,[e]) e] [(,lang '(program ,[e] ,_ ...)) e] ;; duplicated code: [(,lett ([,lhs* ,[rhs*]] ...) ,[bod]) (guard (memq lett '(let* let letrec lazy-letrec))) `(,lett ,(map (lambda (v rhs) (list v (if (>= level 1) rhs '_))) lhs* rhs*) ,bod)] ;; duplicated code: [(lambda ,args ,[bod]) (if (>= level 2) `(lambda ,args ,bod) '_)] [,else '_])])) ; ====================================================================== (define-testing test-regiment_helpers (default-unit-tester "regiment_helpers.ss: Regiment-specific utils." `( ["Reunique names" (reunique-names '(foo_3 foo_43 foo_3 foo)) (foo foo_1 foo foo_2)] ["Reunique names #2" (reunique-names '(foo_3 (bar_3) foo_43 foo_3 (bar_3 bar_4))) (foo (bar) foo_1 foo (bar bar_1))] [(peel-annotations '(src-pos p (assert-type Int x))) x] [(apply/annotations '(src-pos p (assert-type Int x)) (lambda (_ k) (k 3))) (src-pos p (assert-type Int 3))] #; ["deep reg:struct->list" (let* ([v (vector 'a 'b)] [s (list 1 v 2)]) (reg:define-struct (foo a b)) (vector-set! v 0 s) (set-car! s v) (let ([foo (make-foo 1 2)]) (set-foo-b! foo foo) (set-foo-a! foo s) (deep-reg:struct->list foo) )) ,(lambda (x) (and (list? x) (= (length x) 3) (equal? (car x) "foo")))] ))) ) ; End Module.
false
dffd534ee8c7e4a68eafdec74e016d6f4e1cdda7
1ed47579ca9136f3f2b25bda1610c834ab12a386
/sec4/q4.03.scm
8b72a990f5c5831b9c258b82f86dc35a09763510
[]
no_license
thash/sicp
7e89cf020e2bf5ca50543d10fa89eb1440f700fb
3fc7a87d06eccbe4dcd634406e3b400d9405e9c4
refs/heads/master
2021-05-28T16:29:26.617617
2014-09-15T21:19:23
2014-09-15T21:19:23
3,238,591
0
1
null
null
null
null
UTF-8
Scheme
false
false
2,791
scm
q4.03.scm
;; データ主導(data-directed)の形式になるようevalを書きなおせ. ;; -> sec2/q2.73.scm のデータ主導微分プログラムと比較. ;; 要するにeval中でcondによる条件分岐をするんじゃなくて, ;; 渡されたexpの単語でtableからoperatorを検索して適用(apply). ;; (get 'deriv (operator exp)) ;; sec3/sec3.3.3.scm より -- make-table, lookup, assoc, insert! {{{ (define (lookup key table) (let ((record (assoc key (cdr table)))) (if record (cdr record) #f))) (define (assoc key records) (cond ((null? records) #f) ((equal? key (caar records)) (car records)) (else (assoc key (cdr records))))) (define (insert! key value table) (let ((record (assoc key (cdr table)))) (if record (set-cdr! record value) (set-cdr! table (cons (cons key value) (cdr table))))) 'ok) (define (make-table) (list '*table*)) ;; }}} ;; この文脈化でget/putはeval-tableの操作をするものと固定 (define eval-table (make-table)) (define get (lambda (key) (lookup key eval-table))) (define put (lambda (key proc) (insert! key proc eval-table))) (define (eval exp env) (cond ((self-evaluating? exp) exp) ((variable? exp) (lookup-variable-value exp env)) ;; get(=lookup)は対象がなければfalseを返すのでこのように使える. ((get (car exp)) ((get (car exp)) exp env)) ((application? exp) (apply (eval (operator exp) env) (list-of-values (operands exp) env))) (else (error "Unknown expression type -- EVAL" exp)))) ;; sec4.scm で定義されたtagged-list?対象は以下のとおり.これらをtableにぶちこむ. ; (define (quoted? exp) (tagged-list? exp 'quote)) ; (define (assignment? exp) (tagged-list? exp 'set!)) ; (define (definition? exp) (tagged-list? exp 'define)) ; (define (lambda? exp) (tagged-list? exp 'lambda)) ; (define (if? exp) (tagged-list? exp 'if)) ; (define (begin? exp) (tagged-list? exp 'begin)) ; (define (cond? exp) (tagged-list? exp 'cond)) ;; procに当たるのはそれぞれeval中のcondで実行文として与えられていたもの. (put 'quote (lambda (exp env) (text-of-quotation exp)))) (put 'set! (lambda (exp env) (eval-assignment exp env))) (put 'define (lambda (exp env) (eval-definition exp env))) (put 'if (lambda (exp env) (eval-if exp env))) (put 'begin (lambda (exp env) (eval-sequence (begin-actions exp) env))) (put 'cond (lambda (exp env) (eval (cond->if exp) env))) (put 'lambda (lambda (exp env) (make-procedure (lambda-parameters exp) (lambda-body exp) env)))
false
16d4b55fb35df26c8893f39c050ec1dffb802b56
ac67f848928f0fb5d749fc19183c6ec601c37648
/examples/csv.scm
2d32d79735a0aadd28df3a6489416e8c0a430bbd
[ "MIT" ]
permissive
mbal/parsifal
ce5ff84523c9a77c5617557239abe75540c50fa3
6d7d3ae041d71e7ef324f99925ad9ab0413e2b2a
refs/heads/master
2021-01-20T22:28:52.147131
2013-07-31T14:49:33
2013-07-31T14:49:33
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,042
scm
csv.scm
(module csv (run-csv) (import r5rs chicken) (import parser state) ;; A CSV file is either ;; - empty ;; - one or more lines ;; ;; A line consists in words, separated by , ;; so: (defparser csv% (either (many1 (sep-by1 word (char #\,)) (char #\newline)) (succeed '()))) ;; (run csv% "a,b,c,d") ==> (("a" "b" "c" "d")) ;; This parser works fine, but it just parses the first line (defparser new-line (char #\newline)) (defparser csv%% (either (many1 (then (sep-by1 word (char #\,)) new-line)) (succeed '()))) ;; but this doesn't work, for two reasons: ;; - the file has to end with a newline ;; - we don't save the parsed line in the result (defparser csv-line (sep-by1 word (one-of '(#\, #\;)))) (defparser csv (either (sep-by1 (sep-by1 word (char #\,)) (many1 new-line)) (succeed '()))) (define (run-csv str) (parse csv str)) )
false
effbb6d5ee9e133b8c143b6286d2a4fddebec017
f5083e14d7e451225c8590cc6aabe68fac63ffbd
/cs/01-Programming/cs61a/exercises/16_midterm_3.scm
454fa1b0204b7818e8811009182513601d34c375
[]
no_license
Phantas0s/playground
a362653a8feb7acd68a7637334068cde0fe9d32e
c84ec0410a43c84a63dc5093e1c214a0f102edae
refs/heads/master
2022-05-09T06:33:25.625750
2022-04-19T14:57:28
2022-04-19T14:57:28
136,804,123
19
5
null
2021-03-04T14:21:07
2018-06-10T11:46:19
Racket
UTF-8
Scheme
false
false
6,897
scm
16_midterm_3.scm
; Problem 1 1. (let ((x (list 1 2 3))) (set-car! x (list ’a ’b ’c)) (set-car! (cdar x) ’d) x) ; (('a 'b 'c) 'd 3) **WRONG** 0/2 ;SOLUTION ; (let ((x (list 1 2 3))) ; (set-car! x (list 'a 'b 'c)) ; (set-car! (cdar x) 'd) ; x) ; ((a d c) 2 3) is printed. ; X-->[o|o]-->[o|o]-->[o|/] ; | | | ; | V V ; | 2 3 ; V ; (o|o)-->{o|o}-->[o|/] ; | | | ; V V V ; a d c 2. (define x 3) (define m (list x 4 5)) (set! x 6) m ; (3 4 5) **PERFECT** 2/2 ; M-->[o|o]-->[o|o]-->[o|/] ; | | | ; V V V ; 3 4 5 3. (define x (list 1 ’(2 3) 4)) (define y (cdr x)) (set-car! y 5) x ; (1 (5 3) 4) **WRONG** 0/2 ; SOLUTION: ; Y ; | ; | ; V ; X-->[o|o]-->[o|o]-->[o|/] ; | | | ; V V V ; 1 5 4 ; In this example, Y names the same pair as (cdr x). So changing the car of Y ; changes the cadr of X, replacing (2 3) with 5. 4. ; (let ((x (list 1 2 3))) ; (set-cdr! (cdr x) x) ; x) ; (1) **WRONG** 0/2 ; SOLUTION ; (1 2 1 2 1 2 1 2 ... is printed. ; +---------+ ; | | ; V | ; X-->[o|o]-->[o|o] ; | | ; V V ; 1 2 ; This example creates a circular list. ; TOTAL: 02/08 ; Problem 2 ; Suppose we want to write a procedure prev that takes as its argument a procedure proc ; of one argument. Prev returns a new procedure that returns the value returned by the ; previous call to proc. The new procedure should return #f the first time it is called. For ; example: ; > (define slow-square (prev square)) ; > (slow-square 3) ; #f ; > (slow-square 4) ; 9 ; > (slow-square 5) ; 16 Which of the following definitions implements prev correctly? Pick only one. (define (prev proc) (let ((old-result #f)) (lambda (x) (let ((return-value old-result)) (set! old-result (proc x)) return-value)))) (define prev (let ((old-result #f)) (lambda (proc) (lambda (x) (let ((return-value old-result)) (set! old-result (proc x)) return-value))))) (define (prev proc) (lambda (x) (let ((old-result #f)) (let ((return-value old-result)) (set! old-result (proc x)) return-value)))) (define (prev) (let ((old-result #f)) (lambda (proc) (lambda (x) (let ((return-value old-result)) (set! old-result (proc x)) return-value))))) ; 2nd and third one would work, since we would need to call two lambdas after defining slow square. ; 3rd one won't work and always return #f ; First one **PERFECT** ; TOTAL: 4/4 ; Problem 3 See paper sheet **WRONG** ; Didn't read well enough... ; TOTAL: 0 / 3 ; Problem 4 (define (make-alist! l) (set-car! l (cons (car l) (cadr l))) (if (empty? (cddr l)) l (make-alist! (cdr l)))) **WRONG** ; TOTAL: 2/4 ; Problem 5 ; Suppose there are N students taking a midterm. Suppose we have a vector of size N, ; and each element of the vector represents one student’s score on the midterm. Write a ; procedure (histogram scores) that takes this vector of midterm scores and computes ; a histogram vector. That is, the resulting vector should be of size M+1, where M is the ; maximum score on the midterm (it’s M+1 because scores of zero are possible), and element ; number I of the resulting vector is the number of students who got score I on the midterm. ; For example: ; > (histogram (vector 3 2 2 3 2)) ; #(0 0 3 2) ;; no students got 0 points, no students got 1 point, ; ;; 3 students got 2 points, and 2 students got 3 points. ; > (histogram (vector 0 1 0 2)) ; #(2 1 1) ;; 2 students got 0 points, 1 student got 1 point, ; ;; and 1 student got 2 points. ; Do not use list->vector or vector->list. ; Note: You may assume that you have a procedure vector-max that takes a vector of ; numbers as argument, and returns the largest number in the vector. (define (histogram vec) (define (loop v n max) (if (= n max) v (let ((index (vector-ref vec n))) (begin (vector-set! v index (inc (vector-ref v index))) (loop v (+ 1 n) max))))) (loop (make-vector (+ (max-vector vec) 1)) 0 (vector-length vec))) **PERFECT** ; TOTAL: 7/7 ; Problem 6 ; Choose the answer which best describes each of the following: ; (a) You and a friend decide to have lunch at a rather popular Berkeley resturant. Since ; there is a long line at the service counter, each group of people entering the restaurant ; decide to have someone grab a table while someone else waits in the line to order the food. ; This sounds like a good idea, so your friend sits down at the last free table while you get in ; line. Unfortunately, the resturant stops taking orders when there are no tables available, ; and you have to wait in line for the people ahead of you. This is an example of ; incorrect answer ; deadlock ; inefficency (too much serialization) ; unfairness ; none of the above (correct parallelism) ; (b) After you finally get to eat lunch, you and your friend decide to go to the library to ; work on a joint paper. The library has a policy that students who enter the library must ; open their backpacks to show that they are not bringing food into the library. They have ; several employees doing backpack inspection, so there are several lines for people waiting ; to be inspected. However, today there was a bomb threat, and so the inspectors also use a ; handheld metal detector to examine the backpacks. Although there are several inspectors, ; the library only has one metal detector. This is an example of ; incorrect answer ; deadlock ; inefficency (too much serialization) ; unfairness ; none of the above (correct parallelism) ; (c)While you are working on the paper, your friend decides to do some research for your ; paper and leaves for a few hours while you continue writing. This is an example of ; incorrect answer ; deadlock ; inefficency (too much serialization) ; unfairness ; none of the above (correct parallelism) a. Deadlock **PERFECT** b. inefficency (too much serialization) **PERFECT** c. none of the above (correct parallelism) **PERFECT** ; TOTAL: 3/3 ; Problem 7 (Streams). (define (random-choice a b) (if (zero? (random 2)) a b)) (define over 'OVER) (define under 'UNDER) (define pattern (cons-stream (list (random-choice over under)) (lambda () ((random-choice over under))))) ; TOTAL: 1/3 (good try :D) ; SOLUTION ; (define foo ; (cons-stream '() ; (interleave (stream-map (lambda (p) (cons 'over p)) foo) ; (stream-map (lambda (p) (cons 'under p)) foo)))) ; GRAND TOTAL: 20/30 ; PASSED!
false
5ff3f2241ea5d3c6ef23326f01559de53b65c334
d2fc383d46303bc47223f4e4d59ed925e9b446ce
/courses/2008/fall/330/notes/post-14.ss
548d151a415226efbf40da1eadba5baa789e9865
[]
no_license
jeapostrophe/jeapostrophe.github.com
ce0507abc0bf3de1c513955f234e8f39b60e4d05
48ae350248f33f6ce27be3ce24473e2bd225f6b5
refs/heads/master
2022-09-29T07:38:27.529951
2022-09-22T10:12:04
2022-09-22T10:12:04
3,734,650
14
5
null
2022-03-25T14:33:29
2012-03-16T01:13:09
HTML
UTF-8
Scheme
false
false
16,689
ss
post-14.ss
;; The first three lines of this file were inserted by DrScheme. They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "reader.ss" "plai" "lang") ; Contains the code for the start of lecture 14 (halt-on-errors true) #| <VBCFAE> ::= <num> | {+ <VBCFAE> <VBCFAE>} | {* <VBCFAE> <VBCFAE>} | <id> | {fun {<id>} <VBCFAE>} | {refun {<id>} <VBCFAE>} | {<VBCFAE> <VBCFAE>} | {if0 <VBCFAE> <VBCFAE> <VBCFAE>} | {with {<id> <VBCFAE>} <VBCFAE>} | {newbox <VBCFAE>} | {setbox <VBCFAE> <VBCFAE>} | {openbox <VBCFAE>} | {seqn <VBCFAE> <VBCFAE>} | {set <id> <VBCFAE>} where id is not +, *, fun, if0, with, newbox, setbox, openbox, seqn, set, refun |# (define-type VBCFAE [num (n number?)] [add (lhs VBCFAE?) (rhs VBCFAE?)] [mult (lhs VBCFAE?) (rhs VBCFAE?)] [id (sym symbol?)] [fun (param symbol?) (body VBCFAE?)] [refun (param symbol?) (body VBCFAE?)] [app (fun-expr VBCFAE?) (arg-expr VBCFAE?)] [if0 (test VBCFAE?) (truth VBCFAE?) (else VBCFAE?)] [newbox (init VBCFAE?)] [setbox (box-expr VBCFAE?) (val-expr VBCFAE?)] [openbox (box-expr VBCFAE?)] [seqn (fst VBCFAE?) (snd VBCFAE?)] [set (var symbol?) (val VBCFAE?)]) (define-type VBCFAE-value [numV (n number?)] [boxV (loc number?)] [closureV (param symbol?) (body VBCFAE?) (env Env?)] [reclosureV (param symbol?) (body VBCFAE?) (env Env?)]) ;;;; Environments (define-type Env [mtSub] [aSub (name symbol?) (loc number?) (env Env?)]) ;; env-lookup : symbol env -> number ;; looks up a value in the environment (define (env-lookup name env) (type-case Env env [mtSub () (error 'lookup "no binding for identifier: ~e" name)] [aSub (bound-name bound-loc env) (if (symbol=? bound-name name) bound-loc (env-lookup name env))])) (test/exn (env-lookup 'x (mtSub)) "binding") (test (env-lookup 'x (aSub 'x 5 (mtSub))) 5) (test/exn (env-lookup 'x (aSub 'y 5 (mtSub))) "binding") ;;;; Stores (define-type Store [mtStore] [aStore (loc number?) (value VBCFAE-value?) (sto Store?)]) (define-type ValueXStore [vxs (val VBCFAE-value?) (sto Store?)]) ; next-store-location : store -> number (define (next-store-location sto) (type-case Store sto [mtStore () 0] [aStore (loc val sto) (max (add1 loc) (next-store-location sto))])) ;; store-lookup : number store -> value ;; looks up a value in the store (define (store-lookup loc sto) (type-case Store sto [mtStore () (error 'store-lookup "no binding for loc: ~e" loc)] [aStore (mem-loc mem-val sto) (if (= mem-loc loc) mem-val (store-lookup loc sto))])) (test/exn (store-lookup 5 (mtStore)) "binding") (test (store-lookup 5 (aStore 5 (numV 6) (mtStore))) (numV 6)) (test/exn (store-lookup 5 (aStore 7 (numV 6) (mtStore))) "binding") ;;;; Parsing ;; valid? : sexp -> boolean ;; determines if valid symbol (define (valid? se) (and (symbol? se) (not (member se '(+ * fun if0 with newbox setbox openbox seqn set refun))))) (test (valid? '+) false) (test (valid? '*) false) (test (valid? 'fun) false) (test (valid? 'if0) false) (test (valid? 'with) false) (test (valid? 'newbox) false) (test (valid? 'setbox) false) (test (valid? 'openbox) false) (test (valid? 'seqn) false) (test (valid? 'set) false) (test (valid? 'refun) false) (test (valid? '(x)) false) (test (valid? 'x) true) ;; parse : sexp -> VBCFAE ;; parses into VBCFAE (define (parse se) (match se [(? number?) (num se)] [`(+ ,lhs ,rhs) (add (parse lhs) (parse rhs))] [`(* ,lhs ,rhs) (mult (parse lhs) (parse rhs))] [(? valid?) (id se)] [`(fun (,(and param (? valid?))) ,body) (fun param (parse body))] [`(refun (,(and param (? valid?))) ,body) (refun param (parse body))] [`(if0 ,test ,truth ,else) (if0 (parse test) (parse truth) (parse else))] ; Extra syntax [`(with (,(and id (? valid?)) ,named-expr) ,body) (app (fun id (parse body)) (parse named-expr))] [`(newbox ,init-expr) (newbox (parse init-expr))] [`(setbox ,box-expr ,val-expr) (setbox (parse box-expr) (parse val-expr))] [`(openbox ,box-expr) (openbox (parse box-expr))] [`(seqn ,fst ,snd) (seqn (parse fst) (parse snd))] [`(set ,(and id (? valid?)) ,val-expr) (set id (parse val-expr))] ; This matches earlier cases, so we catch it here. [`(,fun-expr ,arg-expr) (app (parse fun-expr) (parse arg-expr))] [_ (error 'parse "Invalid syntax: ~e" se)])) (test (parse 5) (num 5)) (test (parse '{+ 4 6}) (add (num 4) (num 6))) (test/exn (parse '{+ 4}) "syntax") (test/exn (parse '{+ 4 5 6}) "syntax") (test (parse '{* 4 6}) (mult (num 4) (num 6))) (test/exn (parse '{* 4}) "syntax") (test/exn (parse '{* 4 5 6}) "syntax") (test (parse 'fac) (id 'fac)) (test/exn (parse 'with) "syntax") (test (parse '{fun {x} 5}) (fun 'x (num 5))) (test/exn (parse '{fun {with} 5}) "syntax") (test/exn (parse '{fun {} 5}) "syntax") (test/exn (parse '{fun {x} 5 6}) "syntax") (test (parse '{refun {x} 5}) (refun 'x (num 5))) (test/exn (parse '{refun {with} 5}) "syntax") (test/exn (parse '{refun {} 5}) "syntax") (test/exn (parse '{refun {x} 5 6}) "syntax") (test (parse '{5 6}) (app (num 5) (num 6))) (test/exn (parse '{5}) "syntax") (test/exn (parse '{5 6 7}) "syntax") (test (parse '{if0 1 2 3}) (if0 (num 1) (num 2) (num 3))) (test/exn (parse '{if0 1}) "syntax") (test/exn (parse '{if0 1 2}) "syntax") (test/exn (parse '{if0 1 2 3 4}) "syntax") (test (parse '{with {x 5} 7}) (app (fun 'x (num 7)) (num 5))) (test/exn (parse '{with {x 5} 7 8}) "syntax") (test/exn (parse '{with {x 5 9} 7}) "syntax") (test/exn (parse '{with {with 5} 7}) "syntax") (test/exn (parse '{with {7 5} 7}) "syntax") (test/exn (parse '{with {} 7 8}) "syntax") (test/exn (parse '{with 6}) "syntax") (test (parse '{newbox 5}) (newbox (num 5))) (test/exn (parse '{newbox}) "syntax") (test/exn (parse '{newbox 5 6}) "syntax") (test (parse '{setbox 5 6}) (setbox (num 5) (num 6))) (test/exn (parse '{setbox 5 6 7}) "syntax") (test/exn (parse '{setbox 5}) "syntax") (test/exn (parse '{setbox}) "syntax") (test (parse '{openbox 5}) (openbox (num 5))) (test/exn (parse '{openbox}) "syntax") (test/exn (parse '{openbox 5 6}) "syntax") (test (parse '{seqn 5 6}) (seqn (num 5) (num 6))) (test/exn (parse '{seqn 5 6 7}) "syntax") (test/exn (parse '{seqn 5}) "syntax") (test/exn (parse '{seqn}) "syntax") (test (parse '{set x 5}) (set 'x (num 5))) (test/exn (parse '{set x}) "syntax") (test/exn (parse '{set x 5 6}) "syntax") (test/exn (parse '{set 10 5 6}) "syntax") ;;;; Interpretation ;; num-lift : (num num -> num) -> VBCFAE-value VBCFAE-value -> VBCFAE-value ;; lifts a scheme operator to numVs (define (num-lift op) (lambda (l r) (if (and (numV? l) (numV? r)) (numV (op (numV-n l) (numV-n r))) (error 'num-lift "Cannot operate on non-numbers")))) (define num+ (num-lift +)) (test (num+ (numV 1) (numV 2)) (numV 3)) (test/exn (num+ (closureV 'x (num 5) (mtSub)) (numV 2)) "non-number") (test/exn (num+ (numV 2) (closureV 'x (num 5) (mtSub))) "non-number") (define num* (num-lift *)) (test (num* (numV 1) (numV 2)) (numV 2)) (test/exn (num* (closureV 'x (num 5) (mtSub)) (numV 2)) "non-number") (test/exn (num* (numV 2) (closureV 'x (num 5) (mtSub))) "non-number") ;; num-zero? : VBCFAE-value (only numV) -> boolean ;; lifts zero? to numVs (define (num-zero? v) (if (numV? v) (zero? (numV-n v)) (error 'num-zero? "Given non-number"))) (test (num-zero? (numV 0)) true) (test (num-zero? (numV 1)) false) (test/exn (num-zero? (closureV 'x (num 5) (mtSub))) "non-number") ;; interp : VBCFAE env store -> ValueXStore (define (interp expr env sto) (type-case VBCFAE expr [num (n) (vxs (numV n) sto)] [add (l r) (type-case ValueXStore (interp l env sto) [vxs (lv lsto) (type-case ValueXStore (interp r env lsto) [vxs (rv rsto) (vxs (num+ lv rv) rsto)])])] [mult (l r) (type-case ValueXStore (interp l env sto) [vxs (lv lsto) (type-case ValueXStore (interp r env lsto) [vxs (rv rsto) (vxs (num* lv rv) rsto)])])] [if0 (test truth else) (type-case ValueXStore (interp test env sto) [vxs (tv tsto) (if (num-zero? tv) (interp truth env tsto) (interp else env tsto))])] [id (v) (vxs (store-lookup (env-lookup v env) sto) sto)] [fun (bound-id bound-body) (vxs (closureV bound-id bound-body env) sto)] [refun (bound-id bound-body) (vxs (reclosureV bound-id bound-body env) sto)] [app (fun-expr arg-expr) (type-case ValueXStore (interp fun-expr env sto) [vxs (clos fsto) (cond [(closureV? clos) (type-case ValueXStore (interp arg-expr env fsto) [vxs (arg-val asto) (local [(define arg-loc (next-store-location asto))] (interp (closureV-body clos) (aSub (closureV-param clos) arg-loc (closureV-env clos)) (aStore arg-loc arg-val asto)))])] [(reclosureV? clos) (if (id? arg-expr) (interp (reclosureV-body clos) (aSub (reclosureV-param clos) (env-lookup (id-sym arg-expr) env) (reclosureV-env clos)) fsto) (error 'interp "Applying a refun without an identifier"))] [else (error 'interp "Not a closureV")])])] [seqn (fst-expr snd-expr) (type-case ValueXStore (interp fst-expr env sto) [vxs (fv fsto) (interp snd-expr env fsto)])] [newbox (init-expr) (type-case ValueXStore (interp init-expr env sto) [vxs (init-val sto-after-init) (local [(define new-loc (next-store-location sto-after-init))] (vxs (boxV new-loc) (aStore new-loc init-val sto-after-init)))])] [setbox (box-expr val-expr) (type-case ValueXStore (interp box-expr env sto) [vxs (box-val box-sto) (type-case ValueXStore (interp val-expr env box-sto) [vxs (val-val val-sto) (vxs val-val (aStore (boxV-loc box-val) val-val val-sto))])])] [openbox (box-expr) (type-case ValueXStore (interp box-expr env sto) [vxs (box-val box-sto) (vxs (store-lookup (boxV-loc box-val) box-sto) box-sto)])] [set (var-id val-expr) (type-case ValueXStore (interp val-expr env sto) [vxs (new-val val-sto) (vxs new-val (aStore (env-lookup var-id env) new-val val-sto))])])) ;; top-interp : sexp -> VBCFAE-value (define (top-interp se) (vxs-val (interp (parse se) (mtSub) (mtStore)))) (test (top-interp '5) (numV 5)) (test (top-interp '{fun {x} x}) (closureV 'x (id 'x) (mtSub))) (test (top-interp '{+ 4 5}) (numV 9)) (test/exn (top-interp '{+ 4 {fun {x} x}}) "non-number") (test/exn (top-interp '{+ {fun {x} x} 4}) "non-number") (test (top-interp '{* 4 5}) (numV 20)) (test/exn (top-interp '{* 4 {fun {x} x}}) "non-number") (test/exn (top-interp '{* {fun {x} x} 4}) "non-number") (test (top-interp '(if0 0 1 2)) (numV 1)) (test (top-interp '(if0 1 1 2)) (numV 2)) (test (top-interp '(if0 (+ 1 -1) 1 2)) (numV 1)) (test (top-interp '(if0 (+ 1 1) 1 2)) (numV 2)) (test (vxs-val (interp (parse 'x) (aSub 'x 5 (mtSub)) (aStore 5 (numV 1) (mtStore)))) (numV 1)) (test/exn (top-interp 'x) "binding") (test (top-interp '{{fun {x} x} 5}) (numV 5)) (test (top-interp '{with {x 5} x}) (numV 5)) (test (top-interp '{with {x 5} {fun {y} {+ x y}}}) (closureV 'y (add (id 'x) (id 'y)) (aSub 'x 0 (mtSub)))) (test (top-interp '{with {x 5} {with {x 2} x}}) (numV 2)) (test (top-interp '{with {x 5} {with {y x} y}}) (numV 5)) (test (top-interp '{with {x 5} {with {x {+ x 1}} x}}) (numV 6)) (test/exn (top-interp '{with {fac {fun {n} {if0 n 1 {* n {fac {+ n -1}}}}}} {fac 3}}) "binding") ; Box tests (test (top-interp '{seqn 1 2}) (numV 2)) (test (top-interp '{newbox 1}) (boxV 0)) (test (top-interp '{openbox {newbox 1}}) (numV 1)) (test (top-interp '{setbox {newbox 1} 2}) (numV 2)) (test (top-interp '{with {b {newbox 0}} {seqn {setbox b {+ 1 {openbox b}}} {openbox b}}}) (numV 1)) (test/exn (top-interp '{with {a 5} {seqn {with {b 3} b} b}}) "binding") (test (top-interp '{with {a {newbox 1}} {with {f {fun {y} {+ y {openbox a}}}} {seqn {setbox a 2} {f 10}}}}) (numV 12)) (test (top-interp '{with {b {newbox 0}} {with {increment {fun {dum} {with {old {openbox b}} {seqn {setbox b {+ 1 old}} old}}}} {seqn {increment 0} {+ {increment 0} {seqn {increment 0} {increment 0}}}}}}) (numV 4)) ; Var tests (test/exn (top-interp '{set x 5}) "binding") (test (top-interp '{with {x 4} {set x 5}}) (numV 5)) (test (top-interp '{with {x 4} {seqn {set x 5} x}}) (numV 5)) (test (top-interp '{with {a {newbox 5}} {with {b {newbox 6}} {with {swap {fun {fst-box} {fun {snd-box} {with {tmp {openbox fst-box}} {seqn {setbox fst-box {openbox snd-box}} {setbox snd-box tmp}}}}}} {seqn {{swap a} b} {openbox b}}}}}) (numV 5)) (test (top-interp '{with {a 5} {with {b 6} {with {swap {refun {fst} {refun {snd} {with {tmp fst} {seqn {set fst snd} {set snd tmp}}}}}} {seqn {{swap a} b} b}}}}) (numV 5))
false
5387b900090106c1fb9b4bf4fa39ca01d904c1d2
b49e6c2edc0c5323f326e045c2a9fc769ba74778
/1.3.ss
cbfeaee2f8a5508fdf0f38018e50949c1eda0d97
[]
no_license
plotgeek/SICP
73d0109d37ca5f9ac2e98d847ecf633acb371021
e773a8071ae2fae768846a2b295b5ed96b019f8d
refs/heads/master
2023-03-09T18:50:54.195426
2012-08-14T10:18:59
2012-08-14T10:18:59
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
197
ss
1.3.ss
(define a 6) (define b 7) (define c 5) (define (sum-of-big-two a b c) (cond ((and (> a c) (> b c)) (+ a b)) ((and (> a b) (> c b)) (+ a c)) (else (+ b c)))) (sum-of-big-two a b c)
false
71af6f72395857724a94c800698a957e39a1866d
8a0660bd8d588f94aa429050bb8d32c9cd4290d5
/test/tests/syntax-case.scm
4677c98b7e1bc35da3197635f8e81ed3b58afdd4
[ "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,166
scm
syntax-case.scm
;; -*- mode: scheme; coding: utf-8; -*- (library (issue helper) (export loop-10 define-something symbol bar foo) (import (rnrs)) (define-syntax loop-10 (lambda (x) (syntax-case x () [(k e ...) (with-syntax ([break (datum->syntax #'k 'break)]) #'(call-with-current-continuation (lambda (break) (let f () e ... (f)))))]))) (define-syntax define-something (lambda (x) (syntax-case x (lambda) ((_ (name . formals) body ...) #'(define-something name (lambda formals body ...))) ((_ name (lambda formals body ...)) #'(define name (lambda formals body ...)))))) (define (something) (display 'hoge) (newline)) (define symbol 'symbol) (define (problem) 'ok) (define-syntax bar (lambda (x) (define (dummy) `(,(datum->syntax #'bar 'problem))) (syntax-case x () ((k) (dummy))))) (define-syntax foo (lambda (x) (define (dummy) `(,(datum->syntax #'brrr 'problem))) (syntax-case x () ((k) (dummy))))) ) (library (issue :84) (export doit1 doit2) (import (rnrs) (issue helper)) (define-syntax doit1 (lambda (stx) (define (return) #'symbol) (return))) (define-syntax doit2 (lambda (stx) #'symbol)) ) (import (rnrs) (issue helper) (issue :84) (srfi :64 testing)) ;; from mosh issue 138 (define-syntax doit (lambda (stx) (syntax-case stx () ((_ a b c) (for-all identifier? #'(a b c)) #'(begin 'yes)) (_ #'(begin 'no))))) ;; issue 7 ;; the same as r6rs test suites' syntax-case.sls (define-syntax loop (lambda (x) (syntax-case x () [(k e ...) (with-syntax ([break (datum->syntax #'k 'break)]) #'(call-with-current-continuation (lambda (break) (let f () e ... (f)))))]))) ;; because of the defferent behaviour of macro expander ;; when the expression is in macro such as test-equal, ;; we can not test properly. so put it outside of macro ;; and check the return value. (define (loop-test) (let ((n 3) (ls '())) (loop (if (= n 0) (break ls)) (set! ls (cons 'a ls)) (set! n (- n 1))))) (test-begin "syntax-case issues") (test-equal "doit yes" 'yes (doit x y z)) (test-equal "doit no" 'no (doit x 1 z)) (test-equal "loop" '(a a a) (loop-test)) (test-equal "loop-10" '(a a a) (let ((n 3) (ls '())) (loop-10 (if (= n 0) (break ls)) (set! ls (cons 'a ls)) (set! n (- n 1))))) ;; some more syntax-case related tests (let () (define-syntax loop2 (lambda (x) (syntax-case x () [(k e ...) (with-syntax ([?break (datum->syntax #'k 'break)]) #'(call-with-current-continuation (lambda (?break) (let f () e ... (f)))))]))) (test-equal "loop2" '(a a a) (let ((n 3) (ls '())) (loop (if (= n 0) (break ls)) (set! ls (cons 'a ls)) (set! n (- n 1)))))) ;; issue 25 and 86 (test-equal "issue 25" 'ok (bar)) (test-equal "issue 25" 'ok (foo)) ;; issue 84 (test-equal "doit1" 'symbol (doit1)) (test-equal "doit2" 'symbol (doit2)) ;; issue 85 (let () (define-something (bar) (something)) (test-error "Issue 85" (lambda (e) e) (bar))) ;; issue 87 (let () (define-syntax foo (lambda (x) (syntax-case x () ((_) (let ((ok #''ok)) (define-syntax prob (syntax-rules () ((_) ok))) (prob)))))) (test-equal "issue 87" 'ok (foo)) ) ;; issue 117 (let () (define-syntax include (lambda (x) (syntax-case x () ((k) (datum->syntax #'k '(+ a 1)))))) (define-syntax m (syntax-rules () ((_) (lambda (a) (include))))) (test-equal "issue 117" 3 ((m) 2))) ;; issue 128 (library (A) (export def) (import (rnrs)) (define-syntax def (lambda (x) (syntax-case x () ((_ name) #'(define-syntax name (lambda (z) (syntax-case z () ((_ a b) #'(name a)) ((_ a) #'a)))))))) ) (library (B) (export foo) (import (A) (only (sagittarius) %macroexpand) (sagittarius compiler) (pp)) (def foo) ) (import (B)) (test-equal "issue 128" 1 (foo 1)) (test-end)
true
3d6d6f4b1fb0beb5b32c16bf30435217a00234b7
074658682ac27f14d7c1ebf78bf070662012f698
/ds.scm
ac1bcfaabc66a02b6ae5b728759486b235014045
[ "MIT" ]
permissive
triffon/fp-2016-17
dc27b266c891b6d1f81d27e0ab51e727d5fbafbe
553112c19f22169f867b5d3159ccd45f88d60ac5
refs/heads/master
2021-01-11T05:29:18.297824
2017-01-19T09:05:00
2017-01-23T22:27:35
71,508,093
2
0
null
null
null
null
UTF-8
Scheme
false
false
121
scm
ds.scm
(map list '(1 2 3) '(4 5 6) '(7 8 9)) (define m '((1 2 3) (4 5 6) (7 8 9))) (define (transpose m) (apply map list m))
false
e5d407dd37d6fb7d1a1d312832e5692ab38b32c2
84bd214ba2422524b8d7738fb82dd1b3e2951f73
/chapter_1/examples/1.1.7_sqr_by_newton_method/sqrbn.scm
1e7c8d9b4c0f7e69b5cda69f8c0ea4fd381e0634
[]
no_license
aequanimitas/sicp-redux
e5ef32529fa727de0353da973425a326e152c388
560b2bd40a12df245a8532de5d76b0bd2e033a64
refs/heads/master
2020-04-10T06:49:13.302600
2016-03-15T00:59:24
2016-03-15T00:59:24
21,434,389
1
0
null
null
null
null
UTF-8
Scheme
false
false
528
scm
sqrbn.scm
(define (better-guess guess x) (/ (+ guess (/ x guess)) 2)) ; assume that 1 is the square root of all numbers' ; using decimal here (1.0) ensures us that all rational numbers yield to decimal ones ; though I know there's a lib to enforce evaluation in decimal (define (start x) (sqrtn 1.0 x)) (define (good-enough? guess radicand) (< (abs (- (* guess guess) radicand)) 0.001)) (define (sqrtn guess radicand) (if (good-enough? guess radicand) guess (sqrtn (better-guess guess radicand) radicand))) (start 9)
false
36e0ca1a1594caf6a032993db6ab552722dbf856
a2c4df92ef1d8877d7476ee40a73f8b3da08cf81
/ch04-7.scm
ae4e7af13c291e0060b72657f6c2694b1b4249cf
[]
no_license
naoyat/reading-paip
959d0ec42b86bc01fe81dcc3589e3182e92a05d9
739fde75073af36567fcbdf3ee97e221b0f87c8a
refs/heads/master
2020-05-20T04:56:17.375890
2009-04-21T20:01:01
2009-04-21T20:01:01
176,530
1
0
null
null
null
null
UTF-8
Scheme
false
false
4,194
scm
ch04-7.scm
(require "./cl-emu") (require "./debug") (use srfi-1) (use slib) (require 'trace) ;(define (subsetp list1 list2) (lset<= eq? list1 list2)) ;(define *state* '()) ; The Current state: a list of conditions. ;(define *ops* '()) ; A list of available operators. (define-class <op> () ; An operation ((action :init-keyword :action :init-value '()) (preconds :init-keyword :preconds :init-value '()) (add-list :init-keyword :add-list :init-value '()) (del-list :init-keyword :del-list :init-value '()) )) (define (GPS state goals ops) ;; General Problem Solver: achieve all goals using ops. (define (achieve goal) ;; A goal is achieved if it already holds, ;; or if there is an appropriate op for it that is applicable. #;(format #t "[achieve] goal:~a state:~a // ~a || ~a => ~a\n" goal state (member goal state) (map (cut slot-ref <> 'action) (filter (cut appropriate? goal <>) ops)) (any apply-op (filter (cut appropriate? goal <>) ops)) ) (dbg :gps "The current goal is ~a" goal) (or (member goal state) (any apply-op (filter (cut appropriate? goal <>) ops)))) (define (appropriate? goal op) ;; An op is appropriate to a goal if it is in its add list. #;(format #t "[appropriate?] goal:~a op:~a // ~a\n" goal (slot-ref op 'action) (member goal (slot-ref op 'add-list)) ) (member goal (slot-ref op 'add-list))) (define (achieve-all goals) ;; Try to achieve each goal, then make sure they still hold. (and (every achieve goals) (subsetp goals state))) (define (apply-op op) ;; Print a message and update state if op is applicable. #;(format #t "[apply-op] op:~a => ~a\n" (slot-ref op 'action) ;(slot-ref op 'preconds) (every achieve (slot-ref op 'preconds)) ) (if (achieve-all (slot-ref op 'preconds));(every achieve (slot-ref op 'preconds)) (begin (print (list 'executing (slot-ref op 'action))) #;(format #t " state:~a" state) (set! state (lset-difference eq? state (slot-ref op 'del-list))) (set! state (lset-union eq? state (slot-ref op 'add-list))) #;(format #t " => ~a\n" state) #t) #f)) ;;(trace achieve) (print "================") (if (achieve-all goals);;(every achieve goals) (begin (print "solved.") 'solved) (begin (print "NIL") #f))) (define *school-ops* (list (make <op> :action 'drive-son-to-school :preconds '(son-at-home car-works) :add-list '(son-at-school) :del-list '(son-at-home)) (make <op> :action 'shop-installs-battery :preconds '(car-needs-battery shop-knows-problem shop-has-money) :add-list '(car-works)) (make <op> :action 'tell-shop-problem :preconds '(in-communication-with-shop) :add-list '(shop-knows-problem)) (make <op> :action 'telephone-shop :preconds '(know-phone-number) :add-list '(in-communication-with-shop)) (make <op> :action 'look-up-number :preconds '(have-phone-book) :add-list '(know-phone-number)) (make <op> :action 'give-shop-money :preconds '(have-money) :add-list '(shop-has-money) :del-list '(have-money)) )) #| (GPS '(son-at-home car-needs-battery have-money have-phone-book) '(son-at-school) *school-ops*) (GPS '(son-at-home car-needs-battery have-money) '(son-at-school) *school-ops*) (GPS '(son-at-home car-works) '(son-at-school) *school-ops*) ;;; (GPS '(son-at-home have-money car-works) '(have-money son-at-school) *school-ops*) ; must fail => 4.7 (GPS '(son-at-home car-needs-battery have-money have-phone-book) '(have-money son-at-school) *school-ops*) (GPS '(son-at-home car-needs-battery have-money have-phone-book) '(son-at-school have-money) *school-ops*) ;|# ;; 4.9 (push! *school-ops* (make <op> :action 'ask-phone-number :preconds '(in-communication-with-shop) :add-list '(know-phone-number))) ;(trace achieve) ;(debug :gps) #| (GPS '(son-at-home car-needs-battery have-money) '(son-at-school) *school-ops*) |#
false
2633f32c2f987f28f8bd323ba9ea1f4fe50b0c37
5bbc152058cea0c50b84216be04650fa8837a94b
/pre-benchmark/htdp/base/Images/list-boxes.ss
ba47539b751db1b9bf2918792df12e07e0f0a944
[]
no_license
nuprl/gradual-typing-performance
2abd696cc90b05f19ee0432fb47ca7fab4b65808
35442b3221299a9cadba6810573007736b0d65d4
refs/heads/master
2021-01-18T15:10:01.739413
2018-12-15T18:44:28
2018-12-15T18:44:28
27,730,565
11
3
null
2018-12-01T13:54:08
2014-12-08T19:15:22
Racket
UTF-8
Scheme
false
false
1,445
ss
list-boxes.ss
#lang slideshow (require "box-diagram.ss" "write.ss") (define (b) (cc-superimpose (disk 5) (text " ") (blank 30 10))) (define mbullet (b)) (define vbullet (b)) (define mercury (struct-pict "cons" `(("first" "\"Mercury\"") ("rest" "empty")))) (define venus (struct-pict "cons" `(("first" "\"Venus\"") ("rest" ,mbullet)))) (define earth (struct-pict "cons" `(("first" "\"Earth\"") ("rest" ,vbullet)))) (define delta 50) (define (all mercury venus earth) (let* ([blk (blank 10 1)] [all (hb-append mercury blk venus blk earth)] [wdt (pict-width all)] [hgt (pict-height all)]) (cc-superimpose (blank (+ wdt delta) (+ hgt delta)) all))) (define right-to-left (all mercury venus earth)) (define left-to-right (all earth venus mercury)) (define (connect base from to rb-find delta) (define (f base p) (define-values (x y) (rb-find base p)) (values (+ x delta) y)) (pin-arrow-line 5 base from cc-find to f ; rb-find #:start-angle (* -2/4 pi) #:start-pull 1/2 #:end-angle (* 2/4 pi))) (write-pict "list-boxes" (let* ([one (connect right-to-left mbullet mercury rb-find -10)]) (connect one vbullet venus rb-find -10))) (write-pict "list-boxes2" (let* ([one (connect left-to-right mbullet mercury lb-find +10)]) (connect one vbullet venus lb-find +10)))
false
5c276034f3096316dbbdf1c80c9bdc582afe0e7a
c38f6404e86123560ae8c9b38f7de6b66e30f1c4
/slatex/slatex-src.scm
767d4a0725e2bff8f6ffc9260191e5acff2db703
[ "LicenseRef-scancode-warranty-disclaimer", "CC-BY-4.0" ]
permissive
webyrd/dissertation-single-spaced
efeff4346d0c0e506e671c07bfc54820ed95a307
577b8d925b4216a23837547c47fb4d695fcd5a55
refs/heads/master
2023-08-05T22:58:25.105388
2018-12-30T02:11:58
2018-12-30T02:11:58
26,194,521
57
4
null
2018-08-09T09:21:03
2014-11-05T00:00:40
TeX
UTF-8
Scheme
false
false
72,271
scm
slatex-src.scm
;slatex.scm ;SLaTeX v. 2.4z ;(c) Dorai SItaram, 1991-2002 (define *slatex-version* "20090928") ;last modified (define *operating-system* (if (getenv "COMSPEC") 'windows 'unix)) (define-syntax defenum (lambda (so) (datum->syntax so (let ((so-d (syntax->datum so))) (let loop ((z (cdr so-d)) (i 0) (r '())) (if (null? z) `(begin ,@r) (loop (cdr z) (+ i 1) (cons `(define ,(car z) (integer->char ,i)) r)))))))) (define-syntax defrecord (lambda (so) (datum->syntax so (let ((so-d (syntax->datum so))) (let ((name (cadr so-d)) (fields (cddr so-d))) (let loop ((fields fields) (i 0) (r '())) (if (null? fields) `(begin (define ,name (lambda () (make-vector ,i))) ,@r) (loop (cdr fields) (+ i 1) (cons `(define ,(car fields) ,i) r))))))))) (define-syntax setf (lambda (so) (datum->syntax so (let ((so-d (syntax->datum so))) (let ((l (cadr so-d)) (r (caddr so-d))) (if (symbol? l) `(set! ,l ,r) (let ((a (car l))) (if (eq? a 'list-ref) `(set-car! (list-tail ,@(cdr l)) ,r) `(,(cond ((eq? a 'string-ref) 'string-set!) ((eq? a 'vector-ref) 'vector-set!) ((eq? a 'of) 'the-setter-for-of) (else (slatex-error "setf is ill-formed" l r))) ,@(cdr l) ,r))))))))) (define-syntax the-setter-for-of (lambda (so) (datum->syntax so (let ((so-d (syntax->datum so))) (let ((r (cadr so-d)) (i (caddr so-d)) (j (cadddr so-d)) (z (cddddr so-d))) (cond ((null? z) `(vector-set! ,r ,i ,j)) ((and (eq? i '/) (= (length z) 1)) `(string-set! ,r ,j ,(car z))) (else `(the-setter-for-of (vector-ref ,r ,i) ,j ,@z)))))))) (define-syntax of (lambda (so) (datum->syntax so (let ((so-d (syntax->datum so))) (let ((r (cadr so-d)) (i (caddr so-d)) (z (cdddr so-d))) (cond ((null? z) `(vector-ref ,r ,i)) ((and (eq? i '/) (= (length z) 1)) `(string-ref ,r ,(car z))) (else `(of (vector-ref ,r ,i) ,@z)))))))) ;s4.scm ;seqprocs.scm (define ormapcdr (lambda (f l) ;;apply f to successive cdrs of l, returning ;;immediately when an application is true. ;;only one argument list supported (let loop ((l l)) (if (null? l) #f (or (f l) (loop (cdr l))))))) (define list-prefix? (lambda (pfx l) ;;tests if list pfx is a prefix of list l (cond ((null? pfx) #t) ((null? l) #f) ((eqv? (car pfx) (car l)) (list-prefix? (cdr pfx) (cdr l))) (else #f)))) (define string-suffix? (lambda (sfx s) ;;tests if string sfx is a suffix of string s (let ((sfx-len (string-length sfx)) (s-len (string-length s))) (if (> sfx-len s-len) #f (let loop ((i (- sfx-len 1)) (j (- s-len 1))) (if (< i 0) #t (and (char=? (string-ref sfx i) (string-ref s j)) (loop (- i 1) (- j 1))))))))) (define mapcan (lambda (f l) ;;maps f on l but splices (destructively) the results; ;;only one argument list supported (let loop ((l l)) (if (null? l) '() (append! (f (car l)) (loop (cdr l))))))) (define lassoc (lambda (x al eq) (let loop ((al al)) (if (null? al) #f (let ((c (car al))) (if (eq (car c) x) c (loop (cdr al)))))))) (define lmember (lambda (x l eq) (let loop ((l l)) (if (null? l) #f (if (eq (car l) x) l (loop (cdr l))))))) (define delete (lambda (x l eq) (let loop ((l l)) (cond ((null? l) l) ((eq (car l) x) (loop (cdr l))) (else (set-cdr! l (loop (cdr l))) l))))) (define adjoin (lambda (x l eq) (if (lmember x l eq) l (cons x l)))) (define delete-if (lambda (p s) (let loop ((s s)) (cond ((null? s) s) ((p (car s)) (loop (cdr s))) (else (set-cdr! s (loop (cdr s))) s))))) (define string-prefix? (lambda (s1 s2 i) ;Tests if s1 and s2 have the same first i chars. ;Both s1 and s2 must be at least i long. (let loop ((j 0)) (if (= j i) #t (and (char=? (string-ref s1 j) (string-ref s2 j)) (loop (+ j 1))))))) (define sublist (lambda (l i f) ;;finds the sublist of l from index i inclusive to index f exclusive (let loop ((l (list-tail l i)) (k i) (r '())) (cond ((>= k f) (reverse! r)) ((null? l) (slatex-error "sublist: List too small")) (else (loop (cdr l) (+ k 1) (cons (car l) r))))))) (define position-char (lambda (c l) ;;finds the leftmost index of character-list l where character c occurs (let loop ((l l) (i 0)) (cond ((null? l) #f) ((char=? (car l) c) i) (else (loop (cdr l) (+ i 1))))))) (define string-position-right (lambda (c s) ;finds the rightmost index of string s where character c occurs (let ((n (string-length s))) (let loop ((i (- n 1))) (cond ((< i 0) #f) ((char=? (string-ref s i) c) i) (else (loop (- i 1)))))))) ;fileproc.scm ;lerror.scm (define *return* (integer->char 13)) (define *tab* (integer->char 9)) (define slatex-error (lambda (where . what) (display "Error: ") (display where) (newline) (for-each (lambda (v) (write v) (newline)) what) (error "slatex-error"))) (define exit-slatex (lambda () ;in case it's a macro (exit))) ;defaults.scm (define *slatex-case-sensitive?* #t) (define keyword-tokens (list ;;RnRS (plus some additional Scheme) keywords "=>" "%" "abort" "and" "begin" "begin0" "case" "case-lambda" "cond" "define" "define!" "define-macro!" "define-syntax" "defmacro" "defrec!" "delay" "do" "else" "extend-syntax" "fluid-let" "if" "lambda" "let" "let*" "letrec" "let-syntax" "letrec-syntax" "or" "quasiquote" "quote" "rec" "record-case" "record-evcase" "recur" "set!" "sigma" "struct" "syntax" "syntax-rules" "trace" "trace-lambda" "trace-let" "trace-recur" "unless" "unquote" "unquote-splicing" "untrace" "when" "with" )) (define variable-tokens '()) (define constant-tokens '()) (define data-tokens '()) (define special-symbols (reverse (reverse '( ("." . ".") ("..." . "{\\dots}") ("-" . "$-$") ("1-" . "\\va{1$-$}") ("-1+" . "\\va{$-$1$+$}") )))) (define macro-definers '("define-syntax" "syntax-rules" "defmacro" "extend-syntax" "define-macro!")) (define case-and-ilk '("case" "record-case")) (define tex-analog (lambda (c) ;find a TeX string that corresponds to the character c (case c ((#\$ #\& #\% #\# #\_) (string #\\ c)) ;((#\#) "{\\sf\\#}") ;((#\\) "{\\ttbackslash}") ((#\{ #\}) (string #\$ #\\ c #\$)) ((#\\) "$\\backslash$") ((#\+) "$+$") ((#\*) "$\\ast$") ((#\=) "$=$") ((#\<) "$\\lt$") ((#\>) "$\\gt$") ((#\^) "\\^{}") ((#\|) "$\\vert$") ;((#\~) "\\verb-~-") ((#\~) "\\~{}") ((#\@) "{\\atsign}") ((#\") "{\\dq}") (else (string c))))) (define token=? (lambda (t1 t2) ;tests if t1 and t2 are identical tokens ((if *slatex-case-sensitive?* string=? string-ci=?) t1 t2))) (define *slatex-enabled?* #t) (define *slatex-reenabler* "UNDEFINED") (define *intext-triggerers* (list "scheme")) (define *resultintext-triggerers* (list "schemeresult")) (define *display-triggerers* (list "schemedisplay")) (define *response-triggerers* (list "schemeresponse")) (define *respbox-triggerers* (list "schemeresponsebox")) (define *box-triggerers* (list "schemebox")) (define *topbox-triggerers* (list "schemetopbox")) (define *input-triggerers* (list "schemeinput")) (define *region-triggerers* (list "schemeregion")) (define *math-triggerers* '()) (define *slatex-in-protected-region?* #f) (define *protected-files* '()) (define *include-onlys* 'all) (define *latex?* #t) (define *slatex-separate-includes?* #f) (define *tex-calling-directory* "") ;structs.scm (define *max-line-length* 300) (defenum ;possible values of =space &void-space &plain-space &init-space &init-plain-space &paren-space &bracket-space &quote-space &inner-space) (defenum ;possible values of =tab &void-tab &set-tab &move-tab &tabbed-crg-ret &plain-crg-ret) (defenum ;possible values of =notab &void-notab &begin-comment &mid-comment &begin-string &mid-string &end-string &begin-math &mid-math &end-math) (defrecord make-raw-line =rtedge =char =space =tab =notab) (define make-line (lambda () ;makes a "line" record (let ((l (make-raw-line))) (setf (of l =rtedge) 0) (setf (of l =char) (make-string *max-line-length* #\space)) (setf (of l =space) (make-string *max-line-length* &void-space)) (setf (of l =tab) (make-string *max-line-length* &void-tab)) (setf (of l =notab) (make-string *max-line-length* &void-notab)) l))) (define *line1* (make-line)) (define *line2* (make-line)) (defrecord make-case-frame =in-ctag-tkn =in-bktd-ctag-exp =in-case-exp) (defrecord make-bq-frame =in-comma =in-bq-tkn =in-bktd-bq-exp) (define *latex-paragraph-mode?* 'fwd1) (define *intext?* 'fwd2) (define *code-env-spec* "UNDEFINED") (define *in* 'fwd3) (define *out* 'fwd4) (define *in-qtd-tkn* 'fwd5) (define *in-bktd-qtd-exp* 'fwd6) (define *in-mac-tkn* 'fwd7) (define *in-bktd-mac-exp* 'fwd8) (define *case-stack* 'fwd9) (define *bq-stack* 'fwd10) (define display-space (lambda (s p) (cond ((eq? s &plain-space) (display #\space p)) ((eq? s &init-plain-space) (display #\space p)) ((eq? s &init-space) (display "\\HL " p)) ((eq? s &paren-space) (display "\\PRN " p)) ((eq? s &bracket-space) (display "\\BKT " p)) ((eq? s &quote-space) (display "\\QUO " p)) ((eq? s &inner-space) (display "\\ " p))))) (define display-tab (lambda (tab p) (cond ((eq? tab &set-tab) (display "\\=" p)) ((eq? tab &move-tab) (display "\\>" p))))) (define display-notab (lambda (notab p) (cond ((eq? notab &begin-string) (display "\\dt{" p)) ((eq? notab &end-string) (display "}" p))))) ;helpers.scm (define prim-data-token? (lambda (token) ;token cannot be empty string! (or (char=? (string-ref token 0) #\#) (string->number token)))) (define set-keyword (lambda (x) ;add token x to the keyword database (if (not (lmember x keyword-tokens token=?)) (begin (set! constant-tokens (delete x constant-tokens token=?)) (set! variable-tokens (delete x variable-tokens token=?)) (set! data-tokens (delete x data-tokens token=?)) (set! keyword-tokens (cons x keyword-tokens)))))) (define set-constant (lambda (x) ;;add token x to the constant database (if (not (lmember x constant-tokens token=?)) (begin (set! keyword-tokens (delete x keyword-tokens token=?)) (set! variable-tokens (delete x variable-tokens token=?)) (set! data-tokens (delete x data-tokens token=?)) (set! constant-tokens (cons x constant-tokens)))))) (define set-variable (lambda (x) ;;add token x to the variable database (if (not (lmember x variable-tokens token=?)) (begin (set! keyword-tokens (delete x keyword-tokens token=?)) (set! constant-tokens (delete x constant-tokens token=?)) (set! data-tokens (delete x data-tokens token=?)) (set! variable-tokens (cons x variable-tokens)))))) (define set-data (lambda (x) ;;add token x to the "data" database (if (not (lmember x data-tokens token=?)) (begin (set! keyword-tokens (delete x keyword-tokens token=?)) (set! constant-tokens (delete x constant-tokens token=?)) (set! variable-tokens (delete x variable-tokens token=?)) (set! data-tokens (cons x data-tokens)))))) (define set-special-symbol (lambda (x transl) ;;add token x to the special-symbol database with ;;the translation transl (let ((c (lassoc x special-symbols token=?))) (if c (set-cdr! c transl) (set! special-symbols (cons (cons x transl) special-symbols)))))) (define unset-special-symbol (lambda (x) ;disable token x's special-symbol-hood (set! special-symbols (delete-if (lambda (c) (token=? (car c) x)) special-symbols)))) (define texify (lambda (s) ;create a tex-suitable string out of token s (list->string (texify-aux s)))) (define texify-data (lambda (s) ;;create a tex-suitable string out of the data token s (let loop ((l (texify-aux s)) (r '())) (if (null? l) (list->string (reverse! r)) (let ((c (car l))) (loop (cdr l) (if (char=? c #\-) (append! (list #\$ c #\$) r) (cons c r)))))))) (define texify-aux (let ((arrow (string->list "-$>$")) (em-dash (string->list "---")) (en-dash (string->list "--")) (arrow2 (string->list "$\\to$")) (em-dash-2 (string->list "${-}{-}{-}$")) (en-dash-2 (string->list "${-}{-}$"))) (lambda (s) ;;return the list of tex characters corresponding to token s. ;;perhaps some extra context-sensitive prettifying ;;could go in the making of texified-sl below (let ((texified-sl (mapcan (lambda (c) (string->list (tex-analog c))) (string->list s)))) (let loop ((d texified-sl)) ;;cdr down texified-sl ;;to transform any character combinations ;;as desired (cond ((null? d) #f) ((list-prefix? arrow d) ; $->$ (let ((d2 (list-tail d 4))) (set-car! d (car arrow2)) (set-cdr! d (append (cdr arrow2) d2)) (loop d2))) ((list-prefix? em-dash d) ; --- (let ((d2 (list-tail d 3))) (set-car! d (car em-dash-2)) (set-cdr! d (append (cdr em-dash-2) d2)) (loop d2))) ((list-prefix? en-dash d) ; -- (let ((d2 (list-tail d 2))) (set-car! d (car en-dash-2)) (set-cdr! d (append (cdr en-dash-2) d2)) (loop d2))) (else (loop (cdr d))))) texified-sl)))) (define display-begin-sequence (lambda (out) (if (or *intext?* (not *latex?*)) (begin (display "\\" out) (display *code-env-spec* out) (newline out)) (begin (display "\\begin{" out) (display *code-env-spec* out) (display "}%" out) (newline out))))) (define display-end-sequence (lambda (out) (cond (*intext?* ;(or *intext?* (not *latex?*)) (display "\\end" out) (display *code-env-spec* out) ;;(display "{}" out) (newline out)) (*latex?* (display "\\end{" out) (display *code-env-spec* out) (display "}" out) (newline out)) (else (display "\\end" out) (display *code-env-spec* out) (newline out))))) (define display-tex-char (lambda (c p) (display (if (char? c) (tex-analog c) c) p))) (define display-token (lambda (s typ p) (cond ((eq? typ 'syntax) (display "\\sy{" p) (display (texify s) p) (display "}" p)) ((eq? typ 'variable) (display "\\va{" p) (display (texify s) p) (display "}" p)) ((eq? typ 'constant) (display "\\cn{" p) (display (texify s) p) (display "}" p)) ((eq? typ 'data) (display "\\dt{" p) (display (texify-data s) p) (display "}" p)) (else (slatex-error 'display-token "Unknown token type" typ))))) ;peephole.scm (define get-line (let ((curr-notab &void-notab)) (lambda (line) ;;read the current tex line into "line"; ;;returns false on eof (let ((graphic-char-seen? #f)) (let loop ((i 0)) (let ((c (read-char *in*))) (cond (graphic-char-seen? (void)) ((or (eof-object? c) (char=? c *return*) (char=? c #\newline) (char=? c #\space) (char=? c *tab*)) (void)) (else (set! graphic-char-seen? #t))) (cond ((eof-object? c) (cond ((eq? curr-notab &mid-string) (if (> i 0) (setf (of line =notab / (- i 1)) &end-string))) ((eq? curr-notab &mid-comment) (set! curr-notab &void-notab)) ((eq? curr-notab &mid-math) (slatex-error 'get-line "Found eof inside math"))) (setf (of line =char / i) #\newline) (setf (of line =space / i) &void-space) (setf (of line =tab / i) &void-tab) (setf (of line =notab / i) &void-notab) (setf (of line =rtedge) i) (if (eq? (of line =notab / 0) &mid-string) (setf (of line =notab / 0) &begin-string)) (if (= i 0) #f #t)) ((or (char=? c *return*) (char=? c #\newline)) (if (and (memv *operating-system* '(dos windows os2 os2fat)) (char=? c *return*)) (if (char=? (peek-char *in*) #\newline) (read-char *in*))) (setf (of line =notab / i) &void-notab) (cond ((eq? curr-notab &mid-string) (setf (of line =notab / i) &end-string)) ((eq? curr-notab &mid-comment) (set! curr-notab &void-notab)) ((eq? curr-notab &mid-math) (slatex-error 'get-line "Sorry, you can't split " "math formulas across lines in Scheme code"))) (setf (of line =char / i) #\newline) (setf (of line =space / i) &void-space) (setf (of line =tab / i) (cond ((eof-object? (peek-char *in*)) &plain-crg-ret) (*intext?* &plain-crg-ret) (else &tabbed-crg-ret))) ;;(setf (of line =notab / i) &void-notab) (setf (of line =rtedge) i) (if (eq? (of line =notab / 0) &mid-string) (setf (of line =notab / 0) &begin-string)) #t) ((eq? curr-notab &mid-comment) (setf (of line =char / i) c) (setf (of line =space / i) (cond ((char=? c #\space) &plain-space) ((char=? c *tab*) &plain-space) (else &void-space))) (setf (of line =tab / i) &void-tab) (setf (of line =notab / i) &mid-comment) (loop (+ i 1))) ((char=? c #\\) (setf (of line =char / i) c) (setf (of line =space / i) &void-space) (setf (of line =tab / i) &void-tab) (setf (of line =notab / i) curr-notab) (let ((i+1 (+ i 1)) (c+1 (read-char *in*))) (if (char=? c+1 *tab*) (set! c+1 #\space)) (setf (of line =char / i+1) c+1) (setf (of line =space / i+1) (if (char=? c+1 #\space) &plain-space &void-space)) (setf (of line =tab / i+1) &void-tab) (setf (of line =notab / i+1) curr-notab) (loop (+ i+1 1)))) ((eq? curr-notab &mid-math) (if (char=? c *tab*) (set! c #\space)) (setf (of line =space / i) (if (char=? c #\space) &plain-space &void-space)) (setf (of line =tab / i) &void-tab) (cond ((memv c *math-triggerers*) (setf (of line =char / i) #\$) (setf (of line =notab / i) &end-math) (setf curr-notab &void-notab)) (else (setf (of line =char / i) c) (setf (of line =notab / i) &mid-math))) (loop (+ i 1))) ((eq? curr-notab &mid-string) (if (char=? c *tab*) (set! c #\space)) ;;or should tab and space be treated differently? (setf (of line =char / i) c) (setf (of line =space / i) (if (char=? c #\space) &inner-space &void-space)) (setf (of line =tab / i) &void-tab) (setf (of line =notab / i) (cond ((char=? c #\") (set! curr-notab &void-notab) &end-string) (else &mid-string))) (loop (+ i 1))) ;;henceforth curr-notab is &void-notab ((char=? c #\space) (setf (of line =char / i) c) (setf (of line =space / i) (cond (*intext?* &plain-space) (graphic-char-seen? &inner-space) (else &init-space))) (setf (of line =tab / i) &void-tab) (setf (of line =notab / i) &void-notab) (loop (+ i 1))) ((char=? c *tab*) (let loop1 ((i i) (j 0)) (if (< j 8) (begin (setf (of line =char / i) #\space) (setf (of line =space / i) (cond (*intext?* &plain-space) (graphic-char-seen? &inner-space) (else &init-space))) (setf (of line =tab / i) &void-tab) (setf (of line =notab / i) &void-notab) (loop1 (+ i 1) (+ j 1))))) (loop (+ i 8))) ((char=? c #\") (setf (of line =char / i) c) (setf (of line =space / i) &void-space) (setf (of line =tab / i) &void-tab) (setf (of line =notab / i) &begin-string) (set! curr-notab &mid-string) (loop (+ i 1))) ((char=? c #\;) (setf (of line =char / i) c) (setf (of line =space / i) &void-space) (setf (of line =tab / i) &void-tab) (setf (of line =notab / i) &begin-comment) (set! curr-notab &mid-comment) (loop (+ i 1))) ((memv c *math-triggerers*) (setf (of line =char / i) #\$) (setf (of line =space / i) &void-space) (setf (of line =tab / i) &void-tab) (setf (of line =notab / i) &begin-math) (set! curr-notab &mid-math) (loop (+ i 1))) (else (setf (of line =char / i) c) (setf (of line =space / i) &void-space) (setf (of line =tab / i) &void-tab) (setf (of line =notab / i) &void-notab) (loop (+ i 1)))))))))) (define peephole-adjust (lambda (curr prev) ;;adjust the tabbing information on the current line curr and ;;its previous line prev relative to each other (if (or (blank-line? curr) (flush-comment-line? curr)) (if (not *latex-paragraph-mode?*) (begin (set! *latex-paragraph-mode?* #t) (if (not *intext?*) (begin (remove-some-tabs prev 0) (let ((prev-rtedge (of prev =rtedge))) (if (eq? (of prev =tab / prev-rtedge) &tabbed-crg-ret) (setf (of prev =tab / (of prev =rtedge)) &plain-crg-ret))))))) (begin (if *latex-paragraph-mode?* (set! *latex-paragraph-mode?* #f) (if (not *intext?*) (let ((remove-tabs-from #f)) (let loop ((i 0)) (cond ((char=? (of curr =char / i) #\newline) (set! remove-tabs-from i)) ((char=? (of prev =char / i) #\newline) (set! remove-tabs-from #f)) ((eq? (of curr =space / i) &init-space) ;eating initial space of curr (if (eq? (of prev =notab / i) &void-notab) (begin (cond ((or (char=? (of prev =char / i) #\() (eq? (of prev =space / i) &paren-space)) (setf (of curr =space / i) &paren-space)) ((or (char=? (of prev =char / i) #\[) (eq? (of prev =space / i) &bracket-space)) (setf (of curr =space / i) &bracket-space)) ((or (memv (of prev =char / i) '(#\' #\` #\,)) (eq? (of prev =space / i) &quote-space)) (setf (of curr =space / i) &quote-space))) (if (memq (of prev =tab / i) (list &set-tab &move-tab)) (setf (of curr =tab / i) &move-tab)))) (loop (+ i 1))) ;;finished tackling &init-spaces of curr ((= i 0) ;curr starts left-flush (set! remove-tabs-from 0)) ;;at this stage, curr[notab,i] ;;is either #f or a &begin-comment/string ((not (eq? (of prev =tab / i) &void-tab)) ;;curr starts with nice alignment with prev (set! remove-tabs-from (+ i 1)) (if (memq (of prev =tab / i) (list &set-tab &move-tab)) (setf (of curr =tab / i) &move-tab))) ((memq (of prev =space / i) (list &init-space &init-plain-space &paren-space &bracket-space &quote-space)) ;curr starts while prev is still empty (set! remove-tabs-from (+ i 1))) ((and (char=? (of prev =char / (- i 1)) #\space) (eq? (of prev =notab / (- i 1)) &void-notab)) ;;curr can induce new alignment straightaway (set! remove-tabs-from (+ i 1)) (setf (of prev =tab / i) &set-tab) (setf (of curr =tab / i) &move-tab)) (else ;;curr stakes its &move-tab (modulo parens/bkts) ;;and induces prev to have corresp &set-tab (set! remove-tabs-from (+ i 1)) (let loop1 ((j (- i 1))) (cond ((<= j 0) 'exit-loop1) ((not (eq? (of curr =tab / j) &void-tab)) 'exit-loop1) ((memq (of curr =space / j) (list &paren-space &bracket-space &quote-space)) (loop1 (- j 1))) ((or (not (eq? (of prev =notab / j) &void-notab)) (char=? (of prev =char / j) #\space)) (let ((k (+ j 1))) (if (not (memq (of prev =notab / k) (list &mid-comment &mid-math &end-math &mid-string &end-string))) (begin (if (eq? (of prev =tab / k) &void-tab) (setf (of prev =tab / k) &set-tab)) (setf (of curr =tab / k) &move-tab))))) (else 'anything-else?) ))))) (remove-some-tabs prev remove-tabs-from)))) (if (not *intext?*) (add-some-tabs curr)) (clean-init-spaces curr) (clean-inner-spaces curr))))) (define add-some-tabs (lambda (line) ;;add some tabs in the body of line "line" so the next line ;;can exploit them (let loop ((i 1) (succ-parens? #f)) (let ((c (of line =char / i))) (cond ((char=? c #\newline) 'exit-loop) ((not (eq? (of line =notab / i) &void-notab)) (loop (+ i 1) #f)) ((char=? c #\[) (if (eq? (of line =tab / i) &void-tab) (setf (of line =tab / i) &set-tab)) (loop (+ i 1) #f)) ((char=? c #\() (if (eq? (of line =tab / i) &void-tab) (if (not succ-parens?) (setf (of line =tab / i) &set-tab))) (loop (+ i 1) #t)) (else (loop (+ i 1) #f))))))) (define remove-some-tabs (lambda (line i) ;;remove useless tabs on line "line" after index i (if i (let loop ((i i)) (cond ((char=? (of line =char / i) #\newline) 'exit) ((eq? (of line =tab / i) &set-tab) (setf (of line =tab / i) &void-tab) (loop (+ i 1))) (else (loop (+ i 1)))))))) (define clean-init-spaces (lambda (line) ;;remove init-spaces on line "line" because ;;tabs make them defunct (let loop ((i (of line =rtedge))) (cond ((< i 0) 'exit-loop) ((eq? (of line =tab / i) &move-tab) (let loop1 ((i (- i 1))) (cond ((< i 0) 'exit-loop1) ((memq (of line =space / i) (list &init-space &paren-space &bracket-space &quote-space)) (setf (of line =space / i) &init-plain-space) (loop1 (- i 1))) (else (loop1 (- i 1)))))) (else (loop (- i 1))))))) (define clean-inner-spaces (lambda (line) ;;remove single inner spaces in line "line" since ;;paragraph mode takes care of them (let loop ((i 0) (succ-inner-spaces? #f)) (cond ((char=? (of line =char / i) #\newline) 'exit-loop) ((eq? (of line =space / i) &inner-space) (if (not succ-inner-spaces?) (setf (of line =space / i) &plain-space)) (loop (+ i 1) #t)) (else (loop (+ i 1) #f)))))) (define blank-line? (lambda (line) ;;check if line "line" is blank (let loop ((i 0)) (let ((c (of line =char / i))) (cond ((char=? c #\space) (if (eq? (of line =notab / i) &void-notab) (loop (+ i 1)) #f)) ((char=? c #\newline) (let loop1 ((j (- i 1))) (if (not (<= j 0)) (begin (setf (of line =space / i) &void-space) (loop1 (- j 1))))) #t) (else #f)))))) (define flush-comment-line? (lambda (line) ;;check if line "line" is one with ; in the leftmost column (and (char=? (of line =char / 0) #\;) (eq? (of line =notab / 0) &begin-comment) (not (char=? (of line =char / 1) #\;))))) (define display-tex-line (lambda (line) (cond;((and (flush-comment-line? line) ;; (char=? (of line =char / 1) #\%)) ;; (display "\\ZZZZschemecodebreak" *out*) ;; (newline *out*)) (else (let loop ((i (if (flush-comment-line? line) 1 0))) (let ((c (of line =char / i))) (if (char=? c #\newline) (if (not (eq? (of line =tab / i) &void-tab)) (newline *out*)) (begin (write-char c *out*) (loop (+ i 1)))))))))) (define display-scm-line (lambda (line) (let loop ((i 0)) (let ((c (of line =char / i))) (cond ((char=? c #\newline) (let ((notab (of line =notab / i)) (tab (of line =tab / i))) (if (eq? notab &end-string) (display "}" *out*)) (cond ((eq? tab &tabbed-crg-ret) (display "\\\\%" *out*) (newline *out*)) ((eq? tab &plain-crg-ret) (newline *out*)) ((eq? tab &void-tab) (write-char #\% *out*) (newline *out*))))) ((eq? (of line =notab / i) &begin-comment) (display-tab (of line =tab / i) *out*) (write-char c *out*) (loop (+ i 1))) ((eq? (of line =notab / i) &mid-comment) (write-char c *out*) (loop (+ i 1))) ((eq? (of line =notab / i) &begin-string) (display-tab (of line =tab / i) *out*) (display "\\dt{" *out*) (if (char=? c #\space) (display-space (of line =space / i) *out*) (display-tex-char c *out*)) (loop (+ i 1))) ((eq? (of line =notab / i) &mid-string) (if (char=? c #\space) (display-space (of line =space / i) *out*) (display-tex-char c *out*)) (loop (+ i 1))) ((eq? (of line =notab / i) &end-string) (if (char=? c #\space) (display-space (of line =space / i) *out*) (display-tex-char c *out*)) (write-char #\} *out*) (if *in-qtd-tkn* (set! *in-qtd-tkn* #f) (if *in-mac-tkn* (set! *in-mac-tkn* #f))) (loop (+ i 1))) ((eq? (of line =notab / i) &begin-math) (display-tab (of line =tab / i) *out*) (write-char c *out*) (loop (+ i 1))) ((eq? (of line =notab / i) &mid-math) (write-char c *out*) (loop (+ i 1))) ((eq? (of line =notab / i) &end-math) (write-char c *out*) (if *in-qtd-tkn* (set! *in-qtd-tkn* #f) (if *in-mac-tkn* (set! *in-mac-tkn* #f))) (loop (+ i 1))) ; ((memq (of line =notab / i) (list &mid-math &end-math)) ;; (write-char c *out*) ;; (loop (+ i 1))) ((char=? c #\space) (display-tab (of line =tab / i) *out*) (display-space (of line =space / i) *out*) (loop (+ i 1))) ((char=? c #\') (display-tab (of line =tab / i) *out*) (write-char c *out*) (if (or *in-qtd-tkn* (> *in-bktd-qtd-exp* 0) (and (pair? *bq-stack*) (not (of (car *bq-stack*) =in-comma)))) #f (set! *in-qtd-tkn* #t)) (loop (+ i 1))) ((char=? c #\`) (display-tab (of line =tab / i) *out*) (write-char c *out*) (if (or (null? *bq-stack*) (of (car *bq-stack*) =in-comma)) (set! *bq-stack* (cons (let ((f (make-bq-frame))) (setf (of f =in-comma) #f) (setf (of f =in-bq-tkn) #t) (setf (of f =in-bktd-bq-exp) 0) f) *bq-stack*))) (loop (+ i 1))) ((char=? c #\,) (display-tab (of line =tab / i) *out*) (write-char c *out*) (if (not (or (null? *bq-stack*) (of (car *bq-stack*) =in-comma))) (set! *bq-stack* (cons (let ((f (make-bq-frame))) (setf (of f =in-comma) #t) (setf (of f =in-bq-tkn) #t) (setf (of f =in-bktd-bq-exp) 0) f) *bq-stack*))) (if (char=? (of line =char / (+ i 1)) #\@) (begin (display-tex-char #\@ *out*) (loop (+ 2 i))) (loop (+ i 1)))) ((memv c '(#\( #\[)) (display-tab (of line =tab / i) *out*) (write-char c *out*) (cond (*in-qtd-tkn* (set! *in-qtd-tkn* #f) (set! *in-bktd-qtd-exp* 1)) ((> *in-bktd-qtd-exp* 0) (set! *in-bktd-qtd-exp* (+ *in-bktd-qtd-exp* 1)))) (cond (*in-mac-tkn* (set! *in-mac-tkn* #f) (set! *in-bktd-mac-exp* 1)) ((> *in-bktd-mac-exp* 0) ;is this possible? (set! *in-bktd-mac-exp* (+ *in-bktd-mac-exp* 1)))) (if (not (null? *bq-stack*)) (let ((top (car *bq-stack*))) (cond ((of top =in-bq-tkn) (setf (of top =in-bq-tkn) #f) (setf (of top =in-bktd-bq-exp) 1)) ((> (of top =in-bktd-bq-exp) 0) (setf (of top =in-bktd-bq-exp) (+ (of top =in-bktd-bq-exp) 1)))))) (if (not (null? *case-stack*)) (let ((top (car *case-stack*))) (cond ((of top =in-ctag-tkn) (setf (of top =in-ctag-tkn) #f) (setf (of top =in-bktd-ctag-exp) 1)) ((> (of top =in-bktd-ctag-exp) 0) (setf (of top =in-bktd-ctag-exp) (+ (of top =in-bktd-ctag-exp) 1))) ((> (of top =in-case-exp) 0) (setf (of top =in-case-exp) (+ (of top =in-case-exp) 1)) (if (= (of top =in-case-exp) 2) (set! *in-qtd-tkn* #t)))))) (loop (+ i 1))) ((memv c '(#\) #\])) (display-tab (of line =tab / i) *out*) (write-char c *out*) (if (> *in-bktd-qtd-exp* 0) (set! *in-bktd-qtd-exp* (- *in-bktd-qtd-exp* 1))) (if (> *in-bktd-mac-exp* 0) (set! *in-bktd-mac-exp* (- *in-bktd-mac-exp* 1))) (if (not (null? *bq-stack*)) (let ((top (car *bq-stack*))) (if (> (of top =in-bktd-bq-exp) 0) (begin (setf (of top =in-bktd-bq-exp) (- (of top =in-bktd-bq-exp) 1)) (if (= (of top =in-bktd-bq-exp) 0) (set! *bq-stack* (cdr *bq-stack*))))))) (let loop () (if (not (null? *case-stack*)) (let ((top (car *case-stack*))) (cond ((> (of top =in-bktd-ctag-exp) 0) (setf (of top =in-bktd-ctag-exp) (- (of top =in-bktd-ctag-exp) 1)) (if (= (of top =in-bktd-ctag-exp) 0) (setf (of top =in-case-exp) 1))) ((> (of top =in-case-exp) 0) (setf (of top =in-case-exp) (- (of top =in-case-exp) 1)) (if (= (of top =in-case-exp) 0) (begin (set! *case-stack* (cdr *case-stack*)) (loop)))))))) (loop (+ i 1))) (else (display-tab (of line =tab / i) *out*) (loop (do-token line i)))))))) (define do-all-lines (lambda () ;;process all lines, adjusting each adjacent pair (let loop ((line1 *line1*) (line2 *line2*)) (let* ((line2-paragraph? *latex-paragraph-mode?*) (more? (get-line line1))) ;; (peephole-adjust line1 line2) ;; ((if line2-paragraph? display-tex-line display-scm-line) line2) ;; (if (not (eq? line2-paragraph? *latex-paragraph-mode?*)) ((if *latex-paragraph-mode?* display-end-sequence display-begin-sequence) *out*)) ;; (if more? (loop line2 line1)))))) ;scheme2tex is the "interface" procedure supplied by this file -- ;it takes Scheme code from inport and produces LaTeX source for same ;in outport (define scheme2tex (lambda (inport outport) ;create a typeset version of scheme code from inport ;;in outport; ;;local setting of keywords, etc.? (set! *in* inport) (set! *out* outport) (set! *latex-paragraph-mode?* #t) (set! *in-qtd-tkn* #f) (set! *in-bktd-qtd-exp* 0) (set! *in-mac-tkn* #f) (set! *in-bktd-mac-exp* 0) (set! *case-stack* '()) (set! *bq-stack* '()) (let ((flush-line ;needed anywhere else? (lambda (line) (setf (of line =rtedge) 0) (setf (of line =char / 0) #\newline) (setf (of line =space / 0) &void-space) (setf (of line =tab / 0) &void-tab) (setf (of line =notab / 0) &void-notab)))) (flush-line *line1*) (flush-line *line2*)) (do-all-lines))) ;codeset.scm ;display-tex-line ;display-scm-line (define do-token (let ((token-delims (list #\( #\) #\[ #\] #\space *return* #\" #\' #\` #\newline #\, #\;))) (lambda (line i) (let loop ((buf '()) (i i)) (let ((c (of line =char / i))) (cond ((char=? c #\\ ) (loop (cons (of line =char / (+ i 1)) (cons c buf)) (+ i 2))) ((or (memv c token-delims) (memv c *math-triggerers*)) (output-token (list->string (reverse! buf))) i) ((char? c) (loop (cons (of line =char / i) buf) (+ i 1))) (else (slatex-error 'do-token "token contains non-char?" c)))))))) (define output-token (lambda (token) (if (not (null? *case-stack*)) (let ((top (car *case-stack*))) (if (of top =in-ctag-tkn) (begin (setf (of top =in-ctag-tkn) #f) (setf (of top =in-case-exp) 1))))) (if (lassoc token special-symbols token=?) (begin (if *in-qtd-tkn* (set! *in-qtd-tkn* #f) (if *in-mac-tkn* (set! *in-mac-tkn* #f))) (display (cdr (lassoc token special-symbols token=?)) *out*)) (display-token token (cond (*in-qtd-tkn* (set! *in-qtd-tkn* #f) (cond ((equal? token "else") 'syntax) ((lmember token data-tokens token=?) 'data) ((lmember token constant-tokens token=?) 'constant) ((lmember token variable-tokens token=?) 'constant) ((lmember token keyword-tokens token=?) 'constant) ((prim-data-token? token) 'data) (else 'constant))) ((> *in-bktd-qtd-exp* 0) 'constant) ((and (not (null? *bq-stack*)) (not (of (car *bq-stack*) =in-comma))) 'constant) (*in-mac-tkn* (set! *in-mac-tkn* #f) (set-keyword token) 'syntax) ((> *in-bktd-mac-exp* 0) (set-keyword token) 'syntax) ((lmember token data-tokens token=?) 'data) ((lmember token constant-tokens token=?) 'constant) ((lmember token variable-tokens token=?) 'variable) ((lmember token keyword-tokens token=?) (cond ((token=? token "quote") (set! *in-qtd-tkn* #t)) ((lmember token macro-definers token=?) (set! *in-mac-tkn* #t)) ((lmember token case-and-ilk token=?) (set! *case-stack* (cons (let ((f (make-case-frame))) (setf (of f =in-ctag-tkn) #t) (setf (of f =in-bktd-ctag-exp) 0) (setf (of f =in-case-exp) 0) f) *case-stack*)))) 'syntax) ((prim-data-token? token) 'data) (else 'variable)) *out*)) (if (and (not (null? *bq-stack*)) (of (car *bq-stack*) =in-bq-tkn)) (set! *bq-stack* (cdr *bq-stack*))))) ;pathproc.scm (define directory-namestring (lambda (f) (let ((p (string-position-right *directory-mark* f))) (if p (substring f 0 (+ p 1)) "")))) (define basename (lambda (f) (let ((p (string-position-right *directory-mark* f))) (if p (set! f (substring f (+ p 1) (string-length f)))) (let ((p (string-position-right #\. f))) (if p (substring f 0 p) f))))) (define *texinputs* "") (define *texinputs-list* #f) (define *path-separator* (cond ((eq? *operating-system* 'unix) #\:) ((eq? *operating-system* 'mac-os) (integer->char 0)) ((memq *operating-system* '(windows os2 dos os2fat)) #\;) (else (slatex-error "Couldn't determine path separator character.")))) (define *directory-mark* (cond ((eq? *operating-system* 'unix) #\/) ((eq? *operating-system* 'mac-os) #\:) ((memq *operating-system* '(windows os2 dos os2fat)) #\\) (else (slatex-error "Couldn't determine directory mark.")))) (define *directory-mark-string* (list->string (list *directory-mark*))) (define *file-hider* (cond ((memq *operating-system* '(windows os2 unix mac-os)) ".") ((memq *operating-system* '(dos os2fat)) "x") ;no such luck for dos & os2fat (else "."))) ;use any old character (define path-to-list (lambda (p) ;convert a unix or dos representation of a path to a list of ;directory names (strings) (let loop ((p (string->list p)) (r (list ""))) (let ((separator-pos (position-char *path-separator* p))) (if separator-pos (loop (list-tail p (+ separator-pos 1)) (cons (list->string (sublist p 0 separator-pos)) r)) (reverse! (cons (list->string p) r))))))) (define find-some-file (lambda (path . files) ;look through each directory in path till one of files is found (let loop ((path path)) (if (null? path) #f (let ((dir (car path))) (let loop1 ((files (if (or (string=? dir "") (string=? dir ".")) files (map (lambda (file) (string-append dir *directory-mark-string* file)) files)))) (if (null? files) (loop (cdr path)) (let ((file (car files))) (if (file-exists? file) file (loop1 (cdr files))))))))))) (define file-extension (lambda (filename) ;;find extension of filename (let ((i (string-position-right #\. filename))) (if i (substring filename i (string-length filename)) #f)))) (define full-texfile-name (lambda (filename) ;;find the full pathname of the .tex/.sty file filename (let ((extn (file-extension filename))) (if (and extn (or (string=? extn ".sty") (string=? extn ".tex"))) (find-some-file *texinputs-list* filename) (find-some-file *texinputs-list* (string-append filename ".tex") filename))))) (define full-styfile-name (lambda (filename) ;;find the full pathname of the .sty file filename (find-some-file *texinputs-list* (string-append filename ".sty")))) (define full-clsfile-name (lambda (filename) ;;find the full pathname of the .cls file filename (find-some-file *texinputs-list* (string-append filename ".cls")))) (define full-scmfile-name (lambda (filename) ;find the full pathname of the scheme file filename; ;acceptable extensions are .scm .ss .s (apply find-some-file *texinputs-list* filename (map (lambda (extn) (string-append filename extn)) '(".scm" ".ss" ".s"))))) (define subjobname 'fwd) (define primary-aux-file-count -1) (define new-primary-aux-file (lambda (e) ;used by new-aux-file unless in protected region; ;this is the default (set! primary-aux-file-count (+ primary-aux-file-count 1)) (string-append *tex-calling-directory* *file-hider* "Z" (number->string primary-aux-file-count) subjobname e))) (define new-secondary-aux-file (let ((n -1)) (lambda (e) ;used by new-aux-file when in protected region (set! n (+ n 1)) (string-append *tex-calling-directory* *file-hider* "ZZ" (number->string n) subjobname e)))) (define new-aux-file (lambda e (let ((e (if (pair? e) (car e) ""))) ;;create a new auxiliary file with provided extension if any ((if *slatex-in-protected-region?* new-secondary-aux-file new-primary-aux-file) e)))) ;texread.scm (define eat-till-newline (lambda (in) ;;skip all characters from port in till newline inclusive or eof (let loop () (let ((c (read-char in))) (cond ((eof-object? c) 'done) ((char=? c #\newline) 'done) (else (loop))))))) (define read-ctrl-seq (lambda (in) ;;assuming we've just read a backslash, read the remaining ;;part of a latex control sequence from port in (let ((c (read-char in))) (if (eof-object? c) (slatex-error "read-ctrl-exp: \\ followed by eof.")) (if (char-alphabetic? c) (list->string (reverse! (let loop ((s (list c))) (let ((c (peek-char in))) (cond ((eof-object? c) s) ((char-alphabetic? c) (read-char in) (loop (cons c s))) ((char=? c #\%) (eat-till-newline in) (loop s)) (else s)))))) (string c))))) (define eat-tabspace (lambda (in) ;;skip to the next non-space and non-tab character from port in (let loop () (let ((c (peek-char in))) (cond ((eof-object? c) 'done) ((or (char=? c #\space) (char=? c *tab*)) (read-char in) (loop)) (else 'done)))))) (define eat-whitespace (lambda (in) ;skip to the next whitespace character from port in (let loop () (let ((c (peek-char in))) (cond ((eof-object? c) 'done) ((char-whitespace? c) (read-char in) (loop)) (else 'done)))))) (define eat-tex-whitespace (lambda (in) ;;skip to the next whitespace character from port in; ;;skips past latex comments too (let loop () (let ((c (peek-char in))) (cond ((eof-object? c) 'done) ((char-whitespace? c) (read-char in) (loop)) ((char=? c #\%) (eat-till-newline in)) (else 'done)))))) (define chop-off-whitespace (lambda (l) ;;removes leading whitespace from character-list l (ormapcdr (lambda (d) (if (char-whitespace? (car d)) #f d)) l))) (define read-grouped-latexexp (lambda (in) ;;reads a latex grouped expression from port in ;;(removes the groups) (eat-tex-whitespace in) (let ((c (read-char in))) (if (eof-object? c) (slatex-error "read-grouped-latexexp: ~ Expected { but found eof.")) (if (not (char=? c #\{)) (slatex-error "read-grouped-latexexp: ~ Expected { but found ~a." c)) (eat-tex-whitespace in) (list->string (reverse! (chop-off-whitespace (let loop ((s '()) (nesting 0) (escape? #f)) (let ((c (read-char in))) (if (eof-object? c) (slatex-error "read-groupted-latexexp: ~ Found eof inside {...}.")) (cond (escape? (loop (cons c s) nesting #f)) ((char=? c #\\) (loop (cons c s) nesting #t)) ((char=? c #\%) (eat-till-newline in) (loop s nesting #f)) ((char=? c #\{) (loop (cons c s) (+ nesting 1) #f)) ((char=? c #\}) (if (= nesting 0) s (loop (cons c s) (- nesting 1) #f))) (else (loop (cons c s) nesting #f))))))))))) (define read-filename (let ((filename-delims (list #\{ #\} #\[ #\] #\( #\) #\# #\% #\\ #\, #\space *return* #\newline *tab* #\\))) (lambda (in) ;reads a filename as allowed in latex syntax from port in (eat-tex-whitespace in) (let ((c (peek-char in))) (if (eof-object? c) (slatex-error "read-filename: ~ Expected filename but found eof.")) (if (char=? c #\{) (read-grouped-latexexp in) (list->string (reverse! (let loop ((s '()) (escape? #f)) (let ((c (peek-char in))) (cond ((eof-object? c) (if escape? (slatex-error "read-filename: ~ \\ followed by eof.") s)) (escape? (read-char in) (loop (cons c s) #f)) ((char=? c #\\) (read-char in) (loop (cons c s) #t)) ((memv c filename-delims) s) (else (read-char in) (loop (cons c s) #f)))))))))))) (define read-schemeid (let ((schemeid-delims (list #\{ #\} #\[ #\] #\( #\) #\space *return* #\newline *tab*))) (lambda (in) ;;reads a scheme identifier from port in (eat-whitespace in) (list->string (reverse! (let loop ((s '()) (escape? #f)) (let ((c (peek-char in))) (cond ((eof-object? c) s) (escape? (read-char in) (loop (cons c s) #f)) ((char=? c #\\) (read-char in) (loop (cons c s) #t)) ((memv c schemeid-delims) s) (else (read-char in) (loop (cons c s) #f)))))))))) (define read-delimed-commaed-filenames (lambda (in lft-delim rt-delim) ;;reads a filename from port in, assuming it's delimited by ;;lft- and rt-delims (eat-tex-whitespace in) (let ((c (read-char in))) (if (eof-object? c) (slatex-error "read-delimed-commaed-filenames: ~ Expected filename(s) but found eof.")) (if (not (char=? c lft-delim)) (slatex-error "read-delimed-commaed-filenames: ~ Left delimiter ~a not found." lft-delim)) (let loop ((s '())) (eat-tex-whitespace in) (let ((c (peek-char in))) (if (eof-object? c) (slatex-error "read-delimed-commaed-filenames: ~ Found eof inside filename(s).")) (if (char=? c rt-delim) (begin (read-char in) (reverse! s)) (let ((s (cons (read-filename in) s))) (eat-tex-whitespace in) (let ((c (peek-char in))) (if (eof-object? c) (slatex-error "read-delimed-commaed-filenames: ~ Found eof inside filename(s).")) (cond ((char=? c #\,) (read-char in)) ((char=? c rt-delim) (void)) (else (slatex-error "read-delimed-commaed-filenames: ~ Bad filename(s) syntax."))) (loop s))))))))) (define read-grouped-commaed-filenames (lambda (in) ;read a filename from port in, assuming it's grouped (read-delimed-commaed-filenames in #\{ #\}))) (define read-bktd-commaed-filenames (lambda (in) ;read a filename from port in, assuming it's bracketed (read-delimed-commaed-filenames in #\[ #\]))) (define read-grouped-schemeids (lambda (in) ;read a list of scheme identifiers from port in, ;assuming they're all grouped (eat-tex-whitespace in) (let ((c (read-char in))) (if (eof-object? c) (slatex-error "read-grouped-schemeids: ~ Expected Scheme identifiers but found eof.")) (if (not (char=? c #\{)) (slatex-error "read-grouped-schemeids: ~ Expected { but found ~a." c)) (let loop ((s '())) (eat-whitespace in) (let ((c (peek-char in))) (if (eof-object? c) (slatex-error "read-grouped-schemeids: Found eof inside Scheme identifiers.")) (if (char=? c #\}) (begin (read-char in) (reverse! s)) (loop (cons (read-schemeid in) s)))))))) (define eat-delimed-text (lambda (in lft-delim rt-delim) (eat-tex-whitespace in) (let ((c (peek-char in))) (if (eof-object? c) 'exit (if (char=? c lft-delim) (let loop () (let ((c (read-char in))) (if (eof-object? c) 'exit (if (char=? c rt-delim) 'exit (loop)))))))))) (define eat-bktd-text (lambda (in) (eat-delimed-text in #\[ #\]))) (define eat-grouped-text (lambda (in) (eat-delimed-text in #\{ #\}))) ;proctex.scm (define ignore2 (lambda (i ii) ;ignores its two arguments 'void)) (define disable-slatex-temply (lambda (in) ;tell slatex that it should not process slatex commands till ;the enabling control sequence is called (set! *slatex-enabled?* #f) (set! *slatex-reenabler* (read-grouped-latexexp in)))) (define enable-slatex-again (lambda () ;tell slatex to resume processing slatex commands (set! *slatex-enabled?* #t) (set! *slatex-reenabler* "UNDEFINED"))) (define add-to-slatex-db (lambda (in categ) ;;some scheme identifiers to be added to the token category categ (if (memq categ '(keyword constant variable)) (add-to-slatex-db-basic in categ) (add-to-slatex-db-special in categ)))) (define add-to-slatex-db-basic (lambda (in categ) ;read the following scheme identifiers and add them to the ;token category categ (let ((setter (cond ((eq? categ 'keyword) set-keyword) ((eq? categ 'constant) set-constant) ((eq? categ 'variable) set-variable) (else (slatex-error "add-to-slatex-db-basic: ~ Unknown category ~s." categ)))) (ids (read-grouped-schemeids in))) (for-each setter ids)))) (define add-to-slatex-db-special (lambda (in what) ;read the following scheme identifier(s) and either ;enable/disable its special-symbol status (let ((ids (read-grouped-schemeids in))) (cond ((eq? what 'unsetspecialsymbol) (for-each unset-special-symbol ids)) ((eq? what 'setspecialsymbol) (if (not (= (length ids) 1)) (slatex-error "add-to-slatex-db-special: ~ \\setspecialsymbol takes one arg exactly.")) (let ((transl (read-grouped-latexexp in))) (set-special-symbol (car ids) transl))) (else (slatex-error "add-to-slatex-db-special: ~ Unknown command ~s." what)))))) (define process-slatex-alias (lambda (in what which) ;add/remove a slatex control sequence name (let ((triggerer (read-grouped-latexexp in))) (case which ((intext) (set! *intext-triggerers* (what triggerer *intext-triggerers* string=?))) ((resultintext) (set! *resultintext-triggerers* (what triggerer *resultintext-triggerers* string=?))) ((display) (set! *display-triggerers* (what triggerer *display-triggerers* string=?))) ((response) (set! *response-triggerers* (what triggerer *response-triggerers* string=?))) ((respbox) (set! *respbox-triggerers* (what triggerer *respbox-triggerers* string=?))) ((box) (set! *box-triggerers* (what triggerer *box-triggerers* string=?))) ((input) (set! *input-triggerers* (what triggerer *input-triggerers* string=?))) ((region) (set! *region-triggerers* (what triggerer *region-triggerers* string=?))) ((mathescape) (if (not (= (string-length triggerer) 1)) (slatex-error "process-slatex-alias: ~ Math escape should be character.")) (set! *math-triggerers* (what (string-ref triggerer 0) *math-triggerers* char=?))) (else (slatex-error "process-slatex-alias: Unknown command ~s." which)))))) (define decide-latex-or-tex (lambda (latex?) ;create a junk file if the file is in plain tex rather ;than latex; this is used afterward to call the right ;command, i.e., latex or tex (set! *latex?* latex?) (let ((pltexchk.jnk "pltexchk.jnk")) (if (file-exists? pltexchk.jnk) (delete-file pltexchk.jnk)) (if (not *latex?*) (call-with-output-file pltexchk.jnk (lambda (outp) (display 'junk outp) (newline outp))))))) (define process-include-only (lambda (in) ;remember the files mentioned by \includeonly (set! *include-onlys* '()) (for-each (lambda (filename) (let ((filename (full-texfile-name filename))) (if filename (set! *include-onlys* (adjoin filename *include-onlys* string=?))))) (read-grouped-commaed-filenames in)))) (define process-documentstyle (lambda (in) ;process the .sty files corresponding to the documentstyle options (eat-tex-whitespace in) (if (char=? (peek-char in) #\[) (for-each (lambda (filename) (fluid-let ((*slatex-in-protected-region?* #f)) (process-tex-file (string-append filename ".sty")))) (read-bktd-commaed-filenames in))))) (define process-documentclass (lambda (in) (eat-bktd-text in) (eat-grouped-text in))) (define process-case-info (lambda (in) ;find out and tell slatex if the scheme tokens that differ ;only by case should be treated identical or not (let ((bool (read-grouped-latexexp in))) (set! *slatex-case-sensitive?* (cond ((string-ci=? bool "true") #t) ((string-ci=? bool "false") #f) (else (slatex-error "process-case-info: ~ \\schemecasesensitive's arg should be true or false."))))))) (define seen-first-command? #f) (define process-main-tex-file (lambda (filename) ;kick off slatex on the main .tex file filename (display "SLaTeX v. ") (display *slatex-version*) (newline) (set! primary-aux-file-count -1) (set! *slatex-separate-includes?* #f) (if (or (not *texinputs-list*) (null? *texinputs-list*)) (set! *texinputs-list* (if *texinputs* (path-to-list *texinputs*) '("")))) (let ((file-hide-file "xZfilhid.tex")) (if (file-exists? file-hide-file) (delete-file file-hide-file)) (if (memq *operating-system* '(dos os2fat)) (call-with-output-file file-hide-file (lambda (out) (display "\\def\\filehider{x}" out) (newline out))))) (display "typesetting code") (set! *tex-calling-directory* (directory-namestring filename)) (set! subjobname (basename filename)) (set! seen-first-command? #f) (process-tex-file filename) (display "done") (newline))) (define dump-intext (lambda (in out) (let* ((write-char (if out write-char ignore2)) (delim-char (begin (eat-whitespace in) (read-char in))) (delim-char (cond ((char=? delim-char #\{) #\}) (else delim-char)))) (if (eof-object? delim-char) (slatex-error "dump-intext: Expected delimiting character ~ but found eof.")) (let loop () (let ((c (read-char in))) (if (eof-object? c) (slatex-error "dump-intext: Found eof inside Scheme code.")) (if (char=? c delim-char) 'done (begin (write-char c out) (loop)))))))) (define dump-display (lambda (in out ender) (eat-tabspace in) (let ((write-char (if out write-char ignore2)) (ender-lh (string-length ender)) (c (peek-char in))) (if (eof-object? c) (slatex-error "dump-display: Found eof inside displayed code.")) (if (char=? c #\newline) (read-char in)) (let loop ((i 0)) (if (= i ender-lh) 'done (let ((c (read-char in))) (if (eof-object? c) (slatex-error "dump-display: Found eof inside displayed code.")) (if (char=? c (string-ref ender i)) (loop (+ i 1)) (let loop2 ((j 0)) (if (< j i) (begin (write-char (string-ref ender j) out) (loop2 (+ j 1))) (begin (write-char c out) (loop 0))))))))))) ;proctex2.scm (define debug? #f) (define process-tex-file (lambda (raw-filename) ;call slatex on the .tex file raw-filename (if debug? (begin (display "begin ") (display raw-filename) (newline))) (let ((filename (full-texfile-name raw-filename))) (if (not filename) ;didn't find it (begin (display "[") (display raw-filename) (display "]") (flush-output)) (call-with-input-file filename (lambda (in) (let ((done? #f)) (let loop () (if done? 'exit-loop (begin (let ((c (read-char in))) (cond ((eof-object? c) (set! done? #t)) ((char=? c #\%) (eat-till-newline in)) ((char=? c #\\) (let ((cs (read-ctrl-seq in))) (if (not seen-first-command?) (begin (set! seen-first-command? #t) (decide-latex-or-tex (or (string=? cs "documentstyle") (string=? cs "documentclass") (string=? cs "NeedsTeXFormat") )))) (cond ((not *slatex-enabled?*) (if (string=? cs *slatex-reenabler*) (enable-slatex-again))) ((string=? cs "slatexignorecurrentfile") (set! done? #t)) ((string=? cs "slatexseparateincludes") (if *latex?* (set! *slatex-separate-includes?* #t))) ((string=? cs "slatexdisable") (disable-slatex-temply in)) ((string=? cs "begin") (eat-tex-whitespace in) (if (eqv? (peek-char in) #\{) (let ((cs (read-grouped-latexexp in))) (cond ((member cs *display-triggerers*) (trigger-scheme2tex 'envdisplay in cs)) ((member cs *response-triggerers*) (trigger-scheme2tex 'envresponse in cs)) ((member cs *respbox-triggerers*) (trigger-scheme2tex 'envrespbox in cs)) ((member cs *box-triggerers*) (trigger-scheme2tex 'envbox in cs)) ((member cs *topbox-triggerers*) (trigger-scheme2tex 'envtopbox in cs)) ((member cs *region-triggerers*) (trigger-region 'envregion in cs)))))) ((member cs *intext-triggerers*) (trigger-scheme2tex 'intext in #f)) ((member cs *resultintext-triggerers*) (trigger-scheme2tex 'resultintext in #f)) ((member cs *display-triggerers*) (trigger-scheme2tex 'plaindisplay in cs)) ((member cs *response-triggerers*) (trigger-scheme2tex 'plainresponse in cs)) ((member cs *respbox-triggerers*) (trigger-scheme2tex 'plainrespbox in cs)) ((member cs *box-triggerers*) (trigger-scheme2tex 'plainbox in cs)) ((member cs *topbox-triggerers*) (trigger-scheme2tex 'plaintopbox in cs)) ((member cs *region-triggerers*) (trigger-region 'plainregion in cs)) ((member cs *input-triggerers*) (process-scheme-file (read-filename in))) ((string=? cs "input") (let ((f (read-filename in))) (if (not (string=? f "")) (fluid-let ((*slatex-in-protected-region?* #f)) (process-tex-file f))))) ((string=? cs "usepackage") (fluid-let ((*slatex-in-protected-region?* #f)) (process-tex-file (string-append (read-filename in) ".sty")))) ((string=? cs "include") (if *latex?* (let ((f (full-texfile-name (read-filename in)))) (if (and f (or (eq? *include-onlys* 'all) (member f *include-onlys*))) (fluid-let ((*slatex-in-protected-region?* #f)) (if *slatex-separate-includes?* (fluid-let ((subjobname (basename f)) (primary-aux-file-count -1)) (process-tex-file f)) (process-tex-file f))))))) ((string=? cs "includeonly") (if *latex?* (process-include-only in))) ((string=? cs "documentstyle") (if *latex?* (process-documentstyle in))) ((string=? cs "documentclass") (if *latex?* (process-documentclass in))) ((string=? cs "schemecasesensitive") (process-case-info in)) ((string=? cs "defschemetoken") (process-slatex-alias in adjoin 'intext)) ((string=? cs "undefschemetoken") (process-slatex-alias in delete 'intext)) ((string=? cs "defschemeresulttoken") (process-slatex-alias in adjoin 'resultintext)) ((string=? cs "undefschemeresulttoken") (process-slatex-alias in delete 'resultintext)) ((string=? cs "defschemeresponsetoken") (process-slatex-alias in adjoin 'response)) ((string=? cs "undefschemeresponsetoken") (process-slatex-alias in delete 'response)) ((string=? cs "defschemeresponseboxtoken") (process-slatex-alias in adjoin 'respbox)) ((string=? cs "undefschemeresponseboxtoken") (process-slatex-alias in delete 'respbox)) ((string=? cs "defschemedisplaytoken") (process-slatex-alias in adjoin 'display)) ((string=? cs "undefschemedisplaytoken") (process-slatex-alias in delete 'display)) ((string=? cs "defschemeboxtoken") (process-slatex-alias in adjoin 'box)) ((string=? cs "undefschemeboxtoken") (process-slatex-alias in delete 'box)) ((string=? cs "defschemetopboxtoken") (process-slatex-alias in adjoin 'topbox)) ((string=? cs "undefschemetopboxtoken") (process-slatex-alias in delete 'topbox)) ((string=? cs "defschemeinputtoken") (process-slatex-alias in adjoin 'input)) ((string=? cs "undefschemeinputtoken") (process-slatex-alias in delete 'input)) ((string=? cs "defschemeregiontoken") (process-slatex-alias in adjoin 'region)) ((string=? cs "undefschemeregiontoken") (process-slatex-alias in delete 'region)) ((string=? cs "defschememathescape") (process-slatex-alias in adjoin 'mathescape)) ((string=? cs "undefschememathescape") (process-slatex-alias in delete 'mathescape)) ((string=? cs "setkeyword") (add-to-slatex-db in 'keyword)) ((string=? cs "setconstant") (add-to-slatex-db in 'constant)) ((string=? cs "setvariable") (add-to-slatex-db in 'variable)) ((string=? cs "setspecialsymbol") (add-to-slatex-db in 'setspecialsymbol)) ((string=? cs "unsetspecialsymbol") (add-to-slatex-db in 'unsetspecialsymbol)) ))))) (loop))))))))) (if debug? (begin (display "end ") (display raw-filename) (newline))) )) (define process-scheme-file (lambda (raw-filename) ;typeset the scheme file raw-filename so that it can ;be input as a .tex file (let ((filename (full-scmfile-name raw-filename))) (if (not filename) (begin (display "process-scheme-file: ") (display raw-filename) (display " doesn't exist") (newline)) (let ((aux.tex (new-aux-file ".tex"))) (display ".") (flush-output) (if (file-exists? aux.tex) (delete-file aux.tex)) (call-with-input-file filename (lambda (in) (call-with-output-file aux.tex (lambda (out) (fluid-let ((*intext?* #f) (*code-env-spec* "ZZZZschemedisplay")) (scheme2tex in out)))))) (if *slatex-in-protected-region?* (set! *protected-files* (cons aux.tex *protected-files*))) (process-tex-file filename)))))) (define trigger-scheme2tex (lambda (typ in env) ;process the slatex command identified by typ; ;env is the name of the environment (let* ((aux (new-aux-file)) (aux.scm (string-append aux ".scm")) (aux.tex (string-append aux ".tex"))) (if (file-exists? aux.scm) (delete-file aux.scm)) (if (file-exists? aux.tex) (delete-file aux.tex)) (display ".") (flush-output) (call-with-output-file aux.scm (lambda (out) (cond ((memq typ '(intext resultintext)) (dump-intext in out)) ((memq typ '(envdisplay envresponse envrespbox envbox envtopbox)) (dump-display in out (string-append "\\end{" env "}"))) ((memq typ '(plaindisplay plainresponse plainrespbox plainbox plaintopbox)) (dump-display in out (string-append "\\end" env))) (else (slatex-error "trigger-scheme2tex: ~ Unknown triggerer ~s." typ))))) (call-with-input-file aux.scm (lambda (in) (call-with-output-file aux.tex (lambda (out) (fluid-let ((*intext?* (memq typ '(intext resultintext))) (*code-env-spec* (cond ((eq? typ 'intext) "ZZZZschemecodeintext") ((eq? typ 'resultintext) "ZZZZschemeresultintext") ((memq typ '(envdisplay plaindisplay)) "ZZZZschemedisplay") ((memq typ '(envresponse plainresponse)) "ZZZZschemeresponse") ((memq typ '(envrespbox plainrespbox)) "ZZZZschemeresponsebox") ((memq typ '(envbox plainbox)) "ZZZZschemebox") ((memq typ '(envtopbox plaintopbox)) "ZZZZschemetopbox") (else (slatex-error "trigger-scheme2tex: ~ Unknown triggerer ~s." typ))))) (scheme2tex in out)))))) (if *slatex-in-protected-region?* (set! *protected-files* (cons aux.tex *protected-files*))) (if (memq typ '(envdisplay plaindisplay envbox plainbox envtopbox plaintopbox)) (process-tex-file aux.tex)) (delete-file aux.scm) ))) (define trigger-region (lambda (typ in env) ;process a scheme region to create a in-lined file with ;slatex output (let ((aux.tex (new-primary-aux-file ".tex")) (aux2.tex (new-secondary-aux-file ".tex"))) (if (file-exists? aux2.tex) (delete-file aux2.tex)) (if (file-exists? aux.tex) (delete-file aux.tex)) (display ".") (flush-output) (fluid-let ((*slatex-in-protected-region?* #t) (*protected-files* '())) (call-with-output-file aux2.tex (lambda (out) (cond ((eq? typ 'envregion) (dump-display in out (string-append "\\end{" env "}"))) ((eq? typ 'plainregion) (dump-display in out (string-append "\\end" env))) (else (slatex-error "trigger-region: ~ Unknown triggerer ~s." typ))))) (process-tex-file aux2.tex) (set! *protected-files* (reverse! *protected-files*)) (call-with-input-file aux2.tex (lambda (in) (call-with-output-file aux.tex (lambda (out) (inline-protected-files in out))))) (delete-file aux2.tex) )))) (define inline-protected-files (lambda (in out) ;;inline all the protected files in port in into port out (let ((done? #f)) (let loop () (if done? 'exit-loop (begin (let ((c (read-char in))) (cond ((eof-object? c) ;(display "{}" out) (set! done? #t)) ((or (char=? c *return*) (char=? c #\newline)) (let ((c2 (peek-char in))) (if (not (eof-object? c2)) (write-char c out)))) ((char=? c #\%) (write-char c out) (newline out) (eat-till-newline in)) ((char=? c #\\) (let ((cs (read-ctrl-seq in))) (cond ((string=? cs "begin") (let ((cs (read-grouped-latexexp in))) (cond ((member cs *display-triggerers*) (inline-protected 'envdisplay in out cs)) ((member cs *response-triggerers*) (inline-protected 'envresponse in out cs)) ((member cs *respbox-triggerers*) (inline-protected 'envrespbox in out cs)) ((member cs *box-triggerers*) (inline-protected 'envbox in out cs)) ((member cs *topbox-triggerers*) (inline-protected 'envtopbox in out cs)) ((member cs *region-triggerers*) (inline-protected 'envregion in out cs)) (else (display "\\begin{" out) (display cs out) (display "}" out))))) ((member cs *intext-triggerers*) (inline-protected 'intext in out #f)) ((member cs *resultintext-triggerers*) (inline-protected 'resultintext in out #f)) ((member cs *display-triggerers*) (inline-protected 'plaindisplay in out cs)) ((member cs *response-triggerers*) (inline-protected 'plainresponse in out cs)) ((member cs *respbox-triggerers*) (inline-protected 'plainrespbox in out cs)) ((member cs *box-triggerers*) (inline-protected 'plainbox in out cs)) ((member cs *topbox-triggerers*) (inline-protected 'plaintopbox in out cs)) ((member cs *region-triggerers*) (inline-protected 'plainregion in out cs)) ((member cs *input-triggerers*) (inline-protected 'input in out cs)) (else (display "\\" out) (display cs out))))) (else (write-char c out)))) (loop))))))) (define inline-protected (lambda (typ in out env) (cond ((eq? typ 'envregion) (display "\\begin{" out) (display env out) (display "}" out) (dump-display in out (string-append "\\end{" env "}")) (display "\\end{" out) (display env out) (display "}" out)) ((eq? typ 'plainregion) (display "\\" out) (display env out) (dump-display in out (string-append "\\end" env)) (display "\\end" out) (display env out)) (else (let ((f (car *protected-files*))) (set! *protected-files* (cdr *protected-files*)) (call-with-input-file f (lambda (in) (inline-protected-files in out))) (delete-file f) ) (cond ((memq typ '(intext resultintext)) (display "{}" out) (dump-intext in #f)) ((memq typ '(envrespbox envbox envtopbox)) (if (not *latex?*) (display "{}" out)) (dump-display in #f (string-append "\\end{" env "}"))) ((memq typ '(plainrespbox plainbox plaintopbox)) (display "{}" out) (dump-display in #f (string-append "\\end" env))) ((memq typ '(envdisplay envresponse)) (dump-display in #f (string-append "\\end{" env "}"))) ((memq typ '(plaindisplay plainresponse)) (dump-display in #f (string-append "\\end" env))) ((eq? typ 'input) (read-filename in)) ;and throw it away (else (slatex-error "inline-protected: ~ Unknown triggerer ~s." typ)))))))
true
4c7334767c268f59c8ba56f09ed89f155c28db76
a66514d577470329b9f0bf39e5c3a32a6d01a70d
/sdl2/error-functions.ss
3bdb5650c7cce4acf9a05925ee98c69a58bc75ea
[ "Apache-2.0" ]
permissive
ovenpasta/thunderchez
2557819a41114423a4e664ead7c521608e7b6b42
268d0d7da87fdeb5f25bdcd5e62217398d958d59
refs/heads/trunk
2022-08-31T15:01:37.734079
2021-07-25T14:59:53
2022-08-18T09:33:35
62,828,147
149
29
null
2022-08-18T09:33:37
2016-07-07T18:07:23
Common Lisp
UTF-8
Scheme
false
false
251
ss
error-functions.ss
(define-sdl-func int sdl-set-error ((fmt string)) "SDL_SetError") (define-sdl-func string sdl-get-error () "SDL_GetError") (define-sdl-func void sdl-clear-error () "SDL_ClearError") (define-sdl-func int sdl-error ((code sdl-errorcode-t)) "SDL_Error")
false
621bb4651b256ebde0f93d11bb69aa4e28a084b5
73b5d880fa06943c20ff0a9aee9d0c1d1eeebe10
/tinyos-2.x-contrib/sensorscheme/support/sdk/pltscheme/sensor-net.scm
601f43bb53e2957633add18e99c6b03e4f923e24
[]
no_license
x3ro/tinyos-legacy
101d19f9e639f5a9d59d3edd4ed04b1f53221e63
cdc0e7ba1cac505fcace33b974b2e0aca1ccc56a
refs/heads/master
2021-01-16T19:20:21.744228
2015-06-30T20:23:05
2015-06-30T20:23:05
38,358,728
0
1
null
null
null
null
UTF-8
Scheme
false
false
6,560
scm
sensor-net.scm
#lang scheme (require (only-in (lib "1.ss" "srfi") append-map) (only-in (lib "13.ss" "srfi") string-take string-drop) (file "symmap.scm")) (provide net-encode net-decode c-ident net-decode-mapfile net-encode-mapfile read-symmap-file) (define TOK_SYM 0) (define TOK_NUM 1) (define TOK_BROPEN 2) (define TOK_BRCLOSE 3) (define TOK_NIBBLE TOK_SYM ) (define TOK_BYTE TOK_NUM ) (define TOK_WORD TOK_BROPEN ) (define TOK_DWORD TOK_BRCLOSE) (define (net-decode byte-list symmap) (let ((bitbuf 0) (bitcnt 0)) (define (read-bits) (when (= bitcnt 0) (set! bitbuf (car byte-list)) (set! bitcnt 4) (set! byte-list (cdr byte-list))) (let ((res (modulo bitbuf 4))) (set! bitbuf (quotient bitbuf 4)) (set! bitcnt (- bitcnt 1)) res)) (define (read-sym) (let ((res (symname symmap (let ((n (car byte-list))) (if (> n (- 256 8)) (- n 256) n))))) (set! byte-list (cdr byte-list)) res)) (define (read-num) (let ((bits (read-bits))) (cond ((eq? bits TOK_NIBBLE) (+ (* (read-bits) 4) (read-bits))) ((eq? bits TOK_BYTE) (let ((res (car byte-list))) (set! byte-list (cdr byte-list)) (if (>= res 128) (- res 256) res))) ((eq? bits TOK_WORD) (let ((res (+ (* (cadr byte-list) 256) (car byte-list)))) (set! byte-list (cddr byte-list)) (if (>= res (expt 2 15)) (- res (expt 2 16)) res))) ((eq? bits TOK_DWORD) (let ((res (+ (* (+ (* (+ (* (cadddr byte-list) 256) (caddr byte-list)) 256) (cadr byte-list)) 256) (car byte-list)))) (set! byte-list (cddddr byte-list)) (if (>= res (expt 2 31)) (- res (expt 2 32)) res))) (else (display "panic!\n"))))) (define (read-list) (let ((sexpr (read-sexpr))) (cond ((eq? sexpr '<brclose>) '()) ((eq? sexpr '<dot>) (read-sexpr)) (else (cons sexpr (read-list)))))) (define (read-sexpr) (let ((bits (read-bits))) (cond ((eq? bits TOK_SYM) (read-sym)) ((eq? bits TOK_NUM) (read-num)) ((eq? bits TOK_BROPEN) (read-list)) ((eq? bits TOK_BRCLOSE) '<brclose>) (else (display "panic!\n"))))) (read-sexpr))) (define (net-encode sexpr symmap) (let ([byte-list '()] [bitbuf 0] [bitcnt 0] [tls '()]) (define (out! b) (set! tls (cons b tls))) (define (write-bits tok) (when (= bitcnt 4) (set! byte-list (append tls (cons bitbuf byte-list))) (set! tls '()) (set! bitbuf 0) (set! bitcnt 0)) (set! bitbuf (+ (quotient bitbuf 4) (* tok 64))) (set! bitcnt (+ bitcnt 1))) (define (write-sym val) (out! (modulo (symnum symmap val) 256))) (define (write-string val) (write-bits TOK_SYM) (write-sym '%string%) (let* ([num (symnum symmap val)] [hi-num (quotient num 256)]) (write-bits (quotient hi-num 4)) (write-bits (modulo hi-num 4)) (out! (modulo num 256)))) (define (write-num aval) (cond ((<= 0 aval 15) (write-bits TOK_NIBBLE) (write-bits (quotient aval 4)) (write-bits (modulo aval 4))) ((<= (- (/ 256 2)) aval (- (/ 256 2) 1)) (write-bits TOK_BYTE) (out! (modulo aval 256))) ((<= (- (/ (expt 256 2) 2)) aval (- (/ (expt 256 2) 2) 1)) (write-bits TOK_WORD) (out! (modulo aval 256)) (out! (quotient (modulo aval (* 256 256)) 256))) (else (write-bits TOK_DWORD) (let ((val (modulo aval (expt 256 4)))) (out! (modulo val 256)) (out! (modulo (quotient val 256) 256)) (out! (modulo (quotient val (* 256 256)) 256)) (out! (modulo (quotient val (expt 256 3)) 256)))))) (define (write-list sexpr) (cond ((pair? sexpr) (write-sexpr (car sexpr)) (write-list (cdr sexpr))) ((null? sexpr) (write-bits TOK_BRCLOSE)) (else (write-bits TOK_SYM) (write-sym '<dot>) (write-sexpr sexpr)))) (define (write-sexpr sexpr) (cond ((or (symbol? sexpr) (boolean? sexpr)) (write-bits TOK_SYM) (write-sym sexpr)) ((number? sexpr) (write-bits TOK_NUM) (write-num sexpr)) ((pair? sexpr) (write-bits TOK_BROPEN) (write-list sexpr)) ((string? sexpr) (write-string sexpr)) ((null? sexpr) (write-bits TOK_BROPEN) (write-bits TOK_BRCLOSE)))) (define (flush) (define (do-flush) (write-bits TOK_BRCLOSE) (unless (= bitcnt 1) (do-flush))) (if (= bitcnt 4) (begin (do-flush) #;(set! byte-list (cdr byte-list))) (do-flush))) (write-sexpr sexpr) (flush) (reverse byte-list))) ; makes a legal c identifier from a symbol ; it upcases letters in the symvbol, so this is not reversable (define (c-ident sym) (define (esc c) (list #\_ c #\_)) (list->string (append-map (lambda (c) (case c [(#\!) (esc #\X)] [(#\*) (esc #\T)] [(#\-) (esc #\M)] [(#\+) (esc #\P)] [(#\=) (esc #\E)] [(#\/) (esc #\D)] [(#\%) (esc #\L)] [(#\?) (esc #\Q)] [(#\:) (esc #\C)] [(#\<) (esc #\S)] [(#\>) (esc #\G)] [(#\^) (esc #\W)] [(#\&) (esc #\N)] [(#\@) (esc #\A)] [(#\$) (esc #\O)] [else (list (char-upcase c))])) (string->list (symbol->string sym))))) ; decode a message using the encoding in a symbols.map file (define (net-decode-mapfile bytes path) (net-decode bytes (read-symmap-file path))) ; encode a message using the encoding in a symbols.map file, and update the file (define (net-encode-mapfile sexpr path) (let* ([symmap (read-symmap-file path)] [encoded (net-encode sexpr symmap)]) (write-symmap-file symmap path) encoded))
false
b6c720a08d0d05d4ea5027d1ba954948df3dac15
2c01a6143d8630044e3629f2ca8adf1455f25801
/xitomatl/tests/enumerators-tests.sps
ac11e143c68fc6000cd469c44f3963edc7d5dfff
[ "X11-distribute-modifications-variant" ]
permissive
stuhlmueller/scheme-tools
e103fac13cfcb6d45e54e4f27e409adbc0125fe1
6e82e873d29b34b0de69b768c5a0317446867b3c
refs/heads/master
2021-01-25T10:06:33.054510
2017-05-09T19:44:12
2017-05-09T19:44:12
1,092,490
5
1
null
null
null
null
UTF-8
Scheme
false
false
10,485
sps
enumerators-tests.sps
#!r6rs ;; Copyright 2009 Derick Eddington. My MIT-style license is in the file named ;; LICENSE from the original collection this file is distributed with. (import (rnrs) (rnrs mutable-pairs) (xitomatl enumerators) (srfi :78 lightweight-testing) (only (xitomatl lists) make-list last-pair) (only (xitomatl ports) port-closed?)) (define-syntax check-values (syntax-rules () ((_ expr => expected ...) (check (let-values ((vals expr)) vals) => (list expected ...))))) (define-syntax check-AV/msg (syntax-rules () ((_ msg expr) (check (guard (ex (else (and (assertion-violation? ex) (message-condition? ex) (condition-message ex)))) expr 'unexpected-return) => msg)))) ;;---------------------------------------------------------------------------- ;; lists ;;---------------------------------------------------------------------------- ;; basic (check-values (fold '() (lambda _ (assert #F))) => ) (check-values (fold '() (lambda _ (assert #F)) 1 2 3) => 1 2 3) (check-values (fold '(1) (lambda (x . s) (values #T (cons x s)))) => '(1)) (check-values (fold '(1 2) (lambda (x . s) (values #T (cons x s)))) => '(2 (1))) (check-values (fold '(1 2 3) (lambda (x . s) (values #T (cons x s)))) => '(3 (2 (1)))) (check-values (fold '(1 2 3 4) (lambda (x . s) (values #T x s))) => 4 '(3 (2 (1 ())))) (check-values (fold '(1 2 3 4 5) (lambda (x . s) (apply values #T x s))) => 5 4 3 2 1) ;; early termination (check-values (fold '(1 2 3 4 5 6) (lambda (x s) (if (< x 4) (values #T (+ x s)) (values #F s))) 123) => 129) (check-values (fold '(1 2 3 4 5 6) (lambda (x s) (if (< x 5) (values #T (+ x s)) (values #F s))) 123) => 133) ;; varying number of seed values (check-values (fold '(1 2 3 4 5 6 7) (lambda (x . s) (if (odd? x) (apply values #T 'foo s) (apply values #T (make-list x 'y)))) 'a 'b 'c) => 'foo 'y 'y 'y 'y 'y 'y) ;; exceptions (check-AV/msg "not a proper list" (fold '(1 . oops) (lambda _ #T))) (check-AV/msg "not a proper list" (fold '(1 2 . oops) (lambda _ #T))) (check-AV/msg "not a proper list" (fold '(1 2 3 . oops) (lambda _ #T))) (check-AV/msg "circular list" (fold (let ((t (list 1))) (set-cdr! t t) t) (lambda _ #T))) (check-AV/msg "circular list" (fold (let* ((t (list 2)) (l (cons 1 t))) (set-cdr! t l) l) (lambda _ #T))) (check-AV/msg "circular list" (fold (let* ((t (list 3)) (l (cons* 1 2 t))) (set-cdr! t l) l) (lambda _ #T))) (check-AV/msg "circular list" (fold (let ((l (make-list 12345 'foo))) (set-cdr! (last-pair l) l) l) (lambda _ #T))) ;;---------------------------------------------------------------------------- ;; vectors ;;---------------------------------------------------------------------------- ;; basic (check-values (fold '#() (lambda _ (assert #F))) => ) (check-values (fold '#() (lambda _ (assert #F)) 1 2 3) => 1 2 3) (check-values (fold '#(1) (lambda (x . s) (values #T (cons x s)))) => '(1)) (check-values (fold '#(1 2 3 4 5) (lambda (x . s) (apply values #T x s))) => 5 4 3 2 1) ;; early termination (check-values (fold '#(1 2 3 4 5 6) (lambda (x s) (if (< x 4) (values #T (+ x s)) (values #F s))) 123) => 129) ;; varying number of seed values (check-values (fold '#(1 2 3 4 5 6 7) (lambda (x . s) (if (odd? x) (apply values #T 'foo s) (apply values #T (make-list x 'y)))) 'a 'b 'c) => 'foo 'y 'y 'y 'y 'y 'y) ;;---------------------------------------------------------------------------- ;; strings (the strings enumerator uses the same implementation as vectors) ;;---------------------------------------------------------------------------- ;; basic (check-values (fold "" (lambda _ (assert #F))) => ) (check-values (fold "" (lambda _ (assert #F)) 1 2 3) => 1 2 3) (check-values (fold "1" (lambda (x . s) (values #T (cons x s)))) => '(#\1)) (check-values (fold "12345" (lambda (x . s) (apply values #T x s))) => #\5 #\4 #\3 #\2 #\1) ;;---------------------------------------------------------------------------- ;; procedures ;;---------------------------------------------------------------------------- ;; basic (check-values (fold (lambda () (values)) (lambda _ (assert #F))) => ) (check-values (fold (lambda () (values)) (lambda _ (assert #F)) 1 2 3) => 1 2 3) (define (make-gen . vals) (lambda () (if (null? vals) (values) (let ((v (car vals))) (set! vals (cdr vals)) v)))) (check-values (fold (make-gen 1 2 3) (lambda (x s) (values #T (+ x s))) 123) => 129) ;; early termination (check-values (fold (make-gen 1 2 3 4 5 6) (lambda (x s) (if (< x 5) (values #T (+ x s)) (values #F s))) 123) => 133) ;; varying number of seed values (check-values (fold (make-gen 1 2 3 4 5 6 7) (lambda (x . s) (if (odd? x) (apply values #T 'foo s) (apply values #T (make-list x 'y)))) 'a 'b 'c) => 'foo 'y 'y 'y 'y 'y 'y) ;;---------------------------------------------------------------------------- ;; custom fold specialization ;;---------------------------------------------------------------------------- (define-record-type thing (fields value)) (fold-specialize! thing? (lambda (coll proc seeds) (apply fold (reverse (thing-value coll)) proc seeds))) (check-values (fold (make-thing '(1 2 3 4 5)) (lambda (x . s) (apply values #T x s))) => 1 2 3 4 5) ;;---------------------------------------------------------------------------- ;; fold/enumerator and input-port-enumerator ;;---------------------------------------------------------------------------- (define sip0 (open-string-input-port "foo \"bar\" 123")) (check-values (fold/enumerator (input-port-enumerator get-datum) sip0 (lambda (x s) (values #T (cons x s))) '()) => '(123 "bar" foo)) (check (port-closed? sip0) => #F) (define sip1 (open-string-input-port "123 foo \"bar\"")) (check-values (fold/enumerator (input-port-enumerator get-char) sip1 (lambda (x s) (values #T (cons x s))) '()) => '(#\" #\r #\a #\b #\" #\space #\o #\o #\f #\space #\3 #\2 #\1)) (check (port-closed? sip1) => #F) (define text "Blah 123 ()\n\ \"another\" #\\l #(i n) #\\e\n\ a n d ((()))") (check (fold/enumerator (input-port-enumerator get-datum) (open-string-input-port text) (lambda (d a) (values #T (cons d a))) '()) => '(((())) d n a #\e #(i n) #\l "another" () 123 Blah)) (check (fold/enumerator (input-port-enumerator get-char) (open-string-input-port text) (lambda (c i) (if (< i 10) (values #T (+ 1 i)) (values #F c))) 0) => #\)) (check-values (fold/enumerator (input-port-enumerator get-char) (open-string-input-port text) (lambda (c) (values #F 1 2 3 4))) => 1 2 3 4) ;;---------------------------------------------------------------------------- ;; sequence ;;---------------------------------------------------------------------------- (define u8-e (sequence-enumerator bytevector-length bytevector-u8-ref)) ;; basic (check-values (fold/enumerator u8-e #vu8() (lambda _ (assert #F))) => ) (check-values (fold/enumerator u8-e #vu8() (lambda _ (assert #F)) 1 2 3) => 1 2 3) (check-values (fold/enumerator u8-e #vu8(1) (lambda (x . s) (values #T (cons x s)))) => '(1)) (check-values (fold/enumerator u8-e #vu8(1 2 3 4 5) (lambda (x . s) (apply values #T x s))) => 5 4 3 2 1) ;;---------------------------------------------------------------------------- ;; hashtables ;;---------------------------------------------------------------------------- (define (plist->hashtable . plist) (let ((ht (make-eq-hashtable))) (let loop ((plist plist)) (unless (null? plist) (hashtable-set! ht (car plist) (cadr plist)) (loop (cddr plist)))) ht)) ;; basic (check-values (fold (plist->hashtable) (lambda _ (assert #F))) => ) (check-values (fold (plist->hashtable) (lambda _ (assert #F)) 1 2 3) => 1 2 3) (check-values (fold (plist->hashtable 'a 1) (lambda (x . s) (values #T (cons x s)))) => '((a . 1))) (check (let-values ((r (fold (plist->hashtable 'a 1 'b 2 'c 3 'd 4 'e 5) (lambda (x . s) (apply values #T x s))))) (for-all (lambda (x) (and (member x r) #T)) '((a . 1) (b . 2) (c . 3) (d . 4) (e . 5)))) => #T) ;; early termination (check-values (fold (plist->hashtable 'a 1 'b 2 'c 3 'd 4 'e 5 'f 6) (lambda (x s) (values #F (+ 1 s))) 123) => 124) ;; varying number of seed values (check-values (fold (plist->hashtable 'a 1 'b 2 'c 3 'd 4 'e 5 'f 6 'g 7) (lambda (x . s) (if (odd? (cdr x)) (apply values #T 'foo s) (apply values #T s))) 'a 'b 'c) => 'foo 'foo 'foo 'foo 'a 'b 'c) (check-report)
true
7b5458f944ba561e7b4e7aa482370e558cc418f2
4fd95c081ccef6afc8845c94fedbe19699b115b6
/chapter_2/nested_mappings.scm
cb1ca07161c8c4fdfdeca3bf0ea98753161c765a
[ "MIT" ]
permissive
ceoro9/sicp
61ff130e655e705bafb39b4d336057bd3996195d
7c0000f4ec4adc713f399dc12a0596c770bd2783
refs/heads/master
2020-05-03T09:41:04.531521
2019-08-08T12:14:35
2019-08-08T12:14:35
178,560,765
1
0
null
null
null
null
UTF-8
Scheme
false
false
1,073
scm
nested_mappings.scm
(define (accumulate p start-value sequance) (define (iter c result) (if (null? c) result (iter (cdr c) (p (car c) result)))) (iter sequance start-value)) (define (enumerate-interval i j) (define (iter c result) (if (> c j) result (iter (+ c 1) (append result (list c))))) (iter i (list))) (define (get-pairs n) (accumulate append '() (map (lambda (i) (map (lambda (j) (cons i j)) (enumerate-interval 1 (- i 1)))) (enumerate-interval 1 n)))) (define (flatmap p seq) (accumulate append '() (map p seq))) (define (remove item s) (filter (lambda (x) (not (= item x))) s)) (define (permutations s) (if (null? s) (list '()) (flatmap (lambda (x) (map (lambda (p) (cons x p)) (permutations (remove x s)))) s))) (display (permutations (list 1 2 3)))
false
fdd6967adc9bf79c770ec14dd812dd0452dcfd4f
aa83a0110d917f0018e31e5144ead84ca08ba86b
/srfi/207/bytestrings-impl.scm
d30424867303844cd926547fee0f98ff156a0c6b
[]
permissive
Zipheir/srfi-207
2ff53642cd1a0e673083ae3b7c487e9c2aaddfda
bad4761a404cc9336ea6667f192285f5f7ccba35
refs/heads/master
2023-01-04T12:07:20.551279
2020-10-29T18:52:48
2020-10-29T18:52:48
297,557,032
0
0
MIT
2020-09-22T06:31:51
2020-09-22T06:31:50
null
UTF-8
Scheme
false
false
17,582
scm
bytestrings-impl.scm
;;; Copyright (C) 2020 Wolfgang Corcoran-Mathe ;;; ;;; Permission is hereby granted, free of charge, to any person obtaining a ;;; copy of this software and associated documentation files (the ;;; "Software"), to deal in the Software without restriction, including ;;; without limitation the rights to use, copy, modify, merge, publish, ;;; distribute, sublicense, and/or sell copies of the Software, and to ;;; permit persons to whom the Software is furnished to do so, subject to ;;; the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be included ;;; in all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ;;; OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. ;;; IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY ;;; CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ;;; TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE ;;; SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ;;;; Utility (define (exact-natural? x) (and (exact-integer? x) (not (negative? x)))) (define (u8-or-ascii-char? obj) (or (and (char? obj) (char<=? obj #\delete)) (and (exact-natural? obj) (< obj 256)))) (define (string-ascii? obj) (and (string? obj) (string-every (lambda (c) (char<=? c #\delete)) obj) #t)) (define (valid-bytestring-segment? obj) (or (bytevector? obj) (u8-or-ascii-char? obj) (string-ascii? obj))) (define (%bytestring-null? bstring) (zero? (bytevector-length bstring))) (define (%bytestring-last bstring) (assume (not (%bytestring-null? bstring)) "empty bytestring") (bytevector-u8-ref bstring (- (bytevector-length bstring) 1))) (define (negate pred) (lambda (obj) (not (pred obj)))) ;;;; Constructors (define (make-bytestring lis) (assume (or (pair? lis) (null? lis))) (call-with-port (open-output-bytevector) (lambda (out) (for-each (lambda (seg) (%write-bytestring-segment seg out)) lis) (get-output-bytevector out)))) (define (make-bytestring! bvec at lis) (assume (bytevector? bvec)) (assume (and (exact-natural? at) (< at (bytevector-length bvec)))) (bytevector-copy! bvec at (make-bytestring lis))) (define (%write-bytestring-segment obj port) ((cond ((and (exact-natural? obj) (< obj 256)) write-u8) ((and (char? obj) (char<=? obj #\delete)) write-char-binary) ((bytevector? obj) write-bytevector) ((string-ascii? obj) write-string-binary) (else (bytestring-error "invalid bytestring element" obj))) obj port)) ;; If your Scheme allows binary ports to function as textual ports, ;; get rid of this dance. (define (write-char-binary c port) (write-u8 (char->integer c) port)) (define (write-string-binary s port) (string-for-each (lambda (c) (write-char-binary c port)) s)) (define (bytestring . args) (if (null? args) (bytevector) (make-bytestring args))) ;;;; Conversion ;;; Hex string conversion ;; Convert an unsigned integer n to a bytevector representing ;; the base-256 big-endian form (the zero index holds the MSB). (define (integer->bytevector n) (assume (and (integer? n) (not (negative? n)))) (if (zero? n) (make-bytevector 1 0) (u8-list->bytevector (unfold-right zero? (lambda (n) (truncate-remainder n 256)) (lambda (n) (truncate-quotient n 256)) n)))) (define (integer->hex-string n) (cond ((number->string n 16) => (lambda (res) (if (even? (string-length res)) res (string-append "0" res)))) (else (bytestring-error "not an integer" n)))) (define (bytevector->hex-string bv) (assume (bytevector? bv)) (string-concatenate (list-tabulate (bytevector-length bv) (lambda (i) (integer->hex-string (bytevector-u8-ref bv i)))))) (define (hex-string->bytevector hex-str) (assume (string? hex-str)) (let ((len (string-length hex-str))) (unless (even? len) (bytestring-error "incomplete hexadecimal string" hex-str)) (u8vector-unfold (lambda (_ i) (let* ((end (+ i 2)) (s (substring hex-str i end)) (n (string->number s 16))) (if n (values n end) (bytestring-error "invalid hexadecimal sequence" s)))) (truncate-quotient len 2) 0))) (define bytevector->base64 (case-lambda ((bvec) (bytevector->base64 bvec "+/")) ((bvec digits) (assume (bytevector? bvec)) (assume (string? digits)) (utf8->string (base64-encode-bytevector bvec digits))))) (define base64->bytevector (case-lambda ((base64-string) (base64->bytevector base64-string "+/")) ((base64-string digits) (assume (string? base64-string)) (assume (string? digits)) (decode-base64-string base64-string digits)))) (define bytestring->list (case-lambda ((bstring) (bytestring->list bstring 0 (bytevector-length bstring))) ((bstring start) (bytestring->list bstring start (bytevector-length bstring))) ((bstring start end) (assume (bytevector? bstring)) (assume (and (exact-natural? start) (>= start 0)) "invalid start index" start bstring) (assume (and (exact-natural? end) (<= end (bytevector-length bstring))) "invalid end index" end bstring) (assume (>= end start) "invalid indices" start end) (unfold (lambda (i) (= i end)) (lambda (i) (let ((b (bytevector-u8-ref bstring i))) (if (and (>= b #x20) (< b #x7f)) (integer->char b) b))) (lambda (i) (+ i 1)) start)))) ;; Lazily generate the bytestring constructed from objs. (define (make-bytestring-generator . objs) (list->generator (flatten-bytestring-segments objs))) ;; Convert and flatten chars and strings, and flatten bytevectors ;; to yield a flat list of bytes. (define (flatten-bytestring-segments objs) (fold-right (lambda (x res) (cond ((and (exact-natural? x) (< x 256)) (cons x res)) ((and (char? x) (char<=? x #\delete)) (cons (char->integer x) res)) ((bytevector? x) (append (bytevector->u8-list x) res)) ((string-ascii? x) (append (map char->integer (string->list x)) res)) (else (bytestring-error "invalid bytestring segment" x)))) '() objs)) ;;;; Selection (define (%bytestring-pad-left-or-right bstring len char-or-u8 right) (assume (bytevector? bstring)) (assume (exact-natural? len)) (assume (u8-or-ascii-char? char-or-u8)) (let ((pad-len (- len (bytevector-length bstring))) (pad-byte (if (char? char-or-u8) (char->integer char-or-u8) char-or-u8))) (if (<= pad-len 0) (bytevector-copy bstring) (let ((padded (make-bytevector len pad-byte))) (bytevector-copy! padded (if right 0 pad-len) bstring) padded)))) (define (bytestring-pad bstring len char-or-u8) (%bytestring-pad-left-or-right bstring len char-or-u8 #f)) (define (bytestring-pad-right bstring len char-or-u8) (%bytestring-pad-left-or-right bstring len char-or-u8 #t)) (define (bytestring-trim bstring pred) (assume (bytevector? bstring)) (assume (procedure? pred)) (let ((new-start (bytestring-index bstring (negate pred)))) (if new-start (bytevector-copy bstring new-start) (bytevector)))) (define (bytestring-trim-right bstring pred) (assume (bytevector? bstring)) (assume (procedure? pred)) (cond ((bytestring-index-right bstring (negate pred)) => (lambda (end-1) (bytevector-copy bstring 0 (+ 1 end-1)))) (else (bytevector)))) (define (bytestring-trim-both bstring pred) (assume (bytevector? bstring)) (assume (procedure? pred)) (let ((neg-pred (negate pred))) (cond ((bytestring-index bstring neg-pred) => (lambda (start) (bytevector-copy bstring start (+ (bytestring-index-right bstring neg-pred) 1)))) (else (bytevector))))) ;;;; Replacement (define bytestring-replace (case-lambda ((bstring1 bstring2 start end) (bytestring-replace bstring1 bstring2 start end 0 (bytevector-length bstring2))) ((bstring1 bstring2 start1 end1 start2 end2) (assume (bytevector? bstring1)) (assume (bytevector? bstring2)) (assume (and (exact-natural? start1) (>= start1 0) (<= start1 end1)) "invalid start index" start1) (assume (and (exact-natural? end1) (<= end1 (bytevector-length bstring1))) "invalid end index" bstring1) (assume (and (exact-natural? start2) (>= start2 0) (<= start2 end2)) "invalid start index" start2) (assume (and (exact-natural? end2) (<= end2 (bytevector-length bstring2))) "invalid end index" bstring2) (if (and (= start1 end1) (= start2 end2)) (bytevector-copy bstring1) ; replace no bits with no bits (let* ((b1-len (bytevector-length bstring1)) (sub-len (- end2 start2)) (new-len (+ sub-len (- b1-len (- end1 start1)))) (bs-new (make-bytevector new-len))) (bytevector-copy! bs-new 0 bstring1 0 start1) (bytevector-copy! bs-new start1 bstring2 start2 end2) (bytevector-copy! bs-new (+ start1 sub-len) bstring1 end1 b1-len) bs-new))))) ;;;; Comparison (define (%bytestring-prefix-length bstring1 bstring2) (let ((end (min (bytevector-length bstring1) (bytevector-length bstring2)))) (if (eqv? bstring1 bstring2) ; fast path end (let lp ((i 0)) (if (or (>= i end) (not (= (bytevector-u8-ref bstring1 i) (bytevector-u8-ref bstring2 i)))) i (lp (+ i 1))))))) ;;; Primitive bytevector comparison functions. (define (%bytestring-compare bstring1 bstring2 res< res= res>) (let ((len1 (bytevector-length bstring1)) (len2 (bytevector-length bstring2))) (let ((match (%bytestring-prefix-length bstring1 bstring2))) (if (= match len1) (if (= match len2) res= res<) (if (= match len2) res> (if (< (bytevector-u8-ref bstring1 match) (bytevector-u8-ref bstring2 match)) res< res>)))))) (define (bytestring<? bstring1 bstring2) (assume (bytevector? bstring1)) (assume (bytevector? bstring2)) (and (not (eqv? bstring1 bstring2)) (%bytestring-compare bstring1 bstring2 #t #f #f))) (define (bytestring>? bstring1 bstring2) (assume (bytevector? bstring1)) (assume (bytevector? bstring2)) (and (not (eqv? bstring1 bstring2)) (%bytestring-compare bstring1 bstring2 #f #f #t))) (define (bytestring<=? bstring1 bstring2) (assume (bytevector? bstring1)) (assume (bytevector? bstring2)) (or (eqv? bstring1 bstring2) (%bytestring-compare bstring1 bstring2 #t #t #f))) (define (bytestring>=? bstring1 bstring2) (assume (bytevector? bstring1)) (assume (bytevector? bstring2)) (or (eqv? bstring1 bstring2) (%bytestring-compare bstring1 bstring2 #f #t #t))) ;;;; Searching (define bytestring-index (case-lambda ((bstring pred) (bytestring-index bstring pred 0)) ((bstring pred start) (bytestring-index bstring pred start (bytevector-length bstring))) ((bstring pred start end) (assume (bytevector? bstring)) (assume (procedure? pred)) (assume (exact-natural? start)) (assume (exact-natural? end)) (let lp ((i start)) (and (< i end) (if (pred (bytevector-u8-ref bstring i)) i (lp (+ i 1)))))))) (define bytestring-index-right (case-lambda ((bstring pred) (bytestring-index-right bstring pred 0)) ((bstring pred start) (bytestring-index-right bstring pred start (bytevector-length bstring))) ((bstring pred start end) (assume (bytevector? bstring)) (assume (procedure? pred)) (assume (exact-natural? start)) (assume (exact-natural? end)) (let lp ((i (- end 1))) (and (>= i start) (if (pred (bytevector-u8-ref bstring i)) i (lp (- i 1)))))))) (define (bytestring-break bstring pred) (assume (bytevector? bstring)) (assume (procedure? pred)) (cond ((bytestring-index bstring pred) => (lambda (len) (values (bytevector-copy bstring 0 len) (bytevector-copy bstring len)))) (else (values (bytevector-copy bstring) (bytevector))))) (define (bytestring-span bstring pred) (assume (bytevector? bstring)) (assume (procedure? pred)) (cond ((bytestring-index bstring (negate pred)) => (lambda (len) (values (bytevector-copy bstring 0 len) (bytevector-copy bstring len)))) (else (values (bytevector-copy bstring) (bytevector))))) ;;;; Joining & Splitting (define (%bytestring-join-nonempty bstrings delimiter grammar) (call-with-port (open-output-bytevector) (lambda (out) (when (eqv? grammar 'prefix) (write-bytevector delimiter out)) (write-bytevector (car bstrings) out) (for-each (lambda (bstr) (write-bytevector delimiter out) (write-bytevector bstr out)) (cdr bstrings)) (when (eqv? grammar 'suffix) (write-bytevector delimiter out)) (get-output-bytevector out)))) (define bytestring-join (case-lambda ((bstrings delimiter) (bytestring-join bstrings delimiter 'infix)) ((bstrings delimiter grammar) (assume (or (pair? bstrings) (null? bstrings))) (unless (memv grammar '(infix strict-infix prefix suffix)) (bytestring-error "invalid grammar" grammar)) (let ((delim-bstring (bytestring delimiter))) (if (pair? bstrings) (%bytestring-join-nonempty bstrings delim-bstring grammar) (if (eqv? grammar 'strict-infix) (bytestring-error "empty list with strict-infix grammar") (bytevector))))))) (define (%find-right bstring byte end) (bytestring-index-right bstring (lambda (b) (= b byte)) 0 end)) (define (%bytestring-infix-split bstring delimiter) (let lp ((token-end (bytevector-length bstring)) (split '())) (cond ((< token-end 0) split) ((%find-right bstring delimiter token-end) => (lambda (token-start-1) (lp token-start-1 (cons (bytevector-copy bstring (+ 1 token-start-1) token-end) split)))) (else (cons (bytevector-copy bstring 0 token-end) split))))) (define (%trim-byte bstring byte) (bytestring-trim bstring (lambda (b) (= b byte)))) (define (%trim-right-byte bstring byte) (bytestring-trim-right bstring (lambda (b) (= b byte)))) (define (%bytestring-split/trim-outliers bstring delimiter grammar) (let ((trimmed (case grammar ((infix strict-infix) bstring) ((prefix) (%trim-byte bstring delimiter)) ((suffix) (%trim-right-byte bstring delimiter))))) (%bytestring-infix-split trimmed delimiter))) (define bytestring-split (case-lambda ((bstring delimiter) (bytestring-split bstring delimiter 'infix)) ((bstring delimiter grammar) (assume (bytevector? bstring)) (assume (u8-or-ascii-char? delimiter)) (unless (memv grammar '(infix strict-infix prefix suffix)) (bytestring-error "invalid grammar" grammar)) (if (%bytestring-null? bstring) '() (%bytestring-split/trim-outliers bstring (if (char? delimiter) (char->integer delimiter) delimiter) grammar))))) ;;;; I/O (define backslash-codepoints '((7 . #\a) (8 . #\b) (9 . #\t) (10 . #\n) (13 . #\r) (34 . #\") (92 . #\\) (124 . #\|))) (define write-textual-bytestring (case-lambda ((bstring) (write-textual-bytestring bstring (current-output-port))) ((bstring port) (parameterize ((current-output-port port)) (write-string "#u8\"") (u8vector-for-each (lambda (b) (cond ((assv b backslash-codepoints) => (lambda (p) (write-char #\\) (write-char (cdr p)))) ((and (>= b #x20) (<= b #x7e)) (write-char (integer->char b))) (else (write-string "\\x") (write-string (number->string b 16)) (write-char #\;)))) bstring) (write-char #\"))))) (define (write-binary-bytestring port . args) (assume (binary-port? port)) (for-each (lambda (arg) (unless (valid-bytestring-segment? arg) (bytestring-error "invalid bytestring element" arg))) args) (for-each (lambda (seg) (%write-bytestring-segment seg port)) args))
false
aad72a7e535c2ce95df71b8899d8a5c29ccc97ae
defeada37d39bca09ef76f66f38683754c0a6aa0
/UnityEngine/unity-engine/social-platforms/active-platform.sls
146b75e27d8b5b7e40f988d3339cfe6f3bc23693
[]
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
286
sls
active-platform.sls
(library (unity-engine social-platforms active-platform) (export is? active-platform?) (import (ironscheme-clr-port)) (define (is? a) (clr-is UnityEngine.SocialPlatforms.ActivePlatform a)) (define (active-platform? a) (clr-is UnityEngine.SocialPlatforms.ActivePlatform a)))
false
47587d8995fe0eafd1936e28c2379652c5010849
defeada37d39bca09ef76f66f38683754c0a6aa0
/System/system/media/sound-player.sls
432b43e4be3b8f16634e0a4607c2199bd146748b
[]
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,100
sls
sound-player.sls
(library (system media sound-player) (export new is? sound-player? load play-looping play stop play-sync load-async is-load-completed? load-timeout-get load-timeout-set! load-timeout-update! sound-location-get sound-location-set! sound-location-update! stream-get stream-set! stream-update! tag-get tag-set! tag-update!) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Media.SoundPlayer a ...))))) (define (is? a) (clr-is System.Media.SoundPlayer a)) (define (sound-player? a) (clr-is System.Media.SoundPlayer a)) (define-method-port load System.Media.SoundPlayer Load (System.Void)) (define-method-port play-looping System.Media.SoundPlayer PlayLooping (System.Void)) (define-method-port play System.Media.SoundPlayer Play (System.Void)) (define-method-port stop System.Media.SoundPlayer Stop (System.Void)) (define-method-port play-sync System.Media.SoundPlayer PlaySync (System.Void)) (define-method-port load-async System.Media.SoundPlayer LoadAsync (System.Void)) (define-field-port is-load-completed? #f #f (property:) System.Media.SoundPlayer IsLoadCompleted System.Boolean) (define-field-port load-timeout-get load-timeout-set! load-timeout-update! (property:) System.Media.SoundPlayer LoadTimeout System.Int32) (define-field-port sound-location-get sound-location-set! sound-location-update! (property:) System.Media.SoundPlayer SoundLocation System.String) (define-field-port stream-get stream-set! stream-update! (property:) System.Media.SoundPlayer Stream System.IO.Stream) (define-field-port tag-get tag-set! tag-update! (property:) System.Media.SoundPlayer Tag System.Object))
true
3267af047c38c100953b5300fa20da3258e2a8fe
29ed9782cedb0ad46f922fc6d8a1aa90f61cd7a1
/lib/reader/read-file.scm
1df19036973694cb632b8db5bcf48ddf8e535e25
[]
no_license
uson-compiladores/proyecto-final-eduardo
fccdc2291252ba61d7dd148aade277c9e082e91f
6cfdb10b13c073856a23fef2215448ede303e117
refs/heads/master
2021-01-10T02:09:16.541021
2015-12-13T02:40:31
2015-12-13T02:40:31
47,208,716
0
0
null
null
null
null
UTF-8
Scheme
false
false
123
scm
read-file.scm
(define (read-file path) (define raw-input (stream-from-file path)) (syntax->expression (run-parser (lex raw-input))))
false
d23a0c2e937388d94c436f5c5c6602cd143c8cce
a74932f6308722180c9b89c35fda4139333703b8
/edwin48/utlwin.scm
de39ca2981bcaee53fc35cf66a388fd0b82fa585
[]
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
4,327
scm
utlwin.scm
#| -*-Scheme-*- $Id: utlwin.scm,v 1.66 2008/01/30 20:02:07 cph Exp $ Copyright (C) 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Massachusetts Institute of Technology This file is part of MIT/GNU Scheme. MIT/GNU Scheme is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. MIT/GNU Scheme is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MIT/GNU Scheme; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. |# ;;;; Utility Windows ;;;; Blank Window (define-class blank-window vanilla-window ()) (define (blank-window:update-display! window screen x-start y-start xl xu yl yu display-style) window display-style ;ignore (screen-clear-rectangle screen (fix:+ x-start xl) (fix:+ x-start xu) (fix:+ y-start yl) (fix:+ y-start yu) #f) #t) (define-method blank-window :update-display! blank-window:update-display!) ;;;; Vertical Border Window (define-class vertical-border-window vanilla-window ()) (define-method vertical-border-window (:initialize! window window*) (with-instance-variables vertical-border-window window (x-size) (usual==> window :initialize! window*) (set! x-size 1))) (define-method vertical-border-window (:set-x-size! window x) window ;ignore (error "Can't change the x-size of a vertical border window" x)) (define-method vertical-border-window (:set-size! window x y) (if (not (fix:= x 1)) (error "Can't change the x-size of a vertical border window" x)) (with-instance-variables vertical-border-window window (x-size y-size redisplay-flags) (set! x-size x) (set! y-size y) (setup-redisplay-flags! redisplay-flags))) (define (vertical-border-window:update-display! window screen x-start y-start xl xu yl yu display-style) display-style ;ignore (if (fix:< xl xu) (clip-window-region-1 yl yu (window-y-size window) (lambda (yl yu) (let ((xl (fix:+ x-start xl)) (yu (fix:+ y-start yu))) (let loop ((y (fix:+ y-start yl))) (if (fix:< y yu) (begin (screen-output-char screen xl y #\| #f) (loop (fix:+ y 1))))))))) #t) (define-method vertical-border-window :update-display! vertical-border-window:update-display!) ;;;; Cursor Window (define-class cursor-window vanilla-window (enabled?)) (define-method cursor-window (:initialize! window window*) (with-instance-variables cursor-window window (x-size y-size enabled?) (usual==> window :initialize! window*) (set! x-size 1) (set! y-size 1) (set! enabled? #f))) (define-method cursor-window (:set-x-size! window x) window ;ignore (error "Can't change the size of a cursor window" x)) (define-method cursor-window (:set-y-size! window y) window ;ignore (error "Can't change the size of a cursor window" y)) (define-method cursor-window (:set-size! window x y) window ;ignore (error "Can't change the size of a cursor window" x y)) (define (cursor-window:update-display! window screen x-start y-start xl xu yl yu display-style) display-style ;ignore (if (and (with-instance-variables cursor-window window (enabled?) enabled?) (fix:< xl xu) (fix:< yl yu)) (screen-move-cursor screen x-start y-start)) #t) (define-method cursor-window :update-display! cursor-window:update-display!) (define-method cursor-window (:enable! window) (with-instance-variables cursor window (enabled? redisplay-flags) (set! enabled? #t) (setup-redisplay-flags! redisplay-flags))) (define-method cursor-window (:disable! window) (with-instance-variables cursor-window window (enabled? redisplay-flags) (set! enabled? #f) (set-car! redisplay-flags #f))) ;; ;; Local Variables: ;; eval: (put 'with-instance-variables 'scheme-indent-function 3) ;; End: ;;
false
584d974c48be6d814cdde6007f1264da2b5a2236
46244bb6af145cb393846505f37bf576a8396aa0
/sicp/3_25.scm
b33cb3691ca5d6f5980e99b2a4fd7e306eb9ce22
[]
no_license
aoeuidht/homework
c4fabfb5f45dbef0874e9732c7d026a7f00e13dc
49fb2a2f8a78227589da3e5ec82ea7844b36e0e7
refs/heads/master
2022-10-28T06:42:04.343618
2022-10-15T15:52:06
2022-10-15T15:52:06
18,726,877
4
3
null
null
null
null
UTF-8
Scheme
false
false
2,157
scm
3_25.scm
; Exercise 3.25. Generalizing one- and two-dimensional tables, show how to implement ; a table in which values are stored under an arbitrary number of keys and different ; values may be stored under different numbers of keys. The lookup and insert! ; procedures should take as input a list of keys used to access the table. (define (make-table) (let ((local-table (list '*table*))) (define (lookup key) (let ((record (assoc key (cdr local-able)))) (if record (cdr record) false))) (define (assoc key records) (cond ((null? records) #f) ((equal? key (caar records)) (car records)) (else (assoc key (cdr records))))) (define (r-lookup keys) (let ((r (assoc (car keys) (cdr local-table)))) (if r (cond ((null? (cdr keys)) (cdr r)) (else (((cdr r) 'r-lookup) (cdr keys)))) #f))) (define (r-insert! keys value) (if (null? (cdr keys)) (insert! (car keys) value) (let ((record (assoc (car keys) (cdr local-table)))) (if record (((cdr record) 'r-insert!) (cdr keys) value) ; if no record available, create new table, then insert (let ((tb (make-table))) ((tb 'r-insert!) (cdr keys) value) ; insert to new table (insert! (car keys) tb)))))) (define (insert! key value) (let ((record (assoc key (cdr local-table)))) (if record (set-cdr! record value) (set-cdr! local-table (cons (cons key value) (cdr local-table))))) 'ok) (define (pnt-table) local-table) (define (dispatch m) (cond ((eq? m 'lookup-proc) lookup) ((eq? m 'insert-proc!) insert!) ((eq? m 'r-insert!) r-insert!) ((eq? m 'r-lookup) r-lookup) ((eq? m 'pnt) pnt-table) (else (error "Unknown operation -- TABLE" m)))) dispatch)) (define t (make-table)) ((t 'r-insert!) '(1 2 3 4 5) 10) ((t 'pnt)) ((t 'r-lookup) '(1 2 3 4 5)) ((t 'r-lookup) '(1 2 3 4)) ((t 'r-lookup) '(1 2 3 4 6))
false
758e8212549c9dec758ca1b96a1e4fe15d751607
c5de45adc74a609415f9318fda24479561a5728b
/day28-in-class.ss
9a5d20a6e9b3306141e10da3c1b0c40ff4f77b34
[]
no_license
rhit-zhuz9/CSSE304
8b7498336cf9573b18b3cd0f5654ddfb1b1dfc69
f3a10bf17ca1daa532f277a0cf4f7c9746ea89e7
refs/heads/master
2023-03-15T11:54:52.913169
2018-05-30T03:00:43
2018-05-30T03:00:43
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
408
ss
day28-in-class.ss
(define deref cell-ref) (define set-ref! cell-set!) (define apply-env-ref (lambda (env val) ; same code we had before apply-env )) (define apply-env (lambda (env var) (deref (apply-env-ref env var)))) (define cell (lambda (x) (cons x 'this-is-a-cell))) (define cell-ref car) (define cell-set! set-car!) (define cell? (lambda (obj) (and (pair? obj) (eq? (cdr obj) 'this-is-a-cell))))
false
1a6424ec1eaeba188a319dafc8df15fad1cba670
1b771524ff0a6fb71a8f1af8c7555e528a004b5e
/ex361.scm
e8d52ea365ce147b0923dddcb8bd2743e9560f5d
[]
no_license
yujiorama/sicp
6872f3e7ec4cf18ae62bb41f169dae50a2550972
d106005648b2710469067def5fefd44dae53ad58
refs/heads/master
2020-05-31T00:36:06.294314
2011-05-04T14:35:52
2011-05-04T14:35:52
315,072
0
0
null
null
null
null
UTF-8
Scheme
false
false
177
scm
ex361.scm
(load "./chapter3.scm") (load "./ex360.scm") (define (invert-unit-series s) (cons-stream 1 (mul-series (scale-stream (stream-cdr s) -1) (invert-unit-series s))))
false
95d763cf6d488bf5016bdba86e4ccf533845184c
0bb7631745a274104b084f6684671c3ee9a7b804
/lib/gambit/list/list.scm
2abed9068a2638cefac05d523b49ce744c103a84
[ "Apache-2.0", "LGPL-2.1-only", "LicenseRef-scancode-free-unknown", "GPL-3.0-or-later", "LicenseRef-scancode-autoconf-simple-exception" ]
permissive
feeley/gambit
f87fd33034403713ad8f6a16d3ef0290c57a77d5
7438e002c7a41a5b1de7f51e3254168b7d13e8ba
refs/heads/master
2023-03-17T06:19:15.652170
2022-09-05T14:31:53
2022-09-05T14:31:53
220,799,690
0
1
Apache-2.0
2019-11-10T15:09:28
2019-11-10T14:14:16
null
UTF-8
Scheme
false
false
65,026
scm
list.scm
;;;============================================================================ ;;; File: "list.scm" ;;; Copyright (c) 1994-2021 by Marc Feeley, All Rights Reserved. ;;;============================================================================ ;;; List operations. (##include "list#.scm") ;;;---------------------------------------------------------------------------- (implement-check-type-pair) (implement-check-type-pair-list) (implement-check-type-deeper-pair-tree) (implement-check-type-list-list) (implement-check-type-list) (implement-check-type-longer-list) (implement-check-type-proper-list) (implement-check-type-proper-or-circular-list) ;;;---------------------------------------------------------------------------- (define-prim&proc (pair? (obj object))) (define-prim&proc (cons (obj1 object) (obj2 object))) (##define-macro (define-prim&proc-c...r from-length to-length) (define (gen-name pattern) (define (ads pattern) (if (= pattern 1) "" (string-append (ads (quotient pattern 2)) (if (odd? pattern) "d" "a")))) (string->symbol (string-append "c" (ads pattern) "r"))) (define (gen3 i j) (if (> i j) `() (let ((name (gen-name i))) (define (gen1 var pattern) (if (<= pattern 3) `(primitive (,(if (= pattern 3) `cdr `car) ,var)) `(let ((x (primitive (,(if (odd? pattern) `cdr `car) ,var)))) ,(gen1 'x (quotient pattern 2))))) (define (gen2 var pattern) (let ((body (if (<= pattern 3) `(primitive (,(if (= pattern 3) `cdr `car) ,var)) `(let ((x (primitive (,(if (odd? pattern) `cdr `car) ,var)))) (macro-force-vars (x) ,(gen2 'x (quotient pattern 2))))))) (if (eq? var 'pair) ;; avoid repeating initial pair check body `(macro-check-deeper-pair-tree-pair ,var '(1 . pair) ((%procedure%) pair) ,body)))) `((define-primitive (,name (pair pair)) ,(gen1 'pair i)) (define-procedure (,name (pair pair)) (macro-force-vars (pair) ,(gen2 'pair i))) ,@(gen3 (+ i 1) j))))) `(begin ,@(gen3 (expt 2 from-length) (- (expt 2 (+ to-length 1)) 1)))) (define-prim&proc-c...r 1 4) ;; define car to cddddr (define-primitive (set-car! (pair pair) (obj object))) (define-procedure (set-car! (pair pair) (obj object)) (primitive (set-car! pair obj)) (void)) (define-primitive (set-cdr! (pair pair) (obj object))) (define-procedure (set-cdr! (pair pair) (obj object)) (primitive (set-cdr! pair obj)) (void)) (define-prim&proc (null? (obj object))) ;; Floyd's tortoise and hare algorithm for cycle detection ;; https://en.wikipedia.org/wiki/Cycle_detection ;; These procedures may get into an infinite loop if another thread ;; mutates "lst" (if fast and slow each point to disconnected cycles). (define-primitive (possibly-cyclic-tail lst) (let loop ((fast lst) (slow lst)) (macro-force-vars (fast) (if (not (pair? fast)) fast (let ((fast (cdr fast))) (macro-force-vars (fast slow) (cond ((eq? fast slow) ;; Cycle detected. Return some pair in the cycle. fast) ((not (pair? slow)) ;; This case is possible if other threads mutate ;; the list. slow) ((pair? fast) (loop (cdr fast) (cdr slow))) (else fast)))))))) (define-prim&proc (proper-list? (x object)) (null? (primitive (possibly-cyclic-tail x)))) (define-prim&proc (circular-list? (x object)) (pair? (primitive (possibly-cyclic-tail x)))) (define-prim&proc (dotted-list? (x object)) (let ((tail (primitive (possibly-cyclic-tail x)))) (not (or (null? tail) (pair? tail))))) (define-prim&proc (list? (x object)) (null? (primitive (possibly-cyclic-tail x)))) (define-prim&proc (list (objs object) ...) objs) (define-primitive (length (list proper-list)) ;; Note: this code enters an infinite loop when given a circular list (let loop ((x list) (n 0)) (if (pair? x) (loop (cdr x) (fx+ n 1)) n))) (define-procedure (length (list proper-list)) ;; Note: this code enters an infinite loop when given a circular list (let loop ((x list) (n 0)) (macro-force-vars (x) (if (pair? x) (loop (cdr x) (fx+ n 1)) (macro-check-proper-list-null* x list '(1 . list) ((%procedure%) list) n))))) (define-prim&proc (length+ (clist proper-or-circular-list)) (define (err x) (if (eq? x clist) (macro-fail-check-list '(1 . clist) ((%procedure%) clist)) (macro-fail-check-proper-or-circular-list '(1 . clist) ((%procedure%) clist)))) (let loop ((len 0) (fast clist) (slow clist)) (macro-force-vars (fast) (cond ((null? fast) (fx* 2 len)) ((not (pair? fast)) (err fast)) (else (let ((fast (cdr fast))) (macro-force-vars (fast slow) (cond ((eq? fast slow) ;; Cycle detected. #f) ((null? slow) len) ((not (pair? slow)) ;; This case is possible if other threads mutate ;; the list. (err slow)) ((null? fast) (fx+ 1 (fx* 2 len))) ((not (pair? fast)) (err fast)) (else (loop (fx+ len 1) (cdr fast) (cdr slow))))))))))) (define-primitive (proper-list-append2 (list1 list) (list2 list)) (define (app list1 list2) (if (pair? list1) (cons (car list1) (app (cdr list1) list2)) (and (null? list1) list2))) (app list1 list2)) (define-primitive (append2 (list1 list) (list2 list)) (define (app list1 list2) (if (pair? list1) (cons (car list1) (app (cdr list1) list2)) list2)) (app list1 list2)) (define-primitive (append-lists (list-of-lists proper-list)) (if (pair? list-of-lists) (let ((rlst (reverse list-of-lists))) (let loop ((rlst (cdr rlst)) (result (car rlst))) (if (pair? rlst) (loop (cdr rlst) (primitive (append2 (car rlst) result))) result))) '())) (define-primitive (append (list1 list (macro-absent-obj)) (list2 list (macro-absent-obj)) (lists list) ...) (if (eq? list2 (macro-absent-obj)) (if (eq? list1 (macro-absent-obj)) '() list1) (if (null? lists) (primitive (append2 list1 list2)) (primitive (append-lists (cons list1 (cons list2 lists))))))) (define-procedure (append (list1 list (macro-absent-obj)) (list2 list (macro-absent-obj)) (lists list) ...) (define (append-multiple list1 other-lists arg-num1) (if (null? other-lists) list1 (macro-force-vars (list1) (if (null? list1) (append-multiple (car other-lists) (cdr other-lists) (fx+ arg-num1 1)) (list-expected-check (if (pair? list1) (append-multiple-pair list1 other-lists arg-num1 (fx+ arg-num1 1)) (fx- arg-num1))))))) ;; error: list expected (define (append-multiple-pair list1 other-lists arg-num1 arg-num2) ;; list1 is a pair, returns fixnum on error (let ((list2 (car other-lists)) (tail (cdr other-lists))) (if (null? tail) (append-2-pair list1 list2 arg-num1) (macro-force-vars (list2) (if (null? list2) (append-multiple-pair list1 tail arg-num1 (fx+ arg-num2 1)) (if (pair? list2) (let ((result (append-multiple-pair list2 tail arg-num2 (fx+ arg-num2 1)))) (macro-if-checks (if (fixnum? result) result (append-2-pair list1 result arg-num1)) (append-2-pair list1 result arg-num1))) (fx- arg-num2))))))) ;; error: list expected (define (append-2-pair list1 list2 arg-num1) ;; list1 is a pair, returns fixnum on error (let ((result (cons (car list1) '()))) (let loop ((last result) (tail (cdr list1))) (macro-force-vars (tail) (if (pair? tail) (let ((next (cons (car tail) '()))) (set-cdr! last next) (loop next (cdr tail))) (begin (set-cdr! last list2) (macro-if-checks (if (null? tail) result arg-num1) ;; error: proper list expected result))))))) (define (list-expected-check result) (macro-if-checks (if (fixnum? result) (if (fx< result 0) (macro-fail-check-list (fx- result) ((%procedure%) list1 list2 . lists)) (macro-fail-check-proper-list result ((%procedure%) list1 list2 . lists))) result) result)) (cond ((eq? list2 (macro-absent-obj)) (if (eq? list1 (macro-absent-obj)) '() list1)) ((null? lists) (macro-force-vars (list1) (if (null? list1) list2 (list-expected-check (if (pair? list1) (append-2-pair list1 list2 1) -1))))) ;; error: list expected (else (append-multiple list1 (cons list2 lists) 1)))) (define-primitive (proper-list-reverse (list list)) (let loop ((x list) (result '())) (if (pair? x) (loop (cdr x) (cons (car x) result)) (and (null? x) result)))) (define-primitive (reverse (list proper-list)) (let loop ((x list) (result '())) (if (pair? x) (loop (cdr x) (cons (car x) result)) result))) (define-procedure (reverse (list proper-list)) (let loop ((x list) (result '())) (macro-force-vars (x) (if (pair? x) (loop (cdr x) (cons (car x) result)) (macro-check-proper-list-null* x list '(1 . list) ((%procedure%) list) result))))) (define-primitive (list-ref (list pair) (k index)) (let loop ((x list) (i k)) (if (fx< 0 i) (loop (cdr x) (fx- i 1)) (car x)))) (define-procedure (list-ref (list pair) (k index)) (let loop ((x list) (i k)) (if (fx< 0 i) (let ((cdr-x (cdr x))) (macro-force-vars (cdr-x) (macro-check-longer-list-pair cdr-x '(1 . list) ((%procedure%) list k) (loop cdr-x (fx- i 1))))) (car x)))) (define-primitive (list-set! (list pair) (k index) (obj object)) (let loop ((x list) (i k)) (if (fx< 0 i) (loop (cdr x) (fx- i 1)) (begin (set-car! x obj) (void))))) (define-procedure (list-set! (list pair) (k index) (obj object)) (let loop ((x list) (i k)) (if (fx< 0 i) (let ((cdr-x (cdr x))) (macro-force-vars (cdr-x) (macro-check-longer-list-pair cdr-x '(1 . list) ((%procedure%) list k obj) (loop cdr-x (fx- i 1))))) (macro-check-mutable x '(1 . list) ((%procedure%) list k obj) (begin (set-car! x obj) (void)))))) (define-primitive (list-set (list pair) (k index) (obj object)) (define (set x i) (if (fx< 0 i) (cons (car x) (set (cdr x) (fx- i 1))) (cons obj (cdr x)))) (set list k)) (define-procedure (list-set (list pair) (k index) (obj object)) (define (process x i obj) (let ((cdr-x (cdr x))) (if (fx< 0 i) (macro-force-vars (cdr-x) (macro-if-checks (and (pair? cdr-x) (let ((r (process cdr-x (fx- i 1) obj))) (if (pair? r) (cons (car x) r) r))) (let ((r (process cdr-x (fx- i 1) obj))) (if (pair? r) (cons (car x) r) r)))) (cons obj cdr-x)))) (macro-if-checks (let ((r (process list k obj))) (or r (macro-fail-check-longer-list '(1 . list) ((%procedure%) list k obj)))) (process list k obj))) (define-primitive (memq (obj object) (list proper-list)) (let loop ((x list)) (if (pair? x) (if (eq? obj (car x)) x (loop (cdr x))) #f))) (define-procedure (memq (obj object) (list proper-list)) (let loop ((x list)) (macro-force-vars (x) (if (pair? x) (let ((y (car x))) (macro-force-vars (y) (if (eq? obj y) x (loop (cdr x))))) (macro-check-proper-list-null* x list '(2 . list) ((%procedure%) obj list) #f))))) (define-primitive (memv (obj object) (list proper-list)) (let loop ((x list)) (if (pair? x) (if (let () (declare (generic)) ;; avoid fixnum specific eqv? (eqv? obj (car x))) x (loop (cdr x))) #f))) (define-procedure (memv (obj object) (list proper-list)) (let loop ((x list)) (macro-force-vars (x) (if (pair? x) (let ((y (car x))) (macro-force-vars (y) (if (let () (declare (generic)) ;; avoid fixnum specific eqv? (eqv? obj y)) x (loop (cdr x))))) (macro-check-proper-list-null* x list '(2 . list) ((%procedure%) obj list) #f))))) (define-primitive (member (obj object) (list proper-list) (compare procedure (primitive equal?))) (let loop ((x list)) (if (pair? x) (if (compare obj (car x)) x (loop (cdr x))) #f))) (define-procedure (member (obj object) (list proper-list) (compare procedure (primitive equal?))) (let loop ((x list)) (macro-force-vars (x) (if (pair? x) (let ((y (car x))) (if (compare obj y) x (loop (cdr x)))) (macro-check-proper-list-null* x list '(2 . list) ((%procedure%) obj list %compare) ;; need to use %compare to avoid showing a third argument when none was given #f))))) ;; ##assq defined in _kernel.scm (define-procedure (assq (obj object) (alist pair-list)) (let loop ((x alist)) (macro-force-vars (x) (if (pair? x) (let ((couple (car x))) (macro-force-vars (couple) (macro-check-pair-list-pair couple '(2 . alist) ((%procedure%) obj alist) (let ((y (car couple))) (macro-force-vars (y) (if (eq? obj y) couple (loop (cdr x)))))))) (macro-check-proper-list-null* x alist '(2 . alist) ((%procedure%) obj alist) #f))))) (define-primitive (assv (obj object) (alist pair-list)) (let loop ((x alist)) (if (pair? x) (let ((couple (car x))) (if (let () (declare (generic)) ;; avoid fixnum specific eqv? (eqv? obj (car couple))) couple (loop (cdr x)))) #f))) (define-procedure (assv (obj object) (alist pair-list)) (let loop ((x alist)) (macro-force-vars (x) (if (pair? x) (let ((couple (car x))) (macro-force-vars (couple) (macro-check-pair-list-pair couple '(2 . alist) ((%procedure%) obj alist) (let ((y (car couple))) (macro-force-vars (y) (if (let () (declare (generic)) ;; avoid fixnum specific eqv? (eqv? obj y)) couple (loop (cdr x)))))))) (macro-check-proper-list-null* x alist '(2 . alist) ((%procedure%) obj alist) #f))))) (define-primitive (assoc (obj object) (alist pair-list) (compare procedure (primitive equal?))) (let loop ((x alist)) (if (pair? x) (let ((couple (car x))) (if (compare obj (car couple)) couple (loop (cdr x)))) #f))) (define-procedure (assoc (obj object) (alist pair-list) (compare procedure (primitive equal?))) (let loop ((x alist)) (macro-force-vars (x) (if (pair? x) (let ((couple (car x))) (macro-force-vars (couple) (macro-check-pair-list-pair couple '(2 . alist) ((%procedure%) obj alist %compare) ;; need to use %compare to avoid showing a third argument when none was given (let ((y (car couple))) (if (compare obj y) couple (loop (cdr x))))))) (macro-check-proper-list-null* x alist '(2 . alist) ((%procedure%) obj alist %compare) ;; need to use %compare to avoid showing a third argument when none was given #f))))) (define-primitive (assoc-string-equal? (str string) (alist pair-list)) (let loop ((x alist)) (if (pair? x) (let ((couple (car x))) (if (primitive (string-equal? str (car couple))) couple (loop (cdr x)))) #f))) (define-macro (macro-filter prim-call list var test-expr) `(let ((lst ,list)) (define (filter-tail lst) (if (pair? lst) (let* ((,var (car lst)) (matches? ,test-expr) (old-tail (cdr lst)) (new-tail (filter-tail old-tail))) (if (and (or (pair? new-tail) (null? new-tail)) matches?) (if (eq? old-tail new-tail) lst (cons x new-tail)) new-tail)) (macro-if-checks (and (null? lst) lst) lst))) (macro-if-checks (let ((new-lst (filter-tail lst))) (if (or (pair? new-lst) (null? new-lst)) new-lst (if (or (pair? lst) (null? lst)) (macro-fail-check-proper-list '(2 . list) ,(cons '(%procedure%) (cdr prim-call))) (macro-fail-check-list '(2 . list) ,(cons '(%procedure%) (cdr prim-call)))))) (filter-tail lst)))) (define-prim&proc (filter (pred procedure) (list proper-list)) (macro-filter (filter pred list) list x (pred x))) (define-prim&proc (remove (pred procedure) (list proper-list)) (macro-filter (remove pred list) list x (not (pred x)))) (define-prim&proc (remq (elem object) (list proper-list)) (macro-filter (remq elem list) list x (not (eq? x elem)))) (define-prim&proc (partition (pred procedure) (list proper-list)) (let ((lst list)) (define (partition-tail lst) (if (pair? lst) (let* ((x (car lst)) (matches? (pred x)) (tail (cdr lst))) (call-with-values (lambda () (partition-tail tail)) (lambda (in out) (if matches? (values (if (or (pair? in) (null? in)) (if (eq? tail in) lst (cons x in)) in) out) (values in (if (or (pair? out) (null? out)) (if (eq? tail out) lst (cons x out)) out)))))) (macro-if-checks (if (null? lst) (values lst lst) (values #t #t)) (values lst lst)))) (macro-if-checks (call-with-values (lambda () (partition-tail lst)) (lambda (in out) (if (and (or (pair? in) (null? in)) (or (pair? out) (null? out))) (values in out) (if (or (pair? lst) (null? lst)) (macro-fail-check-proper-list '(2 . list) ((%procedure%) pred list)) (macro-fail-check-list '(2 . list) ((%procedure%) pred list)))))) (partition-tail lst)))) ;;;---------------------------------------------------------------------------- (define ##allow-length-mismatch? #t) (define (##allow-length-mismatch?-set! x) (set! ##allow-length-mismatch? x)) (define-primitive (proper-list-length (list list)) (let loop ((list list) (n 0)) (macro-force-vars (list) (cond ((pair? list) (loop (cdr list) (fx+ n 1))) ((null? list) n) (else #f))))) ;; return #f when argument is a dotted list (define-primitive (cars (lists proper-list) (end proper-list)) (define (cars lists end) ;; assumes lists is a list of pairs (if (pair? lists) (let ((list1 (car lists))) (macro-force-vars (list1) (cons (car list1) (cars (cdr lists) end)))) end)) (cars lists end)) (define-primitive (cdrs (lists proper-list)) ;; This procedure computes (map cdr lists) and also checks for ;; special cases, such as one of the elements not being a pair. ;; The return value r depends on the case. Here are the cases when ;; ##allow-length-mismatch? is #f: ;; ;; 1) r = () : lists is () ;; ;; 2) r is a pair : all the elements of lists are pairs ;; ;; 3) r = #f : lists is not () and all the elements of lists are () ;; ;; 4) r is a fixnum > 0 : at least one of the elements of lists is neither ;; () or a pair and the element at index r-1 is ;; the first such element ;; ;; 5) r is a fixnum < 0 : the elements of lists are a mix of () and pairs ;; and the element at index -r-1 is the first () ;; (this case only happens when ;; ##allow-length-mismatch? is #f) (define (cdrs lists) (if (pair? lists) (let* ((tail (cdrs (cdr lists))) (list1 (car lists))) (macro-force-vars (list1) (cond ((pair? list1) (cond ((fixnum? tail) (if (fx< tail 0) (fx- tail 1) (fx+ tail 1))) ((not tail) (if ##allow-length-mismatch? #f -2)) ;; element at index 1 is () (else ;; () or pair (cons (cdr list1) tail)))) ((null? list1) (cond ((fixnum? tail) (if (fx< tail 0) -1 ;; element at index 0 is () (fx+ tail 1))) ((pair? tail) (if ##allow-length-mismatch? #f -1)) ;; element at index 0 is () (else ;; () or #f #f))) (else 1)))) ;; element at index 0 is not () or a pair '())) (cdrs lists)) (define-primitive (map (proc procedure) (list1 proper-list) (lists proper-list) ...) (define (map-1 list1) (define (map-1* lst1) (if (pair? lst1) (let* ((result (proc (car lst1))) (tail (map-1* (cdr lst1)))) (cons result tail)) '())) (map-1* list1)) (define (map-n list1-lists) (define (map-n lsts) (let ((rests (primitive (cdrs lsts)))) (if (pair? rests) (let* ((args (primitive (cars lsts '()))) (result (apply proc args)) (tail (map-n rests))) (cons result tail)) '()))) (map-n list1-lists)) (if (null? lists) (map-1 list1) (map-n (cons list1 lists)))) (define-procedure (map (proc procedure) (list1 proper-list) (lists proper-list) ...) (define (map-1 list1) (define (map-1* lst1) (macro-force-vars (lst1) (if (pair? lst1) (let* ((result (proc (car lst1))) (tail (map-1* (cdr lst1)))) (macro-if-checks (and tail (cons result tail)) (cons result tail))) (macro-if-checks (if (null? lst1) '() #f) '())))) (macro-if-checks (if (null? list1) '() (if (pair? list1) (let ((result (map-1* list1))) (or result (macro-fail-check-proper-list '(2 . list1) ((%procedure%) proc list1)))) (macro-fail-check-list '(2 . list1) ((%procedure%) proc list1)))) (map-1* list1))) (define (map-n list1-lists) (define (map-n* lsts rests) (if (not rests) '() (if (pair? rests) (let* ((args (primitive (cars lsts '()))) (result (apply proc args)) (tail (map-n* rests (primitive (cdrs rests))))) (macro-if-checks (if (fixnum? tail) tail (cons result tail)) (cons result tail))) (macro-if-checks rests '())))) (let ((rests (primitive (cdrs list1-lists)))) (macro-if-checks (if (and (fixnum? rests) (fx> rests 0)) (macro-fail-check-list (argument-id (fx+ 1 rests)) ((%procedure%) proc . list1-lists)) (let ((result (map-n* list1-lists rests))) (if (fixnum? result) (if (fx< result 0) (primitive (raise-length-mismatch-exception (argument-id (fx- 1 result)) '() (%procedure%) proc list1-lists)) (macro-fail-check-proper-list (argument-id (fx+ 1 result)) ((%procedure%) proc . list1-lists))) result))) (map-n* list1-lists rests)))) (define (argument-id i) (if (fx= i 2) '(2 . list1) i)) (if (null? lists) (map-1 list1) (map-n (cons list1 lists)))) (define-primitive (for-each (proc procedure) (list1 proper-list) (lists proper-list) ...) (define (for-each-1 lst1) (if (pair? lst1) (begin (proc (car lst1)) (for-each-1 (cdr lst1))) (void))) (define (for-each-n list1-lists) (define (for-each-n lsts) (let ((rests (primitive (cdrs lsts)))) (if (pair? rests) (begin (apply proc (primitive (cars lsts '()))) (for-each-n rests)) (void)))) (for-each-n list1-lists)) (if (null? lists) (for-each-1 list1) (for-each-n (cons list1 lists)))) (define-procedure (for-each (proc procedure) (list1 proper-list) (lists proper-list) ...) (define (for-each-1 lst1) (macro-force-vars (lst1) (if (pair? lst1) (begin (proc (car lst1)) (for-each-1 (cdr lst1))) (macro-check-proper-list-null* lst1 list1 '(2 . list1) ((%procedure%) proc list1) (void))))) (define (for-each-n list1-lists) (define (for-each-n* lsts rests) (if (not rests) (void) (if (pair? rests) (begin (apply proc (primitive (cars lsts '()))) (for-each-n* rests (primitive (cdrs rests)))) (macro-if-checks (if (fx< rests 0) (primitive (raise-length-mismatch-exception (argument-id (fx- 1 rests)) '() (%procedure%) proc list1-lists)) (macro-fail-check-proper-list (argument-id (fx+ 1 rests)) ((%procedure%) proc . list1-lists))) (void))))) (let ((rests (primitive (cdrs list1-lists)))) (macro-if-checks (if (and (fixnum? rests) (fx> rests 0)) (macro-fail-check-list (argument-id (fx+ 1 rests)) ((%procedure%) proc . list1-lists)) (for-each-n* list1-lists rests)) (for-each-n* list1-lists rests)))) (define (argument-id i) (if (fx= i 2) '(2 . list1) i)) (if (null? lists) (for-each-1 list1) (for-each-n (cons list1 lists)))) ;;;---------------------------------------------------------------------------- ;; R4RS Scheme procedures: (define-primitive (list-tail (list proper-list) (k index)) (let loop ((x list) (i k)) (if (fx< 0 i) (loop (cdr x) (fx- i 1)) x))) (define-procedure (list-tail (list proper-list) (k index)) (let loop ((x list) (i k)) (if (fx< 0 i) (macro-force-vars (x) (macro-if-checks (if (pair? x) (loop (cdr x) (fx- i 1)) (macro-check-proper-list-null* x list '(1 . list) ((%procedure%) list k) (primitive (raise-range-exception '(2 . k) (%procedure%) list k)))) (loop (cdr x) (fx- i 1)))) x))) ;;;---------------------------------------------------------------------------- ;; SRFI-1 procedures: (define-prim&proc (xcons (d object) (a object)) (cons a d)) (define-prim&proc (cons* (elt1 object) (elts object) ...) (if (pair? elts) (let loop ((x elt1) (probe elts)) (let ((y (car probe)) (tail (cdr probe))) (set-car! probe x) (if (pair? tail) (loop y tail) (begin (set-cdr! probe y) elts)))) elt1)) (define-prim&proc (make-list (k index) (fill object 0)) (let loop ((i k) (result '())) (if (fx> i 0) (loop (fx- i 1) (cons fill result)) result))) (define-prim&proc (list-tabulate (n index) (init-proc procedure)) (let loop ((i n) (result '())) (if (fx> i 0) (let ((i (fx- i 1))) (loop i (cons (init-proc i) result))) result))) (define-primitive (proper-list-copy (list list)) (let loop ((probe list) (rev-result '())) (macro-force-vars (probe) (if (pair? probe) (loop (cdr probe) (cons (car probe) rev-result)) (and (null? probe) ;; return #f when argument is not a proper list (reverse! rev-result)))))) (define-prim&proc (list-copy (list list)) (let loop ((probe list) (rev-result '())) (macro-force-vars (probe) (if (pair? probe) (loop (cdr probe) (cons (car probe) rev-result)) (append-reverse! rev-result probe))))) (define-prim&proc (circular-list (elt1 object) (elts object) ...) (let ((result (cons elt1 elts))) (set-cdr! (last-pair result) result) result)) (define-primitive (iota-fixnum (count index) (start fixnum 0)) (let loop ((i count) (result '())) (if (fx> i 0) (let ((i (fx- i 1))) (loop i (cons (fx+ start i) result))) result))) (define-prim&proc (iota (count index) (start number 0) (step number 1)) (if (and (eqv? step 1) (fixnum? start) (primitive (fx+? (fx- count 1) start))) (primitive (iota-fixnum count start)) (let loop ((i count) (result '())) (if (fx> i 0) (let ((i (fx- i 1))) (loop i (cons (+ start (* step i)) result))) result)))) (define-primitive (take (x list) (i index)) (let loop ((probe x) (j i) (rev-result '())) (if (fx> j 0) (loop (cdr probe) (fx- j 1) (cons (car probe) rev-result)) (reverse! rev-result)))) (define-procedure (take (x list) (i index)) (let loop ((probe x) (j i) (rev-result '())) (if (fx> j 0) (macro-force-vars (probe) (macro-if-checks (if (pair? probe) (loop (cdr probe) (fx- j 1) (cons (car probe) rev-result)) (primitive (raise-range-exception '(2 . i) (%procedure%) x i))) (loop (cdr probe) (fx- j 1) (cons (car probe) rev-result)))) (reverse! rev-result)))) (define-primitive (drop (x list) (i index)) (let loop ((probe x) (j i)) (if (fx> j 0) (loop (cdr probe) (fx- j 1)) probe))) (define-procedure (drop (x list) (i index)) (let loop ((probe x) (j i)) (if (fx> j 0) (macro-force-vars (probe) (macro-if-checks (if (pair? probe) (loop (cdr probe) (fx- j 1)) (primitive (raise-range-exception '(2 . i) (%procedure%) x i))) (loop (cdr probe) (fx- j 1)))) probe))) (define-primitive (split-at (x list) (i index)) (let loop ((probe x) (j i) (rev-take '())) (if (fx> j 0) (loop (cdr probe) (fx- j 1) (cons (car probe) rev-take)) (values (reverse! rev-take) probe)))) (define-procedure (split-at (x list) (i index)) (let loop ((probe x) (j i) (rev-take '())) (if (fx> j 0) (macro-force-vars (probe) (macro-if-checks (if (pair? probe) (loop (cdr probe) (fx- j 1) (cons (car probe) rev-take)) (primitive (raise-range-exception '(2 . i) (%procedure%) x i))) (loop (cdr probe) (fx- j 1) (cons (car probe) rev-take)))) (values (reverse! rev-take) probe)))) (define-primitive (last-pair (pair pair)) (let loop ((probe pair)) (let ((tail (cdr probe))) (if (pair? tail) (loop tail) probe)))) (define-procedure (last-pair (pair pair)) (let loop ((probe pair)) (let ((tail (cdr probe))) (macro-force-vars (tail) (if (pair? tail) (loop tail) probe))))) (define-prim&proc (last (pair pair)) (let loop ((probe pair)) (let ((tail (cdr probe))) (macro-force-vars (tail) (if (pair? tail) (loop tail) (car probe)))))) (define-primitive (butlast (pair pair)) (define (butlast probe) (if (pair? (cdr probe)) (cons (car probe) (butlast (cdr probe))) '())) (butlast pair)) (define-primitive (concatenate-reverse (rlist-of-lists proper-list) (separator proper-list '())) (if (pair? rlist-of-lists) (let loop ((rlst (cdr rlist-of-lists)) (result (car rlist-of-lists))) (if (pair? rlst) (loop (cdr rlst) (primitive (append2 (car rlst) (if (eq? separator '()) result (primitive (append2 separator result)))))) result)) '())) (define-primitive (concatenate (list-of-lists proper-list) (separator proper-list '())) (primitive (concatenate-reverse (reverse list-of-lists) separator))) (define-procedure (concatenate (list-of-lists proper-list) (separator proper-list '())) (define (fail-check-list1) (macro-fail-check-list '(1 . list-of-lists) ((%procedure%) list-of-lists %separator))) (define (fail-check-proper-list1) (macro-fail-check-proper-list '(1 . list-of-lists) ((%procedure%) list-of-lists %separator))) (define (fail-check-list-list1) (macro-fail-check-list-list '(1 . list-of-lists) ((%procedure%) list-of-lists %separator))) (define (fail-check-list2) (macro-fail-check-list '(2 . separator) ((%procedure%) list-of-lists %separator))) (define (fail-check-proper-list2) (macro-fail-check-proper-list '(2 . separator) ((%procedure%) list-of-lists %separator))) (define (add-force-list! last probe) (macro-force-vars (probe) (add-list! last probe))) (define (add-list! last probe) (if (pair? probe) (add-pair! last probe) last)) (define (add-pair! last probe) (let ((cdr-probe (cdr probe))) (macro-force-vars (cdr-probe) (let ((next (cons (car probe) cdr-probe))) (set-cdr! last next) (add-list! next cdr-probe))))) (define (concat-with-null-separator lst-of-lst) ;; lst-of-lst is known to be a pair and there is no separator ;; This procedure calls itself recursively to find the first pair element ;; of list-of-lists. (let* ((elem (car lst-of-lst)) (rest (cdr lst-of-lst))) (macro-force-vars (rest) (if (pair? rest) (macro-force-vars (elem) (if (pair? elem) (let () ;; first pair element of list-of-lists found (define (concat-next-list result last rest) (let ((elem (car rest)) (rest (cdr rest))) (macro-force-vars (rest) (if (pair? rest) (macro-force-vars (elem) (if (pair? elem) (let ((last (add-pair! last elem))) (macro-if-checks (if (null? (cdr last)) ;; elem is a proper list (concat-next-list result last rest) (fail-check-list-list1)) (concat-next-list result last rest))) (macro-if-checks (if (null? elem) (concat-next-list result last rest) (fail-check-list-list1)) (concat-next-list result last rest)))) (begin (set-cdr! last elem) (macro-if-checks (if (null? rest) result (fail-check-proper-list1)) result)))))) (let* ((cdr-elem (cdr elem)) (result (cons (car elem) cdr-elem)) (last (add-force-list! result cdr-elem))) (macro-if-checks (if (null? (cdr last)) ;; elem is a proper list (concat-next-list result last rest) (fail-check-list-list1)) (concat-next-list result last rest)))) (macro-if-checks (if (null? elem) (concat-with-null-separator rest) (fail-check-list-list1)) (concat-with-null-separator rest)))) (macro-if-checks (if (null? rest) elem (fail-check-proper-list1)) elem))))) (define (concat-with-pair-separator) ;; list-of-lists is known to be a pair and separator is known to be a pair (let* ((elem (car list-of-lists)) (rest (cdr list-of-lists))) (macro-force-vars (rest) (if (pair? rest) (macro-force-vars (elem) (let () (define (concat-separator result last rest) (let ((last (add-list! last separator))) (macro-if-checks (if (null? (cdr last)) ;; separator is a proper list (concat-next-list result last rest) (fail-check-proper-list2)) (concat-next-list result last rest)))) (define (concat-next-list result last rest) (let ((elem (car rest)) (rest (cdr rest))) (macro-force-vars (rest) (if (pair? rest) (macro-force-vars (elem) (if (pair? elem) (let ((last (add-pair! last elem))) (macro-if-checks (if (null? (cdr last)) ;; elem is a proper list (concat-separator result last rest) (fail-check-list-list1)) (concat-separator result last rest))) (macro-if-checks (if (null? elem) (concat-separator result last rest) (fail-check-list-list1)) (concat-separator result last rest)))) (begin (set-cdr! last elem) (macro-if-checks (if (null? rest) result (fail-check-proper-list1)) result)))))) (if (pair? elem) (let* ((cdr-elem (cdr elem)) (result (cons (car elem) cdr-elem)) (last (add-force-list! result cdr-elem))) (macro-if-checks (if (null? (cdr last)) ;; elem is a proper list (concat-separator result last rest) (fail-check-list-list1)) (concat-separator result last rest))) (let* ((cdr-separator (cdr separator)) (result (cons (car separator) cdr-separator)) (last (add-force-list! result cdr-separator))) (macro-if-checks (if (null? elem) ;; elem is a proper list (if (null? (cdr last)) ;; separator is a proper list (concat-next-list result last rest) (fail-check-proper-list2)) (fail-check-list-list1)) (concat-next-list result last rest)))))) ;; end of list-of-lists (macro-if-checks (if (null? rest) elem (fail-check-proper-list1)) elem))))) (if (pair? list-of-lists) (if (pair? separator) (concat-with-pair-separator) (macro-if-checks (if (null? separator) (concat-with-null-separator list-of-lists) (fail-check-list2)) (concat-with-null-separator list-of-lists))) (macro-if-checks (if (null? list-of-lists) (if (or (null? separator) (pair? separator)) '() (fail-check-list2)) (fail-check-list1)) '()))) (define-primitive (concatenate! (list-of-lists proper-list)) (if (pair? list-of-lists) (let loop1 ((lst list-of-lists)) (let ((elem (car lst)) (rest (cdr lst))) (if (pair? rest) (if (pair? elem) (let loop2 ((result elem) (lst rest) (last (last-pair elem))) (let ((elem (car lst)) (rest (cdr lst))) (set-cdr! last elem) (if (pair? rest) (loop2 result rest (last-pair last)) result))) (loop1 rest)) elem))) '())) (define-procedure (concatenate! (list-of-lists proper-list)) (define (last-pair-with-auto-forcing! pair) (let loop ((probe pair)) (let ((tail (cdr probe))) (macro-if-auto-forcing (macro-force-vars (tail) (begin (set-cdr! probe tail) (if (pair? tail) (loop tail) probe))) (if (pair? tail) (loop tail) probe))))) (if (pair? list-of-lists) (let loop1 ((lst list-of-lists)) (let ((elem (car lst)) (rest (cdr lst))) (macro-force-vars (rest) (if (pair? rest) (macro-force-vars (elem) (if (pair? elem) ;; first pair element of list-of-lists found (let loop2 ((result elem) (lst rest) (last (last-pair-with-auto-forcing! elem))) (macro-check-list-list-null (cdr last) '(1 . list-of-lists) ((%procedure%) list-of-lists) (let ((elem (car lst)) (rest (cdr lst))) (set-cdr! last elem) (macro-force-vars (rest) (if (pair? rest) (loop2 result rest (last-pair-with-auto-forcing! last)) (macro-check-proper-list-null rest '(1 . list-of-lists) ((%procedure%) list-of-lists) result)))))) ;; first pair element not yet found (macro-check-list-list-null elem '(1 . list-of-lists) ((%procedure%) list-of-lists) (loop1 rest)))) ;; all elements of list-of-lists before last are null (macro-check-proper-list-null rest '(1 . list-of-lists) ((%procedure%) list-of-lists) elem))))) (macro-check-list-null list-of-lists '(1 . list-of-lists) ((%procedure%) list-of-lists) '()))) ;; ##reverse! defined in _kernel.scm (define-procedure (reverse! (list proper-list)) (let loop ((prev '()) (curr list)) (macro-force-vars (curr) (if (pair? curr) (let ((next (cdr curr))) (set-cdr! curr prev) (loop curr next)) (macro-check-proper-list-null* curr list '(1 . list) ((%procedure%) list) prev))))) (define-primitive (append-reverse (rev-head proper-list) (tail list)) (let loop ((x rev-head) (result tail)) (if (pair? x) (loop (cdr x) (cons (car x) result)) result))) (define-procedure (append-reverse (rev-head proper-list) (tail list)) (let loop ((x rev-head) (result tail)) (macro-force-vars (x) (if (pair? x) (loop (cdr x) (cons (car x) result)) (macro-check-proper-list-null* x rev-head '(1 . rev-head) ((%procedure%) rev-head tail) result))))) ;; ##append-reverse! defined in _kernel.scm (define-procedure (append-reverse! (rev-head proper-list) (tail list)) (let loop ((prev tail) (curr rev-head)) (macro-force-vars (curr) (if (pair? curr) (let ((next (cdr curr))) (set-cdr! curr prev) (loop curr next)) (macro-check-proper-list-null* curr rev-head '(1 . rev-head) ((%procedure%) rev-head tail) prev))))) (define-primitive (fold (kons procedure) (knil object) (clist1 proper-or-circular-list) (clists proper-or-circular-list) ...) (define (fold-1 clist1) (let loop ((r knil) (x clist1)) (if (pair? x) (loop (kons (car x) r) (cdr x)) r))) (define (fold-n lsts) (let loop ((r knil) (x lsts)) (let ((rests (primitive (cdrs x)))) (if (pair? rests) (loop (apply kons (primitive (cars x (list r)))) rests) r)))) (if (null? clists) (fold-1 clist1) (fold-n (cons clist1 clists)))) (define-procedure (fold (kons procedure) (knil object) (clist1 proper-or-circular-list) (clists proper-or-circular-list) ...) (define (fold-1 clst1) (let loop ((r knil) (x clst1)) (macro-force-vars (x) (if (pair? x) (loop (kons (car x) r) (cdr x)) (macro-check-proper-list-null* x clist1 '(3 . clist1) ((%procedure%) kons knil clist1) r))))) (define (fold-n clist1-clists) (define (fold-n* r x rests) (if (not rests) r (if (pair? rests) (fold-n* (apply kons (primitive (cars x (list r)))) rests (primitive (cdrs rests))) (macro-if-checks (if (fx< rests 0) (primitive (raise-length-mismatch-exception (argument-id (fx- 2 rests)) '() (%procedure%) kons knil clist1-clists)) (macro-fail-check-proper-list (argument-id (fx+ 2 rests)) ((%procedure%) kons knil . clist1-clists))) r)))) (let ((rests (primitive (cdrs clist1-clists)))) (macro-if-checks (if (and (fixnum? rests) (fx> rests 0)) (macro-fail-check-list (argument-id (fx+ 2 rests)) ((%procedure%) kons knil . clist1-clists)) (fold-n* knil clist1-clists rests)) (fold-n* knil clist1-clists rests)))) (define (argument-id i) (if (fx= i 3) '(3 . clist1) i)) (if (null? clists) (fold-1 clist1) (fold-n (cons clist1 clists)))) (define-primitive (fold-right (kons procedure) (knil object) (clist1 proper-or-circular-list) (clists proper-or-circular-list) ...) (define (fold-right-1 x) (if (pair? x) (kons (car x) (fold-right-1 (cdr x))) knil)) (define (fold-right-n x) (let ((rests (primitive (cdrs x)))) (if (pair? rests) (apply kons (primitive (cars x (list (fold-right-n rests))))) knil))) (if (null? clists) (fold-right-1 clist1) (fold-right-n (cons clist1 clists)))) (define-procedure (fold-right (kons procedure) (knil object) (clist1 proper-or-circular-list) (clists proper-or-circular-list) ...) (define (fold-right-1 clist1) (define (fold-right-1* clst1) (macro-force-vars (clst1) (if (pair? clst1) (let ((r (fold-right-1* (cdr clst1)))) (and r (list (kons (car clst1) (car r))))) (macro-if-checks (if (null? clst1) (list knil) #f) (list knil))))) (macro-if-checks (if (or (null? clist1) (pair? clist1)) (let ((r (fold-right-1* clist1))) (if r (car r) (macro-fail-check-proper-list '(3 . clist1) ((%procedure%) kons knil clist1)))) (macro-fail-check-list '(3 . clist1) ((%procedure%) kons knil clist1))) (fold-right-1* clist1))) (define (fold-right-n clist1-clists) (define (fold-right-n* x rests) (if (not rests) (list knil) (if (pair? rests) (let ((r (fold-right-n* rests (primitive (cdrs rests))))) (macro-if-checks (if (fixnum? r) r (list (apply kons (primitive (cars x r))))) (list (apply kons (primitive (cars x r)))))) rests))) (let ((rests (primitive (cdrs clist1-clists)))) (macro-if-checks (if (and (fixnum? rests) (fx> rests 0)) (macro-fail-check-list (argument-id (fx+ 2 rests)) ((%procedure%) kons knil . clist1-clists)) (let ((r (fold-right-n* clist1-clists rests))) (if (fixnum? r) (if (fx< r 0) (primitive (raise-length-mismatch-exception (argument-id (fx- 2 r)) '() (%procedure%) kons knil clist1-clists)) (macro-fail-check-proper-list (argument-id (fx+ 2 r)) ((%procedure%) kons knil . clist1-clists))) (car r)))) (car (fold-right-n* clist1-clists rests))))) (define (argument-id i) (if (fx= i 3) '(3 . clist1) i)) (if (null? clists) (fold-right-1 clist1) (fold-right-n (cons clist1 clists)))) ;;;---------------------------------------------------------------------------- ;;; Sorting. (define-primitive (list-sort! (proc procedure) (list proper-list)) ;; Stable mergesort algorithm (define (sort list len) (if (fx= len 1) (begin (set-cdr! list '()) list) (let ((len1 (fxarithmetic-shift-right len 1))) (let loop ((n len1) (tail list)) (if (fx> n 0) (loop (fx- n 1) (cdr tail)) (let ((x (sort tail (fx- len len1)))) (merge (sort list len1) x))))))) (define (merge list1 list2) (if (pair? list1) (if (pair? list2) (let ((x1 (car list1)) (x2 (car list2))) (if (proc x2 x1) (merge-loop list2 list2 list1 (cdr list2)) (merge-loop list1 list1 (cdr list1) list2))) list1) list2)) (define (merge-loop result prev list1 list2) (if (pair? list1) (if (pair? list2) (let ((x1 (car list1)) (x2 (car list2))) (if (proc x2 x1) (begin (set-cdr! prev list2) (merge-loop result list2 list1 (cdr list2))) (begin (set-cdr! prev list1) (merge-loop result list1 (cdr list1) list2)))) (begin (set-cdr! prev list1) result)) (begin (set-cdr! prev list2) result))) (let ((len (primitive (proper-list-length list)))) (and len (if (fx= len 0) '() (sort list len))))) (define-procedure (list-sort! (proc procedure) (list proper-list)) (let ((result (primitive (list-sort! proc list)))) (or result (macro-fail-check-list '(2 . list) ((%procedure%) proc list))))) (define-primitive (list-sort (proc procedure) (list proper-list)) (list-sort! proc (list-copy list))) (define-procedure (list-sort (proc procedure) (list proper-list)) (macro-if-checks (let ((copy (primitive (proper-list-copy list)))) (if copy (list-sort! proc copy) (macro-fail-check-list '(2 . list) ((%procedure%) proc list)))) (list-sort! proc (list-copy list)))) (define-primitive (nth-pair (pair pair) (k index)) (let loop ((x pair) (i k)) (if (fx< 0 i) (let ((tail (cdr x))) (and (pair? tail) (loop tail (fx- i 1)))) x))) (define-macro (macro-nth pair n) `(let ((x (primitive (nth-pair ,pair ,n)))) (macro-check-deeper-pair-tree-pair x '(1 . pair) ((%procedure%) pair) (car x)))) (define-prim&proc (first (pair pair)) (car pair)) (define-prim&proc (second (pair pair)) (macro-nth pair 1)) (define-prim&proc (third (pair pair)) (macro-nth pair 2)) (define-prim&proc (fourth (pair pair)) (macro-nth pair 3)) (define-prim&proc (fifth (pair pair)) (macro-nth pair 4)) (define-prim&proc (sixth (pair pair)) (macro-nth pair 5)) (define-prim&proc (seventh (pair pair)) (macro-nth pair 6)) (define-prim&proc (eighth (pair pair)) (macro-nth pair 7)) (define-prim&proc (ninth (pair pair)) (macro-nth pair 8)) (define-prim&proc (tenth (pair pair)) (macro-nth pair 9)) (define-prim&proc (not-pair? (x object)) (not (pair? x))) (define-prim&proc (null-list? (list proper-list)) (if (pair? list) ;; does not check that list is not a dotted list #f (macro-check-proper-list-null list '(1 . list) ((%procedure%) list) #t))) (define-prim&proc (car+cdr (pair pair)) (values (car pair) (cdr pair))) (define-procedure (list= (elt= procedure) (list1 proper-list (macro-absent-obj)) (list2 proper-list (macro-absent-obj)) (lists proper-list) ...) (define (compare list1 list2) (or (eq? list1 list2) (if (pair? list1) (if (pair? list2) (and (elt= (car list1) (car list2)) (compare (cdr list1) (cdr list2))) (macro-if-checks (if (null? list2) #f 2) ;; list2 not proper list #f)) (if (pair? list2) (macro-if-checks (if (null? list1) #f 1) ;; list1 not proper list #f) (macro-if-checks (if (null? list1) 2 ;; list2 not proper list because we know list2 != '() 1) ;; list1 not proper list #f))))) (if (or (eq? list1 (macro-absent-obj)) (eq? list2 (macro-absent-obj))) #t (let loop ((list1 list1) (list2 list2) (lists lists) (arg-num 1)) (let ((result (compare list1 list2))) (macro-if-checks (if (fixnum? result) (macro-fail-check-proper-list (fx+ arg-num result) ((%procedure%) elt= list1 list2 . lists)) (and result (if (pair? lists) (loop list2 (car lists) (cdr lists) (fx+ arg-num 1)) #t))) (and result (if (pair? lists) (loop list2 (car lists) (cdr lists) (fx+ arg-num 1)) #t))))))) #| ;; TODO: take-right flist i -> object drop-right flist i -> list take! x i -> list drop-right! flist i -> list split-at x i -> [list object] split-at! x i -> [list object] append! list1 ... -> list zip clist1 clist2 ... -> list (lambda lists (apply map list lists)) unzip1 list -> list unzip2 list -> [list list] unzip3 list -> [list list list] unzip4 list -> [list list list list] unzip5 list -> [list list list list list] count pred clist1 clist2 -> integer pair-fold kons knil clist1 clist2 ... -> value pair-fold-right kons knil clist1 clist2 ... -> value reduce f ridentity list -> value reduce-right f ridentity list -> value unfold p f g seed [tail-gen] -> list unfold-right p f g seed [tail] -> list append-map f clist1 clist2 ... -> value append-map! f clist1 clist2 ... -> value map! f list1 clist2 ... -> list map-in-order f clist1 clist2 ... -> list pair-for-each f clist1 clist2 ... -> unspecific filter-map f clist1 clist2 ... -> list partition pred list -> [list list] filter! pred list -> list partition! pred list -> [list list] remove! pred list -> list find pred clist -> value find-tail pred clist -> pair or false take-while pred clist -> list take-while! pred clist -> list drop-while pred clist -> list span pred clist -> [list clist] span! pred list -> [list list] break pred clist -> [list clist] break! pred list -> [list list] any pred clist1 clist2 ... -> value every pred clist1 clist2 ... -> value list-index pred clist1 clist2 ... -> integer or false delete x list [=] -> list delete! x list [=] -> list delete-duplicates list [=] -> list delete-duplicates! list [=] -> list alist-cons key datum alist -> alist alist-copy alist -> alist alist-delete key alist [=] -> alist alist-delete! key alist [=] -> alist lset<= = list1 ... -> boolean lset= = list1 list2 ... -> boolean lset-adjoin = list elt1 ... -> list lset-union = list1 ... -> list lset-intersection = list1 list2 ... -> list lset-difference = list1 list2 ... -> list lset-xor = list1 ... -> list lset-diff+intersection = list1 list2 ... -> [list list] lset-union! = list1 ... -> list lset-intersection! = list1 list2 ... -> list lset-difference! = list1 list2 ... -> list lset-xor! = list1 ... -> list lset-diff+intersection! = list1 list2 ... -> [list list] |# ;;;============================================================================
false
9084ce0b6a6b5152f0b6bf28ee34c7bb34d6c67f
defeada37d39bca09ef76f66f38683754c0a6aa0
/System.Transactions/system/transactions/transaction-manager-communication-exception.sls
5e33caac77926da6509e35ae820f0d6c6b983ecd
[]
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
659
sls
transaction-manager-communication-exception.sls
(library (system transactions transaction-manager-communication-exception) (export new is? transaction-manager-communication-exception?) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Transactions.TransactionManagerCommunicationException a ...))))) (define (is? a) (clr-is System.Transactions.TransactionManagerCommunicationException a)) (define (transaction-manager-communication-exception? a) (clr-is System.Transactions.TransactionManagerCommunicationException a)))
true
14ef951ff8561a9d0469bcf3cd4359f7bafc2e5e
38fcd70df648a497ee1271fcdbd30e391fb310e5
/parsers.ss
7ef989112be631f8d6a9150723123f131ac7f0a9
[]
no_license
liutanyu/Useful
e9b3d3699dffa21bb1425dddff7d150ab7d7aee7
11a123126833e577a76ce32c22d8563c0f2bbd7d
refs/heads/master
2021-01-19T11:34:24.259506
2013-07-17T04:13:22
2013-07-17T04:13:22
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
17,242
ss
parsers.ss
;;; parser construction ;;; Using List-of-frames representation ;;; #include scan-lof.s ;;; **************************************************************** ;;; make-lazy-stream : (() -> val * stream) -> stream ;;; stream-get : stream * (value -> (stream -> answer)) -> answer (define make-lazy-stream (lambda (th) th)) (define stream-get (lambda (stream rcvr) (let ((the-pair (stream))) (rcvr (car the-pair) (cdr the-pair))))) ;;; **************************************************************** (define string->stream (lambda (str) (let ((length (string-length str))) (letrec ((loop (lambda (i) (make-lazy-stream (lambda () (cons (if (>= i length) #\nul (string-ref str i)) (loop (+ i 1)))))))) (loop 0))))) ;; a better version of stream->list, parameterized on end-of-stream? (define stream->list (lambda (end-of-stream? str) (stream-get str (lambda (val newstr) (if (end-of-stream? val) '() (cons val (stream->list end-of-stream? newstr))))))) ;;; **************************************************************** ;;; Scanner architecture ;;; Scanner = char-stream -> token-stream ;;; State = buf * char * char-stream -> token * char * char-stream (define-record scanner-result (item char stream)) (define *trace-apply-automaton* #f) (define apply-automaton (lambda (automaton state buf c str) (letrec ((apply-state (lambda (state buf c str) (let ((opcode (car state)) (next-state (cadr state))) (if *trace-apply-automaton* (printf "apply-state: opcode = ~s c = ~s~%" opcode c)) (case opcode ((shift) (stream-get str (lambda (c1 str1) (apply-state next-state (cons c buf) c1 str1)))) ((drop) (stream-get str (lambda (c1 str1) (apply-state next-state buf c1 str1)))) ((emit) (let ((cooker (cadr state))) (let ((item (apply-cooker cooker (reverse buf)))) '(printf "emitting item ~s~n" item) (make-scanner-result item c str)))) ((cond) (apply-state (apply-scanner-cond (cdr state) c) buf c str)) ((goto) (apply-state (scanner-label->state next-state automaton) buf c str)) ((fail) (let ((msg (cadr state))) (error 'apply-automaton "scanner failed in state ~s on input ~s" msg c))) ((debug-state) (let ((msg (cadr state)) (next-state (caddr state))) (printf "~s ~s ~s~%" msg buf c) (apply-state next-state buf c str)))))))) (apply-state state buf c str)))) (define apply-scanner-cond (lambda (alternatives c) (if (null? alternatives) (error 'apply-state "couldn't match character ~s in state ~%~s" c alternatives) (let ((alternative1 (car alternatives))) '(printf "apply-scanner-cond: c = ~s alternative = ~s~%" c alternative1) (if (apply-tester (car alternative1) c) (cadr alternative1) (apply-scanner-cond (cdr alternatives) c)))))) (define scanner-label->state (lambda (label automaton) (cadr (assq label automaton)))) (define automaton->start-label caar) (define automaton->scanner (lambda (automaton) (letrec ((loop (lambda (char stream) (make-lazy-stream (lambda () (record-case (apply-automaton automaton (scanner-label->state (automaton->start-label automaton) automaton) '() char stream) (scanner-result (token char stream) (cons token (loop char stream))))))))) (lambda (stream) (stream-get stream loop))))) ;;; driver-1: from string to list of tokens (define driver-1 (lambda (automaton string) (stream->list (lambda (item) (record-case item (token (class data) (eq? class 'end-marker)))) ((automaton->scanner automaton) (string->stream string))))) ;;; **************************************************************** ;;; Standard cookers and testers ;;; Record definitions and cookers (define-record token (class data)) (define cook-identifier (lambda (buffer) (let ((sym (string->symbol (list->string buffer)))) (if (memq sym **keywords-list**) (make-token sym #f) (make-token 'identifier sym))))) (define cook-number (lambda (buffer) (make-token 'number (string->number (list->string buffer))))) (define apply-cooker (lambda (cooker char-list) (case cooker ((cook-identifier) (cook-identifier char-list)) ((cook-number) (cook-number char-list)) (else (if (symbol? cooker) (make-token cooker #f) (else (error 'apply-cooker "unknown cooker ~s" cooker))))))) (define apply-tester (lambda (tester ch) (cond ((char? tester) (eq? tester ch)) ((eq? tester 'else) #t) (else (case tester ((whitespace) (char-whitespace? ch)) ((alphabetic) (char-alphabetic? ch)) ((numeric) (char-numeric? ch)) (else (error 'apply-tester "unknown tester ~s" tester))))))) ;;; **************************************************************** (define automaton-1 '((start-state (cond (whitespace (drop (goto start-state))) (alphabetic (shift (goto identifier-state))) (numeric (shift (goto number-state))) (#\+ (drop (emit plus-sym))) (#\: (shift (goto assign-sym-state))) (#\% (drop (goto comment-state))) (#\; (drop (emit semicolon))) (#\( (drop (emit lparen))) (#\) (drop (emit rparen))) (#\^ (emit end-marker)) (#\nul (emit end-marker)) (else (fail start-state)))) (identifier-state (cond (alphabetic (shift (goto identifier-state))) (numeric (shift (goto identifier-state))) (else (emit cook-identifier)))) (number-state (cond (numeric (shift (goto number-state))) (else (emit cook-number)))) (assign-sym-state (cond (#\= (shift (emit assign-sym))) (else (shift (goto identifier-state))))) (comment-state (cond (#\newline (drop (goto start-state))) (#\^ (goto start-state)) (#\nul (goto start-state)) (else (drop (goto comment-state))))))) (define **keywords-list** '(begin end if then else)) ; > (driver-1 automaton-1 "abc ; def ; % comment ; xyz 13") ; emitting item (token identifier abc) ; emitting item (token identifier def) ; emitting item (token identifier xyz) ; emitting item (token number 13) ; emitting item (token end-marker ()) ; ((token identifier abc) ; (token identifier def) ; (token identifier xyz) ; (token number 13)) ;;; ********* end of scan-ds.s ********************** (define token-stream-get stream-get) ;;; Parser architecture ;;; parser = (list tree) * item * item-stream -> tree * item * item-stream ;;; The item register can either contain an item or '() -- the latter ;;; signifying an empty buffer, to be filled when necessary. (define-record parser-result (tree item stream)) ;;; Grammar of actions: ;;; action :: = ((check/drop class) . action) ;;; ((check/shift class) . action) ;;; ((process/nt non-terminal) . action) ;;; ((reduce prod-name)) ;;; ((emit-list)) ;;; ((goto non-terminal)) ;;; (cond (non-terminal action) ... (else non-terminal)) ;;; ;;; parser ::= ((non-terminal action) ...) (define *trace-apply-parser* #f) (define apply-parser (lambda (parser action buf item stream) (letrec ((apply-parser-action (lambda (action buf item stream) (if *trace-apply-parser* (printf "apply-parser-action: action = ~s~% buf = ~s item = ~s~%" action buf item)) (let* ((fill-item-register (lambda (action) ;; here action is internal -- always a function, not ;; a representation '(printf "starting to fill: buf = ~s item = ~s action = ~s~%" buf item action) (if (null? item) (token-stream-get stream (lambda (item stream) (action buf item stream))) (action buf item stream)))) (parser-check (lambda (class action) ;; action a procedure here too. (fill-item-register (lambda (buf item stream) '(printf "checking: looking for class ~s, look at item ~s~%" class item) (if (eq? class (token->class item)) (begin '(printf "check succeeded: buf = ~s item = ~s~%" buf item) (action buf item stream)) (error 'check "looking for ~s, found ~s" class item))))))) (if (eq? (car action) 'cond) ;; it's a cond (let ((alternatives (cdr action))) '(printf "it's a cond~%") (fill-item-register (lambda (buf item stream) '(printf "item filled~%") '(printf "about to apply action ~s~%" (apply-parser-cond alternatives item)) (apply-parser-action (apply-parser-cond alternatives item) buf item stream)))) ;; otherwise it's an ordinary instruction (let ((instruction (car action)) (action (cdr action)) (whole-action action)) (case (car instruction) ((check/drop) (let ((class (cadr instruction))) (parser-check class (lambda (buf item stream) (apply-parser-action action buf '() stream))))) ((check/shift) (let ((class (cadr instruction))) (parser-check class (lambda (buf item stream) (apply-parser-action action (cons (token->data item) buf) '() stream))))) ((reduce) (let ((prod-name (cadr instruction))) '(printf "reducing ~s: buf = ~s~%" prod-name buf) (make-parser-result (apply (make-record-from-name prod-name) (reverse buf)) item stream))) ((emit-list) '(printf "emit-list: emitting ~s~%" (reverse buf)) (make-parser-result (reverse buf) item stream)) ((fail) (let ((state (cadr instruction))) (error 'parser "couldn't match token ~s in state:~%~s" item state))) ((parser-goto goto) (let ((non-terminal (cadr instruction))) (apply-parser-action (cadr (assq non-terminal parser)) buf item stream))) ((process-nt) (let ((non-terminal (cadr instruction))) (let ((next-result (apply-parser-action (cadr (assq non-terminal parser)) '() item stream))) (record-case next-result (parser-result (tree item stream) (apply-parser-action action (cons tree buf) item stream)) (else (error 'process-nt "bad parser-result ~s~%" next-result)))))) (else (error 'apply-parser-action "unknown action ~s~%" whole-action))))))))) (apply-parser-action action buf item stream)))) (define apply-parser-cond (lambda (alternatives item) '(printf "apply-parser-cond: alternatives = ~s item = ~s~%" alternatives item) (if (null? alternatives) (error 'apply-parser-cond "couldn't match token ~s~%" item) (let ((alternative-1 (car alternatives))) '(printf "apply-parser-cond: item = ~s alternative = ~s~%" item alternative-1) (if (or (eq? (car alternative-1) (token->class item)) ;; "else" is always true if it's last alternative (and (eq? (car alternative-1) 'else) (null? (cdr alternatives)))) (cadr alternative-1) (apply-parser-cond (cdr alternatives) item)))))) ;; ;; new parse-top-level ;; (define parse-top-level (lambda (parser token-stream) (let ((result (apply-parser parser '((goto start-state)) '() '() token-stream))) '(printf "top-level parse returned.~%") '(pretty-print result) (record-case result (parser-result (tree item stream) (let ((item (if (null? item) (token-stream-get stream (lambda (item stream) item)) item))) (if (eq? (token->class item) 'end-marker) tree (error 'parse-top-level "symbols left over: ~s..." item)))) (else (error 'parse-top-level "top-level-parse not a parser-result")))))) ;; a simpler driver (define simple-parse-top-level (lambda (parser token-stream) (apply-parser '((goto start-state)) '() '() token-stream))) ;;; **************************************************************** ;;; constructors for example (define-record compound-command (command-list)) (define-record while-command (exp cmd)) (define-record if-command (exp cmd1 cmd2)) (define-record assignment-command (var exp)) (define-record variable-expression (var)) (define-record sum-expression (exp1 exp2)) (define-record end-marker-command ()) (define **keywords-list** '(begin end)) (define parser-2 '((start-state ((goto command))) (command (cond (begin ((check/drop begin) (process-nt compound-command) (reduce compound-command))) (identifier ((check/shift identifier) (check/drop assign-sym) (process-nt expression) (reduce assignment))) (end ((check/drop end) (reduce end-marker-command))) (else ((fail command))))) (compound-command ((process-nt command) (parser-goto compound-command-loop))) (compound-command-loop (cond (semicolon ((check/drop semicolon) (process-nt command) (parser-goto compound-command-loop))) (end ((check/drop end) (emit-list))) (else ((fail compound-command-loop))))) (expression (cond (identifier ((check/shift identifier) (reduce var-expression))) (number ((check/shift number) (reduce const-expression))) (lparen ((check/drop lparen) (process-nt expression) (check/drop plus-sym) (process-nt expression) (check/drop rparen) (reduce addition-expression))) (else ((parser-fail expression))))))) (define string->token-stream (lambda (automaton string) ((automaton->scanner automaton) (string->stream string)))) (define test1 (lambda (input-string) (parse-top-level parser-2 (string->token-stream state-1 input-string)))) ; > (test1 "x := y") ; (assignment ; (token identifier x) ; (var-expression (token identifier y))) ; > (test1 "begin x:=y; x := z end") ; (compound ; (assignment ; (token identifier x) ; (var-expression (token identifier y))) ; (assignment ; (token identifier x) ; (var-expression (token identifier z)))) ; >
false
54c5079f5daf25b63f713e2a6710e9ecff43b76d
31cdaf9ee26d4be27ae7db6095dec59639b77a61
/constraints.scm
6e6b82cdfceb905c183a37eef313c66707b14c9d
[]
no_license
panicz/eidolon
ce99cd5fde4369120f15ed913de718e77a55ac23
b6273681566be4668e965e2b792f4fd5a77be94b
refs/heads/master
2021-01-20T02:49:16.142845
2018-09-15T15:34:45
2018-09-15T15:34:45
101,335,270
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,506
scm
constraints.scm
(define-module (constraints) #:use-module (grand scheme) #:use-module (assignable-procedures) #:use-module (notifying-assignment) #:export-syntax (impose) #:export (constraint-variables untangle revoke-constraint!)) (use-modules (grand scheme) (assignable-procedures) (notifying-assignment)) (define (operator? x) (is x member '(+ - / *))) (define (comparator? x) (is x member '(=))) (define (used-in? factor formula) (or (equal? factor formula) (and-let* ((`(,<.> ,first ,second) formula) ((operator? <.>))) (or (is factor used-in? first) (is factor used-in? second))))) (e.g. (is 'x used-in? '(* x 2))) (e.g. (is '(f x) used-in? '(* 2 (f x)))) (define (extract-left operation formula) (match operation (`(+ ,left ,right) `(- ,formula ,right)) (`(* ,left ,right) `(/ ,formula ,right)) (`(- ,left ,right) `(+ ,formula ,right)) (`(/ ,left ,right) `(* ,formula ,right)))) (define (extract-right operation formula) (match operation (`(+ ,left ,right) `(- ,formula ,left)) (`(* ,left ,right) `(/ ,formula ,left)) (`(- ,left ,right) `(- ,left ,formula)) (`(/ ,left ,right) `(/ ,left ,formula)))) (define (extract factor #;from source #;into target) (if (equal? factor source) target (let ((`(,<.> ,first ,second) source)) (cond ((or (isnt <.> operator?) (and (is factor used-in? first) (is factor used-in? second))) 'oops) ((is factor used-in? first) (let ((target* (extract-left source target))) (extract factor first target*))) ((is factor used-in? second) (let ((target* (extract-right source target))) (extract factor second target*))))))) (define (untangle factor #;from equation) (let ((`(,>?< ,left ,right) equation)) (cond ((and (is factor used-in? left) (is factor used-in? right)) `(oops: ,equation)) ((is factor used-in? left) (extract factor #;from left #;into right)) ((is factor used-in? right) (extract factor #;from right #;into left))))) (e.g. (untangle 'a #;from '(= (/ a b) (/ c d))) ===> (* (/ c d) b)) (define (factors formula) (or (and-let* ((`(,<.> . ,operands) formula) ((or (operator? <.>) (comparator? <.>)))) (apply union (map factors operands))) `(,formula))) (e.g. (is (factors '(= (/ a b) (/ c d))) same-set? '(a b c d))) (e.g. (is (factors '(= (* (f x) (g y)) (z w))) same-set? '((f x) (g y) (z w)))) (define (constraint-variables formula) (filter (isnt _ number?) (factors formula))) (define-macro (impose constraint) (let ((expressions (constraint-variables constraint)) (_ (make-symbol "_"))) `(list . ,(map (lambda (expression) (let ((others (delete expression #;from expressions))) `(on-change ,expression (primitive-lambda ,_ . ,(map (lambda (observer) `(set! ,observer ,(untangle observer constraint))) others))))) expressions)))) (define (revoke-constraint! constraint) (for notification in constraint (revoke-notification! notification))) #| ;; We don't want these symbols to clutter global namespace (e.g. (begin (define x 5) (define y 1/5) (impose (= x (/ 1 y))) (set! x 6) y) ===> 1/6) (e.g. (begin (define a 2) (define b 3) (define c 6) (impose (= (* a b) c)) (print (observers a)) (set! a 5) (values a b c)) ===> 5 3 15) |#
false
94f35b20a908f0337976b8331364e35179d9c3b9
c9830cb8c25b1039bb1fdf67dc8c8c1aa9a8147d
/sample/sample.scm
aeefdd992c755dbedfb37f6dcbc98c8e9790b4a2
[ "MIT" ]
permissive
yoppi/ubigraph
bf809302302134bce9a71a3f3c5ee83b905c3dff
cc1c78051de350e39f26e1f0c5a8c8360576b453
refs/heads/master
2021-01-16T21:23:24.163991
2009-02-25T10:14:43
2009-02-25T10:14:43
125,777
1
0
null
null
null
null
UTF-8
Scheme
false
false
796
scm
sample.scm
(use rfc.uri) (use xsm.xml-rpc.client) (define scheme "http") (define host "localhost") (define port 20738) (define path "/RPC2") ;;========== Main (define (main args) (let ((client (make-xml-rpc-client (uri-compose :scheme scheme :host host :port port :path path))) (handler (current-exception-handler))) (with-exception-handler (lambda (e) (use gauche.interactive) (d e) (handler e)) (lambda () (print (call client "ubigraph.new_vertex" ) ;(call client "ubigraph.new_vertex_w_id" 2) ;(call client "ubigraph.new_edge" 1 2) )))))
false
4e54f3cf6acf0e55a81b01491af12edd8b15d6fa
bb65446a9debece8580bf0a20a229055038a5f6b
/guile/dds/base-impl/primitives-syntax.scm
bdeb1f3786d535e0e6b0c5063a5157cc6b5074a0
[]
no_license
arvyy/DataDrivenScreenshots
f4ee1171c03a4a51cd96a3dd26b7205335445080
bd96d5bf22fdd449d681eaa509807108f72be442
refs/heads/master
2020-11-24T13:47:33.153065
2019-12-15T12:10:37
2019-12-15T12:10:37
228,175,925
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,518
scm
primitives-syntax.scm
(define-module (dds base-impl primitives-syntax) #:export (define-record-type+fact define-record-type+fact+bind*)) (use-modules (srfi srfi-9) (dds base-impl fieldbind) (dds base-impl override)) (define-syntax define-record-type+fact (syntax-rules () ((_ type fact-name (constr key* ...) pred (key getter) ...) (define-record-type+fact type fact-name (constr key* ...) pred () (key getter) ...)) ((_ type fact-name (constr key* ...) pred ((key/no-fac getter/no-fac) ...) (key getter) ...) (begin (define-record-type type (constr key* ...) pred (key/no-fac getter/no-fac) ... (key getter) ...) (define (fact-name base) (lambda* (#:key (key (getter base)) ...) (constr (getter/no-fac base) ... key ...))) (export getter ...) (export getter/no-fac ...) (export fact-name pred))))) (define-syntax define-record-type+fact+bind* (syntax-rules() ((_ type fact-name bind-name override-name (constr key* ...) pred ((data data-getter) (key/no-fac getter/no-fac) ...) (key getter) ...) (begin (define-record-type+fact type fact-name (constr key* ...) pred ((data data-getter) (key/no-fac getter/no-fac) ...) (key getter) ...) (define bind-name (let ((getters (list getter ...)) (getters/no-fac (list getter/no-fac ...))) (lambda (def datum) (define fields/no-fac (map (lambda(get) (get def)) getters/no-fac)) (define fields (fv* def getters datum)) (apply constr (append (list datum) fields/no-fac fields))))) (define override-name (let ((getters (list getter ...)) (getters/no-fac (list getter/no-fac ...))) (lambda (item-def override-def) (define new-fields/no-fac (map (lambda(get) (get item-def)) getters/no-fac)) (define new-fields (getters->overriden_fields getters item-def override-def)) (apply constr (append (list (data-getter item-def)) new-fields/no-fac new-fields))))) (export bind-name override-name)))))
true
e3e2d7b71af1e5059d44a69fd60fcae127b777de
1384f71796ddb9d11c34c6d988c09a442b2fc8b2
/tests/types-collection-dsl-scm.t
1ce33c19ebcb9b7d7d13269ca369e10f70dee889
[]
no_license
ft/xmms2-guile
94c2479eec427a370603425fc9e757611a796254
29670e586bf440c20366478462f425d5252b953c
refs/heads/master
2021-07-08T07:58:15.066996
2020-10-12T01:24:04
2020-10-12T01:24:04
74,858,831
1
2
null
null
null
null
UTF-8
Scheme
false
false
10,492
t
types-collection-dsl-scm.t
;; -*- scheme -*- ;; Copyright (c) 2016 xmms2-guile workers, All rights reserved. ;; ;; Terms for redistribution and use can be found in LICENCE. (use-modules (test tap) (test setup) (xmms2 constants collection) (xmms2 types)) (init-test-tap!) (setlocale LC_ALL "") (define *universe* (make-universe)) (define *big-three* (collection (∪ (artist = Slayer) (artist = Metallica) (artist = Anthrax)))) (define *complex* (collection (∩ (∪ (¬ (artist = Slayer)) (artist = Megadeth) (artist = Chopin)) (∪ (album = One) (∩ (artist = Björk) (artist = "Tori Amos")) (album = "Call of the Mastodon")) (¬ (artist = Mozart))))) (define-syntax-rule (simple-equals-tests desc src ...) (let ((c (collection (artist = "Slayer"))) (fmt (string-concatenate (list "simple" desc ", equals: ~a is ~s")))) (define-test (format #f fmt 'operator 'COLLECTION-TYPE-EQUALS) (pass-if-= (collection-operator c) COLLECTION-TYPE-EQUALS)) (define-test (format #f fmt 'field "artist") (pass-if-string=? (collection-attribute c 'field) "artist")) (define-test (format #f fmt 'value "Slayer") (pass-if-string=? (collection-attribute c 'value) "Slayer")) (define-test (format #f fmt 'source '*universe*) (pass-if-equal? (car (collection-children c)) *universe*)))) (define *tests-per-simple-equals* 4) (define-syntax-rule (simple-has-tests desc src ...) (let ((c (collection (has artist))) (fmt-1 (string-concatenate (list "simple" desc ", has: ~a"))) (fmt-2 (string-concatenate (list "simple" desc ", has: ~a is ~s")))) (define-test (format #f fmt-2 'operator 'COLLECTION-TYPE-HAS) (pass-if-= (collection-operator c) COLLECTION-TYPE-HAS)) (define-test (format #f fmt-1 "artist") (pass-if-string=? (collection-attribute c 'field) "artist")) (define-test (format #f fmt-2 'source '*universe*) (pass-if-equal? (car (collection-children c)) *universe*)))) (define *tests-per-simple-has* 3) (define-syntax-rule (collection-type-test sym coll id) (define-test (format #f "collection ~12,,,' @a ~32,,,'.@a" 'sym 'id) (pass-if-= (collection-operator (collection coll)) id))) (with-fs-test-bundle (plan (+ (* 3 *tests-per-simple-equals*) (* 3 *tests-per-simple-has*) 54)) (simple-equals-tests "") (simple-equals-tests " (universe keyword)" #:from universe) (simple-equals-tests " (universe variable)" #:from *universe*) (simple-has-tests "") (simple-has-tests " (universe keyword)" #:from universe) (simple-has-tests " (universe variable)" #:from *universe*) (let* ((has-artist (collection (has artist))) (missing-artist (collection (¬ has-artist)))) (define-test "not: operator is COLLECTION-TYPE-COMPLEMENT" (pass-if-= (collection-operator missing-artist) COLLECTION-TYPE-COMPLEMENT)) (define-test "not: source of missing-artist is has-artist" (pass-if-equal? (car (collection-children missing-artist)) has-artist))) (define-test "id-lists work #1" (pass-if-equal? (collection-idlist (collection (‣ (1 2 3 4 5 6 7)))) '(1 2 3 4 5 6 7))) (define-test "id-lists work #2" (let ((lst '(1 2 3 4 5 6 7))) (pass-if-equal? (collection-idlist (collection (‣ (| lst)))) lst))) (define-test "id-lists can set type" (let ((lst '(1 2 3 4 5 6 7))) (pass-if-equal? (collection-attribute (collection (‣ lst #:type pshuffle)) 'type) "pshuffle"))) (define-test "variables as arguments work" (let ((band "Slayer")) (pass-if-equal? (collection-attribute (collection (artist = (| band))) 'value) band))) (define-test "expression may be complex in argument position" (let* ((band "Slayer") (stuff `((thing . "fish") (band . ,band)))) (pass-if-equal? (collection-attribute (collection (artist = (| (assq-ref stuff 'band)))) 'value) band))) (define-test "key expression may be complex as well" (let* ((band "Slayer") (stuff `((thing . "fish") (band . ,band))) (key "artist") (wat `((value . band) (key . ,key)))) (pass-if-equal? (collection-attribute (collection ((| (assq-ref wat 'key)) = (| (assq-ref stuff 'band)))) 'field) "artist"))) (define-test "#:namespace argument can be evaluated as well" (let ((ns "Collectionation")) (pass-if-equal? (collection-attribute (collection (→ Slayer #:namespace (| ns))) 'namespace) ns))) (define-test "#:case-sensitive? works #1" (pass-if-= (collection-attribute (collection (artist = Slayer #:case-sensitive? #f)) 'case-sensitive) 0)) (define-test "#:case-sensitive? works #2" (pass-if-= (collection-attribute (collection (artist = Slayer #:case-sensitive? #t)) 'case-sensitive) 1)) (define-test "#:case-sensitive? can use evaluated expressions" (let ((active? #t)) (pass-if-= (collection-attribute (collection (artist = Slayer #:case-sensitive? (| active?))) 'case-sensitive) 1))) (define-test "#:collation works" (pass-if-string=? (collection-attribute (collection (artist = Slayer #:collation BINARY)) 'collation) "BINARY")) (define-test "#:collation upcases symbols" (pass-if-string=? (collection-attribute (collection (artist = Slayer #:collation binary)) 'collation) "BINARY")) (define-test "#:collation upcases strings" (pass-if-string=? (collection-attribute (collection (artist = Slayer #:collation "binary")) 'collation) "BINARY")) (define-test "#:source-preference works" (pass-if-string=? (collection-attribute (collection (artist = Slayer #:source-preference all)) 'source-preference) "all")) (define-test "#:source works" (pass-if-string=? (collection-attribute (collection (artist = Slayer #:source plugin/vorbis)) 'source) "plugin/vorbis")) (define-test "#:order works" (pass-if-string=? (collection-attribute (collection (artist = Slayer #:order ASC)) 'order) "ASC")) (define-test "#:order upcases symbols" (pass-if-string=? (collection-attribute (collection (artist = Slayer #:order asc)) 'order) "ASC")) (define-test "#:order upcases strings" (pass-if-string=? (collection-attribute (collection (artist = Slayer #:order "desc")) 'order) "DESC")) (define-test "#:start works" (pass-if-= (collection-attribute (collection (artist = Slayer #:start 23)) 'start) 23)) (define-test "#:length works" (pass-if-= (collection-attribute (collection (artist = Slayer #:length 42)) 'length) 42)) (collection-type-test = (artist = Slayer) COLLECTION-TYPE-EQUALS) (collection-type-test ≠ (artist ≠ Slayer) COLLECTION-TYPE-NOTEQUAL) (collection-type-test != (artist != Slayer) COLLECTION-TYPE-NOTEQUAL) (collection-type-test INTERSECTION (INTERSECTION (artist = Slayer)) COLLECTION-TYPE-INTERSECTION) (collection-type-test ∩ (∩ (artist = Slayer)) COLLECTION-TYPE-INTERSECTION) (collection-type-test and (and (artist = Slayer)) COLLECTION-TYPE-INTERSECTION) (collection-type-test UNION (UNION (artist = Slayer)) COLLECTION-TYPE-UNION) (collection-type-test ∪ (∪ (artist = Slayer)) COLLECTION-TYPE-UNION) (collection-type-test or (or (artist = Slayer)) COLLECTION-TYPE-UNION) (collection-type-test > (artist > Slayer) COLLECTION-TYPE-GREATER) (collection-type-test ≥ (artist ≥ Slayer) COLLECTION-TYPE-GREATEREQ) (collection-type-test >= (artist >= Slayer) COLLECTION-TYPE-GREATEREQ) (collection-type-test < (artist < Slayer) COLLECTION-TYPE-SMALLER) (collection-type-test ≤ (artist ≤ Slayer) COLLECTION-TYPE-SMALLEREQ) (collection-type-test <= (artist <= Slayer) COLLECTION-TYPE-SMALLEREQ) (collection-type-test not (not (artist = Slayer)) COLLECTION-TYPE-COMPLEMENT) (collection-type-test COMPLEMENT (COMPLEMENT (artist = Slayer)) COLLECTION-TYPE-COMPLEMENT) (collection-type-test ¬ (¬ (artist = Slayer)) COLLECTION-TYPE-COMPLEMENT) (collection-type-test ~ (artist ~ Slayer) COLLECTION-TYPE-MATCH) (collection-type-test match (artist match Slayer) COLLECTION-TYPE-MATCH) (collection-type-test has (has artist) COLLECTION-TYPE-HAS) (collection-type-test REFERENCE (REFERENCE Slayer) COLLECTION-TYPE-REFERENCE) (collection-type-test reference (reference Slayer) COLLECTION-TYPE-REFERENCE) (collection-type-test ‣ (‣ '(1 2 2 3 4 5)) COLLECTION-TYPE-IDLIST) (collection-type-test id-list (id-list '(1 2 2 3 4 5)) COLLECTION-TYPE-IDLIST) (collection-type-test ID-LIST (ID-LIST '(1 2 2 3 4 5)) COLLECTION-TYPE-IDLIST) (collection-type-test limit (limit #:start 100 #:length 100 #:from universe) COLLECTION-TYPE-LIMIT) (collection-type-test media-set (media-set #:from universe) COLLECTION-TYPE-MEDIASET) (collection-type-test ∈ (∈ #:from universe) COLLECTION-TYPE-MEDIASET) (collection-type-test order (order #:type random #:from universe) COLLECTION-TYPE-ORDER) (collection-type-test token (artist token * #:from universe) COLLECTION-TYPE-TOKEN) (collection-type-test ~~ (artist ~~ * #:from universe) COLLECTION-TYPE-TOKEN))
true
b1fbb0e449d8026cd0eb243c0e15d3b671ace0c7
de21ee2b90a109c443485ed2e25f84daf4327af3
/exercise/section3/3.62.scm
2d147b691017028896e665d257722a8939f50e0c
[]
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,773
scm
3.62.scm
;= Question ============================================================================= ; ; 問題 3.62 ; ; 問題3.60と3.61を使い, 二つのべき級数を割る手続きdiv-seriesを定義せよ. ; 分母の級数は零でない定数項で始るとし, 任意の二つの級数について働くものとする. ; (分母が零の定数項を持つなら, div-seriesはエラーを出すべきである.) ; div-seriesを問題3.59の結果と共に使い, 正接のべき級数を生成する方法を述べよ. ; ;= Prepared ============================================================================= (load "./stream.scm") (define (integers-starting-from n) (cons-stream n (integers-starting-from (+ n 1)))) (define integers (integers-starting-from 1)) (define (mul-series s1 s2) (cons-stream (* (stream-car s1) (stream-car s2)) (add-streams (stream-map (lambda (x) (* (stream-car s1) x)) (stream-cdr s2)) (mul-series (stream-cdr s1) s2)))) (define ones (cons-stream 1 ones)) (define (scale-stream stream factor) (stream-map (lambda (x) (* x factor)) stream)) (define (invert-unit-series s1) (cons-stream 1 (mul-series (scale-stream (stream-cdr s1) -1) (invert-unit-series s1) ))) ;= Answer =============================================================================== (define (div-series2 s1 s2) (mul-series s1 (invert-unit-series s2))) ;= Test ================================================================================= (define s (div-series2 integers ones)) (stream-head s 5)
false
2fee23b23a02c9a7045401a16268d91e83012e95
3fa28c4040652eaa485ae0b4eebeaf22956e0da3
/streams/streams.scm
5f857fe50ad24057ec09a0c3ddd8816762c55499
[]
no_license
indraastra/scheme
a9e09bbb2567ff0aa3985d8023a2c25db85713b7
17dab89914a931ed6b31f747bff49741a908744a
refs/heads/master
2021-01-24T06:41:01.890407
2011-09-08T00:55:49
2011-09-08T00:55:49
2,345,530
0
0
null
null
null
null
UTF-8
Scheme
false
false
740
scm
streams.scm
(define (double x) (* 2 x)) (define (square x) (* x x)) ;; defining and working with streams (define (s-car s) (car s)) (define (s-cdr s) (cons ((cdr s) (car s)) (cdr s))) (define (stream n f) (cons n f)) (define (map-stream f s) (let ((first (s-car s)) (rest (s-cdr s))) (stream first (lambda (n) ; ignores n (set! first (s-car rest)) (set! rest (s-cdr rest)) (f first))))) (define (generate-n s n) (if (= n 0) '() (cons (s-car s) (generate-n (s-cdr s) (- n 1))))) ;; some useful streams (define ints (stream 0 (lambda (n) (+ n 1)))) (define evens (map-stream double ints)) (define squares (map-stream square ints))
false
db8c8ffd9515374e567d25c65184278166817080
6f86602ac19983fcdfcb2710de6e95b60bfb0e02
/exercises/practice/phone-number/test.scm
f27ef1b52f802bedf419de3c21ba81653cca0c60
[ "MIT", "CC-BY-SA-3.0" ]
permissive
exercism/scheme
a28bf9451b8c070d309be9be76f832110f2969a7
d22a0f187cd3719d071240b1d5a5471e739fed81
refs/heads/main
2023-07-20T13:35:56.639056
2023-07-18T08:38:59
2023-07-18T08:38:59
30,056,632
34
37
MIT
2023-09-04T21:08:27
2015-01-30T04:46:03
Scheme
UTF-8
Scheme
false
false
2,030
scm
test.scm
(load "test-util.ss") (define test-cases `((test-success "cleans the number" equal? clean '("(223) 456-7890") "2234567890") (test-success "cleans numbers with dots" equal? clean '("223.456.7890") "2234567890") (test-success "cleans numbers with multiple spaces" equal? clean '("223 456 7890 ") "2234567890") (test-error "invalid when 9 digits" clean '("123456789")) (test-error "invalid when 11 digits does not start with a 1" clean '("22234567890")) (test-success "valid when 11 digits and starting with 1" equal? clean '("12234567890") "2234567890") (test-success "valid when 11 digits and starting with 1 even with punctuation" equal? clean '("+1 (223) 456-7890") "2234567890") (test-error "invalid when more than 11 digits" clean '("321234567890")) (test-error "invalid with letters" clean '("123-abc-7890")) (test-error "invalid with punctuations" clean '("123-@:!-7890")) (test-error "invalid if area code starts with 0" clean '("(023) 456-7890")) (test-error "invalid if area code starts with 1" clean '("(123) 456-7890")) (test-error "invalid if exchange code starts with 0" clean '("(223) 056-7890")) (test-error "invalid if exchange code starts with 1" clean '("(223) 156-7890")) (test-error "invalid if area code starts with 0 on valid 11-digit number" clean '("1 (023) 456-7890")) (test-error "invalid if area code starts with 1 on valid 11-digit number" clean '("1 (123) 456-7890")) (test-error "invalid if exchange code starts with 0 on valid 11-digit number" clean '("1 (223) 056-7890")) (test-error "invalid if exchange code starts with 1 on valid 11-digit number" clean '("1 (223) 156-7890")))) (run-with-cli "phone-number.scm" (list test-cases))
false
cf5ae38e12813dff2c091fafd949345ea1149edb
40395de4446cbdbf1ffd0d67f9076c1f61d572ad
/cyclone/cyclone.scm
cc7f007c735d0ff2a428345996f76fdec3b96970
[]
no_license
justinethier/nugget
959757d66f0a8597ab9a25d027eb17603e3e1823
0c4e3e9944684ea83191671d58b5c8c342f64343
refs/heads/master
2020-12-22T06:36:53.844584
2016-07-14T03:30:09
2016-07-14T03:30:09
3,466,831
16
4
null
null
null
null
UTF-8
Scheme
false
false
5,110
scm
cyclone.scm
;; Cyclone Scheme ;; Copyright (c) 2014, Justin Ethier ;; All rights reserved. ;; ;; This module contains a front-end for the compiler itself. ;; (cond-expand (chicken (require-extension extras) ;; pretty-print (require-extension chicken-syntax) ;; when (load "parser.so") (load "trans.so") (load "cgen.so")) ; (husk ; (import (husk pretty-print)) ; ;; TODO: load files ; ) (else (load "parser.scm") (load "trans.scm") (load "cgen.scm"))) ;; Code emission. ; c-compile-and-emit : (string -> A) exp -> void (define (c-compile-and-emit input-program) (call/cc (lambda (return) (define globals '()) (emit *c-file-header-comment*) ; Guarantee placement at top of C file (trace:info "---------------- input program:") (trace:info input-program) ;pretty-print (set! input-program (add-libs input-program)) (set! input-program (expand input-program)) (trace:info "---------------- after macro expansion:") (trace:info input-program) ;pretty-print (set! input-program (filter-unused-variables (isolate-globals input-program))) (trace:info "---------------- after processing globals") (trace:info input-program) ;pretty-print ; Note alpha-conversion is overloaded to convert internal defines to ; set!'s below, since all remaining phases operate on set!, not define. ; ; TODO: consider moving some of this alpha-conv logic below back into trans? (set! globals (global-vars input-program)) (set! input-program (map (lambda (expr) (alpha-convert expr globals return)) input-program)) (trace:info "---------------- after alpha conversion:") (trace:info input-program) ;pretty-print (set! input-program (map (lambda (expr) (cps-convert expr)) input-program)) (trace:info "---------------- after CPS:") (trace:info input-program) ;pretty-print (set! input-program (map (lambda (expr) (clear-mutables) (analyze-mutable-variables expr) (wrap-mutables expr globals)) input-program)) (trace:info "---------------- after wrap-mutables:") (trace:info input-program) ;pretty-print (set! input-program (map (lambda (expr) (if (define? expr) ;; Global `(define ,(define->var expr) ,@(caddr (closure-convert (define->exp expr) globals))) (caddr ;; Strip off superfluous lambda (closure-convert expr globals)))) input-program)) ; (caddr ;; Strip off superfluous lambda ; (closure-convert input-program))) (trace:info "---------------- after closure-convert:") (trace:info input-program) ;pretty-print (if (not *do-code-gen*) (begin (trace:error "DEBUG, existing program") (exit))) (trace:info "---------------- C code:") (mta:code-gen input-program globals) (return '())))) ;; No codes to return ;; TODO: longer-term, will be used to find where cyclone's data is installed (define (get-data-path) ".") (define (get-lib filename) (string-append (get-data-path) "/" filename)) (define (read-file filename) (call-with-input-file filename (lambda (port) (read-all port)))) ;; Compile and emit: (define (run-compiler args cc?) (let* ((in-file (car args)) (in-prog (read-file in-file)) (exec-file (basename in-file)) (src-file (string-append exec-file ".c")) (create-c-file (lambda (program) (with-output-to-file src-file (lambda () (c-compile-and-emit program))))) (result (create-c-file in-prog))) ;; Load other modules if necessary (cond ((not (null? result)) (let ((program (append (if (member 'eval result) (read-file (get-lib "eval.scm")) '()) (if (member 'read result) (append (read-file (get-lib "parser.scm")) '((define read cyc-read))) '()) in-prog))) (create-c-file program)))) ;; Compile the generated C file (if cc? (system ;; -I is a hack, real answer is to use 'make install' to place .h file (string-append "gcc " src-file " -I. -g -o " exec-file))))) ;; Handle command line arguments (let ((args (command-line-arguments))) ;; TODO: port (command-line-arguments) to husk?? (cond ((< (length args) 1) (display "cyclone: no input file") (newline)) ((member "-h" args) (display "TODO: display help text") (newline)) ((member "-v" args) (display *version-banner*)) ((member "-d" args) (run-compiler args #f)) ;; Debug, do not run GCC (else (run-compiler args #t))))
false
c27d3805012269a1111d811a5eecec779c8f2307
dd4cc30a2e4368c0d350ced7218295819e102fba
/vendored_parsers/vendor/tree-sitter-scala/queries/highlights.scm
4a0c8494d049c6618ea614fc6d028382cefe39f7
[ "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
835
scm
highlights.scm
;; Annotations "@" @operator ;; Types (class_definition name: (identifier) @type) (trait_definition name: (identifier) @type) (object_definition name: (identifier) @type) (type_identifier) @type ;; Variables ((identifier) @constant (#match? @constant "^_*[A-Z][A-Z\\d_]+$")) (identifier) @variable ;; Literals [ (integer_literal) (floating_point_literal) ] @number [ (character_literal) (string) ] @string [ (boolean_literal) (null_literal) ] @constant.builtin (comment) @comment ;; Keywords [ "abstract" "case" "catch" "class" "def" "do" "else" "extends" "final" "finally" "for" "if" "implicit" "import" "lazy" "match" "new" "object" "override" "package" "private" "protected" "return" "sealed" "throw" "trait" "try" "while" "with" ] @keyword
false
e99677101cbb5387533d5b5e0b276c17793c3a5e
f08220a13ec5095557a3132d563a152e718c412f
/logrotate/skel/usr/share/guile/2.0/language/scheme/decompile-tree-il.scm
fad857d33dd9a939520da788889b8761199e8c8d
[ "Apache-2.0" ]
permissive
sroettger/35c3ctf_chals
f9808c060da8bf2731e98b559babd4bf698244ac
3d64486e6adddb3a3f3d2c041242b88b50abdb8d
refs/heads/master
2020-04-16T07:02:50.739155
2020-01-15T13:50:29
2020-01-15T13:50:29
165,371,623
15
5
Apache-2.0
2020-01-18T11:19:05
2019-01-12T09:47:33
Python
UTF-8
Scheme
false
false
33,501
scm
decompile-tree-il.scm
;;; Guile VM code converters ;; Copyright (C) 2001, 2009, 2012, 2013 Free Software Foundation, Inc. ;;;; This library is free software; you can redistribute it and/or ;;;; modify it under the terms of the GNU Lesser General Public ;;;; License as published by the Free Software Foundation; either ;;;; version 3 of the License, or (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; Lesser General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Lesser General Public ;;;; License along with this library; if not, write to the Free Software ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ;;; Code: (define-module (language scheme decompile-tree-il) #:use-module (language tree-il) #:use-module (srfi srfi-1) #:use-module (srfi srfi-26) #:use-module (ice-9 receive) #:use-module (ice-9 vlist) #:use-module (ice-9 match) #:use-module (system base syntax) #:export (decompile-tree-il)) (define (decompile-tree-il e env opts) (apply do-decompile e env opts)) (define* (do-decompile e env #:key (use-derived-syntax? #t) (avoid-lambda? #t) (use-case? #t) (strip-numeric-suffixes? #f) #:allow-other-keys) (receive (output-name-table occurrence-count-table) (choose-output-names e use-derived-syntax? strip-numeric-suffixes?) (define (output-name s) (hashq-ref output-name-table s)) (define (occurrence-count s) (hashq-ref occurrence-count-table s)) (define (const x) (lambda (_) x)) (define (atom? x) (not (or (pair? x) (vector? x)))) (define (build-void) '(if #f #f)) (define (build-begin es) (match es (() (build-void)) ((e) e) (_ `(begin ,@es)))) (define (build-lambda-body e) (match e (('let () body ...) body) (('begin es ...) es) (_ (list e)))) (define (build-begin-body e) (match e (('begin es ...) es) (_ (list e)))) (define (build-define name e) (match e ((? (const avoid-lambda?) ('lambda formals body ...)) `(define (,name ,@formals) ,@body)) ((? (const avoid-lambda?) ('lambda* formals body ...)) `(define* (,name ,@formals) ,@body)) (_ `(define ,name ,e)))) (define (build-let names vals body) (match `(let ,(map list names vals) ,@(build-lambda-body body)) ((_ () e) e) ((_ (b) ('let* (bs ...) body ...)) `(let* (,b ,@bs) ,@body)) ((? (const use-derived-syntax?) (_ (b1) ('let (b2) body ...))) `(let* (,b1 ,b2) ,@body)) (e e))) (define (build-letrec in-order? names vals body) (match `(,(if in-order? 'letrec* 'letrec) ,(map list names vals) ,@(build-lambda-body body)) ((_ () e) e) ((_ () body ...) `(let () ,@body)) ((_ ((name ('lambda (formals ...) body ...))) (name args ...)) (=> failure) (if (= (length formals) (length args)) `(let ,name ,(map list formals args) ,@body) (failure))) ((? (const avoid-lambda?) ('letrec* _ body ...)) `(let () ,@(map build-define names vals) ,@body)) (e e))) (define (build-if test consequent alternate) (match alternate (('if #f _) `(if ,test ,consequent)) (_ `(if ,test ,consequent ,alternate)))) (define (build-and xs) (match xs (() #t) ((x) x) (_ `(and ,@xs)))) (define (build-or xs) (match xs (() #f) ((x) x) (_ `(or ,@xs)))) (define (case-test-var test) (match test (('memv (? atom? v) ('quote (datums ...))) v) (('eqv? (? atom? v) ('quote datum)) v) (_ #f))) (define (test->datums v test) (match (cons v test) ((v 'memv v ('quote (xs ...))) xs) ((v 'eqv? v ('quote x)) (list x)) (_ #f))) (define (build-else-tail e) (match e (('if #f _) '()) (('and xs ... x) `((,(build-and xs) ,@(build-begin-body x)) (else #f))) (_ `((else ,@(build-begin-body e)))))) (define (build-cond-else-tail e) (match e (('cond clauses ...) clauses) (_ (build-else-tail e)))) (define (build-case-else-tail v e) (match (cons v e) ((v 'case v clauses ...) clauses) ((v 'if ('memv v ('quote (xs ...))) consequent . alternate*) `((,xs ,@(build-begin-body consequent)) ,@(build-case-else-tail v (build-begin alternate*)))) ((v 'if ('eqv? v ('quote x)) consequent . alternate*) `(((,x) ,@(build-begin-body consequent)) ,@(build-case-else-tail v (build-begin alternate*)))) (_ (build-else-tail e)))) (define (clauses+tail clauses) (match clauses ((cs ... (and c ('else . _))) (values cs (list c))) (_ (values clauses '())))) (define (build-cond tests consequents alternate) (case (length tests) ((0) alternate) ((1) (build-if (car tests) (car consequents) alternate)) (else `(cond ,@(map (lambda (test consequent) `(,test ,@(build-begin-body consequent))) tests consequents) ,@(build-cond-else-tail alternate))))) (define (build-cond-or-case tests consequents alternate) (if (not use-case?) (build-cond tests consequents alternate) (let* ((v (and (not (null? tests)) (case-test-var (car tests)))) (datum-lists (take-while identity (map (cut test->datums v <>) tests))) (n (length datum-lists)) (tail (build-case-else-tail v (build-cond (drop tests n) (drop consequents n) alternate)))) (receive (clauses tail) (clauses+tail tail) (let ((n (+ n (length clauses))) (datum-lists (append datum-lists (map car clauses))) (consequents (append consequents (map build-begin (map cdr clauses))))) (if (< n 2) (build-cond tests consequents alternate) `(case ,v ,@(map cons datum-lists (map build-begin-body (take consequents n))) ,@tail))))))) (define (recurse e) (define (recurse-body e) (build-lambda-body (recurse e))) (record-case e ((<void>) (build-void)) ((<const> exp) (if (and (self-evaluating? exp) (not (vector? exp))) exp `(quote ,exp))) ((<sequence> exps) (build-begin (map recurse exps))) ((<application> proc args) (match `(,(recurse proc) ,@(map recurse args)) ((('lambda (formals ...) body ...) args ...) (=> failure) (if (= (length formals) (length args)) (build-let formals args (build-begin body)) (failure))) (e e))) ((<primitive-ref> name) name) ((<lexical-ref> gensym) (output-name gensym)) ((<lexical-set> gensym exp) `(set! ,(output-name gensym) ,(recurse exp))) ((<module-ref> mod name public?) `(,(if public? '@ '@@) ,mod ,name)) ((<module-set> mod name public? exp) `(set! (,(if public? '@ '@@) ,mod ,name) ,(recurse exp))) ((<toplevel-ref> name) name) ((<toplevel-set> name exp) `(set! ,name ,(recurse exp))) ((<toplevel-define> name exp) (build-define name (recurse exp))) ((<lambda> meta body) (if body (let ((body (recurse body)) (doc (assq-ref meta 'documentation))) (if (not doc) body (match body (('lambda formals body ...) `(lambda ,formals ,doc ,@body)) (('lambda* formals body ...) `(lambda* ,formals ,doc ,@body)) (('case-lambda (formals body ...) clauses ...) `(case-lambda (,formals ,doc ,@body) ,@clauses)) (('case-lambda* (formals body ...) clauses ...) `(case-lambda* (,formals ,doc ,@body) ,@clauses)) (e e)))) '(case-lambda))) ((<lambda-case> req opt rest kw inits gensyms body alternate) (let ((names (map output-name gensyms))) (cond ((and (not opt) (not kw) (not alternate)) `(lambda ,(if rest (apply cons* names) names) ,@(recurse-body body))) ((and (not opt) (not kw)) (let ((alt-expansion (recurse alternate)) (formals (if rest (apply cons* names) names))) (case (car alt-expansion) ((lambda) `(case-lambda (,formals ,@(recurse-body body)) ,(cdr alt-expansion))) ((lambda*) `(case-lambda* (,formals ,@(recurse-body body)) ,(cdr alt-expansion))) ((case-lambda) `(case-lambda (,formals ,@(recurse-body body)) ,@(cdr alt-expansion))) ((case-lambda*) `(case-lambda* (,formals ,@(recurse-body body)) ,@(cdr alt-expansion)))))) (else (let* ((alt-expansion (and alternate (recurse alternate))) (nreq (length req)) (nopt (if opt (length opt) 0)) (restargs (if rest (list-ref names (+ nreq nopt)) '())) (reqargs (list-head names nreq)) (optargs (if opt `(#:optional ,@(map list (list-head (list-tail names nreq) nopt) (map recurse (list-head inits nopt)))) '())) (kwargs (if kw `(#:key ,@(map list (map output-name (map caddr (cdr kw))) (map recurse (list-tail inits nopt)) (map car (cdr kw))) ,@(if (car kw) '(#:allow-other-keys) '())) '())) (formals `(,@reqargs ,@optargs ,@kwargs . ,restargs))) (if (not alt-expansion) `(lambda* ,formals ,@(recurse-body body)) (case (car alt-expansion) ((lambda lambda*) `(case-lambda* (,formals ,@(recurse-body body)) ,(cdr alt-expansion))) ((case-lambda case-lambda*) `(case-lambda* (,formals ,@(recurse-body body)) ,@(cdr alt-expansion)))))))))) ((<conditional> test consequent alternate) (define (simplify-test e) (match e (('if ('eqv? (? atom? v) ('quote a)) #t ('eqv? v ('quote b))) `(memv ,v '(,a ,b))) (('if ('eqv? (? atom? v) ('quote a)) #t ('memv v ('quote (bs ...)))) `(memv ,v '(,a ,@bs))) (('case (? atom? v) ((datum) #t) ... ('else ('eqv? v ('quote last-datum)))) `(memv ,v '(,@datum ,last-datum))) (_ e))) (match `(if ,(simplify-test (recurse test)) ,(recurse consequent) ,@(if (void? alternate) '() (list (recurse alternate)))) (('if test ('if ('and xs ...) consequent)) (build-if (build-and (cons test xs)) consequent (build-void))) ((? (const use-derived-syntax?) ('if test1 ('if test2 consequent))) (build-if (build-and (list test1 test2)) consequent (build-void))) (('if (? atom? x) x ('or ys ...)) (build-or (cons x ys))) ((? (const use-derived-syntax?) ('if (? atom? x) x y)) (build-or (list x y))) (('if test consequent) `(if ,test ,consequent)) (('if test ('and xs ...) #f) (build-and (cons test xs))) ((? (const use-derived-syntax?) ('if test consequent #f)) (build-and (list test consequent))) ((? (const use-derived-syntax?) ('if test1 consequent1 ('if test2 consequent2 . alternate*))) (build-cond-or-case (list test1 test2) (list consequent1 consequent2) (build-begin alternate*))) (('if test consequent ('cond clauses ...)) `(cond (,test ,@(build-begin-body consequent)) ,@clauses)) (('if ('memv (? atom? v) ('quote (xs ...))) consequent ('case v clauses ...)) `(case ,v (,xs ,@(build-begin-body consequent)) ,@clauses)) (('if ('eqv? (? atom? v) ('quote x)) consequent ('case v clauses ...)) `(case ,v ((,x) ,@(build-begin-body consequent)) ,@clauses)) (e e))) ((<let> gensyms vals body) (match (build-let (map output-name gensyms) (map recurse vals) (recurse body)) (('let ((v e)) ('or v xs ...)) (=> failure) (if (and (not (null? gensyms)) (= 3 (occurrence-count (car gensyms)))) `(or ,e ,@xs) (failure))) (('let ((v e)) ('case v clauses ...)) (=> failure) (if (and (not (null? gensyms)) ;; FIXME: This fails if any of the 'memv's were ;; optimized into multiple 'eqv?'s, because the ;; occurrence count will be higher than we expect. (= (occurrence-count (car gensyms)) (1+ (length (clauses+tail clauses))))) `(case ,e ,@clauses) (failure))) (e e))) ((<letrec> in-order? gensyms vals body) (build-letrec in-order? (map output-name gensyms) (map recurse vals) (recurse body))) ((<fix> gensyms vals body) ;; not a typo, we really do translate back to letrec. use letrec* since it ;; doesn't matter, and the naive letrec* transformation does not require an ;; inner let. (build-letrec #t (map output-name gensyms) (map recurse vals) (recurse body))) ((<let-values> exp body) `(call-with-values (lambda () ,@(recurse-body exp)) ,(recurse (make-lambda #f '() body)))) ((<dynwind> body winder unwinder) `(dynamic-wind ,(recurse winder) (lambda () ,@(recurse-body body)) ,(recurse unwinder))) ((<dynlet> fluids vals body) `(with-fluids ,(map list (map recurse fluids) (map recurse vals)) ,@(recurse-body body))) ((<dynref> fluid) `(fluid-ref ,(recurse fluid))) ((<dynset> fluid exp) `(fluid-set! ,(recurse fluid) ,(recurse exp))) ((<prompt> tag body handler) `(call-with-prompt ,(recurse tag) (lambda () ,@(recurse-body body)) ,(recurse handler))) ((<abort> tag args tail) `(apply abort ,(recurse tag) ,@(map recurse args) ,(recurse tail))))) (values (recurse e) env))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Algorithm for choosing better variable names ;; ============================================ ;; ;; First we perform an analysis pass, collecting the following ;; information: ;; ;; * For each gensym: how many occurrences will occur in the output? ;; ;; * For each gensym A: which gensyms does A conflict with? Gensym A ;; and gensym B conflict if they have the same base name (usually the ;; same as the source name, but see below), and if giving them the ;; same name would cause a bad variable reference due to unintentional ;; variable capture. ;; ;; The occurrence counter is indexed by gensym and is global (within each ;; invocation of the algorithm), implemented using a hash table. We also ;; keep a global mapping from gensym to source name as provided by the ;; binding construct (we prefer not to trust the source names in the ;; lexical ref or set). ;; ;; As we recurse down into lexical binding forms, we keep track of a ;; mapping from base name to an ordered list of bindings, innermost ;; first. When we encounter a variable occurrence, we increment the ;; counter, look up the base name (preferring not to trust the 'name' in ;; the lexical ref or set), and then look up the bindings currently in ;; effect for that base name. Hopefully our gensym will be the first ;; (innermost) binding. If not, we register a conflict between the ;; referenced gensym and the other bound gensyms with the same base name ;; that shadow the binding we want. These are simply the gensyms on the ;; binding list that come before our gensym. ;; ;; Top-level bindings are treated specially. Whenever top-level ;; references are found, they conflict with every lexical binding ;; currently in effect with the same base name. They are guaranteed to ;; be assigned to their source names. For purposes of recording ;; conflicts (which are normally keyed on gensyms) top-level identifiers ;; are assigned a pseudo-gensym that is an interned pair of the form ;; (top-level . <name>). This allows them to be compared using 'eq?' ;; like other gensyms. ;; ;; The base name is normally just the source name. However, if the ;; source name has a suffix of the form "-N" (where N is a positive ;; integer without leading zeroes), then we strip that suffix (multiple ;; times if necessary) to form the base name. We must do this because ;; we add suffixes of that form in order to resolve conflicts, and we ;; must ensure that only identifiers with the same base name can ;; possibly conflict with each other. ;; ;; XXX FIXME: Currently, primitives are treated exactly like top-level ;; bindings. This handles conflicting lexical bindings properly, but ;; does _not_ handle the case where top-level bindings conflict with the ;; needed primitives. ;; ;; Also note that this requires that 'choose-output-names' be kept in ;; sync with 'tree-il->scheme'. Primitives that are introduced by ;; 'tree-il->scheme' must be anticipated by 'choose-output-name'. ;; ;; We also ensure that lexically-bound identifiers found in operator ;; position will never be assigned one of the standard primitive names. ;; This is needed because 'tree-il->scheme' recognizes primitive names ;; in operator position and assumes that they have the standard ;; bindings. ;; ;; ;; How we assign an output name to each gensym ;; =========================================== ;; ;; We process the gensyms in order of decreasing occurrence count, with ;; each gensym choosing the best output name possible, as long as it ;; isn't the same name as any of the previously-chosen output names of ;; conflicting gensyms. ;; ;; ;; 'choose-output-names' analyzes the top-level form e, chooses good ;; variable names that are as close as possible to the source names, ;; and returns two values: ;; ;; * a hash table mapping gensym to output name ;; * a hash table mapping gensym to number of occurrences ;; (define choose-output-names (let () (define primitive? ;; This is a list of primitives that 'tree-il->scheme' assumes ;; will have the standard bindings when found in operator ;; position. (let* ((primitives '(if quote @ @@ set! define define* begin let let* letrec letrec* and or cond case lambda lambda* case-lambda case-lambda* apply call-with-values dynamic-wind with-fluids fluid-ref fluid-set! call-with-prompt abort memv eqv?)) (table (make-hash-table (length primitives)))) (for-each (cut hashq-set! table <> #t) primitives) (lambda (name) (hashq-ref table name)))) ;; Repeatedly strip suffix of the form "-N", where N is a string ;; that could be produced by number->string given a positive ;; integer. In other words, the first digit of N may not be 0. (define compute-base-name (let ((digits (string->char-set "0123456789"))) (define (base-name-string str) (let ((i (string-skip-right str digits))) (if (and i (< (1+ i) (string-length str)) (eq? #\- (string-ref str i)) (not (eq? #\0 (string-ref str (1+ i))))) (base-name-string (substring str 0 i)) str))) (lambda (sym) (string->symbol (base-name-string (symbol->string sym)))))) ;; choose-output-names (lambda (e use-derived-syntax? strip-numeric-suffixes?) (define lexical-gensyms '()) (define top-level-intern! (let ((table (make-hash-table))) (lambda (name) (let ((h (hashq-create-handle! table name #f))) (or (cdr h) (begin (set-cdr! h (cons 'top-level name)) (cdr h))))))) (define (top-level? s) (pair? s)) (define (top-level-name s) (cdr s)) (define occurrence-count-table (make-hash-table)) (define (occurrence-count s) (or (hashq-ref occurrence-count-table s) 0)) (define (increment-occurrence-count! s) (let ((h (hashq-create-handle! occurrence-count-table s 0))) (if (zero? (cdr h)) (set! lexical-gensyms (cons s lexical-gensyms))) (set-cdr! h (1+ (cdr h))))) (define base-name (let ((table (make-hash-table))) (lambda (name) (let ((h (hashq-create-handle! table name #f))) (or (cdr h) (begin (set-cdr! h (compute-base-name name)) (cdr h))))))) (define source-name-table (make-hash-table)) (define (set-source-name! s name) (if (not (top-level? s)) (let ((name (if strip-numeric-suffixes? (base-name name) name))) (hashq-set! source-name-table s name)))) (define (source-name s) (if (top-level? s) (top-level-name s) (hashq-ref source-name-table s))) (define conflict-table (make-hash-table)) (define (conflicts s) (or (hashq-ref conflict-table s) '())) (define (add-conflict! a b) (define (add! a b) (if (not (top-level? a)) (let ((h (hashq-create-handle! conflict-table a '()))) (if (not (memq b (cdr h))) (set-cdr! h (cons b (cdr h))))))) (add! a b) (add! b a)) (let recurse-with-bindings ((e e) (bindings vlist-null)) (let recurse ((e e)) ;; We call this whenever we encounter a top-level ref or set (define (top-level name) (let ((bname (base-name name))) (let ((s (top-level-intern! name)) (conflicts (vhash-foldq* cons '() bname bindings))) (for-each (cut add-conflict! s <>) conflicts)))) ;; We call this whenever we encounter a primitive reference. ;; We must also call it for every primitive that might be ;; inserted by 'tree-il->scheme'. It is okay to call this ;; even when 'tree-il->scheme' will not insert the named ;; primitive; the worst that will happen is for a lexical ;; variable of the same name to be renamed unnecessarily. (define (primitive name) (top-level name)) ;; We call this whenever we encounter a lexical ref or set. (define (lexical s) (increment-occurrence-count! s) (let ((conflicts (take-while (lambda (s*) (not (eq? s s*))) (reverse! (vhash-foldq* cons '() (base-name (source-name s)) bindings))))) (for-each (cut add-conflict! s <>) conflicts))) (record-case e ((<void>) (primitive 'if)) ; (if #f #f) ((<const>) (primitive 'quote)) ((<application> proc args) (if (lexical-ref? proc) (let* ((gensym (lexical-ref-gensym proc)) (name (source-name gensym))) ;; If the operator position contains a bare variable ;; reference with the same source name as a standard ;; primitive, we must ensure that it will be given a ;; different name, so that 'tree-il->scheme' will not ;; misinterpret the resulting expression. (if (primitive? name) (add-conflict! gensym (top-level-intern! name))))) (recurse proc) (for-each recurse args)) ((<primitive-ref> name) (primitive name)) ((<lexical-ref> gensym) (lexical gensym)) ((<lexical-set> gensym exp) (primitive 'set!) (lexical gensym) (recurse exp)) ((<module-ref> public?) (primitive (if public? '@ '@@))) ((<module-set> public? exp) (primitive 'set!) (primitive (if public? '@ '@@)) (recurse exp)) ((<toplevel-ref> name) (top-level name)) ((<toplevel-set> name exp) (primitive 'set!) (top-level name) (recurse exp)) ((<toplevel-define> name exp) (top-level name) (recurse exp)) ((<conditional> test consequent alternate) (cond (use-derived-syntax? (primitive 'and) (primitive 'or) (primitive 'cond) (primitive 'case) (primitive 'else) (primitive '=>))) (primitive 'if) (recurse test) (recurse consequent) (recurse alternate)) ((<sequence> exps) (primitive 'begin) (for-each recurse exps)) ((<lambda> body) (if body (recurse body) (primitive 'case-lambda))) ((<lambda-case> req opt rest kw inits gensyms body alternate) (primitive 'lambda) (cond ((or opt kw alternate) (primitive 'lambda*) (primitive 'case-lambda) (primitive 'case-lambda*))) (primitive 'let) (if use-derived-syntax? (primitive 'let*)) (let* ((names (append req (or opt '()) (if rest (list rest) '()) (map cadr (if kw (cdr kw) '())))) (base-names (map base-name names)) (body-bindings (fold vhash-consq bindings base-names gensyms))) (for-each increment-occurrence-count! gensyms) (for-each set-source-name! gensyms names) (for-each recurse inits) (recurse-with-bindings body body-bindings) (if alternate (recurse alternate)))) ((<let> names gensyms vals body) (primitive 'let) (cond (use-derived-syntax? (primitive 'let*) (primitive 'or))) (for-each increment-occurrence-count! gensyms) (for-each set-source-name! gensyms names) (for-each recurse vals) (recurse-with-bindings body (fold vhash-consq bindings (map base-name names) gensyms))) ((<letrec> in-order? names gensyms vals body) (primitive 'let) (cond (use-derived-syntax? (primitive 'let*) (primitive 'or))) (primitive (if in-order? 'letrec* 'letrec)) (for-each increment-occurrence-count! gensyms) (for-each set-source-name! gensyms names) (let* ((base-names (map base-name names)) (bindings (fold vhash-consq bindings base-names gensyms))) (for-each (cut recurse-with-bindings <> bindings) vals) (recurse-with-bindings body bindings))) ((<fix> names gensyms vals body) (primitive 'let) (primitive 'letrec*) (cond (use-derived-syntax? (primitive 'let*) (primitive 'or))) (for-each increment-occurrence-count! gensyms) (for-each set-source-name! gensyms names) (let* ((base-names (map base-name names)) (bindings (fold vhash-consq bindings base-names gensyms))) (for-each (cut recurse-with-bindings <> bindings) vals) (recurse-with-bindings body bindings))) ((<let-values> exp body) (primitive 'call-with-values) (recurse exp) (recurse body)) ((<dynwind> winder body unwinder) (primitive 'dynamic-wind) (recurse winder) (recurse body) (recurse unwinder)) ((<dynlet> fluids vals body) (primitive 'with-fluids) (for-each recurse fluids) (for-each recurse vals) (recurse body)) ((<dynref> fluid) (primitive 'fluid-ref) (recurse fluid)) ((<dynset> fluid exp) (primitive 'fluid-set!) (recurse fluid) (recurse exp)) ((<prompt> tag body handler) (primitive 'call-with-prompt) (primitive 'lambda) (recurse tag) (recurse body) (recurse handler)) ((<abort> tag args tail) (primitive 'apply) (primitive 'abort) (recurse tag) (for-each recurse args) (recurse tail))))) (let () (define output-name-table (make-hash-table)) (define (set-output-name! s name) (hashq-set! output-name-table s name)) (define (output-name s) (if (top-level? s) (top-level-name s) (hashq-ref output-name-table s))) (define sorted-lexical-gensyms (sort-list lexical-gensyms (lambda (a b) (> (occurrence-count a) (occurrence-count b))))) (for-each (lambda (s) (set-output-name! s (let ((the-conflicts (conflicts s)) (the-source-name (source-name s))) (define (not-yet-taken? name) (not (any (lambda (s*) (and=> (output-name s*) (cut eq? name <>))) the-conflicts))) (if (not-yet-taken? the-source-name) the-source-name (let ((prefix (string-append (symbol->string the-source-name) "-"))) (let loop ((i 1) (name the-source-name)) (if (not-yet-taken? name) name (loop (+ i 1) (string->symbol (string-append prefix (number->string i))))))))))) sorted-lexical-gensyms) (values output-name-table occurrence-count-table)))))
false
2aff7e29a7c4a577764100f21a2848f30cef8550
3d7d838bfd035e9d42d607ffd644572dfa622b98
/guile/examples.scm
da76d8ef1fdd097bea3b44dd0fde2d9b790d894e
[]
no_license
scheme-requests-for-implementation/srfi-202
216ae2da2e4028f68b9da814d603a2166b9f547d
40f7f1961ae60f59f833814f9ae88b9e6e72da9e
refs/heads/master
2023-01-15T07:17:14.197710
2020-11-28T23:29:11
2020-11-28T23:29:14
275,073,973
0
1
null
2020-11-27T05:05:22
2020-06-26T04:35:17
HTML
UTF-8
Scheme
false
false
4,858
scm
examples.scm
#!/usr/bin/guile \ -L . -s !# (use-modules (srfi srfi-202)) ;; Before showing the capabilities of SRFI-202, ;; we're going to build a little unit test framework ;; for ourselves. The main interface to the framework ;; will be the "e.g." form, whose main use is going to ;; be: ;; (e.g. <expression> ===> <value>) ;; which checks whether <expression> evaluates to <value>, ;; and reports an error if that's not the case. ;; Moreover, since Scheme expressions can in general have ;; more (or less) than one value, we allow the usages: ;; (e.g. <expression> ===> <values> ...) ;; where <values> ... is a sequence of zero or more ;; literals. (define-syntax e.g. (syntax-rules (===>) ((e.g. <expression> ===> <values> ...) (call-with-values (lambda () <expression>) (lambda results (if (equal? results '(<values> ...)) (apply values results) (error '(<expression> ===> <values> ...) results))))) )) ;; The SRFI-202 should be backwards compatible with ;; SRFI-2, including the following use cases: ;; if the 'claws' do not stand on the way, the empty ;; body evaluates to #t (e.g. (and-let* ()) ===> #t) (e.g. (and-let* ((even-two (even? 2)))) ===> #t) (e.g. (and-let* ((b+ (memq 'b '(a b c))))) ===> #t) ;; presence of a false binding evaluates to #f: (e.g. (and-let* ((even-one (even? 1))) 'body) ===> #f) ;; if we don't want to use the result, we can skip ;; the variable name: (e.g. (and-let* (((even? 1))) 'body) ===> #f) ;; successfully passing the claws causes the and-let* ;; expression to have the value(s) of its body: (e.g. (and-let* ((even-two (even? 2))) 'body) ===> body) (e.g. (and-let* ((b+ (memq 'b '(a b c)))) b+) ===> (b c)) (e.g. (and-let* ((abc '(a b c)) (b+ (memq 'b abc)) (c+ (memq 'c abc)) ((eq? (cdr b+) c+))) (values b+ c+)) ===> (b c) (c)) (e.g. (and-let* () (values 1 2)) ===> 1 2) ;; The novel parts of SRFI-202 compared to ;; SRFI-2 are: the support for multiple values ;; combined with the support for pattern matching. ;; Multiple values can be handled in two ways: ;; either by passing the additional idenifiers/patterns ;; directly after the first one (e.g. (and-let* ((a b (values 1 2)))) ===> #t) ;; or by using the "values" keyword (e.g. (and-let* (((values a b) (values 1 2)))) ===> #t) ;; (mind that the result of combining those two methods ;; is unspecified, and in principle they should not be ;; combined) ;; The key difference between those two methods is that ;; in the first, the additional return values are simply ;; ignored (e.g. (and-let* ((a b (values 1 2 3)))) ===> #t) ;; whereas in the second, the presence of additional ;; values causes the form to "short-circuit": (e.g. (and-let* (((values a b) (values 1 2 3)))) ===> #f) ;; However, the second method allows to capture the ;; remaining values in a list: (e.g. (and-let* (((values a b . c) (values 1 2 3))) (values a b c)) ===> 1 2 (3)) ;; Another, more subtle difference is that, if the ;; first method of capturing multiple values is used, ;; and the first pattern is an identifier, then ;; the value of the variable represented by ;; that identifier must be non-#f to succeed (e.g. (and-let* ((a b (values #f #t)))) ===> #f) ;; whereas, if the "values" keyword is used, this is ;; not the case: (e.g. (and-let* (((values a b) (values #f #t)))) ===> #t) ;; If one finds this behavior undesirable, then ;; in the first case, one can either use a trivial ;; pattern in the position of the first received value (e.g. (and-let* ((`,a b (values #f #t)))) ===> #t) ;; or (e.g. (and-let* (((or a) b (values #f #t)))) ===> #t) ;; or -- if the value is known to be #f -- to express ;; that explicitly without making a binding (e.g. (and-let* ((#f b (values #f #t)))) ===> #t) ;; and in the second case, one needs to add a guard ;; if they want to short-circuit the sequence: (e.g. (and-let* (((values a b) (values #f #t)) (a))) ===> #f) ;; This SRFI doesn't specify the pattern matcher ;; to be used for destructuring. Here, we assume ;; Guile's (ice-9 match) module that was used for ;; the underlying implementation (the Wright-Cartwright ;; -Shinn matcher, described by SRFI-200 and SRFI-204), ;; but any matcher that comes with a particular Scheme ;; implementation or that is widely recognized by some ;; Scheme community should be fine. ;; SRFI-202 assumes that a match failure causes ;; the form to short-circuit/fail: (e.g. (and-let* ((`(,x . ,y) '()))) ===> #f) (e.g. (and-let* ((`(,x ,y) '(1 2 3)))) ===> #f) (e.g. (and-let* ((5 (+ 2 2)))) ===> #f) (e.g. (and-let* ((#t #f #t (values #f #t #f)))) ===> #f) ;; on the other hand, a successful match causes ;; the variables to be bound at later scopes: (e.g. (and-let* ((`(,x ,y) '(2 3)) (x+y (+ x y)) ((odd? x+y)) (5 x+y)) x) ===> 2)
true
9a86ecaa107696f2b5c726db40bdf154f820bfac
120324bbbf63c54de0b7f1ca48d5dcbbc5cfb193
/packages/irregex/irregex-r6rs.scm
d866eec97b4e3e88e2f6f8ba30c4ce812c1521be
[ "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
169,351
scm
irregex-r6rs.scm
;;;; irregex.scm -- IrRegular Expressions ;; ;; Copyright (c) 2005-2016 Alex Shinn. All rights reserved. ;; BSD-style license: http://synthcode.com/license.txt ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; At this moment there was a loud ring at the bell, and I could ;; hear Mrs. Hudson, our landlady, raising her voice in a wail of ;; expostulation and dismay. ;; ;; "By heaven, Holmes," I said, half rising, "I believe that ;; they are really after us." ;; ;; "No, it's not quite so bad as that. It is the unofficial ;; force, -- the Baker Street irregulars." ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Notes ;; ;; This code should not require any porting - it should work out of ;; the box in any R[45]RS Scheme implementation. Slight modifications ;; are needed for R6RS (a separate R6RS-compatible version is included ;; in the distribution as irregex-r6rs.scm). ;; ;; The goal of portability makes this code a little clumsy and ;; inefficient. Future versions will include both cleanup and ;; performance tuning, but you can only go so far while staying ;; portable. AND-LET*, SRFI-9 records and custom macros would've been ;; nice. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; History ;; 0.9.6: 2016/12/05 - fixed exponential memory use of + in compilation ;; of backtracking matcher. ;; 0.9.5: 2016/09/10 - fixed a bug in irregex-fold handling of bow ;; 0.9.4: 2015/12/14 - performance improvement for {n,m} matches ;; 0.9.3: 2014/07/01 - R7RS library ;; 0.9.2: 2012/11/29 - fixed a bug in -fold on conditional bos patterns ;; 0.9.1: 2012/11/27 - various accumulated bugfixes ;; 0.9.0: 2012/06/03 - Using tags for match extraction from Peter Bex. ;; 0.8.3: 2011/12/18 - various accumulated bugfixes ;; 0.8.2: 2010/08/28 - (...)? submatch extraction fix and alternate ;; named submatches from Peter Bex ;; Added irregex-split, irregex-extract, ;; irregex-match-names and irregex-match-valid-index? ;; to Chicken and Guile module export lists and made ;; the latter accept named submatches. The procedures ;; irregex-match-{start,end}-{index,chunk} now also ;; accept named submatches, with the index argument ;; made optional. Improved argument type checks. ;; Disallow negative submatch index. ;; Improve performance of backtracking matcher. ;; Refactor charset handling into a consistent API ;; 0.8.1: 2010/03/09 - backtracking irregex-match fix and other small fixes ;; 0.8.0: 2010/01/20 - optimizing DFA compilation, adding SRE escapes ;; inside PCREs, adding utility SREs ;; 0.7.5: 2009/08/31 - adding irregex-extract and irregex-split ;; *-fold copies match data (use *-fold/fast for speed) ;; irregex-opt now returns an SRE ;; 0.7.4: 2009/05/14 - empty alternates (or) and empty csets always fail, ;; bugfix in default finalizer for irregex-fold/chunked ;; 0.7.3: 2009/04/14 - adding irregex-fold/chunked, minor doc fixes ;; 0.7.2: 2009/02/11 - some bugfixes, much improved documentation ;; 0.7.1: 2008/10/30 - several bugfixes (thanks to Derick Eddington) ;; 0.7.0: 2008/10/20 - support abstract chunked strings ;; 0.6.2: 2008/07/26 - minor bugfixes, allow global disabling of utf8 mode, ;; friendlier error messages in parsing, \Q..\E support ;; 0.6.1: 2008/07/21 - added utf8 mode, more utils, bugfixes ;; 0.6: 2008/05/01 - most of PCRE supported ;; 0.5: 2008/04/24 - fully portable R4RS, many PCRE features implemented ;; 0.4: 2008/04/17 - rewriting NFA to use efficient closure compilation, ;; normal strings only, but all of the spencer tests pass ;; 0.3: 2008/03/10 - adding DFA converter (normal strings only) ;; 0.2: 2005/09/27 - adding irregex-opt (like elisp's regexp-opt) utility ;; 0.1: 2005/08/18 - simple NFA interpreter over abstract chunked strings ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Data Structures (define irregex-tag '*irregex-tag*) (define (make-irregex dfa dfa/search nfa flags submatches lengths names) (vector irregex-tag dfa dfa/search nfa flags submatches lengths names)) (define (irregex? obj) (and (vector? obj) (= 8 (vector-length obj)) (eq? irregex-tag (vector-ref obj 0)))) (define (irregex-dfa x) (vector-ref x 1)) (define (irregex-dfa/search x) (vector-ref x 2)) (define (irregex-nfa x) (vector-ref x 3)) (define (irregex-flags x) (vector-ref x 4)) (define (irregex-num-submatches x) (vector-ref x 5)) (define (irregex-lengths x) (vector-ref x 6)) (define (irregex-names x) (vector-ref x 7)) (define (vector-copy v) (let ((r (make-vector (vector-length v)))) (do ((i (- (vector-length v) 1) (- i 1))) ((< i 0) r) (vector-set! r i (vector-ref v i))))) (define (irregex-new-matches irx) (make-irregex-match (irregex-num-submatches irx) (irregex-names irx))) (define (irregex-reset-matches! m) (do ((i (- (vector-length m) 1) (- i 1))) ((<= i 3) m) (vector-set! m i #f))) (define (irregex-copy-matches m) (and (vector? m) (vector-copy m))) (define irregex-match-tag '*irregex-match-tag*) (define (irregex-match-data? obj) (and (vector? obj) (>= (vector-length obj) 11) (eq? irregex-match-tag (vector-ref obj 0)))) (define (make-irregex-match count names) (let ((res (make-vector (+ (* 4 (+ 2 count)) 3) #f))) (vector-set! res 0 irregex-match-tag) (vector-set! res 2 names) res)) (define (irregex-match-num-submatches m) (- (quotient (- (vector-length m) 3) 4) 2)) (define (irregex-match-chunker m) (vector-ref m 1)) (define (irregex-match-names m) (vector-ref m 2)) (define (irregex-match-chunker-set! m str) (vector-set! m 1 str)) (define (%irregex-match-start-chunk m n) (vector-ref m (+ 3 (* n 4)))) (define (%irregex-match-start-index m n) (vector-ref m (+ 4 (* n 4)))) (define (%irregex-match-end-chunk m n) (vector-ref m (+ 5 (* n 4)))) (define (%irregex-match-end-index m n) (vector-ref m (+ 6 (* n 4)))) (define (%irregex-match-fail m) (vector-ref m (- (vector-length m) 1))) (define (%irregex-match-fail-set! m x) (vector-set! m (- (vector-length m) 1) x)) ;; public interface with error checking (define (irregex-match-start-chunk m . opt) (let ((n (irregex-match-numeric-index "irregex-match-start-chunk" m opt))) (and n (%irregex-match-start-chunk m n)))) (define (irregex-match-start-index m . opt) (let ((n (irregex-match-numeric-index "irregex-match-start-index" m opt))) (and n (%irregex-match-start-index m n)))) (define (irregex-match-end-chunk m . opt) (let ((n (irregex-match-numeric-index "irregex-match-end-chunk" m opt))) (and n (%irregex-match-end-chunk m n)))) (define (irregex-match-end-index m . opt) (let ((n (irregex-match-numeric-index "irregex-match-end-index" m opt))) (and n (%irregex-match-end-index m n)))) (define (irregex-match-start-chunk-set! m n start) (vector-set! m (+ 3 (* n 4)) start)) (define (irregex-match-start-index-set! m n start) (vector-set! m (+ 4 (* n 4)) start)) (define (irregex-match-end-chunk-set! m n end) (vector-set! m (+ 5 (* n 4)) end)) (define (irregex-match-end-index-set! m n end) (vector-set! m (+ 6 (* n 4)) end)) ;; Tags use indices that are aligned to start/end positions just like the ;; match vectors. ie, a tag 0 is a start tag, 1 is its corresponding end tag. ;; They start at 0, which requires us to map them to submatch index 1. ;; Sorry for the horrible name ;) (define (irregex-match-chunk&index-from-tag-set! m t chunk index) (vector-set! m (+ 7 (* t 2)) chunk) (vector-set! m (+ 8 (* t 2)) index)) ;; Helper procedure to convert any type of index from a rest args list ;; to a numeric index. Named submatches are converted to their corresponding ;; numeric index, and numeric submatches are checked for validity. ;; An error is raised for invalid numeric or named indices, #f is returned ;; for defined but nonmatching indices. (define (irregex-match-numeric-index location m opt) (cond ((not (irregex-match-data? m)) (error (string-append location ": not match data") m)) ((not (pair? opt)) 0) ((pair? (cdr opt)) (apply error (string-append location ": too many arguments") m opt)) (else (let ((n (car opt))) (if (number? n) (if (and (integer? n) (exact? n)) (if (irregex-match-valid-numeric-index? m n) (and (irregex-match-matched-numeric-index? m n) n) (error (string-append location ": not a valid index") m n)) (error (string-append location ": not an exact integer") n)) (let lp ((ls (irregex-match-names m)) (unknown? #t)) (cond ((null? ls) (and unknown? (error (string-append location ": unknown match name") n))) ((eq? n (caar ls)) (if (%irregex-match-start-chunk m (cdar ls)) (cdar ls) (lp (cdr ls) #f))) (else (lp (cdr ls) unknown?))))))))) (define (irregex-match-valid-numeric-index? m n) (and (>= n 0) (< (+ 3 (* n 4)) (- (vector-length m) 4)))) (define (irregex-match-matched-numeric-index? m n) (and (vector-ref m (+ 4 (* n 4))) #t)) (define (irregex-match-valid-named-index? m n) (and (assq n (irregex-match-names m)) #t)) (define (irregex-match-valid-index? m n) (if (not (irregex-match-data? m)) (error "irregex-match-valid-index?: not match data" m)) (if (integer? n) (if (not (exact? n)) (error "irregex-match-valid-index?: not an exact integer" n) (irregex-match-valid-numeric-index? m n)) (irregex-match-valid-named-index? m n))) (define (irregex-match-substring m . opt) (let* ((n (irregex-match-numeric-index "irregex-match-substring" m opt)) (cnk (irregex-match-chunker m))) (and n ((chunker-get-substring cnk) (%irregex-match-start-chunk m n) (%irregex-match-start-index m n) (%irregex-match-end-chunk m n) (%irregex-match-end-index m n))))) (define (irregex-match-subchunk m . opt) (let* ((n (irregex-match-numeric-index "irregex-match-subchunk" m opt)) (cnk (irregex-match-chunker m)) (get-subchunk (chunker-get-subchunk cnk))) (if (not get-subchunk) (error "this chunk type does not support match subchunks") (and n (get-subchunk (%irregex-match-start-chunk m n) (%irregex-match-start-index m n) (%irregex-match-end-chunk m n) (%irregex-match-end-index m n)))))) ;; chunkers tell us how to navigate through chained chunks of strings (define (make-irregex-chunker get-next get-str . o) (let* ((get-start (or (and (pair? o) (car o)) (lambda (cnk) 0))) (o (if (pair? o) (cdr o) o)) (get-end (or (and (pair? o) (car o)) (lambda (cnk) (string-length (get-str cnk))))) (o (if (pair? o) (cdr o) o)) (get-substr (or (and (pair? o) (car o)) (lambda (cnk1 start cnk2 end) (if (eq? cnk1 cnk2) (substring (get-str cnk1) start end) (let loop ((cnk (get-next cnk1)) (res (list (substring (get-str cnk1) start (get-end cnk1))))) (if (eq? cnk cnk2) (string-cat-reverse (cons (substring (get-str cnk) (get-start cnk) end) res)) (loop (get-next cnk) (cons (substring (get-str cnk) (get-start cnk) (get-end cnk)) res)))))))) (o (if (pair? o) (cdr o) o)) (get-subchunk (and (pair? o) (car o)))) (if (not (and (procedure? get-next) (procedure? get-str) (procedure? get-start) (procedure? get-substr))) (error "make-irregex-chunker: expected a procdure")) (vector get-next get-str get-start get-end get-substr get-subchunk))) (define (chunker-get-next cnk) (vector-ref cnk 0)) (define (chunker-get-str cnk) (vector-ref cnk 1)) (define (chunker-get-start cnk) (vector-ref cnk 2)) (define (chunker-get-end cnk) (vector-ref cnk 3)) (define (chunker-get-substring cnk) (vector-ref cnk 4)) (define (chunker-get-subchunk cnk) (vector-ref cnk 5)) (define (chunker-prev-chunk cnk start end) (if (eq? start end) #f (let ((get-next (chunker-get-next cnk))) (let lp ((start start)) (let ((next (get-next start))) (if (eq? next end) start (and next (lp next)))))))) (define (chunker-prev-char cnk start end) (let ((prev (chunker-prev-chunk cnk start end))) (and prev (string-ref ((chunker-get-str cnk) prev) (- ((chunker-get-end cnk) prev) 1))))) (define (chunker-next-char cnk src) (let ((next ((chunker-get-next cnk) src))) (and next (string-ref ((chunker-get-str cnk) next) ((chunker-get-start cnk) next))))) (define (chunk-before? cnk a b) (and (not (eq? a b)) (let ((next ((chunker-get-next cnk) a))) (and next (if (eq? next b) #t (chunk-before? cnk next b)))))) ;; For look-behind searches, wrap an existing chunker such that it ;; returns the same results but ends at a given point. (define (wrap-end-chunker cnk src i) (make-irregex-chunker (lambda (x) (and (not (eq? x src)) ((chunker-get-next cnk) x))) (chunker-get-str cnk) (chunker-get-start cnk) (lambda (x) (if (eq? x src) i ((chunker-get-end cnk) x))) (chunker-get-substring cnk) (chunker-get-subchunk cnk))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; String Utilities ;; Unicode version (skip surrogates) (define *all-chars* `(/ ,(integer->char 0) ,(integer->char #xD7FF) ,(integer->char #xE000) ,(integer->char #x10FFFF))) ;; ASCII version, offset to not assume 0-255 ;; (define *all-chars* `(/ ,(integer->char (- (char->integer #\space) 32)) ,(integer->char (+ (char->integer #\space) 223)))) ;; set to #f to ignore even an explicit request for utf8 handling (define *allow-utf8-mode?* #t) ;; (define *named-char-properties* '()) (define (string-scan-char str c . o) (let ((end (string-length str))) (let scan ((i (if (pair? o) (car o) 0))) (cond ((= i end) #f) ((eqv? c (string-ref str i)) i) (else (scan (+ i 1))))))) (define (string-scan-char-escape str c . o) (let ((end (string-length str))) (let scan ((i (if (pair? o) (car o) 0))) (cond ((= i end) #f) ((eqv? c (string-ref str i)) i) ((eqv? c #\\) (scan (+ i 2))) (else (scan (+ i 1))))))) (define (string-scan-pred str pred . o) (let ((end (string-length str))) (let scan ((i (if (pair? o) (car o) 0))) (cond ((= i end) #f) ((pred (string-ref str i)) i) (else (scan (+ i 1))))))) (define (string-split-char str c) (let ((end (string-length str))) (let lp ((i 0) (from 0) (res '())) (define (collect) (cons (substring str from i) res)) (cond ((>= i end) (reverse (collect))) ((eqv? c (string-ref str i)) (lp (+ i 1) (+ i 1) (collect))) (else (lp (+ i 1) from res)))))) (define (char-alphanumeric? c) (or (char-alphabetic? c) (char-numeric? c))) (define (%substring=? a b start1 start2 len) (let lp ((i 0)) (cond ((>= i len) #t) ((char=? (string-ref a (+ start1 i)) (string-ref b (+ start2 i))) (lp (+ i 1))) (else #f)))) ;; SRFI-13 extracts (define (%%string-copy! to tstart from fstart fend) (do ((i fstart (+ i 1)) (j tstart (+ j 1))) ((>= i fend)) (string-set! to j (string-ref from i)))) (define (string-cat-reverse string-list) (string-cat-reverse/aux (fold (lambda (s a) (+ (string-length s) a)) 0 string-list) string-list)) (define (string-cat-reverse/aux len string-list) (let ((res (make-string len))) (let lp ((i len) (ls string-list)) (if (pair? ls) (let* ((s (car ls)) (slen (string-length s)) (i (- i slen))) (%%string-copy! res i s 0 slen) (lp i (cdr ls))))) res)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; List Utilities ;; like the one-arg IOTA case (define (zero-to n) (if (<= n 0) '() (let lp ((i (- n 1)) (res '())) (if (zero? i) (cons 0 res) (lp (- i 1) (cons i res)))))) ;; SRFI-1 extracts (simplified 1-ary versions) (define (find pred ls) (cond ((find-tail pred ls) => car) (else #f))) (define (find-tail pred ls) (let lp ((ls ls)) (cond ((null? ls) #f) ((pred (car ls)) ls) (else (lp (cdr ls)))))) (define (last ls) (if (not (pair? ls)) (error "can't take last of empty list" ls) (let lp ((ls ls)) (if (pair? (cdr ls)) (lp (cdr ls)) (car ls))))) (define (any pred ls) (and (pair? ls) (let lp ((head (car ls)) (tail (cdr ls))) (if (null? tail) (pred head) (or (pred head) (lp (car tail) (cdr tail))))))) (define (every pred ls) (or (null? ls) (let lp ((head (car ls)) (tail (cdr ls))) (if (null? tail) (pred head) (and (pred head) (lp (car tail) (cdr tail))))))) (define (fold kons knil ls) (let lp ((ls ls) (res knil)) (if (null? ls) res (lp (cdr ls) (kons (car ls) res))))) (define (filter pred ls) (let lp ((ls ls) (res '())) (if (null? ls) (reverse res) (lp (cdr ls) (if (pred (car ls)) (cons (car ls) res) res))))) (define (remove pred ls) (let lp ((ls ls) (res '())) (if (null? ls) (reverse res) (lp (cdr ls) (if (pred (car ls)) res (cons (car ls) res)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Flags (define (bit-shr n i) (quotient n (expt 2 i))) (define (bit-shl n i) (* n (expt 2 i))) (define (bit-not n) (- #xFFFF n)) (define (bit-ior a b) (cond ((zero? a) b) ((zero? b) a) (else (+ (if (or (odd? a) (odd? b)) 1 0) (* 2 (bit-ior (quotient a 2) (quotient b 2))))))) (define (bit-and a b) (cond ((zero? a) 0) ((zero? b) 0) (else (+ (if (and (odd? a) (odd? b)) 1 0) (* 2 (bit-and (quotient a 2) (quotient b 2))))))) (define (integer-log n) (define (b8 n r) (if (>= n (bit-shl 1 8)) (b4 (bit-shr n 8) (+ r 8)) (b4 n r))) (define (b4 n r) (if (>= n (bit-shl 1 4)) (b2 (bit-shr n 4) (+ r 4)) (b2 n r))) (define (b2 n r) (if (>= n (bit-shl 1 2)) (b1 (bit-shr n 2) (+ r 2)) (b1 n r))) (define (b1 n r) (if (>= n (bit-shl 1 1)) (+ r 1) r)) (if (>= n (bit-shl 1 16)) (b8 (bit-shr n 16) 16) (b8 n 0))) (define (flag-set? flags i) (= i (bit-and flags i))) (define (flag-join a b) (if b (bit-ior a b) a)) (define (flag-clear a b) (bit-and a (bit-not b))) (define ~none 0) (define ~searcher? 1) (define ~consumer? 2) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Parsing Embedded SREs in PCRE Strings ;; (define (with-read-from-string str i proc) ;; (define (port-size in) ;; (let lp ((i 0)) (if (eof-object? (read-char in)) i (lp (+ i 1))))) ;; (let* ((len (string-length str)) ;; (tail-len (- len i)) ;; (in (open-input-string (substring str i len))) ;; (sre (read in)) ;; (unused-len (port-size in))) ;; (close-input-port in) ;; (proc sre (- tail-len unused-len)))) (define close-token (list 'close)) (define dot-token (string->symbol ".")) (define (with-read-from-string str i proc) (define end (string-length str)) (define (read i k) (cond ((>= i end) (error "unterminated embedded SRE" str)) (else (case (string-ref str i) ((#\() (let lp ((i (+ i 1)) (ls '())) (read i (lambda (x j) (cond ((eq? x close-token) (k (reverse ls) j)) ((eq? x dot-token) (if (null? ls) (error "bad dotted form" str) (read j (lambda (y j2) (read j2 (lambda (z j3) (if (not (eq? z close-token)) (error "bad dotted form" str) (k (append (reverse (cdr ls)) (cons (car ls) y)) j3)))))))) (else (lp j (cons x ls)))))))) ((#\)) (k close-token (+ i 1))) ((#\;) (let skip ((i (+ i 1))) (if (or (>= i end) (eqv? #\newline (string-ref str i))) (read (+ i 1) k) (skip (+ i 1))))) ((#\' #\`) (read (+ i 1) (lambda (sexp j) (let ((q (if (eqv? #\' (string-ref str i)) 'quote 'quasiquote))) (k (list q sexp) j))))) ((#\,) (let* ((at? (and (< (+ i 1) end) (eqv? #\@ (string-ref str (+ i 1))))) (u (if at? 'uquote-splicing 'unquote)) (j (if at? (+ i 2) (+ i 1)))) (read j (lambda (sexp j) (k (list u sexp) j))))) ((#\") (let scan ((from (+ i 1)) (i (+ i 1)) (res '())) (define (collect) (if (= from i) res (cons (substring str from i) res))) (if (>= i end) (error "unterminated string in embeded SRE" str) (case (string-ref str i) ((#\") (k (string-cat-reverse (collect)) (+ i 1))) ((#\\) (scan (+ i 1) (+ i 2) (collect))) (else (scan from (+ i 1) res)))))) ((#\#) (case (string-ref str (+ i 1)) ((#\;) (read (+ i 2) (lambda (sexp j) (read j k)))) ((#\\) (read (+ i 2) (lambda (sexp j) (k (case sexp ((space) #\space) ((newline) #\newline) (else (let ((s (if (number? sexp) (number->string sexp) (symbol->string sexp)))) (string-ref s 0)))) j)))) ((#\t #\f) (k (eqv? #\t (string-ref str (+ i 1))) (+ i 2))) (else (error "bad # syntax in simplified SRE" i)))) (else (cond ((char-whitespace? (string-ref str i)) (read (+ i 1) k)) (else ;; symbol/number (let scan ((j (+ i 1))) (cond ((or (>= j end) (let ((c (string-ref str j))) (or (char-whitespace? c) (memv c '(#\; #\( #\) #\" #\# #\\))))) (let ((str2 (substring str i j))) (k (or (string->number str2) (string->symbol str2)) j))) (else (scan (+ j 1)))))))))))) (read i (lambda (res j) (if (eq? res 'close-token) (error "unexpected ')' in SRE" str j) (proc res j))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Parsing PCRE Strings (define ~save? 1) (define ~case-insensitive? 2) (define ~multi-line? 4) (define ~single-line? 8) (define ~ignore-space? 16) (define ~utf8? 32) (define (symbol-list->flags ls) (let lp ((ls ls) (res ~none)) (if (not (pair? ls)) res (lp (cdr ls) (flag-join res (case (car ls) ((i ci case-insensitive) ~case-insensitive?) ((m multi-line) ~multi-line?) ((s single-line) ~single-line?) ((x ignore-space) ~ignore-space?) ((u utf8) (if *allow-utf8-mode?* ~utf8? ~none)) (else #f))))))) (define (maybe-string->sre obj) (if (string? obj) (string->sre obj) obj)) (define (string->sre str . o) (if (not (string? str)) (error "string->sre: expected a string" str)) (let ((end (string-length str)) (flags (symbol-list->flags o))) (let lp ((i 0) (from 0) (flags flags) (res '()) (st '())) ;; handle case sensitivity at the literal char/string level (define (cased-char ch) (if (and (flag-set? flags ~case-insensitive?) (char-alphabetic? ch)) `(or ,ch ,(char-altcase ch)) ch)) (define (cased-string str) (if (flag-set? flags ~case-insensitive?) (sre-sequence (map cased-char (string->list str))) str)) ;; accumulate the substring from..i as literal text (define (collect) (if (= i from) res (cons (cased-string (substring str from i)) res))) ;; like collect but breaks off the last single character when ;; collecting literal data, as the argument to ?/*/+ etc. (define (collect/single) (let* ((utf8? (flag-set? flags ~utf8?)) (j (if (and utf8? (> i 1)) (utf8-backup-to-initial-char str (- i 1)) (- i 1)))) (cond ((< j from) res) (else (let ((c (cased-char (if utf8? (utf8-string-ref str j (- i j)) (string-ref str j))))) (cond ((= j from) (cons c res)) (else (cons c (cons (cased-string (substring str from j)) res))))))))) ;; collects for use as a result, reversing and grouping OR ;; terms, and some ugly tweaking of `function-like' groups and ;; conditionals (define (collect/terms) (let* ((ls (collect)) (func (and (pair? ls) (memq (last ls) '(atomic if look-ahead neg-look-ahead look-behind neg-look-behind => submatch-named w/utf8 w/noutf8)))) (prefix (if (and func (memq (car func) '(=> submatch-named))) (list 'submatch-named (cadr (reverse ls))) (and func (list (car func))))) (ls (if func (if (memq (car func) '(=> submatch-named)) (reverse (cddr (reverse ls))) (reverse (cdr (reverse ls)))) ls))) (let lp ((ls ls) (term '()) (res '())) (define (shift) (cons (sre-sequence term) res)) (cond ((null? ls) (let* ((res (sre-alternate (shift))) (res (if (flag-set? flags ~save?) (list 'submatch res) res))) (if prefix (if (eq? 'if (car prefix)) (cond ((not (pair? res)) 'epsilon) ((memq (car res) '(look-ahead neg-look-ahead look-behind neg-look-behind)) res) ((eq? 'seq (car res)) `(if ,(cadr res) ,(sre-sequence (cddr res)))) (else `(if ,(cadadr res) ,(sre-sequence (cddadr res)) ,(sre-alternate (cddr res))))) `(,@prefix ,res)) res))) ((eq? 'or (car ls)) (lp (cdr ls) '() (shift))) (else (lp (cdr ls) (cons (car ls) term) res)))))) (define (save) (cons (cons flags (collect)) st)) ;; main parsing (if (>= i end) (if (pair? st) (error "unterminated parenthesis in regexp" str) (collect/terms)) (let ((c (string-ref str i))) (case c ((#\.) (lp (+ i 1) (+ i 1) flags (cons (if (flag-set? flags ~single-line?) 'any 'nonl) (collect)) st)) ((#\?) (let ((res (collect/single))) (if (null? res) (error "? can't follow empty pattern" str res) (let ((x (car res))) (lp (+ i 1) (+ i 1) flags (cons (if (pair? x) (case (car x) ((*) `(*? ,@(cdr x))) ((+) `(**? 1 #f ,@(cdr x))) ((?) `(?? ,@(cdr x))) ((**) `(**? ,@(cdr x))) ((=) `(**? ,(cadr x) ,@(cdr x))) ((>=) `(**? ,(cadr x) #f ,@(cddr x))) (else `(? ,x))) `(? ,x)) (cdr res)) st))))) ((#\+ #\*) (let* ((res (collect/single)) (x (if (pair? res) (car res) 'epsilon)) (op (string->symbol (string c)))) (cond ((sre-repeater? x) (error "duplicate repetition (e.g. **) in pattern" str res)) ((sre-empty? x) (error "can't repeat empty pattern (e.g. ()*)" str res)) (else (lp (+ i 1) (+ i 1) flags (cons (list op x) (cdr res)) st))))) ((#\() (cond ((>= (+ i 1) end) (error "unterminated parenthesis in regexp" str)) ((not (memv (string-ref str (+ i 1)) '(#\? #\*))) ; normal case (lp (+ i 1) (+ i 1) (flag-join flags ~save?) '() (save))) ((>= (+ i 2) end) (error "unterminated parenthesis in regexp" str)) ((eqv? (string-ref str (+ i 1)) #\*) (if (eqv? #\' (string-ref str (+ i 2))) (with-read-from-string str (+ i 3) (lambda (sre j) (if (or (>= j end) (not (eqv? #\) (string-ref str j)))) (error "unterminated (*'...) SRE escape" str) (lp (+ j 1) (+ j 1) flags (cons sre (collect)) st)))) (error "bad regexp syntax: (*FOO) not supported" str))) (else ;; (?...) case (case (string-ref str (+ i 2)) ((#\#) (let ((j (string-scan-char str #\) (+ i 3)))) (lp (+ j i) (+ j 1) flags (collect) st))) ((#\:) (lp (+ i 3) (+ i 3) (flag-clear flags ~save?) '() (save))) ((#\=) (lp (+ i 3) (+ i 3) (flag-clear flags ~save?) '(look-ahead) (save))) ((#\!) (lp (+ i 3) (+ i 3) (flag-clear flags ~save?) '(neg-look-ahead) (save))) ((#\<) (cond ((>= (+ i 3) end) (error "unterminated parenthesis in regexp" str)) (else (case (string-ref str (+ i 3)) ((#\=) (lp (+ i 4) (+ i 4) (flag-clear flags ~save?) '(look-behind) (save))) ((#\!) (lp (+ i 4) (+ i 4) (flag-clear flags ~save?) '(neg-look-behind) (save))) (else (let ((j (and (char-alphabetic? (string-ref str (+ i 3))) (string-scan-char str #\> (+ i 4))))) (if j (lp (+ j 1) (+ j 1) (flag-clear flags ~save?) `(,(string->symbol (substring str (+ i 3) j)) submatch-named) (save)) (error "invalid (?< sequence" str)))))))) ((#\>) (lp (+ i 3) (+ i 3) (flag-clear flags ~save?) '(atomic) (save))) ;;((#\' #\P) ; named subpatterns ;; ) ;;((#\R) ; recursion ;; ) ((#\() (cond ((>= (+ i 3) end) (error "unterminated parenthesis in regexp" str)) ((char-numeric? (string-ref str (+ i 3))) (let* ((j (string-scan-char str #\) (+ i 3))) (n (string->number (substring str (+ i 3) j)))) (if (not n) (error "invalid conditional reference" str) (lp (+ j 1) (+ j 1) (flag-clear flags ~save?) `(,n if) (save))))) ((char-alphabetic? (string-ref str (+ i 3))) (let* ((j (string-scan-char str #\) (+ i 3))) (s (string->symbol (substring str (+ i 3) j)))) (lp (+ j 1) (+ j 1) (flag-clear flags ~save?) `(,s if) (save)))) (else (lp (+ i 2) (+ i 2) (flag-clear flags ~save?) '(if) (save))))) ((#\{) (error "unsupported Perl-style cluster" str)) (else (let ((old-flags flags)) (let lp2 ((j (+ i 2)) (flags flags) (invert? #f)) (define (join x) ((if invert? flag-clear flag-join) flags x)) (define (new-res res) (let ((before (flag-set? old-flags ~utf8?)) (after (flag-set? flags ~utf8?))) (if (eq? before after) res (cons (if after 'w/utf8 'w/noutf8) res)))) (cond ((>= j end) (error "incomplete cluster" str i)) (else (case (string-ref str j) ((#\i) (lp2 (+ j 1) (join ~case-insensitive?) invert?)) ((#\m) (lp2 (+ j 1) (join ~multi-line?) invert?)) ((#\x) (lp2 (+ j 1) (join ~ignore-space?) invert?)) ((#\u) (if *allow-utf8-mode?* (lp2 (+ j 1) (join ~utf8?) invert?) (lp2 (+ j 1) flags invert?))) ((#\-) (lp2 (+ j 1) flags (not invert?))) ((#\)) (lp (+ j 1) (+ j 1) flags (new-res (collect)) st)) ((#\:) (lp (+ j 1) (+ j 1) flags (new-res '()) (cons (cons old-flags (collect)) st))) (else (error "unknown regex cluster modifier" str) ))))))))))) ((#\)) (if (null? st) (error "too many )'s in regexp" str) (lp (+ i 1) (+ i 1) (caar st) (cons (collect/terms) (cdar st)) (cdr st)))) ((#\[) (apply (lambda (sre j) (lp (+ j 1) (+ j 1) flags (cons sre (collect)) st)) (string-parse-cset str (+ i 1) flags))) ((#\{) (cond ((or (>= (+ i 1) end) (not (or (char-numeric? (string-ref str (+ i 1))) (eqv? #\, (string-ref str (+ i 1)))))) (lp (+ i 1) from flags res st)) (else (let ((res (collect/single))) (cond ((null? res) (error "{ can't follow empty pattern")) (else (let* ((x (car res)) (tail (cdr res)) (j (string-scan-char str #\} (+ i 1))) (s2 (string-split-char (substring str (+ i 1) j) #\,)) (n (string->number (car s2))) (m (and (pair? (cdr s2)) (string->number (cadr s2))))) (cond ((or (not n) (and (pair? (cdr s2)) (not (equal? "" (cadr s2))) (not m))) (error "invalid {n} repetition syntax" s2)) ((null? (cdr s2)) (lp (+ j 1) (+ j 1) flags `((= ,n ,x) ,@tail) st)) (m (lp (+ j 1) (+ j 1) flags `((** ,n ,m ,x) ,@tail) st)) (else (lp (+ j 1) (+ j 1) flags `((>= ,n ,x) ,@tail) st) ))))))))) ((#\\) (cond ((>= (+ i 1) end) (error "incomplete escape sequence" str)) (else (let ((c (string-ref str (+ i 1)))) (case c ((#\d) (lp (+ i 2) (+ i 2) flags `(numeric ,@(collect)) st)) ((#\D) (lp (+ i 2) (+ i 2) flags `((~ numeric) ,@(collect)) st)) ((#\s) (lp (+ i 2) (+ i 2) flags `(space ,@(collect)) st)) ((#\S) (lp (+ i 2) (+ i 2) flags `((~ space) ,@(collect)) st)) ((#\w) (lp (+ i 2) (+ i 2) flags `((or alphanumeric ("_")) ,@(collect)) st)) ((#\W) (lp (+ i 2) (+ i 2) flags `((~ (or alphanumeric ("_"))) ,@(collect)) st)) ((#\b) (lp (+ i 2) (+ i 2) flags `((or bow eow) ,@(collect)) st)) ((#\B) (lp (+ i 2) (+ i 2) flags `(nwb ,@(collect)) st)) ((#\A) (lp (+ i 2) (+ i 2) flags `(bos ,@(collect)) st)) ((#\Z) (lp (+ i 2) (+ i 2) flags `((? #\newline) eos ,@(collect)) st)) ((#\z) (lp (+ i 2) (+ i 2) flags `(eos ,@(collect)) st)) ((#\R) (lp (+ i 2) (+ i 2) flags `(newline ,@(collect)) st)) ((#\K) (lp (+ i 2) (+ i 2) flags `(reset ,@(collect)) st)) ;; these two are from Emacs and TRE, but not in PCRE ((#\<) (lp (+ i 2) (+ i 2) flags `(bow ,@(collect)) st)) ((#\>) (lp (+ i 2) (+ i 2) flags `(eow ,@(collect)) st)) ((#\x) (apply (lambda (ch j) (lp (+ j 1) (+ j 1) flags `(,ch ,@(collect)) st)) (string-parse-hex-escape str (+ i 2) end))) ((#\k) (let ((c (string-ref str (+ i 2)))) (if (not (memv c '(#\< #\{ #\'))) (error "bad \\k usage, expected \\k<...>" str) (let* ((terminal (char-mirror c)) (j (string-scan-char str terminal (+ i 2))) (s (and j (substring str (+ i 3) j))) (backref (if (flag-set? flags ~case-insensitive?) 'backref-ci 'backref))) (if (not j) (error "unterminated named backref" str) (lp (+ j 1) (+ j 1) flags `((,backref ,(string->symbol s)) ,@(collect)) st)))))) ((#\Q) ;; \Q..\E escapes (let ((res (collect))) (let lp2 ((j (+ i 2))) (cond ((>= j end) (lp j (+ i 2) flags res st)) ((eqv? #\\ (string-ref str j)) (cond ((>= (+ j 1) end) (lp (+ j 1) (+ i 2) flags res st)) ((eqv? #\E (string-ref str (+ j 1))) (lp (+ j 2) (+ j 2) flags (cons (substring str (+ i 2) j) res) st)) (else (lp2 (+ j 2))))) (else (lp2 (+ j 1))))))) ((#\') (with-read-from-string str (+ i 2) (lambda (sre j) (lp j j flags (cons sre (collect)) st)))) ;;((#\p) ; XXXX unicode properties ;; ) ;;((#\P) ;; ) (else (cond ((char-numeric? c) (let* ((j (or (string-scan-pred str (lambda (c) (not (char-numeric? c))) (+ i 2)) end)) (backref (if (flag-set? flags ~case-insensitive?) 'backref-ci 'backref)) (res `((,backref ,(string->number (substring str (+ i 1) j))) ,@(collect)))) (lp j j flags res st))) ((char-alphabetic? c) (let ((cell (assv c posix-escape-sequences))) (if cell (lp (+ i 2) (+ i 2) flags (cons (cdr cell) (collect)) st) (error "unknown escape sequence" str c)))) (else (lp (+ i 2) (+ i 1) flags (collect) st))))))))) ((#\|) (lp (+ i 1) (+ i 1) flags (cons 'or (collect)) st)) ((#\^) (let ((sym (if (flag-set? flags ~multi-line?) 'bol 'bos))) (lp (+ i 1) (+ i 1) flags (cons sym (collect)) st))) ((#\$) (let ((sym (if (flag-set? flags ~multi-line?) 'eol 'eos))) (lp (+ i 1) (+ i 1) flags (cons sym (collect)) st))) ((#\space) (if (flag-set? flags ~ignore-space?) (lp (+ i 1) (+ i 1) flags (collect) st) (lp (+ i 1) from flags res st))) ((#\#) (if (flag-set? flags ~ignore-space?) (let ((j (or (string-scan-char str #\newline (+ i 1)) (- end 1)))) (lp (+ j 1) (+ j 1) flags (collect) st)) (lp (+ i 1) from flags res st))) (else (lp (+ i 1) from flags res st)))))))) (define posix-escape-sequences `((#\n . #\newline) (#\r . ,(integer->char (+ (char->integer #\newline) 3))) (#\t . ,(integer->char (- (char->integer #\newline) 1))) (#\a . ,(integer->char (- (char->integer #\newline) 3))) (#\e . ,(integer->char (+ (char->integer #\newline) #x11))) (#\f . ,(integer->char (+ (char->integer #\newline) 2))) )) (define (char-altcase c) (if (char-upper-case? c) (char-downcase c) (char-upcase c))) (define (char-mirror c) (case c ((#\<) #\>) ((#\{) #\}) ((#\() #\)) ((#\[) #\]) (else c))) (define (string-parse-hex-escape str i end) (cond ((>= i end) (error "incomplete hex escape" str i)) ((eqv? #\{ (string-ref str i)) (let ((j (string-scan-char-escape str #\} (+ i 1)))) (if (not j) (error "incomplete hex brace escape" str i) (let* ((s (substring str (+ i 1) j)) (n (string->number s 16))) (if n (list (integer->char n) j) (error "bad hex brace escape" s)))))) ((>= (+ i 1) end) (error "incomplete hex escape" str i)) (else (let* ((s (substring str i (+ i 2))) (n (string->number s 16))) (if n (list (integer->char n) (+ i 2)) (error "bad hex escape" s)))))) (define (string-parse-cset str start flags) (let* ((end (string-length str)) (invert? (and (< start end) (eqv? #\^ (string-ref str start)))) (utf8? (flag-set? flags ~utf8?))) (define (go i prev-char cset) (if (>= i end) (error "incomplete char set" str i end) (let ((c (string-ref str i))) (case c ((#\]) (if (cset-empty? cset) (go (+ i 1) #\] (cset-adjoin cset #\])) (let ((ci? (flag-set? flags ~case-insensitive?))) (list (let ((res (if ci? (cset-case-insensitive cset) cset))) (cset->sre (if invert? (cset-complement res) res))) i)))) ((#\-) (cond ((or (= i start) (and (= i (+ start 1)) (eqv? #\^ (string-ref str start))) (eqv? #\] (string-ref str (+ i 1)))) (go (+ i 1) c (cset-adjoin cset c))) ((not prev-char) (error "bad char-set")) (else (let ((char (string-ref str (+ i 1)))) (apply (lambda (c j) (if (char<? c prev-char) (error "inverted range in char-set" prev-char c) (go j #f (cset-union cset (range->cset prev-char c))))) (cond ((and (eqv? #\\ char) (assv char posix-escape-sequences)) => (lambda (x) (list (cdr x) (+ i 3)))) ((and (eqv? #\\ char) (eqv? (string-ref str (+ i 2)) #\x)) (string-parse-hex-escape str (+ i 3) end)) ((and utf8? (<= #x80 (char->integer char) #xFF)) (let ((len (utf8-start-char->length char))) (list (utf8-string-ref str (+ i 1) len) (+ i 1 len)))) (else (list char (+ i 2))))))))) ((#\[) (let* ((inv? (eqv? #\^ (string-ref str (+ i 1)))) (i2 (if inv? (+ i 2) (+ i 1)))) (case (string-ref str i2) ((#\:) (let ((j (string-scan-char str #\: (+ i2 1)))) (if (or (not j) (not (eqv? #\] (string-ref str (+ j 1))))) (error "incomplete character class" str) (let* ((class (sre->cset (string->symbol (substring str (+ i2 1) j)))) (class (if inv? (cset-complement class) class))) (go (+ j 2) #f (cset-union cset class)))))) ((#\= #\.) (error "collating sequences not supported" str)) (else (go (+ i 1) #\[ (cset-adjoin cset #\[)))))) ((#\\) (let ((c (string-ref str (+ i 1)))) (case c ((#\d #\D #\s #\S #\w #\W) (go (+ i 2) #f (cset-union cset (sre->cset (string->sre (string #\\ c)))))) ((#\x) (apply (lambda (ch j) (go j ch (cset-adjoin cset ch))) (string-parse-hex-escape str (+ i 2) end))) (else (let ((c (cond ((assv c posix-escape-sequences) => cdr) (else c)))) (go (+ i 2) c (cset-adjoin cset c))))))) (else (if (and utf8? (<= #x80 (char->integer c) #xFF)) (let ((len (utf8-start-char->length c))) (go (+ i len) (utf8-string-ref str i len) (cset-adjoin cset (utf8-string-ref str i len)))) (go (+ i 1) c (cset-adjoin cset c)))))))) (if invert? (go (+ start 1) #f (if (flag-set? flags ~multi-line?) (char->cset #\newline) (make-cset))) (go start #f (make-cset))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; UTF-8 Utilities ;; Here are some hairy optimizations that need to be documented ;; better. Thanks to these, we never do any utf8 processing once the ;; regexp is compiled. ;; two chars: ab..ef ;; a[b..xFF]|[b-d][x80..xFF]|e[x80..xFF] ;; three chars: abc..ghi ;; ab[c..xFF]|a[d..xFF][x80..xFF]| ;; [b..f][x80..xFF][x80..xFF]| ;; g[x80..g][x80..xFF]|gh[x80..i] ;; four chars: abcd..ghij ;; abc[d..xFF]|ab[d..xFF][x80..xFF]|a[c..xFF][x80..xFF][x80..xFF]| ;; [b..f][x80..xFF][x80..xFF][x80..xFF]| ;; g[x80..g][x80..xFF][x80..xFF]|gh[x80..h][x80..xFF]|ghi[x80..j] (define (high-char? c) (<= #x80 (char->integer c))) ;; number of total bytes in a utf8 char given the 1st byte (define utf8-start-char->length (let ((table '#( 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 0x 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 1x 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 2x 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 3x 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 4x 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 5x 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 6x 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 7x 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 8x 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 9x 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; ax 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; bx 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ; cx 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ; dx 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 ; ex 4 4 4 4 4 4 4 4 5 5 5 5 6 6 0 0 ; fx ))) (lambda (c) (vector-ref table (char->integer c))))) (define (utf8-string-ref str i len) (define (byte n) (char->integer (string-ref str n))) (case len ((1) ; shouldn't happen in this module (string-ref str i)) ((2) (integer->char (+ (bit-shl (bit-and (byte i) #b00011111) 6) (bit-and (byte (+ i 1)) #b00111111)))) ((3) (integer->char (+ (bit-shl (bit-and (byte i) #b00001111) 12) (bit-shl (bit-and (byte (+ i 1)) #b00111111) 6) (bit-and (byte (+ i 2)) #b00111111)))) ((4) (integer->char (+ (bit-shl (bit-and (byte i) #b00000111) 18) (bit-shl (bit-and (byte (+ i 1)) #b00111111) 12) (bit-shl (bit-and (byte (+ i 2)) #b00111111) 6) (bit-and (byte (+ i 3)) #b00111111)))) (else (error "invalid utf8 length" str len i)))) (define (utf8-backup-to-initial-char str i) (let lp ((i i)) (if (= i 0) 0 (let ((c (char->integer (string-ref str i)))) (if (or (< c #x80) (>= c #xC0)) i (lp (- i 1))))))) (define (utf8-lowest-digit-of-length len) (case len ((1) 0) ((2) #xC0) ((3) #xE0) ((4) #xF0) (else (error "invalid utf8 length" len)))) (define (utf8-highest-digit-of-length len) (case len ((1) #x7F) ((2) #xDF) ((3) #xEF) ((4) #xF7) (else (error "invalid utf8 length" len)))) (define (char->utf8-list c) (let ((i (char->integer c))) (cond ((<= i #x7F) (list i)) ((<= i #x7FF) (list (bit-ior #b11000000 (bit-shr i 6)) (bit-ior #b10000000 (bit-and i #b111111)))) ((<= i #xFFFF) (list (bit-ior #b11100000 (bit-shr i 12)) (bit-ior #b10000000 (bit-and (bit-shr i 6) #b111111)) (bit-ior #b10000000 (bit-and i #b111111)))) ((<= i #x1FFFFF) (list (bit-ior #b11110000 (bit-shr i 18)) (bit-ior #b10000000 (bit-and (bit-shr i 12) #b111111)) (bit-ior #b10000000 (bit-and (bit-shr i 6) #b111111)) (bit-ior #b10000000 (bit-and i #b111111)))) (else (error "unicode codepoint out of range:" i))))) (define (unicode-range->utf8-pattern lo hi) (let ((lo-ls (char->utf8-list lo)) (hi-ls (char->utf8-list hi))) (if (not (= (length lo-ls) (length hi-ls))) (sre-alternate (list (unicode-range-climb-digits lo-ls hi-ls) (unicode-range-up-to hi-ls))) (let lp ((lo-ls lo-ls) (hi-ls hi-ls)) (cond ((null? lo-ls) '()) ((= (car lo-ls) (car hi-ls)) (sre-sequence (list (integer->char (car lo-ls)) (lp (cdr lo-ls) (cdr hi-ls))))) ((= (+ (car lo-ls) 1) (car hi-ls)) (sre-alternate (list (unicode-range-up-from lo-ls) (unicode-range-up-to hi-ls)))) (else (sre-alternate (list (unicode-range-up-from lo-ls) (unicode-range-middle lo-ls hi-ls) (unicode-range-up-to hi-ls))))))))) (define (unicode-range-helper one ls prefix res) (if (null? ls) res (unicode-range-helper one (cdr ls) (cons (car ls) prefix) (cons (sre-sequence `(,@(map integer->char prefix) ,(one (car ls)) ,@(map (lambda (_) `(/ ,(integer->char #x80) ,(integer->char #xFF))) (cdr ls)))) res)))) (define (unicode-range-up-from lo-ls) (sre-sequence (list (integer->char (car lo-ls)) (sre-alternate (unicode-range-helper (lambda (c) `(/ ,(integer->char (+ (car lo-ls) 1)) ,(integer->char #xFF))) (cdr (reverse (cdr lo-ls))) '() (list (sre-sequence (append (map integer->char (reverse (cdr (reverse (cdr lo-ls))))) `((/ ,(integer->char (last lo-ls)) ,(integer->char #xFF))))))))))) (define (unicode-range-up-to hi-ls) (sre-sequence (list (integer->char (car hi-ls)) (sre-alternate (unicode-range-helper (lambda (c) `(/ ,(integer->char #x80) ,(integer->char (- (car hi-ls) 1)))) (cdr (reverse (cdr hi-ls))) '() (list (sre-sequence (append (map integer->char (reverse (cdr (reverse (cdr hi-ls))))) `((/ ,(integer->char #x80) ,(integer->char (last hi-ls)))))))))))) (define (unicode-range-climb-digits lo-ls hi-ls) (let ((lo-len (length lo-ls))) (sre-alternate (append (list (sre-sequence (cons `(/ ,(integer->char (car lo-ls)) ,(integer->char (if (<= (car lo-ls) #x7F) #x7F #xFF))) (map (lambda (_) `(/ ,(integer->char #x80) ,(integer->char #xFF))) (cdr lo-ls))))) (map (lambda (i) (sre-sequence (cons `(/ ,(integer->char (utf8-lowest-digit-of-length (+ i lo-len 1))) ,(integer->char (utf8-highest-digit-of-length (+ i lo-len 1)))) (map (lambda (_) `(/ ,(integer->char #x80) ,(integer->char #xFF))) (zero-to (+ i lo-len)))))) (zero-to (- (length hi-ls) (+ lo-len 1)))) (list (sre-sequence (cons `(/ ,(integer->char (utf8-lowest-digit-of-length (utf8-start-char->length (integer->char (- (car hi-ls) 1))))) ,(integer->char (- (car hi-ls) 1))) (map (lambda (_) `(/ ,(integer->char #x80) ,(integer->char #xFF))) (cdr hi-ls))))))))) (define (unicode-range-middle lo-ls hi-ls) (let ((lo (integer->char (+ (car lo-ls) 1))) (hi (integer->char (- (car hi-ls) 1)))) (sre-sequence (cons (if (char=? lo hi) lo `(/ ,lo ,hi)) (map (lambda (_) `(/ ,(integer->char #x80) ,(integer->char #xFF))) (cdr lo-ls)))))) ;; Maybe this should just modify the input? (define (cset->utf8-pattern cset) (let lp ((ls (cset->plist cset)) (alts '()) (lo-cset '())) (if (null? ls) (sre-alternate (append (reverse alts) (if (null? lo-cset) '() (list (cons '/ (reverse lo-cset)))))) (if (or (high-char? (car ls)) (high-char? (cadr ls))) (lp (cddr ls) (cons (unicode-range->utf8-pattern (car ls) (cadr ls)) alts) lo-cset) (lp (cddr ls) alts (cons (cadr ls) (cons (car ls) lo-cset))))))) (define (sre-adjust-utf8 sre flags) (let adjust ((sre sre) (utf8? (flag-set? flags ~utf8?)) (ci? (flag-set? flags ~case-insensitive?))) (define (rec sre) (adjust sre utf8? ci?)) (cond ((pair? sre) (case (car sre) ((w/utf8) (adjust (sre-sequence (cdr sre)) #t ci?)) ((w/noutf8) (adjust (sre-sequence (cdr sre)) #f ci?)) ((w/case) (cons (car sre) (map (lambda (s) (adjust s utf8? #f)) (cdr sre)))) ((w/nocase) (cons (car sre) (map (lambda (s) (adjust s utf8? #t)) (cdr sre)))) ((/ ~ & -) (if (not utf8?) sre (let ((cset (sre->cset sre ci?))) (if (any high-char? (cset->plist cset)) (if ci? (list 'w/case (cset->utf8-pattern cset)) (cset->utf8-pattern cset)) sre)))) ((*) (case (sre-sequence (cdr sre)) ;; special case optimization: .* w/utf8 == .* w/noutf8 ((any) '(* any)) ((nonl) '(* nonl)) (else (cons '* (map rec (cdr sre)))))) (else (cons (car sre) (map rec (cdr sre)))))) (else (case sre ((any) 'utf8-any) ((nonl) 'utf8-nonl) (else (if (and utf8? (char? sre) (high-char? sre)) (sre-sequence (map integer->char (char->utf8-list sre))) sre))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Compilation (define (irregex x . o) (cond ((irregex? x) x) ((string? x) (apply string->irregex x o)) (else (apply sre->irregex x o)))) (define (string->irregex str . o) (apply sre->irregex (apply string->sre str o) o)) (define (sre->irregex sre . o) (let* ((pat-flags (symbol-list->flags o)) (sre (if *allow-utf8-mode?* (sre-adjust-utf8 sre pat-flags) sre)) (searcher? (sre-searcher? sre)) (sre-dfa (if searcher? (sre-remove-initial-bos sre) sre)) (dfa-limit (cond ((memq 'small o) 1) ((memq 'fast o) 50) (else 10))) ;; TODO: Maybe make these two promises; if we only want to search, ;; it's wasteful to compile the matcher, and vice versa ;; Maybe provide a flag to compile eagerly, to help benchmarking etc. (dfa/search (cond ((memq 'backtrack o) #f) (searcher? #t) ((sre->nfa `(seq (* any) ,sre-dfa) pat-flags) => (lambda (nfa) (nfa->dfa nfa (* dfa-limit (nfa-num-states nfa))))) (else #f))) (dfa (cond ((and dfa/search (sre->nfa sre-dfa pat-flags)) => (lambda (nfa) (nfa->dfa nfa (* dfa-limit (nfa-num-states nfa))))) (else #f))) (submatches (sre-count-submatches sre-dfa)) (names (sre-names sre-dfa 1 '())) (lens (sre-length-ranges sre-dfa names)) (flags (flag-join (flag-join ~none (and searcher? ~searcher?)) (and (sre-consumer? sre) ~consumer?)))) (cond (dfa (make-irregex dfa dfa/search #f flags submatches lens names)) (else (let ((f (sre->procedure sre pat-flags names))) (make-irregex #f #f f flags submatches lens names)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; SRE Analysis ;; returns #t if the sre can ever be empty (define (sre-empty? sre) (if (pair? sre) (case (car sre) ((* ? look-ahead look-behind neg-look-ahead neg-look-behind) #t) ((**) (or (not (number? (cadr sre))) (zero? (cadr sre)))) ((or) (any sre-empty? (cdr sre))) ((: seq $ submatch => submatch-named + atomic) (every sre-empty? (cdr sre))) (else #f)) (memq sre '(epsilon bos eos bol eol bow eow commit)))) (define (sre-any? sre) (or (eq? sre 'any) (and (pair? sre) (case (car sre) ((seq : $ submatch => submatch-named) (and (pair? (cdr sre)) (null? (cddr sre)) (sre-any? (cadr sre)))) ((or) (every sre-any? (cdr sre))) (else #f))))) (define (sre-repeater? sre) (and (pair? sre) (or (memq (car sre) '(* +)) (and (memq (car sre) '($ submatch => submatch-named seq :)) (pair? (cdr sre)) (null? (cddr sre)) (sre-repeater? (cadr sre)))))) (define (sre-searcher? sre) (if (pair? sre) (case (car sre) ((* +) (sre-any? (sre-sequence (cdr sre)))) ((seq : $ submatch => submatch-named) (and (pair? (cdr sre)) (sre-searcher? (cadr sre)))) ((or) (every sre-searcher? (cdr sre))) (else #f)) (eq? 'bos sre))) (define (sre-consumer? sre) (if (pair? sre) (case (car sre) ((* +) (sre-any? (sre-sequence (cdr sre)))) ((seq : $ submatch => submatch-named) (and (pair? (cdr sre)) (sre-consumer? (last sre)))) ((or) (every sre-consumer? (cdr sre))) (else #f)) (eq? 'eos sre))) (define (sre-has-submatches? sre) (and (pair? sre) (or (memq (car sre) '($ submatch => submatch-named)) (if (eq? 'posix-string (car sre)) (sre-has-submatches? (string->sre (cadr sre))) (any sre-has-submatches? (cdr sre)))))) (define (sre-count-submatches sre) (let count ((sre sre) (sum 0)) (if (pair? sre) (fold count (+ sum (case (car sre) (($ submatch => submatch-named) 1) ((dsm) (+ (cadr sre) (caddr sre))) ((posix-string) (sre-count-submatches (string->sre (cadr sre)))) (else 0))) (cdr sre)) sum))) (define (sre-length-ranges sre . o) (let ((names (if (pair? o) (car o) (sre-names sre 1 '()))) (sublens (make-vector (+ 1 (sre-count-submatches sre)) #f))) (vector-set! sublens 0 (let lp ((sre sre) (n 1) (lo 0) (hi 0) (return cons)) (define (grow i) (return (+ lo i) (and hi (+ hi i)))) (cond ((pair? sre) (if (string? (car sre)) (grow 1) (case (car sre) ((/ ~ & -) (grow 1)) ((posix-string) (lp (string->sre (cadr sre)) n lo hi return)) ((seq : w/case w/nocase atomic) (let lp2 ((ls (cdr sre)) (n n) (lo2 0) (hi2 0)) (if (null? ls) (return (+ lo lo2) (and hi hi2 (+ hi hi2))) (lp (car ls) n 0 0 (lambda (lo3 hi3) (lp2 (cdr ls) (+ n (sre-count-submatches (car ls))) (+ lo2 lo3) (and hi2 hi3 (+ hi2 hi3)))))))) ((or) (let lp2 ((ls (cdr sre)) (n n) (lo2 #f) (hi2 0)) (if (null? ls) (return (+ lo (or lo2 1)) (and hi hi2 (+ hi hi2))) (lp (car ls) n 0 0 (lambda (lo3 hi3) (lp2 (cdr ls) (+ n (sre-count-submatches (car ls))) (if lo2 (min lo2 lo3) lo3) (and hi2 hi3 (max hi2 hi3)))))))) ((if) (cond ((or (null? (cdr sre)) (null? (cddr sre))) (return lo hi)) (else (let ((n1 (sre-count-submatches (car sre))) (n2 (sre-count-submatches (cadr sre)))) (lp (if (or (number? (cadr sre)) (symbol? (cadr sre))) 'epsilon (cadr sre)) n lo hi (lambda (lo2 hi2) (lp (caddr sre) (+ n n1) 0 0 (lambda (lo3 hi3) (lp (if (pair? (cdddr sre)) (cadddr sre) 'epsilon) (+ n n1 n2) 0 0 (lambda (lo4 hi4) (return (+ lo2 (min lo3 lo4)) (and hi2 hi3 hi4 (+ hi2 (max hi3 hi4)) )))))))))))) ((dsm) (lp (sre-sequence (cdddr sre)) (+ n (cadr sre)) lo hi return)) (($ submatch => submatch-named) (lp (sre-sequence (if (eq? 'submatch (car sre)) (cdr sre) (cddr sre))) (+ n 1) lo hi (lambda (lo2 hi2) (vector-set! sublens n (cons lo2 hi2)) (return lo2 hi2)))) ((backref backref-ci) (let ((n (cond ((number? (cadr sre)) (cadr sre)) ((assq (cadr sre) names) => cdr) (else (error "unknown backreference" (cadr sre)))))) (cond ((or (not (integer? n)) (not (< 0 n (vector-length sublens)))) (error "sre-length: invalid backreference" sre)) ((not (vector-ref sublens n)) (error "sre-length: invalid forward backreference" sre)) (else (let ((lo2 (car (vector-ref sublens n))) (hi2 (cdr (vector-ref sublens n)))) (return (+ lo lo2) (and hi hi2 (+ hi hi2)))))))) ((* *?) (lp (sre-sequence (cdr sre)) n lo hi (lambda (lo hi) #f)) (return lo #f)) ((** **?) (cond ((or (and (number? (cadr sre)) (number? (caddr sre)) (> (cadr sre) (caddr sre))) (and (not (cadr sre)) (caddr sre))) (return lo hi)) (else (if (caddr sre) (lp (sre-sequence (cdddr sre)) n 0 0 (lambda (lo2 hi2) (return (+ lo (* (cadr sre) lo2)) (and hi hi2 (+ hi (* (caddr sre) hi2)))))) (lp (sre-sequence (cdddr sre)) n 0 0 (lambda (lo2 hi2) (return (+ lo (* (cadr sre) lo2)) #f))))))) ((+) (lp (sre-sequence (cdr sre)) n lo hi (lambda (lo2 hi2) (return (+ lo lo2) #f)))) ((? ??) (lp (sre-sequence (cdr sre)) n lo hi (lambda (lo2 hi2) (return lo (and hi hi2 (+ hi hi2)))))) ((= =? >= >=?) (lp `(** ,(cadr sre) ,(if (memq (car sre) '(>= >=?)) #f (cadr sre)) ,@(cddr sre)) n lo hi return)) ((look-ahead neg-look-ahead look-behind neg-look-behind) (return lo hi)) (else (cond ((assq (car sre) sre-named-definitions) => (lambda (cell) (lp (apply (cdr cell) (cdr sre)) n lo hi return))) (else (error "sre-length-ranges: unknown sre operator" sre))))))) ((char? sre) (grow 1)) ((string? sre) (grow (string-length sre))) ((memq sre '(any nonl)) (grow 1)) ((memq sre '(epsilon bos eos bol eol bow eow nwb commit)) (return lo hi)) (else (let ((cell (assq sre sre-named-definitions))) (if cell (lp (if (procedure? (cdr cell)) ((cdr cell)) (cdr cell)) n lo hi return) (error "sre-length-ranges: unknown sre" sre))))))) sublens)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; SRE Manipulation ;; build a (seq ls ...) sre from a list (define (sre-sequence ls) (cond ((null? ls) 'epsilon) ((null? (cdr ls)) (car ls)) (else (cons 'seq ls)))) ;; build a (or ls ...) sre from a list (define (sre-alternate ls) (cond ((null? ls) '(or)) ((null? (cdr ls)) (car ls)) (else (cons 'or ls)))) ;; returns an equivalent SRE without any match information (define (sre-strip-submatches sre) (if (not (pair? sre)) sre (case (car sre) (($ submatch) (sre-strip-submatches (sre-sequence (cdr sre)))) ((=> submatch-named) (sre-strip-submatches (sre-sequence (cddr sre)))) ((dsm) (sre-strip-submatches (sre-sequence (cdddr sre)))) (else (map sre-strip-submatches sre))))) ;; given a char-set list of chars and strings, flattens them into ;; chars only (define (sre-flatten-ranges ls) (let lp ((ls ls) (res '())) (cond ((null? ls) (reverse res)) ((string? (car ls)) (lp (append (string->list (car ls)) (cdr ls)) res)) (else (lp (cdr ls) (cons (car ls) res)))))) (define (sre-names sre n names) (if (not (pair? sre)) names (case (car sre) (($ submatch) (sre-names (sre-sequence (cdr sre)) (+ n 1) names)) ((=> submatch-named) (sre-names (sre-sequence (cddr sre)) (+ n 1) (cons (cons (cadr sre) n) names))) ((dsm) (sre-names (sre-sequence (cdddr sre)) (+ n (cadr sre)) names)) ((seq : or * + ? *? ?? w/case w/nocase atomic look-ahead look-behind neg-look-ahead neg-look-behind) (sre-sequence-names (cdr sre) n names)) ((= >=) (sre-sequence-names (cddr sre) n names)) ((** **?) (sre-sequence-names (cdddr sre) n names)) (else names)))) (define (sre-sequence-names ls n names) (if (null? ls) names (sre-sequence-names (cdr ls) (+ n (sre-count-submatches (car ls))) (sre-names (car ls) n names)))) (define (sre-remove-initial-bos sre) (cond ((pair? sre) (case (car sre) ((seq : $ submatch => submatch-named * +) (cond ((not (pair? (cdr sre))) sre) ((eq? 'bos (cadr sre)) (cons (car sre) (cddr sre))) (else (cons (car sre) (cons (sre-remove-initial-bos (cadr sre)) (cddr sre)))))) ((or) (sre-alternate (map sre-remove-initial-bos (cdr sre)))) (else sre))) (else sre))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Basic Matching (define irregex-basic-string-chunker (make-irregex-chunker (lambda (x) #f) car cadr caddr (lambda (src1 i src2 j) (substring (car src1) i j)))) (define (irregex-search x str . o) (if (not (string? str)) (error "irregex-search: not a string" str)) (let ((start (or (and (pair? o) (car o)) 0)) (end (or (and (pair? o) (pair? (cdr o)) (cadr o)) (string-length str)))) (if (not (and (integer? start) (exact? start))) (error "irregex-search: not an exact integer" start)) (if (not (and (integer? end) (exact? end))) (error "irregex-search: not an exact integer" end)) (irregex-search/chunked x irregex-basic-string-chunker (list str start end) start))) (define (irregex-search/chunked x cnk src . o) (let* ((irx (irregex x)) (matches (irregex-new-matches irx)) (i (if (pair? o) (car o) ((chunker-get-start cnk) src)))) (irregex-match-chunker-set! matches cnk) (irregex-search/matches irx cnk (cons src i) src i matches))) ;; internal routine, can be used in loops to avoid reallocating the ;; match vector (define (irregex-search/matches irx cnk init src i matches) (cond ((irregex-dfa irx) (cond ((flag-set? (irregex-flags irx) ~searcher?) (cond ((dfa-match/longest (irregex-dfa irx) cnk src i #f #f matches 0) (irregex-match-start-chunk-set! matches 0 src) (irregex-match-start-index-set! matches 0 i) matches) (else #f))) ((dfa-match/shortest (irregex-dfa/search irx) cnk src i matches 0) (let ((dfa (irregex-dfa irx)) (get-start (chunker-get-start cnk)) (get-end (chunker-get-end cnk)) (get-next (chunker-get-next cnk))) (let lp1 ((src src) (i i)) (let ((end (get-end src))) (let lp2 ((i i)) (cond ((dfa-match/longest dfa cnk src i #f #f matches 0) (irregex-match-start-chunk-set! matches 0 src) (irregex-match-start-index-set! matches 0 i) matches) ((>= i end) (let ((next (get-next src))) (and next (lp1 next (get-start next))))) (else (lp2 (+ i 1))))))))) (else #f))) (else (let ((res (irregex-search/backtrack irx cnk init src i matches))) (if res (%irregex-match-fail-set! res #f)) res)))) (define (irregex-search/backtrack irx cnk init src i matches) (let ((matcher (irregex-nfa irx)) (str ((chunker-get-str cnk) src)) (end ((chunker-get-end cnk) src)) (get-next (chunker-get-next cnk))) (if (flag-set? (irregex-flags irx) ~searcher?) (matcher cnk init src str i end matches (lambda () #f)) (let lp ((src2 src) (str str) (i i) (end end)) (cond ((matcher cnk init src2 str i end matches (lambda () #f)) (irregex-match-start-chunk-set! matches 0 src2) (irregex-match-start-index-set! matches 0 i) matches) ((< i end) (lp src2 str (+ i 1) end)) (else (let ((src2 (get-next src2))) (if src2 (lp src2 ((chunker-get-str cnk) src2) ((chunker-get-start cnk) src2) ((chunker-get-end cnk) src2)) #f)))))))) (define (irregex-match irx str . o) (if (not (string? str)) (error "irregex-match: not a string" str)) (let ((start (or (and (pair? o) (car o)) 0)) (end (or (and (pair? o) (pair? (cdr o)) (cadr o)) (string-length str)))) (if (not (and (integer? start) (exact? start))) (error "irregex-match: not an exact integer" start)) (if (not (and (integer? end) (exact? end))) (error "irregex-match: not an exact integer" end)) (irregex-match/chunked irx irregex-basic-string-chunker (list str start end)))) (define (irregex-match/chunked irx cnk src) (let* ((irx (irregex irx)) (matches (irregex-new-matches irx))) (irregex-match-chunker-set! matches cnk) (cond ((irregex-dfa irx) (and (dfa-match/longest (irregex-dfa irx) cnk src ((chunker-get-start cnk) src) #f #f matches 0) (= ((chunker-get-end cnk) (%irregex-match-end-chunk matches 0)) (%irregex-match-end-index matches 0)) (begin (irregex-match-start-chunk-set! matches 0 src) (irregex-match-start-index-set! matches 0 ((chunker-get-start cnk) src)) matches))) (else (let* ((matcher (irregex-nfa irx)) (str ((chunker-get-str cnk) src)) (i ((chunker-get-start cnk) src)) (end ((chunker-get-end cnk) src)) (init (cons src i))) (let lp ((m (matcher cnk init src str i end matches (lambda () #f)))) (and m (cond ((and (not ((chunker-get-next cnk) (%irregex-match-end-chunk m 0))) (= ((chunker-get-end cnk) (%irregex-match-end-chunk m 0)) (%irregex-match-end-index m 0))) (%irregex-match-fail-set! m #f) m) ((%irregex-match-fail m) (lp ((%irregex-match-fail m)))) (else #f))))))))) (define (irregex-match? . args) (and (apply irregex-match args) #t)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; DFA Matching ;; inline these (define (dfa-init-state dfa) (vector-ref dfa 0)) (define (dfa-next-state dfa node) (vector-ref dfa (cadr node))) (define (dfa-cell-commands dfa node) (cddr node)) (define (dfa-finalizer dfa state) (car state)) ;; this searches for the first end index for which a match is possible (define (dfa-match/shortest dfa cnk src start matches index) (let ((get-str (chunker-get-str cnk)) (get-start (chunker-get-start cnk)) (get-end (chunker-get-end cnk)) (get-next (chunker-get-next cnk)) ;; Skip the "set-up" state, we don't need to set tags. (start-state (dfa-next-state dfa (cadr (dfa-init-state dfa))))) (let lp1 ((src src) (start start) (state start-state)) (and src (let ((str (get-str src)) (end (get-end src))) (let lp2 ((i start) (state state)) (cond ((dfa-finalizer dfa state) (cond (index (irregex-match-end-chunk-set! matches index src) (irregex-match-end-index-set! matches index i))) #t) ((< i end) (let* ((ch (string-ref str i)) (next (find (lambda (x) (or (eqv? ch (car x)) (and (not (char? (car x))) (cset-contains? (car x) ch)))) (cdr state)))) (and next (lp2 (+ i 1) (dfa-next-state dfa next))))) (else (let ((next (get-next src))) (and next (lp1 next (get-start next) state))))))))))) (define (finalize! finalizer memory matches) (for-each (lambda (tag&slot) (let* ((tag (car tag&slot)) (slot (vector-ref memory (cdr tag&slot))) (chunk&pos (vector-ref slot tag))) (irregex-match-chunk&index-from-tag-set! matches tag (and chunk&pos (car chunk&pos)) (and chunk&pos (cdr chunk&pos))))) finalizer)) (define (make-initial-memory slots matches) (let ((size (* (irregex-match-num-submatches matches) 2)) (memory (make-vector slots))) (do ((i 0 (+ i 1))) ((= i slots) memory) (vector-set! memory i (make-vector size #f))))) ;; this finds the longest match starting at a given index (define (dfa-match/longest dfa cnk src start end-src end matches index) (let* ((get-str (chunker-get-str cnk)) (get-start (chunker-get-start cnk)) (get-end (chunker-get-end cnk)) (get-next (chunker-get-next cnk)) (initial-state (dfa-init-state dfa)) (memory-size (car initial-state)) (submatches? (not (zero? memory-size))) ;; A vector of vectors, each of size <number of start/end submatches> (memory (make-initial-memory memory-size matches)) (init-cell (cadr initial-state)) (start-state (dfa-next-state dfa init-cell)) (start-finalizer (dfa-finalizer dfa start-state))) (cond (index (irregex-match-end-chunk-set! matches index #f) (irregex-match-end-index-set! matches index #f))) (cond (submatches? (for-each (lambda (s) (let ((slot (vector-ref memory (cdr s)))) (vector-set! slot (car s) (cons src start)))) (cdr (dfa-cell-commands dfa init-cell))))) (let lp1 ((src src) (start start) (state start-state) (res-src (and start-finalizer src)) (res-index (and start-finalizer start)) (finalizer start-finalizer)) (let ((str (get-str src)) (end (if (eq? src end-src) end (get-end src)))) (let lp2 ((i start) (state state) (res-src res-src) (res-index res-index) (finalizer finalizer)) (cond ((>= i end) (cond ((and index res-src) (irregex-match-end-chunk-set! matches index res-src) (irregex-match-end-index-set! matches index res-index))) (let ((next (and (not (eq? src end-src)) (get-next src)))) (if next (lp1 next (get-start next) state res-src res-index finalizer) (and index (%irregex-match-end-chunk matches index) (or (not finalizer) (finalize! finalizer memory matches)) #t)))) (else (let* ((ch (string-ref str i)) (cell (find (lambda (x) (or (eqv? ch (car x)) (and (not (char? (car x))) (cset-contains? (car x) ch)))) (cdr state)))) (cond (cell (let* ((next (dfa-next-state dfa cell)) (new-finalizer (dfa-finalizer dfa next))) (cond (submatches? (let ((cmds (dfa-cell-commands dfa cell))) ;; Save match when we're moving from accepting state to ;; rejecting state; this could be the last accepting one. (cond ((and finalizer (not new-finalizer)) (finalize! finalizer memory matches))) (for-each (lambda (s) (let ((slot (vector-ref memory (cdr s))) (chunk&position (cons src (+ i 1)))) (vector-set! slot (car s) chunk&position))) (cdr cmds)) (for-each (lambda (c) (let* ((tag (vector-ref c 0)) (ss (vector-ref memory (vector-ref c 1))) (ds (vector-ref memory (vector-ref c 2)))) (vector-set! ds tag (vector-ref ss tag)))) (car cmds))))) (if new-finalizer (lp2 (+ i 1) next src (+ i 1) new-finalizer) (lp2 (+ i 1) next res-src res-index #f)))) (res-src (cond (index (irregex-match-end-chunk-set! matches index res-src) (irregex-match-end-index-set! matches index res-index))) (cond (finalizer (finalize! finalizer memory matches))) #t) ((and index (%irregex-match-end-chunk matches index)) (cond (finalizer (finalize! finalizer memory matches))) #t) (else #f)))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Named Definitions (define sre-named-definitions `((any . ,*all-chars*) (nonl . (- ,*all-chars* (,(string #\newline)))) (alphabetic . (/ #\a #\z #\A #\Z)) (alpha . alphabetic) (alphanumeric . (/ #\a #\z #\A #\Z #\0 #\9)) (alphanum . alphanumeric) (alnum . alphanumeric) (lower-case . (/ #\a #\z)) (lower . lower-case) (upper-case . (/ #\A #\Z)) (upper . upper-case) (numeric . (/ #\0 #\9)) (num . numeric) (digit . numeric) (punctuation . (or #\! #\" #\# #\% #\& #\' #\( #\) #\* #\, #\- #\. #\/ #\: #\; #\? #\@ #\[ #\\ #\] #\_ #\{ #\})) (punct . punctuation) (graphic . (or alphanumeric punctuation #\$ #\+ #\< #\= #\> #\^ #\` #\| #\~)) (graph . graphic) (blank . (or #\space ,(integer->char (- (char->integer #\space) 23)))) (whitespace . (or blank #\newline)) (space . whitespace) (white . whitespace) (printing or graphic whitespace) (print . printing) ;; XXXX we assume a (possibly shifted) ASCII-based ordering (control . (/ ,(integer->char (- (char->integer #\space) 32)) ,(integer->char (- (char->integer #\space) 1)))) (cntrl . control) (hex-digit . (or numeric (/ #\a #\f #\A #\F))) (xdigit . hex-digit) (ascii . (/ ,(integer->char (- (char->integer #\space) 32)) ,(integer->char (+ (char->integer #\space) 95)))) (ascii-nonl . (/ ,(integer->char (- (char->integer #\space) 32)) ,(integer->char (- (char->integer #\newline) 1)) ,(integer->char (+ (char->integer #\newline) 1)) ,(integer->char (+ (char->integer #\space) 95)))) (newline . (or (seq ,(integer->char (+ (char->integer #\newline) 3)) #\newline) (/ #\newline ,(integer->char (+ (char->integer #\newline) 3))))) ;; ... it's really annoying to support old Scheme48 (word . (seq bow (+ (or alphanumeric #\_)) eow)) (utf8-tail-char . (/ ,(integer->char (+ (char->integer #\space) #x60)) ,(integer->char (+ (char->integer #\space) #xA1)))) (utf8-2-char . (seq (/ ,(integer->char (+ (char->integer #\space) #xA2)) ,(integer->char (+ (char->integer #\space) #xBF))) utf8-tail-char)) (utf8-3-char . (seq (/ ,(integer->char (+ (char->integer #\space) #xC0)) ,(integer->char (+ (char->integer #\space) #xCF))) utf8-tail-char utf8-tail-char)) (utf8-4-char . (seq (/ ,(integer->char (+ (char->integer #\space) #xD0)) ,(integer->char (+ (char->integer #\space) #xD7))) utf8-tail-char utf8-tail-char utf8-tail-char)) (utf8-any . (or ascii utf8-2-char utf8-3-char utf8-4-char)) (utf8-nonl . (or ascii-nonl utf8-2-char utf8-3-char utf8-4-char)) ;; extended library patterns (integer . (seq (? (or #\+ #\-)) (+ numeric))) (real . (seq (? (or #\+ #\-)) (+ numeric) (? #\. (+ numeric)) (? (or #\e #\E) integer))) ;; slightly more lax than R5RS, allow ->foo, etc. (symbol-initial . (or alpha ("!$%&*/:<=>?^_~"))) (symbol-subsequent . (or symbol-initial digit ("+-.@"))) (symbol . (or (seq symbol-initial (* symbol-subsequent)) (seq ("+-") (? symbol-initial (* symbol-subsequent))) (seq ".." (* ".")))) (sexp-space . (seq (* (* space) ";" (* nonl) newline) (+ space))) (string . (seq #\" (escape #\\ #\") #\")) (escape . ,(lambda (esc . o) `(* (or (~ ,esc ,@o) (seq ,esc any))))) (ipv4-digit . (seq (? (/ "12")) (? numeric) numeric)) (ipv4-address . (seq ipv4-digit (= 3 #\. ipv4-digit))) ;; XXXX lax, allows multiple double-colons or < 8 terms w/o a :: (ipv6-address . (seq (** 0 4 hex-digit) (** 1 7 #\: (? #\:) (** 0 4 hex-digit)))) (ip-address . (or ipv4-address ipv6-address)) (domain-atom . (+ (or alphanumeric #\_ #\-))) (domain . (seq domain-atom (+ #\. domain-atom))) ;; XXXX now anything can be a top-level domain, but this is still handy (top-level-domain . (w/nocase (or "arpa" "com" "gov" "mil" "net" "org" "aero" "biz" "coop" "info" "museum" "name" "pro" (= 2 alpha)))) (domain/common . (seq (+ domain-atom #\.) top-level-domain)) ;;(email-local-part . (seq (+ (or (~ #\") string)))) (email-local-part . (+ (or alphanumeric #\_ #\- #\. #\+))) (email . (seq email-local-part #\@ domain)) (url-char . (or alnum #\_ #\- #\+ #\\ #\= #\~ #\. #\, #\& #\; (seq "%" hex-digit hex-digit))) (url-final-char . (or alnum #\_ #\- #\+ #\\ #\= #\~ #\& (seq "%" hex-digit hex-digit))) (http-url . (w/nocase "http" (? "s") "://" (or domain/common ipv4-address) ;; (seq "[" ipv6-address "]") (? ":" (+ numeric)) ;; port ;; path (? "/" (* (or url-char "/")) (? "?" (* url-char)) ;; query (? "#" (? (* url-char) url-final-char)) ;; fragment ))) )) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; SRE->tNFA compilation ;; ;; A tagged NFA (tNFA) state is a numbered node with a list of ;; pattern->number transitions, where pattern is character set range, ;; or epsilon (indicating an empty transition). ;; ;; (Only) epsilon transitions may be *tagged*. Each tag represents ;; either the start or the end of a submatch. ;; ;; There may be overlapping ranges - since it's an NFA we process it ;; by considering all possible transitions. (define *nfa-presize* 128) ;; constant (define *nfa-num-fields* 4) ;; constant (define (nfa-num-states nfa) (quotient (vector-length nfa) *nfa-num-fields*)) (define (nfa-start-state nfa) (- (nfa-num-states nfa) 1)) (define (nfa-num-tags nfa) (vector-ref nfa 0)) (define (nfa-highest-map-index nfa) (vector-ref nfa 1)) (define (nfa-set-highest-map-index! nfa idx) (vector-set! nfa 1 idx)) (define (nfa-get-state-trans nfa i) (if (= i 0) '() (vector-ref nfa (* i *nfa-num-fields*)))) (define (nfa-set-state-trans! nfa i x) (vector-set! nfa (* i *nfa-num-fields*) x)) (define (nfa-get-epsilons nfa i) (if (= i 0) '() (vector-ref nfa (+ (* i *nfa-num-fields*) 1)))) (define (nfa-set-epsilons! nfa i x) (vector-set! nfa (+ (* i *nfa-num-fields*) 1) x)) (define (nfa-add-epsilon! nfa i x t) (let ((eps (nfa-get-epsilons nfa i))) (if (not (assv x eps)) (nfa-set-epsilons! nfa i (cons (cons x t) eps))))) (define (nfa-get-reorder-commands nfa mst) (cond ((assoc mst (vector-ref nfa (+ (* (mst-hash mst) *nfa-num-fields*) 2))) => cdr) (else #f))) (define (nfa-set-reorder-commands! nfa mst x) (let ((i (+ (* (mst-hash mst) *nfa-num-fields*) 2))) (vector-set! nfa i (cons (cons mst x) (vector-ref nfa i))))) (define (nfa-get-closure nfa mst) (cond ((assoc mst (vector-ref nfa (+ (* (mst-hash mst) *nfa-num-fields*) 3))) => cdr) (else #f))) (define (nfa-add-closure! nfa mst x) (let ((i (+ (* (mst-hash mst) *nfa-num-fields*) 3))) (vector-set! nfa i (cons (cons mst x) (vector-ref nfa i))))) ;; Compile and return the vector of NFA states (in groups of ;; *nfa-num-fields* packed elements). The start state will be the ;; last element(s) of the vector, and all remaining states will be in ;; descending numeric order, with state 0 being the unique accepting ;; state. (define (sre->nfa sre init-flags) (let* ((buf (make-vector (* *nfa-presize* *nfa-num-fields*) '())) ;; Get cons cells and map them to numeric submatch indexes. ;; Doing it here is slightly easier than integrating into the loop below (match-index (let lp ((sre (list sre)) (max 0) (res '())) (cond ((not (pair? sre)) ;; We abuse the transitions slot for state 0 (the final state, ;; which can have no transitions) to store the number of tags. (vector-set! buf 0 (* max 2)) ;; We abuse the epsilons slot for state 0 to store the highest ;; encountered memory slot mapping index. Initialize to -1. (vector-set! buf 1 -1) res) ((pair? (car sre)) ;; The appends here should be safe (are they?) (case (caar sre) (($ submatch => submatch-named) (lp (append (cdar sre) (cdr sre)) (+ max 1) (cons (cons (car sre) max) res))) (else (lp (append (car sre) (cdr sre)) max res)))) (else (lp (cdr sre) max res)))))) ;; we loop over an implicit sequence list (define (lp ls n flags next) (define (new-state-number state) (max n (+ 1 state))) (define (add-state! n2 trans-ls) (if (>= (* n2 *nfa-num-fields*) (vector-length buf)) (let ((tmp (make-vector (* 2 (vector-length buf)) '()))) (do ((i (- (vector-length buf) 1) (- i 1))) ((< i 0)) (vector-set! tmp i (vector-ref buf i))) (set! buf tmp))) (nfa-set-state-trans! buf n2 trans-ls) n2) (define (extend-state! next trans-cs) (and next (add-state! (new-state-number next) (cons trans-cs next)))) (define (add-char-state! next ch) (let ((alt (char-altcase ch))) (if (flag-set? flags ~case-insensitive?) (extend-state! next (cset-union (char->cset ch) (char->cset alt))) (extend-state! next (char->cset ch))))) (if (null? ls) next (cond ((or (eq? 'epsilon (car ls)) (equal? "" (car ls))) ;; chars and epsilons go directly into the transition table (let ((next (lp (cdr ls) n flags next))) (and next (let ((new (add-state! (new-state-number next) '()))) (nfa-add-epsilon! buf new next #f) new)))) ((string? (car ls)) ;; process literal strings a char at a time (let ((next (lp (cdr ls) n flags next))) (and next (let lp2 ((i (- (string-length (car ls)) 1)) (next next)) (if (< i 0) next (lp2 (- i 1) (add-char-state! next (string-ref (car ls) i)))) )))) ((char? (car ls)) (add-char-state! (lp (cdr ls) n flags next) (car ls))) ((symbol? (car ls)) (let ((cell (assq (car ls) sre-named-definitions))) (and cell (lp (cons (if (procedure? (cdr cell)) ((cdr cell)) (cdr cell)) (cdr ls)) n flags next)))) ((pair? (car ls)) (cond ((string? (caar ls)) ; Enumerated character set (let ((set (if (flag-set? flags ~case-insensitive?) (cset-case-insensitive (string->cset (caar ls))) (string->cset (caar ls))))) (extend-state! (lp (cdr ls) n flags next) set))) (else (case (caar ls) ((seq :) ;; for an explicit sequence, just append to the list (lp (append (cdar ls) (cdr ls)) n flags next)) ((w/case w/nocase w/utf8 w/noutf8) (let* ((next (lp (cdr ls) n flags next)) (flags ((if (memq (caar ls) '(w/case w/utf8)) flag-clear flag-join) flags (if (memq (caar ls) '(w/case w/nocase)) ~case-insensitive? ~utf8?)))) (and next (lp (cdar ls) (new-state-number next) flags next)))) ((/ - & ~) (let ((range (sre->cset (car ls) (flag-set? flags ~case-insensitive?)))) (extend-state! (lp (cdr ls) n flags next) range))) ((or) (let ((next (lp (cdr ls) n flags next))) (and next (if (null? (cdar ls)) ;; empty (or) always fails (add-state! (new-state-number next) '()) ;; compile both branches and insert epsilon ;; transitions to either (let* ((b (lp (list (sre-alternate (cddar ls))) (new-state-number next) flags next)) (a (and b (lp (list (cadar ls)) (new-state-number (max b next)) flags next)))) (and a (let ((c (add-state! (new-state-number a) '()))) (nfa-add-epsilon! buf c a #f) (nfa-add-epsilon! buf c b #f) c))))))) ((?) (let ((next (lp (cdr ls) n flags next))) ;; insert an epsilon transition directly to next (and next (let ((a (lp (cdar ls) (new-state-number next) flags next))) (if a (nfa-add-epsilon! buf a next #f)) a)))) ((+ *) (let ((next (lp (cdr ls) n flags next))) (and next (let* ((new (lp '(epsilon) (new-state-number next) flags next)) (a (lp (cdar ls) (new-state-number new) flags new))) (cond (a ;; for *, insert an epsilon transition as in ? above (if (eq? '* (caar ls)) (nfa-add-epsilon! buf a new #f)) ;; for both, insert a loop back to self (nfa-add-epsilon! buf new a #f))) a)))) ;; need to add these to the match extractor first, ;; but they tend to generate large DFAs ;;((=) ;; (lp (append (vector->list ;; (make-vector (cadar ls) ;; (sre-sequence (cddar ls)))) ;; (cdr ls)) ;; n flags next)) ;;((>=) ;; (lp (append (vector->list ;; (make-vector (- (cadar ls) 1) ;; (sre-sequence (cddar ls)))) ;; (cons `(+ ,@(cddar ls)) (cdr ls))) ;; n flags next)) ;;((**) ;; (lp (append (vector->list ;; (make-vector (cadar ls) ;; (sre-sequence (cdddar ls)))) ;; (map ;; (lambda (x) `(? ,x)) ;; (vector->list ;; (make-vector (- (caddar ls) (cadar ls)) ;; (sre-sequence (cdddar ls))))) ;; (cdr ls)) ;; n flags next)) ;; ignore submatches altogether (($ submatch) (let* ((pre-tag (* (cdr (assq (car ls) match-index)) 2)) (post-tag (+ pre-tag 1)) (next (lp (cdr ls) n flags next))) (and next (let* ((after (add-state! (new-state-number next) '())) (sub (lp (list (sre-sequence (cdar ls))) (new-state-number after) flags after)) (before (and sub (add-state! (new-state-number sub) '())))) (cond (before (nfa-add-epsilon! buf before sub pre-tag) (nfa-add-epsilon! buf after next post-tag))) before)))) ((=> submatch-named) (let* ((pre-tag (* (cdr (assq (car ls) match-index)) 2)) (post-tag (+ pre-tag 1)) (next (lp (cdr ls) n flags next))) (and next (let* ((after (add-state! (new-state-number next) '())) (sub (lp (list (sre-sequence (cddar ls))) (new-state-number after) flags after)) (before (and sub (add-state! (new-state-number sub) '())))) (cond (before (nfa-add-epsilon! buf before sub pre-tag) (nfa-add-epsilon! buf after next post-tag))) before)))) (else (cond ((assq (caar ls) sre-named-definitions) => (lambda (cell) (if (procedure? (cdr cell)) (lp (cons (apply (cdr cell) (cdar ls)) (cdr ls)) n flags next) (error "non-procedure in op position" (caar ls))))) (else #f))))))) (else #f)))) (let ((len (lp (list sre) 1 init-flags 0))) (and len (let ((nfa (make-vector (* *nfa-num-fields* (+ len 1))))) (do ((i (- (vector-length nfa) 1) (- i 1))) ((< i 0)) (vector-set! nfa i (vector-ref buf i))) nfa))))) ;; We don't really want to use this, we use the closure compilation ;; below instead, but this is included for reference and testing the ;; sre->nfa conversion. ;; (define (nfa-match nfa str) ;; (let ((matches (make-vector (nfa-num-tags nfa) #f))) ;; (let lp ((pos 0) (ls (string->list str)) (state (nfa-start-state nfa)) (epsilons '())) ;; (and (or (and (null? ls) (zero? state)) ;; (let ((t (nfa-get-state-trans nfa state))) ;; (and (not (null? t)) (not (null? ls)) ;; (cset-contains? (car t) (car ls)) ;; (lp (+ pos 1) (cdr ls) (cdr t) '()))) ;; (any (lambda (e) ;; (let ((old-matches (vector-copy matches))) ;; (cond ((cdr e) ;; (vector-set! matches (cdr e) pos))) ;; (or (and (not (memv (car e) epsilons)) ;; (lp pos ls (car e) (cons (car e) epsilons))) ;; ;; reset match, apparently this branch failed ;; (begin (set! matches old-matches) #f)))) ;; (nfa-get-epsilons nfa state))) ;; matches)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; NFA multi-state representation (define *mst-first-state-index* 3) (define (mst-mappings-summary mst) (vector-ref mst 0)) (define (mst-num-states mst) (vector-ref mst 1)) (define (mst-num-states-set! mst num) (vector-set! mst 1 num)) (define (mst-hash mst) ;; We could do (modulo X (nfa-num-states nfa)) here which would be faster, ;; but we can't assume a full numerical tower (and updating *could* ;; produce a bignum), so we do it each time when updating the hash. (vector-ref mst 2)) (define (mst-hash-set! mst hash) (vector-set! mst 2 hash)) ;; Returns #f if NFA state does not occur in multi-state (define (mst-state-mappings mst state) (vector-ref mst (+ state *mst-first-state-index*))) (define (mst-state-mappings-set! mst state mappings) (vector-set! mst (+ state *mst-first-state-index*) mappings)) ;; A multi-state holds a set of states with their tag-to-slot mappings. ;; Slot 0 contains a summary of all mappings for all states in the multi-state. ;; Slot 1 contains the total number of states in the multi-state. ;; Slot 2 contains a hash value, which is used for quick lookup of cached ;; reorder-commands or epsilon-closure in the NFA. This is the sum of all ;; state numbers plus each tag value (once per occurrence). This is a silly ;; hashing calculation, but it seems to produce a well-spread out hash table and ;; it has the added advantage that we can use the value as a quick check if the ;; state is definitely NOT equivalent to another in mst-same-states? ;; The other slots contain mappings for each corresponding state. (define (make-mst nfa) (let ((mst (make-vector (+ (nfa-num-states nfa) *mst-first-state-index*) #f))) (vector-set! mst 0 (make-vector (nfa-num-tags nfa) '())) ; tag summary (vector-set! mst 1 0) ; total number of states (vector-set! mst 2 0) ; states and tags hash mst)) ;; NOTE: This doesn't do a deep copy of the mappings. Don't mutate them! (define (mst-copy mst) (let ((v (vector-copy mst))) (vector-set! v 0 (vector-copy (vector-ref mst 0))) v)) (define (nfa-state->mst nfa state mappings) (let ((mst (make-mst nfa))) (mst-add! nfa mst state mappings) mst)) ;; Extend multi-state with a state and add its tag->slot mappings. (define (mst-add! nfa mst state mappings) (let ((hash-value (mst-hash mst))) (cond ((not (mst-state-mappings mst state)) ; Update state hash & count? (set! hash-value (+ hash-value state)) (mst-num-states-set! mst (+ (mst-num-states mst) 1)))) (mst-state-mappings-set! mst state mappings) (let ((all-mappings (mst-mappings-summary mst))) (for-each (lambda (tag&slot) (let* ((t (car tag&slot)) (s (cdr tag&slot)) (m (vector-ref all-mappings t))) (cond ((not (memv s m)) (set! hash-value (+ hash-value t)) (vector-set! all-mappings t (cons s m)))))) mappings)) (mst-hash-set! mst (modulo hash-value (nfa-num-states nfa))))) ;; Same as above, but skip updating mappings summary. ;; Called when we know all the tag->slot mappings are already in the summary. (define (mst-add/fast! nfa mst state mappings) (cond ((not (mst-state-mappings mst state)) ; Update state hash & count? (mst-hash-set! mst (modulo (+ (mst-hash mst) state) (nfa-num-states nfa))) (mst-num-states-set! mst (+ (mst-num-states mst) 1)))) (mst-state-mappings-set! mst state mappings)) ;; Same as above, assigning a new slot for a tag. This slot is then ;; added to the summary, if it isn't in there yet. This is more efficient ;; than looping through all the mappings. (define (mst-add-tagged! nfa mst state mappings tag slot) (let* ((mappings-summary (mst-mappings-summary mst)) (summary-tag-slots (vector-ref mappings-summary tag)) (new-mappings (let lp ((m mappings) (res '())) (cond ((null? m) (cons (cons tag slot) res)) ((= (caar m) tag) (append res (cons (cons tag slot) (cdr m)))) (else (lp (cdr m) (cons (car m) res)))))) (hash-value (mst-hash mst))) (cond ((not (mst-state-mappings mst state)) ; Update state hash & count? (set! hash-value (+ hash-value state)) (mst-num-states-set! mst (+ (mst-num-states mst) 1)))) (mst-state-mappings-set! mst state new-mappings) (cond ((not (memv slot summary-tag-slots)) ; Update tag/slot summary (set! hash-value (+ hash-value tag)) (vector-set! mappings-summary tag (cons slot summary-tag-slots)))) (mst-hash-set! mst (modulo hash-value (nfa-num-states nfa))) new-mappings)) (define (mst-same-states? a b) ;; First check if hash and state counts match, then check each state (and (= (mst-hash a) (mst-hash b)) (= (mst-num-states a) (mst-num-states b)) (let ((len (vector-length a))) (let lp ((i *mst-first-state-index*)) (or (= i len) (and (equal? (not (vector-ref a i)) (not (vector-ref b i))) (lp (+ i 1)))))))) (define (mst-fold mst kons knil) (let ((limit (vector-length mst))) (let lp ((i *mst-first-state-index*) (acc knil)) (if (= i limit) acc (let ((m (vector-ref mst i))) (lp (+ i 1) (if m (kons (- i *mst-first-state-index*) m acc) acc))))))) ;; Find the lowest fresh index for this tag that's unused ;; in the multi-state. This also updates the nfa's highest ;; tag counter if a completely new slot number was assigned. (define (next-index-for-tag! nfa tag mst) (let* ((highest (nfa-highest-map-index nfa)) (tag-slots (vector-ref (mst-mappings-summary mst) tag)) (new-index (do ((slot 0 (+ slot 1))) ((not (memv slot tag-slots)) slot)))) (cond ((> new-index highest) (nfa-set-highest-map-index! nfa new-index))) new-index)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; tNFA->DFA compilation ;; During processing, the DFA is a list of the form: ;; ;; ((annotated-tNFA-states ...) finalizer transitions ...) ;; ;; where the transitions are as in the NFA, except there are no ;; epsilons, duplicate characters or overlapping char-set ranges, and ;; the states moved to are closures (sets of NFA states). Multiple ;; DFA states may be accepting states. If the state is an accepting state, ;; the finalizer is a list of (tag . memory-slot) retrieval commands. ;; tNFA-states are annotated with mappings which store the tag values of ;; memory slots, if any. There is always at most one slot for a tag. ;; ;; The DFA itself simulates a NFA by representing all the simultaneous ;; states the NFA can be in at any given point in time as one DFA state. ;; The tag values are ambiguous since each NFA transition can set a tag. ;; To solve this we keep a bank of memory slots around which tracks tag ;; values for each distinct path through the NFA. ;; ;; Once we get to a final state we can pluck the tag values from the ;; memory slots corresponding to the path through which the NFA could have ;; reached the final state. To resolve ambiguities, states are assigned ;; priorities, and the path to the final state is chosen correspondingly. ;; ;; For a more detailed explanation about this process, see ;; Ville Laurikari; ``NFAs with Tagged Transitions, their Conversion to ;; Deterministic Automata and Application to Regular Expressions'' (2000). ;; Laurikari also wrote a master's thesis about this approach which is ;; less terse but the algorithms are not exactly the same. ;; ``Efficient submatch addressing for regular expressions'' (2001). ;; This implementation follows the 2000 paper where they differ. (define (nfa->dfa nfa . o) (let* ((max-states (and (pair? o) (car o))) (start (nfa-state->mst nfa (nfa-start-state nfa) '())) (start-closure (nfa-epsilon-closure nfa start)) ;; Set up a special "initializer" state from which we reach the ;; start-closure to ensure that leading tags are set properly. (init-set (tag-set-commands-for-closure nfa start start-closure '())) (dummy (make-mst nfa)) (init-state (list dummy #f `((,start-closure #f () . ,init-set))))) ;; Unmarked states are just sets of NFA states with tag-maps, marked states ;; are sets of NFA states with transitions to sets of NFA states (let lp ((unmarked-states (list start-closure)) (marked-states (list init-state)) (dfa-size 0)) (cond ((null? unmarked-states) ;; Abuse finalizer slot for storing the number of memory slots we need (set-car! (cdr init-state) (+ (nfa-highest-map-index nfa) 1)) (dfa-renumber (reverse marked-states))) ((and max-states (> dfa-size max-states)) ; Too many DFA states #f) ((assoc (car unmarked-states) marked-states) ; Seen set of NFA-states? (lp (cdr unmarked-states) marked-states dfa-size)) (else (let ((dfa-state (car unmarked-states))) (let lp2 ((trans (get-distinct-transitions nfa dfa-state)) (unmarked-states (cdr unmarked-states)) (dfa-trans '())) (if (null? trans) (let ((finalizer (mst-state-mappings dfa-state 0))) (lp unmarked-states (cons (list dfa-state finalizer dfa-trans) marked-states) (+ dfa-size 1))) (let* ((closure (nfa-epsilon-closure nfa (cdar trans))) (reordered (find-reorder-commands nfa closure marked-states)) (copy-cmds (if reordered (cdr reordered) '())) ;; Laurikari doesn't mention what "k" is, but it seems it ;; must be the mappings of the state's reach (set-cmds (tag-set-commands-for-closure nfa (cdar trans) closure copy-cmds)) (trans-closure (if reordered (car reordered) closure))) (lp2 (cdr trans) (if reordered unmarked-states (cons trans-closure unmarked-states)) (cons `(,trans-closure ,(caar trans) ,copy-cmds . ,set-cmds) dfa-trans))))))))))) ;; When the conversion is complete we renumber the DFA sets-of-states ;; in order and convert the result to a vector for fast lookup. ;; Charsets containing single characters are converted to those characters ;; for quick matching of the literal parts in a regex. (define (dfa-renumber states) (let ((indexes (let lp ((i 0) (states states) (indexes '())) (if (null? states) indexes (lp (+ i 1) (cdr states) (cons (cons (caar states) i) indexes))))) (dfa (make-vector (length states)))) (do ((i 0 (+ i 1)) (states states (cdr states))) ((null? states) dfa) (let ((maybe-finalizer (cadar states)) (transitions (caddar states))) (vector-set! dfa i (cons maybe-finalizer (map (lambda (tr) `(,(and (cadr tr) (maybe-cset->char (cadr tr))) ,(cdr (assoc (car tr) indexes)) . ,(cddr tr))) transitions))))))) ;; Extract all distinct ranges and the potential states they can transition ;; to from a given set of states. Any ranges that would overlap with ;; distinct characters are split accordingly. ;; This function is like "reach" in Laurikari's papers, but for each ;; possible distinct range of characters rather than per character. (define (get-distinct-transitions nfa annotated-states) (define (csets-intersect? a b) (let ((i (cset-intersection a b))) (and (not (cset-empty? i)) i))) (mst-fold annotated-states (lambda (st mappings res) (let ((trans (nfa-get-state-trans nfa st))) ; Always one state per trans (if (null? trans) res (let lp ((ls res) (cs (car trans)) (state (cdr trans)) (res '())) (cond ;; State not seen yet? Add a new state transition ((null? ls) ;; TODO: We should try to find an existing DFA state ;; with only this NFA state in it, and extend the cset ;; with the current one. This produces smaller DFAs, ;; but takes longer to compile. (cons (cons cs (nfa-state->mst nfa state mappings)) res)) ((cset=? cs (caar ls)) ;; Add state to existing set for this charset (mst-add! nfa (cdar ls) state mappings) (append ls res)) ((csets-intersect? cs (caar ls)) => (lambda (intersection) (let* ((only-in-new (cset-difference cs (caar ls))) (only-in-old (cset-difference (caar ls) cs)) (states-in-both (cdar ls)) (states-for-old (and (not (cset-empty? only-in-old)) (mst-copy states-in-both))) (res (if states-for-old (cons (cons only-in-old states-for-old) res) res))) (mst-add! nfa states-in-both state mappings) ;; Add this state to the states already here and ;; restrict to the overlapping charset and continue ;; with the remaining subset of the new cset (if ;; nonempty) (if (cset-empty? only-in-new) (cons (cons intersection states-in-both) (append (cdr ls) res)) (lp (cdr ls) only-in-new state (cons (cons intersection states-in-both) res)))))) (else (lp (cdr ls) cs state (cons (car ls) res)))))))) '())) ;; The epsilon-closure of a set of states is all the states reachable ;; through epsilon transitions, with the tags encountered on the way. (define (nfa-epsilon-closure-internal nfa annotated-states) ;; The stack _MUST_ be in this order for some reason I don't fully understand (let lp ((stack (mst-fold annotated-states (lambda (st m res) (cons (cons st m) res)) '())) (priorities (make-vector (nfa-num-states nfa) 0)) (closure (mst-copy annotated-states))) (if (null? stack) closure (let ((prio/orig-state (caar stack)) ; priority is just the state nr. (mappings (cdar stack))) (let lp2 ((trans (nfa-get-epsilons nfa prio/orig-state)) (stack (cdr stack))) (if (null? trans) (lp stack priorities closure) (let ((state (caar trans))) (cond ;; Our priorities are inverted because we start at ;; the highest state number and go downwards to 0. ((> prio/orig-state (vector-ref priorities state)) (vector-set! priorities state prio/orig-state) (cond ((cdar trans) => ; tagged transition? (lambda (tag) (let* ((index (next-index-for-tag! nfa tag closure)) (new-mappings (mst-add-tagged! nfa closure state mappings tag index))) (lp2 (cdr trans) (cons (cons state new-mappings) stack))))) (else (mst-add/fast! nfa closure state mappings) (lp2 (cdr trans) (cons (cons state mappings) stack))))) (else (lp2 (cdr trans) stack)))))))))) (define (nfa-epsilon-closure nfa states) (or (nfa-get-closure nfa states) (let ((res (nfa-epsilon-closure-internal nfa states))) (nfa-add-closure! nfa states res) res))) ;; Generate "set" commands for all tags in the closure that are ;; not present in the original state. (define (tag-set-commands-for-closure nfa orig-state closure copy-cmds) (let ((num-tags (nfa-num-tags nfa)) (closure-summary (mst-mappings-summary closure)) (state-summary (mst-mappings-summary orig-state))) (let lp ((t 0) (cmds '())) (if (= t num-tags) cmds (let lp2 ((s1 (vector-ref closure-summary t)) (s2 (vector-ref state-summary t)) (cmds cmds)) (cond ((null? s1) (lp (+ t 1) cmds)) ((or (memv (car s1) s2) ; Tag in original state? ;; Try to avoid generating set-commands for any slots ;; that will be overwritten by copy commands, but only ;; if that slot isn't copied to another slot. (and (not (null? copy-cmds)) ; null check for performance ;; Look for copy command overwriting this tag-slot (any (lambda (c) (and (= (vector-ref c 0) t) (= (vector-ref c 2) (car s1)))) copy-cmds) ;; Ensure it's not copied to another slot before ;; discarding the set-command. (not (any (lambda (c) (and (= (vector-ref c 0) t) (= (vector-ref c 1) (car s1)))) copy-cmds)))) (lp2 (cdr s1) s2 cmds)) (else (lp2 (cdr s1) s2 (cons (cons t (car s1)) cmds))))))))) ;; Look in dfa-states for an already existing state which matches ;; closure, but has different tag value mappings. ;; If found, calculate reordering commands so we can map the closure ;; to that state instead of adding a new DFA state. ;; This is completely handwaved away in Laurikari's paper (it basically ;; says "insert reordering algorithm here"), so this code was constructed ;; after some experimentation. In other words, bugs be here. (define (find-reorder-commands-internal nfa closure dfa-states) (let ((num-states (nfa-num-states nfa)) (num-tags (nfa-num-tags nfa)) (closure-summary (mst-mappings-summary closure))) (let lp ((dfa-states dfa-states)) (if (null? dfa-states) #f (if (not (mst-same-states? (caar dfa-states) closure)) (lp (cdr dfa-states)) (let lp2 ((state-summary (mst-mappings-summary (caar dfa-states))) (t 0) (cmds '())) (if (= t num-tags) (cons (caar dfa-states) cmds) (let lp3 ((closure-slots (vector-ref closure-summary t)) (state-slots (vector-ref state-summary t)) (cmds cmds)) (cond ((null? closure-slots) (if (null? state-slots) (lp2 state-summary (+ t 1) cmds) (lp (cdr dfa-states)))) ((null? state-slots) (lp (cdr dfa-states))) (else (lp3 (cdr closure-slots) (cdr state-slots) (if (= (car closure-slots) (car state-slots)) cmds (cons (vector t (car closure-slots) (car state-slots)) cmds))))))))))))) (define (find-reorder-commands nfa closure dfa-states) (or (nfa-get-reorder-commands nfa closure) (let ((res (find-reorder-commands-internal nfa closure dfa-states))) (nfa-set-reorder-commands! nfa closure res) res))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Closure Compilation ;; ;; We use this for non-regular expressions instead of an interpreted ;; NFA matcher. We use backtracking anyway, but this gives us more ;; freedom of implementation, allowing us to support patterns that ;; can't be represented in the above NFA representation. (define (sre->procedure sre . o) (define names (if (and (pair? o) (pair? (cdr o))) (cadr o) (sre-names sre 1 '()))) (let lp ((sre sre) (n 1) (flags (if (pair? o) (car o) ~none)) (next (lambda (cnk init src str i end matches fail) (irregex-match-start-chunk-set! matches 0 (car init)) (irregex-match-start-index-set! matches 0 (cdr init)) (irregex-match-end-chunk-set! matches 0 src) (irregex-match-end-index-set! matches 0 i) (%irregex-match-fail-set! matches fail) matches))) ;; XXXX this should be inlined (define (rec sre) (lp sre n flags next)) (cond ((pair? sre) (if (string? (car sre)) (sre-cset->procedure (sre->cset (car sre) (flag-set? flags ~case-insensitive?)) next) (case (car sre) ((~ - & /) (sre-cset->procedure (sre->cset sre (flag-set? flags ~case-insensitive?)) next)) ((or) (case (length (cdr sre)) ((0) (lambda (cnk init src str i end matches fail) (fail))) ((1) (rec (cadr sre))) (else (let* ((first (rec (cadr sre))) (rest (lp (sre-alternate (cddr sre)) (+ n (sre-count-submatches (cadr sre))) flags next))) (lambda (cnk init src str i end matches fail) (first cnk init src str i end matches (lambda () (rest cnk init src str i end matches fail)))))))) ((w/case) (lp (sre-sequence (cdr sre)) n (flag-clear flags ~case-insensitive?) next)) ((w/nocase) (lp (sre-sequence (cdr sre)) n (flag-join flags ~case-insensitive?) next)) ((w/utf8) (lp (sre-sequence (cdr sre)) n (flag-join flags ~utf8?) next)) ((w/noutf8) (lp (sre-sequence (cdr sre)) n (flag-clear flags ~utf8?) next)) ((seq :) (case (length (cdr sre)) ((0) next) ((1) (rec (cadr sre))) (else (let ((rest (lp (sre-sequence (cddr sre)) (+ n (sre-count-submatches (cadr sre))) flags next))) (lp (cadr sre) n flags rest))))) ((?) (let ((body (rec (sre-sequence (cdr sre))))) (lambda (cnk init src str i end matches fail) (body cnk init src str i end matches (lambda () (next cnk init src str i end matches fail)))))) ((??) (let ((body (rec (sre-sequence (cdr sre))))) (lambda (cnk init src str i end matches fail) (next cnk init src str i end matches (lambda () (body cnk init src str i end matches fail)))))) ((*) (cond ((sre-empty? (sre-sequence (cdr sre))) (error "invalid sre: empty *" sre)) (else (let ((body (rec (list '+ (sre-sequence (cdr sre)))))) (lambda (cnk init src str i end matches fail) (body cnk init src str i end matches (lambda () (next cnk init src str i end matches fail)))))))) ((*?) (cond ((sre-empty? (sre-sequence (cdr sre))) (error "invalid sre: empty *?" sre)) (else (letrec ((body (lp (sre-sequence (cdr sre)) n flags (lambda (cnk init src str i end matches fail) (next cnk init src str i end matches (lambda () (body cnk init src str i end matches fail) )))))) (lambda (cnk init src str i end matches fail) (next cnk init src str i end matches (lambda () (body cnk init src str i end matches fail)))))))) ((+) (cond ((sre-empty? (sre-sequence (cdr sre))) (error "invalid sre: empty +" sre)) (else (letrec ((body (lp (sre-sequence (cdr sre)) n flags (lambda (cnk init src str i end matches fail) (body cnk init src str i end matches (lambda () (next cnk init src str i end matches fail) )))))) body)))) ((=) (rec `(** ,(cadr sre) ,(cadr sre) ,@(cddr sre)))) ((>=) (rec `(** ,(cadr sre) #f ,@(cddr sre)))) ((**) (cond ((or (and (number? (cadr sre)) (number? (caddr sre)) (> (cadr sre) (caddr sre))) (and (not (cadr sre)) (caddr sre))) (lambda (cnk init src str i end matches fail) (fail))) (else (letrec ((from (cadr sre)) (to (caddr sre)) (body-contents (sre-sequence (cdddr sre))) (body (lambda (count) (lp body-contents n flags (lambda (cnk init src str i end matches fail) (if (and to (= count to)) (next cnk init src str i end matches fail) ((body (+ 1 count)) cnk init src str i end matches (lambda () (if (>= count from) (next cnk init src str i end matches fail) (fail)))))))))) (if (and (zero? from) to (zero? to)) next (lambda (cnk init src str i end matches fail) ((body 1) cnk init src str i end matches (lambda () (if (zero? from) (next cnk init src str i end matches fail) (fail)))))))))) ((**?) (cond ((or (and (number? (cadr sre)) (number? (caddr sre)) (> (cadr sre) (caddr sre))) (and (not (cadr sre)) (caddr sre))) (lambda (cnk init src str i end matches fail) (fail))) (else (letrec ((from (cadr sre)) (to (caddr sre)) (body-contents (sre-sequence (cdddr sre))) (body (lambda (count) (lp body-contents n flags (lambda (cnk init src str i end matches fail) (if (< count from) ((body (+ 1 count)) cnk init src str i end matches fail) (next cnk init src str i end matches (lambda () (if (and to (= count to)) (fail) ((body (+ 1 count)) cnk init src str i end matches fail)))))))))) (if (and (zero? from) to (zero? to)) next (lambda (cnk init src str i end matches fail) (if (zero? from) (next cnk init src str i end matches (lambda () ((body 1) cnk init src str i end matches fail))) ((body 1) cnk init src str i end matches fail)))))))) ((word) (rec `(seq bow ,@(cdr sre) eow))) ((word+) (rec `(seq bow (+ (& (or alphanumeric "_") (or ,@(cdr sre)))) eow))) ((posix-string) (rec (string->sre (cadr sre)))) ((look-ahead) (let ((check (lp (sre-sequence (cdr sre)) n flags (lambda (cnk init src str i end matches fail) i)))) (lambda (cnk init src str i end matches fail) (if (check cnk init src str i end matches (lambda () #f)) (next cnk init src str i end matches fail) (fail))))) ((neg-look-ahead) (let ((check (lp (sre-sequence (cdr sre)) n flags (lambda (cnk init src str i end matches fail) i)))) (lambda (cnk init src str i end matches fail) (if (check cnk init src str i end matches (lambda () #f)) (fail) (next cnk init src str i end matches fail))))) ((look-behind neg-look-behind) (let ((check (lp (sre-sequence (cons '(* any) (append (cdr sre) '(eos)))) n flags (lambda (cnk init src str i end matches fail) i)))) (lambda (cnk init src str i end matches fail) (let* ((cnk* (wrap-end-chunker cnk src i)) (str* ((chunker-get-str cnk*) (car init))) (i* (cdr init)) (end* ((chunker-get-end cnk*) (car init)))) (if ((if (eq? (car sre) 'look-behind) (lambda (x) x) not) (check cnk* init (car init) str* i* end* matches (lambda () #f))) (next cnk init src str i end matches fail) (fail)))))) ((atomic) (let ((once (lp (sre-sequence (cdr sre)) n flags (lambda (cnk init src str i end matches fail) i)))) (lambda (cnk init src str i end matches fail) (let ((j (once cnk init src str i end matches (lambda () #f)))) (if j (next cnk init src str j end matches fail) (fail)))))) ((if) (let* ((test-submatches (sre-count-submatches (cadr sre))) (pass (lp (caddr sre) flags (+ n test-submatches) next)) (fail (if (pair? (cdddr sre)) (lp (cadddr sre) (+ n test-submatches (sre-count-submatches (caddr sre))) flags next) (lambda (cnk init src str i end matches fail) (fail))))) (cond ((or (number? (cadr sre)) (symbol? (cadr sre))) (let ((index (if (symbol? (cadr sre)) (cond ((assq (cadr sre) names) => cdr) (else (error "unknown named backref in SRE IF" sre))) (cadr sre)))) (lambda (cnk init src str i end matches fail2) (if (%irregex-match-end-chunk matches index) (pass cnk init src str i end matches fail2) (fail cnk init src str i end matches fail2))))) (else (let ((test (lp (cadr sre) n flags pass))) (lambda (cnk init src str i end matches fail2) (test cnk init src str i end matches (lambda () (fail cnk init src str i end matches fail2))) )))))) ((backref backref-ci) (let ((n (cond ((number? (cadr sre)) (cadr sre)) ((assq (cadr sre) names) => cdr) (else (error "unknown backreference" (cadr sre))))) (compare (if (or (eq? (car sre) 'backref-ci) (flag-set? flags ~case-insensitive?)) string-ci=? string=?))) (lambda (cnk init src str i end matches fail) (let ((s (irregex-match-substring matches n))) (if (not s) (fail) ;; XXXX create an abstract subchunk-compare (let lp ((src src) (str str) (i i) (end end) (j 0) (len (string-length s))) (cond ((<= len (- end i)) (cond ((compare (substring s j (string-length s)) (substring str i (+ i len))) (next cnk init src str (+ i len) end matches fail)) (else (fail)))) (else (cond ((compare (substring s j (+ j (- end i))) (substring str i end)) (let ((src2 ((chunker-get-next cnk) src))) (if src2 (lp src2 ((chunker-get-str cnk) src2) ((chunker-get-start cnk) src2) ((chunker-get-end cnk) src2) (+ j (- end i)) (- len (- end i))) (fail)))) (else (fail))))))))))) ((dsm) (lp (sre-sequence (cdddr sre)) (+ n (cadr sre)) flags next)) (($ submatch) (let ((body (lp (sre-sequence (cdr sre)) (+ n 1) flags (lambda (cnk init src str i end matches fail) (let ((old-source (%irregex-match-end-chunk matches n)) (old-index (%irregex-match-end-index matches n))) (irregex-match-end-chunk-set! matches n src) (irregex-match-end-index-set! matches n i) (next cnk init src str i end matches (lambda () (irregex-match-end-chunk-set! matches n old-source) (irregex-match-end-index-set! matches n old-index) (fail)))))))) (lambda (cnk init src str i end matches fail) (let ((old-source (%irregex-match-start-chunk matches n)) (old-index (%irregex-match-start-index matches n))) (irregex-match-start-chunk-set! matches n src) (irregex-match-start-index-set! matches n i) (body cnk init src str i end matches (lambda () (irregex-match-start-chunk-set! matches n old-source) (irregex-match-start-index-set! matches n old-index) (fail))))))) ((=> submatch-named) (rec `(submatch ,@(cddr sre)))) (else (error "unknown regexp operator" sre))))) ((symbol? sre) (case sre ((any) (lambda (cnk init src str i end matches fail) (if (< i end) (next cnk init src str (+ i 1) end matches fail) (let ((src2 ((chunker-get-next cnk) src))) (if src2 (let ((str2 ((chunker-get-str cnk) src2)) (i2 ((chunker-get-start cnk) src2)) (end2 ((chunker-get-end cnk) src2))) (next cnk init src2 str2 (+ i2 1) end2 matches fail)) (fail)))))) ((nonl) (lambda (cnk init src str i end matches fail) (if (< i end) (if (not (eqv? #\newline (string-ref str i))) (next cnk init src str (+ i 1) end matches fail) (fail)) (let ((src2 ((chunker-get-next cnk) src))) (if src2 (let ((str2 ((chunker-get-str cnk) src2)) (i2 ((chunker-get-start cnk) src2)) (end2 ((chunker-get-end cnk) src2))) (if (not (eqv? #\newline (string-ref str2 i2))) (next cnk init src2 str2 (+ i2 1) end2 matches fail) (fail))) (fail)))))) ((bos) (lambda (cnk init src str i end matches fail) (if (and (eq? src (car init)) (eqv? i (cdr init))) (next cnk init src str i end matches fail) (fail)))) ((bol) (lambda (cnk init src str i end matches fail) (if (or (and (eq? src (car init)) (eqv? i (cdr init))) (and (> i ((chunker-get-start cnk) src)) (eqv? #\newline (string-ref str (- i 1))))) (next cnk init src str i end matches fail) (fail)))) ((bow) (lambda (cnk init src str i end matches fail) (if (and (if (> i ((chunker-get-start cnk) src)) (not (char-alphanumeric? (string-ref str (- i 1)))) (let ((ch (chunker-prev-char cnk init src))) (or (not ch) (not (char-alphanumeric? ch))))) (if (< i end) (char-alphanumeric? (string-ref str i)) (let ((next ((chunker-get-next cnk) src))) (and next (char-alphanumeric? (string-ref ((chunker-get-str cnk) next) ((chunker-get-start cnk) next))))))) (next cnk init src str i end matches fail) (fail)))) ((eos) (lambda (cnk init src str i end matches fail) (if (and (>= i end) (not ((chunker-get-next cnk) src))) (next cnk init src str i end matches fail) (fail)))) ((eol) (lambda (cnk init src str i end matches fail) (if (if (< i end) (eqv? #\newline (string-ref str i)) (let ((src2 ((chunker-get-next cnk) src))) (if (not src2) #t (eqv? #\newline (string-ref ((chunker-get-str cnk) src2) ((chunker-get-start cnk) src2)))))) (next cnk init src str i end matches fail) (fail)))) ((eow) (lambda (cnk init src str i end matches fail) (if (and (if (< i end) (not (char-alphanumeric? (string-ref str i))) (let ((ch (chunker-next-char cnk src))) (or (not ch) (not (char-alphanumeric? ch))))) (if (> i ((chunker-get-start cnk) src)) (char-alphanumeric? (string-ref str (- i 1))) (let ((prev (chunker-prev-char cnk init src))) (or (not prev) (char-alphanumeric? prev))))) (next cnk init src str i end matches fail) (fail)))) ((nwb) ;; non-word-boundary (lambda (cnk init src str i end matches fail) (let ((c1 (if (< i end) (string-ref str i) (chunker-next-char cnk src))) (c2 (if (> i ((chunker-get-start cnk) src)) (string-ref str (- i 1)) (chunker-prev-char cnk init src)))) (if (and c1 c2 (if (char-alphanumeric? c1) (char-alphanumeric? c2) (not (char-alphanumeric? c2)))) (next cnk init src str i end matches fail) (fail))))) ((epsilon) next) (else (let ((cell (assq sre sre-named-definitions))) (if cell (rec (cdr cell)) (error "unknown regexp" sre)))))) ((char? sre) (if (flag-set? flags ~case-insensitive?) ;; case-insensitive (lambda (cnk init src str i end matches fail) (if (>= i end) (let lp ((src2 ((chunker-get-next cnk) src))) (if src2 (let ((str2 ((chunker-get-str cnk) src2)) (i2 ((chunker-get-start cnk) src2)) (end2 ((chunker-get-end cnk) src2))) (if (>= i2 end2) (lp ((chunker-get-next cnk) src2)) (if (char-ci=? sre (string-ref str2 i2)) (next cnk init src2 str2 (+ i2 1) end2 matches fail) (fail)))) (fail))) (if (char-ci=? sre (string-ref str i)) (next cnk init src str (+ i 1) end matches fail) (fail)))) ;; case-sensitive (lambda (cnk init src str i end matches fail) (if (>= i end) (let lp ((src2 ((chunker-get-next cnk) src))) (if src2 (let ((str2 ((chunker-get-str cnk) src2)) (i2 ((chunker-get-start cnk) src2)) (end2 ((chunker-get-end cnk) src2))) (if (>= i2 end2) (lp ((chunker-get-next cnk) src2)) (if (char=? sre (string-ref str2 i2)) (next cnk init src2 str2 (+ i2 1) end2 matches fail) (fail)))) (fail))) (if (char=? sre (string-ref str i)) (next cnk init src str (+ i 1) end matches fail) (fail)))) )) ((string? sre) (rec (sre-sequence (string->list sre))) ;; XXXX reintroduce faster string matching on chunks ;; (if (flag-set? flags ~case-insensitive?) ;; (rec (sre-sequence (string->list sre))) ;; (let ((len (string-length sre))) ;; (lambda (cnk init src str i end matches fail) ;; (if (and (<= (+ i len) end) ;; (%substring=? sre str 0 i len)) ;; (next str (+ i len) matches fail) ;; (fail))))) ) (else (error "unknown regexp" sre))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Character Sets ;; ;; Simple character sets as lists of ranges, as used in the NFA/DFA ;; compilation. This is not especially efficient, but is portable and ;; scalable for any range of character sets. (define (sre-cset->procedure cset next) (lambda (cnk init src str i end matches fail) (if (< i end) (if (cset-contains? cset (string-ref str i)) (next cnk init src str (+ i 1) end matches fail) (fail)) (let ((src2 ((chunker-get-next cnk) src))) (if src2 (let ((str2 ((chunker-get-str cnk) src2)) (i2 ((chunker-get-start cnk) src2)) (end2 ((chunker-get-end cnk) src2))) (if (cset-contains? cset (string-ref str2 i2)) (next cnk init src2 str2 (+ i2 1) end2 matches fail) (fail))) (fail)))))) (define (make-cset) (vector)) (define (range->cset from to) (vector (cons from to))) (define (char->cset ch) (vector (cons ch ch))) (define (cset-empty? cs) (zero? (vector-length cs))) (define (maybe-cset->char cs) (if (and (= (vector-length cs) 1) (char=? (car (vector-ref cs 0)) (cdr (vector-ref cs 0)))) (car (vector-ref cs 0)) cs)) ;; Since csets are sorted, there's only one possible representation of any cset (define cset=? equal?) (define (cset-size cs) (let ((len (vector-length cs))) (let lp ((i 0) (size 0)) (if (= i len) size (lp (+ i 1) (+ size 1 (- (char->integer (cdr (vector-ref cs i))) (char->integer (car (vector-ref cs i)))))))))) (define (cset->plist cs) (let lp ((i (- (vector-length cs) 1)) (res '())) (if (= i -1) res (lp (- i 1) (cons (car (vector-ref cs i)) (cons (cdr (vector-ref cs i)) res)))))) (define (plist->cset ls) (let lp ((ls ls) (res (make-cset))) (if (null? ls) res (lp (cddr ls) (cset-union (range->cset (car ls) (cadr ls)) res))))) (define (string->cset s) (fold (lambda (ch cs) (cset-adjoin cs ch)) (make-cset) (string->list s))) (define (sre->cset sre . o) (let lp ((sre sre) (ci? (and (pair? o) (car o)))) (define (rec sre) (lp sre ci?)) (cond ((pair? sre) (if (string? (car sre)) (if ci? (cset-case-insensitive (string->cset (car sre))) (string->cset (car sre))) (case (car sre) ((~) (cset-complement (fold cset-union (rec (cadr sre)) (map rec (cddr sre))))) ((&) (fold cset-intersection (rec (cadr sre)) (map rec (cddr sre)))) ((-) (fold (lambda (x res) (cset-difference res x)) (rec (cadr sre)) (map rec (cddr sre)))) ((/) (let ((res (plist->cset (sre-flatten-ranges (cdr sre))))) (if ci? (cset-case-insensitive res) res))) ((or) (fold cset-union (rec (cadr sre)) (map rec (cddr sre)))) ((w/case) (lp (sre-alternate (cdr sre)) #f)) ((w/nocase) (lp (sre-alternate (cdr sre)) #t)) (else (error "not a valid sre char-set operator" sre))))) ((char? sre) (if ci? (cset-case-insensitive (range->cset sre sre)) (range->cset sre sre))) ((string? sre) (rec (list sre))) (else (let ((cell (assq sre sre-named-definitions))) (if cell (rec (cdr cell)) (error "not a valid sre char-set" sre))))))) (define (cset->sre cset) (cons '/ (fold (lambda (x res) (cons (car x) (cons (cdr x) res))) '() (vector->list cset)))) (define (cset-contains? cset ch) (let ((len (vector-length cset))) (case len ((0) #f) ((1) (let ((range (vector-ref cset 0))) (and (char<=? ch (cdr range)) (char<=? (car range) ch)))) (else (let lp ((lower 0) (upper len)) (let* ((middle (quotient (+ upper lower) 2)) (range (vector-ref cset middle))) (cond ((char<? (cdr range) ch) (let ((next (+ middle 1))) (and (< next upper) (lp next upper)))) ((char<? ch (car range)) (and (< lower middle) (lp lower middle))) (else #t)))))))) (define (char-ranges-union a b) (cons (if (char<=? (car a) (car b)) (car a) (car b)) (if (char>=? (cdr a) (cdr b)) (cdr a) (cdr b)))) (define (cset-union a b) (let union-range ((a (vector->list a)) (b (vector->list b)) (res '())) (cond ((null? a) (list->vector (reverse (append (reverse b) res)))) ((null? b) (list->vector (reverse (append (reverse a) res)))) (else (let ((a-range (car a)) (b-range (car b))) (cond ;; Can't use next-char here since it will cause an error if we are ;; comparing a cset with the maximum character as high char. ((< (+ (char->integer (cdr a-range)) 1) (char->integer (car b-range))) (union-range (cdr a) b (cons a-range res))) ((> (char->integer (car a-range)) (+ (char->integer (cdr b-range)) 1)) (union-range (cdr b) a (cons b-range res))) ((char>=? (cdr a-range) (car b-range)) (union-range (cons (char-ranges-union a-range b-range) (cdr a)) (cdr b) res)) (else (union-range (cdr a) (cons (char-ranges-union a-range b-range) (cdr b)) res)))))))) (define (cset-adjoin cs ch) (cset-union cs (char->cset ch))) (define (next-char c) (integer->char (+ (char->integer c) 1))) (define (prev-char c) (integer->char (- (char->integer c) 1))) (define (cset-difference a b) (let diff ((a (vector->list a)) (b (vector->list b)) (res '())) (cond ((null? a) (list->vector (reverse res))) ((null? b) (list->vector (append (reverse res) a))) (else (let ((a-range (car a)) (b-range (car b))) (cond ((char<? (cdr a-range) (car b-range)) (diff (cdr a) b (cons a-range res))) ((char>? (car a-range) (cdr b-range)) (diff a (cdr b) res)) ((and (char<=? (car b-range) (car a-range)) (char>=? (cdr b-range) (cdr a-range))) (diff (cdr a) b res)) (else (let ((left (and (char<? (car a-range) (car b-range)) (cons (car a-range) (prev-char (car b-range))))) (right (and (char>? (cdr a-range) (cdr b-range)) (cons (next-char (cdr b-range)) (cdr a-range))))) (diff (if right (cons right (cdr a)) (cdr a)) b (if left (cons left res) res)))))))))) (define (min-char a b) (if (char<? a b) a b)) (define (max-char a b) (if (char<? a b) b a)) (define (cset-intersection a b) (let intersect ((a (vector->list a)) (b (vector->list b)) (res '())) (if (or (null? a) (null? b)) (list->vector (reverse res)) (let ((a-range (car a)) (b-range (car b))) (cond ((char<? (cdr a-range) (car b-range)) (intersect (cdr a) b res)) ((char>? (car a-range) (cdr b-range)) (intersect a (cdr b) res)) (else (let ((result (cons (max-char (car b-range) (car a-range)) (min-char (cdr a-range) (cdr b-range))))) (intersect (if (char>? (cdr a-range) (cdr result)) a (cdr a)) (if (char>? (cdr b-range) (cdr result)) b (cdr b)) (cons result res))))))))) (define (cset-complement a) (cset-difference (sre->cset *all-chars*) a)) ;; This could use some optimization :) (define (cset-case-insensitive a) (let lp ((ls (vector->list a)) (res '())) (cond ((null? ls) (list->vector (reverse res))) ((and (char-alphabetic? (caar ls)) (char-alphabetic? (cdar ls))) (lp (cdr ls) (reverse (vector->list (cset-union (cset-union (list->vector (reverse res)) (vector (car ls))) (range->cset (char-altcase (caar ls)) (char-altcase (cdar ls)))))))) (else (lp (cdr ls) (reverse (vector->list (cset-union (list->vector (reverse res)) (vector (car ls)))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Match and Replace Utilities (define (irregex-fold/fast irx kons knil str . o) (if (not (string? str)) (error "irregex-fold: not a string" str)) (let* ((irx (irregex irx)) (matches (irregex-new-matches irx)) (finish (or (and (pair? o) (car o)) (lambda (i acc) acc))) (start (if (and (pair? o) (pair? (cdr o))) (cadr o) 0)) (end (if (and (pair? o) (pair? (cdr o)) (pair? (cddr o))) (caddr o) (string-length str))) (init-src (list str start end)) (init (cons init-src start))) (if (not (and (integer? start) (exact? start))) (error "irregex-fold: not an exact integer" start)) (if (not (and (integer? end) (exact? end))) (error "irregex-fold: not an exact integer" end)) (irregex-match-chunker-set! matches irregex-basic-string-chunker) (let lp ((src init-src) (i start) (acc knil)) (if (>= i end) (finish i acc) (let ((m (irregex-search/matches irx irregex-basic-string-chunker init src i matches))) (if (not m) (finish i acc) (let ((j (%irregex-match-end-index m 0))) (if (= j i) ;; skip one char forward if we match the empty string (lp (list str (+ j 1) end) (+ j 1) acc) (let ((acc (kons i m acc))) (irregex-reset-matches! matches) ;; no need to continue looping if this is a ;; searcher - it's already consumed the only ;; available match (if (flag-set? (irregex-flags irx) ~searcher?) (finish j acc) (lp (list str j end) j acc))))))))))) (define (irregex-fold irx kons . args) (if (not (procedure? kons)) (error "irregex-fold: not a procedure" kons)) (let ((kons2 (lambda (i m acc) (kons i (irregex-copy-matches m) acc)))) (apply irregex-fold/fast irx kons2 args))) (define (irregex-fold/chunked/fast irx kons knil cnk start . o) (let* ((irx (irregex irx)) (matches (irregex-new-matches irx)) (finish (or (and (pair? o) (car o)) (lambda (src i acc) acc))) (i (if (and (pair? o) (pair? (cdr o))) (cadr o) ((chunker-get-start cnk) start))) (init (cons start i))) (if (not (integer? i)) (error "irregex-fold/chunked: not an integer" i)) (irregex-match-chunker-set! matches cnk) (let lp ((start start) (i i) (acc knil)) (if (not start) (finish start i acc) (let ((m (irregex-search/matches irx cnk init start i matches))) (if (not m) (finish start i acc) (let ((end-src (%irregex-match-end-chunk m 0)) (end-index (%irregex-match-end-index m 0))) (if (and (eq? end-src start) (= end-index i)) (if (>= end-index ((chunker-get-end cnk) end-src )) (let ((next ((chunker-get-next cnk) end-src))) (lp next ((chunker-get-start cnk) next) acc)) (lp end-src (+ end-index 1) acc)) (let ((acc (kons start i m acc))) (irregex-reset-matches! matches) ;; no need to continue looping if this is a ;; searcher - it's already consumed the only ;; available match (if (flag-set? (irregex-flags irx) ~searcher?) (finish end-src end-index acc) (lp end-src end-index acc))))))))))) (define (irregex-fold/chunked irx kons . args) (if (not (procedure? kons)) (error "irregex-fold/chunked: not a procedure" kons)) (let ((kons2 (lambda (s i m acc) (kons s i (irregex-copy-matches m) acc)))) (apply irregex-fold/chunked/fast irx kons2 args))) (define (irregex-replace irx str . o) (if (not (string? str)) (error "irregex-replace: not a string" str)) (let ((m (irregex-search irx str))) (if m (string-cat-reverse (cons (substring str (%irregex-match-end-index m 0) (string-length str)) (append (irregex-apply-match m o) (list (substring str 0 (%irregex-match-start-index m 0))) ))) str))) (define (irregex-replace/all irx str . o) (if (not (string? str)) (error "irregex-replace/all: not a string" str)) (irregex-fold/fast irx (lambda (i m acc) (let ((m-start (%irregex-match-start-index m 0))) (append (irregex-apply-match m o) (if (>= i m-start) acc (cons (substring str i m-start) acc))))) '() str (lambda (i acc) (let ((end (string-length str))) (string-cat-reverse (if (>= i end) acc (cons (substring str i end) acc))))))) (define (irregex-apply-match m ls) (let lp ((ls ls) (res '())) (if (null? ls) res (cond ((integer? (car ls)) (lp (cdr ls) (cons (or (irregex-match-substring m (car ls)) "") res))) ((procedure? (car ls)) (lp (cdr ls) (cons ((car ls) m) res))) ((symbol? (car ls)) (case (car ls) ((pre) (lp (cdr ls) (cons (substring (car (%irregex-match-start-chunk m 0)) 0 (%irregex-match-start-index m 0)) res))) ((post) (let ((str (car (%irregex-match-start-chunk m 0)))) (lp (cdr ls) (cons (substring str (%irregex-match-end-index m 0) (string-length str)) res)))) (else (cond ((assq (car ls) (irregex-match-names m)) => (lambda (x) (lp (cons (cdr x) (cdr ls)) res))) (else (error "unknown match replacement" (car ls))))))) (else (lp (cdr ls) (cons (car ls) res))))))) (define (irregex-extract irx str . o) (if (not (string? str)) (error "irregex-extract: not a string" str)) (apply irregex-fold/fast irx (lambda (i m a) (cons (irregex-match-substring m) a)) '() str (lambda (i a) (reverse a)) o)) (define (irregex-split irx str . o) (if (not (string? str)) (error "irregex-split: not a string" str)) (let ((start (if (pair? o) (car o) 0)) (end (if (and (pair? o) (pair? (cdr o))) (cadr o) (string-length str)))) (irregex-fold/fast irx (lambda (i m a) (if (= i (%irregex-match-start-index m 0)) a (cons (substring str i (%irregex-match-start-index m 0)) a))) '() str (lambda (i a) (reverse (if (= i end) a (cons (substring str i end) a)))) start end)))
false
5b3f643fbe2abcd5a37813de6c86e4e428b87093
27e8f9a818527bd169c03c60ec54eec822780d47
/test/utils.scm
d9530df0950ee7578c3d1f9df8de7c5abdb58500
[ "BSD-3-Clause" ]
permissive
jhidding/pfds
db0e875bb293b21de3160dd1279cddbbb3a9e23f
9755ffc2c59df2a303aa5f0885ecfefae2c67097
refs/heads/master
2021-01-12T14:45:31.068141
2017-12-28T19:02:15
2017-12-28T19:02:15
72,078,412
5
0
null
2016-10-27T06:35:23
2016-10-27T06:35:22
null
UTF-8
Scheme
false
false
252
scm
utils.scm
(library (test utils) (export add1 iota) (import (rnrs (6))) (define (add1 x) (+ x 1)) (define (iota n) (define (recur x) (if (< x n) (cons x (recur (+ x 1))) '())) (assert (integer? n)) (recur 0)) )
false
f40b321e64eca72ffdcc796b1fa4c60eee4dba3e
0855447c3321a493efa9861b3713209e37c03a4c
/g-point/lib/common.ss
261dbf45e990077062cc412e6a525a3a1413956e
[]
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
3,904
ss
common.ss
(library (lib common) (export string-split string-empty? string-join string-trim-left string-trim-right string-trim string-start-with string-end-with string-contain? ->string partial ->> mapcat file-size println eval-from-str) (import (chezscheme)) ;; string (define string-trim-left (lambda (s) (list->string (let loop ([ls (string->list s)]) (cond [(null? ls) '()] [(char-whitespace? (car ls)) (loop (cdr ls))] [else ls]))))) (define string-trim-right (lambda (s) (list->string (reverse (let loop ([ls (reverse (string->list s))]) (cond [(null? ls) '()] [(char-whitespace? (car ls)) (loop (cdr ls))] [else ls])))))) (define string-trim (lambda (s) (string-trim-right (string-trim-left s)))) (define string-start-with (lambda (s start) (let ([slen (string-length s)] [start-len (string-length start)]) (and (>= slen start-len) (equal? (substring s 0 (string-length start)) start))))) (define string-end-with (lambda (s end) (equal? end (let ([len (string-length s)]) (substring s (- len (string-length end)) len))))) ;; (string-contain? "sadfasdgg" "gg") (define (string-contain? s sub) (let ([slen (string-length s)] [sublen (string-length sub)]) (cond [(< slen sublen) #f] [(string-start-with s sub) #t] [else (string-contain? (substring s 1 slen) sub)]))) ;; 将 aa-bb-cc 分割为 '(aa bb cc) (define (string-split str delim) (define in (open-input-string str)) (let recur ((out (open-output-string))) (define c (read-char in)) (cond ((eof-object? c) (list (get-output-string out))) ((char=? c delim) (cons (get-output-string out) (recur (open-output-string)))) (else (write-char c out) (recur out))))) ;; 判断一个字符串是不是空串 (define (string-empty? str) (string=? str "")) ;; 将'(aa bb cc) 合并成 aa-bb-cc (define (string-join strs delim) (fold-left (lambda (rs str) (string-append rs (if (string-empty? rs) "" delim) str)) "" strs)) ;; 将x合理变成字符串 (define (->string x) (with-output-to-string (lambda () (display x)))) (define mapcat (lambda (proc ls) (apply append (map proc ls)))) ;; file相关函数 (define (file-size filename) (call-with-input-file filename (lambda (port) (let loop ((c (read-char port)) (count 0)) (if (eof-object? c) count (loop (read-char port) (+ 1 count))))))) ;; 其他函数 (define-syntax partial (syntax-rules () [(_ (fn arg ...)) (lambda (x) (fn arg ... x))] [(_ fn) (lambda (x) (fn x))])) (define-syntax ->> (lambda (x) (syntax-case x () [(_ e) #'e] [(_ e1 e2 ...) (let unfold ([ls #'(e2 ...)] [rs #'e1]) (cond ((null? ls) rs) (else (unfold (cdr ls) #`((partial #,(car ls)) #,rs)))))]))) (define (println . args) (cond [(null? args) (newline)] [else (begin (display (car args)) (apply println (cdr args)))])) (define eval-from-str (lambda (s) (let ([p (open-input-string s)]) (let f ([x (read p)] [rs #f]) (if (eof-object? x) rs (f (read p) (eval x))))))) )
true
cdc63db723fa9af55eb6bbd9863e73fada7ee1e6
2163cd08beac073044187423727f84510a1dbc34
/documentation/ch4_simple_query.scm
86e53af846dd0582ceae5ff95cf64dbf261529c2
[]
no_license
radiganm/sicp
b40995ad4d681e2950698295df1bbe3a75565528
32a7dcdf5678bb54d07ee3ee8a824842907489f0
refs/heads/master
2021-01-19T10:48:52.579235
2016-12-12T10:47:18
2016-12-12T10:47:18
63,052,284
3
0
null
null
null
null
UTF-8
Scheme
false
false
227
scm
ch4_simple_query.scm
(define (simple-query query-pattern frame-stream) (stream-flatmap (lambda (frame) (stream-append-delayed (find-assertions query-pattern frame) (delay (apply-rules query-pattern frame)))) frame-stream))
false
034c3f65368071bbc7c891291c7ffac7426ac6c7
1ed47579ca9136f3f2b25bda1610c834ab12a386
/sec4/q4.40.scm
360089feed11a1a572a9e198cdeef2b5cdd389f3
[]
no_license
thash/sicp
7e89cf020e2bf5ca50543d10fa89eb1440f700fb
3fc7a87d06eccbe4dcd634406e3b400d9405e9c4
refs/heads/master
2021-05-28T16:29:26.617617
2014-09-15T21:19:23
2014-09-15T21:19:23
3,238,591
0
1
null
null
null
null
UTF-8
Scheme
false
false
1,491
scm
q4.40.scm
;; (1). 階の割り当てが相異なるというrequire式の前後で, 可能性の数はそれぞれいくつか. (load "./sec4.3-nondeterministic") ;(driver-loop) ;;; driver-loopを起動した後に定義する. >>> ココカラ (define (require p) (if (not p) (amb))) (define (an-element-of items) (require (not (null? items))) (amb (car items) (an-element-of (cdr items)))) (define (distinct? items) (cond ((null? items) true) ((null? (cdr items)) true) ((member (car items) (cdr items)) false) (else (distinct? (cdr items))))) ;; http://wqzhang.wordpress.com/2010/04/23/sicp-exercise-4-40/ ;; The following code is about 20 times faster than the original code. (define (multiple-dwelling) (let ((cooper (amb 2 3 4 5)) (miller (amb 1 2 3 4 5))) (require (> miller cooper)) ;; あれ, この条件ならcooper 1-5, miller 2-5じゃね? (let ((fletcher (amb 2 3 4))) (require (not (= (abs (- fletcher cooper)) 1))) (let ((smith (amb 1 2 3 4 5))) (require (not (= (abs (- smith fletcher)) 1))) (let ((baker (amb 1 2 3 4))) (require (distinct? (list baker cooper fletcher miller smith))) (list (list 'baker baker) (list 'cooper cooper) (list 'fletcher fletcher) (list 'miller miller) (list 'smith smith))))))) ;(filter multiple-dwelling (permutation '(1 2 3 4 5))) ;みたいな表示方法つかってた.
false
0524d3b3f4e90150e5c7136267be9a147ea90933
4bba82967988e9a4d87994a65742e2c59bc414f8
/sample/nqueen.scm
253255964f6111378babc6f19901134cfcfa270f
[]
no_license
haramako/cslisp
e1cd4c52a8e6c87fd585d795e8ad01ab48a8c0ec
e5a94884d45c1b9d7c397df247a93003c66a9ee3
refs/heads/master
2021-06-24T05:28:02.531342
2021-04-17T01:39:36
2021-04-17T01:39:36
219,874,404
0
0
null
null
null
null
SHIFT_JIS
Scheme
false
false
8,694
scm
nqueen.scm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Eight Queens with board symmetry ;;; Scheme version ;;; ;;; by T.Shido ;;; August 17, 2005 ;;; last modified: July 18, 2008 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; utilities ;;(require rnrs/base-6) ; vector-for-each ;;(require rnrs/hashtables-6) ; hashtable ;;(require rnrs/control-6) ; when を使うため (%load "macrotest.scm") (%load "lib/prelude.scm") (%load "lib/srfi-1.scm") (%load "minitest.scm") (define (1+ x) (+ x 1)) (define (1- x) (- x 1)) (define (range n) (let loop((i 0) (ls1 '())) (if (= i n) (reverse ls1) (loop (1+ i) (cons i ls1))))) (define (my-remove x ls) (let loop((ls0 ls) (ls1 '())) (if (null? ls0) (reverse ls1) (loop (cdr ls0) (if (eqv? x (car ls0)) ls1 (cons (car ls0) ls1)))))) (define (position x ls) (let loop((ls0 ls) (i 0)) (cond ((null? ls0) #f) ((eqv? x (car ls0)) i) (else (loop (cdr ls0) (1+ i)))))) (define (print-lines . lines) (let loop((ls0 lines)) (when (pair? ls0) (display (car ls0)) (newline) (loop (cdr ls0))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; check if queens conflict each other (define (conflict? q qs) (let loop((inc (1+ q)) (dec (1- q)) (ls0 qs)) (if (null? ls0) #f (let ((c (car ls0))) (or (= c inc) (= c dec) (loop (1+ inc) (1- dec) (cdr ls0))))))) ;;; convert int <-> list (define (q2int n qs) (let loop((ls0 qs) (i 0)) (if (null? ls0) i (loop (cdr ls0) (+ (* i n) (car ls0)))))) (define (int2q n i) (let loop((j i) (ls1 '())) (if (= j 0) ls1 (loop (quotient j n) (cons (modulo j n) ls1))))) ;;; symmetry operations ;; turn 90 degree (define (t90 qs) (let ((n (length qs))) (let loop ((ls1 '()) (i 0)) (if (= i n) ls1 (loop (cons (position i qs) ls1) (1+ i)))))) ;; turn 180 degree (define (t180 qs) (usd (reverse qs))) ;; turn 270 degree (define (t270 qs) (t90 (t180 qs))) ;; up side down (define (usd qs) (let ((n (1- (length qs)))) (map (lambda (x) (- n x)) qs))) ;; reflection on diagonal 1 (define (d1 qs) (reverse (t90 qs))) ;; reflection on diagonal 2 (define (d2 qs) (usd (t90 qs))) ;;; plotting using gnuplot ;; drawing grid (define (draw-grid n) (let ((p (number->string (1+ n)))) (let loop((i 0)) (when (<= i n) (let ((s (number->string (1+ i)))) (print-lines (string-append "set arrow from " s ", 1 to " s ", " p " nohead lt 5") (string-append "set arrow from 1, " s " to " p ", " s " nohead lt 5")) (loop (1+ i))))))) ;; plotting data file of the solution (define (plot-queen len) (let loop((i 0)) (when (< i len) (print-lines (string-append "set title \"solution: " (number->string (1+ i)) "\"") (string-append "plot \"q" (number->string i) ".dat\" title \"queen\" with point pointsize 3") "pause -1 \"Hit return to continue\"") (loop (1+ i))))) ;; writing data files (define (q-write-dat qls) (let loop((i 0) (ls qls)) (when (pair? ls) (with-output-to-file (string-append "q" (number->string i) ".dat") (lambda () (let rec((j 0) (ls1 (car ls))) (when (pair? ls1) (print-lines (string-append (number->string (+ j 1.5)) " " (number->string (+ (car ls1) 1.5)))) (rec (1+ j) (cdr ls1)))))) (loop (1+ i) (cdr ls))))) ;; making a command file for gnuplot (define (qplot n qls) (q-write-dat qls) (with-output-to-file "queen.plt" (lambda () (let ((s (number->string (+ n 2)))) (print-lines "reset" "set size square" (string-append "set xrange [0:" s "]") (string-append "set yrange [0:" s "]")) (draw-grid n) (plot-queen (length qls)))))) ;;; the main function (define (queen n) (let ((qsol (make-eqv-hashtable)) (qlist '())) (letrec ((q-sethash (lambda (qs) ;; registrate on the hash table (let ((qi (q2int n qs))) (when (eq? (hashtable-ref qsol qi 'not-yet) 'not-yet) (for-each (lambda (op) (hashtable-set! qsol (q2int n (op qs)) #f)) (list t90 t180 t270 reverse usd d1 d2)) (hashtable-set! qsol qi #t))))) (q-add (lambda (qs i pool) ;; adding new queen (if (= i n) (q-sethash qs) (for-each (lambda (x) (or (conflict? x qs) (q-add (cons x qs) (1+ i) (my-remove x pool)))) pool))))) (q-add '() 0 (range n))) (let-values (((key value) (hashtable-entries qsol))) ; pick up distinct solutions (vector-for-each (lambda (k v) (when v (set! qlist (cons (int2q n k) qlist)))) key value)) ;(plot n qlist) ;; (qplot n qlist) ;; plotting the distinct solutions (length qlist))) ;; make my own memv as memv in MzScheme require a 'proper list' (define (my-memv obj ls) (cond ((null? ls) #f) ((= obj (car ls)) #t) (else (my-memv obj (cdr ls))))) ;;; the main function to find symmetrical solutions (define (queen_sym n) (let ((qsol (make-eqv-hashtable)) (qlist '())) (letrec ((q-sethash (lambda (qs) ;; registrate on the hash table (let ((qi (q2int n qs))) (when (not (hashtable-contains? qsol qi)) (let ((ls_sym (map (lambda (op) (q2int n (op qs))) `(,t90 ,t180 ,t270 ,reverse ,usd ,d1 ,d2)))) (when (my-memv qi ls_sym) (for-each (lambda (v) (hashtable-set! qsol v #f)) ls_sym) (hashtable-set! qsol qi #t))))))) (q-add (lambda (qs i pool) ;; adding new queen (if (= i n) (q-sethash qs) (for-each (lambda (x) (or (conflict? x qs) (q-add (cons x qs) (1+ i) (my-remove x pool)))) pool))))) (q-add '() 0 (range n))) (let-values (((key value) (hashtable-entries qsol))) ; pick up distinct solutions (vector-for-each (lambda (k v) (when v (set! qlist (cons (int2q n k) qlist)))) key value)) (qplot qlist) ;; plotting the distinct solutions (length qlist))) ;; for my lisp (define (make-eqv-hashtable) (list-copy '(()))) (define (hashtable-ref hash key def) (let ((val (assoc key (cdr hash)))) (if val (cdr val) def))) (define (hashtable-set! hash key val) (set-cdr! hash (alist-cons key val (alist-delete! key (cdr hash))))) (define (hashtable-contains? hash key) (assoc key (cdr hash))) (define (hashtable-keys hash) (let recur ((hash (cdr hash))) (if (null? hash) '() (cons (caar hash) (recur (cdr hash)))))) (define (hashtable-vals hash) (let recur ((hash (cdr hash))) (if (null? hash) '() (cons (cdar hash) (recur (cdr hash)))))) (define (hashtable-entries hash) (values (hashtable-keys hash) (hashtable-vals hash))) (define (range n) (let loop ((lis '()) (n n)) (if (zero? n) lis (loop (cons (- n 1) lis) (- n 1))))) (define (vector-for-each f . lis) (let loop ((lis lis)) (when (pair? (car lis)) (apply f (map car lis)) (loop (map cdr lis))))) (define-syntax for (syntax-rules () ((_ x lis body ...) (for-each (lambda (x) body ...) lis)))) (define (plot n qs) (for q qs (puts (make-string 80 #\=)) (for a q (puts (string-append (make-string a #\.) "Q" (make-string (- n a 1) #\.))))) (puts (make-string 80 #\=))) (assert 1 (queen 4)) (assert 2 (queen 5)) (assert 1 (queen 6)) (assert 6 (queen 7)) (assert 12 (queen 8)) (minitest-finish)
true
adae42cc80ae1ff8bd9e137dda3058273fbd7a1c
37245ece3c767e9434a93a01c2137106e2d58b2a
/src/stdlibs.scm
97577942b456ecfb3c92f8a15d98fcc25d41f3ee
[ "MIT" ]
permissive
mnieper/unsyntax
7ef93a1fff30f20a2c3341156c719f6313341216
144772eeef4a812dd79515b67010d33ad2e7e890
refs/heads/master
2023-07-22T19:13:48.602312
2021-09-01T11:15:54
2021-09-01T11:15:54
296,947,908
12
0
null
null
null
null
UTF-8
Scheme
false
false
2,161
scm
stdlibs.scm
;; Copyright © Marc Nieper-Wißkirchen (2020). ;; This file is part of Unsyntax. ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation files ;; (the "Software"), to deal in the Software without restriction, ;; including without limitation the rights to use, copy, modify, merge, ;; publish, distribute, sublicense, and/or sell copies of the Software, ;; and to permit persons to whom the Software is furnished to do so, ;; subject to the following conditions: ;; The above copyright notice and this permission notice (including the ;; next paragraph) shall be included in all copies or substantial ;; portions of the Software. ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS ;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN ;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. (rnrs records syntactic) (rnrs records procedural) (rnrs records inspection) (scheme base) (scheme case-lambda) (scheme char) (scheme complex) (scheme cxr) (scheme eval) (scheme file) (scheme inexact) (scheme lazy) (scheme load) (scheme process-context) (scheme read) (scheme repl) (scheme r5rs) (scheme time) (scheme write) (srfi 1) (srfi 2) (srfi 8) (srfi 27) (srfi 28) (srfi 37) (srfi 59) (srfi 64) (srfi 111) (srfi 125) (srfi 128) (srfi 139) (srfi 158) (srfi 188) (srfi 190) (srfi 206) (srfi 211 define-macro) (srfi 211 explicit-renaming) (srfi 211 identifier-syntax) (srfi 211 implicit-renaming) (srfi 211 low-level) (srfi 211 syntactic-closures) (srfi 211 syntax-case) (srfi 211 syntax-parameter) (srfi 211 variable-transformer) (srfi 211 with-ellipsis) (srfi 212) (srfi 213) (unsyntax) (alias (srfi 1) (scheme list)) (alias (srfi 111) (scheme box)) (alias (srfi 125) (scheme hash-table)) (alias (srfi 128) (scheme comparator)) (auxiliary-syntax (srfi 206 all))
false
0f6c8a54d32970cdc1c2540076fe4ecfdaf0dc68
4f17c70ae149426a60a9278c132d5be187329422
/scheme/refimpl/arithmetic/impl/rational.scm
629b2319799dcf7a087f719b95b0a03277f687e5
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ]
permissive
okuoku/yuni-core
8da5e60b2538c79ae0f9d3836740c54d904e0da4
c709d7967bcf856bdbfa637f771652feb1d92625
refs/heads/master
2020-04-05T23:41:09.435685
2011-01-12T15:54:23
2011-01-12T15:54:23
889,749
2
0
null
null
null
null
UTF-8
Scheme
false
false
1,843
scm
rational.scm
(library (yuni scheme refimpl arithmetic impl rational) (export rational- rational-negative? rational->string rational=? rational/ rational+ rational* rational<? ) (import (yuni scheme refimpl arithmetic backend) (yuni scheme refimpl arithmetic impl integer) (yuni scheme refimpl arithmetic impl ratnum)) ; This file is part of the reference implementation of the R6RS Arithmetic SRFI. ; See file COPYING. ; Generic rational arithmetic arithmetic built on top of ; generic integer arithmetic. (define (exact-rational? p) (or (exact-integer? p) (ratnum? p))) (define (rational-numerator p) (if (ratnum? p) (ratnum-numerator p) p)) (define (rational-denominator p) (if (ratnum? p) (ratnum-denominator p) (core->integer 1))) (define (rational->ratnum r) (cond ((exact-integer? r) (make-unreduced-ratnum r (core->integer 1))) ((ratnum? r) r))) (define (make-r*r->v op) (lambda (p q) (op (rational->ratnum p) (rational->ratnum q)))) (define rational* (make-r*r->v ratnum*)) (define rational/ (make-r*r->v ratnum/)) (define rational+ (make-r*r->v ratnum+)) (define rational- (make-r*r->v ratnum-)) (define rational<? (make-r*r->v ratnum<?)) (define rational=? (make-r*r->v ratnum=?)) (define (make-r->v op) (lambda (p) (op (rational->ratnum p)))) (define rational-truncate (make-r->v ratnum-truncate)) (define rational-floor (make-r->v ratnum-floor)) (define rational-positive? (make-r->v ratnum-positive?)) (define rational-negative? (make-r->v ratnum-negative?)) (define (rational->string b r) (cond ((exact-integer? b) (integer->string b r)) ((ratnum? b) (ratnum->string b r)))) )
false
bba69e2c8bbc3e45933b4d8a1cb61a124a881898
d074b9a2169d667227f0642c76d332c6d517f1ba
/sicp/ch_2/exercise.2.38.scm
3daeb5368d913b93daabcce9d1afb491ba4b13be
[]
no_license
zenspider/schemers
4d0390553dda5f46bd486d146ad5eac0ba74cbb4
2939ca553ac79013a4c3aaaec812c1bad3933b16
refs/heads/master
2020-12-02T18:27:37.261206
2019-07-14T15:27:42
2019-07-14T15:27:42
26,163,837
7
0
null
null
null
null
UTF-8
Scheme
false
false
1,242
scm
exercise.2.38.scm
#lang racket/base (require "../lib/test.rkt") (require "../lib/myutils.scm") ;; Exercise 2.38 ;; The `accumulate' procedure is also known as `fold-right', because ;; it combines the first element of the sequence with the result of ;; combining all the elements to the right. There is also a ;; `fold-left', which is similar to `fold-right', except that it ;; combines elements working in the opposite direction: ;; (define (fold-left op initial sequence) ;; (define (iter result rest) ;; (if (null? rest) ;; result ;; (iter (op result (car rest)) ;; (cdr rest)))) ;; (iter initial sequence)) ;; What are the values of ;; ;; (fold-right / 1 (list 1 2 3)) ;; ;; (fold-left / 1 (list 1 2 3)) ;; ;; (fold-right list nil (list 1 2 3)) ;; ;; (fold-left list nil (list 1 2 3)) ;; ;; Give a property that `op' should satisfy to guarantee that ;; `fold-right' and `fold-left' will produce the same values for any ;; sequence. (assert-equal (/ 3 2 1 1) (fold-right / 1 (list 1 2 3))) (assert-equal (/ 1 1 2 3) (fold-left / 1 (list 1 2 3))) (assert-equal '(1 (2 (3 ()))) (fold-right list null (list 1 2 3))) (assert-equal '(((() 1) 2) 3) (fold-left list null (list 1 2 3))) (done)
false
d8127ec26a32cc27013d5d553711acbc200dc9b8
93979d95c1bd6c56e1a2b13d4a29fb37a072fb72
/hmac.scm
a8a12b05d8385d23273141f35d276d1bf5aaa86f
[ "MIT" ]
permissive
theschemer/hashing
1b6abf391351a832225472f95fc294ad3ebae4bb
abdbaf7ce8324540e324acf1ecff670b170ae10d
refs/heads/master
2021-05-05T21:50:14.133424
2017-12-24T20:21:09
2017-12-24T20:50:40
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,608
scm
hmac.scm
;; -*- mode: scheme; coding: utf-8 -*- ;; Copyright © 2009, 2012, 2017 Göran Weinholt <[email protected]> ;; SPDX-License-Identifier: MIT ;; Permission is hereby granted, free of charge, to any person obtaining a ;; copy of this software and associated documentation files (the "Software"), ;; to deal in the Software without restriction, including without limitation ;; the rights to use, copy, modify, merge, publish, distribute, sublicense, ;; and/or sell copies of the Software, and to permit persons to whom the ;; Software is furnished to do so, subject to the following conditions: ;; The above copyright notice and this permission notice shall be included in ;; all copies or substantial portions of the Software. ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ;; THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;; DEALINGS IN THE SOFTWARE. #!r6rs ;; RFC 2104, FIPS-198-1. (library (hashing hmac) (export make-hmac) (import (rnrs)) ;; Returns a procedure that calculates the HMAC given a secret and ;; data (both of which are bytevectors). (define (make-hmac block-length hash ->bytevector make-hash update! finish! clear!) (lambda (secret . data) (let lp ((secret secret)) (if (> (bytevector-length secret) block-length) (lp (->bytevector (hash secret))) (let ((k-ipad (make-bytevector block-length 0)) (k-opad (make-bytevector block-length 0))) (bytevector-copy! secret 0 k-ipad 0 (bytevector-length secret)) (bytevector-copy! secret 0 k-opad 0 (bytevector-length secret)) (do ((i 0 (fx+ i 1))) ((fx=? i block-length)) (bytevector-u8-set! k-ipad i (fxxor #x36 (bytevector-u8-ref k-ipad i))) (bytevector-u8-set! k-opad i (fxxor #x5c (bytevector-u8-ref k-opad i)))) (let ((state (make-hash))) (update! state k-ipad) (for-each (lambda (d) (update! state d)) data) (finish! state) (let ((digest (->bytevector state))) (clear! state) (update! state k-opad) (update! state digest) (finish! state) state))))))))
false
6d452320f829f14ebd67238dae60ed6a55a402a1
6c69f4c35bcecb0ab4642d75e01183d2ee4de8b9
/src/transport/file-io.scm
5db2248fc6a92fc47d5e057f8516fc05d1464f13
[ "MIT" ]
permissive
Lattay/chicken-meta-rpc
2c488928e7f288eef9bb30acc303b379e4ad24b8
a633b9870af384bc7926334156632a26159af624
refs/heads/master
2020-07-12T21:56:48.065087
2019-11-26T21:18:50
2019-11-26T21:18:50
204,916,209
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,295
scm
file-io.scm
; server side (define-class <transport-server-file> (<transport-server>) ((ready #f) (in #f) (out #f))) (define-method (multiple-client? (serv <transport-server-file>)) #f) (define-method (one-shot? (serv <transport-server-file>)) #f) (define-method (ready? (serv <transport-server-file>)) (slot-value serv 'ready)) (define-method (shutdown (serv <transport-server-file>)) (let ((in (slot-value serv 'in)) (out (slot-value serv 'out))) (unless (port-closed? in) (close-input-port in)) (unless (port-closed? out) (close-output-port out)))) ; fifo specific (define-class <transport-server-fifo> (<transport-server-file>) (infile outfile)) (define (make-transport-server-fifo infile outfile) (make <transport-server-fifo> 'infile infile 'outfile 'outfile)) (define-method (accept (serv <transport-server-fifo>)) (set! (slot-value serv 'ready) #f) (let ((in (open-input-file (slot-value serv 'infile))) (out (open-output-file (slot-value serv 'outfile)))) (set! (slot-value serv 'in) in) (set! (slot-value serv 'out) out) (values in out))) ; stdio specific (define-class <transport-server-stdio> (<transport-server-file>)) (define (make-transport-server-stdio) (make <transport-server-fifo>)) (define-method (accept (serv <transport-server-stdio>)) (set! (slot-value serv 'ready) #f) (let ((in (current-input-port)) (out (current-output-port))) (set! (slot-value serv 'in) in) (set! (slot-value serv 'out) out) (values in out))) ; client side (define-class <transport-client-file> (<transport-client>)) (define-method (one-shot? (cli <transport-client-file>)) #f) (define-class <transport-client-fifo> (<transport-client-file>) (infile outfile)) (define (make-transport-client-fifo infile outfile) (make <transport-client-fifo> 'infile infile 'outfile 'outfile)) (define-method (connect (cli <transport-client-fifo>)) (values (open-input-file (slot-value cli 'infile)) (open-output-file (slot-value cli 'outfile)))) ; stdio specific (define-class <transport-client-stdio> (<transport-client-file>)) (define (make-transport-client-stdio) (make <transport-client-stdio>)) (define-method (connect (cli <transport-client-stdio>)) (values (current-input-port) (current-output-port)))
false
bd09dc01f1ca3409664f7aa8b45a8e9a1881fc03
522ae461262a3c166ca95f1ece562258f9fe228a
/constance.scm
dd772b1c97ecc50f2404f592435798e06c9756fb
[]
no_license
localchart/constance
7f567009298dc321255407ad0f9c79a4e9e4a49a
c90c3235415332071bd2f92957cf5d0f2028a772
refs/heads/master
2021-01-18T10:55:55.006030
2011-08-17T02:32:45
2011-08-17T02:32:45
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
916
scm
constance.scm
(define-syntax define-constance (lambda (e rename c) (let* ((constance-name (cadr e)) (c-headers (caddr e)) (pairs (cadddr e)) (results (get-value-pairs-from-c constance-name c-headers pairs))) `(,(rename 'begin) ,@(map (lambda (pair) `(,(rename 'define) ,(string->symbol (first pair)) ,(second pair))) results))))) ;; (define-constance constance-name ;; (headers ...) ;; ((id c-macro) ;; (id2 c-macro2) ;; ...)) ;; => ;; (begin (define id value) ;; (define id2 value2)) ;; where value is the value of c-macro in the environment of a c program with ;; the header files specified by c-headers ;; NOTE: constance-name MUST BE UNIQUE within a project (specifically, amongst ;; any DEFINE-CONSTANCE forms which have the same working directory at macro ;; expansion time
true
cc45a80687da393578f63e2095b397a5ae40c2d8
7666204be35fcbc664e29fd0742a18841a7b601d
/code/1.3.4.scm
0e04a06d110581111b67a4f6d3e88c2a52aed44e
[]
no_license
cosail/sicp
b8a78932e40bd1a54415e50312e911d558f893eb
3ff79fd94eda81c315a1cee0165cec3c4dbcc43c
refs/heads/master
2021-01-18T04:47:30.692237
2014-01-06T13:32:54
2014-01-06T13:32:54
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
561
scm
1.3.4.scm
#lang racket (define (fixed-point f x) (define tolerance 0.000001) (define (close-enough? x y) (< (abs (- x y)) tolerance)) (define (try t) (define v (f t)) (if (close-enough? t v) t (try v))) (try x)) (define (average x y) (/ (+ x y) 2.0)) (define (average-damp f) (lambda (x) (average x (f x)))) (define (sqrt-new x) (fixed-point (average-damp (lambda (y) (/ x y))) 1.0)) ;(sqrt-new 5.0) (define (cube-root x) (fixed-point (average-damp (lambda (y) (/ x (* y y)))) 1.0)) ;(cube-root 8.0)
false
70cb1a3819936b01d06e665609f920964bc2374d
a2c4df92ef1d8877d7476ee40a73f8b3da08cf81
/ch11-2-test.scm
74ec803b39b79686759d620e4281992a55b7e7a4
[]
no_license
naoyat/reading-paip
959d0ec42b86bc01fe81dcc3589e3182e92a05d9
739fde75073af36567fcbdf3ee97e221b0f87c8a
refs/heads/master
2020-05-20T04:56:17.375890
2009-04-21T20:01:01
2009-04-21T20:01:01
176,530
1
0
null
null
null
null
UTF-8
Scheme
false
false
3,418
scm
ch11-2-test.scm
(require "./ch11-2") (use gauche.test) (test-start "§ 11.2") ;; ;; for buggy version ;; (test-section "p.352 - pat-match") (test* "" '((?y . 1) (?x . 2)) (pat-match '(?x + ?y) '(2 + 1)) ) (test-section "p.352 - unify<0>") (test* "" '((?y . 1) (?x . 2)) (unify0 '(?x + 1) '(2 + ?y)) ) (test* "" '((?x . ?y)) (unify0 '(f ?x) '(f ?y)) ) (test* "" '((?y . 0) (?x . ?y) (?a . ?x)) (unify0 '(?a + ?a = 0) '(?x + ?y = ?y)) ) ;(test* "" '(0 + 0 = 0) (unifier '(?a + ?a = 0) '(?x + ?y = ?y)) ) ;(test* "" '(2 + 2 = 2) (unifier '(?a + ?a = 2) '(?x + ?y = ?y)) ) (test-section "p.354 - unify<0> is buggy!") (test* "" '((?y . 1) (?x . 2)) (unify0 '(?x + 1) '(2 + ?y)) ) ;; again (test* "" '((?x . ?y)) (unify0 '?x '?y)) (test* "" '((?y . ?y) (?x . ?y)) (unify0 '(?x ?x) '(?y ?y)) ) ;(test* "error" '() (unify '(?x ?x ?x) '(?y ?y ?y))) (test-section "p.355 - unify<1>") (test* "" '((?x . ?y)) (unify1 '(?x ?x) '(?y ?y))) (test* "" '((?x . ?y)) (unify1 '(?x ?x ?x) '(?y ?y ?y))) (test* "" '((?y . ?x) (?x . ?y)) (unify1 '(?x ?y) '(?y ?x))) ;(test* "" '() (unify1 '(?x ?y a) '(?y ?x ?x))) (test-section "p.355 - unify<2>") (test* "" '((?x . ?y)) (unify2 '(?x ?x) '(?y ?y))) (test* "" '((?x . ?y)) (unify2 '(?x ?x ?x) '(?y ?y ?y))) ;(test* "" '((?y . ?x) (?x . ?y)) (unify '(?x ?y) '(?y ?x))) (test* "" '((?x . ?y)) (unify2 '(?x ?y) '(?y ?x))) (test* "" '((?y . a) (?x . ?y)) (unify2 '(?x ?y a) '(?y ?x ?x))) (test* "problem" '((?x f ?x)) (unify2 '?x '(f ?x))) ;; must bean ((?x . ((f ?x)))) (test-section "p.356 - unify<3>") (test* "" '((?x . ?y)) (unify '(?x ?x) '(?y ?y))) (test* "" '((?x . ?y)) (unify '(?x ?x ?x) '(?y ?y ?y))) (test* "" '((?x . ?y)) (unify '(?x ?y) '(?y ?x))) (test* "" '((?y . a) (?x . ?y)) (unify '(?x ?y a) '(?y ?x ?x))) (test* "infinite loop" '() (unify '?x '(f ?x))) ;; must bean ((?x . ((f ?x)))) (test-section "p.357") (test* "" '((?y . a) (?x . ?y)) (unify '(?x ?y a) '(?y ?x ?x))) (test* "" '() (unify '?x '(f ?x))) (test* "" '() (unify '(?x ?y) '((f ?y) (f ?x)))) (test* "" '() (unify '(?x ?y ?z) '((?y ?z) (?x ?z) (?x ?y)))) (test* "" '((#t . #t)) (unify 'a 'a)) (test-section "p.357 - unifier") (test* "" '(a a a) (unifier '(?x ?y a) '(?y ?x ?x))) (test* "" '((?a * 5 ^ 2) + (4 * 5) + 3) (unifier '((?a * ?x ^ 2) + (?b * ?x) + ?c) '(?z + (4 * 5) + 3))) (test-section "p.358 - if *occurs-check* is false") (set! *occurs-check* #f) (test* "" '((?x f ?x)) (unify '?x '(f ?x))) (test* "" '((?y f ?x) (?x f ?y)) (unify '(?x ?y) '((f ?y) (f ?x)))) (test* "" '((?z ?x ?y) (?y ?x ?z) (?x ?y ?z)) (unify '(?x ?y ?z) '((?y ?z) (?x ?z) (?x ?y)))) (set! *occurs-check* #t) ;; (test-section "") (<- (likes Kim Robin)) (<- (likes Sandy Lee)) (<- (likes Sandy Kim)) (<- (likes Robin cats)) (<- (likes Sandy ?x) (likes ?x cats)) (<- (likes Kim ?x) (likes ?x Lee) (likes ?x Kim)) (<- (likes ?x ?x)) (<- (member ?item (?item . ?rest))) (<- (member ?item (?x . ?rest)) (member ?item ?rest)) (test-end) #;(test* "" '(((?who . Lee)) ((?who . Kim)) ((?x2856 . Robin) (?who . ?x2856)) ((?x2860 . cats) (?x2857 . cats) (?x2856 . Sandy) (?who . ?x2856)) ((?x2865 . cats) (?x2856 . ?x2865) (?who . ?x2856)) (??who . Sandy) (?x2867 . Sandy)) (?- (likes Sandy ?who)) ) (?- (likes Sandy ?who)) (?- (likes ?who Sandy)) (?- (likes Robin Lee)) (?- (likes ?x ?y) (likes ?y ?x)) (?- (member 2 (1 2 3))) (?- (member 2 (1 2 3 2 1))) ;(?- (member 2 ?list)) ;(?- (member ?item ?list))
false
ee8ab525a7283e3dd603fe881b7738b44a3238a9
cdab7b6efc54afca468ee90c1cd68fee67955caa
/chap1/hash.scm
804a5f25ae3017fe007ce6772b18cc61d1634714
[]
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
234
scm
hash.scm
(define variables-table (make-hash-table)) (hash-table-push! variables-table + 3) (ref variables-table +) (define lookup3 (lambda (id env) (ref variables-table id))) (hash-table-push! variables-table + 3) (lookup3 + '())
false
1414f4f3547f326d6ae1b88169cba8b2c14031ce
6c6cf6e4b77640825c2457e54052a56d5de6f4d2
/ch3/3_69-triples.scm
ed8b20c9b4b998e6cdc20be4d5c6dcb532db652f
[]
no_license
leonacwa/sicp
a469c7bc96e0c47e4658dccd7c5309350090a746
d880b482d8027b7111678eff8d1c848e156d5374
refs/heads/master
2018-12-28T07:20:30.118868
2015-02-07T16:40:10
2015-02-07T16:40:10
11,738,761
0
0
null
null
null
null
UTF-8
Scheme
false
false
296
scm
3_69-triples.scm
; ex 3.69 triples ; triples (define (triples s t u) (cons-stream (list (stream-car s) (stream-car t) (stream-car u)) (interleave (stream-map (lambda (x) (list (stream-car s) (car x) (cadr x))) (pairs t (stream-cdr u))) (triples (stream-cdr s) (stream-cdr t) (stream-cdr u)))))
false
06bbc2fcd93e445d7515e994cdca3d603b54dacf
42814fb3168a44672c8d69dbb56ac2e8898f042e
/private/gui-struct.ss
66bc507149c4faefe161c8f22168ae9357c63d35
[]
no_license
dyoo/gui-world
520096c3e66b904a9b361fe852be3c5e2ab35e88
41e52a1c4686cc6ee4014bf7ded2fcbec337f6eb
refs/heads/master
2016-09-06T14:54:13.316419
2009-04-02T19:10:18
2009-04-02T19:10:18
159,708
1
0
null
null
null
null
UTF-8
Scheme
false
false
12,704
ss
gui-struct.ss
#lang scheme/base (require scheme/contract htdp/image htdp/error scheme/match "prim.ss" (only-in lang/htdp-beginner image?)) (define-struct elt () #:prefab) ;; An gui element is one of the following: (define-struct (row-elt elt) (elts) #:prefab) (define-struct (column-elt elt) (elts) #:prefab) (define-struct (box-group-elt elt) (val-f elt enabled?-f) #:prefab) (define-struct (displayable-elt elt) (val-f) #:prefab) (define-struct (canvas-elt elt) (scene-f callback) #:prefab) (define-struct (button-elt elt) (val-f callback enabled?-f) #:prefab) (define-struct (drop-down-elt elt) (val-f choices-f callback enabled?-f) #:prefab) (define-struct (text-field-elt elt) (val-f callback enabled?-f) #:prefab) (define-struct (slider-elt elt) (val-f min-f max-f callback enabled?-f) #:prefab) (define-struct (checkbox-elt elt) (label-f val-f callback enabled?-f) #:prefab) (define world/c any/c) (define subworld/c any/c) (define (gvalueof t) (world/c . -> . t)) (define (gvalueof* t) (or/c (world/c . -> . t) t)) (define (gcallbackof t) (world/c t . -> . world/c)) (define (gcallbackof-2 t1 t2) (world/c t1 t2 . -> . world/c)) (define callback/c (world/c . -> . world/c)) ;; displayable?: any -> boolean (define (displayable? datum) (or (string? datum) (symbol? datum) (number? datum) (boolean? datum))) ;; displayable->string: displayable -> string (define (displayable->string datum) (match datum [(? string?) datum] [(? symbol?) (symbol->string datum)] [(? number?) (number->string datum)] [(? boolean?) (cond [datum "true"] [else "false"])])) ;; scene?: any -> boolean (define (scene? i) (and (image? i) (= 0 (pinhole-x i)) (= 0 (pinhole-y i)))) ;; wrap-primitive: (any/c -> boolean) (or/c X (world -> X)) -> (world -> X) (define (wrap-primitive a-name a-pred a-gvalue) (cond [(a-pred a-gvalue) (lambda (a-world) a-gvalue)] [(procedure? a-gvalue) (check-fun-res a-gvalue a-pred (object-name a-pred))] [else (gw-error a-name "Expected either a <~s> or a (world -> ~s) function, but got ~s instead" (object-name a-pred) (object-name a-pred) a-gvalue)])) (define-struct (gui-world-exn exn) ()) (define (gw-error name fmt . args) (raise (make-gui-world-exn (string-append (format "~a: " name) (apply format fmt args)) (current-continuation-marks)))) (define (row . elts) (make-row-elt (coerse-primitive-types-to-elts elts))) (define (col . elts) (make-column-elt (coerse-primitive-types-to-elts elts))) (define (message a-gvalue) (make-displayable-elt (wrap-primitive 'message displayable? a-gvalue))) (define (button/enabled val callback [enabled #t]) (make-button-elt (wrap-primitive 'button/enabled displayable? val) callback (wrap-primitive 'button/enabled boolean? enabled))) (define (button val callback) (make-button-elt (wrap-primitive 'button displayable? val) callback (wrap-primitive 'button boolean? #t))) (define (slider/enabled val min max callback [enabled? #t]) (make-slider-elt (wrap-primitive 'slider/enabled number? val) (wrap-primitive 'slider/enabled number? min) (wrap-primitive 'slider/enabled number? max) callback (wrap-primitive 'slider/enabled boolean? enabled?))) (define (slider val min max callback) (make-slider-elt (wrap-primitive 'slider number? val) (wrap-primitive 'slider number? min) (wrap-primitive 'slider number? max) callback (wrap-primitive 'slider boolean? #t))) (define (drop-down/enabled val choices callback [enabled? #t]) (make-drop-down-elt (wrap-primitive 'drop-down/enabled displayable? val) (wrap-primitive 'drop-down/enabled (flat-contract-predicate (listof displayable?)) choices) callback (wrap-primitive 'drop-down/enabled boolean? enabled?))) (define (drop-down val choices callback) (make-drop-down-elt (wrap-primitive 'drop-down displayable? val) (wrap-primitive 'drop-down (flat-contract-predicate (listof displayable?)) choices) callback (wrap-primitive 'drop-down boolean? #t))) (define (text-field/enabled val callback [enabled? #t]) (make-text-field-elt (wrap-primitive 'text-field/enabled displayable? val) callback (wrap-primitive 'text-field/enabled boolean? enabled?))) (define (text-field val callback) (make-text-field-elt (wrap-primitive 'text-field displayable? val) callback (wrap-primitive 'text-field boolean? #t))) (define (canvas/callback a-scene [callback (lambda (world x y) world)]) (make-canvas-elt (wrap-primitive 'canvas/callback scene? a-scene) callback)) (define (canvas a-scene) (make-canvas-elt (wrap-primitive 'canvas scene? a-scene) (lambda (world x y) world))) (define (box-group/enabled val a-gui [enabled? #t]) (make-box-group-elt (wrap-primitive 'box-group/enabled displayable? val) (coerse-primitive-to-elt a-gui) (wrap-primitive 'box-group/enabled boolean? enabled?))) (define (box-group val a-gui) (make-box-group-elt (wrap-primitive 'box-group displayable? val) (coerse-primitive-to-elt a-gui) (wrap-primitive 'box-group boolean? #t))) (define (checkbox/enabled label val callback [enabled? #t]) (make-checkbox-elt (wrap-primitive 'checkbox/enabled displayable? label) (wrap-primitive 'checkbox/enabled boolean? val) callback (wrap-primitive 'checkbox/enabled boolean? enabled?))) (define (checkbox label val callback) (make-checkbox-elt (wrap-primitive 'checkbox displayable? label) (wrap-primitive 'checkbox boolean? val) callback (wrap-primitive 'checkbox boolean? #t))) ;; coerse-primitive-types-to-elts: (listof (or/c elt displayable scene)) -> (listof elt) ;; Helper to turn displayables into displayable-elts, and images into image-elts. (define (coerse-primitive-types-to-elts elts) (map coerse-primitive-to-elt elts)) ;; coerse-primitive-type-to-elt: (or/c elt displayable scene) -> elt (define (coerse-primitive-to-elt an-elt) (cond [(displayable? an-elt) (message an-elt)] [(scene? an-elt) (canvas an-elt)] [else an-elt])) ;; project/inject/gui: elt (world -> sub-world) (world sub-world -> world) -> elt ;; Scoping operator on structure. (define (project/inject/gui an-elt w->s s->w) (match an-elt [(struct row-elt (elts)) (make-row-elt (map (lambda (a-subelt) (project/inject/gui a-subelt w->s s->w)) elts))] [(struct column-elt (elts)) (make-column-elt (map (lambda (a-subelt) (project/inject/gui a-subelt w->s s->w)) elts))] [(struct box-group-elt (val-f a-subelt enabled?-f)) (make-box-group-elt (project val-f w->s) (project/inject/gui a-subelt w->s s->w) (project enabled?-f w->s))] [(struct displayable-elt (val-f)) (make-displayable-elt (project val-f w->s))] [(struct canvas-elt (scene-f callback)) (make-canvas-elt (project scene-f w->s) (project/inject-2 callback w->s s->w))] [(struct button-elt (val-f callback enabled?-f)) (make-button-elt (project val-f w->s) (project/inject-0 callback w->s s->w) (project enabled?-f w->s))] [(struct drop-down-elt (val-f choices-f callback enabled?-f)) (make-drop-down-elt (project val-f w->s) (project choices-f w->s) (project/inject-1 callback w->s s->w) (project enabled?-f w->s))] [(struct text-field-elt (val-f callback enabled?-f)) (make-text-field-elt (project val-f w->s) (project/inject-1 callback w->s s->w) (project enabled?-f w->s))] [(struct slider-elt (val-f min-f max-f callback enabled?-f)) (make-slider-elt (project val-f w->s) (project min-f w->s) (project max-f w->s) (project/inject-1 callback w->s s->w) (project enabled?-f w->s))] [(struct checkbox-elt (label-f val-f callback enabled?-f)) (make-checkbox-elt (project label-f w->s) (project val-f w->s) (project/inject-1 callback w->s s->w) (project enabled?-f w->s))])) ;; project: (S -> X) (W -> S) -> (W -> X) (define (project a-gvalue w->s) (lambda (a-world) (a-gvalue (w->s a-world)))) ;; project/inject-2: (S X Y -> S) (W -> S) (W S -> W) -> (W X Y -> W) ;; project/inject-1: (S X -> S) (W -> S) (W S -> W) -> (W X -> W) ;; project/inject-0: (S -> S) (W -> S) (W S -> W) -> (W -> W) (define (project/inject-2 a-gcallback w->s s->w) (lambda (a-world v1 v2) (s->w a-world (a-gcallback (w->s a-world) v1 v2)))) (define (project/inject-1 a-gcallback w->s s->w) (lambda (a-world a-val) (s->w a-world (a-gcallback (w->s a-world) a-val)))) (define (project/inject-0 a-gcallback w->s s->w) (lambda (a-world) (s->w a-world (a-gcallback (w->s a-world))))) (provide col row message button button/enabled slider slider/enabled drop-down drop-down/enabled text-field text-field/enabled checkbox checkbox/enabled canvas canvas/callback box-group box-group/enabled project/inject/gui) (provide/contract [struct elt ()] [struct (row-elt elt) ([elts (listof elt?)])] [struct (column-elt elt) ([elts (listof elt?)])] [struct (box-group-elt elt) ([val-f (gvalueof displayable?)] [elt elt?] [enabled?-f (gvalueof boolean?)])] [struct (displayable-elt elt) ([val-f (gvalueof displayable?)])] [struct (canvas-elt elt) ([scene-f (gvalueof scene?)] [callback (gcallbackof-2 number? number?)])] [struct (button-elt elt) ([val-f (gvalueof displayable?)] [callback callback/c] [enabled?-f (gvalueof boolean?)])] [struct (drop-down-elt elt) ([val-f (gvalueof displayable?)] [choices-f (gvalueof (listof displayable?))] [callback (gcallbackof displayable?)] [enabled?-f (gvalueof boolean?)])] [struct (text-field-elt elt) ([val-f (gvalueof displayable?)] [callback (gcallbackof displayable?)] [enabled?-f (gvalueof boolean?)])] [struct (slider-elt elt) ([val-f (gvalueof number?)] [min-f (gvalueof number?)] [max-f (gvalueof number?)] [callback (gcallbackof number?)] [enabled?-f (gvalueof boolean?)])] [struct (checkbox-elt elt) ([label-f (gvalueof displayable?)] [val-f (gvalueof boolean?)] [callback (gcallbackof boolean?)] [enabled?-f (gvalueof boolean?)])] [displayable? (any/c . -> . boolean?)] [displayable->string (displayable? . -> . displayable?)])
false
b1d914e5b1291017837516b08cc6da4ac8788b0e
2f72cf5e903cc92a815e639f8ad12fe538b89564
/Music transcribe/LilyPond/usr/share/lilypond/current/scm/parser-clef.scm
5ab1c1175b1d19dde29a58aac583f510ba81af56
[]
no_license
Pookie-Cookie/music-transcription
a5b9801f9ac4c943f4b69b85edc4641209dfdad3
832f6b2220a6b8546b30bbef2ef9ceafc2134d95
refs/heads/master
2023-03-09T03:34:55.775398
2021-02-18T22:07:43
2021-02-18T22:07:43
312,693,050
0
0
null
2021-02-05T11:45:29
2020-11-13T22:00:07
Python
UTF-8
Scheme
false
false
8,511
scm
parser-clef.scm
;;;; This file is part of LilyPond, the GNU music typesetter. ;;;; ;;;; Copyright (C) 2004--2015 Han-Wen Nienhuys <[email protected]> ;;;; ;;;; LilyPond is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; LilyPond is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with LilyPond. If not, see <http://www.gnu.org/licenses/>. ;; (name . (glyph clef-position transposition)) ;; ;; -- the name clefTransposition is a bit misleading. Value 7 means ;; a transposition of an octave, not a seventh. (define-public supported-clefs '(("treble" . ("clefs.G" -2 0)) ("violin" . ("clefs.G" -2 0)) ("G" . ("clefs.G" -2 0)) ("G2" . ("clefs.G" -2 0)) ("GG" . ("clefs.GG" -2 0)) ("tenorG" . ("clefs.tenorG" -2 0)) ("french" . ("clefs.G" -4 0)) ("soprano" . ("clefs.C" -4 0)) ("mezzosoprano" . ("clefs.C" -2 0)) ("alto" . ("clefs.C" 0 0)) ("C" . ("clefs.C" 0 0)) ("varC" . ("clefs.varC" 0 0)) ("altovarC" . ("clefs.varC" 0 0)) ("tenor" . ("clefs.C" 2 0)) ("tenorvarC" . ("clefs.varC" 2 0)) ("baritone" . ("clefs.C" 4 0)) ("baritonevarC" . ("clefs.varC" 4 0)) ("varbaritone" . ("clefs.F" 0 0)) ("baritonevarF" . ("clefs.F" 0 0)) ("bass" . ("clefs.F" 2 0)) ("F" . ("clefs.F" 2 0)) ("subbass" . ("clefs.F" 4 0)) ("percussion" . ("clefs.percussion" 0 0)) ("varpercussion" . ("clefs.varpercussion" 0 0)) ("tab" . ("clefs.tab" 0 0)) ;; should move mensural stuff to separate file? ("vaticana-do1" . ("clefs.vaticana.do" -1 0)) ("vaticana-do2" . ("clefs.vaticana.do" 1 0)) ("vaticana-do3" . ("clefs.vaticana.do" 3 0)) ("vaticana-fa1" . ("clefs.vaticana.fa" -1 0)) ("vaticana-fa2" . ("clefs.vaticana.fa" 1 0)) ("medicaea-do1" . ("clefs.medicaea.do" -1 0)) ("medicaea-do2" . ("clefs.medicaea.do" 1 0)) ("medicaea-do3" . ("clefs.medicaea.do" 3 0)) ("medicaea-fa1" . ("clefs.medicaea.fa" -1 0)) ("medicaea-fa2" . ("clefs.medicaea.fa" 1 0)) ("hufnagel-do1" . ("clefs.hufnagel.do" -1 0)) ("hufnagel-do2" . ("clefs.hufnagel.do" 1 0)) ("hufnagel-do3" . ("clefs.hufnagel.do" 3 0)) ("hufnagel-fa1" . ("clefs.hufnagel.fa" -1 0)) ("hufnagel-fa2" . ("clefs.hufnagel.fa" 1 0)) ("hufnagel-do-fa" . ("clefs.hufnagel.do.fa" 4 0)) ("mensural-c1" . ("clefs.mensural.c" -4 0)) ("mensural-c2" . ("clefs.mensural.c" -2 0)) ("mensural-c3" . ("clefs.mensural.c" 0 0)) ("mensural-c4" . ("clefs.mensural.c" 2 0)) ("mensural-c5" . ("clefs.mensural.c" 4 0)) ("blackmensural-c1" . ("clefs.blackmensural.c" -4 0)) ("blackmensural-c2" . ("clefs.blackmensural.c" -2 0)) ("blackmensural-c3" . ("clefs.blackmensural.c" 0 0)) ("blackmensural-c4" . ("clefs.blackmensural.c" 2 0)) ("blackmensural-c5" . ("clefs.blackmensural.c" 4 0)) ("mensural-f" . ("clefs.mensural.f" 2 0)) ("mensural-g" . ("clefs.mensural.g" -2 0)) ("neomensural-c1" . ("clefs.neomensural.c" -4 0)) ("neomensural-c2" . ("clefs.neomensural.c" -2 0)) ("neomensural-c3" . ("clefs.neomensural.c" 0 0)) ("neomensural-c4" . ("clefs.neomensural.c" 2 0)) ("neomensural-c5" . ("clefs.neomensural.c" 4 0)) ("petrucci-c1" . ("clefs.petrucci.c1" -4 0)) ("petrucci-c2" . ("clefs.petrucci.c2" -2 0)) ("petrucci-c3" . ("clefs.petrucci.c3" 0 0)) ("petrucci-c4" . ("clefs.petrucci.c4" 2 0)) ("petrucci-c5" . ("clefs.petrucci.c5" 4 0)) ("petrucci-f2" . ("clefs.petrucci.f" -2 0)) ("petrucci-f3" . ("clefs.petrucci.f" 0 0)) ("petrucci-f4" . ("clefs.petrucci.f" 2 0)) ("petrucci-f5" . ("clefs.petrucci.f" 4 0)) ("petrucci-f" . ("clefs.petrucci.f" 2 0)) ("petrucci-g1" . ("clefs.petrucci.g" -4 0)) ("petrucci-g2" . ("clefs.petrucci.g" -2 0)) ("petrucci-g" . ("clefs.petrucci.g" -2 0)) ("kievan-do" . ("clefs.kievan.do" 0 0)))) ;; "an alist mapping GLYPHNAME to the position of the middle C for ;; that symbol" (define c0-pitch-alist '(("clefs.G" . -4) ("clefs.GG" . 3) ("clefs.tenorG" . 3) ("clefs.C" . 0) ("clefs.varC" . 0) ("clefs.F" . 4) ("clefs.percussion" . 0) ("clefs.varpercussion" . 0) ("clefs.tab" . 0 ) ("clefs.vaticana.do" . 0) ("clefs.vaticana.fa" . 4) ("clefs.medicaea.do" . 0) ("clefs.medicaea.fa" . 4) ("clefs.hufnagel.do" . 0) ("clefs.hufnagel.fa" . 4) ("clefs.hufnagel.do.fa" . 0) ("clefs.mensural.c" . 0) ("clefs.mensural.f" . 4) ("clefs.mensural.g" . -4) ("clefs.blackmensural.c" . 0) ("clefs.neomensural.c" . 0) ("clefs.petrucci.c1" . 0) ("clefs.petrucci.c2" . 0) ("clefs.petrucci.c3" . 0) ("clefs.petrucci.c4" . 0) ("clefs.petrucci.c5" . 0) ("clefs.petrucci.f2" . 4) ("clefs.petrucci.f3" . 4) ("clefs.petrucci.f4" . 4) ("clefs.petrucci.f5" . 4) ("clefs.petrucci.f" . 4) ("clefs.petrucci.g1" . -4) ("clefs.petrucci.g2" . -4) ("clefs.petrucci.g" . -4) ("clefs.kievan.do" . 0))) (define-public (make-clef-set clef-name) "Generate the clef setting commands for a clef with name @var{clef-name}." (let* ((match (string-match "^(.*)([_^])([^0-9a-zA-Z]*)([1-9][0-9]*)([^0-9a-zA-Z]*)$" clef-name)) (e (assoc-get (if match (match:substring match 1) clef-name) supported-clefs)) (oct (if match ((if (equal? (match:substring match 2) "^") - +) (1- (string->number (match:substring match 4)))) 0)) (style (cond ((not match) 'default) ((equal? (match:substring match 3) "(") 'parenthesized) ((equal? (match:substring match 3) "[") 'bracketed) (else 'default)))) (if e (let ((musics (list (make-property-set 'clefGlyph (car e)) (make-property-set 'middleCClefPosition (+ oct (cadr e) (assoc-get (car e) c0-pitch-alist))) (make-property-set 'clefPosition (cadr e)) (make-property-set 'clefTransposition (- oct)) (make-property-set 'clefTranspositionStyle style) (make-apply-context ly:set-middle-C!)))) (context-spec-music (make-sequential-music musics) 'Staff)) (begin (ly:warning (_ "unknown clef type `~a'") clef-name) (ly:warning (_ "supported clefs: ~a") (string-join (sort (map car supported-clefs) string<?))) (make-music 'Music))))) (define-public (make-cue-clef-set clef-name) "Generate the clef setting commands for a cue clef with name @var{clef-name}." (define cue-clef-map '((clefGlyph . cueClefGlyph) (middleCClefPosition . middleCCuePosition) (clefPosition . cueClefPosition) (clefTransposition . cueClefTransposition) (clefTranspositionFormatter . cueClefTranspositionFormatter) (clefTranspositionStyle . cueClefTranspositionStyle))) (let ((clef (make-clef-set clef-name))) (for-each (lambda (m) (let ((mapped (assq-ref cue-clef-map (ly:music-property m 'symbol)))) (if mapped (set! (ly:music-property m 'symbol) mapped)))) (extract-named-music clef 'PropertySet)) clef)) (define-public (make-cue-clef-unset) "Reset the clef settings for a cue clef." (map-some-music (lambda (m) (and (eq? (ly:music-property m 'name) 'PropertySet) (make-music 'PropertyUnset 'symbol (ly:music-property m 'symbol)))) (make-cue-clef-set "treble_(8)"))) ;; a function to add new clefs at runtime (define-public (add-new-clef clef-name clef-glyph clef-position transposition c0-position) "Append the entries for a clef symbol to supported clefs and @code{c0-pitch-alist}." (set! supported-clefs (acons clef-name (list clef-glyph clef-position transposition) supported-clefs)) (set! c0-pitch-alist (acons clef-glyph c0-position c0-pitch-alist)))
false
23ed2e47d77f6ef4b61998b8063e5cb5148cb701
b9d0fc9d5d0d135aadd1e4644b45004fd2c94b94
/scheme/html-tags/.svn/text-base/html-tags.meta.svn-base
4907199dd234368865f55365d9f89bb0a45c692b
[]
no_license
alvatar/snippets
f704413d39b6c9363e1c435444ec82e270184f75
89ce0c71ff1554a9307ed0726b84dfa5782babe6
refs/heads/master
2021-06-28T21:59:15.358791
2016-10-25T16:26:52
2016-10-25T16:26:52
2,073,559
1
0
null
null
null
null
UTF-8
Scheme
false
false
367
html-tags.meta.svn-base
;;; html-tags.meta -*- Scheme -*- ((egg "html-tags.egg") (synopsis "Procedures to generate [X]HTML code") (category web) (license "BSD") (test-depends test) (author "<a href=\"http://chicken.wiki.br/users/mario-domenech-goulart\">Mario Domenech Goulart</a>") (files "html-tags.scm" "html-tags.setup" "html-tags.meta" "tests/run.scm" "html-tags.release-info"))
false
3b07ab3bc8b08c5ddc16c821c9bda32dfadaa794
d2fc383d46303bc47223f4e4d59ed925e9b446ce
/courses/2008/fall/330/notes/18.ss
b8221e660f494d88b20cc53bd2b89d360f123081
[]
no_license
jeapostrophe/jeapostrophe.github.com
ce0507abc0bf3de1c513955f234e8f39b60e4d05
48ae350248f33f6ce27be3ce24473e2bd225f6b5
refs/heads/master
2022-09-29T07:38:27.529951
2022-09-22T10:12:04
2022-09-22T10:12:04
3,734,650
14
5
null
2022-03-25T14:33:29
2012-03-16T01:13:09
HTML
UTF-8
Scheme
false
false
824
ss
18.ss
;; The first three lines of this file were inserted by DrScheme. They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "reader.ss" "plai" "lang") #| (call/cc (lambda (k) ...)) (let/cc k ...) |# ; Basic (let/cc k (k 3)) ; Involved (+ 1 (let/cc k (k 3))) ; Exceptions (define (f n) (+ 10 (* 5 (let/cc k (/ 1 n))))) (+3 (f 0)) ; Pseudo web-read #;(define (web-read prompt) (let/cc k (let ([k-id (next-kont-id)]) (hash-table-put! web-ht k-id k) (send-to-browser (generate-prompt-with-url-to-kont prompt k-id)) (halt)))) ; Producers & Consumers (define (route-producer send) (begin (send 'palmyra) (send 'kirtland) (send 'far-west) (send 'nauvoo)))
false
ed2153272a3cfcfef1c5618e222924b5beb9a34b
b60cb8e39ec090137bef8c31ec9958a8b1c3e8a6
/test/changes/scheme/gcipd.scm
d990ad62796cf6b6e1ed1b840ad96a34ef1b4361
[]
no_license
acieroid/scala-am
eff387480d3baaa2f3238a378a6b330212a81042
13ef3befbfc664b77f31f56847c30d60f4ee7dfe
refs/heads/master
2021-01-17T02:21:41.692568
2021-01-15T07:51:20
2021-01-15T07:51:20
28,140,080
32
16
null
2020-04-14T08:53:20
2014-12-17T14:14:02
Scheme
UTF-8
Scheme
false
false
263
scm
gcipd.scm
(letrec ((f (lambda (n) (if (<= n 1) 1 (* n (f (- n 1)))))) (g (lambda (n) (if (<= n 1) 1 (+ (* n n) (g (- n 1))))))) (+ ((<change> g f) 2) ((<change> f g) 2)))
false
bade4c9bf0c7d7ff1228bbca20520f2a9d0687f7
fd9daee097ae6e309e4abf907513487315e91ca5
/src/loop.ss
aa4781c8dd68e8fd9cb37f4d64bde130a58a5bef
[ "MIT" ]
permissive
tqtifnypmb/choices
93c96e49e557f4c6871aab28eb8f0abae70bb901
d3dd2d31cb43f46d7a73c07611521f5cde7b57c2
refs/heads/master
2021-01-19T19:56:36.293246
2017-05-03T08:06:48
2017-05-03T08:06:48
88,466,503
2
2
null
null
null
null
UTF-8
Scheme
false
false
1,247
ss
loop.ss
(define (make-loop) (new loop-init (uv-loop-size))) (define (make-default-loop) (let ((loop (default-loop))) (if (eq? loop 0) #f loop))) (define (uv-loop-close loop) (let ((res (loop-close loop))) (if (= res 0) (begin (foreign-free loop) #t) #f))) (define loop-init (foreign-procedure "uv_loop_init" (uptr) int)) (define default-loop (foreign-procedure "uv_default_loop" () uptr)) (define loop-close (foreign-procedure "uv_loop_close" (uptr) int)) ; (define loop-data-set ; (foreign-procedure "loop_data_set" (uv-loop void*) void)) ; (define loop-data ; (foreign-procedure "loop_data" (uptr) void*)) (define uv-run-default 0) (define uv-run-once 1) (define uv-run-nowait 2) (define uv-run (foreign-procedure "uv_run" (uptr int) int)) (define uv-loop-alive (foreign-procedure "uv_loop_alive" (uptr) boolean)) (define uv-loop-size (foreign-procedure "uv_loop_size" () size_t)) (define uv-loop-stop (foreign-procedure "uv_stop" (uptr) void)) (define uv-now (foreign-procedure "uv_now" (uptr) unsigned-64)) (define uv-backend-timeout (foreign-procedure "uv_backend_timeout" (uptr) int)) (define uv-update-time (foreign-procedure "uv_update_time" (uptr) void))
false
4452f0c919f7bd4c826673fbdbd684ab6294033a
cc6a300f6d5414a5e7173968c7a6be1f8a8425dc
/tests/tdo.scm
3a8eca40d7034e2f811d9ceca94307bda38aed6d
[ "Artistic-2.0" ]
permissive
hdijkema/speme
2b4058164c8d59df721a7f54fa4f6c805e7e5621
e5d72c54d07af81e98f0f5e059f7180e36ff4f4a
refs/heads/master
2020-05-17T21:41:34.617879
2013-07-24T08:04:51
2013-07-24T08:04:51
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
146
scm
tdo.scm
(package tdo 0.1 (tdo) (define (tdo n) (let ((l (list))) (do ((i 0 (+ i 1))) ((> i n) l) (set! l (cons i l))))) )
false
05fb1341489cd3cc1e51f95c0a3563121c1b90a3
bdcc255b5af12d070214fb288112c48bf343c7f6
/robin/constants.sls
5649c8c2b138f11d3f0fa240c6559882f4bbd5b8
[]
no_license
xaengceilbiths/chez-lib
089af4ab1d7580ed86fc224af137f24d91d81fa4
b7c825f18b9ada589ce52bf5b5c7c42ac7009872
refs/heads/master
2021-08-14T10:36:51.315630
2017-11-15T11:43:57
2017-11-15T11:43:57
109,713,952
5
1
null
null
null
null
UTF-8
Scheme
false
false
1,886
sls
constants.sls
#!chezscheme ;; Constants library for R7RS Scheme ;; Some important mathematical/physical constants ;; -- import with a prefix! ;; Written by Peter Lane, 2017 ;; # Open Works License ;; ;; This is version 0.9.4 of the Open Works License ;; ;; ## Terms ;; ;; Permission is hereby granted by the holder(s) of copyright or other legal ;; privileges, author(s) or assembler(s), and contributor(s) of this work, to any ;; person who obtains a copy of this work in any form, to reproduce, modify, ;; distribute, publish, sell, sublicense, use, and/or otherwise deal in the ;; licensed material without restriction, provided the following conditions are ;; met: ;; ;; Redistributions, modified or unmodified, in whole or in part, must retain ;; applicable copyright and other legal privilege notices, the above license ;; notice, these conditions, and the following disclaimer. ;; ;; NO WARRANTY OF ANY KIND IS IMPLIED BY, OR SHOULD BE INFERRED FROM, THIS LICENSE ;; OR THE ACT OF DISTRIBUTION UNDER THE TERMS OF THIS LICENSE, INCLUDING BUT NOT ;; LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, ;; AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS, ASSEMBLERS, OR HOLDERS OF ;; COPYRIGHT OR OTHER LEGAL PRIVILEGE BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER ;; LIABILITY, WHETHER IN ACTION OF CONTRACT, TORT, OR OTHERWISE ARISING FROM, OUT ;; OF, OR IN CONNECTION WITH THE WORK OR THE USE OF OR OTHER DEALINGS IN THE WORK. (library (robin constants) (export G c PI e) (import (scheme base)) (begin (define G 6.67408e-11) ; Newton's constant of gravitation m^3 kg^-1 s^-2 (define c 299792458) ; Speed of light in a vacuum m s^-1 (define PI 3.14159265358979323846264338327950) ; from http://www.geom.uiuc.edu/~huberty/math5337/groupe/digits.html (define e 2.7182818284590452353602875) ))
false
9b36141bdcbc32816f05324b9cf533064c6dd81e
7ab94f43ade2471689729ad90bcbfce6731b0dca
/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-10.ss
3d7ee0eb86f4eb67808ade31902db23bae2e6322
[]
no_license
vmakovsky/RosettaCodeData
a6beb9e0661755c5fe496f950d164947869b824e
6883b40e1e89e8d7780b8418c1635120a55291aa
refs/heads/master
2021-01-14T10:23:28.742416
2015-10-07T14:36:24
2015-10-07T14:36:24
43,821,774
0
0
null
2015-10-07T14:33:42
2015-10-07T14:33:42
null
UTF-8
Scheme
false
false
288
ss
sieve-of-eratosthenes-10.ss
(define odd-primes (s-cons 3 (s-diff (from-By 5 2) (s-foldr (lambda (p r) (let ((q (* p p))) (s-cons q (s-union (from-By (+ q (* 2 p)) (* 2 p)) r)))) '() odd-primes)))) (define primes (s-cons 2 odd-primes)) ;;;; TODO: implement s-foldr function
false
99b809a97e093c2833e504a6db152bffd513799a
c74dcb1facbd920d762017345171f47f8e41d0c5
/chapter_3/3.72.scm
8a86527e416502f20db4bfc3970ccbf374bedc09
[]
no_license
akash-akya/sicp-exercises
5125c1118c7f0e4400cb823508797fb67c745592
c28f73719740c2c495b7bc38ee8b790219482b67
refs/heads/master
2021-06-15T19:12:47.679967
2019-08-03T14:03:20
2019-08-03T14:03:20
136,158,517
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,993
scm
3.72.scm
#lang sicp (#%require "utils.scm") (#%require "stream-utils.scm") ;; Exercise 3.72: In a similar way to Exercise 3.71 generate a stream ;; of all numbers that can be written as the sum of two squares in ;; three different ways (showing how they can be so written). (define (merge-weighted s1 s2 weight) (cond ((stream-null? s1) s2) ((stream-null? 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 s t weight) (cons-stream (list (stream-car s) (stream-car t)) (merge-weighted (stream-map (lambda (x) (list (stream-car s) x)) (stream-cdr t)) (weighted-pairs (stream-cdr s) (stream-cdr t) weight) weight))) (define (weight-func p) (+ (square (car p)) (square (cadr p)))) (define square-sum-pairs (weighted-pairs integers integers weight-func)) (define (sq-pairs s) (let ((a (stream-car s)) (b (stream-car (stream-cdr s))) (c (stream-car (stream-cdr (stream-cdr s))))) (if (= (weight-func a) (weight-func b) (weight-func c)) (cons-stream (list a b c) (sq-pairs (stream-cdr s))) (sq-pairs (stream-cdr s))))) (define sq-pairs-stream (sq-pairs square-sum-pairs)) ;; test (define (test) (define pairs (take-n sq-pairs-stream 5)) (define (show p) (if (null? p) (newline) (begin (let ((numbers (car p))) (display (car numbers)) (display "\t") (display (cadr numbers)) (display "\t") (display (caddr numbers)) (newline)) (show (cdr p))))) (show pairs))
false
dd4ca816a430dd8ed79377d5414c4d222e108306
382770f6aec95f307497cc958d4a5f24439988e6
/projecteuler/053/053-imp2.scm
e6898399959bfd45ba3d8a37cada9a8a43c43351
[ "Unlicense" ]
permissive
include-yy/awesome-scheme
602a16bed2a1c94acbd4ade90729aecb04a8b656
ebdf3786e54c5654166f841ba0248b3bc72a7c80
refs/heads/master
2023-07-12T19:04:48.879227
2021-08-24T04:31:46
2021-08-24T04:31:46
227,835,211
1
0
null
null
null
null
UTF-8
Scheme
false
false
490
scm
053-imp2.scm
(define max 100) (define limit 1000000) (let pro ([n max] [nCr 1] [count 0] [r 0]) (let f ([re r] [curr nCr]) (cond ((>= re (/ n 2)) count) (else (let ([Cr (* curr (- n re) (/ (+ re 1)))]) (if (<= Cr limit) (f (+ re 1) Cr) (pro (- n 1) (* curr (- n re) (/ n)) (- (+ count n) (+ (* re 2) 1)) re))))))) #| (time (let pro ...)) no collections 0.000000000s elapsed cpu time 0.000022200s elapsed real time 3344 bytes allocated 4075 |#
false
00d65c53ee9845da55f8720b688e01c02cadf3a4
fae4190f90ada065bc9e5fe64aab0549d4d4638a
/660-typed-scheme/private/effect-rep.ss
e33977f9b6123819143fe9c47837d138de9c92be
[]
no_license
ilya-klyuchnikov/old-typed-racket
f161481661a2ed5cfc60e268f5fcede728d22488
fa7c1807231f447ff37497e89b25dcd7a9592f64
refs/heads/master
2021-12-08T04:19:59.894779
2008-04-13T10:54:34
2008-04-13T10:54:34
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,116
ss
effect-rep.ss
#lang scheme/base (require (lib "plt-match.ss")) (require (lib "etc.ss")) (require "rep-utils.ss" "free-variance.ss") (de True-Effect () [#:frees #f] [#:fold-rhs #:base]) (de False-Effect () [#:frees #f] [#:fold-rhs #:base]) ;; v is an identifier (de Var-True-Effect (v) [#:intern (hash-id v)] [#:frees #f] [#:fold-rhs #:base]) ;; v is an identifier (de Var-False-Effect (v) [#:intern (hash-id v)] [#:frees #f] [#:fold-rhs #:base]) ;; t is a Type ;; v is an identifier (de Restrict-Effect (t v) [#:intern (list t (hash-id v))] [#:frees (free-vars* t) (free-idxs* t)] [#:fold-rhs (*Restrict-Effect (type-rec-id t) v)]) ;; t is a Type ;; v is an identifier (de Remove-Effect (t v) [#:intern (list t (hash-id v))] [#:frees (free-vars* t) (free-idxs* t)] [#:fold-rhs (*Remove-Effect (type-rec-id t) v)]) ;; t is a Type (de Latent-Restrict-Effect (t)) ;; t is a Type (de Latent-Remove-Effect (t)) (de Latent-Var-True-Effect () [#:frees #f] [#:fold-rhs #:base]) (de Latent-Var-False-Effect () [#:frees #f] [#:fold-rhs #:base]) ;; could also have latent true/false effects, but seems pointless
false
27a3dbbc8cc28e4ca5475c9c238c3fc5a7546ef4
3888492b9b0c8a8f6c49670822e3c92a99ac3454
/guix/configs/elbruz.scm
48c3175e81d985f76e980fc1823f1f869f18f33d
[]
no_license
avoine/conf
e8bce2824c8774eb43c0d68bb8b5282ee303627e
8a07b482fcce160ac98a14eaac191f8c84cf018f
refs/heads/master
2021-03-13T01:01:22.224750
2017-05-15T17:58:42
2017-05-15T17:58:42
91,472,762
1
1
null
2017-05-16T15:14:12
2017-05-16T15:14:12
null
UTF-8
Scheme
false
false
2,671
scm
elbruz.scm
(use-modules (srfi srfi-1) (srfi srfi-26) (gnu)) (use-service-modules desktop cuirass networking) (primitive-load "/home/mathieu/conf/guix/configs/common.scm") (define %cuirass-specs ;; Cuirass specifications to build Guix. #~(list `((#:name . "guix") (#:url . "git://git.savannah.gnu.org/guix.git") (#:branch . "master") (#:no-compile? #t) (#:load-path . ".") (#:proc . drv-list) (#:file . #$(local-file "/home/mathieu/conf/guix/cuirass/guix-drv.scm"))))) (define %elbruz-base-services ((compose (cut remove (lambda (service) (eq? (service-kind service) connman-service-type)) <>) (cut modify-services <> (guix-service-type config => (guix-configuration (inherit config) (substitute-urls (remove (lambda (s) (string=? "http://cuirass.lassieur.org" s)) (guix-configuration-substitute-urls config))))))) (cons* (static-networking-service "enp7s0f0" "192.168.0.51" #:gateway "192.168.0.254" #:name-servers (list "8.8.8.8")) (guix-publish-service #:host "0.0.0.0") (service cuirass-service-type (cuirass-configuration (interval 30) (use-substitutes? #t) (port 8082) (load-path '("/home/mathieu/conf/guix/common_packages")) (specifications %cuirass-specs))) (operating-system-user-services %common-os)))) (operating-system (inherit %common-os) (host-name "elbruz") (kernel linux-libre) ;; (kernel linux-libre-4.4) ;;(kernel linux-nonfree-elbruz) ;; ----> maybe does not boot !! (kernel-arguments '("modprobe.blacklist=pcspkr" "console=tty0" "console=ttyS0,115200n8" "earlyprintk=serial,ttyS0,115200")) (file-systems (cons (file-system (mount-point "/tmp") (device "none") (title 'device) (type "tmpfs") (check? #f)) (operating-system-file-systems %common-os))) (users (cons (user-account (name "clement") (group "users") (supplementary-groups '("wheel" "netdev" "audio" "video")) (home-directory "/home/clement")) (operating-system-users %common-os))) (services %elbruz-base-services))
false
d2ab16a7dfe7b9429469c1c22d1b087bd842f394
1384f71796ddb9d11c34c6d988c09a442b2fc8b2
/scheme/xmms2/ipc.scm
e8a4c3862e7b2156c1d797e3d1acf75147f8d9ce
[]
no_license
ft/xmms2-guile
94c2479eec427a370603425fc9e757611a796254
29670e586bf440c20366478462f425d5252b953c
refs/heads/master
2021-07-08T07:58:15.066996
2020-10-12T01:24:04
2020-10-12T01:24:04
74,858,831
1
2
null
null
null
null
UTF-8
Scheme
false
false
9,261
scm
ipc.scm
;; Copyright (c) 2016 xmms2-guile workers, All rights reserved. ;; ;; Terms for redistribution and use can be found in LICENCE. (define-module (xmms2 ipc) #:use-module (ice-9 optargs) #:use-module (srfi srfi-1) #:use-module (srfi srfi-9) #:use-module (xmms2 constants) #:use-module (xmms2 constants meta) #:use-module (xmms2 header) #:use-module (xmms2 payload) #:export (define-ipc-packet-generator make-ipc-broadcast make-ipc-method make-ipc-signal ipc-broadcast? ipc-method? ipc-signal? broadcast-name broadcast-object broadcast-identifier broadcast-documentation broadcast-return-value broadcast-generator method-name method-object method-identifier method-documentation method-arguments method-return-value method-generator signal-name signal-object signal-identifier signal-documentation signal-return-value signal-generator)) ;; The following macro can be used to define functions, that generate XMMS2 ;; protocol data from scheme data structures. Example: ;; ;; (define-ipc-packet-generator make-hello public OBJECT-MAIN CMD-HELLO ;; "Say 'Hello' to the server." ;; (integer protocol-version) (string client-name)) ;; ;; This will define a function (using ‘define-public’, because of the ‘public’ ;; tag), that does the following: ;; ;; (make-hello PROTOCOL-VERSION "cmc") ;; ;; => (#vu8(0 0 0 1 0 0 0 32 0 0 0 0 0 0 0 36) ; Header ;; #vu8(0 0 0 6) ; Tag: List ;; #vu8(0 0 0 0 0 0 0 2) ; List length: 2 ;; #vu8(0 0 0 2) ; Tag: Integer ;; #vu8(0 0 0 0 0 0 0 23) ; Integer: 23 ;; #vu8(0 0 0 3) ; Tag: String ;; #vu8(0 0 0 4 99 109 99 0)) ; XMMS2-String: "cmc" ;; ;; ...which is indeed a valid message in XMMS2's protocol. ;; ;; The generated function does perform type checks on the arguments passed to ;; it and throws ‘type-error’ in case an invalid datum was handed to it in ;; either of the required arguments. ;; ;; All generated ipc code in (xmms2 ipc *) uses this macro to create its ;; protocol generators. (define-syntax define-ipc-packet-generator (lambda (ctx) (define (generate-predicate-checks kw lst) (let loop ((rest lst) (return-value '())) (if (null? rest) (datum->syntax kw (reverse return-value)) (loop (cdr rest) (cons (let ((type (syntax->datum (caar rest))) (argument (syntax->datum (cadar rest)))) (cond ((eq? type 'binary) `(bytevector? ,argument)) ((eq? type 'integer) `(integer? ,argument)) ((eq? type 'string) `(string? ,argument)) ((eq? type 'collection) `(collection? ,argument)) ;; We could perform much stricter tests with lists ;; and dicts here, but that would impact performance ;; with large data structures. Maybe we could make ;; this optional via a #:keyword flag, similar to ;; #:cookie. ((and (list? type) (eq? 'dictionary (car type))) `(or (association-list? ,argument) (dictionary? ,argument))) ((and (list? type) (eq? 'list (car type))) `(list? ,argument)) ((and (list? type) (eq? 'enumeration (car type))) `(integer? ,argument)) (else ;; This should be fatal in the future. ;;(throw 'xmms2/unknown-type type 'with argument) (format (current-error-port) "WARNING: Unknown type `~a' with argument `~a'~%" type argument)))) return-value))))) (syntax-case ctx (public private) ((kw ipc private object identifier (type name) ...) #'(kw define* ipc object identifier "Documentation missing." (type name) ...)) ((kw ipc public object identifier (type name) ...) #'(kw define*-public ipc object identifier "Documentation missing." (type name) ...)) ((kw ipc private object identifier documentation (type name) ...) #'(kw define* ipc object identifier documentation (type name) ...)) ((kw ipc public object identifier documentation (type name) ...) #'(kw define*-public ipc object identifier documentation (type name) ...)) ((kw definer ipc object identifier documentation (type name) ...) (with-syntax (((payload types arguments acc) (generate-temporaries '(payload types arguments acc)))) #`(definer (ipc name ... #:key (cookie 0)) documentation (if (not (and #,@(generate-predicate-checks #'kw #'((type name) ...)))) (apply throw 'xmms2/type-error (let zip ((types '(type ...)) (arguments (list name ...)) (acc '())) (if (or (null? types) (null? arguments)) (reverse acc) (zip (cdr types) (cdr arguments) (cons (cons (car types) (car arguments)) acc))))) (let ((payload (make-list-payload (list name ...)))) (cons (make-protocol-header object identifier cookie (payload-length payload)) payload))))))))) ;; The record types are used to pass around methods, broadcasts and signals ;; with all the available information for full introspection. (define-record-type <ipc-broadcast> (make-ipc-broadcast* name object identifier documentation return-value generator) ipc-broadcast? (name broadcast-name) (object broadcast-object) (identifier broadcast-identifier) (documentation broadcast-documentation) (return-value broadcast-return-value) (generator broadcast-generator)) (define-ipc-packet-generator make-broadcast-generator public OBJECT-SIGNAL IPC-COMMAND-SIGNAL-BROADCAST "Generates a message that can be used to request a certain broadcast." (integer identifer)) (define* (make-ipc-broadcast name #:key (object (throw 'xmms2/required-arg)) (identifier (throw 'xmms2/required-arg)) (generator (throw 'xmms2/required-arg)) (documentation '("No documentation yet")) (return-value '())) (make-ipc-broadcast* name object identifier documentation return-value generator)) (define-record-type <ipc-method> (make-ipc-method* name object identifier documentation arguments return-value generator) ipc-method? (name method-name) (object method-object) (identifier method-identifier) (documentation method-documentation) (arguments method-arguments) (return-value method-return-value) (generator method-generator)) (define* (make-ipc-method name #:key (object (throw 'xmms2/required-arg)) (identifier (throw 'xmms2/required-arg)) (generator (throw 'xmms2/required-arg)) (documentation '("No documentation yet")) (arguments '()) (return-value '())) (make-ipc-method* name object identifier documentation arguments return-value generator)) (define-record-type <ipc-signal> (make-ipc-signal* name object identifier documentation return-value generator) ipc-signal? (name signal-name) (object signal-object) (identifier signal-identifier) (documentation signal-documentation) (return-value signal-return-value) (generator signal-generator)) (define-ipc-packet-generator make-signal-generator public OBJECT-SIGNAL IPC-COMMAND-SIGNAL-SIGNAL "Generates a message that can be used to request a certain signal." (integer identifer)) (define* (make-ipc-signal name #:key (object (throw 'xmms2/required-arg)) (identifier (throw 'xmms2/required-arg)) (generator (throw 'xmms2/required-arg)) (documentation '("No documentation yet")) (return-value '())) (make-ipc-signal* name object identifier documentation return-value generator))
true
d583c52f175beb520aad93e4096b9acc947cb6ef
0b1826093fb47c0a7293573d80f03a28e859640f
/chapter-3/ex-3.50.scm
8b16f574942ad7414f022b37ed6139c87135b8a5
[ "MIT" ]
permissive
yysaki/sicp
253ef8ef52a330af6c2107ca7063773e63f1a4aa
36d2964c980c58ba13a2687e0af773a5e12d770d
refs/heads/master
2021-01-20T11:50:20.648783
2017-12-10T03:43:38
2017-12-10T08:08:18
56,677,496
0
0
null
null
null
null
UTF-8
Scheme
false
false
840
scm
ex-3.50.scm
(load "./3.5") (define (stream-map proc . argstreams) (if (stream-null? (car argstreams)) the-empty-stream (cons-stream (apply proc (map stream-car argstreams)) (apply stream-map (cons proc (map stream-cdr argstreams)))))) (display-stream (stream-map list (stream-enumerate-interval 1 10) (stream-map (lambda (x) (* x 3)) (stream-enumerate-interval 1 10)) (stream-enumerate-interval 3 12))) #?= (stream-map list (stream-enumerate-interval 1 10) (stream-map (lambda (x) (* x 3)) (stream-enumerate-interval 1 10)) (stream-enumerate-interval 3 12)) #?= (stream-car (stream-cdr (stream-map list (stream-enumerate-interval 1 10) (stream-map (lambda (x) (* x 3)) (stream-enumerate-interval 1 10)) (stream-enumerate-interval 3 12))))
false
a24aacafc3eeda583bb9a2e98dd8e467b4f56011
a0c856484b0cafd1d7c428fb271a820dd19be577
/lab8/object.ss
29cf5702bbb71225571e8bd271d4bae82100401e
[]
no_license
ctreatma/scheme_exercises
b13ba7743dfd28af894eb54429297bad67c14ffa
94b4e8886b2500a7b645e6dc795c0d239bf2a3bb
refs/heads/master
2020-05-19T07:30:58.538798
2012-12-03T23:12:22
2012-12-03T23:12:22
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
750
ss
object.ss
(require "smm.ss") (define <point-class> (class (x y) ([visible #f]) (<object>) ([Location? (method () (if (numbers? x y) (list x y) (begin (printf "I don't know~%") (list x y))))] [Visible? (method () visible)] [MoveTo (method (newx newy) (set! x newx) (set! y newy) (list x y))] [MoveRel (method (newx newy) (if (numbers? x y newx newy) (begin (set! x (+ x newx)) (set! y (+ y newy)) (list x y)) (error 'MoveRel "no move to non-numeric position")))] [SetVisible (method (value) (set! visible (if value #t #f)) visible)]))) (define numbers? (lambda n (andmap number? n)))
false
96002300f3936e5ceb1e571922a52afa6aa3a376
a8216d80b80e4cb429086f0f9ac62f91e09498d3
/lib/chibi/show/base.sld
dfd5551926b63c243815145414884d29e75fa82d
[ "BSD-3-Clause" ]
permissive
ashinn/chibi-scheme
3e03ee86c0af611f081a38edb12902e4245fb102
67fdb283b667c8f340a5dc7259eaf44825bc90bc
refs/heads/master
2023-08-24T11:16:42.175821
2023-06-20T13:19:19
2023-06-20T13:19:19
32,322,244
1,290
223
NOASSERTION
2023-08-29T11:54:14
2015-03-16T12:05:57
Scheme
UTF-8
Scheme
false
false
64
sld
base.sld
(define-library (chibi show base) (alias-for (srfi 166 base)))
false
f6fc8d4363c3ce3007b496ba41b555d116e5741d
0bb7631745a274104b084f6684671c3ee9a7b804
/lib/gambit/prim/bytevector.sld
8dfbcac9ec6a66a2f4ec25d56ee00e316f0e040a
[ "Apache-2.0", "LGPL-2.1-only", "LicenseRef-scancode-free-unknown", "GPL-3.0-or-later", "LicenseRef-scancode-autoconf-simple-exception" ]
permissive
feeley/gambit
f87fd33034403713ad8f6a16d3ef0290c57a77d5
7438e002c7a41a5b1de7f51e3254168b7d13e8ba
refs/heads/master
2023-03-17T06:19:15.652170
2022-09-05T14:31:53
2022-09-05T14:31:53
220,799,690
0
1
Apache-2.0
2019-11-10T15:09:28
2019-11-10T14:14:16
null
UTF-8
Scheme
false
false
728
sld
bytevector.sld
;;;============================================================================ ;;; File: "bytevector.sld" ;;; Copyright (c) 1994-2021 by Marc Feeley, All Rights Reserved. ;;;============================================================================ ;;; Bytevector operations. (define-library (bytevector) (namespace "##") (export ;; r7rs ;;UNIMPLEMENTED bytevector ;;UNIMPLEMENTED bytevector-append ;;UNIMPLEMENTED bytevector-copy ;;UNIMPLEMENTED bytevector-copy! ;;UNIMPLEMENTED bytevector-length ;;UNIMPLEMENTED bytevector-u8-ref ;;UNIMPLEMENTED bytevector-u8-set! ;;UNIMPLEMENTED bytevector? ;;UNIMPLEMENTED make-bytevector )) ;;;============================================================================
false
8b25d0a64d562e641234cd48f683cbc80a50e980
6ac5c268b4d11421993d6ee22325643219eebf98
/Example--Assn/Test Files/After Generating Tests/test.0/in/5/001/test.ss
2ec29258104bffb849d9652419993c6126cfdfea
[]
no_license
trsong/AutotestGenerator
ee5f1f1a55a481dac3ffd8a0c637b8c81466598e
7fb6566de32455e8f773c0e4262595bffca20906
refs/heads/master
2021-01-11T10:50:06.170051
2016-12-11T14:34:08
2016-12-11T14:34:08
76,160,341
0
0
null
null
null
null
UTF-8
Scheme
false
false
48
ss
test.ss
(result (my-reverse empty )) (expected empty )
false
dc83c2ddc094d357114c95a0296072d9746d2e30
b62560d3387ed544da2bbe9b011ec5cd6403d440
/examples/scripts/async-threads.scm
f6f503a46a425db5ab08e02e595eb9f08e30b25d
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "Apache-2.0" ]
permissive
mattwparas/steel
c6fb91b20c4e613e6a8db9d9310d1e1c72313df2
700144a5a1aeb33cbdb2f66440bbe38cf4152458
refs/heads/master
2023-09-04T03:41:35.352916
2023-09-01T03:26:01
2023-09-01T03:26:01
241,949,362
207
10
Apache-2.0
2023-09-06T04:31:21
2020-02-20T17:39:28
Rust
UTF-8
Scheme
false
false
2,552
scm
async-threads.scm
; *thread-queue* : list[continuation] (define *thread-queue* '()) ; halt : continuation (define halt #f) ; current-continuation : -> continuation (define (current-continuation) (call/cc (lambda (cc) (cc cc)))) ; await : future -> value ; yield the current thread and loop until the value is completed (define (await future) (define output (poll! future)) ; (displayln output) (if output output (begin (yield) (await future)))) ; spawn : (-> anything) -> void (define (spawn thunk) (let ((cc (current-continuation))) (if (continuation? cc) (set! *thread-queue* (append *thread-queue* (list cc))) (begin (thunk) (quit))))) ; yield : value -> void (define (yield) (let ((cc (current-continuation))) (if (and (continuation? cc) (pair? *thread-queue*)) (let ((next-thread (car *thread-queue*))) (set! *thread-queue* (append (cdr *thread-queue*) (list cc))) (next-thread 'resume)) void))) ; quit : -> ... (define (quit) (if (pair? *thread-queue*) (let ((next-thread (car *thread-queue*))) (set! *thread-queue* (cdr *thread-queue*)) (next-thread 'resume)) (halt))) ; start-threads : -> ... (define (start-threads) (let ((cc (current-continuation))) (if cc (begin (set! halt (lambda () (cc #f))) (if (null? *thread-queue*) void (let ((next-thread (car *thread-queue*))) (set! *thread-queue* (cdr *thread-queue*)) (next-thread 'resume)))) void))) ;; Define an entry point (define-syntax async-main (syntax-rules () [(async-main main-func) (begin main-func (spawn main) (start-threads))])) ;; Use a macro to make it a little bit prettier (async-main (define (main) (displayln "Starting the main thread now!") (define fut-1 (test)) (define fut-2 (test)) (define fut-3 (test)) ;; we're just going to block on the three different async calls (await (join! fut-1 fut-2 fut-3)))) ;; Alternatively, we could just do this normally ; (define (main) ; (displayln "Starting the main thread now!") ; (define fut-1 (test)) ; (define fut-2 (test)) ; (define fut-3 (test)) ; ;; we're just going to block on the three different async calls ; (await ; (join! fut-1 fut-2 fut-3))) ; ;; Start one 'thread' for main ; (spawn main) ; ;; Kick off the execution ; (start-threads)
true
0815f5b70c4eb90869498cd3f78956710e092df7
4b480cab3426c89e3e49554d05d1b36aad8aeef4
/chapter-01/ex1.38-CoMKiD.scm
954d787d1e834e96971837d61a7e98772a590019
[]
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
592
scm
ex1.38-CoMKiD.scm
(define (cont-frac-iter n d k) (define (iter i result) (if (= i 0) result (iter (- i 1) (/ (n i) (+ (d i) result))))) (iter k 0)) (define (d i) (cond ((= i 2) 2.0) ((= (remainder (- i 2) 3) 0) (+ 2.0 (* (quotient (- i 2) 3) 2))) (else 1.0))) (define (base-of-natural-log? k) (> 0.00001 (abs (- 2.718281828459 (+ 2 (cont-frac-iter (lambda (i) 1.0) d k)))))) (define (find-k pred) (define (find i) (if (pred i) i (find (+ i 1)))) (find 1)) (find-k base-of-natural-log?)
false
4ae839955214af279a82a640e9e928c1af986a99
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
/ext/crypto/sagittarius/crypto/pkcs/keys.scm
e1a339a70f29de01399dc49944b17d455340ae46
[ "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
9,759
scm
keys.scm
;;; -*- mode:scheme; coding:utf-8; -*- ;;; ;;; sagittarius/crypto/pkcs/keys.scm - PKCS#8 key operation ;;; ;;; Copyright (c) 2022 Takashi Kato <[email protected]> ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; #!nounbound (library (sagittarius crypto pkcs keys) (export import-private-key export-private-key pkcs-encrypted-private-key-info? <pkcs-encrypted-private-key-info> pkcs-encrypted-private-key-info-encryption-algorithm pkcs-encrypted-private-key-info-encrypted-data read-pkcs-encrypted-private-key-info bytevector->pkcs-encrypted-private-key-info write-pkcs-encrypted-private-key-info pkcs-encrypted-private-key-info->bytevector make-pkcs-encrypted-private-key-info pkcs-one-asymmetric-key? <pkcs-one-asymmetric-key> pkcs-one-asymmetric-key-version pkcs-one-asymmetric-key-private-key-algorithm pkcs-one-asymmetric-key-private-key pkcs-one-asymmetric-key-raw-key-value ;; for PKCS#12 secret key pkcs-one-asymmetric-key-attributes pkcs-one-asymmetric-key-public-key pkcs-one-asymmetric-key->bytevector private-key->pkcs-one-asymmetric-key write-pkcs-one-asymmetric-key bytevector->pkcs-one-asymmetric-key pkcs-one-asymmetric-key->bytevector pkcs-one-asymmetric-key->pkcs-encrypted-private-key-info pkcs-encrypted-private-key-info->pkcs-one-asymmetric-key ;; For (rsa pkcs :8)... one-asymmetric-key->private-key ;; For keystore one-asymmetric-key->pkcs-one-asymmetric-key pkcs-one-asymmetric-key->one-asymmetric-key encrypted-private-key-info->pkcs-encrypted-private-key-info pkcs-encrypted-private-key-info->encrypted-private-key-info) (import (rnrs) (clos user) (sagittarius crypto asn1) (sagittarius crypto asn1 modules) (sagittarius crypto pkcs modules akp) (sagittarius crypto pkcs algorithms) (sagittarius crypto pkix algorithms) (sagittarius crypto pkix attributes) (sagittarius crypto pkix modules x509) (sagittarius crypto keys) (sagittarius combinators)) (define (make-slot-ref getter conv) (lambda (o) (conv (getter o)))) (define (one-asymmetric-key->private-key (oakp one-asymmetric-key?)) (import-private-key (asn1-encodable->asn1-object oakp) (private-key-format private-key-info))) (define (one-asymmetric-key->public-key (oakp one-asymmetric-key?)) (let ((pk (one-asymmetric-key-public-key oakp))) (and pk (import-public-key (make <subject-public-key-info> :algorithm (one-asymmetric-key-private-key-algorithm oakp) :subject-public-key pk))))) (define-class <pkcs-one-asymmetric-key> (<asn1-encodable-container>) ((version :allocation :virtual :cached #t :slot-ref (make-slot-ref (.$ one-asymmetric-key-vertsion asn1-encodable-container-c) der-integer->integer) :reader pkcs-one-asymmetric-key-version) (private-key-algorithm :allocation :virtual :cached #t :slot-ref (make-slot-ref (.$ one-asymmetric-key-private-key-algorithm asn1-encodable-container-c) algorithm-identifier->x509-algorithm-identifier) :reader pkcs-one-asymmetric-key-private-key-algorithm) (private-key :allocation :virtual :cached #t :slot-ref (make-slot-ref (.$ asn1-encodable-container-c) one-asymmetric-key->private-key) :reader pkcs-one-asymmetric-key-private-key) (raw-key-value :allocation :virtual :cached #t :slot-ref (make-slot-ref (.$ one-asymmetric-key-private-key asn1-encodable-container-c) der-octet-string->bytevector) :reader pkcs-one-asymmetric-key-raw-key-value) (attributes :allocation :virtual :cached #t :slot-ref (make-slot-ref (.$ one-asymmetric-key-attributes asn1-encodable-container-c) attributes->x509-attributes) :reader pkcs-one-asymmetric-key-attributes) (public-key :allocation :virtual :cached #t :slot-ref (make-slot-ref (.$ asn1-encodable-container-c) one-asymmetric-key->public-key) :reader pkcs-one-asymmetric-key-public-key))) (define (pkcs-one-asymmetric-key? o) (is-a? o <pkcs-one-asymmetric-key>)) (define-method import-private-key ((key <pkcs-one-asymmetric-key>)) (one-asymmetric-key->private-key (asn1-encodable-container-c key))) (define-method export-private-key ((key <pkcs-one-asymmetric-key>)) (pkcs-one-asymmetric-key->bytevector key)) (define-method import-private-key ((key <one-asymmetric-key>)) (one-asymmetric-key->private-key key)) (define-method export-private-key ((key <one-asymmetric-key>)) (asn1-encodable->bytevector key)) (define (private-key->one-asymmetric-key (private-key private-key?)) (let ((bv (export-private-key private-key (private-key-format private-key-info)))) (bytevector->asn1-encodable <one-asymmetric-key> bv))) (define (private-key->pkcs-one-asymmetric-key (private-key private-key?)) (let ((c (private-key->one-asymmetric-key private-key))) (make <pkcs-one-asymmetric-key> :c c))) (define (pkcs-one-asymmetric-key->one-asymmetric-key oak) (asn1-encodable-container-c oak)) (define (pkcs-one-asymmetric-key->bytevector oak) (asn1-encodable->bytevector (pkcs-one-asymmetric-key->one-asymmetric-key oak))) (define (write-pkcs-one-asymmetric-key oak :optional (out (current-output-port))) (put-bytevector out (pkcs-one-asymmetric-key->bytevector oak))) (define (bytevector->pkcs-one-asymmetric-key bv) (read-pkcs-one-asymmetric-key (open-bytevector-input-port bv))) (define (read-pkcs-one-asymmetric-key in) (one-asymmetric-key->pkcs-one-asymmetric-key (asn1-object->asn1-encodable <one-asymmetric-key> (read-asn1-object in)))) (define (one-asymmetric-key->pkcs-one-asymmetric-key epki) (make <pkcs-one-asymmetric-key> :c epki)) (define-class <pkcs-encrypted-private-key-info> (<asn1-encodable-container>) ((encryption-algorithm :allocation :virtual :cached #t :slot-ref (make-slot-ref (.$ encrypted-private-key-info-encryption-algorithm asn1-encodable-container-c) algorithm-identifier->x509-algorithm-identifier) :reader pkcs-encrypted-private-key-info-encryption-algorithm) (encrypted-date :allocation :virtual :cached #t :slot-ref (make-slot-ref (.$ encrypted-private-key-info-encrypted-data asn1-encodable-container-c) der-octet-string->bytevector) :reader pkcs-encrypted-private-key-info-encrypted-data))) (define (pkcs-encrypted-private-key-info? o) (is-a? o <pkcs-encrypted-private-key-info>)) (define (make-pkcs-encrypted-private-key-info (x509-aid x509-algorithm-identifier?) (bv bytevector?)) (define aid (x509-algorithm-identifier->algorithm-identifier x509-aid)) (make <pkcs-encrypted-private-key-info> :c (make <encrypted-private-key-info> :encryption-algorithm aid :encrypted-data (bytevector->der-octet-string bv)))) (define (bytevector->pkcs-encrypted-private-key-info bv) (read-pkcs-encrypted-private-key-info (open-bytevector-input-port bv))) (define (read-pkcs-encrypted-private-key-info in) (encrypted-private-key-info->pkcs-encrypted-private-key-info (asn1-object->asn1-encodable <encrypted-private-key-info> (read-asn1-object in)))) (define (encrypted-private-key-info->pkcs-encrypted-private-key-info epki) (make <pkcs-encrypted-private-key-info> :c epki)) (define (pkcs-encrypted-private-key-info->encrypted-private-key-info epki) (asn1-encodable-container-c epki)) (define (write-pkcs-encrypted-private-key-info epki :optional (out (current-output-port))) (put-bytevector out (pkcs-encrypted-private-key-info->bytevector epki))) (define (pkcs-encrypted-private-key-info->bytevector epki) (asn1-encodable->bytevector (pkcs-encrypted-private-key-info->encrypted-private-key-info epki))) (define (pkcs-one-asymmetric-key->pkcs-encrypted-private-key-info (oak pkcs-one-asymmetric-key?) (aid x509-algorithm-identifier?) key . opts) (let ((data (pkcs-one-asymmetric-key->bytevector oak))) (make-pkcs-encrypted-private-key-info aid (apply pkcs-encrypt-data aid key data opts)))) (define (pkcs-encrypted-private-key-info->pkcs-one-asymmetric-key (epki pkcs-encrypted-private-key-info?) key . opts) (define aid (pkcs-encrypted-private-key-info-encryption-algorithm epki)) (define data (pkcs-encrypted-private-key-info-encrypted-data epki)) (bytevector->pkcs-one-asymmetric-key (apply pkcs-decrypt-data aid key data opts))) )
false
ea072f621bde7e8c184e1e9663116b8bbb6f6138
a7a99f1f9124d23b04558fdac002f9153079b9c0
/sine/interpreter.ss
f5395174884f5d0c8c0c114a2c84cc15033a1fc7
[]
no_license
stuhlmueller/sine
a451c3803283de220f3475dba4c6c1fcde883822
ce6ec938e8f46c31925f23b557284405c1ba0b11
refs/heads/master
2016-09-06T10:23:19.360983
2012-07-20T21:09:59
2012-07-20T21:10:11
3,517,254
4
0
null
null
null
null
UTF-8
Scheme
false
false
8,473
ss
interpreter.ss
#!r6rs ;; Based on metacircular interpreter in SICP and MIT-CHURCH. ;; ;; Extensions: ;; - added random primitives ;; - interpreter takes two additional arguments: ;; - a function that will be called instead of the interpreter on recursive calls ;; - a function that will be called when the interpreter needs randomness ;; - all data structures are "compressed" value-number objects ;; - environments are vectors of relevant variables (library (sine interpreter) (export (rename (eval interpreter-eval)) interpreter sicp-interpreter default-source make-default-subcall setup-environment) (import (rename (rnrs) (apply scheme-apply)) (sine preamble) (sine env-flat) (sine syntax) (sine desugar) (sine primitives) (scheme-tools value-number) (scheme-tools srfi-compat :1) (only (scheme-tools) true? false? rest pair tagged-list? compose pe) (only (scheme-tools math) random-real)) ;; -------------------------------------------------------------------- ;; Eval (define (eval-dispatch-fn syntax) (cond [(syntax:self-evaluating? syntax) eval-self-evaluating] [(syntax:variable? syntax) eval-variable] [(syntax:quoted? syntax) eval-quoted] [(syntax:lambda? syntax) eval-lambda] [(syntax:if? syntax) eval-if] [(syntax:cache? syntax) eval-cache] [(syntax:application? syntax) eval-application] [else (error syntax "eval: unknown expression type")])) (define (eval syntax env subcall source) (let ([dispatch-fn (eval-dispatch-fn syntax)]) (dispatch-fn syntax env subcall source))) (define (eval-if syntax env subcall source) (if (true? (&expand-boolean (subcall (if-syntax->if-predicate syntax) env))) (subcall (if-syntax->if-consequent syntax) env) (subcall (if-syntax->if-alternative syntax) env))) (define (eval-cache syntax env subcall source) (subcall (cache-syntax->content syntax) env)) (define (eval-lambda syntax env subcall source) (make-procedure (lambda-syntax->lambda-parameters syntax) (lambda-syntax->lambda-body syntax) (restrict-environment (syntax->&free-vars syntax) env))) (define (eval-quoted syntax env subcall source) (quote-syntax->text-of-quotation syntax)) (define (eval-variable syntax env subcall source) (let [(closure-address (variable-syntax->lexical-address syntax))] (lookup-value-by-id closure-address env))) (define (eval-self-evaluating syntax env subcall source) (self-evaluating-syntax->value syntax)) (define (eval-application syntax env subcall source) (apply (subcall (application-syntax->operator-syntax syntax) env) (list-of-values (application-syntax->operands-syntax syntax) env subcall) subcall source)) (define (list-of-values exps env subcall) (if (null? exps) '() (cons (subcall (first exps) env) (list-of-values (rest exps) env subcall)))) (define (eval-sequence exps env subcall) (cond ((null? (cdr exps)) (subcall (first exps) env)) (else (subcall (first exps) env) (eval-sequence (rest exps) env subcall)))) ;; -------------------------------------------------------------------- ;; Apply (define (apply? &proc) (and (&symbol?->b &proc) (eq? (&expand-symbol &proc) 'apply))) (define (apply-dispatch-fn procedure) (cond [(apply? procedure) apply-apply] [(deterministic-primitive-procedure? procedure) apply-deterministic-primitive-procedure] [(stochastic-primitive-procedure? procedure) apply-stochastic-primitive-procedure] [(compound-procedure? procedure) apply-compound-procedure] [else (begin (pe "got: " procedure "\n" "expanded: " (&expand-recursive procedure) "\n") (error procedure "apply: unknown procedure type"))])) (define (apply procedure arguments subcall source) (let ([dispatch-fn (apply-dispatch-fn procedure)]) (dispatch-fn procedure arguments subcall source))) (define (bindings params vals) (cond [(null? params) (pair '() '())] [(symbol? params) (pair (list params) (if (symbol? vals) (list vals) (list (compress-list vals))))] [else (if (null? vals) (error (pair params vals) "bindings: not enough arguments!") (let ([remainder (bindings (rest params) (rest vals))]) (pair (pair (first params) (first remainder)) (pair (first vals) (rest remainder)))))])) (define (apply-compound-procedure proc args subcall source) (let* ([binds (bindings (procedure-parameters proc) args)] [binding-vars (first binds)] [binding-vals (rest binds)]) (subcall (procedure-body proc) (extend-environment binding-vars binding-vals (procedure-environment proc))))) (define (apply-apply proc args subcall source) (apply (car args) (&expand-list (cadr args)) subcall source)) ;; -------------------------------------------------------------------- ;; Procedure data type (compressed) (define (make-procedure parameters &body &env) (&list (compress-symbol 'procedure) (compress-recursive parameters) &body &env)) (define (compound-procedure? &p) (&tagged-list?->b &p 'procedure)) (define (procedure-parameters p) (&expand-recursive (&cadr p))) (define (procedure-body p) (&caddr p)) (define (procedure-environment p) (&cadddr p)) ;; -------------------------------------------------------------------- ;; Primitive procedures, generic (compressed) (define (primitive-implementation &proc) (&expand-procedure (&cadr &proc))) (define (primitive-procedure-names procs) (map car procs)) (define (primitive-procedure-objects procs type-symbol) (map (lambda (proc) (&list (compress-symbol type-symbol) (compress-procedure (cadr proc) (car proc)))) procs)) (define (all-primitive-names) (append (primitive-procedure-names deterministic-primitive-procedures) (primitive-procedure-names stochastic-primitive-procedures) (map car primitive-constants))) (define (all-primitive-objects) (append (primitive-procedure-objects deterministic-primitive-procedures 'primitive) (primitive-procedure-objects stochastic-primitive-procedures 'rand) (map second primitive-constants))) ;; -------------------------------------------------------------------- ;; Deterministic primitive procedures (compressed) (define (deterministic-primitive-procedure? &proc) (&tagged-list?->b &proc 'primitive)) (define (apply-deterministic-primitive-procedure &proc args subcall source) (scheme-apply (primitive-implementation &proc) args)) ;; -------------------------------------------------------------------- ;; Stochastic primitive procedures (compressed) (define (stochastic-primitive-procedure? &proc) (&tagged-list?->b &proc 'rand)) (define (apply-stochastic-primitive-procedure &proc args subcall source) (scheme-apply (primitive-implementation &proc) (cons source args))) ;; -------------------------------------------------------------------- ;; Top-level (define (setup-environment) (extend-environment (all-primitive-names) (all-primitive-objects) (the-empty-environment))) (define default-source (lambda (p) (< (random-real) p))) (define (make-default-subcall source) (letrec ([subcall (lambda (syntax env) (begin (assert (syntax? syntax)) (eval syntax env subcall source)))]) subcall)) (define (interpreter expr subcall) (let ([env (setup-environment)]) (subcall (sexpr->syntax expr env) env))) (define (sicp-interpreter expr) (let ([env (setup-environment)] [subcall (make-default-subcall default-source)]) (&expand-recursive (subcall (sexpr->syntax (with-preamble expr) env) env)))) )
false
bfcad1b009a3343bb1685bc5345ce9fc683777b5
6438e08dfc709754e64a4d8e962c422607e5ed3e
/scheme/gamesh.scm
5dec716a3a17a4938e85dbde1a3c41e90512528a
[]
no_license
HugoNikanor/GuileGamesh
42043183167cdc9d45b4dc626266750aecbee4ff
77d1be4a20b3f5b9ff8f18086bf6394990017f23
refs/heads/master
2018-10-13T10:54:00.134522
2018-07-11T19:45:15
2018-07-11T19:45:15
110,285,413
0
0
null
null
null
null
UTF-8
Scheme
false
false
5,844
scm
gamesh.scm
(define-module (gamesh) #:use-module (scene scene2) #:use-module (scene scene3) #:use-module (scene scene4) #:use-module (scene scene5) #:use-module (event) ; event-func ;; These three are for event-func to work #:use-module (event key) #:use-module (event mouse-btn) #:use-module (event mouse-motion) #:use-module (vector) #:use-module (engine) #:use-module (oop goops) #:use-module (oop goops describe) #:use-module (objects character) #:use-module (objects sprite) #:use-module (objects tileworld) #:use-module (objects scene-changer) #:use-module (scene) ;; Only (mines scene) is needed to be imported, ;; the others are just for testing. #:use-module (mines scene) #:use-module (mines square) #:use-module (mines board) #:use-module (mines helpers) #:use-module (mines utils) #:use-module (objects camera-panner) ) ;; (define c (create-character (@@ (scene scene2) f))) (define scenelist (list scene2 scene3 scene4 scene5 mine-scene ) ) (define scene-changer (make <scene-changer> #:list scenelist)) ;; imported from scene2 (set-current-scene! mine-scene) (for-each (lambda (scene) (add-event-listener! <keyboard-event> (make-camera-panner (current-camera scene)) scene)) scenelist) #| (define-method (event-do (box <box>) (event <key-event>)) (slot-set! other-debug 'text "huh?")) |# ;;; These should be moved to objects/text.scm #| (define-method (draw-func (text <text-obj>)) (draw-text (slot-ref text 'text) (x (pos text)) (y (pos text)))) (define-method (tick-func (text <text-obj>)) (let ((func (slot-ref text 'update-text))) (when func (slot-set! text 'text (func text))))) |# ;;; ------------------------------------------------------------ ;;; ------------------------------------------------------------ ;; (define input-listener (make <game-object> #:name "[INPUT LISTENER]")) ;; (register-event-object! input-listener) ;(slot-set! (current-scene) 'name "SCENE 1") ;(define scene1 (current-scene)) ;(define scene2 (make <scene> #:name "SCENE 2")) ;(set-current-scene! scene1) ;(set-current-scene! scene2) #| ;; TODO this only works in scene2 ;;;(define-method (event-do (obj <ctrl-box>) (define-method (event-do (obj <ctrl-el>) (event <key-event>)) ;;;;(display (slot-ref event 'scancode)) (case (slot-ref event 'scancode) ((82) (slot-mod! (pos obj) 'y 1- )) ;; ((81) (slot-mod! (pos obj) 'y 1+ )) ((79) (slot-mod! (pos obj) 'x 1+ )) ;; ((80) (slot-mod! (pos obj) 'x 1- )) (else #f)) (next-method)) |# ;;; ------------------------------------------------------------ #| (define-class <tile-set> (<game-object>) tile-sheet ; SDL_texture tile-size ; 16 board-size ; v2 16 16 (in tiles) ) (define tileset (make <tile-set>)) (slot-set! tileset 'tile-size 16) (slot-set! tileset 'board-size (make <v2> #:x 32 #:y 32)) (define tile-defs (make-array '(0 0) '(0 31) '(0 31))) (define-method (draw-func (tileset <tile-set>)) (apply-for-each (lambda (x y) (render-texture (slot-ref tileset 'tile-sheet) (slot-ref tileset 'tile-size) ;'(0 0) ; sprite position in sheet (array-ref tile-defs y x) (list x y))) (cart-prod (iota (x (slot-ref tileset 'board-size))) (iota (y (slot-ref tileset 'board-size)))))) (define (next-tile tile) (let ((a (car tile)) (b (cadr tile))) (if (= b 31) (list (1+ a) b) (list a (1+ b))))) (define mouse-pos #f) (define tiles-of-interest '((2 0) (2 1) (2 2) (1 0) (1 1) (1 2) (0 0) (0 1) (0 2))) ;; 49 - 57 sym ;; 89 - 97 u 30 - 39 scancode (define-method (event-do (tileset <tile-set>) (event <key-event>)) (when mouse-pos (let ((x (floor (/ (x mouse-pos) 16))) (y (floor (/ (y mouse-pos) 16)))) (let ((n (slot-ref event 'scancode))) (cond ((< 30 n 39) (set! n (- n 30))) ((< 89 n 98) (set! n (- n 89)))) (when (<= 1 n 9) (array-set! tile-defs (list-ref tiles-of-interest n) y x))))) (next-method)) (define-method (event-do (tileset <tile-set>) (event <mouse-motion-event>)) (set! mouse-pos (make <v2> #:x (mousem-x event) #:y (mousem-y event))) (next-method)) (register-event-object! tileset) ;;(register-draw-object! other-debug) (register-draw-object! box-pos) (register-tick-object! box-pos) ;; Note that objects can be shared between scenes ;; (slot-set! other-debug 'text "Hello, World!") (define fpath "/home/hugo/code/guile/engine/assets/PathAndObjects_0.png") (define (init-tile-set) (slot-set! tileset 'tile-sheet (load-image fpath)) (register-draw-object! tileset scene2)) (define removed-scene3 (make <scene> #:name "SCENE 3")) (set-current-scene! scene3) ;;(define-class <tileset-grid> (<tile-set>)) (define-class <tileset-grid> ()) (define-method (draw-func (obj <tileset-grid>)) (for-each (lambda (y) (for-each (lambda (x) (draw-line 0 y 512 y) (draw-line x 0 x 512)) (map (cut * <> 16) (iota 32)))) (map (cut * <> 16) (iota 32))) ;;(next-method)) ) (define ts-grid (make <tileset-grid>)) (register-draw-object! ts-grid) |# ;; (set-current-scene! scene2)
false
e091fc1c58334e9d29ff52d7fab2b80ae8d9c25b
c060c077dd2e5a662c9bcbec20a0958daff89afc
/src/Llib/mk.scm
f8d5fdcfb708d42ae21efe3a27fbc97abeb8fd78
[]
no_license
donaldsonjw/bkanren
fffa5d40ee3f29b364dda7595e7a640b7bd80ea5
14fec22a95530097be18a621b505db26737ce2dd
refs/heads/master
2021-01-10T18:41:06.993461
2016-10-16T21:30:47
2016-10-16T21:30:47
17,566,085
2
1
null
2014-11-07T14:21:38
2014-03-09T14:33:21
Scheme
UTF-8
Scheme
false
false
22,908
scm
mk.scm
(module bkanren (include "mk.sch") (export mk-take bind == succeed fail choice empty-f (inline make-var s) var? var-s reify reify-name walk* eigen-var eigen-absento empty-c (inline make-c b e s d y n g t) ;(syntax make-c) ground? mplus mzero unit absento symbolo numbero booleano stringo onceo =/= c->B c->E c->S c->D c->Y c->N c->G c->T else ) (export (final-class %var sym) (final-class %package (B (default '())) (E (default '())) (S (default '())) (D (default '())) (Y (default '())) (N (default '())) (G (default '())) (T (default '())) )) ) ;;; newer version: Sept. 18 2013 (with eigens) ;;; Jason Hemann, Will Byrd, and Dan Friedman ;;; E = (e* . x*)*, where e* is a list of eigens and x* is a list of variables. ;;; Each e in e* is checked for any of its eigens be in any of its x*. Then it fails. ;;; Since eigen-occurs-check is chasing variables, we might as will do a memq instead ;;; of an eq? when an eigen is found through a chain of walks. See eigen-occurs-check. ;;; All the e* must be the eigens created as part of a single eigen. The reifier just ;;; abandons E, if it succeeds. If there is no failure by then, there were no eigen ;;; violations. ;; add missing r6rs remp function (define (remp proc list) (filter (lambda (x) (not (proc x))) list)) ;; add missing exists function (define exists any) ;; original minikanren file (define c->B (lambda (c::%package) (-> c B))) (define c->E (lambda (c::%package) (-> c E))) (define c->S (lambda (c::%package) (-> c S))) (define c->D (lambda (c::%package) (-> c D))) (define c->Y (lambda (c::%package) (-> c Y))) (define c->N (lambda (c::%package) (-> c N))) (define c->G (lambda (c::%package) (-> c G))) (define c->T (lambda (c::%package) (-> c T))) (define empty-c (instantiate::%package)) (define-inline (make-c b e s d y n g t) (instantiate::%package (B b) (E e) (S s) (D d) (Y y) (N n) (G g) (T t)) ) ; (define-syntax make-c (syntax-rules () ; ([_ b e s d y n g t] ; (instantiate::%package (B b) (E e) (S s) (D d) (Y y) (N n) (G g) (T t)) ; ))) (define eigen-tag (vector 'eigen-tag)) (define rhs (lambda (pr) (cdr pr))) (define lhs (lambda (pr) (car pr))) (define eigen-var (lambda () (vector eigen-tag))) (define eigen? (lambda (x) (and (vector? x) (eq? (vector-ref x 0) eigen-tag)))) (define-inline (make-var dummy) (instantiate::%var (sym dummy)) ) (define var? (lambda (x) (isa? x %var))) (define var-s (lambda (c::%var) (-> c sym))) ; (define var ; (lambda (dummy) ; (vector dummy))) ; (define var? ; (lambda (x) ; (and (vector? x) (not (eq? (vector-ref x 0) eigen-tag))))) (define walk (lambda (u S) (cond ((and (var? u) (assq u S)) => (lambda (pr) (walk (rhs pr) S))) (else u)))) (define prefix-S (lambda (S+ S) (cond ((eq? S+ S) '()) (else (cons (car S+) (prefix-S (cdr S+) S)))))) (define unify (lambda (u v s) (let ((u (walk u s)) (v (walk v s))) (cond ((eq? u v) s) ((var? u) (ext-s-check u v s)) ((var? v) (ext-s-check v u s)) ((and (pair? u) (pair? v)) (let ((s (unify (car u) (car v) s))) (and s (unify (cdr u) (cdr v) s)))) ((or (eigen? u) (eigen? v)) #f) ((equal? u v) s) (else #f))))) (define occurs-check (lambda (x v s) (let ((v (walk v s))) (cond ((var? v) (eq? v x)) ((pair? v) (or (occurs-check x (car v) s) (occurs-check x (cdr v) s))) (else #f))))) (define eigen-occurs-check (lambda (e* x s) (let ((x (walk x s))) (cond ((var? x) #f) ((eigen? x) (memq x e*)) ((pair? x) (or (eigen-occurs-check e* (car x) s) (eigen-occurs-check e* (cdr x) s))) (else #f))))) (define empty-f (lambdaf@ () (mzero))) (define ext-s-check (lambda (x v s) (cond ((occurs-check x v s) #f) (else (cons `(,x . ,v) s))))) (define unify* (lambda (S+ S) (unify (map lhs S+) (map rhs S+) S))) (define bind (lambda (c-inf g) (case-inf c-inf (() (mzero)) ((f) (inc (bind (f) g))) ((c) (g c)) ((c f) (mplus (g c) (lambdaf@ () (bind (f) g))))))) (define mk-take (lambda (n f) (cond ((and n (zero? n)) '()) (else (case-inf (f) (() '()) ((f) (mk-take n f)) ((c) (cons c '())) ((c f) (cons c (mk-take (and n (- n 1)) f)))))))) (define mplus (lambda (c-inf f) (case-inf c-inf (() (f)) ((f^) (inc (mplus (f) f^))) ((c) (choice c f)) ((c f^) (choice c (lambdaf@ () (mplus (f) f^))))))) (define mzero (lambda () #f)) (define unit (lambda (c) c)) (define choice (lambda (c f) (cons c f))) (define tagged? (lambda (S Y y^) (exists (lambda (y) (eqv? (walk y S) y^)) Y))) (define untyped-var? (lambda (S Y N t^) (let ((in-type? (lambda (y) (eq? (walk y S) t^)))) (and (var? t^) (not (exists in-type? Y)) (not (exists in-type? N)))))) (define walk* (lambda (v S) (let ((v (walk v S))) (cond ((var? v) v) ((pair? v) (cons (walk* (car v) S) (walk* (cdr v) S))) (else v))))) (define reify-S (lambda (v S) (let ((v (walk v S))) (cond ((var? v) (let ((n (length S))) (let ((name (reify-name n))) (cons `(,v . ,name) S)))) ((pair? v) (let ((S (reify-S (car v) S))) (reify-S (cdr v) S))) (else S))))) (define reify-name (lambda (n) (string->symbol (string-append "_" "." (number->string n))))) (define drop-dot (lambda (X) (map (lambda (t) (let ((a (lhs t)) (d (rhs t))) `(,a ,d))) X))) (define sorter (lambda (ls) (sort lex<=? ls))) (define lex<=? (lambda (x y) (string<=? (datum->string x) (datum->string y)))) (define datum->string (lambda (x) (call-with-output-string (lambda (p) (display x p))))) (define anyvar? (lambda (u r) (cond ((pair? u) (or (anyvar? (car u) r) (anyvar? (cdr u) r))) (else (var? (walk u r)))))) ; (define (ground? u) ; (lambda (S) ; (not (anyvar? u S)))) (define ground? (lambda (v) (cond ((var? v) #f) ((pair? v) (and (ground? (car v)) (ground? (cdr v)))) (else #t)))) (define anyeigen? (lambda (u r) (cond ((pair? u) (or (anyeigen? (car u) r) (anyeigen? (cdr u) r))) (else (eigen? (walk u r)))))) (define member* (lambda (u v) (cond ((equal? u v) #t) ((pair? v) (or (member* u (car v)) (member* u (cdr v)))) (else #f)))) ;;; (define drop-G-b/c-const (lambdag@ (c : B E S D Y N G T) (let ((const? (lambda (n) (not (var? (walk n S)))))) (cond ((find const? G) => (lambda (g) (make-c B E S D Y N (remq1 g G) T))) (else c))))) (define drop-N-b/c-const (lambdag@ (c : B E S D Y N G T) (let ((const? (lambda (n) (not (var? (walk n S)))))) (cond ((find const? N) => (lambda (n) (make-c B E S D Y (remq1 n N) G T))) (else c))))) (define drop-Y-b/c-const (lambdag@ (c : B E S D Y N G T) (let ((const? (lambda (y) (not (var? (walk y S)))))) (cond ((find const? Y) => (lambda (y) (make-c B E S D (remq1 y Y) N G T))) (else c))))) (define remq1 (lambda (elem ls) (cond ((null? ls) '()) ((eq? (car ls) elem) (cdr ls)) (else (cons (car ls) (remq1 elem (cdr ls))))))) (define same-var? (lambda (v) (lambda (v^) (and (var? v) (var? v^) (eq? v v^))))) (define find-dup (lambda (f S) (lambda (set) (let loop ((set^ set)) (cond ((null? set^) #f) (else (let ((elem (car set^))) (let ((elem^ (walk elem S))) (cond ((find (lambda (elem^^) ((f elem^) (walk elem^^ S))) (cdr set^)) elem) (else (loop (cdr set^)))))))))))) (define drop-G-b/c-dup-var (lambdag@ (c : B E S D Y N G T) (cond (((find-dup same-var? S) G) => (lambda (g) (make-c B E S D Y N (remq1 g G) T))) (else c)))) (define drop-N-b/c-dup-var (lambdag@ (c : B E S D Y N G T) (cond (((find-dup same-var? S) N) => (lambda (n) (make-c B E S D Y (remq1 n N) G T))) (else c)))) (define drop-Y-b/c-dup-var (lambdag@ (c : B E S D Y N G T) (cond (((find-dup same-var? S) Y) => (lambda (y) (make-c B E S D (remq1 y Y) N G T))) (else c)))) (define var-type-mismatch? (lambda (S Y N G t1^ t2^) (cond ((num? S N t1^) (not (num? S N t2^))) ((sym? S Y t1^) (not (sym? S Y t2^))) ((str? S G t1^) (not (str? S G t2^))) (else #f)))) (define term-ununifiable? (lambda (S Y N G t1 t2) (let ((t1^ (walk t1 S)) (t2^ (walk t2 S))) (cond ((or (untyped-var? S Y N t1^) (untyped-var? S Y N t2^)) #f) ((var? t1^) (var-type-mismatch? S Y N G t1^ t2^)) ((var? t2^) (var-type-mismatch? S Y N G t2^ t1^)) ((and (pair? t1^) (pair? t2^)) (or (term-ununifiable? S Y N G (car t1^) (car t2^)) (term-ununifiable? S Y N G (cdr t1^) (cdr t2^)))) (else (not (eqv? t1^ t2^))))))) (define T-term-ununifiable? (lambda (S Y N G) (lambda (t1) (let ((t1^ (walk t1 S))) (letrec ((t2-check (lambda (t2) (let ((t2^ (walk t2 S))) (cond ((pair? t2^) (and (term-ununifiable? S Y N G t1^ t2^) (t2-check (car t2^)) (t2-check (cdr t2^)))) (else (term-ununifiable? S Y N G t1^ t2^))))))) t2-check))))) (define num? (lambda (S N n) (let ((n (walk n S))) (cond ((var? n) (tagged? S N n)) (else (number? n)))))) (define sym? (lambda (S Y y) (let ((y (walk y S))) (cond ((var? y) (tagged? S Y y)) (else (symbol? y)))))) (define str? (lambda (S G g) (let ((n (walk g S))) (cond ((var? g) (tagged? S G g)) (else (string? g)))))) (define drop-T-b/c-Y-and-N (lambdag@ (c : B E S D Y N G T) (let ((drop-t? (T-term-ununifiable? S Y N G))) (cond ((find (lambda (t) ((drop-t? (lhs t)) (rhs t))) T) => (lambda (t) (make-c B E S D Y N G (remq1 t T)))) (else c))))) (define move-T-to-D-b/c-t2-atom (lambdag@ (c : B E S D Y N G T) (cond ((exists (lambda (t) (let ((t2^ (walk (rhs t) S))) (cond ((and (not (untyped-var? S Y N t2^)) (not (pair? t2^))) (let ((T (remq1 t T))) (make-c B E S `((,t) . ,D) Y N G T))) (else #f)))) T)) (else c)))) (define terms-pairwise=? (lambda (pr-a^ pr-d^ t-a^ t-d^ S) (or (and (term=? pr-a^ t-a^ S) (term=? pr-d^ t-a^ S)) (and (term=? pr-a^ t-d^ S) (term=? pr-d^ t-a^ S))))) (define for-all (lambda (f ls . more) (let for-all ([ls ls] [more more] [a #t]) (if (null? ls) a (let ([a (apply f (car ls) (map car more))]) (and a (for-all (cdr ls) (map cdr more) a))) )) )) (define T-superfluous-pr? (lambda (S Y N T) (lambda (pr) (let ((pr-a^ (walk (lhs pr) S)) (pr-d^ (walk (rhs pr) S))) (cond ((exists (lambda (t) (let ((t-a^ (walk (lhs t) S)) (t-d^ (walk (rhs t) S))) (terms-pairwise=? pr-a^ pr-d^ t-a^ t-d^ S))) T) (for-all (lambda (t) (let ((t-a^ (walk (lhs t) S)) (t-d^ (walk (rhs t) S))) (or (not (terms-pairwise=? pr-a^ pr-d^ t-a^ t-d^ S)) (untyped-var? S Y N t-d^) (pair? t-d^)))) T)) (else #f)))))) (define drop-from-D-b/c-T (lambdag@ (c : B E S D Y N G T) (cond ((find (lambda (d) (exists (T-superfluous-pr? S Y N T) d)) D) => (lambda (d) (make-c B E S (remq1 d D) Y N G T))) (else c)))) (define drop-t-b/c-t2-occurs-t1 (lambdag@ (c : B E S D Y N G T) (cond ((find (lambda (t) (let ((t-a^ (walk (lhs t) S)) (t-d^ (walk (rhs t) S))) (mem-check t-d^ t-a^ S))) T) => (lambda (t) (make-c B E S D Y N G (remq1 t T)))) (else c)))) (define split-t-move-to-d-b/c-pair (lambdag@ (c : B E S D Y N G T) (cond ((exists (lambda (t) (let ((t2^ (walk (rhs t) S))) (cond ((pair? t2^) (let ((ta `(,(lhs t) . ,(car t2^))) (td `(,(lhs t) . ,(cdr t2^)))) (let ((T `(,ta ,td . ,(remq1 t T)))) (make-c B E S `((,t) . ,D) Y N G T)))) (else #f)))) T)) (else c)))) (define find-d-conflict (lambda (S Y N G) (lambda (D) (find (lambda (d) (exists (lambda (pr) (term-ununifiable? S Y N G (lhs pr) (rhs pr))) d)) D)))) (define drop-D-b/c-Y-or-N (lambdag@ (c : B E S D Y N G T) (cond (((find-d-conflict S Y N G) D) => (lambda (d) (make-c B E S (remq1 d D) Y N G T))) (else c)))) (define cycle (lambdag@ (c) (let loop ((c^ c) (fns^ (LOF)) (n (length (LOF)))) (cond ((zero? n) c^) ((null? fns^) (loop c^ (LOF) n)) (else (let ((c^^ ((car fns^) c^))) (cond ((not (eq? c^^ c^)) (loop c^^ (cdr fns^) (length (LOF)))) (else (loop c^ (cdr fns^) (- n 1)))))))))) (define absento (lambda (u v) (lambdag@ (c : B E S D Y N G T) (cond [(mem-check u v S) (mzero)] [else (unit (make-c B E S D Y N G `((,u . ,v) . ,T)))])))) (define eigen-absento (lambda (e* x*) (lambdag@ (c : B E S D Y N G T) (cond [(eigen-occurs-check e* x* S) (mzero)] [else (unit (make-c B `((,e* . ,x*) . ,E) S D Y N G T))])))) (define mem-check (lambda (u t S) (let ((t (walk t S))) (cond ((pair? t) (or (term=? u t S) (mem-check u (car t) S) (mem-check u (cdr t) S))) (else (term=? u t S)))))) (define term=? (lambda (u t S) (cond ((unify u t S) => (lambda (S0) (eq? S0 S))) (else #f)))) (define ground-non-<type>? (lambda (pred) (lambda (u S) (let ((u (walk u S))) (cond ((var? u) #f) (else (not (pred u)))))))) ;; moved (define ground-non-string? (ground-non-<type>? string?)) (define ground-non-symbol? (ground-non-<type>? symbol?)) (define ground-non-number? (ground-non-<type>? number?)) (define symbolo (lambda (u) (lambdag@ (c : B E S D Y N G T) (cond [(ground-non-symbol? u S) (mzero)] [(mem-check u N S) (mzero)] [(mem-check u G S) (mzero)] [else (unit (make-c B E S D `(,u . ,Y) N G T))])))) (define stringo (lambda (u) (lambdag@ (c : B E S D Y N G T) (cond [(ground-non-string? u S) (mzero)] [(mem-check u N S) (mzero)] [(mem-check u Y S) (mzero)] [else (unit (make-c B E S D Y N `(,u . ,G) T))])))) (define numbero (lambda (u) (lambdag@ (c : B E S D Y N G T) (cond [(ground-non-number? u S) (mzero)] [(mem-check u Y S) (mzero)] [(mem-check u G S) (mzero)] [else (unit (make-c B E S D Y `(,u . ,N) G T))])))) ;; end moved (define =/= ;; moved (lambda (u v) (lambdag@ (c : B E S D Y N G T) (cond ((unify u v S) => (lambda (S0) (let ((pfx (prefix-S S0 S))) (cond ((null? pfx) (mzero)) (else (unit (make-c B E S `(,pfx . ,D) Y N G T))))))) (else c))))) (define == (lambda (u v) (lambdag@ (c : B E S D Y N G T) (cond ((unify u v S) => (lambda (S0) (cond ((==fail-check B E S0 D Y N G T) (mzero)) (else (unit (make-c B E S0 D Y N G T)))))) (else (mzero)))))) (define succeed (== #f #f)) (define fail (== #f #t)) (define ==fail-check (lambda (B E S0 D Y N G T) (cond ((eigen-absento-fail-check E S0) #t) ((atomic-fail-check S0 G ground-non-string?) #t) ((atomic-fail-check S0 Y ground-non-symbol?) #t) ((atomic-fail-check S0 N ground-non-number?) #t) ((symbolo-numbero-stringo-fail-check S0 Y N G) #t) ((=/=-fail-check S0 D) #t) ((absento-fail-check S0 T) #t) (else #f)))) (define eigen-absento-fail-check (lambda (E S0) (exists (lambda (e*/x*) (eigen-occurs-check (car e*/x*) (cdr e*/x*) S0)) E))) (define atomic-fail-check (lambda (S A pred) (exists (lambda (a) (pred (walk a S) S)) A))) (define symbolo-numbero-stringo-fail-check (lambda (S A N G) (let ((N (map (lambda (n) (walk n S)) N)) (G (map (lambda (g) (walk g S)) G))) (exists (lambda (a) (let ([a (walk a S)]) (or (exists (same-var? a) N) (exists (same-var? a) G) ))) A)))) (define absento-fail-check (lambda (S T) (exists (lambda (t) (mem-check (lhs t) (rhs t) S)) T))) (define =/=-fail-check (lambda (S D) (exists (d-fail-check S) D))) (define d-fail-check (lambda (S) (lambda (d) (cond ((unify* d S) => (lambda (S+) (eq? S+ S))) (else #f))))) (define reify (lambda (x) (lambda (c) (let ((c (cycle c))) (let* ((S (c->S c)) (D (walk* (c->D c) S)) (Y (walk* (c->Y c) S)) (N (walk* (c->N c) S)) (G (walk* (c->G c) S)) (T (walk* (c->T c) S))) (let ((v (walk* x S))) (let ((R (reify-S v '()))) (reify+ v R (let ((D (remp (lambda (d) (let ((dw (walk* d S))) (or (anyvar? dw R) (anyeigen? dw R)))) (rem-xx-from-d D S)))) (rem-subsumed D)) (remp (lambda (y) (var? (walk y R))) Y) (remp (lambda (n) (var? (walk n R))) N) (remp (lambda (g) (var? (walk g R))) G) (remp (lambda (t) (or (anyeigen? t R) (anyvar? t R))) T))))))))) (define reify+ (lambda (v R D Y N G T) (form (walk* v R) (walk* D R) (walk* Y R) (walk* N R) (walk* G R) (rem-subsumed-T (walk* T R))))) (define form (lambda (v D Y N G T) (let ((fd (sort-D D)) (fy (sorter Y)) (fn (sorter N)) (fg (sorter G)) (ft (sorter T))) (let ((fd (if (null? fd) fd (let ((fd (drop-dot-D fd))) `((=/= . ,fd))))) (fy (if (null? fy) fy `((sym . ,fy)))) (fn (if (null? fn) fn `((num . ,fn)))) (fg (if (null? fg) fg `((str . ,fg)))) (ft (if (null? ft) ft (let ((ft (drop-dot ft))) `((absento . ,ft)))))) (cond ((and (null? fd) (null? fy) (null? fn) (null? fg) (null? ft)) v) (else (append `(,v) fd fn fy fg ft))))))) (define sort-D (lambda (D) (sorter (map sort-d D)))) (define sort-d (lambda (d) (sort (lambda (x y) (lex<=? (car x) (car y))) (map sort-pr d)))) (define drop-dot-D (lambda (D) (map drop-dot D))) (define lex<-reified-name? (lambda (r) (char<? (string-ref (datum->string r) 0) #\_))) (define sort-pr (lambda (pr) (let ((l (lhs pr)) (r (rhs pr))) (cond ((lex<-reified-name? r) pr) ((lex<=? r l) `(,r . ,l)) (else pr))))) (define rem-subsumed (lambda (D) (let rem-subsumed ((D D) (d^* '())) (cond ((null? D) d^*) ((or (subsumed? (car D) (cdr D)) (subsumed? (car D) d^*)) (rem-subsumed (cdr D) d^*)) (else (rem-subsumed (cdr D) (cons (car D) d^*))))))) (define subsumed? (lambda (d d*) (cond ((null? d*) #f) (else (let ((d^ (unify* (car d*) d))) (or (and d^ (eq? d^ d)) (subsumed? d (cdr d*)))))))) (define rem-xx-from-d (lambda (D S) (remp not (map (lambda (d) (cond ((unify* d S) => (lambda (S0) (prefix-S S0 S))) (else #f))) D)))) (define rem-subsumed-T (lambda (T) (let rem-subsumed ((T T) (T^ '())) (cond ((null? T) T^) (else (let ((lit (lhs (car T))) (big (rhs (car T)))) (cond ((or (subsumed-T? lit big (cdr T)) (subsumed-T? lit big T^)) (rem-subsumed (cdr T) T^)) (else (rem-subsumed (cdr T) (cons (car T) T^)))))))))) (define subsumed-T? (lambda (lit big T) (cond ((null? T) #f) (else (let ((lit^ (lhs (car T))) (big^ (rhs (car T)))) (or (and (eq? big big^) (member* lit^ lit)) (subsumed-T? lit big (cdr T)))))))) (define LOF (lambda () `(,drop-G-b/c-const ,drop-N-b/c-const ,drop-Y-b/c-const ,drop-G-b/c-dup-var ,drop-N-b/c-dup-var ,drop-Y-b/c-dup-var ,drop-D-b/c-Y-or-N ,drop-T-b/c-Y-and-N ,move-T-to-D-b/c-t2-atom ,split-t-move-to-d-b/c-pair ,drop-from-D-b/c-T ,drop-t-b/c-t2-occurs-t1))) ;;;;; (define booleano (lambda (x) (conde ((== #f x)) ((== #t x))))) (define onceo (lambda (g) (condu (g)))) ;; define else as an alias for succeed ;; this permits more idiomatic scheme usage in conde (define else succeed)
true
3852ab61cd3589248c91b13f9423cc91b9bfacb5
4b480cab3426c89e3e49554d05d1b36aad8aeef4
/chapter-03/ex3.01-yarra.scm
d564e8813593150bf5f02aaca1d9c0ceeafe9900
[]
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
822
scm
ex3.01-yarra.scm
(load "../misc/scheme-test.scm") ; 3.1 ; Accumulator 란 여러 수를 차례대로 이어 받아서 합을 내는 프로시저인데, 이 프로시저를 ; 돌리면 그때까지 받은 인자 값을 모두 더한 값이 나온다고 하자. ; 새 accumulator 를 직어내는 프로시저 make-accumulator 를 정의하라. ; 단, accumulator 마다 더한 값을 따로 들게 해야 한다. make-accumulator 는 인자로 첫값을 ; 받는다. 아래는 그 사례다. ;(define A (make-accumulator 5)) ;(A 10) ==> 15 ;(A 10) ==> 25 ; solution (define (make-accumulator initval) (define (sum num) (begin (set! initval (+ initval num)) initval)) sum) ; test (define A (make-accumulator 5)) (run (make-testcase '(assert-equal? 15 (A 10)) '(assert-equal? 25 (A 10))))
false
cc2eb3addc7c640611f5b92dd0edea91013d25c3
648776d3a0d9a8ca036acaf6f2f7a60dcdb45877
/queries/lalrpop/highlights.scm
b6fda252e4c009ca5d2f524c0d57c66ca2bd0e8b
[ "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
801
scm
highlights.scm
[ "enum" "extern" "grammar" "match" "type" "pub" ] @keyword [ "match" "else" ] @conditional [ "+" "*" "?" ; TODO: inaccessible node ; => "=>@L" "=>@R" ] @operator (grammar_type_params ["<" ">"] @punctuation.bracket) (symbol ["<" ">"] @punctuation.bracket) (binding_symbol ["<" ">"] @punctuation.bracket) (binding_symbol name: (identifier) @parameter) (bare_symbol (macro ((macro_id) @type.definition))) (bare_symbol (identifier) @type.definition) (nonterminal_name (macro_id) @type.definition) (nonterminal_name (identifier) @type.definition) (nonterminal (type_ref) @type.builtin) ["(" ")" "[" "]"] @punctuation.bracket [";" ":"] @punctuation.delimiter (lifetime (identifier) @storageclass) (string_literal) @string (regex_literal) @string
false
a1b5382cec641e2c5e32d3c71b795ce62e672586
92b8d8f6274941543cf41c19bc40d0a41be44fe6
/kawa/lib/rnrs/programs.scm
66b11d76fe89c04e0282f8b8e1d610df15fc7912
[ "MIT" ]
permissive
spurious/kawa-mirror
02a869242ae6a4379a3298f10a7a8e610cf78529
6abc1995da0a01f724b823a64c846088059cd82a
refs/heads/master
2020-04-04T06:23:40.471010
2017-01-16T16:54:58
2017-01-16T16:54:58
51,633,398
6
0
null
null
null
null
UTF-8
Scheme
false
false
2,687
scm
programs.scm
(module-name <kawa.lib.rnrs.programs>) (module-export command-line exit emergency-exit) (require <kawa.lib.prim_syntax>) (define (command-line) :: list (let* ((rest ; Actual arguments, not including "argv[0]" equivalent. (gnu.lists.LList:makeList gnu.expr.ApplicationMainSupport:commandLineArgArray 0)) (command-name ;; Explicitly specified "argv[0]" equivalent ::java.lang.String (gnu.expr.ApplicationMainSupport:commandName:get #!null)) (arg0 (if (eq? command-name #!null) (let ((command ::java.lang.String (try-catch ;; No explicitly passed-in argv[0]. ;; Try looking at entire command line. (let* ((raw1 (java.lang.System:getProperty "kawa.command.line")) (raw (if (eq? raw1 #!null) (let ((raw2 (java.lang.System:getProperty "sun.java.command"))) (if (eq? raw2 #!null) #!null ("java ":concat raw2))) raw1))) (if (eq? raw #!null) #!null ;; Strip off the tail of the property value that ;; duplicates the rest value. (let* ((frest (format #f "~{ ~a~}" rest)) (rlen (raw:length)) (flen (frest:length)) (alen (- rlen flen))) (cond ((= flen 0) raw) ;; Sanity check ((and (>= alen 0) ((raw:substring alen):equals frest)) (raw:substring 0 alen)) (else #!null))))) (exp java.lang.Throwable #!null)))) (if (eq? command #!null) "kawa" command)) command-name))) (cons arg0 rest))) (define (exit #!optional (code 0)) :: void (let ((status :: int (cond ((integer? code) code) (code 0) (else -1)))) (gnu.kawa.util.ExitCalled:doExit status))) (define (emergency-exit #!optional (code 0)) :: void (let ((status :: int (cond ((integer? code) code) (code 0) (else -1)))) ((java.lang.Runtime:getRuntime):halt status)))
false