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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a1aff9300d0e037e1577907576e0c31fbaa04fbf
|
56e35a272861c29e067b4777f0e0e5cb3daec72b
|
/scripts/rewrite.scm
|
969b327ae022db87693f16682cfac1a0338e485c
|
[
"MIT"
] |
permissive
|
jhwillett/jhwscm
|
7234f5a6eb3e37e832517b537c09e585dffb42bb
|
add44387d5decbcfb227bccc8409985cfe99fd36
|
refs/heads/main
| 2023-08-16T16:32:15.816191 | 2021-10-03T16:15:57 | 2021-10-03T16:15:57 | 412,934,154 | 0 | 0 | null | 2021-10-03T00:06:58 | 2021-10-02T23:36:35 |
Java
|
UTF-8
|
Scheme
| false | false | 510 |
scm
|
rewrite.scm
|
#!/usr/bin/guile
!#
;; A little ditty I wrote to see what a rewrite rule for transforming
;; let expressions into a lambda-based expression. Guided the
;; maturation of sub_let.
(define (rewrite expr)
(let ((params (map car (cadr expr)))
(values (map cadr (cadr expr)))
(body (caddr expr)))
(cons (list 'lambda params body) values)))
(define let-expr '(let ((a 1) (b 2)) (+ a b)))
(define lambda-expr (rewrite let-expr))
(display let-expr)
(newline)
(display lambda-expr)
(newline)
| false |
d3a00fc82876609e7621a4235af57ffda07421a1
|
120324bbbf63c54de0b7f1ca48d5dcbbc5cfb193
|
/packages/nanopass/tests/unit-test-helpers.ss
|
08e3f7792de046fc75010160e6ac34eadadab2fe
|
[
"MIT"
] |
permissive
|
evilbinary/scheme-lib
|
a6d42c7c4f37e684c123bff574816544132cb957
|
690352c118748413f9730838b001a03be9a6f18e
|
refs/heads/master
| 2022-06-22T06:16:56.203827 | 2022-06-16T05:54:54 | 2022-06-16T05:54:54 | 76,329,726 | 609 | 71 |
MIT
| 2022-06-16T05:54:55 | 2016-12-13T06:27:36 |
Scheme
|
UTF-8
|
Scheme
| false | false | 4,042 |
ss
|
unit-test-helpers.ss
|
;;; Copyright (c) 2000-2015 Andrew W. Keep, R. Kent Dybvig
;;; See the accompanying file Copyright for details
(library (tests unit-test-helpers)
(export test-suite test assert-equal? with-output-to-string)
(import (rnrs) (tests unit-test-helpers-implementation))
(define-syntax test-suite
(lambda (x)
(define name->run-name
(lambda (name)
(datum->syntax name
(string->symbol
(string-append "run-" (symbol->string (syntax->datum name)))))))
(syntax-case x ()
[(_ name test test* ...)
(with-syntax ([run (name->run-name #'name)])
#'(define run
(lambda ()
(display "Running ")
(write (quote name))
(display " test suite...\n")
(let f ([tests (list (lambda () test) (lambda () test*) ...)]
[successes 0] [failures 0] [exceptions 0])
(if (null? tests)
(begin
(display "Ran ")
(write (+ successes failures exceptions))
(display " tests with ")
(write successes)
(display " successes, ")
(write failures)
(display " failures, and ")
(write exceptions)
(display " exceptions\n"))
(guard (e [else
(display " caught expection... ")
(display-condition e)
(newline)
(f (cdr tests) successes failures
(+ exceptions 1))])
(let ([result ((car tests))])
(write result)
(newline)
(if result
(f (cdr tests) (+ successes 1) failures
exceptions)
(f (cdr tests) successes (+ failures 1)
exceptions)))))))))])))
(define-syntax test
(syntax-rules ()
[(_ name assertion assertion* ...)
(begin
(display " Testing ")
(write (quote name))
(display " ...")
(and assertion assertion* ...))]))
(define-syntax assert-equal?
(syntax-rules ()
[(_ expected actual)
(or (equal? expected actual)
(begin
(newline)
(display "!!! ")
(write actual)
(display " does not match expected: ")
(write expected)
(newline)
#f))]))
(define-syntax assert-error
(syntax-rules ()
[(_ ?msg ?expr)
(let ([msg ?msg])
(guard (e [else
(let ([e-msg
(or (and (format-condition? e)
(apply format (condition-message e)
(condition-irritants e)))
(and (message-condition? e)
(string=? msg (condition-message e))))])
(or (string=? msg e-msg)
#t
(raise (condition
(make-format-condition)
(make-message-condition
"expected error message of ~s but got ~s")
(make-irritants (list msg e-mesg))
e))))])
(let ([t ?expr])
(raise
(condition
(make-format-condition)
(make-message-condition
"exptected error with message of ~s but instead got result ~s")
(make-irritants (list msg t)))))))])))
| true |
9584f2f797557330068efab9aa8b202e60c9d486
|
fbd478ccd1b4fa2b0822353a2df5444ad1d856cf
|
/util/record-match.scm
|
acfa7d880a9d1086a31eae57a5d8b91c52871af1
|
[
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
dannypsnl-fork/paper-towards-the-essence-of-hygiene-expander
|
71b16d78956a60abfa9f534c0fa74dc5dee3c715
|
b1d8f11f1999f04c5dc529930481e3eb4b69804d
|
refs/heads/master
| 2022-06-01T04:06:22.514591 | 2014-12-05T21:05:38 | 2014-12-05T21:05:38 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 3,159 |
scm
|
record-match.scm
|
(library (util record-match)
(export match define-match)
(import (rnrs) (util record-match-helpers))
;; This library implements a 'match' pattern matching form that makes
;; it easy to pattern match records and a 'define-match' form that
;; makes it easy to define functions that pattern match their
;; argument.
;;
;; Note that this implementation is not efficient. In addition, due
;; to phase restrictions in Scheme, the main functions implementing
;; matching are in the record-match-helpers library.
;; Usage: (match scr (lits ...) [pat guard body] ...)
;; - Scr is an expression that is pattern matched
;; - Lits is a lit of literals that are treated as literal *symbols* in the following patterns
;; - Pat is a pattern. Notably we use vector notation to pattern match records (e.g., #(rec-name field1 field2)).
;; - Guard is a predicate that is tested to see whether to run the body. This part is optional and treated as #f if omitted.
;; - Body is an expression to run if the pattern matches and the guard passes.
(define-syntax match
(lambda (stx)
(syntax-case stx ()
[(_ scr lits . clauses)
(let ()
(define (mk-clauses clauses)
(syntax-case clauses ()
[() #'(error 'match "unmatched value" tmp)]
[([pat body] . rest) (mk-clauses #'([pat #t body] . rest))]
[([pat guard body] . rest)
#`(let ([next-clause (lambda () #,(mk-clauses #'rest))]
[env (match-pattern (syntax->list #'lits) #'#,(escape-ellipses #'pat) tmp)])
(if env
(let #,(map (lambda (key) #`[#,key (cdr (assp (curry bound-identifier=? #'#,key) env))])
(pattern-vars (syntax->list #'lits) #'pat))
(if guard
body
(next-clause)))
(next-clause)))]))
#`(let ([tmp scr]) #,(mk-clauses #'clauses)))])))
;; This form defines a function that pattern matches its argument.
;;
;; Usage #1: (define-match func [pat body] ...)
;; Defines a function 'func' that takes one argument that is pattern matched against each 'pat'.
;;
;; Usage #2: (define-match (func pat) body)
;; This is a simplified version of define-match for when there is only one pattern match clause
(define-syntax define-match
(syntax-rules ()
[(_ (name pattern) body ...) (define-match name [pattern (begin body ...)])]
[(_ name clauses ...) (define (name tmp)
(match tmp ()
clauses ...
[_ (error 'name "unmatched input" tmp)]))]))
#;(define (tests)
(print-gensym 'pretty)
(expand '(match x () [a b]))
(expand '(match x () [a b c]))
(expand '(match x () [a b c] [i j k]))
(expand '(match x () [(1 . 2) b]))
(expand '(match x () [() y]))
(expand '(match x () [(l y) y]))
(expand '(match x (l m) [(l y) y]))
(expand '(match x (l m) [(l y) y][(m z) z]))
(define-record-type pair (fields fst snd))
(expand '(match x () [#(pair y z) 3]))
(match (make-pair 1 2) () [#(pair x y) (list x y)])
)
)
| true |
45add0b93b234a2c5ce1e303464054d94ccf00e8
|
0bb7631745a274104b084f6684671c3ee9a7b804
|
/lib/srfi/179/generalized-arrays.scm
|
e56aaee313da6111eb04ee05c7e3e7dab30e234e
|
[
"Apache-2.0",
"LGPL-2.1-only",
"LicenseRef-scancode-free-unknown",
"GPL-3.0-or-later",
"LicenseRef-scancode-autoconf-simple-exception"
] |
permissive
|
feeley/gambit
|
f87fd33034403713ad8f6a16d3ef0290c57a77d5
|
7438e002c7a41a5b1de7f51e3254168b7d13e8ba
|
refs/heads/master
| 2023-03-17T06:19:15.652170 | 2022-09-05T14:31:53 | 2022-09-05T14:31:53 | 220,799,690 | 0 | 1 |
Apache-2.0
| 2019-11-10T15:09:28 | 2019-11-10T14:14:16 | null |
UTF-8
|
Scheme
| false | false | 191,750 |
scm
|
generalized-arrays.scm
|
#|
SRFI 179: Nonempty Intervals and Generalized Arrays (Updated)
Copyright 2016, 2018, 2020 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.
|#
(##namespace ("srfi/179#"))
(##include "~~lib/gambit#.scm")
(##declare (standard-bindings)
(extended-bindings)
(block)
(mostly-fixnum)
(not safe))
;;; Our naming convention prefixes %% to the names of internal procedures,
(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)))
(declare (not inline))
;;; We do not need a multi-argument every.
(define (%%every pred list)
;; don't inline %%every, but unroll the loop if advantageous
(declare (inline))
(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))
;;; 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-structure %%interval
dimension ;; a fixnum
%%volume ;; #f or an exact integer, calculated when needed
lower-bounds ;; a vector of exact integers l_0,...,l_n-1
upper-bounds ;; a vector of exact integers u_0,...,u_n-1
) ;; end %%interval
(define (interval? x)
(%%interval? x))
(declare (not inline))
(define %%vector-of-zeros
'#(#()
#(0)
#(0 0)
#(0 0 0)
#(0 0 0 0)))
(define (%%finish-interval lower-bounds upper-bounds)
(make-%%interval (vector-length upper-bounds)
#f
(vector-copy lower-bounds)
(vector-copy upper-bounds)))
(define make-interval
(case-lambda
((upper-bounds)
(cond ((not (and (vector? upper-bounds)
(fx< 0 (vector-length upper-bounds))
(%%vector-every (lambda (x) (exact-integer? x)) upper-bounds)
(%%vector-every (lambda (x) (positive? x)) upper-bounds)))
(error "make-interval: The argument is not a nonempty vector of positive 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)
(fx< 0 (vector-length lower-bounds))
(%%vector-every (lambda (x) (exact-integer? x)) lower-bounds)))
(error "make-interval: The first argument is not a nonempty vector of exact integers: " lower-bounds upper-bounds))
((not (and (vector? upper-bounds)
(fx< 0 (vector-length upper-bounds))
(%%vector-every (lambda (x) (exact-integer? x)) upper-bounds)))
(error "make-interval: The second argument is not a nonempty 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 less than the associated upper-bound: " lower-bounds upper-bounds))
(else
(%%finish-interval (vector-copy lower-bounds)
(vector-copy upper-bounds)))))))
(declare (inline))
#|
;;; Now a cached field of %%interval
(define (%%interval-dimension interval)
(vector-length (%%interval-lower-bounds interval)))
|#
(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-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)))
(declare (not inline))
(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-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 (fx< 1 (%%interval-dimension interval))) ;; redundant check, but useful error message
(error "interval-projections: The dimension of the first argument is not greater than 1: " 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 (exclusive): " interval right-dimension))
(else
(%%interval-projections interval right-dimension))))
(define (%%interval-projections interval right-dimension)
(let* ((n (%%interval-dimension interval))
(left-dimension (fx- n right-dimension))
(lower-bounds (%%interval-lower-bounds interval))
(upper-bounds (%%interval-upper-bounds interval))
(left-lower-bounds (make-vector left-dimension))
(left-upper-bounds (make-vector left-dimension))
(right-lower-bounds (make-vector (- n left-dimension)))
(right-upper-bounds (make-vector (- n left-dimension))))
(do ((i 0 (fx+ i 1)))
((fx= i left-dimension)
(do ((i i (fx+ i 1)))
((fx= i n)
(values (%%finish-interval left-lower-bounds
left-upper-bounds)
(%%finish-interval right-lower-bounds
right-upper-bounds)))
(vector-set! right-lower-bounds (fx- i left-dimension) (vector-ref lower-bounds i))
(vector-set! right-upper-bounds (fx- i left-dimension) (vector-ref upper-bounds i))))
(vector-set! left-lower-bounds i (vector-ref lower-bounds i))
(vector-set! left-upper-bounds i (vector-ref upper-bounds i)))))
(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)))
(%%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)
(%%finish-interval (vector-concatenate (map %%interval-lower-bounds intervals))
(vector-concatenate (map %%interval-upper-bounds intervals))))
(define (interval-cartesian-product interval #!rest intervals)
(let ((intervals (cons interval 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: The resulting interval is empty: " interval lower-diffs upper-diffs))))))
(define (%%interval-volume interval)
(or (%%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 (interval-volume interval)
(cond ((not (interval? interval))
(error "interval-volume: The argument is not an interval: " interval))
(else
(%%interval-volume interval))))
(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 (fx= (%%interval-dimension interval1) (%%interval-dimension interval2))
(%%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 i #!rest multi-index-tail)
;; 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))
(else
(let ((multi-index (cons i multi-index-tail)))
(cond ((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)
(case (%%interval-dimension interval)
((1) (let ((lower-i (%%interval-lower-bound interval 0))
(upper-i (%%interval-upper-bound interval 0)))
(let i-loop ((i lower-i))
(if (< i upper-i)
(begin
(f i)
(i-loop (+ i 1)))))))
((2) (let ((lower-i (%%interval-lower-bound interval 0))
(lower-j (%%interval-lower-bound interval 1))
(upper-i (%%interval-upper-bound interval 0))
(upper-j (%%interval-upper-bound interval 1)))
(let i-loop ((i lower-i))
(if (< i upper-i)
(let j-loop ((j lower-j))
(if (< j upper-j)
(begin
(f i j)
(j-loop (+ j 1)))
(i-loop (+ i 1))))))))
((3) (let ((lower-i (%%interval-lower-bound interval 0))
(lower-j (%%interval-lower-bound interval 1))
(lower-k (%%interval-lower-bound interval 2))
(upper-i (%%interval-upper-bound interval 0))
(upper-j (%%interval-upper-bound interval 1))
(upper-k (%%interval-upper-bound interval 2)))
(let i-loop ((i lower-i))
(if (< i upper-i)
(let j-loop ((j lower-j))
(if (< j upper-j)
(let k-loop ((k lower-k))
(if (< k upper-k)
(begin
(f i j k)
(k-loop (+ k 1)))
(j-loop (+ j 1))))
(i-loop (+ i 1))))))))
((4) (let ((lower-i (%%interval-lower-bound interval 0))
(lower-j (%%interval-lower-bound interval 1))
(lower-k (%%interval-lower-bound interval 2))
(lower-l (%%interval-lower-bound interval 3))
(upper-i (%%interval-upper-bound interval 0))
(upper-j (%%interval-upper-bound interval 1))
(upper-k (%%interval-upper-bound interval 2))
(upper-l (%%interval-upper-bound interval 3)))
(let i-loop ((i lower-i))
(if (< i upper-i)
(let j-loop ((j lower-j))
(if (< j upper-j)
(let k-loop ((k lower-k))
(if (< k upper-k)
(let l-loop ((l lower-l))
(if (< l upper-l)
(begin
(f i j k l)
(l-loop (+ l 1)))
(k-loop (+ k 1))))
(j-loop (+ j 1))))
(i-loop (+ i 1))))))))
(else
(let* ((lower-bounds (%%interval-lower-bounds->list interval))
(upper-bounds (%%interval-upper-bounds->list interval))
(arg (map values lower-bounds))) ; copy lower-bounds
;; I'm not particularly happy with set! here because f might capture the continuation
;; and then funny things might pursue ...
;; But it seems that the only way to have this work efficiently without the set
;; is to have arrays with fortran-style numbering.
;; blah
(define (iterate lower-bounds-tail
upper-bounds-tail
arg-tail)
(let ((lower-bound (car lower-bounds-tail))
(upper-bound (car upper-bounds-tail)))
(if (null? (cdr arg-tail))
(let loop ((i lower-bound))
(if (< i upper-bound)
(begin
(set-car! arg-tail i)
(apply f arg)
(loop (+ i 1)))))
(let loop ((i lower-bound))
(if (< i upper-bound)
(begin
(set-car! arg-tail i)
(iterate (cdr lower-bounds-tail)
(cdr upper-bounds-tail)
(cdr arg-tail))
(loop (+ i 1))))))))
(iterate lower-bounds
upper-bounds
arg)))))
;;; 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
;;; This version assumes, and may use, that f is thread-safe and that operator is associative.
;;; The order of application of f and operator is not specified.
(define (%%interval-fold f operator identity interval)
(case (%%interval-dimension interval)
((1) (let ((lower-i (%%interval-lower-bound interval 0))
(upper-i (%%interval-upper-bound interval 0)))
(let i-loop ((i lower-i) (result identity))
(if (= i upper-i)
result
(i-loop (+ i 1) (operator (f i) result))))))
((2) (let ((lower-i (%%interval-lower-bound interval 0))
(lower-j (%%interval-lower-bound interval 1))
(upper-i (%%interval-upper-bound interval 0))
(upper-j (%%interval-upper-bound interval 1)))
(let i-loop ((i lower-i) (result identity))
(if (= i upper-i)
result
(let j-loop ((j lower-j) (result result))
(if (= j upper-j)
(i-loop (+ i 1) result)
(j-loop (+ j 1) (operator (f i j) result))))))))
((3) (let ((lower-i (%%interval-lower-bound interval 0))
(lower-j (%%interval-lower-bound interval 1))
(lower-k (%%interval-lower-bound interval 2))
(upper-i (%%interval-upper-bound interval 0))
(upper-j (%%interval-upper-bound interval 1))
(upper-k (%%interval-upper-bound interval 2)))
(let i-loop ((i lower-i) (result identity))
(if (= i upper-i)
result
(let j-loop ((j lower-j) (result result))
(if (= j upper-j)
(i-loop (+ i 1) result)
(let k-loop ((k lower-k) (result result))
(if (= k upper-k)
(j-loop (+ j 1) result)
(k-loop (+ k 1) (operator (f i j k) result))))))))))
((4) (let ((lower-i (%%interval-lower-bound interval 0))
(lower-j (%%interval-lower-bound interval 1))
(lower-k (%%interval-lower-bound interval 2))
(lower-l (%%interval-lower-bound interval 3))
(upper-i (%%interval-upper-bound interval 0))
(upper-j (%%interval-upper-bound interval 1))
(upper-k (%%interval-upper-bound interval 2))
(upper-l (%%interval-upper-bound interval 3)))
(let i-loop ((i lower-i) (result identity))
(if (= i upper-i)
result
(let j-loop ((j lower-j) (result result))
(if (= j upper-j)
(i-loop (+ i 1) result)
(let k-loop ((k lower-k) (result result))
(if (= k upper-k)
(j-loop (+ j 1) result)
(let l-loop ((l lower-l) (result result))
(if (= l upper-l)
(k-loop (+ k 1) result)
(l-loop (+ l 1) (operator (f i j k l) result))))))))))))
(else
(let* ((lower-bounds (%%interval-lower-bounds->list interval))
(upper-bounds (%%interval-upper-bounds->list interval))
(arg (map values lower-bounds))) ; copy lower-bounds
;; I'm not particularly happy with set! here because f or operator might capture
;; the continuation and then funny things might pursue ...
;; But it seems that the only way to have this work efficiently without the set~
;; is to have arrays with fortran-style numbering.
;; blah
(define (iterate lower-bounds-tail
upper-bounds-tail
arg-tail
result)
(let ((lower-bound (car lower-bounds-tail))
(upper-bound (car upper-bounds-tail)))
(if (null? (cdr arg-tail))
(let loop ((i lower-bound)
(result result))
(if (= i upper-bound)
result
(begin
(set-car! arg-tail i)
(loop (+ i 1)
(operator (apply f arg) result)))))
(let loop ((i lower-bound)
(result result))
(if (= i upper-bound)
result
(begin
(set-car! arg-tail i)
(loop (+ i 1)
(iterate (cdr lower-bounds-tail)
(cdr upper-bounds-tail)
(cdr arg-tail)
result))))))))
(iterate lower-bounds
upper-bounds
arg
identity)))))
;; We'll use the same basic container for all types of arrays.
(declare (inline))
(define-structure %%array
;; Part of all arrays
domain ;; an interval
getter ;; (lambda (i_0 ... i_n-1) ...) returns a value for (i_0,...,i_n-1) in (array-domain a)
;; Part of mutable arrays
setter ;; (lambda (v i_0 ... i_n-1) ...) sets a value for (i_0,...,i_n-1) in (array-domain a)
;; Part of specialized arrays
storage-class ;; a storage-class
body ;; the backing store for this array
indexer ;; see below
safe? ;; do we check whether bounds (in getters and setters) and values (in setters) are valid
in-order? ;; are the elements adjacent and in order?
copier: #f ;; We'll define our own %%array-copy
)
(define specialized-array-default-safe?
(let ((%%specialized-array-default-safe? #f))
(case-lambda
(() %%specialized-array-default-safe?)
((bool)
(cond ((not (boolean? bool))
(error "specialized-array-default-safe?: The argument is not a boolean: " bool))
(else
(set! %%specialized-array-default-safe? bool)))))))
(define specialized-array-default-mutable?
(let ((%%specialized-array-default-mutable? #t))
(case-lambda
(()
%%specialized-array-default-mutable?)
((bool)
(cond ((not (boolean? bool))
(error "specialized-array-default-mutable?: The argument is not a boolean: " bool))
(else
(set! %%specialized-array-default-mutable? bool)))))))
(declare (not inline))
;; 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 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
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
getter
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))))
;;;
;;; 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
;;;
(define-structure storage-class getter setter checker maker copier length default)
;;; 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 (srfi/179#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)
`(define ,(symbol-concatenate name '-storage-class)
(make-storage-class
;; getter:
(lambda (v i)
(,(symbol-concatenate prefix 'vector-ref) v i))
;; setter:
(lambda (v i val)
(,(symbol-concatenate prefix 'vector-set!) v i val))
;; checker
,checker
;; maker:
,(symbol-concatenate 'make- prefix 'vector)
;; copier
,(symbol-concatenate prefix 'vector-copy!)
;; length:
,(symbol-concatenate prefix 'vector-length)
;; default:
,default)))
'(generic s8 u8 s16 u16 s32 u32 s64 u64 f32 f64)
'("" s8 u8 s16 u16 s32 u32 s64 u64 f32 f64)
'(#f 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
))))
(make-standard-storage-classes)
;;; This sample implementation does not implement the following.
(define f16-storage-class #f)
(define f8-storage-class #f)
;;; 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)))))))
;; 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))
(define-macro (srfi/179#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)))
;; checker
(lambda (obj)
(and (complex? obj)
(inexact? (real-part obj))
(inexact? (imag-part obj))))
;; maker
(lambda (n val)
(let ((l (* 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)))))
(let ((result
`(begin
,@(map construct
'(32 64)))))
result))
(make-complex-storage-classes)
;;;
;;; 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 two functions were written by hand, so beware of bugs.
(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
(lambda multi-index
(do ((multi-index multi-index (cdr multi-index))
(lower-bounds lower-bounds (cdr lower-bounds))
(increments increments (cdr increments))
(result base (+ result (* (car increments)
(- (car multi-index)
(car lower-bounds))))))
((null? multi-index) result)))))
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.
;;;
(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 (%%compute-array-elements-in-order? domain indexer)
(case (%%interval-dimension domain)
((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)))))))))))))
(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-elements-in-order? array)
(let ((in-order? (%%array-in-order? array)))
(if (boolean? in-order?)
in-order?
(let ((in-order?
(%%compute-array-elements-in-order?
(%%array-domain array)
(%%array-indexer array))))
(%%array-in-order?-set! array in-order?)
in-order?))))
(define (array-elements-in-order? array)
(cond ((not (specialized-array? array))
(error "array-elements-in-order?: The argument is not a specialized array: " array))
(else
(%%array-elements-in-order? 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 'vector replacement-suffix)
expr)))
'(generic s8 u8 s16 u16 s32 u32 s64 u64 f32 f64)
'("" s8 u8 s16 u16 s32 u32 s64 u64 f32 f64))
(else
,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
(if safe?
(case (%%interval-dimension domain)
((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)))))))
(case (%%interval-dimension domain)
((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?
(if safe?
(case (%%interval-dimension domain)
((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))))))
(case (%%interval-dimension domain)
((1) (expand-setters (lambda (value i) (storage-class-setter body (indexer i) value))))
((2) (expand-setters (lambda (value i j) (storage-class-setter body (indexer i j) value))))
((3) (expand-setters (lambda (value i j k) (storage-class-setter body (indexer i j k) value))))
((4) (expand-setters (lambda (value i j k l) (storage-class-setter body (indexer i j k l) value))))
(else (expand-setters (lambda (value . multi-index) (storage-class-setter body (apply indexer multi-index) value)))))))))
(make-%%array domain
getter
setter
storage-class
body
indexer
safe?
in-order?))))
(define (%%interval->basic-indexer interval)
(case (%%interval-dimension interval)
((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-upper-bound interval 1)
(%%interval-lower-bound 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-upper-bound interval 2)
(%%interval-lower-bound interval 2))))
(increment-0 (* increment-1
(- (%%interval-upper-bound interval 1)
(%%interval-lower-bound 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-upper-bound interval 3)
(%%interval-lower-bound interval 3))))
(increment-1 (* increment-2
(- (%%interval-upper-bound interval 2)
(%%interval-lower-bound interval 2))))
(increment-0 (* increment-1
(- (%%interval-upper-bound interval 1)
(%%interval-lower-bound interval 1)))))
(%%indexer-4 0
low-0 low-1 low-2 low-3
increment-0 increment-1 increment-2 increment-3)))
(else
(let ((lower-bounds (%%interval-lower-bounds->list interval))
(upper-bounds (%%interval-upper-bounds->list interval)))
(let ((ranges (map (lambda (u l) (- u l)) upper-bounds lower-bounds)))
(do ((ranges (reverse ranges) (cdr ranges))
(increments (list 1) (cons (* (car increments) (car ranges))
increments)))
((null? (cdr ranges)) (%%indexer-generic 0 lower-bounds increments))))))))
(define (%%make-specialized-array interval
storage-class
;; must be mutable
safe?)
(let* ((body ((storage-class-maker storage-class)
(%%interval-volume interval)
(storage-class-default storage-class)))
(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 interval
#!optional
(storage-class generic-storage-class)
;; must be mutable?
(safe? (specialized-array-default-safe?)))
;; Returns a mutable specialized-array
(cond ((not (interval? interval))
(error "make-specialized-array: The first argument is not an interval: " interval))
((not (storage-class? storage-class))
(error "make-specialized-array: The second argument is not a storage-class: " interval storage-class))
((not (boolean? safe?))
(error "make-specialized-array: The third argument is not a boolean: " interval storage-class safe?))
(else
(%%make-specialized-array interval
storage-class
;; must be mutable
safe?))))
;;; We consolidate all moving of array elements to the following procedure.
(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
;; then
;; If the source is a specialized array
;; with 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
;; we now require that the domains of destination and source are
;; the same.
;; 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
;; We require the domains of destination and source to be the same.
;; 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.
(if (not (= (%%interval-volume (%%array-domain source))
(%%interval-volume (%%array-domain destination))))
(error (string-append caller "Arrays must have the same volume: ")
destination source))
(if (specialized-array? destination)
(if (%%array-elements-in-order? destination)
;; Now we do not assume that the domains are the same
;; maybe we can do a block copy
(if (and (specialized-array? source)
(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-elements-in-order? source))
;; do a block copy
(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.
(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)
((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")
((and (specialized-array? source)
(eq? destination-storage-class
(%%array-storage-class source)))
;; No checks needed
(let ((setter (storage-class-setter destination-storage-class))
(body (%%array-body destination)))
(%%interval-for-each
(case (%%interval-dimension domain)
((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)
((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)))
(error
(string-append
caller
"Not all elements of the source can be stored in destination: ")
destination source multi-index item)))))))
domain))
"In order, checks needed"))))
;; the elements of destination are not in order.
;; so we need the domains to be the same.
(let* ((setter
(%%array-setter destination))
(getter
(%%array-getter source))
(checker
(storage-class-checker (%%array-storage-class destination)))
(domain
(%%array-domain destination)))
(cond ((not (%%interval= domain (%%array-domain source)))
(error (string-append
caller
"Arrays must have the same domains: ")
destination source))
((or (eq? (%%array-storage-class destination)
generic-storage-class)
(and (specialized-array? source)
(eq? (%%array-storage-class destination)
(%%array-storage-class source))))
;; no checks needed
(%%interval-for-each
(case (%%interval-dimension domain)
((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)
"Out of order, no checks needed")
(else
;; checks needed
(%%interval-for-each
(case (%%interval-dimension domain)
((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)
(error
(string-append
caller
"Not all elements of the source can be stored in destination: ")
destination source multi-index item))))))
domain)
"Out of order, checks needed"))))
;; destination is not a specialized array, so checks,
;; if any, are built into the setter.
(let ((domain (%%array-domain destination)))
(if (not (%%interval= domain (%%array-domain source)))
(error (string-append
caller
"Arrays must have the same domains: ")
destination source)
(let* ((setter
(%%array-setter destination))
(getter
(%%array-getter source))
(domain
(%%array-domain destination)))
(%%interval-for-each
(case (%%interval-dimension domain)
((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 (%%array-copy array
result-storage-class
domain
mutable?
safe?)
(let ((result (%%make-specialized-array domain
result-storage-class
safe?)))
(%%move-array-elements result array "array-copy: ")
(if (not mutable?) ;; set the setter to #f if the final array is not mutable
(%%array-setter-set! result #f))
result))
(define (array-copy array
#!optional
(result-storage-class generic-storage-class)
(new-domain #f)
(mutable? (specialized-array-default-mutable?))
(safe? (specialized-array-default-safe?)))
(cond ((not (array? array))
(error "array-copy: The first argument is not an array: " array))
((not (storage-class? result-storage-class))
(error "array-copy: The second argument is not a storage-class: " result-storage-class))
((not (or (eq? new-domain #f) (%%interval? new-domain)))
(error "array-copy: The third argument is neither #f nor an interval: " new-domain))
((and (%%interval? new-domain)
(not (= (%%interval-volume new-domain)
(%%interval-volume (%%array-domain array)))))
(error
"array-copy: The volume of the third argument is not the volume of the domain of the first argument: "
array result-storage-class new-domain))
((not (boolean? mutable?))
(error "array-copy: The fourth argument is not a boolean: " mutable?))
((not (boolean? safe?))
(error "array-copy: The fifth argument is not a boolean: " safe?))
(else
(%%array-copy array
result-storage-class
(if new-domain new-domain (%%array-domain array))
mutable?
safe?))))
;;;
;;; 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)
(case (%%interval-dimension new-domain)
((1) (let* ((lower-0 (%%interval-lower-bound new-domain 0))
(upper-0 (%%interval-upper-bound new-domain 0))
(base (call-with-values
(lambda () (new-domain->old-domain lower-0))
old-indexer))
(increment-0 (if (< (+ lower-0 1) upper-0)
(- (call-with-values
(lambda () (new-domain->old-domain (+ lower-0 1)))
old-indexer)
base)
0)))
(%%indexer-1 base lower-0 increment-0)))
((2) (let* ((lower-0 (%%interval-lower-bound new-domain 0))
(lower-1 (%%interval-lower-bound new-domain 1))
(upper-0 (%%interval-upper-bound new-domain 0))
(upper-1 (%%interval-upper-bound new-domain 1))
(base (call-with-values
(lambda () (new-domain->old-domain lower-0 lower-1))
old-indexer))
(increment-0 (if (< (+ lower-0 1) upper-0)
(- (call-with-values
(lambda () (new-domain->old-domain (+ lower-0 1) lower-1))
old-indexer)
base)
0))
(increment-1 (if (< (+ lower-1 1) upper-1)
(- (call-with-values
(lambda () (new-domain->old-domain lower-0 (+ lower-1 1)))
old-indexer)
base)
0)))
(%%indexer-2 base lower-0 lower-1 increment-0 increment-1)))
((3) (let* ((lower-0 (%%interval-lower-bound new-domain 0))
(lower-1 (%%interval-lower-bound new-domain 1))
(lower-2 (%%interval-lower-bound new-domain 2))
(upper-0 (%%interval-upper-bound new-domain 0))
(upper-1 (%%interval-upper-bound new-domain 1))
(upper-2 (%%interval-upper-bound new-domain 2))
(base (call-with-values
(lambda () (new-domain->old-domain lower-0 lower-1 lower-2))
old-indexer))
(increment-0 (if (< (+ lower-0 1) upper-0)
(- (call-with-values
(lambda () (new-domain->old-domain (+ lower-0 1) lower-1 lower-2))
old-indexer)
base)
0))
(increment-1 (if (< (+ lower-1 1) upper-1)
(- (call-with-values
(lambda () (new-domain->old-domain lower-0 (+ lower-1 1) lower-2))
old-indexer)
base)
0))
(increment-2 (if (< (+ lower-2 1) upper-2)
(- (call-with-values
(lambda () (new-domain->old-domain lower-0 lower-1 (+ lower-2 1)))
old-indexer)
base)
0)))
(%%indexer-3 base lower-0 lower-1 lower-2 increment-0 increment-1 increment-2)))
((4) (let* ((lower-0 (%%interval-lower-bound new-domain 0))
(lower-1 (%%interval-lower-bound new-domain 1))
(lower-2 (%%interval-lower-bound new-domain 2))
(lower-3 (%%interval-lower-bound new-domain 3))
(upper-0 (%%interval-upper-bound new-domain 0))
(upper-1 (%%interval-upper-bound new-domain 1))
(upper-2 (%%interval-upper-bound new-domain 2))
(upper-3 (%%interval-upper-bound new-domain 3))
(base (call-with-values
(lambda () (new-domain->old-domain lower-0 lower-1 lower-2 lower-3))
old-indexer))
(increment-0 (if (< (+ lower-0 1) upper-0)
(- (call-with-values
(lambda () (new-domain->old-domain (+ lower-0 1) lower-1 lower-2 lower-3))
old-indexer)
base)
0))
(increment-1 (if (< (+ lower-1 1) upper-1)
(- (call-with-values
(lambda () (new-domain->old-domain lower-0 (+ lower-1 1) lower-2 lower-3))
old-indexer)
base)
0))
(increment-2 (if (< (+ lower-2 1) upper-2)
(- (call-with-values
(lambda () (new-domain->old-domain lower-0 lower-1 (+ lower-2 1) lower-3))
old-indexer)
base)
0))
(increment-3 (if (< (+ lower-3 1) upper-3)
(- (call-with-values
(lambda () (new-domain->old-domain lower-0 lower-1 lower-2 (+ lower-3 1)))
old-indexer)
base)
0)))
(%%indexer-4 base lower-0 lower-1 lower-2 lower-3 increment-0 increment-1 increment-2 increment-3)))
(else
(let* ((lower-bounds (%%interval-lower-bounds->list new-domain))
(upper-bounds (%%interval-upper-bounds->list new-domain))
(base (call-with-values
(lambda () (apply new-domain->old-domain lower-bounds))
old-indexer))
(increments (let ((increments (map (lambda (x) 0) lower-bounds))
(lower-bounds (map (lambda (x) x) lower-bounds)))
(let loop ((l lower-bounds)
(u upper-bounds)
(i increments)
(base base))
(if (null? l)
increments
(let ((new-base
(if (< (+ (car l) 1)
(car u))
(begin
(set-car! l (+ (car l) 1))
(let ((new-base (call-with-values
(lambda () (apply new-domain->old-domain lower-bounds))
old-indexer)))
(set-car! i (- new-base base))
new-base))
base)))
(loop (cdr l)
(cdr u)
(cdr i)
new-base)))))))
(%%indexer-generic base lower-bounds 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))
(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))
(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 array sides)
(cond ((not (array? array))
(error "array-tile: The first argument is not an array: " array sides))
((not (and (vector? sides)
(%%vector-every (lambda (x) (and (exact-integer? x) (positive? x))) sides)))
(error "array-tile: The second argument is not a vector of exact positive integers: " array sides))
((not (fx= (%%array-dimension array)
(vector-length sides)))
(error "array-tile: The dimension of the first argument (an array) does not equal the length of the second argument (a vector): " array sides))
(else
(let* ((n
(vector-length sides))
(domain
(%%array-domain array))
(lower-bounds
(%%interval-lower-bounds domain))
(upper-bounds
(%%interval-upper-bounds domain))
(result-lower-bounds
(make-vector n 0))
(result-upper-bounds
(vector-map (lambda (l u s)
(quotient (+ (- u l)
(- s 1))
s))
lower-bounds upper-bounds sides))
(result-domain
(%%finish-interval result-lower-bounds result-upper-bounds)))
(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 n
,@(map (lambda (k)
(let* ((indices
(iota k))
(args
(map (lambda (j) (symbol-append 'i j)) indices))
(lowers
(map (lambda (j) (symbol-append 'l j)) indices))
(uppers
(map (lambda (j) (symbol-append 'u j)) indices))
(sides
(map (lambda (j) (symbol-append 's j)) indices)))
`((,k)
(lambda ,args
(if (not (and ,@(map (lambda (arg) `(exact-integer? ,arg)) args)
(,(symbol-append '%%interval-contains-multi-index?- k) result-domain ,@args)))
(error "array-tile: Index to result array is not valid: " ,@args)
(let* (,@(map (lambda (l j)
`(,l (vector-ref lower-bounds ,j)))
lowers indices)
,@(map (lambda (u j)
`(,u (vector-ref upper-bounds ,j)))
uppers indices)
,@(map (lambda (s j)
`(,s (vector-ref sides ,j)))
sides indices)
(subdomain
(%%finish-interval (vector ,@(map (lambda (l s i)
`(+ ,l (* ,s ,i)))
lowers sides args))
(vector ,@(map (lambda (l u s i)
`(min ,u (+ ,l (* ,s (+ ,i 1)))))
lowers uppers sides args)))))
(%%array-extract array subdomain)))))))
'(1 2 3 4))
(else
(lambda i
(if (not (and (fx= (length i) n)
(%%every (lambda (x) (exact-integer? x)) i)
(%%interval-contains-multi-index?-general result-domain i)))
(apply error "array-tile: Index to result array is not valid: " i)
(let* ((i (list->vector i))
(subdomain (%%finish-interval
(vector-map (lambda (l s i)
(+ l (* s i)))
lower-bounds sides i)
(vector-map (lambda (l u s i)
(min u (+ l (* s (+ i 1)))))
lower-bounds upper-bounds sides i))))
(%%array-extract array subdomain)))))))
(make-array result-domain (generate-result))))))
(define (%%getter-translate getter translation)
(case (vector-length translation)
((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 - indices translation-list)))))))))
(define (%%setter-translate setter translation)
(case (vector-length translation)
((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 - indices translation-list)))))))))
(define (%%immutable-array-translate array translation)
(make-array (%%interval-translate (%%array-domain array) translation)
(%%getter-translate (%%array-getter array) translation)))
(define (%%mutable-array-translate array translation)
(make-array (%%interval-translate (%%array-domain array) translation)
(%%getter-translate (%%array-getter array) translation)
(%%setter-translate (%%array-setter array) translation)))
(define (%%specialized-array-translate array translation)
(%%specialized-array-share array
(%%interval-translate (%%array-domain array) translation)
(%%getter-translate values translation)
(%%array-in-order? array)))
(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))
((specialized-array? array)
(%%specialized-array-translate array translation))
((mutable-array? array)
(%%mutable-array-translate array translation))
(else
(%%immutable-array-translate array translation))))
(define-macro (srfi/179#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 (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))))))
'(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 (%%rotation->permutation k size)
;; Generates a permutation that rotates
;; 0 1 ... size-1
;; left by k units.
(let ((result (make-vector size)))
(let left-loop ((i 0)
(j k))
(if (fx< j size)
(begin
(vector-set! result i j)
(left-loop (fx+ i 1)
(fx+ j 1)))
(let right-loop ((i i)
(j 0))
(if (fx< i size)
(begin
(vector-set! result i j)
(right-loop (fx+ i 1)
(fx+ j 1)))
result))))))
(define (interval-rotate interval dim)
(if (not (interval? interval))
(error "interval-rotate: The first argument is not an interval: " interval dim)
(let ((d (%%interval-dimension interval)))
(if (not (and (fixnum? dim)
(fx< -1 dim d)))
(error "interval-rotate: The second argument is not an exact integer betweeen 0 (inclusive) and the interval-dimension of the first argument (exclusive): " interval dim)
(%%interval-permute interval (%%rotation->permutation dim d))))))
(define (array-rotate array dim)
(if (not (array? array))
(error "array-rotate: The first argument is not an array: " array dim)
(let ((d (%%array-dimension array)))
(if (not (and (fixnum? dim)
(fx< -1 dim d)))
(error "array-rotate: The second argument is not an exact integer betweeen 0 (inclusive) and the array-dimension of the first argument (exclusive): " array dim)
(%%array-permute array (%%rotation->permutation dim d))))))
(define-macro (srfi/179#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))
'(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 (srfi/179#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))
'(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 array1 array2)
(let* ((domain1 (%%array-domain array1))
(domain2 (%%array-domain array2))
(getter1 (%%array-getter array1))
(getter2 (%%array-getter array2))
(dimension1
(%%interval-dimension domain1))
(dimension2
(%%interval-dimension domain2))
(result-domain
(%%interval-cartesian-product (list domain1 domain2)))
(result-getter
(case dimension1
((1)
(case dimension2
((1)
(lambda (i1 i2)
(combiner (getter1 i1)
(getter2 i2))))
((2)
(lambda (i1 i2 j2)
(combiner (getter1 i1)
(getter2 i2 j2))))
((3)
(lambda (i1 i2 j2 k2)
(combiner (getter1 i1)
(getter2 i2 j2 k2))))
(else
(lambda (i1 . rest)
(combiner (getter1 i1)
(apply getter2 rest))))))
((2)
(case dimension2
((1)
(lambda (i1 j1 i2)
(combiner (getter1 i1 j1)
(getter2 i2))))
((2)
(lambda (i1 j1 i2 j2)
(combiner (getter1 i1 j1)
(getter2 i2 j2))))
(else
(lambda (i1 j1 . rest)
(combiner (getter1 i1 j1)
(apply getter2 rest))))))
((3)
(case dimension2
((1)
(lambda (i1 j1 k1 i2)
(combiner (getter1 i1 j1 k1)
(getter2 i2))))
(else
(lambda (i1 j1 k1 . rest)
(combiner (getter1 i1 j1 k1)
(apply getter2 rest))))))
(else
(lambda args
(combiner (apply getter1 (take args dimension1))
(apply getter2 (drop args dimension1))))))))
(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 (%%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-array left-interval
(case (%%interval-dimension left-interval)
((1) (case (%%interval-dimension right-interval)
((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)
((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)
((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)))))))
(else (lambda left-multi-index
(make-array right-interval
(lambda right-multi-index
(apply getter (append left-multi-index right-multi-index))))))))))))
(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-array left-interval
(case (%%interval-dimension left-interval)
((1) (case (%%interval-dimension right-interval)
((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)
((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)
((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)))))))
(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))))))))))))
(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-elements-in-order?
;; 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.
(%%compose-indexers (%%array-indexer array)
right-interval
(lambda right-multi-index
(apply values
(append (%%interval-lower-bounds->list left-interval)
right-multi-index))))))))
(make-array
left-interval
(case (%%interval-dimension left-interval)
((1) (case (%%interval-dimension right-interval)
((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)
((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)
((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?)))))
(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?)))))))))
(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)) (exclusive): " array right-dimension))
((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))))
;;;
;;; 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))
(getter-0 (%%array-getter array)))
(case (length arrays)
((0) (case (%%interval-dimension domain)
((1) (lambda (i) (f (getter-0 i))))
((2) (lambda (i j) (f (getter-0 i j))))
((3) (lambda (i j k) (f (getter-0 i j k))))
((4) (lambda (i j k l) (f (getter-0 i j k l))))
(else (lambda multi-index (f (apply getter-0 multi-index))))))
((1) (let ((getter-1 (%%array-getter (car arrays))))
(case (%%interval-dimension domain)
((1) (lambda (i) (f (getter-0 i)
(getter-1 i))))
((2) (lambda (i j) (f (getter-0 i j)
(getter-1 i j))))
((3) (lambda (i j k) (f (getter-0 i j k)
(getter-1 i j k))))
((4) (lambda (i j k l) (f (getter-0 i j k l)
(getter-1 i j k l))))
(else (lambda multi-index (f (apply getter-0 multi-index)
(apply getter-1 multi-index)))))))
((2) (let ((getter-1 (%%array-getter (car arrays)))
(getter-2 (%%array-getter (cadr arrays))))
(case (%%interval-dimension domain)
((1) (lambda (i) (f (getter-0 i)
(getter-1 i)
(getter-2 i))))
((2) (lambda (i j) (f (getter-0 i j)
(getter-1 i j)
(getter-2 i j))))
((3) (lambda (i j k) (f (getter-0 i j k)
(getter-1 i j k)
(getter-2 i j k))))
((4) (lambda (i j k l) (f (getter-0 i j k l)
(getter-1 i j k l)
(getter-2 i j k l))))
(else (lambda multi-index (f (apply getter-0 multi-index)
(apply getter-1 multi-index)
(apply getter-2 multi-index)))))))
((3) (let ((getter-1 (%%array-getter (car arrays)))
(getter-2 (%%array-getter (cadr arrays)))
(getter-3 (%%array-getter (caddr arrays))))
(case (%%interval-dimension domain)
((1) (lambda (i) (f (getter-0 i)
(getter-1 i)
(getter-2 i)
(getter-3 i))))
((2) (lambda (i j) (f (getter-0 i j)
(getter-1 i j)
(getter-2 i j)
(getter-3 i j))))
((3) (lambda (i j k) (f (getter-0 i j k)
(getter-1 i j k)
(getter-2 i j k)
(getter-3 i j k))))
((4) (lambda (i j k l) (f (getter-0 i j k l)
(getter-1 i j k l)
(getter-2 i j k l)
(getter-3 i j k l))))
(else (lambda multi-index (f (apply getter-0 multi-index)
(apply getter-1 multi-index)
(apply getter-2 multi-index)
(apply getter-3 multi-index)))))))
(else
(let ((getters (cons getter-0 (map array-getter arrays))))
(case (%%interval-dimension domain)
((1) (lambda (i) (apply f (map (lambda (g) (g i)) getters))))
((2) (lambda (i j) (apply f (map (lambda (g) (g i j)) getters))))
((3) (lambda (i j k) (apply f (map (lambda (g) (g i j k)) getters))))
((4) (lambda (i j k l) (apply f (map (lambda (g) (g i j k l)) getters))))
(else (lambda multi-index (apply f (map (lambda (g) (apply g multi-index)) getters))))))))))
(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 arguments after the first have the same domain: " f array arrays))
(else
(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 #!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 arguments after the first have the same domain: " f array arrays))
(else
(%%interval-for-each (%%specialize-function-applied-to-array-getters f array arrays)
(%%array-domain array)))))
(define-macro (srfi/179#macro-make-predicates)
(define (concat . args)
(string->symbol (apply string-append (map (lambda (s) (if (string? s) s (symbol->string s ))) args))))
(define (make-predicate name connector)
`(define (,(concat '%%interval- name) f interval)
(case (%%interval-dimension interval)
((1) (let ((lower-i (%%interval-lower-bound interval 0))
(upper-i (%%interval-upper-bound interval 0))
(index 0)
(n (%%interval-volume interval)))
(let i-loop ((i lower-i)
(index (fx- n 1)))
(cond ((eqv? 0 index)
(f i))
(else
(,connector (f i)
(i-loop (+ i 1)
(fx- index 1))))))))
((2) (let ((lower-i (%%interval-lower-bound interval 0))
(lower-j (%%interval-lower-bound interval 1))
(upper-i (%%interval-upper-bound interval 0))
(upper-j (%%interval-upper-bound interval 1))
(n (%%interval-volume interval)))
(let i-loop ((i lower-i)
(index (fx- n 1)))
;; (< i upper-i) is always true because index is >= 0
(let j-loop ((j lower-j)
(index index))
(cond ((= j upper-j)
(i-loop (+ i 1)
index))
((eqv? 0 index)
(f i j))
(else
(,connector (f i j)
(j-loop (+ j 1)
(fx- index 1)))))))))
((3) (let ((lower-i (%%interval-lower-bound interval 0))
(lower-j (%%interval-lower-bound interval 1))
(lower-k (%%interval-lower-bound interval 2))
(upper-i (%%interval-upper-bound interval 0))
(upper-j (%%interval-upper-bound interval 1))
(upper-k (%%interval-upper-bound interval 2))
(n (%%interval-volume interval)))
(let i-loop ((i lower-i)
(index (fx- n 1)))
;; (< i upper-i) is always true because index is >= 0
(let j-loop ((j lower-j)
(index index))
(if (< j upper-j)
(let k-loop ((k lower-k)
(index index))
(cond ((= k upper-k)
(j-loop (+ j 1)
index))
((eqv? 0 index)
(f i j k))
(else
(,connector (f i j k)
(k-loop (+ k 1)
(fx- index 1))))))
(i-loop (+ i 1)
index))))))
((4) (let ((lower-i (%%interval-lower-bound interval 0))
(lower-j (%%interval-lower-bound interval 1))
(lower-k (%%interval-lower-bound interval 2))
(lower-l (%%interval-lower-bound interval 3))
(upper-i (%%interval-upper-bound interval 0))
(upper-j (%%interval-upper-bound interval 1))
(upper-k (%%interval-upper-bound interval 2))
(upper-l (%%interval-upper-bound interval 3))
(n (%%interval-volume interval)))
(let i-loop ((i lower-i)
(index (fx- n 1)))
(let j-loop ((j lower-j)
(index index))
(if (< j upper-j)
(let k-loop ((k lower-k)
(index index))
(if (< k upper-k)
(let l-loop ((l lower-l)
(index index))
(cond ((= l upper-l)
(k-loop (+ k 1)
index))
((eqv? 0 index)
(f i j k l))
(else
(,connector (f i j k l)
(l-loop (+ l 1)
(fx- index 1))))))
(j-loop (+ j 1)
index)))
(i-loop (+ i 1)
index))))))
(else
(let* ((lowers (%%interval-lower-bounds interval))
(uppers (%%interval-upper-bounds interval))
(dimensions (vector-length lowers))
(arg (vector->list lowers)) ;; the argument to which f is applied
(tails (let ((result (make-vector dimensions))) ;; the tails of the argument
(do ((i 0 (fx+ i 1))
(arg arg (cdr arg)))
((fx= i dimensions) result)
(vector-set! result i arg)))))
(let loop ((dimension 0)
(total-index (fx- (%%interval-volume interval) 1)))
(cond ((= (car (vector-ref tails dimension))
(vector-ref uppers dimension))
;; We're done iterating in this dimension, set the arg index
;; at this dimension back to the lower bound, increment the
;; arg index at the previous dimension, and go back to the
;; previous dimension
(let ((previous-tail (vector-ref tails (fx- dimension 1))))
(set-car! (vector-ref tails dimension)
(vector-ref lowers dimension))
(set-car! previous-tail
(+ 1 (car previous-tail)))
(loop (fx- dimension 1)
total-index)))
((fx< dimension (fx- dimensions 1))
(loop (fx+ dimension 1)
total-index))
;; Now we're at the final dimension
((eqv? 0 total-index)
(apply f arg))
(else
(,connector (apply f arg)
(let ((current-tail (vector-ref tails dimension)))
(set-car! current-tail
(+ (car current-tail) 1))
(loop dimension
(fx- total-index 1))))))))))))
(let ((result
`(begin
,@(map make-predicate
'(any every)
'(or and)))))
result))
(macro-make-predicates)
(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 arguments after the first have the same domain: " f array arrays))
(else
(%%interval-every (%%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 arguments after the first have the same domain: " f array arrays))
(else
(%%interval-any (%%specialize-function-applied-to-array-getters f array arrays)
(%%array-domain array)))))
(define (%%array-fold op id a)
(%%interval-fold (%%array-getter a) op id (%%array-domain a)))
(define (array-fold op id a)
(cond ((not (procedure? op))
(error "array-fold: The first argument is not a procedure: " op id a))
((not (array? a))
(error "array-fold: The third argument is not an array: " op id a))
(else
(%%array-fold op id a))))
(define (array-fold-right op id a)
(cond ((not (procedure? op))
(error "array-fold-right: The first argument is not a procedure: " op id a))
((not (array? a))
(error "array-fold-right: The third argument is not an array: " op id a))
(else
;; We let array-reverse do a redundant array? check to not generate
;; a new vector of #t's.
(%%array-fold op id (array-reverse 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
(case (%%array-dimension A)
((1) (let ((box '())
(A_ (%%array-getter A)))
(%%interval-for-each
(lambda (i)
(if (null? box)
(set! box (list (A_ i)))
(set-car! box (sum (car box)
(A_ i)))))
(%%array-domain A))
(car box)))
((2) (let ((box '())
(A_ (%%array-getter A)))
(%%interval-for-each
(lambda (i j)
(if (null? box)
(set! box (list (A_ i j)))
(set-car! box (sum (car box)
(A_ i j)))))
(%%array-domain A))
(car box)))
((3) (let ((box '())
(A_ (%%array-getter A)))
(%%interval-for-each
(lambda (i j k)
(if (null? box)
(set! box (list (A_ i j k)))
(set-car! box (sum (car box)
(A_ i j k)))))
(%%array-domain A))
(car box)))
((4) (let ((box '())
(A_ (%%array-getter A)))
(%%interval-for-each
(lambda (i j k l)
(if (null? box)
(set! box (list (A_ i j k l)))
(set-car! box (sum (car box)
(A_ i j k l)))))
(%%array-domain A))
(car box)))
(else (let ((box '())
(A_ (%%array-getter A)))
(%%interval-for-each
(lambda args
(if (null? box)
(set! box (list (apply A_ args)))
(set-car! box (sum (car box)
(apply A_ args)))))
(%%array-domain A))
(car box)))))))
(define (array->list array)
(cond ((not (array? array))
(error "array->list: The argument is not an array: " array))
(else
(array-fold-right cons '() array))))
(define (list->array l
interval
#!optional
(result-storage-class generic-storage-class)
(mutable? (specialized-array-default-mutable?))
(safe? (specialized-array-default-safe?)))
(cond ((not (list? l))
(error "list->array: The first argument is not a list: " l interval))
((not (interval? interval))
(error "list->array: The second argument is not an interval: " l interval))
((not (storage-class? result-storage-class))
(error "list->array: The third argument is not a storage-class: " l interval result-storage-class))
((not (boolean? mutable?))
(error "list->array: The fourth argument is not a boolean: " l interval result-storage-class mutable?))
((not (boolean? safe?))
(error "list->array: The fifth argument is not a boolean: " l interval result-storage-class mutable? safe?))
(else
(let* ((checker
(storage-class-checker result-storage-class))
(setter
(storage-class-setter result-storage-class))
(result
(%%make-specialized-array interval
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))
(begin
(if (not mutable?)
(%%array-setter-set! result #f))
result)
(error "list->array: The length of the first argument does not equal the volume of the second: " l interval))
(let ((item (car local)))
(if (checker item)
(begin
(setter body i item)
(loop (fx+ i 1)
(cdr local)))
(error "list->array: Not every element of the list can be stored in the body of the array: " l interval item)))))))))
(define (array-assign! destination source)
(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))
((interval= (%%array-domain destination)
(%%array-domain source))
(%%move-array-elements destination source "array-assign!: ")
destination)
((not (fx= (%%interval-volume (%%array-domain destination))
(%%interval-volume (%%array-domain source))))
(error "array-assign!: The destination and source do not have the same number of elements: " destination source))
((not (specialized-array? destination))
(error "array-assign!: The destination and source do not have the same domains, and the destination is not a specialized array: " destination source))
((not (%%array-elements-in-order? destination))
(error "array-assign!: The destination and source do not have the same domains, and the elements of the destination are not stored adjacently and in order: "
destination source))
(else
(%%move-array-elements destination source "array-assign!: ")
destination)))
;;; 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 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 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))
(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)))
(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
(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?
(%%array-copy array
(%%array-storage-class array)
new-domain
(mutable-array? array)
(array-safe? array))
(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
((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)))))))))
(declare (inline))
| false |
b12b4de182b2551a968da5d9b3a076397213e58d
|
260c2fe607680e85283d6a83fafeeaab2a8ce5cb
|
/explore/flisp/diff-with-r5rs.scm
|
d3a1e7ae6f40180ff3830518e6917daa0c480807
|
[] |
no_license
|
KDr2/DS-III
|
742c663ace73904513c98e2c14807805960b4127
|
272a4f5430d67bc5be2b59d71a3ab25d1fe5a0f4
|
refs/heads/master
| 2023-06-23T06:00:15.178389 | 2023-06-20T08:55:44 | 2023-06-20T08:56:22 | 48,179,756 | 3 | 1 | null | 2019-05-14T08:03:14 | 2015-12-17T14:43:28 |
Shell
|
UTF-8
|
Scheme
| false | false | 342 |
scm
|
diff-with-r5rs.scm
|
;;
;; lambda/function with default args
(define (test-1 (a 1) (b 2)) (+ a b))
(princ (number->string (test-1 10)))
(newline)
;; read time evaluation [CLTL: Input/Output > PPLO > MC]
#.'(+ 1 2)
;; table library:
;; - table table? get put! table.clone
;; - table.values table.pairs table.keys table.invert
;; - table.foreach table.foldl
| false |
c0719745afd3f096f209d5685c27f9d72592fc75
|
fd9daee097ae6e309e4abf907513487315e91ca5
|
/src/buf.ss
|
ae4aa19a02341cdff6cff2bd7a7d4e77934396ca
|
[
"MIT"
] |
permissive
|
tqtifnypmb/choices
|
93c96e49e557f4c6871aab28eb8f0abae70bb901
|
d3dd2d31cb43f46d7a73c07611521f5cde7b57c2
|
refs/heads/master
| 2021-01-19T19:56:36.293246 | 2017-05-03T08:06:48 | 2017-05-03T08:06:48 | 88,466,503 | 2 | 2 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,901 |
ss
|
buf.ss
|
;buf
(define-ftype uv-buf
(struct
(base (* char))
(len size_t)))
(define (uv-buf-fill buf size)
(let ((region (make-ftype-pointer char
(foreign-alloc size))))
(ftype-set! uv-buf (base) buf region)
(ftype-set! uv-buf (len) buf size)))
(define (uv-buf->list buf)
(let ((size (ftype-ref uv-buf (len) buf)))
(let loop ((ret '())
(idx 0))
(if (< idx size)
(loop (append ret (cons (ftype-ref uv-buf (base idx) buf) '())) (+ idx 1))
ret))))
(define (list->uv-buf lst)
(let* ((len (length lst))
(region (make-ftype-pointer char (foreign-alloc (* len (ftype-sizeof char)))))
(buf (make-ftype-pointer uv-buf (foreign-alloc (ftype-sizeof uv-buf)))))
(ftype-set! uv-buf (base) buf region)
(ftype-set! uv-buf (len) buf len)
;; assign content to region
(let loop ((idx 0)
(l lst))
(if (< idx len)
(begin
(ftype-set! char () region idx (car l))
(loop (+ idx 1) (cdr l)))
buf))))
(define (uv-buf->string buf)
(list->string (uv-buf->list buf)))
(define (string->uv-buf str)
(list->uv-buf (string->list str)))
(define (release-uv-buf buf)
(foreign-free buf))
;sockaddr
(define-ftype sockaddr
(struct
(sa-len unsigned-8)
(sa-family unsigned-8)
(_ (array 14 char))))
(define-ftype in-addr
(struct
(s-addr unsigned-32)))
(define-ftype sockaddr-in
(struct
(sin-len unsigned-8)
(sin-family unsigned-8)
(sin-port unsigned-16)
(sin-addr in-addr)
(zero (array 8 char))))
(define (make-sockaddr-in)
(let ((ptr (make-ftype-pointer sockaddr-in
(foreign-alloc
(ftype-sizeof sockaddr-in)))))
ptr))
(define (release-sockaddr-in addr)
(foreign-free addr))
(define-syntax cast
(syntax-rules ()
((_ type ptr) (make-ftype-pointer type
(ftype-pointer-address ptr)))))
| true |
7bcb2c22b5dcc9c7b3a47758f852aea0b1d41928
|
4b480cab3426c89e3e49554d05d1b36aad8aeef4
|
/chapter-02/ex2.21-Yarra.ss
|
fec9cf6b5b31758d502efe31d5d0cc66b277a035
|
[] |
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 |
ss
|
ex2.21-Yarra.ss
|
(load "../misc/scheme-test.scm")
(define (map2 proc items)
(if (null? items)
'()
(cons (proc (car items))
(map proc (cdr items)))))
; 2.21
(define (square x) (* x x))
(define (square-list1 items)
(if (null? items)
'()
(cons (square (car items)) (square-list1 (cdr items)))))
(define (square-list2 items)
(map2 (lambda (x) (* x x)) items))
(equal?
(square-list1 (list 1 2 3 4 5))
(square-list2 (list 1 2 3 4 5)))
(define list1 (list 1 2 3 4 5))
(run
(make-testcase
'(assert-equal? (square-list1 list1) '(1 4 9 16 25))
'(assert-equal? (square-list2 list1) '(1 4 9 16 25))))
| false |
f02d3c2f84b3796bdde0d6ae789fe063fe3f3115
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/System/system/net/configuration/smtp-specified-pickup-directory-element.sls
|
0aa1b55285d6be0069030a02ea079e82a4425d09
|
[] |
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,063 |
sls
|
smtp-specified-pickup-directory-element.sls
|
(library (system
net
configuration
smtp-specified-pickup-directory-element)
(export new
is?
smtp-specified-pickup-directory-element?
pickup-directory-location-get
pickup-directory-location-set!
pickup-directory-location-update!)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new
System.Net.Configuration.SmtpSpecifiedPickupDirectoryElement
a
...)))))
(define (is? a)
(clr-is
System.Net.Configuration.SmtpSpecifiedPickupDirectoryElement
a))
(define (smtp-specified-pickup-directory-element? a)
(clr-is
System.Net.Configuration.SmtpSpecifiedPickupDirectoryElement
a))
(define-field-port
pickup-directory-location-get
pickup-directory-location-set!
pickup-directory-location-update!
(property:)
System.Net.Configuration.SmtpSpecifiedPickupDirectoryElement
PickupDirectoryLocation
System.String))
| true |
aa0be652ea2ce282f70531e4a6878a4c785b4846
|
971e9cb164ca5ca8bcc1b1da4d758b5e958d3c0f
|
/scheme-tests/equal.scm
|
35d7c0d2726218bd78a528260a4467475be88ac1
|
[
"BSD-3-Clause"
] |
permissive
|
lassik/upscheme
|
7c54210eb5172976db38fcfb56a3bb5d2c0be46f
|
61935bd866acb18902199bc4bc4cdd1760aa1ffc
|
refs/heads/master
| 2021-07-21T03:44:49.147081 | 2020-08-02T20:23:15 | 2020-08-02T20:23:15 | 201,488,401 | 4 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,410 |
scm
|
equal.scm
|
; Terminating equal predicate
; by Jeff Bezanson
;
; This version only considers pairs and simple atoms.
; equal?, with bounded recursion. returns 0 if we suspect
; nontermination, otherwise #t or #f for the correct answer.
(define (bounded-equal a b N)
(cond ((<= N 0) 0)
((and (pair? a) (pair? b))
(let ((as
(bounded-equal (car a) (car b) (- N 1))))
(if (number? as)
0
(and as
(bounded-equal (cdr a) (cdr b) (- N 1))))))
(else (eq? a b))))
; union-find algorithm
; find equivalence class of a cons cell, or #f if not yet known
; the root of a class is a cons that is its own class
(define (class table key)
(let ((c (hashtable-ref table key #f)))
(if (or (not c) (eq? c key))
c
(class table c))))
; move a and b to the same equivalence class, given c and cb
; as the current values of (class table a) and (class table b)
; Note: this is not quite optimal. We blindly pick 'a' as the
; root of the new class, but we should pick whichever class is
; larger.
(define (union! table a b c cb)
(let ((ca (if c c a)))
(if cb
(hashtable-set! table cb ca))
(hashtable-set! table a ca)
(hashtable-set! table b ca)))
; cyclic equal. first, attempt to compare a and b as best
; we can without recurring. if we can't prove them different,
; set them equal and move on.
(define (cyc-equal a b table)
(cond ((eq? a b) #t)
((not (and (pair? a) (pair? b))) (eq? a b))
(else
(let ((aa (car a)) (da (cdr a))
(ab (car b)) (db (cdr b)))
(cond ((or (not (eq? (atom? aa) (atom? ab)))
(not (eq? (atom? da) (atom? db)))) #f)
((and (atom? aa)
(not (eq? aa ab))) #f)
((and (atom? da)
(not (eq? da db))) #f)
(else
(let ((ca (class table a))
(cb (class table b)))
(if (and ca cb (eq? ca cb))
#t
(begin (union! table a b ca cb)
(and (cyc-equal aa ab table)
(cyc-equal da db table)))))))))))
(define (equal a b)
(let ((guess (bounded-equal a b 2048)))
(if (boolean? guess) guess
(cyc-equal a b (make-eq-hashtable)))))
| false |
8a046d9edb8867ce59c59f0533c6a37a915a9be6
|
3508dcd12d0d69fec4d30c50334f8deb24f376eb
|
/v8/src/compiler/midend/inlate.scm
|
6d21685c6f14314d6ec23acddbf919db3ffa03d8
|
[] |
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 | 6,582 |
scm
|
inlate.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.
|#
;;;; Scode->KMP Scheme
;;; package: (compiler midend)
(declare (usual-integrations))
(define (inlate/top-level scode)
(inlate/remember (inlate/scode scode #F)
(new-dbg-expression/make scode #F)))
(define-macro (define-inlator scode-type components . body)
(let ((proc-name (symbol-append 'INLATE/ scode-type))
(destructor (symbol-append scode-type '-COMPONENTS)))
`(DEFINE ,proc-name
(NAMED-LAMBDA (,proc-name FORM OUTER-FORM)
(LET ((HANDLER (LAMBDA ,components ,@body)))
(INLATE/REMEMBER (,destructor FORM HANDLER)
(NEW-DBG-EXPRESSION/MAKE FORM OUTER-FORM)))))))
(define (inlate/sequence+ form outer-form)
;; Kludge
(if (not (open-block? form))
(inlate/sequence form outer-form)
(inlate/remember
(let ((form* (open-block-components form unscan-defines)))
(if (sequence? form*)
(beginnify
(inlate/map-declarations
(map (lambda (action) (inlate/scode action form))
(sequence-actions form*))))
(inlate/scode form* form)))
(new-dbg-expression/make form outer-form))))
(define (inlate/constant object outer-form)
outer-form
`(QUOTE ,(if (unassigned-reference-trap? object) %unassigned object)))
(define (inlate/map-declarations exprs)
(let loop ((exprs exprs))
(cond ((null? exprs) '())
((and (QUOTE/? (car exprs))
(block-declaration? (quote/text (car exprs))))
(cons `(DECLARE ,@(block-declaration-text (quote/text (car exprs))))
(loop (cdr exprs))))
(else
(cons (car exprs) (loop (cdr exprs)))))))
(define-inlator VARIABLE (name)
`(LOOKUP ,name))
(define-inlator ASSIGNMENT (name svalue)
`(SET! ,name ,(inlate/scode svalue form)))
(define-inlator DEFINITION (name svalue)
`(DEFINE ,name ,(inlate/scode svalue form)))
(define-inlator THE-ENVIRONMENT ()
`(THE-ENVIRONMENT))
(define (inlate/lambda form outer-form)
outer-form ; ignored
(lambda-components form
(lambda (name req opt rest aux decls sbody)
name ; Not used
(let* ((lambda-list
(append req
(if (null? opt)
'()
(cons #!optional opt))
(if (not rest)
'()
(list #!rest rest))
(if (null? aux)
'()
(cons #!aux aux))))
(new
`(LAMBDA ,(cons (new-continuation-variable) lambda-list)
,(let ((body (inlate/scode sbody #F)))
(if (null? decls)
body
(beginnify
(list `(DECLARE ,@decls)
body)))))))
(inlate/remember new (new-dbg-procedure/make form))))))
#|
(define (inlate/lambda* name req opt rest aux decls sbody)
name ; ignored
`(LAMBDA ,(append (cons (new-continuation-variable) req)
(if (null? opt)
'()
(cons #!optional opt))
(if (not rest)
'()
(list #!rest rest))
(if (null? aux)
'()
(cons #!aux aux)))
,(let ((body (inlate/scode sbody)))
(if (null? decls)
body
(beginnify
(list `(DECLARE ,@decls)
body))))))
|#
(define-inlator IN-PACKAGE (environment expression)
`(IN-PACKAGE ,(inlate/scode environment form)
,(inlate/scode expression #F)))
(define-inlator COMBINATION (rator rands)
(let-syntax ((ucode-primitive
(macro (name)
(make-primitive-procedure name))))
(let-syntax ((is-operator?
(macro (value name)
`(or (eq? ,value (ucode-primitive ,name))
(and (absolute-reference? ,value)
(eq? (absolute-reference-name ,value)
',name))))))
(if (and (is-operator? rator LEXICAL-UNASSIGNED?)
(not (null? rands))
(the-environment? (car rands))
(not (null? (cdr rands)))
(symbol? (cadr rands)))
`(UNASSIGNED? ,(cadr rands))
`(CALL ,(inlate/scode rator form)
(QUOTE #F) ; continuation
,@(map (lambda (rand) (inlate/scode rand form))
rands))))))
(define-inlator COMMENT (text body)
text ; ignored
(inlate/scode body form))
(define-inlator SEQUENCE (actions)
(beginnify
(map (lambda (action) (inlate/scode action form))
actions)))
(define-inlator CONDITIONAL (pred conseq alt)
`(IF ,(inlate/scode pred form)
,(inlate/scode conseq form)
,(inlate/scode alt form)))
(define-inlator DISJUNCTION (pred alt)
`(OR ,(inlate/scode pred form)
,(inlate/scode alt form)))
(define-inlator ACCESS (environment name)
`(ACCESS ,name ,(inlate/scode environment form)))
(define-inlator DELAY (expression)
`(DELAY ,(inlate/scode expression form)))
(define inlate/scode
(let ((dispatch-vector
(make-vector (microcode-type/code-limit) inlate/constant)))
(let-syntax
((dispatch-entry
(macro (type handler)
`(VECTOR-SET! DISPATCH-VECTOR ,(microcode-type type)
(LAMBDA (EXPR OUTER-FORM)
(,handler EXPR OUTER-FORM))))))
(let-syntax
((dispatch-entries
(macro (types handler)
`(BEGIN ,@(map (lambda (type)
`(DISPATCH-ENTRY ,type ,handler))
types))))
(standard-entry
(macro (name)
`(DISPATCH-ENTRY ,name ,(symbol-append 'INLATE/ name)))))
;; quotations are treated as constants.
(standard-entry access)
(standard-entry assignment)
(standard-entry comment)
(standard-entry conditional)
(standard-entry definition)
(standard-entry delay)
(standard-entry disjunction)
(standard-entry variable)
(standard-entry in-package)
(standard-entry the-environment)
(dispatch-entries (combination-1 combination-2 combination
primitive-combination-0
primitive-combination-1
primitive-combination-2
primitive-combination-3)
inlate/combination)
(dispatch-entries (lambda lexpr extended-lambda) inlate/lambda)
(dispatch-entries (sequence-2 sequence-3) inlate/sequence+))
(named-lambda (inlate/expression expression outer-form)
((vector-ref dispatch-vector (object-type expression))
expression
outer-form)))))
;; Utilities
(define (inlate/remember new old)
(code-rewrite/remember* new old))
| false |
8f87c85c8714b1f9f480fd58b36fd0f0ea10e6b6
|
1de3d2f5aea84e4d19825c290980a3b4f7815f32
|
/monarchy/prototyping/queen.scm
|
c9de6a1730eea241cd81cad0ffa4658a2797978c
|
[] |
no_license
|
certainty/lisp-misc
|
37798607ca0275552c39683bad3080a42ba931fe
|
d5ee799f3ab0f2cc74bf3b2a83604dace160a649
|
refs/heads/master
| 2017-12-30T03:02:25.789701 | 2016-11-12T09:27:43 | 2016-11-12T09:27:43 | 69,743,925 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,030 |
scm
|
queen.scm
|
;; =license=
;; =/license=
;; This is the stable part of the program. It's a message bus that receives
;; Messages from the agent and publishes them to the consumers
(use zmq)
(main)
(define (main)
(let ((options (process-command-line)))
(if (daemonize? options)
(daemonized options (lambda () (run-application initialize)))
(run-application options))))
(define (daemonize? options)
(not (alist-ref "f" options)))
(define (daemonized options thunk)
;;daemonize
(thunk))
(define (run-application options)
(let ((agents (make-agents-updates-socket options))
(publisher (make-publisher-socket)))
(event-loop agents (make-event-handler publisher))))
(define (event-loop sockets handler)
(let loop ((items (map (lambda (socket) (make-poll-item socket in: #t)))))
(handler (poll items #t))
(loop items)))
(define ((make-event-handler publisher) connection)
;; process the message that comes in according to the protocol
;; and invoke apropriate actions
#t
)
| false |
154c06984ad0019373b57a2a3fb2ec00b91f92ba
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/mscorlib/system/runtime/remoting/channels/base-channel-with-properties.sls
|
32a11afe28e573191324a4153dc3a9aed554200c
|
[] |
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 | 579 |
sls
|
base-channel-with-properties.sls
|
(library (system runtime remoting channels base-channel-with-properties)
(export is? base-channel-with-properties? properties)
(import (ironscheme-clr-port))
(define (is? a)
(clr-is
System.Runtime.Remoting.Channels.BaseChannelWithProperties
a))
(define (base-channel-with-properties? a)
(clr-is
System.Runtime.Remoting.Channels.BaseChannelWithProperties
a))
(define-field-port
properties
#f
#f
(property:)
System.Runtime.Remoting.Channels.BaseChannelWithProperties
Properties
System.Collections.IDictionary))
| false |
31210fb115db3edf537df78d3cf4fdad78bd6c0f
|
424b80e2c2a1829f8815378dd08ed6b6021310f7
|
/homework/01/task-1.scm
|
3e9f9ded7190bdb652216557762b8b7d50a77175
|
[
"MIT"
] |
permissive
|
fmi-lab/fp-elective-2017
|
b8238b413f346f6e74a02af043293d27822c9ce2
|
e88d5c0319b6d03c0ecd8a12a2856fb1bf5dcbf3
|
refs/heads/master
| 2021-09-06T22:01:16.421169 | 2018-02-12T09:53:52 | 2018-02-12T09:53:52 | 106,176,573 | 7 | 3 |
MIT
| 2018-01-15T15:00:40 | 2017-10-08T13:02:09 |
Scheme
|
UTF-8
|
Scheme
| false | false | 933 |
scm
|
task-1.scm
|
(require rackunit rackunit/text-ui)
(define (argopt comparator f args)
(define (argopt-2 a b)
(if (comparator (f a) (f b)) a b))
(cond ((null? args) 'no-args)
((null? (cdr args)) (car args))
(else (argopt-2 (argopt comparator f (cdr args))
(car args)))))
(define (argmax f args)
(argopt > f args))
(define (argmin f args)
(argopt < f args))
(define (square x) (* x x))
(define task-1-tests
(test-suite
"Tests for task 1"
(check = (argmax square '(1 3 0 4 2.5 -4)) 4)
(check = (argmax square '(1 3 0 -4 2.5 4)) -4)
(check = (argmin square '(1 3 0 4 2.5 -4)) 0)
(check-equal? (argmin length '((1 2) () (2 a 5 7) (2 4))) '())
(check-equal? (argmin length '((1 2) (2 a 5 7) (2 4))) '(1 2))
(check-equal? (argmin length '((2 4) (2 a 5 7) (1 2))) '(2 4))
(check-equal? (argmax length '((1 2) () (2 a 5 7) (2 4))) '(2 a 5 7))))
(run-tests task-1-tests)
| false |
14ed7d988aee3c0a581d2ae4762629e726a12014
|
ae8b793a4edd1818c3c8b14a48ba0053ac5d160f
|
/Applications/iterators.scm
|
f4ccb1521ae535c3026b0452b2ba9bad6cb202b6
|
[] |
no_license
|
experimentsin/telosis
|
e820d0752f1b20e2913f6f49c0e2a4023f5eda97
|
4b55140efa8fc732291d251f18f1056dc700442f
|
refs/heads/master
| 2020-04-19T08:32:05.037165 | 2013-07-13T18:59:36 | 2013-07-13T18:59:36 | 11,391,770 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 3,552 |
scm
|
iterators.scm
|
;; Abstract (should just be a specification):
(define-abstract-class <iteration-state> (<object>) ())
(define-generic (initial-state (collection <object>)))
(define-generic (final-state (collection <object>)))
(define-generic (current-element (state <iteration-state>)))
(define-generic (completed-state? (state <iteration-state>)))
(define-generic (advance-state! (state <iteration-state>)))
;; Useful generic implementation class:
;; (Makes hybrid use of objects+closures - bleargh!)
(define-class <generic-iteration-state> (<iteration-state>)
((position accessor generic-iteration-position)
(access reader generic-iteration-access)
(next-position reader generic-iteration-next-position)
(done? reader generic-iteration-done?))
initargs (position access next-position done?)
constructor (make-generic-iteration-state position
access
next-position
done?)
predicate generic-iteration-state?)
(define-method (current-element (s <generic-iteration-state>))
((generic-iteration-access s) (generic-iteration-position s)))
(define-method (completed-state? (s <generic-iteration-state>))
((generic-iteration-done? s) (generic-iteration-position s)))
(define-method (advance-state! (s <generic-iteration-state>))
(let ((next-pos ((generic-iteration-next-position s)
(generic-iteration-position s))))
(set-generic-iteration-position! s next-pos))
s)
;; For built-in types...
;; Lists:
(define-method (initial-state (l <list>))
(make-generic-iteration-state l first rest null?))
(define-method (final-state (l <list>))
(make-generic-iteration-state (reverse l) first rest null?))
;; Array-like things:
(define (array-state array length ref forward?)
(let ((len (length array)))
(make-generic-iteration-state
0
(if forward?
(lambda (i) (ref array i))
(lambda (i) (ref array (- (- len i) 1))))
(lambda (i) (+ 1 i))
(lambda (i) (>= i len)))))
;; Vectors:
(define-method (initial-state (v <vector>))
(array-state v vector-length vector-ref #t))
(define-method (final-state (v <vector>))
(array-state v vector-length vector-ref #f))
;; Strings:
(define-method (initial-state (s <string>))
(array-state s string-length string-ref #t))
(define-method (final-state (s <string>))
(array-state s string-length string-ref #f))
;; ---
;; Useful functions:
(define (map-collections->list f c . others)
(let walk ((states (map initial-state (cons c others))))
(if (any? completed-state? states) '()
(let ((val (apply f (map current-element states))))
(for-each advance-state! states)
(cons val (walk states))))))
(define (for-each-in-collections f c . others)
(let walk ((states (map initial-state (cons c others))))
(unless (any? completed-state? states)
(apply f (map current-element states))
(for-each advance-state! states)
(walk states)))
#t)
(define (foldl-states f acc state)
(if (completed-state? state) acc
(let ((val (current-element state)))
(foldl-states f (f acc val) (advance-state! state)))))
(define (foldr-states f acc state)
(if (completed-state? state) acc
(let ((val (current-element state)))
(f val (foldr-states f acc (advance-state! state))))))
(define (foldl-collection f acc c)
(foldl-states f acc (initial-state c)))
(define (foldr-collection f acc c)
(foldr-states f acc (initial-state c)))
;; e.g.
(map-collections->list list '(1 2 3) "abc" (vector 'x 'y 'z))
;; -> '((1 #\a x) (2 #\b y) (3 #\c z))
| false |
fcf30ad8fc0043e13b71fb2d4d1d007dbc147466
|
0cf59b26a9e712f012594b6f664b83d9a4aaa9a1
|
/test/plugin.scm.test
|
9e54c66cf83b79941536875fe306ee9e30618717
|
[] |
no_license
|
keiji0/gauche-lib
|
343be938e9b69b639633655ef63c4160a970c57d
|
052b91cc06448fa0d84c112e8bfcaf04047e41bb
|
refs/heads/master
| 2016-09-09T21:05:31.271088 | 2012-01-09T12:34:31 | 2012-01-09T12:34:31 | 3,136,366 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 297 |
test
|
plugin.scm.test
|
;; -*- mode: scheme -*-
;; $Id: plugin.test.scm,v 1.1.1.1 2005/09/14 10:33:24 keiji Exp $
(use gauche.test)
(test-start "mw.plugin")
(use mw.plugin)
(test-module 'mw.plugin)
(initialize-plugins "%plugin")
(import-plugin hoge bar)
(test* "initialize-plugins" '(8)
(bar 8))
(test-end)
| false |
f9f443579d5530a5ad60f5438ee74cf9741e5d2d
|
1ed47579ca9136f3f2b25bda1610c834ab12a386
|
/sec3/sec3.4.1.scm
|
cfaae5850a7cad633a2364e07e78ac790103059e
|
[] |
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 | 605 |
scm
|
sec3.4.1.scm
|
;; 3.4. 並列性: 時が本質的
;; 局所状態を持つ計算オブジェクトのモデル化によって、
;; * 参照透明性の喪失
;; * 同一性と変化についての難しさ
;; * 評価の置き換えモデルが使えなくなる
;; といったデメリットを抱え込んだ。
;;
;; 代わりに得たものは"時"の概念である。式の評価結果が、評価されるタイミングによって異なる。
;; 3.4.1. 並列システムでの時
;; 並列システムでは、複数のプロセスが共通の状態変数を共有する必要がある
| false |
e119ccfd44b2803b2a826e158474a7afcfceace6
|
a8216d80b80e4cb429086f0f9ac62f91e09498d3
|
/lib/srfi/160/u32.sld
|
56a5f60c3366bebb58ef0c6df474fd22ec62eb42
|
[
"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,847 |
sld
|
u32.sld
|
(define-library (srfi 160 u32)
(export
make-u32vector
u32?
u32vector?
u32vector-ref
u32vector-set!
u32vector-length
(rename uvector-unfold u32vector-unfold)
(rename uvector-unfold-right u32vector-unfold-right)
(rename vector-copy u32vector-copy)
(rename vector-reverse-copy u32vector-reverse-copy)
(rename vector-append u32vector-append)
(rename vector-concatenate u32vector-concatenate)
(rename vector-append-subvectors u32vector-append-subvectors)
(rename vector-empty? u32vector-empty?)
(rename vector= u32vector=)
(rename vector-take u32vector-take)
(rename vector-take-right u32vector-take-right)
(rename vector-drop u32vector-drop)
(rename vector-drop-right u32vector-drop-right)
(rename vector-segment u32vector-segment)
(rename vector-fold u32vector-fold)
(rename vector-fold-right u32vector-fold-right)
(rename vector-map u32vector-map)
(rename vector-map! u32vector-map!)
(rename vector-for-each u32vector-for-each)
(rename vector-count u32vector-count)
(rename vector-cumulate u32vector-cumulate)
(rename vector-take-while u32vector-take-while)
(rename vector-take-while-right u32vector-take-while-right)
(rename vector-drop-while u32vector-drop-while)
(rename vector-drop-while-right u32vector-drop-while-right)
(rename vector-index u32vector-index)
(rename vector-index-right u32vector-index-right)
(rename vector-skip u32vector-skip)
(rename vector-skip-right u32vector-skip-right)
(rename vector-binary-search u32vector-binary-search)
(rename vector-any u32vector-any)
(rename vector-every u32vector-every)
(rename vector-partition u32vector-partition)
(rename vector-filter u32vector-filter)
(rename vector-remove u32vector-remove)
(rename vector-swap! u32vector-swap!)
(rename vector-fill! u32vector-fill!)
(rename vector-reverse! u32vector-reverse!)
(rename vector-copy! u32vector-copy!)
(rename vector-reverse-copy! u32vector-reverse-copy!)
(rename reverse-vector->list reverse-u32vector->list)
(rename reverse-list->vector reverse-list->u32vector)
(rename uvector->vector u32vector->vector)
(rename vector->uvector vector->u32vector)
(rename make-vector-generator make-u32vector-generator)
(rename write-vector write-u32vector))
(import (except (scheme base)
vector-append vector-copy vector-copy!
vector-map vector-for-each)
(scheme write)
(srfi 160 base))
(begin
(define uvector? u32vector?)
(define make-uvector make-u32vector)
(define vector u32vector)
(define uvector->list u32vector->list)
(define list->uvector list->u32vector)
(define uvector-length u32vector-length)
(define uvector-ref u32vector-ref)
(define uvector-set! u32vector-set!))
(include "uvector.scm"))
| false |
32760c258d84f0fb2e0ca03f0e55ba1658c02e44
|
a8216d80b80e4cb429086f0f9ac62f91e09498d3
|
/lib/scheme/define-values.scm
|
49c96732cc4284fe1d99d7735b0093fec3aa0edd
|
[
"BSD-3-Clause"
] |
permissive
|
ashinn/chibi-scheme
|
3e03ee86c0af611f081a38edb12902e4245fb102
|
67fdb283b667c8f340a5dc7259eaf44825bc90bc
|
refs/heads/master
| 2023-08-24T11:16:42.175821 | 2023-06-20T13:19:19 | 2023-06-20T13:19:19 | 32,322,244 | 1,290 | 223 |
NOASSERTION
| 2023-08-29T11:54:14 | 2015-03-16T12:05:57 |
Scheme
|
UTF-8
|
Scheme
| false | false | 1,030 |
scm
|
define-values.scm
|
(define-syntax define-values
(syntax-rules ()
((define-values () expr)
(define dummy
(call-with-values (lambda () expr)
(lambda args #f))))
((define-values (var) expr)
(define var expr))
((define-values (var0 var1 ... varn) expr)
(begin
(define var0
(call-with-values (lambda () expr) list))
(define var1
(let ((v (cadr var0)))
(set-cdr! var0 (cddr var0))
v))
...
(define varn
(let ((v (cadr var0)))
(set! var0 (car var0))
v))))
((define-values (var0 var1 ... . var-dot) expr)
(begin
(define var0
(call-with-values (lambda () expr) list))
(define var1
(let ((v (cadr var0)))
(set-cdr! var0 (cddr var0))
v))
...
(define var-dot
(let ((v (cdr var0)))
(set! var0 (car var0))
v))))
((define-values var expr)
(define var
(call-with-values (lambda () expr) list)))))
| true |
1f393cee6c64d67d9c7b33b84b7198d3b442e0a2
|
9998f6f6940dc91a99e0e2acb4bc4e918f49eef0
|
/src/collects/moby/runtime/error-struct-to-dom.ss
|
237b0de01484b4ca3aaa481609d3464d91979fa0
|
[] |
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 | 31,116 |
ss
|
error-struct-to-dom.ss
|
#lang s-exp "../../../private/restricted-runtime-scheme.ss"
(require "arity-struct.ss")
(require "error-struct.ss")
(require "stx.ss")
(require "scheme-value-to-dom.ss")
(require "dom-helpers.ss")
(require "dom-parameters.ss")
;; Error structure to dom code.
;; These functions produce DOMs out of the values in error-struct,
;; ready to be styled.
(define (loc->jsexpr a-loc)
(make-hash `((offset . ,(number->string (Loc-offset a-loc)))
(line . ,(number->string (Loc-line a-loc)))
(column . ,(number->string (Loc-column a-loc)))
(span . ,(number->string (Loc-span a-loc)))
(id . ,(Loc-id a-loc)))))
(define (error-struct->jsexpr an-error)
(define error-type (moby-error-error-type an-error))
(cond
[(Message? error-type)
(let loop ([parts (Message-parts error-type)])
(apply append (map (lambda (part)
(cond
[(list? part)
(apply append (map loop part))]
[(string? part)
(list part)]
[(ColoredPart? part)
(list (make-hash `((type . "ColoredPart")
(text . ,(ColoredPart-text part))
(loc . ,(loc->jsexpr (ColoredPart-loc part))))))]
[(GradientPart? part)
(list (make-hash `((type . "GradientPart")
(parts . ,(map loop (GradientPart-parts part))))))]
[(MultiPart? part)
(list (make-hash `((type . "MultiPart")
(text . ,(MultiPart-text part))
(locs . ,(map loc->jsexpr (MultiPart-locs part)))
(solid . ,(MultiPart-solid part)))))]))
parts)))]
[else
#f]))
;; error-struct-to-dom-sexp: dom (dom-parameters | false) -> sexp
;; Convert an error structure to a dom-sexp. Optionally provide a dom-parameters
;; that defines custom dom converters.
(define (error-struct->dom-sexp an-error maybe-dom-parameters)
(local [(define embedded-location (moby-error-location an-error))
(define error-type (moby-error-error-type an-error))
(define (add-toplevel-dom-error-wrapper a-dom)
`(span ((class "Error"))
,a-dom
(br () "")
(span ((class "Error.location"))
,(Loc->dom-sexp embedded-location))))]
(add-toplevel-dom-error-wrapper
(cond
[(Message? error-type)
`(span ((class "Message"))
,@(let loop ([parts (Message-parts error-type)])
(apply append (map (lambda (part)
(cond
[(list? part)
(apply append (map loop part))]
[(string? part)
(list part)]
[(ColoredPart? part)
(list (ColoredPart-text part))]
[(GradientPart? part)
(apply append (map loop (GradientPart-parts part)))]
[(MultiPart? part)
(list (MultiPart-text part))]))
parts))))]
[(moby-error-type:unclosed-lexical-token? error-type)
`(span ((class "Error-UnclosedLexicalToken"))
(span ((class "Error.reason"))
"Found "
,(scheme-value->dom-sexp (moby-error-type:unclosed-lexical-token-opener error-type)
maybe-dom-parameters)
" to start a "
,(moby-error-type:unclosed-lexical-token-type error-type)
", but no "
,(scheme-value->dom-sexp (moby-error-type:unclosed-lexical-token-closer error-type)
maybe-dom-parameters)
" to close it.")
(span ((class "Error-UnclosedLexicalToken.type")
(style "display:none"))
,(moby-error-type:unclosed-lexical-token-type error-type))
(span ((class "Error-UnclosedLexicalToken.opener")
(style "display:none"))
,(symbol->string (moby-error-type:unclosed-lexical-token-opener error-type)))
(span ((class "Error-UnclosedLexicalToken.closer")
(style "display:none"))
,(symbol->string (moby-error-type:unclosed-lexical-token-closer error-type))))]
[(moby-error-type:unrecognized-lexical-token? error-type)
`(span ((class "Error-UnrecognizedLexicalToken"))
(span ((class "Error.reason"))
"Found "
,(scheme-value->dom-sexp (moby-error-type:unrecognized-lexical-token-token error-type)
maybe-dom-parameters)
" which is not recognized as a program element.")
(span ((class "Error-UnrecognizedLexicalToken.token")
(style "display:none"))
,(symbol->string (moby-error-type:unrecognized-lexical-token-token error-type))))]
[(moby-error-type:unsupported-lexical-token? error-type)
`(span ((class "Error-UnsupportedLexicalToken"))
(span ((class "Error.reason"))
,(scheme-value->dom-sexp (moby-error-type:unsupported-lexical-token-token error-type)
maybe-dom-parameters)
" is currently not supported.")
(span ((class "Error-UnsupportedLexicalToken.token")
(style "display:none"))
,(symbol->string (moby-error-type:unsupported-lexical-token-token error-type))))]
[(moby-error-type:unsupported-expression-form? error-type)
`(span ((class "Error-UnsupportedExpressionForm"))
(span ((class "Error.reason"))
,(stx->dom-sexp (moby-error-type:unsupported-expression-form-expr error-type)
maybe-dom-parameters)
" is currently not supported.")
(span ((class "Error-UnsupportedExpressionForm.expr")
(style "display:none"))
,(stx->dom-sexp (moby-error-type:unsupported-expression-form-expr error-type)
maybe-dom-parameters)))]
;;fixme: is this ever called?
[(moby-error-type:unclosed-parentheses? error-type)
`(span ((class "Error-UnclosedParentheses"))
(span ((class "Error.reason"))
"Found "
,(scheme-value->dom-sexp (moby-error-type:unclosed-parentheses-opener error-type)
maybe-dom-parameters)
" to start an expression, but no "
,(scheme-value->dom-sexp (moby-error-type:unclosed-parentheses-closer error-type)
maybe-dom-parameters)
" to close it.")
(span ((class "Error-UnclosedParentheses.opener")
(style "display:none"))
,(symbol->string (moby-error-type:unclosed-parentheses-opener error-type)))
(span ((class "Error-UnclosedParentheses.closer")
(style "display:none"))
,(symbol->string (moby-error-type:unclosed-parentheses-closer error-type))))]
;;fixme: is this ever called?
[(moby-error-type:unbalanced-parentheses? error-type)
`(span ((class "Error-UnbalancedParentheses"))
"Found "
,(scheme-value->dom-sexp
(moby-error-type:unbalanced-parentheses-opener error-type)
maybe-dom-parameters)
" earlier, and expected it to be matched with "
,(scheme-value->dom-sexp
(moby-error-type:unbalanced-parentheses-closer error-type)
maybe-dom-parameters)
", but instead found "
,(scheme-value->dom-sexp
(moby-error-type:unbalanced-parentheses-observed error-type)
maybe-dom-parameters)
".")]
[(moby-error-type:syntax-not-applied? error-type)
`(span ((class "Error-SyntaxNotApplied"))
""
,(stx->dom-sexp (moby-error-type:syntax-not-applied-keyword error-type)
maybe-dom-parameters)
": expected an open parenthesis before "
,(stx->dom-sexp (moby-error-type:syntax-not-applied-keyword error-type)
maybe-dom-parameters)
", but found none"
)]
;;fixme: is this ever called?
[(moby-error-type:closing-parenthesis-before-opener? error-type)
`(span ((class "Error-ClosingParenthesisBeforeOpener"))
"Found "
,(scheme-value->dom-sexp
(moby-error-type:closing-parenthesis-before-opener-closer error-type)
maybe-dom-parameters)
" without it being paired with a left parenthesis.")]
[(moby-error-type:duplicate-identifier? error-type)
`(span ((class "Error-DuplicateIdentifier"))
(span ((class "Error.reason"))
"The variable "
,(scheme-value->dom-sexp (moby-error-type:duplicate-identifier-id error-type)
maybe-dom-parameters)
" has been duplicated.")
(span ((class "Error-DuplicateIdentifier.secondLocation")
(style "display:none"))
,(Loc->dom-sexp (moby-error-type:duplicate-identifier-second-location error-type))))]
[(moby-error-type:expected-identifier? error-type)
`(span ((class "Error-ExpectedIdentifier"))
(span ((class "Error.reason"))
"Expected a variable but received "
,(stx->dom-sexp (moby-error-type:expected-identifier-observed error-type)
maybe-dom-parameters)
" instead."))]
[(moby-error-type:expected-list-of-identifiers? error-type)
`(span ((class "Error-ExpectedListOfIdentifiers"))
(span ((class "Error.reason"))
"Within " ,@(prepend-indefinite-article
(stx->dom-sexp
(moby-error-type:expected-list-of-identifiers-who error-type)
maybe-dom-parameters))
", expected a list of identifiers but received "
,(stx->dom-sexp (moby-error-type:expected-list-of-identifiers-observed error-type)
maybe-dom-parameters)
" instead."))]
[(moby-error-type:undefined-identifier? error-type)
`(span ((class "Error-UndefinedIdentifier"))
(span ((class "Error.reason"))
,(scheme-value->dom-sexp (moby-error-type:undefined-identifier-id error-type)
maybe-dom-parameters)
" is unknown; it's not defined as an input or a primitive."))]
[(moby-error-type:structure-identifier-not-expression? error-type)
`(span ((class "Error-StructureIdentifierNotExpression"))
(span ((class "Error.reason"))
"The structure name "
,(scheme-value->dom-sexp (moby-error-type:structure-identifier-not-expression-id
error-type)
maybe-dom-parameters)
" can't be used as an expression."))]
[(moby-error-type:provided-name-not-defined? error-type)
`(span ((class "Error-ProvidedNameNotDefined"))
(span ((class "Error.reason"))
"The provided name "
,(scheme-value->dom-sexp (moby-error-type:provided-name-not-defined-id error-type)
maybe-dom-parameters)
" is not defined in the program."))]
[(moby-error-type:redefinition-not-allowed? error-type)
`(span ((class "Error-RedefinitionNotAllowed"))
(span ((class "Error.reason"))
"The defined name "
,(scheme-value->dom-sexp
(moby-error-type:redefinition-not-allowed-id error-type)
maybe-dom-parameters)
" is being defined in the program, but it already has a definition that is not allowed to be redefined."))]
[(moby-error-type:unknown-module? error-type)
`(span ((class "Error-UnknownModule"))
(span ((class "Error.reason"))
"Found require of the module "
,(scheme-value->dom-sexp (moby-error-type:unknown-module-path error-type)
maybe-dom-parameters)
", but this module is unknown."))]
[(moby-error-type:branch-value-not-boolean? error-type)
`(span ((class "Error-BranchValueNotBoolean"))
"Expected the question's value to be a boolean expression, "
"("
,(scheme-value->dom-sexp true maybe-dom-parameters)
" or "
,(scheme-value->dom-sexp false maybe-dom-parameters)
"), "
"but instead found "
,(scheme-value->dom-sexp
(moby-error-type:branch-value-not-boolean-observed error-type)
maybe-dom-parameters)
".")]
[(moby-error-type:begin-body-empty? error-type)
`(span ((class "Error-BeginBodyEmpty"))
"Inside a begin, expected to find a body, but nothing was found.")]
[(moby-error-type:boolean-chain-too-few-elements? error-type)
`(span ((class "Error-BooleanChainTooFewElements"))
"Inside an "
,(scheme-value->dom-sexp (moby-error-type:boolean-chain-too-few-elements-id error-type)
maybe-dom-parameters)
", expected to see at least two expressions, but both were not found.")]
[(moby-error-type:lambda-too-few-elements? error-type)
`(span ((class "Error-LambdaTooFewElements"))
"Inside a lambda, expected to see a list of arguments and a single body, "
"but both of these were not found.")]
[(moby-error-type:lambda-too-many-elements? error-type)
`(span ((class "Error-LambdaTooManyElements"))
"Inside a lambda, expected to see a list of arguments and a single body, "
"more than two of these were found.")]
[(moby-error-type:missing-expression-following-quote? error-type)
`(span ((class "Error-MissingExpressionFollowingQuote"))
"After a "
,(stx->dom-sexp (moby-error-type:missing-expression-following-quote-quote-stx error-type)
maybe-dom-parameters)
", expected to see another expression immediately following it, but none was found.")]
[(moby-error-type:quote-too-few-elements? error-type)
`(span ((class "Error-QuoteTooFewElements"))
"Inside a quote, expected to see a single argument, but none was found.")]
[(moby-error-type:quote-too-many-elements? error-type)
`(span ((class "Error-QuoteTooManyElements"))
"Inside a quote, expected to single a single element, but more than one was found.")]
[(moby-error-type:quasiquote-too-few-elements? error-type)
`(span ((class "Error-QuasiquoteTooFewElements"))
"Inside a quasiquote, expected to find a single argument, but none was found.")]
[(moby-error-type:quasiquote-too-many-elements? error-type)
`(span ((class "Error-QuasiquoteTooManyElements"))
"Inside a quasiquote, expected find a single element, but more than one were found.")]
[(moby-error-type:unquote-too-few-elements? error-type)
`(span ((class "Error-UnquoteTooFewElements"))
"Inside an unquote, expected to find a single argument, but none was found.")]
[(moby-error-type:unquote-too-many-elements? error-type)
`(span ((class "Error-UnquoteTooManyElements"))
"Inside a unquote, expected to find a single element, but more than one were found.")]
[(moby-error-type:unquote-splicing-too-few-elements? error-type)
`(span ((class "Error-UnquoteTooFewElements"))
"Inside an unquote-splicing, expected to find a single argument, but none was found.")]
[(moby-error-type:unquote-splicing-too-many-elements? error-type)
`(span ((class "Error-UnquoteTooManyElements"))
"Inside a unquote-splicing, expected to single a single element, but more than one were found.")]
[(moby-error-type:when-no-body? error-type)
`(span ((class "Error-WhenNoBody"))
"Inside a " (scheme-value->dom-sexp 'when maybe-dom-parameters)
", expected to find a body, but none was found.")]
[(moby-error-type:unless-no-body? error-type)
`(span ((class "Error-WhenNoBody"))
"Inside an " (scheme-value->dom-sexp 'unless maybe-dom-parameters)
", expected to find a body, but none was found.")]
[(moby-error-type:check-expect? error-type)
`(span ((class "Error-CheckExpect"))
"Inside a "
,(scheme-value->dom-sexp 'check-expect maybe-dom-parameters)
", the observed value "
,(scheme-value->dom-sexp (moby-error-type:check-expect-observed error-type) maybe-dom-parameters)
" does not match the expected value "
,(scheme-value->dom-sexp (moby-error-type:check-expect-expected error-type) maybe-dom-parameters)
".")]
[(moby-error-type:check-within? error-type)
`(span ((class "Error-CheckWithin"))
"Inside a "
,(scheme-value->dom-sexp 'check-within maybe-dom-parameters)
", the observed value "
,(scheme-value->dom-sexp (moby-error-type:check-within-observed error-type) maybe-dom-parameters)
" does not match the expected value "
,(scheme-value->dom-sexp (moby-error-type:check-within-expected error-type) maybe-dom-parameters)
" within the bounds "
,(scheme-value->dom-sexp (moby-error-type:check-within-within error-type) maybe-dom-parameters)
".")]
[(moby-error-type:check-error? error-type)
`(span ((class "Error-CheckError"))
"Inside a "
,(scheme-value->dom-sexp 'check-expect maybe-dom-parameters)
", the observed error "
,(scheme-value->dom-sexp (moby-error-type:check-error-observed error-type) maybe-dom-parameters)
" does not match the expected error "
,(scheme-value->dom-sexp (moby-error-type:check-error-expected error-type) maybe-dom-parameters)
".")]
[(moby-error-type:check-error-no-error? error-type)
`(span ((class "Error-CheckErrorNoError"))
"Expected the error "
,(scheme-value->dom-sexp (moby-error-type:check-error-no-error-expected error-type) maybe-dom-parameters)
" but instead received the value "
,(scheme-value->dom-sexp (moby-error-type:check-error-no-error-observed error-type) maybe-dom-parameters))]
[(moby-error-type:application-arity? error-type)
`(span ((class "Error-ApplicationArity"))
(span ((class "Error.reason"))
"The function "
,(scheme-value->dom-sexp (moby-error-type:application-arity-who error-type) maybe-dom-parameters)
" expects "
,(arity-to-dom-sexp (moby-error-type:application-arity-expected error-type))
" inputs, but instead found "
,(number->string (moby-error-type:application-arity-observed error-type))
" inputs."))]
[(moby-error-type:application-operator-not-a-function? error-type)
`(span ((class "Error-ApplicationOperatorNotAFunction"))
(span ((class "Error.reason"))
"The operator "
,(scheme-value->dom-sexp
(moby-error-type:application-operator-not-a-function-who error-type)
maybe-dom-parameters)
" has a value "
,(scheme-value->dom-sexp
(moby-error-type:application-operator-not-a-function-val error-type)
maybe-dom-parameters)
", but this value isn't a function."))]
[(moby-error-type:type-mismatch? error-type)
`(span ((class "Error-TypeMismatch"))
(span ((class "Error.reason"))
"The function "
,(scheme-value->dom-sexp
(moby-error-type:type-mismatch-who error-type)
maybe-dom-parameters)
" expects "
,@(prepend-indefinite-article
(expected-value-to-dom-sexp
(moby-error-type:type-mismatch-expected error-type)))
" as its "
,(number->string
(moby-error-type:type-mismatch-position error-type))
,(ordinal-ending (moby-error-type:type-mismatch-position error-type))
" argument, but instead found "
,(scheme-value->dom-sexp
(moby-error-type:type-mismatch-observed error-type)
maybe-dom-parameters)
"."))]
[(moby-error-type:index-out-of-bounds? error-type)
`(span ((class "Error-IndexOutOfBounds"))
(span ((class "Error.reason"))
"The index "
,(scheme-value->dom-sexp
(moby-error-type:index-out-of-bounds-observed error-type)
maybe-dom-parameters)
" is not within the expected boundary ["
,(scheme-value->dom-sexp
(moby-error-type:index-out-of-bounds-minimum error-type)
maybe-dom-parameters)
", "
,(scheme-value->dom-sexp
(moby-error-type:index-out-of-bounds-maximum error-type)
maybe-dom-parameters)
"]"
))]
[(moby-error-type:conditional-exhausted? error-type)
`(span ((class "Error-ConditionalExhausted"))
(span ((class "Error.reason"))
"All of the questions inside a cond were false, "
"and at least one of them has to be true."))]
[(moby-error-type:generic-runtime-error? error-type)
`(span ((class "Error-GenericRuntimeError"))
(span ((class "Error.reason"))
,(moby-error-type:generic-runtime-error-reason error-type)))]
[(moby-error-type:generic-syntactic-error? error-type)
`(span ((class "Error-GenericSyntacticError"))
(span ((class "Error.reason"))
,(moby-error-type:generic-syntactic-error-reason error-type))
(span ((class "Error-GenericSyntacticError.otherLocations"))
,@(map Loc->dom-sexp
(moby-error-type:generic-syntactic-error-other-locations error-type))))]
[(moby-error-type:generic-read-error? error-type)
`(span ((class "Error-GenericReadError"))
(span ((class "Error.reason"))
,(moby-error-type:generic-read-error-message error-type))
(span ((class "Error-GenericReadError.locations"))
,@(map Loc->dom-sexp
(moby-error-type:generic-read-error-locations error-type))))]
[else
(error 'error-struct-to-dom "Could not convert ~a" error-type)]))))
;; Loc->dom-sexp: loc -> sexp
;; Given a location, produce a dom representation of that location.
(define (Loc->dom-sexp a-loc)
`(span ((class "location-reference")
(style "display:none"))
(span ((class "location-offset")) ,(number->string (Loc-offset a-loc)))
(span ((class "location-line")) ,(number->string (Loc-line a-loc)))
(span ((class "location-column")) ,(number->string (Loc-column a-loc)))
(span ((class "location-span")) ,(number->string (Loc-span a-loc)))
(span ((class "location-id")) ,(Loc-id a-loc))))
;; separate-with-br-elements: (listof dom) -> (listof dom)
;; Splice in br elements between each dom.
(define (separate-with-br-elements doms)
(cond
[(empty? doms)
empty]
[(empty? (rest doms))
(list (first doms))]
[else
(cons (first doms)
'(br ())
(separate-with-br-elements (rest doms)))]))
;; ordinal-ending: natural-number -> string
;; Produces the ordinal ending of a number. For example, 1 => st, 4 => th.
(define (ordinal-ending n)
(cond
[(= (modulo (quotient n 10) 10) 1)
"th"]
[else
(list-ref '("th" "st" "nd" "rd" "th"
"th" "th" "th" "th" "th")
(modulo n 10))]))
;; prepend-indefinite-article: dom -> (listof dom)
;; Produces a list containting the appropriate indefinite article and the dom.
(define (prepend-indefinite-article a-dom)
(list (indefinite-article (dom-string-content a-dom))
" "
a-dom))
;; indefinite-article: string -> string
;; Tries to get the indefinite article of a word.
(define (indefinite-article a-word)
(cond
[(begins-with-vowel-sound? a-word)
"an"]
[else
"a"]))
;; begins-with-vowel-sound?: string -> boolean
;; Tries to produces true if there's a vowel sound at the beginning of the
;; word.
;; This is not quite right because it doesn't use a dictionary.
(define (begins-with-vowel-sound? a-word)
(cond
[(= 0 (string-length a-word))
false]
[(vowel-character? (string-ref a-word 0))
true]
;; Check to see if it's a "y" vowel sound
[(and (> (string-length a-word) 2)
(char=? (string-ref a-word 0) #\y)
(not (vowel-character? (string-ref a-word 1))))
true]
[else
false]))
;; vowel-character?: char -> boolean
;; Produces true if the given character is a vowel character.
(define (vowel-character? a-char)
(member a-char '(#\a #\e #\i #\o #\u)))
;; stx-to-dom-sexp: stx -> dom
;; Converts a stx to a dom s-expression.
(define (stx->dom-sexp a-stx maybe-dom-parameters)
(scheme-value->dom-sexp (stx->datum a-stx) maybe-dom-parameters))
;; expected-value-to-dom-sexp: moby-expected -> dom
;; Translates an expectation to a dom.
(define (expected-value-to-dom-sexp expected)
(cond
[(moby-expected:string? expected)
`(span ((class "Expected-String"))
"string")]
[(moby-expected:integer? expected)
`(span ((class "Expected-Integer"))
"integer")]
[(moby-expected:natural? expected)
`(span ((class "Expected-Natural"))
"natural")]
[(moby-expected:rational? expected)
`(span ((class "Expected-Rational"))
"rational")]
[(moby-expected:real? expected)
`(span ((class "Expected-Real"))
"real")]
[(moby-expected:complex? expected)
`(span ((class "Expected-Complex"))
"complex")]
[(moby-expected:number? expected)
`(span ((class "Expected-Number"))
"number")]
[(moby-expected:boolean? expected)
`(span ((class "Expected-Boolean"))
"boolean")]
[(moby-expected:char? expected)
`(span ((class "Expected-Char"))
"char")]
[(moby-expected:symbol? expected)
`(span ((class "Expected-Symbol"))
"symbol")]
[(moby-expected:list? expected)
`(span ((class "Expected-List"))
"list")]
[(moby-expected:listof? expected)
`(span ((class "Expected-Listof"))
"list of "
(expected-value-to-dom-sexp (moby-expected:listof-thing expected))
"" )]
[(moby-expected:vector? expected)
`(span ((class "Expected-Vector"))
"vector")]
[(moby-expected:struct? expected)
`(span ((class "Expected-Struct"))
"struct")]
[(moby-expected:box? expected)
`(span ((class "Expected-Box"))
"box")]
[(moby-expected:hash? expected)
`(span ((class "Expected-Hash"))
"hash")]
[(moby-expected:function? expected)
`(span ((class "Expected-Function"))
"function")]
[(moby-expected:something? expected)
`(span ((class "Expected-Something"))
,(moby-expected:something-description expected))]))
;; Converts an arity to a dom sexpression.
(define (arity-to-dom-sexp an-arity)
(cond
[(arity:fixed? an-arity)
`(span ((class "Arity-Fixed"))
,(number->string (arity:fixed-n an-arity)))]
[(arity:variable? an-arity)
`(span ((class "Arity-Variable"))
(span ((class "Arity-Variable.minimum"))
,(number->string (arity:variable-min an-arity)))
(span ((class "Arity-Variable.maximum"))
,(number->string (arity:variable-max an-arity))))]
[(arity:mixed? an-arity)
`(span ((class "Arity-Mixed"))
,@(map (lambda (a)
`(span ((class "Arity-Mixed.item"))
,(arity-to-dom-sexp a)))))]))
(provide/contract
[error-struct->dom-sexp (any/c (or/c false/c dom-parameters?) . -> . any)]
[error-struct->jsexpr (any/c . -> . any)]
[loc->jsexpr (Loc? . -> . any)])
| false |
7bd3a600c63601221f94e93941b2748ae164be85
|
2c01a6143d8630044e3629f2ca8adf1455f25801
|
/xitomatl/tests/sxml-tools/vcontext.sps
|
fd335f15bd66f79eb734ac0af38cec1f3cbbee3b
|
[
"X11-distribute-modifications-variant"
] |
permissive
|
stuhlmueller/scheme-tools
|
e103fac13cfcb6d45e54e4f27e409adbc0125fe1
|
6e82e873d29b34b0de69b768c5a0317446867b3c
|
refs/heads/master
| 2021-01-25T10:06:33.054510 | 2017-05-09T19:44:12 | 2017-05-09T19:44:12 | 1,092,490 | 5 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 676 |
sps
|
vcontext.sps
|
#!r6rs
;; Copyright 2009 Derick Eddington. My MIT-style license is in the file named
;; LICENSE from the original collection this file is distributed with.
(import
(rnrs)
(xitomatl sxml-tools xpath-context--xlink)
(xitomatl include)
(xitomatl sxml-tools sxpathlib)
(xitomatl tests sxml-tools xtest-harness)
(xitomatl tests sxml-tools xtest-lib)
(xitomatl tests sxml-tools define-macro)
(xitomatl ssax private-5-1 output)
(rename (only (xitomatl common) pretty-print)
(pretty-print pp)))
(define (myenv:error . args)
(apply assertion-violation 'sxp:error "test failed" args))
(include/resolve ("xitomatl" "tests" "sxml-tools") "vcontext.scm")
| false |
37e7747ba4dfedd16eb32f46f1855b9c301f01cb
|
3b599e0f15d1b7ce3e42789b2e5c6d477b6a572b
|
/Lisp/dicp/atcsq01_shared.ss
|
8702eaed61ed4eaa883d86deccaeefe772738b9a
|
[] |
no_license
|
iacxc/MyProjects
|
1b2ccc80fca2c0935e1a91c98a7555b880745297
|
6998c87012273726bb290f5268ba1f8a9fd37381
|
refs/heads/master
| 2021-01-15T15:45:01.742263 | 2018-03-05T10:41:32 | 2018-03-05T10:41:32 | 25,804,036 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 5,734 |
ss
|
atcsq01_shared.ss
|
(load "cluster_conf.ss")
(define msa001 (make-msa 'msa001 '1.1-24 'ATCSQ01))
(define msa002 (make-msa 'msa002 '1.1-24 'ATCSQ01))
(define msa003 (make-msa 'msa003 '1.1-24 'ATCSQ01))
(define msa004 (make-msa 'msa004 '1.1-24 'ATCSQ01))
(define msa005 (make-msa 'msa005 '1.1-24 'ATCSQ01))
(define msa006 (make-msa 'msa006 '1.1-24 'ATCSQ01))
(define msa007 (make-msa 'msa007 '1.1-24 'ATCSQ01))
(define msa008 (make-msa 'msa008 '1.1-24 'ATCSQ01))
(define n001 (make-node 'n001 8 2 'ATCSQ01))
(define n002 (make-node 'n002 8 2 'ATCSQ01))
(define n003 (make-node 'n003 8 2 'ATCSQ01))
(define n004 (make-node 'n004 8 2 'ATCSQ01))
(define n005 (make-node 'n005 8 2 'ATCSQ01))
(define n006 (make-node 'n006 8 2 'ATCSQ01))
(define n007 (make-node 'n007 8 2 'ATCSQ01))
(define n008 (make-node 'n008 8 2 'ATCSQ01))
(define n009 (make-node 'n009 8 2 'FREE))
(define n010 (make-node 'n010 8 2 'FREE))
(define n011 (make-node 'n011 8 2 'FREE))
(define n012 (make-node 'n012 8 2 'FREE))
(define n013 (make-node 'n013 8 2 'FREE))
(define n014 (make-node 'n014 8 2 'FREE))
(define atcsq01
(let ( (squserN (make-user
'squserN ; user id
'seaquest ; group
'redhat06 ; password
"0750" ; permission
'/opt/hp/nv/instance/sqconfig_ATCSQ01_squserN ; sqconfig
(list n001 n002 n003 n004 n005 n006 n007 n008) ; sql-nodes
nil ; conn-nodes
(list n001 n002 n003 n004) ; tlog-nodes
(list n005 n006 n007 n008) ; system-nodes
))
(sqdev1 (make-user 'sqdev1 'seaquest 'redhat06 "0750"
'/opt/hp/nv/instance/sqconfig_ATCSQ01_sqdev1
(list n001 n002 n003 n004 n005 n006 n007 n008)
nil
(list n001)
(list n002)))
)
(make-cluster
'ATCSQ01 ; cluster-name
'16.235.162.51 ; cluster-ip
'shared ; cluster-type
'MSAShelves_300-300GB ; msa-typefile
'BLADE ; node-type
'/opt/hp/platform/config/xml/Profile.xml ; profile
"[email protected]" ; requestor
"" ; comments
;; list of cabinets
(list (make-cab 1
(list msa001 msa002 msa003 msa004
msa005 msa006 msa007 msa008)
(list n001 n002 n003 n004 n005 n006 n007
n008 n009 n010 n011 n012 n013 n014)))
;; list of instances
(list (make-instance
'ATCSQ01 ; instance-id
'/opt/hp/nv/instance/sqconfig_TRITON_squserN ; sqconfig
'NRAID ; storage-type
'development ; user-type
'ATCSQ01 ; bdr-name
32000 ; bdr-port
'yes ; disable-firewall
'no ; float-ip-flag
(list n001 n002 n003 n004 n005 n006 n007 n008) ; sql-nodes
nil ; conn-nodes
nil ; spare-nodes
2 ; no-of-ase
8 ; no-of-tse
nil ; tlog-nodes
nil ; system-nodes
(list msa001 msa002 msa003 msa004 ; msa-list
msa005 msa006 msa007 msa008)
(list squserN sqdev1) ; user-list
"[email protected]" ; requestor
"no" ; comments
)))))
(display "\nBuilding cluster with sqdev1\n")
(build-obj atcsq01)
(show-obj atcsq01)
(let ( (sqdev2 (make-user 'sqdev2 'seaquest 'redhat06 "0750"
'/opt/hp/nv/instance/sqconfig_ATCSQ01_sqdev1
(list n001 n002 n003 n004)
nil
(list n001)
(list n002)))
(sqdev3 (make-user 'sqdev3 'seaquest 'redhat06 "0750"
'/opt/hp/nv/instance/sqconfig_ATCSQ01_sqdev1
(list n005 n006 n007 n008)
nil
(list n005)
(list n006)))
(sqdev4 (make-user 'sqdev4 'seaquest 'redhat06 "0750"
'/opt/hp/nv/instance/sqconfig_ATCSQ01_sqdev4
(list n003 n004 n005 n006)
nil
(list n003)
(list n004))) )
(display "\nAdding sqdev2, sqdev3 and sqdev4\n")
((atcsq01 'add-user) sqdev2)
((atcsq01 'add-user) sqdev3)
((atcsq01 'add-user) sqdev4)
(show-obj atcsq01)
)
(display "\nDelete sqdev2 and sqdev3\n")
((atcsq01 'del-user) 'sqdev2)
((atcsq01 'del-user) 'sqdev3)
(show-obj atcsq01)
;(exit)
| false |
1943e6024666032dd7ffee60d96768b6210f30b3
|
6f86602ac19983fcdfcb2710de6e95b60bfb0e02
|
/input/exercises/rotational-cipher/test.ss
|
a2fb57bf271f6d81d7f6ec261af369baad671c21
|
[
"MIT",
"CC-BY-SA-3.0"
] |
permissive
|
exercism/scheme
|
a28bf9451b8c070d309be9be76f832110f2969a7
|
d22a0f187cd3719d071240b1d5a5471e739fed81
|
refs/heads/main
| 2023-07-20T13:35:56.639056 | 2023-07-18T08:38:59 | 2023-07-18T08:38:59 | 30,056,632 | 34 | 37 |
MIT
| 2023-09-04T21:08:27 | 2015-01-30T04:46:03 |
Scheme
|
UTF-8
|
Scheme
| false | false | 700 |
ss
|
test.ss
|
(define (parse-test test)
`(test-success ,(lookup 'description test)
equal?
rotate
'(,(lookup-spine '(input text) test)
,(lookup-spine '(input shiftKey) test))
,(lookup 'expected test)))
(define (spec->tests spec)
(map parse-test
(lookup 'cases (car (lookup 'cases spec)))))
(let ((spec (get-test-specification 'rotational-cipher)))
(put-problem!
'rotational-cipher
`((test . ,(spec->tests spec))
(stubs rotate)
(version . ,(lookup 'version spec))
(skeleton . "rotational-cipher.scm")
(solution . "example.scm")
(markdown . ,(splice-exercism 'rotational-cipher)))))
| false |
d21f204207ef9ce31b25d1603335bdd3d94fb1b6
|
174072a16ff2cb2cd60a91153376eec6fe98e9d2
|
/Chap-Three/3-72.scm
|
8e9aa66fcff2f792cb737d7c8fc6c22b14cf2921
|
[] |
no_license
|
Wang-Yann/sicp
|
0026d506ec192ac240c94a871e28ace7570b5196
|
245e48fc3ac7bfc00e586f4e928dd0d0c6c982ed
|
refs/heads/master
| 2021-01-01T03:50:36.708313 | 2016-10-11T10:46:37 | 2016-10-11T10:46:37 | 57,060,897 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,152 |
scm
|
3-72.scm
|
(load "3-71.scm")
(define (Ramanujan3 s)
(define (stream-cadr s) (stream-car (stream-cdr s)))
(define (stream-cddr s) (stream-cdr (stream-cdr s)))
(define (stream-cdddr s) (stream-cdr (stream-cdr (stream-cdr s))))
(let ((scar (stream-car s)) (scadr (stream-cadr s))(scaddr (stream-car(stream-cddr s ))) )
(if (= (weight3 scar) (weight3 scadr) (weight3 scaddr))
;;;;此处使用=的扩张形式,(= a b c) ,不过效率并没有提高
(cons-stream (list (weight3 scar) scar scadr scaddr ) (Ramanujan3 (stream-cdddr s)))
(Ramanujan3 (stream-cdr s)))))
; (define Ramanujan3-numbers
; (Ramanujan3 (weighted-pairs integers integers weight3)))
;;;此上Ramanujan3-numbers 流生成第一组数较慢,导入时解释器会一直等待
;(display-stream (stream-section Ramanujan3-numbers 0 10))
;;;(87539319 (167 436) (228 423) (255 414))
;;(119824488 (11 493) (90 492) (346 428))
;;(143604279 (111 522) (359 460) (408 423))
;;(175959000 (70 560) (198 552) (315 525))
;;(327763000 (300 670) (339 661) (510 580))
;;没有看清问题,此是立方数版本,可以运行,速度较慢,以上为几组结果,用时10分钟
(define sum-square (lambda(x) (+ (square (car x)) (square (cadr x)) )))
(define (square3 s)
(define (stream-cadr s) (stream-car (stream-cdr s)))
(define (stream-cddr s) (stream-cdr (stream-cdr s)))
(define (stream-cdddr s) (stream-cdr (stream-cdr (stream-cdr s))))
(let ((scar (stream-car s)) (scadr (stream-cadr s))(scaddr (stream-car(stream-cddr s ))) )
(if (and (= (sum-square scar) (sum-square scadr))
(= (sum-square scar) (sum-square scaddr)))
(cons-stream (list (sum-square scar) scar scadr scaddr ) (square3 (stream-cdddr s)))
(square3 (stream-cdr s)))))
(define square3-numbers
(square3 (weighted-pairs integers integers sum-square)))
;(display-stream (stream-section square3-numbers 0 10))
;;;平方形式比立方形式运行快的多,是结果本身的分布导致
| false |
126c3a235a81db687b5f6b6ee85dd17e80843d97
|
2bcf33718a53f5a938fd82bd0d484a423ff308d3
|
/programming/sicp/ch2/ex-2.35.scm
|
f1bcfbd398892325264e960f7b3c0b928535c759
|
[] |
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,788 |
scm
|
ex-2.35.scm
|
#lang scheme
;; https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-15.html#%_thm_2.35
(require "accumulate.scm")
;; Original count-leaves:
(define (count-leaves t)
(cond ((null? t) 0)
((not (pair? t)) 1)
(else (+ (count-leaves (car t))
(count-leaves (cdr t))))))
;; Implementation using accumulate.
;; This is tricky: the accumlation is just summing the count of leaves from each
;; sub-tree. Trees are represented by nested lists, so if an elemnt is a pair,
;; it's a sub-tree and we recurse, if it is not, it is a leaf.
(define (count-leaves t)
(accumulate + 0 (map (lambda (t)
(if (pair? t)
(count-leaves t)
1))
t)))
;; Remember the way to "read" these as trees is (pairs as internal nodes),
;; primitives as leaves:
;; ((1 2) 3 4)
;; ┌──────●──────┐
;; │ │ │
;; │ │ │
;; (1 2) │ │ │
;; ┌─●─┐ │ │
;; │ │ 3 4
;; │ │
;; 1 2
(define t1
(cons (list 1 2) (list 3 4))) ; (cons a (list b c)) is (list a b c)
(count-leaves t1)
;; => 4
;; (1 (2 (3 4)))
;; ┌──────●─────┐
;; │ │
;; │ │
;; │ │(2 (3 4))
;; │ ┌───●───┐
;; 1 │ │(3 4)
;; │ ┌─●─┐
;; 2 │ │
;; │ │
;; 3 4
(define t2
(list 1 (list 2 (list 3 4))))
(count-leaves t2)
;; => 4
| false |
70f9f1a700951f7e49ae308b915892a7e1bc5b07
|
c63772c43d0cda82479d8feec60123ee673cc070
|
/ch2/17.scm
|
509cf060e9f2aa421fdd22b92a2cbc37173254c9
|
[
"Apache-2.0"
] |
permissive
|
liuyang1/sicp-ans
|
26150c9a9a9c2aaf23be00ced91add50b84c72ba
|
c3072fc65baa725d252201b603259efbccce990d
|
refs/heads/master
| 2021-01-21T05:02:54.508419 | 2017-09-04T02:48:46 | 2017-09-04T02:48:52 | 14,819,541 | 2 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 364 |
scm
|
17.scm
|
#lang racket
(define (last-pair lst)
(define (last-pair-ip lst)
(let ((newlst (cdr lst)))
(if (null? newlst)
lst
(last-pair-ip newlst))))
(if (null? lst)
'()
(last-pair-ip lst)))
(last-pair '())
(last-pair (list 0))
(last-pair (list 1 0))
(last-pair (list 2 1 0))
(last-pair (list 23 72 149 34))
(last-pair (list 1 (cons 2 3)))
| false |
e6947cc49f4a107ffc9acc873db812e133d0cdea
|
132c419c27fc5c89759c963ab9749a9e5a7af126
|
/lib/olisp_compiler/linux_x86/asm.scm
|
747eb87d20497182d9d8810433d1581f2ae33792
|
[] |
no_license
|
niyarin/Onigilisp
|
b767b65d7ae16ec4ef25d5dd843fd56ed122c887
|
ee737bcc1df396a80a972ec4346fda2a11e68331
|
refs/heads/master
| 2020-04-12T10:25:18.548218 | 2019-07-22T23:54:34 | 2019-07-22T23:54:34 | 162,429,140 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 27,541 |
scm
|
asm.scm
|
;頭にPUSH EBX;末尾にPOP EBXいれたけど、もっと局所的にやったほうがよいかな..
;仕様っぽもの
; <MEM> レジスタ ローカル スタック 引数
;
; syntax list
;
; OLISP-COMPILER-MV <MEM>/<CONST-EXPRESSION> <MEM>
;
(define-library (olisp-compiler linux-86 asm)
(import (scheme base)
(scheme cxr)
(scheme write)
(srfi 143))
(export olisp-compiler-linux-x86-asm)
(begin
(define *PTR-SIZE 4)
(define *STACK-HEAD 3)
(define *LOCAL-STACK-POSITION 2)
(define *TMP-REGISTER 3)
(define (%mem-compare? a b)
(cond
((eqv? a b) #t)
((not (and (pair? a) (pair? b))) #f)
((not (eqv? (car a) (cdr b))) #f)
(else (%mem-compare? (cdr a) (cdr b)))))
;quasi-quoteがまだないよ
(define (%create-allocate-code size target)
(list
'(OLISP-COMPILER-SET-CURRENT-POSITION-MEMORY 1)
'(OLISP-COMPILER-MV (MEMCHANK-REF 0) (REGISTER 0))
'(OLISP-COMPILER-MV (REGISTER-REF 0 0) (REGISTER 0))
'(OLISP-COMPILER-MV (REGISTER 0) (REGISTER 1))
(list 'OLISP-COMPILER-ADD size '(REGISTER 1))
(list 'OLISP-COMPILER-MV '(MEMCHANK-REF 1) (list 'REGISTER *TMP-REGISTER))
(list 'OLISP-COMPILER-MV (list 'REGISTER-REF *TMP-REGISTER 0) (list 'REGISTER *TMP-REGISTER))
(list 'OLISP-COMPILER-CMPL (list 'REGISTER *TMP-REGISTER) '(REGISTER 1))
'(OLISP-COMPILER-JA 5 <=)
'(OLISP-COMPILER-MV (ARG -1) (REGISTER 0))
(list 'OLISP-COMPILER-REF-CURRENT-MEMORY 1 (list 'REGISTER-REF 0 (fx* 2 *PTR-SIZE)))
'(OLISP-COMPILER-MV (ARG -1) (REGISTER 0))
(list 'OLISP-COMPILER-MV '(CONST 1) (list 'REGISTER-REF 0 (fx* 3 *PTR-SIZE)))
'(OLISP-COMPILER-RET)
;END
(list 'OLISP-COMPILER-MV '(MEMCHANK-REF 0) (list 'REGISTER *TMP-REGISTER))
(list 'OLISP-COMPILER-MV '(REGISTER 1) (list 'REGISTER-REF *TMP-REGISTER 0))
(list 'OLISP-COMPILER-MV '(MEMCHANK-REF 0) (list 'REGISTER *TMP-REGISTER))
(list 'OLISP-COMPILER-LSHIFT '(REGISTER 0) '(CONST 2))
(list 'OLISP-COMPILER-ADD '(REGISTER 0) (list 'REGISTER *TMP-REGISTER))
(list 'OLISP-COMPILER-MV '(REGISTER 0) target)
))
(define (%create-write-write-info target1 target2 target3 target4)
(list
(list 'OLISP-COMPILER-PUSH target1)
(list 'OLISP-COMPILER-PUSH target2)
(list 'OLISP-COMPILER-PUSH target3)
(list 'OLISP-COMPILER-PUSH target4)
'(OLISP-COMPILER-ALLOCATE 2 (REGISTER 1))
'(OLISP-COMPILER-MV (ARG -1) (REGISTER 0))
(list 'OLISP-COMPILER-ADD (fx* *PTR-SIZE 4) '(REGISTER 0))
'(OLISP-COMPILER-MV (REGISTER-REF 0 0) (REGISTER 0))
'(OLISP-COMPILER-PTR-PRIMITIVE-SET (REGISTER 1) (CONST 1) (REGISTER 0))
'(OLISP-COMPILER-PUSH (REGISTER 1))
'(OLISP-COMPILER-ALLOCATE 4 (REGISTER 0))
'(OLISP-COMPILER-POP (REGISTER 1))
'(OLISP-COMPILER-PTR-PRIMITIVE-SET (REGISTER 1) (CONST 0) (REGISTER 0))
'(OLISP-COMPILER-MV (REGISTER 0) (REGISTER 1))
'(OLISP-COMPILER-POP (REGISTER 0))
'(OLISP-COMPILER-PTR-PRIMITIVE-SET (REGISTER 1) (CONST 3) (REGISTER 0))
'(OLISP-COMPILER-POP (REGISTER 0))
'(OLISP-COMPILER-PTR-PRIMITIVE-SET (REGISTER 1) (CONST 2) (REGISTER 0))
'(OLISP-COMPILER-POP (REGISTER 0))
'(OLISP-COMPILER-PTR-PRIMITIVE-SET (REGISTER 1) (CONST 1) (REGISTER 0))
'(OLISP-COMPILER-POP (REGISTER 0))
'(OLISP-COMPILER-PTR-PRIMITIVE-SET (REGISTER 1) (CONST 0) (REGISTER 0))
));END
(define (convert-ref position)
(cond
((eq? (car position) 'REGISTER)
(list 'REGISTER-REF (cadr position) 0))
((eq? (car position) 'LOCAL)
(list 'LOCAL-REF (cadr position)))
(else (error "ERROR"))
))
(define (%encode-jmp-opecode asm-code)
(cond
((eq? (caddr asm-code) '<=)
119)
(else (display asm-code)(newline)(error "TBA"))))
(define (%encode-little-endiun num len)
(let loop ((num num)
(cnt len))
(if (fx=? cnt 0)
'()
(cons
(fxand 255 num)
(loop
(fxarithmetic-shift-right cnt 3)
(fx- cnt 1))))))
(define (%encode-operand o1 o2)
(cond
((and (not (pair? o1))
(eq? (car o2) 'REGISTER))
(list
(fx+
192;0b11000000
(cadr o2))
o1
))
((and
(eq? (car o1) 'CONST)
(eq? (car o2) 'REGISTER-REF))
(if (fx=? (caddr o2) 0)
(cons
(cadr o2)
(%encode-little-endiun (cadr o1) 4))
(cons
(fx+ 64 (cadr o2))
(cons;TODO:(caddr o2)が大きいケース
(caddr o2)
(%encode-little-endiun (cadr o1) 4))
)))
((and
(eq? (car o1) 'CONST)
(eq? (car o2) 'REGISTER))
(%encode-little-endiun (cadr o1) 4))
((and (eq? (car o1) 'REGISTER)
(eq? (car o2) 'REGISTER))
(list
(fx+
192;0b11000000
(fx+
(fxarithmetic-shift-left (cadr o2) 3)
(cadr o1)))))
((and (eq? (car o1) 'ARG)
(eq? (car o2) 'REGISTER))
(list
(fx+
64;0b01000000
(fx+
(fxarithmetic-shift-left (cadr o2) 3)
5
))
(fx* (fx+ (cadr o1) *STACK-HEAD) *PTR-SIZE)))
((and
(eq? (car o1) 'REGISTER-REF)
(eq? (car o2) 'REGISTER)
(fx<? (cadr (cdr o1)) 128))
(list
(fx+
64;0b01000000
(fx+
(fxarithmetic-shift-left (cadr o2) 3)
(cadr o1)
))
(cadr (cdr o1))))
((and
(eq? (car o1) 'REGISTER)
(eq? (car o2) 'REGISTER-REF)
(fx=? (caddr o2) 0))
(list
(fx+
(fxarithmetic-shift-left (cadr o1) 3)
(cadr o2)
)))
(else (error "TBA?" (list o1 o2)))
))
(define (%calc-offset-size reg-ref)
(caddr reg-ref))
(define (%encode-opecode-mov code)
(cond
((and (eq? (car (cadr code)) 'REGISTER);REGISTER以外にもいけるだろう
(%mem-compare? (cadr code) (caddr code)))
'())
((or
(and (eq? (car (cadr code)) 'REGISTER)
(eq? (car (caddr code)) 'REGISTER))
(and (eq? (car (cadr code)) 'ARG)
(eq? (car (caddr code)) 'REGISTER))
(and (eq? (car (cadr code)) 'REGISTER-REF)
(eq? (car (caddr code)) 'REGISTER)))
139)
((or
(and (eq? (car (cadr code)) 'REGISTER)
(eq? (car (caddr code)) 'REGISTER-REF)))
137)
((eq? (car (cadr code)) 'LOCAL-REF)
;8b 45 08 mov 0x8(%ebp),%eax
(list
(list
'OLISP-COMPILER-MV
(list 'ARG -1)
(caddr code))
(list
'OLISP-COMPILER-MV
(list 'REGISTER-REF (cadr (caddr code)) 0)
(caddr code))
(list
'OLISP-COMPILER-ADD
(fx*
(cadr (cadr code))
*PTR-SIZE)
(caddr code))
))
((and
(eq? (car (cadr code)) 'CONST)
(eq? (car (caddr code)) 'REGISTER-REF))
199)
((and
(eq? (car (cadr code)) 'CONST)
(eq? (car (caddr code)) 'REGISTER))
(fx+
(cadr (caddr code))
184))
((eq? (caadr code) 'LOCAL)
(list
(list
'OLISP-COMPILER-MV
(list 'LOCAL-REF (cadr (cadr code)))
(caddr code))
(list
'OLISP-COMPILER-MV
(convert-ref (caddr code))
(caddr code))))
((eq? (car (caddr code)) 'LOCAL)
(list
(list
'OLISP-COMPILER-MV
(list 'LOCAL-REF (cadr (caddr code)))
(list 'REGISTER *TMP-REGISTER))
(list 'OLISP-COMPILER-MV (cadr code) (list 'REGISTER-REF *TMP-REGISTER 0))))
((eq? (car (cadr code)) 'MEMCHANK-REF)
(list;↑ あとでまとめる
(list
'OLISP-COMPILER-MV
(list 'ARG -1)
(caddr code))
(list
'OLISP-COMPILER-MV
(list
'REGISTER-REF
(cadr (caddr code))
*PTR-SIZE)
(caddr code));PTR[1] => eax
(list
'OLISP-COMPILER-ADD
(fx*
(cadr (cadr code))
*PTR-SIZE)
(caddr code))
))
(else (error "TBA enc %mv opecode " code))
))
(define (olisp-compiler-linux-x86-asm code)
(letrec ((res (make-bytevector 512))
(jmp-addrs (make-vector 128))
(index 0)
(insert-jmp #t)
(%mv-encode
(lambda (mv-code)
;TODO:EBX (REGISTER 3) への書き込みはSTACKつかう
(let ((mov-code
(%encode-opecode-mov mv-code)))
(cond
((null? mov-code)
#t)
((pair? mov-code)
(begin
(for-each
%encode
mov-code
)))
(else
(bytevector-u8-set!
res
index
mov-code
)
(set! index (fx+ index 1))
(let ((encoded-operands
(%encode-operand
(cadr mv-code)
(cadr (cdr mv-code)))))
(let internal-loop ((encoded-operands encoded-operands))
(unless (null? encoded-operands)
(bytevector-u8-set!
res
index
(car encoded-operands))
(set! index (fx+ index 1))
(internal-loop (cdr encoded-operands))))))
))))
(%shift-encode
(lambda (register reg)
(begin ;SHR 2 REG;
(bytevector-u8-set!
res
index
193)
(bytevector-u8-set!
res
(fx+ index 1)
(fx+
register
224
))
(bytevector-u8-set!
res
(fx+ index 2)
reg)
(set!
index
(+ index 3)))))
(%shift2-encode
(lambda (register)
(%shift-encode register 2)
))
(%add-encode
(lambda (asm-code)
(begin
(cond
((not (pair? (cadr asm-code)))
(begin
(bytevector-u8-set!
res
index
131)
(set! index (fx+ index 1))))
(else
(begin
(bytevector-u8-set!
res
index
1
)
(set! index (fx+ index 1))
)
))
(let ((operands
(%encode-operand (cadr asm-code) (caddr asm-code))))
(if (pair? operands)
(for-each
(lambda (operand)
(bytevector-u8-set!
res
index
operand)
(set! index (fx+ index 1)))
operands)
(begin
(bytevector-u8-set!
res
index
operands)
(set! index (fx+ index 1)))
)))))
(%cmpl-encode
(lambda (asm-code)
(begin
(cond
((and;TODO:このcond節 未検証
(not (pair? (caddr asm-code)))
(fx<? (caddr asm-code) 256)
(pair? (cadr asm-code))
(eq? (car (cadr asm-code)) 'REGISTER))
(begin
(bytevector-u8-set!
res
index
131)
(bytevector-u8-set!
res
(fx+ index 1)
(fx+
248
(cadr (cadr asm-code))))
(bytevector-u8-set!
res
(fx+ index 2)
(caddr asm-code))
(set! index (fx+ index 2))))
((and
(pair? (caddr asm-code))
(pair? (cadr asm-code))
(eq? (car (caddr asm-code)) 'REGISTER)
(eq? (car (cadr asm-code)) 'REGISTER))
(bytevector-u8-set!
res
index
57)
(set! index (fx+ index 1))
(for-each
(lambda (a)
(begin
(bytevector-u8-set!
res
index
a)
(set! index (fx+ index 1))))
(%encode-operand (cadr asm-code) (caddr asm-code))))
(else (error "ERROR"))))))
(%encode
(lambda (asm-code)
(cond
((eq? (car asm-code) 'OLISP-COMPILER-MV)
(%mv-encode asm-code))
((eq? (car asm-code) 'OLISP-COMPILER-ADD)
(%add-encode asm-code))
((eq? (car asm-code) 'OLISP-COMPILER-CMPL)
(%cmpl-encode asm-code))
((eq? (car asm-code) 'OLISP-COMPILER-PUSH)
(cond
((eq? (caadr asm-code) 'REGISTER)
(begin
(bytevector-u8-set!
res
index
(fx+
80
(cadr (cadr asm-code))))
(set! index (fx+ index 1))))
((eq? (caadr asm-code) 'CONST)
(begin
(bytevector-u8-set!
res
index
104)
(set! index (fx+ index 1));
(for-each
(lambda (x)
(begin
(bytevector-u8-set!
res
index
x)
(set! index (fx+ index 1))))
(%encode-little-endiun (cadadr asm-code) 4))
))
(else (error "TBA!" asm-code))))
((eq? (car asm-code) 'OLISP-COMPILER-POP)
(if (eq? (caadr asm-code) 'REGISTER)
(begin
(bytevector-u8-set!
res
index
(fx+
88
(cadr (cadr asm-code))))
(set! index (fx+ index 1)))
(error "TBA!")))
((eq? (car asm-code) 'OLISP-COMPILER-SET-CURRENT-POSITION-MEMORY)
(vector-set!
jmp-addrs
(cadr asm-code)
(list 'CONST index))
)
((eq? (car asm-code) 'OLISP-COMPILER-PTR-PRIMITIVE-SET )
(if (eq? (car (caddr asm-code)) 'CONST)
;無駄が多い あとで修正
(for-each
%encode
(list
(list 'OLISP-COMPILER-MV (cadr asm-code) (list 'REGISTER *TMP-REGISTER))
(list
'OLISP-COMPILER-ADD
(fx* (cadr (caddr asm-code)) *PTR-SIZE)
(list 'REGISTER *TMP-REGISTER))
(list
'OLISP-COMPILER-MV
(cadddr asm-code)
(list 'REGISTER-REF *TMP-REGISTER 0))
))
(error "TBA"))
)
((eq? (car asm-code) 'OLISP-COMPILER-REF-CURRENT-MEMORY )
(list
'OLISP-COMPILER-MV
(vector-ref jmp-addrs (cadr asm-code))
(caddr asm-code)))
((eq? (car asm-code) 'OLISP-COMPILER-PUSH-ONLY-REGISTER )
(when (eq? (caadr asm-code) 'REGISTER)
(%encode
(cons 'OLISP-COMPILER-PUSH
(cdr asm-code)))))
((eq? (car asm-code) 'OLISP-COMPILER-POP-ONLY-REGISTER )
(when (eq? (caadr asm-code) 'REGISTER)
(%encode
(cons 'OLISP-COMPILER-POP
(cdr asm-code)))))
((eq? (car asm-code) 'OLISP-COMPILER-LSHIFT)
(cond
((and (eq? (caadr asm-code) 'REGISTER)
(eq? (caaddr asm-code) 'CONST))
(%shift-encode (cadadr asm-code) (cadr (caddr asm-code))))
(else (error "ERROR"))))
((eq? (car asm-code) 'OLISP-COMPILER-RSHIFT)
(cond
((and (eq? (caadr asm-code) 'REGISTER)
(eq? (caaddr asm-code) 'CONST))
(%shift-encode (fx+ (cadadr asm-code) 8) (cadr (caddr asm-code))))
(else (error "ERROR"))))
((eq? (car asm-code) 'OLISP-COMPILER-RET)
(bytevector-u8-set! res index 91)
(bytevector-u8-set! res (fx+ index 1)93)
(bytevector-u8-set! res (fx+ index 2) 195)
(set! index (fx+ index 3)))
((eq? (car asm-code) 'OLISP-COMPILER-REMOVE-TYPE)
(%shift2-encode
(fx+
(cadr (cadr asm-code))
8))
(%shift2-encode
(cadr (cadr asm-code))))
((and (eq? (car asm-code) 'OLISP-COMPILER-PTR-REF)
(eq? (car (cadddr asm-code)) 'REGISTER)
(not (pair? (caddr asm-code))))
(cond
((eq? (caadr asm-code) 'REGISTER)
(%shift2-encode
(fx+
(cadr (cadr asm-code))
8))
(%shift2-encode
(cadr (cadr asm-code)))
(%mv-encode
(list
'OLISP-COMPILER-MV
(list
'REGISTER-REF
(cadadr asm-code)
(fx*
(caddr asm-code)
*PTR-SIZE))
(cadr (cddr asm-code)))))
((eq? (caadr asm-code) 'ARG)
(%mv-encode
(list
'OLISP-COMPILER-MV
(cadr asm-code)
(cadddr asm-code)))
(%shift2-encode
(fx+
(cadr (cadddr asm-code))
8))
(%shift2-encode
(cadr (cadddr asm-code)))
(%mv-encode
(list
'OLISP-COMPILER-MV
(list
'REGISTER-REF
(cadadr asm-code)
(fx*
(caddr asm-code)
*PTR-SIZE))
(cadddr asm-code))))
(else (error "TBA"))))
(else
(write asm-code)(newline)
(write "<===\n")
(error "TBA!!!!?"))
);end cond
)
);%end encode
)
(begin ;PUSH EBP;MOV ESP EBP
(bytevector-u8-set! res 0 85)
(bytevector-u8-set! res 1 137)
(bytevector-u8-set! res 2 229)
(set! index 3))
(begin;PUSH EBX
(bytevector-u8-set!
res
3
83)
(set! index 4))
(when insert-jmp
(bytevector-u8-set! res 4 235)
(bytevector-u8-set! res 5 0)
(set! index 6))
(let loop ((code code))
(unless (null? code)
(cond
((eqv? (caar code) 'OLISP-COMPILER-JA)
(begin
(bytevector-u8-set!
res
index
(%encode-jmp-opecode (car code)))
(bytevector-u8-set!
res
(fx+ index 1)
0)
(let ((jmp-address-index (fx+ index 1))
(loop-size (cadr (car code))));re18
(set! index (fx+ index 2))
(let loop-internal ((code (cdr code))
(cnt 0))
(if (fx=? cnt loop-size)
(begin
(bytevector-u8-set!
res
jmp-address-index
(fx- (fx- index 1) jmp-address-index))
(loop code))
(begin
(%encode (car code))
(loop-internal (cdr code) (fx+ cnt 1))))))))
((eq? (caar code) 'OLISP-COMPILER-ALLOCATE)
(loop
(append
(%create-allocate-code (cadar code) (caddar code))
(cdr code))))
((eq? (caar code) 'OLISP-COMPILER-WRITE-BARRIER)
(loop
(append
(%create-write-write-info
(cadr (car code))
(caddr (car code))
(cadddr (car code))
(cadr (cdddar code))
)
(cdr code))))
(else
(%encode (car code))
(loop
(cdr code))))))
(begin ;POP EBX
(bytevector-u8-set! res index 91)
(set! index (fx+ index 1))
)
(begin;POP EBP;RET;
(bytevector-u8-set! res index 93)
(bytevector-u8-set! res (fx+ index 1) 195)
)
res
))))
(import (scheme base)
(scheme write)
(olisp-compiler linux-86 asm))
(display "ALLOCATE")(newline)
'(display
(olisp-compiler-linux-x86-asm
'(
(OLISP-COMPILER-ALLOCATE 2 (REGISTER 0))
(OLISP-COMPILER-PTR-PRIMITIVE-SET (REGISTER 0) (CONST 0) (CONST 32))
(OLISP-COMPILER-PTR-PRIMITIVE-SET (REGISTER 1) (CONST 0) (CONST 0))
(OLISP-COMPILER-ADD 1 (REGISTER 0))
)))
(display
(olisp-compiler-linux-x86-asm
`(
(OLISP-COMPILER-ALLOCATE 3 (REGISTER 0))
(OLISP-COMPILER-WRITE-BARRIER (REGISTER 0) (CONST 1) (CONST 2) (CONST 3))
(OLISP-COMPILER-ALLOCATE 2 (REGISTER 0))
(OLISP-COMPILER-PTR-PRIMITIVE-SET (REGISTER 0) (CONST 0) (CONST 32))
(OLISP-COMPILER-ADD 1 (REGISTER 0))
)
))
| false |
ea90b5f46005fcf75a9b3f2f8d07783544d0444a
|
13b5f31e63477c3db8d3a77ae8c814b16534f684
|
/Akku.manifest
|
aadc0c221302c72440a25acc9fdcf80ea60a206a
|
[
"MIT"
] |
permissive
|
hinkelman/dataframe
|
946163db48e426bbdb504f6ef2b307f640584937
|
06b370fd1877f1d9ab44dd62166304ebfa799fac
|
refs/heads/master
| 2023-09-01T00:03:24.511922 | 2023-07-10T04:31:18 | 2023-07-10T04:31:18 | 249,494,173 | 16 | 4 |
NOASSERTION
| 2021-04-24T05:34:18 | 2020-03-23T17:09:28 |
Scheme
|
UTF-8
|
Scheme
| false | false | 435 |
manifest
|
Akku.manifest
|
#!r6rs ; -*- mode: scheme; coding: utf-8 -*-
(import (akku format manifest))
(akku-package ("dataframe" "0.6.0")
(synopsis
"A dataframe record type for Scheme (R6RS) with procedures to select, drop, and rename columns, and filter, sort, split, bind, append, join, reshape, and aggregate dataframes.")
(authors "Travis Hinkelman")
(license "MIT")
(depends ((slib format) "^3.1.5") ("chez-srfi" "^0.0.0-akku.209.552cd37"))
)
| false |
0b1e511315b3036d40071e3a064b5a7c762d9d45
|
140a499a12332fa8b77fb738463ef58de56f6cb9
|
/worlds/core/verbcode/8/@program-4.scm
|
0f454251eb894aed8ed9ac8fd2646b5b72d55568
|
[
"MIT"
] |
permissive
|
sid-code/nmoo
|
2a5546621ee8c247d4f2610f9aa04d115aa41c5b
|
cf504f28ab473fd70f2c60cda4d109c33b600727
|
refs/heads/master
| 2023-08-19T09:16:37.488546 | 2023-08-15T16:57:39 | 2023-08-15T16:57:39 | 31,146,820 | 10 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 567 |
scm
|
@program-4.scm
|
(if (= 0 (len argstr))
(player:tell "Syntax: @program obj:verb")
;; The second argument (0) means we only want verbs defined
;; on the object, not on its ancestors
(let ((verb-loc ($verbutils:parse-verbstr argstr 0)))
(cond
((istype verb-loc "str") (player:tell verb-loc))
((istype verb-loc "list")
(let ((code (caller:read-till-dot)))
(do (setverbcode (get verb-loc 0) (get verb-loc 1) code)
(player:tell "Verb edited successfully!"))))
((player:tell "Something has gone terribly wrong.")))))
| false |
8b4baa817da24015978f6689fe76d017628d201b
|
f17ecf48249d4fba76d276ba35248a70b7fa347e
|
/schemep3-panel-database-filter.scm
|
05c554146452668218373e6ffa6eefd81ff60fbf
|
[] |
no_license
|
liulanghaitun/schemep3
|
8f7832d32cc4cf73936ba7a5d6afaa6278b37bb7
|
513a3f2bbe164f510d1d4c6edd02eaadab75ff0c
|
refs/heads/master
| 2023-03-16T10:01:43.121901 | 2019-08-27T00:36:09 | 2019-08-27T00:36:09 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 3,430 |
scm
|
schemep3-panel-database-filter.scm
|
#lang scheme/gui
(provide filter-panel%)
(require framework/gui-utils)
(require srfi/2)
(require srfi/26)
(require "schemep3-playlist.scm")
(require "schemep3-database.scm")
(require "schemep3-status.scm")
(require "schemep3-main-menu.scm")
(require "schemep3-mixins-gui.scm")
(require "schemep3-helpers.scm")
(define filter-panel%
(class (checkable-panel-mixin group-box-panel% "Database Filter")
(define field-labels (list "Artist" "Album" "Title"))
(define field-text-boxes #f)
(define choice-rating #f)
(define choice-sort #f)
(define check-reverse-sort #f)
(define/public (get-selected-rating)
(let ((r (send choice-rating get-selection)))
(cond [(= r 0) #f]
[else (- 6 r)])))
(define (get-query-string)
(let ((clauses
(filter-map
(lambda (label-string text-field)
(let ((text (send text-field get-value)))
(and (>= (string-length text) 2)
(format "~A LIKE \"%~A%\"" label-string text))))
field-labels
field-text-boxes)))
(and-let* ((r (get-selected-rating)))
(push! clauses (format "RATING>=~A" r)))
(and
(not (empty? clauses))
(format "~A ORDER BY lower(~A) ~A"
(string-join clauses " AND ")
(send choice-sort get-string-selection)
(if (send check-reverse-sort get-value) "DESC" "ASC")))))
(define apply-query
(let ([cancel-fn #f])
(lambda x
(and-let* ((where-clause (get-query-string)))
(when cancel-fn
(cancel-fn))
(set! cancel-fn
(gui-utils:delay-action
1
(lambda ()
(queue-callback (cut playlist-set-from-database where-clause)))
(lambda ()
(set! cancel-fn #f))))))))
(super-new
(label "Database Filter")
(alignment '(left top))
(stretchable-height #f))
(let ((h-panel
(new horizontal-panel%
(parent this))))
(set! field-text-boxes
(for/list ((label-string field-labels))
(new text-field%
(parent h-panel)
(callback apply-query)
(label
(format "~A: " label-string)))))
(set!
choice-rating
(new choice%
(parent h-panel)
(label "Rating >= ")
(callback apply-query)
(choices
'("Any" "5" "4" "3" "2" "1"))))
(set! choice-sort
(new choice%
(parent h-panel)
(label "Sort: ")
(callback apply-query)
(choices
'("filename"
"random()"
"last_played"
"play_count"
"rating"
"artist" "album" "title"))))
(set! check-reverse-sort
(new check-box%
(parent h-panel)
(label "Reverse")
(callback apply-query))))))
| false |
30b665a0465e70742a5cf20d4b08758bc6177c8a
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/UnityEngine/unity-engine/i-os/notification-services.sls
|
52c2a11afdc5666c84c2e08a91f2c428d76600a6
|
[] |
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,355 |
sls
|
notification-services.sls
|
(library (unity-engine i-os notification-services)
(export new
is?
notification-services?
get-remote-notification
register-for-notifications
clear-remote-notifications
get-local-notification
unregister-for-remote-notifications
schedule-local-notification
cancel-all-local-notifications
present-local-notification-now
clear-local-notifications
cancel-local-notification
local-notification-count
local-notifications
scheduled-local-notifications
remote-notification-count
remote-notifications
enabled-notification-types
device-token
registration-error)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new UnityEngine.iOS.NotificationServices a ...)))))
(define (is? a) (clr-is UnityEngine.iOS.NotificationServices a))
(define (notification-services? a)
(clr-is UnityEngine.iOS.NotificationServices a))
(define-method-port
get-remote-notification
UnityEngine.iOS.NotificationServices
GetRemoteNotification
(static: UnityEngine.iOS.RemoteNotification System.Int32))
(define-method-port
register-for-notifications
UnityEngine.iOS.NotificationServices
RegisterForNotifications
(static:
System.Void
UnityEngine.iOS.NotificationType
System.Boolean)
(static: System.Void UnityEngine.iOS.NotificationType))
(define-method-port
clear-remote-notifications
UnityEngine.iOS.NotificationServices
ClearRemoteNotifications
(static: System.Void))
(define-method-port
get-local-notification
UnityEngine.iOS.NotificationServices
GetLocalNotification
(static: UnityEngine.iOS.LocalNotification System.Int32))
(define-method-port
unregister-for-remote-notifications
UnityEngine.iOS.NotificationServices
UnregisterForRemoteNotifications
(static: System.Void))
(define-method-port
schedule-local-notification
UnityEngine.iOS.NotificationServices
ScheduleLocalNotification
(static: System.Void UnityEngine.iOS.LocalNotification))
(define-method-port
cancel-all-local-notifications
UnityEngine.iOS.NotificationServices
CancelAllLocalNotifications
(static: System.Void))
(define-method-port
present-local-notification-now
UnityEngine.iOS.NotificationServices
PresentLocalNotificationNow
(static: System.Void UnityEngine.iOS.LocalNotification))
(define-method-port
clear-local-notifications
UnityEngine.iOS.NotificationServices
ClearLocalNotifications
(static: System.Void))
(define-method-port
cancel-local-notification
UnityEngine.iOS.NotificationServices
CancelLocalNotification
(static: System.Void UnityEngine.iOS.LocalNotification))
(define-field-port
local-notification-count
#f
#f
(static: property:)
UnityEngine.iOS.NotificationServices
localNotificationCount
System.Int32)
(define-field-port
local-notifications
#f
#f
(static: property:)
UnityEngine.iOS.NotificationServices
localNotifications
UnityEngine.iOS.LocalNotification[])
(define-field-port
scheduled-local-notifications
#f
#f
(static: property:)
UnityEngine.iOS.NotificationServices
scheduledLocalNotifications
UnityEngine.iOS.LocalNotification[])
(define-field-port
remote-notification-count
#f
#f
(static: property:)
UnityEngine.iOS.NotificationServices
remoteNotificationCount
System.Int32)
(define-field-port
remote-notifications
#f
#f
(static: property:)
UnityEngine.iOS.NotificationServices
remoteNotifications
UnityEngine.iOS.RemoteNotification[])
(define-field-port
enabled-notification-types
#f
#f
(static: property:)
UnityEngine.iOS.NotificationServices
enabledNotificationTypes
UnityEngine.iOS.NotificationType)
(define-field-port
device-token
#f
#f
(static: property:)
UnityEngine.iOS.NotificationServices
deviceToken
System.Byte[])
(define-field-port
registration-error
#f
#f
(static: property:)
UnityEngine.iOS.NotificationServices
registrationError
System.String))
| true |
1f96618edf25fb1a89ad7dbb0613884b66c0c5e0
|
1b1828426867c9ece3f232aaad1efbd2d59ebec7
|
/Chapter 3/sicp3-50.scm
|
37fa901fc62d51da815d1feacedcefd3054c8c0c
|
[] |
no_license
|
vendryan/sicp
|
60c1338354f506e02c714a96f643275d35a7dc51
|
d42f0cc6f985aaf369f2760f962928381ca74332
|
refs/heads/main
| 2023-06-07T02:04:56.332591 | 2021-06-19T10:28:57 | 2021-06-19T10:28:57 | 369,958,898 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 280 |
scm
|
sicp3-50.scm
|
(define (stream-map proc . argstream)
(if (stream-null? (car argstream))
the-mepty-stream
(cons-stream
(apply proc (map stream-car argstream))
(apply stream-map
(cons proc (map stream-cdr
argstream))))))
| false |
8b858a04c889d06c92a4347f8871a5d6a0b03c82
|
d2104eab4e36f4ddd4c5ed854fd74e015f33d885
|
/scheme/oid.scm
|
42f9157679516de6ffdcef0d2288b444d107dbe4
|
[
"LicenseRef-scancode-public-domain",
"Unlicense"
] |
permissive
|
catseye/Dipple
|
d507a5e4fc6a66ac8e91de2cc5417506f89e5b6d
|
8b6328568d47a4dddbd5712bea89aca32d46ce12
|
refs/heads/master
| 2023-08-09T11:27:52.202516 | 2023-07-21T09:24:21 | 2023-07-21T09:24:21 | 3,479,822 | 9 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,403 |
scm
|
oid.scm
|
; The 'oid' Control Structure: let* meets cond.
; Sometime in early 2009, Chris Pressey, Cat's Eye Technologies
; $Id: oid.scm 842 2010-11-28 09:17:01Z cpressey $
; The idea here is that I observed that so much of my Scheme code
; followed this idiom:
; (let* ((foo blah) (bar blah))
; (cond
; ((> 23 foo)
; (let* ((moo blah) (goo blah))
; ...))
; ((eq? bar baaz)
; ...))
; (else gar)))
; That is to say, cond's nested in let*'s nested in cond's
; nested in let*'s, etc. So, I thought, why not devise a
; single structure that encompasses this pattern? Here it is:
(define-syntax oid
(syntax-rules (else)
((oid ((var expr)) branch ...)
(let ((var expr)) (oid () branch ...)))
((oid ((var expr) binding ...) branch ...)
(let ((var expr)) (oid (binding ...) branch ...)))
((oid () (else ((var expr) binding ...) inner-branch ...))
(oid ((var expr) binding ...) inner-branch ...))
((oid () (else expr))
expr)
((oid () (test ((var expr) binding ...) inner-branch ...) branch ...)
(if test (oid ((var expr) binding ...) inner-branch ...) (oid () branch ...)))
((oid () (test expr) branch ...)
(if test expr (oid () branch ...)))))
(oid ((a 3) (b 2))
((eq? b 2) ((c 4) (d 3))
((> c b) "goo")
(else "gar"))
((eq? a 3) "hello")
(else "nada")
)
| true |
0d5dd3fee18667f090ac69f009115a75f571b105
|
ac6ca831a64544efd82dd1e6c8fc44c35a9538a2
|
/test/a.scm
|
97d218ba4bb6489e1f78bbd6fd194d3c43ace708
|
[
"MIT"
] |
permissive
|
ypyf/fscm
|
4bce4622cccccbfce8a5a1b4f482880ed14fa7c7
|
8be570e1c85a7ad6e1b888a2e3069ddcf4319569
|
refs/heads/master
| 2023-09-04T04:47:07.247132 | 2023-08-29T13:38:22 | 2023-08-29T13:59:56 | 5,802,289 | 5 | 1 | null | 2015-05-17T01:10:29 | 2012-09-13T23:10:28 |
Scheme
|
UTF-8
|
Scheme
| false | false | 235 |
scm
|
a.scm
|
(let ((result '(0 0 0)))
(if (eqv? result '(0 0 0))
(display "Map is call/cc safe, but probably not tail recursive or inefficient.")
(display "Map is not call/cc safe, but probably tail recursive and efficient."))
)
| false |
33ffe16e5e1a770eb0a1842f7509b5d4bbd95220
|
def26f110cf94581c6e0523383cec8c56c779d51
|
/srfi/41/primitive.sld
|
3feb976b6683ea2dc5380a46243c608f9c0f6619
|
[
"MIT"
] |
permissive
|
TaylanUB/scheme-srfis
|
f86649e4a71e8af59d2afd71bd33e96aaae4760f
|
7c4ba635c9829a35ce7134fa12db9959e4d1982a
|
refs/heads/master
| 2021-07-06T00:29:53.807790 | 2021-06-01T00:41:31 | 2021-06-01T00:41:31 | 37,764,520 | 39 | 4 | null | 2015-08-25T10:09:16 | 2015-06-20T09:20:04 |
Scheme
|
UTF-8
|
Scheme
| false | false | 210 |
sld
|
primitive.sld
|
(define-library (srfi 41 primitive)
(export
stream-null stream-cons stream? stream-null? stream-pair?
stream-car stream-cdr stream-lambda
)
(import (scheme base))
(include "primitive.body.scm"))
| false |
d9f3a6ba09da61eec0ff20030a207679de93c8b8
|
de21ee2b90a109c443485ed2e25f84daf4327af3
|
/exercise/section2/2.32.scm
|
2462e382702ebf0d039d7b1c4d56b0e672b01c94
|
[] |
no_license
|
s-tajima/SICP
|
ab82518bdc0551bb4c99447ecd9551f8d3a2ea1d
|
9ceff8757269adab850d01f238225d871748d5dc
|
refs/heads/master
| 2020-12-18T08:56:31.032661 | 2016-11-10T11:37:52 | 2016-11-10T11:37:52 | 18,719,524 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,078 |
scm
|
2.32.scm
|
;= Question =============================================================================
;
; 問題 2.32
;
; 集合は相異る要素のリストで表現出来る.
; また, 集合のすべての部分集合の集合を, リストのリストで表現出来る.
; 例えば集合が(1 2 3)の時,
; すべての部分集合の集合は(() (3) (2) (2 3) (1) (1 3) (1 2) (1 2 3))である.
; 集合の部分集合の集合を作り出す手続きの次の定義を完成し,
; なぜうまくいくか, 明快に説明せよ.
;
;(define (subsets s)
; (if (null? s)
; (list nil)
; (let ((rest (subsets (cdr s))))
; (append rest (map ⟨??⟩ rest)))))
;
;
;
;= Prepared =============================================================================
;= Answer ===============================================================================
(define (subsets s)
(if (null? s)
(list ())
(let ((rest (subsets (cdr s))))
(append rest (map (lambda (r) (append (list (car s)) r)) rest)))))
(print (subsets (list (list 1 2 3)))
| false |
c5dad104f764f2a9ca19c672f69a04050f4cec21
|
b39668eccdb1b003b6f98ea6e7a92c7bb2b5e951
|
/cards/card-artifact.ss
|
ec17b117c1fb78753a1ce1b314773a60fbfd9c78
|
[] |
no_license
|
angryzor/magic-the-gathering-project
|
d9c1f99bfbb38a8f9850427140d72db8c691297c
|
a58993eae9a7b0130353735b2d09ae6c8b07b006
|
refs/heads/master
| 2021-01-01T17:17:16.742759 | 2013-01-12T17:32:04 | 2013-01-12T17:32:04 | 7,578,284 | 0 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 495 |
ss
|
card-artifact.ss
|
#!r6rs
(library
(card-artifact)
(export card-artifact)
(import (rnrs base (6))
(magic cards card-tappable)
(magic object))
; Card-artifact
(define-dispatch-subclass (card-artifact name color cost game player picture)
(supports-type? get-type)
(card-tappable name color cost game player picture)
(define (supports-type? type)
(or (eq? type card-artifact) (super 'supports-type? type)))
(define (get-type)
card-artifact))
)
| false |
cb7b8f80912d2a3db769062b9ae4a5d171ca29d6
|
b14c18fa7a4067706bd19df10f846fce5a24c169
|
/Chapter3/3.64.scm
|
5daad62c70de3e5c5501e8cf9cdccf1718dc6eb4
|
[] |
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 | 759 |
scm
|
3.64.scm
|
#lang racket
(require racket/stream)
(define (average x y) (/ (+ x y) 2))
(define (sqrt-improve guess x)
(average guess (/ x guess)))
(define (sqrt-stream x)
(define guesses
(stream-cons 1.0
(stream-map
(lambda (guess)
(sqrt-improve guess x))
guesses)))
guesses)
(define (stream-limit stream tolerance)
(define (stream-limit-inner first stream tolerance)
(if (< (abs (- first (stream-first stream))) tolerance)
(stream-first stream)
(stream-limit-inner (stream-first stream) (stream-rest stream) tolerance)
)
)
(stream-limit-inner (stream-first stream) (stream-rest stream) tolerance)
)
(define (sqrt x tolerance)
(stream-limit (sqrt-stream x) tolerance)
)
(sqrt 2 1)
(sqrt 2 0.1)
(sqrt 2 0.01)
(sqrt 2 0.0000000001)
| false |
9565aad4fa2ddf6a740f1dbb422b799f68d71273
|
bdcc255b5af12d070214fb288112c48bf343c7f6
|
/pfds-tests/priority-search-test.sps
|
c538741d5b5cea40b39f5c1fd3b72732bc30a967
|
[] |
no_license
|
xaengceilbiths/chez-lib
|
089af4ab1d7580ed86fc224af137f24d91d81fa4
|
b7c825f18b9ada589ce52bf5b5c7c42ac7009872
|
refs/heads/master
| 2021-08-14T10:36:51.315630 | 2017-11-15T11:43:57 | 2017-11-15T11:43:57 | 109,713,952 | 5 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 5,083 |
sps
|
priority-search-test.sps
|
#!chezscheme
;; Original Test Suite from https://github.com/ijp/pfds
;; converted to use SRFI 64 tests by Peter Lane
(import (scheme base)
(pfds priority-search-queue)
(only (scheme list) fold filter)
(surfage s64 testing)
(scheme sort))
(define (alist->psq alist key<? priority<?)
(fold (lambda (kv psq)
(psq-set psq (car kv) (cdr kv)))
(make-psq key<? priority<?)
alist))
(define (add1 n) (+ 1 n))
(test-begin "pfds-priority-search-queue")
(test-assert (psq? (make-psq string<? <)))
(test-assert (psq-empty? (make-psq string<? <)))
(test-assert (zero? (psq-size (make-psq string<? <))))
;; psq-set
(let* ((empty (make-psq char<? <))
(psq1 (psq-set empty #\a 10))
(psq2 (psq-set psq1 #\b 33))
(psq3 (psq-set psq2 #\c 3))
(psq4 (psq-set psq3 #\a 12)))
(test-equal 10 (psq-ref psq1 #\a))
(test-error (psq-ref psq1 #\b))
(test-equal 1 (psq-size psq1))
(test-equal 10 (psq-ref psq2 #\a))
(test-equal 33 (psq-ref psq2 #\b))
(test-assert (not (psq-contains? psq2 #\c)))
(test-equal 2 (psq-size psq2))
(test-equal 10 (psq-ref psq3 #\a))
(test-equal 33 (psq-ref psq3 #\b))
(test-equal 3 (psq-ref psq3 #\c))
(test-equal 3 (psq-size psq3))
(test-equal 12 (psq-ref psq4 #\a))
(test-equal 33 (psq-ref psq4 #\b))
(test-equal 3 (psq-ref psq4 #\c))
(test-equal 3 (psq-size psq4)))
;; psq-delete
(let* ((psq1 (alist->psq '((#\a . 10) (#\b . 33) (#\c . 3))
char<?
<))
(psq2 (psq-delete psq1 #\c))
(psq3 (psq-delete psq2 #\b))
(psq4 (psq-delete psq3 #\a))
(psq5 (psq-delete psq1 #\d)))
(test-equal #t (psq-contains? psq1 #\c))
(test-assert (not (psq-contains? psq2 #\c)))
(test-equal #t (psq-contains? psq2 #\b))
(test-assert (not (psq-contains? psq3 #\b)))
(test-equal #t (psq-contains? psq3 #\a))
(test-assert (psq-empty? psq4))
(test-equal (psq-size psq1)
(psq-size psq5)))
;; psq-update
(let* ((empty (make-psq char<? <))
(psq1 (psq-update empty #\a add1 10))
(psq2 (psq-update psq1 #\b add1 33))
(psq3 (psq-update psq2 #\c add1 3))
(psq4 (psq-update psq3 #\a add1 0))
(psq5 (psq-update psq3 #\c add1 0)))
(test-equal 11 (psq-ref psq3 #\a))
(test-equal 34 (psq-ref psq3 #\b))
(test-equal 4 (psq-ref psq3 #\c))
(test-equal 12 (psq-ref psq4 #\a))
(test-equal 34 (psq-ref psq4 #\b))
(test-equal 4 (psq-ref psq4 #\c))
(test-equal 3 (psq-size psq4))
(test-equal 11 (psq-ref psq5 #\a))
(test-equal 34 (psq-ref psq5 #\b))
(test-equal 5 (psq-ref psq5 #\c))
(test-equal 3 (psq-size psq5)))
;; priority-queue-functions
(let* ((psq1 (alist->psq '((#\a . 10) (#\b . 33) (#\c . 3) (#\d . 23) (#\e . 7))
char<?
<))
(psq2 (psq-delete-min psq1))
(psq3 (psq-delete-min (psq-set psq2 #\b 9)))
(psq4 (make-psq < <)))
(test-equal #\c (psq-min psq1))
(test-equal #\e (psq-min psq2))
(test-error (psq-delete-min psq4))
(test-equal #\a (psq-min (psq-set psq1 #\a 0)))
(call-with-values
(lambda ()
(psq-pop psq3))
(lambda (min rest)
(test-equal #\b min)
(test-equal #\a (psq-min rest)))))
;; ranged-functions
(let* ((alist '((#\f . 24) (#\u . 42) (#\p . 16) (#\s . 34) (#\e . 17)
(#\x . 45) (#\l . 14) (#\z . 5) (#\t . 45) (#\r . 41)
(#\k . 32) (#\w . 14) (#\d . 12) (#\c . 16) (#\m . 20) (#\j . 25)))
(alist-sorted (list-sort (lambda (x y)
(char<? (car x) (car y)))
alist))
(psq (alist->psq alist char<? <)))
(test-equal alist-sorted
(psq-at-most psq +inf.0))
(test-equal '() (psq-at-most psq 0))
(test-equal '((#\c . 16) (#\d . 12) (#\e . 17) (#\l . 14)
(#\m . 20) (#\p . 16) (#\w . 14) (#\z . 5))
(psq-at-most psq 20))
(test-equal alist-sorted
(psq-at-most-range psq +inf.0 #\x00 #\xFF))
;; with bounds outwith range in psq, is the same as psq-at-most
(test-equal '() (psq-at-most-range psq 0 #\x00 #\xFF))
(test-equal '((#\c . 16) (#\d . 12) (#\e . 17) (#\l . 14)
(#\m . 20) (#\p . 16) (#\w . 14) (#\z . 5))
(psq-at-most-range psq 20 #\x00 #\xFF))
(test-equal '((#\c . 16) (#\d . 12) (#\e . 17) (#\l . 14)
(#\m . 20) (#\p . 16) (#\w . 14) (#\z . 5))
(psq-at-most psq 20))
(test-equal (filter (lambda (x) (char<=? #\e (car x) #\u)) alist-sorted)
(psq-at-most-range psq +inf.0 #\e #\u))
(test-equal '() (psq-at-most-range psq 0 #\e #\u))
(test-equal '((#\e . 17) (#\l . 14) (#\m . 20) (#\p . 16))
(psq-at-most-range psq 20 #\e #\u))
;; inclusiveness check
(test-equal '((#\t . 45))
(psq-at-most-range psq 80 #\t #\t))
;; if lower bound is higher than upper, then nothing
(test-equal '() (psq-at-most-range psq 80 #\t #\r)))
(test-end)
| false |
92878d035f38c6e11b4b6c989b2fc99f88438ea5
|
a9d1a0e915293c3e6101e598b3f8fc1d8b8647a9
|
/scheme/raytrace/test-ray.scm
|
f6fb0cd4d8dc5e96ff133ecf0f2ae5c27cbb4484
|
[] |
no_license
|
mbillingr/raytracing
|
a3b5b988007536a7065e51ef2fc17e6b5ac44d43
|
9c786e5818080cba488d3795bc6777270c505e5e
|
refs/heads/master
| 2021-04-16T17:10:40.435285 | 2020-11-11T07:02:18 | 2020-11-11T07:02:18 | 249,372,261 | 2 | 4 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,966 |
scm
|
test-ray.scm
|
(import (scheme base)
(raytrace testing)
(raytrace ray)
(raytrace tuple)
(raytrace shapes)
(raytrace transformations))
(test "Creating and querying a ray"
(given (origin <- (point 1 2 3))
(direction <- (point 4 5 6)))
(when (r <- (ray origin direction)))
(then ((ray-origin r) == origin)
((ray-direction r) == direction)))
(test "Computing a point from a distance"
(given (r <- (ray (point 2 3 4) (vec 1 0 0))))
(then ((ray-position r 0) == (point 2 3 4))
((ray-position r 1) == (point 3 3 4))
((ray-position r -1) == (point 1 3 4))
((ray-position r 2.5) == (point 4.5 3 4))))
(test "An intersection encapsulates t and object"
(given (s <- (vector 'dummy-shape)))
(when (i <- (intersection 3.5 s)))
(then ((intersection-t i) == 3.5)
((intersection-object i) == s)))
(test "Aggregating intersections"
(given (s <- (vector 'dummy-shape))
(i1 <- (intersection 1 s))
(i2 <- (intersection 2 s)))
(when (xs <- (intersections i1 i2)))
(then ((length xs) == 2)
((intersection-t (car xs)) == 1)
((intersection-t (cadr xs)) == 2)))
(test "Intersect sets the object on intersection"
(given (r <- (ray (point 0 0 -5) (vec 0 0 1)))
(s <- (sphere)))
(when (xs <- (intersect s r)))
(then ((length xs) == 2)
((intersection-object (car xs)) == s)
((intersection-object (cadr xs)) == s)))
(test "The hit, when all intersections have positive t"
(given (s <- (sphere))
(i1 <- (intersection 1 s))
(i2 <- (intersection 2 s))
(xs <- (intersections i2 i1)))
(when (i <- (hit xs)))
(then (i == i1)))
(test "The hit, when some intersections have negative t"
(given (s <- (sphere))
(i1 <- (intersection -1 s))
(i2 <- (intersection 1 s))
(xs <- (intersections i2 i1)))
(when (i <- (hit xs)))
(then (i == i2)))
(test "The hit, when all intersections have negative t"
(given (s <- (sphere))
(i1 <- (intersection -2 s))
(i2 <- (intersection -1 s))
(xs <- (intersections i2 i1)))
(when (i <- (hit xs)))
(then (i == #f)))
(test "The hit is always the lowest nonnegative intersection"
(given (s <- (sphere))
(i1 <- (intersection 5 s))
(i2 <- (intersection 7 s))
(i3 <- (intersection -3 s))
(i4 <- (intersection 2 s))
(xs <- (intersections i1 i2 i3 i4)))
(when (i <- (hit xs)))
(then (i == i4)))
(test "Translating a ray"
(given (r <- (ray (point 1 2 3) (vec 0 1 0)))
(m <- (translation 3 4 5)))
(when (r2 <- (ray-transform r m)))
(then ((ray-origin r2) == (point 4 6 8))
((ray-direction r2) == (vec 0 1 0))))
(test "Scaling a ray"
(given (r <- (ray (point 1 2 3) (vec 0 1 0)))
(m <- (scaling 2 3 4)))
(when (r2 <- (ray-transform r m)))
(then ((ray-origin r2) == (point 2 6 12))
((ray-direction r2) == (vec 0 3 0))))
| false |
6a34c760e0d70b433f148ea68974974ffc9636a9
|
4b2aeafb5610b008009b9f4037d42c6e98f8ea73
|
/12.1/binary-tree.scm
|
51c039129495e06f6e6a54910eb619aca54aa3bd
|
[] |
no_license
|
mrinalabrol/clrs
|
cd461d1a04e6278291f6555273d709f48e48de9c
|
f85a8f0036f0946c9e64dde3259a19acc62b74a1
|
refs/heads/master
| 2021-01-17T23:47:45.261326 | 2010-09-29T00:43:32 | 2010-09-29T00:43:32 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,853 |
scm
|
binary-tree.scm
|
(define-record-type :bt-node
(make-bt-node key datum left right parent)
bt-node?
(key bt-node-key set-bt-node-key!)
(datum bt-node-datum set-bt-node-datum!)
(left bt-node-left set-bt-node-left!)
(right bt-node-right set-bt-node-right!)
(parent bt-node-parent set-bt-node-parent!))
(define (bt-tree-filter proc root)
(let ((filter '()))
(let continue ((root root))
(if root
(begin (if (proc root) (set! filter (cons root filter)))
(continue (bt-node-left root))
(continue (bt-node-right root)))))
filter))
(define (bt-inorder-tree-map proc root)
(let ((mapping '()))
(let continue ((root root))
(if root
(begin (continue (bt-node-left root))
(set! mapping (cons (proc root) mapping))
(continue (bt-node-right root)))))
mapping))
;;; Reverse the order because of cons
(define (bt-preorder-tree-map proc root)
(let ((mapping '()))
(let continue ((root root))
(if root
(begin (continue (bt-node-left root))
(continue (bt-node-right root))
(set! mapping (cons (proc root) mapping)))))
mapping))
;;; Reverse the order because of cons
(define (bt-postorder-tree-map proc root)
(let ((mapping '()))
(let continue ((root root))
(if root
(begin (set! mapping (cons (proc root) mapping))
(continue (bt-node-left root))
(continue (bt-node-right root)))))
mapping))
(define (bt-inorder-tree-map/iterative proc root)
(let ((mapping '())
(nodes (make-stack (make-vector 12 #f) -1)))
(let continue ((root root))
(if root
(let ((left (bt-node-left root)))
(push! nodes root)
(continue left))
(if (stack-empty? nodes)
mapping
(let ((root (pop! nodes)))
(set! mapping (cons (proc root) mapping))
(continue (bt-node-right root))))))))
(define (set-bt-node-left-right-parent! node left right parent)
(set-bt-node-left! node left)
(set-bt-node-right! node right)
(set-bt-node-parent! node parent))
(define exercise-12.1
(let ((n1 (make-bt-node 1 1 #f #f #f))
(n4 (make-bt-node 4 4 #f #f #f))
(n5 (make-bt-node 5 5 #f #f #f))
(n10 (make-bt-node 10 10 #f #f #f))
(n16 (make-bt-node 16 16 #f #f #f))
(n17 (make-bt-node 17 17 #f #f #f))
(n21 (make-bt-node 21 21 #f #f #f)))
(set-bt-node-left-right-parent! n10 n4 n17 #f)
(set-bt-node-left-right-parent! n4 n1 n5 n10)
(set-bt-node-left-right-parent! n1 #f #f n4)
(set-bt-node-left-right-parent! n5 #f #f n4)
(set-bt-node-left-right-parent! n17 n16 n21 n10)
(set-bt-node-left-right-parent! n16 #f #f n17)
(set-bt-node-left-right-parent! n21 #f #f n17)
n10))
| false |
3da87f0b7897a21f360fb9d2d70699b023b13d62
|
99f659e747ddfa73d3d207efa88f1226492427ef
|
/datasets/srfi/srfi-10/vcond-expand.scm
|
b05cc857badfb666e22bdc5a78718f1dbd6fe8a3
|
[
"MIT"
] |
permissive
|
michaelballantyne/n-grams-for-synthesis
|
241c76314527bc40b073b14e4052f2db695e6aa0
|
be3ec0cf6d069d681488027544270fa2fd85d05d
|
refs/heads/master
| 2020-03-21T06:22:22.374979 | 2018-06-21T19:56:37 | 2018-06-21T19:56:37 | 138,215,290 | 0 | 0 |
MIT
| 2018-06-21T19:51:45 | 2018-06-21T19:51:45 | null |
UTF-8
|
Scheme
| false | false | 3,870 |
scm
|
vcond-expand.scm
|
; Validate implementation of cond-expand as a read-time application
; See cond-expand.scm for all the details.
;
; $Id$
(##include "myenv.scm")
(cerr
"\nValidating implementation of cond-expand as a read-time application...\n\n")
(define SRFI0-ex1-code
(apply string-append
(list-intersperse
(list
"#,(cond-expand"
"((and srfi-1 srfi-10)"
"(write 1))"
"((or srfi-1 srfi-10)"
"(write 2))"
"(else))")
"\n")))
; Interpret file file-name given feature-list
(define (with-features feature-list file-name)
(cerr "\n\twhen features " feature-list " are defined: ")
(OS:system "gsi -e '(##include \"cond-expand.scm\")' "
"-e \"(define ALL-FEATURES '"
(with-output-to-string (lambda () (write feature-list)))
")\" " file-name))
(cerr "cond-expanding code in SRFI-0, example 1...\n" SRFI0-ex1-code nl)
(let ((file-name "/tmp/a"))
(with-output-to-file file-name
(lambda () (display SRFI0-ex1-code)))
(with-features '(srfi-1) file-name)
(with-features '(srfi-10) file-name)
(with-features '(srfi-1 srfi-10) file-name)
(with-features '(srfi-2) file-name)
(cerr "\n\tDone\n")
)
(cerr "\nprinting cond-expanded code in SRFI-0, example 1...\n" SRFI0-ex1-code nl)
(let ((file-name "/tmp/a"))
(with-output-to-file file-name
(lambda () (display "(display '") (display SRFI0-ex1-code) (display ")")))
(with-features '(srfi-1) file-name)
(with-features '(srfi-10) file-name)
(with-features '(srfi-1 srfi-10) file-name)
(with-features '(srfi-2) file-name)
(cerr "\n\tDone\n")
)
(define SRFI0-ex2-code
(apply string-append
(list-intersperse
(list
"#,(cond-expand"
"(command-line"
"(define (program-name) (car (argv)))))"
"(pp program-name)")
"\n")))
(cerr "\ncond-expanding code in SRFI-0, example 2...\n" SRFI0-ex2-code nl)
(let ((file-name "/tmp/a"))
(with-output-to-file file-name
(lambda () (display SRFI0-ex2-code)))
(with-features '(command-line) file-name)
(with-features '(srfi-10 command-line) file-name)
(with-features '(srfi-10) file-name)
(cerr "\n\tDone\n")
)
; Emulating #+ and #- of CL
;
; http://www.harlequin.com/education/books/HyperSpec/Body/sec_24-1-2-1-1.html
; <BLOCKQUOTE>
; 24.1.2.1.1 Examples of Feature Expressions
; For example, suppose that in implementation A, the features spice and
; perq are present, but the feature lispm is not present; in
; implementation B, the feature lispm is present, but the features spice
; and perq are not present; and in implementation C, none of the features
; spice, lispm, or perq are present. The next figure shows some sample
; expressions, and how they would be read in these implementations.
; </BLOCKQUOTE>
(cerr "\n\ncond-expanding code similar to CL's"
" 24.1.2.1.1 Examples of Feature Expressions\n")
(define (interpret-string-in-ABC . strs)
(let ((file-name "/tmp/a"))
(with-output-to-file file-name
(lambda () (display "(write ") (for-each display strs) (display ")")))
(cerr "\ninterpreting string: ") (for-each display strs) (newline)
(with-features '(spice perq) file-name)
(with-features '(lispm) file-name)
(with-features '(srfi-10) file-name)
(cerr "\n\tDone\n")
))
(interpret-string-in-ABC
"(cons #,(cond-expand (spice \"Spice\") ((not spice) \"Lispm\")) 'X)")
(interpret-string-in-ABC
"(cons #,(cond-expand (spice \"Spice\") (lispm \"Lispm\")) 'X)")
(interpret-string-in-ABC
"(cons #,(cond-expand (spice \"Spice\") (perq \"Lispm\")) 'X)")
(interpret-string-in-ABC
"(cons #,(cond-expand (perq \"Perq\") (spice \"Spice\")) 'X)")
(interpret-string-in-ABC
"'#,(cond-expand ((or spice lispm) (let ((a 3) (b 3)) (foo a))) "
" (else (let ((a 3)) (foo a))))")
(interpret-string-in-ABC
"(cons #,(cond-expand (lispm \"Spice\") (spice \"foo\") "
"((not (or lispm spice)) 7)) 'x)")
| false |
522191c9df26ea3f8b6723ca29702da123360465
|
f08220a13ec5095557a3132d563a152e718c412f
|
/logrotate/skel/usr/share/guile/2.0/language/elisp/compile-tree-il.scm
|
0df21c7e619ab7a7aabbb938b5f891a33c001f6d
|
[
"Apache-2.0"
] |
permissive
|
sroettger/35c3ctf_chals
|
f9808c060da8bf2731e98b559babd4bf698244ac
|
3d64486e6adddb3a3f3d2c041242b88b50abdb8d
|
refs/heads/master
| 2020-04-16T07:02:50.739155 | 2020-01-15T13:50:29 | 2020-01-15T13:50:29 | 165,371,623 | 15 | 5 |
Apache-2.0
| 2020-01-18T11:19:05 | 2019-01-12T09:47:33 |
Python
|
UTF-8
|
Scheme
| false | false | 36,116 |
scm
|
compile-tree-il.scm
|
;;; Guile Emacs Lisp
;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
;; 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 3, 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; see the file COPYING. If not, write to
;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
;;; Code:
(define-module (language elisp compile-tree-il)
#:use-module (language elisp bindings)
#:use-module (language elisp runtime)
#:use-module (language tree-il)
#:use-module (system base pmatch)
#:use-module (system base compile)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-8)
#:use-module (srfi srfi-11)
#:use-module (srfi srfi-26)
#:export (compile-tree-il
compile-progn
compile-if
compile-defconst
compile-defvar
compile-setq
compile-let
compile-lexical-let
compile-flet
compile-let*
compile-lexical-let*
compile-flet*
compile-without-void-checks
compile-with-always-lexical
compile-guile-ref
compile-guile-primitive
compile-while
compile-function
compile-defmacro
compile-defun
#{compile-`}#
compile-quote))
;;; Certain common parameters (like the bindings data structure or
;;; compiler options) are not always passed around but accessed using
;;; fluids to simulate dynamic binding (hey, this is about elisp).
;;; The bindings data structure to keep track of symbol binding related
;;; data.
(define bindings-data (make-fluid))
;;; Store for which symbols (or all/none) void checks are disabled.
(define disable-void-check (make-fluid))
;;; Store which symbols (or all/none) should always be bound lexically,
;;; even with ordinary let and as lambda arguments.
(define always-lexical (make-fluid))
;;; Find the source properties of some parsed expression if there are
;;; any associated with it.
(define (location x)
(and (pair? x)
(let ((props (source-properties x)))
(and (not (null? props))
props))))
;;; Values to use for Elisp's nil and t.
(define (nil-value loc)
(make-const loc (@ (language elisp runtime) nil-value)))
(define (t-value loc)
(make-const loc (@ (language elisp runtime) t-value)))
;;; Modules that contain the value and function slot bindings.
(define runtime '(language elisp runtime))
(define value-slot (@ (language elisp runtime) value-slot-module))
(define function-slot (@ (language elisp runtime) function-slot-module))
;;; The backquoting works the same as quasiquotes in Scheme, but the
;;; forms are named differently; to make easy adaptions, we define these
;;; predicates checking for a symbol being the car of an
;;; unquote/unquote-splicing/backquote form.
(define (unquote? sym)
(and (symbol? sym) (eq? sym '#{,}#)))
(define (unquote-splicing? sym)
(and (symbol? sym) (eq? sym '#{,@}#)))
;;; Build a call to a primitive procedure nicely.
(define (call-primitive loc sym . args)
(make-application loc (make-primitive-ref loc sym) args))
;;; Error reporting routine for syntax/compilation problems or build
;;; code for a runtime-error output.
(define (report-error loc . args)
(apply error args))
(define (runtime-error loc msg . args)
(make-application loc
(make-primitive-ref loc 'error)
(cons (make-const loc msg) args)))
;;; Generate code to ensure a global symbol is there for further use of
;;; a given symbol. In general during the compilation, those needed are
;;; only tracked with the bindings data structure. Afterwards, however,
;;; for all those needed symbols the globals are really generated with
;;; this routine.
(define (generate-ensure-global loc sym module)
(make-application loc
(make-module-ref loc runtime 'ensure-fluid! #t)
(list (make-const loc module)
(make-const loc sym))))
(define (ensuring-globals loc bindings body)
(make-sequence
loc
`(,@(map-globals-needed (fluid-ref bindings)
(lambda (mod sym)
(generate-ensure-global loc sym mod)))
,body)))
;;; Build a construct that establishes dynamic bindings for certain
;;; variables. We may want to choose between binding with fluids and
;;; with-fluids* and using just ordinary module symbols and
;;; setting/reverting their values with a dynamic-wind.
(define (let-dynamic loc syms module vals body)
(call-primitive
loc
'with-fluids*
(make-application loc
(make-primitive-ref loc 'list)
(map (lambda (sym)
(make-module-ref loc module sym #t))
syms))
(make-application loc (make-primitive-ref loc 'list) vals)
(make-lambda loc
'()
(make-lambda-case #f '() #f #f #f '() '() body #f))))
;;; Handle access to a variable (reference/setting) correctly depending
;;; on whether it is currently lexically or dynamically bound. lexical
;;; access is done only for references to the value-slot module!
(define (access-variable loc
sym
module
handle-global
handle-lexical
handle-dynamic)
(let ((lexical (get-lexical-binding (fluid-ref bindings-data) sym)))
(cond
(lexical (handle-lexical lexical))
((equal? module function-slot) (handle-global))
(else (handle-dynamic)))))
;;; Generate code to reference a variable. For references in the
;;; value-slot module, we may want to generate a lexical reference
;;; instead if the variable has a lexical binding.
(define (reference-variable loc sym module)
(access-variable
loc
sym
module
(lambda () (make-module-ref loc module sym #t))
(lambda (lexical) (make-lexical-ref loc lexical lexical))
(lambda ()
(mark-global-needed! (fluid-ref bindings-data) sym module)
(call-primitive loc
'fluid-ref
(make-module-ref loc module sym #t)))))
;;; Generate code to set a variable. Just as with reference-variable, in
;;; case of a reference to value-slot, we want to generate a lexical set
;;; when the variable has a lexical binding.
(define (set-variable! loc sym module value)
(access-variable
loc
sym
module
(lambda ()
(make-application
loc
(make-module-ref loc runtime 'set-variable! #t)
(list (make-const loc module) (make-const loc sym) value)))
(lambda (lexical) (make-lexical-set loc lexical lexical value))
(lambda ()
(mark-global-needed! (fluid-ref bindings-data) sym module)
(call-primitive loc
'fluid-set!
(make-module-ref loc module sym #t)
value))))
;;; Process the bindings part of a let or let* expression; that is,
;;; check for correctness and bring it to the form ((sym1 . val1) (sym2
;;; . val2) ...).
(define (process-let-bindings loc bindings)
(map
(lambda (b)
(if (symbol? b)
(cons b 'nil)
(if (or (not (list? b))
(not (= (length b) 2)))
(report-error
loc
"expected symbol or list of 2 elements in let")
(if (not (symbol? (car b)))
(report-error loc "expected symbol in let")
(cons (car b) (cadr b))))))
bindings))
;;; Split the let bindings into a list to be done lexically and one
;;; dynamically. A symbol will be bound lexically if and only if: We're
;;; processing a lexical-let (i.e. module is 'lexical), OR we're
;;; processing a value-slot binding AND the symbol is already lexically
;;; bound or is always lexical, OR we're processing a function-slot
;;; binding.
(define (bind-lexically? sym module)
(or (eq? module 'lexical)
(eq? module function-slot)
(and (equal? module value-slot)
(let ((always (fluid-ref always-lexical)))
(or (eq? always 'all)
(memq sym always)
(get-lexical-binding (fluid-ref bindings-data) sym))))))
(define (split-let-bindings bindings module)
(let iterate ((tail bindings)
(lexical '())
(dynamic '()))
(if (null? tail)
(values (reverse lexical) (reverse dynamic))
(if (bind-lexically? (caar tail) module)
(iterate (cdr tail) (cons (car tail) lexical) dynamic)
(iterate (cdr tail) lexical (cons (car tail) dynamic))))))
;;; Compile let and let* expressions. The code here is used both for
;;; let/let* and flet/flet*, just with a different bindings module.
;;;
;;; A special module value 'lexical means that we're doing a lexical-let
;;; instead and the bindings should not be saved to globals at all but
;;; be done with the lexical framework instead.
;;; Let is done with a single call to let-dynamic binding them locally
;;; to new values all "at once". If there is at least one variable to
;;; bind lexically among the bindings, we first do a let for all of them
;;; to evaluate all values before any bindings take place, and then call
;;; let-dynamic for the variables to bind dynamically.
(define (generate-let loc module bindings body)
(let ((bind (process-let-bindings loc bindings)))
(call-with-values
(lambda () (split-let-bindings bind module))
(lambda (lexical dynamic)
(for-each (lambda (sym)
(mark-global-needed! (fluid-ref bindings-data)
sym
module))
(map car dynamic))
(let ((make-values (lambda (for)
(map (lambda (el) (compile-expr (cdr el)))
for)))
(make-body (lambda ()
(make-sequence loc (map compile-expr body)))))
(if (null? lexical)
(let-dynamic loc (map car dynamic) module
(make-values dynamic) (make-body))
(let* ((lexical-syms (map (lambda (el) (gensym)) lexical))
(dynamic-syms (map (lambda (el) (gensym)) dynamic))
(all-syms (append lexical-syms dynamic-syms))
(vals (append (make-values lexical)
(make-values dynamic))))
(make-let loc
all-syms
all-syms
vals
(with-lexical-bindings
(fluid-ref bindings-data)
(map car lexical) lexical-syms
(lambda ()
(if (null? dynamic)
(make-body)
(let-dynamic loc
(map car dynamic)
module
(map
(lambda (sym)
(make-lexical-ref loc
sym
sym))
dynamic-syms)
(make-body)))))))))))))
;;; Let* is compiled to a cascaded set of "small lets" for each binding
;;; in turn so that each one already sees the preceding bindings.
(define (generate-let* loc module bindings body)
(let ((bind (process-let-bindings loc bindings)))
(begin
(for-each (lambda (sym)
(if (not (bind-lexically? sym module))
(mark-global-needed! (fluid-ref bindings-data)
sym
module)))
(map car bind))
(let iterate ((tail bind))
(if (null? tail)
(make-sequence loc (map compile-expr body))
(let ((sym (caar tail))
(value (compile-expr (cdar tail))))
(if (bind-lexically? sym module)
(let ((target (gensym)))
(make-let loc
`(,target)
`(,target)
`(,value)
(with-lexical-bindings
(fluid-ref bindings-data)
`(,sym)
`(,target)
(lambda () (iterate (cdr tail))))))
(let-dynamic loc
`(,(caar tail))
module
`(,value)
(iterate (cdr tail))))))))))
;;; Split the argument list of a lambda expression into required,
;;; optional and rest arguments and also check it is actually valid.
;;; Additionally, we create a list of all "local variables" (that is,
;;; required, optional and rest arguments together) and also this one
;;; split into those to be bound lexically and dynamically. Returned is
;;; as multiple values: required optional rest lexical dynamic
(define (bind-arg-lexical? arg)
(let ((always (fluid-ref always-lexical)))
(or (eq? always 'all)
(memq arg always))))
(define (split-lambda-arguments loc args)
(let iterate ((tail args)
(mode 'required)
(required '())
(optional '())
(lexical '())
(dynamic '()))
(cond
((null? tail)
(let ((final-required (reverse required))
(final-optional (reverse optional))
(final-lexical (reverse lexical))
(final-dynamic (reverse dynamic)))
(values final-required
final-optional
#f
final-lexical
final-dynamic)))
((and (eq? mode 'required)
(eq? (car tail) '&optional))
(iterate (cdr tail) 'optional required optional lexical dynamic))
((eq? (car tail) '&rest)
(if (or (null? (cdr tail))
(not (null? (cddr tail))))
(report-error loc "expected exactly one symbol after &rest")
(let* ((rest (cadr tail))
(rest-lexical (bind-arg-lexical? rest))
(final-required (reverse required))
(final-optional (reverse optional))
(final-lexical (reverse (if rest-lexical
(cons rest lexical)
lexical)))
(final-dynamic (reverse (if rest-lexical
dynamic
(cons rest dynamic)))))
(values final-required
final-optional
rest
final-lexical
final-dynamic))))
(else
(if (not (symbol? (car tail)))
(report-error loc
"expected symbol in argument list, got"
(car tail))
(let* ((arg (car tail))
(bind-lexical (bind-arg-lexical? arg))
(new-lexical (if bind-lexical
(cons arg lexical)
lexical))
(new-dynamic (if bind-lexical
dynamic
(cons arg dynamic))))
(case mode
((required) (iterate (cdr tail) mode
(cons arg required) optional
new-lexical new-dynamic))
((optional) (iterate (cdr tail) mode
required (cons arg optional)
new-lexical new-dynamic))
(else
(error "invalid mode in split-lambda-arguments"
mode)))))))))
;;; Compile a lambda expression. One thing we have to be aware of is
;;; that lambda arguments are usually dynamically bound, even when a
;;; lexical binding is intact for a symbol. For symbols that are marked
;;; as 'always lexical,' however, we lexically bind here as well, and
;;; thus we get them out of the let-dynamic call and register a lexical
;;; binding for them (the lexical target variable is already there,
;;; namely the real lambda argument from TreeIL).
(define (compile-lambda loc args body)
(if (not (list? args))
(report-error loc "expected list for argument-list" args))
(if (null? body)
(report-error loc "function body must not be empty"))
(receive (required optional rest lexical dynamic)
(split-lambda-arguments loc args)
(define (process-args args)
(define (find-pairs pairs filter)
(lset-intersection (lambda (name+sym x)
(eq? (car name+sym) x))
pairs
filter))
(let* ((syms (map (lambda (x) (gensym)) args))
(pairs (map cons args syms))
(lexical-pairs (find-pairs pairs lexical))
(dynamic-pairs (find-pairs pairs dynamic)))
(values syms pairs lexical-pairs dynamic-pairs)))
(let*-values (((required-syms
required-pairs
required-lex-pairs
required-dyn-pairs)
(process-args required))
((optional-syms
optional-pairs
optional-lex-pairs
optional-dyn-pairs)
(process-args optional))
((rest-syms rest-pairs rest-lex-pairs rest-dyn-pairs)
(process-args (if rest (list rest) '())))
((the-rest-sym) (if rest (car rest-syms) #f))
((all-syms) (append required-syms
optional-syms
rest-syms))
((all-lex-pairs) (append required-lex-pairs
optional-lex-pairs
rest-lex-pairs))
((all-dyn-pairs) (append required-dyn-pairs
optional-dyn-pairs
rest-dyn-pairs)))
(for-each (lambda (sym)
(mark-global-needed! (fluid-ref bindings-data)
sym
value-slot))
dynamic)
(with-dynamic-bindings
(fluid-ref bindings-data)
dynamic
(lambda ()
(with-lexical-bindings
(fluid-ref bindings-data)
(map car all-lex-pairs)
(map cdr all-lex-pairs)
(lambda ()
(make-lambda
loc
'()
(make-lambda-case
#f
required
optional
rest
#f
(map (lambda (x) (nil-value loc)) optional)
all-syms
(let ((compiled-body
(make-sequence loc (map compile-expr body))))
(make-sequence
loc
(list
(if rest
(make-conditional
loc
(call-primitive loc
'null?
(make-lexical-ref loc
rest
the-rest-sym))
(make-lexical-set loc
rest
the-rest-sym
(nil-value loc))
(make-void loc))
(make-void loc))
(if (null? dynamic)
compiled-body
(let-dynamic loc
dynamic
value-slot
(map (lambda (name-sym)
(make-lexical-ref
loc
(car name-sym)
(cdr name-sym)))
all-dyn-pairs)
compiled-body)))))
#f)))))))))
;;; Handle the common part of defconst and defvar, that is, checking for
;;; a correct doc string and arguments as well as maybe in the future
;;; handling the docstring somehow.
(define (handle-var-def loc sym doc)
(cond
((not (symbol? sym)) (report-error loc "expected symbol, got" sym))
((> (length doc) 1) (report-error loc "too many arguments to defvar"))
((and (not (null? doc)) (not (string? (car doc))))
(report-error loc "expected string as third argument of defvar, got"
(car doc)))
;; TODO: Handle doc string if present.
(else #t)))
;;; Handle macro and special operator bindings.
(define (find-operator sym type)
(and
(symbol? sym)
(module-defined? (resolve-interface function-slot) sym)
(let* ((op (module-ref (resolve-module function-slot) sym))
(op (if (fluid? op) (fluid-ref op) op)))
(if (and (pair? op) (eq? (car op) type))
(cdr op)
#f))))
;;; See if a (backquoted) expression contains any unquotes.
(define (contains-unquotes? expr)
(if (pair? expr)
(if (or (unquote? (car expr)) (unquote-splicing? (car expr)))
#t
(or (contains-unquotes? (car expr))
(contains-unquotes? (cdr expr))))
#f))
;;; Process a backquoted expression by building up the needed
;;; cons/append calls. For splicing, it is assumed that the expression
;;; spliced in evaluates to a list. The emacs manual does not really
;;; state either it has to or what to do if it does not, but Scheme
;;; explicitly forbids it and this seems reasonable also for elisp.
(define (unquote-cell? expr)
(and (list? expr) (= (length expr) 2) (unquote? (car expr))))
(define (unquote-splicing-cell? expr)
(and (list? expr) (= (length expr) 2) (unquote-splicing? (car expr))))
(define (process-backquote loc expr)
(if (contains-unquotes? expr)
(if (pair? expr)
(if (or (unquote-cell? expr) (unquote-splicing-cell? expr))
(compile-expr (cadr expr))
(let* ((head (car expr))
(processed-tail (process-backquote loc (cdr expr)))
(head-is-list-2 (and (list? head)
(= (length head) 2)))
(head-unquote (and head-is-list-2
(unquote? (car head))))
(head-unquote-splicing (and head-is-list-2
(unquote-splicing?
(car head)))))
(if head-unquote-splicing
(call-primitive loc
'append
(compile-expr (cadr head))
processed-tail)
(call-primitive loc 'cons
(if head-unquote
(compile-expr (cadr head))
(process-backquote loc head))
processed-tail))))
(report-error loc
"non-pair expression contains unquotes"
expr))
(make-const loc expr)))
;;; Temporarily update a list of symbols that are handled specially
;;; (disabled void check or always lexical) for compiling body. We need
;;; to handle special cases for already all / set to all and the like.
(define (with-added-symbols loc fluid syms body)
(if (null? body)
(report-error loc "symbol-list construct has empty body"))
(if (not (or (eq? syms 'all)
(and (list? syms) (and-map symbol? syms))))
(report-error loc "invalid symbol list" syms))
(let ((old (fluid-ref fluid))
(make-body (lambda ()
(make-sequence loc (map compile-expr body)))))
(if (eq? old 'all)
(make-body)
(let ((new (if (eq? syms 'all)
'all
(append syms old))))
(with-fluids ((fluid new))
(make-body))))))
;;; Special operators
(defspecial progn (loc args)
(make-sequence loc (map compile-expr args)))
(defspecial if (loc args)
(pmatch args
((,cond ,then . ,else)
(make-conditional loc
(compile-expr cond)
(compile-expr then)
(if (null? else)
(nil-value loc)
(make-sequence loc
(map compile-expr else)))))))
(defspecial defconst (loc args)
(pmatch args
((,sym ,value . ,doc)
(if (handle-var-def loc sym doc)
(make-sequence loc
(list (set-variable! loc
sym
value-slot
(compile-expr value))
(make-const loc sym)))))))
(defspecial defvar (loc args)
(pmatch args
((,sym) (make-const loc sym))
((,sym ,value . ,doc)
(if (handle-var-def loc sym doc)
(make-sequence
loc
(list
(make-conditional
loc
(make-conditional
loc
(call-primitive
loc
'module-bound?
(call-primitive loc
'resolve-interface
(make-const loc value-slot))
(make-const loc sym))
(call-primitive loc
'fluid-bound?
(make-module-ref loc value-slot sym #t))
(make-const loc #f))
(make-void loc)
(set-variable! loc sym value-slot (compile-expr value)))
(make-const loc sym)))))))
(defspecial setq (loc args)
(define (car* x) (if (null? x) '() (car x)))
(define (cdr* x) (if (null? x) '() (cdr x)))
(define (cadr* x) (car* (cdr* x)))
(define (cddr* x) (cdr* (cdr* x)))
(make-sequence
loc
(let loop ((args args) (last (nil-value loc)))
(if (null? args)
(list last)
(let ((sym (car args))
(val (compile-expr (cadr* args))))
(if (not (symbol? sym))
(report-error loc "expected symbol in setq")
(cons
(set-variable! loc sym value-slot val)
(loop (cddr* args)
(reference-variable loc sym value-slot)))))))))
(defspecial let (loc args)
(pmatch args
((,bindings . ,body)
(generate-let loc value-slot bindings body))))
(defspecial lexical-let (loc args)
(pmatch args
((,bindings . ,body)
(generate-let loc 'lexical bindings body))))
(defspecial flet (loc args)
(pmatch args
((,bindings . ,body)
(generate-let loc function-slot bindings body))))
(defspecial let* (loc args)
(pmatch args
((,bindings . ,body)
(generate-let* loc value-slot bindings body))))
(defspecial lexical-let* (loc args)
(pmatch args
((,bindings . ,body)
(generate-let* loc 'lexical bindings body))))
(defspecial flet* (loc args)
(pmatch args
((,bindings . ,body)
(generate-let* loc function-slot bindings body))))
;;; Temporarily set symbols as always lexical only for the lexical scope
;;; of a construct.
(defspecial with-always-lexical (loc args)
(pmatch args
((,syms . ,body)
(with-added-symbols loc always-lexical syms body))))
;;; guile-ref allows building TreeIL's module references from within
;;; elisp as a way to access data within the Guile universe. The module
;;; and symbol referenced are static values, just like (@ module symbol)
;;; does!
(defspecial guile-ref (loc args)
(pmatch args
((,module ,sym) (guard (and (list? module) (symbol? sym)))
(make-module-ref loc module sym #t))))
;;; guile-primitive allows to create primitive references, which are
;;; still a little faster.
(defspecial guile-primitive (loc args)
(pmatch args
((,sym)
(make-primitive-ref loc sym))))
;;; A while construct is transformed into a tail-recursive loop like
;;; this:
;;;
;;; (letrec ((iterate (lambda ()
;;; (if condition
;;; (begin body
;;; (iterate))
;;; #nil))))
;;; (iterate))
;;;
;;; As letrec is not directly accessible from elisp, while is
;;; implemented here instead of with a macro.
(defspecial while (loc args)
(pmatch args
((,condition . ,body)
(let* ((itersym (gensym))
(compiled-body (map compile-expr body))
(iter-call (make-application loc
(make-lexical-ref loc
'iterate
itersym)
(list)))
(full-body (make-sequence loc
`(,@compiled-body ,iter-call)))
(lambda-body (make-conditional loc
(compile-expr condition)
full-body
(nil-value loc)))
(iter-thunk (make-lambda loc
'()
(make-lambda-case #f
'()
#f
#f
#f
'()
'()
lambda-body
#f))))
(make-letrec loc
#f
'(iterate)
(list itersym)
(list iter-thunk)
iter-call)))))
(defspecial function (loc args)
(pmatch args
(((lambda ,args . ,body))
(compile-lambda loc args body))
((,sym) (guard (symbol? sym))
(reference-variable loc sym function-slot))))
(defspecial defmacro (loc args)
(pmatch args
((,name ,args . ,body)
(if (not (symbol? name))
(report-error loc "expected symbol as macro name" name)
(let* ((tree-il
(make-sequence
loc
(list
(set-variable!
loc
name
function-slot
(make-application
loc
(make-module-ref loc '(guile) 'cons #t)
(list (make-const loc 'macro)
(compile-lambda loc args body))))
(make-const loc name)))))
(compile (ensuring-globals loc bindings-data tree-il)
#:from 'tree-il
#:to 'value)
tree-il)))))
(defspecial defun (loc args)
(pmatch args
((,name ,args . ,body)
(if (not (symbol? name))
(report-error loc "expected symbol as function name" name)
(make-sequence loc
(list (set-variable! loc
name
function-slot
(compile-lambda loc
args
body))
(make-const loc name)))))))
(defspecial #{`}# (loc args)
(pmatch args
((,val)
(process-backquote loc val))))
(defspecial quote (loc args)
(pmatch args
((,val)
(make-const loc val))))
;;; Compile a compound expression to Tree-IL.
(define (compile-pair loc expr)
(let ((operator (car expr))
(arguments (cdr expr)))
(cond
((find-operator operator 'special-operator)
=> (lambda (special-operator-function)
(special-operator-function loc arguments)))
((find-operator operator 'macro)
=> (lambda (macro-function)
(compile-expr (apply macro-function arguments))))
(else
(make-application loc
(if (symbol? operator)
(reference-variable loc
operator
function-slot)
(compile-expr operator))
(map compile-expr arguments))))))
;;; Compile a symbol expression. This is a variable reference or maybe
;;; some special value like nil.
(define (compile-symbol loc sym)
(case sym
((nil) (nil-value loc))
((t) (t-value loc))
(else (reference-variable loc sym value-slot))))
;;; Compile a single expression to TreeIL.
(define (compile-expr expr)
(let ((loc (location expr)))
(cond
((symbol? expr)
(compile-symbol loc expr))
((pair? expr)
(compile-pair loc expr))
(else (make-const loc expr)))))
;;; Process the compiler options.
;;; FIXME: Why is '(()) passed as options by the REPL?
(define (valid-symbol-list-arg? value)
(or (eq? value 'all)
(and (list? value) (and-map symbol? value))))
(define (process-options! opt)
(if (and (not (null? opt))
(not (equal? opt '(()))))
(if (null? (cdr opt))
(report-error #f "Invalid compiler options" opt)
(let ((key (car opt))
(value (cadr opt)))
(case key
((#:warnings) ; ignore
#f)
((#:always-lexical)
(if (valid-symbol-list-arg? value)
(fluid-set! always-lexical value)
(report-error #f
"Invalid value for #:always-lexical"
value)))
(else (report-error #f
"Invalid compiler option"
key)))))))
;;; Entry point for compilation to TreeIL. This creates the bindings
;;; data structure, and after compiling the main expression we need to
;;; make sure all globals for symbols used during the compilation are
;;; created using the generate-ensure-global function.
(define (compile-tree-il expr env opts)
(values
(with-fluids ((bindings-data (make-bindings))
(disable-void-check '())
(always-lexical '()))
(process-options! opts)
(let ((compiled (compile-expr expr)))
(ensuring-globals (location expr) bindings-data compiled)))
env
env))
| false |
7e16beb031885aa1ed051d5cd39c3d7f64ea73ef
|
1a64a1cff5ce40644dc27c2d951cd0ce6fcb6442
|
/testing/test-class-field-access.scm
|
3d36a1fc290f75b017b342030813291345d2e8d3
|
[] |
no_license
|
skchoe/2007.rviz-objects
|
bd56135b6d02387e024713a9f4a8a7e46c6e354b
|
03c7e05e85682d43ab72713bdd811ad1bbb9f6a8
|
refs/heads/master
| 2021-01-15T23:01:58.789250 | 2014-05-26T17:35:32 | 2014-05-26T17:35:32 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,574 |
scm
|
test-class-field-access.scm
|
#lang mzscheme
(require (lib "mred.ss" "mred")
(lib "framework.ss" "framework")
(lib "etc.ss")
(lib "class.ss"))
(define child-object%
(class object%
(init size)
(define member1 size)
(super-new)
(define/public set-member1
(lambda (cn)
(set! member1 cn)))
(define/public get-member1
(lambda () member1))
(set! member1 100)))
(define fish%
(class object%
(init-field size weight) ; initialization argument
(init-field ht)
(super-new) ; superclass initialization
;; methods
(define/public set-size
(lambda (sz)
(set! size sz)))
(define/public (get-size)
size)
(define/public (grow amt)
(set! size (+ amt size)))
(define/public set-weight
(lambda (wt)
(set! weight wt)))
(define/public (get-weight)
weight)
(define/public (get-ht)
ht)
(define/public (eat other-fish)
(grow (send other-fish get-size)))))
(define init-ht
(lambda ()
(make-hash-table 'equal)))
(define charlie (instantiate fish% () [size 10] [weight 100] [ht (init-ht)]))
(define viz-class (new child-object% [size 100]))
(define (main)
(let* ((c charlie)
(d viz-class))
(send c grow 1000)
(send c set-weight 200)
(display (send c get-size)) (newline)
(display (send c get-weight)) (newline)
(send d set-member1 200)
(display (send d get-member1))
))
(main)
| false |
33e0e4dfe8da9d2f469dbb55ef02a7f6dabfb4e0
|
b49e6c2edc0c5323f326e045c2a9fc769ba74778
|
/1.31a.ss
|
8afae566461d03aac46129ea6f0ce72862f26f5e
|
[] |
no_license
|
plotgeek/SICP
|
73d0109d37ca5f9ac2e98d847ecf633acb371021
|
e773a8071ae2fae768846a2b295b5ed96b019f8d
|
refs/heads/master
| 2023-03-09T18:50:54.195426 | 2012-08-14T10:18:59 | 2012-08-14T10:18:59 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 340 |
ss
|
1.31a.ss
|
(define (product term a next b)
(if (> a b)
1
(* (term a) (product term (next a) next b))))
(define (pi-product a b)
(define (pi-term n)
(cond ((= n 1) (/ 2.0 3.0))
((even? n) (/ (+ n 2) (+ n 1)))
(else (/ (+ n 1) (+ n 2)))))
(define (pi-next n)
(+ n 1))
(* (product pi-term a pi-next b) 4))
| false |
91646f6b00c27ea12c62b6b6e981939696f8dcff
|
e8e2b3f22c7e1921e99f44593fc0ba5e5e44eebb
|
/PortableApps/GnuCashPortable/App/GnuCash/share/gnucash/scm/gnucash/gnome-utils.scm
|
9b2488dc377d04a038d828747dfc7f0967273f4d
|
[] |
no_license
|
314pi/PortableOffice
|
da262df5eaca240a00921e8348d366efa426ae57
|
08a5e828b35ff3cade7c56d101d7f6712b19a308
|
refs/heads/master
| 2022-11-25T19:20:33.942725 | 2018-05-11T07:49:35 | 2018-05-11T07:49:35 | 132,839,264 | 1 | 2 | null | 2022-11-02T22:19:00 | 2018-05-10T02:42:46 |
Python
|
UTF-8
|
Scheme
| false | false | 2,312 |
scm
|
gnome-utils.scm
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 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, contact:
;;
;; Free Software Foundation Voice: +1-617-542-5942
;; 51 Franklin Street, Fifth Floor Fax: +1-617-542-2652
;; Boston, MA 02110-1301, USA [email protected]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-module (gnucash gnome-utils))
(use-modules (gnucash main)) ;; FIXME: delete after we finish modularizing.
(use-modules (gnucash gnc-module))
(cond-expand
(guile-2
(eval-when
(compile load eval expand)
(load-extension "libgncmod-gnome-utils" "scm_init_sw_gnome_utils_module")))
(else ))
(use-modules (sw_gnome_utils))
(gnc:module-load "gnucash/app-utils" 0)
;; from gnc-menu-extensions.scm
(export gnc:extension-type)
(export gnc:extension-name)
(export gnc:extension-guid)
(export gnc:extension-documentation)
(export gnc:extension-path)
(export gnc:extension-script)
(export gnc:make-menu-item)
(export gnc:make-menu)
(export gnc:make-separator)
(export gnc:kvp-option-dialog)
(load-from-path "gnc-menu-extensions")
(define (gnc:kvp-option-dialog id-type slots title changed_cb)
(let* ((options (gnc-make-kvp-options id-type))
(optiondb (gnc-option-db-new options))
(optionwin (gnc-options-dialog-new title)))
(define (apply-cb)
(gnc:options-scm->kvp options slots gnc:*kvp-option-path* #t)
(if changed_cb (changed_cb)))
(define (close-cb)
(gnc-options-dialog-destroy optionwin)
(gnc-option-db-destroy optiondb))
(gnc:options-kvp->scm options slots gnc:*kvp-option-path*)
(gnc-options-dialog-set-scm-callbacks optionwin apply-cb close-cb)
(gnc-options-dialog-build-contents optionwin optiondb)))
| false |
fee58390cb998d8a91dd08ee62d9693a5b82a754
|
8039bfbcb61c8c060e3fbc8de02b07bfeb532aaa
|
/basic-codes/Tree.scm
|
489c6906be4e05ba3399d4caaf94dbfa6a317ea3
|
[] |
no_license
|
agarwalr98/Paradigms-Of-Programming-CS302
|
ac5bcc24ee84a52e331f4baa742f94070d628498
|
598d9198fb13c1605fd54bf15cf5be280358c270
|
refs/heads/master
| 2023-03-07T02:28:25.910129 | 2021-02-23T14:42:00 | 2021-02-23T14:42:00 | 341,571,623 | 0 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,470 |
scm
|
Tree.scm
|
#lang sicp
; Tree Data structures : BST
; make-tree : return a list of (current-node value, left tree list, right tree )
(define (make-tree current_node left_tree right_tree)
(list current_node left_tree right_tree))
(define (datum t) (car t))
(define (left t) (cadr t))
(define (right t) (caddr t) )
;Insert a value in a BST
(define (insert value t)
(cond ((eq? '() t) (make-tree value '() '()))
((< value (datum t)) (make-tree (datum t) (insert value (left t)) (right t)))
((> value (datum t))(make-tree (datum t) (left t) (insert value (right t)))) ))
;Convert a list to BSt
(define (list2tree t list)
(if (null? list) t
(list2tree (insert (car list) t) (cdr list))))
;Inorder traversal - sorted
(define (inorder t)
(if (null? t) '()
(append (inorder (left t) ) (list (datum t)) (inorder (right t) ))))
;Preorder
(define (preorder t)
(if (null? t) '()
(append (list (datum t)) (preorder (left t)) (preorder (right t)))))
;postorder
(define (postorder t)
(if (null? t) '()
(append (postorder (left t)) (postorder (right t)) (list (datum t)))))
(define (search t value)
(cond ((null? t) #f)
((eq? (datum t) value) #t)
((if (< value (datum t)) (search (left t) value) (search (right t) value)) )))
(define l '(1 4 2 3 7 6 5 8 9 11) )
(define tree (list2tree '() l) )
(inorder tree)
(search tree 4)
| false |
e30521b671ad8ca90d16d32eecbbde50384ddaae
|
3b599e0f15d1b7ce3e42789b2e5c6d477b6a572b
|
/Lisp/sicp/common.ss
|
fad9211f0db39955b315fc16149e566ca0f82756
|
[] |
no_license
|
iacxc/MyProjects
|
1b2ccc80fca2c0935e1a91c98a7555b880745297
|
6998c87012273726bb290f5268ba1f8a9fd37381
|
refs/heads/master
| 2021-01-15T15:45:01.742263 | 2018-03-05T10:41:32 | 2018-03-05T10:41:32 | 25,804,036 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 3,082 |
ss
|
common.ss
|
;;; constants
(define nil '())
(define true #t)
(define false #f)
(define empty "")
;;; utilities
(define (square x) (* x x))
(define (accumulate op initial sequence)
(if (null? sequence) initial
(op (car sequence)
(accumulate op initial (cdr sequence)))))
(define (average x y) (/ (+ x y) 2))
(define (display-line x) (display x) (newline))
(define (logical-and s1 s2)
(cond ( (or (= s1 0) (= s2 0)) 0 )
( (and (= s1 1) (= s2 1)) 1 )
( else (error "Invalid signal" (list s1 s2)))))
(define (logical-not s)
(cond ( (= s 0) 1 )
( (= s 1) 0 )
( else (error "Invalid signal" s))))
(define (logical-or s1 s2)
(cond ( (or (= s1 1) (= s2 1)) 1 )
( (and (= s1 0) (= s2 0)) 0 )
( else (error "Invalid signal" (list s1 s2)))))
(define (make-string val)
(cond ( (null? val) empty )
( (string? val) val )
( (number? val) (number->string val) )
( (symbol? val) (symbol->string val) )
( else (error "Unrecognized data type" val) )
))
(define (range low high)
(if (> low high) nil
(cons low (range (+ low 1) high))))
(define (string-join str-list seperator)
(cond ( (null? str-list) empty )
( (null? (cdr str-list)) (car str-list) )
( else (string-append (car str-list)
seperator
(string-join (cdr str-list) seperator)) )))
(define (find-if predict? lst)
(cond ( (null? lst) #f )
( else (if (predict? (car lst)) (car lst)
(find-if predict? (cdr lst))) )))
(define (remove-if predict? lst)
(cond ( (null? lst) lst )
( else (if (predict? (car lst)) (cdr lst)
(cons (car lst) (remove-if predict? (cdr lst)))) )))
;;; objects
(define (make-point x y)
(lambda (op)
(cond ( (eq? op 'x) x )
( (eq? op 'y) y )
( else (error "Invalid op -- make-point" op) ))))
;; distance of two points from make-point
(define (distance p1 p2)
(sqrt (+ (square (- (p1 'x) (p2 'x)))
(square (- (p1 'y) (p2 'y))))))
(define (make-circle center radius)
(define (in point)
(<= (distance point center) radius))
(define (dispatch m)
(cond ( (eq? m 'center) center )
( (eq? m 'radius) radius )
( (eq? m 'in) in )
( else (error "Invalid operation -- make-circle" m) )))
dispatch)
(define (make-rectangle x1 y1 x2 y2)
; (if (or (>= x1 x2) (>= y1 y2)) (error "Invalid rectangle"))
(define (dispatch m)
(cond ( (eq? m 'x1) x1 )
( (eq? m 'y1) y1 )
( (eq? m 'x2) x2 )
( (eq? m 'y2) y2 )
( (eq? m 'width) (- x2 x1) )
( (eq? m 'height) (- y2 y1) )
( (eq? m 'center)
(make-point (/ (+ x2 x1) 2) (/ (+ y2 y1) 2)) )
( (eq? m 'area) (* (- x2 x1) (- y2 y1)) )
( else (error "Invalid operation -- make-circle" m) )))
dispatch)
| false |
97522e57c7f48e1b6be877f55713e3576adb46bc
|
880bb9d4ed95741e553d903238083f69b8fcfd84
|
/srfi/r7rs/Akku.manifest
|
4e909b8104802609f5e9672871099de2fa77ef7a
|
[
"MIT",
"CC0-1.0"
] |
permissive
|
pre-srfi/r6rs-r7rs-compat
|
8c16aa991f924fa14676e6298a82ff5e6651d14c
|
ac6ae78f59575b341b4848be23f3b867a795dd11
|
refs/heads/master
| 2023-01-23T20:28:08.748274 | 2020-12-07T19:41:54 | 2020-12-07T19:41:54 | 310,610,604 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 721 |
manifest
|
Akku.manifest
|
#!r6rs ; -*- mode: scheme; coding: utf-8 -*-
(import (akku format manifest))
(akku-package ("akku-r7rs" "1.0.1")
(synopsis "R7RS standard library for Akku.scm")
(description
"Akku.scm has the ability to convert R7RS define-library forms to R6RS library forms. This package provides the R7RS standard library for use with such converted libraries."
"Chez or Guile is required for full support."
"Akku.scm 0.3.0 or later is required. When used with Akku 1.0.0 or later it does not conflict with the built-in support in Larceny and Sagittarius.")
(authors "Göran Weinholt <[email protected]>"
"okuoku")
(license "CC0-1.0")
(depends ("chez-srfi" "^0.0.0-akku") ("laesare" "^1.0.0-alpha.1"))
)
| false |
68d5813137156d339714dc679239e95f128a58ee
|
fb9a1b8f80516373ac709e2328dd50621b18aa1a
|
/ch3/exercise3-79.scm
|
d109fec0cb58a4c444fb91540503b67148e09720
|
[] |
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 | 104 |
scm
|
exercise3-79.scm
|
;; 問題3.79
;; 3.78を一般化して、一般的な二階微分方程式を解けるようにせよ
| false |
da7d5a4b0fa002026be4bbf4551b9e5df3f576d9
|
0bb7631745a274104b084f6684671c3ee9a7b804
|
/lib/srfi/111/111.scm
|
1958868980fa4ff55b7c690f2af5b3da2818420d
|
[
"Apache-2.0",
"LGPL-2.1-only",
"LicenseRef-scancode-free-unknown",
"GPL-3.0-or-later",
"LicenseRef-scancode-autoconf-simple-exception"
] |
permissive
|
feeley/gambit
|
f87fd33034403713ad8f6a16d3ef0290c57a77d5
|
7438e002c7a41a5b1de7f51e3254168b7d13e8ba
|
refs/heads/master
| 2023-03-17T06:19:15.652170 | 2022-09-05T14:31:53 | 2022-09-05T14:31:53 | 220,799,690 | 0 | 1 |
Apache-2.0
| 2019-11-10T15:09:28 | 2019-11-10T14:14:16 | null |
UTF-8
|
Scheme
| false | false | 497 |
scm
|
111.scm
|
;;;============================================================================
;;; File: "111.scm"
;;; Copyright (c) 2021 by Marc Feeley, All Rights Reserved.
;;;============================================================================
;;; SRFI 111, Boxes
(##supply-module srfi/111)
;;;============================================================================
;; the box related procedures are builtin
;;;============================================================================
| false |
0c29a7725947f0d103427a0d22fd59a3860a67a3
|
a59389f876d6815a9b5d49167e264c4f4272c9a1
|
/packages/gui/graphic.ss
|
d1346c06091924c39acaadc8b6ce8c80a9364fe9
|
[
"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 | 18,347 |
ss
|
graphic.ss
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;作者:evilbinary on 11/19/16.
;邮箱:[email protected]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(library (gui graphic)
(export
graphic-init
graphic-resize
graphic-draw-text
graphic-draw-line
graphic-draw-solid-quad
graphic-draw-texture-quad
graphic-draw-line-strip
graphic-render
graphic-destroy
graphic-sissor-begin
graphic-sissor-end
graphic-new-edit
graphic-draw-edit
graphic-edit-add-text
graphic-new-markup
graphic-edit-set-text
graphic-draw-string
graphic-get-font
graphic-draw-string-prepare
graphic-draw-string-end
graphic-draw-string-colors
graphic-edit-set-color
graphic-get-fps
graphic-set-ratio
gl-markup-set-foreground
gl-markup-set-background
gl-markup-set-font-size
gl-edit-set-markup
gl-edit-set-highlight
gl-edit-char-event
gl-edit-get-text
gl-edit-set-font
gl-edit-mouse-event
gl-free-markup
gl-edit-key-event
)
(import (scheme) (utils libutil) (cffi cffi) (gles gles2) )
(load-librarys "libgui")
(def-function glShaderSource2 "glShaderSource2" (int int string void*) void)
(def-function shader-load-from-string "shader_load_from_string" (string string) int)
(def-function shader-load "shader_load" (string string) int)
(def-function gl-resize-edit-window "gl_resize_edit_window" (void* float float ) void)
(def-function gl-free-markup "gl_free_markup" (void*) void)
(def-function gl-new-markup "gl_new_markup" (string float) void*)
(def-function gl-markup-set-foreground "gl_markup_set_foreground" (void* float float float float) void)
(def-function gl-markup-set-background "gl_markup_set_background" (void* float float float float) void)
(def-function gl-markup-set-font-size "gl_markup_set_font_size" (void* float) void)
(def-function gl-edit-set-editable "gl_edit_set_editable" (void* int) void)
(def-function gl-edit-set-color "gl_edit_set_color" (void* int) void)
(def-function gl-edit-set-font "gl_edit_set_font" (void* string float) void)
(def-function gl-edit-set-markup "gl_edit_set_markup" (void* void* int) void)
(def-function gl-new-edit "gl_new_edit" (int float float float float) void*)
(def-function gl-edit-add-text "gl_add_edit_text" (void* string ) void)
(def-function gl-edit-set-text "gl_set_edit_text" (void* string ) void)
(def-function gl-edit-get-text "gl_get_edit_text" (void* ) string)
(def-function gl-render-edit "gl_render_edit" ( void* float float) void)
(def-function gl-render-edit-once "gl_render_edit_once" ( void* float float string int) void)
(def-function gl-edit-key-event "gl_edit_key_event" ( void* int int int int) void)
(def-function gl-edit-char-event "gl_edit_char_event" ( void* int int) void)
(def-function gl-edit-mouse-event "gl_edit_mouse_event" ( void* int float float) void)
(def-function graphic-get-fps "get_fps" (void) int)
(def-function sth-create "sth_create" (int int) void*)
(def-function sth-add-font "sth_add_font" (void* string) void*)
(def-function mvp-create "mvp_create" (int int int) void*)
(def-function font-create "font_create" (string) void*)
(def-function gl-render-string "gl_render_string" ( void* float string
float float
void* void* int) void)
(def-function gl-render-string-colors "gl_render_string_colors" (void*
float
float float
string
void*
float) void)
(def-function gl-render-prepare-string "gl_render_prepare_string" (void* void*) void)
(def-function gl-render-end-string "gl_render_end_string" (void*) void)
(def-function gl-edit-set-highlight "gl_edit_set_highlight" (void* void*) void)
(define texture-vert-shader 0)
(define texture-frag-shader 0)
(define v-shader-str
"attribute vec2 vPosition; \n
attribute vec2 vTexCoord; \n
varying vec2 v_TexCoordinate; \n
uniform vec2 screenSize; \n
void main() \n
{ \n
v_TexCoordinate = vTexCoord; \n
gl_Position = vec4(vPosition.x * 2.0 / screenSize.x - 1.0, ( screenSize.y - vPosition.y) * 2.0 / screenSize.y - 1.0, 0.0, 1.0); \n
} \n
\n"
)
(define f-shader-str
" \n
uniform sampler2D u_Texture; \n
varying vec2 v_TexCoordinate; \n
void main() \n
{ \n
gl_FragColor = texture2D(u_Texture, v_TexCoordinate); \n
} \n")
(define v-solid-shader-str
"attribute vec2 vPosition; \n
uniform vec2 screenSize; \n
void main() \n
{ \n
gl_Position = vec4(vPosition.x * 2.0 / screenSize.x - 1.0, ( screenSize.y - vPosition.y) * 2.0 / screenSize.y - 1.0, 0.0, 1.0); \n
} \n"
)
(define f-solid-shader-str
" \n
uniform vec4 color; \n
void main() \n
{ \n
gl_FragColor = color; \n
} \n")
(define texture-program 0)
(define uniform-screen-size 0)
(define uniform-texture 0)
(define uniform-solid-color 0)
(define uniform-solid-screen-size 0)
(define solid-program 0)
(define solid-vert-shader 0)
(define solid-frag-shader 0)
(define my-width 0)
(define my-height 0)
(define graphic-ratio 1.0)
(define font-string-cache (make-hashtable equal-hash eqv?) )
(define font-program 0)
(define font-vert-shader 0)
(define font-frag-shader 0)
(define uniform-font-texture 0)
(define uniform-font-model 0)
(define uniform-font-view 0)
(define uniform-font-projection 0)
(define gtext 0)
(define all-edit-cache (make-hashtable equal-hash eqv?) )
(define all-font-cache (make-hashtable equal-hash eqv?))
(define default-mvp 0)
(define f-font-shader-str
"uniform sampler2D texture;
varying vec2 v_TexCoordinate;
varying vec4 v_color;
void main()
{
gl_FragColor =vec4(v_color.rgb,texture2D(texture,v_TexCoordinate).a*v_color.a );
}")
;;float a = texture2D(texture,v_TexCoordinate.xy).r;
;; gl_FragColor = vec4(v_color.rgb,v_color.a*a);
(define v-font-shader-str
"uniform mat4 model;\n
uniform mat4 view;\n
uniform mat4 projection;\n
attribute vec3 vertex;\n
attribute vec2 tex_coord;\n
attribute vec4 color;\n
varying vec2 v_TexCoordinate;
varying vec4 v_color;
void main()\n
{\n
v_TexCoordinate=tex_coord;
v_color=color;
gl_Position =projection*(view*(model*vec4(vertex,1.0)));\n
}"
)
;; color;\n
;; gl_TexCoord[0].xy = tex_coord;
;;
(define (graphic-set-ratio ratio)
(set! graphic-ratio ratio))
(define (graphic-resize width height)
(set! my-width width)
(set! my-height height)
(gl-resize-edit-window gtext width height)
(let ((eds (vector->list (hashtable-values all-edit-cache))))
(let loop ((ed eds))
(if (pair? ed)
(begin
(gl-resize-edit-window (car ed) width height)
(loop (cdr ed))))))
)
(define (graphic-init width height)
(set! my-width width)
(set! my-height height)
(set! texture-vert-shader (glCreateShader GL_VERTEX_SHADER))
(glShaderSource2 texture-vert-shader 1 v-shader-str 0 )
(glCompileShader texture-vert-shader)
(set! texture-frag-shader (glCreateShader GL_FRAGMENT_SHADER))
(glShaderSource2 texture-frag-shader 1 f-shader-str 0 )
(glCompileShader texture-frag-shader)
(set! texture-program (glCreateProgram ))
(glAttachShader texture-program texture-vert-shader)
(glAttachShader texture-program texture-frag-shader)
(glBindAttribLocation texture-program 0 "vPosition")
(glBindAttribLocation texture-program 1 "vTexCoord")
(glLinkProgram texture-program)
(glUseProgram texture-program)
(set! uniform-screen-size (glGetUniformLocation texture-program "screenSize"))
(set! uniform-texture (glGetUniformLocation texture-program "u_Texture"))
;;solid shader
(set! solid-vert-shader (glCreateShader GL_VERTEX_SHADER))
(glShaderSource2 solid-vert-shader 1 v-solid-shader-str 0 )
(glCompileShader solid-vert-shader)
(set! solid-frag-shader (glCreateShader GL_FRAGMENT_SHADER))
(glShaderSource2 solid-frag-shader 1 f-solid-shader-str 0 )
(glCompileShader solid-frag-shader)
(set! solid-program (glCreateProgram))
(glAttachShader solid-program solid-vert-shader)
(glAttachShader solid-program solid-frag-shader)
(glBindAttribLocation solid-program 0 "vPosition")
(glLinkProgram solid-program)
(glUseProgram solid-program)
(set! uniform-solid-color (glGetUniformLocation solid-program "color"))
(set! uniform-solid-screen-size (glGetUniformLocation solid-program "screenSize"))
;;(draw-line solid-program uniform-solid-screen-size uniform-solid-color 0.0 0.0 200.0 200.0 255.0 0.0 0.0 0.0 )
;;(graphic-draw-line 0.0 12.0 34.0 56.0 255.0 0.0 0.0 0.0 )
;;font shader
(set! font-vert-shader (glCreateShader GL_VERTEX_SHADER))
(glShaderSource2 font-vert-shader 1 v-font-shader-str 0 )
(glCompileShader font-vert-shader)
(set! font-frag-shader (glCreateShader GL_FRAGMENT_SHADER))
(glShaderSource2 font-frag-shader 1 f-font-shader-str 0 )
(glCompileShader font-frag-shader)
(set! font-program (glCreateProgram))
(glAttachShader font-program font-vert-shader)
(glAttachShader font-program font-frag-shader)
(glBindAttribLocation font-program 0 "vertex")
(glBindAttribLocation font-program 1 "tex_coord")
(glBindAttribLocation font-program 2 "color")
(glLinkProgram font-program)
(glUseProgram font-program)
;;(set! font-program (shader-load-from-string v-font-shader-str f-font-shader-str))
;;(set! font-program (shader-load "shaders/v3f-t2f-c4f.vert" "shaders/v3f-t2f-c4f.frag"))
(set! uniform-font-texture (glGetUniformLocation font-program "texture"))
(set! uniform-font-model (glGetUniformLocation font-program "model"))
(set! uniform-font-view (glGetUniformLocation font-program "view"))
(set! uniform-font-projection (glGetUniformLocation font-program "projection"))
(set! gtext (gl-new-edit font-program my-width my-height my-width my-height))
(gl-edit-set-editable gtext 0)
;;(printf "gtext ~x\n" gtext)
(set! default-mvp (grpahic-new-mvp))
)
(define (graphic-new-edit w h)
(let ((ed (gl-new-edit font-program w h my-width my-height) ))
(hashtable-set! all-edit-cache ed ed)
ed
))
(define (graphic-draw-edit edit x y)
(gl-render-edit edit x (- my-height y)))
(define (graphic-edit-add-text edit text)
(gl-edit-add-text edit text))
(define (graphic-edit-set-text edit text)
(gl-edit-set-text edit text))
(define (graphic-edit-set-color edit color)
(gl-edit-set-color edit color))
(define (graphic-new-markup name size)
(gl-new-markup name size))
(define graphic-draw-text
(case-lambda
[(x y text)
(gl-render-edit-once gtext x (- my-height y) text #xffffff)]
[(x y text color)
(gl-render-edit-once gtext x (- my-height y) text color)]
))
(define (graphic-get-font name)
(let ((font (hashtable-ref all-font-cache name '())))
(if (null? font)
(begin
(set! font (font-create name))
(hashtable-set! all-font-cache name font)
font)
font
)))
(define (grpahic-new-mvp)
(mvp-create font-program my-width my-height ))
(define (graphic-draw-string-prepare font)
(gl-render-prepare-string default-mvp font)
)
(define (graphic-draw-string-end font)
(gl-render-end-string font)
)
(define cache-dx (cffi-alloc 8))
(define cache-dy (cffi-alloc 8))
(define (graphic-draw-string font size color x y text )
(let ((ret '()))
;;(printf "font=~a\n" font)
(gl-render-string font size text x (- (* graphic-ratio my-height) y) cache-dx cache-dy color )
(set! ret (list (cffi-get-float cache-dx) (cffi-get-float cache-dy)))
ret
))
(define (graphic-draw-string-colors font size x y text colors width)
(gl-render-string-colors font size x (- (* graphic-ratio my-height) y) text colors width) )
(define graphic-draw-line
(case-lambda
[( x1 y1 x2 y2 r g b a)
(let ((vertices (v 'float (list x1 y1 x2 y2))))
(glUseProgram solid-program)
(glUniform2f uniform-solid-screen-size (* 1.0 my-width) (* 1.0 my-height))
(glUniform4f uniform-solid-color (/ r 255.0) (/ g 255.0) (/ b 255.0) (* a 1.0))
(glVertexAttribPointer 0 2 GL_FLOAT GL_FALSE 0 vertices)
(glEnableVertexAttribArray 0)
(glDrawArrays GL_LINE_STRIP 0 2)
(glUseProgram 0)
(uv vertices)
)]
[( x1 y1 x2 y2 color)
(let ((vertices (v 'float (list x1 y1 x2 y2)))
(r (fixnum->flonum (bitwise-bit-field color 16 24)))
(g (fixnum->flonum (bitwise-bit-field color 8 16)))
(b (fixnum->flonum (bitwise-bit-field color 0 8)))
(a (/ (fixnum->flonum (if (= 0 (bitwise-bit-field color 24 32))
255
(bitwise-bit-field color 24 32)
)) 255.0)) )
(glUseProgram solid-program)
(glUniform2f uniform-solid-screen-size (* 1.0 my-width) (* 1.0 my-height))
(glUniform4f uniform-solid-color (/ r 255.0) (/ g 255.0) (/ b 255.0) (* a 1.0))
(glVertexAttribPointer 0 2 GL_FLOAT GL_FALSE 0 vertices)
(glEnableVertexAttribArray 0)
(glDrawArrays GL_LINE_STRIP 0 2)
(glUseProgram 0)
(uv vertices)
)]
))
(define (graphic-draw-line-strip lines r g b a)
(let ((vertices (v 'float lines)))
(glUseProgram solid-program)
(glUniform2f uniform-solid-screen-size (* 1.0 my-width) (* 1.0 my-height))
(glUniform4f uniform-solid-color (/ r 255.0) (/ g 255.0) (/ b 255.0) (* a 1.0))
(glVertexAttribPointer 0 2 GL_FLOAT GL_FALSE 0 vertices)
(glEnableVertexAttribArray 0)
(glDrawArrays GL_LINE_STRIP 0 2)
(glUseProgram 0)
(uv vertices)
))
(define (graphic-sissor-begin x y width height)
(glEnable GL_SCISSOR_TEST)
(glScissor (flonum->fixnum (* graphic-ratio x )) (flonum->fixnum (* graphic-ratio (- my-height height y) ) )
(flonum->fixnum (* graphic-ratio width ))
(flonum->fixnum (* graphic-ratio height) ))
;;(glScissor 660 240 800 600)
)
(define (graphic-sissor-end )
(glDisable GL_SCISSOR_TEST)
)
(define graphic-draw-solid-quad
(case-lambda
[(x1 y1 x2 y2 r g b a)
(let ((vertices (v 'float (list x1 y2
x1 y1
x2 y2 x2 y1))))
(glUseProgram solid-program)
(glUniform2f uniform-solid-screen-size (* 1.0 my-width) (* 1.0 my-height))
(glUniform4f uniform-solid-color (/ r 255.0) (/ g 255.0) (/ b 255.0) (* a 1.0))
(glVertexAttribPointer 0 2 GL_FLOAT GL_FALSE 0 vertices)
(glEnableVertexAttribArray 0)
(glDrawArrays GL_TRIANGLE_STRIP 0 4)
(glUseProgram 0)
(uv vertices)
)]
[(x1 y1 x2 y2 color)
(let ((vertices (v 'float (list x1 y2
x1 y1
x2 y2 x2 y1)))
(r (fixnum->flonum (bitwise-bit-field color 16 24)))
(g (fixnum->flonum (bitwise-bit-field color 8 16)))
(b (fixnum->flonum (bitwise-bit-field color 0 8)))
(a (/ (fixnum->flonum (if (= 0 (bitwise-bit-field color 24 32))
255
(bitwise-bit-field color 24 32)
)) 255.0)) )
(glUseProgram solid-program)
(glUniform2f uniform-solid-screen-size (* 1.0 my-width) (* 1.0 my-height))
(glUniform4f uniform-solid-color (/ r 255.0) (/ g 255.0) (/ b 255.0) (* a 1.0))
(glVertexAttribPointer 0 2 GL_FLOAT GL_FALSE 0 vertices)
(glEnableVertexAttribArray 0)
(glDrawArrays GL_TRIANGLE_STRIP 0 4)
(glUseProgram 0)
(uv vertices)
)]
))
(define (graphic-draw-texture-quad x1 y1 x2 y2 tx1 ty1 tx2 ty2 texture-id)
(let ((vertices (v 'float (list x1 y2
x1 y1
x2 y2
x2 y1)))
(text-coords (v 'float (list
tx1 ty2
tx1 ty1
tx2 ty2
tx2 ty1)))
)
(glUseProgram texture-program)
(glUniform2f uniform-solid-screen-size (* 1.0 my-width) (* 1.0 my-height))
(glActiveTexture GL_TEXTURE0)
(glBindTexture GL_TEXTURE_2D texture-id)
(glUniform1i uniform-texture 0)
;;(glUniform4f uniform-solid-color (/ r 255.0) (/ g 255.0) (/ b 255.0) (* a 1.0))
(glVertexAttribPointer 0 2 GL_FLOAT GL_FALSE 0 vertices)
(glEnableVertexAttribArray 0)
(glVertexAttribPointer 1 2 GL_FLOAT GL_FALSE 0 text-coords)
(glEnableVertexAttribArray 1)
(glDrawArrays GL_TRIANGLE_STRIP 0 4)
(glUseProgram 0)
(uv vertices)
(uv text-coords)
))
(define (graphic-render)
'()
)
(define (graphic-destroy )
'())
(define (v type vec )
(if (list? vec)
(set! vec (list->vector vec)))
(let* ((len (vector-length vec))
(size (foreign-sizeof type))
(data (foreign-alloc (* len size)))
)
(let loop ((i 0))
(if (< i len)
(let ((v (vector-ref vec i)))
(cond
((flonum? v) (foreign-set! type data (* i size) v))
((fixnum? v) (foreign-set! type data (* i size) v)))
(loop (+ i 1)
)
)))
data))
(define (uv vec)
(foreign-free vec))
)
| false |
36f5fda01f92abf184e2e4db90537a3c35e1ad6b
|
43612e5ed60c14068da312fd9d7081c1b2b7220d
|
/tools/benchtimes/resultbak/m5eponly/lattice.scm.scm
|
658c8a881f8aa37b9d1f9c9bba1cd7091f45ab2d
|
[
"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 | 12,827 |
scm
|
lattice.scm.scm
|
;;------------------------------------------------------------------------------
;; Macros
(##define-macro (def-macro form . body)
`(##define-macro ,form (let () ,@body)))
(def-macro (FLOATvector-const . lst) `',(list->vector lst))
(def-macro (FLOATvector? x) `(vector? ,x))
(def-macro (FLOATvector . lst) `(vector ,@lst))
(def-macro (FLOATmake-vector n . init) `(make-vector ,n ,@init))
(def-macro (FLOATvector-ref v i) `(vector-ref ,v ,i))
(def-macro (FLOATvector-set! v i x) `(vector-set! ,v ,i ,x))
(def-macro (FLOATvector-length v) `(vector-length ,v))
(def-macro (nuc-const . lst)
`',(list->vector lst))
(def-macro (FLOAT+ . lst) `(+ ,@lst))
(def-macro (FLOAT- . lst) `(- ,@lst))
(def-macro (FLOAT* . lst) `(* ,@lst))
(def-macro (FLOAT/ . lst) `(/ ,@lst))
(def-macro (FLOAT= . lst) `(= ,@lst))
(def-macro (FLOAT< . lst) `(< ,@lst))
(def-macro (FLOAT<= . lst) `(<= ,@lst))
(def-macro (FLOAT> . lst) `(> ,@lst))
(def-macro (FLOAT>= . lst) `(>= ,@lst))
(def-macro (FLOATnegative? . lst) `(negative? ,@lst))
(def-macro (FLOATpositive? . lst) `(positive? ,@lst))
(def-macro (FLOATzero? . lst) `(zero? ,@lst))
(def-macro (FLOATabs . lst) `(abs ,@lst))
(def-macro (FLOATsin . lst) `(sin ,@lst))
(def-macro (FLOATcos . lst) `(cos ,@lst))
(def-macro (FLOATatan . lst) `(atan ,@lst))
(def-macro (FLOATsqrt . lst) `(sqrt ,@lst))
(def-macro (FLOATmin . lst) `(min ,@lst))
(def-macro (FLOATmax . lst) `(max ,@lst))
(def-macro (FLOATround . lst) `(round ,@lst))
(def-macro (FLOATinexact->exact . lst) `(inexact->exact ,@lst))
(def-macro (GENERIC+ . lst) `(+ ,@lst))
(def-macro (GENERIC- . lst) `(- ,@lst))
(def-macro (GENERIC* . lst) `(* ,@lst))
(def-macro (GENERIC/ . lst) `(/ ,@lst))
(def-macro (GENERICquotient . lst) `(quotient ,@lst))
(def-macro (GENERICremainder . lst) `(remainder ,@lst))
(def-macro (GENERICmodulo . lst) `(modulo ,@lst))
(def-macro (GENERIC= . lst) `(= ,@lst))
(def-macro (GENERIC< . lst) `(< ,@lst))
(def-macro (GENERIC<= . lst) `(<= ,@lst))
(def-macro (GENERIC> . lst) `(> ,@lst))
(def-macro (GENERIC>= . lst) `(>= ,@lst))
(def-macro (GENERICexpt . lst) `(expt ,@lst))
;;------------------------------------------------------------------------------
;; Functions used by LC to get time info
(def-macro (##lc-time expr)
(let ((sym (gensym)))
`(let ((r (##lc-exec-stats (lambda () ,expr))))
(println "CPU time: "
(+ (cdr (assoc "User time" (cdr r)))
(cdr (assoc "Sys time" (cdr r)))))
(map (lambda (el) (println (car el) ": " (cdr el))) (cdr r))
r)))
(define (##lc-exec-stats thunk)
(let* ((at-start (gambit$$##process-statistics))
(result (thunk))
(at-end (gambit$$##process-statistics)))
(define (get-info msg idx)
(cons msg
(- (gambit$$##f64vector-ref at-end idx)
(gambit$$##f64vector-ref at-start idx))))
(list
result
(get-info "User time" 0)
(get-info "Sys time" 1)
(get-info "Real time" 2)
(get-info "GC user time" 3)
(get-info "GC sys time" 4)
(get-info "GC real time" 5)
(get-info "Nb gcs" 6))))
;;------------------------------------------------------------------------------
(define ###TIME_BEFORE### 0)
(define ###TIME_AFTER### 0)
(define (run-bench name count ok? run)
(let loop ((i count) (result '(undefined)))
(if (< 0 i)
(loop (- i 1) (run))
result)))
(define (run-benchmark name count ok? run-maker . args)
(let ((run (apply run-maker args)))
(let ((result (car (##lc-time (run-bench name count ok? run)))))
(if (not (ok? result))
(begin
(display "*** wrong result ***")
(newline)
(display "*** got: ")
(write result)
(newline))))))
; Gabriel benchmarks
(define boyer-iters 20)
(define browse-iters 600)
(define cpstak-iters 1000)
(define ctak-iters 100)
(define dderiv-iters 2000000)
(define deriv-iters 2000000)
(define destruc-iters 500)
(define diviter-iters 1000000)
(define divrec-iters 1000000)
(define puzzle-iters 100)
(define tak-iters 2000)
(define takl-iters 300)
(define trav1-iters 100)
(define trav2-iters 20)
(define triangl-iters 10)
; Kernighan and Van Wyk benchmarks
(define ack-iters 10)
(define array1-iters 1)
(define cat-iters 1)
(define string-iters 10)
(define sum1-iters 10)
(define sumloop-iters 10)
(define tail-iters 1)
(define wc-iters 1)
; C benchmarks
(define fft-iters 2000)
(define fib-iters 5)
(define fibfp-iters 2)
(define mbrot-iters 100)
(define nucleic-iters 5)
(define pnpoly-iters 100000)
(define sum-iters 20000)
(define sumfp-iters 20000)
(define tfib-iters 20)
; Other benchmarks
(define conform-iters 40)
(define dynamic-iters 20)
(define earley-iters 200)
(define fibc-iters 500)
(define graphs-iters 300)
(define lattice-iters 1)
(define matrix-iters 400)
(define maze-iters 4000)
(define mazefun-iters 1000)
(define nqueens-iters 2000)
(define paraffins-iters 1000)
(define peval-iters 200)
(define pi-iters 2)
(define primes-iters 100000)
(define ray-iters 5)
(define scheme-iters 20000)
(define simplex-iters 100000)
(define slatex-iters 20)
(define perm9-iters 10)
(define nboyer-iters 100)
(define sboyer-iters 100)
(define gcbench-iters 1)
(define compiler-iters 300)
;;; LATTICE -- Obtained from Andrew Wright.
; Given a comparison routine that returns one of
; less
; more
; equal
; uncomparable
; return a new comparison routine that applies to sequences.
(define lexico
(lambda (base)
(define lex-fixed
(lambda (fixed lhs rhs)
(define check
(lambda (lhs rhs)
(if (null? lhs)
fixed
(let ((probe
(base (car lhs)
(car rhs))))
(if (or (eq? probe 'equal)
(eq? probe fixed))
(check (cdr lhs)
(cdr rhs))
'uncomparable)))))
(check lhs rhs)))
(define lex-first
(lambda (lhs rhs)
(if (null? lhs)
'equal
(let ((probe
(base (car lhs)
(car rhs))))
(case probe
((less more)
(lex-fixed probe
(cdr lhs)
(cdr rhs)))
((equal)
(lex-first (cdr lhs)
(cdr rhs)))
((uncomparable)
'uncomparable))))))
lex-first))
(define (make-lattice elem-list cmp-func)
(cons elem-list cmp-func))
(define lattice->elements car)
(define lattice->cmp cdr)
; Select elements of a list which pass some test.
(define zulu-select
(lambda (test lst)
(define select-a
(lambda (ac lst)
(if (null? lst)
(reverse! ac)
(select-a
(let ((head (car lst)))
(if (test head)
(cons head ac)
ac))
(cdr lst)))))
(select-a '() lst)))
(define reverse!
(letrec ((rotate
(lambda (fo fum)
(let ((next (cdr fo)))
(set-cdr! fo fum)
(if (null? next)
fo
(rotate next fo))))))
(lambda (lst)
(if (null? lst)
'()
(rotate lst '())))))
; Select elements of a list which pass some test and map a function
; over the result. Note, only efficiency prevents this from being the
; composition of select and map.
(define select-map
(lambda (test func lst)
(define select-a
(lambda (ac lst)
(if (null? lst)
(reverse! ac)
(select-a
(let ((head (car lst)))
(if (test head)
(cons (func head)
ac)
ac))
(cdr lst)))))
(select-a '() lst)))
; This version of map-and tail-recurses on the last test.
(define map-and
(lambda (proc lst)
(if (null? lst)
#t
(letrec ((drudge
(lambda (lst)
(let ((rest (cdr lst)))
(if (null? rest)
(proc (car lst))
(and (proc (car lst))
(drudge rest)))))))
(drudge lst)))))
(define (maps-1 source target pas new)
(let ((scmp (lattice->cmp source))
(tcmp (lattice->cmp target)))
(let ((less
(select-map
(lambda (p)
(eq? 'less
(scmp (car p) new)))
cdr
pas))
(more
(select-map
(lambda (p)
(eq? 'more
(scmp (car p) new)))
cdr
pas)))
(zulu-select
(lambda (t)
(and
(map-and
(lambda (t2)
(memq (tcmp t2 t) '(less equal)))
less)
(map-and
(lambda (t2)
(memq (tcmp t2 t) '(more equal)))
more)))
(lattice->elements target)))))
(define (maps-rest source target pas rest to-1 to-collect)
(if (null? rest)
(to-1 pas)
(let ((next (car rest))
(rest (cdr rest)))
(to-collect
(map
(lambda (x)
(maps-rest source target
(cons
(cons next x)
pas)
rest
to-1
to-collect))
(maps-1 source target pas next))))))
(define (maps source target)
(make-lattice
(maps-rest source
target
'()
(lattice->elements source)
(lambda (x) (list (map cdr x)))
(lambda (x) (apply append x)))
(lexico (lattice->cmp target))))
(define (count-maps source target)
(maps-rest source
target
'()
(lattice->elements source)
(lambda (x) 1)
sum))
(define (sum lst)
(if (null? lst)
0
(+ (car lst) (sum (cdr lst)))))
(define (run)
(let* ((l2
(make-lattice '(low high)
(lambda (lhs rhs)
(case lhs
((low)
(case rhs
((low)
'equal)
((high)
'less)
(else
(fatal-error 'make-lattice "base" rhs))))
((high)
(case rhs
((low)
'more)
((high)
'equal)
(else
(fatal-error 'make-lattice "base" rhs))))
(else
(fatal-error 'make-lattice "base" lhs))))))
(l3 (maps l2 l2))
(l4 (maps l3 l3)))
(count-maps l2 l2)
(count-maps l3 l3)
(count-maps l2 l3)
(count-maps l3 l2)
(count-maps l4 l4)))
(define (main)
(run-benchmark
"lattice"
lattice-iters
(lambda (result) (equal? result 120549))
(lambda () (lambda () (run)))))
(main)
| false |
52f3397998100ddb8a4f5e22231cafc38e4c77a9
|
710e486f87b70e57cc3c2a411d12c30644544b75
|
/command.sld
|
5de7844a654ca3b7e73c9dcf6bb655fe0ae1776b
|
[
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"BlueOak-1.0.0"
] |
permissive
|
ar-nelson/schemepunk
|
6236a3200343257a9ce15a6e3f4bda1dd450c729
|
249bf057b256bbb9212f60345a84d84615c61893
|
refs/heads/master
| 2021-05-18T07:47:36.721609 | 2021-04-24T17:05:48 | 2021-04-24T17:05:48 | 251,185,680 | 92 | 7 |
NOASSERTION
| 2021-05-12T14:07:38 | 2020-03-30T02:53:33 |
Scheme
|
UTF-8
|
Scheme
| false | false | 18,893 |
sld
|
command.sld
|
;; Command-line argument processor, loosely based on (chibi app) but with
;; a different spec syntax.
;;
;; (run-application <spec> <args> <proc>) parses the command-line argument list
;; <args> with the spec <spec>. It passes five arguments to <proc>:
;;
;; (<options> <extra-args> <command> <command-options> <command-extra-args>)
;;
;; <options> and <command-options> are alists of - or -- options, before and
;; after the command name.
;;
;; <extra-args> and <command-extra-args> are lists of string arguments; all
;; arguments before and after the command name that are not options.
;;
;; <command> is the command name; it is #f if no command is passed.
;;
;; A specification is a configuration alist, usually quoted. Here is an example,
;; a translation of (chibi app)'s zoo example:
;;
;; ((name "Zookeeper Application")
;; (doc "Example application from (chibi app) documentation, adapted for \
;; (schemepunk command).")
;; (copyright "Copyright (c) 2020")
;; (options
;; (animals
;; (type (list symbol))
;; (doc "list of animals to act on (default all)"))
;; (lions
;; (short #\l)
;; (doc "also apply the action to lions")))
;; (commands
;; (feed
;; (short-doc "feed the animals")
;; (doc-args <animals> ...))
;; (wash
;; (short-doc "wash the animals")
;; (doc-args <animals> ...)
;; (options (soap)))
;; (help
;; (short-doc "print help")))
;; (default-help-option #t)
;; (default-help-command #f)
;; (require-command #t))
;;
(define-library (schemepunk command)
(export parse-options parse-app run-application
app-help command-help app-usage command-usage
command-error?)
(import (scheme base)
(scheme process-context)
(scheme char)
(scheme read)
(scheme write)
(schemepunk syntax)
(schemepunk list)
(schemepunk function)
(schemepunk string)
(schemepunk show base)
(schemepunk show columnar)
(schemepunk show color))
(begin
(define (conf-get alist key)
(match (assv key alist)
((_ x) x)
((_ . x) x)
(else #f)))
(define (conf-get-list alist key)
(match (assv key alist)
((_ . (? pair? x)) x)
((_ . x) (list x))
(else '())))
(define command-error-marker (list 'command-error))
(define (command-error? err)
(and (error-object? err)
(pair? (error-object-irritants err))
(eq? command-error-marker (car (error-object-irritants err)))))
(define (fail . fmts)
(error (apply show #f fmts)
command-error-marker
(each-in-list fmts)))
(define (run-application spec args proc)
(guard (err ((command-error? err)
(show (current-error-port)
(as-red (cadr (error-object-irritants err)))
fl
nl
(app-usage spec args))
(exit 1)))
(call-with-values
(λ() (parse-app spec args))
(chain proc
((if (conf-get spec 'default-help-command)
(λ proc
(λ(o a command co ca)
(case command
((help)
(match ca
((command)
(show (current-error-port)
(command-help spec command args)))
(else (fail (each "Expected command name after "
(as-bold "help")
".")))))
(else (proc o a command co ca)))))
identity)
_)
((if (conf-get spec 'default-help-option)
(λ proc
(λ(options a c co ca)
(if (conf-get options 'help)
(show (current-error-port) (app-help spec args))
(proc options a c co ca))))
identity)
_)))))
(define (spec-with-help spec)
(define options-spec (conf-get-list spec 'options))
(define commands-spec (conf-get-list spec 'commands))
(when (conf-get spec 'default-help-option)
(set! options-spec
(snoc options-spec
'(help (doc "Display this help and exit.")
(short #\h)))))
(when (conf-get spec 'default-help-command)
(set! commands-spec
(snoc commands-spec
'(help (short-doc "Display help and options for a command.")
(doc-args <command>)))))
(map
(λ((k . v))
(case k
((options) (cons k options-spec))
((commands) (cons k commands-spec))
(else (cons k v))))
spec))
(define (parse-app spec args)
(define spec* (spec-with-help spec))
(define options-spec (conf-get-list spec* 'options))
(define commands-spec (conf-get-list spec* 'commands))
(define require-command (conf-get spec* 'require-command))
(let*-values
(((options extra-args command rest)
(parse-options options-spec commands-spec (cdr args)))
((command-spec)
(if command
(cdr (assv command commands-spec))
(if (and require-command
(not (and (conf-get spec 'default-help-option)
(conf-get options 'help))))
(fail "A command is required.")
#f)))
((command-options command-extra-args _1 _2)
(if command-spec
(parse-options (conf-get-list command-spec 'options) '() rest)
(values '() '() #f #f))))
(values options extra-args command command-options command-extra-args)))
(define (parse-options options-spec commands-spec args)
(let loop ((options '()) (extra-args '()) (rest args))
(match rest
(()
(values options (reverse extra-args) #f '()))
(("--" . all-args)
(values options (append (reverse extra-args) all-args) #f '()))
(((? (λ=> (string->symbol _) (assv _ commands-spec)) command) . rest)
(values options (reverse extra-args) (string->symbol command) rest))
(((? (λ=> (substring _ 0 2) (equal? _ "--")) option) . rest)
(match-let1 (opt rest)
(parse-long-option options-spec (string-drop option 2) rest)
(loop (cons opt options) extra-args rest)))
(("-" . rest)
(loop options (cons "-" extra-args) rest))
(((? (λ=> (substring _ 0 1) (equal? _ "-")) option) . rest)
(match-let1 (new-options rest)
(parse-short-option options-spec (string-drop option 1) rest)
(loop (append new-options options) extra-args rest)))
((arg . rest)
(loop options (cons arg extra-args) rest)))))
(define (parse-long-option options-spec option rest)
(define (has-alias? alias spec)
(member alias (conf-get-list (cdr spec) 'long)))
(define len (string-length option))
(define-values (before= after=)
(do ((i 0 (+ i 1)))
((or (is i >= len)
(is (string-ref option i) eqv? #\=))
(values (substring option 0 i)
(and (is i < len) (substring option (+ i 1) len))))))
(define option-spec
(or (assv (string->symbol before=) options-spec)
(find (is before= has-alias? _) options-spec)))
(if option-spec
(let1-values (value rest)
(parse-option-value (cdr option-spec)
(string-append "--" before=)
after=
rest)
(list (cons (car option-spec) value) rest))
(or
(and-let* (((equal? "no-" (substring before= 0 3)))
(neg-opt (string-drop before= 3))
(neg-spec
(or (assv (string->symbol neg-opt) options-spec)
(find (is neg-opt has-alias? _) options-spec))))
(case (or (conf-get (cdr neg-spec) 'type) 'boolean)
((boolean)
(let1-values (value rest)
(parse-option-value (cdr neg-spec)
(string-append "--" before=)
after=
rest)
(list (cons (car neg-spec) (not value)) rest)))
(else
(fail "Unrecognized option "
(as-bold "--" before=)
" (prefix 'no-' cannot be used with non-boolean option "
(as-bold "--" neg-opt)
")."))))
(fail "Unrecognized option " (as-bold "--" before=) "."))))
(define (parse-short-option options-spec option rest)
(define (has-alias? alias spec)
(member alias (conf-get-list (cdr spec) 'short)))
(chain (string->list option)
(pair-fold
(λ((ch . next) accum)
(match (find (is ch has-alias? _) options-spec)
((name . spec)
(cond
((null? next)
(let1-values (value new-rest)
(parse-option-value spec (string #\- ch) #f rest)
(set! rest new-rest)
(cons (cons name value) accum)))
((eqv? 'boolean (or (conf-get spec 'type) 'boolean))
(cons (cons name #t) accum))
(else
(fail "Missing value for option " (as-bold "-" ch) "."))))
(else
(fail "Unrecognized option " (as-bold "-" ch) "."))))
'()
_)
(list _ rest)))
(define (parse-option-value option-spec option-name after= rest)
(define flag? (eqv? 'boolean (or (conf-get option-spec 'type) 'boolean)))
(define value-string
(or after=
(and (not flag?)
(pair? rest)
(or (is (string-length (car rest)) < 2)
(isnt (string-ref (car rest) 0) eqv? #\-))
(let1 x (car rest)
(set! rest (cdr rest))
x))))
(cond
(value-string
(match (parse-value (or (conf-get option-spec 'type) 'boolean)
value-string)
((val #f) (values val rest))
((_ err) (fail "Bad value for option "
(as-bold option-name)
": "
err
", got "
(as-bold (written value-string))
"."))))
(flag?
(values #t rest))
(else
(fail "Missing value for option " (as-bold option-name) "."))))
(define (parse-value type str)
(match type
(('list el)
(let1-values (vals errs) (chain str
(string-split _ ",")
(map (cut parse-value el <>) _)
(unzip2 _))
(list vals (find string? errs))))
('boolean
(chain str
(string-downcase _)
(member _ '("0" "no" "off" "false" "#f" "#false"))
(not _)
(list _ #f)))
((or 'integer 'number 'real)
(let1 n (string->number str)
(list n
(cond
((not n) "expected a number")
((and (eq? type 'integer) (not (integer? n))) "expected an integer")
((and (eq? type 'real) (not (real? n))) "expected a real number")
(else #f)))))
('symbol
(list (string->symbol str) #f))
('char
(if (= 1 (string-length str))
(list (string-ref str 0) #f)
(list #f "expected a single character")))
('sexp
(list (guard (exn (else (list #f "expected a Scheme S-expression")))
(with-input-from-string str read))
#f))
(else
(list str #f))))
(define (long-option->string name doc-value)
(string-append
"--"
name
(if doc-value (string-append "=" doc-value) "")))
(define (short-option->string name doc-value)
(string-append
(string #\- name)
(if doc-value (string-append " " doc-value) "")))
(define (option->string option-spec separator)
(define type
(or (conf-get (cdr option-spec) 'type) 'boolean))
(define doc-value
(or (chain-and (conf-get (cdr option-spec) 'doc-value)
(show #f _))
(and (not (eqv? 'boolean type))
(format #f "<~a>" type))))
(string-join
(append
(map (cut short-option->string <> doc-value)
(conf-get-list (cdr option-spec) 'short))
(list (long-option->string (symbol->string (car option-spec))
doc-value))
(map (λ=> (format #f "~a" _) (long-option->string _ doc-value))
(conf-get-list (cdr option-spec) 'long)))
separator))
(define (app-help spec args)
(define name (conf-get spec 'name))
(define doc (conf-get spec 'doc))
(define copyright (conf-get spec 'copyright))
(each
(if name
(each (as-bold (wrapped name)) fl nl)
nothing)
(if doc
(each (wrapped doc) fl nl)
nothing)
(app-usage spec args)
(if copyright
(each fl nl (as-gray (wrapped copyright)))
nothing)
fl))
(define (command-help spec command args)
(define command-spec
(conf-get-list (conf-get-list spec 'commands)
(if (string? command)
(string->symbol command)
command)))
(define doc (conf-get command-spec 'doc))
(define copyright (conf-get spec 'copyright))
(each
(as-bold command)
fl
nl
(if doc
(each (wrapped doc) fl nl)
nothing)
(command-usage spec command args)
(if copyright
(each fl nl (as-gray (wrapped copyright)))
nothing)
fl))
(define (app-usage spec args)
(define spec* (spec-with-help spec))
(define executable (if (pair? args) (car args) "app"))
(define options-spec (conf-get-list spec* 'options))
(define commands-spec (conf-get-list spec* 'commands))
(define documented-options (filter (λ=> (cdr _) (assv 'doc _)) options-spec))
(fn (string-width)
(each
(as-bold "Usage:")
nl
nl
(collapsed-if-one-line
(columnar
(string-width executable) (each executable)
" "
(each
(wrapped/list
(map (λ=> (option->string _ " | ") (format #f "[~a]" _))
options-spec))
fl
(wrapped/list
(append
(map (cut show #f <>) (conf-get-list spec 'doc-args))
(if (pair? commands-spec)
(if (conf-get spec 'require-command)
'("<command>" "<args>" "...")
'("[<command> <args> ...]"))
'()))))))
(if (pair? documented-options)
(each
fl
nl
(as-bold "Options:")
nl
nl
(joined
(λ option-spec
(each
(as-light-white
(wrapped (option->string option-spec ", ")))
fl
(columnar
" "
(wrapped (conf-get (cdr option-spec) 'doc)))))
documented-options
fl))
nothing)
(if (pair? commands-spec)
(each
fl
nl
(as-bold "Commands:")
nl
nl
(let1 width (fold max 0
(map (compose string-width symbol->string car) commands-spec))
(joined
(λ((command . spec))
(columnar width 'right (as-light-white command)
3 (as-gray " - ")
(wrapped (or (conf-get spec 'short-doc)
(conf-get spec 'doc)
""))))
commands-spec
fl)))
nothing)
fl)))
(define (command-usage spec command args)
(define executable (if (pair? args) (car args) "app"))
(define command-spec
(conf-get-list (conf-get-list spec 'commands)
(if (string? command)
(string->symbol command)
command)))
(define options-spec (conf-get-list command-spec 'options))
(define documented-options (filter (λ=> (cdr _) (assv 'doc _)) options-spec))
(fn (string-width)
(each
(as-bold "Usage:")
nl
nl
(collapsed-if-one-line
(columnar
(+ (string-width executable)
1
(string-width (if (symbol? command)
(symbol->string command)
command)))
(each executable " " command)
" "
(each
(wrapped/list
(map (λ=> (option->string _ " | ") (format #f "[~a]" _))
options-spec))
fl
(wrapped/list
(map (cut show #f <>) (conf-get-list command-spec 'doc-args))))))
(if (pair? documented-options)
(each
fl
nl
(as-bold "Options:")
nl
nl
(joined
(λ option-spec
(each
(as-light-white
(wrapped (option->string option-spec ", ")))
fl
(columnar
" "
(wrapped (conf-get (cdr option-spec) 'doc)))))
documented-options
fl))
nothing)
fl)))))
| false |
2821f2ca8bfa0fb328ef30dcb9e38e2051d30591
|
b0c1935baa1e3a0b29d1ff52a4676cda482d790e
|
/tests/r5rs_pitfall.scm
|
f5e2fb0636990f3faad76dbd69419c1a017f8980
|
[
"MIT"
] |
permissive
|
justinethier/husk-scheme
|
35ceb8f763a10fbf986340cb9b641cfb7c110509
|
1bf5880b2686731e0870e82eb60529a8dadfead1
|
refs/heads/master
| 2023-08-23T14:45:42.338605 | 2023-05-17T00:30:56 | 2023-05-17T00:30:56 | 687,620 | 239 | 28 |
MIT
| 2023-05-17T00:30:07 | 2010-05-26T17:02:56 |
Haskell
|
UTF-8
|
Scheme
| false | false | 10,233 |
scm
|
r5rs_pitfall.scm
|
; From: http://sisc-scheme.org/r5rs_pitfall.php
;
; This file may be run directly from the command line:
;
; ./huski scm-unit-tests/r5rs_pitfall.scm
;
;; r5rs_pitfalls.scm
;;
;; This program attempts to test a Scheme implementation's conformance
;; to various subtle edge-cases and consequences of the R5RS Scheme standard.
;; Code was collected from public forums, and is hereby placed in the public domain.
;;
;;
(define-syntax should-be
(syntax-rules ()
((_ test-id value expression)
(let ((return-value expression))
(if (not (equal? return-value value))
(for-each (lambda (v) (display v))
`("Failure: " test-id ", expected '"
value "', got '" ,return-value "'." #\newline))
(for-each (lambda (v) (display v))
'("Passed: " test-id #\newline)))))))
(define call/cc call-with-current-continuation)
;; Section 1: Proper letrec implementation
;;Credits to Al Petrofsky
;; In thread:
;; defines in letrec body
;; http://groups.google.com/groups?selm=87bsoq0wfk.fsf%40app.dial.idiom.com
(should-be 1.1 0
(let ((cont #f))
(letrec ((x (call-with-current-continuation (lambda (c) (set! cont c) 0)))
(y (call-with-current-continuation (lambda (c) (set! cont c) 0))))
(if cont
(let ((c cont))
(set! cont #f)
(set! x 1)
(set! y 1)
(c 0))
(+ x y)))))
;;Credits to Al Petrofsky
;; In thread:
;; Widespread bug (arguably) in letrec when an initializer returns twice
;; http://groups.google.com/groups?selm=87d793aacz.fsf_-_%40app.dial.idiom.com
(should-be 1.2 #t
(letrec ((x (call/cc list)) (y (call/cc list)))
(cond ((procedure? x) (x (pair? y)))
((procedure? y) (y (pair? x))))
(let ((x (car x)) (y (car y)))
(and (call/cc x) (call/cc y) (call/cc x)))))
;;Credits to Alan Bawden
;; In thread:
;; LETREC + CALL/CC = SET! even in a limited setting
;; http://groups.google.com/groups?selm=19890302162742.4.ALAN%40PIGPEN.AI.MIT.EDU
(should-be 1.3 #t
(letrec ((x (call-with-current-continuation
(lambda (c)
(list #t c)))))
(if (car x)
((cadr x) (list #f (lambda () x)))
(eq? x ((cadr x))))))
;; Section 2: Proper call/cc and procedure application
;;Credits to Al Petrofsky, (and a wink to Matthias Blume)
;; In thread:
;; Widespread bug in handling (call/cc (lambda (c) (0 (c 1)))) => 1
;; http://groups.google.com/groups?selm=87g00y4b6l.fsf%40radish.petrofsky.org
(should-be 2.1 1
(call/cc (lambda (c) (0 (c 1)))))
;; Section 3: Hygienic macros
;; Eli Barzilay
;; In thread:
;; R5RS macros...
;; http://groups.google.com/groups?selm=skitsdqjq3.fsf%40tulare.cs.cornell.edu
(should-be 3.1 4
(let-syntax ((foo
(syntax-rules ()
((_ expr) (+ expr 1)))))
(let ((+ *))
(foo 3))))
;; Al Petrofsky again
;; In thread:
;; Buggy use of begin in r5rs cond and case macros.
;; http://groups.google.com/groups?selm=87bse3bznr.fsf%40radish.petrofsky.org
(should-be 3.2 2
(let-syntax ((foo (syntax-rules ()
((_ var) (define var 1)))))
(let ((x 2))
(begin (define foo +))
(cond (else (foo x)))
x)))
;;Al Petrofsky
;; In thread:
;; An Advanced syntax-rules Primer for the Mildly Insane
;; http://groups.google.com/[email protected]
(should-be 3.3 1
(let ((x 1))
(let-syntax
((foo (syntax-rules ()
((_ y) (let-syntax
((bar (syntax-rules ()
((_) (let ((x 2)) y)))))
(bar))))))
(foo x))))
;; Al Petrofsky
;; Contributed directly
(should-be 3.4 1
(let-syntax ((x (syntax-rules ()))) 1))
;; Setion 4: No identifiers are reserved
;;(Brian M. Moore)
;; In thread:
;; shadowing syntatic keywords, bug in MIT Scheme?
;; http://groups.google.com/groups?selm=6e6n88%248qf%241%40news.cc.ukans.edu
(should-be 4.1 '(x)
((lambda lambda lambda) 'x))
(should-be 4.2 '(1 2 3)
((lambda (begin) (begin 1 2 3)) (lambda lambda lambda)))
(should-be 4.3 #f
(let ((quote -)) (eqv? '1 1)))
;; Section 5: #f/() distinctness
;; Scott Miller
(should-be 5.1 #f
(eq? #f '()))
(should-be 5.2 #f
(eqv? #f '()))
(should-be 5.3 #f
(equal? #f '()))
;; Section 6: string->symbol case sensitivity
;; Jens Axel S?gaard
;; In thread:
;; Symbols in DrScheme - bug?
;; http://groups.google.com/groups?selm=3be55b4f%240%24358%24edfadb0f%40dspool01.news.tele.dk
(should-be 6.1 #f
(eq? (string->symbol "f") (string->symbol "F")))
;; Section 7: First class continuations
;; Scott Miller
;; No newsgroup posting associated. The gist of this test and 7.2
;; is that once captured, a continuation should be unmodified by the
;; invocation of other continuations. This test determines that this is
;; the case by capturing a continuation and setting it aside in a temporary
;; variable while it invokes that and another continuation, trying to
;; side effect the first continuation. This test case was developed when
;; testing SISC 1.7's lazy CallFrame unzipping code.
(define r #f)
(define a #f)
(define b #f)
(define c #f)
(define i 0)
(should-be 7.1 28
(let ()
(set! r (+ 1 (+ 2 (+ 3 (call/cc (lambda (k) (set! a k) 4))))
(+ 5 (+ 6 (call/cc (lambda (k) (set! b k) 7))))))
(if (not c)
(set! c a))
(set! i (+ i 1))
(case i
((1) (a 5))
((2) (b 8))
((3) (a 6))
((4) (c 4)))
r))
;; Same test, but in reverse order
(define r #f)
(define a #f)
(define b #f)
(define c #f)
(define i 0)
(should-be 7.2 28
(let ()
(set! r (+ 1 (+ 2 (+ 3 (call/cc (lambda (k) (set! a k) 4))))
(+ 5 (+ 6 (call/cc (lambda (k) (set! b k) 7))))))
(if (not c)
(set! c a))
(set! i (+ i 1))
(case i
((1) (b 8))
((2) (a 5))
((3) (b 7))
((4) (c 4)))
r))
;; Credits to Matthias Radestock
;; Another test case used to test SISC's lazy CallFrame routines.
(should-be 7.3 '((-1 4 5 3)
(4 -1 5 3)
(-1 5 4 3)
(5 -1 4 3)
(4 5 -1 3)
(5 4 -1 3))
(let ((k1 #f)
(k2 #f)
(k3 #f)
(state 0))
(define (identity x) x)
(define (fn)
((identity (if (= state 0)
(call/cc (lambda (k) (set! k1 k) +))
+))
(identity (if (= state 0)
(call/cc (lambda (k) (set! k2 k) 1))
1))
(identity (if (= state 0)
(call/cc (lambda (k) (set! k3 k) 2))
2))))
(define (check states)
(set! state 0)
(let* ((res '())
(r (fn)))
(set! res (cons r res))
(if (null? states)
res
(begin (set! state (car states))
(set! states (cdr states))
(case state
((1) (k3 4))
((2) (k2 2))
((3) (k1 -)))))))
(map check '((1 2 3) (1 3 2) (2 1 3) (2 3 1) (3 1 2) (3 2 1)))))
;; Modification of the yin-yang puzzle so that it terminates and produces
;; a value as a result. (Scott G. Miller)
(should-be 7.4 '(10 9 8 7 6 5 4 3 2 1 0)
(let ((x '())
(y 0))
(call/cc
(lambda (escape)
(let* ((yin ((lambda (foo)
(set! x (cons y x))
(if (= y 10)
(escape x)
(begin
(set! y 0)
foo)))
(call/cc (lambda (bar) bar))))
(yang ((lambda (foo)
(set! y (+ y 1))
foo)
(call/cc (lambda (baz) baz)))))
(yin yang))))))
;; Miscellaneous
;;Al Petrofsky
;; In thread:
;; R5RS Implementors Pitfalls
;; http://groups.google.com/[email protected]
(should-be 8.1 -1
(let - ((n (- 1))) n))
(should-be 8.2 '(1 2 3 4 1 2 3 4 5)
(let ((ls (list 1 2 3 4)))
(append ls ls '(5))))
;; This example actually illustrates a bug in R5RS. If a Scheme system
;; follows the letter of the standard, 1 should be returned, but
;; the general agreement is that 2 should instead be returned.
;; The reason is that in R5RS, let-syntax always introduces new scope, thus
;; in the following test, the let-syntax breaks the definition section
;; and begins the expression section of the let.
;;
;; The general agreement by the implementors in 1998 was that the following
;; should be possible, but isn't:
;;
;; (define ---)
;; (let-syntax (---)
;; (define ---)
;; (define ---))
;; (define ---)
;;
;; Scheme systems based on the Portable syntax-case expander by Dybvig
;; and Waddell do allow the above, and thus often violate the letter of
;; R5RS. In such systems, the following will produce a local scope:
;;
;; (define ---)
;; (let-syntax ((a ---))
;; (let ()
;; (define ---)
;; (define ---)))
;; (define ---)
;;
;; Credits to Matthias Radestock and thanks to R. Kent Dybvig for the
;; explanation and background
(should-be 8.3 1
(let ((x 1))
(let-syntax ((foo (syntax-rules () ((_) 2))))
(define x (foo))
3)
x))
;;Not really an error to fail this (Matthias Radestock)
;;If this returns (0 1 0), your map isn't call/cc safe, but is probably
;;tail-recursive. If its (0 0 0), the opposite is true.
(let ((result
(let ()
(define executed-k #f)
(define cont #f)
(define res1 #f)
(define res2 #f)
(set! res1 (map (lambda (x)
(if (= x 0)
(call/cc (lambda (k) (set! cont k) 0))
0))
'(1 0 2)))
(if (not executed-k)
(begin (set! executed-k #t)
(set! res2 res1)
(cont 1)))
res2)))
(if (equal? result '(0 0 0))
(display "Map is call/cc safe, but probably not tail recursive or inefficient.")
(display "Map is not call/cc safe, but probably tail recursive and efficient."))
(newline))
| true |
1f1ccfaa1fd31cec8178f02c40ab3e1a78e9c59c
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/mscorlib/system/security/cryptography/rsapkcs1-sha1-signature-description.sls
|
97ab2021a97a94039f348ad1493a6e7709503acc
|
[] |
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 | 961 |
sls
|
rsapkcs1-sha1-signature-description.sls
|
(library (system
security
cryptography
rsapkcs1-sha1-signature-description)
(export new
is?
rsapkcs1-sha1-signature-description?
create-deformatter)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new
System.Security.Cryptography.RSAPKCS1SHA1SignatureDescription
a
...)))))
(define (is? a)
(clr-is
System.Security.Cryptography.RSAPKCS1SHA1SignatureDescription
a))
(define (rsapkcs1-sha1-signature-description? a)
(clr-is
System.Security.Cryptography.RSAPKCS1SHA1SignatureDescription
a))
(define-method-port
create-deformatter
System.Security.Cryptography.RSAPKCS1SHA1SignatureDescription
CreateDeformatter
(System.Security.Cryptography.AsymmetricSignatureDeformatter
System.Security.Cryptography.AsymmetricAlgorithm)))
| true |
eaed599a6b9c5f13dd77a5b5983a37d5a66ea51e
|
1a66dbeff3b9755e408b1bf0a14dbb58b44c8c6a
|
/file/tex.scm
|
3a2bfb4125a4737f92b4c240c59c69c8f8f64c04
|
[
"BSD-2-Clause"
] |
permissive
|
tabe/Gauche-TeX
|
4a135f0aa9f67d0e6154b982b79c72dcba9cb2de
|
7707821fbffbdc7c7ffc98d6e2d71bb190cdf925
|
refs/heads/master
| 2016-09-08T02:39:30.238074 | 2009-07-15T18:38:28 | 2009-07-15T18:38:28 | 252,063 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 7,675 |
scm
|
tex.scm
|
;;;
;;; tex.scm
;;;
;;; Copyright (c) 2007 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.
;;;
;;; $Id$
(define-module file.tex
(use srfi-13)
(export-all))
(select-module file.tex)
;; Chapter 7: How TeX Reads What You Type
(define (catcode x)
(case x
((92) ; \
0) ; Escape character
((123) ; {
1) ; Beginning of group
((125) ; }
2) ; End of group
((36) ; $
3) ; Math Shift
((38) ; &
4) ; Alignment tab
((13) ; <return>
5) ; End of line
((35) ; #
6) ; Parameter
((94) ; ^
7) ; Superscript
((95) ; _
8) ; Subscript
((0) ; <null>
9) ; Ignored character
((32) ; <space>
10) ; Space
((65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122)
11) ; A, ..., Z and a, ..., z
((126) ; ~
13) ; Active character
((37) ; %
14) ; Comment character
((127) ; <delete>
15) ; Invalid character
(else
12)))
;; Chapter 8: The Characters You Type
(define (tex-masticate catcode iport)
(define (hexadecimal-code e f)
(logior (ash (if (<= 48 e 57)
(- e 48)
(- e 87))
4)
(if (<= 48 f 57)
(- f 48)
(- f 87))))
(define (replace-trio-or-quad c rest)
(and-let* (( (pair? rest))
(d (car rest))
( (= c d))
(est (cdr rest))
( (pair? est))
(e (car est))
(st (cdr est)))
(cond ((and-let* (( (or (<= 48 e 57) (<= 97 e 102)))
( (pair? st))
(f (car st))
( (or (<= 48 f 57) (<= 97 f 102))))
f)
=> (lambda (f)
(cons (hexadecimal-code e f) (cdr st))))
((<= 0 e 63)
(cons (+ e 64) st))
((<= 64 e 127)
(cons (- e 64) st))
(else
#f))))
(let lp ((result '())
(line (read-line iport)))
(cond ((eof-object? line)
(reverse result))
(else
(let ((ls (map char->integer (string->list (string-trim-right line #\space))))) ; number 32
;; insert a <return> at the right end of the line
(if (null? ls)
(set! ls '(13))
(set-cdr! (last-pair ls) '(13)))
(let ilp ((temp '())
(ls ls)
(state 'N))
(if (null? ls)
(lp (cons (reverse temp) result) (read-line iport))
(let ((c (car ls)))
(case (catcode c)
((0)
(let ilp0 ((name '())
(rest (cdr ls)))
(if (null? rest)
(ilp (cons (reverse name) temp) '() (if (null? name) 'M 'S))
(let ((d (car rest)))
(case (catcode d)
((7)
(let ((r (cdr rest)))
(cond ((replace-trio-or-quad d r)
=> (cut ilp0 name <>))
(else
(ilp (cons (list d) temp) r 'M)))))
((11)
(ilp0 (cons d name) (cdr rest)))
(else
(if (null? name)
(ilp (cons (list d) temp) (cdr rest) 'M)
(ilp (cons (reverse name) temp) rest 'M))))))))
((7)
(let ((rest (cdr ls)))
(cond ((replace-trio-or-quad c rest)
=> (cut ilp temp <> state))
(else
(ilp (acons c 7 temp) rest 'M)))))
((10)
(case state
((N S)
(ilp temp (cdr ls) state))
((M)
(ilp (acons c 10 temp) (cdr ls) 'S))
(else
(error "unknown state" state))))
((1 2 3 4 6 8 11 12 13)
=> (lambda (code)
(ilp (acons c code temp) (cdr ls) 'M)))
((5)
(case state
((N)
(ilp (cons '(112 97 114) temp) (cdr ls) state)) ; par
((M)
(ilp (acons 32 10 temp) (cdr ls) 'S))
((S)
(ilp temp (cdr ls) state))
(else
(error "unknown state" state))))
((9)
(ilp temp (cdr ls) state))
((10)
(case state
((N S)
(ilp temp (cdr ls) state))
((M)
(ilp (acons c 10 temp) (cdr ls) 'S))
(else
(error "unknown state" state))))
((14)
(lp (cons (reverse temp) result) (read-line iport)))
((15)
(format (current-error-port) "a character of category 15 found: ~d\n" c)
(ilp temp (cdr ls) state))
(else
=> (cut error "unexpected catcode" <>)))))))))))
;; Chapter 20: Definitions (also called Macros)
;; pp. 212-
(define (tex-digest token-list)
token-list)
(provide "file/tex")
| false |
76e991405dd8a2537b99b72a16f23a36b6fefb6c
|
51861d4b51fc7692449550da7fd2e0035eabca30
|
/attic/probabilistic-backtracking-search/two-continuation/dfs/mk.scm
|
56786e1a16621a7225b1bb97cd35dc680784ce62
|
[
"MIT"
] |
permissive
|
stjordanis/probKanren
|
e611429b197e236c5df1a10369f6bfb4a167c2c7
|
00cd62c8211a8a210099c36be961b8927b298ce8
|
refs/heads/master
| 2020-09-18T20:53:33.468153 | 2015-10-20T21:40:23 | 2015-10-20T21:40:23 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 3,276 |
scm
|
mk.scm
|
(define-syntax rhs
(syntax-rules ()
((_ x) (cdr x))))
(define-syntax lhs
(syntax-rules ()
((_ x) (car x))))
(define-syntax size-s
(syntax-rules ()
((_ x) (length x))))
(define-syntax var
(syntax-rules ()
((_ x) (vector x))))
(define-syntax var?
(syntax-rules ()
((_ x) (vector? x))))
(define empty-s '())
(define ext-s
(lambda (x v s)
(cons `(,x . ,v) s)))
(define ext-s-check
(lambda (x v s)
(cond
((occurs-check x v s) #f)
(else (ext-s x v s)))))
(define occurs-check
(lambda (x v s)
(let ((v (walk v s)))
(cond
((var? v) (eq? v x))
((pair? v)
(or
(occurs-check x (car v) s)
(occurs-check x (cdr v) s)))
(else #f)))))
(define walk
(lambda (u S)
(cond
((and (var? u) (assq u S)) =>
(lambda (pr) (walk (rhs pr) S)))
(else u))))
(define walk*
(lambda (w s)
(let ((v (walk w s)))
(cond
((var? v) v)
((pair? v)
(cons
(walk* (car v) s)
(walk* (cdr v) s)))
(else v)))))
(define unify
(lambda (u v s)
(let ((u (walk u s))
(v (walk v s)))
(cond
((eq? u v) s)
((var? u) (ext-s-check u v s))
((var? v) (ext-s-check v u s))
((and (pair? u) (pair? v))
(let ((s (unify
(car u) (car v) s)))
(and s (unify
(cdr u) (cdr v) s))))
((equal? u v) s)
(else #f)))))
(define ==
(lambda (u v)
(lambda (sk fk s)
(let ((s (unify u v s)))
(if s
(sk fk s)
(fk))))))
(define disj
(lambda (g1 g2)
(lambda (sk fk s)
(g1 sk (lambda () (g2 sk fk s)) s))))
(define conj
(lambda (g1 g2)
(lambda (sk fk s)
(g1 (lambda (fk^ s^) (g2 sk fk^ s^)) fk s))))
(define disj* (lambda args (disj*-aux args)))
(define conj* (lambda args (conj*-aux args)))
(define disj*-aux
(lambda (g*)
(cond
((null? g*) fail)
((null? (cdr g*)) (car g*))
(else (disj (car g*) (disj*-aux (cdr g*)))))))
(define conj*-aux
(lambda (g*)
(cond
((null? g*) succeed)
((null? (cdr g*)) (car g*))
(else (conj (car g*) (conj*-aux (cdr g*)))))))
(define-syntax fresh
(syntax-rules ()
[(_ (x* ...) g g* ...)
(let ((x* (var 'x*)) ...)
(conj* g g* ...))]))
(define-syntax conde
(syntax-rules ()
[(_ (g0 g0* ...) (g* g** ...) ...)
(disj* (conj* g0 g0* ...) (conj* g* g** ...) ...)]))
(define-syntax run*
(syntax-rules ()
[(_ (x) g g* ...)
(let ((x (var 'x)))
((fresh () g g* ...)
(lambda (fk s) (cons (reify x s) (fk)))
(lambda () '())
empty-s))]))
(define reify-s
(lambda (v s)
(let ((v (walk v s)))
(cond
((var? v)
(ext-s v (reify-name (size-s s)) s))
((pair? v) (reify-s (cdr v)
(reify-s (car v) s)))
(else s)))))
(define reify-name
(lambda (n)
(string->symbol
(string-append "_" "." (number->string n)))))
(define reify
(lambda (v s)
(let ((v (walk* v s)))
(walk* v (reify-s v empty-s)))))
(define succeed
(lambda (sk fk s)
(sk fk s)))
(define fail
(lambda (sk fk s)
(fk)))
| true |
a9772ed5261253a19536254c36d63e62033721d7
|
03e4064a7a55b5d00937e74cddb587ab09cf7af9
|
/nscheme/old/old-5/lib/hash.scm
|
473a3c35b370bc544ca253c6974de03e92c2ffd6
|
[
"BSD-2-Clause"
] |
permissive
|
gregr/ina
|
29f28396cd47aa443319147ecde5235d11e1c3d1
|
16188050caa510899ae22ff303a67897985b1c3b
|
refs/heads/master
| 2023-08-25T13:31:44.131598 | 2023-08-14T16:46:48 | 2023-08-14T16:46:48 | 40,606,975 | 17 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 582 |
scm
|
hash.scm
|
((provide hash))
;; TODO: define general and maybe rolling hash functions.
;; For simplicity start with FNV-1a.
;; Maybe define a rolling variant using + instead of xor.
;; hash-null
;; hash-boolean
;; hash-char
;; hash-number
;; hash-string
;; hash-pair
;; hash-vector
(define (hash d)
((cond ((null? d) hash-null)
((boolean? d) hash-boolean)
((char? d) hash-char)
((number? d) hash-number)
((string? d) hash-string)
((pair? d) hash-pair)
((vector? d) hash-vector)
(#t (error '"cannot hash:" d))) d))
| false |
89ff398fb01c5cc6101f0194a667f00b6b43a8b8
|
a4d6eeda1e8e80653fb874bd04883c212f19a9fb
|
/pass/generators.ss
|
f9afaa84c32d2d3947c491a996fed1575a7d85e2
|
[] |
no_license
|
mml/incr
|
a199ff01f41238775730fceb75db41d86045017a
|
5b9657dcecc9474ee88c2b78369374f2dc0bcd38
|
refs/heads/master
| 2023-01-01T12:32:36.980967 | 2020-10-27T11:17:13 | 2020-10-27T11:17:13 | 282,290,358 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,742 |
ss
|
generators.ss
|
#lang racket
(provide tmp unique-variable unique-box)
(define tmp
(let ()
(define i 0)
(lambda ()
(let ([n i])
(set! i (add1 i))
(string->symbol
(string-append "tmp" (number->string n)))))))
(define unique-variable
(let ()
(define i 0)
(lambda (x)
(let ([n i])
(set! i (add1 i))
(string->symbol
(string-append (symbol->string x) "." (number->string n)))))))
(define unique-box
(let()
(define i 0)
(define (ni)
(let ([n i])
(set! i (add1 i))
n))
(define (internal-ubox sym)
(string->symbol
(string-append
(symbol->string sym)
".ubox"
(number->string (ni)))))
(lambda (sym)
(let ([char* (string->list (symbol->string sym))])
(let loop ([seendot #f] [rchar* (reverse char*)] [suffix '()])
(cond
[(null? rchar*) (internal-ubox sym)]
[seendot
(string->symbol
(string-append
(list->string (reverse rchar*))
".box"
(list->string suffix)))]
[(eq? #\. (car rchar*))
(loop #t (cdr rchar*) suffix)]
[(char-numeric? (car rchar*))
(loop #f (cdr rchar*) (cons (car rchar*) suffix))]
[else (internal-ubox sym)]))))))
(module+ test
(require rackunit)
(check-eq? (unique-box 'a.20) 'a.box20)
(check-eq? (unique-box '.a.25) '.a.box25)
(check-eq? (unique-box 'a.b.30) 'a.b.box30)
(check-eq? (unique-box '.a.b.35) '.a.b.box35)
(check-eq? (unique-box 'a) 'a.ubox0)
(check-eq? (unique-box 'a.b) 'a.b.ubox1)
(check-eq? (unique-box '.a) '.a.ubox2)
)
| false |
b1a56b6b4d055563ea39cb1baa79ecf552182cd9
|
958488bc7f3c2044206e0358e56d7690b6ae696c
|
/scheme/digital/transistor.scm
|
0eefac72572d2e882898aacec10cce62cad0e254
|
[] |
no_license
|
possientis/Prog
|
a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4
|
d4b3debc37610a88e0dac3ac5914903604fd1d1f
|
refs/heads/master
| 2023-08-17T09:15:17.723600 | 2023-08-11T12:32:59 | 2023-08-11T12:32:59 | 40,361,602 | 3 | 0 | null | 2023-03-27T05:53:58 | 2015-08-07T13:24:19 |
Coq
|
UTF-8
|
Scheme
| false | false | 6,094 |
scm
|
transistor.scm
|
(load "wire.scm")
;; This connects three wires called 'gate' 'source' and 'drain'
;; to a MOS transistor of given 'type' (#f or #t).
;;
;; When type = #t the transistor is an n-type transistor
;; This means that the gate wire needs to be in state #t in order
;; for the connection between source and drain to be established.
;;
;; When type = #f the transistor is a p-type transistor
;; This means that the gate wire needs to be in state #f in order
;; for the connection between source and drain to be established.
;;
;; When three wires are connected to a transistor, their respective
;; states are subject to constraints which need to be met. This is
;; implemented by adding three actions (one action for each wire)
;; on the wires' actions list (those actions which are executed
;; following a change of state in a wire). The three actions
;; are described as follows:
;;
;; drain-action:
;; This is the action to be added to the drain's actions list
;; This action will be executed on a drain change of state
;; This action reads the current state of the gate wire,
;; and provided it has the right value (depending on type)
;; it communicates the new drain signal to the source wire
;; as if both wires were connected.
;;
;; source-action:
;; This is the action to be added to the source's actions list
;; This action will be executed on a source change of state
;; This action reads the current state of the gate wire,
;; and provided it has the right value (depending on type)
;; it communicates the new source signal to the drain wire
;; as if both wires were connected.
;;
;; gate-action:
;; This is the action to be added to the gate's actions list
;; This action will be executed on a gate change of state
;; This action reads the new gate signal. The effect of the
;; new gate signal is either the establishment of a connection
;; between drain and source, or the removal of such connection.
;; In the first case, this action will communicate the drain
;; signal to the source and the source signal to the drain.
;; In the second case, this action will notify both the drain
;; and source wires that the transistor relinquishes any claim
;; to impose the current value of their states.
(define transistor ;; makes a transitor object, duly connected to wires
;; type = #t for an n-type transistor
;; type = #f for a p-type transistor
;;
;; static private data
(let ((time-fast 1) ; time for propagation of cancel actions
(time-slow 3) ; time for propagation of ownership actions
;;
;; static private members
(init-tag
(lambda (gate source drain type)
(let ((str (if (eq? type #t) "n" "p")))
(string->symbol
(string-append
str
"-tr-"
(symbol->string (gate 'get-tag))
"-"
(symbol->string (source 'get-tag))
"-"
(symbol->string (drain 'get-tag))))))))
;;
(lambda (gate source drain type)
;;
;; private data
(define tag '())
;;
;; public interface
(define (dispatch m)
(cond ((eq? m 'get-tag) tag)
(else (display "transistor: unknown operation error\n"))))
;;
;; private members
;;
;; new action to be carried out by the drain wire on a change of state
(define (drain-action)
(if (not (eq? (source 'get-signal) (drain 'get-signal)))
(if (eq? type (gate 'get-signal))
(let ((action
(lambda ()
(if (not (eq? (drain 'get-signal) (source 'get-signal)))
((source 'set-signal!) (drain 'get-signal) dispatch)))))
((global 'add-event!) time-fast action)))))
;;
;; new action to be carried out by the source wire on a change of state
(define (source-action)
(if (not (eq? (source 'get-signal) (drain 'get-signal)))
(if (eq? type (gate 'get-signal))
(let ((action
(lambda ()
(if (not (eq? (drain 'get-signal) (source 'get-signal)))
((drain 'set-signal!) (source 'get-signal) dispatch)))))
((global 'add-event!) time-fast action)))))
;;
;; new action to be carried out by the gate wire on a change of state
(define (gate-action)
(if (eq? type (gate 'get-signal))
(begin
(if (not (eq? (drain 'get-signal) (source 'get-signal)))
(let ((action
(lambda()
(if (not (eq? (drain 'get-signal) (source 'get-signal)))
(begin
((drain 'set-signal!) (source 'get-signal) dispatch)
((source 'set-signal!) (drain 'get-signal) dispatch))))))
((global 'add-event!) time-slow action))))
(begin
(let ((action
(lambda()
(if (not (eq? '() (drain 'get-signal)))
((drain 'set-signal!) '() dispatch))
(if (not (eq? '() (source 'get-signal)))
((source 'set-signal!) '() dispatch)))))
((global 'add-event!) time-fast action)))))
; (define (gate-action)
; (let ((action
; (lambda ()
; (if (eq? type (gate 'get-signal))
; (begin
; ((drain 'set-signal!) (source 'get-signal) dispatch)
; ((source 'set-signal!)(drain 'get-signal) dispatch))
; (begin
; ((drain 'set-signal!) '() dispatch)
; ((source 'set-signal!) '() dispatch)))))
; (time-delay (if (eq? type (gate 'get-signal)) time-slow time-fast)))
; ((global 'add-event!) time-delay action)))
;; initialize tag and adding new actions to respective wires
(set! tag (init-tag gate source drain type))
((gate 'add-action!) gate-action)
((source 'add-action!) source-action)
((drain 'add-action!) drain-action)
;;
;; returning public message passing interface
dispatch)))
(define (n-transistor gate source drain)
(transistor gate source drain #t))
(define (p-transistor gate source drain)
(transistor gate source drain #f))
| false |
c91dea16933588477b2bb1a356d96bf491aa6497
|
837a5fb8eb8418ed50448b7cfbc049c807e1266d
|
/chicken-fileio-ptl.scm
|
23def38b4e086ceb46f849e4ac133ad4a880fbdd
|
[
"MIT"
] |
permissive
|
reddress/scheme-learning
|
afdcd358304e92ae4908ed752457fb4c3aaf0120
|
beaa20d25196ce3eb756dfb6a61898a96372f895
|
refs/heads/master
| 2016-09-13T12:57:20.854212 | 2016-05-18T19:45:35 | 2016-05-18T19:45:35 | 56,538,721 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 113 |
scm
|
chicken-fileio-ptl.scm
|
(define PATH "c:/Users/Heitor/Desktop/emacs-24.3/bin/scheme-learning/")
(load (string-append PATH "hello.scm"))
| false |
04334249013798746823e86c6957b351af93372d
|
ffb2e7c6951bb43c61fb5142c94f95f8b2ed5ffa
|
/Assignment 1/1-test.ss
|
7d9726f27280184ea2cca606f6d1f30c7fe75bfb
|
[] |
no_license
|
shahdk/SchemeInterpreter
|
6dd97d9ddf085947876eb569aab953c0dc1fef50
|
8a2035e658e862ab3c185fe362c2dd62ca46950a
|
refs/heads/master
| 2021-01-10T19:51:02.159237 | 2014-06-12T01:04:44 | 2014-06-12T01:04:44 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,668 |
ss
|
1-test.ss
|
(define (test-interval-contains?)
(and (equal? (interval-contains? '(5 8) 6) #t)
(equal? (interval-contains? '(5 8) 5) #t)
(equal? (interval-contains? '(5 8) 4) #f)
(equal? (interval-contains? '(5 5) 14) #f)
(equal? (interval-contains? '(5 5) 5) #t)))
(define (test-interval-intersects?)
(and (equal? (interval-intersects? '(1 4) '(2 5)) #t)
(equal? (interval-intersects? '(1 4) '(4 5)) #t)
(equal? (interval-intersects? '(2 5) '(1 14)) #t)
(equal? (interval-intersects? '(1 14) '(2 5)) #t)
(equal? (interval-intersects? '(1 3) '(12 17)) #f)
(equal? (interval-intersects? '(12 17) '(1 3)) #f)))
(define (test-last)
(and (equal? (last '(1 5 2 4)) 4)
(equal? (last '(c)) 'c)))
(define (test-all-but-last)
(and (equal? (all-but-last '(1 5 2 4)) '(1 5 2))
(equal? (all-but-last '(c)) '())))
(define (test-replace)
(and (equal? (replace 5 7 '()) '())
(equal? (replace 5 7 '(1 5 2 5 4)) '(1 7 2 7 4))
(equal? (replace 5 7 '(7 5 7 5 7)) '(7 7 7 7 7))
(equal? (replace 5 7 '(1 3 2 6 4)) '(1 3 2 6 4))))
(define (test-remove-first)
(and (equal? (remove-first 'b '(a b c b d)) '(a c b d))
(equal? (remove-first 'b '(a c d)) '(a c d))
(equal? (remove-first 'b '(a c b d)) '(a c d))
(equal? (remove-first 'b '()) '())))
(define (test-remove-last)
(and (equal? (remove-last 'b '(a b c b d)) '(a b c d))
(equal? (remove-last 'b '(a c d)) '(a c d))
(equal? (remove-last 'b '(a c b d)) '(a c d))
(equal? (remove-last 'b '(a b c b d b e b f)) '(a b c b d b e f))
(equal? (remove-last 'b '(b a b c b d)) '(b a b c d))))
| false |
aafe6f1a0dbe1d85c57b049cd17850edd6c0364d
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/System.Xml/mono/xml/dtdelement-declaration.sls
|
62d01779c8413fbeb17f9b3221c33329db2e1ec4
|
[] |
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,587 |
sls
|
dtdelement-declaration.sls
|
(library (mono xml dtdelement-declaration)
(export is?
dtdelement-declaration?
name-get
name-set!
name-update!
is-empty?-get
is-empty?-set!
is-empty?-update!
is-any?-get
is-any?-set!
is-any?-update!
is-mixed-content?-get
is-mixed-content?-set!
is-mixed-content?-update!
content-model
attributes)
(import (ironscheme-clr-port))
(define (is? a) (clr-is Mono.Xml.DTDElementDeclaration a))
(define (dtdelement-declaration? a)
(clr-is Mono.Xml.DTDElementDeclaration a))
(define-field-port
name-get
name-set!
name-update!
(property:)
Mono.Xml.DTDElementDeclaration
Name
System.String)
(define-field-port
is-empty?-get
is-empty?-set!
is-empty?-update!
(property:)
Mono.Xml.DTDElementDeclaration
IsEmpty
System.Boolean)
(define-field-port
is-any?-get
is-any?-set!
is-any?-update!
(property:)
Mono.Xml.DTDElementDeclaration
IsAny
System.Boolean)
(define-field-port
is-mixed-content?-get
is-mixed-content?-set!
is-mixed-content?-update!
(property:)
Mono.Xml.DTDElementDeclaration
IsMixedContent
System.Boolean)
(define-field-port
content-model
#f
#f
(property:)
Mono.Xml.DTDElementDeclaration
ContentModel
Mono.Xml.DTDContentModel)
(define-field-port
attributes
#f
#f
(property:)
Mono.Xml.DTDElementDeclaration
Attributes
Mono.Xml.DTDAttListDeclaration))
| false |
ddcc284b54db113385f62d20504b8bdb5208dc54
|
ae4938300d7eea07cbcb32ea4a7b0ead9ac18e82
|
/list/permutation.sls
|
1ce4fb30d76bd1646cf8a8f57b8b3e5270a607cb
|
[] |
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 | 784 |
sls
|
permutation.sls
|
#!r6rs
(library (imi list permutation)
(export list-rotate-right
list-rotate-left
list-combinations)
(import (rnrs)
(imi sugar list-let)
(imi list processing))
(define (list-rotate-right ls amount)
(list-rotate-left ls (- (length ls)
amount)))
(define (list-rotate-left ls amount)
(list-let (end start) (list-split-at* ls
(mod amount
(length ls)))
(append start end)))
(define (list-combinations ls0 ls1)
(if (null? ls0)
'()
(append (map (lambda (e)
(cons (car ls0) e))
ls1)
(list-combinations (cdr ls0) ls1))))
)
| false |
f0eb831cf04a1653542364d0be87086926ebed7d
|
a8216d80b80e4cb429086f0f9ac62f91e09498d3
|
/lib/srfi/143/fixnum.scm
|
c68e4a6089bb24094d184d7ae8c183a0265b1463
|
[
"BSD-3-Clause"
] |
permissive
|
ashinn/chibi-scheme
|
3e03ee86c0af611f081a38edb12902e4245fb102
|
67fdb283b667c8f340a5dc7259eaf44825bc90bc
|
refs/heads/master
| 2023-08-24T11:16:42.175821 | 2023-06-20T13:19:19 | 2023-06-20T13:19:19 | 32,322,244 | 1,290 | 223 |
NOASSERTION
| 2023-08-29T11:54:14 | 2015-03-16T12:05:57 |
Scheme
|
UTF-8
|
Scheme
| false | false | 1,318 |
scm
|
fixnum.scm
|
(define fx=? =)
(define fx<? <)
(define fx>? >)
(define fx<=? <=)
(define fx>=? >=)
(define fxzero? zero?)
(define fxpositive? positive?)
(define fxnegative? negative?)
(define fxodd? odd?)
(define fxeven? even?)
(define fxmax max)
(define fxmin min)
(define fx+ +)
(define fx- -)
(define fx* *)
(define fxquotient quotient)
(define fxremainder remainder)
(define fxabs abs)
(define fxsquare square)
(define fxsqrt exact-integer-sqrt)
(define fx-width
(if (fixnum? (expt 2 32)) 62 30))
(define fx-greatest
(- (expt 2 fx-width) 1))
(define fx-least
(- -1 fx-greatest))
(define (fxneg x) (- x))
(define (fx+/carry i j k)
(let ((s (+ i j k)))
(call-with-values (lambda () (balanced/ s (expt 2 fx-width)))
(lambda (q r) (values r q)))))
(define (fx-/carry i j k)
(let ((d (- i j k)))
(call-with-values (lambda () (balanced/ d (expt 2 fx-width)))
(lambda (q r) (values r q)))))
(define (fx*/carry i j k)
(let ((s (+ (* i j) k)))
(call-with-values (lambda () (balanced/ s (expt 2 fx-width)))
(lambda (q r) (values r q)))))
(define fxarithmetic-shift-left fxarithmetic-shift)
(define (fxarithmetic-shift-right i count)
(fxarithmetic-shift i (- count)))
(define (fxbit-set? index i)
(or (bit-set? index i)
(and (negative? i)
(>= index (fxlength i)))))
| false |
0f0e2cca5510305dc58af40959665d34baf89ef6
|
fca62d08480d0db43627f51449b9caea48295601
|
/sources/units/compare.scm
|
ff7ee60b1b0d42a605d2211d9f67a6d4a84cf65f
|
[
"MIT"
] |
permissive
|
alxbnct/Schemings
|
aa4783cca04b4a393972ead754cd3e2ce89bf193
|
a7c322ee37bf9f43b696c52fc290488aa2dcc238
|
refs/heads/master
| 2023-06-01T02:06:38.441543 | 2021-06-12T15:27:28 | 2021-06-12T15:27:28 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 4,942 |
scm
|
compare.scm
|
(import srfi-1)
(import srfi-69)
(import (chicken sort))
(declare (unit compare))
(declare (uses list))
;; encapsulates compare results
(define-typed-record compare-results
(added-elements (list-of *))
(changed-elements (list-of *))
(unchanged-elements (list-of *))
(deleted-elements (list-of *)))
;; compares two sets of elements
;; elements are matched according to their id
(: compare-elements
(forall (e1 e2 k) (
(list-of e1) (e1 -> k)
(list-of e2) (e2 -> k)
(e1 e2 -> boolean)
(e2 -> *) (e1 e2 -> *) (e1 e2 -> *) (e1 -> *) ->
(struct compare-results))))
(define
(compare-elements
original-elements
original-element-id-procedure
current-elements
current-element-id-procedure
element-changed?-procedure
make-added-element-procedure
make-changed-element-procedure
make-unchanged-element-procedure
make-deleted-element-procedure)
;; make a hash table for each set of elements
(let ((original-elements-hash-table (make-hash-table = number-hash))
(current-elements-hash-table (make-hash-table = number-hash)))
;; provide a unique negative id
;; for any element that does not have one
(let ((first-original-elements-negative-id
(- 0 (length original-elements) (length current-elements)))
(first-current-elements-negative-id
(- 0 (length current-elements))))
;; adds elements to a hash table
(letrec*
((hash-elements
(lambda (elements hash-table element-id-procedure next-unique-id)
(unless (null? elements)
(let* ((element (car elements))
(element-id (element-id-procedure element)))
(if element-id
(hash-table-set! hash-table element-id element)
(hash-table-set! hash-table next-unique-id element))
(hash-elements
(cdr elements)
hash-table element-id-procedure
(+ next-unique-id 1)))))))
;; hash the original elements
(hash-elements
original-elements
original-elements-hash-table
original-element-id-procedure
first-original-elements-negative-id)
;; hash the current elements
(hash-elements
current-elements
current-elements-hash-table
current-element-id-procedure
first-current-elements-negative-id)
;; get the list of distinct elements id
(let* ((original-elements-id (hash-table-keys original-elements-hash-table))
(current-elements-id (hash-table-keys current-elements-hash-table))
(appended-elements-id (append original-elements-id current-elements-id))
(elements-id (sort (list-distinct-values appended-elements-id identity) <)))
;; compare the hash table elements
;; for every element id
(let* ((compare-element
(lambda (element-id)
(let ((original-element
(hash-table-ref/default original-elements-hash-table element-id #f))
(current-element
(hash-table-ref/default current-elements-hash-table element-id #f)))
(cond ((not original-element)
(cons
(make-added-element-procedure current-element)
'added))
((not current-element)
(cons
(make-deleted-element-procedure original-element)
'deleted))
((element-changed?-procedure original-element current-element)
(cons
(make-changed-element-procedure original-element current-element)
'changed))
(else
(cons
(make-unchanged-element-procedure original-element current-element)
'unchanged))))))
(compare-results
(map compare-element elements-id)))
;; filters the compare results
;; matching a state
(let ((filter-compare-results
(lambda (status)
(map car
(filter
(lambda (compare-result)
(eq? (cdr compare-result) status))
compare-results)))))
;; make the compare results
(make-compare-results
(filter-compare-results 'added)
(filter-compare-results 'changed)
(filter-compare-results 'unchanged)
(filter-compare-results 'deleted)))))))))
| false |
b589d6cd5a8ecf7eb56f11b0a361264b5da83a68
|
c63772c43d0cda82479d8feec60123ee673cc070
|
/ch3/07.scm
|
4f5ec89d435d97548a7fca2d36faf3e6d4ee010e
|
[
"Apache-2.0"
] |
permissive
|
liuyang1/sicp-ans
|
26150c9a9a9c2aaf23be00ced91add50b84c72ba
|
c3072fc65baa725d252201b603259efbccce990d
|
refs/heads/master
| 2021-01-21T05:02:54.508419 | 2017-09-04T02:48:46 | 2017-09-04T02:48:52 | 14,819,541 | 2 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,111 |
scm
|
07.scm
|
(define (make-account balance init-pwd)
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount))
balance)
(define (error-password amount)
"Incorrect password")
(define (dispatch pwd m)
(cond ((not (eq? pwd init-pwd)) error-password)
((eq? m 'withdraw) withdraw)
((eq? m 'deposit) deposit)
(else (error "unkown request" m))))
dispatch)
; 3.7
(define (make-joint account pwd joint-pwd)
(define (error-password amount)
"Incorrect password")
(define (dispatch inputpwd m)
(cond ((eq? inputpwd joint-pwd) (account pwd m))
(else error-password)))
dispatch)
; test code
(define acc (make-account 100 'password))
(display ((acc 'password 'withdraw) 50))
(newline)
(display ((acc 'password 'deposit) 50))
(newline)
(define paul-acc
(make-joint acc 'password 'jointpwd))
(display ((paul-acc 'jointpwd 'withdraw) 10))
(newline)
(display ((paul-acc 'fakepwd 'withdraw) 10))
(newline)
| false |
937bb14778aa75089cc854b1733a0df0c1bb7cb7
|
ae76253c0b7fadf8065777111d3aa6b57383d01b
|
/chap4/exec-4.36.ss
|
cdf0276c3353d3be2ef4c5a41d6949072af1047c
|
[] |
no_license
|
cacaegg/sicp-solution
|
176995237ad1feac39355f0684ee660f693b7989
|
5bc7df644c4634adc06355eefa1637c303cf6b9e
|
refs/heads/master
| 2021-01-23T12:25:25.380872 | 2014-04-06T09:35:15 | 2014-04-06T09:35:15 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 895 |
ss
|
exec-4.36.ss
|
(define (require p)
(if (not p) (amb)))
(define (an-integer-between low high)
(require (< low high))
(amb low (an-integer-between (+ low 1) high)))
(define (a-pythagorean-triple-between low high)
(let ((i (an-integer-between low high)))
(let ((j (an-integer-between i high)))
(let ((k (an-integer-between j high)))
(require (= (+ (* i i) (* j j)) (* k k)))
(list i j k)))))
; It's due to some branch will terminate as soon as it find an answer.
; However, there might be other answer within that branch.
;
; Hence, we can put an amb after list answer to get backtrack.
(define (a-pythagorean-triple-between low high)
(let ((i (an-integer-between low high)))
(let ((j (an-integer-between i high)))
(let ((k (an-integer-between j high)))
(require (= (+ (* i i) (* j j)) (* k k)))
(display (list i j k))(newline)
(amb)))))
| false |
d32b8e9a52befaf2b42fc49de4dee68d95991c43
|
0d084b2c1cb254ac40ace745f059c7336cb84f72
|
/prelude/list-comprehensions.scm
|
b807bb6cffbad98c90072c3631518d4edb8df8e3
|
[] |
no_license
|
redentis/programming-praxis
|
0d30227936d9435d64fdf44cd25b62ffb9de1692
|
a42d00d5302db5864d0dfe06937ebc68a5d94212
|
refs/heads/master
| 2016-09-06T15:04:56.935040 | 2014-11-28T10:32:06 | 2014-11-28T10:32:06 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,061 |
scm
|
list-comprehensions.scm
|
(define-syntax fold-of
(syntax-rules (range in is)
((_ "z" f b e)
(set! b (f b e)))
((_ "z" f b e (v range first past stop) c ...)
(let* ((x first) (p past) (s stop)
(le? (if (positive? s) <= >=)))
(do ((v x (+ v s))) ((le? p v) b)
(fold-of "z" f b e c ...))))
((_ "z" f b e (v range first past) c ...)
(let* ((x first) (p past) (s (if (< x p) 1 -1)))
(fold-of "z" f b e (v range x p s) c ...)))
((_ "z" f b e (v range past) c ...)
(fold-of "z" f b e (v range 0 past) c ...))
((_ "z" f b e (x in xs) c ...)
(do ((t xs (cdr t))) ((null? t) b)
(let ((x (car t)))
(fold-of "z" f b e c ...))))
((_ "z" f b e (x is y) c ...)
(let ((x y)) (fold-of f b e c ...)))
((_ "z" f b e p? c ...)
(if p? (fold-of "z" f b e c ...)))
((_ f i e c ...) ; main entry point, the other syntax rules are internal
(let ((b i)) (fold-of "z" f b e c ...)))))
(define-syntax list-of
(syntax-rules ()
((_ arg ...) (reverse (fold-of (lambda (d a) (cons a d)) '() arg ...)))))
| true |
861fe3ed01430df5ecec140f2ef2758ab05349ea
|
b4e3e2194fcb5722ff6b0022831348ef5d36daeb
|
/io.scm
|
d1ffbaa89ce8eb965086218882082e6e3664e380
|
[] |
no_license
|
nyaago/my-scheme-learning
|
3adf46cf99c8579d05f483851e30732912b2faa2
|
e1ccca44f577ba26a3a85532ba171ad7a4669425
|
refs/heads/master
| 2021-01-10T05:47:09.311306 | 2015-06-05T15:42:59 | 2015-06-05T15:42:59 | 36,940,789 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 923 |
scm
|
io.scm
|
;(print (write-to-string '(1 "abc" "\"" #\z )))
(define (write-to-string x )
(call-with-output-string
(lambda (out) (write x out) )
)
)
(define (read-from-string x)
(call-with-input-string x
(lambda (in) (read in) )
)
)
;;
;(print (write-to-string '(1 "abc" "\"" #\z )))
;(define x (write-to-string '(1 "abc" "\"" #\z )))
;(print (read-from-string x) )
(define (write-tree tree port . separator)
(cond [(pair? tree)
(write-tree (car tree) port )
(write-tree (cdr tree) port) ]
[(null? tree)]
[else (display tree port)] ;要素
)
)
(define (tree->string tree)
(call-with-output-string
(lambda (out) (write-tree tree out) )
)
)
;(define t (cons (cons "cat" "dog") "bear") )
;(write-tree t (current-output-port))
;(print (write-to-string '(1 2 3 )))
;(define x (write-to-string '(1 2 3 )))
;(print (read-from-string x) )
| false |
5e789b4606b58bfa3c5ccb57b884ebdcce4e7e86
|
7e0c613b8a2781aab692a5976b0e8896ac18b4fb
|
/tests/aes.sps
|
c9338e2548a52e81780e27a62858883649fd3d00
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
atomontage/industria
|
f279fb71cc69032cc4084c1e2f09bfacefe2fc6c
|
f13b067ce3b8b82f09c5670a45dfde29da29c5fb
|
refs/heads/master
| 2021-01-22T12:13:08.369334 | 2019-05-26T18:07:25 | 2019-05-26T18:07:25 | 24,039,099 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 13,792 |
sps
|
aes.sps
|
#!/usr/bin/env scheme-script
;; -*- mode: scheme; coding: utf-8 -*- !#
;; Copyright © 2009, 2010, 2011, 2018 Göran Weinholt <[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.
#!r6rs
(import (industria bytevectors)
(industria crypto aes)
(srfi :64 testing)
(rnrs))
;;; Appendix A in FIPS-197
(test-begin "aes-appendix-a")
(test-equal '#(#x2b7e1516 #x28aed2a6 #xabf71588 #x09cf4f3c
#xa0fafe17 #x88542cb1 #x23a33939 #x2a6c7605 #xf2c295f2
#x7a96b943 #x5935807a #x7359f67f #x3d80477d #x4716fe3e
#x1e237e44 #x6d7a883b #xef44a541 #xa8525b7f #xb671253b
#xdb0bad00 #xd4d1c6f8 #x7c839d87 #xcaf2b8bc #x11f915bc
#x6d88a37a #x110b3efd #xdbf98641 #xca0093fd #x4e54f70e
#x5f5fc9f3 #x84a64fb2 #x4ea6dc4f #xead27321 #xb58dbad2
#x312bf560 #x7f8d292f #xac7766f3 #x19fadc21 #x28d12941
#x575c006e #xd014f9a8 #xc9ee2589 #xe13f0cc8 #xb6630ca6)
(expand-aes-key
;; 128-bit key
#vu8(#x2b #x7e #x15 #x16 #x28 #xae #xd2 #xa6 #xab #xf7 #x15 #x88 #x09 #xcf #x4f #x3c)))
(test-equal '#(#x8e73b0f7 #xda0e6452 #xc810f32b #x809079e5 #x62f8ead2 #x522c6b7b
#xfe0c91f7 #x2402f5a5 #xec12068e #x6c827f6b #x0e7a95b9 #x5c56fec2
#x4db7b4bd #x69b54118 #x85a74796 #xe92538fd #xe75fad44 #xbb095386
#x485af057 #x21efb14f #xa448f6d9 #x4d6dce24 #xaa326360 #x113b30e6
#xa25e7ed5 #x83b1cf9a #x27f93943 #x6a94f767 #xc0a69407 #xd19da4e1
#xec1786eb #x6fa64971 #x485f7032 #x22cb8755 #xe26d1352 #x33f0b7b3
#x40beeb28 #x2f18a259 #x6747d26b #x458c553e #xa7e1466c #x9411f1df
#x821f750a #xad07d753 #xca400538 #x8fcc5006 #x282d166a #xbc3ce7b5
#xe98ba06f #x448c773c #x8ecc7204 #x01002202)
(expand-aes-key
;; 192-bit key
#vu8(#x8e #x73 #xb0 #xf7 #xda #x0e #x64 #x52 #xc8 #x10 #xf3 #x2b
#x80 #x90 #x79 #xe5 #x62 #xf8 #xea #xd2 #x52 #x2c #x6b #x7b)))
(test-equal '#(#x603deb10 #x15ca71be #x2b73aef0 #x857d7781 #x1f352c07 #x3b6108d7 #x2d9810a3 #x0914dff4
#x9ba35411 #x8e6925af #xa51a8b5f #x2067fcde #xa8b09c1a #x93d194cd #xbe49846e #xb75d5b9a
#xd59aecb8 #x5bf3c917 #xfee94248 #xde8ebe96 #xb5a9328a #x2678a647 #x98312229 #x2f6c79b3
#x812c81ad #xdadf48ba #x24360af2 #xfab8b464 #x98c5bfc9 #xbebd198e #x268c3ba7 #x09e04214
#x68007bac #xb2df3316 #x96e939e4 #x6c518d80 #xc814e204 #x76a9fb8a #x5025c02d #x59c58239
#xde136967 #x6ccc5a71 #xfa256395 #x9674ee15 #x5886ca5d #x2e2f31d7 #x7e0af1fa #x27cf73c3
#x749c47ab #x18501dda #xe2757e4f #x7401905a #xcafaaae3 #xe4d59b34 #x9adf6ace #xbd10190d
#xfe4890d1 #xe6188d0b #x046df344 #x706c631e)
(expand-aes-key
;; 256-bit key
#vu8(#x60 #x3d #xeb #x10 #x15 #xca #x71 #xbe #x2b #x73 #xae #xf0 #x85 #x7d #x77 #x81
#x1f #x35 #x2c #x07 #x3b #x61 #x08 #xd7 #x2d #x98 #x10 #xa3 #x09 #x14 #xdf #xf4)))
(test-end)
;;; Appendix B in FIPS-197 - cipher example
(test-begin "aes-appendix-b")
(define (encrypt plaintext key)
(let ((ret (make-bytevector 16 0))
(sched (expand-aes-key key)))
(aes-encrypt! plaintext 0 ret 0 sched)
(clear-aes-schedule! sched)
ret))
(define (decrypt plaintext key)
(let ((ret (make-bytevector 16 0))
(sched (reverse-aes-schedule (expand-aes-key key))))
(aes-decrypt! plaintext 0 ret 0 sched)
(clear-aes-schedule! sched)
ret))
(test-equal #vu8(#x39 #x25 #x84 #x1d #x02 #xdc #x09 #xfb #xdc #x11 #x85 #x97 #x19 #x6a #x0b #x32)
(encrypt #vu8(#x32 #x43 #xf6 #xa8 #x88 #x5a #x30 #x8d #x31 #x31 #x98 #xa2 #xe0 #x37 #x07 #x34)
#vu8(#x2b #x7e #x15 #x16 #x28 #xae #xd2 #xa6 #xab #xf7 #x15 #x88 #x09 #xcf #x4f #x3c)))
(test-equal #vu8(#x32 #x43 #xf6 #xa8 #x88 #x5a #x30 #x8d #x31 #x31 #x98 #xa2 #xe0 #x37 #x07 #x34)
(decrypt #vu8(#x39 #x25 #x84 #x1d #x02 #xdc #x09 #xfb #xdc #x11 #x85 #x97 #x19 #x6a #x0b #x32)
#vu8(#x2b #x7e #x15 #x16 #x28 #xae #xd2 #xa6 #xab #xf7 #x15 #x88 #x09 #xcf #x4f #x3c)))
(test-end)
;;; Appendix C in FIPS-197
(test-begin "aes-appendix-c")
(define-syntax test
(lambda (x)
(define (num->bv n len)
(let ((bv (make-bytevector (/ len 8))))
(bytevector-uint-set! bv 0 n (endianness big) (/ len 8))
bv))
(syntax-case x ()
((_ plaintext keylen key output)
(with-syntax ((pt (num->bv (syntax->datum #'plaintext) 128))
(k (num->bv (syntax->datum #'key) (syntax->datum #'keylen)))
(out (num->bv (syntax->datum #'output) 128)))
#'(begin (test-equal out (encrypt pt k))
(test-equal pt (decrypt (encrypt pt k) k))))))))
(test #x00112233445566778899aabbccddeeff
128 #x000102030405060708090a0b0c0d0e0f
#x69c4e0d86a7b0430d8cdb78070b4c55a)
(test #x00112233445566778899aabbccddeeff
192 #x000102030405060708090a0b0c0d0e0f1011121314151617
#xdda97ca4864cdfe06eaf70a0ec0d7191)
(test #x00112233445566778899aabbccddeeff
256 #x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f
#x8ea2b7ca516745bfeafc49904b496089)
(test-end)
;;; http://csrc.nist.gov/groups/ST/toolkit/examples.html
(test-begin "aes-examples")
(test #x6BC1BEE22E409F96E93D7E117393172A
128 #x2B7E151628AED2A6ABF7158809CF4F3C
#x3AD77BB40D7A3660A89ECAF32466EF97)
(test #xAE2D8A571E03AC9C9EB76FAC45AF8E51
128 #x2B7E151628AED2A6ABF7158809CF4F3C
#xF5D3D58503B9699DE785895A96FDBAAF)
(test #x30C81C46A35CE411E5FBC1191A0A52EF
128 #x2B7E151628AED2A6ABF7158809CF4F3C
#x43B1CD7F598ECE23881B00E3ED030688)
(test #xF69F2445DF4F9B17AD2B417BE66C3710
128 #x2B7E151628AED2A6ABF7158809CF4F3C
#x7B0C785E27E8AD3F8223207104725DD4)
(test #x6BC1BEE22E409F96E93D7E117393172A
192 #x8E73B0F7DA0E6452C810F32B809079E562F8EAD2522C6B7B
#xBD334F1D6E45F25FF712A214571FA5CC)
(test #xAE2D8A571E03AC9C9EB76FAC45AF8E51
192 #x8E73B0F7DA0E6452C810F32B809079E562F8EAD2522C6B7B
#x974104846D0AD3AD7734ECB3ECEE4EEF)
(test #x30C81C46A35CE411E5FBC1191A0A52EF
192 #x8E73B0F7DA0E6452C810F32B809079E562F8EAD2522C6B7B
#xEF7AFD2270E2E60ADCE0BA2FACE6444E)
(test #xF69F2445DF4F9B17AD2B417BE66C3710
192 #x8E73B0F7DA0E6452C810F32B809079E562F8EAD2522C6B7B
#x9A4B41BA738D6C72FB16691603C18E0E)
(test #x6BC1BEE22E409F96E93D7E117393172A
256 #x603DEB1015CA71BE2B73AEF0857D77811F352C073B6108D72D9810A30914DFF4
#xF3EED1BDB5D2A03C064B5A7E3DB181F8)
(test #xAE2D8A571E03AC9C9EB76FAC45AF8E51
256 #x603DEB1015CA71BE2B73AEF0857D77811F352C073B6108D72D9810A30914DFF4
#x591CCB10D410ED26DC5BA74A31362870)
(test #x30C81C46A35CE411E5FBC1191A0A52EF
256 #x603DEB1015CA71BE2B73AEF0857D77811F352C073B6108D72D9810A30914DFF4
#xB6ED21B99CA6F4F9F153E7B1BEAFED1D)
(test #xF69F2445DF4F9B17AD2B417BE66C3710
256 #x603DEB1015CA71BE2B73AEF0857D77811F352C073B6108D72D9810A30914DFF4
#x23304B7A39F9F3FF067D8D8F9E24ECC7)
(test-end)
;;; CTR mode from the above URL
(test-begin "aes-ctr")
(define (ctr ctr key)
(define pt #vu8(#x6b #xc1 #xbe #xe2 #x2e #x40 #x9f #x96 #xe9 #x3d #x7e #x11 #x73 #x93 #x17 #x2a
#xae #x2d #x8a #x57 #x1e #x03 #xac #x9c #x9e #xb7 #x6f #xac #x45 #xaf #x8e #x51
#x30 #xc8 #x1c #x46 #xa3 #x5c #xe4 #x11 #xe5 #xfb #xc1 #x19 #x1a #x0a #x52 #xef
#xf6 #x9f #x24 #x45 #xdf #x4f #x9b #x17 #xad #x2b #x41 #x7b #xe6 #x6c #x37 #x10))
(let ((ret (make-bytevector (bytevector-length pt))))
(aes-ctr! pt 0 ret 0 (bytevector-length ret) (expand-aes-key key) ctr)
ret))
(test-equal #vu8(#x87 #x4d #x61 #x91 #xb6 #x20 #xe3 #x26 #x1b #xef #x68 #x64 #x99 #x0d #xb6 #xce
#x98 #x06 #xf6 #x6b #x79 #x70 #xfd #xff #x86 #x17 #x18 #x7b #xb9 #xff #xfd #xff
#x5a #xe4 #xdf #x3e #xdb #xd5 #xd3 #x5e #x5b #x4f #x09 #x02 #x0d #xb0 #x3e #xab
#x1e #x03 #x1d #xda #x2f #xbe #x03 #xd1 #x79 #x21 #x70 #xa0 #xf3 #x00 #x9c #xee)
(ctr #xf0f1f2f3f4f5f6f7f8f9fafbfcfdfeff
#vu8(#x2b #x7e #x15 #x16 #x28 #xae #xd2 #xa6 #xab #xf7 #x15 #x88 #x09 #xcf #x4f #x3c)))
(test-equal #vu8(#x1a #xbc #x93 #x24 #x17 #x52 #x1c #xa2 #x4f #x2b #x04 #x59 #xfe #x7e #x6e #x0b
#x09 #x03 #x39 #xec #x0a #xa6 #xfa #xef #xd5 #xcc #xc2 #xc6 #xf4 #xce #x8e #x94
#x1e #x36 #xb2 #x6b #xd1 #xeb #xc6 #x70 #xd1 #xbd #x1d #x66 #x56 #x20 #xab #xf7
#x4f #x78 #xa7 #xf6 #xd2 #x98 #x09 #x58 #x5a #x97 #xda #xec #x58 #xc6 #xb0 #x50)
(ctr #xf0f1f2f3f4f5f6f7f8f9fafbfcfdfeff
#vu8(#x8e #x73 #xb0 #xf7 #xda #x0e #x64 #x52 #xc8 #x10 #xf3 #x2b #x80 #x90 #x79 #xe5
#x62 #xf8 #xea #xd2 #x52 #x2c #x6b #x7b)))
(test-equal #vu8(#x60 #x1e #xc3 #x13 #x77 #x57 #x89 #xa5 #xb7 #xa7 #xf5 #x04 #xbb #xf3 #xd2 #x28
#xf4 #x43 #xe3 #xca #x4d #x62 #xb5 #x9a #xca #x84 #xe9 #x90 #xca #xca #xf5 #xc5
#x2b #x09 #x30 #xda #xa2 #x3d #xe9 #x4c #xe8 #x70 #x17 #xba #x2d #x84 #x98 #x8d
#xdf #xc9 #xc5 #x8d #xb6 #x7a #xad #xa6 #x13 #xc2 #xdd #x08 #x45 #x79 #x41 #xa6)
(ctr #xf0f1f2f3f4f5f6f7f8f9fafbfcfdfeff
#vu8(#x60 #x3d #xeb #x10 #x15 #xca #x71 #xbe #x2b #x73 #xae #xf0 #x85 #x7d #x77 #x81
#x1f #x35 #x2c #x07 #x3b #x61 #x08 #xd7 #x2d #x98 #x10 #xa3 #x09 #x14 #xdf #xf4)))
(test-end)
;;; CBC tests from RFC3602
(test-begin "aes-cbc")
(define (cbc128 key iv pt)
(let ((ret (make-bytevector (bytevector-length pt)))
(scr (make-bytevector (bytevector-length pt))))
(aes-cbc-encrypt! pt 0 ret 0 (bytevector-length ret)
(expand-aes-key (uint->bytevector key))
(uint->bytevector iv))
(aes-cbc-decrypt! ret 0 scr 0 (bytevector-length ret)
(reverse-aes-schedule (expand-aes-key (uint->bytevector key)))
(uint->bytevector iv))
(list (bytevector=? scr pt)
(bytevector->uint ret))))
;; #1
(test-equal '(#t #xe353779c1079aeb82708942dbe77181a)
(cbc128 #x06a9214036b8a15b512e03d534120006
#x3dafba429d9eb430b422da802c9fac41
(string->utf8 "Single block msg")))
;; #2
(test-equal '(#t #xd296cd94c2cccf8a3a863028b5e1dc0a7586602d253cfff91b8266bea6d61ab1)
(cbc128 #xc286696d887c9aa0611bbb3e2025a45a
#x562e17996d093d28ddb3ba695a2e6f58
#vu8(#x00 #x01 #x02 #x03 #x04 #x05 #x06 #x07 #x08 #x09 #x0a #x0b #x0c #x0d #x0e #x0f #x10 #x11
#x12 #x13 #x14 #x15 #x16 #x17 #x18 #x19 #x1a #x1b #x1c #x1d #x1e #x1f)))
;; #3
(test-equal '(#t #xd0a02b3836451753d493665d33f0e8862dea54cdb293abc7506939276772f8d5021c19216bad525c8579695d83ba2684)
(cbc128 #x6c3ea0477630ce21a2ce334aa746c2cd
#xc782dc4c098c66cbd9cd27d825682c81
(string->utf8 "This is a 48-byte message (exactly 3 AES blocks)")))
;; #4
(test-equal '(#t #xc30e32ffedc0774e6aff6af0869f71aa0f3af07a9a31a9c684db207eb0ef8e4e35907aa632c3ffdf868bb7b29d3d46ad83ce9f9a102ee99d49a53e87f4c3da55)
(cbc128 #x56e47a38c5598974bc46903dba290349
#x8ce82eefbea0da3c44699ed7db51b7d9
#vu8(#xa0 #xa1 #xa2 #xa3 #xa4 #xa5 #xa6 #xa7 #xa8 #xa9 #xaa #xab #xac #xad #xae
#xaf #xb0 #xb1 #xb2 #xb3 #xb4 #xb5 #xb6 #xb7 #xb8 #xb9 #xba #xbb #xbc
#xbd #xbe #xbf #xc0 #xc1 #xc2 #xc3 #xc4 #xc5 #xc6 #xc7 #xc8 #xc9 #xca
#xcb #xcc #xcd #xce #xcf #xd0 #xd1 #xd2 #xd3 #xd4 #xd5 #xd6 #xd7 #xd8
#xd9 #xda #xdb #xdc #xdd #xde #xdf)))
;; CBC in-place
(let ((key (uint->bytevector #x6c3ea0477630ce21a2ce334aa746c2cd))
(iv (uint->bytevector #xc782dc4c098c66cbd9cd27d825682c81))
(pt (string->utf8 "This is a 48-byte message (exactly 3 AES blocks)"))
(ct (uint->bytevector #xd0a02b3836451753d493665d33f0e8862dea54cdb293abc7506939276772f8d5021c19216bad525c8579695d83ba2684)))
(aes-cbc-encrypt! pt 0 pt 0 (bytevector-length pt)
(expand-aes-key key)
(bytevector-copy iv))
(test-equal ct pt)
(aes-cbc-decrypt! pt 0 pt 0 (bytevector-length pt)
(reverse-aes-schedule (expand-aes-key key))
(bytevector-copy iv))
(test-equal "This is a 48-byte message (exactly 3 AES blocks)"
(utf8->string pt)))
(test-end)
(exit (if (zero? (test-runner-fail-count (test-runner-get))) 0 1))
| true |
a78718785397892c19603725181e5537c29c7b84
|
3ecee09e72582189e8a4a48b3d85447c7927142f
|
/static/now/std__error.scm
|
b931fce1f1c5949e9cd99e6e33af8a7763a5af36
|
[
"MIT"
] |
permissive
|
drewc/gx-quasar
|
6c745b9ec13c60ab6d1af8964a25ff14ceb4549b
|
17513967f611d46cc2d5a44999c90a7891e5d2d0
|
refs/heads/main
| 2023-02-02T17:01:12.011714 | 2020-12-18T22:18:19 | 2020-12-18T22:18:19 | 310,720,698 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,390 |
scm
|
std__error.scm
|
(declare (block) (standard-bindings) (extended-bindings))
(begin
(define std/error#<error>::display-exception
(lambda (_self36965_ _port36966_)
(call-with-parameters
(lambda ()
(let ((_$e36969_ (error-trace _self36965_)))
(if _$e36969_
((lambda (_where36972_) (display* _where36972_ '": "))
_$e36969_)
'#!void))
(display*
'"["
(let ((__tmp272540 (object-type _self36965_)))
(declare (not safe))
(##type-name __tmp272540))
'"] ")
(displayln (error-message _self36965_))
(let ((_irritants36974_ (error-irritants _self36965_)))
(if (null? _irritants36974_)
'#!void
(begin
(display '"--- irritants: ")
(for-each
(lambda (_obj36976_) (display* _obj36976_ '" "))
_irritants36974_)
(newline)))))
current-output-port
_port36966_)))
(bind-method!
error::t
'display-exception
std/error#<error>::display-exception
'#t)
(define std/error#io-error::t
(make-struct-type
'std/error#io-error::t
error::t
'0
'io-error
'()
'#f
'()))
(define std/error#io-error? (make-struct-predicate std/error#io-error::t))
(define std/error#make-io-error
(lambda _$args36839_
(apply make-struct-instance std/error#io-error::t _$args36839_)))
(define std/error#timeout-error::t
(make-struct-type
'std/error#timeout-error::t
error::t
'0
'timeout-error
'()
'#f
'()))
(define std/error#timeout-error?
(make-struct-predicate std/error#timeout-error::t))
(define std/error#make-timeout-error
(lambda _$args36836_
(apply make-struct-instance std/error#timeout-error::t _$args36836_)))
(define std/error#raise-io-error
(lambda (_where36832_ _what36833_ . _irritants36834_)
(raise (make-struct-instance
std/error#io-error::t
_what36833_
_irritants36834_
_where36832_))))
(define std/error#raise-timeout
(lambda (_where36828_ _what36829_ . _irritants36830_)
(raise (make-struct-instance
std/error#timeout-error::t
_what36829_
_irritants36830_
_where36828_)))))
| false |
13050e13099f7b02edb8322c79e8e1b25bf05d15
|
d8bdd07d7fff442a028ca9edbb4d66660621442d
|
/scam/tests/10-scheme/00-base/ZZ-rest/min.scm
|
55d28892169537e704b443fe7e2622b2db9f0e96
|
[] |
no_license
|
xprime480/scam
|
0257dc2eae4aede8594b3a3adf0a109e230aae7d
|
a567d7a3a981979d929be53fce0a5fb5669ab294
|
refs/heads/master
| 2020-03-31T23:03:19.143250 | 2020-02-10T20:58:59 | 2020-02-10T20:58:59 | 152,641,151 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 182 |
scm
|
min.scm
|
(import (only (scheme base) min)
(test narc))
(narc-label "Min")
(narc-expect
(-123 (min 123 -123))
(17.5 (min 42.01 17.5))
(-9.999 (min -5 -9.999)))
(narc-report)
| false |
962c44e99b756c66c20647e128b9dff064c2a6f7
|
3e2f30eba7bc37c77628f5b10229ec6e4a5bcda9
|
/lambda/number.ss
|
b09272807ca9f753adc7b92bbbbd04275988c732
|
[] |
no_license
|
luohaha/some-interpreters
|
ce88706578b56dcbca0b66ae7265ccc59fc4db48
|
be943da9b25f7d2694f478ace1c021ef38db3676
|
refs/heads/master
| 2020-04-06T07:54:27.051677 | 2016-08-25T04:48:34 | 2016-08-25T04:48:34 | 64,315,669 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 262 |
ss
|
number.ss
|
(define zero
(lambda (p)
(lambda (x)
x)))
(define one
(lambda (p)
(lambda (x)
(p x))))
(define two
(lambda (p)
(lambda (x)
(p (p x)))))
(define to-integer
(lambda (p)
((p (lambda (x) (+ x 1))) 0)))
(to-integer two)
| false |
b72ecd8ebdfc58c6cc81bd2d76dfe8510d588f17
|
f08220a13ec5095557a3132d563a152e718c412f
|
/logrotate/skel/usr/share/guile/2.0/ice-9/iconv.scm
|
125dad8b8100af643dc2218ed68144a738298bc2
|
[
"Apache-2.0"
] |
permissive
|
sroettger/35c3ctf_chals
|
f9808c060da8bf2731e98b559babd4bf698244ac
|
3d64486e6adddb3a3f3d2c041242b88b50abdb8d
|
refs/heads/master
| 2020-04-16T07:02:50.739155 | 2020-01-15T13:50:29 | 2020-01-15T13:50:29 | 165,371,623 | 15 | 5 |
Apache-2.0
| 2020-01-18T11:19:05 | 2019-01-12T09:47:33 |
Python
|
UTF-8
|
Scheme
| false | false | 3,735 |
scm
|
iconv.scm
|
;;; Encoding and decoding byte representations of strings
;; Copyright (C) 2013 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (ice-9 iconv)
#:use-module (rnrs bytevectors)
#:use-module (ice-9 binary-ports)
#:use-module ((ice-9 rdelim) #:select (read-string))
#:export (string->bytevector
bytevector->string
call-with-encoded-output-string))
;; Like call-with-output-string, but actually closes the port.
(define (call-with-output-string* proc)
(let ((port (open-output-string)))
(proc port)
(let ((str (get-output-string port)))
(close-port port)
str)))
(define (call-with-output-bytevector* proc)
(call-with-values (lambda () (open-bytevector-output-port))
(lambda (port get-bytevector)
(proc port)
(let ((bv (get-bytevector)))
(close-port port)
bv))))
(define* (call-with-encoded-output-string encoding proc
#:optional
(conversion-strategy 'error))
"Call PROC on a fresh port. Encode the resulting string as a
bytevector according to ENCODING, and return the bytevector."
(if (and (string-ci=? encoding "utf-8")
(eq? conversion-strategy 'error))
;; I don't know why, but this appears to be faster; at least for
;; serving examples/debug-sxml.scm (1464 reqs/s versus 850
;; reqs/s).
(string->utf8 (call-with-output-string* proc))
(call-with-output-bytevector*
(lambda (port)
(set-port-encoding! port encoding)
(if conversion-strategy
(set-port-conversion-strategy! port conversion-strategy))
(proc port)))))
;; TODO: Provide C implementations that call scm_from_stringn and
;; friends?
(define* (string->bytevector str encoding
#:optional (conversion-strategy 'error))
"Encode STRING according to ENCODING, which should be a string naming
a character encoding, like \"utf-8\"."
(if (and (string-ci=? encoding "utf-8")
(eq? conversion-strategy 'error))
(string->utf8 str)
(call-with-encoded-output-string
encoding
(lambda (port)
(display str port))
conversion-strategy)))
(define* (bytevector->string bv encoding
#:optional (conversion-strategy 'error))
"Decode the string represented by BV. The bytes in the bytevector
will be interpreted according to ENCODING, which should be a string
naming a character encoding, like \"utf-8\"."
(if (and (string-ci=? encoding "utf-8")
(eq? conversion-strategy 'error))
(utf8->string bv)
(let ((p (open-bytevector-input-port bv)))
(set-port-encoding! p encoding)
(if conversion-strategy
(set-port-conversion-strategy! p conversion-strategy))
(let ((res (read-string p)))
(close-port p)
(if (eof-object? res)
""
res)))))
| false |
38f811f443031aa6724103355bad1b80ede25569
|
d63c4c79d0bf83ae646d0ac023ee0528a0f4a879
|
/cs133/assn3/a3q4.ss
|
4e45e8aa75bb90e9076be041952f8eff640bb97d
|
[] |
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 | 1,167 |
ss
|
a3q4.ss
|
;; contract- substitute: num num lon -> lon
;; purpose- to consume 2 numbers - a target & replacement - and a list of numbers (lon), and produces a lon which is the input list with every occurrence of the target replaced by the replacement
;; e.g. (substitute 1 6 (cons 1 (cons 4 (cons 2 (cons 1 (cons 9 empty)))))) =>
;; (cons 6 (cons 4 (cons 2 (cons 6 (cons 9 empty)))))
;; (substitute 1 6 (cons 2 (cons 4 (cons 3 (cons 7 (cons 9 empty)))))) =>
;; (cons 2 (cons 4 (cons 3 (cons 7 (cons 9 empty)))))
(define (substitute target replacement numlist)
(cond
[(empty? numlist) empty]
[else
(cond
[(= target (first numlist)) (cons replacement (substitute target replacement (rest numlist)))]
[else (cons (first numlist) (substitute target replacement (rest numlist)))])]))
;; tests
(equal? (substitute 1 6 (cons 1 (cons 4 (cons 2 (cons 1 (cons 9 empty))))))
(cons 6 (cons 4 (cons 2 (cons 6 (cons 9 empty))))))
(equal? (substitute 1 6 (cons 2 (cons 4 (cons 3 (cons 7 (cons 9 empty))))))
(cons 2 (cons 4 (cons 3 (cons 7 (cons 9 empty))))))
| false |
83e19af8c8d1c663de7a79ddecd344c18c29f646
|
3508dcd12d0d69fec4d30c50334f8deb24f376eb
|
/etc/pack.scm
|
85a955d56744dce08f245bf555dec4abea4fe9b1
|
[] |
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 | 2,813 |
scm
|
pack.scm
|
#| -*-Scheme-*-
Copyright (c) 1992-93 Massachusetts Institute of Technology
This material was developed by the Scheme project at the Massachusetts
Institute of Technology, Department of Electrical Engineering and
Computer Science. Permission to copy this software, to redistribute
it, and to use it for any purpose is granted, subject to the following
restrictions and understandings.
1. Any copy made of this software must include this copyright notice
in full.
2. Users of this software agree to make their best efforts (a) to
return to the MIT Scheme project any improvements or extensions that
they make, so that these may be included in future releases; and (b)
to inform MIT of noteworthy uses of this software.
3. All materials developed as a consequence of the use of this
software shall duly acknowledge such use, in accordance with the usual
standards of acknowledging credit in academic research.
4. MIT has made no warrantee or representation that the operation of
this software will be error-free, and MIT is under no obligation to
provide any services, by way of maintenance, update, or otherwise.
5. In conjunction with products arising from the use of this material,
there shall be no use of the name of the Massachusetts Institute of
Technology nor of any adaptation thereof in any advertising,
promotional, or sales literature without prior written consent from
MIT in each case. |#
;;;; Binary file packer, to be loaded in (runtime load)
(declare (usual-integrations))
(define (pack-binaries output files-lists)
(if (null? files-lists)
(error:bad-range-argument files-lists 'PACK-BINARIES))
(with-binary-output-file (->pathname output)
(lambda (channel)
(channel-fasdump
(syntax
`((lambda (environment-to-load)
(load/push-hook!
(let ((pathname (current-load-pathname)))
(lambda ()
((access load-packed-binaries
(->environment '(runtime load)))
pathname
,(->namestring output)
,(length files-lists)
environment-to-load)))))
(the-environment))
system-global-syntax-table)
channel
#f)
(for-each
(lambda (files)
(with-working-directory-pathname (car files)
(lambda ()
(channel-fasdump (map (lambda (file)
(cons (->namestring file)
(fasload (->pathname file))))
(cdr files))
channel
#f))))
files-lists))))
(define (with-binary-output-file file action)
(with-binary-file-channel file action
open-binary-output-file
output-port/channel
'WITH-BINARY-OUTPUT-FILE))
(define channel-fasdump
(make-primitive-procedure 'PRIMITIVE-FASDUMP 3))
(if (not (environment-bound? system-global-environment 'PACK-BINARIES))
(environment-link-name system-global-environment
(the-environment)
'PACK-BINARIES))
| false |
6615789ebf795fcb65c76c3bac422695acb50315
|
434a6f6b2e788eae6f6609d02262f9c9819773a7
|
/day20/program-a.scm
|
5989aaa6bb8bb96b2491556e41d23fea2554e200
|
[] |
no_license
|
jakeleporte/advent-of-code-2020
|
978fc575d580c63386c53bb40fc14f24d5137be7
|
649292bf17feaccf572e02d4dad711d2c46d66cb
|
refs/heads/main
| 2023-02-07T22:29:08.479708 | 2021-01-03T01:16:22 | 2021-01-03T01:16:22 | 318,069,993 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,941 |
scm
|
program-a.scm
|
#!/usr/bin/env guile
!#
(use-modules (ice-9 rdelim) (ice-9 receive) (srfi srfi-1))
(define (read-tile)
"Read an array of characters from stdin and return the
tile id and the tile."
(define id 0)
(let ((line (read-line)))
(if (eof-object? line) (values #f #nil)
(begin
(set! id
(string->number (car (string-tokenize line char-set:digit))))
(let loop ((tile '()) (line (read-line)))
(if (or (eof-object? line) (string-null? line))
(values id (list->array 2 tile))
(loop (cons (string->list line) tile) (read-line))))))))
(define (read-tiles)
"Read tiles from stdin and return a hash table of ID: TILE"
(define tiles (make-hash-table))
(let loop ()
(receive (id tile) (read-tile)
(if (null? tile) tiles
(begin (hash-set! tiles id tile) (loop))))))
(define (edges tile)
"Build a list of 4 strings representing the four edges
of the given input TILE character array, in the order top, right,
bottom, left"
(define dims (array-dimensions tile))
(define t (transpose-array tile 1 0))
(define top (array-slice tile 0))
(define right (array-slice t (1- (cadr dims))))
(define bottom (array-slice tile (1- (car dims))))
(define left (array-slice t 0))
(map (compose list->string array->list) (list top bottom left right)))
(define (tiles->edges tiles)
"Return a hash table of id: list of tile edges"
(define tile-edges (make-hash-table))
(hash-for-each
(lambda (k v)
(hash-set! tile-edges k (edges v)))
tiles)
tile-edges)
(define (%neighbor tile-edges the-id the-edge)
"Given THE-EDGE from the tile with id THE-ID, search
TILE-EDGES for the corresponding edge"
(call/cc
(lambda (ret)
(hash-for-each
(lambda (id edges)
(when (not (= id the-id))
(for-each
(lambda (e)
(if (or (string=? the-edge e)
(string=? the-edge (string-reverse e)))
(ret id)))
edges)))
tile-edges)
#f)))
(define (edges->neighbors tile-edges)
"Given a hash table of TILE-EDGES, return a hash table of
id: List of neighbor ids (or #f if there is no neighbor on a side)"
(define neighbors (make-hash-table))
(hash-for-each
(lambda (id edges)
(hash-set! neighbors
id
(map (lambda (e) (%neighbor tile-edges id e)) edges)))
tile-edges)
neighbors)
(define (%corner? neighbor-ids)
"Return #t if the neighbor-id list represents a corner, else #f"
(= (length (filter identity neighbor-ids)) 2))
(define (corner-ids-product tiles)
"Build a product of ids representing the tiles that would
go in the corners if the tiles were arranged correctly, with matching
edges lined up."
(define neighbors (edges->neighbors (tiles->edges tiles)))
(define product 1)
(hash-for-each
(lambda (id neighbor-ids)
(when (%corner? neighbor-ids)
(set! product (* product id))))
neighbors)
product)
(define (main)
(let ((tiles (read-tiles)))
(display (corner-ids-product tiles)) (newline)))
(main)
| false |
23868ea794f7de8b8fdcae71ff6c5d3af0bc3c04
|
d2bea435baf97fe65d916ea403c6eb83d4da3b22
|
/scheme/e092.scm
|
2602b3bb4cd2b816877439347dcad6f88af1a9bb
|
[] |
no_license
|
tgallant/euler
|
751a88ab43209f5fd3e089ae67634a6822ec93a2
|
caa1a1c87738ac55fb78b0628ea9203f72945072
|
refs/heads/master
| 2021-01-21T01:57:00.882913 | 2016-07-13T01:27:49 | 2016-07-13T01:27:49 | 11,758,025 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 429 |
scm
|
e092.scm
|
(load "lib/helpers.scm")
;; e92
(define (chain x)
(let ((digit-square
(reduce + (map (lambda (w) (* w w)) (num->list x)))))
(cond
((= digit-square 89) #t)
((= digit-square 1) #f)
(else (chain digit-square)))))
(define (e92 x)
(define (inner y count)
(if (> y x)
count
(if (chain y)
(inner (+ y 1) (+ count 1))
(inner (+ y 1) count))))
(inner 1 0))
| false |
79ba08c43eaf07d2def29db4e40be6619855c23b
|
53cb8287b8b44063adcfbd02f9736b109e54f001
|
/ast/valdef-structs.scm
|
eb0dc88245b7535fcd6b1750aba3bb83c5bce49c
|
[] |
no_license
|
fiddlerwoaroof/yale-haskell-reboot
|
72aa8fcd2ab7346a4990795621b258651c6d6c39
|
339b7d85e940db0b8cb81759e44abbb254c54aad
|
refs/heads/master
| 2021-06-22T10:32:25.076594 | 2020-10-30T00:00:31 | 2020-10-30T00:00:31 | 92,361,235 | 3 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 7,856 |
scm
|
valdef-structs.scm
|
;;; File: ast/valdef-structs Author: John
;;; Ast structure for local declarations
;;; <decl> -> <signdecl>
;;; -> <valdef>
;;; decl contains value declarations and type signatures.(
;;; type related decls are topdecls and are separated from
;;; these decls.
(define-struct decl
(include ast-node))
;;; <signdecl> -> <vars> :: [<context> =>] <type>
;;;
;;; <vars> -> <var> , ... , <var>
;;;
(define-struct signdecl ; this affixes a signature to a list of variables
(include decl)
(predicate signdecl?)
(slots
(vars (type (list var-ref)))
(signature (type signature))))
;;; This is introduced into decl lists by dependency analysis
(define-struct recursive-decl-group
(include decl)
(slots
;; none of these are recursive decl groups
(decls (type (list decl)))
))
;;; <valdef> -> <lhs> = <exp> [where { <decls> [;] }]
;;; -> <lhs> <gdrhs> [where { <decls> [;] }]
;;;
;;; <lhs> -> <apat>
;;; -> <funlhs>
;;;
;;; <funlhs> -> <afunlhs>
;;; -> <pat> <varop> <pat>
;;; -> <lpat> <varop> <pat>
;;; -> <pat> <varop> <rpat>
;;;
;;; <afunlhs> -> <var> <apat>
;;; -> ( <funlhs> ) <apat> (infix operator with more than 2 args)
;;; -> <afunlhs> <apat> (multiple argument pattern)
(define-struct valdef ; this defines values.
(include decl)
(predicate valdef?)
(slots
;; this pattern contains all new variables defined.
;; For a function definition the pattern will always
;; be a simple variable.
(lhs (type pattern))
;; this is a list of right hand sides.
;; for a pattern definition, this list is always a singleton. For
;; a function definition, there is a member for every successive
;; alternative for the function.
(definitions (type (list single-fun-def)))
;; this is used internally by dependency analysis
(depend-val (type int) (uninitialized? #t))
;; this is filled in by the type phase
(dictionary-args (type (list var)) (uninitialized? #t))
;; used for defaulting
(module (type symbol) (default '|Prelude|))
))
(define-struct single-fun-def
(include ast-node)
(slots
;; this list is always empty for pattern definition
;; and always non-empty for function definition.
;; The length of this list is the arity of the function.
;; All single-fun-defs for a function have the same arity.
(args (type (list pattern)))
;; <gdrhs>, this contains a list of guard , expression pairs
(rhs-list (type (list guarded-rhs)))
;; this contains declarations local to the
;; single fun def. It scopes over the args. The
;; guarded-rhs may refer to these values.
(where-decls (type (list decl)))
;; true when declared in infix style. Used for printing
;; and to check precs in prec parsing.
(infix? (type bool) (bit #t))
))
;;; <gdrhs> -> <gd> = <exp> [<gdrhs>]
;;;
;;; <gd> -> | <exp>
(define-struct guarded-rhs ; a single guarded expression. A special expression
(include ast-node)
(slots
;; node - omitted-guard - is used when no guard given
(guard (type exp))
(rhs (type exp))))
;;; Some examples of the above:
;;; (a,b) | z>y = (z,y)
;;; | otherwise = (1,2)
;;; where z = x-2
;;;
;;; valdef:
;;; lhs = (a,b)
;;; definitions =
;;; [single-fun-def:
;;; args = []
;;; rhs-list = [guarded-rhs: guard = z>y
;;; rhs = (z,y),
;;; guarded-rhs: guard = otherwise
;;; rhs = (1,2)]
;;; where-decls = [valdef: lhs = z
;;; definitions =
;;; [single-fun-def:
;;; args = []
;;; rhs-list = [guarded-rhs:
;;; guard = omitted-guard
;;; exp = x-2]
;;; where-decls = []]]]
;;;
;;; fact 0 = 1
;;; fact (n+1) = (n+1)*fact n
;;;
;;; valdef:
;;; lhs = fact
;;; definitions =
;;; [single-fun-def:
;;; args = [0]
;;; rhs-list = [guarded-rhs: guard = omitted-guard
;;; rhs = 1]
;;; where-decls = [],
;;; single-fun-def:
;;; args = [n+1]
;;; rhs-list = [guarded-rhs: guard = omitted-guard
;;; rhs = (n+1)*fact n]
;;; where-decls = []]
;;; Definitions for patterns
;;; This is a simplification; the real syntax is complicated by
;;; rules for precedence and associativity.
;;;
;;; <pat> -> <pat> <conop> <pat> pcon
;;; -> <pat> + <integer> plus-pat
;;; -> - <integer-or-float> *** ??? const-pat?
;;; -> <apat>
;;; -> <con> <apat> .... <apat> pcon
;;;
;;; <apat> -> <var> var-pat
;;; -> <var> @ <apat> as-pat
;;; -> <con> *** ??? var-pat?
;;; -> <literal> const-pat
;;; -> _ wildcard-pat
;;; -> () pcon special case
;;; -> ( <pat> ) (grouping syntax)
;;; -> ( <pat> , ... , <pat> ) pcon special case
;;; -> [ <pat> , ... , <pat> ] list-pat
;;; -> ~ <apat> irr-pat
(define-struct pattern
(include ast-node))
(define-struct apat
(include pattern))
(define-struct as-pat ;; var@pat
(include apat)
(slots
(var (type var-ref))
(pattern (type pattern))))
(define-struct irr-pat ;; ~pat
(include apat)
(slots
(pattern (type pattern))))
(define-struct var-pat ;; v
(include apat)
(predicate var-pat?)
(slots
(var (type var-ref))))
(define-struct wildcard-pat ;; _
(include apat)
(predicate wildcard-pat?))
(define-struct const-pat ;; literal
(include apat)
(predicate const-pat?)
(slots
(value (type const))
;; this is the code that actually performs the match.
;; it's filled in by type phase.
(match-fn (type exp) (uninitialized? #t))))
(define-struct plus-pat ;; p+k
(include pattern)
(slots
(pattern (type pattern))
(k (type integer))
;; code to check for match, filled in by type phase
(match-fn (type exp) (uninitialized? #t))
;; code to bind result, filled in by type phase
(bind-fn (type exp) (uninitialized? #t))
))
(define-struct pcon ;; con pat1 pat2 ...
(include pattern) ;; pat1 con pat2
(predicate pcon?)
(slots
(name (type symbol))
(con (type def))
(pats (type (list pattern)))
(infix? (type bool) (bit #t))))
(define-struct list-pat ;; [p1,p2,...]
(include apat)
(slots
(pats (type (list pattern)))))
;;; The following structs deal with prec parsing of patterns.
(define-struct pp-pat-list
(include pattern)
(slots
(pats (type (list pattern)))))
(define-struct pp-pat-plus
(include pattern)
(predicate pp-pat-plus?))
(define-struct pp-pat-negated
(include pattern)
(predicate pp-pat-negated?))
;;; Structs for annotations
(define-struct annotation
(include decl)
(predicate annotation?))
(define-struct annotation-decl
(include annotation)
(predicate annotation-decl?)
(slots
(names (type (list symbol)))
(annotations (type (list annotation-value)))))
(define-struct annotation-value
(include annotation)
(predicate annotation-value?)
(slots
(name (type symbol))
(args (type (list t)))))
;;; This is a list of annotations placed in where decls lists in the same
;;; manner a signdecls.
(define-struct annotation-decls
(include annotation)
(predicate annotation-decls?)
(slots
(annotations (type (list annotation)))))
| false |
c355da20476efc838a0f8eadc09dfc65c2f272da
|
404799b4b2d5f83ee5304392826a69defc25da77
|
/ex3-6.scm
|
c03a102ab278d836dcbd2e72e689a61733cce6d9
|
[] |
no_license
|
WuzhangFang/SICP-exercise
|
38ae650c63e74bb7c6639bf984285e06743db925
|
d9977009ec3e32a74edb13b4f13f6ebbbc44ab32
|
refs/heads/master
| 2020-04-16T16:01:18.058287 | 2019-10-01T21:52:40 | 2019-10-01T21:52:40 | 165,722,260 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 592 |
scm
|
ex3-6.scm
|
;; Exercise 3.6
(define (rand-update x)
(let ((m 127)
(a 32)
(b 28))
(modulo (+ (* a x) b) m)))
(define rand
(let ((x 0))
(define (generate)
(set! x (rand-update x)) x)
(define (reset n)
(set! x n))
(define (dispatch m)
(cond ((eq? m 'generate) (generate))
((eq? m 'reset) reset)
(else (error "no such method" m))))
dispatch))
;; test
(rand 'generate)
(rand 'generate)
((rand 'reset) 10)
(rand 'generate)
(rand 'generate)
((rand 'reset) 10)
(rand 'generate)
| false |
31b623c364d725b44eaf6dbbc6379986dcde952b
|
f64f8602ab0a8b5170358092cd70ef967b4a45a6
|
/tests/kloop-tests-5.scm
|
5d87c025f1895b6f4e4af69faba751c091d26cac
|
[
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
] |
permissive
|
ellerh/kloop
|
e422a232c0b73c8080d930f6841ccd5c4bba7716
|
dbdfd55e8d6119b161b960a74ff701eca8fd4010
|
refs/heads/master
| 2016-09-06T10:29:54.451580 | 2012-06-09T09:12:55 | 2012-06-09T09:12:55 | 3,648,888 | 0 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,225 |
scm
|
kloop-tests-5.scm
|
(begin-tests "initial-final-clause"
(test-equal 0 (loop initially (return 0)))
(test-equal 0 (loop repeat 2 finally (return 0)))
(test-equal 1 (loop with x = 0 initially (incf x) return x))
(test-equal 2
(loop with x = 0 for a from 0 below 3
initially (incf x) finally (return (incf x))))
(test-equal 3
(loop with x = 0 for a from 0 below 3
initially (incf x) (incf x) finally (return (incf x))))
(test-equal 3
(loop with x = 0 for a from 0 upto 3
initially (incf x) finally (incf x) (return (incf x))))
(test-equal 4
(loop with x = 0 for a from 0 upto 3
initially (incf x) (incf x)
finally (incf x) (return (incf x))))
(test-equal 7
(loop with x = 0 for a from 0 below 3
do (incf x)
initially (incf x) (incf x)
finally (incf x) (return (incf x))))
(test-equal (loop with x = 2
initially (setq x (* x 3))
for i below 3
initially (setq x (* x 5))
do (incf x i)
finally (return x)) 33)
(test-equal '(initially0 initially1 initially2 initially3
body0 body1 body0 body1
finally0 finally1 finally2 finally3)
(loop with x = '()
repeat 2
initially (push 'initially0 x)
finally (push 'finally0 x)
initially (push 'initially1 x)
finally (push 'finally1 x)
do (push 'body0 x)
finally (push 'finally2 x) (push 'finally3 x)
finally (return (reverse x))
initially (push 'initially2 x) (push 'initially3 x)
do (push 'body1 x)))
)
(begin-tests "do-clause"
(test-equal '(0 1 2)
(loop with i = 3
with stack = '()
do (when (zerop i) (loop-finish))
(decf i)
(push i stack)
finally (return stack)))
(test-equal '(0 1 2)
(loop with i = 3
with stack = '()
doing (when (zerop i) (loop-finish))
(decf i)
(push i stack)
finally (return stack)))
(test-equal 10 (loop with x = 10 do (return x)))
(test-equal 10 (loop with x = 10 doing (return x)))
(test-equal 2 (loop with x = 0 do (incf x) doing (incf x) (return x)))
(test-equal 2 (loop with x = 0 do (incf x) doing (incf x) do (return x)))
(test-equal 2 (loop with x = 0 do (incf x) (incf x) doing (return x)))
(test-equal 4 (loop with x = 0 do (incf x) (incf x) (incf x)
doing (incf x) (return x)))
)
| false |
2d3a8db7a5e9d209577bbb4d439f088e45bf8616
|
120324bbbf63c54de0b7f1ca48d5dcbbc5cfb193
|
/packages/srfi/%3a31/rec.sls
|
811f1a6f7c374e4ca3cd6552418f6c03985cab4e
|
[
"X11-distribute-modifications-variant",
"MIT"
] |
permissive
|
evilbinary/scheme-lib
|
a6d42c7c4f37e684c123bff574816544132cb957
|
690352c118748413f9730838b001a03be9a6f18e
|
refs/heads/master
| 2022-06-22T06:16:56.203827 | 2022-06-16T05:54:54 | 2022-06-16T05:54:54 | 76,329,726 | 609 | 71 |
MIT
| 2022-06-16T05:54:55 | 2016-12-13T06:27:36 |
Scheme
|
UTF-8
|
Scheme
| false | false | 477 |
sls
|
rec.sls
|
#!r6rs
;; Copyright 2009 Derick Eddington. My MIT-style license is in the file named
;; LICENSE from the original collection this file is distributed with.
(library (srfi :31 rec)
(export rec)
(import (rnrs))
;; Taken directly from the SRFI-31
(define-syntax rec
(syntax-rules ()
((rec (NAME . VARIABLES) . BODY)
(letrec ( (NAME (lambda VARIABLES . BODY)) ) NAME))
((rec NAME EXPRESSION)
(letrec ( (NAME EXPRESSION) ) NAME))))
)
| true |
74002fc1247f41d215e881ff15c38d080acede26
|
7666204be35fcbc664e29fd0742a18841a7b601d
|
/code/table.scm
|
189217d654b7eb2ca8b9aec3f7ede171a3289f80
|
[] |
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 | 710 |
scm
|
table.scm
|
#lang racket
(require scheme/mpair)
(define cons mcons)
(define car mcar)
(define cdr mcdr)
(define set-car! set-mcar!)
(define set-cdr! set-mcdr!)
(define list mlist)
(define assoc massoc)
(define (make-table) (list '*table*))
(define (lookup key table)
(let ((record (assoc key (cdr table))))
(if record
(cdr record)
#f)))
(define (insert! key value table)
(let ((record (assoc key (cdr table))))
(if record
(set-cdr! record value)
(set-cdr! table
(cons (cons key value) (cdr table))))))
#|
(define t (make-table))
(lookup 'a t)
(insert! 'a 1 t)
(insert! 'b 1 t)
(insert! 'a 2 t)
(lookup 'a t)
(lookup 'b t)
|#
| false |
7a8e574d450e5974bd1ba7e4d8d3daa44a8be6ee
|
06d73af66d0c8450e2c9cb20757774c61c813ee6
|
/miu-traces.ss
|
1b6611f8fe5b375b1ce8a0a4ffb2dbada0eaf306
|
[] |
no_license
|
logicshan/lc-with-redex
|
ce5dc164abc6550bb431b2a7fa20c98f5c024037
|
63aa4cbf1f0acf0553c545686ba00a1699f003f8
|
refs/heads/master
| 2020-12-29T01:42:06.026750 | 2014-04-29T05:23:37 | 2014-04-29T05:23:37 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 92 |
ss
|
miu-traces.ss
|
#lang scheme ; File MIU-traces.ss
(require "MIU-puzzle.ss")
(traces MIU-rules '(M I))
| false |
8e1cf6442ba56ea5b8e30541b0bf729825e7df95
|
c5de45adc74a609415f9318fda24479561a5728b
|
/day18-bintree-datatype.ss
|
b8db870fd122b1823f6ecf36a93aee9e9bf00840
|
[] |
no_license
|
rhit-zhuz9/CSSE304
|
8b7498336cf9573b18b3cd0f5654ddfb1b1dfc69
|
f3a10bf17ca1daa532f277a0cf4f7c9746ea89e7
|
refs/heads/master
| 2023-03-15T11:54:52.913169 | 2018-05-30T03:00:43 | 2018-05-30T03:00:43 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 979 |
ss
|
day18-bintree-datatype.ss
|
(load "chez-init.ss") ; not needed if you are using DrScheme
(define-datatype bintree bintree?
[leaf-node
(datum number?)]
[interior-node
(key symbol?)
(left bintree?)
(right bintree?)])
(define leaf-sum ; of a bintree
(lambda (tree)
(cases bintree tree
[leaf-node (datum) datum]
[interior-node (key left right)
(+ (leaf-sum left)
(leaf-sum right))])))
(define inorder ; lisinting of interior nodes in a bintree,
(lambda (tree)
(cases bintree tree
[leaf-node (datum) '()]
[interior-node (key left right)
(append (inorder left) (list key) (inorder right))])))
(define list-to-bintree ; construct a bintree from a list representation.
(lambda (t)
(cond
[(number? t)
(leaf-node t)]
[(symbol? (car t))
(interior-node
(car t)
(list-to-bintree (cadr t))
(list-to-bintree (caddr t)))])))
(define t2 (list-to-bintree
'(a (b 3 4) 5)))
| false |
1d5caaea14bcbc5452a5abe121390ba802d9bfc6
|
41648be07e8803784690d9b4f6f08091e322b193
|
/core-control.ss
|
4c7b7f5f2cce799e32ad46def626d7a4d4e69343
|
[] |
no_license
|
samth/not-a-box
|
dad25a9ea65debf318a14f2a5f5788b331b62a76
|
9fa61e07b278be52148612fb5a77f4058eca5a9f
|
refs/heads/master
| 2021-01-19T12:51:12.457049 | 2017-03-02T19:57:20 | 2017-03-03T19:59:37 | 82,343,642 | 0 | 0 | null | 2017-02-17T22:27:36 | 2017-02-17T22:27:36 | null |
UTF-8
|
Scheme
| false | false | 2,972 |
ss
|
core-control.ss
|
(define-syntax begin0
(syntax-rules ()
[(_ expr0 expr ...)
(call-with-values (lambda ()
(call-with-values (lambda () expr0)
(case-lambda
[(x) (values x #f)]
[args (values args #t)])))
(lambda (l apply?)
expr ...
(if apply?
(chez:apply values l)
l)))]))
;; ----------------------------------------
(define-record continuation-mark-set (marks k))
(define-record mark-stack-frame (prev ; prev frame
k ; continuation for this frame
table ; hamt mapping keys to values
flat)) ; #f or list that contains only tables
(define mark-stack #f)
(define-syntax with-continuation-mark
(syntax-rules ()
[(_ key val body)
(call/cm key val (lambda () body))]))
(define (call/cm key val proc)
(call/cc
(lambda (k)
(if (and mark-stack
(eq? k (mark-stack-frame-k mark-stack)))
(begin
(set-mark-stack-frame-table! mark-stack
(hamt-set (mark-stack-frame-table mark-stack)
key
val))
(set-mark-stack-frame-flat! mark-stack #f)
(proc))
(begin0
(call/cc
(lambda (k)
(set! mark-stack
(make-mark-stack-frame mark-stack
k
(hasheq key val)
#f))
(proc)))
(set! mark-stack (mark-stack-frame-prev mark-stack)))))))
(define (current-marks)
(let loop ([mark-stack mark-stack])
(cond
[(not mark-stack) null]
[(mark-stack-frame-flat mark-stack) => (lambda (l) l)]
[else
(let ([l (cons (mark-stack-frame-table mark-stack)
(loop (mark-stack-frame-prev mark-stack)))])
(set-mark-stack-frame-flat! mark-stack l)
l)])))
(define continuation-mark-set-first
(case-lambda
[(marks key) (continuation-mark-set-first marks key #f)]
[(marks key none-v prompt-tag) (continuation-mark-set-first marks key none-v)]
[(marks key none-v)
(let loop ([marks (or (and marks
(continuation-mark-set-marks marks))
(current-marks))])
(cond
[(null? marks)
(if (eq? key parameterization-key)
empty-parameterization
none-v)]
[else
(let ([v (hamt-ref (car marks) key none)])
(if (eq? v none)
(loop (cdr marks))
v))]))]))
(define (current-continuation-marks)
(call/cc
(lambda (k)
;; For now, keep `k` for error context
(make-continuation-mark-set (current-marks) k))))
| true |
01d0e239c93be66340ea9ca61fc5583cfded3c17
|
6b288a71553cf3d8701fe7179701d100c656a53c
|
/s/front.ss
|
f214cebed2513f5ccd3673380281cbb15ccc934c
|
[
"Apache-2.0"
] |
permissive
|
cisco/ChezScheme
|
03e2edb655f8f686630f31ba2574f47f29853b6f
|
c048ad8423791de4bf650fca00519d5c2059d66e
|
refs/heads/main
| 2023-08-26T16:11:15.338552 | 2023-08-25T14:17:54 | 2023-08-25T14:17:54 | 56,263,501 | 7,763 | 1,410 |
Apache-2.0
| 2023-08-28T22:45:52 | 2016-04-14T19:10:25 |
Scheme
|
UTF-8
|
Scheme
| false | false | 7,932 |
ss
|
front.ss
|
;;; front.ss
;;; Copyright 1984-2017 Cisco Systems, Inc.
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
(begin
(define-who make-parameter
(case-lambda
[(init guard) (#2%make-parameter init guard)]
[(v) (#2%make-parameter v)]))
(when-feature pthreads
(let ()
(define allocate-thread-parameter
(let ()
(define free-list '()) ; list of pairs w/ index as car
(define index-guardian (make-guardian))
(lambda (initval)
(with-tc-mutex
(let ([index
(or (index-guardian)
(and (not (null? free-list))
(let ([index (car free-list)])
(set! free-list (cdr free-list))
index))
(let* ([n (vector-length ($tc-field 'parameters ($tc)))]
[m (fx* (fx+ n 1) 2)])
(for-each
(lambda (thread)
(let ([tc ($thread-tc thread)])
(let ([old ($tc-field 'parameters tc)]
[new (make-vector m)])
(do ([i (fx- n 1) (fx- i 1)])
((fx< i 0))
(vector-set! new i (vector-ref old i)))
($tc-field 'parameters tc new))))
($thread-list))
(set! free-list
(do ([i (fx- m 1) (fx- i 1)]
[ls free-list (cons (list i) ls)])
((fx= i n) ls)))
(list n)))])
(let loop ()
(let ([index (index-guardian)])
(when index
(for-each
(lambda (thread)
(vector-set!
($tc-field 'parameters ($thread-tc thread))
(car index)
0))
($thread-list))
(set! free-list (cons index free-list))
(loop))))
(for-each
(lambda (thread)
(vector-set!
($tc-field 'parameters ($thread-tc thread))
(car index)
initval))
($thread-list))
(index-guardian index)
index)))))
(define set-thread-parameter!
(lambda (index value)
(with-tc-mutex
(vector-set! ($tc-field 'parameters ($tc)) (car index) value))))
(set-who! make-thread-parameter
(case-lambda
[(init guard)
(unless (procedure? guard) ($oops who "~s is not a procedure" guard))
(let ([index (allocate-thread-parameter (guard init))])
(case-lambda
[() (vector-ref ($tc-field 'parameters ($tc)) (car index))]
[(u) (set-thread-parameter! index (guard u))]))]
[(init)
(let ([index (allocate-thread-parameter init)])
(case-lambda
[() (vector-ref ($tc-field 'parameters ($tc)) (car index))]
[(u) (set-thread-parameter! index u)]))]))
(set! $allocate-thread-parameter allocate-thread-parameter)
(set! $set-thread-parameter! set-thread-parameter!))
)
(define case-sensitive ($make-thread-parameter #t (lambda (x) (and x #t))))
(define compile-interpret-simple ($make-thread-parameter #t (lambda (x) (and x #t))))
(define generate-interrupt-trap ($make-thread-parameter #t (lambda (x) (and x #t))))
(define generate-allocation-counts ($make-thread-parameter #f (lambda (x) (and x #t))))
(define generate-instruction-counts ($make-thread-parameter #f (lambda (x) (and x #t))))
(define enable-cross-library-optimization ($make-thread-parameter #t (lambda (x) (and x #t))))
(define machine-type
(lambda ()
(constant machine-type-name)))
(define-who $fasl-target ($make-thread-parameter #f))
;;; package stubs are defined here in case we exclude certain packages
(eval-when (compile)
(define-syntax package-stub
(lambda (x)
(syntax-case x ()
[(_ name msg)
(identifier? #'name)
#'(package-stub (name name) msg)]
[(_ (name pub-name) msg)
#'(define name (lambda args ($oops 'pub-name msg)))])))
(define-syntax package-stubs
(lambda (x)
(syntax-case x ()
[(_ pkg name ...)
(with-syntax ([msg (format "~a package is not loaded" (datum pkg))])
#'(begin (package-stub name msg) ...))])))
)
(package-stubs cafe
waiter-prompt-and-read
waiter-write
waiter-prompt-string
new-cafe)
(package-stubs compile
($clear-dynamic-closure-counts compile)
($c-make-closure compile)
($c-make-code compile)
compile
($compile-backend compile)
compile-file
($compile-host-library compile)
compile-library
compile-port
compile-program
compile-script
compile-to-file
compile-to-port
compile-whole-library
compile-whole-program
($dynamic-closure-counts compile)
($loop-unroll-limit compile)
make-boot-file
($make-boot-file make-boot-file)
make-boot-header
($make-boot-header make-boot-header)
maybe-compile-file
maybe-compile-library
maybe-compile-program
($np-boot-code compile)
($np-compile compile)
($np-get-timers compile)
($np-last-pass compile)
($np-reset-timers! compile)
($np-tracer compile)
($optimize-closures compile)
($track-dynamic-closure-counts compile)
($track-static-closure-counts compile))
(package-stubs fasl
($fasl-bld-graph fasl-write)
($fasl-enter fasl-write)
($fasl-start fasl-write)
($fasl-table fasl-write)
($fasl-out fasl-write)
($fasl-wrf-graph fasl-write)
fasl-write
fasl-file)
(package-stubs inspect
inspect
inspect/object)
(package-stubs interpret
interpret)
(package-stubs pretty-print
pretty-format
pretty-line-length
pretty-one-line-limit
pretty-initial-indent
pretty-standard-indent
pretty-maximum-lines
pretty-print
pretty-file)
(package-stubs profile
profile-clear
profile-dump)
(package-stubs sc-expand
sc-expand
($syntax-dispatch sc-expand)
syntax-error
literal-identifier=?
bound-identifier=?
free-identifier=?
identifier?
generate-temporaries
syntax->datum
datum->syntax)
(package-stubs trace
trace-output-port
trace-print
($trace trace)
($untrace untrace)
($trace-closure trace))
(package-stubs compiler-support
$cp0
$cpvalid
$cpletrec
$cpcheck)
(package-stubs syntax-support
$uncprep)
(define current-eval
($make-thread-parameter
(lambda args ($oops 'eval "no current evaluator"))
(lambda (x)
(unless (procedure? x)
($oops 'current-eval "~s is not a procedure" x))
x)))
(define current-expand
($make-thread-parameter
(lambda args ($oops 'expand "no current expander"))
(lambda (x)
(unless (procedure? x)
($oops 'current-expand "~s is not a procedure" x))
x)))
(define eval
(case-lambda
[(x) ((current-eval) x)]
[(x env-spec) ((current-eval) x env-spec)]))
(define expand
(case-lambda
[(x) ((current-expand) x)]
[(x env-spec) ((current-expand) x env-spec)]
[(x env-spec records?) ((current-expand) x env-spec records?)]
[(x env-spec records? compiling-a-file) ((current-expand) x env-spec records? compiling-a-file)]
[(x env-spec records? compiling-a-file outfn) ((current-expand) x env-spec records? compiling-a-file outfn)]))
(define $compiler-is-loaded? #f)
)
| true |
4bd57297ff3b71335b1b5a473455890f23ebfddd
|
ee10242f047e9b4082a720c48abc7d94fe2b64a8
|
/bs-lib.sch
|
3e86398de5f907c31e89d31ff96a1967f95d632c
|
[
"Apache-2.0"
] |
permissive
|
netguy204/brianscheme
|
168c20139c31d5e7494e55033c78f59741c81eb9
|
1b7d7b35485ffdec3b76113064191062e3874efa
|
refs/heads/master
| 2021-01-19T08:43:43.682516 | 2012-07-21T18:30:39 | 2012-07-21T18:30:39 | 1,121,869 | 5 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 12,462 |
sch
|
bs-lib.sch
|
;;; bullshit! (bs) --- a stupid issue tracker
;; Design:
;;
;; This will be heavily geared at Git. Like Git, bs itself does
;; not directly interact with the user. Commands are generally
;; non-interactive transaction on the issue database, and in the
;; event interaction is needed (entering detailed issue notes) the
;; EDITOR is displayed.
;;
;; Issues are identified by a unique ID (not a hash). Like a Git
;; hash, they can be referenced by the substring. They are stored as
;; a specially-printed plist in a flat-file database.
;; bs init
;; Create an empty issue database.
;;
;; bs list
;; List all open issues.
;;
;; bs show ISSUE
;; Show all details on given issue.
;;
;; bs new MESSAGE
;; Just like create, but immediately commit the issue into Git.
;;
;; bs close ISSUE
;; Set an issue to closed.
;;
;; bs commit MSG
;; Commit all database changes into repository.
;; By default almost all commands will immediately commit the
;; database change into Git. There will be an option switch to not do
;; this.
(require 'getopt)
(require 'sugar)
(define *bs-dir* ".bs"
"Location of issue database.")
(define (config-file)
"Return location of global config file."
(string-append (or (getenv "HOME") "") "/.bsconfig"))
(define (get-editor)
"Return name of user's editor."
(or (getenv "EDITOR") "nano"))
(define *default-msg* "Update bs database."
"Default commit message.")
(define *tmp-file* ".git/BS_EDIT"
"Temporary EDITOR file.")
(define *props* '(id priority status category user date title comments))
(define *priorities* '(low normal high urgent)
"Priorities in order, 0-4.")
;; Error handling
(define (bs-error . msgs)
"Produce an error message for the user."
(display "bs: error: ")
(dolist (msg msgs)
(display msg))
(newline)
(exit 1))
(define (bs-warning . msgs)
"Produce a warning message for the user."
(display "bs: warning: ")
(dolist (msg msgs)
(display msg))
(newline))
;; Argument processing
(define (go-to-root)
"Change current working directory to the project root."
(cond
((file-exists? *bs-dir*) #t)
((equal? "/" (getcwd))
(bs-error "Not in a project, or project uninitialized."))
(#t (begin (chdir "..") (go-to-root)))))
(define (process-args-img)
"Process arguments as an image."
(define *argv* *args*)
(bs-exec (first *args*) (cdr *args*)))
(define (process-args)
"Process arguments as a script."
(define *argv* (cdr *args*))
(bs-exec (second *args*) (cddr *args*)))
(define (optlist opts)
"Turn arguments into a plist."
(letrec ((iter (lambda (opt)
(if opt
(append (list (string->symbol
(char->string opt)) *optarg*)
(iter (getopt opts)))
'()))))
(let ((plist (iter (getopt opts))))
(append (list 'rest (nthcdr *optind* *argv*)) plist))))
;; Command processing
(define (bs-exec cmd args)
"Execute user command."
(load-config)
(cond
((equal? cmd "help") (bs-help args))
((equal? cmd "init") (bs-init args))
((equal? cmd "list") (bs-list args))
((equal? cmd "show") (bs-show args))
((equal? cmd "new") (bs-new args))
((equal? cmd "close") (bs-close args))
((equal? cmd "commit") (bs-commit args))
((eq? cmd nil) (bs-help args))
(#t (begin
(display "Unknown command ")
(display cmd)))))
(define (bs-init args)
"Initialize bs database in current directory."
(if (file-exists? *bs-dir*)
(bs-error "database already initialized"))
(if (mkdir *bs-dir*)
(display "Initialized empty issue database.\n")
(bs-error "failed to initialize database\n")))
(define (bs-help args)
(display "usage: bs [bs-opts] command [cmd-opts]\n\n")
(display "help Print this help information\n")
(display "init Create an empty issue database\n")
(display "list Print list of current issues.\n")
(display "show Show all information on a commit.\n")
(display "new Create a new issue.\n")
(display "close Set issue status to closed.\n")
(display "commit Commit database to Git.\n"))
(define (bs-list args)
"List the current issues."
(go-to-root)
(dolist (issue (dir *bs-dir*))
(print-issue-short (fetch-issue issue))))
(define (bs-show args)
"Show all information on an issue."
(print-issue (fetch-issue (canon (car args)))))
(define (bs-new args)
"Create a new issue."
(go-to-root)
(let* ((opts (optlist "np:c:t:"))
(do-commit (not (plist-get opts 'n)))
(id (create-id))
(priority (priority (or (plist-get opts 'p) 'normal)))
(cat (string->symbol (or (plist-get opts 'c) "bug")))
(title (or (plist-get opts 't) (edit-message)))
(message (if (plist-get opts 't) '() (list (get-message))))
(issue (list 'id id 'priority priority 'category cat 'user *full*
'date (date-string) 'title title 'status 'open
'comments message)))
(write-issue issue)
(print-issue-short issue)
(display (string-append "Created issue " id "\n"))
(if do-commit
(commit-issue issue))))
(define (bs-close args)
"Set a commit status to closed."
(let* ((opts (optlist "n"))
(do-commit (not (plist-get opts 'n)))
(issue (fetch-issue (canon (car (plist-get opts 'rest))))))
(if (eq? (plist-get issue 'status) 'closed)
(bs-warning "issue was already closed")
(begin
(plist-set! issue 'status 'closed)
(write-issue issue)
(if do-commit
(commit-issue issue
(string-append "closed: " (co-msg issue))))))))
(define (bs-commit args)
"Commit current database to the repository."
(go-to-root)
(commit (car-else args *default-msg*)))
;; Issue handling
(define (canon short)
"Find the full issue name for a possible short-hand name."
(if (null? short)
(bs-error "must provide a commit to show"))
(letrec ((match (lambda (lst)
(if (null? lst)
(bs-error "unknown issue: " short)
(if (equal? short (substring (car lst) 0
(string-length short)))
(car lst)
(match (cdr lst)))))))
(match (dir *bs-dir*))))
(define (fetch-issue name)
"Fetch an issue s-exp by name."
(let ((file (string-append *bs-dir* "/" name)))
(if (file-exists? file)
(call-with-input-file file read-port)
(bs-error "No such issue: " name))))
(define (short-id issue)
"Return short id version of issue."
(substring (plist-get issue 'id) 0 7))
(define (print-issue-short issue)
"Print out the issue summary in one line."
(when (eq? (plist-get issue 'status) 'open)
(display (short-id issue))
(display " ")
(display (plist-get issue 'priority))
(display " ")
(display (plist-get issue 'category))
(display " ")
(display (plist-get issue 'title))
(display "\n")))
(define (print-issue issue)
"Print out the issue summary in one line."
(printf "issue %s %a (%a priority)\n"
(plist-get issue 'id)
(plist-get issue 'status)
(plist-get issue 'priority))
(printf "Category: %a\n" (plist-get issue 'category))
(printf "Author: %s\n" (plist-get issue 'user))
(printf "Date: %s\n" (plist-get issue 'date))
(printf "\n\t%s\n\n" (plist-get issue 'title))
(dolist (msg (plist-get issue 'comments))
(display msg)
(newline)))
(define (write-issue issue)
"Write the given issue to the database."
(let ((port (open-output-port (issue-file issue))))
(write-string "(" port)
(dolist (prop *props*)
(write-port prop port)
(write-char #\tab port)
(write-port (plist-get issue prop) port)
(write-char #\newline port))
(write-string ")\n" port)
(close-output-port port)))
(define (issue-file issue)
"Determine file corresponding to the given issue."
(string-append *bs-dir* "/" (plist-get issue 'id)))
(define (create-id)
"Create a new issue id."
(let ((pad (lambda (str)
(if (< (string-length str) 4)
(string-append (make-string (- 4 (string-length str)) #\0)
str)
str))))
(apply string-append
(map (compose pad (rcurry integer->string :base 16) random)
(make-list 4 (expt 2 16))))))
;; Committing
(define (string-prot s)
"Protect string for use in the shell."
(string-append "\"" s "\""))
(define (argcat . args)
"Concatenate strings for use in a command line."
(or (reduce (lambda (a b) (string-append a " " b)) (map string-prot args))
""))
(define-syntax (git cmd . args)
"Run a git command."
`(system (string-append "git " ,(symbol->string cmd) " "
(argcat ,@args) " > /dev/null")))
(define (commit msg)
"Commit all current changes into the git repository."
(unless (and (git reset)
(git add *bs-dir*)
(git commit "-qm" (string-append "[issue] " msg)))
(display "No database changes to commit.\n")))
(define (co-msg issue)
"Create standard commit message for the given issue."
(string-append (plist-get issue 'title) " (" (short-id issue) ")"))
(define (commit-issue issue . msg)
"Commit a single issue into git."
(unless (and (git reset)
(git add (issue-file issue))
(git commit "-qm"
(string-append "[issue] " (car-else msg (co-msg issue)))))
(display "Failed to commit issue.\n")))
;; Environment
(let ((old-read-line read-line))
(define (read-line port) ; redefine
"Read a non-comment line from the file."
(let ((line (old-read-line port)))
(cond
((eof-object? line) line)
((eq? (string-ref line 0) #\#) (read-line port))
(#t line)))))
(define (load-config)
"Load configuration into global variables."
(let ((config (get-config)))
(define *user* (plist-get config 'user))
(define *email* (plist-get config 'email))
(define *full* (string-append *user* " <" *email* ">"))
config))
(define (get-config)
"Fetch configuration."
(if (file-exists? (config-file))
(call-with-input-file (config-file) read-port)
(get-git-config)))
(define (eof-to-empty line)
(if (eof-object? line) "" line))
(define (get-git-config)
"Derive a config from Git."
(let* ((name-in (open-input-pipe "git config user.name"))
(mail-in (open-input-pipe "git config user.email"))
(res (list 'user (eof-to-empty (read-line name-in))
'email (eof-to-empty (read-line mail-in)))))
(close-input-port name-in)
(close-input-port mail-in)
(if (or (= 0 (string-length (plist-get res 'user)))
(= 0 (string-length (plist-get res 'email))))
(list 'user "unknown" 'email "unknown")
res)))
(define (edit-message)
"Summon the EDITOR to interact with the user."
(let ((template (open-output-port *tmp-file*)))
(display "\n" template)
(display "# Put your issue message above. " template)
(display "Lines starting with # are ignored.\n" template)
(display "#\n" template)
(display "# The first line is the issue title. " template)
(display "Follow this with a blank line and\n" template)
(display "# then a detailed commentary of the issue.\n" template)
(display "#\n" template)
(close-output-port template))
(let* ((ret (system (string-append (get-editor) " " *tmp-file*)))
(title (call-with-input-file *tmp-file* read-line)))
(unless ret
(bs-error "editor aborted"))
(if (= 0 (string-length title))
(bs-error "empty message/title: aborting"))
title))
(define (get-message)
"Get the message from the tempfile, less the title."
(call-with-input-file *tmp-file*
[begin (read-line _) (read-line _) (slurp-port _)]))
;; Misc
(define (priority p)
"Return the appropriate priority symbol."
;; Waiting on read-string to make this useful.
(let ((p (if (string? p) (string->symbol p) p)))
(cond
((null? p) (priority 1))
((and (number? p) (>= p 0) (<= p (length *priorities*)))
(list-ref *priorities* p))
((and (symbol? p) (member? p *priorities*)) p)
(#t (bs-error "unknown priority: " p)))))
| true |
f84be5863b106c732c3b3eb36ad51375c798626f
|
907a2a4ee3dc63cf6ac542156fc649254c6260eb
|
/srfi/nnn.sld
|
d2c532a1d334faf94059fd8216b273e2145e5977
|
[
"MIT"
] |
permissive
|
pre-srfi/define-higher-order-lambda
|
0840396b970ff7e8b90ec46a94d0e91471f41ad9
|
b40805e89799780506d8324d4983df975464a7b5
|
refs/heads/master
| 2023-02-25T04:31:01.960026 | 2021-02-03T19:45:14 | 2021-02-03T19:45:14 | 334,439,765 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 843 |
sld
|
nnn.sld
|
(define-library (srfi nnn)
(export define)
(import (rename (scheme base) (define define/standard)))
(begin
(define-syntax define
(syntax-rules ()
((_ ((name args ... . tail) xargs ... . xtail) xbody ...)
(define/standard (name args ... . tail)
(lambda (xargs ... . xtail) xbody ...)))
((_ ((name args ... . tail) xargs ...) xbody ...)
(define/standard (name args ... . tail)
(lambda (xargs ...) xbody ...)))
((_ ((name args ...) xargs ... . xtail) xbody ...)
(define/standard (name args ...)
(lambda (xargs ... . xtail) xbody ...)))
((_ ((name args ...) xargs ...) xbody ...)
(define/standard (name args ...)
(lambda (xargs ...) xbody ...)))
((_ things ...)
(define/standard things ...))))))
| true |
aad74574ab267a20a02eee92f729a7643456454d
|
38fcd70df648a497ee1271fcdbd30e391fb310e5
|
/syntax/syntax/simple-extend.ss
|
3e632681a51854e161a4d0288d7644c85d6bec72
|
[] |
no_license
|
liutanyu/Useful
|
e9b3d3699dffa21bb1425dddff7d150ab7d7aee7
|
11a123126833e577a76ce32c22d8563c0f2bbd7d
|
refs/heads/master
| 2021-01-19T11:34:24.259506 | 2013-07-17T04:13:22 | 2013-07-17T04:13:22 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 6,007 |
ss
|
simple-extend.ss
|
;;; simple-extend.ss
;;; Copyright (C) 1987 R. Kent Dybvig
;;; Permission to copy this software, in whole or in part, to use this
;;; software for any lawful purpose, and to redistribute this software
;;; is granted subject to the restriction that all copies made of this
;;; software must include this copyright notice in full.
;;; The basic design of extend-syntax is due to Eugene Kohlbecker. See
;;; "E. Kohlbecker: Syntactic Extensions in the Programming Language Lisp",
;;; Ph.D. Dissertation, Indiana University, 1986." The structure of "with"
;;; pattern/value clauses, the method for compiling extend-syntax into
;;; Scheme code, and the actual implementation are due to Kent Dybvig.
(letrec
([id (lambda (name access control) (list name access control))]
[id-name car]
[id-access cadr]
[id-control caddr]
[loop (lambda () (cons '() '()))]
[loop-ids car]
[loop-ids! set-car!]
[parse
(lambda (keys pat acc cntl ids)
(cond
[(symbol? pat)
(if (memq pat keys)
ids
(cons (id pat acc cntl) ids))]
[(pair? pat)
(if (equal? (cdr pat) '(...))
(let ([x (gensym)])
(parse keys (car pat) x (id x acc cntl) ids))
(parse keys (car pat) `(car ,acc) cntl
(parse keys (cdr pat) `(cdr ,acc) cntl ids)))]
[else ids]))]
[gen
(lambda (exp ids loops)
(cond
[(symbol? exp)
(let ([x (mem (lambda (x) (eq? (id-name x) exp)) ids)])
(if (null? x)
`',exp
(let ([id (car x)])
(add-control! (id-control id) loops)
(id-access id))))]
[(pair? exp)
(cond
[(eq? (car exp) 'with)
(unless (syntax-match? '(with) '(with ((p x) ...) e ...) exp)
(error 'extend-syntax "invalid 'with' form ~s" exp))
(gen-with (map car (cadr exp))
(map cadr (cadr exp))
(caddr exp)
ids
loops)]
[(equal? (cdr exp) '(...))
(let ([x (loop)])
(make-loop x
(gen (car exp) ids (cons x loops))
(gen (cddr exp) ids loops)))]
[else
`(cons ,(gen (car exp) ids loops)
,(gen (cdr exp) ids loops))])]
[else exp]))]
[gen-with
(lambda (pats exps body ids loops)
(if (null? pats)
(gen body ids loops)
(let ([p (car pats)] [e (car exps)] [g (gensym)])
`(let ([,g ,(gen-quotes e ids loops)])
,(gen-with (cdr pats)
(cdr exps)
body
(parse '() p g '() ids)
loops)))))]
[gen-quotes
(lambda (exp ids loops)
(cond
[(syntax-match? '(quote) '(quote x) exp)
(gen (cadr exp) ids loops)]
[(pair? exp)
(cons (gen-quotes (car exp) ids loops)
(gen-quotes (cdr exp) ids loops))]
[else exp]))]
[add-control!
(lambda (id loops)
(unless (null? id)
(let ([x (loop-ids (car loops))])
(unless (memq id x)
(loop-ids! (car loops) (cons id x))
(add-control! (id-control id) (cdr loops))))))]
[make-loop
(lambda (loop body tail)
(let* ([ids (loop-ids loop)]
[exp `(map (lambda ,(map id-name ids) ,body)
,@(map id-access ids))])
`(append ,exp ,tail)))]
[make-clause
(lambda (keys clause x)
(cond
[(syntax-match? '() '(pat exp) clause)
(let ([pat (car clause)] [exp (cadr clause)])
(let ([ids (parse keys pat x '() '())])
`((syntax-match? ',keys ',pat ,x)
,(gen exp ids '()))))]
[(syntax-match? '() '(pat fdr exp) clause)
(let ([pat (car clause)] [fdr (cadr clause)] [exp (caddr clause)])
(let ([ids (parse keys pat x '() '())])
`((and (syntax-match? ',keys ',pat ,x)
,(gen-quotes fdr ids '()))
,(gen exp ids '()))))]
[else
(error 'extend-syntax "invalid clause ~s" clause)]))]
[make-syntax
(let ([x (make-temp-symbol "x")] [e (make-temp-symbol "e")])
(lambda (keys clauses)
`(lambda (,x ,e)
(,e (cond
,@(map (lambda (c) (make-clause keys c x)) clauses)
(else
(error ',(car keys) "invalid syntax ~s" ,x)))))))])
(extend-syntax (extend-syntax)
[(extend-syntax (key1 key2 ...) clause ...)
(andmap symbol? '(key1 key2 ...))
(with ([expander (make-syntax '(key1 key2 ...) '(clause ...))])
(define-syntax-expander key1 expander))])
(extend-syntax (extend-syntax/code)
[(extend-syntax/code (key1 key2 ...) clause ...)
(andmap symbol? '(key1 key2 ...))
(with ([expander (make-syntax '(key1 key2 ...) '(clause ...))])
'expander)]))
(define syntax-match?
(rec match?
(lambda (keys pat exp)
(cond
[(symbol? pat) (if (memq pat keys) (eq? exp pat) #t)]
[(pair? pat)
(if (equal? (cdr pat) '(...))
(recur f ([lst exp])
(or (null? lst)
(and (pair? lst)
(match? keys (car pat) (car lst))
(f (cdr lst)))))
(and (pair? exp)
(match? keys (car pat) (car exp))
(match? keys (cdr pat) (cdr exp))))]
[else (equal? exp pat)]))))
| true |
d9c3922acddffc044b40e96fe569b6ad69c39b67
|
7a0ff7112aa87d4d6e96df3868a06fde0ab3484d
|
/seam-carving.scm
|
fc81020a062093e696952f8c118960a62d9fb597
|
[] |
no_license
|
hayamiz/seam-carving-scm
|
6dbf84bc07a359802e888bfc361511425b5f8cdc
|
d190334ccd4dcc36b20ee1bc758f32b66ef7049f
|
refs/heads/master
| 2016-08-04T18:13:54.243502 | 2010-02-01T09:40:16 | 2010-02-01T09:40:16 | 495,914 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 13,077 |
scm
|
seam-carving.scm
|
#!/usr/bin/env gosh
;; -*- coding: utf-8 -*-
(use srfi-1) ;; List library
(use srfi-13) ;; String library
(use srfi-27) ;; Random library
(use srfi-43) ;; Vector library
(use gauche.parseopt)
(use gauche.process)
(use binary.io)
(define (pixel:create r g b) (list r g b))
(define (pixel:get accessor pixel . rest)
(let ((val (if (list? pixel) (accessor pixel) pixel)))
(if (null? rest)
val
(cond ((< val 0) 0)
((> val 255) 255)
(else val)))))
(define (pixel:r pixel . rest) (apply pixel:get car pixel rest))
(define (pixel:g pixel . rest) (apply pixel:get cadr pixel rest))
(define (pixel:b pixel . rest) (apply pixel:get caddr pixel rest))
(define (pixel:scale scale pixel)
(list (* scale (car pixel)) (* scale (cadr pixel)) (* scale (caddr pixel))))
(define (pixel:scale! scale pixel)
(let ((x (car pixel)) (xs (cdr pixel)))
(set-car! pixel (round->exact (* scale x)))
(let ((x (car xs)) (xs_ (cdr xs)))
(set-car! xs (round->exact (* scale x)))
(let ((x (car xs_)))
(set-car! xs_ (round->exact (* scale x))))))
pixel)
(define (pixel:+ . pixels)
(let loop((r 0) (g 0) (b 0) (pixels pixels))
(if (null? pixels)
(list r g b)
(let1 pixel (car pixels)
(loop (+ r (car pixel)) (+ g (car pixel)) (+ b (car pixel))
(cdr pixels))))))
(define (pixel:- pixel . pixels)
(let loop((r (car pixel)) (g (cadr pixel)) (b (caddr pixel))
(pixels pixels))
(if (null? pixels)
(list r g b)
(let1 pixel (car pixels)
(loop (+ r (car pixel)) (+ g (car pixel)) (+ b (car pixel))
(cdr pixels))))))
(define (pixel:abs! pixel)
(let ((x (car pixel)) (xs (cdr pixel)))
(set-car! pixel (abs x))
(let ((x (car xs)) (xs_ (cdr xs)))
(set-car! xs (abs x))
(let ((x (car xs_)))
(set-car! xs_ (abs x)))))
pixel)
(define (pixel:abs pixel) (pixel:abs! (reverse (reverse pixel))))
(define (pixel:norm pixel)
(let ((x (car pixel)) (y (cadr pixel)) (z (caddr pixel)))
(round->exact (sqrt (+ (* x x) (* y y) (* z z))))))
(define (image:get-pixel image x y . rest)
(let ((width (image:width image))
(height (image:height image)))
(unless (null? rest)
(unless (< -1 x width)
(set! x (cond ((< x 0) 0)
((>= x width)
(- width 1))
(else x))))
(unless (< -1 y height)
(set! y (cond ((< y 0) 0)
((>= y height)
(- height 1))
(else y)))))
(vector-ref (vector-ref (cdr (assq 'data image)) y) x)))
(define (image:row-get-pixel row x . rest)
(let ((width (vector-length row)))
(unless (null? rest)
(unless (< -1 x width)
(set! x (cond ((< x 0) 0)
((>= x width)
(- width 1))
(else x))))
(vector-ref row x))))
(define (image:set-pixel image x y pixel)
(let1 row (vector-ref (cdr (assq 'data image)) y #f)
(if row
(vector-set! row x pixel)
#f)))
(define (image:data image) (cdr (assq 'data image)))
(define (image:width image) (cdr (assq 'width image)))
(define (image:height image) (cdr (assq 'height image)))
(define (image:set-width! image width) (set-cdr! (assq 'width image) width))
(define (image:set-height! image height) (set-cdr! (assq 'height image) height))
(define (image::load-ppm-raw input)
(let1 input-port (if (string? input)
(open-input-file input)
input)
(unwind-protect
(with-input-from-port input-port
(lambda ()
(let ((fmt (read-line))
(comment (if (eq? #\# (peek-char ))
(read-line)
#f))
(size (read-line))
(max-brightness (read-line)))
(format #t "fmt: ~s\ncomment: ~s\nsize: ~s\nmax-brightness: ~s\n"
fmt comment size max-brightness)
(unless (equal? "P6" fmt)
(error "Invliad format file '~s': '~s'" path fmt))
(receive (width height) (image::parse-size size)
(let ((image (image::create width height)))
(dotimes (y height)
(dotimes (x width)
(let ((r (read-byte))
(g (read-byte))
(b (read-byte)))
(let1 pixel (pixel:create r g b)
(image:set-pixel image x y pixel)))))
image))
)))
(when (string? input)
(close-input-port input-port)))))
(define (image::save-ppm-raw image output)
(let1 output-port (if (string? output)
(open-output-file output)
(begin
(let1 proc (run-process `("display" "-")
:input :pipe
:wait #f)
(process-input proc))))
(unwind-protect
(with-output-to-port output-port
(lambda ()
(print "P6")
(format #t "~d ~d\n" (image:width image) (image:height image))
(print "255")
(dotimes (y (image:height image))
(dotimes (x (image:width image))
(let1 pixel (image:get-pixel image x y)
(write-byte (pixel:r pixel #t))
(write-byte (pixel:g pixel #t))
(write-byte (pixel:b pixel #t)))))))
(begin
(close-output-port output-port)
(unless (string? output)
(process-wait-any)))))
#t)
(define (image::create width height . rest)
(let1 data (if (not (null? rest))
(car rest)
(let1 rows (make-vector height #f)
(do ((i 0 (+ i 1)))
((>= i height) rows)
(vector-set! rows i (make-vector width #f)))))
`((width . ,width) (height . ,height) (data . ,data))))
(define (image::clone image)
(let ((image-data (image:data image))
(data (make-vector (image:height image))))
(dotimes (y (image:height image))
(vector-set! data y (vector-copy (vector-ref image-data y))))
(image::create (image:width image)
(image:height image)
data)))
(define (image::parse-size size-str)
(with-input-from-string size-str
(lambda ()
(let ((width (read))
(height (read)))
(if (and (integer? width)
(integer? height))
(values width height)
(error "Invalid size string: ~s" size-str))))))
(define (image::sc-vertically image size)
"Carve a seam vertically."
(dotimes (i size)
(let ((energy-map (time (image::make-energy-map image))))
(let1 seam (time (image::find-vertical-seam energy-map))
(image::carve-seam image seam)
(image:set-width! image (- (image:width image) 1))
(image::carve-seam energy-map seam)
(image:set-width! energy-map (- (image:width energy-map) 1))
)))
#t)
(define (image::sc-vertically-file input output width-shrink)
(let1 image (image::load-ppm-raw input)
(image::sc-vertically image
(or width-shrink
(round->exact
(/ (image:width image) 2))))
(image::save-ppm-raw image output)))
(define (image::carve-seam image seam)
(let* ((width (image:width image))
(new-width (- width 1)))
(vector-map!
(lambda (y row)
(let ((seam-x (caar seam))
(seam-y (cdar seam))
(new-row (vector-copy row 0 new-width)))
(vector-copy! new-row seam-x
row (+ seam-x 1) width)
new-row))
(image:data image)))
#t)
(define (image::mark-seam image seam)
(dotimes (y (image:height image))
(let ((seam-x (caar seam))
(seam-y (cdar seam)))
(unless (eq? y seam-y)
(error ""))
(image:set-pixel image seam-x seam-y
(pixel:create 255 0 0))
(set! seam (cdr seam)))))
(define (image::find-vertical-seam energy-map)
(let ((width (image:width energy-map))
(height (image:height energy-map)))
(let* ((range-width 50)
(init-search-begin
(random-integer (max (- width range-width) 0))
)
(init-search-end
(min (max (+ init-search-begin range-width)
(- width 1)))))
(let1 start-x
(let loop((min-energy 0)
(min-x init-search-begin)
(x 0))
(if (<= x init-search-end)
(if (> min-energy (image:get-pixel energy-map x 0))
(loop (image:get-pixel energy-map x 0) x (+ x 1))
(loop min-energy min-x (+ x 1)))
min-x))
(let ((cost-map (image::create width height)))
(image:set-pixel cost-map start-x 0 (cons 0 #f))
(let ((choose-prevline-minpixel
(lambda (x prev-row)
(let ((left (image:row-get-pixel prev-row (- x 1) #f))
(center (image:row-get-pixel prev-row x #f))
(right (image:row-get-pixel prev-row (+ x 1) #f)))
(let ((min-x 0)
(min-cost +inf.0))
(when (and left (< (car left) min-cost))
(set! min-x (- x 1))
(set! min-cost (car left)))
(when (and center (<= (car center) min-cost))
(set! min-x x)
(set! min-cost (car center)))
(when (and right (< (car right) min-cost))
(set! min-x (+ x 1))
(set! min-cost (car right)))
(values min-cost min-x)
)))))
(let1 prev-row (vector-ref (image:data cost-map) 0)
(vector-for-each
(lambda (y row)
(unless (eq? y 0)
(do ((x (max 0 (- start-x y)) (+ x 1)))
((>= x (min (+ start-x y) width)))
(receive (min-cost min-x)
(choose-prevline-minpixel x prev-row)
(vector-set!
row x
(cons (+ (image:get-pixel energy-map x y) min-cost)
min-x)))))
(set! prev-row row))
(image:data cost-map)))
)
;; cost map was build. backtrace it
;; first, find end point
(let* ((min-energy-x (max 0 (+ 1 (- start-x height))))
(min-energy-cost-pixel (image:get-pixel cost-map
min-energy-x
(- height 1))))
(min (- (+ start-x height) 1)
(- width 1))
(do ((x (max 0 (+ 1 (- start-x height))) (+ x 1)))
((>= x (min (- (+ start-x height) 1)
(- width 1))))
(let ((cost-pixel (image:get-pixel cost-map x (- height 1))))
(when (< (car cost-pixel) (car min-energy-cost-pixel))
(set! min-energy-cost-pixel cost-pixel)
(set! min-energy-x x))))
(let loop((seam ())
(x min-energy-x)
(y (- height 1)))
(if (< y 0)
seam
(let1 cost-pixel (image:get-pixel cost-map x y)
(loop (cons (cons x y) seam)
(cdr cost-pixel)
(- y 1)))))))))))
(define (image::make-energy-map image . rest)
(apply image::make-energy-map-simple-diff image rest))
(define-syntax image::sobel-operator-horizontal
(syntax-rules ()
((_ x-1y-1 x+1y-1 x-1y x+1y x-1y+1 x+1y+1)
(- (+ x+1y-1 (* 2 x+1y) x+1y+1)
x-1y-1 (* 2 x-1y) x-1y+1))))
(define-syntax image::sobel-operator-vertical
(syntax-rules ()
((_ x-1y-1 xy-1 x+1y-1 x-1y+1 xy+1 x+1y+1)
(- (+ x-1y+1 (* 2 xy+1) x+1y+1)
x-1y-1 (* 2 xy-1) x+1y-1))))
(define (image::make-energy-map-simple-diff image . rest)
"Simple differential"
(let-optionals* rest
((normalize? #f))
(let* ((width (image:width image))
(height (image:height image))
(norm-map
(image::create
(image:width image) (image:height image)
(vector-map
(lambda (y row)
(vector-map
(lambda (x pixel)
(pixel:norm pixel))
row))
(image:data image))))
(energy-map (image::create (image:width image)
(image:height image)))
(max-energy 0)
(norm-map-data (image:data norm-map)))
(let ((row-1 (vector-ref norm-map-data 0))
(row0 (vector-ref norm-map-data 0))
(row+1 (vector-ref norm-map-data 1)))
(vector-for-each
(lambda (y row)
(let ((P-1 (lambda (x)
(image:row-get-pixel
row-1 x #f)))
(P0 (lambda (x)
(image:row-get-pixel row0 x #f)))
(P+1 (lambda (x)
(image:row-get-pixel
row+1 x #f))))
(let ((x-1y-1 (P-1 -1)) (xy-1 (P-1 0)) (x+1y-1 (P-1 1))
(x-1y (P0 -1)) (xy (P0 0)) (x+1y (P0 1))
(x-1y+1 (P+1 -1)) (xy+1 (P+1 0)) (x+1y+1 (P+1 1)))
(vector-map!
(lambda (x _)
(let ((dx (abs (image::sobel-operator-horizontal
x-1y-1 x+1y-1 x-1y x+1y x-1y+1 x+1y+1)))
(dy (abs (image::sobel-operator-vertical
x-1y-1 xy-1 x+1y-1 x-1y+1 xy+1 x+1y+1))))
(let1 x+2 (+ x 2)
(when (< x width)
(set! x-1y-1 xy-1) (set! x-1y xy )
(set! x-1y+1 xy+1) (set! xy-1 x+1y-1)
(set! xy x+1y ) (set! xy+1 x+1y+1)
(set! x+1y-1 (P-1 x+2))
(set! x+1y (P0 x+2))
(set! x+1y+1 (P+1 x+2))))
(let1 e (+ dx dy)
(set! max-energy (max e max-energy))
e)))
row)))
(set! row-1 row0) (set! row0 row+1)
(set! row+1 (if (>= y (- height 2))
(vector-ref norm-map-data (- height 1))
(vector-ref norm-map-data (+ y 2)))))
(image:data energy-map)))
;; normalize
(when (and #?=normalize? (> max-energy 255))
(let1 scale (/ 255 max-energy)
(dotimes (y (image:height energy-map))
(dotimes (x (image:width energy-map))
(image:set-pixel energy-map x y
(round->exact
(* scale (image:get-pixel energy-map x y))))))))
energy-map
)))
(define (image::seam-carving image width height)
(let ((width-delta (- (image:width image) width))
(height-delta (- (image:height image) height)))
(when (< width-delta 0)
(error "Width enlarging is not supported."))
(when (< height-delta 0)
(error "Height enlarging is not supported."))
(dotimes (i width-delta)
(image::sc-vertically image))
image))
(define (main args)
(let-args (cdr args)
((output "-o|output=s" #f)
(width-shrink "-w|--width-shrink=i" #f)
. restargs)
(let-optionals* restargs
((input (standard-input-port)))
(image::sc-vertically-file input output width-shrink)))
0)
| true |
8f8849e488deebd0f9273fe094942a8afbe9ed91
|
beac83b9c75b88060f4af609498541cf84437fd3
|
/site/render-html.ss
|
e3ca3c7bacbaf4d926e450d10fef5ca446bd2381
|
[] |
no_license
|
nuprl/prl-website
|
272ce3b9edd5b3ada23798a694f6cb7c6d510776
|
31a321f629a62f945968c3e4c59d180de0f656f6
|
refs/heads/master
| 2021-05-16T02:06:38.847789 | 2016-09-16T14:41:22 | 2016-09-16T14:41:22 | 412,044 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 3,181 |
ss
|
render-html.ss
|
(module render-html scheme
(require
(lib "list.ss")
(lib "xml.ss" "xml"))
;first filename in the list is the actual name, others are redirects
(define all-files
'(("Home" "content/home.ss" ("home.html" "index.html") #t)
("Projects" "content/projects.ss" ("projects.html" "Projects.html") #f) ;not visible
("People" "people-list.ss" ("people.html" "People.html") #t)
("Photo gallery" "people-gallery.ss" ("photos.html" "gallery/index.html") #f)
("Publications" "recent-publications.ss" ("recent_publications.html" "Publications.html") #t)
("All publications" "all-publications.ss" ("all_publications.html") #f)
("Seminars" "content/seminars.ss" ("seminars.html" "Seminars.html") #t)))
(define toplevel-files
(filter cadddr all-files))
(define filenames caddr)
(define (apply-general-style sxml page-name)
`(html
(head (title ,(string-append page-name
" - Programming Research Laboratory - Northeastern University"))
(link ((rel "stylesheet") (type "text/css") (href "static/prl.css"))))
(body
(a ((name "top")) "")
(div ((class "sidebar"))
(a ((href "home.html"))
(img ((src "static/prl.png"))))
(ul ;links to other PRL pages
,@(map
(lambda (page-stuff)
`(li (a ((href ,(car (filenames page-stuff)))
(class ,(if (string=? (car page-stuff) page-name)
"internal-self-link"
"internal-link")))
,(car page-stuff))))
toplevel-files)))
(div ((class "mainstream"))
,@(if (string=? "Home" page-name) '() (list `(h1 ,page-name)))
,sxml)
(div ((class "footer"))
"Built with " (a ((href "http://www.racket-lang.org")) "Racket")))))
; String[file name] -> Void
; effect: create or overwrite file.html with page
(define (produce-page page-stuff)
(let ((title (car page-stuff))
(sxml-source (string-append (cadr page-stuff))))
(let ((sxml (apply-general-style (dynamic-require sxml-source 'page) title))
(file.html (open-output-file (string-append "output/" (car (filenames page-stuff)))
#:exists 'replace)))
(write-xml/content (xexpr->xml sxml) file.html))))
;create redirects
(define (produce-redirects)
(call-with-output-file "output/.htaccess" #:exists 'replace
(lambda (out)
(fprintf out "IndexIgnore */*~%")
(fprintf out "DirectoryIndex home.html~%")
(for-each
(lambda (page-stuff)
(for-each
(lambda (alternative)
(fprintf out
"Redirect ~a ~a ~%"
alternative (string-append "http://www.ccs.neu.edu/research/prl/"
(car (filenames page-stuff)))))
(cdr (filenames page-stuff))))
all-files))))
(for-each produce-page all-files)
(produce-redirects)
)
| false |
1972d09281f52a9b97a9fdf54e38ce007fc1bd30
|
5355071004ad420028a218457c14cb8f7aa52fe4
|
/1.2/e-1.17.scm
|
66a767f758d44b780987087281f3b5db1ccd7eff
|
[] |
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,192 |
scm
|
e-1.17.scm
|
; Exercise 1.17.
;
; The exponentiation algorithms in this section are based on
; performing exponentiation by means of repeated multiplication.
; In a similar way, one can perform integer multiplication by means of repeated addition.
; The following multiplication procedure (in which it is assumed that our language can only add, not multiply)
; is analogous to the expt procedure:
; (define (* a b)
; (if (= b 0)
; 0
; (+ a (* a (- b 1)))))
; This algorithm takes a number of steps that is linear in b.
; Now suppose we include, together with addition, operations double,
; which doubles an integer, and halve, which divides an (even) integer by 2.
; Using these, design a multiplication procedure analogous to
; fast-expt that uses a logarithmic number of steps.
; --------------------------------
; First we define needed auxillary procedures
(load "../common.scm")
; Recursive procedure which halves the problem size in every new call have
; logarithmic order of growth
(define (fast-mult a b)
(cond ((= b 0) 0)
((even? b) (double (fast-mult a (halve b))))
(else (+ a (fast-mult a (- b 1))))))
(display (fast-mult 220000 38000003))
(newline)
| false |
667ee5309692a299ebf29e7d8018e0cda65f84be
|
4fd95c081ccef6afc8845c94fedbe19699b115b6
|
/chapter_3/3.80.scm
|
b0e910cb7201d977d053bbbadb4bfb67c6d75339
|
[
"MIT"
] |
permissive
|
ceoro9/sicp
|
61ff130e655e705bafb39b4d336057bd3996195d
|
7c0000f4ec4adc713f399dc12a0596c770bd2783
|
refs/heads/master
| 2020-05-03T09:41:04.531521 | 2019-08-08T12:14:35 | 2019-08-08T12:14:35 | 178,560,765 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,971 |
scm
|
3.80.scm
|
(define (force delayed-object) (delayed-object))
(define-syntax delay
(syntax-rules ()
((_ exp) (lambda () exp))))
(define-syntax cons-stream
(syntax-rules ()
((_ a b) (cons a (delay b)))))
(define (stream-car s) (car s))
(define (stream-cdr s) (force (cdr s)))
(define the-empty-stream '())
(define (stream-null? s) (eq? s the-empty-stream))
(define (stream-map proc . argstreams)
(if (stream-null? (car argstreams))
the-empty-stream
(cons-stream
(apply proc (map stream-car argstreams))
(apply stream-map
(cons proc (map stream-cdr argstreams))))))
(define (stream-ref s n)
(newline)
(display (stream-car s))
(if (= n 0)
(stream-car s)
(stream-ref (stream-cdr s) (- n 1))))
(define (add-streams s1 s2)
(stream-map + s1 s2))
(define (stream-scale s factor)
(stream-map (lambda (x) (* x factor)) s))
; -----------------------------------------------------------------
; -----------------------------------------------------------------
; -----------------------------------------------------------------
(define (integral delayed-integrand initial-value dt)
(cons-stream
initial-value
(let ((integrand (force delayed-integrand)))
(if (stream-null? integrand)
the-empty-stream
(integral (delay (stream-cdr integrand))
(+ (* dt (stream-car integrand))
initial-value)
dt)))))
(define (RLC R L C dt)
(lambda (vc0 il0)
(define vc
(integral
(delay (stream-scale il (/ -1 C)))
vc0
dt))
(define il
(integral
(delay
(add-streams
(stream-scale vc (/ 1 L))
(stream-scale il (/ (* R -1) L))))
il0
dt))
(stream-map cons vc il)))
(define rlc-example (RLC 1 1 0.2 0.1))
(define result (rlc-example 10 0))
(stream-ref result 10)
| true |
80a2096c54c1a1b597bec6957c303383125f034b
|
ac2a3544b88444eabf12b68a9bce08941cd62581
|
/contrib/GambitREPL/emacs.scm
|
f0655c77f62edba641ebb26cebbe41d688444beb
|
[
"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 | 15,245 |
scm
|
emacs.scm
|
;;;============================================================================
;;; File: "emacs.scm"
;;; Copyright (c) 2014-2015 by Marc Feeley, All Rights Reserved.
;;;============================================================================
(##namespace ("emacs#"))
(##include "~~lib/gambit#.scm")
(##include "~~lib/_gambit#.scm")
(##include "emacs#.scm")
(##include "intf#.scm")
(##include "json#.scm")
(##include "tar#.scm")
(##include "url#.scm")
(##namespace
(""
repl
repl-eval)
("gr#"
generic-event-handler)
)
(declare
(standard-bindings)
(extended-bindings)
(block)
(fixnum)
;;(not safe)
)
;;;============================================================================
;; emacs code (in JavaScript) must be in the app bundle otherwise
;; the app violates clause 2.8 of the App Store Review Guidelines:
;; "Apps that install or launch other executable code will be rejected".
(define emacs-in-bundle? #f)
(set! emacs-in-bundle? #t)
(define emacs-root-dir (path-expand (if emacs-in-bundle? "~~/emacs" "~/emacs")))
(define emacs-version-file (path-expand "v1" emacs-root-dir))
(define emacs-root-html-file (path-expand "GambitREPL.html" emacs-root-dir))
(define emacs-tar-file (##path-normalize (path-expand "~~/emacs.tgz")))
(define emacs-webView 4)
(define emacs-initialized? #f)
(define (emacs . files-to-visit)
(hide-toolbar)
(set-event-handler
(lambda (old-event-handler) emacs-event-handler))
(set-navigation -1)
(show-view emacs-webView)
(if (not emacs-initialized?)
(begin
(emacs-init files-to-visit)
(set! emacs-initialized? #t))
(emacs-visit-files files-to-visit))
(show-view emacs-webView #t #t))
(define (set-generic-keys)
(set-ext-keys
emacs-webView
"*^C+?/\\-,.2406835179'\"(`~:;)@#"
"\003\u2191\u2190\030\u2193{}\u2192[]<>C=_*^+!?/\\-,.2406835179'\"(`~:;)@#"
"\u2190\u2191\u2190\u2190\u2193\u2192\u2192\u2192\003\004{}\t\007\023[]\033\030\032<>C=_*^+&$/\\-|%2406835179'\"(`~:;)@#"))
(define (set-scheme-keys)
(set-ext-keys
emacs-webView
"*^C+?/\\-,.2406835179'\"(`~:;)@#"
"s\u2191\u2190L\u2193l\u03bb\u2192k\003<>C=_*^+!?/\\-,.2406835179'\"(`~:;)@#"
"s\u2191\u2190L\u2193l\u03bb\u2192k\003{}\t\004\007[]\033\023\030<>C=_*^+&$/\\-|%2406835179'\"(`~:;)@#"))
(define (emacs-init files-to-visit)
(if (equal? CFBundleDisplayName "Not Emacs")
(set-generic-keys)
(set-scheme-keys))
(if (and (not emacs-in-bundle?)
(not (eq? 'regular
(with-exception-catcher
(lambda (e) #f)
(lambda () (file-type emacs-version-file))))))
(parameterize ((current-directory (path-directory emacs-root-dir)))
(tar-write-unchecked (tar-unpack-file emacs-tar-file #t))))
(eval-js-in-webView
emacs-webView
(string-append "var filesToVisit = "
(json-encode (list->vector files-to-visit))
";"))
(set-webView-content-from-file emacs-webView emacs-root-html-file))
(define (emacs-visit-files files-to-visit)
(eval-js-in-webView
emacs-webView
(string-append "visitFiles("
(json-encode (list->vector files-to-visit))
");")))
;;;----------------------------------------------------------------------------
(define (emacs-event-handler event)
(define (respond request response)
(eval-js-in-webView
emacs-webView
(string-append "receiveResponse("
(number->string (table-ref request "requestId"))
","
(json-encode response)
");")))
(cond ((has-prefix? event "event:") =>
(lambda (rest)
(let ((request (json-decode (url-decode rest))))
(let ((method (table-ref request "method")))
(respond
request
(with-exception-catcher
(lambda (e)
(display
(call-with-output-string
""
(lambda (p) (display-exception e p)))
(repl-output-port))
(call-with-output-string
""
(lambda (p) (display-exception e p))))
(lambda ()
(cond ((equal? method "fileType")
(do-fileType request))
((equal? method "getDirectory")
(do-getDirectory request))
((equal? method "getFileContents")
(do-getFileContents request))
((equal? method "setFileContents")
(do-setFileContents request))
((equal? method "deleteFile")
(do-deleteFile request))
((equal? method "remapDir")
(do-remapDir request))
((equal? method "killTerminal")
(do-killTerminal request))
((equal? method "resetKeyboard")
(do-resetKeyboard request))
((equal? method "makeProcess")
(do-makeProcess request))
((equal? method "startProcess")
(do-startProcess request))
((equal? method "killProcess")
(do-killProcess request))
((equal? method "sendProcessInterrupt")
(do-sendProcessInterrupt request))
((equal? method "sendProcessInput")
(do-sendProcessInput request))
((equal? method "finishSetupEmacs")
(do-finishSetupEmacs request))
(else
'())))))))))
(else
(generic-event-handler event))))
(define (do-fileType request)
(let ((path (table-ref request "path" "")))
(with-exception-catcher
(lambda (e)
'())
(lambda ()
(symbol->string (file-type path))))))
(define (do-getDirectory request)
(let ((path (table-ref request "path" "")))
(with-exception-catcher
(lambda (e)
'())
(lambda ()
(parameterize ((current-directory path))
(let ((cd (current-directory)))
(let ((files (directory-files (list path: cd))))
(list->table
(map (lambda (name)
(let ((fi (file-info name)))
(cons name
(list->table
(list (cons "name"
name)
(cons "path"
(path-expand name cd))
(cons "type"
(symbol->string (file-info-type fi)))
(cons "mode"
(file-info-mode fi))
(cons "nlinks"
(file-info-number-of-links fi))
(cons "size"
(file-info-size fi))
(cons "lastmod"
(time->int
(file-info-last-modification-time fi))))))))
files)))))))))
(define (time->int t)
(floor (inexact->exact (time->seconds t))))
(define (do-getFileContents request)
(let ((path (table-ref request "path" ""))
(nothrow (table-ref request "nothrow" #f)))
(with-exception-catcher
(lambda (e)
(vector '() '()))
(lambda ()
(let* ((content
(call-with-input-file
(list path: path char-encoding: 'UTF-8)
(lambda (p) (read-line p #f))))
(lastmod
(time->int
(file-last-modification-time path))))
(vector content lastmod))))))
(define (do-setFileContents request)
(let ((path (table-ref request "path" ""))
(content (table-ref request "content" ""))
(stamp (table-ref request "stamp" 0)))
(if (or (null? stamp)
(with-exception-catcher
(lambda (e)
#t)
(lambda ()
(equal? stamp
(time->int
(file-last-modification-time path))))))
(with-exception-catcher
(lambda (e)
'())
(lambda ()
(call-with-output-file
(list path: path char-encoding: 'UTF-8)
(lambda (p) (display content p)))
(time->int
(file-last-modification-time path))))
'())))
(define (do-deleteFile request)
(let ((path (table-ref request "path" "")))
(with-exception-catcher
(lambda (e)
'())
(lambda ()
(delete-file path)
'()))))
(define (do-remapDir request)
(let ((path (table-ref request "path" "")))
path))
(define (do-killTerminal request)
(if (not (equal? CFBundleDisplayName "Not Emacs"))
(begin
(show-toolbar)
(repl)))
'())
(define (do-resetKeyboard request)
(show-currentView)
'())
(define (do-makeProcess request)
(let ((process (table-ref request "process" "")))
(let ((thunk (eval (with-input-from-string process read))))
(if (procedure? thunk)
(setup-process-group-io!
(make-process thunk (void))
(lambda (processId output)
(eval-js-in-webView
emacs-webView
(string-append "receiveProcessOutput("
(number->string processId)
","
(json-encode output)
");"))))
'()))))
(define (do-startProcess request)
(let ((processId (table-ref request "processId" -1)))
(start-process! processId)
'()))
(define (do-killProcess request)
(let ((processId (table-ref request "processId" -1)))
(kill-process processId)
'()))
(define (do-sendProcessInterrupt request)
(let ((processId (table-ref request "processId" -1)))
(send-process-interrupt processId)
'()))
(define (do-sendProcessInput request)
(let ((processId (table-ref request "processId" -1))
(input (table-ref request "input" "")))
(send-process-input processId input)
'()))
(define (do-finishSetupEmacs request)
(setup-iCloudStatus)
(let ((splash (table-ref request "splash" #f)))
(if splash
(eval-js-in-webView
emacs-webView
(if (equal? CFBundleDisplayName "Not Emacs")
"ymacs.getActiveBuffer().signalInfo('<center><img src=\"icon.png\" style=\"width:128px;height:128px\"><h3>This is Not Emacs</h3>For help please use the Help menu</center>', true, 10000);
file_menu_item.getMenu().children(3).destroy();
help_menu_item.getMenu().children(3).destroy();"
"ymacs.getActiveBuffer().signalInfo('<center>For help please use the Help menu</center>', true, 5000);
withSchemeBuffer(function (buf) { });"))))
'())
(define (setup-iCloudStatus)
(eval-js-in-webView
emacs-webView
(if app-icloud-container-dir
"iCloudStatus_set(undefined);"
"iCloudStatus_set('iCloud unavailable');")))
;;;----------------------------------------------------------------------------
;; Process groups.
(define (process-output-pump-start! process-ports output-substring)
(define buf (make-string 1024))
(define (process-output)
(let ((out-rd-port (vector-ref process-ports 3)))
(let loop ()
(let ((n (read-substring buf 0 (string-length buf) out-rd-port 1)))
(output-substring buf 0 n)
(loop)))))
(let ((tgroup (make-thread-group 'process-output-pump #f)))
(thread-start! (make-thread
(lambda ()
(with-exception-catcher
(lambda (e)
#f)
process-output))
#f
tgroup))))
(define (make-process-ports process-group)
(receive (in-rd-port in-wr-port) (open-string-pipe '(direction: input permanent-close: #f buffering: #f))
(receive (out-wr-port out-rd-port) (open-string-pipe '(direction: output buffering: #f))
(begin
;; Hack... set the names of the ports
(##vector-set! in-rd-port 4 (lambda (port) '(stdin)))
(##vector-set! out-wr-port 4 (lambda (port) '(stdout)))
(vector in-rd-port in-wr-port out-wr-port out-rd-port process-group #f)))))
(define (setup-repl-channel! process-ports)
(let ((in-rd-port (vector-ref process-ports 0))
(out-wr-port (vector-ref process-ports 2))
(process-group (vector-ref process-ports 4)))
(let ((repl-channel (##make-repl-channel-ports in-rd-port out-wr-port)))
(table-set! repl-server#repl-channel-table process-group repl-channel))))
(define (make-process thunk name)
(let* ((process-group (make-thread-group 'process-group #f))
(process-ports (make-process-ports process-group))
(main-thread
(make-thread
(lambda () (setup-repl-channel! process-ports) (thunk))
name
process-group)))
(vector-set! process-ports 5 main-thread)
process-ports))
(define (start-process! processId)
(let ((process-ports (table-ref process-group-table processId #f)))
(if process-ports
(let ((main-thread (vector-ref process-ports 5)))
(thread-start! main-thread)))))
(define process-group-table (make-table))
(define process-group-counter 0)
(define (setup-process-group-io! process-ports send-output)
(let ((processId process-group-counter))
(set! process-group-counter (+ process-group-counter 1))
(table-set! process-group-table processId process-ports)
(process-output-pump-start!
process-ports
(lambda (str start end)
(send-output processId (substring str start end))))
processId))
(define (kill-process processId)
(let ((process-ports (table-ref process-group-table processId #f)))
(if process-ports
(begin
(table-set! process-group-table processId)
(let ((main-thread (vector-ref process-ports 5)))
(##thread-terminate! main-thread))))))
(define (send-process-interrupt processId)
(let ((process-ports (table-ref process-group-table processId #f)))
(if process-ports
(let ((main-thread (vector-ref process-ports 5)))
(##thread-interrupt! main-thread)))))
(define (send-process-input processId input)
(let ((process-ports (table-ref process-group-table processId #f)))
(if process-ports
(let ((port (vector-ref process-ports 1)))
(if (string? input)
(begin
(display input port)
(force-output port))
(close-output-port port))))))
;;;============================================================================
| false |
7453d1142860fded753cfc233dadccfdc25ec3f1
|
c7d69c2477eceec0dabdf0510b395febf8094850
|
/scm/scratch-truck.scm
|
0793b5478eda9449897e1478c6afba0165f95e1c
|
[] |
no_license
|
Adellica/cocoscheme
|
2daafb6f2fe9935c679d04a2a2484a87ddcec3a7
|
1d92626a926696042ba917cc4fd1bf7cb76cd431
|
refs/heads/master
| 2016-09-15T17:29:15.200258 | 2012-11-16T09:47:54 | 2012-11-16T09:47:54 | 6,510,594 | 4 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 5,610 |
scm
|
scratch-truck.scm
|
(use chickmunk)
;; string is a svg path,
;; typically m x1,y2 x2,y2 .....
(define (string->path str)
(map (lambda (str)
(map string->number (string-split str ",")))
(string-split
(string-filter
(o not char-alphabetic?)
str) " ")))
;; path coordinates are relative
;; make them absolute
(define (path->vertices path)
(let loop ([curr (car path)]
[result (list (car path))]
[path (cdr path)])
(if (null? path)
(reverse result)
(let ([pos (map + curr (car path))])
(loop pos (cons pos result) (cdr path))))))
;; very untidy
;; paths coord 0,0 is top-left
(define (absolute-path path)
(map (lambda (pos) (list (car pos) (- 100 (cadr pos)))) path))
(define (string->vertices str)
(absolute-path (path->vertices (string->path str))))
(begin
(define static-nodes
(let ([ms (lambda (x1 y1 x2 y2)
`(segment (friction 0.9)
(radius 1.0)
(endpoints ((,x1 ,y1)
(,x2 ,y2)))))])
`(space ((gravity (0 -400))
(iterations 10))
(body ((static 1))
,(ms 2 150 760 150)
,(ms 2 150 2 300)
,(ms 2 500 200 500)
,(ms 100 350 300 400)
,(ms 300 400 500 350)
,(ms 500 350 800 500)
,(ms 800 500 1000 450)
,(ms 1000 450 1050 480)
,(ms 1050 480 1100 450)
,(ms 1100 450 2000 500)
,(ms 2000 500 2050 550)
,(ms 2050 550 2100 500)
,(ms 2100 500 2500 500)
,(ms 2800 500 2200 100)
,(ms 2200 100 1700 200)
,(ms 1600 180 1500 180)
,(ms 1500 180 1000 150)
,(ms 1000 150 970 180)
,(ms 970 180 940 150)
,(ms 940 150 910 180)
,(ms 910 180 880 150)
,(ms 880 150 850 180)
,(ms 850 180 820 150)
,(ms 820 150 790 180)
,(ms 790 180 760 150)
;; wall behind starting-position
,(ms 2 500 2 550)
;; "secret" area, going left
,(ms -200 300 -500 300)
,(ms -500 300 -1000 500)
;; steep hill:
,(ms -1000 500 -2000 1800)
;; jumpable platou
,(ms -2000 1800 -2500 1700)
;; platou 'fence'
,(ms -2500 1700 -2600 1800)
;; jump platform (you land here after the big jump)
,(ms -1800 1700 -1200 1700)
,(ms -1200 1700 -50 800)
,(ms -50 800 2 550)
))))
(define space (nodes->space static-nodes)))
(define truck-nodes
(let ([bpos '(100 600)]
[f 0.3] [fw 4])
`((wheel-rear . (body ((pos ,bpos))
(circle (radius 20)
(elasticity 0)
(friction ,fw)
(offset (18.6 15)))))
(wheel-front . (body ((pos ,bpos))
(circle (radius 20)
(elasticity 0)
(friction ,fw)
(offset (80 15)))))
(truck . (body ((id truck)
(pos ,bpos))
(poly (id bottom) (friction ,f)
(vertices ,(string->vertices "m 28.469775,55.676233 6.432735,8.8445 30.252919,-0.2837 6.574601,-8.5608 z")))
(poly (id cabin) (friction ,f)
(vertices ,(string->vertices "m 72.328529,49.638133 -13.636867,-8.41884 -14.851595,0.28373 -0.993062,7.56761 z")))
(poly (id body) (friction ,f)
(vertices ,(string->vertices "m 13.760046,53.548333 14.709729,2.1279 43.260255,0 13.928338,-0.4628 0.0233,-4.866 -13.353131,-0.7093 -29.481523,-0.5675 -29.337497,0.8431 z")))
(poly (id front) (friction ,f)
(vertices ,(string->vertices "m 85.658368,55.213433 8.615049,6.705 -1.844257,-7.4879 -6.7475,-4.0831 z")))
(poly (id rear) (friction ,f)
(vertices ,(string->vertices "m 3.3550631,50.205533 0.3945653,9.8376 3.152084,0.5054 6.8583336,-7.0002 -0.250537,-3.6346 z"))))))))
(define truck #f)
(define wf #f)
(define wr #f)
(define (reset-space-with-truck)
(define myspace (nodes->space static-nodes 0.01))
(space-set-gravity myspace (v 0 -1800))
(define bobo (map (lambda (spec) (cons (car spec) (caar (space-add myspace (cdr spec) 0.01)))) truck-nodes))
(set! truck (alist-ref 'truck bobo))
(set! wf (alist-ref 'wheel-front bobo))
(set! wr (alist-ref 'wheel-rear bobo))
(define pivot-joint1 (pivot-joint-new truck wr (vadd (v 18.6 15) (v 100 600))))
(space-add-constraint myspace pivot-joint1)
(define pivot-joint2 (pivot-joint-new truck wf (vadd (v 80 15) (v 100 600))))
(space-add-constraint myspace pivot-joint2)
(body-set-ang-vel-limit wr 60)
(body-set-ang-vel-limit wf 60)
(set! space myspace))
(reset-space-with-truck)
(define (*callback* sender)
(reset-space-with-truck))
| false |
1bb48fe2a634d735d4c218d9744d4cd0edec6c47
|
d474cce91812fbcdf351f8c27ddfb999e5b4b29b
|
/sdl2/mouse-types.ss
|
08797bf818a05f40f3251a37ab2f804d3c11905e
|
[] |
no_license
|
localchart/thunderchez
|
8c70ccb2d55210207f0ee1a5df88a52362d2db27
|
9af3026617b1fb465167d3907416f482e25ef791
|
refs/heads/master
| 2021-01-22T00:20:15.576577 | 2016-08-17T11:49:37 | 2016-08-17T11:49:37 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 887 |
ss
|
mouse-types.ss
|
(define-enumeration* sdl-system-cursor
(arrow ; arrow */
i-beam ; i-beam */
wait ; wait */
crosshair ; crosshair */
waitarrow ; small wait cursor (or wait if not available) */
size-nw-se ; double arrow pointing northwest and southeast */
size-ne-sw ; double arrow pointing northeast and southwest */
size-we ; double arrow pointing west and east */
size-ns ; double arrow pointing north and south */
size-all ; four pointed arrow pointing north, south, east, and west */
no ; slashed circle or crossbones */
hand ; hand */
num-system-cursors))
(define-ftype sdl-cursor-t (struct))
(define-flags sdl-button (left 1) (middle 2) (right 3) (x1 4) (x2 5))
(define (sdl-button-mask button)
(bitwise-arithmetic-shift-left
1
(- (cdr (assq button (flags-alist sdl-button-flags)))
1)))
| false |
9c27a2d00c4f0858dce75235f030b1dbfef6d8be
|
4eb5fea3fc3efb64b4fef2c7f3911368a6125b91
|
/tests/hh.scm
|
b1b8d7fdc43663b8991a9eb31fd127627451b7b8
|
[
"BSD-3-Clause"
] |
permissive
|
iraikov/chicken-sundials
|
fdf17bdd56343798923de8e463319b0ebb8d7283
|
ba503bd78385812fc1a206a658398642bd027b26
|
refs/heads/master
| 2021-06-15T22:09:55.237708 | 2021-05-02T03:54:44 | 2021-05-02T03:54:44 | 38,978,199 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 6,066 |
scm
|
hh.scm
|
;;
;; Hodgkin-Huxley pulse propagation model
;;
(import mathh sundials srfi-4 (chicken format) (chicken memory))
(define neg -)
(define pow expt)
(define TEND 250.0)
;; Model parameters
(define (I_stim t) 10)
(define C_m 1)
(define E_Na 50)
(define E_K -77)
(define E_L -54.4)
(define gbar_Na 120)
(define gbar_K 36)
(define g_L 0.3)
;; Rate functions
(define (amf v) (* 0.1 (/ (+ v 40) (- 1.0 (exp (/ (neg (+ v 40)) 10))))))
(define (bmf v) (* 4.0 (exp (/ (neg (+ v 65)) 18))))
(define (ahf v) (* 0.07 (exp (/ (neg (+ v 65)) 20))))
(define (bhf v) (/ 1.0 (+ 1.0 (exp (/ (neg (+ v 35)) 10)))))
(define (anf v) (* 0.01 (/ (+ v 55) (- 1 (exp (/ (neg (+ v 55)) 10))))))
(define (bnf v) (* 0.125 (exp (/ (neg (+ v 65)) 80))))
;; Model equations
(define (rhs t yy)
(let ((v (f64vector-ref yy 0))
(m (f64vector-ref yy 1))
(h (f64vector-ref yy 2))
(n (f64vector-ref yy 3)))
;; transition rates at current step
(let ((am (amf v))
(an (anf v))
(ah (ahf v))
(bm (bmf v))
(bn (bnf v))
(bh (bhf v))
(g_Na (* gbar_Na (* h (pow m 3))))
(g_K (* gbar_K (pow n 4))))
(let (
;; currents
(I_Na (* (- v E_Na) g_Na))
(I_K (* (- v E_K) g_K))
(I_L (* g_L (- v E_L))))
(let (
;; state equations
(dm (- (* am (- 1 m)) (* bm m)))
(dh (- (* ah (- 1 h)) (* bh h)))
(dn (- (* an (- 1 n)) (* bn n)))
(dv (/ (- (I_stim t) (+ I_L I_Na I_K)) C_m))
)
(f64vector dv dm dh dn)
)))
))
(define (rhs/unsafe t yy yp _)
(let ((v (pointer-f64-ref yy))
(m (pointer-f64-ref (pointer+f64 yy 1)))
(h (pointer-f64-ref (pointer+f64 yy 2)))
(n (pointer-f64-ref (pointer+f64 yy 3))))
;; transition rates at current step
(let ((am (amf v))
(an (anf v))
(ah (ahf v))
(bm (bmf v))
(bn (bnf v))
(bh (bhf v))
(g_Na (* gbar_Na (* h (pow m 3))))
(g_K (* gbar_K (pow n 4))))
(let (
;; currents
(I_Na (* (- v E_Na) g_Na))
(I_K (* (- v E_K) g_K))
(I_L (* g_L (- v E_L))))
(let (
;; state equations
(dm (- (* am (- 1 m)) (* bm m)))
(dh (- (* ah (- 1 h)) (* bh h)))
(dn (- (* an (- 1 n)) (* bn n)))
(dv (/ (- (I_stim t) I_L I_Na I_K) C_m))
)
(pointer-f64-set! yp dv)
(pointer-f64-set! (pointer+f64 yp 1) dm)
(pointer-f64-set! (pointer+f64 yp 2) dh)
(pointer-f64-set! (pointer+f64 yp 3) dn)
)))
))
(define (main)
(let ((yy (f64vector -65 0.052 0.596 0.317)) ;; v m h n
;; Integration limits
(t0 0.0)
(tf TEND)
(dt 1e-1))
;; CVODE initialization
(let ((solver (cvode-create-solver
t0 yy rhs
tstop: tf
abstol: 1e-4
reltol: 1e-4)))
;; In loop, call CVodeSolve, print results, and test for error.
(let recur ((tnext (+ t0 dt)) (iout 1))
(let ((flag (cvode-solve solver tnext)))
(if (negative? flag) (error 'main "CVODE solver error" flag))
;; (print-results/cvode solver)
(if (< tnext tf)
(recur (+ tnext dt) (+ 1 iout)))
))
(let ((yy (cvode-yy solver)))
(let ((v (f64vector-ref yy 0))
(m (f64vector-ref yy 1))
(h (f64vector-ref yy 2))
(n (f64vector-ref yy 3)))
(printf "v = ~A m = ~A h = ~A n = ~A ~%" v m h n)
))
(cvode-destroy-solver solver)
)))
(define (main/unsafe)
(let ((yy (f64vector -65 0.052 0.596 0.317)) ;; v m h n
;; Integration limits
(t0 0.0)
(tf TEND)
(dt 0.1))
;; CVODE initialization
(let ((solver (cvode-create-solver/unsafe
t0 yy rhs/unsafe
tstop: tf
abstol: 1e-4
reltol: 1e-4)))
;; In loop, call CVodeSolve, print results, and test for error.
(let recur ((tnext (+ t0 dt)) (iout 1))
(let ((flag (cvode-solve solver tnext)))
(if (negative? flag) (error 'main "CVODE solver error" flag))
(if (< tnext tf)
(recur (+ tnext dt) (+ 1 iout)))
))
(let ((yy (cvode-yy solver)))
(let ((v (f64vector-ref yy 0))
(m (f64vector-ref yy 1))
(h (f64vector-ref yy 2))
(n (f64vector-ref yy 3)))
(printf "v = ~A m = ~A h = ~A n = ~A ~%" v m h n)
))
(cvode-destroy-solver solver)
)))
(define (ida-main)
(define (ressc t yy yp)
(let ((dd (rhs t yy)))
(let ((dv (- (f64vector-ref yp 0) (f64vector-ref dd 0) ))
(dm (- (f64vector-ref yp 1) (f64vector-ref dd 1) ))
(dh (- (f64vector-ref yp 2) (f64vector-ref dd 2) ))
(dn (- (f64vector-ref yp 3) (f64vector-ref dd 3) ))
)
(f64vector dv dm dh dn))))
(let* ((yy (f64vector -65 0.052 0.596 0.317)) ;; v m h n
(yp (rhs 0.0 yy))
;; Integration limits
(t0 0.0)
(tf TEND)
(dt 1e-1))
;; IDA initialization
(let ((solver (ida-create-solver t0 yy yp ressc
tstop: tf
abstol: 1e-4
reltol: 1e-4)))
;; In loop, call IDASolve, print results, and test for error.
(let recur ((tnext (+ t0 dt)) (iout 1))
(let ((flag (ida-solve solver tnext)))
(if (negative? flag) (error 'main "IDA solver error" flag))
(print-results/ida solver)
(if (< tnext tf)
(recur (+ tnext dt) (+ 1 iout)))
))
(print-results/ida solver)
(ida-destroy-solver solver)
)))
(define (print-results/cvode solver )
(let ((yy (cvode-yy solver))
(t (cvode-t solver)))
(printf "~A ~A ~A ~A ~A~%"
t
(f64vector-ref yy 0)
(f64vector-ref yy 1)
(f64vector-ref yy 2)
(f64vector-ref yy 3)
)))
(define (print-results/ida solver )
(let ((yy (ida-yy solver))
(t (ida-t solver)))
(printf "~A ~A ~A ~A ~A~%"
t
(f64vector-ref yy 0)
(f64vector-ref yy 1)
(f64vector-ref yy 2)
(f64vector-ref yy 3)
)))
(ida-main)
(main)
(main/unsafe)
| false |
b8580b8474944e62178ad11ed3c080c3504821d2
|
185024f40e1ceed452781a1f3f57e6d16f57d799
|
/bonfire/point.ss
|
a6116a906fb5d34d8a65803f0dc9ccda9beaed76
|
[] |
no_license
|
noelwelsh/numeric
|
b82cd4ca9e4afb18df0129ec2231fc03f9b66450
|
ac4488cf8cc6f0558f74ca9b8faad0f198e76a84
|
refs/heads/master
| 2021-01-18T21:32:27.393991 | 2010-02-22T14:05:19 | 2010-02-22T14:05:19 | 275,898 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,121 |
ss
|
point.ss
|
#lang typed/scheme
;; Points represented as vectors
;;
;; A point is a vector of at least two elements, both of
;; which are numbers. This representation allows the vector
;; to contain other data, which may or may not be
;; interpreted by Bonfire.
;; The primary utility for this abstraction is to allow the
;; client to provide a wider range of data types, and hence
;; do less data munging
(define-type-alias Point (Vectorof Real))
(: point (Real * -> Point))
(define (point . vals)
(apply vector vals))
(: point-x (Point -> Real))
(define (point-x pt)
(vector-ref pt 0))
(: point-y (Point -> Real))
(define (point-y pt)
(vector-ref pt 1))
(: point-r (Point -> Real))
(define (point-r pt)
(vector-ref pt 2))
(: point-w (Point -> Real))
(define (point-w pt)
(vector-ref pt 2))
(: point-h (Point -> Real))
(define (point-h pt)
(vector-ref pt 3))
(: point-end-x (Point -> Real))
(define (point-end-x pt)
(vector-ref pt 2))
(: point-end-y (Point -> Real))
(define (point-end-y pt)
(vector-ref pt 3))
(provide
Point
point
point-x
point-y
point-r
point-w
point-h
point-end-x
point-end-y)
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.