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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f09511287983ba47e316ff692155c32a0915007a
|
3508dcd12d0d69fec4d30c50334f8deb24f376eb
|
/tests/runtime/test-char-set.scm
|
e8e4642b133c367c86069b78ebd83428c805ba46
|
[] |
no_license
|
barak/mit-scheme
|
be625081e92c2c74590f6b5502f5ae6bc95aa492
|
56e1a12439628e4424b8c3ce2a3118449db509ab
|
refs/heads/master
| 2023-01-24T11:03:23.447076 | 2022-09-11T06:10:46 | 2022-09-11T06:10:46 | 12,487,054 | 12 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 10,121 |
scm
|
test-char-set.scm
|
#| -*-Scheme-*-
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, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016,
2017, 2018, 2019, 2020, 2021, 2022 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.
|#
;;;; Test of character-set abstraction
(declare (usual-integrations))
(define (make-segment start end)
(if (= (- end start) 1)
start
(cons start end)))
(define (segment-start segment)
(if (pair? segment)
(car segment)
segment))
(define (segment-end segment)
(if (pair? segment)
(cdr segment)
(+ segment 1)))
(define (append-map-tail! procedure items)
(if (pair? items)
(append! (procedure items)
(append-map-tail! procedure (cdr items)))
'()))
(define (every-tail pred items)
(if (pair? items)
(and (pred items)
(every-tail pred (cdr items)))
(pred items)))
(define interesting-points
(list 0
1
(- char-code-limit 1)
char-code-limit))
(define (mapper->generator mapper)
(lambda (points)
(let loop ((points points))
(if (pair? points)
(append! (mapper (car points) points)
(loop (cdr points)))
'()))))
(define 1-generator
(mapper->generator
(lambda (start ends)
(map (lambda (end)
(list (make-segment start end)))
ends))))
(define (n+1-generator n-generator)
(mapper->generator
(lambda (start tails)
(append-map-tail! (lambda (tail)
(let ((segment (make-segment start (car tail))))
(map (lambda (segments)
(cons segment segments))
(n-generator (cdr tail)))))
tails))))
(define 2-generator
(n+1-generator 1-generator))
(define 3-generator
(n+1-generator 2-generator))
(define interesting-svls
(cons (list)
(if keep-it-fast!?
(1-generator interesting-points)
(append! (1-generator interesting-points)
(2-generator interesting-points)
(3-generator interesting-points)))))
(define-test 'interesting-svl-round-trip
(map (lambda (svl)
(lambda ()
(with-test-properties
(lambda ()
(assert-equal-canonical-svls (trim-empty-segments svl)
(svl-round-trip svl)))
'EXPRESSION `(SVL-ROUND-TRIP ,svl))))
interesting-svls))
(define (svl-round-trip svl)
(char-set->code-points (char-set* svl)))
(define (make-random-svls n-ranges n-iter)
(map (lambda (i)
i
(make-random-svl n-ranges))
(iota n-iter)))
(define (make-random-svl n-ranges)
(let ((modulus #x1000))
(make-initialized-list n-ranges
(lambda (i)
i
(let loop ()
(let ((n (random (- char-code-limit modulus))))
(let ((m (random modulus)))
(if (= m 1)
n
(cons n (+ n m))))))))))
(define-test 'random-svl-round-trip
(map (lambda (svl)
(lambda ()
(with-test-properties
(lambda ()
(guarantee code-point-list? svl)
(assert-equal-canonical-svls (canonicalize-svl svl)
(svl-round-trip svl))))))
(append! (append-map! (lambda (i)
(make-random-svls i 100))
(iota 4 1))
(make-random-svls 100 100))))
(define (canonicalize-svl svl)
(named-call 'NORMALIZE-RANGES
normalize-ranges
svl))
(define-test 'membership
(map (lambda (svl)
(lambda ()
(map (lambda (value)
(with-test-properties
(lambda ()
(assert-boolean=
(char-in-set? (integer->char value) (char-set* svl))
(named-call 'SVL-MEMBER? svl-member? svl value))
(assert-boolean=
(code-point-in-char-set? value (char-set* svl))
(named-call 'SVL-MEMBER? svl-member? svl value)))
'EXPRESSION `(CHAR-IN-SET? ,value ,svl)))
(enumerate-test-values))))
interesting-svls))
(define (enumerate-test-values)
(append (iota #x808)
(if keep-it-fast!?
'()
(iota 8 (- char-code-limit 8)))))
(define (svl-member? svl value)
(let loop ((svl svl))
(if (pair? svl)
(if (and (<= (segment-start (car svl)) value)
(< value (segment-end (car svl))))
#t
(loop (cdr svl)))
#f)))
(define-test 'invert
(map (lambda (svl)
(lambda ()
(with-test-properties
(lambda ()
(assert-equal
(svl-invert-thru svl)
(svl-invert-direct (trim-empty-segments svl))))
'EXPRESSION `(SVL-INVERT ,svl))))
interesting-svls))
(define (svl-invert-thru svl)
(char-set->code-points (char-set-invert (char-set* svl))))
(define (svl-invert-direct svl)
(define (go svl prev-end)
(if (pair? svl)
(cons (make-segment prev-end
(segment-start (car svl)))
(go (cdr svl)
(segment-end (car svl))))
(if (< prev-end char-code-limit)
(list (make-segment prev-end char-code-limit))
'())))
(if (and (pair? svl)
(= (segment-start (car svl)) 0))
(go (cdr svl)
(segment-end (car svl)))
(go svl 0)))
(define (make-binary-test name operation svl-direct)
(map (lambda (svl1)
(map (lambda (svl2)
(lambda ()
(with-test-properties
(lambda ()
(assert-equal
(char-set->code-points
(operation (char-set* svl1)
(char-set* svl2)))
(svl-direct (trim-empty-segments svl1)
(trim-empty-segments svl2))))
'EXPRESSION `(,name ,svl1 ,svl2))))
interesting-svls))
interesting-svls))
(define-test 'union
(make-binary-test 'CHAR-SET-UNION
char-set-union
(lambda (svl1 svl2)
(named-call 'SVL-UNION svl-union svl1 svl2))))
(define (svl-union svl1 svl2)
(if (pair? svl1)
(if (pair? svl2)
(let ((s1 (segment-start (car svl1)))
(e1 (segment-end (car svl1)))
(s2 (segment-start (car svl2)))
(e2 (segment-end (car svl2))))
(cond ((< e1 s2)
(cons (car svl1)
(svl-union (cdr svl1) svl2)))
((< e2 s1)
(cons (car svl2)
(svl-union svl1 (cdr svl2))))
(else
(let ((s3 (min s1 s2)))
(receive (e3 svl1 svl2)
(union:find-end (max e1 e2)
(cdr svl1)
(cdr svl2))
(cons (make-segment s3 e3)
(svl-union svl1 svl2)))))))
svl1)
svl2))
(define (union:find-end e0 svl1 svl2)
(let ((s1
(if (pair? svl1)
(segment-start (car svl1))
#f))
(s2
(if (pair? svl2)
(segment-start (car svl2))
#f)))
(if (or (and (not s1) (not s2))
(< e0
(cond ((not s1) s2)
((not s2) s1)
(else (min s1 s2)))))
(values e0 svl1 svl2)
(if (and s1
(or (not s2)
(< s1 s2)))
(union:find-end (max e0 (segment-end (car svl1)))
(cdr svl1)
svl2)
(union:find-end (max e0 (segment-end (car svl2)))
svl1
(cdr svl2))))))
(define-test 'intersection
(make-binary-test 'CHAR-SET-INTERSECTION
char-set-intersection
(lambda (svl1 svl2)
(named-call 'SVL-INTERSECTION
svl-intersection svl1 svl2))))
(define (svl-intersection svl1 svl2)
(let loop ((svl1 svl1) (svl2 svl2))
(if (and (pair? svl1) (pair? svl2))
(let ((s1 (segment-start (car svl1)))
(e1 (segment-end (car svl1)))
(s2 (segment-start (car svl2)))
(e2 (segment-end (car svl2))))
(cond ((<= e1 s2) (loop (cdr svl1) svl2))
((<= e2 s1) (loop svl1 (cdr svl2)))
(else
(cons (make-segment (max s1 s2) (min e1 e2))
(cond ((< e1 e2)
(loop (cdr svl1) svl2))
((> e1 e2)
(loop svl1 (cdr svl2)))
(else
(loop (cdr svl1) (cdr svl2))))))))
'())))
(define-test 'difference
(make-binary-test 'CHAR-SET-DIFFERENCE
char-set-difference
(lambda (svl1 svl2)
(named-call 'SVL-DIFFERENCE svl-difference svl1 svl2))))
(define (svl-difference svl1 svl2)
(let loop ((svl1 svl1) (svl2 svl2))
(if (pair? svl1)
(if (pair? svl2)
(let ((s1 (segment-start (car svl1)))
(e1 (segment-end (car svl1)))
(s2 (segment-start (car svl2)))
(e2 (segment-end (car svl2))))
(cond ((<= e1 s2)
(cons (car svl1)
(loop (cdr svl1) svl2)))
((<= e2 s1)
(loop svl1 (cdr svl2)))
(else
(let ((tail
(cond ((< e1 e2)
(loop (cdr svl1)
(cons (make-segment e1 e2)
(cdr svl2))))
((= e1 e2)
(loop (cdr svl1) (cdr svl2)))
(else
(loop (cons (make-segment e2 e1)
(cdr svl1))
(cdr svl2))))))
(if (< s1 s2)
(cons (make-segment s1 s2) tail)
tail)))))
svl1)
'())))
(define (assert-equal-canonical-svls svl1 svl2)
(list (assert-canonical-svl svl1)
(assert-canonical-svl svl2)
(assert-equal svl1 svl2)))
(define (assert-canonical-svl svl)
(assert-true (canonical-svl? svl)
'EXPRESSION `(CANONICAL-SVL? ,svl)))
(define (named-call name operation . args)
(with-test-properties (lambda () (apply operation args))
'EXPRESSION (cons name args)))
(define (trim-empty-segments svl)
(filter (lambda (segment)
(< (segment-start segment)
(segment-end segment)))
svl))
(define (canonical-svl? items)
(and (list-of-type? items
(lambda (item)
(if (pair? item)
(and (exact-nonnegative-integer? (car item))
(exact-nonnegative-integer? (cdr item))
(< (car item) (cdr item))
(<= (cdr item) char-code-limit))
(and (exact-nonnegative-integer? item)
(< item char-code-limit)))))
(every-tail (lambda (tail)
(if (and (pair? tail)
(pair? (cdr tail)))
(< (segment-end (car tail))
(segment-start (cadr tail)))
#t))
items)))
| false |
2f85ac45b7fe0b3c88a87ed4c5ccf75923b6daa2
|
43612e5ed60c14068da312fd9d7081c1b2b7220d
|
/unit-tests/IFT3065/1/etape1-if3.scm
|
fc0e011956507fde0eba74b2f98c7eaf6c84fed8
|
[
"BSD-3-Clause"
] |
permissive
|
bsaleil/lc
|
b1794065183b8f5fca018d3ece2dffabda6dd9a8
|
ee7867fd2bdbbe88924300e10b14ea717ee6434b
|
refs/heads/master
| 2021-03-19T09:44:18.905063 | 2019-05-11T01:36:38 | 2019-05-11T01:36:38 | 41,703,251 | 27 | 1 |
BSD-3-Clause
| 2018-08-29T19:13:33 | 2015-08-31T22:13:05 |
Scheme
|
UTF-8
|
Scheme
| false | false | 132 |
scm
|
etape1-if3.scm
|
(println
(let ((x 11))
(let ((y 33))
(if (let ((y (* x 1)))
(= x y))
(+ x y)
(* x y)))))
;44
| false |
bbab590fe21f21517b96adcda31fb84e3ae1576a
|
6438e08dfc709754e64a4d8e962c422607e5ed3e
|
/scheme/objects/multi-sprite.scm
|
2c252f02593b5222d4dc5f2e2434516b07770f3f
|
[] |
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 | 1,701 |
scm
|
multi-sprite.scm
|
(define-module (objects multi-sprite)
#:use-module (oop goops)
#:use-module (engine)
#:use-module (vector)
#:use-module (objects)
#:use-module (objects spritesheet)
#:export (<multi-sprite>
sprite-list
size current-sprite
access-sprite))
;;; A multi-sprite is like a swap-sprite, but with the difference that
;;; the different sprites are stored in different files.
(define-class <multi-sprite> (<geo-object>)
(current-sprite #:init-value 0
#:init-keyword #:cur
#:accessor current-sprite)
(file-list #:init-value '("assets/MissingTexture.jpg")
#:init-keyword #:files
#:allocation #:each-subclass)
;; This really should be a vector
(sprite-list #:getter sprite-list
#:allocation #:each-subclass
#:init-value #f)
;; This currently holds just one value, should hold a pair
(size #:getter size #:allocation #:each-subclass))
(define-method (initialize (this <multi-sprite>) args)
(next-method)
(unless (sprite-list this)
(slot-set! this 'sprite-list
(map load-image (slot-ref this 'file-list)))
(slot-set! this 'size
(car (texture-size
(car (sprite-list this)))))))
(define-method (access-sprite (this <multi-sprite>))
"Access the current sprite, default implementation
Uses the current-sprite field for a numeric index, but
other implementations are free to do how they please."
(list-ref (sprite-list this)
(current-sprite this)))
(define-method (draw-func (this <multi-sprite>))
(next-method)
(render-sprite! (access-sprite this)
(pos this)))
| false |
00180f38426b22b96fb57993d5ddf24846bc6b5b
|
9b2eb10c34176f47f7f490a4ce8412b7dd42cce7
|
/lib-compat/chez-r7b/i23.sls
|
fcfa9de8d243074f4e146d24aa7bfd42db80c1ec
|
[
"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 | 210 |
sls
|
i23.sls
|
(library (chez-r7b i23)
(export error)
(import (except (rnrs) error)
(rename (rnrs) (error error:r6)))
(define (error msg . x)
(apply error:r6 #f msg x)))
| false |
723fc0616fb73ca69e2b9d0e56a1272dbcf6ca22
|
3712980eb7926e723afcd0e8d641be3ae9b6bd93
|
/2.33.scm
|
d08ec837ada5af58fcd43fd3f09db0da6abd145e
|
[] |
no_license
|
philippegabriel/sicp
|
febe34fd2ac9449d2d0c240d198f08ccbc401a93
|
c0090344cf5d7d205eaab1695cb4e55c2cfbd416
|
refs/heads/master
| 2023-08-08T04:52:15.719206 | 2023-07-20T17:23:18 | 2023-07-20T17:23:18 | 19,210,543 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 724 |
scm
|
2.33.scm
|
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op initial (cdr sequence)))))
(define (map p sequence)
(accumulate
(lambda (x y) (cons (p x) y))
()
sequence)
)
)
(map (lambda (x) (+ 1 x)) (list 57 321 88))
(define (length sequence)
(accumulate (lambda (x y) (+ 1 y)) 0 sequence))
(length (list 0 1 2 3 4 5 6 7 8 9))
;;normal recursive version
(define (append seq1 seq2)
(cond ((null? seq1) seq2)
((null? seq2) seq1)
(else (cons (car seq1) (append (cdr seq1) seq2)))
)
)
(append (list 0 1 2 3 4 5) (list 6 7 8 9))
(define (append seq1 seq2)
(accumulate cons seq2 seq1))
(append (list 0 1 2 3 4 5) (list 6 7 8 9))
| false |
b9dc8afa137fcffd0011b6c5d3088e8eca605d57
|
ac2a3544b88444eabf12b68a9bce08941cd62581
|
/gsc/tests/18-u16vector/vectorref.scm
|
dc6c976d6580bdddb672a481f811f418762efdd3
|
[
"Apache-2.0",
"LGPL-2.1-only"
] |
permissive
|
tomelam/gambit
|
2fd664cf6ea68859d4549fdda62d31a25b2d6c6f
|
d60fdeb136b2ed89b75da5bfa8011aa334b29020
|
refs/heads/master
| 2020-11-27T06:39:26.718179 | 2019-12-15T16:56:31 | 2019-12-15T16:56:31 | 229,341,552 | 1 | 0 |
Apache-2.0
| 2019-12-20T21:52:26 | 2019-12-20T21:52:26 | null |
UTF-8
|
Scheme
| false | false | 512 |
scm
|
vectorref.scm
|
(declare (extended-bindings) (not constant-fold) (not safe))
(define v1 (##u16vector 0 111 65535))
(define v2 (##make-u16vector 10))
(define v3 (##make-u16vector 10 111))
(define v4 (##make-u16vector 10 65535))
(define v5 '#u16(0 111 65535))
(define (test v i expected)
(let ((val (##u16vector-ref v i)))
(println (if (##fx= val expected) "good" "bad"))))
(test v1 0 0)
(test v1 1 111)
(test v1 2 65535)
(test v2 9 0)
(test v3 9 111)
(test v4 9 65535)
(test v5 0 0)
(test v5 1 111)
(test v5 2 65535)
| false |
6641381733da199ced21412c0284ddc30750b158
|
b43e36967e36167adcb4cc94f2f8adfb7281dbf1
|
/scheme/swl1.3/tests/error-help/test19.ss
|
de056e8a95224dbab46dac681eee1e675cacb019
|
[
"SWL",
"TCL"
] |
permissive
|
ktosiu/snippets
|
79c58416117fa646ae06a8fd590193c9dd89f414
|
08e0655361695ed90e1b901d75f184c52bb72f35
|
refs/heads/master
| 2021-01-17T08:13:34.067768 | 2016-01-29T15:42:14 | 2016-01-29T15:42:14 | 53,054,819 | 1 | 0 | null | 2016-03-03T14:06:53 | 2016-03-03T14:06:53 | null |
UTF-8
|
Scheme
| false | false | 67 |
ss
|
test19.ss
|
; Test error "invalid string character \\~c"
"I need \3d glasses"
| false |
a1941f918d18ae02871083a3ec39db42a01e2144
|
0011048749c119b688ec878ec47dad7cd8dd00ec
|
/src/spoilers/357/solution.scm
|
e140fa70c0dffa2094768aa91df9ca2d38fd037a
|
[
"0BSD"
] |
permissive
|
turquoise-hexagon/euler
|
e1fb355a44d9d5f9aef168afdf6d7cd72bd5bfa5
|
852ae494770d1c70cd2621d51d6f1b8bd249413c
|
refs/heads/master
| 2023-08-08T21:01:01.408876 | 2023-07-28T21:30:54 | 2023-07-28T21:30:54 | 240,263,031 | 8 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,013 |
scm
|
solution.scm
|
(import
(chicken fixnum)
(euler))
(define (make-prime? n)
(let ((acc (make-vector (fx+ n 1) #f)))
(for-each
(lambda (p)
(vector-set! acc p #t))
(primes (fx+ n 1)))
(define (prime? n)
(vector-ref acc n))
prime?))
(define (solve n)
(let ((prime? (make-prime? n)))
(let ((cache (make-vector (fx+ n 1) #t)))
(let loop ((a 1) (acc (fx/ (fx* n (fx+ n 1)) 2)))
(if (fx> (fx* a a) n)
acc
(if (vector-ref cache a)
(let subloop ((b (fx* a a)) (acc acc))
(if (fx> b n)
(loop (fx+ a 1) acc)
(subloop (fx+ b a)
(if (vector-ref cache b)
(if (prime? (fx+ a (fx/ b a)))
acc
(begin
(vector-set! cache b #f)
(fx- acc b)))
acc))))
(loop (fx+ a 1) acc)))))))
(let ((_ (solve #e1e8)))
(print _) (assert (= _ 1739023853137)))
| false |
9dcf7f2d62131ac2bc91f647efe51f59efe2cb25
|
307481dbdfd91619aa5fd854c0a19cd592408f1b
|
/node_modules/biwascheme/,/library/lib1.sld
|
716f13997f521a0474549f82da60aa04e537b82e
|
[
"MIT",
"CC-BY-3.0"
] |
permissive
|
yukarigohan/firstrepository
|
38ff2db62bb8baa85b21daf65b12765e10691d46
|
2bcdb91cbb6f01033e2e0a987a9dfee9d3a98ac7
|
refs/heads/master
| 2020-04-20T10:59:02.600980 | 2019-02-02T07:08:41 | 2019-02-02T07:08:41 | 168,803,970 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 157 |
sld
|
lib1.sld
|
(define-library (lib1)
(export foo)
(import (scheme base))
(begin
;(set! gvar 2)
(define (foo) gvar)
(define gvar "gvar-in-lib")
))
| false |
30f822ac35c7feaf91dc352c064dee97b8e1c53f
|
4b480cab3426c89e3e49554d05d1b36aad8aeef4
|
/chapter-03/ex3.54-falsetru.scm
|
3e5876a01eee7f52412939e9b51c79431d0092fa
|
[] |
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 | 658 |
scm
|
ex3.54-falsetru.scm
|
#lang racket
(require "stream-base-falsetru.scm")
(define (mul-streams s1 s2) (stream-map * s1 s2))
(define (integers-starting-from n)
(cons-stream n (integers-starting-from (+ n 1))))
(define factorials
(cons-stream 1 (mul-streams (integers-starting-from 2) factorials)))
(require rackunit)
(require rackunit/text-ui)
(define ex3.54-tests
(test-suite
"Test for ex3.54"
(check-equal? (stream-ref factorials 0) 1)
(check-equal? (stream-ref factorials 1) 2)
(check-equal? (stream-ref factorials 2) 6)
(check-equal? (stream-ref factorials 3) 24)
(check-equal? (stream-ref factorials 4) 120)
))
(exit (run-tests ex3.54-tests))
| false |
7b2745f650fd8545fc79657ba8e69b477709e7b6
|
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
|
/sitelib/util/concurrent/actor.scm
|
f4c9e020670aa438f20fd221f62af068c8ae19a5
|
[
"BSD-3-Clause",
"LicenseRef-scancode-other-permissive",
"MIT",
"BSD-2-Clause"
] |
permissive
|
ktakashi/sagittarius-scheme
|
0a6d23a9004e8775792ebe27a395366457daba81
|
285e84f7c48b65d6594ff4fbbe47a1b499c9fec0
|
refs/heads/master
| 2023-09-01T23:45:52.702741 | 2023-08-31T10:36:08 | 2023-08-31T10:36:08 | 41,153,733 | 48 | 7 |
NOASSERTION
| 2022-07-13T18:04:42 | 2015-08-21T12:07:54 |
Scheme
|
UTF-8
|
Scheme
| false | false | 4,843 |
scm
|
actor.scm
|
;;; -*- mode: scheme; coding: utf-8 -*-
;;;
;;; util/concurrent/actor.scm - Actor
;;;
;;; Copyright (c) 2017 Takashi Kato <[email protected]>
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; 2. Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;
#!nounbound
(library (util concurrent actor)
(export actor? (rename actor <actor>) make-actor
actor-send-message!
actor-receive-message!
actor-running?
actor-wait!
actor-terminate!
actor-state
actor-start!
actor-interrupt!
make-shared-queue-channel-actor
make-shared-priority-queue-channel-actor
make-shared-queue-channel
make-shared-priority-queue-channel
*actor-thread-name-factory*
)
(import (rnrs)
(sagittarius threads) ;; need thread-interrrupt!
(sagittarius)
(srfi :39 parameters)
(util concurrent shared-queue))
(define *actor-thread-name-factory*
(make-parameter (lambda () (gensym "actor-thread-"))))
;; base actor record
;; actor has 2 channels to receive/send messages
(define-record-type (actor make-actor actor?)
(fields (mutable state) thread receiver sender)
(protocol
(lambda (p)
(lambda (task make-receiver make-sender . maybe-start?)
;; default start (for backward compatibility...
(define start? (or (null? maybe-start?) (car maybe-start?)))
(let-values (((receiver/actor sender/client) (make-receiver))
((receiver/client sender/actor) (make-sender)))
(let* ((t (make-thread
(lambda ()
(define actor (thread-specific (current-thread)))
(guard (e (else (actor-state-set! actor 'error)
(raise e)))
(task receiver/client sender/client)
(actor-state-set! actor 'finished)))
((*actor-thread-name-factory*))))
(actor (p 'created t receiver/actor sender/actor)))
(thread-specific-set! t actor)
(if start?
(actor-start! actor)
actor)))))))
(define (make-shared-queue-channel . opt)
(define sq (apply make-shared-queue opt))
(define (receiver . opt) (apply shared-queue-get! sq opt))
(define (sender v . opt) (apply shared-queue-put! sq v opt))
(values receiver sender))
(define (make-shared-priority-queue-channel compare . opt)
(define sq (apply make-shared-priority-queue compare opt))
(define (receiver . opt) (apply shared-priority-queue-get! sq opt))
(define (sender v . opt) (apply shared-priority-queue-put! sq v opt))
(values receiver sender))
(define (actor-start! actor)
(when (eq? 'created (actor-state actor))
(thread-start! (actor-thread actor))
(actor-state-set! actor 'running))
actor)
(define (actor-interrupt! actor)
(and (actor-running? actor)
(thread-interrupt! (actor-thread actor))))
(define (actor-running? actor) (eq? (actor-state actor) 'running))
(define (actor-send-message! actor message . opt)
(apply (actor-sender actor) message opt))
(define (actor-receive-message! actor . opt)
(apply (actor-receiver actor) opt))
;; need this?
(define (actor-wait! actor . timeout)
(apply thread-join! (actor-thread actor) timeout))
(define (actor-terminate! actor)
(thread-terminate! (actor-thread actor))
(actor-state-set! actor 'terminated))
;; common actors
(define (make-shared-queue-channel-actor task . opt)
(apply make-actor task make-shared-queue-channel make-shared-queue-channel
opt))
(define (make-shared-priority-queue-channel-actor task compare . opt)
(define (make-channel) (make-shared-priority-queue-channel compare))
(apply make-actor task make-channel make-channel opt))
)
| false |
b42024d7168201a88fb2bad2c6c4d6aef228cb0f
|
81788f723d53fa098f2fce87d4d022dc78aaa68c
|
/chap-3/3-46.scm
|
8780fa1440dc909c8c7e544722cfee3f31562860
|
[] |
no_license
|
docmatrix/sicp
|
01ef2028b1fde0c035e4fa49106d2e07b4baf42d
|
c7f1214bdd6da23ef8edb0670b61cdb222147674
|
refs/heads/master
| 2020-12-24T06:44:10.783386 | 2017-11-28T17:03:09 | 2017-11-28T17:03:09 | 58,923,881 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 166 |
scm
|
3-46.scm
|
; No more diagrams.
; It is the same thing, two processes can easily test (car cell) and find it false,
; which would cause them both to acquire the mutex.
; CORRECT
| false |
4e2586670c6db89f03ac6b80eb40847bc1a71fb9
|
8807c9ce1537d4c113cb5640f021be645d1bee50
|
/examples/nehe_tutorials_4.scm
|
a2f1918a1cb62f6d322fca6787050db37d9e120b
|
[] |
no_license
|
Borderliner/tehila
|
fabd8dbf981fe0f637e986d12d568c582ac36c47
|
576a89dc0a1be192ead407265bc2272cd6a55226
|
refs/heads/master
| 2020-04-05T09:46:46.508539 | 2010-12-14T01:03:45 | 2010-12-14T01:03:45 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,538 |
scm
|
nehe_tutorials_4.scm
|
;; Tutorial-specific settings
(define *clear-color* '(0 0 0 0))
(define (game-loop delta)
(let* ((total-time (- (current-milliseconds) *start-time*))
(triangle-rotation (/ total-time 4))
(quad-rotation (/ total-time 2)))
;; Get a new matrix (same as pushing and popping the matrix)
(with-new-matrix
(lambda ()
;; Move left 1.5 units and "out of" the screen 6 units
(translate -1.5 0.0 -6.0)
;; Rotate about the Y axis before we draw the triangle
(rotate triangle-rotation 0 1 0)
;; Draw a colored triangle
(triangle (color 1 0 0) ;; Red
(vertex 0 1 0) ;; Top
(color 0 1 0) ;; Green
(vertex -1 -1 0) ;; Bottom Left
(color 0 0 1) ;; Blue
(vertex 1 -1 0)) ;; Bottom Right
))
;; Reset to the default matrix
(with-new-matrix
(lambda ()
;; Move left 1.5 units and "out of" the screen 6 units
(translate 1.5 0.0 -6.0)
;; Rotate about the Y axis before we draw the triangle
(rotate quad-rotation 1 0 0)
;; Draw a flat-colored (one-color) quad
(flat-quad (color 0 0 1) ;; Blue
(vertex -1 1 0) ;; Top Left
(vertex 1 1 0) ;; Top Right
(vertex 1 -1 0) ;; Bottom Right
(vertex -1 -1 0)) ;; Bottom Left
))))
;; q for quit in this tutorial
(define (handle-keyboard-state delta)
(if (kb:key-pressed? #\q) (exit)))
| false |
84ade63be51c1d745ec9c605b058794bc176ce4a
|
7ab94f43ade2471689729ad90bcbfce6731b0dca
|
/Task/Knuth-shuffle/Scheme/knuth-shuffle.ss
|
5982c3f24586ec035bfbca4f65e5eb716734ee92
|
[] |
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 | 264 |
ss
|
knuth-shuffle.ss
|
(define (swap vec i j)
(let ([tmp (vector-ref vec i)])
(vector-set! vec i (vector-ref vec j))
(vector-set! vec j tmp)))
(define (shuffle vec)
(for ((i (in-range (- (vector-length vec) 1) 0 -1)))
(let ((r (random i)))
(swap vec i r)))
vec)
| false |
2a309c0b8a38c211453f7d3c1f067b07f3494c5f
|
984b20c7a66129447883a52132ed1298479e4deb
|
/data/item-gems.scm
|
d76a77f0bc571e676a00c77f7466ab9c020bf0b0
|
[] |
no_license
|
TAEB/bridey
|
e4bf76f9e663e67f1c1a0a5758d2d849ca4d1886
|
c28f47e31c235dfdef83edc645dd301f41895338
|
refs/heads/master
| 2021-01-15T10:47:44.534210 | 2008-04-04T22:07:46 | 2008-04-04T22:07:46 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,498 |
scm
|
item-gems.scm
|
(define (gems-init)
(for-each
(lambda (color)
(let ((name (string-append "worthless piece of " color "glass"))
(plural (string-append "worthless pieces of " color "glass")))
(add-item name 'gem plural 0 1 #f #f)))
gem-colors)
(for-each
(lambda (x)
(let* ((name (car x))
(plural (if (string=? name "ruby")
"rubies"
(string-append name "s")))
(cost (cadr x)))
(add-item name 'gem plural cost 1 #f #f)))
'(("dilithium crystal" 4500) ("diamond" 4000) ("ruby" 3500)
("jacinth stone" 3250) ("sapphire" 3000) ("black opal" 2500)
("emerald" 2500) ("turquoise stone" 2000) ("aquamarine stone" 1500)
("citrine stone" 1500) ("amber stone" 1000) ("topaz stone" 900)
("jet stone" 850) ("opal" 800) ("chrysoberyl stone" 700)
("garnet stone" 700) ("amethyst stone" 600) ("jasper stone" 500)
("fluorite stone" 400) ("jade stone" 300) ("agate stone" 200)
("obsidian stone" 200)))
(add-item "loadstone" 'stone "loadstones" 1 500 #f #f)
(add-item "luckstone" 'stone "luckstones" 60 10 #f #f)
(add-item "flint stone" 'stone "flint stones" 1 10 #f #f)
(add-item "rock" 'stone "rocks" 0 10 #f "rock"))
(define gem-colors
'("black" "blue" "green" "orange" "red" "violet" "white" "yellow"
"yellowish brown"))
(define (unidentified-gem? item)
(let* ((name (item-name item))
(color (or (string-drop-suffix " gem" name)
(string-drop-suffix " gems" name))))
(and color (member color gem-colors))))
| false |
88d792f231ffd926e07404d19e236b7f36a19494
|
58381f6c0b3def1720ca7a14a7c6f0f350f89537
|
/Chapter 4/4.2/4.25.scm
|
a802e6cf33c2e58e23bb63f6f546e9d8b8f16fe6
|
[] |
no_license
|
yaowenqiang/SICPBook
|
ef559bcd07301b40d92d8ad698d60923b868f992
|
c8a0228ebf66d9c1ddc5ef1fcc1d05d8684f090a
|
refs/heads/master
| 2020-04-19T04:03:15.888492 | 2015-11-02T15:35:46 | 2015-11-02T15:35:46 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 982 |
scm
|
4.25.scm
|
#lang racket
(define (unless condition
usual-value
exceptional-value)
(if condition
exceptional-value
usual-value))
(define (factorial n)
(unless (= n 1)
(* n (factorial (- n 1)))
1))
(factorial 5)
;; Applicative order
;; Never ending loop because both input conditions are always evaluated
;; thus there is no way it'll stop - it'll continue going to 0, -1, -2...
;; Normal order
;; This will stop since once the condition is true, there is no need to
;; evaluate both halves.
;; in fact the only reason why if works and is not stuck is because if is
;; primitive procedure in the language.
;; See example below for proof
(define (if2 condition
usual-value
exceptional-value)
(if condition
usual-value
exceptional-value))
(define (factorial2 n)
(if2 (= n 1)
1
(* n (factorial (- n 1)))))
(factorial2 5)
;; Also never-ending loop
| false |
80baeb6941042e986689d7c7e23e6467d58c3082
|
b14c18fa7a4067706bd19df10f846fce5a24c169
|
/Chapter1/1.44.scm
|
df4a4fc50e827b5878b4a14a1b11d0ba52a94e53
|
[] |
no_license
|
silvesthu/LearningSICP
|
eceed6267c349ff143506b28cf27c8be07e28ee9
|
b5738f7a22c9e7967a1c8f0b1b9a180210051397
|
refs/heads/master
| 2021-01-17T00:30:29.035210 | 2016-11-29T17:57:16 | 2016-11-29T17:57:16 | 19,287,764 | 3 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 491 |
scm
|
1.44.scm
|
#lang scheme
(define (compose f g)
(lambda (x) (f (g x)))
)
(define (square x)
(* x x)
)
(define (inc x) (+ x 1))
(define (repeated f n)
(lambda (x)
(if (= n 1)
(f x) ; last one
((repeated f (- n 1)) (f x))
)
)
)
(define dx 0.000001)
(define (smooth f)
(lambda (x)
(/ (+ (f (- x dx)) (f x) (f (+ x dx))) 3)
)
)
((smooth sin) 1)
(((repeated smooth 10) sin) 1)
(define (n-fold-smooth f n)
(lambda (x)
(((repeated smooth n) f) x)
)
)
((n-fold-smooth sin 10) 1)
| false |
7dcd704b13b7ed8dee11392f82dbc1bb549262b9
|
e1fc47ba76cfc1881a5d096dc3d59ffe10d07be6
|
/ch2/2.21.scm
|
dcec3d0b0a6f9e2c5a0d0493d07fe0237cf710c6
|
[] |
no_license
|
lythesia/sicp-sol
|
e30918e1ebd799e479bae7e2a9bd4b4ed32ac075
|
169394cf3c3996d1865242a2a2773682f6f00a14
|
refs/heads/master
| 2021-01-18T14:31:34.469130 | 2019-10-08T03:34:36 | 2019-10-08T03:34:36 | 27,224,763 | 2 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 249 |
scm
|
2.21.scm
|
(load "util.scm")
; handed
(define (square-list l)
(if (null? l)
'()
(cons (square (car l)) (square-list (cdr l)))
)
)
; built-in map
(define (square-list l)
(map square l)
)
; test
; (display (square-list (list 1 2 3 4)))(newline)
| false |
e7b85e4559b42437735e68d7e16561aded6f2912
|
063934d4e0bf344a26d5679a22c1c9e5daa5b237
|
/old/iptables-parser/iptables.ss
|
3be8571ec3b58df48807d97441a5a0f376a50136
|
[] |
no_license
|
tnelson/Margrave
|
329b480da58f903722c8f7c439f5f8c60b853f5d
|
d25e8ac432243d9ecacdbd55f996d283da3655c9
|
refs/heads/master
| 2020-05-17T18:43:56.187171 | 2014-07-10T03:24:06 | 2014-07-10T03:24:06 | 749,146 | 5 | 2 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 8,404 |
ss
|
iptables.ss
|
#lang scheme
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; iptables Modeling
;; Copyright (C) 2009-2010 Christopher Barratt All rights reserved.
;;
;; This file is part of Margrave.
;;
;; Margrave 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.
;;
;; Margrave 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 Margrave. If not, see <http://www.gnu.org/licenses/>.
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require scheme/class)
(require scheme/list)
(require "margrave.ss")
(require "ip.ss")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Interfaces
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; symbol -> boolean
;; Recognizes interfaces in symbolic form
(define (net-interface? interf)
(and (symbol? interf)
(regexp-match #px"if-(\\w+)" (symbol->string interf))))
;; symbol -> atom<%>
;; Parses a network interface
(define (parse-net-interface interf)
(if (eq? interf 'if-any)
(new-root-atom 'if-any 'Interface)
(new-atom interf 'Interface)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Chains
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; symbol -> boolean
;; Recognizes packet-processing chains in symbolic form
(define (chain? chain)
(and (symbol? chain)
(or (eq? chain 'chain-any)
(eq? chain 'INPUT)
(eq? chain 'OUTPUT)
(eq? chain 'FORWARD)
(eq? chain 'PREROUTING)
(eq? chain 'POSTROUTING))))
;; symbol -> atom<%>
;; Parses a packet-processing chain
(define (parse-chain chain)
(if (eq? chain 'chain-any)
(new-root-atom 'chain-any 'Chain)
(new-atom chain 'Chain)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; TCP States and Control Flags
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; symbol -> boolean
;; Recognizes a TCP state
(define (state? state)
(and (symbol? state)
(or (eq? state 'state-any)
(eq? state 'INVALID)
(eq? state 'NEW)
(eq? state 'ESTABLISHED)
(eq? state 'RELATED))))
;; symbol -> atom<%>
;; Parses a TCP state
(define (parse-state state)
(if (eq? state 'state-any)
(new-root-atom 'state-any 'State)
(new-atom state 'State)))
;; symbol -> boolean
;; Recognizes a TCP control flag
(define (flag? flag)
(and (symbol? flag)
(or (eq? flag 'flag-any)
(eq? flag 'NONE)
(eq? flag 'ALL)
(eq? flag 'SYN)
(eq? flag '!SYN)
(eq? flag 'ACK)
(eq? flag 'RST)
(eq? flag 'FIN)
(eq? flag 'PSH)
(eq? flag 'URG))))
;; symbol -> atom<%>
;; Parses a TCP control flag
(define (parse-flag flag)
(if (eq? flag 'flag-any)
(new-root-atom 'flag-any 'Flag)
(new-atom flag 'Flag)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Policy Parsing
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define types `((chain Chain)
(in-interface Interface)
(src-addr Address)
(src-port Port)
(protocol Protocol)
(message Message)
(state State)
(flag Flag)
(dest-addr Address)
(dest-port Port)
(out-interface Interface)))
;; symbol -> atom<%>
;; Parses an atom
(define (parse-atom atom)
(cond [(icmp-message? atom) (parse-icmp-message atom)]
[(address? atom) (parse-address atom)]
[(protocol? atom) (parse-protocol atom)]
[(net-interface? atom) (parse-net-interface atom)]
[(chain? atom) (parse-chain atom)]
[(state? atom) (parse-state atom)]
[(flag? atom) (parse-flag atom)]
[(port? atom) (parse-port atom)]
[else (error "Unrecognized atom" atom)]))
;; S-expr -> rule<%>
;; Parses a rule
(define (parse-rule s-expr)
(new-rule (first s-expr)
(first (third s-expr))
(map (λ (name)
(new-required-variable name
(second (assoc name types))))
(rest (third s-expr)))
(map (λ (predicate)
(local [(define variable (second predicate))]
(new-predicate (parse-atom (first predicate))
(new-required-variable variable
(second (assoc variable types))))))
(drop s-expr 4))))
;; (listof S-expr) -> policy<%>
;; Parses a policy
(define (parse-policy s-expr)
(new-policy (second s-expr)
(fourth s-expr)
(map (λ (rule)
(parse-rule rule))
(rest (sixth s-expr)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Vocabulary Generation
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define addresses (new-atom-tree (new-ipv4-cidr-network 0 0)))
(define ports (new-atom-tree (new-port-range 0 65535)))
(define protocols (new-atom-tree (new-protocol 0)))
(define messages (new-atom-tree (parse-icmp-message 'icmp-any)))
(define states (new-atom-tree (new-root-atom 'state-any 'State)))
(define flags (new-atom-tree (new-root-atom 'flag-any 'Flags)))
(define chains (new-atom-tree (new-root-atom 'chain-any 'Chain)))
(define interfaces (new-atom-tree (new-root-atom 'if-any 'Interface)))
;; string string -> void
;; Compiles a vocabulary for a policy file
(define (compile-vocabulary policy-file vocabulary-file)
(local [(define input (open-input-file (string->path policy-file) #:mode 'text))
(define output (open-output-file (string->path vocabulary-file) #:mode 'text #:exists 'replace))]
(begin
(pretty-print (send (build-vocabulary (parse-policy (read input))) get-text) output)
(close-input-port input)
(close-output-port output))))
;; policy<%> -> vocabulary<%>
;; Builds a vocabulary for a policy
(define (build-vocabulary policy)
(printf "Building vocab~n")
(new-vocabulary 'iptables-firewall
(build-types policy)
(list 'ACCEPT 'LOG 'DROP 'REJECT 'SNAT)
'()
(map (λ (variable)
(new-required-variable (first variable) (second variable)))
types)
(send policy get-constraints)))
;; policy<%> -> hash
;; Builds the type definitions for a policy
(define (build-types policy)
(local [(define rules (send policy get-rules))]
(make-immutable-hash `((Chain ,@(build-type chains rules))
(Interface ,@(build-type interfaces rules))
(Address ,@(build-type addresses rules))
(Port ,@(build-type ports rules))
(Protocol ,@(build-type protocols rules))
(Message ,@(build-type messages rules))
(State ,@(build-type states rules))
(Flag ,@(build-type flags rules))))))
;; atom-tree<%> (listof rule<%>) -> atom-tree<%>
;; Builds a type definition from a list of rules
(define (build-type type-tree rules)
(if (empty? rules)
type-tree
(build-type (foldl (λ (atom result-tree)
(if (eq? (send atom get-type-name)
(send result-tree get-type-name))
(send result-tree insert atom)
result-tree))
type-tree
(send (first rules) get-atoms))
(rest rules))))
| false |
9eac76be75c2f9fb61cb02be523b449a5d0e23f2
|
6c6cf6e4b77640825c2457e54052a56d5de6f4d2
|
/ch2/print-interval.scm
|
3d9876a42e16fb67f4f437f820aed0521cd0ff28
|
[] |
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 | 146 |
scm
|
print-interval.scm
|
(define (print-interval z)
(display "(")
(display (lower-bound z))
(display ",")
(display (upper-bound z))
(display ")")
(newline))
| false |
cfa75c592628c038a67ffdbeb55835c14413fc8f
|
4b5dddfd00099e79cff58fcc05465b2243161094
|
/chapter_5/exercise_5_33_b.scm
|
82e014b41d7d1269f99d5a9949fd5cc8b71f7b3d
|
[
"MIT"
] |
permissive
|
hjcapple/reading-sicp
|
c9b4ef99d75cc85b3758c269b246328122964edc
|
f54d54e4fc1448a8c52f0e4e07a7ff7356fc0bf0
|
refs/heads/master
| 2023-05-27T08:34:05.882703 | 2023-05-14T04:33:04 | 2023-05-14T04:33:04 | 198,552,668 | 269 | 41 |
MIT
| 2022-12-20T10:08:59 | 2019-07-24T03:37:47 |
Scheme
|
UTF-8
|
Scheme
| false | false | 2,930 |
scm
|
exercise_5_33_b.scm
|
#lang racket
;; P419 - [练习 5.33], factorial-atl 的编译结果
'((env)
(val)
((assign val (op make-compiled-procedure) (label entry1) (reg env))
(goto (label after-lambda2))
entry1
(assign env (op compiled-procedure-env) (reg proc))
(assign env (op extend-environment) (const (n)) (reg argl) (reg env))
(save continue)
(save env)
(assign proc (op lookup-variable-value) (const =) (reg env))
(assign val (const 1))
(assign argl (op list) (reg val))
(assign val (op lookup-variable-value) (const n) (reg env))
(assign argl (op cons) (reg val) (reg argl))
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-branch6))
compiled-branch7
(assign continue (label after-call8))
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
primitive-branch6
(assign val (op apply-primitive-procedure) (reg proc) (reg argl))
after-call8
(restore env)
(restore continue)
(test (op false?) (reg val))
(branch (label false-branch4))
true-branch3
(assign val (const 1))
(goto (reg continue))
false-branch4
(assign proc (op lookup-variable-value) (const *) (reg env))
(save continue)
(save proc)
(save env)
(assign proc (op lookup-variable-value) (const factorial-atl) (reg env))
(save proc)
(assign proc (op lookup-variable-value) (const -) (reg env))
(assign val (const 1))
(assign argl (op list) (reg val))
(assign val (op lookup-variable-value) (const n) (reg env))
(assign argl (op cons) (reg val) (reg argl))
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-branch9))
compiled-branch10
(assign continue (label after-call11))
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
primitive-branch9
(assign val (op apply-primitive-procedure) (reg proc) (reg argl))
after-call11
(assign argl (op list) (reg val))
(restore proc)
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-branch12))
compiled-branch13
(assign continue (label after-call14))
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
primitive-branch12
(assign val (op apply-primitive-procedure) (reg proc) (reg argl))
after-call14
(assign argl (op list) (reg val))
(restore env)
(assign val (op lookup-variable-value) (const n) (reg env))
(assign argl (op cons) (reg val) (reg argl))
(restore proc)
(restore continue)
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-branch15))
compiled-branch16
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
primitive-branch15
(assign val (op apply-primitive-procedure) (reg proc) (reg argl))
(goto (reg continue))
after-call17
after-if5
after-lambda2
(perform (op define-variable!) (const factorial-atl) (reg val) (reg env))
(assign val (const ok))))
| false |
ae65645ac4f42ba1507b4736184c53b6f34d8920
|
ac2a3544b88444eabf12b68a9bce08941cd62581
|
/gsc/_host.scm
|
4e002376c256edf71d19fadecb0b21719bc3d629
|
[
"Apache-2.0",
"LGPL-2.1-only"
] |
permissive
|
tomelam/gambit
|
2fd664cf6ea68859d4549fdda62d31a25b2d6c6f
|
d60fdeb136b2ed89b75da5bfa8011aa334b29020
|
refs/heads/master
| 2020-11-27T06:39:26.718179 | 2019-12-15T16:56:31 | 2019-12-15T16:56:31 | 229,341,552 | 1 | 0 |
Apache-2.0
| 2019-12-20T21:52:26 | 2019-12-20T21:52:26 | null |
UTF-8
|
Scheme
| false | false | 27,614 |
scm
|
_host.scm
|
;;;============================================================================
;;; File: "_host.scm"
;;; Copyright (c) 1994-2018 by Marc Feeley, All Rights Reserved.
;;;============================================================================
(include "fixnum.scm")
;;;============================================================================
;; Host system interface:
;; ---------------------
;; This module contains definitions to interface to the host system in
;; which the compiler is loaded. This is the only module that contains
;; non-portable scheme code. So one should be able to port the
;; compiler to another system by adjusting this file.
;;;----------------------------------------------------------------------------
;; The host dependent variables:
;; ----------------------------
'(begin ; *** remove the quote at the start of this line if not using Gambit
;; These procedures are the interface to 'keyword objects'. On a
;; system which lacks native support for them, keywords are implemented
;; with symbols.
(define (string->keyword-object str)
(string->symbol (string-append str ":")))
(define (keyword-object->string key)
(let ((str (symbol->string key)))
(substring str 0 (- (string-length str) 1))))
(define (keyword-object? obj)
(and (symbol? obj)
(let* ((str (symbol->string obj))
(len (string-length str)))
(and (< 1 len)
(char=? (string-ref str (- len 1)) #\:)))))
(define (keyword-object-interned? key)
#t)
;; These definitions are needed to support objects which are not
;; standard in all implementations of Scheme. On implementations which
;; do not support these objects, they are represented with symbols.
;; Note that this implies that false-object? and symbol-object?
;; must be used to test for #f and symbols.
(define false-object
(if (eq? '() #f) (string->symbol "#f") #f))
(define (false-object? obj)
(eq? obj false-object))
(define absent-object
(string->symbol "#<absent>"))
(define (absent-object? obj)
(eq? obj absent-object))
(define unused-object
(string->symbol "#<unused>"))
(define (unused-object? obj)
(eq? obj unused-object))
(define deleted-object
(string->symbol "#<deleted>"))
(define (deleted-object? obj)
(eq? obj deleted-object))
(define void-object
(string->symbol "#!void"))
(define (void-object? obj)
(eq? obj void-object))
(define unbound1-object
(string->symbol "#!unbound"))
(define (unbound1-object? obj)
(eq? obj unbound1-object))
(define (unbound2-object? obj)
(eq? obj unbound2-object))
(define unbound2-object
(string->symbol "#!unbound2"))
(define end-of-file-object
(string->symbol "#!eof"))
(define (end-of-file-object? obj)
(eq? obj end-of-file-object))
(define optional-object
(string->symbol "#!optional"))
(define (optional-object? obj)
(eq? obj optional-object))
(define key-object
(string->symbol "#!key"))
(define (key-object? obj)
(eq? obj key-object))
(define rest-object
(string->symbol "#!rest"))
(define (rest-object? obj)
(eq? obj rest-object))
;(define body-object
;; (string->symbol "#!body"))
;;
;(define (body-object? obj)
;; (eq? obj body-object))
(define (symbol-object? obj)
(and (symbol? obj)
(not (keyword-object? obj)) ; keywords might be implemented with symbols
(not (false-object? obj))
(not (absent-object? obj))
(not (unused-object? obj))
(not (deleted-object? obj))
(not (void-object? obj))
(not (unbound1-object? obj))
(not (unbound2-object? obj))
(not (end-of-file-object? obj))
(not (optional-object? obj))
(not (key-object? obj))
(not (rest-object? obj))
;; (not (body-object? obj))
))
(define (symbol-object-interned? sym)
#t)
(define box-tag (list 'box))
(define (box-object? obj)
(and (vector? obj)
(> (vector-length obj) 0)
(eq? (vector-ref obj 0) box-tag)))
(define (box-object obj)
(vector box-tag obj))
(define (unbox-object box)
(vector-ref box 1))
(define (set-box-object! box val)
(vector-set! box 1 val))
(define (structure-object? obj)
#f)
(define (structure->list obj)
'())
;; 'open-input-file*' is like open-input-file but returns #f when the
;; named file does not exist.
(define (open-input-file* path)
(open-input-file path))
(define (open-input-file*-preserving-case path)
(open-input-file* path))
(define (open-output-file-preserving-case path)
(open-output-file path))
;; 'pp-expression' is used to pretty print an expression on a given
;; port.
(define (pp-expression expr port)
(newline port)
(write expr port)
(newline port))
;; 'write-returning-len' is like 'write' but it returns the number of
;; characters that were written out.
(define (write-returning-len obj port)
(write obj port)
1)
;; 'display-returning-len' is like 'display' but it returns the number
;; of characters that were written out.
(define (display-returning-len obj port)
(display obj port)
1)
;; 'write-word' is used to write out files containing binary data.
(define (write-word w port)
(write-char (integer->char (quotient w 256)) port)
(write-char (integer->char (modulo w 256)) port))
;; 'character->unicode' is used to convert Scheme characters into their
;; corresponding encoding in Unicode. 'unicode->character' performs
;; the inverse operation. 'in-char-range?' tests to see if its
;; non-negative integer argument is in the range expected by
;; 'unicode->character'.
(define (character->unicode c)
(char->integer c))
(define (unicode->character n)
(integer->char n))
(define (in-char-range? n)
(<= n 255))
;; 'in-integer-range?' is used to test if an integer is in a certain range.
(define (in-integer-range? n lo hi)
(and (not (< n lo)) (not (< hi n))))
;; 'fatal-err' is used to signal non-recoverable errors.
(define (fatal-err msg arg)
(error msg arg))
;; 'scheme-global-var', 'scheme-global-var-ref',
;; 'scheme-global-var-define!' and 'scheme-global-eval' define an
;; interface to the built-in evaluator (if there is one). The
;; evaluator is only needed for the processing of macros.
(define (scheme-global-var name)
name)
(define (scheme-global-var-ref var)
(scheme-global-eval var))
(define (scheme-global-var-define! var val)
(scheme-global-eval (list 'define var (list 'quote val)) fatal-err))
(define (scheme-global-eval expr err)
(eval expr))
;; 'format-filepos' is called when the compiler detects a user error in
;; a source file. In a windowed environment this can be used to show
;; the location of an error. If #f is returned, the default format will
;; be used to display the location information in the error message.
(define (format-filepos path filepos pinpoint?)
#f)
;; The following functions define an interface to the file system's
;; naming conventions. The current implementation is suitable for UNIX.
;;
;; For example, under UNIX:
;; (path-expand "../baz.scm" "/home/feeley/foo") => "/home/feeley/baz.scm"
;; (path-extension "foo/bar/baz.scm") => ".scm"
;; (path-extension "foo/bar/baz") => ""
;; (path-strip-extension "foo/bar/baz.scm") => "foo/bar/baz"
;; (path-directory "foo/bar/baz.scm") => "foo/bar/"
;; (path-strip-directory "foo/bar/baz.scm") => "baz.scm"
(define file-path-sep #\/)
(define file-ext-sep #\.)
(define (path-expand path . dir)
path)
(define (path-extension path)
(let loop1 ((i (string-length path)))
(if (or (= i 0) (char=? (string-ref path (- i 1)) file-path-sep))
""
(if (not (char=? (string-ref path (- i 1)) file-ext-sep))
(loop1 (- i 1))
(let* ((i (- i 1))
(result (make-string (- (string-length path) i))))
(let loop2 ((j (- (string-length path) 1)))
(if (< j i)
result
(begin
(string-set! result (- j i) (string-ref path j))
(loop2 (- j 1))))))))))
(define (path-strip-extension path)
(let loop1 ((i (string-length path)))
(if (or (= i 0) (char=? (string-ref path (- i 1)) file-path-sep))
path
(if (not (char=? (string-ref path (- i 1)) file-ext-sep))
(loop1 (- i 1))
(let ((result (make-string (- i 1))))
(let loop2 ((j (- i 2)))
(if (< j 0)
result
(begin
(string-set! result j (string-ref path j))
(loop2 (- j 1))))))))))
(define (path-directory path)
(let loop1 ((i (string-length path)))
(if (and (> i 0) (not (char=? (string-ref path (- i 1)) file-path-sep)))
(loop1 (- i 1))
(let ((result (make-string i)))
(let loop2 ((j (- i 1)))
(if (< j 0)
result
(begin
(string-set! result j (string-ref path j))
(loop2 (- j 1)))))))))
(define (path-strip-directory path)
(let loop1 ((i (string-length path)))
(if (and (> i 0) (not (char=? (string-ref path (- i 1)) file-path-sep)))
(loop1 (- i 1))
(let ((result (make-string (- (string-length path) i))))
(let loop2 ((j (- (string-length path) 1)))
(if (< j i)
result
(begin
(string-set! result (- j i) (string-ref path j))
(loop2 (- j 1)))))))))
(define scheme-file-extensions
'((".scm" . #f)
(".six" . six)))
;; Bytevector data types.
(define s8vect-tag (list 's8vect))
(define (make-s8vect n)
(vector s8vect-tag (make-vector n 0)))
(define (s8vect? x)
(and (vector? x)
(> (vector-length x) 0)
(eq? (vector-ref x 0) s8vect-tag)))
(define (s8vect->list v)
(vect->list (vector-ref v 1)))
(define (s8vect-length v)
(vector-length (vector-ref v 1)))
(define (s8vect-ref v i)
(vector-ref (vector-ref v 1) i))
(define (s8vect-set! v i n)
(vector-set! (vector-ref v 1) i n))
(define u8vect-tag (list 'u8vect))
(define (make-u8vect n)
(vector u8vect-tag (make-vector n 0)))
(define (u8vect? x)
(and (vector? x)
(> (vector-length x) 0)
(eq? (vector-ref x 0) u8vect-tag)))
(define (u8vect->list v)
(vect->list (vector-ref v 1)))
(define (u8vect-length v)
(vector-length (vector-ref v 1)))
(define (u8vect-ref v i)
(vector-ref (vector-ref v 1) i))
(define (u8vect-set! v i n)
(vector-set! (vector-ref v 1) i n))
(define s16vect-tag (list 's16vect))
(define (make-s16vect n)
(vector s16vect-tag (make-vector n 0)))
(define (s16vect? x)
(and (vector? x)
(> (vector-length x) 0)
(eq? (vector-ref x 0) s16vect-tag)))
(define (s16vect->list v)
(vect->list (vector-ref v 1)))
(define (s16vect-length v)
(vector-length (vector-ref v 1)))
(define (s16vect-ref v i)
(vector-ref (vector-ref v 1) i))
(define (s16vect-set! v i n)
(vector-set! (vector-ref v 1) i n))
(define u16vect-tag (list 'u16vect))
(define (make-u16vect n)
(vector u16vect-tag (make-vector n 0)))
(define (u16vect? x)
(and (vector? x)
(> (vector-length x) 0)
(eq? (vector-ref x 0) u16vect-tag)))
(define (u16vect->list v)
(vect->list (vector-ref v 1)))
(define (u16vect-length v)
(vector-length (vector-ref v 1)))
(define (u16vect-ref v i)
(vector-ref (vector-ref v 1) i))
(define (u16vect-set! v i n)
(vector-set! (vector-ref v 1) i n))
(define s32vect-tag (list 's32vect))
(define (make-s32vect n)
(vector s32vect-tag (make-vector n 0)))
(define (s32vect? x)
(and (vector? x)
(> (vector-length x) 0)
(eq? (vector-ref x 0) s32vect-tag)))
(define (s32vect->list v)
(vect->list (vector-ref v 1)))
(define (s32vect-length v)
(vector-length (vector-ref v 1)))
(define (s32vect-ref v i)
(vector-ref (vector-ref v 1) i))
(define (s32vect-set! v i n)
(vector-set! (vector-ref v 1) i n))
(define u32vect-tag (list 'u32vect))
(define (make-u32vect n)
(vector u32vect-tag (make-vector n 0)))
(define (u32vect? x)
(and (vector? x)
(> (vector-length x) 0)
(eq? (vector-ref x 0) u32vect-tag)))
(define (u32vect->list v)
(vect->list (vector-ref v 1)))
(define (u32vect-length v)
(vector-length (vector-ref v 1)))
(define (u32vect-ref v i)
(vector-ref (vector-ref v 1) i))
(define (u32vect-set! v i n)
(vector-set! (vector-ref v 1) i n))
(define s64vect-tag (list 's64vect))
(define (make-s64vect n)
(vector s64vect-tag (make-vector n 0)))
(define (s64vect? x)
(and (vector? x)
(> (vector-length x) 0)
(eq? (vector-ref x 0) s64vect-tag)))
(define (s64vect->list v)
(vect->list (vector-ref v 1)))
(define (s64vect-length v)
(vector-length (vector-ref v 1)))
(define (s64vect-ref v i)
(vector-ref (vector-ref v 1) i))
(define (s64vect-set! v i n)
(vector-set! (vector-ref v 1) i n))
(define u64vect-tag (list 'u64vect))
(define (make-u64vect n)
(vector u64vect-tag (make-vector n 0)))
(define (u64vect? x)
(and (vector? x)
(> (vector-length x) 0)
(eq? (vector-ref x 0) u64vect-tag)))
(define (u64vect->list v)
(vect->list (vector-ref v 1)))
(define (u64vect-length v)
(vector-length (vector-ref v 1)))
(define (u64vect-ref v i)
(vector-ref (vector-ref v 1) i))
(define (u64vect-set! v i n)
(vector-set! (vector-ref v 1) i n))
(define f32vect-tag (list 'f32vect))
(define (make-f32vect n)
(vector f32vect-tag (make-vector n 0.)))
(define (f32vect? x)
(and (vector? x)
(> (vector-length x) 0)
(eq? (vector-ref x 0) f32vect-tag)))
(define (f32vect->list v)
(vect->list (vector-ref v 1)))
(define (f32vect-length v)
(vector-length (vector-ref v 1)))
(define (f32vect-ref v i)
(vector-ref (vector-ref v 1) i))
(define (f32vect-set! v i n)
(vector-set! (vector-ref v 1) i n))
(define f64vect-tag (list 'f64vect))
(define (make-f64vect n)
(vector f64vect-tag (make-vector n 0.)))
(define (f64vect? x)
(and (vector? x)
(> (vector-length x) 0)
(eq? (vector-ref x 0) f64vect-tag)))
(define (f64vect->list v)
(vect->list (vector-ref v 1)))
(define (f64vect-length v)
(vector-length (vector-ref v 1)))
(define (f64vect-ref v i)
(vector-ref (vector-ref v 1) i))
(define (f64vect-set! v i n)
(vector-set! (vector-ref v 1) i n))
(define (vector-object? obj)
(and (vector? obj)
(not (box-object? obj))
(not (s8vect? obj))
(not (u8vect? obj))
(not (s16vect? obj))
(not (u16vect? obj))
(not (s32vect? obj))
(not (u32vect? obj))
(not (s64vect? obj))
(not (u64vect? obj))
(not (f32vect? obj))
(not (f64vect? obj))
(not (table? obj))))
(define (float-copysign x y)
(if (< y 0.)
(- (abs x))
(abs x)))
;; Stuff for the reader.
(define (**comply-to-standard-scheme?) #f);;;;;;;;;;;;;;;;
(define **main-readtable #f)
(define read-datum-or-eof #f)
(define (**subtype-set! obj subtype) obj)
(define (max-lines) 65536)
(define (max-fixnum32-div-max-lines) 8191)
(define (subtype-structure) #f)
(define (symbol-object-hash sym) 0)
(define (keyword-object-hash key) 0)
;; Tables.
(define table-tag (list 'table))
(define (make-table . args)
(let* ((t (memq 'test: args))
(test (if t (cadr t) equal?)))
(vector table-tag
test
'())))
(define (table? x)
(and (vector? x)
(> (vector-length x) 0)
(eq? (vector-ref x 0) table-tag)))
(define (table-lookup table key)
(let ((test (vector-ref table 1)))
(let loop ((lst (vector-ref table 2)))
(if (null? lst)
#f
(let ((couple (car lst)))
(if (test (car couple) key)
couple
(loop (cdr lst))))))))
(define (table-ref table key . default)
(let ((couple (table-lookup table key)))
(if couple
(cdr couple)
(if (null? default)
(error "unbound table key" key)
(car default)))))
(define (table-set! table key val)
(let ((couple (table-lookup table key)))
(if couple
(set-cdr! couple val)
(vector-set! table 2 (cons (cons key val) (vector-ref table 2))))))
(define (table->list table)
(vector-ref table 2))
)
;;;============================================================================
;; Definitions when host system is Gambit:
;" *** remove the semicolon at the start of this line if not using Gambit
(define (string->keyword-object str)
(##string->keyword str))
(define (keyword-object->string key)
(##keyword->string key))
(define (keyword-object? obj)
(##keyword? obj))
(define (keyword-object-interned? key)
(##keyword-interned? key))
(define false-object #f)
(define (false-object? obj)
(eq? obj false-object))
(define absent-object (macro-absent-obj))
(define (absent-object? obj)
(eq? obj absent-object))
(define unused-object (macro-unused-obj))
(define (unused-object? obj)
(eq? obj unused-object))
(define deleted-object (macro-deleted-obj))
(define (deleted-object? obj)
(eq? obj deleted-object))
(define void-object (##void))
(define (void-object? obj)
(eq? obj void-object))
(define (unbound1-object? obj)
(eq? obj (macro-unbound1-obj)))
(define (unbound2-object? obj)
(eq? obj (macro-unbound2-obj)))
(define end-of-file-object #!eof)
(define (end-of-file-object? obj)
(eq? obj end-of-file-object))
(define optional-object #!optional)
(define (optional-object? obj)
(eq? obj optional-object))
(define key-object #!key)
(define (key-object? obj)
(eq? obj key-object))
(define rest-object #!rest)
(define (rest-object? obj)
(eq? obj rest-object))
;(define body-object #!body)
;;
;(define (body-object? obj)
;; (eq? obj body-object))
(define (symbol-object? obj)
(symbol? obj))
(define (symbol-object-interned? sym)
(##symbol-interned? sym))
(define (box-object? obj)
(##box? obj))
(define (box-object obj)
(##box obj))
(define (unbox-object box)
(##unbox box))
(define (set-box-object! box val)
(##set-box! box val))
(define (structure-object? obj)
(##structure? obj))
(define (structure->list obj)
(##vector->list obj))
(define (open-input-file* path)
(##open-file-generic
(macro-direction-in)
#f
(lambda (port) (if (input-port? port) port #f))
open-input-file
path))
(define (open-input-file*-preserving-case path)
(parameterize ((current-readtable
(readtable-keywords-allowed?-set
(readtable-case-conversion?-set
(##make-standard-readtable)
#f)
#t)))
(open-input-file* path)))
(define open-output-file ##open-output-file)
(define (open-output-file-preserving-case path)
(parameterize ((current-readtable
(readtable-keywords-allowed?-set
(readtable-case-conversion?-set
(##make-standard-readtable)
#f)
#t)))
(open-output-file path)))
(define (pp-expression expr port)
(pp expr port))
(define (write-returning-len obj port)
(##namespace ("" with-output-to-string))
(let ((str (with-output-to-string '() (lambda () (write obj)))))
(display str port)
(string-length str)))
(define (display-returning-len obj port)
(##namespace ("" with-output-to-string))
(let ((str (with-output-to-string '() (lambda () (display obj)))))
(display str port)
(string-length str)))
(define (write-word w port)
(write-char (integer->char (quotient w 256)) port)
(write-char (integer->char (modulo w 256)) port))
(define (character->unicode c)
(char->integer c))
(define (unicode->character n)
(integer->char n))
(define (in-char-range? n)
(##declare (generic)) ; in case n is a bignum
(<= n ##max-char))
(define (in-integer-range? n lo hi)
(##declare (generic)) ; in case n is a bignum
(and (not (< n lo)) (not (< hi n))))
(define (fatal-err msg arg)
(error msg arg))
(define (scheme-global-var name)
name)
(define (scheme-global-var-ref var)
(scheme-global-eval var))
(define (scheme-global-var-define! var val)
(scheme-global-eval (list 'define var (list 'quote val)) fatal-err))
(define (scheme-global-eval expr err)
(eval expr))
(define (format-filepos path filepos pinpoint?)
(##format-filepos path filepos pinpoint?))
;; The path functions are already defined by Gambit
;;(define path-expand path-expand)
;;(define path-extension path-extension)
;;(define path-strip-extension path-strip-extension)
;;(define path-directory path-directory)
;;(define path-strip-directory path-strip-directory)
(define scheme-file-extensions ##scheme-file-extensions)
(define (make-s8vect n) (##make-s8vector n 0))
(define s8vect? ##s8vector?)
(define s8vect->list ##s8vector->list)
(define s8vect-length ##s8vector-length)
(define s8vect-ref ##s8vector-ref)
(define s8vect-set! ##s8vector-set!)
(define (make-u8vect n) (##make-u8vector n 0))
(define u8vect? ##u8vector?)
(define u8vect->list ##u8vector->list)
(define u8vect-length ##u8vector-length)
(define u8vect-ref ##u8vector-ref)
(define u8vect-set! ##u8vector-set!)
(define (make-s16vect n) (##make-s16vector n 0))
(define s16vect? ##s16vector?)
(define s16vect->list ##s16vector->list)
(define s16vect-length ##s16vector-length)
(define s16vect-ref ##s16vector-ref)
(define s16vect-set! ##s16vector-set!)
(define (make-u16vect n) (##make-u16vector n 0))
(define u16vect? ##u16vector?)
(define u16vect->list ##u16vector->list)
(define u16vect-length ##u16vector-length)
(define u16vect-ref ##u16vector-ref)
(define u16vect-set! ##u16vector-set!)
(define (make-s32vect n) (##make-s32vector n 0))
(define s32vect? ##s32vector?)
(define s32vect->list ##s32vector->list)
(define s32vect-length ##s32vector-length)
(define s32vect-ref ##s32vector-ref)
(define s32vect-set! ##s32vector-set!)
(define (make-u32vect n) (##make-u32vector n 0))
(define u32vect? ##u32vector?)
(define u32vect->list ##u32vector->list)
(define u32vect-length ##u32vector-length)
(define u32vect-ref ##u32vector-ref)
(define u32vect-set! ##u32vector-set!)
(define (make-s64vect n) (##make-s64vector n 0))
(define s64vect? ##s64vector?)
(define s64vect->list ##s64vector->list)
(define s64vect-length ##s64vector-length)
(define s64vect-ref ##s64vector-ref)
(define s64vect-set! ##s64vector-set!)
(define (make-u64vect n) (##make-u64vector n 0))
(define u64vect? ##u64vector?)
(define u64vect->list ##u64vector->list)
(define u64vect-length ##u64vector-length)
(define u64vect-ref ##u64vector-ref)
(define u64vect-set! ##u64vector-set!)
(define (make-f32vect n) (##make-f32vector n (macro-inexact-+0)))
(define f32vect? ##f32vector?)
(define f32vect->list ##f32vector->list)
(define f32vect-length ##f32vector-length)
(define f32vect-ref ##f32vector-ref)
(define f32vect-set! ##f32vector-set!)
(define (make-f64vect n) (##make-f64vector n (macro-inexact-+0)))
(define f64vect? ##f64vector?)
(define f64vect->list ##f64vector->list)
(define f64vect-length ##f64vector-length)
(define f64vect-ref ##f64vector-ref)
(define f64vect-set! ##f64vector-set!)
(define (vector-object? obj)
(vector? obj))
(define float-copysign ##flcopysign)
(define (**comply-to-standard-scheme?) #f);;;;;;;;;;;;;;;;;;;;;;
(define **main-readtable #f);;;;;;;
(define read-datum-or-eof #f);;;;;;;;;
(define (**subtype-set! obj subtype)
(##subtype-set! obj subtype))
(define (max-lines)
(macro-max-lines))
(define (max-fixnum32-div-max-lines)
(macro-max-fixnum32-div-max-lines))
(define (subtype-structure)
(macro-subtype-structure))
(define (symbol-object-hash sym)
(##symbol-hash sym))
(define (keyword-object-hash key)
(##keyword-hash key))
(define (**make-macro-descr def-syntax? size expander expander-src)
(##make-macro-descr def-syntax? size expander expander-src))
(define (**macro-descr-def-syntax? descr)
(##macro-descr-def-syntax? descr))
(define (**macro-descr-size descr)
(##macro-descr-size descr))
(define (**macro-descr-expander descr)
(##macro-descr-expander descr))
(define (**macro-descr-expander-src descr)
(##macro-descr-expander-src descr))
(define **compilation-ctx (make-parameter #f))
(define (**in-new-compilation-ctx thunk)
(if (##unbound? ;; TODO: remove dynamic check after bootstrap
(##global-var-ref (##make-global-var '##in-new-compilation-ctx)))
;; bootstrap not yet done
(let* ((comp-ctx
(vector '() ;; supply-modules
'() ;; demand-modules
(make-table) ;; meta-info
#f ;; module-ref
'())) ;; module-aliases
(result
(parameterize ((**compilation-ctx comp-ctx)) (thunk))))
(values result
comp-ctx))
;; bootstrap done
(##in-new-compilation-ctx thunk)))
(define (**compilation-ctx-meta-info-add! key val)
(if (##unbound? ;; TODO: remove dynamic check after bootstrap
(##global-var-ref (##make-global-var '##compilation-ctx-meta-info-add!)))
;; bootstrap not yet done
#f ;; ignore meta info
;; bootstrap done
(##compilation-ctx-meta-info-add! key val)))
(define (**compilation-ctx-module-ref-set! module-ref)
(if (##unbound? ;; TODO: remove dynamic check after bootstrap
(##global-var-ref (##make-global-var '##compilation-ctx-module-ref-set!)))
;; bootstrap not yet done
(let ((ctx (**compilation-ctx)))
(**macro-compilation-ctx-module-ref-set! ctx module-ref))
;; bootstrap done
(##compilation-ctx-module-ref-set! module-ref)))
(define (**macro-compilation-ctx-supply-modules ctx)
(##vector-ref ctx 0) ;; TODO: remove after bootstrap
;; (macro-compilation-ctx-supply-modules ctx)
)
(define (**macro-compilation-ctx-supply-modules-set! ctx supply-modules)
(##vector-set! ctx 0 supply-modules) ;; TODO: remove after bootstrap
;; (macro-compilation-ctx-supply-modules-set! ctx supply-modules)
)
(define (**macro-compilation-ctx-demand-modules ctx)
(##vector-ref ctx 1) ;; TODO: remove after bootstrap
;; (macro-compilation-ctx-demand-modules ctx)
)
(define (**macro-compilation-ctx-demand-modules-set! ctx demand-modules)
(##vector-set! ctx 0 demand-modules) ;; TODO: remove after bootstrap
;; (macro-compilation-ctx-demand-modules-set! ctx demand-modules)
)
(define (**macro-compilation-ctx-meta-info ctx)
(##vector-ref ctx 2) ;; TODO: remove after bootstrap
;; (macro-compilation-ctx-meta-info ctx)
)
(define (**macro-compilation-ctx-meta-info-set! ctx meta-info)
(##vector-set! ctx 2 meta-info) ;; TODO: remove after bootstrap
;; (macro-compilation-ctx-meta-info-set! ctx meta-info)
)
(define (**meta-info->alist meta-info)
(##table->list meta-info) ;; TODO: remove after bootstrap
;; (##meta-info->alist meta-info)
)
(define (**macro-compilation-ctx-module-ref ctx)
(##vector-ref ctx 3) ;; TODO: remove after bootstrap
;; (macro-compilation-ctx-module-ref ctx)
)
(define (**macro-compilation-ctx-module-ref-set! ctx module-ref)
(##vector-set! ctx 3 module-ref) ;; TODO: remove after bootstrap
;; (macro-compilation-ctx-module-ref-set! ctx module-ref)
)
(if (##unbound? ;; TODO: remove dynamic check after bootstrap
(##global-var-ref (##make-global-var '##parameterize)))
(##global-var-set! (##make-global-var '##parameterize) ##parameterize1))
;"
| false |
933aed43b520758edb710af9c7c3c49c848a5a79
|
d87e7efcff91d5a22fa3a3278258257a0b87ea2e
|
/test-syntax.scm
|
9682fc5e48ae11e077066d590702b6639f916cec
|
[] |
no_license
|
ktakashi/scheme-clojure
|
a901290d498b69189f3dd890413111fc44e87907
|
852309f7e94be5e5626ce023f608b18cbdbb39ca
|
refs/heads/master
| 2021-01-13T14:00:09.182147 | 2012-10-25T11:57:31 | 2012-10-25T11:57:31 | 6,372,007 | 2 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 944 |
scm
|
test-syntax.scm
|
(import (clojure syntax)
(only (rnrs) define for-each display newline zero? - * procedure?)
;;(srfi :64)
)
(def print (fn #(& args) (for-each display args) (newline)))
(def test-begin print)
(def test-assert print)
(def test-equal print)
(def test-end print)
(test-begin "Toy clojure test")
(test-assert "fn" (procedure? (fn #(a) a)))
(test-assert "if (true)" (if (zero? 0) true))
(test-equal "if (false)" nil (if (zero? 1) true))
(test-equal "if (false nil)" nil (if nil true))
(test-equal "if (false)" false (if nil true false))
(test-equal "let" 1 (let #(x 1 y x) y))
(test-equal "loop" 120 (loop #(cnt 5 acc 1)
(if (zero? cnt)
acc
(recur (- cnt 1) (* acc cnt)))))
(test-equal "try" 'ok (try 'ok
(catch zero? e 'ng)
(finally (display 'finally) (newline))))
(test-equal "try (throw)" 'ok
(try (throw 0)
(catch zero? e 'ok)
(finally (display 'finally) (newline))))
(test-end)
| false |
22f7b0e5333a0728475d534f22c0faca7dc8c77c
|
dfa3c518171b330522388a9faf70e77caf71b0be
|
/examples/empathy/source.scm
|
dd0652e48563c1c8ca53fad79faa725c8455aeb0
|
[
"BSD-2-Clause"
] |
permissive
|
dharmatech/abstracting
|
c3ff314917857f92e79200df59b889d7f69ec34b
|
9dc5d9f45a9de03c6ee379f1928ebb393dfafc52
|
refs/heads/master
| 2021-01-19T18:08:22.293608 | 2009-05-12T02:03:55 | 2009-05-12T02:03:55 | 122,992 | 3 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,773 |
scm
|
source.scm
|
;; Original version by Kyle McDonald:
;;
;; http://www.openprocessing.org/visuals/?visualID=1182
;;
;; Ported to Abstracting by Ed Cavazos
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(for-each require-lib '("list" "math" "tendrils/nodebox"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define *number-of-cells* 5000)
(define *base-line-length* 37)
(define *rotation-speed-step* 0.004)
(define *slow-down-rate* 0.97)
(set! *y-increases-up* #f)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (det x1 y1 x2 y2 x3 y3)
(- (* (- x2 x1)
(- y3 y1))
(* (- x3 x1)
(- y2 y1))))
(define (cell x y)
(let ((spin-velocity 0)
(current-angle 0))
(let ((sense
(lambda ()
(if (or (not (= *p-mouse-x* 0))
(not (= *p-mouse-y* 0)))
(set! spin-velocity
(+ spin-velocity
(/ (* *rotation-speed-step*
(det x y *p-mouse-x* *p-mouse-y* *mouse-x* *mouse-y*))
(+ (dist x y *mouse-x* *mouse-y*) 1)))))
(set! spin-velocity (* spin-velocity *slow-down-rate*))
(set! current-angle (+ current-angle spin-velocity))
(let ((d (+ 0.001 (* *base-line-length* spin-velocity))))
(glVertex2d x y)
(glVertex2d (+ x (* d (cos current-angle)))
(+ y (* d (sin current-angle))))))))
(vector 'cell sense))))
(define (sense cell)
((vector-ref cell 1)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(set! *title* "Empathy by Kyle McDonald")
(size 500 500)
;; (set! *frames-per-second* #t)
(set! *frames-per-second* 30)
(init-nodebox)
(stroke 0.0 0.0 0.0 0.5)
(define *cells*
(list-tabulate *number-of-cells*
(lambda (i)
(let ((theta (+ i (random 0 (/ pi 9))))
(dista (+ 3
(random -3 3)
(* (/ i *number-of-cells*)
(/ *width* 2)
(* (/ (- *number-of-cells* i) *number-of-cells*) 3.3)))))
(cell (+ (/ *width* 2) (* dista (cos theta)))
(+ (/ *height* 2) (* dista (sin theta))))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(set! *draw*
(lambda ()
(background 1.0)
(glColor4d 0.0 0.0 0.0 0.5)
(glBegin GL_LINES)
(for-each sense *cells*)
(glEnd)
(set! *p-mouse-x* *mouse-x*)
(set! *p-mouse-y* *mouse-y*)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(run-nodebox)
| false |
514901ab0aead85608e8dd0a6efd8c9cbcd0c6e2
|
2e50e13dddf57917018ab042f3410a4256b02dcf
|
/contrib/50.for/t/test.scm
|
8edfc771f7f97802b7fefb07c965bc54a9edb138
|
[
"MIT"
] |
permissive
|
koba-e964/picrin
|
c0ca2596b98a96bcad4da9ec77cf52ce04870482
|
0f17caae6c112de763f4e18c0aebaa73a958d4f6
|
refs/heads/master
| 2021-01-22T12:44:29.137052 | 2016-07-10T16:12:36 | 2016-07-10T16:12:36 | 17,021,900 | 0 | 0 |
MIT
| 2019-05-17T03:46:41 | 2014-02-20T13:55:33 |
Scheme
|
UTF-8
|
Scheme
| false | false | 510 |
scm
|
test.scm
|
(import (scheme base)
(picrin control list)
(picrin test))
(test '(1 2 3)
(for
(in '(1 2 3))))
(test '((1 . a) (1 . b) (1 . c) (2 . a) (2 . b) (2 . c) (3 . a) (3 . b) (3 . c))
(for
(let ((n (in '(1 2 3)))
(c (in '(a b c))))
(cons n c))))
(define (fail) (in zero))
(test '((2 . a) (2 . b) (2 . c))
(for
(let ((n (in '(1 2 3)))
(c (in '(a b c))))
(if (even? n)
(cons n c)
(fail)))))
| false |
2369a61d276529def6970993e97c5609bfef66c2
|
9998f6f6940dc91a99e0e2acb4bc4e918f49eef0
|
/src/test/sample-moby-programs/gui-world-location.ss
|
384ae6ecbe580e1d360470e39713d2b9fd145ff9
|
[] |
no_license
|
JessamynT/wescheme-compiler2012
|
326d66df382f3d2acbc2bbf70fdc6b6549beb514
|
a8587f9d316b3cb66d8a01bab3cf16f415d039e5
|
refs/heads/master
| 2020-05-30T07:16:45.185272 | 2016-03-19T07:14:34 | 2016-03-19T07:14:34 | 70,086,162 | 0 | 0 | null | 2016-10-05T18:09:51 | 2016-10-05T18:09:51 | null |
UTF-8
|
Scheme
| false | false | 1,127 |
ss
|
gui-world-location.ss
|
;; The first three lines of this file were inserted by DrScheme. They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-reader.ss" "lang")((modname gui-world-location) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ())))
(require (lib "gui-world.ss" "gui-world"))
;; Location, using the on-location-changed hook.
(define-struct world (latitude longitude))
(define initial-world (make-world 0 0))
;; lat-msg: world -> string
(define (lat-msg w)
(number->string (world-latitude w)))
;; long-msg: world -> string
(define (long-msg w)
(number->string (world-longitude w)))
;; The gui shows the latitude and longitude.
(define view
(col
(row "Latitude: " (message lat-msg))
(row "Longitude: " (message long-msg))))
;; handle-location-change: world number number -> world
(define (handle-location-change a-world a-latitude a-longitude)
(make-world a-latitude
a-longitude))
(big-bang initial-world view
(on-location-change handle-location-change))
| false |
0990b79f7bef8629f702a4992e8ab7078ca544e8
|
b8fc3c5c214081dac9c52b86bb0c8bfeb0a70662
|
/test.scm
|
77433b0c003cb32c63ea23c31b708b2fa8fabcf7
|
[
"BSD-2-Clause"
] |
permissive
|
leque/list-sort
|
aea672c950213b0ac13ac2823632f8652e6381ee
|
33de8e28f403af4dd149e9f1118c28e9593fb60a
|
refs/heads/master
| 2021-01-20T09:41:51.158958 | 2012-08-23T20:42:46 | 2012-08-23T20:42:46 | 5,531,891 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,538 |
scm
|
test.scm
|
(add-load-path "." :relative #t)
(load "sort")
(use gauche.test)
(define (list-sorted? xs less?)
(or (null? xs)
(null? (cdr xs))
(and (not (less? (cadr xs)
(car xs)))
(list-sorted? (cdr xs) less?))))
(define (test-sort expected xs)
(let ((v (list-copy xs)))
(test* (x->string xs) expected (list-stable-sort! v))))
(test-start "sort")
(test-sort '() '())
(test-sort '(1) '(1))
(test-sort '(1 2) '(1 2))
(test-sort '(1 2) '(2 1))
(test-sort '(1 2 3) '(1 2 3))
(test-sort '(1 2 3) '(1 3 2))
(test-sort '(1 2 3) '(2 1 3))
(test-sort '(1 2 3) '(2 3 1))
(test-sort '(1 2 3) '(3 1 2))
(test-sort '(1 2 3) '(3 2 1))
(use srfi-1)
(use srfi-27)
(dotimes (n 10)
(let ((i (+ n 4)))
(test* (format "sorted? - length = ~A" i)
#t
(list-sorted?
(list-stable-sort!
(list-tabulate i (^_ (random-integer
(ceiling->exact (/ i 2)))))
<)
<))))
(dotimes (i 10)
(let* ((i (+ i 10))
(n (ceiling->exact (/ i 3))))
(test* (format "stable? - length = ~A" i)
#t
(list-sorted?
(list-stable-sort!
(map cons
(list-tabulate i (^_ (random-integer n)))
(iota i))
(lambda (a b)
(< (car a) (car b))))
(lambda (a b)
(or (< (car a) (car b))
(and (eqv? (car a) (car b))
(< (cdr a) (cdr b)))))))))
(test-end)
| false |
2b0575148915efac6b6e532cd807491fd2c9a53c
|
f033ff2c78c89e2d7d24d7b8e711fa6d1b230142
|
/ccc/sequential/benchmarks/graphs/minimal-aux.ss
|
355dbd56d49d5d087a25374d55d9422f1e7024dc
|
[] |
no_license
|
zane/research
|
3cb47d47bb2708f6e83ee16cef89647a47db139d
|
8b4ecfe6035fe30c9113f3add380c91598f7262a
|
refs/heads/master
| 2021-01-01T19:09:58.166662 | 2009-12-16T16:53:57 | 2009-12-16T16:53:57 | 62,193 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 682 |
ss
|
minimal-aux.ss
|
(module minimal-aux scheme
(require "./util.ss")
(require "./ptfold.ss")
(provide t-folder-for-make-minimal)
;;(provide/contract
;; [t-folder-for-make-minimal
;; (->d
;; ([size integer?-and-exact?-and-positive?]
;; [perm vector?]
;; [folder procedure?])
;; ()
;; [result
;; (->d
;; ([leaf-depth (lambda (x) (eqv? x size))]
;; [state any/c]
;; [accross any/c])
;; ()
;; [result-final any/c])])])
(define t-folder-for-make-minimal
(lambda (size perm folder)
(lambda (leaf-depth state accross)
(folder perm state accross))))
)
| false |
fa6b4fc1a8baa1057d41ee70543251733813102c
|
9e0dd24b228b2787274d07ba7a73e53fb4310da8
|
/piclib/built-in.scm
|
ddb175ebca277ff81f097200ca3feb8a0401e72b
|
[
"MIT"
] |
permissive
|
krig/picrin
|
d3fed60acaf20ceecfe63364065cf89db2b17bfa
|
e0007fb6fcc078d68e2465b1e9ff9fcc0de3ceef
|
refs/heads/master
| 2021-01-18T02:36:21.790533 | 2014-05-28T11:15:48 | 2014-05-28T11:15:48 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 35,996 |
scm
|
built-in.scm
|
;;; Appendix A. Standard Libraries CxR
(define-library (scheme cxr)
(import (scheme base))
(define (caaar p) (car (caar p)))
(define (caadr p) (car (cadr p)))
(define (cadar p) (car (cdar p)))
(define (caddr p) (car (cddr p)))
(define (cdaar p) (cdr (caar p)))
(define (cdadr p) (cdr (cadr p)))
(define (cddar p) (cdr (cdar p)))
(define (cdddr p) (cdr (cddr p)))
(define (caaaar p) (caar (caar p)))
(define (caaadr p) (caar (cadr p)))
(define (caadar p) (caar (cdar p)))
(define (caaddr p) (caar (cddr p)))
(define (cadaar p) (cadr (caar p)))
(define (cadadr p) (cadr (cadr p)))
(define (caddar p) (cadr (cdar p)))
(define (cadddr p) (cadr (cddr p)))
(define (cdaaar p) (cdar (caar p)))
(define (cdaadr p) (cdar (cadr p)))
(define (cdadar p) (cdar (cdar p)))
(define (cdaddr p) (cdar (cddr p)))
(define (cddaar p) (cddr (caar p)))
(define (cddadr p) (cddr (cadr p)))
(define (cdddar p) (cddr (cdar p)))
(define (cddddr p) (cddr (cddr p)))
(export caaar caadr cadar caddr
cdaar cdadr cddar cdddr
caaaar caaadr caadar caaddr
cadaar cadadr caddar cadddr
cdaaar cdaadr cdadar cdaddr
cddaar cddadr cdddar cddddr))
;;; hygienic macros
(define-library (picrin macro)
(import (scheme base))
(define (sc-macro-transformer f)
(lambda (expr use-env mac-env)
(make-syntactic-closure mac-env '() (f expr use-env))))
(define (rsc-macro-transformer f)
(lambda (expr use-env mac-env)
(make-syntactic-closure use-env '() (f expr mac-env))))
(export sc-macro-transformer
rsc-macro-transformer))
;;; core syntaces
(define-library (picrin core-syntax)
(import (scheme base)
(scheme cxr)
(picrin macro))
(define-syntax let
(er-macro-transformer
(lambda (expr r compare)
(if (symbol? (cadr expr))
(begin
(define name (cadr expr))
(define bindings (caddr expr))
(define body (cdddr expr))
(list (r 'let) '()
(list (r 'define) name
(cons (r 'lambda) (cons (map car bindings) body)))
(cons name (map cadr bindings))))
(begin
(set! bindings (cadr expr))
(set! body (cddr expr))
(cons (cons (r 'lambda) (cons (map car bindings) body))
(map cadr bindings)))))))
(define-syntax cond
(er-macro-transformer
(lambda (expr r compare)
(let ((clauses (cdr expr)))
(if (null? clauses)
#f
(if (compare (r 'else) (caar clauses))
(cons (r 'begin) (cdar clauses))
(if (if (>= (length (car clauses)) 2)
(compare (r '=>) (cadar clauses))
#f)
(list (r 'let) (list (list 'x (caar clauses)))
(list (r 'if) 'x
(list (caddar clauses) 'x)
(cons (r 'cond) (cdr clauses))))
(list (r 'if) (caar clauses)
(cons (r 'begin) (cdar clauses))
(cons (r 'cond) (cdr clauses))))))))))
(define (single? list)
(if (pair? list)
(null? (cdr list))
#f))
(define-syntax and
(er-macro-transformer
(lambda (expr r compare)
(let ((exprs (cdr expr)))
(cond
((null? exprs)
#t)
((single? exprs)
(car exprs))
(else
(list (r 'let) (list (list (r 'it) (car exprs)))
(list (r 'if) (r 'it)
(cons (r 'and) (cdr exprs))
(r 'it)))))))))
(define-syntax or
(er-macro-transformer
(lambda (expr r compare)
(let ((exprs (cdr expr)))
(cond
((null? exprs)
#t)
((single? exprs)
(car exprs))
(else
(list (r 'let) (list (list (r 'it) (car exprs)))
(list (r 'if) (r 'it)
(r 'it)
(cons (r 'or) (cdr exprs))))))))))
(define (quasiquote? form compare?)
(and (pair? form) (compare? (car form) 'quasiquote)))
(define (unquote? form compare?)
(and (pair? form) (compare? (car form) 'unquote)))
(define (unquote-splicing? form compare?)
(and (pair? form) (pair? (car form)) (compare? (car (car form)) 'unquote-splicing)))
(define-syntax quasiquote
(ir-macro-transformer
(lambda (form inject compare)
(define (qq depth expr)
(cond
;; unquote
((unquote? expr compare)
(if (= depth 1)
(car (cdr expr))
(list 'list
(list 'quote (inject 'unquote))
(qq (- depth 1) (car (cdr expr))))))
;; unquote-splicing
((unquote-splicing? expr compare)
(if (= depth 1)
(list 'append
(car (cdr (car expr)))
(qq depth (cdr expr)))
(list 'cons
(list 'list
(list 'quote (inject 'unquote-splicing))
(qq (- depth 1) (car (cdr (car expr)))))
(qq depth (cdr expr)))))
;; quasiquote
((quasiquote? expr compare)
(list 'list
(list 'quote (inject 'quasiquote))
(qq (+ depth 1) (car (cdr expr)))))
;; list
((pair? expr)
(list 'cons
(qq depth (car expr))
(qq depth (cdr expr))))
;; simple datum
(else
(list 'quote expr))))
(let ((x (cadr form)))
(qq 1 x)))))
#;
(define-syntax let*
(ir-macro-transformer
(lambda (form inject compare)
(let ((bindings (cadr form))
(body (cddr form)))
(if (null? bindings)
`(let () ,@body)
`(let ((,(caar bindings)
,@(cdar bindings)))
(let* (,@(cdr bindings))
,@body)))))))
(define-syntax let*
(er-macro-transformer
(lambda (form r compare)
(let ((bindings (cadr form))
(body (cddr form)))
(if (null? bindings)
`(,(r 'let) () ,@body)
`(,(r 'let) ((,(caar bindings)
,@(cdar bindings)))
(,(r 'let*) (,@(cdr bindings))
,@body)))))))
(define-syntax letrec*
(er-macro-transformer
(lambda (form r compare)
(let ((bindings (cadr form))
(body (cddr form)))
(let ((vars (map (lambda (v) `(,v #f)) (map car bindings)))
(initials (map (lambda (v) `(,(r 'set!) ,@v)) bindings)))
`(,(r 'let) (,@vars)
,@initials
,@body))))))
(define-syntax letrec
(er-macro-transformer
(lambda (form rename compare)
`(,(rename 'letrec*) ,@(cdr form)))))
(define-syntax do
(er-macro-transformer
(lambda (form r compare)
(let ((bindings (cadr form))
(finish (caddr form))
(body (cdddr form)))
`(,(r 'let) ,(r 'loop) ,(map (lambda (x)
(list (car x) (cadr x)))
bindings)
(,(r 'if) ,(car finish)
(,(r 'begin) ,@(cdr finish))
(,(r 'begin) ,@body
(,(r 'loop) ,@(map (lambda (x)
(if (null? (cddr x))
(car x)
(car (cddr x))))
bindings)))))))))
(define-syntax when
(er-macro-transformer
(lambda (expr rename compare)
(let ((test (cadr expr))
(body (cddr expr)))
`(,(rename 'if) ,test
(,(rename 'begin) ,@body)
#f)))))
(define-syntax unless
(er-macro-transformer
(lambda (expr rename compare)
(let ((test (cadr expr))
(body (cddr expr)))
`(,(rename 'if) ,test
#f
(,(rename 'begin) ,@body))))))
(define-syntax case
(er-macro-transformer
(lambda (expr r compare)
(let ((key (cadr expr))
(clauses (cddr expr)))
`(,(r 'let) ((,(r 'key) ,key))
,(let loop ((clauses clauses))
(if (null? clauses)
#f
`(,(r 'if) (,(r 'or)
,@(map (lambda (x) `(,(r 'eqv?) ,(r 'key) (,(r 'quote) ,x)))
(caar clauses)))
(begin ,@(cdar clauses))
,(loop (cdr clauses))))))))))
(define-syntax syntax-error
(er-macro-transformer
(lambda (expr rename compare)
(apply error (cdr expr)))))
(define-syntax define-auxiliary-syntax
(er-macro-transformer
(lambda (expr r c)
`(,(r 'define-syntax) ,(cadr expr)
(,(r 'sc-macro-transformer)
(,(r 'lambda) (expr env)
(,(r 'error) "invalid use of auxiliary syntax")))))))
(define-auxiliary-syntax else)
(define-auxiliary-syntax =>)
(define-auxiliary-syntax _)
(define-auxiliary-syntax ...)
(define-auxiliary-syntax unquote)
(define-auxiliary-syntax unquote-splicing)
(export let let* letrec letrec*
quasiquote unquote unquote-splicing
and or
cond case else =>
do when unless
_ ... syntax-error))
;;; multiple value
(define-library (picrin multiple-value)
(import (scheme base)
(scheme cxr)
(picrin macro)
(picrin core-syntax))
(define-syntax let*-values
(er-macro-transformer
(lambda (form r c)
(let ((formals (cadr form)))
(if (null? formals)
`(,(r 'let) () ,@(cddr form))
`(,(r 'call-with-values) (,(r 'lambda) () ,@(cdar formals))
(,(r 'lambda) (,@(caar formals))
(,(r 'let*-values) (,@(cdr formals))
,@(cddr form)))))))))
(define-syntax let-values
(er-macro-transformer
(lambda (form r c)
`(,(r 'let*-values) ,@(cdr form)))))
(define-syntax define-values
(er-macro-transformer
(lambda (form r c)
(let ((formals (cadr form)))
`(,(r 'begin)
,@(do ((vars formals (cdr vars))
(defs '()))
((null? vars)
defs)
(set! defs (cons `(,(r 'define) ,(car vars) #f) defs)))
(,(r 'call-with-values)
(,(r 'lambda) () ,@(cddr form))
(,(r 'lambda) (,@(map r formals))
,@(do ((vars formals (cdr vars))
(assn '()))
((null? vars)
assn)
(set! assn (cons `(,(r 'set!) ,(car vars) ,(r (car vars))) assn))))))))))
(export let-values
let*-values
define-values))
;;; parameter
(define-library (picrin parameter)
(import (scheme base)
(scheme cxr)
(picrin macro)
(picrin core-syntax))
;; reopen (pircin parameter)
;; see src/var.c
(define-syntax parameterize
(er-macro-transformer
(lambda (form r compare)
(let ((bindings (cadr form))
(body (cddr form)))
(let ((vars (map car bindings))
(gensym (lambda (var)
(string->symbol
(string-append
"parameterize-"
(symbol->string var))))))
`(,(r 'let) (,@(map (lambda (var)
`(,(r (gensym var)) (,var)))
vars))
,@bindings
(,(r 'let) ((,(r 'result) (begin ,@body)))
,@(map (lambda (var)
`(,(r 'parameter-set!) ,var ,(r (gensym var))))
vars)
,(r 'result))))))))
(export parameterize))
;;; Record Type
(define-library (picrin record)
(import (scheme base)
(scheme cxr)
(picrin macro)
(picrin core-syntax))
(define record-marker (list 'record-marker))
(define real-vector? vector?)
(set! vector?
(lambda (x)
(and (real-vector? x)
(or (= 0 (vector-length x))
(not (eq? (vector-ref x 0)
record-marker))))))
#|
;; (scheme eval) is not provided for now
(define eval
(let ((real-eval eval))
(lambda (exp env)
((real-eval `(lambda (vector?) ,exp))
vector?))))
|#
(define (record? x)
(and (real-vector? x)
(< 0 (vector-length x))
(eq? (vector-ref x 0) record-marker)))
(define (make-record size)
(let ((new (make-vector (+ size 1))))
(vector-set! new 0 record-marker)
new))
(define (record-ref record index)
(vector-ref record (+ index 1)))
(define (record-set! record index value)
(vector-set! record (+ index 1) value))
(define record-type% (make-record 3))
(record-set! record-type% 0 record-type%)
(record-set! record-type% 1 'record-type%)
(record-set! record-type% 2 '(name field-tags))
(define (make-record-type name field-tags)
(let ((new (make-record 3)))
(record-set! new 0 record-type%)
(record-set! new 1 name)
(record-set! new 2 field-tags)
new))
(define (record-type record)
(record-ref record 0))
(define (record-type-name record-type)
(record-ref record-type 1))
(define (record-type-field-tags record-type)
(record-ref record-type 2))
(define (field-index type tag)
(let rec ((i 1) (tags (record-type-field-tags type)))
(cond ((null? tags)
(error "record type has no such field" type tag))
((eq? tag (car tags)) i)
(else (rec (+ i 1) (cdr tags))))))
(define (record-constructor type tags)
(let ((size (length (record-type-field-tags type)))
(arg-count (length tags))
(indexes (map (lambda (tag) (field-index type tag)) tags)))
(lambda args
(if (= (length args) arg-count)
(let ((new (make-record (+ size 1))))
(record-set! new 0 type)
(for-each (lambda (arg i) (record-set! new i arg)) args indexes)
new)
(error "wrong number of arguments to constructor" type args)))))
(define (record-predicate type)
(lambda (thing)
(and (record? thing)
(eq? (record-type thing)
type))))
(define (record-accessor type tag)
(let ((index (field-index type tag)))
(lambda (thing)
(if (and (record? thing)
(eq? (record-type thing)
type))
(record-ref thing index)
(error "accessor applied to bad value" type tag thing)))))
(define (record-modifier type tag)
(let ((index (field-index type tag)))
(lambda (thing value)
(if (and (record? thing)
(eq? (record-type thing)
type))
(record-set! thing index value)
(error "modifier applied to bad value" type tag thing)))))
(define-syntax define-record-field
(ir-macro-transformer
(lambda (form inject compare?)
(let ((type (cadr form))
(field-tag (caddr form))
(acc-mod (cdddr form)))
(if (= 1 (length acc-mod))
`(define ,(car acc-mod)
(record-accessor ,type ',field-tag))
`(begin
(define ,(car acc-mod)
(record-accessor ,type ',field-tag))
(define ,(cadr acc-mod)
(record-modifier ,type ',field-tag))))))))
(define-syntax define-record-type
(ir-macro-transformer
(lambda (form inject compare?)
(let ((type (cadr form))
(constructor (caddr form))
(predicate (cadddr form))
(field-tag (cddddr form)))
`(begin
(define ,type
(make-record-type ',type ',(cdr constructor)))
(define ,(car constructor)
(record-constructor ,type ',(cdr constructor)))
(define ,predicate
(record-predicate ,type))
,@(map
(lambda (x)
`(define-record-field ,type ,(car x) ,(cadr x) ,@(cddr x)))
field-tag))))))
(export define-record-type vector?))
(import (picrin macro)
(picrin core-syntax)
(picrin multiple-value)
(picrin parameter)
(picrin record))
(export let let* letrec letrec*
quasiquote unquote unquote-splicing
and or
cond case else =>
do when unless
_ ... syntax-error)
(export let-values
let*-values
define-values)
(export make-parameter
parameterize)
(export vector? ; override definition
define-record-type)
(define (every pred list)
(if (null? list)
#t
(if (pred (car list))
(every pred (cdr list))
#f)))
(define (fold f s xs)
(if (null? xs)
s
(fold f (f (car xs) s) (cdr xs))))
;;; 6.2. Numbers
(define (floor/ n m)
(values (floor-quotient n m)
(floor-remainder n m)))
(define (truncate/ n m)
(values (truncate-quotient n m)
(truncate-remainder n m)))
; (import (only (scheme inexact) sqrt))
(import (scheme inexact))
(define (exact-integer-sqrt k)
(let ((n (exact (floor (sqrt k)))))
(values n (- k (square n)))))
(export floor/ truncate/
exact-integer-sqrt)
;;; 6.3 Booleans
(define (boolean=? . objs)
(or (every (lambda (x) (eq? x #t)) objs)
(every (lambda (x) (eq? x #f)) objs)))
(export boolean=?)
;;; 6.4 Pairs and lists
(define (memq obj list)
(if (null? list)
#f
(if (eq? obj (car list))
list
(memq obj (cdr list)))))
(define (memv obj list)
(if (null? list)
#f
(if (eqv? obj (car list))
list
(memq obj (cdr list)))))
(define (assq obj list)
(if (null? list)
#f
(if (eq? obj (caar list))
(car list)
(assq obj (cdr list)))))
(define (assv obj list)
(if (null? list)
#f
(if (eqv? obj (caar list))
(car list)
(assq obj (cdr list)))))
(define (member obj list . opts)
(let ((compare (if (null? opts) equal? (car opts))))
(if (null? list)
#f
(if (compare obj (car list))
list
(member obj (cdr list) compare)))))
(define (assoc obj list . opts)
(let ((compare (if (null? opts) equal? (car opts))))
(if (null? list)
#f
(if (compare obj (caar list))
(car list)
(assoc obj (cdr list) compare)))))
(export memq memv member
assq assv assoc)
;;; 6.5. Symbols
(define (symbol=? . objs)
(let ((sym (car objs)))
(if (symbol? sym)
(every (lambda (x)
(and (symbol? x)
(eq? x sym)))
(cdr objs))
#f)))
(export symbol=?)
;;; 6.6 Characters
(define-macro (define-char-transitive-predicate name op)
`(define (,name . cs)
(apply ,op (map char->integer cs))))
(define-char-transitive-predicate char=? =)
(define-char-transitive-predicate char<? <)
(define-char-transitive-predicate char>? >)
(define-char-transitive-predicate char<=? <=)
(define-char-transitive-predicate char>=? >=)
(export char=?
char<?
char>?
char<=?
char>=?)
;;; 6.7 String
(define (string->list string . opts)
(let ((start (if (pair? opts) (car opts) 0))
(end (if (>= (length opts) 2)
(cadr opts)
(string-length string))))
(do ((i start (+ i 1))
(res '()))
((= i end)
(reverse res))
(set! res (cons (string-ref string i) res)))))
(define (list->string list)
(let ((len (length list)))
(let ((v (make-string len)))
(do ((i 0 (+ i 1))
(l list (cdr l)))
((= i len)
v)
(string-set! v i (car l))))))
(define (string . objs)
(list->string objs))
(export string string->list list->string)
;;; 6.8. Vector
(define (vector . objs)
(let ((len (length objs)))
(let ((v (make-vector len)))
(do ((i 0 (+ i 1))
(l objs (cdr l)))
((= i len)
v)
(vector-set! v i (car l))))))
(define (vector->list vector . opts)
(let ((start (if (pair? opts) (car opts) 0))
(end (if (>= (length opts) 2)
(cadr opts)
(vector-length vector))))
(do ((i start (+ i 1))
(res '()))
((= i end)
(reverse res))
(set! res (cons (vector-ref vector i) res)))))
(define (list->vector list)
(apply vector list))
(define (vector-copy! to at from . opts)
(let ((start (if (pair? opts) (car opts) 0))
(end (if (>= (length opts) 2)
(cadr opts)
(vector-length from))))
(do ((i at (+ i 1))
(j start (+ j 1)))
((= j end))
(vector-set! to i (vector-ref from j)))))
(define (vector-copy v . opts)
(let ((start (if (pair? opts) (car opts) 0))
(end (if (>= (length opts) 2)
(cadr opts)
(vector-length v))))
(let ((res (make-vector (vector-length v))))
(vector-copy! res 0 v start end)
res)))
(define (vector-append . vs)
(define (vector-append-2-inv w v)
(let ((res (make-vector (+ (vector-length v) (vector-length w)))))
(vector-copy! res 0 v)
(vector-copy! res (vector-length v) w)
res))
(fold vector-append-2-inv #() vs))
(define (vector-fill! v fill . opts)
(let ((start (if (pair? opts) (car opts) 0))
(end (if (>= (length opts) 2)
(cadr opts)
(vector-length v))))
(do ((i start (+ i 1)))
((= i end)
#f)
(vector-set! v i fill))))
(define (vector->string . args)
(list->string (apply vector->list args)))
(define (string->vector . args)
(list->vector (apply string->list args)))
(export vector vector->list list->vector
vector-copy! vector-copy
vector-append vector-fill!
vector->string string->vector)
;;; 6.9 bytevector
(define (bytevector . objs)
(let ((len (length objs)))
(let ((v (make-bytevector len)))
(do ((i 0 (+ i 1))
(l objs (cdr l)))
((= i len)
v)
(bytevector-u8-set! v i (car l))))))
(define (bytevector-copy! to at from . opts)
(let ((start (if (pair? opts) (car opts) 0))
(end (if (>= (length opts) 2)
(cadr opts)
(bytevector-length from))))
(do ((i at (+ i 1))
(j start (+ j 1)))
((= j end))
(bytevector-u8-set! to i (bytevector-u8-ref from j)))))
(define (bytevector-copy v . opts)
(let ((start (if (pair? opts) (car opts) 0))
(end (if (>= (length opts) 2)
(cadr opts)
(bytevector-length v))))
(let ((res (make-bytevector (bytevector-length v))))
(bytevector-copy! res 0 v start end)
res)))
(define (bytevector-append . vs)
(define (bytevector-append-2-inv w v)
(let ((res (make-bytevector (+ (bytevector-length v) (bytevector-length w)))))
(bytevector-copy! res 0 v)
(bytevector-copy! res (bytevector-length v) w)
res))
(fold bytevector-append-2-inv #() vs))
(define (bytevector->list v start end)
(do ((i start (+ i 1))
(res '()))
((= i end)
(reverse res))
(set! res (cons (bytevector-u8-ref v i) res))))
(define (list->bytevector v)
(apply bytevector v))
(define (utf8->string v . opts)
(let ((start (if (pair? opts) (car opts) 0))
(end (if (>= (length opts) 2)
(cadr opts)
(bytevector-length v))))
(list->string (map integer->char (bytevector->list v start end)))))
(define (string->utf8 s . opts)
(let ((start (if (pair? opts) (car opts) 0))
(end (if (>= (length opts) 2)
(cadr opts)
(string-length s))))
(list->bytevector (map char->integer (string->list s start end)))))
(export bytevector
bytevector-copy!
bytevector-copy
bytevector-append
utf8->string
string->utf8)
;;; 6.10 control features
(define (string-map f v . vs)
(let* ((len (fold min (string-length v) (map string-length vs)))
(vec (make-string len)))
(let loop ((n 0))
(if (= n len)
vec
(begin (string-set! vec n
(apply f (cons (string-ref v n)
(map (lambda (v) (string-ref v n)) vs))))
(loop (+ n 1)))))))
(define (string-for-each f v . vs)
(let* ((len (fold min (string-length v) (map string-length vs))))
(let loop ((n 0))
(unless (= n len)
(apply f (string-ref v n)
(map (lambda (v) (string-ref v n)) vs))
(loop (+ n 1))))))
(define (vector-map f v . vs)
(let* ((len (fold min (vector-length v) (map vector-length vs)))
(vec (make-vector len)))
(let loop ((n 0))
(if (= n len)
vec
(begin (vector-set! vec n
(apply f (cons (vector-ref v n)
(map (lambda (v) (vector-ref v n)) vs))))
(loop (+ n 1)))))))
(define (vector-for-each f v . vs)
(let* ((len (fold min (vector-length v) (map vector-length vs))))
(let loop ((n 0))
(unless (= n len)
(apply f (vector-ref v n)
(map (lambda (v) (vector-ref v n)) vs))
(loop (+ n 1))))))
(export string-map string-for-each
vector-map vector-for-each)
;;; 6.13. Input and output
(define (call-with-port port proc)
(dynamic-wind
(lambda () #f)
(lambda () (proc port))
(lambda () (close-port port))))
(export call-with-port)
;;; Appendix A. Standard Libraries Lazy
(define-library (scheme lazy)
(import (scheme base)
(picrin macro))
(define-record-type promise
(make-promise% done obj)
promise?
(done promise-done? promise-done!)
(obj promise-value promise-value!))
(define-syntax delay-force
(ir-macro-transformer
(lambda (form rename compare?)
(let ((expr (cadr form)))
`(make-promise% #f (lambda () ,expr))))))
(define-syntax delay
(ir-macro-transformer
(lambda (form rename compare?)
(let ((expr (cadr form)))
`(delay-force (make-promise% #t ,expr))))))
(define (promise-update! new old)
(promise-done! old (promise-done? new))
(promise-value! old (promise-value new)))
(define (force promise)
(if (promise-done? promise)
(promise-value promise)
(let ((promise* ((promise-value promise))))
(unless (promise-done? promise)
(promise-update! promise* promise))
(force promise))))
(define (make-promise obj)
(if (promise? obj)
obj
(make-promise% #f obj)))
(export delay-force delay force make-promise promise?))
;;; syntax-rules
(define-library (picrin syntax-rules)
(import (scheme base)
(scheme cxr)
(picrin macro))
;;; utility functions
(define (reverse* l)
;; (reverse* '(a b c d . e)) => (e d c b a)
(let loop ((a '())
(d l))
(if (pair? d)
(loop (cons (car d) a) (cdr d))
(cons d a))))
(define (var->sym v)
(let loop ((cnt 0)
(v v))
(if (symbol? v)
(string->symbol (string-append (symbol->string v) "/" (number->string cnt)))
(loop (+ 1 cnt) (car v)))))
(define push-var list)
(define (every? pred l)
(if (null? l)
#t
(and (pred (car l)) (every? pred (cdr l)))))
(define (flatten l)
(cond
((null? l) '())
((pair? (car l))
(append (flatten (car l)) (flatten (cdr l))))
(else
(cons (car l) (flatten (cdr l))))))
;;; main function
(define-syntax syntax-rules
(er-macro-transformer
(lambda (form r compare)
(define _define (r 'define))
(define _let (r 'let))
(define _if (r 'if))
(define _begin (r 'begin))
(define _lambda (r 'lambda))
(define _set! (r 'set!))
(define _not (r 'not))
(define _and (r 'and))
(define _car (r 'car))
(define _cdr (r 'cdr))
(define _cons (r 'cons))
(define _pair? (r 'pair?))
(define _null? (r 'null?))
(define _symbol? (r 'symbol?))
(define _eqv? (r 'eqv?))
(define _string=? (r 'string=?))
(define _map (r 'map))
(define _vector->list (r 'vector->list))
(define _list->vector (r 'list->vector))
(define _quote (r 'quote))
(define _quasiquote (r 'quasiquote))
(define _unquote (r 'unquote))
(define _unquote-splicing (r 'unquote-splicing))
(define _syntax-error (r 'syntax-error))
(define _call/cc (r 'call/cc))
(define _er-macro-transformer (r 'er-macro-transformer))
(define (compile-match ellipsis literals pattern)
(letrec ((compile-match-base
(lambda (pattern)
(cond ((compare pattern (r '_)) (values #f '()))
((member pattern literals compare)
(values
`(,_if (,_and (,_symbol? expr) (cmp expr (rename ',pattern)))
#f
(exit #f))
'()))
((and ellipsis (compare pattern ellipsis))
(values `(,_syntax-error "invalid pattern") '()))
((symbol? pattern)
(values `(,_set! ,(var->sym pattern) expr) (list pattern)))
((pair? pattern)
(compile-match-list pattern))
((vector? pattern)
(compile-match-vector pattern))
((string? pattern)
(values
`(,_if (,_not (,_string=? ',pattern expr))
(exit #f))
'()))
(else
(values
`(,_if (,_not (,_eqv? ',pattern expr))
(exit #f))
'())))))
(compile-match-list
(lambda (pattern)
(let loop ((pattern pattern)
(matches '())
(vars '())
(accessor 'expr))
(cond ;; (hoge)
((not (pair? (cdr pattern)))
(let*-values (((match1 vars1) (compile-match-base (car pattern)))
((match2 vars2) (compile-match-base (cdr pattern))))
(values
`(,_begin ,@(reverse matches)
(,_if (,_pair? ,accessor)
(,_begin
(,_let ((expr (,_car ,accessor)))
,match1)
(,_let ((expr (,_cdr ,accessor)))
,match2))
(exit #f)))
(append vars (append vars1 vars2)))))
;; (hoge ... rest args)
((and ellipsis (compare (cadr pattern) ellipsis))
(let-values (((match-r vars-r) (compile-match-list-reverse pattern)))
(values
`(,_begin ,@(reverse matches)
(,_let ((expr (,_let loop ((a ())
(d ,accessor))
(,_if (,_pair? d)
(loop (,_cons (,_car d) a) (,_cdr d))
(,_cons d a)))))
,match-r))
(append vars vars-r))))
(else
(let-values (((match1 vars1) (compile-match-base (car pattern))))
(loop (cdr pattern)
(cons `(,_if (,_pair? ,accessor)
(,_let ((expr (,_car,accessor)))
,match1)
(exit #f))
matches)
(append vars vars1)
`(,_cdr ,accessor))))))))
(compile-match-list-reverse
(lambda (pattern)
(let loop ((pattern (reverse* pattern))
(matches '())
(vars '())
(accessor 'expr))
(cond ((and ellipsis (compare (car pattern) ellipsis))
(let-values (((match1 vars1) (compile-match-ellipsis (cadr pattern))))
(values
`(,_begin ,@(reverse matches)
(,_let ((expr ,accessor))
,match1))
(append vars vars1))))
(else
(let-values (((match1 vars1) (compile-match-base (car pattern))))
(loop (cdr pattern)
(cons `(,_let ((expr (,_car ,accessor))) ,match1) matches)
(append vars vars1)
`(,_cdr ,accessor))))))))
(compile-match-ellipsis
(lambda (pattern)
(let-values (((match vars) (compile-match-base pattern)))
(values
`(,_let loop ((expr expr))
(,_if (,_not (,_null? expr))
(,_let ,(map (lambda (var) `(,(var->sym var) '())) vars)
(,_let ((expr (,_car expr)))
,match)
,@(map
(lambda (var)
`(,_set! ,(var->sym (push-var var))
(,_cons ,(var->sym var) ,(var->sym (push-var var)))))
vars)
(loop (,_cdr expr)))))
(map push-var vars)))))
(compile-match-vector
(lambda (pattern)
(let-values (((match vars) (compile-match-list (vector->list pattern))))
(values
`(,_let ((expr (,_vector->list expr)))
,match)
vars)))))
(let-values (((match vars) (compile-match-base (cdr pattern))))
(values `(,_let ((expr (,_cdr expr)))
,match
#t)
vars))))
;;; compile expand
(define (compile-expand ellipsis reserved template)
(letrec ((compile-expand-base
(lambda (template ellipsis-valid)
(cond ((member template reserved compare)
(values (var->sym template) (list template)))
((symbol? template)
(values `(rename ',template) '()))
((pair? template)
(compile-expand-list template ellipsis-valid))
((vector? template)
(compile-expand-vector template ellipsis-valid))
(else
(values `',template '())))))
(compile-expand-list
(lambda (template ellipsis-valid)
(let loop ((template template)
(expands '())
(vars '()))
(cond ;; (... hoge)
((and ellipsis-valid
(pair? template)
(compare (car template) ellipsis))
(if (and (pair? (cdr template)) (null? (cddr template)))
(compile-expand-base (cadr template) #f)
(values '(,_syntax-error "invalid template") '())))
;; hoge
((not (pair? template))
(let-values (((expand1 vars1)
(compile-expand-base template ellipsis-valid)))
(values
`(,_quasiquote (,@(reverse expands) . (,_unquote ,expand1)))
(append vars vars1))))
;; (a ... rest syms)
((and ellipsis-valid
(pair? (cdr template))
(compare (cadr template) ellipsis))
(let-values (((expand1 vars1)
(compile-expand-base (car template) ellipsis-valid)))
(loop (cddr template)
(cons
`(,_unquote-splicing
(,_map (,_lambda ,(map var->sym vars1) ,expand1)
,@(map (lambda (v) (var->sym (push-var v))) vars1)))
expands)
(append vars (map push-var vars1)))))
(else
(let-values (((expand1 vars1)
(compile-expand-base (car template) ellipsis-valid)))
(loop (cdr template)
(cons
`(,_unquote ,expand1)
expands)
(append vars vars1))))))))
(compile-expand-vector
(lambda (template ellipsis-valid)
(let-values (((expand1 vars1)
(compile-expand-list (vector->list template) ellipsis-valid)))
`(,_list->vector ,expand1)
vars1))))
(compile-expand-base template ellipsis)))
(define (check-vars vars-pattern vars-template)
;;fixme
#t)
(define (compile-rule ellipsis literals rule)
(let ((pattern (car rule))
(template (cadr rule)))
(let*-values (((match vars-match)
(compile-match ellipsis literals pattern))
((expand vars-expand)
(compile-expand ellipsis (flatten vars-match) template)))
(if (check-vars vars-match vars-expand)
(list vars-match match expand)
'mismatch))))
(define (expand-clauses clauses rename)
(cond ((null? clauses)
`(,_quote (syntax-error "no matching pattern")))
((compare (car clauses) 'mismatch)
`(,_syntax-error "invalid rule"))
(else
(let ((vars (car (car clauses)))
(match (cadr (car clauses)))
(expand (caddr (car clauses))))
`(,_let ,(map (lambda (v) (list (var->sym v) '())) vars)
(,_let ((result (,_call/cc (,_lambda (exit) ,match))))
(,_if result
,expand
,(expand-clauses (cdr clauses) rename))))))))
(define (normalize-form form)
(if (and (list? form) (>= (length form) 2))
(let ((ellipsis '...)
(literals (cadr form))
(rules (cddr form)))
(when (symbol? literals)
(set! ellipsis literals)
(set! literals (car rules))
(set! rules (cdr rules)))
(if (and (symbol? ellipsis)
(list? literals)
(every? symbol? literals)
(list? rules)
(every? (lambda (l) (and (list? l) (= (length l) 2))) rules))
(if (member ellipsis literals compare)
`(syntax-rules #f ,literals ,@rules)
`(syntax-rules ,ellipsis ,literals ,@rules))
#f))
#f))
(let ((form (normalize-form form)))
(if form
(let ((ellipsis (cadr form))
(literals (caddr form))
(rules (cdddr form)))
(let ((clauses (map (lambda (rule) (compile-rule ellipsis literals rule))
rules)))
`(,_er-macro-transformer
(,_lambda (expr rename cmp)
,(expand-clauses clauses r)))))
`(,_syntax-error "malformed syntax-rules"))))))
(export syntax-rules))
(import (picrin syntax-rules))
(export syntax-rules)
| true |
83802b5973bd5dc79988b3103ecf99616c6f5657
|
88386d7bf1842f8d5eba5ad5c65ff5ccb36b976f
|
/naoyat/matrix.scm
|
7c26f3e2784a0c4b421c1b2e6a0c4ef2cbd2e8a2
|
[
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
ysei/gauche-naoyat-lib
|
ab524e27c721a23d7d796f8cfac4a1b47137130a
|
0615815d1d05c4aa384da757b064e5fcb74a4033
|
refs/heads/master
| 2021-01-18T08:43:21.384621 | 2010-01-20T14:22:42 | 2010-01-20T14:22:42 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 11,112 |
scm
|
matrix.scm
|
(define-module naoyat.matrix
(use srfi-1)
;;(use srfi-25) ; shape
(use gauche.array)
(use math.mt-random)
(use naoyat.list) ; make-list-with-generator, make-random-int-list
(export %rep %: %c %vec %t ->array
%solve %-1 %det
%^ %+ %+! %/ %/! %- %* %*%
%matrix %array
%RxC
%1x1 %1x2 %1x3 %1x4
%2x1 %2x2 %2x3 %2x4
%3x1 %3x2 %3x3 %3x4
%4x1 %4x2 %4x3 %4x4
%0 %1
O1x1 O1x2 O1x3 O1x4
O2x1 O2x2 O2x3 O2x4
O3x1 O3x2 O3x3 O3x4
O4x1 O4x2 O4x3 O4x4
I1 I2 I3 I4
->list
%rbind %cbind
%dim %nrow %ncol
%row %col %elem %find
%row1 %col1 %elem1 %find1
%diag %set-diag!
%Tr
;; %upper-tri %lower-tri
;; %set!
%moore-penrose %†
scalar? matrix?
make-random-matrix
matrix-print
))
(select-module naoyat.matrix)
(define *undef* (if #f #f))
(define (%rep elem len) (make-list len elem))
(define (%: from to) (iota (+ (- to from) 1) from))
(define (make-random-matrix nrow ncol min max)
;;(define (rnd) (+ min (mt-random-integer *mt* (+ (- max min) 1))))
(%matrix (make-random-int-list (* nrow ncol) min max) :ncol ncol :nrow nrow))
;;;
;;; gauche.array
;;;
;(define %t array-transpose)
(define %c vector) ; 横ベクトル (1xN行列)
(define (%vec . elems) ; 縦ベクトル (Nx1行列)
(apply array (shape 0 (length elems) 0 1) elems))
(define (%t o)
(cond [(array? o) (array-transpose o)]
[(vector? o) ;;(vector->array o)] ; 縦
(apply array (shape 0 (vector-length o) 0 1) (vector->list o))]
[(list? o) (apply array (shape 0 (length o) 0 1) o)]
[else #f]))
;(define (vector->array vec) ;; 基本的に縦
; (apply array (shape 0 (vector-length vec) 0 1) (vector->list vec)))
(define (->array o)
(cond [(array? o) o]
[(vector? o) ;(%t (vector->array o))] ; 横
(apply array (shape 0 1 0 (vector-length o)) (vector->list o))]
[(list? o) (apply array (shape 0 1 0 (length o)) o)]
[else #f]))
(define %solve array-inverse) ; 逆行列
(define %-1 array-inverse)
(define %det determinant) ; 行列式 |A|
;; array-rotate-90
;; array-flip
;; identity-array
;;
(define scalar? number?)
(define %^ array-expt) ; (%^ array pow)
(define %+ array-add-elements)
(define %+! array-add-elements!)
;(define %- array-sub-elements)
;(define %-! array-sub-elements!)
;(define %* array-mul-elements)
;(define %*! array-mul-elements!)
(define %/ array-div-elements)
(define %/! array-div-elements!)
(define (%- . ms)
(if (= 1 (length ms))
(array-mul-elements (car ms) -1)
(apply array-sub-elements ms)))
(define (%*% . ms) ;; array-mul を3つ以上の行列に拡張
(let loop ((rest (cdr ms)) (prod (->array (car ms))))
(if (null? rest)
prod
(let1 leftmost (car rest)
(loop (cdr rest)
(if (scalar? leftmost)
(array-mul-elements prod leftmost)
(array-mul prod (->array leftmost))))))))
(define (%* . ms)
(let1 prod (apply %*% ms)
(if (= 1 (array-size prod))
(array-ref prod 0 0)
prod))) ; 結果が1x1行列の場合、スカラー値を返す
;;
;; let-keyword の restvar で得られる残り引数が元の順番と異なる(2個ずつのペアで逆順)ので
;; キーワード部以前の引数を元の順番で得たいというニーズに応える関数を作った
;;
(define (omit-keywords options)
(let loop ((orig options) (dest '()))
(if (null? orig)
(values (reverse! dest) '())
(if (keyword? (car orig))
(values (reverse! dest) orig)
(loop (cdr orig) (cons (car orig) dest))))))
(define (matrix-print mx)
(let ([start0 (array-start mx 0)] [end0 (array-end mx 0)] [length0 (array-length mx 0)]
[start1 (array-start mx 1)] [end1 (array-end mx 1)] [length1 (array-length mx 1)])
(do ((y start0 (+ y 1)))
((= y end0) *undef*)
(do ((x start1 (+ x 1)))
((= x end1) (newline))
(format #t " ~d" (array-ref mx y x)) ))))
;;(define pp matrix-print)
(define (%matrix x . options)
(unless (pair? x) (set! x (list x))) ; xがatomの場合リスト化
(let1 itemcnt (length x)
(receive (args keywords) (omit-keywords options)
(let-keywords keywords ((nrow #f) (nr #f)
(ncol #f) (nc #f)
(byrow #f) (b *undef*)) ; デフォルトで行主導。arrayでは列主導
(when nr (set! nrow nr))
(when nc (set! ncol nc))
(unless (undefined? b) (set! byrow b))
(let-optionals* args ((nrow_ #f)
(ncol_ #f)
(byrow_ *undef*))
(when nrow_ (set! nrow nrow_))
(when ncol_ (set! ncol ncol_))
(unless (undefined? byrow_) (set! byrow byrow_)))
(cond [(and nrow ncol) #t]
[(and nrow (not ncol))
(set! ncol (/ itemcnt nrow))]
[(and ncol (not nrow))
(set! nrow (/ itemcnt ncol))]
[else (set! nrow 0) (set! ncol 0)])
(unless (= itemcnt (* nrow ncol))
(set! x (make-list* (* nrow ncol) x)))
(if byrow
(apply array (shape 0 nrow 0 ncol) x)
(array-transpose
(apply array (shape 0 ncol 0 nrow) x)) )
))))
(define-macro (%RxC nrow ncol . elems) `(array (shape 0 ,nrow 0 ,ncol) ,@elems))
;(define (%RxC nrow ncol . elems) (apply array (shape 0 nrow 0 ncol) elems))
;(define (%1x1 . elems) (apply array (shape 0 1 0 1) elems))
(define-macro (%1x1 . elems) `(%RxC 1 1 ,@elems)) (define-macro (%1x2 . elems) `(%RxC 1 2 ,@elems))
(define-macro (%1x3 . elems) `(%RxC 1 3 ,@elems)) (define-macro (%1x4 . elems) `(%RxC 1 4 ,@elems))
(define-macro (%2x1 . elems) `(%RxC 2 1 ,@elems)) (define-macro (%2x2 . elems) `(%RxC 2 2 ,@elems))
(define-macro (%2x3 . elems) `(%RxC 2 3 ,@elems)) (define-macro (%2x4 . elems) `(%RxC 2 4 ,@elems))
(define-macro (%3x1 . elems) `(%RxC 3 1 ,@elems)) (define-macro (%3x2 . elems) `(%RxC 3 2 ,@elems))
(define-macro (%3x3 . elems) `(%RxC 3 3 ,@elems)) (define-macro (%3x4 . elems) `(%RxC 3 4 ,@elems))
(define-macro (%4x1 . elems) `(%RxC 4 1 ,@elems)) (define-macro (%4x2 . elems) `(%RxC 4 2 ,@elems))
(define-macro (%4x3 . elems) `(%RxC 4 3 ,@elems)) (define-macro (%4x4 . elems) `(%RxC 4 4 ,@elems))
(define-macro (%0 nrow ncol) `(make-array (shape 0 ,nrow 0 ,ncol) 0))
(define O1x1 (%0 1 1)) (define O1x2 (%0 1 2)) (define O1x3 (%0 1 3)) (define O1x4 (%0 1 4))
(define O2x1 (%0 2 1)) (define O2x2 (%0 2 2)) (define O2x3 (%0 2 3)) (define O2x4 (%0 2 4))
(define O3x1 (%0 3 1)) (define O3x2 (%0 3 2)) (define O3x3 (%0 3 3)) (define O3x4 (%0 3 4))
(define O4x1 (%0 4 1)) (define O4x2 (%0 4 2)) (define O4x3 (%0 4 3)) (define O4x4 (%0 4 4))
(define %1 identity-array)
(define I1 (%1 1)) (define I2 (%1 2)) (define I3 (%1 3)) (define I4 (%1 4))
;(define E1 (%1 1)) (define E2 (%1 2)) (define E3 (%1 3)) (define E4 (%1 4))
(define (%array x s . options)
;;array は必ず列主導(byrow=#f)で要素が並べられる
(let ((nrow (first s))
(ncol (second s)))
;; (format #t "(matrix ~a nrow:~d ncol:~d byrow:F base:~d)\n" x nrow ncol base)
(array-transpose
(apply array (shape 0 ncol 0 nrow) x)) ))
(define (->list list-or-vector)
(if (vector? list-or-vector) (vector->list list-or-vector) list-or-vector))
(define (%rbind . rows)
(let* ((rows* (map ->list rows))
(nrow (length rows*))
(ncol (length (car rows*))))
; (format #t ">> rbind(nrow:~d, ncol:~d)\n" nrow ncol)
(apply array (shape 0 nrow 0 ncol)
(apply append (map ->list rows*)))))
(define (%cbind . cols)
(let* ((cols* (map ->list cols))
(nrow (length cols*))
(ncol (length (car cols*))))
(format #t ">> rbind(nrow:~d, ncol:~d)\n" nrow ncol)
(array-transpose (apply array (shape 0 ncol 0 nrow)
(apply append cols*)))))
(define (%dim mx) (list (array-length mx 0) (array-length mx 1)))
(define (%nrow mx) (array-length mx 0))
(define (%ncol mx) (array-length mx 1))
(define (%row mx row)
(list->vector
(map (cute array-ref mx row <>)
(iota (%ncol mx)) )))
(define (%col mx col)
(%t (list->vector
(map (cute array-ref mx <> col)
(iota (%nrow mx)) ))))
(define %elem array-ref)
(define (%find mx elem)
(call/cc (lambda (ret)
(array-for-each-index mx
(lambda ix (when (= elem (apply array-ref mx ix)) (ret ix)))
)
(ret #f))))
(define (%row1 mx row1) (%row mx (- row1 1)))
(define (%col1 mx col1) (%col mx (- col1 1)))
(define (%elem1 mx row1 col1) (%elem mx (- row1 1) (- col1 1)))
(define (%find1 mx elem)
(let1 found (%find mx elem)
(if found (map (cut + 1 <>) found) #f)))
(define (matrix? obj) (and (array? obj) (= 2 (array-rank obj))))
(define (%set-diag! mx elems)
(unless (pair? elems) (set! elems (list elems)))
(let ([start 0]
[end (min (array-length mx 0) (array-length mx 1))])
(let loop ((i start) (el elems))
(if (= i end) mx
(begin (array-set! mx i i (car el))
(loop (+ i 1) (if (null? (cdr el)) elems (cdr el))) )))))
(define (%diag . options)
; (when (odd? (length options))
; (set! options (append options (list :dummy))))
(define (make-diag nrow ncol elems)
; (format #t "(make-diag nrow:~d ncol:~d elems:~a)\n" nrow ncol elems)
(let ([start 0]
[end (min nrow ncol)])
(let1 mx (make-array (shape 0 nrow 0 ncol) 0)
(%set-diag! mx elems))))
(define (diag-elements mx)
(let ([start (min (array-start mx 0) (array-start mx 1))]
[end (min (array-end mx 0) (array-end mx 1))])
(let loop ((i start) (elems '()))
(if (= end i) (reverse! elems)
(loop (+ i 1) (cons (array-ref mx i i) elems))))))
(if (matrix? (car options))
(diag-elements (car options))
(receive (args keywords) (omit-keywords options)
(let-keywords keywords ((nrow #f) (nr #f)
(ncol #f) (nc #f))
;;(format #t "(diag nrow:~d ncol:~d rest:~a)\n" nrow ncol args))
(case (length args)
[(0) '?]
[(1) ; (dim) / (elem)
(if nrow
;; (elem)
(let1 elems (car args)
(make-diag nrow (or ncol nrow) elems))
;; (dim)
(cond [(number? (car args)) ;; N次元の単位行列
(let1 dim (car args)
;(identity-array dim)
(make-diag (or nrow dim) (or ncol dim) '(1))
)]
[(pair? (car args)) ;;(length (car args))次元の対角行列
(let1 dim (length (car args))
(make-diag (or nrow dim) (or ncol dim) (car args))
)]
[else #f]) )]
[(2 3) ; (elem dim)
(cond [(number? (first args)) ;; dim次元の単位行列xelem
(let ([nrow (second args)]
[ncol (last args)])
(let1 elems (make-list (min nrow ncol) (first args))
(make-diag (or nrow dim) (or ncol dim) elems)))]
[(pair? (first args)) ;;dim次元の対角行列
(let ([elems (first args)]
[nrow (second args)]
[ncol (last args)])
(make-diag (or nrow dim) (or ncol dim) elems) )]
[else #f]) ]
[else #\?])
))))
;; トレース
(define (%Tr mx) (apply + (%diag mx)))
;; 三角行列
#;(define (%upper-tri mx . options)
(let-keyword options ((diag #f))
'()))
#;(define (%lower-tri mx . options)
(let-keyword options ((diag #f))
'()))
(define (%set! mx my) ; mx <- my
)
;;; ムーア-ペンローズの疑似逆行列
;;; (Moore-Penrose pseudo-inverse matrix)
(define (%moore-penrose phi) ;; (3.17)Φ†
(let1 phiT (%t phi)
(%*% (%-1 (%*% phiT phi) phiT))))
(define %† %moore-penrose)
(provide "naoyat/matrix")
;;EOF
| false |
04583e4e637d0e919dd79f015cc8f948e6e0fd66
|
2ffc964c347dec19198bf5e56e3ab8c48830a2af
|
/tk.scm
|
5b7da04c165c92add5d171443bb75e7baee84904
|
[] |
no_license
|
shirok/Gauche-tk
|
4654b957367c7f1fe7a8516010d2f006fb2e68b6
|
3e16cd0429e9c9d9d245507aadb305ab74e3184e
|
refs/heads/master
| 2021-09-22T20:48:04.893363 | 2021-09-20T08:24:15 | 2021-09-20T08:24:15 | 3,968,209 | 7 | 2 | null | 2023-09-04T21:28:23 | 2012-04-09T01:28:20 |
Scheme
|
UTF-8
|
Scheme
| false | false | 14,893 |
scm
|
tk.scm
|
;;;
;;; Simple Tk binding
;;;
;;; Copyright (c) 2012 Shiro Kawai <[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.
;;;
;;; 3. Neither the name of the authors nor the names of its contributors
;;; may be used to endorse or promote products derived from this
;;; software without specific prior written permission.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; 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.
(define-module tk
(use gauche.process)
(use gauche.threads)
(use gauche.parameter)
(use gauche.generator)
(use gauche.sequence)
(use file.util)
(use text.tree)
(use util.match)
(use parser.peg)
(use parser.peg.deprecated)
(use srfi-13)
(export wish-path <tk-error> tk-call tk-parse-list tk-escape
tk-ref tk-set! tk-init tk-shutdown tk-mainloop tklambda
define-tk-command
tk-bell tk-bind tk-bindtags tk-bitmap tk-button tk-canvas
tk-checkbutton tk-clipboard tk-colors tk-console tk-cursors
tk-destory tk-entry tk-event tk-focus tk-font tk-frame tk-grab
tk-grid tk-image tk-keysyms tk-label tk-labelframe tk-listbox
tk-lower tk-menu tk-menubutton tk-option tk-options tk-pack
tk-panedwindow tk-photo tk-place tk-radiobutton tk-raise
tk-scale tk-scorllbar tk-selection tk-send tk-spinbox tk-text
tk-tk tk-bisque tk-chooseColor tk-chooseDirectory tk-dialog
tk-focusFollowsMouse tk-focusNext tk-focusPrev tk-getOpenFile
tk-getSaveFile tk-menuSetFocus tk-messageBox tk-optionMenu
tk-popup tk-setPalette tk-textCopy tk-textCut tk-textPaste
tk-tkerror tk-tkvars tk-tkwait tk-toplevel tk-winfo tk-wm
ttk-button ttk-checkbutton ttk-combobox ttk-entry ttk-frame
ttk-intro ttk-label ttk-labelframe ttk-menubutton ttk-notebook
ttk-sizegrip ttk-spinbox ttk-separator ttk-style ttk-treeview
ttk-panedwindow ttk-progressbar ttk-radiobutton ttk-scale
ttk-scrollbar ttk-widget ttk_image ttk_vsapi
))
(select-module tk)
;; This module enables Gauche programs to use Tk toolkit. For the
;; simplicity, we run a 'wish' process (an interactive shell of Tcl/Tk)
;; and talk to it via pipe, instead of linking Tcl/Tk library.
;;
;; We don't provide any fancy wrapper---Tcl deals with strings, and
;; that's mostly what you see from Scheme. An exception is Scheme
;; closures for callbacks---we can't pass Scheme closures to Tcl,
;; so we register it to a table and pass a dummy Tcl code fragment
;; to Tcl. When the code is kicked, our mainloop calls corresponding
;; Scheme closure.
;;
;; The communication is asynchronous, since callbacks can be invoked
;; at any time. We use stdout to receive synchronous response, while
;; use stderr to receive callback triggers.
;;
;; The callback closure is registered in the callback table (ctab), and
;; assigned a unique callback ID. In the Tcl side, a dummy command is
;; registered, which prints out the callback ID to stderr. The event
;; loop in the Gauche side reads it and invokes appropriate callbacks.
;;
;; Currently we don't garbage-collect ctab. It will be a problem if
;; you swap registered callbacks too often---if you need to change the
;; behavior of a widget, it's better to handle it in the Scheme side.
;;
;; Global parameters
;;
;; API
(define wish-path
(make-parameter (find-file-in-paths "wish")))
(define *wish* ;(<process> <callback-table>)
(atom #f (make-hash-table 'eqv?)))
;; set this #t to dump communication with wish
(define *tk-debug* #f)
;;;
;;; Communication layer
;;;
;; API
(define-condition-type <tk-error> <error> #f)
;; wrap response from wish
(define (wish-initialize tkproc)
(define (d s) (display s (process-input tkproc)))
;; Make sure we communicate in the same encoding. Fix from natsutan.
;; NB: It seems that Tcl doesn't understand sjis; we fall back to ASCII.
(let1 enc (case (gauche-character-encoding)
[(utf-8) 'utf-8]
[(euc-jp) 'euc-jp]
[(none) 'iso8859-1]
[else 'ascii])
(d #"fconfigure stdin -encoding ~enc\n")
(d #"fconfigure stdout -encoding ~enc\n")
(d #"fconfigure stderr -encoding ~enc\n"))
(d "proc gauche__tk__do args {\n\
set r [catch {eval $args} gauche__tk__result] \n\
set lines [split $gauche__tk__result \"\\n\"] \n\
if { $r == 0 || $r == 2 } { \n\
puts \"ok\" \n\
} { \n\
puts \"error\" \n\
} \n\
foreach l $lines { \n\
puts -nonewline \";\" \n\
puts $l \n\
} \n\
puts \"end\" \n\
}\n")
(d "proc gauche__tk__callback args {\n\
puts stderr $args \n\
}\n")
(d "proc gauche__tk__varref {name} { \n\
if {[info exists $name]} { \n\
upvar $name x \n\
return $x \n\
} { \n\
error \"no such variable: $name\" \n\
} \n\
}\n")
(flush (process-input tkproc)))
(define (tk-debug fmt . args)
(when *tk-debug*
(apply format (current-error-port) fmt args)))
;; we wrap Scheme procedure by <tk-callback>
(define-class <tk-callback> ()
((id)
(proc :init-keyword :proc)
(substs :init-keyword :substs :init-value '())
(id-counter :allocation :class :init-value (atom 0))))
(define-method initialize ((c <tk-callback>) initargs)
(next-method)
(set! (~ c'id) (atomic-update! (~ c'id-counter) (cut + <> 1))))
;; Scheme object -> Tcl object
(define-method encode ((x <keyword>)) #"-~(keyword->string x)") ;; :foo => -foo
(define-method encode ((x <boolean>)) (if x "1" "0"))
(define-method encode ((x <string>)) (tk-escape (format "~s" x)))
(define-method encode ((x <list>)) `("{",@(intersperse " "(map encode x))"}"))
(define-method encode ((x <tk-callback>))
`("\"gauche__tk__callback ",(x->integer (~ x'id))
" ",@(intersperse " "(map x->string (~ x'substs)))"\""))
(define-method encode ((x <top>)) (x->string x))
(define (send-to-wish tkproc ctab args)
(let1 s (tree->string
`("gauche__tk__do " ,(intersperse " "(map encode args))"\n"))
(tk-debug "> ~a" s)
(display s (process-input tkproc)))
(let* ([gen (cute read-line (process-output tkproc))]
[status (gen)]
[results (string-join ($ map (cut string-drop <> 1) $ generator->list
$ gtake-while (^s (not (equal? s "end"))) gen)
"\n")])
(tk-debug "< ~a\n~a\n" status results)
(if (equal? status "ok")
(begin
(dolist [cb (filter (cut is-a? <> <tk-callback>) args)]
(hash-table-put! ctab (~ cb'id) cb))
(rxmatch-case results
[#/^gauche__tk__callback (\d+)/ (_ n)
(if-let1 cb (hash-table-get ctab (x->integer n) #f)
(~ cb'proc)
(error <tk-error> "Stray callback" results))]
[else results]))
(error <tk-error> results))))
;; API
(define (tk-call . command)
(let1 args (map (^c (if (procedure? c)
(make <tk-callback> :proc c)
c))
command)
(atomic *wish* (^[p c] (send-to-wish p c args)))))
;; API
;; Turn string representation of Tcl list to Scheme list
;; Tcl has two kind of quoting characters, so we can't do a simple
;; string-split.
(define (tk-parse-list string)
(peg-parse-string %tk-list string))
;; TODO: This refers old peg API in parser.peg.deprecated.
;; Revise after Gauche 1.0 release.
(define %tk-word ($->rope ($many1 ($or ($one-of #[^\\\s\{\}])
($seq ($char #\\) anychar)))))
(define %tk-braced ($between ($char #\{) ($lazy %tk-list) ($char #\})))
(define %tk-quoted ($between ($char #\")
($->rope ($many ($or ($one-of #[^\\\"])
($seq ($char #\\) anychar))))
($char #\")))
(define %tk-term ($between ($skip-many ($one-of #[\s]))
($or %tk-braced %tk-quoted %tk-word)
($skip-many ($one-of #[\s]))))
(define %tk-list ($many %tk-term))
;; API
;; Escape special characters in a string when we want to pass a string
;; data literally to Tcl, without letting Tcl interpreting it again.
(define (tk-escape string)
(regexp-replace-all* string #/[\[$]/ "\\\\\\0"))
;; API
(define (tk-ref var) (tk-call 'gauche__tk__varref var))
;; API
(define (tk-set! var val) (tk-call 'set var val))
;; API
(define-syntax tklambda
(syntax-rules ()
[(_ (formals ...) body ...)
(make <tk-callback>
:proc (lambda (formals ...) body ...)
:substs '(formals ...))]))
;;;
;;; Initialization and main loop
;;;
;; API
(define (tk-init argv)
(unless (wish-path)
(error "cannot find `wish' binary. Set the parameter `wish-path'"))
(atomic-update! *wish*
(^[p c]
(when p (error "tk is already initialized"))
(let1 p (run-process `(,(wish-path) ,@argv)
:input :pipe :output :pipe
:error :pipe)
(wish-initialize p)
(values p c))))
#t)
;; API
(define (tk-shutdown)
(atomic-update! *wish*
(^[p c]
(when p
(display "exit\n" (process-input p))
(close-output-port (process-input p))
(process-wait p))
(values #f (make-hash-table 'eqv?))))
#t)
;; API
;; Returns when the pipe is closed (= when wish exits)
(define (tk-mainloop :key (background #f))
(define (mainloop)
(let1 port (process-error (atom-ref *wish* 0))
(let loop ([msg (read-line port)]) ;this blocks
(when (string? msg)
(tk-debug "! ~a\n" msg)
(let* ([items (string-split msg #[\s])]
[cnum (string->number (car items))])
(if cnum
(if-let1 cb (atomic *wish* (^[p c] (hash-table-get c cnum #f)))
(guard (e [else (tk-bgerror "~a" (~ e'message))])
(apply (~ cb'proc) (cdr items)))
(tk-bgerror "bogus callback: ~a" msg))
(tk-bgerror "~a" msg)))
(loop (read-line port))))))
(if background
(thread-start! (make-thread mainloop))
(mainloop)))
;; Background error handler.
;; TODO: Make this customizable!
(define (tk-bgerror fmt . args)
(apply format (current-error-port) #"TK Error: ~fmt" args))
;;;
;;; For the convenience
;;;
(define-syntax define-tk-command
(syntax-rules ()
[(_ name tkname)
(define (name . args)
(apply tk-call 'tkname args))]))
(define-syntax define-tk-commands
(syntax-rules ()
[(_ (name tkname) ...)
(begin (define-tk-command name tkname) ...)]))
(define-tk-commands
(tk-bell bell)
(tk-bind bind)
(tk-bindtags bindtags)
(tk-bitmap bitmap)
(tk-button button)
(tk-canvas canvas)
(tk-checkbutton checkbutton)
(tk-clipboard clipboard)
(tk-colors colors)
(tk-console console)
(tk-cursors cursors)
(tk-destory destroy)
(tk-entry entry)
(tk-event event)
(tk-focus focus)
(tk-font font)
(tk-frame frame)
(tk-grab grab)
(tk-grid grid)
(tk-image image)
(tk-keysyms keysyms)
(tk-label label)
(tk-labelframe labelframe)
(tk-listbox listbox)
(tk-lower lower)
(tk-menu menu)
(tk-menubutton menubutton)
(tk-option option)
(tk-options options)
(tk-pack pack)
(tk-panedwindow panedwindow)
(tk-photo photo)
(tk-place place)
(tk-radiobutton radiobutton)
(tk-raise raise)
(tk-scale scale)
(tk-scorllbar scrollbar)
(tk-selection selection)
(tk-send send)
(tk-spinbox spinbox)
(tk-text text)
(tk-tk tk)
(tk-bisque tk_bisque)
(tk-chooseColor tk_chooseColor)
(tk-chooseDirectory tk_chooseDirectory)
(tk-dialog tk_dialog)
(tk-focusFollowsMouse tk_focusFollowsMouse)
(tk-focusNext tk_focusNext)
(tk-focusPrev tk_focusPrev)
(tk-getOpenFile tk_getOpenFile)
(tk-getSaveFile tk_getSaveFile)
(tk-menuSetFocus tk_menuSetFocus)
(tk-messageBox tk_messageBox)
(tk-optionMenu tk_optionMenu)
(tk-popup tk_popup)
(tk-setPalette tk_setPalette)
(tk-textCopy tk_textCopy)
(tk-textCut tk_textCut)
(tk-textPaste tk_textPaste)
(tk-tkerror tkerror)
(tk-tkvars tkvars)
(tk-tkwait tkwait)
(tk-toplevel toplevel)
(tk-winfo winfo)
(tk-wm wm)
;; Ttk widgets
(ttk-button ttk::button)
(ttk-checkbutton ttk:checkbutton)
(ttk-combobox ttk::combobox)
(ttk-entry ttk::entry)
(ttk-frame ttk::frame)
(ttk-intro ttk::intro)
(ttk-label ttk::label)
(ttk-labelframe ttk::labelframe)
(ttk-menubutton ttk::menubutton)
(ttk-notebook ttk::notebook)
(ttk-sizegrip ttk::sizegrip)
(ttk-spinbox ttk::spinbox)
(ttk-separator ttk::separator)
(ttk-style ttk::style)
(ttk-treeview ttk::treeview)
(ttk-panedwindow ttk::panedwindow)
(ttk-progressbar ttk::progressbar)
(ttk-radiobutton ttk::radiobutton)
(ttk-scale ttk::scale)
(ttk-scrollbar ttk::scrollbar)
(ttk-widget ttk::widget)
(ttk_image ttk_image)
(ttk_vsapi ttk_vsapi)
)
| true |
e4e69661a14d27a55ac02d3c057df126efc0b0e8
|
3508dcd12d0d69fec4d30c50334f8deb24f376eb
|
/v8/src/compiler/midend/triveval.scm
|
d69776d77e015890e9b9623a516f5b06913c828d
|
[] |
no_license
|
barak/mit-scheme
|
be625081e92c2c74590f6b5502f5ae6bc95aa492
|
56e1a12439628e4424b8c3ce2a3118449db509ab
|
refs/heads/master
| 2023-01-24T11:03:23.447076 | 2022-09-11T06:10:46 | 2022-09-11T06:10:46 | 12,487,054 | 12 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 14,568 |
scm
|
triveval.scm
|
#| -*-Scheme-*-
Copyright (c) 1994, 1999 Massachusetts Institute of Technology
This program 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.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
|#
;;;; "Trivial" KMP Scheme evaluator
;;; package: (compiler midend)
(declare (usual-integrations))
;;;; Trivial evaluator's runtime library
;; New special forms handled as procedures
(define (lookup value)
value)
(define (call operator cont . operands)
(if (eq? operator %invoke-continuation)
(apply cont operands)
(call-with-values
(lambda ()
(collect-operands cont operands))
(lambda (cont operands)
(let ((rator (operator->procedure operator)))
(cond ((cps-proc? rator)
(cps-proc/apply rator cont operands))
((not cont)
(apply rator operands))
((continuation? cont)
(within-continuation cont
(lambda ()
(apply rator operands))))
(else
(cont (apply rator operands)))))))))
(define (collect-operands cont operands)
;; (values cont operands)
(if (not (stack-closure? cont))
(values cont operands)
(let ((proc (stack-closure/proc cont)))
(if (or (compound-procedure? proc)
(not proc))
(values cont operands)
(values proc
(append operands
(vector->list
(stack-closure/values cont))))))))
(define-structure (cps-proc
(conc-name cps-proc/)
(constructor %cps-proc/make%))
(handler false read-only true))
(define (cps-proc/apply proc cont operands)
;; if cont is false, proc should not need it
#|
(if (not cont)
(apply proc operands)
(apply (cps-proc/handler proc) cont operands))
|#
(apply (cps-proc/handler proc) cont operands))
(define (funcall nargs operator . operands)
nargs ; ignored
(apply operator operands))
(define *last-env*)
(define *this-env* (the-environment))
(define (fetch-environment)
(let ((env *last-env*))
(set! *last-env*)
env))
(define (execute expr env)
(set! *last-env* env)
(set! *stack-closure* false)
(eval (cond ((cps-program1? expr)
(cps-rewrite (caddr expr)))
((cps-program2? expr)
(cps-rewrite expr))
((compatible-program? expr)
(compatible-rewrite expr))
(else
(pre-cps-rewrite expr)))
*this-env*))
(define (pre-cps-rewrite expr)
`(let-syntax ((NON-CPS-LAMBDA
(macro (param-list body)
(list 'LAMBDA (cdr param-list) body))))
,(form/replace expr '((LAMBDA NON-CPS-LAMBDA)))))
(define triveval/?cont-variable (->pattern-variable 'CONT-VARIABLE))
(define triveval/?env-variable (->pattern-variable 'ENV-VARIABLE))
(define triveval/?body (->pattern-variable 'BODY))
(define triveval/?ignore (->pattern-variable 'IGNORE))
(define triveval/?frame (->pattern-variable 'FRAME))
(define triveval/?frame-vector (->pattern-variable 'FRAME-VECTOR))
(define triveval/compatible-expr-pattern
`(LAMBDA (,triveval/?cont-variable ,triveval/?env-variable)
,triveval/?body))
(define (compatible-program? expr)
(let ((result (form/match triveval/compatible-expr-pattern expr)))
(and result
(let ((cont (cadr (assq triveval/?cont-variable result)))
(env (cadr (assq triveval/?env-variable result))))
(and (continuation-variable? cont)
(environment-variable? env))))))
(define (compatible-rewrite expr)
(let ((expr* (%cps-rewrite (caddr expr)))
(cont-name (car (cadr expr)))
(env-name (cadr (cadr expr))))
`(call-with-current-continuation
(lambda (,cont-name)
(let ((,env-name *last-env*))
,expr*)))))
;;this no longer appears to be the only correct pattern, a (letrec () ...)
;;appears before this let, so I just make two tests, and do the
;;appropriate thing
;;JBANK
(define triveval/cps-expr-pattern1
`(LETREC ()
(LET ((,triveval/?cont-variable
(CALL (QUOTE ,%fetch-continuation)
(QUOTE #F))))
,triveval/?body)))
(define triveval/cps-expr-pattern1-2
`(LET ()
(LET ((,triveval/?cont-variable
(CALL (QUOTE ,%fetch-continuation)
(QUOTE #F))))
,triveval/?body)))
(define triveval/cps-expr-pattern2
`(LET ((,triveval/?cont-variable
(CALL (QUOTE ,%fetch-continuation)
(QUOTE #F))))
,triveval/?body))
(define (cps-program1? expr)
(or (form/match triveval/cps-expr-pattern1 expr)
(form/match triveval/cps-expr-pattern1-2 expr)))
(define (cps-program2? expr)
(form/match triveval/cps-expr-pattern2 expr))
(define (%cps-rewrite expr)
`(let-syntax ((cps-lambda
(macro (param-list body)
(call-with-values
(lambda ()
((access lambda-list/parse
(->environment '(compiler midend)))
(cdr param-list)))
(lambda (required optional rest aux)
aux ; ignored
(let ((max-reg
((access rtlgen/number-of-argument-registers
(->environment '(compiler midend)))))
(names
(append required optional (if rest
(list rest)
'()))))
(list
'%cps-proc/make%
(list 'LAMBDA
param-list
(if (<= (length names) max-reg)
body
(let ((stack-names
(list-tail names max-reg)))
`(begin
(set! *stack-closure*
(make-stack-closure
#f
'#(,@stack-names)
,@stack-names))
,body)))))))))))
,(form/replace expr '((LAMBDA CPS-LAMBDA)))))
(define (cps-rewrite expr)
`(call-with-current-continuation
(lambda (,(car (car (cadr expr)))) ; cont variable
,(%cps-rewrite (caddr expr)))))
(define-structure (variable-cache
(conc-name variable-cache/)
(constructor variable-cache/make))
env name)
(define (make-read-variable-cache env name)
(variable-cache/make env name))
(define (make-write-variable-cache env name)
(variable-cache/make env name))
(define (variable-cache-ref cache ignore-traps? name)
ignore-traps? name ; ignored
(lexical-reference (variable-cache/env cache)
(variable-cache/name cache)))
(define (variable-cache-set! cache value ignore-traps? name)
ignore-traps? name ; ignored
(lexical-assignment (variable-cache/env cache)
(variable-cache/name cache)
value))
(define (safe-variable-cache-ref cache ignore-traps? name)
ignore-traps? name ; ignored
(let ((env (variable-cache/env cache))
(name (variable-cache/name cache)))
(if (lexical-unassigned? env name)
%unassigned
(lexical-reference env name))))
(define (variable-cell-ref cache)
(let ((env (variable-cache/env cache))
(name (variable-cache/name cache)))
(if (lexical-unassigned? env name)
%unassigned
(lexical-reference env name))))
(define (variable-cell-set! cache value)
(lexical-assignment (variable-cache/env cache)
(variable-cache/name cache)
value))
(define-structure (operator-cache
(conc-name operator-cache/)
(constructor operator-cache/make))
env name arity)
(define (make-operator-variable-cache env name arity)
(operator-cache/make env name arity))
(define (make-remote-operator-variable-cache package name arity)
(operator-cache/make (->environment package) name arity))
(define (invoke-operator-cache name cache . args)
name ; ignored
(let ((arity (operator-cache/arity cache)))
(if (not (= (length args) arity))
(error "Operator cache called with wrong number of arguments"
args arity)
(apply (lexical-reference (operator-cache/env cache)
(operator-cache/name cache))
args))))
(define (cell/make value name)
name ; ignored
(make-cell value))
(define (cell-ref cell name)
name ; ignored
(cell-contents cell))
(define (cell-set! cell value name)
name ; ignored
(set-cell-contents! cell value))
(define (make-closure proc names . values)
names ; ignored
(make-entity proc (list->vector values)))
(define (closure-ref closure index name)
name ; ignored
(vector-ref (entity-extra closure) index))
(define (closure-set! closure index value name)
name ; ignored
(vector-set! (entity-extra closure) index value))
(define *stack-closure* false)
(define-structure (%stack-closure
(conc-name %stack-closure/)
(constructor %stack-closure/make))
proc
names
values)
(define (fetch-stack-closure names)
names ; ignored
(let ((closure *stack-closure*))
(set! *stack-closure* false) ; clear for gc
closure))
(define (make-stack-closure proc names . values)
(make-entity (lambda (closure . args)
(set! *stack-closure* closure)
(apply proc args))
(%stack-closure/make
proc
names
(list->vector values))))
(define (stack-closure-ref closure index name)
name ; ignored
(vector-ref (%stack-closure/values (entity-extra closure)) index))
(define (stack-closure? object)
(and (entity? object)
(%stack-closure? (entity-extra object))))
(define (stack-closure/proc object)
(%stack-closure/proc (entity-extra object)))
(define (stack-closure/values object)
(%stack-closure/values (entity-extra object)))
(define (projection/2/0 x y)
y ; ignored
x)
(define (%unknown . all)
all ; ignored
(error "Unknown operator"))
(define internal-apply/compatible
(%cps-proc/make%
(lambda (stack-closure nargs operator)
nargs ; ignored
(let ((elements (vector->list (stack-closure/values stack-closure))))
(apply call
operator
(car elements)
(reverse (cdr elements)))))))
(define *operator->procedure*
(make-eq-hash-table))
(define (operator->procedure rator)
(if (not (symbol? rator))
rator
(hash-table/get *operator->procedure* rator rator)))
(define (init-operators!)
(let* ((table *operator->procedure*)
(declare-operator
(lambda (token handler)
(hash-table/put! table token handler))))
(declare-operator %invoke-operator-cache invoke-operator-cache)
(declare-operator %invoke-remote-cache invoke-operator-cache)
(declare-operator %variable-cache-ref variable-cache-ref)
(declare-operator %variable-cache-set! variable-cache-set!)
(declare-operator %safe-variable-cache-ref safe-variable-cache-ref)
(declare-operator %unassigned? (lambda (obj) (eq? obj %unassigned)))
(declare-operator %make-promise (lambda (proc) (delay (proc))))
(declare-operator %make-cell cell/make)
(declare-operator %make-static-binding cell/make)
(declare-operator %cell-ref cell-ref)
(declare-operator %static-binding-ref cell-ref)
(declare-operator %cell-set! cell-set!)
(declare-operator %static-binding-set! cell-set!)
(declare-operator %cons cons)
(declare-operator %vector vector)
(declare-operator %*lookup
(lambda (env name depth offset)
depth offset ; ignored
(lexical-reference env name)))
(declare-operator %*set!
(lambda (env name value depth offset)
depth offset ; ignored
(lexical-assignment env name value)))
(declare-operator %*unassigned?
(lambda (env name depth offset)
depth offset ; ignored
(lexical-unassigned? env name)))
(declare-operator %*define local-assignment)
(declare-operator %*define* define-multiple)
(declare-operator %*make-environment *make-environment)
(declare-operator %execute execute)
(declare-operator %fetch-environment fetch-environment)
(declare-operator %fetch-continuation
(lambda ()
(error "Fetch-continuation executed!")))
(declare-operator %make-read-variable-cache make-read-variable-cache)
(declare-operator %make-write-variable-cache make-write-variable-cache)
(declare-operator %make-operator-variable-cache
make-operator-variable-cache)
(declare-operator %make-remote-operator-variable-cache
make-remote-operator-variable-cache)
(declare-operator %copy-program %copy-program)
(declare-operator %make-heap-closure make-closure)
(declare-operator %make-trivial-closure identity-procedure)
(declare-operator %heap-closure-ref closure-ref)
(declare-operator %heap-closure-set! closure-set!)
(declare-operator %make-stack-closure make-stack-closure)
(declare-operator %stack-closure-ref stack-closure-ref)
(declare-operator %fetch-stack-closure fetch-stack-closure)
(declare-operator %internal-apply funcall)
(declare-operator %internal-apply-unchecked funcall)
(declare-operator %primitive-apply funcall)
; (declare-operator %invoke-continuation identity-procedure)
(declare-operator %vector-index vector-index)
(declare-operator %small-fixnum? small-fixnum?)
(declare-operator %+ +)
(declare-operator %- -)
(declare-operator %* *)
(declare-operator %/ /)
(declare-operator %quotient quotient)
(declare-operator %remainder remainder)
(declare-operator %= =)
(declare-operator %< <)
(declare-operator %> >)
(declare-operator %vector-cons make-vector)
(declare-operator %string-allocate string-allocate)
(declare-operator %floating-vector-cons flo:vector-cons)
;; Compatiblity operators:
(declare-operator %make-return-address
(lambda (obj)
obj ; ignored
(error "make-return-address executed!")))
(declare-operator %variable-read-cache projection/2/0)
(declare-operator %variable-write-cache projection/2/0)
(declare-operator %variable-cell-ref variable-cell-ref)
(declare-operator %hook-variable-cell-ref variable-cell-ref)
(declare-operator %hook-safe-variable-cell-ref variable-cell-ref)
(declare-operator %variable-cell-set! variable-cell-set!)
(declare-operator %hook-variable-cell-set! variable-cell-set!)
(declare-operator %reference-trap? (lambda (obj) (eq? obj %unassigned)))
(declare-operator %primitive-apply/compatible internal-apply/compatible)))
;; This makes cps procs and ordinary procs intermixable
(set-record-type-application-method!
cps-proc
(lambda (the-proc . args)
(call-with-current-continuation
(lambda (cont)
(apply (cps-proc/handler the-proc) cont args)))))
(init-operators!)
| false |
d496095f5413cb076d0bc276033b3468040c8dcc
|
f0aadb8937159f3b3b16473fae75356449cf5a15
|
/src/game.scm
|
effdbd5dafd405151dd1f369fff786bfbde1748c
|
[] |
no_license
|
joethecodhr/card-crawl-monte-carlo
|
a4cce87baf6a86d6062e3657f020673a6f7a2413
|
c4adb918d6c35bc8402d12d645e3ef853490f3c2
|
refs/heads/master
| 2023-06-02T14:04:07.481841 | 2021-06-19T04:00:16 | 2021-06-19T04:00:16 | 375,422,226 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 3,986 |
scm
|
game.scm
|
(define (make-game deck dealer-slots player-slots discard-pile sacrifice-counter game-state)
(list
;; dealers deck
deck
;; playfield
(cons dealer-slots player-slots)
;; the discard pile
discard-pile
;; sacrifice counter
sacrifice-counter
;; game state
game-state))
(define (make-new-game)
(make-game (make-deck) (make-dealer-slots) (make-player-slots) 'the-empty-deck 0 'game-not-started))
(define (deck game) (list-ref game 0))
(define (dealer-slots game) (car (list-ref game 1)))
(define (player-slots game) (cdr (list-ref game 1)))
(define (discard-pile game) (list-ref game 2))
(define (sacrifice-counter game) (list-ref game 3))
(define (game-state game) (list-ref game 4))
;; Deal cards into empty slots, until there are no more empty slots.
;; Returns (list [new deck state] [new slot state])
(define (deal game)
(let* ((game-deck (deck game))
(slots (dealer-slots game)))
(define (slot-iter new-slots remaining-slots remaining-deck)
(cond
((= (length new-slots) (length slots)) (list remaining-deck new-slots))
((= (length remaining-deck) 0) (list remaining-deck new-slots))
(else
(let ((test-slot (car remaining-slot))
(top-card (list-ref remaining-deck 0)))
(cond ((= (length new-slots) (length slots))
new-slots)
((equal? (slot-card test-slot) 'the-empty-slot)
(slot-iter (append new-slots (list (put-card-in-slot top-card test-slot))) (list-tail remaining-slots 1) (list-tail remaining-deck 1)))
(else
(slot-iter (append new-slots (list test-slot)) (list-tail remaining-slots 1) remaining-deck)))))))
(let ((post-deal-state (slot-iter '() slots game-deck)))
(list
(list-ref post-deal-state 0)
(cons (list-ref post-deal-state 1) (player-slots game))
(discard-pile game)
(sacrifice-counter game)
(game-state game)))))
;; Takes a card from a slot
;; Returns (list [card taken] [new slot state])
(define (take-card-from-slot slot-number slots)
(cond ((or (< slot-number 0) (> slot-number (- (length slots) 1))) (error 'take-card-from-slot "slot-number out of range"))
((equal? (slot-card (list-ref slots slot-number)) 'the-empty-slot) (error 'take-card-from-slot "slot is empty"))
(else (list (list-ref slots slot-number) (replace-card-in-slot slot-number slots 'the-empty-card)))))
;; Replaces a card in a slot
;; Returns [new slot state]
(define (replace-card-in-slot slot-number slots card)
(define (slot-iter return-slots remaining-slots)
(cond ((= (length return-slots) (length slots)) return-slots)
((= slot-number (length return-slots)) (slot-iter (append return-slots (list card)) (list-tail remaining-slots 1)))
(else (slot-iter (append return-slots (list (car remaining-slots))) (list-tail remaining-slots 1)))))
(slot-iter '() slots))
;; Game over conditions.
(define (player-is-dead? game) #f)
(define (dealer-slots-empty? game) #f)
;; Game loop!
(define (do-nothing-action state) state)
(define (determine-player-action game) do-nothing-action)
(define (one-turn game player-action-fn)
(let* ((post-deal-state (deal game))
(post-player-action-state (player-action-fn post-deal-state)))
post-player-action-state))
(define (play-game game)
(define (game-loop game-state turn-count)
(display game-state)
(display "\n")
(let* ((player-action (determine-player-action game-state))
(end-of-turn-state (one-turn game-state player-action))
(new-turn-count (+ turn-count 1)))
(display "turn ")
(display new-turn-count)
(display "\n")
(cond ((player-is-dead? end-of-turn-state) (display "player-is-dead") end-of-turn-state)
((dealer-slots-empty? end-of-turn-state) (display "player-won") end-of-turn-state)
((> new-turn-count 100) (display "turn-count-too-high") end-of-turn-state)
(else (game-loop end-of-turn-state new-turn-count)))))
(game-loop game 0))
| false |
201daee74dd60bb852143673c1a8e5e6c99cc332
|
b1173d4fc0810dcdb11ce9aa18425bf7867f922d
|
/PreviousAttempts/xor-sat-solve.scm
|
0735dba903f705df30e008c0ba173597281b95a4
|
[] |
no_license
|
scottviteri/XORSatSolver
|
1adfe781ccaafc82d6bf345782f090c2d339260f
|
19b9b1d83cb98bdd84cc990f170355e40ab1ba9a
|
refs/heads/main
| 2023-01-21T13:26:17.942569 | 2020-12-03T16:35:40 | 2020-12-03T16:35:40 | 312,746,742 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 6,789 |
scm
|
xor-sat-solve.scm
|
(use-modules
(srfi srfi-1)
(srfi srfi-69)
(ice-9 match)
(ice-9 popen)
(ice-9 rdelim)
(ice-9 receive)
(ice-9 vlist))
; create hash-cons repr
(define-syntax test
(syntax-rules ()
((_ commands ...)
(begin
(display (begin (reset)
commands
...))
(newline)))))
(define (pa f x) (lambda (y) (f x y)))
(define H (alist->vhash '((x0 . 2) (one . 1) (zero . 0))))
(define A (list->vlist '(x0 one zero)))
(define memo (alist->vhash '()))
(define (reset)
(set! H (alist->vhash '((x0 . 2) (one . 1) (zero . 0))))
(set! A (list->vlist '(x0 one zero)))
(set! memo (alist->vhash '())))
(define* (lookup term)
(if (number? term) term
(let ((found (vhash-assoc term H)))
(if found
(cdr found)
(let ((new-id (vlist-length A)))
(set! H (vhash-cons term new-id H))
(set! A (vlist-cons term A))
new-id)))))
(test
(lookup '(* 0 1))
(vhash-assoc '(* 0 1) H)); -> ((* 0 1) . 3)
(define (s-and t1 t2)
(lookup (list '* t1 t2)))
(define (s-xor t1 t2)
(lookup (list '+ t1 t2)))
(define leaf? (compose not list?))
(define (share term)
; (share '(+ (* x0 x1) (+ x0 x2)))
(if (leaf? term)
(lookup term)
(if (eq? (car term) '*)
(s-and (share (cadr term))
(share (caddr term)))
(s-xor (share (cadr term))
(share (caddr term))))))
(define (vlist-ref' index)
(vlist-ref A (- (vlist-length A) index 1)))
(define (unroll prog-idx)
(let ((prog (vlist-ref' prog-idx)))
(if (leaf? prog) prog
(list (car prog)
(unroll (cadr prog))
(unroll (caddr prog))))))
(test
(lookup 'x1)
(lookup (list '* 2 3))
(lookup (list '+ 4 4))
(unroll 5)) ; (+ (* x0 x1) (* x0 x1))
(define (compile-to-xor formula) ; (∧ (∧ x0 x0) x1) -> 6
(if (leaf? formula) (lookup formula)
(if (= 2 (length formula)) ; ¬ case
(share (list '+ 'one (compile-to-xor (cadr formula))))
(let* ([binop (car formula)]
[fst (cadr formula)]
[snd (caddr formula)]
[fst-xor (compile-to-xor fst)]
[snd-xor (compile-to-xor snd)])
(share (match binop
['∧ (list '* fst-xor snd-xor)]
['∨ (list '+ fst-xor (list '+ snd-xor (list '* fst-xor snd-xor)))]
['⇒ (list '+ 'one (list '+ fst-xor (list '* fst-xor snd-xor)))]
['⊕ (list '+ fst-xor snd-xor)]
['⇔ (list '+ 'one (list '+ fst-xor snd-xor))]))))))
(test
(compile-to-xor '(⊕ (∧ x0 x1) (∧ x0 x1))) ;5
(display (vlist->list H)) (newline)
;(((+ 4 4) . 5) ((* 2 3) . 4) (x1 . 3) (x0 . 2) (one . 1) (zero . 0))
(unroll 5)) ; (+ (* x0 x1) (* x0 x1))
(test (unroll (compile-to-xor '(⇒ (⇔ x0 one) (⇔ x0 one)))))
; (+ one (+ (+ one (+ x0 one)) (* (+ one (+ x0 one)) (+ one (+ x0 one)))))
; A + B <-> B + A ; can implement by moving to normal form (using hash order)
; A * B <-> B * A ; can implement by moving to normal form
; A + A -> 0
; A * A -> A
; A + 0 -> A
; A * 1 -> A
; A * 0 -> 0
; A * (B + C) -> A * B + A * C ; could do greedily
; (A + B) * C -> A * C + B * C ; could do greedily
; greedy distrib law is same as pushing multiplications down in the tree
; also evaluation order matters (want to do push mult down last)
; be careful with distrib <-- could split to prevent space blowup
; don't forget assoc of add and mult <-- maybe not necessary?
; what about (+ 1 (+ 1 x0))? want to reduce to x0
; this is why not doing in one step
; A + A -> 0
; A * A -> A
; A + 0 -> A
; 0 + A -> A
; A * 1 -> A
; 1 * A -> A
; A * 0 -> 0
; 0 * A -> 0
(define (idemp-add? lst) (and (list? lst) (eq? (car lst) '+) (eq? (cadr lst) (caddr lst))))
(define (idemp-mult? lst) (and (list? lst) (eq? (car lst) '*) (eq? (cadr lst) (caddr lst))))
(define (mult-distrib-fst-lst? lst) (and (eq? (car lst) '*) ;vref
(not (leaf? (cadr lst)))
(eq? (car (cadr lst)) '+)))
(define (mult-distrib-snd-lst? lst) (and (eq? (car lst) '*)
(not (leaf? (caddr lst)))
(eq? (car (caddr lst)) '+)))
(define (simplify-xor prog-idx) ; currently caches intermediate computations
(let ([formula (vlist-ref' prog-idx)])
(if (leaf? formula) prog-idx ; no nots
(match formula
[('+ '0 snd) (simplify-xor snd)]
[('+ fst '0) (simplify-xor fst)]
[('* '0 snd) (lookup 'zero)]
[('* fst '0) (lookup 'zero)]
[('* '1 snd) (simplify-xor snd)]
[('* fst '1) (simplify-xor fst)]
[(? idemp-add? x) (lookup 'zero)]
[(? idemp-mult? x) (simplify-xor (cadr x))]
[('+ fst snd) (lookup (if (<= fst snd)
(list '+ (simplify-xor fst) (simplify-xor snd))
(list '+ (simplify-xor snd) (simplify-xor fst))))]
[(? mult-distrib-snd-lst? x) ; (* a (+ b c)) -> (+ (* a b) (* a c))
(let* ([a (cadr x)] [b (cadr (caddr x))] [c (caddr (caddr x))]
[sa (simplify-xor a)] [sb (simplify-xor b)] [sc (simplify-xor c)])
(share (list '+ (list '* sa sb) (list '* sa sc))))]
[(? mult-distrib-snd-lst? x) ; (* (+ a b) c) -> (+ (* a c) (* b c))
(let* ([a (cadr (cadr x))] [b (caddr (cadr x))] [c (caddr x)]
[sa (simplify-xor a)] [sb (simplify-xor b)] [sc (simplify-xor c)])
(share (list '+ (list '* sa sc) (list '* sb sc))))]
[('* fst snd) (lookup (list '* (simplify-xor fst) (simplify-xor snd)))]
[else formula]))))
; final form 1 + a + b + c + ab + ac + bc + abc <-- if all coeffs one
; will have to do fixpoint, because for example (* (+ a b) (+ c d))
; would have to extend vhash to be nary, maybe not terrible <-- worth doing in other file
; want to make n-ary, by collecting by assoc
; normal commutative form not enough (+ 1 (+ x0 (+ 1 x0)))
(test (unroll (simplify-xor (share '(+ zero x1))))) ;x1
(test (unroll (simplify-xor (share '(* x1 zero))))) ;zero
(test (unroll (simplify-xor (share '(* zero x1))))) ;zero
(test (unroll (simplify-xor (share '(* x1 x1))))) ;x1
(test (unroll (simplify-xor (share '(+ x1 x1))))) ;zero
(test (unroll (simplify-xor (share '(* (+ x1 x2) (+ x3 x4))))))
(test (unroll (simplify-xor (share '(+ (+ x1 x2) (+ x1 x2)))))) ; zero
(test (unroll (simplify-xor (share '(+ one (+ one x0)))))) ; (+ one (+ one x0))
;(test (simplify-xor (share '(+ one (+ (+ one (+ x0 one))
; (* (+ one (+ x0 one)) (+ one (+ x0 one))))))))
| true |
4ee41e2c4f33ada8837d60acc7dc1de369b08ff1
|
9cb1626e30c6ea40b11cd3715c03d0d5b88722de
|
/config.scm
|
0e9a51031e862d3a7d08849663410f277ddfeeab
|
[
"Zlib"
] |
permissive
|
alvatar/sphere-core
|
fbc2a76ed6743cbe7be99ff0abf50a79e331bb55
|
09e07d8b881f6b0292a4292b8b9a30a4ab5798f7
|
refs/heads/master
| 2020-05-18T13:32:08.074184 | 2015-03-21T12:17:50 | 2015-03-21T12:17:50 | 976,512 | 9 | 0 | null | 2014-04-26T12:30:09 | 2010-10-10T15:43:10 |
Scheme
|
UTF-8
|
Scheme
| false | false | 116 |
scm
|
config.scm
|
(sphere: "core")
(dependencies:
(ffi
(prelude
(= ffi-prelude)))
(ffi-macros
(include
(= base-macros))))
| false |
9c7d7b477e7e63b0b7bf21d5f507293bae83e56f
|
46fca96aa808b5df06f3131020d54b495220ef2c
|
/base/view.scm
|
bc2789917832e0d6371b000410334c7257430dbe
|
[
"BSD-3-Clause"
] |
permissive
|
gurugeek/province
|
d28222b8992e16e5b725215f16cbe518c9f71227
|
76c8d2c9475787cc3a60b3f62727c7430e635483
|
refs/heads/master
| 2021-03-02T18:39:59.517603 | 2017-12-09T18:55:42 | 2017-12-09T19:00:32 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,916 |
scm
|
view.scm
|
;;
;; View layer helpers
;; (c) 2017 Alexander Sharikhin
;; Part of province web engine
;;
;; Mine logicless templating
(define (tpl->string template #!optional list-of-params)
(unless (string? template) (abort '"Template must be a string"))
(unless (or (list? list-of-params) (eq? #f list-of-params)) (abort '"List-of-params must be #f or list"))
(when (list? list-of-params)
(let ((replacements (map
(lambda (element)
(cons
(string-append "<% " (car element) " %>")
(cadr element)))
list-of-params)))
(set! template (string-translate* template replacements))))
(string-substitute* template '(("<% .+ %>" . ""))))
(define tpl-cache (make-hash-table))
;; Read file and use it as template
(define (file-tpl->string file-name #!optional list-of-params)
(unless (string? file-name) (abort '"File name must be string"))
(cond
((hash-table-ref/default tpl-cache file-name #f)
(tpl->string (hash-table-ref tpl-cache file-name) list-of-params))
(else
(hash-table-set! tpl-cache file-name (file->string (string-append "tpl/" file-name)))
(file-tpl->string file-name list-of-params))))
;; Layouted view
(define (layouted-view layout-file-name file-name list-of-params #!key layout-params)
(unless (string? layout-file-name) (abort '"Layout file name must be a string"))
(unless (string? file-name) (abort '"File name of template must be a string"))
(let* ((content (file-tpl->string file-name list-of-params)))
(layout-fields `(("Content" ,content)))
(when layout-params (merge! layout-fields layout-params))
(file-tpl->string (string-append "layouts/" layout-file-name) layout-fields)))
| false |
4a18c957daea321dd69abca93bc39022ae7ca706
|
20c28c3cf18308c8b975311c60a572835f044210
|
/weinholt/r6rs-compatibility.sld
|
6245a9ea7d72449d78383c1a9e46ad8685aa7d56
|
[
"MIT"
] |
permissive
|
sethalves/industria
|
c364644518104c7f8d5621f071f8d0cbc11c4982
|
5129460d5db0bc467c0c714026adc9c2fb3b3c19
|
refs/heads/master
| 2021-01-17T23:36:30.100029 | 2014-07-29T16:13:54 | 2014-07-29T16:13:54 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 24,491 |
sld
|
r6rs-compatibility.sld
|
(define-library (weinholt r6rs-compatibility)
(export
assert
bitwise-length
utf16->string
for-all
exists
bitwise-bit-set?
bitwise-bit-field
bytevector-fill!
native-endianness
bytevector-ieee-single-native-ref
bytevector-ieee-single-ref
bytevector-ieee-double-native-ref
bytevector-ieee-double-ref
bytevector-ieee-single-native-set!
bytevector-ieee-single-set!
bytevector-ieee-double-native-set!
bytevector-ieee-double-set!
;; bytevector-u8-ref
bytevector-s8-ref
bytevector-u8-native-ref
bytevector-s8-native-ref
;; bytevector-u8-set!
bytevector-s8-set!
bytevector-u8-native-set!
bytevector-s8-native-set!
bytevector-u16-ref
bytevector-s16-ref
bytevector-u16-native-ref
bytevector-s16-native-ref
bytevector-u16-set!
bytevector-s16-set!
bytevector-u16-native-set!
bytevector-s16-native-set!
bytevector-u32-ref
bytevector-s32-ref
bytevector-u32-native-ref
bytevector-s32-native-ref
bytevector-u32-set!
bytevector-s32-set!
bytevector-u32-native-set!
bytevector-s32-native-set!
bytevector-u64-ref
bytevector-s64-ref
bytevector-u64-native-ref
bytevector-s64-native-ref
bytevector-u64-set!
bytevector-s64-set!
bytevector-u64-native-set!
bytevector-s64-native-set!
bytevector-uint-ref
bytevector-sint-ref
bytevector-uint-set!
bytevector-sint-set!
call-with-bytevector-output-port
call-with-string-output-port
bitwise-bit-count
bitwise-reverse-bit-field
bitwise-rotate-bit-field
fxarithmetic-shift-left
fxarithmetic-shift-right
bitwise-arithmetic-shift-left
bitwise-arithmetic-shift-right
fx+
fx-
fx*
fx=?
fx>=?
fxbit-count
fxbit-field
fxior
fxand
)
(import (scheme base)
(scheme write)
(srfi 60))
(cond-expand
(chicken
;; without this, chicken has trouble with large numbers near the
;; fixnum limit -- for example 9223372036854775808
(import (numbers)))
(else))
(begin
(define-syntax assert
(syntax-rules ()
((_ e)
(if (not e)
(error "Assertion failed" `e e)))))
(define (bitwise-length i)
(do ((result 0 (+ result 1))
(bits (if (negative? i)
(bitwise-not i)
i)
(arithmetic-shift bits -1)))
((zero? bits)
result)))
(define (utf16->string bv endian)
(error "write utf16->string"))
;; from sagittarius
(define (list-transpose+ . rest)
(let ((len (length (car rest))))
(let loop ((i 0)
(rest rest)
(r '()))
(if (= i len)
(reverse r)
(loop (+ i 1)
(let loop ((r '())
(p rest))
(if (null? p)
(reverse r)
(loop (cons (cdr (car p)) r) (cdr p))))
(cons
(let loop ((r '())
(p rest))
(if (null? p)
(reverse r)
(loop (cons (car (car p)) r) (cdr p))))
r))))))
;; from sagittarius
(define (for-all pred lst1 . lst2)
(define (for-all-n pred list-of-lists)
(let ((argc (length list-of-lists)))
(define (collect-cdr lst)
(let loop ((lst lst))
(cond ((null? lst) '())
((null? (cdar lst)) (loop (cdr lst)))
(else (cons (cdar lst) (loop (cdr lst)))))))
(define (collect-car lst)
(let loop ((lst lst))
(cond ((null? lst) '())
((pair? (car lst))
(cons (caar lst) (loop (cdr lst))))
(else
(error "for-all -- traversal reached to non-pair element."
(car lst))))))
(let loop ((head (collect-car list-of-lists)) (rest (collect-cdr list-of-lists)))
(or (= (length head) argc)
(error "for-all -- expected same length chains of pairs" list-of-lists))
(if (null? rest)
(apply pred head)
(and (apply pred head)
(loop (collect-car rest) (collect-cdr rest)))))))
(define (for-all-n-quick pred lst)
(or (null? lst)
(let loop ((head (car lst)) (rest (cdr lst)))
(if (null? rest)
(apply pred head)
(and (apply pred head)
(loop (car rest) (cdr rest)))))))
(define (for-all-1 pred lst)
(cond ((null? lst) #t)
((pair? lst)
(let loop ((head (car lst)) (rest (cdr lst)))
(cond ((null? rest) (pred head))
((pair? rest)
(and (pred head)
(loop (car rest) (cdr rest))))
(else
(and (pred head)
(error "for-all -- traversal reached to non-pair element" rest))))))
(else
(error "for-all -- expected chain of pairs" (list pred lst)))))
(cond ((null? lst2)
(for-all-1 pred lst1))
((apply list-transpose+ lst1 lst2)
=> (lambda (lst) (for-all-n-quick pred lst)))
(else
(for-all-n pred (cons lst1 lst2)))))
;; from sagittarius
(define (exists pred lst1 . lst2)
(define (exists-1 pred lst)
(cond ((null? lst) #f)
((pair? lst)
(let loop ((head (car lst)) (rest (cdr lst)))
(cond ((null? rest) (pred head))
((pred head))
((pair? rest) (loop (car rest) (cdr rest)))
(else
(error "exists -- traversal reached to non-pair element"
rest)))))
(else
(error "exists -- expected chain of pairs." (list pred lst)))))
(define (exists-n-quick pred lst)
(and (pair? lst)
(let loop ((head (car lst)) (rest (cdr lst)))
(if (null? rest)
(apply pred head)
(or (apply pred head)
(loop (car rest) (cdr rest)))))))
(define (exists-n pred list-of-lists)
(let ((argc (length list-of-lists)))
(define (collect-cdr lst)
(let loop ((lst lst))
(cond ((null? lst) '())
((null? (cdar lst)) (loop (cdr lst)))
(else (cons (cdar lst) (loop (cdr lst)))))))
(define (collect-car lst)
(let loop ((lst lst))
(cond ((null? lst) '())
((pair? (car lst))
(cons (caar lst) (loop (cdr lst))))
(else
(error "exists -- traversal reached to non-pair"
(car lst))))))
(let loop ((head (collect-car list-of-lists)) (rest (collect-cdr list-of-lists)))
(or (= (length head) argc)
(error "exists -- expected same length chains of pairs"
list-of-lists))
(if (null? rest)
(apply pred head)
(or (apply pred head)
(loop (collect-car rest) (collect-cdr rest)))))))
(cond ((null? lst2)
(exists-1 pred lst1))
((apply list-transpose+ lst1 lst2)
=> (lambda (lst) (exists-n-quick pred lst)))
(else
(exists-n pred (cons lst1 lst2)))))
(define (bitwise-bit-set? n i)
(> (bitwise-and (arithmetic-shift n (- i)) 1) 0))
(define (bytevector-fill! bv n)
(let loop ((i 0))
(cond ((= i (bytevector-length bv)) bv)
(else
(bytevector-u8-set! bv i n)
(loop (+ i 1))))))
(define (native-endianness) 'big)
(define (ieee-754->number bits)
(cond ;; scheme2js can't parse the +inf.0
;; ((= bits #x7f800000) +inf.0)
;; ((= bits #xff800000) -inf.0)
;; ((= (bitwise-and bits #xff800000) #xff800000) -nan.0)
;; ((= (bitwise-and bits #x7f800000) #x7f800000) +nan.0)
(else
(let* ((sign-bit (arithmetic-shift (bitwise-and bits #x80000000) -31))
(exponent (arithmetic-shift (bitwise-and bits #x7f800000) -23))
(fraction (bitwise-and bits #x007fffff))
(fraction-as-number
(let loop ((i #x00400000)
(v (/ 1.0 2.0))
(result 0))
(if (= i 0)
(if (= exponent 0) result (+ 1.0 result))
(loop (arithmetic-shift i -1)
(/ v 2.0)
(if (> (bitwise-and fraction i) 0)
(+ result v)
result))))))
(* (if (= sign-bit 0) 1.0 -1.0)
(expt 2 (- exponent 127)) fraction-as-number)))))
(define (number->ieee-754 f32)
(cond ;; ((eqv? f32 +inf.0) #x7f800000)
;; ((eqv? f32 -inf.0) #xff800000)
;; ((eqv? f32 +nan.0) #x7f800001)
((eqv? f32 0) #x00000000)
((eqv? f32 0.0) #x00000000)
(else
(let* ((sign-bit (if (< f32 0) 1 0))
(f32 (if (< f32 0) (- f32) f32))
)
(let loop ((f32-shifted f32)
(exponent 0))
(cond ((< f32-shifted 1.0)
(loop (* f32-shifted 2.0) (- exponent 1)))
((>= f32-shifted 2.0)
(loop (/ f32-shifted 2.0) (+ exponent 1)))
(else
(let loop ((fraction (- f32-shifted 1.0))
(fraction-bits 0)
(pow2 #x400000))
(if (> pow2 0)
(cond ((>= (* fraction 2.0) 1.0)
(loop (- (* fraction 2.0) 1.0)
(bitwise-ior pow2 fraction-bits)
(arithmetic-shift pow2 -1)))
(else
(loop (* fraction 2.0)
fraction-bits
(arithmetic-shift pow2 -1))))
;; done
(begin
;; (cout "sign="
;; (number->string sign-bit 2) "\n")
;; (cout "exponent="
;; (number->string (+ exponent 127) 2) "\n")
;; (cout "fraction="
;; (number->string fraction-bits 2) "\n")
(bitwise-ior
(arithmetic-shift sign-bit 31)
(arithmetic-shift (+ exponent 127) 23)
fraction-bits))
)))))))))
(define (bytevector-ieee-single-native-ref bv k)
(bytevector-ieee-single-ref bv k (native-endianness)))
(define (bytevector-ieee-single-ref bv k endianness)
(ieee-754->number (bytevector-u32-ref bv k endianness)))
(define (bytevector-ieee-double-native-ref bv k)
(bytevector-ieee-double-ref bv k (native-endianness)))
(define (bytevector-ieee-double-ref bv k endianness)
;; XXX ieee-754->number isn't right
(ieee-754->number (bytevector-u64-ref bv k endianness)))
(define (bytevector-ieee-single-native-set! bv k x)
(bytevector-ieee-single-set! bv k x (native-endianness)))
(define (bytevector-ieee-single-set! bv k n endianness)
(bytevector-u32-set! bv k (number->ieee-754 n) endianness))
(define (bytevector-ieee-double-native-set! bv k x)
(bytevector-ieee-double-set! bv k x (native-endianness)))
(define (bytevector-ieee-double-set! bv k n endianness)
;; XXX ieee-754->number isn't right
(bytevector-u64-set! bv k (number->ieee-754 n) endianness))
;; (define (bytevector-u8-ref bv k endianness)
;; (error "write bytevector-u8-ref"))
(define (bytevector-s8-ref bv k)
(let ((n (bytevector-u8-ref bv k)))
(if (= (bitwise-and n #x80) 0)
n
(- (+ (bitwise-and (bitwise-not n) #xff) 1)))))
(define (bytevector-u8-native-ref bv k)
(bytevector-u8-ref bv k))
(define (bytevector-s8-native-ref bv k)
(bytevector-s8-ref bv k))
;; (define (bytevector-u8-set! bv k n)
;; (error "write bytevector-u8-set!"))
(define (bytevector-s8-set! bv k n)
(bytevector-u8-set!
bv k (if (>= n 0)
n
(+ (bitwise-and (bitwise-not (- n)) #xff) 1))))
(define (bytevector-u8-native-set! bv k n)
(bytevector-u8-set! bv k n))
(define (bytevector-s8-native-set! bv k n)
(bytevector-s8-set! bv k n))
(define (bytevector-u16-ref bv k endianness)
(case endianness
((big)
(bitwise-ior (arithmetic-shift (bytevector-u8-ref bv k) 8)
(bytevector-u8-ref bv (+ k 1))))
((little)
(bitwise-ior
(bytevector-u8-ref bv k)
(arithmetic-shift (bytevector-u8-ref bv (+ k 1)) 8)))))
(define (bytevector-s16-ref bv k endianness)
(let ((n (bytevector-u16-ref bv k endianness)))
(if (= (bitwise-and n #x8000) 0)
n
(- (+ (bitwise-and (bitwise-not n) #xffff) 1)))))
(define (bytevector-u16-native-ref bv k)
(bytevector-u16-ref bv k (native-endianness)))
(define (bytevector-s16-native-ref bv k)
(bytevector-s16-ref bv k (native-endianness)))
(define (bytevector-u16-set! bv k n endianness)
(case endianness
((big)
(bytevector-u8-set! bv k (bitwise-and (arithmetic-shift n -8) #xff))
(bytevector-u8-set! bv (+ k 1) (bitwise-and n #xff)))
((little)
(bytevector-u8-set! bv k (bitwise-and n #xff))
(bytevector-u8-set!
bv (+ k 1) (bitwise-and (arithmetic-shift n -8) #xff)))))
(define (bytevector-s16-set! bv k n endianness)
(bytevector-u16-set!
bv k (if (>= n 0)
n
(+ (bitwise-and (bitwise-not (- n)) #xffff) 1))
endianness))
(define (bytevector-u16-native-set! bv k n)
(bytevector-u16-set! bv k n (native-endianness)))
(define (bytevector-s16-native-set! bv k n)
(bytevector-s16-set! bv k n (native-endianness)))
(define (bytevector-u32-ref bv k endianness)
(case endianness
((big)
(bitwise-ior
(arithmetic-shift (bytevector-u16-ref bv k 'big) 16)
(bytevector-u16-ref bv (+ k 2) 'big)))
((little)
(bitwise-ior
(bytevector-u16-ref bv k 'little)
(arithmetic-shift (bytevector-u16-ref bv (+ k 2) 'little) 16)))))
(define (bytevector-s32-ref bv k endianness)
(let ((n (bytevector-u32-ref bv k endianness)))
(if (= (bitwise-and n #x80000000) 0)
n
(- (+ (bitwise-and (bitwise-not n) #xffffffff) 1)))))
(define (bytevector-u32-native-ref bv k)
(bytevector-u32-ref bv k (native-endianness)))
(define (bytevector-s32-native-ref bv k)
(bytevector-s32-ref bv k (native-endianness)))
(define (bytevector-u32-set! bv k n endianness)
(case endianness
((big)
(bytevector-u16-set!
bv k (bitwise-and (arithmetic-shift n -16) #xffff) 'big)
(bytevector-u16-set! bv (+ k 2) (bitwise-and n #xffff) 'big))
((little)
(bytevector-u16-set! bv k (bitwise-and n #xffff) 'little)
(bytevector-u16-set!
bv (+ k 2) (bitwise-and (arithmetic-shift n -16) #xffff) 'little)))
)
(define (bytevector-s32-set! bv k n endianness)
(bytevector-u32-set!
bv k (if (>= n 0)
n
(+ (bitwise-and (bitwise-not (- n)) #xffffffff) 1))
endianness))
(define (bytevector-u32-native-set! bv k n)
(bytevector-u32-set! bv k n (native-endianness)))
(define (bytevector-s32-native-set! bv k n)
(bytevector-s32-set! bv k n (native-endianness)))
(define (bytevector-u64-ref bv k endianness)
(case endianness
((big)
(bitwise-ior
(arithmetic-shift (bytevector-u32-ref bv k 'big) 32)
(bytevector-u32-ref bv (+ k 4) 'big)))
((little)
(bitwise-ior
(bytevector-u32-ref bv k 'little)
(arithmetic-shift (bytevector-u32-ref bv (+ k 4) 'little) 32)))))
(define (bytevector-s64-ref bv k endianness)
(let ((n (bytevector-u64-ref bv k endianness)))
(if (= (bitwise-and n #x8000000000000000) 0)
n
(- (+ (bitwise-and (bitwise-not n) #xffffffffffffffff) 1)))))
(define (bytevector-u64-native-ref bv k)
(bytevector-u64-ref bv k (native-endianness)))
(define (bytevector-s64-native-ref bv k)
(bytevector-s64-ref bv k (native-endianness)))
(define (bytevector-u64-set! bv k n endianness)
(case endianness
((big)
(bytevector-u32-set!
bv k (bitwise-and (arithmetic-shift n -32) #xffffffff) 'big)
(bytevector-u32-set! bv (+ k 4) (bitwise-and n #xffffffff) 'big))
((little)
(bytevector-u32-set! bv k (bitwise-and n #xffffffff) 'little)
(bytevector-u32-set!
bv (+ k 4) (bitwise-and (arithmetic-shift n -32)
#xffffffff) 'little))))
(define (bytevector-s64-set! bv k n endianness)
(bytevector-u64-set!
bv k (if (>= n 0)
n
(+ (bitwise-and (bitwise-not (- n)) #xffffffffffffffff) 1))
endianness))
(define (bytevector-u64-native-set! bv k n)
(bytevector-u64-set! bv k n (native-endianness)))
(define (bytevector-s64-native-set! bv k n)
(bytevector-s64-set! bv k n (native-endianness)))
;; from sagittarius
(define (bytevector-uint-ref bv index endien size)
(cond ((eq? endien 'big)
(let ((end (+ index size)))
(let loop ((i index) (acc 0))
(if (>= i end)
acc
(loop (+ i 1)
(+ (* 256 acc) (bytevector-u8-ref bv i)))))))
((eq? endien 'little)
(let loop ((i (+ index size -1)) (acc 0))
(if (< i index)
acc
(loop (- i 1) (+ (* 256 acc) (bytevector-u8-ref bv i))))))
(else
(error 'bytevector-uint-ref "expected endianness" endien))))
;; from sagittarius
(define (bytevector-sint-ref bv index endien size)
(cond ((eq? endien 'big)
(if (> (bytevector-u8-ref bv index) 127)
(- (bytevector-uint-ref bv index endien size) (expt 256 size))
(bytevector-uint-ref bv index endien size)))
((eq? endien 'little)
(if (> (bytevector-u8-ref bv (+ index size -1)) 127)
(- (bytevector-uint-ref bv index endien size) (expt 256 size))
(bytevector-uint-ref bv index endien size)))
(else
(error 'bytevector-uint-ref "expected endianness" endien))))
;; from sagittarius
(define (bytevector-uint-set! bv index val endien size)
(cond ((= val 0)
(let ((end (+ index size)))
(let loop ((i index))
(cond ((>= i end) #t)
(else
(bytevector-u8-set! bv i 0)
(loop (+ i 1)))))))
((< 0 val (expt 256 size))
(cond ((eq? endien 'big)
(let ((start (- (+ index size) 1)))
(let loop ((i start) (acc val))
(cond ((< i index) #t)
(else
;; mod256 -> bitwise-and
(bytevector-u8-set! bv i (bitwise-and acc 255))
;; div256 -> bitwise-arithmetic-shift
(loop (- i 1) (arithmetic-shift acc -8)))))))
((eq? endien 'little)
(let ((end (+ index size)))
(let loop ((i index) (acc val))
(cond ((>= i end) #t)
(else
;; mod256 -> bitwise-and
(bytevector-u8-set! bv i (bitwise-and acc 255))
;; div256 -> bitwise-arithmetic-shift
(loop (+ i 1) (arithmetic-shift acc -8)))))))))
(else
(error 'bytevector-uint-set! "value out of range" val))))
;; from sagittarius
(define (bytevector-sint-set! bv index val endien size)
(let* ((p-bound (expt 2 (- (* size 8) 1)))
(n-bound (- (+ p-bound 1))))
(if (< n-bound val p-bound)
(if (> val 0)
(bytevector-uint-set! bv index val endien size)
(bytevector-uint-set! bv index (+ val (expt 256 size))
endien size))
(error 'bytevector-sint-set! "value out of range" val))))
(define (call-with-bytevector-output-port func)
(let ((out-bv (open-output-bytevector)))
(func out-bv)
(get-output-bytevector out-bv)))
(define (call-with-string-output-port func)
(let ((out-bv (open-output-string)))
(func out-bv)
(get-output-string out-bv)))
(define (bitwise-reverse-bit-field v start end)
(do ((i start (+ i 1))
(ret 0 (if (bitwise-bit-set? v i)
(bitwise-ior
ret (arithmetic-shift 1 (- end i 1)))
ret)))
((= i end)
(bitwise-ior (arithmetic-shift ret start)
(copy-bit-field v 0 start end)))))
(define (bitwise-rotate-bit-field n start end count)
(let ((width (- end start)))
(if (positive? width)
(let* ((count (modulo count width))
(field0 (bitwise-bit-field n start end))
(field1 (arithmetic-shift field0 count))
(field2 (arithmetic-shift field0 (- width count)))
(field (bitwise-ior field1 field2)))
(copy-bit-field n start end field))
n)))
(define (bitwise-bit-count ei)
(cond ((>= ei 0)
(let loop ((ei ei)
(result 0))
(if (= ei 0) result
(loop (arithmetic-shift ei -1)
(if (> (bitwise-and ei 1) 0)
(+ result 1)
result)))))
(else
(bitwise-not (bitwise-bit-count (bitwise-not ei))))))
(define (bitwise-bit-field x1 x2 x3)
(let ((mask (bitwise-not (arithmetic-shift -1 x3))))
(arithmetic-shift (bitwise-and x1 mask) (- x2))))
(define (fxarithmetic-shift-left v n)
(cond ((>= n 32) 0)
((< n -32) 0)
(else
(bitwise-and #xffffffffffffffff
(arithmetic-shift (bitwise-and #xffffffffffffffff v) n)))))
(define (fxarithmetic-shift-right v n)
(fxarithmetic-shift-left v (- n)))
(define (bitwise-arithmetic-shift-left v n)
(arithmetic-shift v n))
(define (bitwise-arithmetic-shift-right v n)
(arithmetic-shift v (- n)))
(define (fx+ a b)
(bitwise-and #xffffffffffffffff (+ a b)))
(define (fx- a b)
(bitwise-and #xffffffffffffffff (- a b)))
(define (fx* a b)
(bitwise-and #xffffffffffffffff (* a b)))
(define (fx=? a b)
(= a b))
(define (fx>=? a b)
(>= a b))
(define (fxbit-count v)
(bitwise-bit-count v))
(define (fxbit-field v a b)
(bitwise-bit-field (bitwise-and #xffffffffffffffff v) a b))
(define (fxior a b)
(bitwise-ior
(bitwise-and #xffffffffffffffff a)
(bitwise-and #xffffffffffffffff b)))
(define (fxand a b)
(bitwise-and
(bitwise-and #xffffffffffffffff a)
(bitwise-and #xffffffffffffffff b)))
))
| true |
a10bc9cfe8b786fffa7144262c5f65f06e4d4e91
|
46244bb6af145cb393846505f37bf576a8396aa0
|
/sicp/1_33.scm
|
11ca68f7c3ea7a500319583c6506dacb455f57e8
|
[] |
no_license
|
aoeuidht/homework
|
c4fabfb5f45dbef0874e9732c7d026a7f00e13dc
|
49fb2a2f8a78227589da3e5ec82ea7844b36e0e7
|
refs/heads/master
| 2022-10-28T06:42:04.343618 | 2022-10-15T15:52:06 | 2022-10-15T15:52:06 | 18,726,877 | 4 | 3 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,576 |
scm
|
1_33.scm
|
#lang racket
; Exercise 1.33. You can obtain an even more general version of accumulate (exercise 1.32) by
; introducing the notion of a filter on the terms to be combined.
; That is, combine only those terms derived from values in the range that satisfy a specified condition.
; The resulting filtered-accumulate abstraction takes the same arguments as accumulate,
; together with an additional predicate of one argument that specifies the filter.
; Write filtered-accumulate as a procedure. Show how to express the following using filtered-accumulate:
; copy the old prime? test code here
(define (square n) (* n n))
(define (smallest-divisor n)
(find-divisor n 2))
(define (next n)
(if (= n 2)
3
(+ n 2)))
(define (find-divisor n test-divisor)
(cond ((> (square test-divisor) n) n)
((divides? test-divisor n) test-divisor)
(else (find-divisor n (next test-divisor)))))
(define (divides? a b)
(= (remainder b a) 0))
(define (prime? n)
(= n (smallest-divisor n)))
; white the accumulate with filter
(define (accumlate combiner filter null-value term a next b)
(if (> a b)
null-value
(if (filter a)
(combiner (term a)
(accumlate combiner filter null-value term (next a) next b))
(accumlate combiner filter null-value term (next a) next b))
))
; a. the sum of the squares of the prime numbers in the interval a to b
; (assuming that you have a prime? predicate already written)
(define (pnext n) (+ n 1))
; 2^2 + 3^2 + 5^2 + 7^2
(accumlate + prime? 0 square 2 pnext 10)
| false |
888b27106696d4c9e2415686711f6b477e515953
|
a8216d80b80e4cb429086f0f9ac62f91e09498d3
|
/lib/scheme/fixnum.sld
|
fff356cc32808a3664b4660f2139dd81b0507b09
|
[
"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 | 57 |
sld
|
fixnum.sld
|
(define-library (scheme fixnum) (alias-for (srfi 143)))
| false |
6b46ec52514c85db613ac37b32fa37355873cba8
|
7a0de0d176e43453ee442354020ca0fd01111163
|
/examples/sum-no-sync.scm
|
0bfdaa57fb62de7c346d89752e8088abb64a26a6
|
[] |
no_license
|
cyclone-scheme/srfi-230
|
7e86480064c2fa1c37a8d5230884947dee668598
|
fa1bd9ef6496e41198265975953a2e20f8c415c0
|
refs/heads/master
| 2023-08-07T11:49:07.062809 | 2021-09-20T20:23:25 | 2021-09-20T20:23:25 | 408,588,306 | 5 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 462 |
scm
|
sum-no-sync.scm
|
(import (scheme base)
(scheme write)
(srfi 18)
(srfi 230))
(define *counter* 0)
(define (task)
(do ((i 0 (+ i 1)))
((= i 100000))
(set! *counter* (+ *counter* 1))))
(define threads (make-vector 10))
(do ((i 0 (+ i 1)))
((= i 10))
(let ((thread (make-thread task)))
(vector-set! threads i thread)
(thread-start! thread)))
(do ((i 0 (+ i 1)))
((= i 10))
(thread-join! (vector-ref threads i)))
(display *counter*)
(newline)
| false |
9b0ed55a32c54bcc406cf65c148f2c0e3de96c00
|
acc632afe0d8d8b94b781beb1442bbf3b1488d22
|
/deps/sdl2/lib/sdl2-internals/functions/renderer-draw.scm
|
2ed3c2fe2dac13baa475abf2932acb0753f191d7
|
[
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
kdltr/life-is-so-pretty
|
6cc6e6c6e590dda30c40fdbfd42a5a3a23644794
|
5edccf86702a543d78f8c7e0f6ae544a1b9870cd
|
refs/heads/master
| 2021-01-20T21:12:00.963219 | 2016-05-13T12:19:02 | 2016-05-13T12:19:02 | 61,128,206 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 4,048 |
scm
|
renderer-draw.scm
|
;;
;; chicken-sdl2: CHICKEN Scheme bindings to Simple DirectMedia Layer 2
;;
;; Copyright © 2013, 2015-2016 John Croisant.
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; - Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;;
;; - Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in
;; the documentation and/or other materials provided with the
;; distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
;; COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
;; HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
;; STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
;; OF THE POSSIBILITY OF SUCH DAMAGE.
(export SDL_GetRenderDrawBlendMode
SDL_SetRenderDrawBlendMode
SDL_GetRenderDrawColor
SDL_SetRenderDrawColor
SDL_RenderClear
SDL_RenderDrawLine
SDL_RenderDrawLines
SDL_RenderDrawPoint
SDL_RenderDrawPoints
SDL_RenderDrawRect
SDL_RenderDrawRects
SDL_RenderFillRect
SDL_RenderFillRects)
(define-function-binding SDL_GetRenderDrawBlendMode
return: (Sint32 zero-on-success)
args: ((SDL_Renderer* renderer)
((c-pointer "SDL_BlendMode") blend-mode-out)))
(define-function-binding SDL_SetRenderDrawBlendMode
return: (Sint32 zero-on-success)
args: ((SDL_Renderer* renderer)
(SDL_BlendMode blend-mode)))
(define-function-binding SDL_GetRenderDrawColor
return: (Sint32 zero-on-success)
args: ((SDL_Renderer* renderer)
(Uint8* r-out)
(Uint8* g-out)
(Uint8* b-out)
(Uint8* a-out)))
(define-function-binding SDL_SetRenderDrawColor
return: (Sint32 zero-on-success)
args: ((SDL_Renderer* renderer)
(Uint8 r)
(Uint8 g)
(Uint8 b)
(Uint8 a)))
(define-function-binding SDL_RenderClear
return: (Sint32 zero-on-success)
args: ((SDL_Renderer* renderer)))
(define-function-binding SDL_RenderDrawLine
return: (Sint32 zero-on-success)
args: ((SDL_Renderer* renderer)
(Sint32 x1)
(Sint32 y1)
(Sint32 x2)
(Sint32 y2)))
(define-function-binding SDL_RenderDrawLines
return: (Sint32 zero-on-success)
args: ((SDL_Renderer* renderer)
(SDL_Point* points)
(Sint32 count)))
(define-function-binding SDL_RenderDrawPoint
return: (Sint32 zero-on-success)
args: ((SDL_Renderer* renderer)
(Sint32 x)
(Sint32 y)))
(define-function-binding SDL_RenderDrawPoints
return: (Sint32 zero-on-success)
args: ((SDL_Renderer* renderer)
(SDL_Point* points)
(Sint32 count)))
(define-function-binding SDL_RenderDrawRect
return: (Sint32 zero-on-success)
args: ((SDL_Renderer* renderer)
(SDL_Rect*-or-null rect)))
(define-function-binding SDL_RenderDrawRects
return: (Sint32 zero-on-success)
args: ((SDL_Renderer* renderer)
(SDL_Rect* rects)
(Sint32 count)))
(define-function-binding SDL_RenderFillRect
return: (Sint32 zero-on-success)
args: ((SDL_Renderer* renderer)
(SDL_Rect*-or-null rect)))
(define-function-binding SDL_RenderFillRects
return: (Sint32 zero-on-success)
args: ((SDL_Renderer* renderer)
(SDL_Rect* rects)
(Sint32 count)))
| false |
b95fe6b210721d8e0ac12cf186b8ca8d0cdd2f8a
|
9998f6f6940dc91a99e0e2acb4bc4e918f49eef0
|
/src/test/sample-moby-programs/gui-world-box-group.ss
|
7779e1034b9348dd596dc9bf8b57a31189eba304
|
[] |
no_license
|
JessamynT/wescheme-compiler2012
|
326d66df382f3d2acbc2bbf70fdc6b6549beb514
|
a8587f9d316b3cb66d8a01bab3cf16f415d039e5
|
refs/heads/master
| 2020-05-30T07:16:45.185272 | 2016-03-19T07:14:34 | 2016-03-19T07:14:34 | 70,086,162 | 0 | 0 | null | 2016-10-05T18:09:51 | 2016-10-05T18:09:51 | null |
UTF-8
|
Scheme
| false | false | 443 |
ss
|
gui-world-box-group.ss
|
;; The first three lines of this file were inserted by DrScheme. They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-reader.ss" "lang")((modname gui-world-box-group) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ())))
(require (lib "gui-world.ss" "gui-world"))
(big-bang 0 (box-group "hello" "world"))
| false |
bc45650018ec88a153f3da96f9c0a499cb9e3907
|
42e0a1ffb4ccc7643f282f805566fc38aa376027
|
/connman.scm
|
d9e078c2c63ae00610c0fa803b92c551a7fa4f50
|
[] |
no_license
|
rmrfchik/jc
|
a0dd353659d6faf3b283b07002671d186b7e92b8
|
b4d09f92bcd7298f829131c4fa0704cfe78ca27f
|
refs/heads/master
| 2016-08-04T23:22:47.026582 | 2010-02-16T18:54:29 | 2010-02-16T18:54:29 | 520,652 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,463 |
scm
|
connman.scm
|
(require 'tcp)
(require 'ctx)
(tcp-read-timeout #f)
(define (make-connection instream oport)
(cons instream oport))
(define conn:in car)
(define conn:out cdr)
(define decl/stream (string->stream "<?xml version='1.0'?><stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' id='1216579762' from='localhost' version='1.0' xml:lang='en'>
<stream:features>
<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tl\"/>
<mechanisms xmlns=\"urn:ietf:params:xml:ns:xmpp-sas\">
<mechanism>DIGEST-MD5</mechanism>
<mechanism>PLAIN</mechanism>
</mechanisms>
<register xmlns=\"http://jabber.org/features/iq-register\"/>
</stream:features>"))
(define tls/stream (string->stream "<challenge xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">bm9uY2U9IjM1ODYzMjE3NjkiLHFvcD0iYXV0aCIsY2hhcnNldD11dGYtOCxhbGdvcml0aG09bWQ1LXNlc3M=</challenge>"))
(define (tcp-stream host port)
(let-values (((in out) (tcp-connect host port)))
(make-connection (reader->stream (lambda () (let ((c (read-char in)))
;(display c)
c)))
out)))
(define (get-connection* ctx)
;(make-connection decl/stream (current-output-port)))
(tcp-stream (car ctx) (cdr ctx)))
(define (get-connection ctx)
;(make-connection decl/stream (current-output-port)))
(ctx:connection->ctx (tcp-stream (ctx:ctx->hostname ctx) (ctx:ctx->port ctx)) ctx))
(define (switch-tls ctx)
(make-connection tls/stream (cdr ctx)))
| false |
39808c15a5d9d46f8f6b7657ee7caf3b84b255c2
|
a10b9011582079d783282e79e4cfdc93ace6f6d3
|
/exercises/10/03edges.scm
|
4856f5d29b11cd946b8179591f8e5d7d27ecfc41
|
[] |
no_license
|
hristozov/fpkn1415
|
2996a488c1feba6a595e466ca42a1418b03e2a77
|
9b44eb9c9ff4402ff22c2a5f55285c1f59b99722
|
refs/heads/master
| 2016-09-05T13:02:38.264241 | 2015-08-22T14:11:05 | 2015-08-22T14:11:05 | 24,793,324 | 11 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,996 |
scm
|
03edges.scm
|
(load "01graph.scm")
; Идеята на вземането на всички ребра:
; 1. Филтрираме върховете, които нямат никакви съседи (т.е. не участват в ребра)
; 2. За всеки от филтрираните върхове намираме всичките му съседи.
; 3. За всеки съсед от стъпка 2 създаваме двойката (връх съсед) и (с map) я
; правим част от списък от двойки който има вида ((връх-i съсед-1)
; (връх-i съсед-2) ...). Резултатът от тази операция ще са всичките ребра,
; които имат за начало избрания на стъпка 2 връх.
; 4. Залепяме списъците, получени на стъпка 3.
(define (edges g)
; С apply append „залепяме“ списъците с ребра за всеки връх. Тоест, превръщаме
; списък от вида (за върховете 1, 2, 3):
; (((1 2) (1 3)) ((2 1) (2 4)) ((3 5)))
; В списък от вида:
; ((1 2) (1 3) (2 1) (2 4) (3 5))
(apply
append
(map (lambda (vertex)
; Създаваме списък от всички ребра с начало vertex.
(map (lambda (neighbour)
; Добавяме ребро към резултата.
(list vertex neighbour))
(neighbours vertex g)))
; Филтрираме върховете, които имат съседи:
(filter (lambda (vertex)
(> (length (neighbours vertex g))
0))
(vertices g)))))
(define g1 (create-graph '(5 7)))
(add-vertex! 1 g1)
(add-vertex! 2 g1)
(add-vertex! 4 g1)
(add-edge! 1 2 g1)
(add-edge! 1 4 g1)
(add-edge! 5 2 g1)
(assert-equal '((5 2) (1 4) (1 2)) (edges g1))
| false |
8d1a27a46ad7dbf2fa246c0498dfac2ba2df96c0
|
784dc416df1855cfc41e9efb69637c19a08dca68
|
/src/lang/scheme/cxr.ss
|
3aa15b6602605cb144cfc49003ac1e98623ec0ce
|
[
"LGPL-2.1-only",
"Apache-2.0",
"LGPL-2.1-or-later"
] |
permissive
|
danielsz/gerbil
|
3597284aa0905b35fe17f105cde04cbb79f1eec1
|
e20e839e22746175f0473e7414135cec927e10b2
|
refs/heads/master
| 2021-01-25T09:44:28.876814 | 2018-03-26T21:59:32 | 2018-03-26T21:59:32 | 123,315,616 | 0 | 0 |
Apache-2.0
| 2018-02-28T17:02:28 | 2018-02-28T17:02:28 | null |
UTF-8
|
Scheme
| false | false | 314 |
ss
|
cxr.ss
|
;;; -*- Gerbil -*-
;;; (C) vyzo at hackzen.org
;;; R7RS (scheme cxr) library
package: scheme
(export
caaaar
caaadr
caaar
caadar
caaddr
caadr
cadaar
cadadr
cadar
caddar
cadddr
caddr
cdaaar
cdaadr
cdaar
cdadar
cdaddr
cdadr
cddaar
cddadr
cddar
cdddar
cddddr
cdddr
)
| false |
6d60e6914cddc37933751dffdc2ee4d624efc702
|
32130475e9aa1dbccfe38b2ffc562af60f69ac41
|
/exercises/03_67.scm
|
4f8b0894c1e49f135153ff90d5d504425927ac37
|
[] |
no_license
|
cinchurge/SICP
|
16a8260593aad4e83c692c4d84511a0bb183989a
|
06ca44e64d0d6cb379836d2f76a34d0d69d832a5
|
refs/heads/master
| 2020-05-20T02:43:30.339223 | 2015-04-12T17:54:45 | 2015-04-12T17:54:45 | 26,970,643 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,889 |
scm
|
03_67.scm
|
; SICP exercise 3.67
; (c) 2015 Eric Chung
;
(load "../examples/streams.scm")
(define (pairs s t)
(printf "pairs ~S ~S~N" s t)
(cons-stream
; We first take the head of both s and t and pair them together
; to create the head of the stream
(list (stream-car s) (stream-car t))
; We then pair the head of s with the rest of t, and interleave
; that with the sequence of pairs generated with the rest of s
; and the rest of t
(interleave-3
; In its original form, we add only one (x, t) term.
; now we want both (x, t) and (t, x), so we must add in a new
; stream. If we interleave (x, t) with the result of another
; interleave, we'll get duplicate results, therefore we'll
; need an interleave procedure that takes 3 streams.
(stream-map (lambda (x) (list (stream-car s) x))
(stream-cdr t))
(stream-map (lambda (x) (list x (stream-car s)))
(stream-cdr t))
(pairs (stream-cdr s) (stream-cdr t)))))
(define (interleave s1 s2)
(printf "interleave ~S ~S~N" s1 s2)
(if (stream-null? s1)
s2
(cons-stream (stream-car s1)
(interleave s2 (stream-cdr s1)))))
(define (interleave-3 s1 s2 s3)
(printf "interleave ~S ~S ~S~N" s1 s2 s3)
(cond ((stream-null? s1) (interleave s2 s3))
((stream-null? s2) (interleave s1 s3))
((stream-null? s3) (interleave s1 s2))
(else
(cons-stream (stream-car s1)
(cons-stream (stream-car s2)
(cons-stream (stream-car s3)
(interleave-3 (stream-cdr s1)
(stream-cdr s2)
(stream-cdr s3))))))))
(display-stream-upto (pairs integers integers) 20)
| false |
c3f382c419869e700336bf63fef10f676ba6289a
|
b6511594e926aab17fce152db02a8108b6a9eb53
|
/inverser-paires.scm
|
9817f70b84bf604b341ff3cde3a7caead0db2b27
|
[] |
no_license
|
sebhtml/scheme-exemples
|
5e6e36c7f678ba626652526ada55d9aa0dc4a363
|
ba2365e7d32f1b66b8931dbacdbcf94cf95ab9fd
|
refs/heads/master
| 2016-09-06T03:25:30.279204 | 2011-10-20T15:00:34 | 2011-10-20T15:00:34 | 2,613,841 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 278 |
scm
|
inverser-paires.scm
|
(define invert
(lambda (aList)
(if (null? aList)
null
(cons (car (cdr aList))
(cons (car aList)
(invert (cdr (cdr aList))))))))
(invert (list 1 2 2 3 4 5 6 7))
; la liste a un nombre pair de trucs
; doit retourner (list 2 1 3 2 5 4 7 6)
| false |
aab8e6ed88d5e935488944bdf5af0ccf6e748ed0
|
eef5f68873f7d5658c7c500846ce7752a6f45f69
|
/spheres/markup/sxml-modification.scm
|
d697f23ccd9071398d1524bb55b63d09b6041cf6
|
[
"MIT"
] |
permissive
|
alvatar/spheres
|
c0601a157ddce270c06b7b58473b20b7417a08d9
|
568836f234a469ef70c69f4a2d9b56d41c3fc5bd
|
refs/heads/master
| 2021-06-01T15:59:32.277602 | 2021-03-18T21:21:43 | 2021-03-18T21:21:43 | 25,094,121 | 13 | 3 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 36,386 |
scm
|
sxml-modification.scm
|
;;!!! A tool for making functional-style modifications to SXML documents
;; The basics of modification language design was inspired by Patrick Lehti and
;; his data manipulation processor for XML Query Language:
;; http://www.ipsi.fraunhofer.de/~lehti/
;; However, with functional techniques we can do this better...
;;
;; This software is in Public Domain.
;; IT IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
;;
;; Please send bug reports and comments to:
;; [email protected] Dmitry Lizorkin
;;
;; The basics of modification language design was inspired by Patrick Lehti
;; and his data manipulation processor for XML Query Language:
;; http://www.ipsi.fraunhofer.de/~lehti/
;; However, with functional techniques we can do this better...
;;-------------------------------------------------------------------------------
;;!! Modification core
;;! Displays an error to stderr and returns #f
(define (sxml:modification-error . text)
(display (string-append "Modification error: " text "\n")
(current-error-port))
#f)
;;! Separates the list into two lists with respect to the predicate
;; Returns: (values res-lst1 res-lst2)
;; res-lst1 - contains all members from the input lst that satisfy the pred?
;; res-lst2 - contains the remaining members of the input lst
(define (sxml:separate-list pred? lst)
(let loop ((lst lst)
(satisfy '())
(rest '()))
(cond
((null? lst)
(values (reverse satisfy) (reverse rest)))
((pred? (car lst)) ; the first member satisfies the predicate
(loop (cdr lst)
(cons (car lst) satisfy) rest))
(else
(loop (cdr lst)
satisfy (cons (car lst) rest))))))
;;-------------------------------------------------------------------------------
;;!! Miscellaneous helpers
;;! Asserts that the given obj is a proper attribute node.
;; If this is the case, returns #t. Otherwise, calls sxml:modification-error
;; with the appropriate error message.
;; Handles singular attributes correctly. In accordance with SXML 3.0, accepts
;; aux lists as attribute nodes
(define (sxml:assert-proper-attribute obj)
(if
(or (and (pair? obj) ; aux node - any content is acceptable
(not (null? obj))
(eq? (car obj) '@))
(and (list? obj) ; '() is not a list
(symbol? (car obj))
(or (null? (cdr obj)) ; singular attribute
(null? (cddr obj)))))
#t
(sxml:modification-error
"improper attribute node - " obj)))
;;! Unites a list of annot-attributes into a single annot-attributes.
;; Ensures that every attribute is a proper one, and that there is no duplicate
;; attributes
;; annot-attributes-lst ::= (listof annot-attributes)
;; In accordance with SXML specification, version 3.0:
;; [3] <annot-attributes> ::= (@ <attribute>* <annotations>? )
;; In case of an error, returns #f.
;; In the correct case, returns: annot-attributes
(define (sxml:unite-annot-attributes-lists . annot-attributes-lst)
(if
(null? annot-attributes-lst) ; nothing to do
'()
(let iter-lst ((src annot-attributes-lst)
(attrs '())
(annotations '()))
(if
(null? src) ; Recursion finished
(if (null? annotations)
(cons '@ (reverse attrs))
`(@ ,@(reverse attrs) (@ ,@annotations)))
(let iter-annot-attrs ((annot-attrs (cdar src))
(attrs attrs)
(annotations annotations))
(if
(null? annot-attrs) ; proceed with the outer loop
(iter-lst (cdr src) attrs annotations)
(let ((curr (car annot-attrs)))
(cond
((and (pair? curr)
(not (null? curr))
(eq? (car curr) '@))
;; an annotation node
(iter-annot-attrs (cdr annot-attrs)
attrs
(append annotations (cdr curr))))
((sxml:assert-proper-attribute curr)
(if
(assq (car curr) attrs) ; duplicate attribute detected
(sxml:modification-error
"duplicate attribute - " (car curr))
(iter-annot-attrs (cdr annot-attrs)
(cons curr attrs)
annotations)))
(else ; improper attribute
#f)))))))))
;;-------------------------------------------------------------------------------
;;!! The core function of document transformation into a new document
;;! Recursive SXML tree transformation
;; curr-node - the node to be transformed
;; targets-alist ::= (listof (cons node-chain update-target))
;; node-chain ::= (listof node)
;; node-chain - the chain of nodes, starting from the `curr-node' and proceeding
;; with its decsednants until the update target
;; Returns the transformed node
(define (sxml:tree-trans curr-node targets-alist)
(call-with-values
(lambda () (sxml:separate-list
(lambda (pair) (null? (car pair)))
targets-alist))
(lambda (matched ; handlers which match this node the rest
targets-alist)
(and-let*
((after-subnodes ; curr-node after its subnodes are processed
(if
(or (not (pair? curr-node)) ; leaf node
(null? targets-alist)) ; no more handlers
curr-node
(let process-attrs ((targets-alist targets-alist)
(src-attrs (sxml:attr-list curr-node))
(res-attrs '()))
(if
(null? src-attrs) ; all attributes processed
;; Go to proceed child elements
(if
(null? targets-alist) ; children don't need to be processed
(cons ; Constructing the result node
(car curr-node) ; node name
((lambda (kids)
(if (null? res-attrs) ; no attributes
kids
(cons (cons '@ (reverse res-attrs))
kids)))
((if (and (not (null? (cdr curr-node)))
(pair? (cadr curr-node))
(eq? (caadr curr-node) '@))
cddr cdr)
curr-node)))
(let process-kids ((targets-alist targets-alist)
(src-kids (cdr curr-node))
(res-kids '()))
(cond
((null? src-kids) ; all kids processed
(call-with-values
(lambda () (sxml:separate-list
(lambda (obj)
(and (pair? obj) (eq? (car obj) '@)))
res-kids))
(lambda (more-attrs kids)
(if
(and (null? res-attrs) (null? more-attrs))
(cons ; Constructing the result node
(car curr-node) ; node name
kids)
(and-let*
((overall-attrs
(apply
sxml:unite-annot-attributes-lists
(cons
(cons '@ (reverse res-attrs))
more-attrs))))
(cons (car curr-node) ; node name
(cons overall-attrs kids)))))))
((and (pair? (car src-kids))
(eq? (caar src-kids) '@))
;; attribute node - already processed
(process-kids
targets-alist (cdr src-kids) res-kids))
(else
(let ((kid-templates
(xlink:filter
(lambda (pair)
(eq? (caar pair) (car src-kids)))
targets-alist)))
(if
(null? kid-templates)
;; this child node remains as is
(process-kids
targets-alist
(cdr src-kids)
(append res-kids (list (car src-kids))))
(and-let*
((new-kid
(sxml:tree-trans
(car src-kids)
(map
(lambda (pair)
(cons (cdar pair) (cdr pair)))
kid-templates))))
(process-kids
(xlink:filter
(lambda (pair)
(not (eq? (caar pair) (car src-kids))))
targets-alist)
(cdr src-kids)
(append
res-kids
(if (nodeset? new-kid)
new-kid
(list new-kid)))))))))))
(let* ((curr-attr (car src-attrs))
(attr-templates
(xlink:filter
(lambda (pair)
(eq? (caar pair) curr-attr))
targets-alist)))
(if
(null? attr-templates)
;; this attribute remains as is
(process-attrs targets-alist
(cdr src-attrs)
(cons curr-attr res-attrs))
(let ((new-attr ; cannot produce error for attrs
(sxml:tree-trans
curr-attr
(map
(lambda (pair)
(cons (cdar pair) (cdr pair)))
attr-templates))))
(process-attrs
(xlink:filter
(lambda (pair)
(not (eq? (caar pair) curr-attr)))
targets-alist)
(cdr src-attrs)
(if (nodeset? new-attr)
(append (reverse new-attr) res-attrs)
(cons new-attr res-attrs)))))))))))
(let process-this ((new-curr-node after-subnodes)
(curr-handlers (map cdr matched)))
(if
(null? curr-handlers)
(if ; all handlers processed
(not (pair? new-curr-node))
new-curr-node ; atomic node
(call-with-values ; otherwise - unite attr lists
(lambda () (sxml:separate-list
(lambda (obj) (and (pair? obj) (eq? (car obj) '@)))
(cdr new-curr-node)))
(lambda (attrs kids)
(if (null? attrs)
new-curr-node ; node remains unchanged
(and-let*
((overall-attrs
(apply sxml:unite-annot-attributes-lists attrs)))
(cons
(car new-curr-node) ; node name
(cons overall-attrs kids)))))))
(process-this
((cadar curr-handlers) ; lambda
new-curr-node
(caar curr-handlers) ; context
;; base-node
(caddar curr-handlers))
(cdr curr-handlers))))))))
;; doc - a source SXML document
;; update-targets ::= (listof update-target)
;; update-target ::= (list context handler base-node)
;; context - context of the node selected by the location path
;; handler ::= (lambda (node context base-node) ...)
;; handler - specifies the required transformation over the node selected
;; base-node - the node with respect to which the location path was evaluated
;;! Returns the new document. In case of a transformation that results to a
;; non-well-formed document, returns #f and the error message is displayed to
;; stderr as a side effect
(define (sxml:transform-document doc update-targets)
(let ((targets-alist
(map-union
(lambda (triple)
(let ((node-path (reverse (sxml:context->content (car triple)))))
(if
(eq? (car node-path) doc)
(list (cons (cdr node-path) triple))
'())))
update-targets)))
(if (null? targets-alist) ; nothing to do
doc
(sxml:tree-trans doc targets-alist))))
;;-------------------------------------------------------------------------------
;;!! Processing update-specifiers
;;! Evaluates lambda-upd-specifiers for the SXML document doc
;; Returns:
;; update-targets ::= (listof update-target)
;; update-target ::= (list context handler base-node)
;; context - context of the node selected by the location path
;; handler ::= (lambda (node context base-node) ...)
;; handler - specifies the required transformation over the node selected
;; base-node - the node with respect to which the location path was evaluated
(define (sxml:lambdas-upd-specifiers->targets doc lambdas-upd-specifiers)
(let ((doc-list (list doc)))
(letrec
((construct-targets
;; base-cntxtset - base context set for the current upd-specifier
;; lambdas-upd-specifiers - is assumed to be non-null?
(lambda (base-cntxtset lambdas-upd-specifiers)
(let ((triple (car lambdas-upd-specifiers)))
;; Iterates members of the base context-set
;; new-base ::= (listof context-set)
;; Each context-set is obtained by applying the txpath-lambda
;; to the each member of base-cntxtset
(let iter-base ((base-cntxtset base-cntxtset)
(res '())
(new-base '()))
(if
(null? base-cntxtset) ; finished scanning base context-set
(if
(null? (cdr lambdas-upd-specifiers)) ; no more members
res
(append
res
(construct-targets
(if
(cadadr lambdas-upd-specifiers) ; following is relative
(apply ddo:unite-multiple-context-sets new-base)
doc-list)
(cdr lambdas-upd-specifiers))))
(let* ((curr-base-context (car base-cntxtset))
(context-set ((car triple)
(list curr-base-context)
(cons 1 1)
'()))) ; dummy var-binding
(iter-base
(cdr base-cntxtset)
(append res
(map
(lambda (context)
(list context
(caddr triple) ; handler
(sxml:context->node curr-base-context)))
context-set))
(cons context-set new-base)))))))))
(if
(null? lambdas-upd-specifiers) ; no transformation rules
'()
(construct-targets doc-list lambdas-upd-specifiers)))))
;;! "Precompiles" each of update-specifiers, by transforming location paths and
;; update actions into lambdas.
;; Returns:
;; lambdas-upd-specifiers ::= (listof lambdas-upd-specifier)
;; lambdas-upd-specifier ::= (list txpath-lambda relative? handler)
;; txpath-lambda ::= (lambda (nodeset position+size var-binding) ...)
;; txpath-lambda - full-argument implementation of a location path
;; relative? - whether the txpath lambda is to be evaluated relatively to the
;; node selected by the previous lambdas-upd-specifier, or with respect to
;; the root of the document. For relative?=#t the base-node is the node
;; selected by the previous lambdas-upd-specifier, otherwise the base node is
;; the root of the document being transformed
;; handler ::= (lambda (node context base-node) ...)
(define (sxml:update-specifiers->lambdas update-specifiers)
(let iter ((src update-specifiers)
(res '()))
(if
(null? src) ; every specifier processed
(reverse res)
(let ((curr (car src)))
(if
(or (not (list? curr))
(null? (cdr curr)))
(sxml:modification-error "improper update-specifier: " curr)
(and-let*
;; Convert Location path to XPath AST
((ast (txp:xpath->ast (car curr))))
(call-with-values
(lambda ()
(if
(eq? (car ast) 'absolute-location-path)
(values
(ddo:ast-relative-location-path
(cons 'relative-location-path (cdr ast))
#f ; keep all ancestors
#t ; on a single level, since a single node
0 ; zero predicate nesting
'(0) ; initial var-mapping
)
#f)
(values
(ddo:ast-relative-location-path ast #f #t 0 '(0))
;; absolute for the first rule
(not (null? res)))))
(lambda (txpath-pair relative?)
(if
(not txpath-pair) ; semantic error
txpath-pair ; propagate the error
(let ((txpath-lambda (car txpath-pair))
(action (cadr curr)))
(if
(procedure? action) ; user-supplied handler
(iter (cdr src)
(cons
(list txpath-lambda relative? action)
res))
(case action
((delete delete-undeep)
(iter (cdr src)
(cons
(list
txpath-lambda
relative?
(cdr
(assq action
`((delete . ,modif:delete)
(delete-undeep . ,modif:delete-undeep)))))
res)))
((insert-into insert-following insert-preceding)
(let ((params (cddr curr)))
(iter (cdr src)
(cons
(list
txpath-lambda
relative?
((cdr
(assq
action
`((insert-into . ,modif:insert-into)
(insert-following . ,modif:insert-following)
(insert-preceding . ,modif:insert-preceding))))
(lambda (context base-node) params)))
res))))
((replace)
(let ((params (cddr curr)))
(iter (cdr src)
(cons
(list txpath-lambda relative?
(lambda (node context base-node) params))
res))))
((rename)
(if
(or (null? (cddr curr)) ; no parameter supplied
(not (symbol? (caddr curr))))
(sxml:modification-error
"improper new name for the node to be renamed: "
curr)
(iter
(cdr src)
(cons
(let ((new-name (caddr curr)))
(list txpath-lambda relative? (modif:rename new-name)))
res))))
((move-into move-following move-preceding)
(if
(or (null? (cddr curr)) ; no lpath supplied
(not (string? (caddr curr))))
(sxml:modification-error
"improper destination location path for move action: "
curr)
(and-let*
((ast (txp:xpath->ast (caddr curr)))
(txpath-pair (ddo:ast-location-path ast #f #t 0 '(0))))
(iter (cdr src)
(cons
(list
(car txpath-pair)
#t
((cdr
(assq
action
`((move-into . ,modif:insert-into)
(move-following . ,modif:insert-following)
(move-preceding . ,modif:insert-preceding))))
(lambda (context base-node) base-node)))
(cons
(list txpath-lambda relative? modif:delete)
res))))))
(else
(sxml:modification-error "unknown action: " curr))))))))))))))
;;-------------------------------------------------------------------------------
;;!! Several popular handlers
;;! Node insertion
;; node-specifier ::= (lambda (context base-node) ...)
;; The lambda specifies the node to be inserted
(define (modif:insert-following node-specifier)
(lambda (node context base-node)
((if (nodeset? node) append cons)
node
(as-nodeset (node-specifier context base-node)))))
(define (modif:insert-preceding node-specifier)
(lambda (node context base-node)
(let ((new (node-specifier context base-node)))
((if (nodeset? new) append cons)
new
(as-nodeset node)))))
(define (modif:insert-into node-specifier)
(lambda (node context base-node)
(let* ((to-insert (as-nodeset (node-specifier context base-node)))
(insert-into-single ; inserts into single node
(lambda (node)
(if (not (pair? node)) ; can't insert into
node
(append node to-insert)))))
(if (nodeset? node)
(map insert-into-single node)
(insert-into-single node)))))
;;! Rename
(define (modif:rename new-name)
(let ((rename-single ; renames a single node
(lambda (node)
(if (pair? node) ; named node
(cons new-name (cdr node))
node))))
(lambda (node context base-node)
(if (nodeset? node)
(map rename-single node)
(rename-single node)))))
;;! Delete
(define modif:delete
(lambda (node context base-node) '()))
(define modif:delete-undeep
(let ((delete-undeep-single
(lambda (node)
(if (pair? node) (cdr node) '()))))
(lambda (node context base-node)
(if (nodeset? node)
(map delete-undeep-single node)
(delete-undeep-single node)))))
;;-------------------------------------------------------------------------------
;;!! Highest-level API function
;; update-specifiers ::= (listof update-specifier)
;; update-specifier ::= (list xpath-location-path action [action-parametes])
;; xpath-location-path - addresses the node(s) to be transformed, in the form of
;; XPath location path. If the location path is absolute, it addresses the
;; node(s) with respect to the root of the document being transformed. If the
;; location path is relative, it addresses the node(s) with respect to the
;; node selected by the previous update-specifier. The location path in the
;; first update-specifier always addresses the node(s) with respect to the
;; root of the document. We'll further refer to the node with respect of which
;; the location path is evaluated as to the base-node for this location path.
;; action - specifies the modification to be made over each of the node(s)
;; addressed by the location path. Possible actions are described below.
;; action-parameters - additional parameters supplied for the action. The number
;; of parameters and their semantics depend on the definite action.
;
;; action ::= 'delete | 'delete-undeep |
;; 'insert-into | 'insert-following | 'insert-preceding |
;; 'replace |
;; 'move-into | 'move-following | 'move-preceding |
;; handler
;; 'delete - deletes the node. Expects no action-parameters
;; 'delete-undeep - deletes the node, but keeps all its content (which thus
;; moves to one level upwards in the document tree). Expects no
;; action-parameters
;; 'insert-into - inserts the new node(s) as the last children of the given
;; node. The new node(s) are specified in SXML as action-parameters
;; 'insert-following, 'insert-preceding - inserts the new node(s) after (before)
;; the given node. Action-parameters are the same as for 'insert-into
;; 'replace - replaces the given node with the new node(s). Action-parameters
;; are the same as for 'insert-into
;; 'rename - renames the given node. The node to be renamed must be a pair (i.e.
;; not a text node). A single action-parameter is expected, which is to be
;; a Scheme symbol to specify the new name of the given node
;; 'move-into - moves the given node to a new location. The single
;; action-parameter is the location path, which addresses the new location
;; with respect to the given node as the base node. The given node becomes
;; the last child of the node selected by the parameter location path.
;; 'move-following, 'move-preceding - the given node is moved to the location
;; respectively after (before) the node selected by the parameter location
;; path
;; handler ::= (lambda (node context base-node) ...)
;; handler - specifies the required transformation. It is an arbitrary lambda
;; that consumes the node and its context (the latter can be used for addressing
;; the other node of the source document relative to the given node). The hander
;; can return one of the following 2 things: a node or a nodeset.
;; 1. If a node is returned, than it replaces the source node in the result
;; document
;; 2. If a nodeset is returned, than the source node is replaced by (multiple)
;; nodes from this nodeset, in the same order in which they appear in the
;; nodeset. In particular, if the empty nodeset is returned by the handler, the
;; source node is removed from the result document and nothing is inserted
;; instead.
;;! Returns either (lambda (doc) ...) or #f
;; The latter signals of an error, an the error message is printed into stderr
;; as a side effect. In the former case, the lambda can be applied to an SXML
;; document and produces the new SXML document being the result of the
;; modification specified.
(define (sxml:modify . update-specifiers)
(and-let*
((lambdas-upd-specifiers
(sxml:update-specifiers->lambdas update-specifiers)))
(lambda (doc)
(sxml:transform-document
doc
(sxml:lambdas-upd-specifiers->targets doc lambdas-upd-specifiers)))))
;;-------------------------------------------------------------------------------
;;!! Destructive modifications
;; Helper cloning facilities
;; These are required to avoid circular structures and such as the result of
;; destructive modifications
;;! Clones the given SXML node
(define (sxml:clone node)
(letrec
((clone-nodeset ; clones nodeset
(lambda (nset)
(if (null? nset)
nset
(cons (sxml:clone (car nset)) (cdr nset))))))
(cond
((pair? node)
(cons (car node) (clone-nodeset (cdr node))))
; Atomic node
((string? node)
(string-copy node))
((number? node)
(string->number (number->string node)))
(else ; unknown node type - do not clone it
node))))
;;! Clones all members of the `nodeset', except for the `node', which is not
;; cloned
(define (sxml:clone-nset-except nodeset node)
(letrec
((iter-nset
;; encountered? - a boolean value: whether `node' already encountered
;; in the head of the nodeset being processed
(lambda (nset encountered?)
(cond
((null? nset) nset)
((eq? (car nset) node)
(cons
(if encountered? ; already encountered before
(sxml:clone (car nset)) ; is to be now cloned
(car nset))
(iter-nset (cdr nset) #t)))
(else
(cons (sxml:clone (car nset))
(iter-nset (cdr nset) encountered?)))))))
(iter-nset nodeset #f)))
;;-------------------------------------------------------------------------------
;;!! Facilities for mutation
;;! Destructively replaces the next list member for `prev' with the new `lst'
(define (sxml:replace-next-with-lst! prev lst)
(let ((next (cddr prev)))
(if
(null? lst) ; the member is to be just removed
(set-cdr! prev next)
(begin
(set-cdr! prev lst)
(let loop ((lst lst)) ; the lst is non-null
(if
(null? (cdr lst))
(set-cdr! lst next)
(loop (cdr lst))))))))
;;! Destructively updates the SXML document
;; Returns the modified doc
;; mutation-lst ::= (listof (cons context new-value)),
;; new-value - a nodeset: the new value to be set to the node
(define (sxml:mutate-doc! doc mutation-lst)
(letrec
((tree-walk
(lambda (curr-node targets-alist)
(if
(not (pair? curr-node)) ; an atom
#t ; nothing to do
;; Otherwise, the `curr-node' is a pair
(let loop ((lst curr-node)
(targets targets-alist))
(if
(null? targets)
#t ; nothing more to do
(begin
(if ((ntype?? '@) (car lst)) ; attribute node
(tree-walk (car lst) targets-alist)
#t) ; dummy else-branch
(if
(null? (cdr lst)) ; this is the last member
#t ; nothing more to be done
(let ((next (cadr lst)))
(call-with-values
(lambda ()
(sxml:separate-list
(lambda (pair) (eq? (caar pair) next))
targets))
(lambda (matched ; handlers which match `next'
targets ; the rest
)
(if
(null? matched) ; nothing matched the next node
(loop (cdr lst) targets)
(let ((matched
(map
(lambda (pair) (cons (cdar pair) (cdr pair)))
matched)))
(cond
((assv '() matched) ; the `next' is to be mutated
=> (lambda (pair)
(let ((k (length (cdr pair))))
(sxml:replace-next-with-lst! lst (cdr pair))
(loop (list-tail lst k) targets))))
(else
(tree-walk next matched)
(loop (cdr lst) targets))))))))))))))))
(let ((targets-alist
(map-union
(lambda (pair)
(let ((node-path (reverse (sxml:context->content (car pair)))))
(if
(eq? (car node-path) doc)
(list (cons (cdr node-path) (cdr pair)))
'())))
mutation-lst)))
(cond
((null? targets-alist) ; nothing to do
#t)
((assv '() targets-alist) ; assv is specified for empty lists
;; The root of the document itself is to be modified
=> (lambda (pair)
(set! doc (cadr pair))))
(else
(tree-walk doc targets-alist)))
doc)))
;;! Selects the nodes to be mutated (by a subsequent destructive modification)
;; This function is the close analog of `sxml:transform-document'
;;
;; Returns:
;; mutation-lst ::= (listof (cons context new-value)),
;; new-value - a nodeset: the new value to be set to the node;
;; or #f in case of semantic error during tree processing (e.g. not a
;; well-formed document after modification)
;;
;; doc - a source SXML document
;; update-targets ::= (listof update-target)
;; update-target ::= (list context handler base-node)
;; context - context of the node selected by the location path
;; handler ::= (lambda (node context base-node) ...)
;; handler - specifies the required transformation over the node selected
;; base-node - the node with respect to which the location path was evaluated
(define (sxml:nodes-to-mutate doc update-targets)
(letrec
;; targets-alist ::= (listof (cons node-chain update-target))
;; node-chain - the chain of nodes, starting from the current node
;; anc-upd? - whether an ancestor of the current node us updated
((tree-walk
(lambda (curr-node targets-alist)
(call-with-values
(lambda () (sxml:separate-list
(lambda (pair) (null? (car pair)))
targets-alist))
(lambda (matched ; handlers which match this node
targets) ; the rest
(if
;; No updates both on this level and on ancestor's level
(null? matched)
(let loop ((targets targets-alist)
(subnodes (append (sxml:attr-list curr-node)
((sxml:child sxml:node?) curr-node)))
(res '()))
(if
(or (null? targets) (null? subnodes))
res
(call-with-values
(lambda ()
(sxml:separate-list
(lambda (pair) (eq? (caar pair) (car subnodes)))
targets))
(lambda (matched targets)
(loop targets
(cdr subnodes)
(if
(null? matched)
res
(append res
(tree-walk
(car subnodes)
(map
(lambda (pair) (cons (cdar pair) (cdr pair)))
matched)))))))))
(list
(cons (cadar matched) ; context
(sxml:clone-nset-except
(as-nodeset
(sxml:tree-trans curr-node targets-alist))
curr-node)))))))))
(let ((targets-alist
(map-union
(lambda (triple)
(let ((node-path (reverse (sxml:context->content (car triple)))))
(if
(eq? (car node-path) doc)
(list (cons (cdr node-path) triple))
'())))
update-targets)))
(if (null? targets-alist) ; nothing to do
'()
(tree-walk doc targets-alist)))))
;;! A highest-level function
(define (sxml:modify! . update-specifiers)
(and-let*
((lambdas-upd-specifiers
(sxml:update-specifiers->lambdas update-specifiers)))
(lambda (doc)
(sxml:mutate-doc!
doc
(sxml:nodes-to-mutate
doc
(sxml:lambdas-upd-specifiers->targets doc lambdas-upd-specifiers))))))
| false |
eff1b6cfff8de5b58e165565ddd8e7afa32f5c33
|
81d1b95e884f89ec9cbda45b70c500e7acb2b55e
|
/euler/10.scm
|
8930c3982679406cc0478fe9db5bf15fe369f9e5
|
[] |
no_license
|
eraserhd/ehk
|
3ec065adc5a06f4948c8ea2ad539eec5cffd0055
|
bde0c07d33f6d5498d61361a838dbe1848a6300e
|
refs/heads/master
| 2022-12-21T21:50:03.325068 | 2022-12-13T14:53:48 | 2022-12-13T14:53:48 | 24,571,764 | 9 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 355 |
scm
|
10.scm
|
(define sieve (make-vector 2000000 #t))
(let loop ((sum 2)
(p 3))
(cond
((>= p 2000000)
(display sum)
(newline))
((vector-ref sieve p)
(let s-loop ((n (+ p p)))
(if (>= n 2000000)
#f
(begin
(vector-set! sieve n #f)
(s-loop (+ n p)))))
(loop (+ sum p) (+ p 2)))
(else
(loop sum (+ p 2)))))
| false |
d0bc848c1f4b341b6541556b92592cd1b07cd2dc
|
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
|
/ext/crypto/sagittarius/crypto/signatures.scm
|
7435815b0c1ab3e2f9b16ce1d88b3f611752f0ed
|
[
"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 | 11,263 |
scm
|
signatures.scm
|
;;; -*- mode:scheme; coding:utf-8; -*-
;;;
;;; sagittarius/crypto/signatures.scm - Signature signer / verifier
;;;
;;; 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 signatures)
(export signer? <signer> make-signer
signer-sign-message signer-init! signer-process! signer-sign!
verifier? <verifier> make-verifier
verifier-verify-signature verifier-init! verifier-process!
verifier-verify!
*signature:rsa*
*signature:dsa*
*signature:ecdsa*
*signature:eddsa*
*signature:ed25519*
*signature:ed25519ctx*
*signature:ed25519ph*
*signature:ed448*
*signature:ed448ph*
;; make-signer-state signer-state->signature
;; make-verifier-state verifier-state-verify-message
mgf-1 *oid:mgf1*
pkcs1-emsa-pss-encode pkcs1-emsa-pss-verify
pkcs1-emsa-v1.5-encode pkcs1-emsa-v1.5-verify
make-random-k-generator make-hmac-k-generator
oid->mgf
oid->signer-maker
oid->verifier-maker
*signature-algorithm:rsa-pkcs-v1.5-sha1*
*signature-algorithm:rsa-pkcs-v1.5-sha256*
*signature-algorithm:rsa-pkcs-v1.5-sha384*
*signature-algorithm:rsa-pkcs-v1.5-sha512*
*signature-algorithm:rsa-pkcs-v1.5-sha224*
*signature-algorithm:rsa-pkcs-v1.5-sha512/224*
*signature-algorithm:rsa-pkcs-v1.5-sha512/256*
*signature-algorithm:rsa-pkcs-v1.5-sha3-224*
*signature-algorithm:rsa-pkcs-v1.5-sha3-256*
*signature-algorithm:rsa-pkcs-v1.5-sha3-384*
*signature-algorithm:rsa-pkcs-v1.5-sha3-512*
*signature-algorithm:rsa-ssa-pss*
*signature-algorithm:dsa-sha224*
*signature-algorithm:dsa-sha256*
*signature-algorithm:dsa-sha384*
*signature-algorithm:dsa-sha512*
*signature-algorithm:ecdsa-sha1*
*signature-algorithm:ecdsa-sha224*
*signature-algorithm:ecdsa-sha256*
*signature-algorithm:ecdsa-sha384*
*signature-algorithm:ecdsa-sha512*
*signature-algorithm:ecdsa-sha3-224*
*signature-algorithm:ecdsa-sha3-256*
*signature-algorithm:ecdsa-sha3-384*
*signature-algorithm:ecdsa-sha3-512*
*signature-algorithm:ed25519*
*signature-algorithm:ed448*
)
(import (rnrs)
(clos user)
(sagittarius crypto signatures types)
(sagittarius crypto signatures k-generators)
(sagittarius crypto signatures rsa)
(sagittarius crypto signatures dsa)
(sagittarius crypto signatures ecdsa)
(sagittarius crypto signatures eddsa)
(sagittarius crypto keys)
(sagittarius crypto digests)
(sagittarius mop immutable))
(define-class <signature> (<immutable>)
((state :init-keyword :state :reader signature-state)
(processor :init-keyword :processor :reader signature-processor)))
(define-class <signer> (<signature>) ())
(define (signer? o) (is-a? o <signer>))
(define (make-signer scheme key . opts)
(let ((state (apply make-signer-state scheme key opts)))
(make <signer> :state state
:processor (signature-state-processor state))))
(define (signer-sign-message signer message)
(signer-sign! (signer-process! (signer-init! signer) message)))
(define (signer-init! (signer signer?))
(signature-state-init! (signature-state signer))
signer)
(define (signer-process! (signer signer?) (msg bytevector?)
:optional (start 0)
(len (- (bytevector-length msg) start)))
((signature-processor signer) (signature-state signer) msg start len)
signer)
(define (signer-sign! (signer signer?))
(signer-state->signature (signature-state signer)))
(define-class <verifier> (<signature>) ())
(define (verifier? o) (is-a? o <verifier>))
(define (make-verifier scheme key . opts)
(let ((state (apply make-verifier-state scheme key opts)))
(make <verifier> :state state
:processor (signature-state-processor state))))
(define (verifier-verify-signature verifier message signature)
(verifier-verify! (verifier-process! (verifier-init! verifier) message)
signature))
(define (verifier-init! (verifier verifier?))
(signature-state-init! (signature-state verifier))
verifier)
(define (verifier-process! (verifier verifier?) (msg bytevector?)
:key (start 0)
(len (- (bytevector-length msg) start)))
((signature-processor verifier) (signature-state verifier) msg start len)
verifier)
(define (verifier-verify! (verifier verifier?) (signature bytevector?))
(verifier-state-verify-message (signature-state verifier) signature))
;;; OID thing...
(define *oid:mgf1* "1.2.840.113549.1.1.8")
(define-generic oid->mgf)
(define-method oid->mgf ((oid (equal *oid:mgf1*))) mgf-1)
(define-generic oid->signer-maker)
(define-generic oid->verifier-maker)
(define-syntax define-oid->signer&verifier
(syntax-rules ()
((_ name oid scheme opts ...)
(begin
(define name oid)
;; not sure if we want to have this though...
(define-method oid->key-operation ((m (equal oid))) scheme)
(define-method oid->signer-maker ((m (equal oid)))
(lambda (key . rest)
(apply make-signer scheme key opts ... rest)))
(define-method oid->verifier-maker ((m (equal oid)))
(lambda (key . rest)
(apply make-verifier scheme key opts ... rest)))))))
(define-oid->signer&verifier *signature-algorithm:rsa-pkcs-v1.5-sha1*
"1.2.840.113549.1.1.5" *signature:rsa*
:digest *digest:sha-1*
:encoder pkcs1-emsa-v1.5-encode :verifier pkcs1-emsa-v1.5-verify)
(define-oid->signer&verifier *signature-algorithm:rsa-pkcs-v1.5-sha256*
"1.2.840.113549.1.1.11" *signature:rsa*
:digest *digest:sha-256*
:encoder pkcs1-emsa-v1.5-encode :verifier pkcs1-emsa-v1.5-verify)
(define-oid->signer&verifier *signature-algorithm:rsa-pkcs-v1.5-sha384*
"1.2.840.113549.1.1.12" *signature:rsa*
:digest *digest:sha-384*
:encoder pkcs1-emsa-v1.5-encode :verifier pkcs1-emsa-v1.5-verify)
(define-oid->signer&verifier *signature-algorithm:rsa-pkcs-v1.5-sha512*
"1.2.840.113549.1.1.13" *signature:rsa*
:digest *digest:sha-512*
:encoder pkcs1-emsa-v1.5-encode :verifier pkcs1-emsa-v1.5-verify)
(define-oid->signer&verifier *signature-algorithm:rsa-pkcs-v1.5-sha224*
"1.2.840.113549.1.1.14" *signature:rsa*
:digest *digest:sha-224*
:encoder pkcs1-emsa-v1.5-encode :verifier pkcs1-emsa-v1.5-verify)
(define-oid->signer&verifier *signature-algorithm:rsa-pkcs-v1.5-sha512/224*
"1.2.840.113549.1.1.15" *signature:rsa*
:digest *digest:sha-512/224*
:encoder pkcs1-emsa-v1.5-encode :verifier pkcs1-emsa-v1.5-verify)
(define-oid->signer&verifier *signature-algorithm:rsa-pkcs-v1.5-sha512/256*
"1.2.840.113549.1.1.16" *signature:rsa*
:digest *digest:sha-512/256*
:encoder pkcs1-emsa-v1.5-encode :verifier pkcs1-emsa-v1.5-verify)
(define-oid->signer&verifier *signature-algorithm:rsa-pkcs-v1.5-sha3-224*
"2.16.840.1.101.3.4.3.13" *signature:rsa*
:digest *digest:sha3-224*
:encoder pkcs1-emsa-v1.5-encode :verifier pkcs1-emsa-v1.5-verify)
(define-oid->signer&verifier *signature-algorithm:rsa-pkcs-v1.5-sha3-256*
"2.16.840.1.101.3.4.3.14" *signature:rsa*
:digest *digest:sha3-256*
:encoder pkcs1-emsa-v1.5-encode :verifier pkcs1-emsa-v1.5-verify)
(define-oid->signer&verifier *signature-algorithm:rsa-pkcs-v1.5-sha3-384*
"2.16.840.1.101.3.4.3.15" *signature:rsa*
:digest *digest:sha3-384*
:encoder pkcs1-emsa-v1.5-encode :verifier pkcs1-emsa-v1.5-verify)
(define-oid->signer&verifier *signature-algorithm:rsa-pkcs-v1.5-sha3-512*
"2.16.840.1.101.3.4.3.16" *signature:rsa*
:digest *digest:sha3-512*
:encoder pkcs1-emsa-v1.5-encode :verifier pkcs1-emsa-v1.5-verify)
;; RSA SSA-PSS
(define-oid->signer&verifier *signature-algorithm:rsa-ssa-pss*
"1.2.840.113549.1.1.10" *signature:rsa*
:encoder pkcs1-emsa-pss-encode :verifier pkcs1-emsa-pss-verify)
(define-oid->signer&verifier *signature-algorithm:dsa-sha224*
"2.16.840.1.101.3.4.3.1" *signature:dsa*
:digest *digest:sha-224*)
(define-oid->signer&verifier *signature-algorithm:dsa-sha256*
"2.16.840.1.101.3.4.3.2" *signature:dsa*
:digest *digest:sha-256*)
(define-oid->signer&verifier *signature-algorithm:dsa-sha384*
"2.16.840.1.101.3.4.3.3" *signature:dsa*
:digest *digest:sha-384*)
(define-oid->signer&verifier *signature-algorithm:dsa-sha512*
"2.16.840.1.101.3.4.3.4" *signature:dsa*
:digest *digest:sha-512*)
(define-oid->signer&verifier *signature-algorithm:ecdsa-sha1*
"1.2.840.10045.4.1" *signature:ecdsa*
:digest *digest:sha-1*)
(define-oid->signer&verifier *signature-algorithm:ecdsa-sha224*
"1.2.840.10045.4.3.1" *signature:ecdsa*
:digest *digest:sha-224*)
(define-oid->signer&verifier *signature-algorithm:ecdsa-sha256*
"1.2.840.10045.4.3.2" *signature:ecdsa*
:digest *digest:sha-256*)
(define-oid->signer&verifier *signature-algorithm:ecdsa-sha384*
"1.2.840.10045.4.3.3" *signature:ecdsa*
:digest *digest:sha-384*)
(define-oid->signer&verifier *signature-algorithm:ecdsa-sha512*
"1.2.840.10045.4.3.4" *signature:ecdsa*
:digest *digest:sha-512*)
;; these seems draft OID
(define-oid->signer&verifier *signature-algorithm:ecdsa-sha3-224*
"2.16.840.1.101.3.4.3.9" *signature:ecdsa*
:digest *digest:sha3-224*)
(define-oid->signer&verifier *signature-algorithm:ecdsa-sha3-256*
"2.16.840.1.101.3.4.3.10" *signature:ecdsa*
:digest *digest:sha3-256*)
(define-oid->signer&verifier *signature-algorithm:ecdsa-sha3-384*
"2.16.840.1.101.3.4.3.11" *signature:ecdsa*
:digest *digest:sha3-384*)
(define-oid->signer&verifier *signature-algorithm:ecdsa-sha3-512*
"2.16.840.1.101.3.4.3.12" *signature:ecdsa*
:digest *digest:sha3-512*)
(define-oid->signer&verifier *signature-algorithm:ed25519*
"1.3.101.112" *signature:ed25519*)
(define-oid->signer&verifier *signature-algorithm:ed448*
"1.3.101.113" *signature:ed448*)
;; Seems not defined?
;; (define-oid->signer&verifier "1.3.101.114" *signature:ed25519ph*)
;; (define-oid->signer&verifier "1.3.101.115" *signature:ed448ph*)
)
| true |
331e22d46826b1d4185ad9261f5fba7f7a27f9da
|
4b480cab3426c89e3e49554d05d1b36aad8aeef4
|
/chapter-02/ex2.46-falsetru-test.scm
|
f06b6ccfa75014df2b7bd339362c359a9a5715c7
|
[] |
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 | 577 |
scm
|
ex2.46-falsetru-test.scm
|
(require (planet schematics/schemeunit:3))
(require (planet schematics/schemeunit:3/text-ui))
(load "ex2.46-falsetru.scm")
(define v1 (make-vector1 1 2))
(define v2 (make-vector1 2 3))
(define ex2.46-falsetru-tests
(test-suite
"Test for ex2.46-falsetru"
(check-equal? (xcor-vect v1) 1)
(check-equal? (ycor-vect v1) 2)
(check-equal? (add-vect v1 v2) (make-vector1 3 5))
(check-equal? (sub-vect v2 v1) (make-vector1 1 1))
(check-equal? (scale-vect 2 v1) (make-vector1 2 4))
))
(exit
(cond
((= (run-tests ex2.46-falsetru-tests) 0))
(else 1)))
| false |
a7d1e82a073746ccf2e39dffb3ea46fc01c48b4f
|
ac2a3544b88444eabf12b68a9bce08941cd62581
|
/examples/tcltk/fig16-11.scm
|
94109b95801d905607ea0f4d579f12a293a5546f
|
[
"Apache-2.0",
"LGPL-2.1-only"
] |
permissive
|
tomelam/gambit
|
2fd664cf6ea68859d4549fdda62d31a25b2d6c6f
|
d60fdeb136b2ed89b75da5bfa8011aa334b29020
|
refs/heads/master
| 2020-11-27T06:39:26.718179 | 2019-12-15T16:56:31 | 2019-12-15T16:56:31 | 229,341,552 | 1 | 0 |
Apache-2.0
| 2019-12-20T21:52:26 | 2019-12-20T21:52:26 | null |
UTF-8
|
Scheme
| false | false | 1,205 |
scm
|
fig16-11.scm
|
#!/usr/bin/env gsi-script
; File: "fig16-11.scm"
; Copyright (c) 1997-2007 by Marc Feeley, All Rights Reserved.
; Translation into Scheme of Figure 16.11 from Chapter 16 of John
; Ousterhout's "Tcl and the Tk Toolkit".
(include "tcltk#.scm") ; import Tcl/Tk procedures and variables
(load "tcltk")
(listbox ".words"
relief: 'raised
borderwidth: 2
yscrollcommand: ".scroll set")
(scrollbar ".scroll" command: ".words yview")
(pack ".words" side: 'left)
(pack ".scroll" side: 'right fill: 'y)
(for-each (lambda (word)
(tcl ".words" 'insert 'end word))
'("apple" "boat" "cherry" "donkey" "eagle" "feather" "gorilla"
"house" "indian" "jelly" "kayak" "letter" "man" "nun"
"ox" "puppy" "queen" "rabbit"))
; ==> Equivalent program in pure Tcl/Tk:
;
; listbox .words -relief raised -borderwidth 2 -yscrollcommand ".scroll set"
;
; scrollbar .scroll -command ".words yview"
;
; pack .words -side left
; pack .scroll -side right -fill y
;
; foreach word {apple boat cherry donkey eagle feather gorilla
; house indian jelly kayak letter man nun
; ox puppy queen rabbit} {
; .words insert end $word
; }
| false |
bec5ce4253319f0d8434ed2eeebee1e5ec18bfe5
|
2bcf33718a53f5a938fd82bd0d484a423ff308d3
|
/programming/sicp/ch2/ex-2.74.scm
|
f876b55941f7c0fdc528343c9f5acb499eb459b9
|
[] |
no_license
|
prurph/teach-yourself-cs
|
50e598a0c781d79ff294434db0430f7f2c12ff53
|
4ce98ebab5a905ea1808b8785949ecb52eee0736
|
refs/heads/main
| 2023-08-30T06:28:22.247659 | 2021-10-17T18:27:26 | 2021-10-17T18:27:26 | 345,412,092 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,196 |
scm
|
ex-2.74.scm
|
#lang scheme
;; https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-17.html#%_thm_2.74
;; 2.74(a)
(define get '())
(define put '())
;; Construct a standardized file from the division name and its original file.
(define (make-file division original-file)
(cons division original-file))
(define (file-division file)
(car file))
(define (file-content file)
(cdr file))
;; The main get-record method will look up separate get-record methods based on
;; the division, and apply it to the employee name and the file content. It will
;; return a record of the division and the record, or (division #f) if the
;; record doesn't exist.
(define (get-record employee file)
(make-record (file-division file)
((get 'get-record (file-division file)) employee
(file-content file))))
(define (make-record division original-record)
(cons division original-record))
(define (record-division record)
(car record))
(define (record-content record)
(cdr record))
;; 2.74(b)
;; Each division's module should provide a get-salary method that takes a given
;; record and returns its salary.
(define (get-salary record)
((get 'get-salary (record-division record)) (record-content record)))
;; Here is a sample division package:
(define (install-engineering-division-package)
(define (get-record employee file-content) '())
(define (get-salary employee-record) '())
(put 'get-record '(engineering) get-record)
(put 'get-salary '(engineering) get-salary))
;; 2.74(c)
(define (find-employee-record employee files)
(if (null? files)
(error "employee not found:" employee)
(let ((record (get-record employee (car files))))
(if (record)
record
(find-employee-record employee (cdr files))))))
;; 2.74(d)
;; A new package must be defined and installed, with a globally unique division
;; identifier:
(define (install-newco-package)
(define (get-record employee file-content) '())
(define (get-salary employee-record) '())
(put 'get-record '(newco) get-record)
(put 'get-salary '(newco) get-salary))
;; and the standardized file must be constructed
(make-file '(newco) original-newco-file)
| false |
1ba6e1df69a7de351efb18257d8b8264f1557fd1
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/System.Xml/mono/xml/xpath/location-path-pattern.sls
|
3ad45fc486d033c3c20b6274be11c9515415b170
|
[] |
no_license
|
futsuki/ironscheme-port
|
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
|
4e7a81b0fbeac9a47440464988e53fb118286c54
|
refs/heads/master
| 2016-09-06T17:13:11.462593 | 2015-09-26T18:20:40 | 2015-09-26T18:20:40 | 42,757,369 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,349 |
sls
|
location-path-pattern.sls
|
(library (mono xml xpath location-path-pattern)
(export new
is?
location-path-pattern?
to-string
matches?
default-priority
evaluated-node-type
last-path-pattern)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new Mono.Xml.XPath.LocationPathPattern a ...)))))
(define (is? a) (clr-is Mono.Xml.XPath.LocationPathPattern a))
(define (location-path-pattern? a)
(clr-is Mono.Xml.XPath.LocationPathPattern a))
(define-method-port
to-string
Mono.Xml.XPath.LocationPathPattern
ToString
(System.String))
(define-method-port
matches?
Mono.Xml.XPath.LocationPathPattern
Matches
(System.Boolean
System.Xml.XPath.XPathNavigator
System.Xml.Xsl.XsltContext))
(define-field-port
default-priority
#f
#f
(property:)
Mono.Xml.XPath.LocationPathPattern
DefaultPriority
System.Double)
(define-field-port
evaluated-node-type
#f
#f
(property:)
Mono.Xml.XPath.LocationPathPattern
EvaluatedNodeType
System.Xml.XPath.XPathNodeType)
(define-field-port
last-path-pattern
#f
#f
(property:)
Mono.Xml.XPath.LocationPathPattern
LastPathPattern
Mono.Xml.XPath.LocationPathPattern))
| true |
2bc5e6e199507bdac887b368e84517042bb8e6ee
|
7666204be35fcbc664e29fd0742a18841a7b601d
|
/code/1-37.scm
|
7271bab3a54db0e0cb822be913c994c1ea6b1308
|
[] |
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 | 849 |
scm
|
1-37.scm
|
#lang racket
;; 1-37
(define (cont-frac-sign N D k sign)
(define (iter ans i)
(if (= i 0)
ans
(iter (/ (N i) (sign (D i) ans)) (- i 1))))
(iter 0 k))
(define (cont-frac N D k) (cont-frac-sign N D k +))
(cont-frac (lambda (i) 1.0) (lambda (i) 1.0) 100)
(define (golden-ratio k)
(+ 1 (cont-frac (lambda (i) 1.0) (lambda (i) 1.0) k)))
(golden-ratio 10)
(golden-ratio 11)
;; 1-38
(define (e k)
(+ 2 (cont-frac
(lambda (i) 1.0)
(lambda (i)
(if (= (remainder i 3) 2)
(* 2 (ceiling (/ i 3)))
1))
k)))
(e 10)
(e 25)
;; 1-39
(define (cont-frac-sub N D k) (cont-frac-sign N D k -))
(define (tan-cf x k)
(cont-frac-sub (lambda (i) (if (= i 1) x (* x x))) (lambda (i) (+ i i -1)) k))
(tan 10.0)
(tan-cf 10.0 30)
| false |
e41093aa2690292e1a0e4d9a434597ddd8456a42
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/mscorlib/system/reflection/mono-event.sls
|
01127f09a5b934920e7abcccbcd14a3d2b766fee
|
[] |
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,443 |
sls
|
mono-event.sls
|
(library (system reflection mono-event)
(export new
is?
mono-event?
get-remove-method
get-object-data
get-other-methods
is-defined?
get-add-method
get-custom-attributes
get-raise-method
to-string
attributes
declaring-type
reflected-type
name)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...) #'(clr-new System.Reflection.MonoEvent a ...)))))
(define (is? a) (clr-is System.Reflection.MonoEvent a))
(define (mono-event? a) (clr-is System.Reflection.MonoEvent a))
(define-method-port
get-remove-method
System.Reflection.MonoEvent
GetRemoveMethod
(System.Reflection.MethodInfo System.Boolean))
(define-method-port
get-object-data
System.Reflection.MonoEvent
GetObjectData
(System.Void
System.Runtime.Serialization.SerializationInfo
System.Runtime.Serialization.StreamingContext))
(define-method-port
get-other-methods
System.Reflection.MonoEvent
GetOtherMethods
(System.Reflection.MethodInfo[] System.Boolean))
(define-method-port
is-defined?
System.Reflection.MonoEvent
IsDefined
(System.Boolean System.Type System.Boolean))
(define-method-port
get-add-method
System.Reflection.MonoEvent
GetAddMethod
(System.Reflection.MethodInfo System.Boolean))
(define-method-port
get-custom-attributes
System.Reflection.MonoEvent
GetCustomAttributes
(System.Object[] System.Type System.Boolean)
(System.Object[] System.Boolean))
(define-method-port
get-raise-method
System.Reflection.MonoEvent
GetRaiseMethod
(System.Reflection.MethodInfo System.Boolean))
(define-method-port
to-string
System.Reflection.MonoEvent
ToString
(System.String))
(define-field-port
attributes
#f
#f
(property:)
System.Reflection.MonoEvent
Attributes
System.Reflection.EventAttributes)
(define-field-port
declaring-type
#f
#f
(property:)
System.Reflection.MonoEvent
DeclaringType
System.Type)
(define-field-port
reflected-type
#f
#f
(property:)
System.Reflection.MonoEvent
ReflectedType
System.Type)
(define-field-port
name
#f
#f
(property:)
System.Reflection.MonoEvent
Name
System.String))
| true |
a238a55cdfd9182ec29693acf8d22416f1863063
|
fb9a1b8f80516373ac709e2328dd50621b18aa1a
|
/ch3/3-5-3_Exploiting_the_Stream_Paradigm.scm
|
c68d900217a0bec9d9d8c562c4affad36b3f9867
|
[] |
no_license
|
da1/sicp
|
a7eacd10d25e5a1a034c57247755d531335ff8c7
|
0c408ace7af48ef3256330c8965a2b23ba948007
|
refs/heads/master
| 2021-01-20T11:57:47.202301 | 2014-02-16T08:57:55 | 2014-02-16T08:57:55 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 6,868 |
scm
|
3-5-3_Exploiting_the_Stream_Paradigm.scm
|
;;3.5.3 ストリームパラダイムの開発
;; 反復をストリームプロセスとして形式化する
(load "./ch3/exercise3-55.scm")
(define (sqrt-improve guess x)
(average guess (/ x guess)))
(define (sqrt-stream x)
(define guesses
(cons-stream 1.0
(stream-map (lambda (guess)
(sqrt-improve guess x))
guesses))))
;; ex1-7 average
(show-stream (sqrt-stream 2) 0 10)
(define (pi-summands n)
(cons-stream (/ 1.0 n)
(stream-map - (pi-summands (+ n 2)))))
(define pi-stream
(scale-stream (partial-sums (pi-summands 1)) 4))
(show-stream pi-stream 0 10)
(define (euler-transform s)
(let ((s0 (stream-ref s 0))
(s1 (stream-ref s 1))
(s2 (stream-ref s 2)))
(cons-stream (- s2 (/ (square (- s2 s1))
(+ s0 (* -2 s1) s2)))
(euler-transform (stream-cdr s)))))
(show-stream (euler-transform pi-stream) 0 10)
(define (make-tableau transform s)
(cons-stream s
(make-tableau transform
(transform s))))
(define (accelerate-sequence transform s)
(stream-map stream-car
(make-tableau transform s)))
(show-stream (accelerate-sequence euler-transform pi-stream) 0 10)
;; 対の無限ストリーム
;(stream-filter (lambda (pair)
; (prime? (+ (car pair) (cadr pair))))
; int-pairs)
; int-pairsがi<=jなる整数のすべての対の並び
(define (stream-append s1 s2)
(if (stream-null? s1)
s2
(cons-stream (stream-car s1)
(stream-append (stream-cdr s1) s2))))
(define (interleave s1 s2)
(if (stream-null? s1)
s2
(cons-stream (stream-car s1)
(interleave s2 (stream-cdr s1)))))
(define (pairs s t)
(cons-stream
(list (stream-car s) (stream-car t))
(interleave
(stream-map (lambda (x) (list (stream-car s) x))
(stream-cdr t))
(pairs (stream-cdr s) (stream-cdr t)))))
;; 信号としてのストリーム
;; 積分機
(define (integral integrand initial-value dt)
(define int
(cons-stream initial-value
(add-streams (scale-stream integrand dt)
int)))
int)
;; 3.5.4 ストリームと遅延評価
;; delayを使ったcons-streamではうまく表現できない例
;(define int
; (cons-stream initial-value
; (add-streams (scale-stream integrand dt)
; int)))
(define (solve f y0 dt)
(define y (integral dy y0 dt))
(define dy (stream-map f y))
y)
;; 遅延引数
(define (integral delayed-integrand initial-value dt)
(define int
(cons-stream initial-value
(let ((integrand (force delayed-integrand)))
(add-streams (scale-stream integrand dt)
int))))
int)
(define (solve f y0 dt)
(define y (integral (delay dy) y0 dt))
(define dy (stream-map f y))
y)
;; 昔のgoshのバージョン(0.8)ではfとyを逆にしないと動かなかった
(stream-ref (solve (lambda (y) y) 1 0.001) 1000)
;; 正規順序の評価
;; 3.5.5 関数的プログラムの部品化度とオブジェクトの部品化度(モジュラリティ)
;; ストリーム処理の観点から、モンテカルロ法によるπの見積り(3.1.2節)
(define random-init 7)
(define rand
(let ((x random-init))
(lambda ()
(set! x (rand-update x))
x)))
(define (rand-update x)
(let ((a 27) (b 26) (m 127))
(modulo (+ (* a x) b) m)))
(define random-numbers
(cons-stream random-init
(stream-map rand-update random-numbers)))
(define (map-successive-pairs f s)
(cons-stream
(f (stream-car s) (stream-car (stream-cdr s)))
(map-successive-pairs f (stream-cdr (stream-cdr s)))))
(define cesaro-stream
(map-successive-pairs (lambda (r1 r2) (= (gcd r1 r2) 1))
random-numbers))
;; cesaro-streamはmonte-carlo手続きに与えられ、それは確率の見積りのストリームを作り出す
;; 次にその結果は、πの見積りのストリームへと変換される。
;; プログラムのこの版は、試行を何回行うかを示すパラメータはもはや必要としない
;; piストリームを先のほうまで眺めると、πのよりよい見積りが得られる
(define (monte-carlo experiment-stream passed failed)
(define (next passed failed)
(cons-stream
(/ passed (+ passed failed))
(monte-carlo
(stream-cdr experiment-stream) passed failed)))
(if (stream-car experiment-stream)
(next (+ passed 1) failed)
(next passed (+ failed 1))))
(define pi
(stream-map (lambda (p) (sqrt (/ 6 p)))
(monte-carlo cesaro-stream 0 0)))
(define (sqrt x)
(define (good-enough? guess)
(< (abs (- (square guess) x)) 0.001))
(define (improve guess)
(average guess (/ x guess)))
(define (sqrt-iter guess)
(if (good-enough? guess)
guess
(sqrt-iter (improve guess))))
(sqrt-iter 1.0))
;; 時の関数型プログラミング的視点
;; 支払い処理機の実装を考え直す
;; 3.1.3節ででてきたもの
(define (mak-esimplified-withdraw balance)
(lambda (amount)
(set! balance (- balance amount))
balance))
(define (stream-withdraw balance amount-stream)
(cons-stream
balance
(stream-withdraw (- balance (stream-car amount-stream))
(stream-cdr amount-stream))))
;;stream-withdrawは出力が入力によって完全に決定される
;;入力amount-streamが、利用者が入力した順次の値のストリームであり、結果としての
;;残高のストリームが表示されているとしよう。
;;値を入力し、結果を眺めている利用者の見え方からは、ストリーム処理は、make-simplified-withdrawで作り出したオブジェクトと同じ振る舞いをする。
;; ところが、ストリームには代入も局所状態も存在しない。したがって、3.1.3節で直面した理論的困難は存在しない。しかもシステムには状態が存在する
;;システムに状態を持たせるのは利用者の時間的存在である
;;本章は、モデル化しようとする実世界の認識に合致するモデルを持つ、計算モデルを構築するという
;;目的を持って始めた。
;;われわれは、バラバラで、時に縛られ相互作用する状態を持つオブジェクトの集まりで世界をモデル化することもできるし、また、単一の時にしばられない状態のない個体で世界をモデル化することもできる
;;どちらの見方も強力な利点があるが、どちらかだけでは完全に満足できない。もっと素晴らしい統合が現れなければならない
| false |
52efb5388cba9746e7af36237467cadff5b1ab3a
|
f0747cba9d52d5e82772fd5a1caefbc074237e77
|
/plat/qemu-system-x86_64.scm
|
61504b87100a27849dd9dd01099dd8ad4df87dcd
|
[] |
no_license
|
philhofer/distill
|
a3b024de260dca13d90e23ecbab4a8781fa47340
|
152cb447cf9eef3cabe18ccf7645eb597414f484
|
refs/heads/master
| 2023-08-27T21:44:28.214377 | 2023-04-20T03:20:55 | 2023-04-20T03:20:55 | 267,761,972 | 3 | 0 | null | 2021-10-13T19:06:55 | 2020-05-29T04:06:55 |
Scheme
|
UTF-8
|
Scheme
| false | false | 1,300 |
scm
|
qemu-system-x86_64.scm
|
(import
scheme
(distill base)
(distill plan)
(distill execline)
(distill fs)
(distill image)
(distill system)
(pkg linux-virt-x86_64)
(svc acpid))
;; qemu-preboot formats the tail end of /dev/vda
;; as the /var partition and then reboots so that
;; the kernel can pick up the new partition
(define qemu-preboot
(interned
"/sbin/preboot" #o700
(lambda ()
(write-exexpr
'(if (test -b /dev/vda2) ; sanity
if -t -n (test -b /dev/vda3)
foreground (echo "re-partitioning /dev/vda...")
if (dosextend -n3 -k /dev/vda)
test -b /dev/vda3)))))
;; qemu-system-x86_64 is a platform for KVM-accelerated
;; linux guests; the presumption here is that we're booting
;; using SeaBIOS and that the root disk is provided via the
;; virtio interface
;;
;; NOTE: the presumption re. the bootable image produced
;; is that it is truncate(1)'d to the desired size before booting
(define qemu-system-x86_64
(make-platform
config: (default-config 'x86_64)
kernel: linux-virt-x86_64
cmdline: '("root=/dev/vda2" "rootfstype=squashfs" "console=ttyS0")
services: (cons (var-mount "/dev/vda3")
(var-log-services (list acpid)))
packages: (list qemu-preboot imgtools)
mkimage: (mbr-image "qemu-x86_64")))
| false |
853d7b4816fd9888c604aedb26f1b47c24aa4435
|
2bcf33718a53f5a938fd82bd0d484a423ff308d3
|
/programming/sicp/ch2/ex-2.45.scm
|
bc3fef90263c6d20fa61f23b5c0aeec35bdceca3
|
[] |
no_license
|
prurph/teach-yourself-cs
|
50e598a0c781d79ff294434db0430f7f2c12ff53
|
4ce98ebab5a905ea1808b8785949ecb52eee0736
|
refs/heads/main
| 2023-08-30T06:28:22.247659 | 2021-10-17T18:27:26 | 2021-10-17T18:27:26 | 345,412,092 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 714 |
scm
|
ex-2.45.scm
|
#lang sicp
;; https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-15.html#%_thm_2.45
(#%require sicp-pict)
;; Implement `split` such that the definitions for `right-split` and `up-split`
;; are valid. At first I just did:
;; (lambda (painter) (major painter (minor painter painter)))
;; but that doesn't handle the count argument.
(define (split major minor)
(define (split-rec painter n)
(if (= 0 n)
painter
(let ((smaller (split-rec painter (- n 1))))
(major painter (minor smaller smaller)))))
split-rec)
(define right-split (split beside below))
(define up-split (split below beside))
(paint (right-split einstein 2))
(paint (up-split einstein 2))
| false |
68f783b05ca0a5c1968c73bc8b54d8c5361c8099
|
7ccc32420e7caead27a5a138a02e9c9e789301d0
|
/rational-expand.sls
|
dfbdcb43654a81dcf986db2a72ee5752e7b987be
|
[
"Apache-2.0"
] |
permissive
|
dharmatech/mpl
|
03d9c884a51c3aadc0f494e0d0cebf851f570684
|
36f3ea90ba5dfa0323de9aaffd5fd0f4c11643d7
|
refs/heads/master
| 2023-02-05T20:21:56.382533 | 2023-01-31T18:10:51 | 2023-01-31T18:10:51 | 280,353 | 63 | 8 |
Apache-2.0
| 2023-01-31T18:10:53 | 2009-08-17T21:02:35 |
Scheme
|
UTF-8
|
Scheme
| false | false | 1,204 |
sls
|
rational-expand.sls
|
#!r6rs
(library (mpl rational-expand)
(export rational-expand)
(import (mpl rnrs-sans)
(mpl arithmetic)
(mpl algebraic-expand)
(mpl numerator)
(mpl denominator)
(mpl rational-gre)
(mpl rationalize-expression))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; (define (rational-expand u)
;; (let ((f (algebraic-expand (numerator u)))
;; (g (algebraic-expand (denominator u))))
;; (if (equal? g 0)
;; #f
;; (let ((h (/ f g)))
;; (if (rational-gre? h)
;; h
;; (rational-expand
;; (rationalize-expression h)))))))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (rational-expand u)
(let ((f (algebraic-expand (numerator u)))
(g (algebraic-expand (denominator u))))
(if (equal? g 0)
#f
(let ((h (rationalize-expression (/ f g))))
(if (equal? h u)
u
(rational-expand h))))))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
| false |
48d56a5c26c4d8e06175f030475c587d8217d4bc
|
a8e69b82efa3125947b3af219d8f14335e52d057
|
/construct-ordering-ml-curried.scm
|
3eddb2a935d5d860c3cf57b7fa993735201bf49f
|
[
"MIT"
] |
permissive
|
ArunGant8/n-grams-for-synthesis
|
ad3f14bb082c1220fcea5cfb69029953a2501508
|
b53b071e53445337d3fe20db0249363aeb9f3e51
|
refs/heads/master
| 2023-04-06T05:51:47.903781 | 2020-05-26T17:09:14 | 2020-05-26T17:09:14 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 631 |
scm
|
construct-ordering-ml-curried.scm
|
(define expert-ordering-alist-ml
`((nil . ,nil-evalo)
(num . ,num-evalo)
(bool . ,bool-evalo)
(var . ,var-evalo)
(lambda . ,lambda-evalo)
(app . ,app-evalo)
(car . ,car-evalo)
(cdr . ,cdr-evalo)
(null? . ,null?-evalo)
(cons . ,cons-evalo)
(pair . ,pair-evalo)
(if . ,if-evalo)
(equal? . ,equal?-evalo)
(symbol? . ,symbol?-evalo)
(not . ,not-evalo)
(letrec . ,letrec-evalo)))
(define expert-ordering-ml
(map cdr (if lookup-optimization?
(remove (assq 'var expert-ordering-alist-ml) expert-ordering-alist-ml)
expert-ordering-alist-ml)))
| false |
44b2e23b2d425fa810e81d8e2cc30bc582259fd2
|
6438e08dfc709754e64a4d8e962c422607e5ed3e
|
/scheme/engine.scm
|
3a2fe3bb852c731539cd241c49fd70717e48b8b1
|
[] |
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 | 3,284 |
scm
|
engine.scm
|
;;; This is where the C code is sourced,
;;; and also where the main procedures get
;;; their declarations.
;;; I belive this is also where the graphical
;;; window is spawned, but I'm not sure
(define-module (engine)
#:use-module (oop goops)
#:use-module (util)
#:use-module (objects)
#:use-module (vector)
#:use-module (scene)
#:export (ready!
draw-rect! set-color! draw-text!
draw-line! draw-ellipse!
render-texture! render-sprite!
texture-size load-image
draw-func tick-func collide-func
set-window-size!
))
(load-extension "./main" "init_functions")
#; (define set-color set-color!)
#; (define draw-rect primitive-draw-rect!)
(define* (draw-rect! fill? top-left size
#:optional (camera (current-camera)))
(let ((local-tl (- top-left (pos camera))))
(primitive-draw-rect! fill?
(x local-tl) (y local-tl)
(x size) (y size))))
(define draw-text primitive-draw-text!)
;;; TODO support for different fonts
(define* (draw-text! str position
#:optional (camera (current-camera)))
(let ((lp (- position (pos camera))))
(primitive-draw-text! str (x lp) (y lp))))
#; (define draw-line primitive-draw-line!)
(define* (draw-line! from to #:optional (camera (current-camera)))
(let ((lfrom (- from (pos camera)))
(lto (- to (pos camera))))
(primitive-draw-line! (x lfrom) (y lfrom)
(x lto) (y lto))))
#; (define draw-ellipse primitive-draw-ellipse!)
(define* (draw-ellipse! radius distance center
#:optional (camera (current-camera)))
"TODO figure out what radius is in this context
distance is distance between center and either focus
center is a v2"
(let ((lc (- center (pos camera))))
(primitive-draw-ellipse! radius (x lc) (y lc) distance)))
#; (define draw-pixel primitive-draw-pixel!)
(define* (draw-pixel! pixel #:optional (camera (current-camera)))
(let ((l (- pixel (pos camera))))
(primitive-draw-pixel! (x l) (y l))))
#; (define render-texture primitive-render-texture!)
(define* (render-texture! image tile-size sheet-pos world-pos
#:optional (camera (current-camera)))
"Procedure for drawing a tile from a spritesheet.
- Image is an image ptr
- tile-size is how large each tile is, taken as a v2.
- sheet-pos is the position (in tiles) of the desired sprite
- board pos is the location in the world to draw the sprite"
(let ((p (- world-pos (pos camera))))
(primitive-render-texture!
image
(x p) (y p)
(x tile-size) (y tile-size)
(x sheet-pos) (y sheet-pos))))
#; (define render-sprite primitive-render-sprite!)
(define* (render-sprite! image position
#:optional (camera (current-camera)))
"Render a single sprite"
(let ((p (- position (pos camera))))
(primitive-render-sprite! image (v2->list p))))
(define-generic tick-func)
(define-method (tick-func (obj <game-object>))
(slot-mod! obj 'counter 1+))
(define-generic draw-func)
(define-method (draw-func (obj <geo-object>)))
(define-generic collide-func)
(define-method (collide-func (obj-a <geo-object>)
(obj-b <geo-object>))
#f)
| false |
0fedd23f859290c726a381a180911d86543c036b
|
29fdc68ecadc6665684dc478fc0b6637c1293ae2
|
/src/wiliki.scm
|
60c2791a61c4a59cff900e29cf4dc6c89882d9e4
|
[
"MIT"
] |
permissive
|
shirok/WiLiKi
|
5f99f74551b2755cb4b8deb4f41a2a770138e9dc
|
f0c3169aabd2d8d410a90033d44acae548c65cae
|
refs/heads/master
| 2023-05-11T06:20:48.006068 | 2023-05-05T18:29:48 | 2023-05-05T18:30:12 | 9,766,292 | 20 | 6 |
MIT
| 2018-10-07T19:15:09 | 2013-04-30T07:40:21 |
Scheme
|
UTF-8
|
Scheme
| false | false | 19,011 |
scm
|
wiliki.scm
|
;;;
;;; WiLiKi - Wiki in Scheme
;;;
;;; Copyright (c) 2000-2009 Shiro Kawai <[email protected]>
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without restriction,
;;; including without limitation the rights to use, copy, modify,
;;; merge, publish, distribute, sublicense, and/or sell copies of
;;; the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
;;; OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
;;; AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
;;; OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;;; IN THE SOFTWARE.
;;;
(define-module wiliki
(use dbm)
(use gauche.charconv)
(use gauche.sequence)
(use gauche.version)
(use rfc.uri)
(use scheme.list)
(use srfi.13)
(use text.gettext)
(use text.html-lite)
(use text.tr)
(use text.tree)
(use util.match)
(use wiliki.db)
(use wiliki.format)
(use wiliki.macro)
(use wiliki.page)
(use www.cgi)
(extend wiliki.core)
(export <wiliki> wiliki-main
<wiliki-formatter>
wiliki:language-link wiliki:make-navi-button
wiliki:top-link wiliki:edit-link wiliki:history-link
wiliki:all-link wiliki:recent-link wiliki:search-box
wiliki:menu-links wiliki:page-title wiliki:breadcrumb-links
wiliki:wikiname-anchor wiliki:wikiname-anchor-string
wiliki:get-formatted-page-content
wiliki:recent-changes-alist
wiliki:page-lines-fold
wiliki:lang
wiliki:version
wiliki:self-url
)
)
(select-module wiliki)
;; Load extra code only when needed.
(autoload wiliki.rss rss-page)
(autoload wiliki.pasttime how-long-since)
(autoload wiliki.log wiliki-log-create wiliki-log-pick
wiliki-log-pick-from-file
wiliki-log-parse-entry wiliki-log-entries-after
wiliki-log-diff wiliki-log-diff*
wiliki-log-revert wiliki-log-revert*
wiliki-log-recover-content
wiliki-log-merge)
;; Less frequently used commands are separated to subfiles.
(autoload "wiliki/history" cmd-history cmd-diff cmd-viewold)
(autoload wiliki.edit cmd-edit cmd-preview cmd-commit-edit)
(autoload "wiliki/version" wiliki:version)
;; Some constants
(define *lwp-version* "1.0") ;''lightweight protocol'' version
(define $$ gettext)
;; compatibility stuff
;; wiliki accessors. They're now obsolete; using ref is recommended.
(define (db-path-of w) (~ w'db-path))
(define (db-type-of w) (~ w'db-type))
(define (title-of w) (if w (~ w'title) ""))
(define (top-page-of w) (~ w'top-page))
(define (language-of w) (if w (~ w'language) 'en))
(define (charsets-of w) (~ w'charsets))
(define (editable? w) (~ w'editable?))
(define (style-sheet-of w) (~ w'style-sheet))
(define (image-urls-of w) (~ w'image-urls))
(define (description-of w) (~ w'description))
(define (protocol-of w) (~ w'protocol))
(define (server-name-of w) (~ w'server-name))
(define (server-port-of w) (~ w'server-port))
(define (script-name-of w) (~ w'script-name))
(define (debug-level w) (if w (~ w'debug-level) 0))
(define (gettext-paths w) (~ w'gettext-paths))
(define (textarea-rows-of w) (~ w'textarea-rows)) ;; obsoleted
(define (textarea-cols-of w) (~ w'textarea-cols)) ;; obsoleted
(define redirect-page wiliki:redirect-page)
(define log-file-path wiliki:log-file-path)
;; NB: compatibility kludge - this may return wrong answer
;; if W is not the current wiliki, but I bet switching two
;; wiliki instances are pretty rare.
(define (cgi-name-of w) (and w (wiliki:url)))
(define (full-script-path-of w) (and w (wiliki:url :full)))
(define (url fmt . args) (apply wiliki:url fmt args))
(define (url-full fmt . args) (apply wiliki:url :full fmt args))
(define wiliki:self-url url)
;;;==================================================================
;;; Actions
;;;
;;
;; View page
;;
(define-wiliki-action v :read (pagename)
;; NB: see the comment in format-wikiname about the order of
;; wiliki-db-get and virtual-page? check.
(cond [(wiliki:db-get pagename) => html-page]
[(virtual-page? pagename) (html-page (handle-virtual-page pagename))]
[(equal? pagename (top-page-of (wiliki)))
(let1 toppage (make <wiliki-page>
:title pagename :key pagename :mtime (sys-time))
;; Top page is non-existent, or its name may be changed.
;; create it automatically. We need to ensure db is writable.
(if (editable? (wiliki))
(wiliki:with-db (^[]
(wiliki:db-put! (~ (wiliki)'top-page) toppage)
(html-page toppage))
:rwmode :write)
(errorf "Top-page #f (~a) doesn't exist, and the database \
is read-only" toppage)))]
[(or (string-index pagename #[\[\]])
(#/^\s|\s$/ pagename)
(string-prefix? "$" pagename))
(error "Invalid page name" pagename)]
[else
(html-page
(make <wiliki-page>
:title (string-append ($$ "Nonexistent page: ") pagename)
:content `((p ,($$ "Create a new page: ")
,@(wiliki:format-wikiname pagename)))))]
))
(define-wiliki-action lv :read (pagename)
(let ((page (wiliki:db-get pagename #f)))
`(,(cgi-header
:content-type #"text/plain; charset=~(output-charset)")
,#"title: ~|pagename|\n"
,#"wiliki-lwp-version: ~|*lwp-version*|\n"
,(if page
`(,#"mtime: ~(~ page 'mtime)\n"
"\n"
,(~ page 'content))
`("mtime: 0\n"
"\n")))))
;;
;; All pages, recent changes, RSS
;;
(define-wiliki-action a :read (_)
(html-page
(make <wiliki-page>
:title (string-append (title-of (wiliki))": "($$ "All Pages"))
:command "c=a"
:content `((ul ,@(map (^k `(li ,(wiliki:wikiname-anchor k)))
(sort (wiliki:db-map (^[k v] k)) string<?))))
)))
(define-wiliki-action r :read (_)
(html-page
(make <wiliki-page>
:title (string-append (title-of (wiliki))": "($$ "Recent Changes"))
:command "c=r"
:content
`((table
,@(map (^p `(tr
(td ,(wiliki:format-time (cdr p)))
(td "(" ,(how-long-since (cdr p)) " ago)")
(td ,(wiliki:wikiname-anchor (car p)))))
(wiliki:db-recent-changes))))
)))
(define-wiliki-action rss :read (_
(type :default #f))
(rss-page :item-description (cond
[(member type '("html" "html-partial"
"raw" "raw-partial" "none"))
(string->symbol type)]
[else #f])))
;;
;; Search
;;
(define-wiliki-action s :read (_ (key :convert cv-in))
(if (equal? (cgi-get-metavariable "REQUEST_METHOD") "POST")
(html-page
(make <wiliki-page>
:title (string-append (title-of (wiliki))": "
(format ($$ "Search results of \"~a\"") key))
:command (format #f "c=s&key=~a" (html-escape-string key))
:content
`((ul
,@(map (^p `(li
,(wiliki:wikiname-anchor (car p))
,(or (and-let* ([mtime (get-keyword :mtime (cdr p) #f)])
#"(~(how-long-since mtime))")
"")))
(wiliki:db-search-content key))))
))
(html-page
(make <wiliki-page>
:title (string-append (title-of (wiliki))": search")
:command (format #f "c=s&key=~a" (html-escape-string key))
:content (wiliki:search-box key)))))
;;
;; Edit and commit
;; We redirect GET request to the edit action to the normal view,
;; since it is bothering that search engines pick the link to the edit
;; page. (We allow GET with t parameter, since edit history page
;; contains such links.)
;; The 'n' action is only used from the link of creating a new page.
;; It returns the normal view if the named page already exists.
(define-wiliki-action e :read (pagename
(t :convert x->integer :default #f))
(if (or t
(and-let* ([m (cgi-get-metavariable "REQUEST_METHOD")])
(string-ci=? m "POST")))
(cmd-edit pagename t)
(wiliki:redirect-page pagename)))
(define-wiliki-action n :read (pagename)
(if (wiliki:db-exists? pagename)
(wiliki:redirect-page pagename)
(cmd-edit pagename #f)))
(define-wiliki-action c :write (pagename
(commit :default #f)
(content :convert cv-in)
(mtime :convert x->integer :default 0)
(logmsg :convert cv-in)
(donttouch :default #f))
((if commit cmd-commit-edit cmd-preview)
pagename content mtime logmsg donttouch #f))
;;
;; History
;;
(define-wiliki-action h :read (pagename
(s :convert x->integer :default 0))
(cmd-history pagename s))
(define-wiliki-action hd :read (pagename
(t :convert x->integer :default 0)
(t1 :convert x->integer :default 0))
(cmd-diff pagename t t1))
(define-wiliki-action hv :read (pagename
(t :convert x->integer :default 0))
(cmd-viewold pagename t))
;;================================================================
;; WiLiKi-specific formatting routines
;;
;; Creates a link to switch language
(define (wiliki:language-link page)
(and-let* ([target (or (~ page 'command) (~ page 'key))])
(receive (language label)
(case (wiliki:lang)
[(jp) (values 'en "->English")]
[(vi) (values 'vi "->Vietnamese")]
[else (values 'jp "->Japanese")])
`(a (@ (href ,(string-append (cgi-name-of (wiliki)) "?" target
(lang-spec language '&))))
"[" ,label "]"))))
;; Navigation buttons
(define (wiliki:make-navi-button params content)
`(form (@ (method POST) (action ,(cgi-name-of (wiliki)))
(style "margin:0pt; padding:0pt"))
,@(map (match-lambda
[(n v) `(input (@ (type hidden) (name ,n) (value ,v)))])
params)
(input (@ (type submit) (class "navi-button") (value ,content)))))
(define (wiliki:top-link page)
(and (not (equal? (~ page 'title) (top-page-of (wiliki))))
(wiliki:make-navi-button '() ($$ "Top"))))
(define (wiliki:edit-link page)
(and (eq? (~ (wiliki) 'editable?) #t)
(wiliki:persistent-page? page)
(wiliki:make-navi-button `((p ,(~ page 'key)) (c e)) ($$ "Edit"))))
(define (wiliki:history-link page)
(and (~ (wiliki) 'log-file)
(wiliki:persistent-page? page)
(wiliki:make-navi-button `((p ,(~ page 'key)) (c h)) ($$ "History"))))
(define (wiliki:back-link page)
(and (wiliki:persistent-page? page)
(wiliki:make-navi-button `((key ,#"[[~(~ page'key)]]") (c s))
($$ "Links to here"))))
(define (wiliki:all-link page)
(and (not (equal? (~ page 'command) "c=a"))
(wiliki:make-navi-button '((c a)) ($$ "All"))))
(define (wiliki:recent-link page)
(and (not (equal? (~ page 'command) "c=r"))
(wiliki:make-navi-button '((c r)) ($$ "Recent Changes"))))
(define (wiliki:search-box :optional (key #f))
`((form (@ (method POST) (action ,(cgi-name-of (wiliki)))
(style "margin:0pt; padding:0pt"))
(input (@ (type hidden) (name c) (value s)))
(input (@ (type text) (name key) (size 15)
,@(cond-list
[key `(value ,key)])
(class "search-box")))
(input (@ (type submit) (name search) (value ,($$ "Search"))
(class "navi-button")))
)))
(define (wiliki:breadcrumb-links page delim)
(define (make-link-comp rcomps acc)
(if (null? acc)
(list (car rcomps))
(cons (wiliki:wikiname-anchor (string-join (reverse rcomps) delim)
(car rcomps))
acc)))
(let1 combs (string-split (~ page 'title) delim)
(if (pair? (cdr combs))
`((span (@ (class "breadcrumb-links"))
,@(intersperse
delim
(pair-fold make-link-comp '() (reverse combs)))))
'())))
(define (wiliki:menu-links page)
(define (td x) (list 'td x))
`((table
(@ (border 0) (cellpadding 0))
(tr ,@(cond-list
[(wiliki:top-link page) => td]
[(wiliki:edit-link page) => td]
[(wiliki:history-link page) => td]
[(wiliki:back-link page) => td]
[(wiliki:all-link page) => td]
[(wiliki:recent-link page) => td])
(td ,@(wiliki:search-box))))))
(define (wiliki:page-title page)
`((h1 ,(~ page 'title))))
(define (wiliki:default-page-header page opts)
`(,@(wiliki:page-title page)
(div (@ (align "right")) ,@(wiliki:breadcrumb-links page ":"))
(div (@ (align "right")) ,@(wiliki:menu-links page))
(hr)))
(define (wiliki:default-page-footer page opts)
(if (~ page 'mtime)
`((hr)
(div (@ (align right))
,($$ "Last modified : ")
,(wiliki:format-time (~ page 'mtime))))
'()))
(define (wiliki:default-head-elements page opts)
(let1 w (wiliki)
`((title ,(wiliki:format-head-title (the-formatter) page))
,@(cond-list
[w `(base (@ (href ,(wiliki:url :full))))]
[w `(link (@ (rel "alternate") (type "application/rss+xml")
(title "RSS") (href ,(wiliki:url :full "c=rss"))))]
[w `(meta (@ (property "og:title")
(content ,(wiliki:format-head-title (the-formatter) page))))]
[w `(meta (@ (property "og:url") (content ,(wiliki:url :full))))]
[w `(meta (@ (property "og:type") (content "website")))]
[(and w (~ w'description))
=> (^[desc]
`(meta (@ (property "og:description") (content ,desc))))]
[(and w (~ w'thumbnail))
=> (^[image-url]
`(meta (@ (property "og:image") (content ,image-url))))]
[(and w (~ w'style-sheet))
=> @(^[ss] (map (^s `(link (@ (rel "stylesheet")
(href ,s) (type "text/css"))))
(if (list? ss) ss (list ss))))])
)))
(define (default-format-time time)
(if time
(if (zero? time)
($$ "Epoch")
(sys-strftime "%Y/%m/%d %T %Z" (sys-localtime time)))
"-"))
(define (default-format-wikiname name)
(define (inter-wikiname-prefix head)
(and-let* ([page (wiliki:db-get "InterWikiName")]
[rx (string->regexp #"^:~(regexp-quote head):\\s*")])
(call-with-input-string (~ page 'content)
(^p (let loop ((line (read-line p)))
(cond [(eof-object? line) #f]
[(rx line) =>
(^m (let1 prefix (m 'after)
(if (string-null? prefix)
(let1 prefix (read-line p)
(if (or (eof-object? prefix)
(string-null? prefix))
#f
(string-trim-both prefix)))
(string-trim-both prefix))))]
[else (loop (read-line p))]))))))
(define (reader-macro-wikiname? name)
(cond [(string-prefix? "$$" name) (handle-reader-macro name)]
[(or (string-prefix? "$" name)
(#/^\s/ name)
(#/\s$/ name))
;;invalid wiki name
(list "[[" name "]]")]
[else #f]))
(define (inter-wikiname? name)
(receive (head after) (string-scan name ":" 'both)
(or (and head
(and-let* ([inter-prefix (inter-wikiname-prefix head)])
(values inter-prefix after)))
(values #f name))))
(or (reader-macro-wikiname? name)
(receive (inter-prefix real-name) (inter-wikiname? name)
(cond [inter-prefix
(let1 scheme
(if (#/^(https?|ftp|mailto):/ inter-prefix) "" "http://")
`((a (@ (href ,(format "~a~a~a" scheme inter-prefix
(uri-encode-string
(cv-out real-name)))))
,name)))]
;; NB: the order of checks here is debatable. Should a virtual
;; page shadow an existing page, or an existing page shadow a
;; virtual one? Note also the order of this check must match
;; the order in cmd-view.
[(or (wiliki:db-exists? real-name) (virtual-page? real-name))
(list (wiliki:wikiname-anchor real-name))]
[else
`(,real-name
(a (@ (href ,(url "p=~a&c=n" (cv-out real-name))))
(span (@ (class new-wikiname-suffix)) "?")))]))
)
)
;; Ideally, default-format-wikiname &c should be defined as a method
;; specialized for <wiliki-formatter>. However we need to keep the
;; old protocol for the backward compatibility; existing wiliki app
;; may customize the formatter by setting slots. Newly written scripts
;; should customize by subclassing <wiliki-formatter>, *not* by setting
;; slots.
(define-class <wiliki-formatter> (<wiliki-formatter-base>)
(;; for backward compatibility.
(bracket :init-value default-format-wikiname)
(time :init-value default-format-time)
(header :init-value wiliki:default-page-header)
(footer :init-value wiliki:default-page-footer)
(head-elements :init-value wiliki:default-head-elements)))
(wiliki:formatter (make <wiliki-formatter>)) ;override the default
;; Character conv ---------------------------------
(define cv-in wiliki:cv-in)
(define cv-out wiliki:cv-out)
(define output-charset wiliki:output-charset)
;; CGI processing ---------------------------------
(define html-page wiliki:std-page) ; for backward compatibility
(provide "wiliki")
| false |
97275c41cab240d22fe78c85d44a2d6a2b6046f8
|
1ed47579ca9136f3f2b25bda1610c834ab12a386
|
/sec3/q3.20.scm
|
b750bd4b53d22f1cddec42dc9aee9783d7871b2f
|
[] |
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 | 541 |
scm
|
q3.20.scm
|
;; sec3.3.1.scmの定義を使って以下の式の評価を示す環境の図を書け。
(define x (cons 1 2))
(define z (cons x x))
(set-car! (cdr z) 17)
(car x) ;=> 17
;; 本当はcondとかでも環境はできるんだけど, 細かいところをはしょってる。
;;
;; > ajiyoshi: 端折ってるだけだと思う。3.20のcar/cdr/consの実装ではみんな手続きなので、手続きに引数を作用させる際に環境フレームが構築される。p139最下部の規則にある通り。 |04:04 PM 7 09, 2012|
| false |
ed3b6963aed3e0e6c610c8f567e58918327d689d
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/System/system/net/network-information/ping-exception.sls
|
0c62a46b32de998a0724ced86ad0598dd48f8c0f
|
[] |
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 | 488 |
sls
|
ping-exception.sls
|
(library (system net network-information ping-exception)
(export new is? ping-exception?)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new
System.Net.NetworkInformation.PingException
a
...)))))
(define (is? a)
(clr-is System.Net.NetworkInformation.PingException a))
(define (ping-exception? a)
(clr-is System.Net.NetworkInformation.PingException a)))
| true |
0cbdcaf47050c53c6985add39a6d7877bdc03758
|
a9d1a0e915293c3e6101e598b3f8fc1d8b8647a9
|
/scheme/raytrace/constants.sld
|
169ba2db36c295ce92a4bff3d0be118577ea7a1c
|
[] |
no_license
|
mbillingr/raytracing
|
a3b5b988007536a7065e51ef2fc17e6b5ac44d43
|
9c786e5818080cba488d3795bc6777270c505e5e
|
refs/heads/master
| 2021-04-16T17:10:40.435285 | 2020-11-11T07:02:18 | 2020-11-11T07:02:18 | 249,372,261 | 2 | 4 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 373 |
sld
|
constants.sld
|
(define-library (raytrace constants)
(export EPSILON PI SQRT2 SQRT2/2 SQRT3 SQRT3/3)
(import (scheme base)
(scheme inexact))
(begin
(define EPSILON 0.00001)
(define PI 3.14159265358979323846264338327950288419716939937510582)
(define SQRT2 (sqrt 2))
(define SQRT3 (sqrt 3))
(define SQRT2/2 (/ SQRT2 2))
(define SQRT3/3 (/ SQRT3 3))))
| false |
975b423570a39b5a95540ce63c0fa2613ffaaecd
|
a8216d80b80e4cb429086f0f9ac62f91e09498d3
|
/lib/chibi/app.sld
|
dcc5cdb1551423eee41d67a85c867a2570a262fc
|
[
"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 | 425 |
sld
|
app.sld
|
;;> Unified command-line option parsing and config management.
(define-library (chibi app)
(export parse-option parse-options parse-app run-application
app-help app-help-command)
(import (scheme base)
(scheme read)
(scheme write)
(scheme process-context)
(srfi 1)
(chibi config)
(chibi edit-distance)
(chibi string))
(include "app.scm"))
| false |
0ad961144569bea1f007aaaa77e05f3d9e03689e
|
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
|
/ext/ffi/win32/shell.scm
|
9bb038488e5509beda0eee8f7760aa6e608089f6
|
[
"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 | 3,874 |
scm
|
shell.scm
|
;;; -*- mode: scheme; coding: utf-8; -*-
;;;
;;; shell.scm - Win32 API wrapper library
;;;
;;; Copyright (c) 2021 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 (win32 shell)
(export SHITEMID ITEMIDLIST ITEMIDLIST_ABSOLUTE
PCIDLIST_ABSOLUTE PIDLIST_ABSOLUTE
BFFCALLBACK
BROWSERINFO PBROWSERINFO LPBROWSERINFO
sh-browse-for-folder
sh-get-path-from-id-list
(rename (shell32 *windows-shell32-module*)))
(import (rnrs)
(rename (sagittarius) (define-constant defconst))
(sagittarius ffi)
(win32 defs))
(define shell32 (open-win32-module "shell32.dll"))
(define-syntax define-constant
(syntax-rules ()
((_ name value)
(begin
(export name)
(defconst name value)))))
(define-c-struct SHITEMID
(USHORT cb)
(BYTE array 1 abID))
(define-c-struct ITEMIDLIST
(struct SHITEMID mkid))
(define-c-typedef ITEMIDLIST ITEMIDLIST_ABSOLUTE
(* PCIDLIST_ABSOLUTE)
(* PIDLIST_ABSOLUTE))
(define-c-typedef callback BFFCALLBACK)
(define-c-struct BROWSERINFO
(HWND hwndOwner)
(PCIDLIST_ABSOLUTE pidlRoot)
(LPWSTR pszDisplayName)
(LPCWSTR lpszTitle)
(UINT ulFlags)
(BFFCALLBACK lpfn)
(LPARAM lParam)
(int iImage))
(define-c-typedef BROWSERINFO (* PBROWSERINFO) (* LPBROWSERINFO))
(define-constant BIF_RETURNONLYFSDIRS #x00000001)
(define-constant BIF_DONTGOBELOWDOMAIN #x00000002)
(define-constant BIF_STATUSTEXT #x00000004)
(define-constant BIF_RETURNFSANCESTORS #x00000008)
(define-constant BIF_EDITBOX #x00000010)
(define-constant BIF_VALIDATE #x00000020)
(define-constant BIF_NEWDIALOGSTYLE #x00000040)
(define-constant BIF_USENEWUI
(bitwise-ior BIF_NEWDIALOGSTYLE BIF_EDITBOX))
(define-constant BIF_BROWSEINCLUDEURLS #x00000080)
(define-constant BIF_UAHINT #x00000100)
(define-constant BIF_NONEWFOLDERBUTTON #x00000200)
(define-constant BIF_NOTRANSLATETARGETS #x00000400)
(define-constant BIF_BROWSEFORCOMPUTER #x00001000)
(define-constant BIF_BROWSEFORPRINTER #x00002000)
(define-constant BIF_BROWSEINCLUDEFILES #x00004000)
(define-constant BIF_SHAREABLE #x00008000)
(define-constant BIF_BROWSEFILEJUNCTIONS #x00010000)
(define sh-browse-for-folder
(c-function shell32 PIDLIST_ABSOLUTE SHBrowseForFolderW (LPBROWSERINFO)))
(define sh-get-path-from-id-list
(c-function shell32 BOOL SHGetPathFromIDListW (PCIDLIST_ABSOLUTE LPWSTR)))
)
| true |
b87d74a413e87d601d9912dad41a2de450852bf0
|
7666204be35fcbc664e29fd0742a18841a7b601d
|
/code/4-44.scm
|
dd650b1e1db9fdaa847f299114cc03852ca48183
|
[] |
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 | 851 |
scm
|
4-44.scm
|
(include "4.3.2-common.scm")
(define (safe? solution) ;;copied from queen.scm
(let ((p (car solution)))
(define (conflict? q i)
(or
(= p q)
(= p (+ q i))
(= p (- q i))))
(define (check rest i)
(cond
((null? rest) #t)
((conflict? (car rest) i) #f)
(else (check (cdr rest) (inc i)))))
(check (cdr solution) 1)))
(define (queens n)
(define (iter solution n-left)
(if (= n-left 0)
(begin
(display solution)
(newline))
(begin
(let ((x-solution (cons (an-integer-between 1 n) solution)))
(require (safe? x-solution))
(iter x-solution (- n-left 1))))))
(iter '() n))
(queens 8)
| false |
0efa7da598f021120a0d0c7f12c1865f0954323d
|
5fa722a5991bfeacffb1d13458efe15082c1ee78
|
/src/c3_47b.scm
|
3279ccfb872a52509c0056613f883b48a24b4390
|
[] |
no_license
|
seckcoder/sicp
|
f1d9ccb032a4a12c7c51049d773c808c28851c28
|
ad804cfb828356256221180d15b59bcb2760900a
|
refs/heads/master
| 2023-07-10T06:29:59.310553 | 2013-10-14T08:06:01 | 2013-10-14T08:06:01 | 11,309,733 | 3 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,210 |
scm
|
c3_47b.scm
|
(define (make-semaphore n)
(let ((cell (list #f)))
(define (acquire)
(if (test-and-set! cell)
(acquire)
(begin
(cond ((> n 0)
(set! n (- n 1))
(clear! cell)
#t)
(else
(clear! cell)
(acquire))))))
(define (release)
(if (test-and-set! cell)
(begin
(clear! cell)
(release))
(begin
(set! n (+ n 1))
(clear! cell))))
(define (self msg)
(cond ((eq? msg 'acquire) acquire)
((eq? msg 'release) release)
(else
(error 'semaphore-self "UNKNOWN MESSAGE" msg))))
self))
; a not practical implementation of test-and-set!
(define (test-and-set! cell)
(if (car cell)
#t
(begin (set-car! cell #t)
#f)))
(define (clear! cell)
(set-car! cell #f))
(define (semaphore-acquire sem)
((sem 'acquire)))
(define (semaphore-release sem)
((sem 'release)))
(define (test)
(define sem (make-semaphore 2))
(semaphore-acquire sem)
(semaphore-acquire sem)
(semaphore-release sem)
(semaphore-release sem)
(semaphore-acquire sem)
)
(test)
| false |
1c0a80cc87720c7058fdc3a9e119344a2fc9c652
|
b1b1e288efe8621f2bf2c8bc3eea9e30fc251501
|
/sac/tests/test6.ss
|
cacf900b1126118bf33a334bdbeec85bd959d924
|
[
"ISC"
] |
permissive
|
lojikil/hydra
|
37e32a43afc2443e29a73387fe796b559756a957
|
366cae2e155c6e4d5e27ad19d3183687a40c82a3
|
refs/heads/master
| 2020-05-30T08:41:19.374996 | 2014-11-13T03:10:22 | 2014-11-13T03:10:22 | 58,539,402 | 5 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 224 |
ss
|
test6.ss
|
(define (foo f x)
(display "foo: ")
(display x)
(display "\n")
(f x))
(define (main)
(foo (lambda (z) (* z z)) 10)
(foo (lambda (z) (display "z == ") (display z) (display "\n") (* z z)) 20))
(main)
| false |
1de6d2f8e75e01f88b9701c11fee4e9024d4b298
|
c38f6404e86123560ae8c9b38f7de6b66e30f1c4
|
/fernscode/cartesian-example.ss
|
6298a1b82e045e22c613c6ab6c46b25d58361eb8
|
[
"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 | 93 |
ss
|
cartesian-example.ss
|
(take-bottom 6 (Cartesian-product-bottom (fern bottom 'a 'b) (fern 'x bottom 'y bottom 'z)))
| false |
f898a5b6defe9dfd5d5d40e8bfafb845ce2cfa95
|
e44c651f315b2cca4a6e8b2a6715ac0d8943814d
|
/src/Cyclone-postlude.scm
|
91efb076dc6d6e125e7431fd8dc76f2a7c9cf7e9
|
[] |
no_license
|
ecraven/r7rs-benchmarks
|
75dd4d895fde857077da6e0b6469d2cc0ee9b9f8
|
845345f7e13ac07bb6cd3c6bf745ae9caf9ed7b8
|
refs/heads/master
| 2022-12-10T18:36:21.777848 | 2022-10-17T11:40:09 | 2022-10-17T11:40:09 | 58,028,745 | 271 | 40 | null | 2022-12-05T10:00:54 | 2016-05-04T06:36:49 |
Scheme
|
UTF-8
|
Scheme
| false | false | 86 |
scm
|
Cyclone-postlude.scm
|
(define (this-scheme-implementation-name)
(string-append "cyclone-" (Cyc-version)))
| false |
ac9713e09f5202bce8bf9821390b0692948893db
|
b0ee8ebbe60713adc64d5ccd5a973bffb59bb497
|
/lib/srfi/231/generalized-arrays.scm
|
16fc72886d13cae5e1c939f1e444f276089e978f
|
[
"LGPL-2.1-only",
"LicenseRef-scancode-free-unknown",
"GPL-3.0-or-later",
"LicenseRef-scancode-autoconf-simple-exception",
"Apache-2.0"
] |
permissive
|
SamuelYvon/gambit
|
061f4400eb3ac04de7db29fe538447c09650da33
|
bedea6ad2e0bdc879406b3bbbb50632ad2068275
|
refs/heads/master
| 2023-07-29T05:10:52.202851 | 2023-07-28T19:05:44 | 2023-07-28T19:05:44 | 235,840,132 | 0 | 0 |
Apache-2.0
| 2020-04-30T23:19:59 | 2020-01-23T16:47:33 |
C
|
UTF-8
|
Scheme
| false | false | 268,326 |
scm
|
generalized-arrays.scm
|
#|
SRFI 231: Intervals and Generalized Arrays
Copyright 2016, 2018, 2020, 2021, 2022 Bradley J Lucier.
All Rights Reserved.
Permission is hereby granted, free of charge,
to any person obtaining a copy of this software
and associated documentation files (the "Software"),
to deal in the Software without restriction,
including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice
(including the next paragraph) shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
|#
;;; declarations to reduce the size of the .o file in Gambit
(declare (standard-bindings)
(extended-bindings)
(inlining-limit 600)
(block)
(mostly-fixnum)
(not safe))
;;; VOID: Since the results returned by <whatever>vector-set! is not defined,
;;; and Gambit returns the vector itself when code is compiled with
;;; (declare (standard-bindings) (not safe)),
;;; we follow all setters with the nonstandard procedure (void).
;;; If your Scheme doesn't have (void) you can
;;; (define (void) (if #f #f))
;;; This doesn't work on Racket, which disallows one-armed if's, but Racket
;;; already defines (void).
;;; INLINING: Gambit's inlining directives are a bit of a coarse tool.
;;; So what I've decided to do is not inline by default, and inline
;;; small accessors, etc., by hand. Let's hope I catch them all.
(declare (inline))
;;; An interval is a cross product of multi-indices
;;; [l_0,u_0) x [l_1,u_1) x ... x [l_n-1,u_n-1)
;;; where l_i < u_i for 0 <= i < n, and n >= 0 is the dimension of the interval
(define-type %%interval
id: 63374ab5-06fa-4d43-8c74-dd46f75ff7b5
copier: #f
no-functional-setter:
(dimension read-only:) ;; a fixnum
(%%volume read-write: equality-skip:) ;; #f or an exact integer, calculated when needed
(lower-bounds read-only:) ;; a vector of exact integers l_0,...,l_n-1
(upper-bounds read-only:) ;; a vector of exact integers u_0,...,u_n-1
)
(define-type %%array
id: d0995125-4e60-4b86-90a2-3bffbe52bcc4
copier: #f
;; Part of all arrays
;; an interval
no-functional-setter:
(domain read-only:)
;; (lambda (i_0 ... i_n-1) ...) returns a value for (i_0,...,i_n-1) in (array-domain a)
(getter read-only:)
;; Part of mutable arrays
;; (lambda (v i_0 ... i_n-1) ...) sets a value for (i_0,...,i_n-1) in (array-domain a)
(setter read-write:)
;; Part of specialized arrays
;; a storage class
(storage-class read-only:)
;; the backing store for this array
(body read-only:)
;; see below
(indexer read-only:)
; do we check whether bounds (in getters and setters) and values (in setters) are valid
(safe? read-only:)
; are the elements adjacent and in order?
(in-order? read-write:)
)
;;;
;;; A storage-class contains functions and objects to manipulate the
;;; backing store of a specialized-array.
;;;
;;; getter: (lambda (body i) ...) returns the value of body at index i
;;; setter: (lambda (body i v) ...) sets the value of body at index i to v
;;; checker: (lambda (val) ...) checks that val is an appropriate value for storing in (maker n)
;;; maker: (lambda (n val) ...) makes a body of length n with value val
;;; length: (lambda (body) ...) returns the number of objects in body
;;; default: object is the default value with which to fill body
;;; data?: (lambda (data) ...) returns #t iff data can be converted to a body
;;; data->body: (lambda (data) ...) converts data to a body, raising an exception if needed
;;;
(define-type storage-class
id: 65dd13e3-eb6d-4214-8de6-78d962d71885
copier: #f
read-only:
no-functional-setter:
getter
setter
checker
maker
copier
length
default
data?
data->body
)
(declare (not inline))
;;; Our naming convention prefixes %% to the names of internal procedures,
(cond-expand
((or gambit r7rs)
(begin
(define (c64vector-copy! to at from start end)
(f32vector-copy! to (fx* 2 at) from (fx* 2 start) (fx* 2 end)))
(define (c128vector-copy! to at from start end)
(f64vector-copy! to (fx* 2 at) from (fx* 2 start) (fx* 2 end)))))
(else
;; Punt
(begin
(define vector-copy! #f)
(define s8vector-copy! #f)
(define s16vector-copy! #f)
(define s32vector-copy! #f)
(define s64vector-copy! #f)
(define u8vector-copy! #f)
(define u16vector-copy! #f)
(define u32vector-copy! #f)
(define u64vector-copy! #f)
(define string-copy! #f)
(define c64vector-copy! #f)
(define c128vector-copy! #f))))
;;; We use the built-in Gambit procedure ##mutable?
;; Inlining the following routines causes too much code bloat
;; after compilation.
;;; We do not need a multi-argument every.
(define (%%every pred list)
(let loop ((list list))
(or (null? list)
(and (pred (car list))
(loop (cdr list))))))
;;; the following is used in error checks.
(define %%vector-every
(case-lambda
((pred vec)
(let loop ((i (fx- (vector-length vec) 1)))
(or (fx< i 0)
(and (pred (vector-ref vec i))
(loop (fx- i 1))))))
((pred vec vec2)
(let loop ((i (fx- (vector-length vec) 1)))
(or (fx< i 0)
(and (pred (vector-ref vec i)
(vector-ref vec2 i))
(loop (fx- i 1))))))
((pred vec vec2 . rest)
(let ((vecs (cons vec (cons vec2 rest))))
(let loop ((i (fx- (vector-length vec) 1)))
(or (fx< i 0)
(and (apply pred (map (lambda (vec) (vector-ref vec i)) vecs))
(loop (fx- i 1)))))))))
;;; requires vector-map, vector-copy function
;;; requires vector-concatenate function
;;; requires exact-integer? function
;;; requires iota, drop, take from SRFI-1
;;; requires fixnum? and flonum?
(declare (inline))
(define (interval? x)
(%%interval? x))
(define %%vector-of-zeros
'#(#()
#(0)
#(0 0)
#(0 0 0)
#(0 0 0 0)))
(define (%%finish-interval lower-bounds upper-bounds)
;; Requires that lower-bounds and upper-bounds are not user visible and therefore
;; not user modifiable.
(make-%%interval (vector-length upper-bounds)
#f
lower-bounds
upper-bounds))
(define make-interval
(case-lambda
((upper-bounds)
(cond ((not (and (vector? upper-bounds)
(%%vector-every (lambda (x) (exact-integer? x)) upper-bounds)
(%%vector-every (lambda (x) (not (negative? x))) upper-bounds)))
(error "make-interval: The argument is not a vector of nonnegative exact integers: " upper-bounds))
(else
(let ((dimension (vector-length upper-bounds)))
(%%finish-interval (if (fx< dimension 5)
(vector-ref %%vector-of-zeros dimension)
(make-vector dimension 0))
(vector-copy upper-bounds))))))
((lower-bounds upper-bounds)
(cond ((not (and (vector? lower-bounds)
(%%vector-every (lambda (x) (exact-integer? x)) lower-bounds)))
(error "make-interval: The first argument is not a vector of exact integers: " lower-bounds upper-bounds))
((not (and (vector? upper-bounds)
(%%vector-every (lambda (x) (exact-integer? x)) upper-bounds)))
(error "make-interval: The second argument is not a vector of exact integers: " lower-bounds upper-bounds))
((not (fx= (vector-length lower-bounds)
(vector-length upper-bounds)))
(error "make-interval: The first and second arguments are not the same length: " lower-bounds upper-bounds))
((not (%%vector-every (lambda (x y) (<= x y)) lower-bounds upper-bounds))
(error "make-interval: Each lower-bound must be no greater than the associated upper-bound: " lower-bounds upper-bounds))
(else
(%%finish-interval (vector-copy lower-bounds)
(vector-copy upper-bounds)))))))
(define (%%interval-lower-bound interval i)
(vector-ref (%%interval-lower-bounds interval) i))
(define (%%interval-upper-bound interval i)
(vector-ref (%%interval-upper-bounds interval) i))
(define (%%interval-width interval k)
(- (%%interval-upper-bound interval k)
(%%interval-lower-bound interval k)))
(define (%%interval-widths interval)
(vector-map (lambda (x y) (- x y))
(%%interval-upper-bounds interval)
(%%interval-lower-bounds interval)))
(define (%%interval-lower-bounds->vector interval)
(vector-copy (%%interval-lower-bounds interval)))
(define (%%interval-upper-bounds->vector interval)
(vector-copy (%%interval-upper-bounds interval)))
(define (%%interval-lower-bounds->list interval)
(vector->list (%%interval-lower-bounds interval)))
(define (%%interval-upper-bounds->list interval)
(vector->list (%%interval-upper-bounds interval)))
(define-macro (macro-make-index-tables)
`(begin
(define %%index-rotates
',(list->vector
(map (lambda (n)
(list->vector
(map (lambda (k)
(list->vector
(let ((identity-permutation (iota n)))
(append (drop identity-permutation k)
(take identity-permutation k)))))
(iota (+ n 1)))))
(iota 5))))
(define %%index-firsts
',(list->vector
(map (lambda (n)
(list->vector
(map (lambda (k)
(list->vector
(let ((identity-permutation (iota n)))
(cons k
(append (take identity-permutation k)
(drop identity-permutation (fx+ k 1)))))))
(iota n))))
(iota 5))))
(define %%index-lasts
',(list->vector
(map (lambda (n)
(list->vector
(map (lambda (k)
(list->vector
(let ((identity-permutation (iota n)))
(append (take identity-permutation k)
(drop identity-permutation (fx+ k 1))
(list k)))))
(iota n))))
(iota 5))))
(define %%index-swaps
`,(list->vector
(map (lambda (n)
(list->vector
(map (lambda (i)
(list->vector
(map (lambda (j)
(let ((result (list->vector (iota n))))
(vector-set! result i j)
(vector-set! result j i)
result))
(iota n))))
(iota n))))
(iota 5))))))
(macro-make-index-tables)
(define (%%index-rotate n k)
(if (fx< n 5)
(vector-ref (vector-ref %%index-rotates n) k)
(let ((identity-permutation (iota n)))
(list->vector (append (drop identity-permutation k)
(take identity-permutation k))))))
(define (%%index-first n k)
(if (fx< n 5)
(vector-ref (vector-ref %%index-firsts n) k)
(let ((identity-permutation (iota n)))
(list->vector (cons k
(append (take identity-permutation k)
(drop identity-permutation (fx+ k 1))))))))
(define (%%index-last n k)
(if (fx< n 5)
(vector-ref (vector-ref %%index-lasts n) k)
(let ((identity-permutation (iota n)))
(list->vector (append (take identity-permutation k)
(drop identity-permutation (fx+ k 1))
(list k))))))
(define (%%index-swap n i j)
(if (fx< n 5)
(vector-ref (vector-ref (vector-ref %%index-swaps n) i) j)
(let ((result (list->vector (iota n))))
(vector-set! result i j)
(vector-set! result j i)
result)))
(define (%%interval-empty? interval)
(eqv? (%%interval-volume interval) 0))
(define (%%interval-volume interval)
(or (%%interval-%%volume interval)
(%%compute-interval-volume interval)))
(declare (not inline))
(define (%%compute-interval-volume interval)
(let* ((upper-bounds
(%%interval-upper-bounds interval))
(lower-bounds
(%%interval-lower-bounds interval))
(dimension
(%%interval-dimension interval))
(volume
(do ((i (fx- dimension 1) (fx- i 1))
(result 1 (* result (- (vector-ref upper-bounds i)
(vector-ref lower-bounds i)))))
((fx< i 0) result))))
(%%interval-%%volume-set! interval volume)
volume))
(define (index-rotate n k)
(cond ((not (and (fixnum? n)
(fx<= 0 n)))
(error "index-rotate: The first argument is not a nonnegative fixnum: " n k))
((not (and (fixnum? k)
(fx<= 0 k n)))
(error "index-rotate: The second argument is not a fixnum between 0 and the first argument (inclusive): " n k))
(else
(%%index-rotate n k))))
(define (index-first n k)
(cond ((not (and (fixnum? n)
(fxpositive? n)))
(error "index-first: The first argument is not a positive fixnum: " n k))
((not (and (fixnum? k)
(fx<= 0 k)
(fx< k n)))
(error "index-first: The second argument is not a fixnum between 0 (inclusive) and the first argument (exclusive): " n k))
(else
(%%index-first n k))))
(define (index-last n k)
(cond ((not (and (fixnum? n)
(fxpositive? n)))
(error "index-last: The first argument is not a positive fixnum: " n k))
((not (and (fixnum? k)
(fx<= 0 k)
(fx< k n)))
(error "index-last: The second argument is not a fixnum between 0 (inclusive) and the first argument (exclusive): " n k))
(else
(%%index-last n k))))
(define (index-swap n i j)
(cond ((not (and (fixnum? n)
(fxpositive? n)))
(error "index-swap: The first argument is not a positive fixnum: " n i j))
((not (and (fixnum? i) (fx<= 0 i) (fx< i n)))
(error "index-swap: The second argument is not a fixnum between 0 (inclusive) and the first argument (exclusive): " n i j))
((not (and (fixnum? j) (fx<= 0 j) (fx< j n)))
(error "index-swap: The third argument is not a fixnum between 0 (inclusive) and the first argument (exclusive): " n i j))
(else
(%%index-swap n i j))))
(define (interval-dimension interval)
(cond ((not (interval? interval))
(error "interval-dimension: The argument is not an interval: " interval))
(else
(%%interval-dimension interval))))
(define (interval-lower-bound interval i)
(cond ((not (interval? interval))
(error "interval-lower-bound: The first argument is not an interval: " interval i))
((not (and (fixnum? i)
(fx< -1 i (%%interval-dimension interval))))
(error "interval-lower-bound: The second argument is not an exact integer between 0 (inclusive) and (interval-dimension interval) (exclusive): " interval i))
(else
(%%interval-lower-bound interval i))))
(define (interval-upper-bound interval i)
(cond ((not (interval? interval))
(error "interval-upper-bound: The first argument is not an interval: " interval i))
((not (and (fixnum? i)
(fx< -1 i (%%interval-dimension interval))))
(error "interval-upper-bound: The second argument is not an exact integer between 0 (inclusive) and (interval-dimension interval) (exclusive): " interval i))
(else
(%%interval-upper-bound interval i))))
(define (interval-width interval k)
(cond ((not (interval? interval))
(error "interval-width: The first argument is not an interval: " interval k))
((not (and (fixnum? k)
(fx< -1 k (%%interval-dimension interval))))
(error "interval-width: The second argument is not an exact integer between 0 (inclusive) and the dimension of the first argument (exclusive): " interval k))
(else
(%%interval-width interval k))))
(define (interval-widths interval)
(cond ((not (interval? interval))
(error "interval-widths: The argument is not an interval: " interval))
(else
(%%interval-widths interval))))
(define (interval-lower-bounds->vector interval)
(cond ((not (interval? interval))
(error "interval-lower-bounds->vector: The argument is not an interval: " interval))
(else
(%%interval-lower-bounds->vector interval))))
(define (interval-upper-bounds->vector interval)
(cond ((not (interval? interval))
(error "interval-upper-bounds->vector: The argument is not an interval: " interval))
(else
(%%interval-upper-bounds->vector interval))))
(define (interval-lower-bounds->list interval)
(cond ((not (interval? interval))
(error "interval-lower-bounds->list: The argument is not an interval: " interval))
(else
(%%interval-lower-bounds->list interval))))
(define (interval-upper-bounds->list interval)
(cond ((not (interval? interval))
(error "interval-upper-bounds->list: The argument is not an interval: " interval))
(else
(%%interval-upper-bounds->list interval))))
(define (interval-projections interval right-dimension)
(cond ((not (interval? interval))
(error "interval-projections: The first argument is not an interval: " interval right-dimension))
((not (and (fixnum? right-dimension)
(fx<= 0 right-dimension (%%interval-dimension interval))))
(error "interval-projections: The second argument is not an exact integer between 0 and the dimension of the first argument (inclusive): " interval right-dimension))
(else
(%%interval-projections interval right-dimension))))
(define (%%interval-projections interval right-dimension)
(let ((left-dimension
(fx- (%%interval-dimension interval) right-dimension))
(lowers
(%%interval-lower-bounds->list interval))
(uppers
(%%interval-upper-bounds->list interval)))
(values (%%finish-interval (list->vector (take lowers left-dimension))
(list->vector (take uppers left-dimension)))
(%%finish-interval (list->vector (drop lowers left-dimension))
(list->vector (drop uppers left-dimension))))))
(define (interval-volume interval)
(cond ((not (interval? interval))
(error "interval-volume: The argument is not an interval: " interval))
(else
(%%interval-volume interval))))
(define (interval-empty? interval)
(cond ((not (interval? interval))
(error "interval-empty?: The argument is not an interval: " interval))
(else
(%%interval-empty? interval))))
(define (permutation? permutation)
(and (vector? permutation)
(let* ((n (vector-length permutation))
(permutation-range (make-vector n #f)))
;; we'll write things into permutation-range
;; each box should be written only once
(let loop ((i 0))
(or (fx= i n)
(let ((p_i (vector-ref permutation i)))
(and (fixnum? p_i) ;; a permutation index can't be a bignum
(fx< -1 p_i n)
(not (vector-ref permutation-range p_i))
(let ()
(vector-set! permutation-range p_i #t)
(loop (fx+ i 1))))))))))
(define (%%vector-permute vector permutation)
(let* ((n (vector-length vector))
(result (make-vector n)))
(do ((i 0 (fx+ i 1)))
((fx= i n) result)
(vector-set! result i (vector-ref vector (vector-ref permutation i))))))
(define (%%vector-permute->list vector permutation)
(do ((i (fx- (vector-length vector) 1) (fx- i 1))
(result '() (cons (vector-ref vector (vector-ref permutation i))
result)))
((fx< i 0) result)))
(define (%%permutation-invert permutation)
(let* ((n (vector-length permutation))
(result (make-vector n)))
(do ((i 0 (fx+ i 1)))
((fx= i n) result)
(vector-set! result (vector-ref permutation i) i))))
(define (%%interval-permute interval permutation)
(%%finish-interval (%%vector-permute (%%interval-lower-bounds interval) permutation)
(%%vector-permute (%%interval-upper-bounds interval) permutation)))
(define (interval-permute interval permutation)
(cond ((not (interval? interval))
(error "interval-permute: The first argument is not an interval: " interval permutation))
((not (permutation? permutation))
(error "interval-permute: The second argument is not a permutation: " interval permutation))
((not (fx= (%%interval-dimension interval) (vector-length permutation)))
(error "interval-permute: The dimension of the first argument (an interval) does not equal the length of the second (a permutation): " interval permutation))
(else
(%%interval-permute interval permutation))))
(define (translation? translation)
(and (vector? translation)
(%%vector-every (lambda (x) (exact-integer? x)) translation)))
(define (interval-translate interval translation)
(cond ((not (interval? interval))
(error "interval-translate: The first argument is not an interval: " interval translation))
((not (translation? translation))
(error "interval-translate: The second argument is not a vector of exact integers: " interval translation))
((not (fx= (%%interval-dimension interval)
(vector-length translation)))
(error "interval-translate: The dimension of the first argument (an interval) does not equal the length of the second (a vector): " interval translation))
(else
(%%interval-translate interval translation))))
(define (%%interval-translate Interval translation)
(%%finish-interval (vector-map (lambda (x y) (+ x y)) (%%interval-lower-bounds Interval) translation)
(vector-map (lambda (x y) (+ x y)) (%%interval-upper-bounds Interval) translation)))
(define (%%interval-scale interval scales)
(let* ((uppers (%%interval-upper-bounds interval))
(lowers (%%interval-lower-bounds interval))
(new-uppers (vector-map (lambda (u s)
(quotient (+ u s -1) s))
uppers scales)))
;; lowers is not newly allocated, but it's already been copied because it's the
;; lower bounds of an existing interval
(%%finish-interval lowers new-uppers)))
(define (interval-scale interval scales)
(cond ((not (and (interval? interval)
(%%vector-every (lambda (x) (eqv? 0 x)) (%%interval-lower-bounds interval))))
(error "interval-scale: The first argument is not an interval with all lower bounds zero: " interval scales))
((not (and (vector? scales)
(%%vector-every (lambda (x) (exact-integer? x)) scales)
(%%vector-every (lambda (x) (positive? x)) scales)))
(error "interval-scale: The second argument is not a vector of positive, exact, integers: " interval scales))
((not (fx= (vector-length scales) (%%interval-dimension interval)))
(error "interval-scale: The dimension of the first argument (an interval) is not equal to the length of the second (a vector): "
interval scales))
(else
(%%interval-scale interval scales))))
(define (%%interval-cartesian-product intervals)
;; Even if there is only one interval, its lower and upper bounds have already been copied.
(%%finish-interval (vector-concatenate (map %%interval-lower-bounds intervals))
(vector-concatenate (map %%interval-upper-bounds intervals))))
(define (interval-cartesian-product #!rest intervals)
(cond ((not (%%every interval? intervals))
(apply error "interval-cartesian-product: Not all arguments are intervals: " intervals))
(else
(%%interval-cartesian-product intervals))))
(define (interval-dilate interval lower-diffs upper-diffs)
(cond ((not (interval? interval))
(error "interval-dilate: The first argument is not an interval: " interval lower-diffs upper-diffs))
((not (and (vector? lower-diffs)
(%%vector-every (lambda (x) (exact-integer? x)) lower-diffs)))
(error "interval-dilate: The second argument is not a vector of exact integers: " interval lower-diffs upper-diffs))
((not (and (vector? upper-diffs)
(%%vector-every (lambda (x) (exact-integer? x)) upper-diffs)))
(error "interval-dilate: The third argument is not a vector of exact integers: " interval lower-diffs upper-diffs))
((not (fx= (vector-length lower-diffs)
(vector-length upper-diffs)
(%%interval-dimension interval)))
(error "interval-dilate: The second and third arguments must have the same length as the dimension of the first argument: " interval lower-diffs upper-diffs))
(else
(let ((new-lower-bounds (vector-map (lambda (x y) (+ x y)) (%%interval-lower-bounds interval) lower-diffs))
(new-upper-bounds (vector-map (lambda (x y) (+ x y)) (%%interval-upper-bounds interval) upper-diffs)))
(if (%%vector-every (lambda (x y) (<= x y)) new-lower-bounds new-upper-bounds)
(%%finish-interval new-lower-bounds new-upper-bounds)
(error "interval-dilate: Some resulting lower bounds are greater than corresponding upper bounds: " interval lower-diffs upper-diffs))))))
(define (%%interval= interval1 interval2)
;; This can be used a fair amount, so we open-code it
(or (eq? interval1 interval2)
(and (let ((upper1 (%%interval-upper-bounds interval1))
(upper2 (%%interval-upper-bounds interval2)))
(or (eq? upper1 upper2)
(and (fx= (vector-length upper1) (vector-length upper2))
(%%vector-every (lambda (x y) (= x y)) upper1 upper2))))
(let ((lower1 (%%interval-lower-bounds interval1))
(lower2 (%%interval-lower-bounds interval2)))
(or (eq? lower1 lower2)
;; We don't need to check that the two lower bounds
;; are the same length after checking the upper bounds
(%%vector-every (lambda (x y) (= x y)) lower1 lower2))))))
(define (interval= interval1 interval2)
(cond ((not (and (interval? interval1)
(interval? interval2)))
(error "interval=: Not all arguments are intervals: " interval1 interval2))
(else
(%%interval= interval1 interval2))))
(define (%%interval-subset? interval1 interval2)
(and (%%vector-every (lambda (x y) (>= x y)) (%%interval-lower-bounds interval1) (%%interval-lower-bounds interval2))
(%%vector-every (lambda (x y) (<= x y)) (%%interval-upper-bounds interval1) (%%interval-upper-bounds interval2))))
(define (interval-subset? interval1 interval2)
(cond ((not (and (interval? interval1)
(interval? interval2)))
(error "interval-subset?: Not all arguments are intervals: " interval1 interval2))
((not (fx= (%%interval-dimension interval1)
(%%interval-dimension interval2)))
(error "interval-subset?: The arguments do not have the same dimension: " interval1 interval2))
(else
(%%interval-subset? interval1 interval2))))
(define (%%interval-intersect intervals)
(let ((lower-bounds (apply vector-map max (map %%interval-lower-bounds intervals)))
(upper-bounds (apply vector-map min (map %%interval-upper-bounds intervals))))
(and (%%vector-every (lambda (x y) (<= x y)) lower-bounds upper-bounds)
(%%finish-interval lower-bounds upper-bounds))))
(define (interval-intersect interval #!rest intervals)
(if (null? intervals)
(if (interval? interval)
interval
(error "interval-intersect: The argument is not an interval: " interval))
(let ((intervals (cons interval intervals)))
(cond ((not (%%every interval? intervals))
(apply error "interval-intersect: Not all arguments are intervals: " intervals))
((let* ((dims (map %%interval-dimension intervals))
(dim1 (car dims)))
(not (%%every (lambda (dim) (fx= dim dim1)) (cdr dims))))
(apply error "interval-intersect: Not all arguments have the same dimension: " intervals))
(else
(%%interval-intersect intervals))))))
(declare (inline))
(define (%%interval-contains-multi-index?-1 interval i)
(and (<= (%%interval-lower-bound interval 0) i) (< i (%%interval-upper-bound interval 0))))
(define (%%interval-contains-multi-index?-2 interval i j)
(and (<= (%%interval-lower-bound interval 0) i) (< i (%%interval-upper-bound interval 0))
(<= (%%interval-lower-bound interval 1) j) (< j (%%interval-upper-bound interval 1))))
(define (%%interval-contains-multi-index?-3 interval i j k)
(and (<= (%%interval-lower-bound interval 0) i) (< i (%%interval-upper-bound interval 0))
(<= (%%interval-lower-bound interval 1) j) (< j (%%interval-upper-bound interval 1))
(<= (%%interval-lower-bound interval 2) k) (< k (%%interval-upper-bound interval 2))))
(define (%%interval-contains-multi-index?-4 interval i j k l)
(and (<= (%%interval-lower-bound interval 0) i) (< i (%%interval-upper-bound interval 0))
(<= (%%interval-lower-bound interval 1) j) (< j (%%interval-upper-bound interval 1))
(<= (%%interval-lower-bound interval 2) k) (< k (%%interval-upper-bound interval 2))
(<= (%%interval-lower-bound interval 3) l) (< l (%%interval-upper-bound interval 3))))
(declare (not inline))
(define (%%interval-contains-multi-index?-general interval multi-index)
(let loop ((i 0)
(multi-index multi-index))
(or (null? multi-index)
(let ((component (car multi-index)))
(and (<= (%%interval-lower-bound interval i) component)
(< component (%%interval-upper-bound interval i))
(loop (fx+ i 1)
(cdr multi-index)))))))
(define (interval-contains-multi-index? interval #!rest multi-index)
;; this is relatively slow, but (a) I haven't seen a need to use it yet, and (b) this formulation
;; significantly simplifies testing the error checking
(cond ((not (interval? interval))
(error "interval-contains-multi-index?: The first argument is not an interval: " interval))
((not (fx= (%%interval-dimension interval)
(length multi-index)))
(apply error "interval-contains-multi-index?: The dimension of the first argument (an interval) does not match number of indices: " interval multi-index))
((not (%%every (lambda (x) (exact-integer? x)) multi-index))
(apply error "interval-contains-multi-index?: At least one multi-index component is not an exact integer: " interval multi-index))
(else
(%%interval-contains-multi-index?-general interval multi-index))))
;;; Applies f to every element of the domain; assumes that f is thread-safe,
;;; the order of application is not specified
(define (interval-for-each f interval)
(cond ((not (interval? interval))
(error "interval-for-each: The second argument is not a interval: " interval))
((not (procedure? f))
(error "interval-for-each: The first argument is not a procedure: " f))
(else
(%%interval-for-each f interval))))
(define (%%interval-for-each f interval)
(%%interval-fold-left f
(lambda (ignore f_i)
#t) ;; just compute (apply f multi-index)
'ignore
interval)
(void))
;;; Calculates
;;;
;;; (...(operator (operator (operator identity (f multi-index_1)) (f multi-index_2)) (f multi-index_3)) ...)
;;;
;;; where multi-index_1, multi-index_2, ... are the elements of interval in lexicographical order
(define (interval-fold-left f operator identity interval)
(cond ((not (interval? interval))
(error "interval-fold-left: The fourth argument is not an interval: " f operator identity interval))
((not (procedure? operator))
(error "interval-fold-left: The second argument is not a procedure: " f operator identity interval))
((not (procedure? f))
(error "interval-fold-left: The first argument is not a procedure: " f operator identity interval))
(else
(%%interval-fold-left f operator identity interval))))
(define (%%interval-fold-left f operator identity interval)
(define-macro (generate-code)
(define (symbol-append . args)
(string->symbol
(apply string-append (map (lambda (x)
(cond ((symbol? x) (symbol->string x))
((number? x) (number->string x))
((string? x) x)
(else (error "Arghh!"))))
args))))
(define (make-lower k)
(symbol-append 'lower- k))
(define (make-upper k)
(symbol-append 'upper- k))
(define (make-arg k)
(symbol-append 'i_ k))
(define (make-loop-name k)
(symbol-append 'loop- k))
(define (make-loop index depth k)
`(let ,(make-loop-name index) ((,(make-arg index) ,(make-lower index))
(result result))
(if (= ,(make-arg index) ,(make-upper index))
,(if (= index 0)
`result
`(,(make-loop-name (- index 1)) (+ ,(make-arg (- index 1)) 1) result))
,(if (= depth 0)
`(,(make-loop-name index) (+ ,(make-arg index) 1) (operator result (f ,@(map (lambda (i) (make-arg i)) (iota k)))))
(make-loop (+ index 1) (- depth 1) k)))))
(define (do-one-case k)
(let ((result
`((,k)
(let (,@(map (lambda (j)
`(,(make-lower j) (%%interval-lower-bound interval ,j)))
(iota k))
,@(map (lambda (j)
`(,(make-upper j) (%%interval-upper-bound interval ,j)))
(iota k))
(result identity))
,(make-loop 0 (- k 1) k)))))
result))
`(case (%%interval-dimension interval)
((0) (operator identity (f)))
,@(map do-one-case (iota 8 1))
(else
(let ()
(define (get-next-args reversed-args
reversed-lowers
reversed-uppers)
(let ((next-index (+ (car reversed-args) 1)))
(if (< next-index (car reversed-uppers))
(cons next-index (cdr reversed-args))
(and (not (null? (cdr reversed-args)))
(let ((tail-result (get-next-args (cdr reversed-args)
(cdr reversed-lowers)
(cdr reversed-uppers))))
(and tail-result
(cons (car reversed-lowers) tail-result)))))))
(let ((reversed-lowers (reverse (%%interval-lower-bounds->list interval)))
(reversed-uppers (reverse (%%interval-upper-bounds->list interval))))
(let loop ((reversed-args reversed-lowers)
(result identity))
;;; There's at least one element of the interval, so we can
;;; use a do-until loop
(let ((result (operator result (apply f (reverse reversed-args))))
(next-reversed-args (get-next-args reversed-args
reversed-lowers
reversed-uppers)))
(if next-reversed-args
(loop next-reversed-args result)
result))))))))
(if (%%interval-empty? interval) ;; handle (make-interval '#(10000000 10000000 0)) efficiently
identity
(generate-code)))
(define (interval-fold-right f operator identity interval)
(cond ((not (interval? interval))
(error "interval-fold-right: The fourth argument is not an interval: " f operator identity interval))
((not (procedure? operator))
(error "interval-fold-right: The second argument is not a procedure: " f operator identity interval))
((not (procedure? f))
(error "interval-fold-right: The first argument is not a procedure: " f operator identity interval))
(else
(%%interval-fold-right f operator identity interval))))
(define (%%interval-fold-right f operator identity interval)
(declare (not lambda-lift))
(define-macro (generate-code)
(define (symbol-append . args)
(string->symbol
(apply string-append (map (lambda (x)
(cond ((symbol? x) (symbol->string x))
((number? x) (number->string x))
((string? x) x)
(else (error "Arghh!"))))
args))))
(define (make-lower k)
(symbol-append 'lower- k))
(define (make-upper k)
(symbol-append 'upper- k))
(define (make-arg k)
(symbol-append 'i_ k))
(define (make-loop-name k)
(symbol-append 'loop- k))
(define (make-loop index depth k)
`(let ,(make-loop-name index) ((,(make-arg index) ,(make-lower index)))
(if (= ,(make-arg index) ,(make-upper index))
,(if (= index 0)
`identity
`(,(make-loop-name (- index 1)) (+ ,(make-arg (- index 1)) 1)))
,(if (= depth 0)
`(let* ((item (f ,@(map (lambda (i) (make-arg i)) (iota k))))
(result (,(make-loop-name index) (+ ,(make-arg index) 1))))
(operator item result))
(make-loop (+ index 1) (- depth 1) k)))))
(define (do-one-case k)
(let ((result
`((,k)
(let (,@(map (lambda (j)
`(,(make-lower j) (%%interval-lower-bound interval ,j)))
(iota k))
,@(map (lambda (j)
`(,(make-upper j) (%%interval-upper-bound interval ,j)))
(iota k))
(i 0))
,(make-loop 0 (- k 1) k)))))
result))
(let ((result
`(case (%%interval-dimension interval)
((0) (operator (f) identity))
,@(map do-one-case (iota 8 1))
(else
(let ()
(define (get-next-args reversed-args
reversed-lowers
reversed-uppers)
(let ((next-index (+ (car reversed-args) 1)))
(if (< next-index (car reversed-uppers))
(cons next-index (cdr reversed-args))
(and (not (null? (cdr reversed-args)))
(let ((tail-result (get-next-args (cdr reversed-args)
(cdr reversed-lowers)
(cdr reversed-uppers))))
(and tail-result
(cons (car reversed-lowers) tail-result)))))))
(let ((reversed-lowers (reverse (%%interval-lower-bounds->list interval)))
(reversed-uppers (reverse (%%interval-upper-bounds->list interval))))
(let loop ((reversed-args reversed-lowers))
(if reversed-args
(let* ((item (apply f (reverse reversed-args)))
(result (loop (get-next-args reversed-args
reversed-lowers
reversed-uppers))))
(operator item result))
identity))))))))
result))
(if (%%interval-empty? interval)
identity
(generate-code)))
;; We'll use the same basic container for all types of arrays.
(declare (inline))
(define specialized-array-default-safe?
(make-parameter
#f
(lambda (bool)
(if (boolean? bool)
bool
(error "specialized-array-default-safe?: The argument is not a boolean: " bool)))))
(define specialized-array-default-mutable?
(make-parameter
#t
(lambda (bool)
(if (boolean? bool)
bool
(error "specialized-array-default-mutable?: The argument is not a boolean: " bool)))))
;; An array has a domain (which is an interval) and an getter that maps that domain into some type of
;; Scheme objects
(define %%order-unknown 1) ;; can be any nonboolean
(define (%%empty-getter domain)
(lambda args (apply error "array-getter: Array domain is empty: " domain args)))
(define (%%empty-setter domain)
(lambda args (apply error "array-setter: Array domain is empty: " domain args)))
(define make-array
(case-lambda
((domain getter)
(cond ((not (interval? domain))
(error "make-array: The first argument is not an interval: " domain getter))
((not (procedure? getter))
(error "make-array: The second argument is not a procedure: " domain getter))
(else
(make-%%array domain
(if (%%interval-empty? domain)
(%%empty-getter domain)
getter)
#f ; no setter
#f ; storage-class
#f ; body
#f ; indexer
#f ; safe?
%%order-unknown ; in-order?
))))
((domain getter setter)
(cond ((not (interval? domain))
(error "make-array: The first argument is not an interval: " domain getter setter))
((not (procedure? getter))
(error "make-array: The second argument is not a procedure: " domain getter setter))
((not (procedure? setter))
(error "make-array: The third argument is not a procedure: " domain getter setter))
(else
(make-%%array domain
(if (%%interval-empty? domain)
(%%empty-getter domain)
getter)
(if (%%interval-empty? domain)
(%%empty-setter domain)
setter)
#f ; storage-class
#f ; body
#f ; indexer
#f ; safe?
%%order-unknown ; in-order?
))))))
(define (array? x)
(%%array? x))
(define (array-domain obj)
(cond ((not (array? obj))
(error "array-domain: The argument is not an array: " obj))
(else
(%%array-domain obj))))
(define (array-getter obj)
(cond ((not (array? obj))
(error "array-getter: The argument is not an array: " obj))
(else
(%%array-getter obj))))
(define (%%array-dimension array)
(%%interval-dimension (%%array-domain array)))
(define (array-dimension array)
(cond ((not (array? array))
(error "array-dimension: The argument is not an array: " array))
(else
(%%array-dimension array))))
;;;
;;; A mutable array has, in addition a setter, that satisfies, roughly
;;;
;;; If (i_1, ..., i_n)\neq (j_1, ..., j_n) \in (array-domain a)
;;;
;;; and
;;;
;;; ((array-getter a) j_1 ... j_n) => x
;;;
;;; then "after"
;;;
;;; ((array-setter a) v i_1 ... i_n)
;;;
;;; we have
;;;
;;; ((array-getter a) j_1 ... j_n) => x
;;;
;;; and
;;;
;;; ((array-getter a) i_1 ... i_n) => v
;;;
(define (mutable-array? obj)
(and (array? obj)
(not (eq? (%%array-setter obj) #f))))
(define (array-setter obj)
(cond ((not (mutable-array? obj))
(error "array-setter: The argument is not an mutable array: " obj))
(else
(%%array-setter obj))))
(define (%%array-freeze! A)
(%%array-setter-set! A #f)
A)
(define (array-freeze! A)
(cond ((not (array? A))
(error "array-freeze!: The argument is not an array: " A))
(else
(%%array-freeze! A))))
(declare (not inline))
;;; We define specialized storage-classes for:
;;;
;;; 32- and 64-bit floating-point numbers,
;;; complex numbers with real and imaginary parts of 32- and 64-bit floating-point numbers respectively
;;; 8-, 16-, 32-, and 64-bit signed integers,
;;; 8-, 16-, 32-, and 64-bit unsigned integers, and
;;; 1-bit unsigned integers
;;;
;;; as well as generic objects.
(define-macro (make-standard-storage-classes)
(define (symbol-concatenate . symbols)
(string->symbol (apply string-append (map (lambda (s)
(if (string? s)
s
(symbol->string s)))
symbols))))
`(begin
,@(map (lambda (name prefix default checker)
(let ((name (symbol-concatenate name '-storage-class))
(ref (symbol-concatenate prefix '-ref))
(set! (symbol-concatenate prefix '-set!))
(make (symbol-concatenate 'make- prefix))
(copy! (symbol-concatenate prefix '-copy!))
(length (symbol-concatenate prefix '-length))
(? (symbol-concatenate prefix '?)))
`(define ,name
(make-storage-class
;; getter
(lambda (v i)
(,ref v i))
;; setter
(lambda (v i val)
(,set! v i val) (void))
;; checker
,checker ;; already expanded
;; maker
(lambda (n val)
(,make n val))
;; copier
,copy! ;; complex call to memcopy, so don't expand
;; length
(lambda (v)
(,length v))
;; default
,default
;; data?
(lambda (data)
(,? data))
;; data->body
(lambda (data)
(if (,? data)
data
(error ,(symbol->string
(symbol-concatenate
"Expecting a "
prefix
" passed to "
"(storage-class-data->body "
name
"): "))
data)))))))
'(generic s8 u8 s16 u16 s32 u32 s64 u64 f32 f64 char)
'(vector s8vector u8vector s16vector u16vector s32vector u32vector s64vector u64vector f32vector f64vector string)
'(#f 0 0 0 0 0 0 0 0 0.0 0.0 #\0)
`((lambda (x) #t) ; generic
(lambda (x) ; s8
(and (fixnum? x)
(fx<= ,(- (expt 2 7))
x
,(- (expt 2 7) 1))))
(lambda (x) ; u8
(and (fixnum? x)
(fx<= 0
x
,(- (expt 2 8) 1))))
(lambda (x) ; s16
(and (fixnum? x)
(fx<= ,(- (expt 2 15))
x
,(- (expt 2 15) 1))))
(lambda (x) ; u16
(and (fixnum? x)
(fx<= 0
x
,(- (expt 2 16) 1))))
(lambda (x) ; s32
(declare (generic))
(and (exact-integer? x)
(<= ,(- (expt 2 31))
x
,(- (expt 2 31) 1))))
(lambda (x) ; u32
(declare (generic))
(and (exact-integer? x)
(<= 0
x
,(- (expt 2 32) 1))))
(lambda (x) ; s64
(declare (generic))
(and (exact-integer? x)
(<= ,(- (expt 2 63))
x
,(- (expt 2 63) 1))))
(lambda (x) ; u64
(declare (generic))
(and (exact-integer? x)
(<= 0
x
,(- (expt 2 64) 1))))
(lambda (x) (flonum? x)) ; f32
(lambda (x) (flonum? x)) ; f64
(lambda (x) (char? x)) ; char
))))
(make-standard-storage-classes)
;;; for bit-arrays, body is a vector, the first element of which is the actual number of elements,
;;; the second element of which is a u16vector that contains the bit string
(define u1-storage-class
(make-storage-class
;; getter
(lambda (v i)
(let ((index (fxarithmetic-shift-right i 4))
(shift (fxand i 15))
(bodyv (vector-ref v 1)))
(fxand
(fxarithmetic-shift-right
(u16vector-ref bodyv index)
shift)
1)))
;; setter
(lambda (v i val)
(let ((index (fxarithmetic-shift-right i 4))
(shift (fxand i 15))
(bodyv (vector-ref v 1)))
(u16vector-set! bodyv index (fxior (fxarithmetic-shift-left val shift)
(fxand (u16vector-ref bodyv index)
(fxnot (fxarithmetic-shift-left 1 shift)))))
(void)))
;; checker
(lambda (val)
(and (fixnum? val)
(eq? 0 (fxand -2 val))))
;; maker
(lambda (size initializer)
(let ((u16-size (fxarithmetic-shift-right (+ size 15) 4)))
(vector size (make-u16vector u16-size (if (eqv? 0 initializer) 0 65535)))))
;; no copier (for now)
#f
;; length
(lambda (v)
(vector-ref v 0))
;; default
0
;; data?
(lambda (data)
(u16vector? data))
;; data->body
(lambda (data)
(if (not (u16vector? data))
(error "Expecting a u16vector passed to (storage-class-data->body u1-storage-class): " data)
(vector (fx* 16 (u16vector-length data))
data)))))
(define-macro (make-complex-storage-classes)
(define (symbol-concatenate . symbols)
(string->symbol (apply string-append (map (lambda (s)
(if (string? s)
s
(symbol->string s)))
symbols))))
(define construct
(lambda (size)
(let ((prefix (string-append "c" (number->string (fx* 2 size))))
(floating-point-prefix (string-append "f" (number->string size))))
`(define ,(symbol-concatenate prefix '-storage-class)
(make-storage-class
;; getter
(lambda (body i)
(make-rectangular (,(symbol-concatenate floating-point-prefix 'vector-ref) body (fx* 2 i))
(,(symbol-concatenate floating-point-prefix 'vector-ref) body (fx+ (fx* 2 i) 1))))
;; setter
(lambda (body i obj)
(,(symbol-concatenate floating-point-prefix 'vector-set!) body (fx* 2 i) (real-part obj))
(,(symbol-concatenate floating-point-prefix 'vector-set!) body (fx+ (fx* 2 i) 1) (imag-part obj))
(void))
;; checker
(lambda (obj)
(and (complex? obj)
(inexact? (real-part obj))
(inexact? (imag-part obj))))
;; maker
(lambda (n val)
(let ((l (fx* 2 n))
(re (real-part val))
(im (imag-part val)))
(let ((result (,(symbol-concatenate 'make-
floating-point-prefix
'vector)
l)))
(do ((i 0 (+ i 2)))
((= i l) result)
(,(symbol-concatenate floating-point-prefix 'vector-set!) result i re)
(,(symbol-concatenate floating-point-prefix 'vector-set!) result (fx+ i 1) im)))))
;; copier
,(symbol-concatenate prefix 'vector-copy!)
;; length
(lambda (body)
(fxquotient (,(symbol-concatenate floating-point-prefix 'vector-length) body) 2))
;; default
0.+0.i
;; data?
(lambda (data)
(and (,(symbol-concatenate floating-point-prefix 'vector?) data)
(fxeven? (,(symbol-concatenate floating-point-prefix 'vector-length) data))))
;; data->body
(lambda (data)
(if (and (,(symbol-concatenate floating-point-prefix 'vector?) data)
(fxeven? (,(symbol-concatenate floating-point-prefix 'vector-length) data)))
data
(error ,(symbol->string
(symbol-concatenate
"Expecting a "
floating-point-prefix 'vector
" with an even number of elements passed to "
"(storage-class-data->body "
prefix '-storage-class
"): "))
data))))))))
(let ((result
`(begin
,@(map construct
'(32 64)))))
result))
(make-complex-storage-classes)
;;; And now we define a small float storage class:
;;; Since there is no native f16 in most schemes, we represent an f16 object
;;; with an integer between 0 (inclusive) and 65536 (exclusive), with the
;;; body of f16-storage-class represented by a u16vector. We assume that
;;; integers in this range are fixnums.
;;; It takes noticeable computations and boxing a double to extract the
;;; object represented by an element of an f16-storage-class array, and
;;; even more computations to take a double object and convert it to the
;;; representation of its f16 rounded value. So I may add "hidden" entries
;;; to f16-storage-class to extract and insert the representation of an
;;; f16 value directly, instead of converting to a double and back.
(define-macro (macro-make-representation->double name mantissa-width exponent-width exponent-bias)
(define (append-symbols . args)
(string->symbol
(apply string-append (map (lambda (arg)
(cond ((symbol? arg) (symbol->string arg))
((number? arg) (number->string arg))
((string? arg) arg)
(else
(apply error "append-symbols: unknown argument: " arg))))
args))))
(let* ((exponent-mask (- (fxarithmetic-shift-left 1 exponent-width) 1))
(mantissa-mask (- (fxarithmetic-shift-left 1 mantissa-width) 1))
(2^mantissa-width (fxarithmetic-shift-left 1 mantissa-width))
(result
`(define (,(append-symbols name '->double) x)
(let ((e (fxand ,exponent-mask (fxarithmetic-shift-right x ,mantissa-width)))
(m (fxand ,mantissa-mask x))
(s (fxarithmetic-shift-right x ,(+ mantissa-width exponent-width))))
(cond ((fx= e ,exponent-mask)
(if (fxzero? m)
(if (fxzero? s) +inf.0 -inf.0)
+nan.0))
((fx> e 0)
(let* ((abs-numerator (fx+ ,2^mantissa-width m))
(numerator (if (fxzero? s) abs-numerator (fx- abs-numerator))))
(flscalbn (fl* (fixnum->flonum numerator) ,(fl/ (fixnum->flonum 2^mantissa-width))) (fx- e ,exponent-bias))))
((fxzero? m)
(if (fxzero? s) +0. -0.))
(else
(let* ((abs-numerator m)
(numerator (if (fxzero? s) abs-numerator (fx- abs-numerator))))
(flscalbn (fl* (fixnum->flonum numerator) ,(fl/ (fixnum->flonum 2^mantissa-width))) ,(fx- 1 exponent-bias)))))))))
;; (pp result)
result))
(define-macro (macro-make-double->representation name mantissa-width exponent-width exponent-bias)
(define (append-symbols . args)
(string->symbol
(apply string-append (map (lambda (arg)
(cond ((symbol? arg) (symbol->string arg))
((number? arg) (number->string arg))
((string? arg) arg)
(else
(apply error "append-symbols: unknown argument: " arg))))
args))))
(let* ((exponent-mask (- (fxarithmetic-shift-left 1 exponent-width) 1))
(mantissa-mask (- (fxarithmetic-shift-left 1 mantissa-width) 1))
(2^mantissa-width (fxarithmetic-shift-left 1 mantissa-width))
(result
`(define (,(append-symbols 'double-> name) x)
(declare (inline))
(define (construct-representation sign-bit biased-exponent mantissa)
(fxior (fxarithmetic-shift-left sign-bit ,(+ exponent-width mantissa-width))
(fxior (fxarithmetic-shift-left biased-exponent ,mantissa-width)
mantissa)))
(let ((sign-bit
(if (flnegative? (##flcopysign 1. x)) 1 0)))
(cond ((not (flfinite? x))
(if (flnan? x)
(construct-representation sign-bit ,exponent-mask ,mantissa-mask)
;; an infinity
(construct-representation sign-bit ,exponent-mask 0)))
((flzero? x)
;; a zero
(construct-representation sign-bit 0 0))
(else
;; finite
(let ((exponent (flilogb x)))
(cond ((fx<= ,(- exponent-mask exponent-bias) exponent)
;; infinity, because the exponent is too large
(construct-representation sign-bit ,exponent-mask 0))
((fx< ,(fx- exponent-bias) exponent)
;; probably normal, finite in representation, unless overflow
(let ((possible-mantissa
(##flonum->fixnum (flround (flscalbn (flabs x) (fx- ,mantissa-width exponent))))))
(if (fx< possible-mantissa ,(fx* 2 2^mantissa-width))
;; no overflow
(construct-representation sign-bit
(fx+ exponent ,exponent-bias)
(fxand possible-mantissa ,mantissa-mask))
;; overflow
(if (fx= exponent ,exponent-bias)
;; maximum finite exponent, overflow to infinity
(construct-representation sign-bit ,exponent-mask 0)
;; increase exponent by 1, mantissa is zero, no double rounding
(construct-representation sign-bit (fx+ exponent ,(fx+ exponent-bias 1)) 0)))))
(else
;; usally subnormal
(let ((possible-mantissa
(##flonum->fixnum (flround (flscalbn (flabs x) ,(fx+ exponent-bias mantissa-width -1))))))
(if (fx< possible-mantissa ,2^mantissa-width)
;; doesn't overflow to normal
(construct-representation sign-bit 0 possible-mantissa)
;; overflow to smallest normal
(construct-representation sign-bit 1 0))))))))))))
;; (pp result)
result))
(define f16-storage-class
(let ()
(macro-make-representation->double f16 10 5 15)
(macro-make-double->representation f16 10 5 15)
(make-storage-class
;; getter
(lambda (body i)
(f16->double (u16vector-ref body i)))
;; setter
(lambda (body i obj)
(u16vector-set! body i (double->f16 obj)) (void))
;; checker
(lambda (obj)
(flonum? obj))
;; maker
(lambda (n val)
(make-u16vector n (double->f16 val)))
;; copier
u16vector-copy!
;; length
(lambda (body)
(u16vector-length body))
;; default
0.
;; data?
(lambda (data)
(u16vector? data))
;; data->body
(lambda (data)
(if (u16vector? data)
data
(error "Expecting a u16vector passed to (storage-class-data->body f16-storage-class): " data))))))
#|
;;; The test code for the conversion routines:
(define (test)
(declare (inlining-limit 0))
(define (compose-f16 sign exponent mantissa)
(bitwise-ior (arithmetic-shift sign 15)
(arithmetic-shift exponent 10)
mantissa))
(define-macro (check i expr)
`(if (not (= ,i ,expr))
(begin
(pp (list ,i , expr ',expr))
(error "crap"))))
;; The general strategy is: for the representation of each finite f16 number,
;; 1. Compute the double (x) associated with that representation, the one before (previous-x)
;; and the one after (next-x).
;; 2. Choose a random double strictly between the halfway point between x and each of next-x
;; and previous-x, and see that it rounds to the f16 representation of x. (It's strict
;; for f16, double, and the reference implementation of SRFI 27.)
;; 3. If the representation is even, check that the double exactly between s and next-x, and
;; x and previous x rounds to x. (Round to even rule.)
;; Some care must be taken for the representation of the largest normal f16 number and the representation of 0.
(do ((i 1 (fx+ i 1))) ;; representation of smallest positive number
((fx= i (compose-f16 0 30 1023))) ;; representation of largest finite number
(let* ((x (f16->double i))
(next-x (f16->double (+ i 1)))
(previous-x (f16->double (- i 1))))
(check i (double->f16 (+ x (* 0.5 (random-real) (- next-x x)))))
(check i (double->f16 (+ x (* 0.5 (random-real) (- previous-x x)))))
(if (even? i)
(begin
(check i (double->f16 (+ x (* 0.5 (- next-x x)))))
(check i (double->f16 (+ x (* 0.5 (- previous-x x)))))))))
;; i = 0
(let* ((i 0)
(x (f16->double i))
(next-x (f16->double (+ i 1)))) ;; no previous-x
(check i (double->f16 (+ x (* 0.5 (random-real) (- next-x x)))))
(check i (double->f16 (+ x (* 0.5 (- next-x x))))))
;; largest normal
(let* ((i (compose-f16 0 30 1023))
(x (f16->double i))
(previous-x (f16->double (- i 1)))) ;; no next-x
(check i (double->f16 (+ x (* 0.5 (random-real) (- previous-x x)))))
(check i (double->f16 (+ x (* 0.5 (random-real) (- x previous-x))))) ;; if next-x were finite, this would be the same
(check (+ i 1) (double->f16 (+ x (* 0.5 (- x previous-x)))))) ;; check that 1/2 the difference rounds up to +inf.0
)
|#
;;; This sample implementation does not implement the following.
(define f8-storage-class #f)
;;;
;;; Conceptually, an indexer is itself a 1-1 array that maps one interval to another; thus, it is
;;; an example of an array that can return multiple values.
;;;
;;; Rather than trying to formalize this idea, and trying to get it to work with array-map,
;;; array-fold, ..., we'll just manipulate the getter functions of these conceptual arrays.
;;;
;;; Indexers are 1-1 affine maps from one interval to another.
;;;
;;; The indexer field of a specialized-array obj is a 1-1 mapping from
;;;
;;; (array-domain obj)
;;;
;;; to [0, top), where top is
;;;
;;; ((storage-class-length (array-storage-class obj)) (array-body obj))
;;;
;; unfortunately, the next three functions were written by hand, so beware of bugs.
(define (%%indexer-0 base)
(if (eqv? base 0)
(lambda () 0) ;; Don't generate closure for common case.
(lambda () base)))
(define (%%indexer-1 base
low-0
increment-0)
(if (eqv? base 0)
(if (eqv? 0 low-0)
(cond ((eqv? 1 increment-0) (lambda (i) i))
;;((eqv? -1 increment-0) (lambda (i) (- i))) ;; an impossible case
(else (lambda (i) (* i increment-0))))
(cond ((eqv? 1 increment-0) (lambda (i) (- i low-0)))
;;((eqv? -1 increment-0) (lambda (i) (- low-0 i))) ;; an impossible case
(else (lambda (i) (* increment-0 (- i low-0))))))
(if (eqv? 0 low-0)
(cond ((eqv? 1 increment-0) (lambda (i) (+ base i)))
((eqv? -1 increment-0) (lambda (i) (- base i)))
(else (lambda (i) (+ base (* increment-0 i)))))
(cond ((eqv? 1 increment-0) (lambda (i) (+ base (- i low-0))))
((eqv? -1 increment-0) (lambda (i) (+ base (- low-0 i))))
(else (lambda (i) (+ base (* increment-0 (- i low-0)))))))))
(define (%%indexer-2 base
low-0 low-1
increment-0 increment-1)
(if (eqv? 0 base)
(if (eqv? 0 low-0)
(cond ((eqv? 1 increment-0)
(if (eqv? 0 low-1)
(cond ((eqv? 1 increment-1) (lambda (i j) (+ i j)))
((eqv? -1 increment-1) (lambda (i j) (+ i (- j))))
(else (lambda (i j) (+ i (* increment-1 j)))))
(cond ((eqv? 1 increment-1) (lambda (i j) (+ i (- j low-1))))
((eqv? -1 increment-1) (lambda (i j) (+ i (- low-1 j))))
(else (lambda (i j) (+ i (* increment-1 (- j low-1))))))))
#; ((eqv? -1 increment-0) ;; an impossible case
(if (eqv? 0 low-1)
(cond ((eqv? 1 increment-1) (lambda (i j) (- j i)))
((eqv? -1 increment-1) (lambda (i j) (- (- j) i)))
(else (lambda (i j) (- (* increment-1 j) i))))
(cond ((eqv? 1 increment-1) (lambda (i j) (- (- j low-1) i)))
((eqv? -1 increment-1) (lambda (i j) (- (- low-1 j) i)))
(else (lambda (i j) (- (* increment-1 (- j low-1)) i))))))
(else
(if (eqv? 0 low-1)
(cond ((eqv? 1 increment-1) (lambda (i j) (+ (* increment-0 i) j)))
((eqv? -1 increment-1) (lambda (i j) (+ (* increment-0 i) (- j))))
(else (lambda (i j) (+ (* increment-0 i) (* increment-1 j)))))
(cond ((eqv? 1 increment-1) (lambda (i j) (+ (* increment-0 i) (- j low-1))))
((eqv? -1 increment-1) (lambda (i j) (+ (* increment-0 i) (- low-1 j))))
(else (lambda (i j) (+ (* increment-0 i) (* increment-1 (- j low-1)))))))))
(cond ((eqv? 1 increment-0)
(if (eqv? 0 low-1)
(cond ((eqv? 1 increment-1) (lambda (i j) (+ (- i low-0) j)))
((eqv? -1 increment-1) (lambda (i j) (+ (- i low-0) (- j))))
(else (lambda (i j) (+ (- i low-0) (* increment-1 j)))))
(cond ((eqv? 1 increment-1) (lambda (i j) (+ (- i low-0) (- j low-1))))
((eqv? -1 increment-1) (lambda (i j) (+ (- i low-0) (- low-1 j))))
(else (lambda (i j) (+ (- i low-0) (* increment-1 (- j low-1))))))))
#;((eqv? -1 increment-0) ;; an impossible case
(if (eqv? 0 low-1)
(cond ((eqv? 1 increment-1) (lambda (i j) (- j (- i low-0))))
((eqv? -1 increment-1) (lambda (i j) (- (- j) (- i low-0))))
(else (lambda (i j) (- (* increment-1 j) (- i low-0)))))
(cond ((eqv? 1 increment-1) (lambda (i j) (- (- j low-1) (- i low-0))))
((eqv? -1 increment-1) (lambda (i j) (- (- low-1 j) (- i low-0))))
(else (lambda (i j) (- (* increment-1 (- j low-1)) (- i low-0)))))))
(else
(if (eqv? 0 low-1)
(cond ((eqv? 1 increment-1) (lambda (i j) (+ (* increment-0 (- i low-0)) j)))
((eqv? -1 increment-1) (lambda (i j) (+ (* increment-0 (- i low-0)) (- j))))
(else (lambda (i j) (+ (* increment-0 (- i low-0)) (* increment-1 j)))))
(cond ((eqv? 1 increment-1) (lambda (i j) (+ (* increment-0 (- i low-0)) (- j low-1))))
((eqv? -1 increment-1) (lambda (i j) (+ (* increment-0 (- i low-0)) (- low-1 j))))
(else (lambda (i j) (+ (* increment-0 (- i low-0)) (* increment-1 (- j low-1))))))))))
(if (eqv? 0 low-0)
(cond ((eqv? 1 increment-0)
(if (eqv? 0 low-1)
(cond ((eqv? 1 increment-1) (lambda (i j) (+ base i j)))
((eqv? -1 increment-1) (lambda (i j) (+ base i (- j))))
(else (lambda (i j) (+ base i (* increment-1 j)))))
(cond ((eqv? 1 increment-1) (lambda (i j) (+ base i (- j low-1))))
((eqv? -1 increment-1) (lambda (i j) (+ base i (- low-1 j))))
(else (lambda (i j) (+ base i (* increment-1 (- j low-1))))))))
((eqv? -1 increment-0)
(if (eqv? 0 low-1)
(cond ((eqv? 1 increment-1) (lambda (i j) (- (+ base j) i)))
((eqv? -1 increment-1) (lambda (i j) (- (- base j) i)))
(else (lambda (i j) (- (+ base (* increment-1 j)) i))))
(cond ((eqv? 1 increment-1) (lambda (i j) (- (+ base (- j low-1)) i)))
((eqv? -1 increment-1) (lambda (i j) (- (+ base (- low-1 j)) i)))
(else (lambda (i j) (- (+ base (* increment-1 (- j low-1))) i))))))
(else
(if (eqv? 0 low-1)
(cond ((eqv? 1 increment-1) (lambda (i j) (+ base (* increment-0 i) j)))
((eqv? -1 increment-1) (lambda (i j) (+ base (* increment-0 i) (- j))))
(else (lambda (i j) (+ base (* increment-0 i) (* increment-1 j)))))
(cond ((eqv? 1 increment-1) (lambda (i j) (+ base (* increment-0 i) (- j low-1))))
((eqv? -1 increment-1) (lambda (i j) (+ base (* increment-0 i) (- low-1 j))))
(else (lambda (i j) (+ base (* increment-0 i) (* increment-1 (- j low-1)))))))))
(cond ((eqv? 1 increment-0)
(if (eqv? 0 low-1)
(cond ((eqv? 1 increment-1) (lambda (i j) (+ base (- i low-0) j)))
((eqv? -1 increment-1) (lambda (i j) (+ base (- i low-0) (- j))))
(else (lambda (i j) (+ base (- i low-0) (* increment-1 j)))))
(cond ((eqv? 1 increment-1) (lambda (i j) (+ base (- i low-0) (- j low-1))))
((eqv? -1 increment-1) (lambda (i j) (+ base (- i low-0) (- low-1 j))))
(else (lambda (i j) (+ base (- i low-0) (* increment-1 (- j low-1))))))))
((eqv? -1 increment-0)
(if (eqv? 0 low-1)
(cond ((eqv? 1 increment-1) (lambda (i j) (- (+ base j) (- i low-0))))
((eqv? -1 increment-1) (lambda (i j) (- (- base j) (- i low-0))))
(else (lambda (i j) (- (+ base (* increment-1 j)) (- i low-0)))))
(cond ((eqv? 1 increment-1) (lambda (i j) (- (+ base (- j low-1)) (- i low-0))))
((eqv? -1 increment-1) (lambda (i j) (- (+ base (- low-1 j)) (- i low-0))))
(else (lambda (i j) (- (+ base (* increment-1 (- j low-1))) (- i low-0)))))))
(else
(if (eqv? 0 low-1)
(cond ((eqv? 1 increment-1) (lambda (i j) (+ base (* increment-0 (- i low-0)) j)))
((eqv? -1 increment-1) (lambda (i j) (+ base (* increment-0 (- i low-0)) (- j))))
(else (lambda (i j) (+ base (* increment-0 (- i low-0)) (* increment-1 j)))))
(cond ((eqv? 1 increment-1) (lambda (i j) (+ base (* increment-0 (- i low-0)) (- j low-1))))
((eqv? -1 increment-1) (lambda (i j) (+ base (* increment-0 (- i low-0)) (- low-1 j))))
(else (lambda (i j) (+ base (* increment-0 (- i low-0)) (* increment-1 (- j low-1))))))))))))
;;; after this we basically punt
(define (%%indexer-3 base
low-0 low-1 low-2
increment-0 increment-1 increment-2)
(if (and (eqv? 0 low-0)
(eqv? 0 low-1)
(eqv? 0 low-2))
(if (eqv? base 0)
(if (eqv? increment-2 1)
(lambda (i j k)
(+ (* increment-0 i)
(* increment-1 j)
k))
(lambda (i j k)
(+ (* increment-0 i)
(* increment-1 j)
(* increment-2 k))))
(if (eqv? increment-2 1)
(lambda (i j k)
(+ base
(* increment-0 i)
(* increment-1 j)
k))
(lambda (i j k)
(+ base
(* increment-0 i)
(* increment-1 j)
(* increment-2 k)))))
(if (eqv? base 0)
(if (eqv? increment-2 1)
(lambda (i j k)
(+ (* increment-0 (- i low-0))
(* increment-1 (- j low-1))
(- k low-2)))
(lambda (i j k)
(+ (* increment-0 (- i low-0))
(* increment-1 (- j low-1))
(* increment-2 (- k low-2)))))
(if (eqv? increment-2 1)
(lambda (i j k)
(+ base
(* increment-0 (- i low-0))
(* increment-1 (- j low-1))
(- k low-2)))
(lambda (i j k)
(+ base
(* increment-0 (- i low-0))
(* increment-1 (- j low-1))
(* increment-2 (- k low-2))))))))
(define (%%indexer-4 base
low-0 low-1 low-2 low-3
increment-0 increment-1 increment-2 increment-3)
(if (and (eqv? 0 low-0)
(eqv? 0 low-1)
(eqv? 0 low-2)
(eqv? 0 low-3))
(if (eqv? base 0)
(if (eqv? increment-3 1)
(lambda (i j k l)
(+ (* increment-0 i)
(* increment-1 j)
(* increment-2 k)
l))
(lambda (i j k l)
(+ (* increment-0 i)
(* increment-1 j)
(* increment-2 k)
(* increment-3 l))))
(if (eqv? increment-3 1)
(lambda (i j k l)
(+ base
(* increment-0 i)
(* increment-1 j)
(* increment-2 k)
l))
(lambda (i j k l)
(+ base
(* increment-0 i)
(* increment-1 j)
(* increment-2 k)
(* increment-3 l)))))
(if (eqv? base 0)
(if (eqv? increment-3 1)
(lambda (i j k l)
(+ (* increment-0 (- i low-0))
(* increment-1 (- j low-1))
(* increment-2 (- k low-2))
(- l low-3)))
(lambda (i j k l)
(+ (* increment-0 (- i low-0))
(* increment-1 (- j low-1))
(* increment-2 (- k low-2))
(* increment-3 (- l low-3)))))
(if (eqv? increment-3 1)
(lambda (i j k l)
(+ base
(* increment-0 (- i low-0))
(* increment-1 (- j low-1))
(* increment-2 (- k low-2))
(- l low-3)))
(lambda (i j k l)
(+ base
(* increment-0 (- i low-0))
(* increment-1 (- j low-1))
(* increment-2 (- k low-2))
(* increment-3 (- l low-3))))))))
(define (%%indexer-generic base lower-bounds increments)
(let ((result
(if (%%every (lambda (x) (eqv? x 0)) lower-bounds)
(lambda multi-index
(let loop ((result base)
(indices multi-index)
(increments increments))
(if (null? indices)
(if (null? increments)
result
(apply error "Wrong number of arguments passed to procedure " multi-index))
(if (null? increments)
(apply error "Wrong number of arguments passed to procedure " multi-index)
(loop (+ result (* (car increments) (car indices)))
(cdr indices)
(cdr increments))))))
(lambda multi-index
(let loop ((result base)
(indices multi-index)
(lower-bounds lower-bounds)
(increments increments))
(if (null? indices)
(if (null? increments)
result
(apply error "Wrong number of arguments passed to procedure " multi-index))
(if (null? increments)
(apply error "Wrong number of arguments passed to procedure " multi-index)
(loop (+ result (* (car increments)
(- (car indices)
(car lower-bounds))))
(cdr indices)
(cdr lower-bounds)
(cdr increments)))))))))
result))
;;;
;;; The default getter and the setter of a specialized-array a are given by
;;;
;;; (lambda (i_0 ... i_n-1)
;;; ((storage-class-getter (array-storage-class a))
;;; (array-body a)
;;; ((array-indexer a) i_0 ... i_n-1)))
;;;
;;; (lambda (v i_0 ... i_n-1)
;;; ((storage-class-setter (array-storage-class a))
;;; (array-body a)
;;; ((array-indexer a) i_0 ... i_n-1)
;;; v))
;;;
;;; The default initializer-value is
;;;
;;; (storage-class-default (array-storage-class a))
;;;
;;; The default body is
;;;
;;; ((storage-class-maker (array-storage-class a))
;;; (interval-volume domain)
;;; initializer-value)
;;;
;;; The default indexer is the mapping of
;;; the domain to the natural numbers in lexicographical order.
;;;
(declare (inline))
(define (specialized-array? obj)
(and (array? obj)
(not (eq? (%%array-body obj) #f))))
(define (array-body obj)
(cond ((not (specialized-array? obj))
(error "array-body: The argument is not a specialized array: " obj))
(else
(%%array-body obj))))
(define (array-indexer obj)
(cond ((not (specialized-array? obj))
(error "array-indexer: The argument is not a specialized array: " obj))
(else
(%%array-indexer obj))))
(define (array-storage-class obj)
(cond ((not (specialized-array? obj))
(error "array-storage-class: The argument is not a specialized array: " obj))
(else
(%%array-storage-class obj))))
(define (array-safe? obj)
(cond ((not (specialized-array? obj))
(error "array-safe?: The argument is not a specialized array: " obj))
(else
(%%array-safe? obj))))
(define (%%array-empty? array)
(%%interval-empty? (%%array-domain array)))
(define (array-empty? obj)
(cond ((not (array? obj))
(error "array-empty?: The argument is not an array: " obj))
(else
(%%array-empty? obj))))
(declare (not inline))
(define (%%compute-array-packed? domain indexer)
(or (%%interval-empty? domain)
(case (%%interval-dimension domain)
((0) #t)
((1) (let ((lower-0 (%%interval-lower-bound domain 0))
(upper-0 (%%interval-upper-bound domain 0)))
(let ((increment 1))
(or (eqv? 1 (- upper-0 lower-0))
(= increment
(- (indexer (+ lower-0 1))
(indexer lower-0)))))))
((2) (let ((lower-0 (%%interval-lower-bound domain 0))
(lower-1 (%%interval-lower-bound domain 1))
(upper-0 (%%interval-upper-bound domain 0))
(upper-1 (%%interval-upper-bound domain 1)))
(let ((increment 1))
(and (or (eqv? 1 (- upper-1 lower-1))
(= increment
(- (indexer lower-0 (+ lower-1 1))
(indexer lower-0 lower-1))))
(let ((increment (* increment (- upper-1 lower-1))))
(or (eqv? 1 (- upper-0 lower-0))
(= increment
(- (indexer (+ lower-0 1) lower-1)
(indexer lower-0 lower-1)))))))))
((3) (let ((lower-0 (%%interval-lower-bound domain 0))
(lower-1 (%%interval-lower-bound domain 1))
(lower-2 (%%interval-lower-bound domain 2))
(upper-0 (%%interval-upper-bound domain 0))
(upper-1 (%%interval-upper-bound domain 1))
(upper-2 (%%interval-upper-bound domain 2)))
(let ((increment 1))
(and (or (eqv? 1 (- upper-2 lower-2))
(= increment
(- (indexer lower-0 lower-1 (+ lower-2 1))
(indexer lower-0 lower-1 lower-2))))
(let ((increment (* increment (- upper-2 lower-2))))
(and (or (eqv? 1 (- upper-1 lower-1))
(= increment
(- (indexer lower-0 (+ lower-1 1) lower-2)
(indexer lower-0 lower-1 lower-2))))
(let ((increment (* increment (- upper-1 lower-1))))
(or (eqv? 1 (- upper-0 lower-0))
(= increment
(- (indexer (+ lower-0 1) lower-1 lower-2)
(indexer lower-0 lower-1 lower-2)))))))))))
((4) (let ((lower-0 (%%interval-lower-bound domain 0))
(lower-1 (%%interval-lower-bound domain 1))
(lower-2 (%%interval-lower-bound domain 2))
(lower-3 (%%interval-lower-bound domain 3))
(upper-0 (%%interval-upper-bound domain 0))
(upper-1 (%%interval-upper-bound domain 1))
(upper-2 (%%interval-upper-bound domain 2))
(upper-3 (%%interval-upper-bound domain 3)))
(let ((increment 1))
(and (or (eqv? 1 (- upper-3 lower-3))
(= increment
(- (indexer lower-0 lower-1 lower-2 (+ lower-3 1))
(indexer lower-0 lower-1 lower-2 lower-3))))
(let ((increment (* increment (- upper-3 lower-3))))
(and (or (eqv? 1 (- upper-2 lower-2))
(= increment
(- (indexer lower-0 lower-1 (+ lower-2 1) lower-3)
(indexer lower-0 lower-1 lower-2 lower-3))))
(let ((increment (* increment (- upper-2 lower-2))))
(and (or (eqv? 1 (- upper-1 lower-1))
(= increment
(- (indexer lower-0 (+ lower-1 1) lower-2 lower-3)
(indexer lower-0 lower-1 lower-2 lower-3))))
(let ((increment (* increment (- upper-1 lower-1))))
(or (eqv? 1 (- upper-0 lower-0))
(= increment
(- (indexer (+ lower-0 1) lower-1 lower-2 lower-3)
(indexer lower-0 lower-1 lower-2 lower-3)))))))))))))
;; The next part is not call/cc safe, but the only function we call is indexer,
;; and we calculate all specialized array indexers internally, and they don't call call/cc.
(else (let ((global-lowers
;; will use as an argument list
(%%interval-lower-bounds->list domain))
(global-lowers+1
;; will modify and use as an argument list
(%%interval-lower-bounds->list domain)))
(and
(let loop ((lowers global-lowers+1)
(uppers (%%interval-upper-bounds->list domain)))
;; returns either #f or the increment
;; that the difference of indexers must equal.
(if (null? lowers)
1 ;; increment
(let ((increment (loop (cdr lowers) (cdr uppers))))
(and increment
(or (and (eqv? 1 (- (car uppers) (car lowers)))
;; increment doesn't change
increment)
(begin
;; increment the correct index by 1
(set-car! lowers (+ (car lowers) 1))
(and (= (- (apply indexer global-lowers+1)
(apply indexer global-lowers))
increment)
(begin
;; set it back
(set-car! lowers (- (car lowers) 1))
;; multiply the increment by the difference in
;; the current upper and lower bounds and
;; return it.
(* increment (- (car uppers) (car lowers)))))))))))
;; return a proper boolean instead of the volume of the domain
#t))))))
(define (%%array-packed? array)
(let ((in-order? (%%array-in-order? array)))
(if (boolean? in-order?)
in-order?
(let ((in-order?
(%%compute-array-packed?
(%%array-domain array)
(%%array-indexer array))))
(%%array-in-order?-set! array in-order?)
in-order?))))
(define (array-packed? array)
(cond ((not (specialized-array? array))
(error "array-packed?: The argument is not a specialized array: " array))
(else
(%%array-packed? array))))
(define (%%finish-specialized-array domain storage-class body indexer mutable? safe? in-order?)
(let ((storage-class-getter (storage-class-getter storage-class))
(storage-class-setter (storage-class-setter storage-class))
(checker (storage-class-checker storage-class))
(indexer indexer)
(body body))
;;; we write the following three macros to specialize the setters and getters in the
;;; non-safe case to reduce one more function call.
(define-macro (expand-storage-class original-suffix replacement-suffix expr)
(define (symbol-append . args)
(string->symbol (apply string-append (map (lambda (x) (if (symbol? x) (symbol->string x) x)) args))))
(define (replace old-symbol new-symbol expr)
(let loop ((expr expr))
(cond ((pair? expr) ;; we don't use map because of dotted argument list in general setter
(cons (loop (car expr))
(loop (cdr expr))))
((eq? expr old-symbol)
new-symbol)
(else
expr))))
`(cond ,@(map (lambda (name prefix)
`((eq? storage-class ,(symbol-append name '-storage-class))
,(replace (symbol-append 'storage-class original-suffix)
(symbol-append prefix replacement-suffix)
expr)))
'(generic s8 u8 s16 u16 s32 u32 s64 u64 f32 f64 char)
'(vector s8vector u8vector s16vector u16vector s32vector u32vector s64vector u64vector f32vector f64vector string))
(else
;; There are conversion routines required for getters and setters of other standard storage classes.
,expr)))
(define-macro (expand-getters expr)
`(expand-storage-class -getter -ref ,expr))
(define-macro (expand-setters expr)
`(expand-storage-class -setter -set! ,expr))
(let ((getter
(cond ((%%interval-empty? domain)
(%%empty-getter domain))
(safe?
(case (%%interval-dimension domain)
((0) (lambda ()
(storage-class-getter body (indexer))))
((1) (lambda (i)
(cond ((not (exact-integer? i))
(error "array-getter: multi-index component is not an exact integer: " i))
((not (%%interval-contains-multi-index?-1 domain i))
(error "array-getter: domain does not contain multi-index: " domain i))
(else
(storage-class-getter body (indexer i))))))
((2) (lambda (i j)
(cond ((not (and (exact-integer? i)
(exact-integer? j)))
(error "array-getter: multi-index component is not an exact integer: " i j))
((not (%%interval-contains-multi-index?-2 domain i j))
(error "array-getter: domain does not contain multi-index: " domain i j))
(else
(storage-class-getter body (indexer i j))))))
((3) (lambda (i j k)
(cond ((not (and (exact-integer? i)
(exact-integer? j)
(exact-integer? k)))
(error "array-getter: multi-index component is not an exact integer: " i j k))
((not (%%interval-contains-multi-index?-3 domain i j k))
(error "array-getter: domain does not contain multi-index: " domain i j k))
(else
(storage-class-getter body (indexer i j k))))))
((4) (lambda (i j k l)
(cond ((not (and (exact-integer? i)
(exact-integer? j)
(exact-integer? k)
(exact-integer? l)))
(error "array-getter: multi-index component is not an exact integer: " i j k l))
((not (%%interval-contains-multi-index?-4 domain i j k l))
(error "array-getter: domain does not contain multi-index: " domain i j k l))
(else
(storage-class-getter body (indexer i j k l))))))
(else (lambda multi-index
(cond ((not (%%every (lambda (x) (exact-integer? x)) multi-index))
(apply error "array-getter: multi-index component is not an exact integer: " multi-index))
((not (fx= (%%interval-dimension domain) (length multi-index)))
(apply error "array-getter: multi-index is not the correct dimension: " domain multi-index))
((not (%%interval-contains-multi-index?-general domain multi-index))
(apply error "array-getter: domain does not contain multi-index: " domain multi-index))
(else
(storage-class-getter body (apply indexer multi-index))))))))
(else
(case (%%interval-dimension domain)
((0) (expand-getters (lambda () (storage-class-getter body (indexer)))))
((1) (expand-getters (lambda (i) (storage-class-getter body (indexer i)))))
((2) (expand-getters (lambda (i j) (storage-class-getter body (indexer i j)))))
((3) (expand-getters (lambda (i j k) (storage-class-getter body (indexer i j k)))))
((4) (expand-getters (lambda (i j k l) (storage-class-getter body (indexer i j k l)))))
(else (expand-getters (lambda multi-index (storage-class-getter body (apply indexer multi-index)))))))))
(setter
(and mutable?
(cond ((%%interval-empty? domain)
(%%empty-setter domain))
(safe?
(case (%%interval-dimension domain)
((0) (lambda (value)
(cond ((not (checker value))
(error "array-setter: value cannot be stored in body: " value))
(else
(storage-class-setter body (indexer) value)))))
((1) (lambda (value i)
(cond ((not (exact-integer? i))
(error "array-setter: multi-index component is not an exact integer: " i))
((not (%%interval-contains-multi-index?-1 domain i))
(error "array-setter: domain does not contain multi-index: " domain i))
((not (checker value))
(error "array-setter: value cannot be stored in body: " value))
(else
(storage-class-setter body (indexer i) value)))))
((2) (lambda (value i j)
(cond ((not (and (exact-integer? i)
(exact-integer? j)))
(error "array-setter: multi-index component is not an exact integer: " i j))
((not (%%interval-contains-multi-index?-2 domain i j))
(error "array-setter: domain does not contain multi-index: " domain i j))
((not (checker value))
(error "array-setter: value cannot be stored in body: " value))
(else
(storage-class-setter body (indexer i j) value)))))
((3) (lambda (value i j k)
(cond ((not (and (exact-integer? i)
(exact-integer? j)
(exact-integer? k)))
(error "array-setter: multi-index component is not an exact integer: " i j k))
((not (%%interval-contains-multi-index?-3 domain i j k))
(error "array-setter: domain does not contain multi-index: " domain i j k))
((not (checker value))
(error "array-setter: value cannot be stored in body: " value))
(else
(storage-class-setter body (indexer i j k) value)))))
((4) (lambda (value i j k l)
(cond ((not (and (exact-integer? i)
(exact-integer? j)
(exact-integer? k)
(exact-integer? l)))
(error "array-setter: multi-index component is not an exact integer: " i j k l))
((not (%%interval-contains-multi-index?-4 domain i j k l))
(error "array-setter: domain does not contain multi-index: " domain i j k l))
((not (checker value))
(error "array-setter: value cannot be stored in body: " value))
(else
(storage-class-setter body (indexer i j k l) value)))))
(else (lambda (value . multi-index)
(cond ((not (%%every (lambda (x) (exact-integer? x)) multi-index))
(apply error "array-setter: multi-index component is not an exact integer: " multi-index))
((not (fx= (%%interval-dimension domain) (length multi-index)))
(apply error "array-setter: multi-index is not the correct dimension: " domain multi-index))
((not (%%interval-contains-multi-index?-general domain multi-index))
(apply error "array-setter: domain does not contain multi-index: " domain multi-index))
((not (checker value))
(error "array-setter: value cannot be stored in body: " value))
(else
(storage-class-setter body (apply indexer multi-index) value)))))))
(else
(case (%%interval-dimension domain)
((0) (expand-setters (lambda (value) (storage-class-setter body (indexer) value) (void))))
((1) (expand-setters (lambda (value i) (storage-class-setter body (indexer i) value) (void))))
((2) (expand-setters (lambda (value i j) (storage-class-setter body (indexer i j) value) (void))))
((3) (expand-setters (lambda (value i j k) (storage-class-setter body (indexer i j k) value) (void))))
((4) (expand-setters (lambda (value i j k l) (storage-class-setter body (indexer i j k l) value) (void))))
(else (expand-setters (lambda (value . multi-index) (storage-class-setter body (apply indexer multi-index) value) (void))))))))))
(make-%%array domain
getter
setter
storage-class
body
indexer
safe?
in-order?))))
(define (%%interval->basic-indexer interval)
(case (%%interval-dimension interval)
((0) (%%indexer-0 0))
((1) (let ((low-0 (%%interval-lower-bound interval 0))
(increment-0 1))
(%%indexer-1 0 low-0 increment-0)))
((2) (let* ((low-0 (%%interval-lower-bound interval 0))
(low-1 (%%interval-lower-bound interval 1))
(increment-1 1)
(increment-0 (* increment-1 (%%interval-width interval 1))))
(%%indexer-2 0
low-0 low-1
increment-0 increment-1)))
((3) (let* ((low-0 (%%interval-lower-bound interval 0))
(low-1 (%%interval-lower-bound interval 1))
(low-2 (%%interval-lower-bound interval 2))
(increment-2 1)
(increment-1 (* increment-2 (%%interval-width interval 2)))
(increment-0 (* increment-1 (%%interval-width interval 1))))
(%%indexer-3 0
low-0 low-1 low-2
increment-0 increment-1 increment-2)))
((4) (let* ((low-0 (%%interval-lower-bound interval 0))
(low-1 (%%interval-lower-bound interval 1))
(low-2 (%%interval-lower-bound interval 2))
(low-3 (%%interval-lower-bound interval 3))
(increment-3 1)
(increment-2 (* increment-3 (%%interval-width interval 3)))
(increment-1 (* increment-2 (%%interval-width interval 2)))
(increment-0 (* increment-1 (%%interval-width interval 1))))
(%%indexer-4 0
low-0 low-1 low-2 low-3
increment-0 increment-1 increment-2 increment-3)))
(else
(do ((widths
(reverse (vector->list (%%interval-widths interval)))
(cdr widths))
(increments
(list 1)
(cons (* (car increments) (car widths))
increments)))
((null? (cdr widths))
(%%indexer-generic 0 (%%interval-lower-bounds->list interval) increments))))))
(define (%%make-specialized-array interval
storage-class
initial-value
;; must be mutable
safe?)
(let* ((body ((storage-class-maker storage-class)
(%%interval-volume interval)
initial-value))
(indexer (%%interval->basic-indexer interval)))
(%%finish-specialized-array interval
storage-class
body
indexer
#t ;; mutable?
safe?
#t))) ;; new arrays are always in order
(define (make-specialized-array-from-data data
#!optional
(storage-class generic-storage-class)
(mutable? (specialized-array-default-mutable?))
(safe? (specialized-array-default-safe?)))
(cond ((not (boolean? safe?))
(error "make-specialized-array-from-data: The fourth argument is not a boolean: " data storage-class mutable? safe?))
((not (boolean? mutable?))
(error "make-specialized-array-from-data: The third argument is not a boolean: " data storage-class mutable?))
((not (storage-class? storage-class))
(error "make-specialized-array-from-data: The second argument is not a storage class: " data storage-class))
((not ((storage-class-data? storage-class) data))
(error "make-specialized-array-from-data: The first argument is not compatible with the storage class: " data))
((and mutable?
(not (##mutable? data)))
(error "make-specialized-array-from-data: Cannot make mutable array from immutable data: " data storage-class mutable? safe?))
(else
(%%make-specialized-array-from-data data storage-class mutable? safe?))))
(define (%%make-specialized-array-from-data data storage-class mutable? safe?)
(let* ((body
((storage-class-data->body storage-class) data))
(indexer
(lambda (i) i))
(domain
(make-interval (vector ((storage-class-length storage-class) body)))))
(%%finish-specialized-array domain
storage-class
body
indexer
mutable?
safe?
#t))) ;; this array is in order by definition
(define (%%list*->array dimension nested-list storage-class mutable? safe? caller)
(define (check-nested-list dimension nested-data)
(or (eqv? dimension 0) ;; anything goes in dimension 0
(and (list? nested-data)
(let ((len (length nested-data)))
(cond ((eqv? len 0)
'())
((eqv? dimension 1)
(list len))
(else
(let* ((sublists
(map (lambda (l)
(check-nested-list (fx- dimension 1) l))
nested-data))
(first
(car sublists)))
(and first
(%%every (lambda (l)
(equal? first l))
(cdr sublists))
(cons len first)))))))))
(define (nested-list->array dimension nested-data)
(case dimension
((0)
(%!array-copy (make-array (make-interval '#()) (lambda () nested-data))
storage-class
mutable?
safe?
caller
#f))
((1)
(%%list->array (make-interval (vector (length nested-data)))
nested-data
storage-class
mutable?
safe?
caller))
(else
(if (null? nested-data)
(let ((result (%%make-specialized-array (make-interval (make-vector dimension 0))
storage-class
(storage-class-default storage-class) ;; never used
safe?)))
(if (not mutable?)
(%%array-freeze! result)
result))
(%%%array-stack 0 ;; the new dimension is always the first
(map (lambda (l)
(nested-list->array (fx- dimension 1) l))
nested-data)
storage-class
mutable?
safe?
caller
#f))))) ;; already call/cc-safe
(if (check-nested-list dimension nested-list)
(nested-list->array dimension nested-list)
(error (string-append caller
"The second argument is not the right shape to be converted to an array of the given dimension: ")
dimension nested-list)))
(define (list*->array dimension
nested-data
#!optional
(storage-class generic-storage-class)
(mutable? (specialized-array-default-mutable?))
(safe? (specialized-array-default-safe?)))
(cond ((not (boolean? safe?))
(error "list*->array: The fifth argument is not a boolean: " dimension nested-data storage-class mutable? safe?))
((not (boolean? mutable?))
(error "list*->array: The fourth argument is not a boolean: " dimension nested-data storage-class mutable?))
((not (storage-class? storage-class))
(error "list*->array: The third argument is not a storage class: " dimension nested-data storage-class))
((not (and (fixnum? dimension)
(fx<= 0 dimension)))
(error "list*->array: The first argument is not a nonnegative fixnum: " dimension nested-data))
(else
(%%list*->array dimension nested-data storage-class mutable? safe? "list*->array: "))))
(define (%%vector*->array dimension nested-vector storage-class mutable? safe? caller)
(define (check-nested-vector dimension nested-data)
(or (eqv? dimension 0) ;; anything goes in dimension 0
(and (vector? nested-data)
(let ((len (vector-length nested-data)))
(cond ((eqv? len 0)
'())
((eqv? dimension 1)
(list len))
(else
(let* ((sublists
(vector-map (lambda (l)
(check-nested-vector (fx- dimension 1) l))
nested-data))
(first
(vector-ref sublists 0)))
(and first
(%%vector-every (lambda (l)
(equal? first l))
sublists)
(cons len first)))))))))
(define (nested-vector->array dimension nested-data)
(case dimension
((0)
(%!array-copy (make-array (make-interval '#()) (lambda () nested-data))
storage-class
mutable?
safe?
caller
#f))
((1)
(let ((generic-array
(%%make-specialized-array-from-data nested-data generic-storage-class mutable? safe?))) ;; data is always a generic-vector
(%!array-copy generic-array
storage-class
mutable?
safe?
caller
#f)))
(else
(if (eqv? (vector-length nested-data) 0)
(let ((result (make-specialized-array (make-interval (make-vector dimension 0))
storage-class
(storage-class-default storage-class) ;; never used
safe?)))
(if (not mutable?)
(%%array-freeze! result)
result))
(%%%array-stack 0 ;; the new dimension is always the first
(map (lambda (l)
(nested-vector->array (fx- dimension 1) l))
(vector->list nested-data))
storage-class
mutable?
safe?
caller
#f))))) ;; already call/cc-safe
(if (check-nested-vector dimension nested-vector)
(nested-vector->array dimension nested-vector)
(error (string-append caller "The second argument is not the right shape to be converted to an array of the given dimension: ") dimension nested-vector)))
(define (vector*->array dimension
nested-data
#!optional
(storage-class generic-storage-class)
(mutable? (specialized-array-default-mutable?))
(safe? (specialized-array-default-safe?)))
(cond ((not (boolean? safe?))
(error "vector*->array: The fifth argument is not a boolean: " dimension nested-data storage-class mutable? safe?))
((not (boolean? mutable?))
(error "vector*->array: The fourth argument is not a boolean: " dimension nested-data storage-class mutable?))
((not (storage-class? storage-class))
(error "vector*->array: The third argument is not a storage class: " dimension nested-data storage-class))
((not (and (fixnum? dimension)
(fx<= 0 dimension)))
(error "vector*->array: The first argument is not a nonnegative fixnum: " dimension nested-data))
(else
(%%vector*->array dimension nested-data storage-class mutable? safe? "vector*->array: "))))
(define make-specialized-array
(let ()
(define (one-arg interval storage-class initial-value safe?)
(cond ((not (interval? interval))
(error "make-specialized-array: The first argument is not an interval: "
interval))
(else
(%%make-specialized-array interval
storage-class
initial-value
safe?))))
(define (two-args interval storage-class initial-value safe?)
(cond ((not (storage-class? storage-class))
(error "make-specialized-array: The second argument is not a storage-class: "
interval storage-class))
(else
(one-arg interval
storage-class
(storage-class-default storage-class)
safe?))))
(define (three-args interval storage-class initial-value safe?)
(cond ((not (storage-class? storage-class))
(error "make-specialized-array: The second argument is not a storage-class: "
interval storage-class initial-value))
((not ((storage-class-checker storage-class) initial-value))
(error "make-specialized-array: The third argument cannot be manipulated by the second (a storage class): "
interval storage-class initial-value))
(else
(one-arg interval ;; calls one-arg directly, not two-args
storage-class
initial-value
safe?))))
(define (four-args interval storage-class initial-value safe?)
(cond ((not (boolean? safe?))
(error "make-specialized-array: The fourth argument is not a boolean: "
interval storage-class initial-value safe?))
(else
(three-args interval
storage-class
initial-value
safe?))))
(case-lambda
((interval)
(one-arg interval
generic-storage-class
(storage-class-default generic-storage-class)
(specialized-array-default-safe?)))
((interval storage-class)
(two-args interval
storage-class
'ignore
(specialized-array-default-safe?)))
((interval storage-class initial-value)
(three-args interval
storage-class
initial-value
(specialized-array-default-safe?)))
((interval storage-class initial-value safe?)
(four-args interval
storage-class
initial-value
safe?)))))
(define %%storage-class-compatibility-alist
;; An a-list of compatible storage-classes;
;; in each list, members of the first storage class can be
;; stored without error in all storage classes in the list.
;; We're going to test separately for generic-storage-class,
;; so we can deal gracefully with storing data from
;; a user-defined storage-class to generic-storage-class
;; without running the checker for generic-storage-class
;; (which always returns #t)
(list
(list u1-storage-class
u8-storage-class
u16-storage-class
u32-storage-class
u64-storage-class
s8-storage-class
s16-storage-class
s32-storage-class
s64-storage-class)
(list u8-storage-class
u16-storage-class
u32-storage-class
u64-storage-class
s16-storage-class
s32-storage-class
s64-storage-class)
(list u16-storage-class
u32-storage-class
u64-storage-class
s32-storage-class
s64-storage-class)
(list u32-storage-class
u64-storage-class
s64-storage-class)
(list u64-storage-class)
(list s8-storage-class
s16-storage-class
s32-storage-class
s64-storage-class)
(list s16-storage-class
s32-storage-class
s64-storage-class)
(list s32-storage-class
s64-storage-class)
(list s64-storage-class)
(list f16-storage-class
f32-storage-class
f64-storage-class)
(list f32-storage-class ;; the checkers for these classes are the same, no point in checking
f64-storage-class ;; going from f32-storage-class to f16-storage-class
f16-storage-class)
(list f64-storage-class ;; the checkers for these classes are the same, no point in checking
f32-storage-class ;; going from f64-storage-class to f32-storage-class or f16-storage-class
f16-storage-class)
(list char-storage-class)
(list c64-storage-class
c128-storage-class)
(list c128-storage-class ;; the checker for these classes are the same, no point in checking
c64-storage-class))) ;; going from c128-storage-class to c64-storage-class
;;; We consolidate all moving of array elements to the following procedure.
#;(define %%test-moves '()) ;; TODO: REMOVE AFTER TESTING
(define (%%move-array-elements destination source caller)
;; Here's the logic:
;; We require the source and destination to have the same number of elements.
;; If destination is a specialized array
;; then
;; If its elements are in order
;; and the source is a specialized array
;; then
;; If the source has the same storage class
;; for which a copier exists
;; and whose elements are also in order
;; then
;; do a block copy
;; else
;; if no checks are needed
;; then
;; step through the cells of the destination in order,
;; storing the source elements
;; else
;; step through the cells of the destination in order,
;; storing the source elements after testing they're OK
;; for the destination
;; else
;; If no checks are needed
;; then
;; Copy elements from the source to destination, without checks.
;; else
;; Copy elements from the source to destination, checking whether
;; they're OK
;; else
;; Copy elements of source to destination
;; We check the whether the elements of the destination are in order to save
;; a bit of array indexing (or perhaps to a block copy, which is even better).
;; We check that the elements we move to the destination are OK for the
;; destination because if we don't catch errors here they can be very tricky to find.
;; We'll put this here temporarily because we know these
;; algorithms are not call/cc safe. We'll decide later
;; whether there are some circumstances when we want to
;; use these on generalized arrays.
;; TODO
;; REMOVE BEFORE RELEASE
#;(if (not (or (specialized-array? source)
(member caller %%test-moves)))
(set! %%test-moves (cons caller %%test-moves)))
(cond ((not (%%interval= (%%array-domain source)
(%%array-domain destination)))
(error (string-append
caller
"Arrays must have the same domains: ")
destination source))
((%%interval-empty? (%%array-domain source))
"Empty arrays")
((specialized-array? destination)
(if (and (%%array-packed? destination)
(specialized-array? source))
;; Maybe we can do a block copy
(if (and (eq? (%%array-storage-class destination)
(%%array-storage-class source))
;; does a copier for this storage-class exist?
(storage-class-copier (%%array-storage-class destination))
(%%array-packed? source))
;; do a block copy
(begin
(if (not (%%interval-empty? (%%array-domain source)))
(let* ((source-indexer
(%%array-indexer source))
(destination-indexer
(%%array-indexer destination))
(copier
(storage-class-copier (%%array-storage-class source)))
(initial-destination-index
(%%interval-lower-bounds->list (%%array-domain destination)))
(destination-start
(apply destination-indexer initial-destination-index))
(initial-source-index
(%%interval-lower-bounds->list (%%array-domain source)))
(source-start
(apply source-indexer initial-source-index))
(source-end
(fx+ source-start (%%interval-volume (%%array-domain source)))))
(copier (%%array-body destination)
destination-start
(%%array-body source)
source-start
source-end)))
"Block copy")
;; We can step through the elements of destination in order,
;; and the getter of the source doesn't capture any continuations.
(let* ((domain
(%%array-domain source))
(getter
(%%array-getter source))
(destination-storage-class
(%%array-storage-class destination))
(initial-offset
(apply (%%array-indexer destination)
(%%interval-lower-bounds->list (%%array-domain destination)))))
(cond ((eq? destination-storage-class generic-storage-class)
;; No checks needed, storage-class-setter is vector-set!
(let ((body (%%array-body destination)))
(%%interval-for-each
(case (%%interval-dimension domain)
((0) (let ((index initial-offset))
(lambda ()
(vector-set! body index (getter))
(set! index (fx+ index 1))))) ;; not necessary
((1) (let ((index initial-offset))
(lambda (i)
(vector-set! body index (getter i))
(set! index (fx+ index 1)))))
((2) (let ((index initial-offset))
(lambda (i j)
(vector-set! body index (getter i j))
(set! index (fx+ index 1)))))
((3) (let ((index initial-offset))
(lambda (i j k)
(vector-set! body index (getter i j k))
(set! index (fx+ index 1)))))
((4) (let ((index initial-offset))
(lambda (i j k l)
(vector-set! body index (getter i j k l))
(set! index (fx+ index 1)))))
(else (let ((index initial-offset))
(lambda multi-index
(vector-set! body index (apply getter multi-index))
(set! index (fx+ index 1))))))
domain))
"In order, no checks needed, generic-storage-class")
((or (eq? (%%array-storage-class source)
destination-storage-class)
(let ((compatibility-list
(assq (%%array-storage-class source)
%%storage-class-compatibility-alist)))
(and compatibility-list
(memq destination-storage-class
compatibility-list))))
;; No checks needed
(let ((setter (storage-class-setter destination-storage-class))
(body (%%array-body destination)))
(%%interval-for-each
(case (%%interval-dimension domain)
((0) (let ((index initial-offset))
(lambda ()
(setter body index (getter))
(set! index (fx+ index 1))))) ;; not necessary
((1) (let ((index initial-offset))
(lambda (i)
(setter body index (getter i))
(set! index (fx+ index 1)))))
((2) (let ((index initial-offset))
(lambda (i j)
(setter body index (getter i j))
(set! index (fx+ index 1)))))
((3) (let ((index initial-offset))
(lambda (i j k)
(setter body index (getter i j k))
(set! index (fx+ index 1)))))
((4) (let ((index initial-offset))
(lambda (i j k l)
(setter body index (getter i j k l))
(set! index (fx+ index 1)))))
(else (let ((index initial-offset))
(lambda multi-index
(setter body index (apply getter multi-index))
(set! index (fx+ index 1))))))
domain))
"In order, no checks needed")
(else
;; checks needed
(let ((checker
(storage-class-checker destination-storage-class))
(body
(%%array-body destination))
(setter
(storage-class-setter destination-storage-class)))
(%%interval-for-each
(case (%%interval-dimension domain)
((0)
(let ((index initial-offset))
(lambda ()
(let ((item (getter)))
(if (checker item)
(begin
(setter body index item)
(set! index (fx+ index 1))) ;; not necessary
(error
(string-append
caller
"Not all elements of the source can be stored in destination: ")
destination source item))))))
((1)
(let ((index initial-offset))
(lambda (i)
(let ((item (getter i)))
(if (checker item)
(begin
(setter body index item)
(set! index (fx+ index 1)))
(error
(string-append
caller
"Not all elements of the source can be stored in destination: ")
destination source i item))))))
((2)
(let ((index initial-offset))
(lambda (i j)
(let ((item (getter i j)))
(if (checker item)
(begin
(setter body index item)
(set! index (fx+ index 1)))
(error
(string-append
caller
"Not all elements of the source can be stored in destination: ")
destination source i j item))))))
((3)
(let ((index initial-offset))
(lambda (i j k)
(let ((item (getter i j k)))
(if (checker item)
(begin
(setter body index item)
(set! index (fx+ index 1)))
(error
(string-append
caller
"Not all elements of the source can be stored in destination: ")
destination source i j k item) )))))
((4)
(let ((index initial-offset))
(lambda (i j k l)
(let ((item (getter i j k l)))
(if (checker item)
(begin
(setter body index item)
(set! index (fx+ index 1)))
(error
(string-append
caller
"Not all elements of the source can be stored in destination: ")
destination source i j k l item))))))
(else
(let ((index initial-offset))
(lambda multi-index
(let ((item (apply getter multi-index)))
(if (checker item)
(begin
(setter body index item)
(set! index (fx+ index 1)))
(apply
error
(string-append
caller
"Not all elements of the source can be stored in destination: ")
destination source (append multi-index (list item)))))))))
domain))
"In order, checks needed"))))
;; Either the elements of destination are not in order, or source is not a specialized array.
(let* ((setter
(%%array-setter destination))
(getter
(%%array-getter source))
(destination-storage-class
(%%array-storage-class destination))
(checker
(storage-class-checker destination-storage-class))
(domain
(%%array-domain destination)))
(cond ((or (eq? destination-storage-class generic-storage-class)
(and (specialized-array? source)
(or (eq? (%%array-storage-class source) destination-storage-class)
(let ((compatibility-list
(assq (%%array-storage-class source)
%%storage-class-compatibility-alist)))
(and compatibility-list
(memq destination-storage-class
compatibility-list))))))
;; no checks needed
(%%interval-for-each
(case (%%interval-dimension domain)
((0) (lambda ()
(setter (getter))))
((1) (lambda (i)
(setter (getter i) i)))
((2) (lambda (i j)
(setter (getter i j) i j)))
((3) (lambda (i j k)
(setter (getter i j k) i j k)))
((4) (lambda (i j k l)
(setter (getter i j k l) i j k l)))
(else
(lambda multi-index
(apply setter (apply getter multi-index) multi-index))))
domain)
"No checks needed")
(else
;; checks needed
(%%interval-for-each
(case (%%interval-dimension domain)
((0)
(lambda ()
(let ((item (getter)))
(if (checker item)
(setter item)
(error
(string-append
caller
"Not all elements of the source can be stored in destination: ")
destination source item)))))
((1)
(lambda (i)
(let ((item (getter i)))
(if (checker item)
(setter item i)
(error
(string-append
caller
"Not all elements of the source can be stored in destination: ")
destination source i item)))))
((2)
(lambda (i j)
(let ((item (getter i j)))
(if (checker item)
(setter item i j)
(error
(string-append
caller
"Not all elements of the source can be stored in destination: ")
destination source i j item)))))
((3)
(lambda (i j k)
(let ((item (getter i j k)))
(if (checker item)
(setter item i j k)
(error
(string-append
caller
"Not all elements of the source can be stored in destination: ")
destination source i j k item)))))
((4)
(lambda (i j k l)
(let ((item (getter i j k l)))
(if (checker item)
(setter item i j k l)
(error
(string-append
caller
"Not all elements of the source can be stored in destination: ")
destination source i j k l item)))))
(else
(lambda multi-index
(let ((item (apply getter multi-index)))
(if (checker item)
(apply setter item multi-index)
(apply
error
(string-append
caller
"Not all elements of the source can be stored in destination: ")
destination source (append multi-index (list item))))))))
domain)
"Checks needed")))))
(else
;; destination is not a specialized array, so checks,
;; if any, are built into the setter.
(let ((setter
(%%array-setter destination))
(getter
(%%array-getter source))
(domain
(%%array-domain destination)))
(%%interval-for-each
(case (%%interval-dimension domain)
((0) (lambda ()
(setter (getter))))
((1) (lambda (i)
(setter (getter i)
i)))
((2) (lambda (i j)
(setter (getter i j)
i j)))
((3) (lambda (i j k)
(setter (getter i j k)
i j k)))
((4) (lambda (i j k l)
(setter (getter i j k l)
i j k l)))
(else
(lambda multi-index
(apply setter
(apply getter multi-index)
multi-index))))
domain)
"Destination not specialized array")))
;; %%move-array-elements returns a string that designates
;; the copying method it used.
;; Calling functions should return something useful.
)
;;;
;;; The domain of the result is the same as the domain of the argument.
;;;
;;; Builds a new specialized-array and populates the body of the result with
;;; (array-getter array) applied to the elements of (array-domain array)
(define (%%generalized-array->specialized-array array storage-class mutable? safe? caller)
(let* ((domain (%%array-domain array))
(reversed-elements (%%array->reversed-list array))
(n (%%interval-volume domain))
(body ((storage-class-maker storage-class) n (storage-class-default storage-class)))
(indexer (%%interval->basic-indexer domain))
(setter (storage-class-setter storage-class))
(checker (storage-class-checker storage-class)))
(if (eq? storage-class generic-storage-class)
(let loop ((i (fx- n 1))
(l reversed-elements))
(if (fx<= 0 i)
(begin
(vector-set! body i (car l))
(loop (fx- i 1)
(cdr l)))
(%%finish-specialized-array domain
storage-class
body
indexer
mutable?
safe?
#t)))
(let loop ((i (fx- n 1))
(l reversed-elements))
(if (fx<= 0 i)
(if (checker (car l))
(begin
(setter body i (car l))
(loop (fx- i 1)
(cdr l)))
(error (string-append caller "Not all elements of the source can be stored in destination: ") array storage-class mutable? safe?))
(%%finish-specialized-array domain
storage-class
body
indexer
mutable?
safe?
#t))))))
(define (%%->specialized-array array storage-class caller)
(if (specialized-array? array)
array
(%%generalized-array->specialized-array array storage-class #f #f caller)))
(define (%!array-copy array
result-storage-class
mutable?
safe?
caller
call/cc-safe?)
(if (or (specialized-array? array)
(not call/cc-safe?))
(let ((result (%%make-specialized-array (%%array-domain array)
result-storage-class
(storage-class-default result-storage-class)
safe?)))
(%%move-array-elements result array caller)
(if (not mutable?) ;; set the setter to #f if the final array is not mutable
(%%array-freeze! result)
result))
(%%generalized-array->specialized-array array
result-storage-class
mutable?
safe?
caller)))
(define (%%make-array-copy call/cc-safe?)
(define caller
(if call/cc-safe?
"array-copy: "
"array-copy!: "))
(define (wrap error-reason)
(string-append caller error-reason))
(define (four-args array result-storage-class mutable? safe?)
(if (not (boolean? safe?))
(error (wrap "The fourth argument is not a boolean: ") safe?)
(three-args array
result-storage-class
mutable?
safe?)))
(define (three-args array result-storage-class mutable? safe?)
(if (not (boolean? mutable?))
(error (wrap "The third argument is not a boolean: ") mutable?)
(two-args array
result-storage-class
mutable?
safe?)))
(define (two-args array result-storage-class mutable? safe?)
(if (not (storage-class? result-storage-class))
(error (wrap "The second argument is not a storage-class: ") result-storage-class)
(one-arg array
result-storage-class
mutable?
safe?)))
(define (one-arg array result-storage-class mutable? safe?)
(if (not (array? array))
(error (wrap "The first argument is not an array: ") array)
(%!array-copy array
result-storage-class
mutable?
safe?
caller
call/cc-safe?)))
(case-lambda
((array)
(if (specialized-array? array)
(one-arg array
(%%array-storage-class array)
(mutable-array? array)
(%%array-safe? array))
(one-arg array
generic-storage-class
(specialized-array-default-mutable?)
(specialized-array-default-safe?))))
((array storage-class)
(if (specialized-array? array)
(two-args array
storage-class
(mutable-array? array)
(%%array-safe? array))
(two-args array
storage-class
(specialized-array-default-mutable?)
(specialized-array-default-safe?))))
((array storage-class mutable?)
(if (specialized-array? array)
(three-args array
storage-class
mutable?
(%%array-safe? array))
(three-args array
storage-class
mutable?
(specialized-array-default-safe?))))
((array storage-class mutable? safe?)
(four-args array
storage-class
mutable?
safe?))))
(define array-copy (%%make-array-copy #t))
(define array-copy! (%%make-array-copy #f))
;;;
;;; In the next function, old-indexer is an affine 1-1 mapping from an interval to [0,N), for some N.
;;;
;;; new-domain->old-domain is an affine 1-1 mapping from new-domain to the domain of old-indexer.
;;;
(define (%%compose-indexers old-indexer new-domain new-domain->old-domain)
(define (compute-multi-indices lowers uppers)
(if (null? lowers)
(list lowers)
(let* ((temp (compute-multi-indices (cdr lowers) (cdr uppers)))
(lower (car lowers))
(upper (car uppers))
(next-index (+ lower 1)))
;; returns all lowers first, then list of multi-indices where one
;; of the lowers is incremented if possible while staying in the domain.
(cons (cons lower (car temp))
(cons (cons (if (< next-index upper)
next-index
lower)
(car temp))
(map (lambda (multi-index)
(cons lower multi-index))
(cdr temp)))))))
(if (%%interval-empty? new-domain)
(lambda args
(error "%%compose-indexers: indexer on empty interval should never be called: "
old-indexer new-domain new-domain->old-domain))
(let* ((lowers
(%%interval-lower-bounds->list new-domain))
(uppers
(%%interval-upper-bounds->list new-domain))
(multi-indices
(compute-multi-indices lowers uppers))
(computed-offsets-for-multi-indices
(map (lambda (multi-index)
(call-with-values
(lambda ()
(apply new-domain->old-domain multi-index))
old-indexer))
multi-indices))
(base
(car computed-offsets-for-multi-indices))
(increments
(map (lambda (v)
(- v base))
(cdr computed-offsets-for-multi-indices))))
(case (%%interval-dimension new-domain)
((0) (%%indexer-0 base))
((1) (%%indexer-1 base
(car lowers)
(car increments)))
((2) (%%indexer-2 base
(car lowers) (cadr lowers)
(car increments) (cadr increments)))
((3) (%%indexer-3 base
(car lowers) (cadr lowers) (caddr lowers)
(car increments) (cadr increments) (caddr increments)))
((4) (%%indexer-4 base
(car lowers) (cadr lowers) (caddr lowers) (cadddr lowers)
(car increments) (cadr increments) (caddr increments) (cadddr increments)))
(else
(%%indexer-generic base lowers increments))))))
;;; You want to share the backing store of array.
;;;
;;; So you specify a new domain and an affine 1-1 mapping from the new-domain to the old-domain.
(define (%%specialized-array-share array
new-domain
new-domain->old-domain
#!optional
(in-order? %%order-unknown))
(let ((old-domain (%%array-domain array))
(old-indexer (%%array-indexer array))
(body (%%array-body array))
(storage-class (%%array-storage-class array)))
(%%finish-specialized-array new-domain
storage-class
body
(%%compose-indexers old-indexer new-domain new-domain->old-domain)
(mutable-array? array)
(%%array-safe? array)
in-order?)))
(define (specialized-array-share array
new-domain
new-domain->old-domain)
(cond ((not (specialized-array? array))
(error "specialized-array-share: The first argument is not a specialized-array: "
array new-domain new-domain->old-domain))
((not (interval? new-domain))
(error "specialized-array-share: The second argument is not an interval: "
array new-domain new-domain->old-domain))
((not (procedure? new-domain->old-domain))
(error "specialized-array-share: The third argument is not a procedure: "
array new-domain new-domain->old-domain))
((not (<= (%%interval-volume new-domain)
(%%interval-volume (%%array-domain array))))
;; If new-domain->old-domain is a 1-1 map, then the volume of
;; the new-domain must have no more elements than old-domain
(error "specialized-array-share: The second argument (a domain) has more elements than the domain of the first argument (an array): " array new-domain new-domain->old-domain))
(else
(%%specialized-array-share array
new-domain
new-domain->old-domain))))
(define (%%immutable-array-extract array new-domain)
(make-array new-domain
(%%array-getter array)))
(define (%%mutable-array-extract array new-domain)
(make-array new-domain
(%%array-getter array)
(%%array-setter array)))
(define (%%specialized-array-extract array new-domain)
;; (%%specialized-array-share array new-domain values)
;; We can speed this by calling make-%%array directly,
;; and so avoid a call to %%compose-indexers with values as
;; new-domain->old-domain and avoid the computation of the
;; new indexer, getter, and setter.
(make-%%array new-domain
(if (%%interval-empty? new-domain)
(%%empty-getter new-domain)
(%%array-getter array))
(and (%%array-setter array) ;; If array has no setter, then don't add one to extracted array
(if (%%interval-empty? new-domain)
(%%empty-setter new-domain)
(%%array-setter array)))
(%%array-storage-class array)
(%%array-body array)
(%%array-indexer array)
(%%array-safe? array)
%%order-unknown))
(define (%%array-extract array new-domain)
(cond ((specialized-array? array)
(%%specialized-array-extract array new-domain))
((mutable-array? array)
(%%mutable-array-extract array new-domain))
(else
(%%immutable-array-extract array new-domain))))
(define (array-extract array new-domain)
(cond ((not (array? array))
(error "array-extract: The first argument is not an array: " array new-domain))
((not (interval? new-domain))
(error "array-extract: The second argument is not an interval: " array new-domain))
((not (fx= (%%array-dimension array)
(%%interval-dimension new-domain)))
(error "array-extract: The dimension of the second argument (an interval) does not equal the dimension of the domain of the first argument (an array): " array new-domain))
((not (%%interval-subset? new-domain (%%array-domain array)))
(error "array-extract: The second argument (an interval) is not a subset of the domain of the first argument (an array): " array new-domain))
(else
(%%array-extract array new-domain))))
(define (array-tile A slice-widths)
(define (%%vector-fold-left op id v)
(let ((n (vector-length v)))
(do ((i 0 (fx+ i 1))
(id id (op id (vector-ref v i))))
((fx= i n) id))))
(cond ((not (array? A))
(error "array-tile: The first argument is not an array: " A slice-widths))
((not (and (vector? slice-widths)
(fx= (vector-length slice-widths)
(%%array-dimension A))))
(error "array-tile: The second argument is not a vector of the same length as the dimension of the array first argument: " A slice-widths))
(else
(let* ((A-dim (%%array-dimension A))
(domain (%%array-domain A))
(lowers (%%interval-lower-bounds domain))
(uppers (%%interval-upper-bounds domain))
(widths (%%interval-widths domain)))
(let slice-widths-check ((k 0))
(if (fx< k A-dim)
(let ((S_k (vector-ref slice-widths k)))
(if (eqv? (%%interval-width domain k) 0)
(if (and (vector? S_k)
(not (fx= (vector-length S_k) 0))
(%%vector-every (lambda (x) (eqv? x 0)) S_k))
(slice-widths-check (fx+ k 1))
(error (string-append "array-tile: Axis "
(number->string k)
" of the domain of the first argument has width 0, but element "
(number->string k)
" of the second argument is not a nonempty vector of exact zeros: ")
A slice-widths))
(if (or (and (exact-integer? S_k)
(positive? S_k))
(and (vector? S_k)
(%%vector-every (lambda (x) (and (exact-integer? x) (not (negative? x)))) S_k)
(= (%%vector-fold-left (lambda (x y) (+ x y)) 0 S_k) (%%interval-width domain k))))
(slice-widths-check (fx+ k 1))
(error (string-append "array-tile: Axis "
(number->string k)
" of the domain of the first argument has nonzero width, but element "
(number->string k)
" of the second argument is neither an exact positive integer nor a vector of nonnegative exact integers summing to that width: ")
A slice-widths))))
(let ((offsets (make-vector A-dim)))
(do ((k 0 (fx+ k 1)))
((fx= k A-dim))
(let ((S_k (vector-ref slice-widths k)))
(if (exact-integer? S_k)
(let* ((width_k (vector-ref widths k))
(number-of-slices (quotient (+ width_k (- S_k 1)) S_k))
(slice-offsets (make-vector (+ number-of-slices 1))))
(vector-set! slice-offsets 0 (vector-ref lowers k))
(do ((i 0 (fx+ i 1)))
((fx= i number-of-slices)
(vector-set! slice-offsets
number-of-slices
(min (vector-ref uppers k)
(vector-ref slice-offsets number-of-slices)))
(vector-set! offsets k slice-offsets))
(vector-set! slice-offsets
(fx+ i 1)
(+ (vector-ref slice-offsets i) S_k))))
(let* ((number-of-slices (vector-length S_k))
(slice-offsets (make-vector (+ number-of-slices 1))))
(vector-set! slice-offsets 0 (vector-ref lowers k))
(do ((i 0 (fx+ i 1)))
((fx= i number-of-slices)
(vector-set! offsets k slice-offsets))
(vector-set! slice-offsets
(fx+ i 1)
(+ (vector-ref slice-offsets i)
(vector-ref S_k i))))))))
(let ((result-domain
(make-interval (vector-map (lambda (v)
(- (vector-length v) 1))
offsets))))
(define-macro (generate-result)
(define (symbol-append . args)
(string->symbol
(apply string-append (map (lambda (x)
(cond ((symbol? x) (symbol->string x))
((number? x) (number->string x))
((string? x) x)
(else (error "Arghh!"))))
args))))
`(case A-dim
,@(map (lambda (k)
(let* ((indices (iota k))
(args (map (lambda (j) (symbol-append 'i_ j)) indices)))
`((,k)
(lambda ,args
(%%array-extract
A
(%%finish-interval (vector ,@(map (lambda (index slice-index)
`(vector-ref (vector-ref offsets ,index) ,slice-index))
indices args))
(vector ,@(map (lambda (index slice-index)
`(vector-ref (vector-ref offsets ,index) (fx+ ,slice-index 1)))
indices args))))))))
'(0 1 2 3 4))
(else
(lambda i
(let* ((i
(list->vector i))
(subdomain
(%%finish-interval (vector-map (lambda (slice-offsets i) (vector-ref slice-offsets i)) offsets i)
(vector-map (lambda (slice-offsets i) (vector-ref slice-offsets (fx+ i 1))) offsets i))))
(%%array-extract A subdomain))))))
(%%make-safe-immutable-array result-domain (generate-result) "array-tile: ")))))))))
(define (%%getter-translate getter translation)
(case (vector-length translation)
((0) (lambda ()
(getter)))
((1) (lambda (i)
(getter (- i (vector-ref translation 0)))))
((2) (lambda (i j)
(getter (- i (vector-ref translation 0))
(- j (vector-ref translation 1)))))
((3) (lambda (i j k)
(getter (- i (vector-ref translation 0))
(- j (vector-ref translation 1))
(- k (vector-ref translation 2)))))
((4) (lambda (i j k l)
(getter (- i (vector-ref translation 0))
(- j (vector-ref translation 1))
(- k (vector-ref translation 2))
(- l (vector-ref translation 3)))))
(else
(let ((n (vector-length translation))
(translation-list (vector->list translation)))
(lambda indices
(cond ((not (fx= (length indices) n))
(error "The number of indices does not equal the array dimension: " indices))
(else
(apply getter (map (lambda (x y) (- x y)) indices translation-list)))))))))
(define (%%setter-translate setter translation)
(case (vector-length translation)
((0) (lambda (v)
(setter v)))
((1) (lambda (v i)
(setter v
(- i (vector-ref translation 0)))))
((2) (lambda (v i j)
(setter v
(- i (vector-ref translation 0))
(- j (vector-ref translation 1)))))
((3) (lambda (v i j k)
(setter v
(- i (vector-ref translation 0))
(- j (vector-ref translation 1))
(- k (vector-ref translation 2)))))
((4) (lambda (v i j k l)
(setter v
(- i (vector-ref translation 0))
(- j (vector-ref translation 1))
(- k (vector-ref translation 2))
(- l (vector-ref translation 3)))))
(else
(let ((n (vector-length translation))
(translation-list (vector->list translation)))
(lambda (v . indices)
(cond ((not (fx= (length indices) n))
(error "The number of indices does not equal the array dimension: " v indices))
(else
(apply setter v (map (lambda (x y) (- x y)) indices translation-list)))))))))
(define (%%array-translate array translation)
(cond ((specialized-array? array)
(%%specialized-array-share array
(%%interval-translate (%%array-domain array) translation)
(%%getter-translate values translation)
(%%array-in-order? array)))
((mutable-array? array)
(make-array (%%interval-translate (%%array-domain array) translation)
(%%getter-translate (%%array-getter array) translation)
(%%setter-translate (%%array-setter array) translation)))
(else
(make-array (%%interval-translate (%%array-domain array) translation)
(%%getter-translate (%%array-getter array) translation)))))
(define (array-translate array translation)
(cond ((not (array? array))
(error "array-translate: The first argument is not an array: " array translation))
((not (translation? translation))
(error "array-translate: The second argument is not a vector of exact integers: " array translation))
((not (fx= (%%array-dimension array)
(vector-length translation)))
(error "array-translate: The dimension of the first argument (an array) does not equal the dimension of the second argument (a vector): " array translation))
(else
(%%array-translate array translation))))
(define-macro (setup-permuted-getters-and-setters)
(define (list-remove l i)
;; new list that removes (list-ref l i) from l
(if (zero? i)
(cdr l)
(cons (car l)
(list-remove (cdr l) (- i 1)))))
(define (permutations l)
;; generates list of all permutations of l
(if (or (null? l)
(null? (cdr l)))
(list l)
(apply append (map (lambda (i)
(let ((x (list-ref l i))
(rest (list-remove l i)))
(map (lambda (tail)
(cons x tail))
(permutations rest))))
(iota (length l))))))
(define (concat . args)
(string->symbol (apply string-append (map (lambda (s) (if (string? s) s (symbol->string s ))) args))))
(define (permuter name transform-arguments)
`(define (,(concat name '-permute) ,name permutation)
(case (vector-length permutation)
,@(map (lambda (i)
`((,i) (cond ,@(let ((args (take '(i j k l) i)))
(map (lambda (perm permuted-args)
`((equal? permutation ',(list->vector perm))
(lambda ,(transform-arguments permuted-args)
,`(,name ,@(transform-arguments args)))))
(permutations (take '(0 1 2 3) i))
(permutations args))))))
'(0 1 2 3 4))
(else
(let ((n (vector-length permutation))
(permutation-inverse (%%permutation-invert permutation)))
(lambda ,(transform-arguments 'indices)
(if (not (fx= (length indices) n))
(error "number of indices does not equal permutation dimension: " indices permutation)
(apply ,name ,@(transform-arguments '((%%vector-permute->list (list->vector indices) permutation-inverse)))))))))))
(let ((result
`(begin
,(permuter '%%getter values)
,(permuter '%%setter (lambda (args) (cons 'v args))))))
result))
(setup-permuted-getters-and-setters)
(define (%%array-permute array permutation)
(cond ((specialized-array? array)
(%%specialized-array-share array
(%%interval-permute (%%array-domain array) permutation)
(%%getter-permute values permutation)))
((mutable-array? array)
(make-array (%%interval-permute (%%array-domain array) permutation)
(%%getter-permute (%%array-getter array) permutation)
(%%setter-permute (%%array-setter array) permutation)))
(else
(make-array (%%interval-permute (%%array-domain array) permutation)
(%%getter-permute (%%array-getter array) permutation)))))
(define (array-permute array permutation)
(cond ((not (array? array))
(error "array-permute: The first argument is not an array: " array permutation))
((not (permutation? permutation))
(error "array-permute: The second argument is not a permutation: " array permutation))
((not (fx= (%%array-dimension array)
(vector-length permutation)))
(error "array-permute: The dimension of the first argument (an array) does not equal the dimension of the second argument (a permutation): " array permutation))
(else
(%%array-permute array permutation))))
(define-macro (setup-reversed-getters-and-setters)
(define (make-symbol . args)
(string->symbol
(apply string-append
(map (lambda (x)
(cond ((string? x) x)
((symbol? x) (symbol->string x))
((number? x) (number->string x))))
args))))
(define (truth-table n) ;; generate all combinations of n #t and #f
(if (zero? n)
'(())
(let ((subtable (truth-table (- n 1))))
(apply append (map (lambda (value)
(map (lambda (t)
(cons value t))
subtable))
'(#t #f))))))
(define (generate-code-for-fixed-n name transformer n)
(let ((zero-to-n-1
(iota n))
(table
(truth-table n)))
`((,n) (let (,@(map (lambda (k)
`(,(make-symbol 'adjust_ k) (+ (%%interval-upper-bound interval ,k)
(%%interval-lower-bound interval ,k)
-1)))
zero-to-n-1))
(cond ,@(map (lambda (table-entry)
`((equal? flip? ',(list->vector table-entry))
(lambda ,(transformer (map (lambda (k)
(make-symbol 'i_ k))
zero-to-n-1))
(,name ,@(transformer (map (lambda (flip? k)
(if flip?
`(- ,(make-symbol 'adjust_ k)
,(make-symbol 'i_ k))
`,(make-symbol 'i_ k)))
table-entry zero-to-n-1))))))
table))))))
(define (reverser name transform-arguments)
`(define (,(make-symbol name '-reverse) ,name flip? interval)
(case (vector-length flip?)
,@(map (lambda (n)
(generate-code-for-fixed-n name transform-arguments n))
'(0 1 2 3 4))
(else
(let ((n
(vector-length flip?))
(flip?
(vector->list flip?))
(adjust
(map (lambda (u_k l_k)
(+ u_k l_k -1))
(vector->list (%%interval-upper-bounds interval))
(vector->list (%%interval-lower-bounds interval)))))
(lambda ,(transform-arguments 'indices)
(if (not (fx= (length indices) n))
(error "number of indices does not equal array dimension: " indices)
(apply ,name ,@(transform-arguments '((map (lambda (i adjust flip?)
(if flip?
(- adjust i)
i))
indices adjust flip?)))))))))))
(let ((result
`(begin
,(reverser '%%getter values)
,(reverser '%%setter (lambda (args) (cons 'v args))))))
result))
(setup-reversed-getters-and-setters)
(define (%%array-reverse array flip?)
(cond ((specialized-array? array)
(%%specialized-array-share array
(%%array-domain array)
(%%getter-reverse values flip? (%%array-domain array))))
((mutable-array? array)
(make-array (%%array-domain array)
(%%getter-reverse (%%array-getter array) flip? (%%array-domain array))
(%%setter-reverse (%%array-setter array) flip? (%%array-domain array))))
(else
(make-array (%%array-domain array)
(%%getter-reverse (%%array-getter array) flip? (%%array-domain array))))))
(define %%vector-of-trues
'#(#()
#(#t)
#(#t #t)
#(#t #t #t)
#(#t #t #t #t)))
(define array-reverse
(case-lambda
((array)
(cond ((not (array? array))
(error "array-reverse: The argument is not an array: " array))
(else
(%%array-reverse array
(let ((dim (%%array-dimension array)))
(if (fx< dim 5)
(vector-ref %%vector-of-trues dim)
(make-vector dim #t)))))))
((array flip?)
(cond ((not (array? array))
(error "array-reverse: The first argument is not an array: " array flip?))
((not (and (vector? flip?)
(%%vector-every (lambda (x) (boolean? x)) flip?)))
(error "array-reverse: The second argument is not a vector of booleans: " array flip?))
((not (fx= (%%array-dimension array)
(vector-length flip?)))
(error "array-reverse: The dimension of the first argument (an array) does not equal the dimension of the second argument (a vector of booleans): " array flip?))
(else
(%%array-reverse array flip?))))))
(define-macro (macro-generate-sample)
(define (make-symbol . args)
(string->symbol
(apply string-append
(map (lambda (x)
(cond ((string? x) x)
((symbol? x) (symbol->string x))
((number? x) (number->string x))))
args))))
(define (first-half l)
(take l (quotient (length l) 2)))
(define (second-half l)
(drop l (quotient (length l) 2)))
(define (arg-lists ks)
(if (null? ks)
'(())
(let* ((k (car ks))
(i_k (make-symbol 'i_ k))
(s_k (make-symbol 's_ k))
(sublists
(arg-lists (cdr ks)))
(plains
(map (lambda (l)
(cons i_k l))
sublists))
(scales
(map (lambda (l)
(cons `(* ,i_k ,s_k) l))
sublists)))
(append plains
scales))))
(define (code-for-one-n name transformer n)
(let* ((zero-to-n-1
(iota n))
(arg-list
(map (lambda (k)
(make-symbol 'i_ k))
zero-to-n-1))
(args
(arg-lists zero-to-n-1)))
(define (build-code args ks)
(if (null? (cdr args))
`(lambda ,(transformer arg-list)
(,name ,@(transformer (car args))))
(let* ((k (car ks))
(s_k (make-symbol 's_ k))
(plains (first-half args))
(scales (second-half args)))
`(if (= 1 ,s_k)
,(build-code plains (cdr ks))
,(build-code scales (cdr ks))))))
`((,n)
(let (,@(map (lambda (k)
`(,(make-symbol 's_ k) (vector-ref scales ,k)))
zero-to-n-1))
,(build-code args zero-to-n-1)))))
(define (sampler name transformer)
`(define (,(make-symbol name '-sample) ,name scales interval)
(case (vector-length scales)
,@(map (lambda (n)
(code-for-one-n name transformer n))
'(0 1 2 3 4))
(else
(let ((n
(vector-length scales))
(scales
(vector->list scales)))
(lambda ,(transformer 'indices)
(if (not (fx= (length indices) n))
(error "number of indices does not equal array dimension: " indices)
(apply ,name ,@(transformer '((map (lambda (i s)
(* s i))
indices scales)))))))))))
(let ((result
`(begin
,(sampler '%%getter values)
,(sampler '%%setter (lambda (args) (cons 'v args))))))
result))
(macro-generate-sample)
(define (%%immutable-array-sample array scales)
(make-array (%%interval-scale (%%array-domain array) scales)
(%%getter-sample (%%array-getter array) scales (%%array-domain array))))
(define (%%mutable-array-sample array scales)
(make-array (%%interval-scale (%%array-domain array) scales)
(%%getter-sample (%%array-getter array) scales (%%array-domain array))
(%%setter-sample (%%array-setter array) scales (%%array-domain array))))
(define (%%specialized-array-sample array scales)
(%%specialized-array-share array
(%%interval-scale (%%array-domain array) scales)
(%%getter-sample values scales (%%array-domain array))))
(define (array-sample array scales)
(cond ((not (and (array? array)
(%%vector-every (lambda (x) (eqv? x 0)) (%%interval-lower-bounds (%%array-domain array)))))
(error "array-sample: The first argument is not an array whose domain has zero lower bounds: " array scales))
((not (and (vector? scales)
(%%vector-every (lambda (x) (exact-integer? x)) scales)
(%%vector-every (lambda (x) (positive? x)) scales)))
(error "array-sample: The second argument is not a vector of positive, exact, integers: " array scales))
((not (fx= (vector-length scales) (%%array-dimension array)))
(error "array-sample: The dimension of the first argument (an array) is not equal to the length of the second (a vector): "
array scales))
((specialized-array? array)
(%%specialized-array-sample array scales))
((mutable-array? array)
(%%mutable-array-sample array scales))
(else
(%%immutable-array-sample array scales))))
(define (%%array-outer-product combiner A B)
(let* ((D_A (%%array-domain A))
(D_B (%%array-domain B))
(A_ (%%array-getter A))
(B_ (%%array-getter B))
(dim_A (%%interval-dimension D_A))
(dim_B (%%interval-dimension D_B))
(result-domain (%%interval-cartesian-product (list D_A D_B)))
(result-getter
(case dim_A
((0)
(case dim_B
((0)
(lambda ()
(combiner (A_) (B_))))
((1)
(lambda (i2)
(combiner (A_) (B_ i2))))
((2)
(lambda (i2 j2)
(combiner (A_) (B_ i2 j2))))
((3)
(lambda (i2 j2 k2)
(combiner (A_) (B_ i2 j2 k2))))
((4)
(lambda (i2 j2 k2 l2)
(combiner (A_) (B_ i2 j2 k2 l2))))
(else
(lambda rest
(combiner (A_) (apply B_ rest))))))
((1)
(case dim_B
((0)
(lambda (i1)
(combiner (A_ i1) (B_))))
((1)
(lambda (i1 i2)
(combiner (A_ i1) (B_ i2))))
((2)
(lambda (i1 i2 j2)
(combiner (A_ i1) (B_ i2 j2))))
((3)
(lambda (i1 i2 j2 k2)
(combiner (A_ i1) (B_ i2 j2 k2))))
(else
(lambda (i1 . rest)
(combiner (A_ i1) (apply B_ rest))))))
((2)
(case dim_B
((0)
(lambda (i1 j1)
(combiner (A_ i1 j1) (B_))))
((1)
(lambda (i1 j1 i2)
(combiner (A_ i1 j1) (B_ i2))))
((2)
(lambda (i1 j1 i2 j2)
(combiner (A_ i1 j1) (B_ i2 j2))))
(else
(lambda (i1 j1 . rest)
(combiner (A_ i1 j1) (apply B_ rest))))))
((3)
(case dim_B
((0)
(lambda (i1 j1 k1)
(combiner (A_ i1 j1 k1) (B_))))
((1)
(lambda (i1 j1 k1 i2)
(combiner (A_ i1 j1 k1) (B_ i2))))
(else
(lambda (i1 j1 k1 . rest)
(combiner (A_ i1 j1 k1) (apply B_ rest))))))
((4)
(case dim_B
((0)
(lambda (i1 j1 k1 l1)
(combiner (A_ i1 j1 k1 l1) (B_))))
(else
(lambda (i1 j1 k1 l1 . rest)
(combiner (A_ i1 j1 k1 l1) (apply B_ rest))))))
(else
(lambda args
(combiner (apply A_ (take args dim_A))
(apply B_ (drop args dim_A))))))))
(make-array result-domain result-getter)))
(define (array-outer-product combiner array1 array2)
(cond ((not (array? array1))
(error "array-outer-product: The second argument is not an array: " combiner array1 array2))
((not (array? array2))
(error "array-outer-product: The third argument is not an array: " combiner array1 array2))
((not (procedure? combiner))
(error "array-outer-product: The first argument is not a procedure: " combiner array1 array2))
(else
(%%array-outer-product combiner array1 array2))))
(define (%%make-safe-immutable-array domain getter caller)
(make-array
domain
(case (%%interval-dimension domain)
((0) (lambda ()
(getter)))
((1) (lambda (i)
(cond ((not (exact-integer? i))
(error (string-append caller "multi-index component is not an exact integer: ") i))
((not (%%interval-contains-multi-index?-1 domain i))
(error (string-append caller "domain does not contain multi-index: ") domain i))
(else
(getter i)))))
((2) (lambda (i j)
(cond ((not (and (exact-integer? i)
(exact-integer? j)))
(error (string-append caller "multi-index component is not an exact integer: ") i j))
((not (%%interval-contains-multi-index?-2 domain i j))
(error (string-append caller "domain does not contain multi-index: ") domain i j))
(else
(getter i j)))))
((3) (lambda (i j k)
(cond ((not (and (exact-integer? i)
(exact-integer? j)
(exact-integer? k)))
(error (string-append caller "multi-index component is not an exact integer: ") i j k))
((not (%%interval-contains-multi-index?-3 domain i j k))
(error (string-append caller "domain does not contain multi-index: ") domain i j k))
(else
(getter i j k)))))
((4) (lambda (i j k l)
(cond ((not (and (exact-integer? i)
(exact-integer? j)
(exact-integer? k)
(exact-integer? l)))
(error (string-append caller "multi-index component is not an exact integer: ") i j k l))
((not (%%interval-contains-multi-index?-4 domain i j k l))
(error (string-append caller "domain does not contain multi-index: ") domain i j k l))
(else
(getter i j k l)))))
(else (lambda multi-index
(cond ((not (%%every exact-integer? multi-index))
(apply error (string-append caller "multi-index component is not an exact integer: ") multi-index))
((not (= (length multi-index) (%%interval-dimension domain)))
(apply error (string-append caller "multi-index is not the correct dimension: ") domain multi-index))
((not (%%interval-contains-multi-index?-general domain multi-index))
(apply error (string-append caller "domain does not contain multi-index: ") domain multi-index))
(else
(apply getter multi-index))))))))
(define (%%immutable-array-curry array right-dimension)
(call-with-values
(lambda () (%%interval-projections (%%array-domain array) right-dimension))
(lambda (left-interval right-interval)
(let ((getter (%%array-getter array)))
(%%make-safe-immutable-array
left-interval
(case (%%interval-dimension left-interval)
((0) (case (%%interval-dimension right-interval)
((0) (lambda () (make-array right-interval (lambda () (getter)))))
((1) (lambda () (make-array right-interval (lambda (i) (getter i)))))
((2) (lambda () (make-array right-interval (lambda (i j) (getter i j)))))
((3) (lambda () (make-array right-interval (lambda (i j k) (getter i j k)))))
((4) (lambda () (make-array right-interval (lambda (i j k l) (getter i j k l)))))
(else (lambda () (make-array right-interval (lambda multi-index (apply getter multi-index)))))))
((1) (case (%%interval-dimension right-interval)
((0) (lambda (i) (make-array right-interval (lambda () (getter i)))))
((1) (lambda (i) (make-array right-interval (lambda (j) (getter i j)))))
((2) (lambda (i) (make-array right-interval (lambda (j k) (getter i j k)))))
((3) (lambda (i) (make-array right-interval (lambda (j k l) (getter i j k l)))))
(else (lambda (i) (make-array right-interval (lambda multi-index (apply getter i multi-index)))))))
((2) (case (%%interval-dimension right-interval)
((0) (lambda (i j) (make-array right-interval (lambda ( ) (getter i j)))))
((1) (lambda (i j) (make-array right-interval (lambda ( k) (getter i j k)))))
((2) (lambda (i j) (make-array right-interval (lambda ( k l) (getter i j k l)))))
(else (lambda (i j) (make-array right-interval (lambda multi-index (apply getter i j multi-index)))))))
((3) (case (%%interval-dimension right-interval)
((0) (lambda (i j k) (make-array right-interval (lambda ( ) (getter i j k)))))
((1) (lambda (i j k) (make-array right-interval (lambda ( l) (getter i j k l)))))
(else (lambda (i j k) (make-array right-interval (lambda multi-index (apply getter i j k multi-index)))))))
((4) (case (%%interval-dimension right-interval)
((0) (lambda (i j k l) (make-array right-interval (lambda ( ) (getter i j k l)))))
(else (lambda (i j k l) (make-array right-interval (lambda multi-index (apply getter i j k l multi-index)))))))
(else (lambda left-multi-index
(make-array right-interval
(lambda right-multi-index
(apply getter (append left-multi-index right-multi-index)))))))
"array-curry: ")))))
(define (%%mutable-array-curry array right-dimension)
(call-with-values
(lambda () (%%interval-projections (%%array-domain array) right-dimension))
(lambda (left-interval right-interval)
(let ((getter (%%array-getter array))
(setter (%%array-setter array)))
(%%make-safe-immutable-array
left-interval
(case (%%interval-dimension left-interval)
((0) (case (%%interval-dimension right-interval)
((0) (lambda () (make-array right-interval
(lambda ( ) (getter ))
(lambda (v) (setter v)))))
((1) (lambda () (make-array right-interval
(lambda ( i) (getter i))
(lambda (v i) (setter v i)))))
((2) (lambda () (make-array right-interval
(lambda ( i j) (getter i j))
(lambda (v i j) (setter v i j)))))
((3) (lambda () (make-array right-interval
(lambda ( i j k) (getter i j k))
(lambda (v i j k) (setter v i j k)))))
((4) (lambda () (make-array right-interval
(lambda ( i j k l) (getter i j k l))
(lambda (v i j k l) (setter v i j k l)))))
(else (lambda () (make-array right-interval
(lambda multi-index (apply getter multi-index))
(lambda (v . multi-index) (apply setter v multi-index)))))))
((1) (case (%%interval-dimension right-interval)
((0) (lambda (i) (make-array right-interval
(lambda ( ) (getter i))
(lambda (v) (setter v i)))))
((1) (lambda (i) (make-array right-interval
(lambda ( j) (getter i j))
(lambda (v j) (setter v i j)))))
((2) (lambda (i) (make-array right-interval
(lambda ( j k) (getter i j k))
(lambda (v j k) (setter v i j k)))))
((3) (lambda (i) (make-array right-interval
(lambda ( j k l) (getter i j k l))
(lambda (v j k l) (setter v i j k l)))))
(else (lambda (i) (make-array right-interval
(lambda multi-index (apply getter i multi-index))
(lambda (v . multi-index) (apply setter v i multi-index)))))))
((2) (case (%%interval-dimension right-interval)
((0) (lambda (i j) (make-array right-interval
(lambda ( ) (getter i j))
(lambda (v ) (setter v i j)))))
((1) (lambda (i j) (make-array right-interval
(lambda ( k) (getter i j k))
(lambda (v k) (setter v i j k)))))
((2) (lambda (i j) (make-array right-interval
(lambda ( k l) (getter i j k l))
(lambda (v k l) (setter v i j k l)))))
(else (lambda (i j) (make-array right-interval
(lambda multi-index (apply getter i j multi-index))
(lambda (v . multi-index) (apply setter v i j multi-index)))))))
((3) (case (%%interval-dimension right-interval)
((0) (lambda (i j k) (make-array right-interval
(lambda ( ) (getter i j k))
(lambda (v ) (setter v i j k)))))
((1) (lambda (i j k) (make-array right-interval
(lambda ( l) (getter i j k l))
(lambda (v l) (setter v i j k l)))))
(else (lambda (i j k) (make-array right-interval
(lambda multi-index (apply getter i j k multi-index))
(lambda (v . multi-index) (apply setter v i j k multi-index)))))))
((4) (case (%%interval-dimension right-interval)
((0) (lambda (i j k l) (make-array right-interval
(lambda ( ) (getter i j k l))
(lambda (v ) (setter v i j k l)))))
(else (lambda (i j k l) (make-array right-interval
(lambda multi-index (apply getter i j k l multi-index))
(lambda (v . multi-index) (apply setter v i j k l multi-index)))))))
(else (lambda left-multi-index
(make-array right-interval
(lambda right-multi-index (apply getter (append left-multi-index right-multi-index)))
(lambda (v . right-multi-index) (apply setter v (append left-multi-index right-multi-index)))))))
"array-curry: ")))))
(define (%%specialized-array-curry array right-dimension)
(call-with-values
(lambda () (%%interval-projections (%%array-domain array) right-dimension))
(lambda (left-interval right-interval)
(let* ((input-array-in-order?
(%%array-in-order? array))
(in-order?
(or (and (boolean? input-array-in-order?) ;; we know whether the input array is in order
input-array-in-order?) ;; and it is in order
;; But even if it isn't, the subarrays may be in order, so we
;; compute once whether all the subarrays are in order.
;; We do this without actually instantiating one of the subarrays.
(%%compute-array-packed?
;; The same domain for all subarrays.
right-interval
;; The new indexer computed using the general, nonspecialized new-domain->old-domain function,
;; applied specifically to the first multi-index in the left-interval.
;; If any of the arrays are empty then the indexers could be nonsense, but
;; %%compute-array-packed? special-cases empty intervals.
(%%compose-indexers (%%array-indexer array)
right-interval
(lambda right-multi-index
(apply values
(append (%%interval-lower-bounds->list left-interval)
right-multi-index))))))))
(%%make-safe-immutable-array
left-interval
(case (%%interval-dimension left-interval)
((0) (case (%%interval-dimension right-interval)
((0) (lambda () (%%specialized-array-share array right-interval (lambda () (values )) in-order?)))
((1) (lambda () (%%specialized-array-share array right-interval (lambda (i) (values i )) in-order?)))
((2) (lambda () (%%specialized-array-share array right-interval (lambda (i j) (values i j )) in-order?)))
((3) (lambda () (%%specialized-array-share array right-interval (lambda (i j k) (values i j k )) in-order?)))
((4) (lambda () (%%specialized-array-share array right-interval (lambda (i j k l) (values i j k l)) in-order?)))
(else (lambda () (%%specialized-array-share array right-interval (lambda multi-index (apply values multi-index)) in-order?)))))
((1) (case (%%interval-dimension right-interval)
((0) (lambda (i) (%%specialized-array-share array right-interval (lambda () (values i )) in-order?)))
((1) (lambda (i) (%%specialized-array-share array right-interval (lambda (j) (values i j )) in-order?)))
((2) (lambda (i) (%%specialized-array-share array right-interval (lambda (j k) (values i j k )) in-order?)))
((3) (lambda (i) (%%specialized-array-share array right-interval (lambda (j k l) (values i j k l)) in-order?)))
(else (lambda (i) (%%specialized-array-share array right-interval (lambda multi-index (apply values i multi-index)) in-order?)))))
((2) (case (%%interval-dimension right-interval)
((0) (lambda (i j) (%%specialized-array-share array right-interval (lambda () (values i j )) in-order?)))
((1) (lambda (i j) (%%specialized-array-share array right-interval (lambda (k) (values i j k )) in-order?)))
((2) (lambda (i j) (%%specialized-array-share array right-interval (lambda (k l) (values i j k l)) in-order?)))
(else (lambda (i j) (%%specialized-array-share array right-interval (lambda multi-index (apply values i j multi-index)) in-order?)))))
((3) (case (%%interval-dimension right-interval)
((0) (lambda (i j k) (%%specialized-array-share array right-interval (lambda () (values i j k )) in-order?)))
((1) (lambda (i j k) (%%specialized-array-share array right-interval (lambda (l) (values i j k l)) in-order?)))
(else (lambda (i j k) (%%specialized-array-share array right-interval (lambda multi-index (apply values i j k multi-index)) in-order?)))))
((4) (case (%%interval-dimension right-interval)
((0) (lambda (i j k l) (%%specialized-array-share array right-interval (lambda () (values i j k l)) in-order?)))
(else (lambda (i j k l) (%%specialized-array-share array right-interval (lambda multi-index (apply values i j k l multi-index)) in-order?)))))
(else (lambda left-multi-index
(%%specialized-array-share array right-interval (lambda right-multi-index (apply values (append left-multi-index right-multi-index))) in-order?))))
"array-curry: ")))))
(define (%%array-curry array right-dimension)
(cond ((specialized-array? array)
(%%specialized-array-curry array right-dimension))
((mutable-array? array)
(%%mutable-array-curry array right-dimension))
(else ; immutable array
(%%immutable-array-curry array right-dimension))))
(define (array-curry array right-dimension)
(cond ((not (array? array))
(error "array-curry: The first argument is not an array: " array right-dimension))
((not (and (fixnum? right-dimension)
(fx<= 0 right-dimension (%%array-dimension array))))
(error "array-curry: The second argument is not an exact integer between 0 and (interval-dimension (array-domain array)) (inclusive): " array right-dimension))
(else
(%%array-curry array right-dimension))))
;;;
;;; array-map returns an array whose domain is the same as the common domain of (cons array arrays)
;;; and whose getter is
;;;
;;; (lambda multi-index
;;; (apply f (map (lambda (g) (apply g multi-index)) (map array-getter (cons array arrays)))))
;;;
;;; This function is also used in array-for-each, so we try to specialize the this
;;; function to speed things up a bit.
;;;
(define (%%specialize-function-applied-to-array-getters f array arrays)
(let ((domain (%%array-domain array))
(arrays (cons array arrays)))
(define-macro (generate-cases)
(define-macro (max-getters) 8)
(define-macro (number-of-dimensions) 5)
(define (make-getter i)
(symbol-append 'getter- i))
(define (symbol-append . args)
(string->symbol
(apply string-append (map (lambda (x)
(cond ((symbol? x) (symbol->string x))
((number? x) (number->string x))
((string? x) x)
(else (error "Arghh!"))))
args))))
(define (do-one number-of-getters)
(let ((getters (map make-getter
(iota number-of-getters))))
`((,number-of-getters) (let ,(map (lambda (getter i)
`(,getter (%%array-getter (list-ref arrays ,i))))
getters
(iota number-of-getters))
(case (%%interval-dimension domain)
,@(map (lambda (dimension)
(let ((multi-index (map (lambda (dim)
(symbol-append 'i_ dim))
(iota dimension))))
`((,dimension) (lambda ,multi-index
(f ,@(map (lambda (getter)
`(,(make-getter getter) ,@multi-index))
(iota number-of-getters)))))))
(iota (number-of-dimensions)))
(else (lambda multi-index (f ,@(map (lambda (getter)
`(apply ,getter multi-index))
getters)))))))))
(let ((result
`(case (length arrays)
,@(map do-one (iota (max-getters) 1))
(else
(let ((getters (map array-getter arrays)))
(case (%%interval-dimension domain)
,@(map (lambda (dimension)
(let ((multi-index (map (lambda (dim)
(symbol-append 'i_ dim))
(iota dimension))))
`((,dimension) (lambda ,multi-index
(apply f (map (lambda (g)
(g ,@multi-index))
getters))))))
(iota (number-of-dimensions)))
(else (lambda multi-index (apply f (map (lambda (g) (apply g multi-index)) getters))))))))))
result))
(generate-cases)))
(define (%%array-map f array arrays)
;; unsafe, for internal use on known intervals
(make-array (%%array-domain array)
(%%specialize-function-applied-to-array-getters f array arrays)))
(define (array-map f array #!rest arrays)
(cond ((not (procedure? f))
(apply error "array-map: The first argument is not a procedure: " f array arrays))
((not (%%every array? (cons array arrays)))
(apply error "array-map: Not all arguments after the first are arrays: " f array arrays))
((not (%%every (lambda (d) (%%interval= d (%%array-domain array))) (map %%array-domain arrays)))
(apply error "array-map: Not all arrays have the same domain: " f array arrays))
(else
;; safe
(make-array (%%array-domain array)
(%%specialize-function-applied-to-array-getters f array arrays)))))
;;; applies f to the elements of the arrays in lexicographical order.
(define (%%array-for-each f array arrays)
(%%interval-for-each (%%specialize-function-applied-to-array-getters f array arrays)
(%%array-domain array)))
(define (array-for-each f array #!rest arrays)
(cond ((not (procedure? f))
(apply error "array-for-each: The first argument is not a procedure: " f array arrays))
((not (%%every array? (cons array arrays)))
(apply error "array-for-each: Not all arguments after the first are arrays: " f array arrays))
((not (%%every (lambda (d) (%%interval= d (%%array-domain array))) (map %%array-domain arrays)))
(apply error "array-for-each: Not all arrays have the same domain: " f array arrays))
(else
(%%array-for-each f array arrays))))
(define-macro (macro-make-predicates)
(define (symbol-append . args)
(string->symbol
(apply string-append (map (lambda (x)
(cond ((symbol? x) (symbol->string x))
((number? x) (number->string x))
((string? x) x)
(else (error "Arghh!"))))
args))))
(define (make-lower k)
(symbol-append 'lower- k))
(define (make-upper k)
(symbol-append 'upper- k))
(define (make-arg k)
(symbol-append 'i_ k))
(define (make-loop-name k)
(symbol-append 'loop- k))
(define (make-predicate name connector)
(define (make-loop indentation depth k)
`(let ,(make-loop-name indentation) ((,(make-arg indentation) ,(make-lower indentation))
(index ,(if (= indentation 0)
`(- n 1)
`index)))
,(if (= indentation 0)
(if (= depth 0)
`(cond ((eqv? index 0)
(f ,@(map make-arg (iota k))))
(else
(,connector (f ,@(map make-arg (iota k)))
(,(make-loop-name indentation) (+ ,(make-arg indentation) 1) (- index 1)))))
(make-loop (+ indentation 1) (- depth 1) k))
(if (= depth 0)
`(cond ((= ,(make-arg indentation) ,(make-upper indentation))
(,(make-loop-name (- indentation 1)) (+ ,(make-arg (- indentation 1)) 1) index))
((eqv? index 0)
(f ,@(map make-arg (iota k))))
(else
(,connector (f ,@(map make-arg (iota k)))
(,(make-loop-name indentation) (+ ,(make-arg indentation) 1) (- index 1)))))
`(if (< ,(make-arg indentation) ,(make-upper indentation))
,(make-loop (+ indentation 1) (- depth 1) k)
(,(make-loop-name (- indentation 1)) (+ ,(make-arg (- indentation 1)) 1) index))))))
(define (do-one-case k)
(let ((result
`((,k)
(let (,@(map (lambda (j)
`(,(make-lower j) (%%interval-lower-bound interval ,j)))
(iota k))
,@(map (lambda (j)
`(,(make-upper j) (%%interval-upper-bound interval ,j)))
(iota k))
(n (%%interval-volume interval)))
,(make-loop 0 (- k 1) k)))))
result))
`(define (,(symbol-append '%%interval- name) f interval)
(if (eqv? (%%interval-volume interval) 0)
,(if (eq? name 'any) #f #t)
(case (%%interval-dimension interval)
((0) (f))
,@(map do-one-case (iota 8 1))
(else
(let ()
(define (get-next-args reversed-args
reversed-lowers
reversed-uppers)
(let ((next-index (+ (car reversed-args) 1)))
(if (< next-index (car reversed-uppers))
(cons next-index (cdr reversed-args))
(and (not (null? (cdr reversed-args)))
(let ((tail-result (get-next-args (cdr reversed-args)
(cdr reversed-lowers)
(cdr reversed-uppers))))
(and tail-result
(cons (car reversed-lowers) tail-result)))))))
(let ((reversed-lowers (reverse (%%interval-lower-bounds->list interval)))
(reversed-uppers (reverse (%%interval-upper-bounds->list interval))))
(let loop ((reversed-args reversed-lowers)
(index (- (%%interval-volume interval) 1)))
(if (eqv? index 0)
(apply f (reverse reversed-args))
(,connector (apply f (reverse reversed-args))
(loop (get-next-args reversed-args
reversed-lowers
reversed-uppers)
(- index 1))))))))))))
(let ((result
`(begin
,(make-predicate 'every 'and)
,(make-predicate 'any 'or))))
result))
(macro-make-predicates)
(define (%%array-every f array arrays)
(%%interval-every (%%specialize-function-applied-to-array-getters f array arrays)
(%%array-domain array)))
(define (array-every f array #!rest arrays)
(cond ((not (procedure? f))
(apply error "array-every: The first argument is not a procedure: " f array arrays))
((not (%%every array? (cons array arrays)))
(apply error "array-every: Not all arguments after the first are arrays: " f array arrays))
((not (%%every (lambda (d) (%%interval= d (%%array-domain array))) (map %%array-domain arrays)))
(apply error "array-every: Not all arrays have the same domain: " f array arrays))
(else
(%%array-every f array arrays))))
(define (%%array-any f array arrays)
(%%interval-any (%%specialize-function-applied-to-array-getters f array arrays)
(%%array-domain array)))
(define (array-any f array #!rest arrays)
(cond ((not (procedure? f))
(apply error "array-any: The first argument is not a procedure: " f array arrays))
((not (%%every array? (cons array arrays)))
(apply error "array-any: Not all arguments after the first are arrays: " f array arrays))
((not (%%every (lambda (d) (%%interval= d (%%array-domain array))) (map %%array-domain arrays)))
(apply error "array-any: Not all arrays have the same domain: " f array arrays))
(else
(%%array-any f array arrays))))
(define (array-fold-left op id array . arrays)
(cond ((not (procedure? op))
(apply error "array-fold-left: The first argument is not a procedure: " op id array arrays))
((not (%%every array? (cons array arrays)))
(apply error "array-fold-left: Not all arguments after the first two are arrays: " op id array arrays))
((not (%%every (lambda (a) (%%interval= (%%array-domain a) (%%array-domain array))) arrays))
(apply error "array-fold-left: Not all arrays have the same domain: " op id array arrays))
((null? arrays)
(%%interval-fold-left (%%array-getter array) op id (%%array-domain array)))
(else
(%%interval-fold-left (%%array-getter (%%array-map list array arrays))
(case (length arrays)
((1) (lambda (id elements)
(op id (car elements) (cadr elements))))
((2) (lambda (id elements)
(op id (car elements) (cadr elements) (caddr elements))))
((3) (lambda (id elements)
(op id (car elements) (cadr elements) (caddr elements) (cadddr elements))))
(else
(lambda (id elements)
(apply op id elements))))
id
(%%array-domain array)))))
(define (array-fold-right op id array . arrays)
(cond ((not (procedure? op))
(apply error "array-fold-right: The first argument is not a procedure: " op id array arrays))
((not (%%every array? (cons array arrays)))
(apply error "array-fold-right: Not all arguments after the first two are arrays: " op id array arrays))
((not (%%every (lambda (a) (%%interval= (%%array-domain a) (%%array-domain array))) arrays))
(apply error "array-fold-right: Not all arrays have the same domain: " op id array arrays))
((null? arrays)
(%%interval-fold-right (%%array-getter array) op id (%%array-domain array)))
(else
(%%interval-fold-right (%%array-getter (%%array-map list array arrays))
(case (length arrays)
((1) (lambda (elements id)
(op (car elements) (cadr elements) id)))
((2) (lambda (elements id)
(op (car elements) (cadr elements) (caddr elements) id)))
((3) (lambda (elements id)
(op (car elements) (cadr elements) (caddr elements) (cadddr elements) id)))
(else
(lambda (elements id)
(apply op (append elements (list id))))))
id
(%%array-domain array)))))
(define %%array-reduce
(let ((%%array-reduce-base (list 'base)))
(lambda (sum A caller)
(if (%%array-empty? A)
(error (string-append caller "Attempting to reduce over an empty array: ") sum A)
(%%interval-fold-left (%%array-getter A)
(lambda (id a)
(if (eq? id %%array-reduce-base)
a
(sum id a)))
%%array-reduce-base
(%%array-domain A))))))
(define (array-reduce sum A)
(cond ((not (array? A))
(error "array-reduce: The second argument is not an array: " sum A))
((not (procedure? sum))
(error "array-reduce: The first argument is not a procedure: " sum A))
(else
(%%array-reduce sum A "array-reduce: "))))
(define (%%array->reversed-list array)
;; safe in the face of (%%array-getter array) capturing
;; the continuation using call/cc, as long as the
;; resulting list is not modified.
(%%interval-fold-left (%%array-getter array)
(lambda (a b) (cons b a))
'()
(%%array-domain array)))
(define (%%array->list array)
;; This is faster than using %%interval-fold-right
(reverse (%%array->reversed-list array)))
(define (array->list array)
(cond ((not (array? array))
(error "array->list: The argument is not an array: " array))
(else
(%%array->list array))))
(define (%%array->vector array)
(let* ((reversed-elements (%%array->reversed-list array))
(n (%%interval-volume (%%array-domain array)))
(result (make-vector n)))
(do ((i (fx- n 1) (fx- i 1))
(l reversed-elements (cdr l)))
((fx< i 0) result)
(vector-set! result i (car l)))))
(define (array->vector array)
(cond ((not (array? array))
(error "array->vector: The argument is not an array: " array))
(else
(%%array->vector array))))
;;; Refactored for use in list*->array
(define (%%list->array interval
l
result-storage-class
mutable?
safe?
caller)
(let* ((checker
(storage-class-checker result-storage-class))
(setter
(storage-class-setter result-storage-class))
(result
(%%make-specialized-array interval
result-storage-class
(storage-class-default result-storage-class)
safe?))
(body
(%%array-body result))
(n
(%%interval-volume interval)))
(let loop ((i 0)
(local l))
(if (or (fx= i n) (null? local))
(if (and (fx= i n) (null? local))
(if (not mutable?)
(%%array-freeze! result)
result)
(error (string-append caller "The volume of the first argument does not equal the length of the second: ") interval l))
(let ((item (car local)))
(if (checker item)
(begin
(setter body i item)
(loop (fx+ i 1)
(cdr local)))
(error (string-append caller "Not all elements of the source can be stored in destination: ") interval l item)))))))
(define (list->array interval
l
#!optional
(result-storage-class generic-storage-class)
(mutable? (specialized-array-default-mutable?))
(safe? (specialized-array-default-safe?)))
(cond ((not (interval? interval))
(error "list->array: The first argument is not an interval: " interval l))
((not (list? l))
(error "list->array: The second argument is not a list: " interval l))
((not (storage-class? result-storage-class))
(error "list->array: The third argument is not a storage-class: " interval l result-storage-class))
((not (boolean? mutable?))
(error "list->array: The fourth argument is not a boolean: " interval l result-storage-class mutable?))
((not (boolean? safe?))
(error "list->array: The fifth argument is not a boolean: " interval l result-storage-class mutable? safe?))
(else
(%%list->array interval
l
result-storage-class
mutable?
safe?
"list->array: "))))
(define (vector->array interval
v
#!optional
(result-storage-class generic-storage-class)
(mutable? (specialized-array-default-mutable?))
(safe? (specialized-array-default-safe?)))
(cond ((not (interval? interval))
(error "vector->array: The first argument is not an interval: " interval v))
((not (vector? v))
(error "vector->array: The second argument is not a vector: " interval v))
((not (= (vector-length v)
(%%interval-volume interval)))
(error "vector->array: The volume of the first argument does not equal the length of the second: " interval v))
((not (storage-class? result-storage-class))
(error "vector->array: The third argument is not a storage-class: " interval v result-storage-class))
((not (boolean? mutable?))
(error "vector->array: The fourth argument is not a boolean: " interval v result-storage-class mutable?))
((not (boolean? safe?))
(error "vector->array: The fifth argument is not a boolean: " interval v result-storage-class mutable? safe?))
(else
(specialized-array-reshape
(%!array-copy (%%make-specialized-array-from-data v generic-storage-class #f #f)
result-storage-class
mutable?
safe?
"vector->array: "
#f)
interval))))
(define (array->list* array)
(cond ((not (array? array))
(error "array->list*: The argument is not an array: " array))
(else
(let ()
(define (a->l a)
(let ((dim (%%interval-dimension (%%array-domain a))))
(case dim
((0) ((%%array-getter a))) ;; special case, just the element of the array
((1) (%%array->list a))
(else
(%%array->list
(%%array-map a->l (%%array-curry a (fx- dim 1)) '()))))))
(a->l array)))))
(define (array->vector* array)
(cond ((not (array? array))
(error "array->vector*: The argument is not an array: " array))
(else
(let ()
(define (a->v a)
(let ((dim (%%interval-dimension (%%array-domain a))))
(case dim
((0) ((%%array-getter a))) ;; special case, just the element of the array
((1) (%%array->vector a))
(else
(%%array->vector
(%%array-map a->v (%%array-curry a (fx- dim 1)) '()))))))
(a->v array)))))
(define (array-assign! destination source)
;; This procedure is intrinsically not call/cc safe.
(cond ((not (mutable-array? destination))
(error "array-assign!: The destination is not a mutable array: " destination source))
((not (array? source))
(error "array-assign!: The source is not an array: " destination source))
((not (%%interval= (%%array-domain destination)
(%%array-domain source)))
(error "array-assign: The destination and source do not have the same domains: " destination source))
(else
(%%move-array-elements destination
source
"array-assign!: ")
(void))))
(define (%%array-inner-product A f g B)
;; Copy the curried arrays for efficiency.
;; If any of the curried arrays are empty, that's OK,
;; If the elements of the curried arrays are empty, then
;; the error check in %%array-reduce will catch it.
(%%array-outer-product
(lambda (a b)
(%%array-reduce f (%%array-map g a (list b)) "array-inner-product: "))
(array-copy (%%array-curry A 1))
(array-copy (%%array-curry (%%array-permute B (%%index-rotate (%%array-dimension B) 1)) 1))))
(define (array-inner-product A f g B)
(cond ((not (array? A))
(error "array-inner-product: The first argument is not an array: " A f g B))
((not (procedure? f))
(error "array-inner-product: The second argument is not a procedure: " A f g B))
((not (procedure? g))
(error "array-inner-product: The third argument is not a procedure: " A f g B))
((not (array? B))
(error "array-inner-product: The fourth argument is not an array: " A f g B))
((not (fx< 0 (%%array-dimension A)))
(error "array-inner-product: The first argument has dimension zero: " A f g B))
((not (fx< 0 (%%array-dimension B)))
(error "array-inner-product: The fourth argument has dimension zero: " A f g B))
((let* ((A-dim (%%array-dimension A))
(A-dom (%%array-domain A))
(B-dom (%%array-domain B)))
(not (and (fx= (%%interval-lower-bound A-dom (fx- A-dim 1))
(%%interval-lower-bound B-dom 0))
(fx= (%%interval-upper-bound A-dom (fx- A-dim 1))
(%%interval-upper-bound B-dom 0)))))
(error (string-append "array-inner-product: The bounds of the last dimension of the first argument "
"are not the same as the bounds of the first dimension of the fourth argument: ")
A f g B))
(else
(%%array-inner-product A f g B))))
;;; Refactored from array-stack to use in list*->array and vector*->array
(define (%%%array-stack k arrays storage-class mutable? safe? caller call/cc-safe?)
(let* ((arrays
(if call/cc-safe?
(map (lambda (A)
(%%->specialized-array A storage-class caller))
arrays)
arrays))
(first-array
(car arrays))
(number-of-arrays
(length arrays))
(domain ;; the common domain of all the arrays
(%%array-domain first-array))
(domain-dimension
(%%interval-dimension domain))
(lowers
(%%interval-lower-bounds->list domain))
(uppers
(%%interval-upper-bounds->list domain))
(result-dimension
(fx+ 1 domain-dimension))
(result-domain
(%%finish-interval
(list->vector (append (take lowers k) (cons 0 (drop lowers k))))
(list->vector (append (take uppers k) (cons number-of-arrays (drop uppers k))))))
(result-dimension
(fx+ 1 domain-dimension))
(result-array
(%%make-specialized-array result-domain
storage-class
(storage-class-default storage-class)
safe?))
(permuted-and-curried-result
(%%array-curry (%%array-permute result-array (%%index-first result-dimension k))
domain-dimension)))
;; copy each array argument to the associated place in stack
(%%array-for-each (lambda (destination source)
(%%move-array-elements destination source caller))
permuted-and-curried-result
(list (%%list->array (make-interval (vector number-of-arrays))
arrays
generic-storage-class
#f
#f
caller)))
(if (not mutable?)
(%%array-freeze! result-array)
result-array)))
(define (array-stack k
arrays
#!optional
(storage-class generic-storage-class)
(mutable? (specialized-array-default-mutable?))
(safe? (specialized-array-default-safe?)))
(%%array-stack k arrays storage-class mutable? safe? #t))
(define (array-stack! k
arrays
#!optional
(storage-class generic-storage-class)
(mutable? (specialized-array-default-mutable?))
(safe? (specialized-array-default-safe?)))
(%%array-stack k arrays storage-class mutable? safe? #f))
(define (%%array-stack k arrays storage-class mutable? safe? call/cc-safe?)
(define caller
(if call/cc-safe?
"array-stack: "
"array-stack!: "))
(cond ((not (and (list? arrays)
(not (null? arrays))
(%%every array? arrays)
(%%every (lambda (a) (%%interval= (%%array-domain a) (%%array-domain (car arrays)))) (cdr arrays))))
(error (string-append caller "Expecting a nonnull list of arrays with the same domains as the second argument: ") k arrays))
((not (and (fixnum? k)
(fx<= 0 k (%%array-dimension (car arrays)))))
(error (string-append caller "Expecting an exact integer between 0 (inclusive) and the dimension of the arrays (inclusive) as the first argument:")
k arrays))
((not (storage-class? storage-class))
(error (string-append caller "Expecting a storage class as the third argument: ") k arrays storage-class))
((not (boolean? mutable?))
(error (string-append caller "Expecting a boolean as the fourth argument: ") k arrays storage-class mutable?))
((not (boolean? safe?))
(error (string-append caller "Expecting a boolean as the fifth argument: ") k arrays storage-class mutable? safe?))
(else
(%%%array-stack k arrays storage-class mutable? safe? caller call/cc-safe?))))
(define (array-append k
arrays
#!optional
(storage-class generic-storage-class)
(mutable? (specialized-array-default-mutable?))
(safe? (specialized-array-default-safe?)))
(%%array-append k arrays storage-class mutable? safe? #t))
(define (array-append! k
arrays
#!optional
(storage-class generic-storage-class)
(mutable? (specialized-array-default-mutable?))
(safe? (specialized-array-default-safe?)))
(%%array-append k arrays storage-class mutable? safe? #f))
(define (%%array-append k arrays storage-class mutable? safe? call/cc-safe?)
(define caller
(if call/cc-safe?
"array-append: "
"array-append!: "))
(cond ((not (and (list? arrays)
(not (null? arrays))
(%%every array? arrays)
(%%every (lambda (a) (= (%%array-dimension a) (%%array-dimension (car arrays)))) (cdr arrays))))
(error (string-append caller "Expecting as the second argument a nonnull list of arrays with the same dimension: ") k arrays))
((not (and (fixnum? k)
(fx< -1 k (%%array-dimension (car arrays)))))
(error (string-append caller "Expecting an exact integer between 0 (inclusive) and the dimension of the arrays (exclusive) as the first argument:")
k arrays))
((not (storage-class? storage-class))
(error (string-append caller "Expecting a storage class as the third argument: ") k arrays storage-class))
((not (boolean? mutable?))
(error (string-append caller "Expecting a boolean as the fourth argument: ") k arrays storage-class mutable?))
((not (boolean? safe?))
(error (string-append caller "Expecting a boolean as the fifth argument: ") k arrays storage-class mutable? safe?))
((not (let ((first-domain (%%array-domain (car arrays))))
(%%every (lambda (d)
(%%every (lambda (i)
(or (fx= i k)
(and (= (%%interval-lower-bound first-domain i) ;; may not be fixnums
(%%interval-lower-bound d i))
(= (%%interval-upper-bound first-domain i)
(%%interval-upper-bound d i)))))
(iota (%%interval-dimension first-domain))))
(cdr (map %%array-domain arrays)))))
(error (string-append caller "Expecting as the second argument a nonnull list of arrays with the same upper and lower bounds (except for index "
(number->string k)
"): ")
k arrays))
(else
(call-with-values
(lambda ()
(let loop ((result '(0))
(arrays arrays))
(if (null? arrays)
(values (reverse result) (car result))
(let ((interval (%%array-domain (car arrays))))
(loop (cons (fx+ (car result)
(- (%%interval-upper-bound interval k)
(%%interval-lower-bound interval k)))
result)
(cdr arrays))))))
(lambda (axis-subdividers kth-size)
(let* ((arrays
(if call/cc-safe?
(map (lambda (A)
(%%->specialized-array A storage-class caller))
arrays)
arrays))
(first-array
(car arrays))
(lowers
;; the domains of the arrays differ only in the kth axis
(%%interval-lower-bounds->vector (%%array-domain first-array)))
(uppers
(%%interval-upper-bounds->vector (%%array-domain first-array)))
(result
;; the result array
(%%make-specialized-array
(let ()
(vector-set! lowers k 0)
(vector-set! uppers k kth-size)
(make-interval lowers uppers)) ;; copies lowers and uppers
storage-class
(storage-class-default storage-class)
safe?))
(translation
;; a vector we'll use to align each argument
;; array into the proper subarray of the result
(make-vector (%%array-dimension first-array) 0)))
(let loop ((arrays arrays)
(subdividers axis-subdividers))
(if (null? arrays)
;; we've assigned every array to the appropriate subarray of result
(if (not mutable?)
(%%array-freeze! result)
result)
(let ((array (car arrays)))
(vector-set! lowers k (car subdividers))
(vector-set! uppers k (cadr subdividers))
(vector-set! translation k (- (car subdividers)
(%%interval-lower-bound (%%array-domain array) k)))
(%%move-array-elements
(%%array-extract result (%%finish-interval lowers uppers))
(%%array-translate array translation)
caller)
(loop (cdr arrays)
(cdr subdividers)))))))))))
(define (array-decurry A-arg
#!optional
(storage-class generic-storage-class)
(mutable? (specialized-array-default-mutable?))
(safe? (specialized-array-default-safe?)))
(%%array-decurry A-arg storage-class mutable? safe? #t))
(define (array-decurry! A-arg
#!optional
(storage-class generic-storage-class)
(mutable? (specialized-array-default-mutable?))
(safe? (specialized-array-default-safe?)))
(%%array-decurry A-arg storage-class mutable? safe? #f))
(define (%%array-decurry A-arg storage-class mutable? safe? call/cc-safe?)
(define caller
(if call/cc-safe?
"array-decurry: "
"array-decurry!: "))
(cond ((not (array? A-arg))
(error (string-append caller "The first argument is not an array: ") A-arg))
((%%array-empty? A-arg)
(error (string-append caller "The first argument is an empty array: ") A-arg))
((not (storage-class? storage-class))
(error (string-append caller "The second argument is not a storage class: ") A-arg storage-class))
((not (boolean? mutable?))
(error (string-append caller "The third argument is not a boolean: ") A-arg storage-class mutable?))
((not (boolean? safe?))
(error (string-append caller "The fourth argument is not a boolean: ") A-arg storage-class mutable? safe?))
(else
(let* ((A (array-copy A-arg))
(A_ (%%array-getter A))
(A_D (%%array-domain A)))
(if (not (%%array-every array? A '()))
(error (string-append caller "Not all elements of the first argument (an array) are arrays: ") A-arg)
(let* ((first-element (apply A_ (%%interval-lower-bounds->list A_D)))
(first-domain (%%array-domain first-element)))
(if (not (%%array-every (lambda (a) (%%interval= (%%array-domain a) first-domain)) A '()))
(error (string-append caller "Not all elements of the first argument (an array) have the domain: ") A-arg)
(let* ((A (if (and call/cc-safe?
(not (%%array-every specialized-array? A '())))
(%%->specialized-array (%%array-map (lambda (A)
(%%->specialized-array A storage-class caller))
A
'())
generic-storage-class
caller)
A))
(result-domain (%%interval-cartesian-product (list A_D first-domain)))
(result (%%make-specialized-array result-domain
storage-class
(storage-class-default storage-class)
safe?))
(curried-result (%%array-curry result (%%interval-dimension first-domain))))
(%%array-for-each (lambda (result argument)
(%%move-array-elements result
argument
caller))
curried-result (list A))
(if (not mutable?)
(%%array-freeze! result)
result)))))))))
(define (array-block A-arg
#!optional
(storage-class generic-storage-class)
(mutable? (specialized-array-default-mutable?))
(safe? (specialized-array-default-safe?)))
(%%array-block A-arg storage-class mutable? safe? #t))
(define (array-block! A-arg
#!optional
(storage-class generic-storage-class)
(mutable? (specialized-array-default-mutable?))
(safe? (specialized-array-default-safe?)))
(%%array-block A-arg storage-class mutable? safe? #f))
(define (%%array-block A-arg storage-class mutable? safe? call/cc-safe?)
(define caller
(if call/cc-safe?
"array-block: "
"array-block!: "))
(cond ((not (array? A-arg))
(error (string-append caller "The first argument is not an array: ") A-arg))
((%%array-empty? A-arg)
(error (string-append caller "The first argument is an empty array: ") A-arg))
((not (storage-class? storage-class))
(error (string-append caller "The second argument is not a storage class: ") A-arg storage-class))
((not (boolean? mutable?))
(error (string-append caller "The third argument is not a boolean: ") A-arg storage-class mutable?))
((not (boolean? safe?))
(error (string-append caller "The fourth argument is not a boolean: ") A-arg storage-class mutable? safe?))
(else
(let* ((A (%%array-translate ;; make lower-bounds zero
(array-copy A-arg) ;; evaluate all (array) elements of A-arg
(vector-map (lambda (x) (- x)) (%%interval-lower-bounds (%%array-domain A-arg)))))
(A_D (%%array-domain A))
(A_dim (%%interval-dimension A_D))
(ks (list->vector (iota A_dim))))
(cond ((not (%%array-every array? A '()))
(error (string-append caller "Not all elements of the first argument (an array) are arrays: ") A-arg))
((not (%%array-every (lambda (a) (fx= (%%array-dimension a) A_dim)) A '()))
(error (string-append caller "Not all elements of the first argument (an array) have the same dimension as the first argument itself: ") A-arg))
((not (%%vector-every
(lambda (k) ;; the direction
(let ((slices ;; the slices in that direction
(%%array-curry (%%array-permute A (%%index-first A_dim k))
(fx- A_dim 1))))
(%%array-every
(lambda (slice)
(let ((kth-width-of-arrays-in-slice
(map (lambda (a)
(%%interval-width (%%array-domain a) k))
(%%array->list slice))))
(or (null? kth-width-of-arrays-in-slice)
(%%every (lambda (w) (= (car kth-width-of-arrays-in-slice) w)) (cdr kth-width-of-arrays-in-slice)))))
slices '())))
ks))
(error (string-append caller "Cannot stack array elements of the first argument into result array: ") A-arg))
(else
;; Here we repeat some of the logic of array-append; otherwise, we could apply array-append
;; iteratively in each coordinate direction, but that could incur more memory allocation.
(let* ((slice-offsets ;; the indices in each direction where the "cuts" are
(vector-map
(lambda (k) ;; the direction
(let* ((pencil ;; a pencil in that direction
;; Amazingly, this works when A_dim is 1.
(apply (%%array-getter (%%array-curry (%%array-permute A (%%index-last A_dim k)) 1))
(make-list (fx- A_dim 1) 0)))
(pencil_
(%%array-getter pencil))
(pencil-size
(%%interval-width (%%array-domain pencil) 0))
(result ;; include sum of all kth interval-widths in pencil
(make-vector (fx+ pencil-size 1) 0)))
(do ((i 0 (fx+ i 1)))
((fx= i pencil-size) result)
(vector-set! result
(fx+ i 1)
(fx+ (vector-ref result i)
(%%interval-width (%%array-domain (pencil_ i)) k))))))
ks))
(A
(if (and call/cc-safe?
(not (%%array-every specialized-array? A '())))
(%%->specialized-array (%%array-map (lambda (A)
(%%->specialized-array A storage-class caller))
A
'())
generic-storage-class
caller)
A))
(A_
(%%array-getter A))
(result
(%%make-specialized-array
(make-interval
(vector-map (lambda (v)
(vector-ref v (fx- (vector-length v) 1)))
slice-offsets))
storage-class
(storage-class-default storage-class)
safe?)))
;; We copy the elements from each input array block to the corresponding block
;; in the result array.
(%%interval-for-each
(lambda multi-index
(let* ((vector-multi-index
(list->vector multi-index))
(corner ;; where the subarray will sit in the result array
(vector-map (lambda (i k)
(vector-ref (vector-ref slice-offsets k) i))
vector-multi-index
ks))
(subarray
(apply A_ multi-index))
(translated-subarray ;; translate the subarray to corner
(%%array-translate
subarray
(vector-map (lambda (x y) (- x y))
corner
(%%interval-lower-bounds (%%array-domain subarray))))))
(%%move-array-elements (%%array-extract result (%%array-domain translated-subarray))
translated-subarray
caller)))
A_D)
(if (not mutable?)
(%%array-freeze! result)
result))))))))
;;; Because array-ref and array-set! have variable number of arguments, and
;;; they have to check on every call that the first argument is an array,
;;; compiled code using array-ref and array-set! can take up to three times
;;; as long as our usual notational convention:
;;;
;;; (let ((A_ (array-getter A))) ... (A_ i j) ...)
;;;
(define array-ref
(case-lambda
((A)
(if (not (array? A))
(error "array-ref: The argument is not an array: " A)
((%%array-getter A))))
((A i0)
(if (not (array? A))
(error "array-ref: The first argument is not an array: " A i0)
((%%array-getter A) i0)))
((A i0 i1)
(if (not (array? A))
(error "array-ref: The first argument is not an array: " A i0 i1)
((%%array-getter A) i0 i1)))
((A i0 i1 i2)
(if (not (array? A))
(error "array-ref: The first argument is not an array: " A i0 i1 i2)
((%%array-getter A) i0 i1 i2)))
((A i0 i1 i2 i3)
(if (not (array? A))
(error "array-ref: The first argument is not an array: " A i0 i1 i2 i3)
((%%array-getter A) i0 i1 i2 i3)))
((A i0 i1 i2 i3 . i-tail)
(if (not (array? A))
(apply error "array-ref: The first argument is not an array: " A i0 i1 i2 i3 i-tail)
(apply (%%array-getter A) i0 i1 i2 i3 i-tail)))))
(define array-set!
(case-lambda
((A v)
(if (not (mutable-array? A))
(error "array-set!: The first argument is not a mutable array: " A v)
((%%array-setter A) v)))
((A v i0)
(if (not (mutable-array? A))
(error "array-set!: The first argument is not a mutable array: " A v i0)
((%%array-setter A) v i0)))
((A v i0 i1)
(if (not (mutable-array? A))
(error "array-set!: The first argument is not a mutable array: " A v i0 i1)
((%%array-setter A) v i0 i1)))
((A v i0 i1 i2)
(if (not (mutable-array? A))
(error "array-set!: The first argument is not a mutable array: " A v i0 i1 i2)
((%%array-setter A) v i0 i1 i2)))
((A v i0 i1 i2 i3)
(if (not (mutable-array? A))
(error "array-set!: The first argument is not a mutable array: " A v i0 i1 i2 i3)
((%%array-setter A) v i0 i1 i2 i3)))
((A v i0 i1 i2 i3 . i-tail)
(if (not (mutable-array? A))
(apply error "array-set!: The first argument is not a mutable array: " A v i0 i1 i2 i3 i-tail)
(apply (%%array-setter A) v i0 i1 i2 i3 i-tail)))))
#|
The code for specialized-array-reshape is derived from _attempt_nocopy_reshape in
https://github.com/numpy/numpy/blob/7f836a9aca57de7fcae188b66ee1d8b60c6fc7b1/numpy/core/src/multiarray/shape.c
which is distributed under the following license:
Copyright (c) 2005-2020, NumPy Developers.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the NumPy Developers nor the names of any
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
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.
|#
(define (specialized-array-reshape array new-domain #!optional (copy-on-failure? #f))
(cond ((not (specialized-array? array))
(error "specialized-array-reshape: The first argument is not a specialized array: " array new-domain))
((not (interval? new-domain))
(error "specialized-array-reshape: The second argument is not an interval " array new-domain))
((not (fx= (%%interval-volume (%%array-domain array))
(%%interval-volume new-domain)))
(error "specialized-array-reshape: The volume of the domain of the first argument is not equal to the volume of the second argument: " array new-domain))
((not (boolean? copy-on-failure?))
(error "specialized-array-reshape: The third argument is not a boolean: " array new-domain copy-on-failure?))
(else
(%%specialized-array-reshape array new-domain copy-on-failure?))))
(define (%%specialized-array-reshape array new-domain copy-on-failure?)
(define (vector-filter p v)
;; Decides whether to include v(k) in the result vector
;; by testing p(k), not p(v(k)).
(let ((n (vector-length v)))
(define (helper k i)
(cond ((fx= k n)
(make-vector i))
((p k)
(let ((result (helper (fx+ k 1) (fx+ i 1))))
(vector-set! result i (vector-ref v k))
result))
(else
(helper (fx+ k 1) i))))
(helper 0 0)))
(if (%%array-empty? array)
;; Any empty array can be reshaped to any other empty array.
(%%finish-specialized-array new-domain
(%%array-storage-class array)
(%%array-body array)
(lambda args (apply error "indexer of empty array should not be called" args)) ;; meaningless
(mutable-array? array)
(%%array-safe? array)
(%%array-in-order? array))
(let* ((indexer
(%%array-indexer array))
(domain
(%%array-domain array))
(lowers
(%%interval-lower-bounds domain))
(uppers
(%%interval-upper-bounds domain))
(dims
(vector-length lowers))
(sides
(vector-map (lambda (u l) (- u l)) uppers lowers))
(args
(vector->list lowers))
(base
(apply indexer args))
(strides
(let ((result (make-vector dims))
(vec-args (let ((result (make-vector dims)))
(do ((i 0 (fx+ i 1))
(args-tail args (cdr args-tail)))
((fx= i dims) result)
(vector-set! result i args-tail)))))
(do ((i 0 (fx+ i 1)))
((fx= i dims) result)
(let ((arg (vector-ref vec-args i)))
;; gives a nonsense result if (vector-ref sides i) is 1,
;; but doesn't matter.
(set-car! arg (+ 1 (car arg)))
(vector-set! result i (fx- (apply indexer args) base))
(set-car! arg (+ -1 (car arg)))))))
(filtered-strides
(vector-filter (lambda (i)
(not (eqv? 1 (vector-ref sides i))))
strides))
(filtered-sides
(vector-filter (lambda (i)
(not (eqv? 1 (vector-ref sides i))))
sides))
(new-sides
(vector-map (lambda (u l) (- u l))
(%%interval-upper-bounds new-domain)
(%%interval-lower-bounds new-domain)))
;; Notation from the NumPy code
(newdims
new-sides)
(olddims
filtered-sides)
(oldstrides
filtered-strides)
(newnd
(vector-length new-sides))
(newstrides
(make-vector newnd 0))
(oldnd
(vector-length filtered-sides)))
;; In the following loops, the error call is in tail position
;; so it can be continued.
;; From this point on we're going to closely follow NumPy's code
(let loop-1 ((oi 0)
(oj 1)
(ni 0)
(nj 1))
(if (and (fx< ni newnd)
(fx< oi oldnd))
;; We find a minimal group of adjacent dimensions from left to right
;; on the old and new intervals with the same volume.
;; We then check to see that the elements in the old array of these
;; dimensions are evenly spaced, so an affine map can
;; cover them.
(let loop-2 ((nj nj)
(oj oj)
(np (vector-ref newdims ni))
(op (vector-ref olddims oi)))
(if (not (fx= np op))
(if (fx< np op)
(loop-2 (fx+ nj 1)
oj
(fx* np (vector-ref newdims nj))
op)
(loop-2 nj
(fx+ oj 1)
np
(fx* op (vector-ref olddims oj))))
(let loop-3 ((ok oi))
(if (fx< ok (fx- oj 1))
(if (not (fx= (vector-ref oldstrides ok)
(fx* (vector-ref olddims (fx+ ok 1))
(vector-ref oldstrides (fx+ ok 1)))))
(if copy-on-failure?
(%%specialized-array-reshape
(%!array-copy array
(%%array-storage-class array)
(mutable-array? array)
(%%array-safe? array)
"specialized-array-reshape: "
#f)
new-domain
#f)
(error "specialized-array-reshape: Requested reshaping is impossible: " array new-domain))
(loop-3 (fx+ ok 1)))
(begin
(vector-set! newstrides (fx- nj 1) (vector-ref oldstrides (fx- oj 1)))
(let loop-4 ((nk (fx- nj 1)))
(if (fx< ni nk)
(begin
(vector-set! newstrides (fx- nk 1) (fx* (vector-ref newstrides nk)
(vector-ref newdims nk)))
(loop-4 (fx- nk 1)))
(loop-1 oj
(fx+ oj 1)
nj
(fx+ nj 1)))))))))
;; The NumPy code then sets the strides of the last
;; dimensions with side-length 1 to a value, we leave it zero.
(let* ((new-lowers
(%%interval-lower-bounds new-domain))
(indexer
(case newnd
((0) (%%indexer-0 base))
((1) (%%indexer-1 base
(vector-ref new-lowers 0)
(vector-ref newstrides 0)))
((2) (%%indexer-2 base
(vector-ref new-lowers 0)
(vector-ref new-lowers 1)
(vector-ref newstrides 0)
(vector-ref newstrides 1)))
((3) (%%indexer-3 base
(vector-ref new-lowers 0)
(vector-ref new-lowers 1)
(vector-ref new-lowers 2)
(vector-ref newstrides 0)
(vector-ref newstrides 1)
(vector-ref newstrides 2)))
((4) (%%indexer-4 base
(vector-ref new-lowers 0)
(vector-ref new-lowers 1)
(vector-ref new-lowers 2)
(vector-ref new-lowers 3)
(vector-ref newstrides 0)
(vector-ref newstrides 1)
(vector-ref newstrides 2)
(vector-ref newstrides 3)))
(else
(%%indexer-generic base
(vector->list new-lowers)
(vector->list newstrides))))))
(%%finish-specialized-array new-domain
(%%array-storage-class array)
(%%array-body array)
indexer
(mutable-array? array)
(%%array-safe? array)
(%%array-in-order? array))))))))
| false |
816e757fb3a1738f59b77271478b1c39983830a2
|
a59389f876d6815a9b5d49167e264c4f4272c9a1
|
/packages/gui/layout.ss
|
3cfe4387abfa595415aeb40abf8ca6dbbe67b229
|
[
"MIT"
] |
permissive
|
chclock/scheme-lib
|
589a54580af5beebe7c6e9f0c7e0f24b41366f64
|
1db806fd0a6874fb461b9960fc5540fb797befcd
|
refs/heads/master
| 2021-01-22T04:10:02.809829 | 2019-03-29T20:25:31 | 2019-03-29T20:25:31 | 102,264,193 | 1 | 0 |
MIT
| 2019-03-29T20:25:32 | 2017-09-03T12:49:06 |
Scheme
|
UTF-8
|
Scheme
| false | false | 9,184 |
ss
|
layout.ss
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;作者:evilbinary on 11/19/16.
;邮箱:[email protected]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(library (gui layout)
(export
linear-layout
frame-layout
flow-layout
grid-layout
pop-layout
calc-child-height
calc-all-child-line-height
%match-parent
%wrap-conent
)
(import (scheme)
(utils libutil)
(gui widget)
(cffi cffi))
(define %match-parent -1.0)
(define %wrap-conent 0)
;;layout
(define (grid-layout row col )
(lambda (widget row col)
'()
)
)
(define pop-layout
(case-lambda
[(widget)
(process-match-parent widget)
(let ((x (vector-ref widget %x))
(y (vector-ref widget %y))
(w (vector-ref widget %w))
(h (vector-ref widget %h))
(top (vector-ref widget %top))
(left (vector-ref widget %left))
(right (vector-ref widget %right))
(bottom (vector-ref widget %bottom))
(sx 0.0)
(sy 0.0)
(child (vector-ref widget %child))
)
(begin
(if (equal? #t (widget-get-attrs widget 'root))
(begin
;;(printf "root status ~a\n" (widget-get-attr widget %status))
(widget-set-attr widget %status 0)
(set! sy h)
(set! sx 0.0))
(begin
(set! sy 0.0)
(set! sx w))
)
(if (equal? #t (widget-get-attrs widget 'center))
(begin
;;(printf "root status ~a\n" (widget-get-attr widget %status))
;;(widget-set-attr widget %status 0)
(set! sy 0.0)
(set! sx 0.0 ))
)
)
(let loop ((c child) (px sx) (py sy) )
(if (pair? c)
(begin
;;(process-match-parent (car c))
(if (procedure? (vector-ref (car c) %layout))
((vector-ref (car c) %layout) (car c)))
(vector-set! (car c) %x px)
(vector-set! (car c) %y py)
(if (equal? #t (widget-get-attrs widget 'center))
(set! px (+ px (widget-get-attr (car c ) %w)))
(set! py (+ py (widget-get-attr (car c) %h))))
(loop (cdr c) px py)
)
))
)]
[(widget layout-info)
(let ((x (vector-ref widget %x))
(y (vector-ref widget %y))
(w (vector-ref widget %w))
(h (vector-ref widget %h)))
'()
)]
))
(define (process-match-parent c )
;;match-parent attrib
(let ((parent (vector-ref c %parent))
(window-width (widget-get-window-width))
(window-height (widget-get-window-height))
)
(if (= (widget-get-attrs c '%w ) %match-parent)
(if (null? parent)
(begin
(widget-set-attr c %w (* 1.0 window-width) ))
(begin
(widget-set-attr c %w (widget-get-attr parent %w) )))
)
(if (= (widget-get-attrs c '%h ) %match-parent)
(if (null? parent)
(begin
(widget-set-attr c %h (* 1.0 window-height)))
(widget-set-attr c %h (widget-get-attr parent %h)))
)))
(define linear-layout
(case-lambda
[(widget)
(process-match-parent widget)
(let ((x (vector-ref widget %x))
(y (vector-ref widget %y))
(w (vector-ref widget %w))
(h (vector-ref widget %h))
(top (vector-ref widget %top))
(left (vector-ref widget %left))
(right (vector-ref widget %right))
(bottom (vector-ref widget %bottom))
(child (vector-ref widget %child))
)
(if (= (widget-get-attr widget %status) 1)
(let loop ((c child) (px left) (py top) )
(if (pair? c)
(begin
;;(printf " ********* ~a py=~a\n" (widget-get-attr (car c) %text) py)
(process-match-parent (car c))
(vector-set! (car c) %x px)
(vector-set! (car c) %y py)
(if (= (widget-get-attr (car c) %status) 1)
(begin
(if (procedure? (vector-ref (car c) %layout))
((vector-ref (car c) %layout) (car c)))
;; (printf " >>>>>>>>~a child total height=~a py=~a\n"
;; (widget-get-attr (car c ) %text)
;; (calc-all-child-line-height (car c) 40.0)
;; py
;; )
(set! py (+ py
(widget-get-attr (car c) %h)
))
)
(begin
(widget-set-attr (car c) %h (widget-get-attr (car c ) %top) )
(set! py (+ py (widget-get-attr (car c ) %top) ))
)
)
;; (printf " ~a status=>~a height=~a x=~a y=~a\n"
;; (widget-get-attr (car c) %text)
;; (widget-get-attr (car c) %status)
;; (widget-get-attr (car c) %h)
;; (widget-get-attr (car c) %x)
;; (widget-get-attr (car c) %y)
;; )
;;(printf "~a pos=~a,~a h=~a\n" (widget-get-attr (car child) %text) px py (vector-ref (car child) %h))
(loop (cdr c) px py )
)
(widget-set-attr widget %h py)
;;(widget-set-attr widget %h (+ top (calc-all-child-line-height widget ) bottom) )
)
;;(widget-set-attr widget %h py)
)
(widget-set-attr widget %h (widget-get-attr widget %top) )
)
(widget-update-pos widget)
(widget-child-update-pos widget)
)]
[(widget layout-info)
(let ((x (vector-ref widget %x))
(y (vector-ref widget %y))
(w (vector-ref widget %w))
(h (vector-ref widget %h)))
'()
)]
))
(define frame-layout
(case-lambda
[(widget)
(process-match-parent widget)
(let ((x (vector-ref widget %x))
(y (vector-ref widget %y))
(w (vector-ref widget %w))
(h (vector-ref widget %h))
(top (vector-ref widget %top))
(left (vector-ref widget %left))
(right (vector-ref widget %right))
(bottom (vector-ref widget %bottom))
(child (vector-ref widget %child))
)
(let loop ((c child) )
(if (pair? c)
(begin
(process-match-parent (car c))
(vector-set! (car c) %x left)
(vector-set! (car c) %y top)
(if (procedure? (vector-ref (car c) %layout))
((vector-ref (car c) %layout) (car c)))
(loop (cdr c) )
)
))
)]
[(widget layout-info)
(let ((x (vector-ref widget %x))
(y (vector-ref widget %y))
(w (vector-ref widget %w))
(h (vector-ref widget %h)))
'()
)]
))
(define flow-layout
(case-lambda
[(widget)
(process-match-parent widget)
(let ((x (vector-ref widget %x))
(y (vector-ref widget %y))
(w (vector-ref widget %w))
(h (vector-ref widget %h))
(top (vector-ref widget %top))
(left (vector-ref widget %left))
(right (vector-ref widget %right))
(bottom (vector-ref widget %bottom))
(parent (vector-ref widget %parent))
(child (vector-ref widget %child))
)
(let loop ((c child) (sx left) (sy top) (ww 0) )
(if (pair? c)
(begin
(vector-set! (car c) %status 1);;force visible may change
(process-match-parent (car c))
(vector-set! (car c) %x (+ sx (vector-ref (car c) %margin-left)))
(vector-set! (car c) %y (+ sy (vector-ref (car c) %margin-top)))
(if (pair? (cdr c))
(set! ww (vector-ref (car (cdr c)) %w)))
(if (> (+ sx (vector-ref (car c) %w) ww ) (- w right
(vector-ref (car c) %margin-right)
(vector-ref (car c) %margin-left) ) )
(begin
(set! sx left)
(set! sy (+ sy (vector-ref (car c) %h)
;;(vector-ref (car c) %margin-top)
(vector-ref (car c) %margin-bottom)
))
)
(begin
(set! sx (+ sx (vector-ref (car c) %w)
(vector-ref (car c) %margin-left)
(vector-ref (car c) %margin-right)
))
)
)
(if (procedure? (vector-ref (car c) %layout))
((vector-ref (car c) %layout) (car c)))
(loop (cdr c) sx sy ww )
)
))
)]
[(widget layout-info)
(let ((x (vector-ref widget %x))
(y (vector-ref widget %y))
(w (vector-ref widget %w))
(h (vector-ref widget %h)))
(process-match-parent widget)
)]
))
(define calc-all-child-line-height
(case-lambda
[(widget height)
(let loop ((child (vector-ref widget %child))
(h 0.0))
(if (pair? child)
(begin
(if (= 0 (widget-get-attr (car child) %status))
(set! h (+ h height))
(begin
(set! h (+ h (calc-all-child-line-height (car child) height)))
;;(vector-ref (car child) %h )
))
;; (printf "==========child ~a status=~a sum height=~a\n"
;; (widget-get-attr (car child) %text)
;; (widget-get-attr (car child) %status)
;; h)
;;(printf "child height=~a\n" (vector-ref (car child) %h ))
(loop (cdr child)
h ))
h))]
[(widget)
(let loop ((child (vector-ref widget %child))
(h 0.0))
(if (pair? child)
(begin
(loop (cdr child) (+ h
(vector-ref (car child) %h )
;;(calc-all-child-line-height (car child))
) ))
h))]
))
;;calc visible child height
(define (calc-child-height widget)
(let loop ((child (vector-ref widget %child))
(height 0.0))
(if (pair? child)
(begin
(if (= (widget-get-attr (car child) %status) 1)
(set! height (+ height (vector-ref (car child) %h ))))
(loop (cdr child) height ))
height)))
)
| false |
a15affd2a753b577afe5da4225a158731241bbfd
|
2767601ac7d7cf999dfb407a5255c5d777b7b6d6
|
/sandbox/cheney/data/fitting.ss
|
5bb79bfc1ffb745cdfdf5da7b4dfdb361c10091d
|
[] |
no_license
|
manbaum/moby-scheme
|
7fa8143f3749dc048762db549f1bcec76b4a8744
|
67fdf9299e9cf573834269fdcb3627d204e402ab
|
refs/heads/master
| 2021-01-18T09:17:10.335355 | 2011-11-08T01:07:46 | 2011-11-08T01:07:46 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,283 |
ss
|
fitting.ss
|
#lang scheme/gui
(require plot)
;; read-data: path -> (listof (vectorof number number number))
(define (read-data path)
(for/list ([line (in-lines (open-input-file path))])
(list->vector (append (map string->number (regexp-split #px"\\s+" line)) (list 1)))))
(define safari-sum-using-exception
(read-data "safari/sumUsingException.txt"))
(define safari-sum-iter-using-exception
(read-data "safari/sumIterUsingException.txt"))
(define safari-sum-using-timeout
(read-data "safari/sumUsingTimeout.txt"))
(define safari-sum-iter-using-timeout
(read-data "safari/sumIterUsingTimeout.txt"))
(define firefox-sum-using-exception
(read-data "firefox-3.1/sumUsingException.txt"))
(define firefox-sum-iter-using-exception
(read-data "firefox-3.1/sumIterUsingException.txt"))
(define firefox-sum-using-timeout
(read-data "firefox-3.1/sumUsingTimeout.txt"))
(define firefox-sum-iter-using-timeout
(read-data "firefox-3.1/sumIterUsingTimeout.txt"))
(define (sequence->list a-seq)
(for/list ((x a-seq))
x))
(define (generate-table data)
(let ([ht (make-hash)]
[counts (make-hash)])
(for ([row data])
(let ([key (vector-ref row 0)]
[value (vector-ref row 1)])
(hash-set! ht
key
(+ value (hash-ref ht key 0)))
(hash-set! counts key (add1 (hash-ref counts key 0)))))
(for/list ([key (sort (sequence->list (in-hash-keys ht)) <)])
(vector key (exact->inexact (/ (hash-ref ht key)
(hash-ref counts key)))))))
(define (print-table a-table)
(for ([row a-table])
(printf "~a\t~a~n" (vector-ref row 0) (vector-ref row 1))))
;; Assumption: the function is linear?
(define (fit-fun number-of-trampolines cost-of-summation-work cost-of-single-trampoline)
(+ cost-of-summation-work (* number-of-trampolines cost-of-single-trampoline)))
(define (find-fit data)
(fit fit-fun '((cost-of-summation-work 1)
(cost-of-single-trampoline 100))
data))
(define (plot-fit data)
(plot (points data)
#;(mix (points data)
(line (fit-result-function (find-fit data))))
#:x-min 0
#:x-max 100
#:y-min 1000
#:y-max 20000))
| false |
d424d6f76b4a75d296d5dacee0d00f87d857235a
|
a8216d80b80e4cb429086f0f9ac62f91e09498d3
|
/lib/scheme/r5rs.sld
|
2edaa0bf8a39a172f7d64855892d9d598a78e4c2
|
[
"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 | 2,491 |
sld
|
r5rs.sld
|
(define-library (scheme r5rs)
(import
(rename (scheme base)
(exact inexact->exact)
(inexact exact->inexact))
(scheme cxr)
(scheme char)
(scheme inexact)
(scheme complex)
(scheme read)
(scheme write)
(scheme file)
(scheme lazy)
(scheme eval)
(scheme repl)
(scheme load)
(only (chibi) null-environment scheme-report-environment))
(export
- ... * / + < <= = => > >= _ abs acos and angle append apply asin assoc assq
assv atan begin boolean?
caaaar caaadr caadar caaddr
cadaar cadadr caddar cadddr
cdaaar cdaadr cdadar cdaddr
cddaar cddadr cdddar cddddr
caaar caadr cadar caddr
cdaar cdadr cddar cdddr
caar cadr cdar cddr
call-with-current-continuation call-with-input-file call-with-output-file
call-with-values car case cdr ceiling char->integer char-alphabetic?
char-ci<? char-ci<=? char-ci=? char-ci>? char-ci>=? char-downcase
char-lower-case? char-numeric? char-ready? char-upcase
char-upper-case? char-whitespace? char? char<? char<=? char=? char>?
char>=? close-input-port close-output-port complex? cond cons cos
current-input-port current-output-port define define-syntax delay
denominator display do dynamic-wind else eof-object? eq? equal? eqv?
eval even? exact->inexact exact? exp expt floor for-each force gcd if
imag-part inexact->exact inexact? input-port? integer->char integer?
interaction-environment lambda lcm length let let-syntax let* letrec
letrec-syntax list list->string list->vector list-ref list-tail list?
load log magnitude make-polar make-rectangular make-string make-vector
map max member memq memv min modulo negative? newline not
null-environment null? number->string number? numerator odd?
open-input-file open-output-file or output-port? pair? peek-char
positive? procedure? quasiquote quote quotient rational? rationalize
read read-char real-part real? remainder reverse round
scheme-report-environment set-car! set-cdr! set! sin sqrt string
string->list string->number string->symbol string-append string-ci<?
string-ci<=? string-ci=? string-ci>? string-ci>=? string-copy
string-fill! string-length string-ref string-set! string? string<?
string<=? string=? string>? string>=? substring symbol->string symbol?
syntax-rules tan truncate values vector vector->list vector-fill!
vector-length vector-ref vector-set! vector? with-input-from-file
with-output-to-file write write-char zero?))
| true |
5cee969a63baab9c167d2efd7b2dab455a3f51d7
|
0b31088d2c5267dc646ab9e05400fbf58fbf4dc2
|
/cffi-to-bmx.scm
|
b46191d111a5bc08ac03e8c76e5c3c7c2a0b4582
|
[] |
no_license
|
braxtonrivers/swig2bmx
|
322a0cd966fbfa28a98340e4c34a0a9256208d7a
|
d3172aff86b052baf4454403c6caf34ca61f96b6
|
refs/heads/master
| 2021-01-25T09:20:24.890362 | 2016-04-03T22:48:07 | 2016-04-03T22:48:07 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 30,817 |
scm
|
cffi-to-bmx.scm
|
; Gambit script to convert CFFI declarations to BlitzMax Extern declarations
(include "srfi-13.scm")
(define command-args #f)
(define stdout (current-output-port))
(define out-port (current-output-port))
(define (pr . a) (apply print port: out-port a))
(define (closeout) (close-output-port out-port) (set! out-port stdout))
(define (openwrite f) (set! out-port (open-output-file f)))
(define-syntax defm
(syntax-rules (IGNORE)
((_ n IGNORE) (define-syntax n (syntax-rules () ((_ . a) #f))))
((_ n def) (define-syntax n def)) ))
(define-syntax when
(syntax-rules ()
((_ condition do0! do1! ...) (if condition (begin do0! do1! ...)))))
(define-syntax unless
(syntax-rules ()
((_ condition do0! do1! ...) (if (not condition) (begin do0! do1! ...)))))
(define (merge-sort pred ls)
(define (split ls)
(letrec ((split-h (lambda (ls ls1 ls2)
(cond
((or (null? ls) (null? (cdr ls)))
(cons (reverse ls2) ls1) )
(else (split-h (cddr ls)
(cdr ls1) (cons (car ls1) ls2) ))))))
(split-h ls ls '())))
(define (merge pred ls1 ls2)
(cond
((null? ls1) ls2)
((null? ls2) ls1)
((pred (car ls1) (car ls2))
(cons (car ls1) (merge pred (cdr ls1) ls2)) )
(else (cons (car ls2) (merge pred ls1 (cdr ls2)))) ))
(cond
((null? ls) ls)
((null? (cdr ls)) ls)
(else (let ((splits (split ls)))
(merge pred
(merge-sort pred (car splits))
(merge-sort pred (cdr splits)) )))))
; CL stuff we don't need
(defm cl:defmacro IGNORE)
(defm cl:eval-when IGNORE)
; C definition parser functions
; Get a low-level BlitzMax type label from a CFFI type label
(define (get-type-tag t . default)
(set! default (if (null? default) ":Byte Ptr" (car default)))
(if (pair? t)
(case (car t)
((:pointer :reference :by-value) ":Byte Ptr")
(else ":<<UNKNOWN>>") )
(case t
((:char :unsigned-char :uchar :int8 :uint8) ":Byte")
((:short :unsigned-short :ushort :int16 :uint16) ":Short")
((:int :unsigned-int :uint :long :unsigned-long :ulong :int32 :uint32 :enum :bool) ":Int")
((:float) ":Float")
((:double) ":Double")
((:long-long :unsigned-long-long :llong :ullong :int64 :uint64) ":Long")
((:pointer :string :char-ref :uchar-ref) ":Byte Ptr")
((:short-ref :ushort-ref) ":Short Ptr")
((:int-ref :enum-ref :uint-ref) ":Int Ptr")
((:long-long-ref :ullong-ref) ":Long Ptr")
((:float-ref) ":Float Ptr")
((:double-ref) ":Double Ptr")
((:void) "")
(else default) )))
; Constants (any type, standalone)
(define (max-defconst name val)
(define (typeof v)
(cond ((fixnum? v) "Int")
((flonum? v) "Double")
((number? v) "Long")
((string? v) "String")
((symbol? v) "String")
(else "<<UNKNOWN>>") ))
(pr "Const " name ":" (typeof val) " = "
(if (string? val) (string-append "\"" val "\"") val)
"\n") )
; Getter funtions for C++ globals (by default, no setters, sorry)
(define cvars '())
(define (enqueue-cvar cname name type)
(set! cvars (cons (list cname name type) cvars)) )
(define (emit-cvars)
(define (emit cname name type)
(pr "Function " name (get-type-tag type) "() = \"MAXGETTER_" cname "\"\n"))
(pr "\nExtern\n\n")
(for-each (lambda (v) (apply emit v)) cvars)
(pr "\nEnd Extern\n\n") )
; Create global getter wrapper library
(define (emit-cvar-wrapper)
(define (emit cname name type)
(pr " typeof(f(" cname ")) MAXGETTER_" name "() { return f(" cname "); }\n"))
(pr "#include \"" file ".h\"\n\nUSING\n\n"
"template<typename T> T f(T x) { return x; }\n\n"
"extern \"C\" {\n")
(for-each (lambda (v) (apply emit v)) cvars)
(pr "}\n") )
; Enumerations (types containing only constant ints)
(define unk-enums '())
(define (max-defenum name vals)
(define (unknown-val n)
(set! unk-enums (append unk-enums (list n)))
"<<UNKNOWN>>")
(pr "'enum " name "\n")
(unless (null? vals)
(let loop ((rest (cdr vals))
(enum (car vals))
(val 0)
(prev ""))
(define name
(let ((n (symbol->string (if (list? enum) (car enum) enum))))
(substring n 1 (string-length n)) ))
(set! val (if (list? enum)
(if (or (> (length enum) 2) (pair? (cadr enum)))
(unknown-val name) (cadr enum))
val))
(pr (if (equal? val "<<UNKNOWN>>") "'" ""))
(pr " Const " name ":Int = " val "\n")
(if (null? rest)
#f
(loop (cdr rest)
(car rest)
(if (number? val) (+ 1 val) (string-append prev " + 1"))
name))))
(pr "\n") )
; Extern function declarations
(define funcs '())
(define (enqueue-cfun cname name rtype argtypes)
(set! funcs (cons (list cname name argtypes rtype) funcs)) )
(define (examine-overload n)
(let* ((nl (string-length n))
(c (do ((c (fx- nl 1) (fx- c 1))
(l 0 (fx+ l 1)))
((or (< c 0) (not (char-numeric? (string-ref n c)))) l)
#f) )
(st (fx- nl c)) )
(if (and (fx> c 0)
(string=? (substring n (fx- st 6) st) "_SWIG_") )
(substring n st nl)
#f) ))
(define (emit-funcs)
(define (build-args-list al)
(if (null? al)
""
(let loop ((rst (cdr al)) (this (car al)) (str ""))
(let* ((name (symbol->string (car this)))
(type (cadr this))
(arg (string-append "_" name (get-type-tag type))))
(if (null? rst)
(string-append str arg)
(loop (cdr rst) (car rst) (string-append str arg ", ")) )))))
(define (emit cname name argtypes rtype)
(let* ((over (examine-overload cname))
(bname (string-append (symbol->string name)
(if over (string-append "_OVERLOAD_" over) ""))))
(pr "Function " bname
(get-type-tag rtype) "("
(build-args-list argtypes)
") = \"" cname "\"\n") ))
(pr "\nPrivate\nExtern\n\n")
(for-each (lambda (f) (apply emit f)) funcs)
(pr "\nEnd Extern\nPublic\n\n") )
; C definition macros:
; translate the CFFI declarations into something we can use
(defm cl:defconstant
(syntax-rules ()
((_ n val) (max-defconst (quote n) (quote val))) ))
(defm cffi:defcvar
(syntax-rules ()
((_ (cn n) t) (enqueue-cvar (quote cn) (quote n) (quote t))) ))
(defm cffi:defcenum
(syntax-rules ()
((_ n . sl) (max-defenum (quote n) (quote sl))) ))
(defm cffi:defcfun
(syntax-rules ()
((_ (cn n) rt . at) (enqueue-cfun (quote cn) (quote n) (quote rt) (quote at))) ))
(defm cffi:defcunion ;Not required
IGNORE)
(defm cffi:defcstruct ;Not required - types are rebuilt from the CLOS layer
IGNORE)
(set! command-args (read))
(define file (symbol->string (car command-args)))
(pr "Wrapping: " file "\n")
(pr "With imports: ")
(for-each (lambda (lib) (pr lib " ")) (cdr command-args))
(pr "\n")
; Load the base procedures file, emit and list basic definitions
(openwrite (string-append file "-base.bmx"))
(pr "\n' " file " wrapper\n\n"
"' This file was automatically generated by CFFI2BMX\n"
"' from a CFFI wrapper generated by SWIG\n\n"
"' This is a flat procedural base interface\n"
"' It exists only to provide extern declarations for the high-level interface\n\n")
(load (string-append file ".lisp"))
(unless (null? unk-enums)
(pr "Include \"" file ".extra-enums.bmx\"\n\n") )
(set! cvars (reverse cvars))
(emit-cvars)
(set! funcs (reverse funcs))
(emit-funcs)
(closeout) ;done generating -base.bmx
(unless (null? unk-enums)
(pr "\n" (length unk-enums)
" enum (constant) values could not be computed by CFFI2BMX\n"
"A program to compute them for you has been written to " file
".gen-enums.cpp\n"
"You may need to tweak it slightly to get the right namespaces\n"
"or #include paths. Run it and it will print the missing "
"declarations.\n\n")
(openwrite (string-append file ".gen-enums.cpp"))
(pr "\n// Some enum values could not be inserted automatically\n"
"// Compile and run this program with g++ and it will generate\n"
"// the missing constants to paste into " file ".bmx\n\n"
"#include <cstdio>\n"
"#include \"" file ".h\"\n\n"
"#define SHOWC(N) printf(\"Const \" #N \":Int = %d\\n\", N);\n\n"
"int main() {\n")
(for-each (lambda (n) (pr " SHOWC(" n ");\n")) unk-enums)
(pr " return 0;\n}\n\n")
(closeout) )
(unless (null? cvars)
(pr (length cvars) " global variables were exported by " file "\n"
"These will be made available through the accessor functions defined in\n"
file ".cvar-wrapper.cpp\n\n")
(openwrite (string-append file ".cvar-wrapper.cpp"))
(emit-cvar-wrapper)
(set! cvars #f)
(closeout) )
; Try to coalesce overloads representing default parameters into single entries
(define-structure func cname name args aopt rtype)
(define (list->func l)
(apply (lambda (c n a r) (make-func c (symbol->string n) a 0 r)) l) )
(define defaults (list (list->func (car funcs))))
(define (coalesce cname name args rtype)
;Defaults follow each other in order starting with all params, so it's easy
; to see if a function matches the pattern by comparing types and names
(let ((prev (car defaults)) (name (symbol->string name)))
(if (and (string-ci=? name (func-name prev)) (equal? rtype (func-rtype prev))
(let loop ((atl args) (ptl (func-args prev)))
(cond ((null? ptl) #f)
((null? atl) #t)
((equal? (car atl) (car ptl))
(loop (cdr atl) (cdr ptl)) )
(else #f) )))
(func-aopt-set! (car defaults) (fx+ (func-aopt (car defaults)) 1))
(unless (and (string-ci=? name (func-name prev)) (equal? args (func-args prev)) (equal? rtype (func-rtype prev)))
(set! defaults (cons (make-func cname name args 0 rtype) defaults)) )))) ;Don't emit if the difference is constness
(for-each (lambda (f) (apply coalesce f)) (cdr funcs))
(set! funcs #f)
(define overloads (make-table size: 1024 init: '() test: string-ci=?))
(for-each
(lambda (d)
(let ((n (func-name d)))
(table-set! overloads n (cons d (table-ref overloads n))) ))
defaults)
;overloads is now a table of names each keyed to a list of overloads, defaults not represented
(set! defaults #f)
; CLOS definition parser functions
(define maxified-names (make-table init: #f test: eq?))
(define (maxify-name name)
(define (maxify name)
(set! name ;substring from after the last :
(do ((c (string-length name) (fx- c 1)))
((or (fx= c 0) (char=? (string-ref name (fx- c 1)) #\:))
(substring name c (string-length name)) )))
(set! name ;Capitalise after and remove each -
(do ((c 0 (fx+ c 1))
(r 0 (if (char=? (string-ref name r) #\-) r (fx+ r 1)))
(u #t (if (char=? (string-ref name r) #\-) #t #f)) )
((fx= c (string-length name)) (substring name 0 r))
(let ((chr (string-ref name c)))
(string-set! name r (if u (char-upcase chr) chr)) )))
name)
(case name
((*) "Mul") ((/) "Div") ((%) "Rmdr") ((+) "Add") ((-) "Sub") ((^) "Pow")
((!) "lNot") ((~) "bNot") ((<<) "lShift") ((>>) "rShift")
((<) "Less") ((>) "Greater") ((<=) "lEq") ((>=) "gEq") ((==) "Eq") ((!=) "nEq")
((=) "_assign") ((&) "bitAnd") ((|\||) "bitOr")
((+=) "AddAssign") ((-=) "SubAssign") ((*=) "MulAssign") ((/=) "DivAssign")
((%=) "RmdrAssign") ((<<=) "lShiftAssign") ((>>=) "rShiftAssign")
((&=) "bitAndAssign") ((^=) "PowAssign") ((|\|=|) "bitOrAssign")
((new) "Make")
((end to next exit field forever local then ptr) (string-append "_" (symbol->string name)))
(else
(let ((n (table-ref maxified-names name)))
(if n
n
(begin (set! n (maxify (symbol->string name)))
(table-set! maxified-names name n)
n) )))))
; Declaration for a class
(define classes '())
(define objtypes (make-table test: string-ci=? init: #f))
(define-structure class name base methods ext-bases)
(define (enqueue-class name base ext-bases)
(let* ((name (maxify-name name))
(nc (make-class name (maxify-name base) (make-table test: equal?) (map maxify-name ext-bases))))
(table-set! objtypes name name)
(set! classes (cons nc classes)) ))
; Declaration of a method
(define (enqueue-method name lname . a)
(table-set! (class-methods (car classes))
(cond ((and (eq? name '-) (fx= (length (car a)) 1)) 'Neg)
((pair? name) (string-append (car name) (maxify-name (cdr name))))
(else name) )
lname) )
; CLOS definition macros:
(defm cl:defclass ;Class declarations
(syntax-rules ()
((_ name (base) flds) (enqueue-class (quote name) (quote base) '()))
((_ name () flds) (enqueue-class (quote name) (string->symbol basetype) '()))
((_ name (base0 . baser) flds) (enqueue-class (quote name) (quote base0) (quote baser))) ))
(defm cl:defmethod ;Method declarations
(syntax-rules (initialize-instance)
((_ (cl:setf name) args (lname . cargs)) (enqueue-method (cons "set" (quote name)) (quote lname)))
((_ () args (lname . cargs)) (enqueue-method 'Call (quote lname))) ;Syntax error in -CLOS
((_ name args (lname . cargs)) (enqueue-method (quote name) (quote lname) (quote args)))
((_ initialize-instance . rst) (enqueue-method 'new #f)) ))
(defm cl:shadow ;Overloaded operator declarations, in this case
IGNORE)
; Load custom method advice
(define (before-method-advice c n a)
#f)
(define (var-call-advice arg n)
(string-append (car arg) (number->string n)) )
(define (after-method-advice m)
#f)
(define (return-special-advice c n r)
#f)
(define (return-object-advice c n r)
r)
(define (interface-typemap t)
#f)
(define (additional-imports)
"")
(let ((advice-file (string-append file "-method-advice.scm")))
(if (file-exists? advice-file)
(load advice-file)
#f) )
; Load the CLOS definitions file and build the high-level OO interface
(openwrite (string-append file "-interface.bmx"))
(pr "\n' " file " wrapper\n\n"
"' This file was automatically generated by CFFI2BMX\n"
"' from a CFFI wrapper generated by SWIG\n\n"
"' This is the high-level/OOP interface - use this where possible\n\n"
"Import \"" file "_wrap.o\"\n"
"Import \"" file ".cvar-wrapper.o\"\n"
"Import \"" file ".cast-wrapper.o\"\n")
(let ((helper-bin (string-append file ".help-wrap.o")))
(when (file-exists? helper-bin)
(pr "Import \"" helper-bin "\"\n") ))
(for-each (lambda (lib) (pr "Import \"" lib "\"\n")) (cdr command-args))
(pr (additional-imports) "\nSuperStrict\nNoDebug\n\n")
(pr "Include \"" file "-base.bmx\"\n")
(let ((helper-file (string-append file "-helper.bmx")))
(when (file-exists? helper-file)
(pr "Include \"" helper-file "\"\n") ))
(pr "\n")
(define basetype (string-append "_" file "_Object"))
(pr "Type " basetype " Abstract\n"
" Field _ptr:Byte Ptr\n"
" Field _del(_:Byte Ptr)\n"
" Function _defaultFree(p:Byte Ptr) Final\n"
" End Function\n"
" Function _getPtr:Byte Ptr(o:" basetype ") Final\n"
" If o Then Return o._ptr ; Else Return Byte Ptr(0)\n"
" End Function\n"
" Method New()\n"
" _del = " basetype "._defaultFree\n"
" End Method\n"
" Method Delete()\n"
" _del(_ptr)\n"
" End Method\n"
" Method Compare:Int(with:Object)\n"
" If " basetype "(with) Then Return _ptr - " basetype "(with)._ptr ; Else Return with.Compare(self)\n"
" End Method\n"
" Method _withPtr:" basetype "(_p:Byte Ptr) Final\n"
" _ptr = _p ; Return Self\n"
" End Method\n"
" Method _withDel:" basetype "(_f:Byte Ptr) Final\n"
" _del = _f ; Return Self\n"
" End Method\n"
" Method _Claim(o: " basetype ") Final\n"
" _del = o._del ; o._del = _defaultFree\n"
" End Method\n"
"End Type\n\n")
(load (string-append file "-clos.lisp"))
(set! classes (reverse classes))
; Get a high-level BlitzMax type from a CFFI type tag: '(tagstr orig description . extra)
(define-structure max-type tag orig desc extra)
(define (max-type-definition tag)
(define (object-type tag)
(let ((t (cadr tag)))
(cond ((and (string-index t #\( ) (string-index t #\) ))
(make-max-type ":Byte Ptr" tag 'prim #f))
((and (string-index t #\<) (string-index t #\>))
;(make-max-type (string-append ":template{" t "}") tag 'prim #f))
(make-max-type (string-append ":Byte Ptr") tag 'prim #f))
((table-ref objtypes (strip-c++isms t))
=> (lambda (t) (make-max-type (string-append ":" t) tag 'object #f)) )
(else
(make-max-type ":Byte Ptr" tag 'prim #f) ))))
(define (basic-type tag)
(make-max-type (get-type-tag tag ":<<UNKNOWN>>") tag 'prim #f) )
(define (make-reftype t tag)
(make-max-type t tag 'prim 'reference) )
(let* ((t0 (interface-typemap tag))
(t1 (if t0 t0 (if (pair? tag) (object-type tag) #f)))
(t2 (if t1 t1 (case tag
((:char-ref :uchar-ref) (make-reftype ":Byte" tag))
((:short-ref :ushort-ref) (make-reftype ":Short" tag))
((:int-ref :enum-ref :uint-ref) (make-reftype ":Int" tag))
((:long-long-ref :ullong-ref) (make-reftype ":Long" tag))
((:float-ref) (make-reftype ":Float" tag))
((:double-ref) (make-reftype ":Double" tag))
(else #f) ))))
(if t2 t2 (basic-type tag)) ))
(define (strip-c++isms s)
(let* ((ts (string-index s #\<))
(s (if ts (substring s 0 ts) s))
(ps (string-index-right s #\:))
(s (if ps (substring s (+ 1 ps) (string-length s)) s))
(ss (string-index s #\space)) )
(substring s 0 (if ss ss (string-length s))) ))
(define (default-param-value t)
(cond ((string-ci=? t ":Int") "-2147483648")
((string-ci=? t ":Long") "-9223372036854775808")
((string-ci=? t ":Byte") "-128")
((string-ci=? t ":Short") "-32768")
((or (string-ci=? t ":Float") (string-ci=? t ":Double")) "-1e100000")
(else "Null") ))
(define clash-list #f)
(define omitted-warning '())
(define (is-special? a)
(eq? (max-type-desc (cdr a)) 'special) )
(define (is-object? a)
(eq? (max-type-desc (cdr a)) 'object) )
(define (is-primitive? a)
(eq? (max-type-desc (cdr a)) 'prim) )
(define (is-constref? a)
(and (is-primitive? a) (eq? (max-type-extra (cdr a)) 'reference)) )
(define (emit-proc-body class-name mname mdef is-overload is-method is-ctor)
(define (emit-parameters pl dct)
(unless (null? pl)
(let loop ((pl pl) (dct (fx- (length pl) dct)))
(let* ((nx (car pl)) (t (max-type-tag (cdr nx))))
(pr (car nx) t)
(if (fx< dct 1) (pr " = " (default-param-value t)) #f)
(unless (null? (cdr pl))
(pr ", ")
(loop (cdr pl) (fx- dct 1)) )))))
(define (extend-name mname args aopt retry)
(let ((args (if (fx> aopt 0) (reverse (list-tail (reverse args) aopt)) args)))
(if (null? args)
#f;(if is-ctor (set! mname "MakeNew") (set! mname (string-append mname "0")))
(begin
(set! mname (string-append mname "With"))
(for-each
(lambda (p)
(set! mname (string-append mname (capitalize (tag-to-name
(if retry
(let* ((t (max-type-tag (cdr p))) (sp (string-index t #\space)))
(if sp
(begin (set! t (string-append t)) (string-set! t sp #\_) t)
t) )
(car p) )))))) ;Varnames by default
args) )))
mname)
(define (capitalize s)
(string-set! s 0 (char-upcase (string-ref s 0)))
s)
(define (tag-to-name tag)
(substring tag 1 (string-length tag)) )
(define (is-value rt)
(let ((orig (max-type-orig rt)))
(and (pair? orig) (eq? (car orig) ':by-value)) ))
(define (var-call arg n)
(cond ((is-object? arg) (string-append "p" (number->string n)))
((is-special? arg) (var-call-advice arg n))
((is-constref? arg) (string-append "Varptr(" (car arg) ")"))
(else (car arg)) ))
(define (cat-args args ct st)
(do ((ct ct (fx- ct 1))
(n st (fx+ n 1))
(args args (cdr args))
(str "") )
((fx= ct 0) str)
(set! str (string-append str (var-call (car args) n) (if (fx= 1 ct) "" ", "))) ))
(define (func-maxname f inc)
(let ((over (examine-overload (func-cname f))) (lname (func-name f)))
(if over
(string-append lname "_OVERLOAD_" (number->string (fx+ inc (string->number over))))
lname) ))
(let* ((rtype (max-type-definition (func-rtype mdef)))
(is-void (eq? (func-rtype mdef) ':void))
(args0 (map
(lambda (a)
(cons (string-append "_" (symbol->string (car a))) (max-type-definition (cadr a))) )
(func-args mdef) ))
(args (if (and (not (null? args0)) (string=? (caar args0) "_self"))
(cdr args0) args0) )
(max-name (if is-overload (extend-name mname args (func-aopt mdef) #f) mname)) )
(when (table-ref clash-list max-name)
(set! max-name (extend-name mname args (func-aopt mdef) #t)) )
(if (table-ref clash-list max-name)
(set! omitted-warning (cons (cons class-name max-name) omitted-warning))
(begin
(table-set! clash-list max-name #t)
(pr (if (and is-method (not is-ctor)) " Method " " Function ")
max-name (max-type-tag rtype) "(")
(emit-parameters args (func-aopt mdef))
(pr ")\n")
(before-method-advice class-name max-name args)
(do ((args args (cdr args))
(c 0 (fx+ c 1)) )
((null? args) #t)
(let ((a (car args)))
(when (is-object? a)
(pr "\t\tLocal p" c ":Byte Ptr = " basetype "._getPtr(" (car a) ")\n") )))
(unless is-void ;Declare return slot
(pr " Local ret" (get-type-tag (max-type-orig rtype))
(if (fx= 0 (func-aopt mdef)) " = " "\n") ))
(let* ((has-self (and is-method (not is-ctor)))
(args (if has-self (cons (cons "Self._ptr" (make-max-type "" #f 'prim #f)) args) args))
(la (length args))
(stct (if has-self -1 0))
(aopt (func-aopt mdef)) )
(if (fx= 0 aopt) ;Call wrapper
(pr (if is-void "\t\t." ".") (func-maxname mdef 0) "(" (cat-args args la stct) ")\n")
(begin
(pr "\t\t")
(do ((aopt aopt (fx- aopt 1))
(narg (list-tail args (fx- la aopt)) (cdr narg)) )
((fx= aopt 0) #t)
(pr "If " (caar narg) " = " (default-param-value (max-type-tag (cdar narg))) "\n\t\t\t"
(if is-void "." "ret = .") (func-maxname mdef aopt) "(" (cat-args args (fx- la aopt) stct)
")\n\t\tElse") )
(pr "\n\t\t\t" (if is-void "." "ret = .") (func-maxname mdef 0) "(" (cat-args args la stct) ")\n\t\tEndIf\n") )))
(after-method-advice class-name max-name args)
(unless is-void ;Actually return
(pr " Local rval" (max-type-tag rtype) " = "
(case (max-type-desc rtype)
((special) (return-special-advice class-name max-name rtype))
((prim)
(if (eq? (max-type-extra rtype) 'reference) "ret[0]" "ret") )
((object)
(return-object-advice class-name max-name
(let ((tn (tag-to-name (max-type-tag rtype))))
(string-append tn
"(New _" tn "._withPtr(ret)"
(if (or is-ctor (is-value rtype))
(string-append "._withDel(delete_" tn "))")
")") ))))))
(if (eq? (max-type-desc rtype) 'object)
(pr "\n\t\tIf rval._ptr Then Return rval ; Else Return Null\n")
(pr " ; Return rval\n") ))
(pr (if (and is-method (not is-ctor)) " End Method\n" " End Function\n")) ))))
(define (sort-overloads fs is-method)
(define (is-constref? t)
(and (eq? (max-type-desc t) 'prim) (eq? (max-type-extra t) 'reference)) )
(define (is-nullary? f)
(let* ((args (func-args f)) (al (if is-method (cdr args) args)))
(null? al) ))
(define (cmp l r)
(cond ((is-nullary? l) #t)
((is-nullary? r) #f)
((is-constref? (max-type-definition (func-rtype l))) #t)
((is-constref? (max-type-definition (func-rtype r))) #f)
(else #t) ))
(merge-sort cmp fs) )
(for-each ;Emit implementations
(lambda (c)
(pr "Type " (class-name c) " Extends " (class-base c) " Abstract\n")
(for-each
(lambda (ext-base)
(pr "\tMethod As_" ext-base ":" ext-base "()\n"
"\t\tLocal ret:" ext-base " = New _" ext-base "\n"
"\t\tret._withPtr(dynamic_cast__" (class-name c) "_to_" ext-base "(_ptr))\n"
"\t\tReturn ret\n"
"\tEnd Method\n") )
(class-ext-bases c))
(pr "\tFunction _Cast:" (class-name c) "(o: " basetype ")\n"
"\t\tReturn " (class-name c) "(New _" (class-name c) "._withPtr(o._ptr))\n"
"\tEnd Function\n")
(table-for-each
(lambda (mname lname)
(set! clash-list (make-table test: string=? init: #f))
(let* ((is-ctor (not lname))
(lname (if lname
(symbol->string lname)
(string-append "new_" (class-name c))))
(mname (if (symbol? mname) (maxify-name mname) mname))
(mdef (sort-overloads (table-ref overloads lname) (not is-ctor))) )
(table-set! overloads lname)
(emit-proc-body (class-name c) mname (car mdef) is-ctor #t is-ctor)
(for-each
(lambda (d) (emit-proc-body (class-name c) mname d #t #t is-ctor))
(cdr mdef) )))
(class-methods c) )
(class-methods-set! c #f)
(table-set! overloads (string-append "delete_" (class-name c)))
(pr "End Type\n\n") )
classes)
(pr "\nType " file " Final\n")
(set! clash-list (make-table test: string=? init: #f))
(table-for-each ;Emit public global functions (everything left in overloads list)
(lambda (lname fs)
(set! fs (sort-overloads fs #f))
(emit-proc-body file lname (car fs) #f #f #f)
(for-each (lambda (f) (emit-proc-body file lname f #t #f #f)) (cdr fs)) )
overloads)
(pr "End Type\n\n")
(set! clash-list #f)
(pr "\nPrivate\n\n")
(for-each ;Emit Final seal declarations
(lambda (c)
(pr "Type _" (class-name c) " Extends "
(class-name c) " Final ; End Type\n") )
classes)
(pr "\n")
(pr "\nExtern\n\n") ;Emit dynamic cast wrappers
(for-each
(lambda (c)
(for-each
(lambda (b) (pr "Function dynamic_cast__" (class-name c) "_to_" b ":Byte Ptr(s:Byte Ptr)\n"))
(class-ext-bases c) ))
classes)
(pr "\nEnd Extern\nPublic\n\n")
(closeout)
(openwrite (string-append file ".cast-wrapper.cpp"))
(pr "#include \"" file ".h\"\n\nextern \"C\" {\n")
(for-each
(lambda (c)
(for-each
(lambda (b)
(pr "void * dynamic_cast__" (class-name c) "_to_" b "(" (class-name c) " * s) {\n"
"\treturn dynamic_cast<" b " *>(s);\n}\n"))
(class-ext-bases c) ))
classes)
(pr "}\n")
(closeout)
(unless (null? omitted-warning)
(pr "Warning: the following overloads could not be disambiguated and were\n"
"not emitted for all types:\n")
(for-each
(lambda (n) (pr " " (car n) "." (cdr n) "\n"))
(reverse omitted-warning) ))
| true |
24e0f13ff472fae2f091587d2e64b1ee83e8b6bf
|
557c51d080c302a65e6ef37beae7d9b2262d7f53
|
/workspace/scheme-tester/a/a6.scm
|
e56a29b2110efaa024bb71c3b950f3ba068abbce
|
[] |
no_license
|
esaliya/SchemeStack
|
286a18a39d589773d33e628f81a23bcdd0fc667b
|
dcfa1bbfa63b928a7ea3fc244f305369763678ad
|
refs/heads/master
| 2020-12-24T16:24:08.591437 | 2016-03-08T15:30:37 | 2016-03-08T15:30:37 | 28,023,003 | 3 | 4 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 14,350 |
scm
|
a6.scm
|
;;----------------------------------
;; B521 - Assignment 6
;;----------------------------------
;; Name: Saliya Ekanayake
;; ID: 0002560797
;; Email: [email protected]
;;----------------------------------
;----------------------------------------------------------------
;; Something I grab from Fall 2010 class.
;----------------------------------------------------------------
;;(define rember*1
;; (lambda (ls)
;; (cond
;; [(null? ls) '()]
;; [(pair? (car ls))
;; (cond
;; [(equal? (car ls) (rember*1 (car ls)))
;; (cons (car ls) (rember*1 (cdr ls)))]
;; [else (cons (rember*1 (car ls)) (cdr ls))])]
;; [(eq? (car ls) '?) (cdr ls)]
;; [else (cons (car ls) (rember*1 (cdr ls)))])))
(define rember*1
(lambda (ls k)
(cond
[(null? ls) (k '())]
[(pair? (car ls))
(rember*1 (car ls) (lambda (v) (cond
[(equal? (car ls) v) (rember*1 (cdr ls) (lambda (v) (k (cons (car ls) v))))]
[(rember*1 (car ls) (lambda (v) (k (cons v (cdr ls)))))])))]
[(eq? (car ls) '?) (k (cdr ls))]
[else (rember*1 (cdr ls) (lambda (v) (k (cons (car ls) v))))])))
;; Another nice one. See your pascal example as well. Also see tests/Fall2010.scm for possible mistake as well.
;;
;;(define M
;; (lambda (f)
;; (lambda (ls)
;; (cond
;; ((null? ls) '())
;; (else (cons (f (car ls)) ((M f) (cdr ls))))))))
;;>((M add1) '(1 2 3))
(define M
(lambda (f k)
(k (lambda (ls c)
(cond
((null? ls) (c '()))
(else (M f (lambda (g) (g (cdr ls) (lambda (l) (c (cons (f (car ls)) l))))))))))))
;;>(M add1 (lambda (g) (g '(1 2 3) (lambda (x) x))))
;----------------------------------------------------------------
;----------------------------------------------------------------
; Test macro (taken happily from the assignment itself :))
; ---------------------------------------------------------------
(define-syntax test
(syntax-rules ()
((_ title tested-expression expected-result)
(let* ((expected expected-result)
(produced tested-expression))
(if (equal? expected produced)
(printf "~s works!\n" title)
(error
'test
"Failed ~s: ~a\nExpected: ~a\nComputed: ~a"
title 'tested-expression expected produced))))))
;--------------------------------------------------------------------------------------
; empty-k procedure, taken happily from the assignment itself :)
;--------------------------------------------------------------------------------------
(define empty-k
(lambda ()
(let ([okay #t])
(lambda (v)
(if okay
(begin
(set! okay #f)
v)
(error 'empty-k "k invoked in non-tail position"))))))
;--------------------------------------------------------------------------------------
; non cps version of length
;--------------------------------------------------------------------------------------
;;(define length
;; (lambda (ls)
;; (cond
;; [(null? ls) 0]
;; [else (add1 (length (cdr ls)))])))
;--------------------------------------------------------------------------------------
;--------------------------------------------------------------------------------------
; cps version of length, i.e. length-cps
;--------------------------------------------------------------------------------------
(define length-cps
(lambda (ls k)
(cond
[(null? ls) (k 0)]
[else (length-cps (cdr ls) (lambda (v) (k (add1 v))))])))
;--------------------------------------------------------------------------------------
;--------------------------------------------------------------------------------------
; non cps version of count-syms*
;--------------------------------------------------------------------------------------
;;(define count-syms*
;; (lambda (ls)
;; (cond
;; [(null? ls) 0]
;; [(pair? (car ls)) (+ (count-syms* (car ls)) (count-syms* (cdr ls)))]
;; [(symbol? (car ls)) (add1 (count-syms* (cdr ls)))]
;; [else (count-syms* (cdr ls))])))
;--------------------------------------------------------------------------------------
;--------------------------------------------------------------------------------------
; cps version of count-syms*, i.e. count-syms*-cps
;--------------------------------------------------------------------------------------
(define count-syms*-cps
(lambda (ls k)
(cond
[(null? ls) (k 0)]
[(pair? (car ls)) (count-syms*-cps (car ls) (lambda (v) (count-syms*-cps (cdr ls) (lambda (x) (k (+ v x))))))]
[(symbol? (car ls)) (count-syms*-cps (cdr ls) (lambda (v) (k (add1 v))))]
[else (count-syms*-cps (cdr ls) k)])))
;--------------------------------------------------------------------------------------
;--------------------------------------------------------------------------------------
; non cps version of tree-sum
;--------------------------------------------------------------------------------------
;;(define tree-sum
;; (lambda (ls)
;; (cond
;; [(null? ls) 0]
;; [(pair? (car ls))
;; (+ (tree-sum (car ls))
;; (tree-sum (cdr ls)))]
;; [else (+ (car ls) (tree-sum (cdr ls)))])))
;--------------------------------------------------------------------------------------
;--------------------------------------------------------------------------------------
; cps version of tree-sum, i.e. tree-sum-cps
;--------------------------------------------------------------------------------------
(define tree-sum-cps
(lambda (ls k)
(cond
[(null? ls) (k 0)]
[(pair? (car ls)) (tree-sum-cps (car ls) (lambda (v) (tree-sum-cps (cdr ls) (lambda (x) (k (+ v x))))))]
[else (tree-sum-cps (cdr ls) (lambda (v) (k (+ (car ls) v))))])))
;--------------------------------------------------------------------------------------
;--------------------------------------------------------------------------------------
; non cps version of walk, (this is already tail recursive)
;--------------------------------------------------------------------------------------
;;(define walk
;; (lambda (v ls)
;; (cond
;; [(symbol? v)
;; (let ((p (assq v ls)))
;; (cond
;; [p (walk (cdr p) ls)]
;; [else v]))]
;; [else v])))
;--------------------------------------------------------------------------------------
;--------------------------------------------------------------------------------------
; cps version of walk, i.e. walk-cps
;--------------------------------------------------------------------------------------
(define walk-cps
(lambda (v ls k)
(cond
[(symbol? v) (let ([p (assq v ls)])
(cond
[p (walk-cps (cdr p) ls k)]
[else (k v)]))]
[else (k v)])))
;--------------------------------------------------------------------------------------
;--------------------------------------------------------------------------------------
; non cps version of ack
;--------------------------------------------------------------------------------------
;;(define ack
;; (lambda (m n)
;; (cond
;; [(zero? m) (add1 n)]
;; [(zero? n) (ack (sub1 m) 1)]
;; [else (ack (sub1 m)
;; (ack m (sub1 n)))])))
;--------------------------------------------------------------------------------------
;--------------------------------------------------------------------------------------
; cps version of ack, ack-cps
;--------------------------------------------------------------------------------------
(define ack-cps
(lambda (m n k)
(cond
[(zero? m) (k (add1 n))]
[(zero? n) (ack-cps (sub1 m) 1 k)]
[else (ack-cps m (sub1 n) (lambda (v) (ack-cps (sub1 m) v k)))])))
;--------------------------------------------------------------------------------------
;--------------------------------------------------------------------------------------
; non cps version of every?
;--------------------------------------------------------------------------------------
;;(define every?
;; (lambda (pred ls)
;; (if (null? ls)
;; #t
;; (if (pred (car ls))
;; (every? pred (cdr ls))
;; #f))))
;--------------------------------------------------------------------------------------
;--------------------------------------------------------------------------------------
; cps version of every?, i.e. every?-cps
;--------------------------------------------------------------------------------------
(define every?-cps
(lambda (pred ls k)
(if (null? ls)
(k #t)
(pred (car ls) (lambda (v) (if v (every?-cps pred (cdr ls) k) (k #f)))))))
; test predicates for every?-cps
;---------------------------------
; a cps predicate to check if a given number is binary
(define binary?
(lambda (n k)
(cond
[(zero? n) (k #t)]
[(zero? (sub1 n)) (k #t)]
[else (k #f)])))
; a cps predicate to check if a given number, n, is the factorial of some number, m
; I came up with this predicate and I could improve it if I knew how to check if
; a number contains decimal points.
(define factorial?
(lambda (n k)
(letrec ([f (lambda (n d k)
(cond
[(eq? n 1) (k #t)]
[(< n 1) (k #f)]
[else (f (/ n d) (+ 1 d) k)]))])
(f n 2 k))))
;--------------------------------------------------------------------------------------
;--------------------------------------------------------------------------------------
; non cps version of fact
;--------------------------------------------------------------------------------------
;;(define fact
;; (lambda (n)
;; ((lambda (f-gen)
;; (f-gen f-gen n))
;; (lambda (fact n)
;; (cond
;; [(zero? n) 1]
;; [else (* n (fact fact (sub1 n)))])))))
;--------------------------------------------------------------------------------------
;--------------------------------------------------------------------------------------
; cps version of fact, i.e. fact-cps
;--------------------------------------------------------------------------------------
(define fact-cps
(lambda (n k)
((lambda (f-gen)
(f-gen f-gen n k))
(lambda (fact n d)
(cond
[(zero? n) (d 1)]
[else (fact fact (sub1 n) (lambda (v) (d (* n v))))])))))
;--------------------------------------------------------------------------------------
;--------------------------------------------------------------------------------------
; non cps version of pascal
;--------------------------------------------------------------------------------------
;;(define pascal
;; (lambda (n)
;; (let ((pascal
;; (lambda (pascal)
;; (lambda (m a)
;; (cond
;; [(> m n) '()]
;; [else (let ((a (+ a m)))
;; (cons a ((pascal pascal) (add1 m) a)))])))))
;; ((pascal pascal) 1 0))))
;--------------------------------------------------------------------------------------
;--------------------------------------------------------------------------------------
; cps version of pascal, i.e. pascal-cps
;--------------------------------------------------------------------------------------
(define pascal-cps
(lambda (n k)
(let ([pascal
(lambda (pascal c)
(c (lambda (m a t)
(cond
[(> m n) (t '())]
[else (let ([a (+ a m)])
(pascal pascal (lambda (f) (f (add1 m) a (lambda (v) (t (cons a v)))))))]))))])
(pascal pascal (lambda (f) (f 1 0 k))))))
;--------------------------------------------------------------------------------------
;--------------------------------------------------------------------------------------
; Test cases for the cps functions
;--------------------------------------------------------------------------------------
(printf "\n=================================================\nTests cases for the cps functions\n=================================================\n")
(test "length-cps 1"
(length-cps '(1 3 4 0 88 45) (empty-k))
6)
(test "length-cps 2"
(length-cps '() (empty-k))
0)
(test "length-cps 3"
(length-cps '(()) (empty-k))
1)
(test "count-syms*-cps 1"
(count-syms*-cps '(1 2 x y 3 b 9) (empty-k))
3)
(test "count-syms*-cps 2"
(count-syms*-cps '(2 3 4 5 6 7) (empty-k))
0)
(test "count-syms*-cps 3"
(count-syms*-cps '() (empty-k))
0)
(test "tree-sum-cps 1"
(tree-sum-cps '(1 2 3 45) (empty-k))
51)
(test "tree-sum-cps 2"
(tree-sum-cps '() (empty-k))
0)
(test "tree-sum-cps 3"
(tree-sum-cps '(1 2 (3 4) (5 6 (7 (8)))) (empty-k))
36)
(test "walk-cps 1"
(walk-cps 'a '((a . b) (b . 9) (c . 10)) (empty-k))
9)
(test "walk-cps 2"
(walk-cps 'c '((a . b) (b . 9) (c . 10)) (empty-k))
10)
(test "walk-cps 3"
(walk-cps 'b '((a . b) (b . 9) (c . 10)) (empty-k))
9)
(test "ack-cps 1"
(ack-cps 2 3 (empty-k))
9)
(test "ack-cps 2"
(ack-cps 3 3 (empty-k))
61)
(test "ack-cps 3"
(ack-cps 4 0 (empty-k))
13)
(test "every?-cps 1"
(every?-cps binary? '(1 0 1 0 1 0 0 1 0 1 0) (empty-k))
#t)
(test "every?-cps 2"
(every?-cps binary? '(1 3 1 0 1 0 0 1 0 1 0) (empty-k))
#f)
(test "every?-cps 3"
(every?-cps binary? '() (empty-k))
#t)
(test "every?-cps 4"
(every?-cps factorial? '(1 2 6 24 120 720 5040) (empty-k))
#t)
(test "every?-cps 5"
(every?-cps factorial? '(1 60 120 720 5040) (empty-k))
#f)
(test "fact-cps 1"
(fact-cps 4 (empty-k))
24)
(test "fact-cps 2"
(fact-cps 0 (empty-k))
1)
(test "fact-cps 3"
(fact-cps 7 (empty-k))
5040)
(test "pascal-cps 1"
(pascal-cps 0 (empty-k))
'())
(test "pascal-cps 2"
(pascal-cps 3 (empty-k))
'(1 3 6))
(test "pascal-cps 3"
(pascal-cps 10 (empty-k))
'(1 3 6 10 15 21 28 36 45 55))
;--------------------------------------------------------------------------------------
; Brainteaser
;--------------------------------------------------------------------------------------
; still working on it. I am not sure if I would be able to make it by today, but it (the problem) really is cool
| true |
7733e73518e91a27121cca254c5e946749ad2a18
|
dff2c294370bb448c874da42b332357c98f14a61
|
/input.scm
|
6f27d1dc077c56b55c71a7ef05ad5047511064ff
|
[
"BSD-2-Clause"
] |
permissive
|
kdltr/hypergiant
|
caf14bbeac38b9d5b5713a19982b226082f3daad
|
ffaf76d378cc1d9911ad4de41f1d7219e878371e
|
refs/heads/master
| 2021-01-01T01:43:09.756174 | 2019-04-04T12:38:25 | 2019-04-04T12:38:25 | 239,126,881 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 6,719 |
scm
|
input.scm
|
;;;; input.scm
;;;; Imported by window.scm
(export make-bindings
make-binding
binding?
binding-id
add-binding
get-binding
remove-binding
change-binding
key-bindings
push-key-bindings
pop-key-bindings
char-callback
mouse-bindings
push-mouse-bindings
pop-mouse-bindings
cursor-movement-callback
scroll-callback
get-cursor-position
set-cursor-position
get-cursor-world-position)
(define-record-type binding
%make-binding
#t
(id) (key) (scancode?) (mods) (press) (release) (pressed?))
(define-record-printer (binding b out)
(fprintf out "#<binding ~S>"
(binding-id b)))
(define (make-binding id key #!key scancode? mods (press (lambda () #f)) (release (lambda () #f))
toggle reverse-toggle)
(let ((mods (if mods
(apply bitwise-ior mods)
0)))
(cond
(toggle
(%make-binding id key scancode? mods
(lambda () (toggle (add1 (toggle))))
(lambda () (toggle (sub1 (toggle))))
#f))
(reverse-toggle
(%make-binding id key scancode? mods
(lambda () (reverse-toggle (sub1 (reverse-toggle))))
(lambda () (reverse-toggle (add1 (reverse-toggle))))
#f))
(else (%make-binding id key scancode? mods press release #f)))))
(define (make-bindings bindings)
(map (lambda (b) (apply make-binding b)) bindings))
(define (add-binding bindings binding)
(cons (apply make-binding binding)
bindings))
(define (get-binding bindings id)
(find (lambda (b) (equal? (binding-id b) id))
bindings))
(define (remove-binding bindings id)
(remove (lambda (b) (equal? (binding-id b) id))
bindings))
(define (change-binding bindings id binding)
(if* (find (lambda (b) (equal? (binding-id b) id))
bindings)
(cons (apply make-binding binding)
(delete it bindings))
(error 'set-binding! "Not a binding id:" id)))
;;; Keyboard
(define key-bindings (make-parameter '()))
(define (push-key-bindings bindings)
(cond
((list? bindings)
(key-callback key-binding-event))
(else (key-callback bindings)))
(key-bindings (cons bindings
(key-bindings))))
(define (pop-key-bindings)
(unless (null? (key-bindings))
(key-bindings (cdr (key-bindings)))
(unless (null? (key-bindings))
(cond
((list? (car (key-bindings)))
(key-callback key-binding-event))
(else (key-callback (car (key-bindings))))))))
(define (key-binding-event key scancode action mods)
(when (not (null? (key-bindings)))
(let ((bindings (car (key-bindings))))
(cond
((= action %+press+)
(let loop ((bindings bindings))
(unless (null? bindings)
(let ((binding (car bindings)))
(if (and (if (binding-scancode? binding)
(= (binding-key binding) scancode)
(= (binding-key binding) key))
(= (binding-mods binding) mods))
(begin ((binding-press binding))
(binding-pressed?-set! binding #t))
(loop (cdr bindings)))))))
;; Release for all bindings that share the same key, even with different mods
((= action %+release+)
(for-each (lambda (binding)
(when (and (if (binding-scancode? binding)
(= (binding-key binding) scancode)
(= (binding-key binding) key))
(binding-pressed? binding))
((binding-release binding))
(binding-pressed?-set! binding #f)))
bindings))))))
(define key-callback (make-parameter (lambda (key scancode action mods) #f)))
(define char-callback (make-parameter (lambda (char) #f)))
(define-external (hpgKeyCallback (c-pointer window) (int key) (int scancode)
(int action) (int mods))
void
((key-callback) key scancode action mods))
(define-external (hpgCharCallback (c-pointer window) (unsigned-int char))
void
((char-callback) char))
;;; Mouse
(define mouse-bindings (make-parameter '()))
(define (push-mouse-bindings bindings)
(mouse-bindings (cons bindings
(mouse-bindings))))
(define (pop-mouse-bindings)
(unless (null? (mouse-bindings))
(mouse-bindings (cdr (mouse-bindings)))))
(define (mouse-click window button action mods)
(when (not (null? (mouse-bindings)))
(let ((bindings (car (mouse-bindings))))
(cond
((= action %+press+)
(let loop ((bindings bindings))
(unless (null? bindings)
(let ((binding (car bindings)))
(if (and (= (binding-key binding) button)
(= (binding-mods binding) mods))
(begin ((binding-press binding))
(binding-pressed?-set! binding #t))
(loop (cdr bindings)))))))
;; Release for all bindings that share the same button, even with different mods
((= action %+release+)
(for-each (lambda (binding)
(when (and (= (binding-key binding) button)
(binding-pressed? binding))
((binding-release binding))
(binding-pressed?-set! binding #f)))
bindings))))))
(define cursor-movement-callback (make-parameter (lambda (x y) #f)))
(define scroll-callback (make-parameter (lambda (x y) #f)))
(define-external (hpgCursorPositionCallback (c-pointer window)
(double x) (double y))
void
((cursor-movement-callback) x y))
(define-external (hpgScrollCallback (c-pointer window)
(double x) (double y))
void
((scroll-callback) x y))
(define (get-cursor-position)
(%get-cursor-position (%window)))
(define (set-cursor-position x y)
(%set-cursor-position (%window) x y))
(define (get-cursor-world-position camera)
(define (scale x) (sub1 (* x 2)))
(let-values (((w h) (get-window-size))
((x y) (get-cursor-position)))
(let* ((ivp (make-f32vector 16))
(x (scale (/ x w)))
(y (scale (- 1 (/ y h))))
(near (make-point x y -1))
(far (make-point x y 1)))
(inverse (scene:camera-view-projection camera) (->pointer ivp))
(m*vector! ivp near)
(m*vector! ivp far)
(values near far))))
| false |
3cd86ba5bef1a091e52911268277d905feb32d5b
|
432924338995770f121e1e8f6283702653dd1369
|
/5/ex5.32.scm
|
eb2698a47cb0c8f125a463c15f7de8946031512c
|
[] |
no_license
|
punchdrunker/sicp-reading
|
dfaa3c12edf14a7f02b3b5f4e3a0f61541582180
|
4bcec0aa7c514b4ba48e677cc54b41d72c816b44
|
refs/heads/master
| 2021-01-22T06:53:45.096593 | 2014-06-23T09:51:27 | 2014-06-23T09:51:27 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 948 |
scm
|
ex5.32.scm
|
(load "./5.5.scm")
(define eceval
(make-machine
'(exp env val proc argl continue unev)
ev-application
(save continue)
(assign unev (op operands) (reg exp))
(assign exp (op operator) (reg exp))
(test (op symbol?) (reg exp))
(branch (label ev-operand-symbol))
(save env)
(save unev)
(assign continue (label ev-appl-did-operator-not-symbol))
(goto (label eval-dispatch))
ev-operand-symbol
(save unev)
(assign continue (label ev-appl-did-operator-symbol))
(goto (label eval-dispatch))
ev-appl-did-operator-not-symbol
(restore unev)
(restore env)
(goto (label ev-appl-did-operator))
ev-appl-did-operator-symbol
(restore unev)
(goto (label ev-appl-did-operator))
ev-appl-did-operator
(assign argl (op empty-arglist))
(assign proc (reg val))
(test (op no-operands?) (reg unev))
(branch (label apply-dispatch))
(save proc)
eceval-body))
| false |
32b0b42d0a8f25fd5fa21ee757f4581127fa0388
|
5fa722a5991bfeacffb1d13458efe15082c1ee78
|
/src/eval/c4_21.scm
|
faa658951a99358e47c5d8f8071dc710b0bdf430
|
[] |
no_license
|
seckcoder/sicp
|
f1d9ccb032a4a12c7c51049d773c808c28851c28
|
ad804cfb828356256221180d15b59bcb2760900a
|
refs/heads/master
| 2023-07-10T06:29:59.310553 | 2013-10-14T08:06:01 | 2013-10-14T08:06:01 | 11,309,733 | 3 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,210 |
scm
|
c4_21.scm
|
(load "eval.scm")
(define fact-exp '((lambda (n)
((lambda (fact)
(fact fact n))
(lambda (ft k)
(if (= k 1)
1
(* k (ft ft (- k 1)))))))
10))
; a)
; (println (seck-eval fact-exp global-env))
(define fib-exp '((lambda (n)
((lambda (fib)
(fib fib 0 1 0)
)
(lambda (fib a b k)
(if (= k n)
b
(fib fib b (+ a b) (+ 1 k))))
))
10))
; (println (seck-eval fib-exp global-env))
; b)
(define f-exp '(define (f x)
((lambda (even? odd?)
(even? even? odd? x))
(lambda (ev? od? n)
(if (= n 0)
true
(od? ev? od? (- n 1))))
(lambda (ev? od? n)
(if (= n 0)
false
(ev? ev? od? (- n 1)))))))
(seck-eval f-exp global-env)
(println (seck-eval '(f 4) global-env))
| false |
fd1b8d6c161c0cd617eaddbb11ce14e94d305161
|
3604661d960fac0f108f260525b90b0afc57ce55
|
/SICP-solutions/3.25-keylist-table.scm
|
df63b21d2d0f2daa5e031398ba7bd0e78b2f1585
|
[] |
no_license
|
rythmE/SICP-solutions
|
b58a789f9cc90f10681183c8807fcc6a09837138
|
7386aa8188b51b3d28a663958b807dfaf4ee0c92
|
refs/heads/master
| 2021-01-13T08:09:23.217285 | 2016-09-27T11:33:11 | 2016-09-27T11:33:11 | 69,350,592 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,411 |
scm
|
3.25-keylist-table.scm
|
(load "2/2.54-equal.scm")
(define (make-table)
(let ((local-table (list '*table*)))
(define (lookup keys)
(define (inner-lookup keylist table)
(let ((subtable (assoc (car keylist) (cdr table))))
(if subtable
(if (null? (cdr keylist))
(cdr subtable)
(inner-lookup (cdr keylist) subtable))
false)))
(inner-lookup keys local-table))
(define (insert! keys value)
(define (inner-insert! keylist table value)
(let ((subtable (assoc (car keylist) (cdr table))))
(if subtable
(if (null? (cdr keylist))
(set-cdr! subtable value)
(inner-insert! (cdr keylist) subtable value))
(set-cdr! table
(cons (key-table keylist value)
(cdr table))))))
(inner-insert! keys local-table value))
(define (key-table keylist value)
(if (null? (cdr keylist))
(cons (car keylist) value)
(list (car keylist) (key-table (cdr keylist) value))))
(define (accoc key records)
(cond ((null? records) false)
((equal? key (caar records)) (car records))
(else (assoc key (cdr records)))))
(define (dispatch m)
(cond ((eq? m 'lookup-proc) lookup)
((eq? m 'insert-proc!) insert!)
(else (error "Unknown operation -- TABLE" m))))
dispatch))
(define (insert! keys value table)
((table 'insert-proc!) keys value))
(define (lookup keys table)
((table 'lookup-proc) keys))
| false |
4fd25eeac745c1a5cae773df24283967d7bb587e
|
784dc416df1855cfc41e9efb69637c19a08dca68
|
/src/std/text/hex.ss
|
104799cb69b238e126e8b6fc55c61f5cba345eaa
|
[
"LGPL-2.1-only",
"Apache-2.0",
"LGPL-2.1-or-later"
] |
permissive
|
danielsz/gerbil
|
3597284aa0905b35fe17f105cde04cbb79f1eec1
|
e20e839e22746175f0473e7414135cec927e10b2
|
refs/heads/master
| 2021-01-25T09:44:28.876814 | 2018-03-26T21:59:32 | 2018-03-26T21:59:32 | 123,315,616 | 0 | 0 |
Apache-2.0
| 2018-02-28T17:02:28 | 2018-02-28T17:02:28 | null |
UTF-8
|
Scheme
| false | false | 1,875 |
ss
|
hex.ss
|
;;; -*- Gerbil -*-
;;; (C) vyzo at hackzen.org
;;; hex encoding
package: std/text
(export hex-encode hexlify hex-decode unhexlify hex unhex unhex*)
(import :gerbil/gambit/fixnum)
(def hexes "0123456789abcdef")
(def (hex-encode bytes (start 0) (end #f))
(let* ((end (or end (u8vector-length bytes)))
(len (fx- end start))
(str (make-string (##fx* 2 len))))
(let lp ((n 0))
(if (##fx< n len)
(let* ((ix (##fx+ n start))
(b (##u8vector-ref bytes ix))
(off (##fxarithmetic-shift n 1)))
(##string-set! str off (##string-ref hexes (##fxarithmetic-shift b -4)))
(##string-set! str (##fx+ off 1) (##string-ref hexes (##fxand b #x0f)))
(lp (##fx+ n 1)))
str))))
(def (hex u4)
(string-ref hexes u4))
(def unhexes
(let (ht (make-hash-table-eq))
(for-each (cut hash-put! ht <> <>)
(string->list "0123456789")
(iota 10))
(for-each (cut hash-put! ht <> <>)
(string->list "abcdef")
(iota 6 10))
(for-each (cut hash-put! ht <> <>)
(string->list "ABCDEF")
(iota 6 10))
ht))
(def (unhex char)
(hash-ref unhexes char))
(def (unhex* char)
(hash-get unhexes char))
(def (hex-decode str)
(let (len (string-length str))
(unless (##fxeven? len)
(error "Expected string of even length" str))
(let* ((blen (##fxquotient len 2))
(bytes (make-u8vector blen)))
(let lp ((n 0))
(if (##fx< n blen)
(let (off (##fxarithmetic-shift n 1))
(##u8vector-set! bytes n
(##fxior (##fxarithmetic-shift (unhex (##string-ref str off)) 4)
(unhex (##string-ref str (##fx+ off 1)))))
(lp (##fx+ n 1)))
bytes)))))
(defalias hexlify hex-encode)
(defalias unhexlify hex-decode)
| false |
ad90ed963d31de8a980c2a4b0a39954813ab791d
|
2bcf33718a53f5a938fd82bd0d484a423ff308d3
|
/programming/sicp/ch2/ex-2.36.scm
|
b4087d1e075721f4bc7e57dae2a5eb8593e58fab
|
[] |
no_license
|
prurph/teach-yourself-cs
|
50e598a0c781d79ff294434db0430f7f2c12ff53
|
4ce98ebab5a905ea1808b8785949ecb52eee0736
|
refs/heads/main
| 2023-08-30T06:28:22.247659 | 2021-10-17T18:27:26 | 2021-10-17T18:27:26 | 345,412,092 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,145 |
scm
|
ex-2.36.scm
|
#lang scheme
;; https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-15.html#%_thm_2.36
(require "accumulate.scm")
;; Given a list of lists all of identical length, accumulate the matching
;; indexes of each sublist, and return a list of these accumulations.
(define (accumulate-n op init seqs)
;; Recursing on a lists of lists, so we're done when the first--and therefore
;; all because they are the same length--is empty, e.g. ('() '() ...)
(if (null? (car seqs))
'()
;; Accumulate the first element of each list, then recurse with
;; accumulate-n on the remaining portion of each sublists. My initial pass
;; had (map (lambda (x) (car x) seqs) but of course this is just creating
;; a trivial lambda: just pass `car`!
(cons (accumulate op init (map car seqs))
(accumulate-n op init (map cdr seqs)))))
(accumulate-n + 0 (list '(1 2 3) '(4 5 6) '(7 8 9) '(10 11 12)))
'(22 26 30)
;; Note how trivial it is to implement zip using accumulate-n!
;; Also note this is equivalent to transposing a matrix! (See ex-2.37)
(define (zip seqs)
(accumulate-n cons '() seqs))
| false |
de290bde0a326f5381b792ff0eca6d3424f936d7
|
f03b4ca9cfcdbd0817ec90869b2dba46cedd0937
|
/figure/transforms.scm
|
43720c11a3eab98d0122b0625e5e33d094773e36
|
[] |
no_license
|
lrsjohnson/upptackt
|
d696059263d18cd7390eb7c3d3650954f0b5f732
|
9bfd2ec70b82116701e791620ab342f3e7d9750e
|
refs/heads/master
| 2021-01-19T00:08:06.163617 | 2015-06-24T14:01:03 | 2015-06-24T14:01:03 | 31,883,429 | 2 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 4,304 |
scm
|
transforms.scm
|
;;; transforms.scm --- Transforms on Elements
;;; Commentary:
;; Ideas:
;; - Generic transforms - rotation and translation
;; - None mutate points, just return new copies.
;; Future:
;; - Translation or rotation to match something
;; - Consider mutations?
;; - Reflections?
;;; Code:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Rotations ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Rotates counterclockwise
(define (rotate-point-about rot-origin radians point)
(let ((v (sub-points point rot-origin)))
(let ((rotated-v (rotate-vec v radians)))
(add-to-point rot-origin rotated-v))))
(define (rotate-segment-about rot-origin radians seg)
(define (rotate-point p) (rotate-point-about rot-origin radians p))
(make-segment (rotate-point (segment-endpoint-1 seg))
(rotate-point (segment-endpoint-2 seg))))
(define (rotate-ray-about rot-origin radians r)
(define (rotate-point p) (rotate-point-about rot-origin radians p))
(make-ray (rotate-point-about rot-origin radians (ray-endpoint r))
(add-to-direction (ray-direction r) radians)))
(define (rotate-line-about rot-origin radians l)
(make-line (rotate-point-about rot-origin radians (line-point l))
(add-to-direction (line-direction l) radians)))
(define rotate-about (make-generic-operation 3 'rotate-about))
(defhandler rotate-about rotate-point-about point? number? point?)
(defhandler rotate-about rotate-ray-about point? number? ray?)
(defhandler rotate-about rotate-segment-about point? number? segment?)
(defhandler rotate-about rotate-line-about point? number? line?)
(define (rotate-randomly-about p elt)
(let ((radians (rand-angle-measure)))
(rotate-about p radians elt)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;; Translations ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (translate-point-by vec point)
(add-to-point point vec))
(define (translate-segment-by vec seg)
(define (translate-point p) (translate-point-by vec p))
(make-segment (translate-point (segment-endpoint-1 seg))
(translate-point (segment-endpoint-2 seg))))
(define (translate-ray-by vec r)
(make-ray (translate-point-by vec (ray-endpoint r))
(ray-direction r)))
(define (translate-line-by vec l)
(make-line (translate-point-by vec (line-point l))
(line-direction l)))
(define (translate-angle-by vec a)
(define (translate-point p) (translate-point-by vec p))
(make-angle (angle-arm-1 a)
(translate-point (angle-vertex a))
(angle-arm-2 a)))
(define translate-by (make-generic-operation 2 'rotate-about))
(defhandler translate-by translate-point-by vec? point?)
(defhandler translate-by translate-ray-by vec? ray?)
(defhandler translate-by translate-segment-by vec? segment?)
(defhandler translate-by translate-line-by vec? line?)
(defhandler translate-by translate-angle-by vec? angle?)
;;;;;;;;;;;;;;;;;;;;;;;;;;;; Reflections ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (reflect-about-line line p)
(if (on-line? p line)
p
(let ((s (perpendicular-to line p)))
(let ((v (segment->vec s)))
(add-to-point
p
(scale-vec v 2))))))
;;;;;;;;;;;;;;;;;;;;;;;;; Random Translation ;;;;;;;;;;;;;;;;;;;;;;;;;
(define (translate-randomly-along-line l elt)
(let* ((vec (unit-vec-from-direction (line->direction l)))
(scaled-vec (scale-vec vec (rand-range 0.5 1.5))))
(translate-by vec elt)))
(define (translate-randomly elt)
(let ((vec (rand-translation-vec-for elt)))
(translate-by vec elt)))
(define (rand-translation-vec-for-point p1)
(let ((p2 (random-point)))
(sub-points p2 p1)))
(define (rand-translation-vec-for-segment seg)
(rand-translation-vec-for-point (segment-endpoint-1 seg)))
(define (rand-translation-vec-for-ray r )
(rand-translation-vec-for-point (ray-endpoint r)))
(define (rand-translation-vec-for-line l)
(rand-translation-vec-for-point (line-point l)))
(define rand-translation-vec-for
(make-generic-operation 1 'rand-translation-vec-for))
(defhandler rand-translation-vec-for
rand-translation-vec-for-point point?)
(defhandler rand-translation-vec-for
rand-translation-vec-for-segment segment?)
(defhandler rand-translation-vec-for
rand-translation-vec-for-ray ray?)
(defhandler rand-translation-vec-for
rand-translation-vec-for-line line?)
| false |
78631d11b40640dd2d91dc274ff12082a849508d
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/UnityEngine/unity-engine/audio-reverb-zone.sls
|
4464e12d3d50d02f210088019b6b7232d527b1f0
|
[] |
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 | 4,637 |
sls
|
audio-reverb-zone.sls
|
(library (unity-engine audio-reverb-zone)
(export new
is?
audio-reverb-zone?
min-distance-get
min-distance-set!
min-distance-update!
max-distance-get
max-distance-set!
max-distance-update!
reverb-preset-get
reverb-preset-set!
reverb-preset-update!
room-get
room-set!
room-update!
room-hf-get
room-hf-set!
room-hf-update!
room-lf-get
room-lf-set!
room-lf-update!
decay-time-get
decay-time-set!
decay-time-update!
decay-hfratio-get
decay-hfratio-set!
decay-hfratio-update!
reflections-get
reflections-set!
reflections-update!
reflections-delay-get
reflections-delay-set!
reflections-delay-update!
reverb-get
reverb-set!
reverb-update!
reverb-delay-get
reverb-delay-set!
reverb-delay-update!
hfreference-get
hfreference-set!
hfreference-update!
lfreference-get
lfreference-set!
lfreference-update!
room-rolloff-factor-get
room-rolloff-factor-set!
room-rolloff-factor-update!
diffusion-get
diffusion-set!
diffusion-update!
density-get
density-set!
density-update!)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...) #'(clr-new UnityEngine.AudioReverbZone a ...)))))
(define (is? a) (clr-is UnityEngine.AudioReverbZone a))
(define (audio-reverb-zone? a) (clr-is UnityEngine.AudioReverbZone a))
(define-field-port
min-distance-get
min-distance-set!
min-distance-update!
(property:)
UnityEngine.AudioReverbZone
minDistance
System.Single)
(define-field-port
max-distance-get
max-distance-set!
max-distance-update!
(property:)
UnityEngine.AudioReverbZone
maxDistance
System.Single)
(define-field-port
reverb-preset-get
reverb-preset-set!
reverb-preset-update!
(property:)
UnityEngine.AudioReverbZone
reverbPreset
UnityEngine.AudioReverbPreset)
(define-field-port
room-get
room-set!
room-update!
(property:)
UnityEngine.AudioReverbZone
room
System.Int32)
(define-field-port
room-hf-get
room-hf-set!
room-hf-update!
(property:)
UnityEngine.AudioReverbZone
roomHF
System.Int32)
(define-field-port
room-lf-get
room-lf-set!
room-lf-update!
(property:)
UnityEngine.AudioReverbZone
roomLF
System.Int32)
(define-field-port
decay-time-get
decay-time-set!
decay-time-update!
(property:)
UnityEngine.AudioReverbZone
decayTime
System.Single)
(define-field-port
decay-hfratio-get
decay-hfratio-set!
decay-hfratio-update!
(property:)
UnityEngine.AudioReverbZone
decayHFRatio
System.Single)
(define-field-port
reflections-get
reflections-set!
reflections-update!
(property:)
UnityEngine.AudioReverbZone
reflections
System.Int32)
(define-field-port
reflections-delay-get
reflections-delay-set!
reflections-delay-update!
(property:)
UnityEngine.AudioReverbZone
reflectionsDelay
System.Single)
(define-field-port
reverb-get
reverb-set!
reverb-update!
(property:)
UnityEngine.AudioReverbZone
reverb
System.Int32)
(define-field-port
reverb-delay-get
reverb-delay-set!
reverb-delay-update!
(property:)
UnityEngine.AudioReverbZone
reverbDelay
System.Single)
(define-field-port
hfreference-get
hfreference-set!
hfreference-update!
(property:)
UnityEngine.AudioReverbZone
HFReference
System.Single)
(define-field-port
lfreference-get
lfreference-set!
lfreference-update!
(property:)
UnityEngine.AudioReverbZone
LFReference
System.Single)
(define-field-port
room-rolloff-factor-get
room-rolloff-factor-set!
room-rolloff-factor-update!
(property:)
UnityEngine.AudioReverbZone
roomRolloffFactor
System.Single)
(define-field-port
diffusion-get
diffusion-set!
diffusion-update!
(property:)
UnityEngine.AudioReverbZone
diffusion
System.Single)
(define-field-port
density-get
density-set!
density-update!
(property:)
UnityEngine.AudioReverbZone
density
System.Single))
| true |
789467f7f4c418110ffe3e067f93cec1ab22463c
|
8a0660bd8d588f94aa429050bb8d32c9cd4290d5
|
/test/tests/rfc/%3a5322.scm
|
cd1ae801718499945860f0a7cfa92fe33afd804c
|
[
"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 | 7,205 |
scm
|
%3a5322.scm
|
;; -*- mode:scheme; coding:utf-8 -*-
#< (sagittarius regex) >
(import (rnrs)
(rfc :5322)
(sagittarius regex)
(util list)
(srfi :1 lists)
(srfi :13 strings)
(srfi :19 time)
(srfi :26 cut)
(srfi :64 testing))
(test-begin "RFC 5322 tests")
;; test cases from Gauche
(define rfc5322-header1
"Received: by foo.bar.com id ZZZ55555; Thu, 31 May 2001 16:38:04 -1000 (HST)
Received: from ooo.ooo.com (ooo.ooo.com [1.2.3.4])
by foo.bar.com (9.9.9+3.2W/3.7W-) with ESMTP id ZZZ55555
for <[email protected]>; Thu, 31 May 2001 16:38:02 -1000 (HST)
Received: from zzz ([1.2.3.5]) by ooo.ooo.com with Maccrosoft SMTPSVC(5.5.1877.197.19);
Thu, 31 May 2001 22:33:16 -0400
Message-ID: <[email protected]>
Subject: Bogus Tester
From: Bogus Sender <[email protected]>
To: You <[email protected]>, Another <[email protected]>
Date: Fri, 01 Jun 2001 02:37:31 (GMT)
Mime-Version: 1.0
Content-Type: text/html
Content-Transfer-Encoding: quoted-printable
X-MSMail-Priority: Normal
X-mailer: FooMail 4.0 4.03 (SMT460B92F)
Content-Length: 4349
")
(define rfc5322-header1-list
'(("received" "by foo.bar.com id ZZZ55555; Thu, 31 May 2001 16:38:04 -1000 (HST)")
("received" "from ooo.ooo.com (ooo.ooo.com [1.2.3.4]) by foo.bar.com (9.9.9+3.2W/3.7W-) with ESMTP id ZZZ55555 for <[email protected]>; Thu, 31 May 2001 16:38:02 -1000 (HST)")
("received" "from zzz ([1.2.3.5]) by ooo.ooo.com with Maccrosoft SMTPSVC(5.5.1877.197.19); Thu, 31 May 2001 22:33:16 -0400")
("message-id" "<[email protected]>")
("subject" "Bogus Tester")
("from" "Bogus Sender <[email protected]>")
("to" "You <[email protected]>, Another <[email protected]>")
("date" "Fri, 01 Jun 2001 02:37:31 (GMT)")
("mime-version" "1.0")
("content-type" "text/html")
("content-transfer-encoding" "quoted-printable")
("x-msmail-priority" "Normal")
("x-mailer" "FooMail 4.0 4.03 (SMT460B92F)")
("content-length" "4349")
))
(test-equal "rfc5322-read-headers" #t
(equal? rfc5322-header1-list
(rfc5322-read-headers
(open-string-input-port rfc5322-header1))))
;; token parsers
(test-equal "rfc5322-field->tokens (basic)"
'(("aa") ("bb") ("cc") ("dd") ("ee") (" a\"aa\\aa (a)"))
(map rfc5322-field->tokens
'("aa"
" bb "
" (comment) cc(comment)"
" (co\\mm$$*##&$%ent) dd(com (me) nt)"
"\"ee\""
" \" a\\\"aa\\\\aa (a)\" (comment\\))")))
(test-equal "rfc5322-field->tokens"
'("from" "aaaaa.aaa.org" "by" "ggg.gggg.net" "with" "ESMTP" "id" "24D50175C8")
(rfc5322-field->tokens
"from aaaaa.aaa.org (aaaaa.aaa.org [192.168.0.9]) by ggg.gggg.net (Postfix) with ESMTP id 24D50175C8"))
(test-equal "rfc5322-parse-date" '(2003 3 4 12 34 56 -3600 2)
(receive r (rfc5322-parse-date "Tue, 4 Mar 2003 12:34:56 -3600") r))
(test-equal "rfc5322-parse-date" '(2003 3 4 12 34 56 0 2)
(receive r (rfc5322-parse-date "Tue, 4 Mar 2003 12:34:56 UT") r))
(test-equal "rfc5322-parse-date (no weekday)" '(2003 3 4 12 34 56 -3600 #f)
(receive r (rfc5322-parse-date "4 Mar 2003 12:34:56 -3600") r))
(test-equal "rfc5322-parse-date (no timezone)" '(2003 3 4 12 34 56 #f #f)
(receive r (rfc5322-parse-date "4 Mar 2003 12:34:56") r))
(test-equal "rfc5322-parse-date (old tz)" '(2003 3 4 12 34 56 #f #f)
(receive r (rfc5322-parse-date "4 Mar 2003 12:34:56 jst") r))
(test-equal "rfc5322-parse-date (no seconds)" '(2003 3 4 12 34 #f 900 #f)
(receive r (rfc5322-parse-date "4 Mar 2003 12:34 +0900") r))
(test-equal "rfc5322-parse-date (no seconds)" '(2003 3 4 12 34 #f 900 2)
(receive r (rfc5322-parse-date "Tue, 04 Mar 2003 12:34 +0900") r))
(test-equal "rfc5322-parse-date (2digit year)" '(2003 3 4 12 34 56 -3600 2)
(receive r (rfc5322-parse-date "Tue, 4 Mar 03 12:34:56 -3600") r))
(test-equal "rfc5322-parse-date (2digit year)" '(1987 3 4 12 34 56 -3600 2)
(receive r (rfc5322-parse-date "Tue, 4 Mar 87 12:34:56 -3600") r))
(test-equal "rfc5322-parse-date (Weekday, exhausive)" '(0 1 2 3 4 5 6 #f)
(map-with-index
(lambda (ind wday)
(receive (y m d H M S tz wd)
(rfc5322-parse-date
(format "~a, ~a Jan 2000 00:00:00 +0000" wday (+ 2 ind)))
wd))
'("Sun" "Mon" "Tue" "Wed" "Thu" "Fri" "Sat" "Znn")))
(test-equal "rfc5322-parse-date (Months, exhausive)"
'(1 2 3 4 5 6 7 8 9 10 11 12 #f)
(map (lambda (mon)
(receive (y m d H M S tz wd)
(rfc5322-parse-date
(format "1 ~a 1999 00:00:00 +0000" mon))
m))
'("Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug"
"Sep" "Oct" "Nov" "Dec" "Zzz")))
(test-equal "rfc5322-parse-date (invalid)" '(#f #f #f #f #f #f #f #f)
(receive r (rfc5322-parse-date "Sun 2 Mar 2002") r))
(test-equal "date->rfc5322-date" "Sun, 29 Nov 2009 01:23:45 +0000"
(date->rfc5322-date (make-date 0 45 23 01 29 11 2009 0)))
(test-equal "date->rfc5322-date" "Sun, 29 Nov 2009 01:23:45 +0900"
(date->rfc5322-date (make-date 0 45 23 01 29 11 2009 32400)))
(test-equal "date->rfc5322-date" "Sun, 29 Nov 2009 01:23:45 -0830"
(date->rfc5322-date (make-date 0 45 23 01 29 11 2009 -30600)))
(test-equal "date->rfc5322-date" "Sun, 29 Nov 2009 01:23:45 +0030"
(date->rfc5322-date (make-date 0 45 23 01 29 11 2009 1800)))
(test-equal "rfc5322-invalid-header-field" #f
(rfc5322-invalid-header-field "abcde"))
(test-equal "rfc5322-invalid-header-field" 'bad-character
(rfc5322-invalid-header-field "abc\x3030; def"))
(test-equal "rfc5322-invalid-header-field" 'bad-character
(rfc5322-invalid-header-field "abc\x00; def"))
(test-equal "rfc5322-invalid-header-field" 'line-too-long
(rfc5322-invalid-header-field (make-string 1000 #\a)))
(test-equal "rfc5322-invalid-header-field" 'line-too-long
(rfc5322-invalid-header-field
(string-append (string-join (make-list 5 (make-string 78 #\a))
"\r\n ")
(make-string 1000 #\a))))
(test-equal "rfc5322-invalid-header-field" 'stray-crlf
(rfc5322-invalid-header-field
(string-join (make-list 5 (make-string 78 #\a)) "\r\n")))
(test-equal "rfc5322-invalid-header-field" 'stray-crlf
(rfc5322-invalid-header-field "abc\ndef"))
(test-equal "rfc5322-invalid-header-field" 'stray-crlf
(rfc5322-invalid-header-field "abc\rdef"))
(test-equal "rfc5322-write-headers"
"name: Shiro Kawai\r\n\
address: 1234 Lambda St.\r\n \
Higher Order Functions, HI, 99899\r\n\
registration-date: 2007-12-10\r\n\r\n"
(call-with-string-output-port
(cut rfc5322-write-headers
'(("name" "Shiro Kawai")
("address" "1234 Lambda St.\r\n Higher Order Functions, HI, 99899")
("registration-date" "2007-12-10"))
:output <>)))
(test-equal "rfc5322-write-headers (ignore error)"
(make-list 2 "name: Shiro\x00;Kawai\r\n\r\n")
(map (lambda (x)
(call-with-string-output-port
(cut rfc5322-write-headers '(("name" "Shiro\x00;Kawai"))
:check x
:output <>)))
'(#f :ignore)))
(test-equal "rfc5322-write-headers (continue)"
"x: A\r\nx: B\r\nx: C\r\n\r\n"
(call-with-string-output-port
(lambda (p)
(rfc5322-write-headers '(("x" "A") ("x" "B")) :output p :continue #t)
(rfc5322-write-headers '(("x" "C")) :output p))))
(test-end)
| false |
68666f1651ba800479a91f8400d6c11ae1a55752
|
a4a6e51f015e7968b7760d089bbe2c4cf57d7b4d
|
/randomwalks.scm
|
c8e85766fe33dd05a01bcc89b3eb341c650b5407
|
[] |
no_license
|
jpt4/womb
|
10bcc0c6cee0a6eefb6656518470ad5e64404942
|
a89cb5733e1d3a1b0a13ec583c9c33309b5c59da
|
refs/heads/master
| 2023-07-25T17:16:44.571894 | 2023-07-07T19:35:31 | 2023-07-07T19:35:31 | 37,166,949 | 0 | 2 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 583 |
scm
|
randomwalks.scm
|
;; randomwalks.scm
;; jpt4
;; revised UTC20150610
#|
(define unpack
(lambda (ls)
(cond
[(pair? (car(car ls)))
|#
(define full-graph
(lambda (size)
(cond
[(zero? size) '()]
[else (cons (full-graph-aux size
(sub1 size))
(full-graph (sub1 size)))])))
(define full-graph-aux
(lambda (ni nn)
(cond
[(zero? nn) (cons `(,ni . ,nn)
(cons `(,nn . ,ni) '()))]
[else (cons `(,ni . ,nn)
(cons `(,nn . ,ni)
(full-graph-aux ni (sub1 nn))))])))
| false |
938df9d8752a922b00bb692b066a00cbecd54e3c
|
d63c4c79d0bf83ae646d0ac023ee0528a0f4a879
|
/cs444/types.scm
|
453eeb3dd5088dfeb462400b085a7605b0b97b4e
|
[] |
no_license
|
stratigoster/UW
|
4dc31f08f7f1c9a958301105dcad481c39c5361f
|
7a4bff4f1476607c43278c488f70d01077b1566b
|
refs/heads/master
| 2021-07-07T04:52:01.543221 | 2011-08-15T05:08:48 | 2011-08-15T05:08:48 | 10,858,995 | 1 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 6,026 |
scm
|
types.scm
|
(load "scope.scm")
(require (lib "match.ss"))
(require (lib "pretty.ss"))
(load "parser_utils.scm")
(define myprint
(lambda (x)
(if (string? x) (display x) (print x))))
(define mdisplay
(lambda L
(map (lambda (x) (if (list? x)
(if (null? x)
(print '())
(begin
(myprint (car x))
(map (lambda (y) (begin (display " ") (myprint y))) (cdr x))))
(myprint x)))
(append L '("\n")))))
(define terror #f)
(define val-of car)
(define type-of cadr)
(define const? caddr)
;;types:
;; int
;; float
;; bool
;; string
;; ([String]) (enum)
;; (1, 100, type) (array 1..100 of type)
;; ((name,type)...) (record)
;; ( [in] [out] type, ..) -> void (proc)
;; (type, ..) -> type (func)
(define access? (lambda (T) (and (list? T) (eq? (car T) 'access))))
(define alpha? (lambda (T) (eq? T 'alpha)))
(define array? (lambda (T) (and (list? T) (eq? (car T) 'array))))
(define astring? (lambda (T) (eq? T 'string)))
(define bool? (lambda (T) (eq? T 'bool)))
(define enum?
(lambda (T)
(if (string? T)
(enum? (lookup 'TYPE T))
(and (list? T) (eq? (car T) 'enum)))))
(define exception? (lambda (T) (eq? T 'exception)))
(define float? (lambda (T) (eq? T 'float)))
(define int? (lambda (T) (eq? T 'int)))
(define record? (lambda (T) (and (list? T) (list? (cadr T)) (eq? (car T) 'record))))
(define void? (lambda (T) (eq? T 'void)))
(define ty-error
(lambda msg
(begin
(set! terror #t)
(mdisplay "***ERROR***:" (car msg) ":" (cadr msg) ":\t" (cdddr msg))
(caddr msg))))
(define printt
(match-lambda
('int "universal integer")
('bool "universal boolean")
('float "universal float")
('void "void")
('exception "exception")
('string "universal string")
('alpha "alpha")
('error "error")
((and t (? string?)) t)
(('subtype x) (string-append "subtype of " (printt x)))
; (('enum (and t ((? string?) ...)))
(('enum (or (and t (? string?)) (and t (? list-of-strings?))))
(if (not (list? t))
(string-append "enum element " t)
(string-append "overloaded enum element "
(foldl (lambda (x i)
(string-append (if (equal? i "") "" (string-append i " "))
(car x)))
"" t))))
(('enum (and x (? list-of-lists?))) (string-append "enumeration of (" (foldl (lambda (y i) (string-append (if (equal? i "") "" (string-append i " "))
(car y)))
"" x) ")"))
(((and n (? number?)) (and s (? string?))) (printt s))
(('record x) (string-append "record "
(foldl (lambda (y i)
(string-append (if (equal? i "") "" (string-append i " "))
(car y)
":"
(printt (cadr y))
"; "))
"" x)))
(('access T) (string-append "access to " T))
(('UNCONST (and x (? string?))) (string-append x " range <>"))
(('RANGE a b t) (string-append (printt t) ".." (printt t)))
((and a (? array?)) (string-append "array ["
(foldl (lambda (x i)
(string-append i
(if (equal? i "") "" ",")
(printt x)))
"" (cadr a))
"] of "
(printt (caddr a))))
((num '-> params ret-type) (string-append "function ("
(if (list? params)
(foldl (lambda (x i)
(string-append (if (equal? i "")
""
(string-append i ","))
(if (and (list? x) (not (null? x)))
(caddr x)
(printt x))))
""
params)
(printt params))
") return " (printt ret-type)))
(unknown (begin (if *types* (mdisplay "[printt] INTERNAL ERROR: Unknown type: " unknown) "beta")))
;...
))
(define list-of-strings?
(lambda (L)
(and (list? L) (not (memq #f (map string? L))))))
(define list-of-lists?
(lambda (L)
(and (list? L) (not (memq #f (map list? L))))))
(define apply?
(match-lambda*
((t1 (-> t2 t3)) (if (U t1 t2) t3 #f))
(_ #f)))
(define U
(match-lambda*
(('alpha _) #t)
((_ 'alpha) #t)
(((and a (? symbol?)) (and b (? symbol?))) (eq? a b))
(((and t (? string?)) (and e (? string?))) (equal? t e))
(x (begin (mdisplay x) #f))))
;
;(define U
; (match-lambda*
; (((and x (? string?)) y) (U (string->symbol x) y))
; ((x (and y (? string?))) (U x (string->symbol y)))
; (((and x (? symbol?)) (and y (? symbol?))) (or (eq? x 'alpha) (eq? y 'alpha) (eq? x y)))
; (x (begin (mdisplay "[U] No match for: " x) #f))))
| false |
158a299a5a19c5a5eeaf25bcd44d52ce8bbd7590
|
6b961ef37ff7018c8449d3fa05c04ffbda56582b
|
/bbn_cl/mach/cl/clchap16-a-2.scm
|
b53e99c0e452f9f44626156af7243b6d36544762
|
[] |
no_license
|
tinysun212/bbn_cl
|
7589c5ac901fbec1b8a13f2bd60510b4b8a20263
|
89d88095fc2a71254e04e57cf499ae86abf98898
|
refs/heads/master
| 2021-01-10T02:35:18.357279 | 2015-05-26T02:44:00 | 2015-05-26T02:44:00 | 36,267,589 | 4 | 3 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 3,706 |
scm
|
clchap16-a-2.scm
|
;;; ********
;;;
;;; Copyright 1992 by BBN Systems and Technologies, A division of Bolt,
;;; Beranek and Newman Inc.
;;;
;;; Permission to use, copy, modify and distribute this software and its
;;; documentation is hereby granted without fee, provided that the above
;;; copyright notice and this permission appear in all copies and in
;;; supporting documentation, and that the name Bolt, Beranek and Newman
;;; Inc. not be used in advertising or publicity pertaining to distribution
;;; of the software without specific, written prior permission. In
;;; addition, BBN makes no respresentation about the suitability of this
;;; software for any purposes. It is provided "AS IS" without express or
;;; implied warranties including (but not limited to) all implied warranties
;;; of merchantability and fitness. In no event shall BBN be liable for any
;;; special, indirect or consequential damages whatsoever resulting from
;;; loss of use, data or profits, whether in an action of contract,
;;; negligence or other tortuous action, arising out of or in connection
;;; with the use or performance of this software.
;;;
;;; ********
;;;
;;;
(eval-when (compile)
(load "clchap16-macros.bin")
(load "clchap16-comm.bin"))
;;; Manipulating hash tables:
(defun gethash (key hash-table &optional default)
"Finds the entry in Hash-Table whose key is Key and returns the associated
value and T as multiple values, or returns Default and Nil if there is no
such entry."
(macrolet ((lookup (test)
`(let ((cons (assoc key (aref vector index) :test #',test)))
(if cons
(values (cdr cons) t)
(values default nil)))))
(hashop nil
(lookup eq)
(lookup eql)
(lookup equal))))
(defun %puthash (key hash-table value)
"Create an entry in HASH-TABLE associating KEY with VALUE; if there already
is an entry for KEY, replace it. Returns VALUE."
(macrolet ((store (test)
`(let ((cons (assoc key (aref vector index) :test #',test)))
(cond (cons (setf (cdr cons) value))
(t
(push (cons key value) (aref vector index))
(incf (hash-table-number-entries hash-table))
value)))))
(hashop t
(store eq)
(store eql)
(store equal))))
(defun remhash (key hash-table)
"Remove any entry for KEY in HASH-TABLE. Returns T if such an entry
existed; () otherwise."
(hashop nil
(let ((bucket (aref vector index))) ; EQ case
(cond ((and bucket (eq (caar bucket) key))
(pop (aref vector index))
(decf (hash-table-number-entries hash-table))
t)
(t
(do ((last bucket bucket)
(bucket (cdr bucket) (cdr bucket)))
((null bucket) ())
(when (eq (caar bucket) key)
(rplacd last (cdr bucket))
(decf (hash-table-number-entries hash-table))
(return t))))))
(let ((bucket (aref vector index))) ; EQL case
(cond ((and bucket (eql (caar bucket) key))
(pop (aref vector index))
(decf (hash-table-number-entries hash-table))
t)
(t
(do ((last bucket bucket)
(bucket (cdr bucket) (cdr bucket)))
((null bucket) ())
(when (eql (caar bucket) key)
(rplacd last (cdr bucket))
(decf (hash-table-number-entries hash-table))
(return t))))))
(let ((bucket (aref vector index))) ; EQUAL case
(cond ((and bucket (equal (caar bucket) key))
(pop (aref vector index))
(decf (hash-table-number-entries hash-table))
t)
(t
(do ((last bucket bucket)
(bucket (cdr bucket) (cdr bucket)))
((null bucket) ())
(when (equal (caar bucket) key)
(rplacd last (cdr bucket))
(decf (hash-table-number-entries hash-table))
(return t))))))))
| false |
a8295bc5e2f71e5a6dbe31db6680ffd486d5fc3b
|
98fd12cbf428dda4c673987ff64ace5e558874c4
|
/paip/will/faster-miniKanren/test-simple-interp.scm
|
032e1dfa297ad09e5fce44900afa274c619b57f4
|
[
"MIT",
"Unlicense"
] |
permissive
|
CompSciCabal/SMRTYPRTY
|
397645d909ff1c3d1517b44a1bb0173195b0616e
|
a8e2c5049199635fecce7b7f70a2225cda6558d8
|
refs/heads/master
| 2021-12-30T04:50:30.599471 | 2021-12-27T23:50:16 | 2021-12-27T23:50:16 | 13,666,108 | 66 | 11 |
Unlicense
| 2019-05-13T03:45:42 | 2013-10-18T01:26:44 |
Racket
|
UTF-8
|
Scheme
| false | false | 2,198 |
scm
|
test-simple-interp.scm
|
(load "simple-interp.scm")
(test "running backwards"
(run 5 (q) (evalo q '(closure y x ((x . (closure z z ()))))))
'(((lambda (x) (lambda (y) x)) (lambda (z) z))
((lambda (x) (x (lambda (y) x))) (lambda (z) z))
(((lambda (x) (lambda (y) x))
((lambda (_.0) _.0) (lambda (z) z)))
(sym _.0))
(((lambda (_.0) _.0)
((lambda (x) (lambda (y) x)) (lambda (z) z)))
(sym _.0))
((((lambda (_.0) _.0) (lambda (x) (lambda (y) x)))
(lambda (z) z))
(sym _.0))))
(define lookupo
(lambda (x env t)
(fresh (rest y v)
(== `((,y . ,v) . ,rest) env)
(conde
((== y x) (== v t))
((=/= y x) (lookupo x rest t))))))
(test "eval-exp-lc 1"
(run* (q) (evalo '(((lambda (x) (lambda (y) x)) (lambda (z) z)) (lambda (a) a)) q))
'((closure z z ())))
(test "eval-exp-lc 2"
(run* (q) (evalo '((lambda (x) (lambda (y) x)) (lambda (z) z)) q))
'((closure y x ((x . (closure z z ()))))))
(test "running backwards"
(run 5 (q) (evalo q '(closure y x ((x . (closure z z ()))))))
'(((lambda (x) (lambda (y) x)) (lambda (z) z))
((lambda (x) (x (lambda (y) x))) (lambda (z) z))
(((lambda (x) (lambda (y) x))
((lambda (_.0) _.0) (lambda (z) z)))
(sym _.0))
((((lambda (_.0) _.0) (lambda (x) (lambda (y) x)))
(lambda (z) z))
(sym _.0))
(((lambda (_.0) _.0)
((lambda (x) (lambda (y) x)) (lambda (z) z)))
(sym _.0))))
(test "fully-running-backwards"
(run 5 (q)
(fresh (e v)
(evalo e v)
(== `(,e ==> ,v) q)))
'((((lambda (_.0) _.1)
==> (closure _.0 _.1 ())) (sym _.0))
((((lambda (_.0) _.0) (lambda (_.1) _.2))
==>
(closure _.1 _.2 ()))
(sym _.0 _.1))
((((lambda (_.0) (lambda (_.1) _.2)) (lambda (_.3) _.4))
==>
(closure _.1 _.2 ((_.0 . (closure _.3 _.4 ())))))
(=/= ((_.0 lambda)))
(sym _.0 _.1 _.3))
((((lambda (_.0) (_.0 _.0)) (lambda (_.1) _.1))
==>
(closure _.1 _.1 ()))
(sym _.0 _.1))
((((lambda (_.0) (_.0 _.0))
(lambda (_.1) (lambda (_.2) _.3)))
==>
(closure _.2 _.3 ((_.1 . (closure _.1 (lambda (_.2) _.3) ())))))
(=/= ((_.1 lambda)))
(sym _.0 _.1 _.2))))
| false |
334c1d9192fcf9f425204595f991f6899478a72e
|
ae4938300d7eea07cbcb32ea4a7b0ead9ac18e82
|
/implementation.sls
|
90a938b5f46eda3e35ee1e6e13563fff30123bfe
|
[] |
no_license
|
keenbug/imi-libs
|
05eb294190be6f612d5020d510e194392e268421
|
b78a238f03f31e10420ea27c3ea67c077ea951bc
|
refs/heads/master
| 2021-01-01T19:19:45.036035 | 2012-03-04T21:46:28 | 2012-03-04T21:46:28 | 1,900,111 | 0 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 114 |
sls
|
implementation.sls
|
#!r6rs
(library (imi implementation)
(export implementation-name)
(import (imi implementation compat))
)
| false |
d7f557b6296138622601abddc281e999c7046744
|
5355071004ad420028a218457c14cb8f7aa52fe4
|
/3.5/e-3.72.scm
|
28d916d38f4a9d13ac02c724657f091ae1f17649
|
[] |
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,496 |
scm
|
e-3.72.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).
; ------------------------------------------------------------
(load "e-3.70.scm")
(define square-weight
(lambda (pair)
(let ((i (car pair))
(j (cadr pair)))
(+ (* i i) (* j j)))))
(define square-weighted-pairs
(weighted-pairs
integers
integers
square-weight))
;this can be done by applying twice some more general procedure of ramanujan-stream-filter
;which will produce stream of values we need. Here is implementation for current case
(define (square-weight-filter stream)
(let* ((tail-of-stream (stream-cdr stream))
(weight1 (square-weight (stream-car stream)))
(weight2 (square-weight (stream-car tail-of-stream)))
(weight3 (square-weight (stream-car (stream-cdr tail-of-stream)))))
(if (and (= weight1 weight2) (= weight2 weight3))
(cons-stream
weight1
(cons-stream
(stream-car stream)
(cons-stream
(stream-car tail-of-stream)
(cons-stream
(stream-car (stream-cdr tail-of-stream))
(square-weight-filter (stream-cdr (stream-cdr tail-of-stream)))))))
(square-weight-filter tail-of-stream))))
(define square-weight-numbers (square-weight-filter square-weighted-pairs))
(display-stream-head square-weight-numbers 100)
| false |
2ed45a2e7a709a5019262c3df0397a02217f037e
|
9c8c0fb8f206ea8b1871df102737c1cb51b7c516
|
/tests/publish-subscribe/xpub-xsub-system.scm
|
c3e50472624e6f5ebb2394ac0c6a0d2f2fb28632
|
[
"MIT"
] |
permissive
|
massimo-nocentini/chicken-zmq
|
3c4ca6cbed51e2fbcdcc0b5287b7d05194f039b5
|
b62a1dc8c66c84134770a41802f927d36a7e0f81
|
refs/heads/master
| 2020-04-20T02:32:32.536355 | 2019-04-11T09:00:23 | 2019-04-11T09:00:23 | 168,574,171 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 914 |
scm
|
xpub-xsub-system.scm
|
(module wu-spec *
(import scheme (chicken base) (chicken format))
(import srfi-1)
(import zsugar)
(import xpub-xsub-components)
(define chan (make-channel "tcp" "localhost" "5556"))
(define chan₀ (make-channel "tcp" "localhost" "5555"))
(define measures 3)
(define clients 5)
(define-values (fork PIDs-getter outputs-getter) (zmq-system))
(define start
(lambda ()
(fork "proxy" ((proxy) chan₀ chan))
(fork "server-1" ((server measures) chan₀))
(fork "server-2" ((server measures) chan₀))
(for-each (lambda (i)
(let* ((zipcode (zipcode/random))
(client-name (format #f "client-~a" zipcode)))
(fork client-name ((client zipcode (* 2 measures)) chan))))
(iota clients))
(write-bash-script "kill-all.sh"
`("kill" ("-9") ,(PIDs-getter number->string))))))
(import scheme (chicken base) zsugar)
(start-repl 'wu-spec)
| false |
8cc52683a4e9656944213f1c7df27fb58f9bb652
|
a6a1c8eb973242fd2345878e5a871a89468d4080
|
/3.76.scm
|
32d6cd62ca216b17600f6bf62d0b6e09a61d3041
|
[] |
no_license
|
takkyuuplayer/sicp
|
ec20b6942a44e48d559e272b07dc8202dbb1845a
|
37aa04ce141530e6c9803c3c7122016d432e924b
|
refs/heads/master
| 2021-01-17T07:43:14.026547 | 2017-02-22T03:40:07 | 2017-02-22T03:40:07 | 15,771,479 | 1 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 839 |
scm
|
3.76.scm
|
(load "./lib/stream/base.scm")
(load "./lib/stream/list.scm")
(load "./lib/stream/calc.scm")
(load "./lib/stream/display.scm")
(define ones (cons-stream 1 ones))
(define integers (cons-stream 1 (add-streams ones integers)))
(define (sign-change-detector after before)
(cond ((and (>= before 0) (>= after 0)) 0)
((and (>= before 0) (< after 0)) -1)
((and (< before 0) (>= after 0) 1))
(else 0)
)
)
(define sense-data
(stream-map (lambda (x) (sin x)) integers))
; 3.76
(define (smooth stream)
(cons-stream
(/ (+ (stream-car stream) (stream-car (stream-cdr stream))) 2)
(smooth (stream-cdr stream)))
)
(define zero-crossings
(stream-map
sign-change-detector
(smooth sense-data)
(cons-stream 0 (smooth sense-data))
))
(stream-head zero-crossings 10)
| false |
cbe8a56c88b65c34857ea2b931daac30cd90c419
|
6c6cf6e4b77640825c2457e54052a56d5de6f4d2
|
/ch3/s3_5-stream-macro.scm
|
4f61b10cfd5428f6b7a1674dceb6e477a0b3d060
|
[] |
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 | 308 |
scm
|
s3_5-stream-macro.scm
|
; sector 3.5 stream
; 当程序不是运行在MIT-Scheme环境中时使用的;
; syntax-rules 应该是Scheme标准里的,因为标准里很多地方都用syntax-rules去实现,但是Guile解释器没有实现
(define-syntax cons-stream
(syntax-rules ()
((cons-stream x y) (cons x (delay y)))))
| true |
8d5d0075f339b1435b7f828423200fe2a5206cd2
|
77f0eef0782195c4d90f97675b605da300fe270a
|
/src/tests/test-precompilation.scm
|
895ce6f468ef3f60d01bffac8341bf5259b9c96c
|
[] |
no_license
|
boraseoksoon/scheme_x86
|
a36a273d99195e6203b45641b6cafb4a92c37818
|
2a02cde1e482bc4be73ad460c97d643a4ea0e2e0
|
refs/heads/master
| 2022-03-16T12:08:59.743217 | 2019-11-23T16:44:19 | 2019-11-23T16:44:19 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 4,365 |
scm
|
test-precompilation.scm
|
(add-tests-with-precompiled-output "lambdas to labels"
;; no free vars
[((lambda (x) (prim-apply + x x)) 3)
=> (labels
((label_0 (code (x) () (prim-apply + x x))))
()
(funcall (closure label_0) 3))]
;; single free var
[(let ((y 4)) ((lambda (x) (prim-apply + y x)) 3))
=> (labels
((label_0 (code (x) (y) (prim-apply + y x))))
()
(let ([y 4]) (funcall (closure label_0 y) 3)))]
;; single free var in multiple lambdas
[(let ((y 4) (foobar 99))
((lambda (x) (prim-apply + y x)) 3)
((lambda (z) (prim-apply + y z)) 5)
((lambda (a) (prim-apply + a foobar)) 1))
=> (labels
((label_2 (code (z) (y) (prim-apply + y z)))
(label_1 (code (x) (y) (prim-apply + y x)))
(label_0 (code (a) (foobar) (prim-apply + a foobar))))
()
(let ([y 4] [foobar 99])
(funcall (closure label_1 y) 3)
(funcall (closure label_2 y) 5)
(funcall (closure label_0 foobar) 1)))])
(add-tests-with-precompiled-output "tailcall annotation"
[(let ([g (lambda (x) (prim-apply + x x))])
((lambda (y) (g y)) 5))
=> (labels
((label_1 (code (y) (g) (tailcall g y)))
(label_0 (code (x) () (prim-apply + x x))))
()
(let ([g (closure label_0)])
(funcall (closure label_1 g) 5)))]
[(let ([g (lambda (x) (prim-apply + x x))])
((lambda (y) (if (prim-apply zero? y) 0 (g y))) 5))
=> (labels
((label_1
(code (y) (g) (if (prim-apply zero? y) 0 (tailcall g y))))
(label_0 (code (x) () (prim-apply + x x))))
()
(let ([g (closure label_0)])
(funcall (closure label_1 g) 5)))]
[(let ([other-func (lambda (x y) (prim-apply + x y))])
(let ([g (lambda (x) (other-func x x))])
(g 5)))
=> (labels
((label_1 (code (x_1) (other-func) (tailcall other-func x_1 x_1)))
(label_0 (code (x y) () (prim-apply + x y))))
()
(let ([other-func (closure label_0)])
(let ([g (closure label_1 other-func)]) (funcall g 5))))])
(add-tests-with-precompiled-output "constants to labels"
[(let ((f (lambda () (quote (1 . "H")))))
(prim-apply eq? (f) (f)))
=>
(labels
((label_0 (datum))
(label_1 (code () () (constant-ref label_0))))
((constant-init
label_0
(prim-apply
cons
1
(let ([s (prim-apply make-string 1)])
(prim-apply string-set! s 0 #\H)
s))))
(let ([f (closure label_1)])
(prim-apply eq? (funcall f) (funcall f))))])
(add-tests-with-precompiled-output "set! to vector-set/ref"
[(let ([f (lambda (c)
(prim-apply cons (lambda (v) (set! c v))
(lambda () c)))])
(let ([p (f 0)]) ((prim-apply car p) 12) ((prim-apply cdr p))))
=>
(labels
((label_2
(code (c)
()
(let ([c (let ([v (prim-apply make-vector 1)])
(prim-apply vector-set! v 0 c)
v)])
(prim-apply
cons
(closure label_0 c)
(closure label_1 c)))))
(label_1 (code () (c) (prim-apply vector-ref c 0)))
(label_0 (code (v) (c) (prim-apply vector-set! c 0 v))))
()
(let ([f (closure label_2)])
(let ([p (funcall f 0)])
(funcall (prim-apply car p) 12)
(funcall (prim-apply cdr p)))))])
(add-tests-with-precompiled-output "all precompilations in one"
[(let ([g (lambda (x) (prim-apply + x x))]
[f (lambda () (quote (1 . "H")))])
((lambda (y) (g y)) 5)
(prim-apply eq? (f) (f)))
=> (labels
((label_0 (datum))
(label_3 (code (y) (g) (tailcall g y)))
(label_2 (code () () (constant-ref label_0)))
(label_1 (code (x) () (prim-apply + x x))))
((constant-init
label_0
(prim-apply
cons
1
(let ([s (prim-apply make-string 1)])
(prim-apply string-set! s 0 #\H)
s))))
(let ([g (closure label_1)] [f (closure label_2)])
(funcall (closure label_3 g) 5)
(prim-apply eq? (funcall f) (funcall f))))])
(add-tests-with-precompiled-output "lib primitive refs"
[(add-and-add-four 1 2)
=> (labels () () (funcall (lib-primitive-ref add-and-add-four) 1 2))])
| false |
a8957d4077ab7bfe84dd3fe140d49269095e752e
|
c763eaf97ffd7226a70d2f9a77465cbeae8937a8
|
/scheme/tables/vector-tools.scm
|
8ce5191e6c18208dfbfcf764532192edc677f063
|
[] |
no_license
|
jhidding/crossword
|
66907f12e87593a0b72f234ebfabbd2fb56dae9c
|
b3084b6b1046eb0a996143db1a144fd32379916f
|
refs/heads/master
| 2020-12-02T19:33:08.677722 | 2017-08-21T21:07:43 | 2017-08-21T21:07:43 | 96,357,240 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 182 |
scm
|
vector-tools.scm
|
(library (tables vector-tools)
(export vector-range)
(import (rnrs (6))
(only (srfi srfi-43) vector-unfold))
(define (vector-range n)
(vector-unfold values n)))
| false |
570ec8b164959a4b4129fecd59e6f5ca0d87564c
|
9d80bd0154465851d573fa586839642ba09d27f3
|
/lcs.scm
|
8e91abf41a0783200e6504f1f180d004ab5f9212
|
[
"BSD-3-Clause"
] |
permissive
|
tabe/lcs
|
939c3207c356251361b689ca2c482495377f9fc5
|
6f5f5a46b7dd01b8c9b9111c6df780852190fa13
|
refs/heads/master
| 2016-08-04T09:14:22.404904 | 2009-10-19T06:19:56 | 2009-10-19T06:19:56 | 337,113 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 7,397 |
scm
|
lcs.scm
|
;;
;; Copyright (c) 2009 Takeshi Abe. All rights reserved.
;;
;; 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.
;;
;; 3. Neither the name of the authors nor the names of its contributors
;; may be used to endorse or promote products derived from this
;; software without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(library (lcs)
(export ses
lcs-fold
lcs
lcs-with-positions
lcs-edit-list)
(import (rnrs))
;; cf. S. Wu, U. Manber, G. Myers, and W. Miller, "An O(NP) Sequence Comparison Algorithm" (1989)
(define (ses a b . opt-eq)
(let* ((eq-proc (if (null? opt-eq) equal? (car opt-eq)))
(m (length a))
(n (length b))
(u (if (<= m n) 1 -1))
(M (min m n))
(N (max m n))
(A (list->vector (cons #f (if (<= m n) a b))))
(B (list->vector (cons #f (if (<= m n) b a))))
(M+1 (+ M 1))
(D (- N M))
(fp (make-vector (+ M N 3) -1))
(path (make-vector (+ M N 3) '())))
(letrec-syntax ((fp-ref (syntax-rules () ((_ i) (vector-ref fp (+ i M+1)))))
(fp-set! (syntax-rules () ((_ i v) (vector-set! fp (+ i M+1) v))))
(path-ref (syntax-rules () ((_ i) (vector-ref path (+ i M+1)))))
(path-set! (syntax-rules () ((_ i v) (vector-set! path (+ i M+1) v))))
(path-push! (syntax-rules () ((_ i v) (path-set! i (cons v (path-ref i)))))))
(define (snake! k)
(let* ((y1 (+ (fp-ref (- k 1)) 1))
(y2 (fp-ref (+ k 1)))
(y (max y1 y2)))
(cond ((> y1 y2)
(path-set! k (path-ref (- k 1)))
(path-push! k u))
(else
(path-set! k (path-ref (+ k 1)))
(path-push! k (- u))))
(let loop ((x (- y k))
(y y))
(cond ((and (< x M)
(< y N)
(eq-proc (vector-ref A (+ x 1))
(vector-ref B (+ y 1))))
(path-push! k 0)
(loop (+ x 1) (+ y 1)))
(else (fp-set! k y))))))
(let p-loop ((p 0))
(do ((k (- p) (+ k 1)))
((= k D))
(snake! k))
(do ((k (+ D p) (- k 1)))
((= k D))
(snake! k))
(snake! D)
(if (= (fp-ref D) N)
(values (+ D (* 2 p)) (cdr (reverse (path-ref D))))
(p-loop (+ p 1)))))))
(define (lcs-fold a-proc b-proc both-proc seed a b . opt-eq)
(call-with-values
(lambda () (apply ses a b opt-eq))
(lambda (_ s)
(let loop ((a a)
(i 0)
(b b)
(j 0)
(s s)
(seed seed))
(if (null? s)
seed
(case (car s)
((0)
(loop (cdr a)
(+ i 1)
(cdr b)
(+ j 1)
(cdr s)
(both-proc (car a) seed)))
((1)
(loop a
i
(cdr b)
(+ j 1)
(cdr s)
(b-proc (car b) seed)))
(else
(loop (cdr a)
(+ i 1)
b
j
(cdr s)
(a-proc (car a) seed)))))))))
(define (lcs a b . opt-eq)
(let ((pass (lambda (x seed) seed)))
(reverse (apply lcs-fold pass pass cons '() a b opt-eq))))
(define (lcs-with-positions a b . opt-eq)
(call-with-values
(lambda () (apply ses a b opt-eq))
(lambda (_ s)
(let loop ((a a)
(i 0)
(b b)
(j 0)
(s s)
(n 0)
(r '()))
(if (null? s)
(list n (reverse r))
(case (car s)
((0)
(loop (cdr a)
(+ i 1)
(cdr b)
(+ j 1)
(cdr s)
(+ n 1)
(cons (list (car a) i j) r)))
((1)
(loop a
i
(cdr b)
(+ j 1)
(cdr s)
n
r))
(else
(loop (cdr a)
(+ i 1)
b
j
(cdr s)
n
r))))))))
(define (lcs-edit-list a b . opt-eq)
(call-with-values
(lambda () (apply ses a b opt-eq))
(lambda (_ s)
(let loop ((a a)
(i 0)
(b b)
(j 0)
(s s)
(hunk '())
(hunks '()))
(if (null? s)
(reverse
(if (null? hunk) hunks (cons (reverse hunk) hunks)))
(case (car s)
((0)
(loop (cdr a)
(+ i 1)
(cdr b)
(+ j 1)
(cdr s)
'()
(if (null? hunk) hunks (cons (reverse hunk) hunks))))
((1)
(loop a
i
(cdr b)
(+ j 1)
(cdr s)
`((+ ,j ,(car b)) ,@hunk)
hunks))
(else
(loop (cdr a)
(+ i 1)
b
j
(cdr s)
`((- ,i ,(car a)) ,@hunk)
hunks))))))))
)
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.