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
6206a8a4314213d295570eb41de6e27762a8de8c
a8216d80b80e4cb429086f0f9ac62f91e09498d3
/lib/srfi/38.sld
4be2cee609bd9a153ed1c639310b2afbde3d7557
[ "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
559
sld
38.sld
(define-library (srfi 38) (import (chibi) (srfi 69) (chibi ast)) (export write-with-shared-structure write/ss read-with-shared-structure read/ss) (include "38.scm") (cond-expand (uvector ) (else (begin (define (list->uvector etype ls) (if (eq? etype U8) (let* ((len (length ls)) (bv (make-bytevector len))) (do ((i 0 (+ i 1)) (ls ls (cdr ls))) ((null? ls) bv) (bytevector-u8-set! bv i (car ls)))) (list->vector ls)))))))
false
9c2e3476e428d1d8408e513b5572f260fe833f5e
e1c580145992634f089af18940508f5c26d2e264
/umcu/packages/strelka.scm
62eb90ad094218a6d36cb11443a594edfb8d16eb
[]
no_license
inijman/guix-additions
8542592972e644a4ccd7b36ad4dd9b5631008fb5
b8e0e3f3b9598aade3103e9f491307fa06ece03d
refs/heads/master
2021-07-13T21:35:25.731179
2020-05-28T14:01:04
2020-05-28T14:01:04
142,980,977
0
0
null
2018-07-31T07:49:53
2018-07-31T07:49:53
null
UTF-8
Scheme
false
false
13,319
scm
strelka.scm
;;; GNU Guix --- Functional package management for GNU ;;; Copyright © 2016 Roel Janssen <[email protected]> ;;; ;;; This file is not officially part of GNU Guix. ;;; ;;; GNU Guix is free software; you can redistribute it and/or modify it ;;; under the terms of the GNU General Public License as published by ;;; the Free Software Foundation; either version 3 of the License, or (at ;;; your option) any later version. ;;; ;;; GNU Guix 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 GNU Guix. If not, see <http://www.gnu.org/licenses/>. ;; WARNING: This is non-free software. It will NEVER and SHOULD NEVER be ;; mainlined in GNU Guix. You should avoid using this package, and if you ;; can, please write a free replacement for it. ;; WARNING: This is non-free software. It will NEVER and SHOULD NEVER be ;; mainlined in GNU Guix. You should avoid using this package, and if you ;; can, please write a free replacement for it. (define-module (umcu packages strelka) #:use-module ((guix licenses) #:prefix license:) #:use-module (guix packages) #:use-module (guix download) #:use-module (guix build-system gnu) #:use-module (guix build-system cmake) #:use-module (gnu packages) #:use-module (gnu packages base) #:use-module (gnu packages bash) #:use-module (gnu packages boost) #:use-module (gnu packages bioinformatics) #:use-module (gnu packages compression) #:use-module (gnu packages curl) #:use-module (gnu packages documentation) #:use-module (gnu packages gcc) #:use-module (gnu packages graphviz) #:use-module (gnu packages perl) #:use-module (gnu packages shells) #:use-module (gnu packages python) #:use-module (gnu packages tls) #:use-module (gnu packages web) #:use-module (umcu packages boost) #:use-module (umcu packages vcftools)) (define-public strelka-1.0.15 (package (name "strelka") (version "1.0.15") (source (origin (method url-fetch) (uri (string-append ;;"ftp://strelka:''@ftp.illumina.com/v1-branch/v" ;;version "/strelka_workflow-" version ".tar.gz")) "https://sites.google.com/site/strelkasomaticvariantcaller/home/" "download/" name "_workflow-" version ".tar.gz")) (sha256 (base32 "1cwad2wlhdk09702ivblfiyv921af0al7s1gm1dn2d3b0v31qrp2")) (patches (list (search-patch "strelka-disable-tests.patch") (search-patch "strelka-disable-install.patch"))))) (build-system gnu-build-system) (arguments `(#:tests? #f #:phases (modify-phases %standard-phases (add-before 'install 'build-some-more (lambda _ (with-directory-excursion "strelka" (zero? (system* "make" "-j" (number->string (parallel-job-count)) "install"))))) (replace 'install (lambda* (#:key inputs outputs #:allow-other-keys) (let* ((out (assoc-ref outputs "out")) (perl-lib-dir (string-append out "/lib/perl5/site_perl/" ,(package-version perl))) (bin (string-append out "/bin")) (lib (string-append out "/lib")) (libexec (string-append out "/libexec"))) ;; Substitute the binary directories for samtools and bgzip. (substitute* '("src/perl/bin/configureStrelkaWorkflow.pl" "src/perl/libexec/callSomaticVariants.pl" "src/perl/libexec/consolidateResults.pl") (("my \\$samtoolsDir = File::Spec->catdir\\(\\$optDir,'samtools'\\);") (string-append "my $samtoolsDir = \"" (assoc-ref inputs "samtools") "/bin\";")) (("my \\$samtoolsBin = File::Spec->catfile\\(\\$optDir,'samtools','samtools'\\);") (string-append "my $samtoolsBin = \"" (assoc-ref inputs "samtools") "/bin/samtools\";"))) (substitute* "src/perl/libexec/consolidateResults.pl" (("my \\$bgzipBin = File::Spec->catfile\\(\\$optDir,'tabix','bgzip'\\);") (string-append "my $bgzipBin = \"" (assoc-ref inputs "htslib") "/bin/bgzip\";")) (("my \\$getHeaderCmd = \"bash") (string-append "my $getHeaderCmd = \"" (assoc-ref inputs "bash") "/bin/bash"))) (mkdir-p perl-lib-dir) (mkdir-p lib) (mkdir-p libexec) ;; Instead of patching out $optDir throughout the code, we can create ;; an empty directory so that these checks pass. We already patched the ;; path to samtools and bgzip, so this should be fine. (mkdir-p (string-append out "/opt/samtools")) (install-file "src/c++/libexec/countFastaBases" libexec) (install-file "src/perl/bin/configureStrelkaWorkflow.pl" bin) (install-file "src/perl/libexec/consolidateResults.pl" libexec) (install-file "src/perl/libexec/filterSomaticVariants.pl" libexec) (install-file "src/perl/libexec/callSomaticVariants.pl" libexec) (install-file "src/perl/lib/Utils.pm" perl-lib-dir) (install-file "strelka/src/bin/strelka2" bin) (install-file "strelka/src/bin/starling2" bin) (install-file "strelka/src/bin/strelkaSiteSimulator" bin) ;; Also add Utils.pm to the lib folder, because strelka manipulates ;; its own Perl path to search in this folder. (install-file "src/perl/lib/Utils.pm" lib) ;; The configureStrelkaWorkflow.pl script looks for the ;; strelka2 binary in the libexec directory. (system* "ln" "--symbolic" (string-append bin "/strelka2") (string-append libexec "/strelka2")))))))) (inputs `(("boost" ,boost) ("perl" ,perl) ("bash" ,bash) ("zlib" ,zlib) ("samtools" ,samtools))) (native-inputs `(("bash" ,bash) ("python" ,python-2))) (propagated-inputs `(("vcftools" ,vcftools) ("htslib" ,htslib))) (native-search-paths (package-native-search-paths perl)) (home-page "https://sites.google.com/site/strelkasomaticvariantcaller/") (synopsis "Somatic variant calling workflow for matched tumor-normal samples") (description "Analysis package designed to detect somatic SNVs and small indels from the aligned sequencing reads of matched tumor-normal samples") ;; WARNING: The license is "Illumina Open Source Software License 1". ;; This effectively makes it nonfree software. (license license:non-copyleft))) (define-public strelka-1.0.14 (package (inherit strelka-1.0.15) (name "strelka") (version "1.0.14") (source (origin (method url-fetch) (uri (string-append "ftp://strelka:''@ftp.illumina.com/v1-branch/v" version "/strelka_workflow-" version ".tar.gz")) (sha256 (base32 "0f9g2pkr1f7s4r8sxl53jxr2cjpyx53zf3va0jj8fxzavxiwmbmk")) (patches (list (search-patch "strelka-disable-tests.patch") (search-patch "strelka-disable-install.patch"))))) (propagated-inputs `(("vcftools" ,vcftools-0.1.14) ("htslib" ,htslib))))) (define-public codemin (package (name "codemin") (version "1.0.5") (source (origin (method url-fetch) (uri (string-append "https://github.com/Illumina/strelka/raw/" "5a993884687f2d92f794109e171d0bdeb95e504d" "/redist/CodeMin-1.0.5.tar.bz2")) (sha256 (base32 "1y8wsli1q626i80p3dmrc65p77ch164hj2sbxv497i9y89kvk35s")))) (build-system gnu-build-system) (arguments `(#:tests? #f ; There are no tests. #:phases (modify-phases %standard-phases (delete 'configure) (delete 'build) (replace 'install (lambda* (#:key outputs #:allow-other-keys) (let ((include-dir (string-append (assoc-ref outputs "out") "/include"))) (mkdir-p include-dir) (copy-recursively "include" include-dir))))))) (home-page "https://github.com/Illumina/strelka/tree/master/redist") (synopsis "Set of lightweight minimization functions.") (description "The CodeMin minimization library provides a set of lightweight minimization functions originally developed for the CodeAxe phylogenetic analysis package.") ;; MIT license. (license license:expat))) (define-public strelka-2.9.2 (package (name "strelka") (version "2.9.2") (source (origin (method url-fetch) (uri (string-append "https://github.com/Illumina/strelka/releases/download/v" version "/strelka-" version ".release_src.tar.bz2")) (sha256 (base32 "19bq2wzlxmnv8rx112y8z0sfvgsajnd0m945njmfy9p170qjqr27")) (patches (list (search-patch "strelka2-unbundle-dependencies.patch"))))) (build-system cmake-build-system) (arguments `(#:tests? #f #:phases (modify-phases %standard-phases (add-after 'unpack 'unbundle-dependencies (lambda* (#:key inputs outputs #:allow-other-keys) (substitute* "redist/CMakeLists.txt" ;; HTSlib (("superset\\(HTSLIB_DIR \"\\$\\{CMAKE_CURRENT_BINARY_DIR\\}/\\$\\{HTSLIB_PREFIX\\}\"\\)") (format #f "superset(HTSLIB_DIR \"~a/bin\")" (assoc-ref inputs "htslib"))) (("superset\\(HTSLIB_LIBRARY \"\\$\\{HTSLIB_DIR\\}/libhts.a\"\\)") (format #f "superset(HTSLIB_LIBRARY \"~a/lib/libhts.so\")" (assoc-ref inputs "htslib"))) ;; SAMtools (("set\\(SAMTOOLS_DIR \"\\$\\{CMAKE_CURRENT_BINARY_DIR}/\\$\\{SAMTOOLS_PREFIX\\}\"\\)") (format #f "set(SAMTOOLS_DIR \"~a/bin\")" (assoc-ref inputs "samtools"))) (("set\\(SAMTOOLS_LIBRARY \"\\$\\{SAMTOOLS_DIR\\}/libbam.a\"\\)") (format #f "set(SAMTOOLS_LIBRARY \"~a/lib/libbam.a\")" (assoc-ref inputs "samtools")))))) (add-after 'install 'install-shared-libraries (lambda* (#:key inputs outputs #:allow-other-keys) (let ((libdir (string-append (assoc-ref outputs "out") "/lib"))) (mkdir-p libdir) (map (lambda (file) (copy-file file (string-append libdir "/" (basename file)))) (find-files "." "\\.so"))))) (add-after 'install 'patch-python-bin (lambda* (#:key inputs outputs #:allow-other-keys) (let ((patch-path (string-append (assoc-ref outputs "out") "/lib/python"))) (substitute* (list (string-append patch-path "/makeRunScript.py") (string-append patch-path "/pyflow/pyflow.py")) (("/usr/bin/env python") (string-append (assoc-ref inputs "python") "/bin/python"))))))))) (inputs `(("boost" ,boost) ("perl" ,perl) ("bash" ,bash) ("zlib" ,zlib) ("samtools" ,samtools) ("rapidjson" ,rapidjson) ("codemin" ,codemin) ("curl" ,curl) ("xz" ,xz) ("openssl" ,openssl) ("samtools" ,samtools) ("zlib" ,zlib) ("python" ,python))) (native-inputs `(("bash" ,bash) ("python" ,python-2) ("doxygen" ,doxygen) ("graphviz" ,graphviz))) (propagated-inputs `(("vcftools" ,vcftools) ("htslib" ,htslib))) (native-search-paths (package-native-search-paths perl)) (home-page "https://github.com/Illumina/strelka") (synopsis "Small variant caller") (description "Strelka2 is a fast and accurate small variant caller optimized for analysis of germline variation in small cohorts and somatic variation in tumor/normal sample pairs. The germline caller employs an efficient tiered haplotype model to improve accuracy and provide read-backed phasing, adaptively selecting between assembly and a faster alignment-based haplotyping approach at each variant locus. The germline caller also analyzes input sequencing data using a mixture-model indel error estimation method to improve robustness to indel noise. The somatic calling model improves on the original Strelka method for liquid and late-stage tumor analysis by accounting for possible tumor cell contamination in the normal sample. A final empirical variant re-scoring step using random forest models trained on various call quality features has been added to both callers to further improve precision.") (license license:gpl3+))) (define-public strelka strelka-2.9.2)
false
ea5046df7d9c541f6feb89e755ba5b6acb4f3ecd
6488db22a3d849f94d56797297b2469a61ad22bf
/easyffi/runsilex.scm
c2c4e55ac3b75d880244bd77f0aabea953fce02f
[]
no_license
bazurbat/chicken-eggs
34d8707cecbbd4975a84ed9a0d7addb6e48899da
8e741148d6e0cd67a969513ce2a7fe23241df648
refs/heads/master
2020-05-18T05:06:02.090313
2015-11-18T16:07:12
2015-11-18T16:07:12
22,037,751
0
0
null
null
null
null
UTF-8
Scheme
false
false
139
scm
runsilex.scm
;;;; runsilex.scm ; ; Runs silex and generates easyffi.l.scm (require-extension silex) (lex "easyffi.l" "easyffi.l.scm" 'counters 'none)
false
e1ac86d69da915491399cfc60c245f6dfb6ff4bf
b9eb119317d72a6742dce6db5be8c1f78c7275ad
/racket/run-filter-subprocess.ss
32d1f440b250a6ab0edbe092f731b578a0ae9bbd
[]
no_license
offby1/doodles
be811b1004b262f69365d645a9ae837d87d7f707
316c4a0dedb8e4fde2da351a8de98a5725367901
refs/heads/master
2023-02-21T05:07:52.295903
2022-05-15T18:08:58
2022-05-15T18:08:58
512,608
2
1
null
2023-02-14T22:19:40
2010-02-11T04:24:52
Scheme
UTF-8
Scheme
false
false
2,272
ss
run-filter-subprocess.ss
;; this is something that's hard to do in Perl -- writing to, and ;; reading from, the same subprocess at once (run 'perldoc IPC::Open2' ;; for an explanation of how to do it in Perl). I'm not actually sure ;; that this technique is foolproof -- this program has worked the few ;; times I've run it, but multi-threaded stuff is tricky enough that ;; I'm still not convinced. Still, it seems reasonable. ;; The problem that I'm afraid of is deadlock. Eli Barzilay says this ;; technique (using separate threads to read and write) is fine. (define (writer-proc port) (let loop ((lines-written 0)) (when (< lines-written 100) (let ((datum (random 10))) (display datum port) (newline port) (fprintf (current-error-port) "Wrote ~s~%" datum) (loop (add1 lines-written))))) (close-output-port port)) (define (reader-proc port) (let loop () (let ((datum (read-line port))) (when (not (eof-object? datum)) (fprintf (current-error-port) "Got ~s~%" datum) (loop)))) (close-input-port port)) (define (find-exe-or-die fn) (or (find-executable-path fn) (find-executable-path (string-append fn ".exe")) (raise-user-error 'find-exe-or-die "Couldn't find executable ~s" fn))) (let ((program-name "grep")) (let-values (((proc readme writeme errors) (subprocess #f #f (current-error-port) (find-exe-or-die program-name) "7"))) (let ((reader-thread (thread (lambda () (reader-proc readme)))) (writer-thread (thread (lambda () (writer-proc writeme))))) (subprocess-wait proc) (when (not (zero? (subprocess-status proc))) (raise-user-error 'subprocess "~s returned non-zero exit status: ~a" program-name (subprocess-status proc))) ;; There are three waitable things here -- the subprocess, and ;; the two threads. It's not clear which subset of those three ;; I should wait on. ;; It probably doesn't hurt to wait on these, although they're ;; probably always going to be ready, since the subprocess has ;; exited. (for-each thread-wait (list writer-thread reader-thread)))))
false
90a515e38fd4f7ccb55d0c6637ab9ed3d6b32ca2
0bc4163b3571382861380e47eef4aa1afc862024
/scheme/keywords.scm
7a9b021593d3c14dcce8401f1c9849826235f52b
[]
no_license
mjgordon/fluxcadd
49f7c633d4430d98cfa0f24485bfc737fac1a321
afedf70e8a9b43563bb3fe5fdc2265260f4a981b
refs/heads/master
2023-07-21T10:19:36.544424
2023-07-08T00:19:06
2023-07-08T00:19:06
84,756,384
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,106
scm
keywords.scm
;;; Adding optional argument functionality ;;; Doesn't seem to work yet (define-syntax nil! (syntax-rules () ((_ x) (set! x '())))) (define-syntax defkeywords (syntax-rules () ((_ nargs kwargs body) (with-environment env (eval (macro-expand `(define ,(reduce (flip cons) (cons 'args) (reverse 'nargs)) (begin (with-environment env (let ((dict (apply make-hash args))) (map ($ (let* ((k (car %)) (s (atom->symbol k))) (eval `(define ,s ,(if (in? dict k) (dict k) (eval (get-from % 1)))) env))) (quote ,(treat-keywords 'kwargs))))) ,body)))))))) (define (treat-keywords args) (case (length args) ((0) []) ((1) `((,(car args) nil))) (else (let ((key (car args)) (meta (cadr args))) (if (eq? :default meta) (++ `((,key ,(caddr args))) (treat-keywords (cdddr args))) (++ `((,key ,nil)) (treat-keywords (cdr args))))))))
true
399abe2491bf063b0c6138c1fa558b982732fea3
63a1f38e64b0604377fbfa0d10d48545c609cc86
/two-state/tl.ss
f3fa15adc83ea284c105a192353c7012542e7006
[]
no_license
jeapostrophe/redex
d02b96b441f27e3afa1ef92726741ec026160944
8e5810e452878a4ab5153d19725cfc4cf2b0bf46
refs/heads/master
2016-09-06T00:55:02.265152
2013-10-31T01:24:11
2013-10-31T01:24:11
618,062
2
1
null
null
null
null
UTF-8
Scheme
false
false
10,798
ss
tl.ss
#lang scheme (require redex/reduction-semantics "set.ss") (provide tl-grammar free-vars_tl -->_tl get-marks-tl wcm-merge wcm-replace) ;; Grammar (define-language tl-grammar [e a (w ... e) (letrec ([sigma v] ...) e) (match w l ...) (wcm ([w w] ...) e) (c-c-m w ...) (abort e)] [l [(K x ...) => e] [else => e]] [a w (K a ...)] [w v x] [v (! sigma) ; XXX not good (λ (x ...) e) (K v ...)] [x variable-not-otherwise-mentioned] [K string] [sigma string] [Sigma mt (snoc Sigma [sigma -> v])] [e* (/ Sigma e)] [E (wcm ([v v] ...) F) F] [F hole (v ... E)] [TE (/ Sigma E)]) ;; Meta-functions ;;; Free vars (define-metafunction tl-grammar defined-vars_tl : Sigma -> (sigma ...) [(defined-vars_tl mt) ()] [(defined-vars_tl (snoc Sigma_1 [sigma_1 -> v])) ,(cons (term sigma_1) (term (defined-vars_tl Sigma_1)))]) (define-metafunction tl-grammar free-vars_tl : any -> any ; e* [(free-vars_tl (/ Sigma_1 e_1)) ,(set-sub (cons (term (free-vars_tl e_1)) (term (free-vars_tl Sigma_1))) (term (defined-vars_tl Sigma_1)))] ; Sigma [(free-vars_tl mt) ()] [(free-vars_tl (snoc Sigma_1 [sigma_1 -> v_1])) (sigma_1 (free-vars_tl Sigma_1) (free-vars_tl v_1))] ; e [(free-vars_tl (w_1 ... e_1)) ((free-vars_tl w_1) ... (free-vars_tl e_1))] [(free-vars_tl (letrec ([sigma_1 v_1] ...) e_1)) ,(set-sub (term ((free-vars_tl v_1) ... (free-vars_tl e_1))) (term (sigma_1 ...)))] [(free-vars_tl (match w_1 l_1 ...)) ((free-vars_tl w_1) (free-vars_tl l_1) ...)] [(free-vars_tl (wcm ([w_k w_v] ...) e_1)) ((free-vars_tl w_k) ... (free-vars_tl w_v) ... (free-vars_tl e_1))] [(free-vars_tl (c-c-m w_1 ...)) ((free-vars_tl w_1) ...)] [(free-vars_tl (abort e_1)) (free-vars_tl e_1)] ; l [(free-vars_tl [(K x_1 ...) => e_1]) ,(set-sub (term (free-vars_tl e_1)) (term (x_1 ...)))] [(free-vars_tl [else => e_1]) (free-vars_tl e_1)] ; a/w/v [(free-vars_tl x_1) x_1] [(free-vars_tl (! sigma_1)) sigma_1] [(free-vars_tl (λ (x_1 ...) e_1)) ,(set-sub (term (free-vars_tl e_1)) (term (x_1 ...)))] [(free-vars_tl (K a_1 ...)) ((free-vars_tl a_1) ...)]) ;;; Substitution (define-metafunction tl-grammar subst-e : x e e -> e [(subst-e x_s e_s a_1) (subst-a x_s e_s a_1)] [(subst-e x_s e_s (w_1 ... e_1)) ((subst-w x_s e_s w_1) ... (subst-e x_s e_s e_1))] [(subst-e x_s e_s (letrec ([sigma_1 v_1] ...) e_1)) (letrec ([sigma_1 (subst-v x_s e_s v_1)] ...) (subst-e x_s e_s e_1))] [(subst-e x_s e_s (wcm ([w_1 w_2]) e_1)) (wcm ([(subst-a x_s e_s w_1) (subst-a x_s e_s w_2)]) (subst-e x_s e_s e_1))] [(subst-e x_s e_s (c-c-m w_1 ...)) (c-c-m (subst-a x_s e_s w_1) ...)] [(subst-e x_s e_s (abort e_1)) (abort (subst-e x_s e_s e_1))] [(subst-e x_s e_s (match w_1 l_1 ...)) (match (subst-w x_s e_s w_1) (subst-l x_s e_s l_1) ...)]) (define-metafunction tl-grammar subst-l : x e l -> l [(subst-l x_s e_s [(K x_1 ...) => e_1]) [(K x_1 ...) => (subst-e x_s e_s e_1)] (side-condition (not (memq (term x_s) (term (x_1 ...)))))] [(subst-l x_s e_s l_1) l_1]) (define-metafunction tl-grammar subst-a : x e a -> e [(subst-a x_s e_s w_1) (subst-w x_s e_s w_1)] [(subst-a x_s e_s (K a_1 ...)) (K (subst-a x_s e_s a_1) ...)]) (define-metafunction tl-grammar subst-w : x e w -> e [(subst-w x_s e_s v_1) (subst-v x_s e_s v_1)] [(subst-w x_s e_s x_s) e_s] [(subst-w x_s e_s x_1) x_1 (side-condition (not (equal? (term x_s) (term x_1))))]) (define-metafunction tl-grammar subst-v : x e v -> e [(subst-v x_s e_s (λ (x_1 ...) e_1)) (λ (x_1 ...) e_1) (side-condition (memq (term x_s) (term (x_1 ...))))] [(subst-v x_s e_s (λ (x_1 ...) e_1)) ,(term-let ([(x_new ...) (variables-not-in (term e_s) (term (x_1 ...)))]) (term (λ (x_new ...) (subst-e x_s e_s (subst-e* (x_1 ...) (x_new ...) e_1))))) (side-condition (not (memq (term x_s) (term (x_1 ...)))))] [(subst-v x_s e_s (K v_1 ...)) (K (subst-v x_s e_s v_1) ...)] ;; All other values are atomic [(subst-v x_s e_s v_1) v_1]) (define-metafunction tl-grammar subst-e* : (x ...) (e ...) e -> e [(subst-e* () () e_1) e_1] [(subst-e* (x_1 x_2 ...) (e_1 e_2 ...) e_t) (subst-e x_1 e_1 (subst-e* (x_2 ...) (e_2 ...) e_t))]) ;;; Lookup (define-metafunction tl-grammar in-Sigma : Sigma sigma -> any [(in-Sigma mt sigma_1) (none)] [(in-Sigma (snoc Sigma_1 [sigma_1 -> v_1]) sigma_1) (some v_1)] [(in-Sigma (snoc Sigma_1 [sigma_1 -> v_1]) sigma_2) (in-Sigma Sigma_1 sigma_2) (side-condition (not (equal? (term sigma_1) (term sigma_2))))]) ;;; Synthetic terms (define-metafunction tl-grammar snoc* : Sigma ([sigma v] ...) -> Sigma [(snoc* Sigma_1 ()) Sigma_1] [(snoc* Sigma_1 ([sigma_1 v_1] [sigma_2 v_2] ...)) (snoc* (snoc Sigma_1 [sigma_1 -> v_1]) ([sigma_2 v_2] ...))]) (define-metafunction tl-grammar select : v ([v v] ...) -> v [(select v_t ()) ("none")] [(select v_t ([v_t v_vi] [v_k v_v] ...)) ("some" v_vi)] [(select v_t ([v_ki v_vi] [v_k v_v] ...)) (select v_t ([v_k v_v] ...)) (side-condition (not (equal? (term v_t) (term v_ki))))]) (define-metafunction tl-grammar select* : (v ...) ([v v] ...) -> v [(select* (v_t ...) ([v_k v_v] ...)) ("marks" (select v_t ([v_k v_v] ...)) ...)]) (define (any-in?-fun l1 l2) (for/or ([i1 (in-list l1)]) (for/or ([i2 (in-list l2)]) (equal? i1 i2)))) (define-metafunction tl-grammar any-in? : (v ...) (v ...) -> any [(any-in? (v_1 ...) (v_2 ...)) ,(any-in?-fun (term (v_1 ...)) (term (v_2 ...)))]) (define (->bool v) (not (not v))) (define-metafunction tl-grammar ∈ : v (v ...) -> any [(∈ v_1 (v_2 ...)) ,(->bool (member (term v_1) (term (v_2 ...))))]) (define-metafunction tl-grammar get-marks-tl : E (v ...) -> v [(get-marks-tl hole (v_t ...)) ("nil")] [(get-marks-tl (v_1 ... E_1) (v_t ...)) (get-marks-tl E_1 (v_t ...))] [(get-marks-tl (wcm ([v_k v_v] ...) F_1) (v_t ...)) ("cons" (select* (v_t ...) ([v_k v_v] ...)) (get-marks-tl F_1 (v_t ...))) (side-condition (term (any-in? (v_t ...) (v_k ...))))] [(get-marks-tl (wcm ([v_k v_v] ...) F_1) (v_t ...)) (get-marks-tl F_1 (v_t ...)) (side-condition (term (¬ (any-in? (v_t ...) (v_k ...)))))]) (define-metafunction tl-grammar wcm-replace : v v ([v v] ...) -> ([v v] ...) ; Add it if it is not present [(wcm-replace v_k v_v ([v_ki v_vi] ...)) ([v_k v_v] [v_ki v_vi] ...) (side-condition (term (¬ (∈ v_k (v_ki ...)))))] ; Replace if it is present [(wcm-replace v_k v_v ([v_kb v_vb] ... [v_k v_v-old] [v_ka v_va] ...)) ([v_kb v_vb] ... [v_k v_v] [v_ka v_va] ...)]) (define-metafunction tl-grammar wcm-merge : ([v v] ...) ([v v] ...) -> ([v v] ...) [(wcm-merge ([v_k-fst v_v-fst] ...) ()) ([v_k-fst v_v-fst] ...)] [(wcm-merge ([v_k-fst v_v-fst] ...) ([v_k v_v] [v_k-snd v_v-snd] ...)) (wcm-merge any_step ([v_k-snd v_v-snd] ...)) (where any_step (wcm-replace v_k v_v ([v_k-fst v_v-fst] ...)))]) ;; Reduction rules (define-metafunction tl-grammar ¬ : any -> any [(¬ #t) #f] [(¬ #f) #t]) (define-metafunction tl-grammar == : any any -> any [(== any_1 any_2) #t (side-condition (equal? (term any_1) (term any_2)))] [(== any_1 any_2) #f (side-condition (not (equal? (term any_1) (term any_2))))]) (define (no-blank-wcm?-fun t) (not (redex-match tl-grammar (in-hole E (wcm any hole)) t))) (define-metafunction tl-grammar no-blank-wcm? : E -> any [(no-blank-wcm? E_1) ,(no-blank-wcm?-fun (term E_1))]) (define (not-adt?-fun t) (redex-match tl-grammar (λ (x ...) e) t)) (define-metafunction tl-grammar not-adt? : v -> any [(not-adt? v_1) ,(not-adt?-fun (term v_1))]) (define -->_tl (reduction-relation tl-grammar ; beta (~~> ((λ (x_1 ..._1) e_1) v_1 ..._1) (subst-e* (x_1 ...) (v_1 ...) e_1) "beta") ; beta on values (~~> ((K v_1 ...) v_2 ...) (abort ("not a function")) "no beta") ; match (~~> (match (K_1 v_1 ..._1) [(K_1 x_1 ..._1) => e_1] l_1 ...) (subst-e* (x_1 ...) (v_1 ...) e_1) "match") ; match else (~~> (match v_1 [else => e_1] l_1 ...) e_1 "match else") ; match empty (~~> (match v_1) (abort ("match error")) "match empty") ; match next (~~> (match (K_1 v_1 ...) [(K_2 x_1 ...) => e_1] l_1 ...) (match (K_1 v_1 ...) l_1 ...) (side-condition (term (¬ (== K_1 K_2)))) "match next") ; match next (other) (~~> (match v_1 [(K_1 x_1 ...) => e_1] l_1 ...) (match v_1 l_1 ...) (side-condition (term (not-adt? v_1))) "match next (non-datatype)") ; letrec (--> (/ Sigma_1 (in-hole E_1 (letrec ([sigma_1 v_1] ...) e_1))) (/ (snoc* Sigma_1 ([sigma_1 v_1] ...)) (in-hole E_1 e_1)) "letrec") ; sigma (--> (/ Sigma_1 (in-hole E_1 ((! sigma_1) v_1 ...))) (/ Sigma_1 (in-hole E_1 (v_l v_1 ...))) (where (some v_l) (in-Sigma Sigma_1 sigma_1)) "sigma") ; match + sigma (--> (/ Sigma_1 (in-hole E_1 (match (! sigma_1) l_1 ...))) (/ Sigma_1 (in-hole E_1 (match v_1 l_1 ...))) (where (some v_1) (in-Sigma Sigma_1 sigma_1)) "match + sigma") ; abort (==> (in-hole E_1 (abort e_1)) e_1 "abort") ; wcm merge (==> (in-hole E_1 (wcm ([v_ki v_vi] ...) (wcm ([v_kj v_vj] ...) e_1))) (in-hole E_1 (wcm (wcm-merge ([v_ki v_vi] ...) ([v_kj v_vj] ...)) e_1)) (side-condition (term (no-blank-wcm? E_1))) "wcm merge") ; wcm return (==> (in-hole E_1 (wcm ([v_ki v_vi] ...) v_2)) (in-hole E_1 v_2) (side-condition (term (no-blank-wcm? E_1))) "wcm return") ; c-c-m (==> (in-hole E_1 (c-c-m v_1 ...)) (in-hole E_1 (get-marks-tl E_1 (v_1 ...))) "c-c-m") with ;; ==> is evaluation independent of store [(--> (/ Sigma_1 from) (/ Sigma_1 to)) (==> from to)] ;; ~~> is evaluation in any E: [(==> (in-hole E_1 from) (in-hole E_1 to)) (~~> from to)]))
false
819f3f6007b76dce44c5adb4eeccb85109da072c
ee10242f047e9b4082a720c48abc7d94fe2b64a8
/clos-repl.sch
a5f23cb523e89e29e6deb93219432c819e0eb243
[ "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
792
sch
clos-repl.sch
;; now build up the clos environment and jump into the more ;; object aware repl (require 'clos) (define (write-port obj . port) (let ((stream (if port (make <native-output-stream> 'port (car port)) stdout-stream))) (print-object stream obj))) ;; define a VM exception handler that uses our higher level condition ;; system (set-error-restart! (lambda (ex) (raise (list 'vm-error ex)))) (define (clos-repl) (letrec ((repl-loop (lambda () (display "bs> ") (let* ((exp (read-port stdin)) (res (eval exp))) (when (eof-object? res) (newline) (exit 0)) (print-object stdout-stream res) (newline) (repl-loop))))) (guard (ex (#t (printf "clos-repl: %a\n" ex))) (repl-loop))) (clos-repl))
false
134e06ab047c0dd0ac30d7a27e2b52cca3b3daab
165a4ff581651cdad1bc512ec1c82cebc0ac575a
/src/SICP/2/ex2-96.ss
e153d7ac0479761840a110aefccee89de21804cf
[]
no_license
haruyama/yami
5028e416a2caa40a0193d46018fe4be81d7820dc
32997caecc18d9d82a28b88fabe5b414a55e0e18
refs/heads/master
2020-12-25T09:47:04.240216
2018-06-16T08:28:41
2018-06-16T08:28:41
898,824
1
1
null
null
null
null
UTF-8
Scheme
false
false
985
ss
ex2-96.ss
(define (pseudoremainder-terms p q) (let ((o1 (caar p)) (o2 (caar q)) (c (cadar q))) (let ((factor (expt c (+ 1 o1 (- o2))))) (cadr (div-terms (map (lambda (x) (list (car x) (mul factor (cadr x)))) p) q))))) ;(define (gcd-terms a b) ; (if (empty-termlist? b) ; a ; (gcd-terms b (pseudoremainder-terms a b)))) (define (accumulate op initial sequence) (if (null? sequence) initial (op (car sequence) (accumulate op initial (cdr sequence))))) ;(accumulate gcd 1458 '(-2916 1458)) ;(accumulate gcd 0 '(10 4 6)) (define (mul-coeff-term a n) (map (lambda (x) (list (car x) (mul (cadr x) n))) a)) (define (div-coeff-term a n) (map (lambda (x) (list (car x) (div (cadr x) n))) a)) (define (gcd-terms a b) (if (empty-termlist? b) (let ((coeffs (map coeff a))) (let ((div-number (accumulate gcd 0 coeffs))) (div-coeff-term a div-number))) (gcd-terms b (pseudoremainder-terms a b))))
false
aefc4c12ad99d2c7a5b21fbc30ba5b7feb8217c6
958488bc7f3c2044206e0358e56d7690b6ae696c
/poly/DesignPatterns/Decorator/decorator.scm
089423c183095013eb82d7e45acffb6457d7c9de
[]
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
7,086
scm
decorator.scm
; Decorator Design Pattern ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Pizza ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define Pizza ; constuctor (let ((let-name-encapsulation 'dont-care)) ; object created from data is message passing interface (define (this data) (lambda (m) (cond ((eq? m 'description) (description data)) ((eq? m 'cost) (cost data)) (else (error "Pizza: unknown operation " m))))) ; (define (description data) (error "Pizza::description is not implemented")) ; (define (cost data) (error "Pizza::cost is not implemented")) ; ; returning no argument constructor (lambda () (this 'no-data)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; PlainPizza ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define PlainPizza ; constructor (let ((let-name-encapsulation 'dont-care)) ; object created from data is message passing interface (define (this data) (lambda (m) (cond ((eq? m 'description) (description data)) ; override ((eq? m 'cost) (cost data)) ; override (else ((base data) m))))) ; passing on to base object ; (define (description data) "Plain pizza") (define (cost data) 3.0) (define (base data) (cadr data)) ; data = (list 'data base) ; ; returning no argument constructor (lambda() (this (list 'data (Pizza)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; PizzaDecorator ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define PizzaDecorator ; constructor (let ((let-name-encapsulation 'dont-care)) ; object created from data is message passing interface (define (this data) (lambda (m) (cond ((eq? m 'description) (description data)) ; override ((eq? m 'cost) (cost data)) ; override ((eq? m 'pizza) (get-pizza data)) (else ((base data) m))))) ; passing on to base object ; (define (description data) ((get-pizza data) 'description)) (define (cost data) ((get-pizza data) 'cost)) (define (base data) (cadr data)) ; data = (list 'data base) (define (get-pizza data) (caddr data)) ; ; returning one argument interface (lambda (pizza-object) (this (list 'data (Pizza) pizza-object))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; WithExtraCheese ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define WithExtraCheese ; constructor (let ((let-name-encapsulation 'dont-care)) ; object created from data is message passing interface (define (this data) (lambda (m) (cond ((eq? m 'description) (description data)) ; override ((eq? m 'cost) (cost data)) ; override (else ((base data) m))))) ; passing on to base object ; (define (description data) (string-append ((get-pizza data) 'description) " + extra cheese")) ; (define (cost data) (+ ((get-pizza data) 'cost) 0.5)) (define (base data) (cadr data)) ; data = (list 'data base) (define (get-pizza data) ((base data) 'pizza)) ; ; returning one argument interface (lambda(pizza-object) (this (list 'data (PizzaDecorator pizza-object)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; WithExtraOlives ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define WithExtraOlives ; constructor (let ((let-name-encapsulation 'dont-care)) ; object created from data is message passing interface (define (this data) (lambda (m) (cond ((eq? m 'description) (description data)) ; override ((eq? m 'cost) (cost data)) ; override (else ((base data) m))))) ; passing on to base object ; (define (description data) (string-append ((get-pizza data) 'description) " + extra olives")) ; (define (cost data) (+ ((get-pizza data) 'cost) 0.7)) (define (base data) (cadr data)) ; data = (list 'data base) (define (get-pizza data) ((base data) 'pizza)) ; ; returning one argument interface (lambda(pizza-object) (this (list 'data (PizzaDecorator pizza-object)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; WithExtraAnchovies ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define WithExtraAnchovies ; constructor (let ((let-name-encapsulation 'dont-care)) ; object created from data is message passing interface (define (this data) (lambda (m) (cond ((eq? m 'description) (description data)) ; override ((eq? m 'cost) (cost data)) ; override (else ((base data) m))))) ; passing on to base object ; (define (description data) (string-append ((get-pizza data) 'description) " + extra anchovies")) ; (define (cost data) (+ ((get-pizza data) 'cost) 0.8)) (define (base data) (cadr data)) ; data = (list 'data base) (define (get-pizza data) ((base data) 'pizza)) ; ; returning one argument interface (lambda(pizza-object) (this (list 'data (PizzaDecorator pizza-object)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Main ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define plain-pizza (PlainPizza)) (define nice-pizza (WithExtraCheese (PlainPizza))) (define super-pizza (WithExtraOlives (WithExtraCheese (PlainPizza)))) (define ultra-pizza (WithExtraAnchovies (WithExtraOlives (WithExtraCheese (PlainPizza))))) (display "Plain Pizza: ") (display "\tCost: ")(display (plain-pizza 'cost)) (display "\tDescription: ") (display (plain-pizza 'description)) (newline) (display "Nice Pizza: ") (display "\tCost: ")(display (nice-pizza 'cost)) (display "\tDescription: ") (display (nice-pizza 'description)) (newline) (display "Super Pizza: ") (display "\tCost: ")(display (super-pizza 'cost)) (display "\tDescription: ") (display (super-pizza 'description)) (newline) (display "Ultra Pizza: ") (display "\tCost: ")(display (ultra-pizza 'cost)) (display "\tDescription: ") (display (ultra-pizza 'description)) (newline) (exit 0)
false
40936d069941ceace9bfa9f0ddc53b332d5d8ed4
8734005cd23bb6206cc4b471a0025109592a8497
/src/parser/grammar.sld
4eaa30a45e080a421051de6dcebeb73cbf0f89b1
[ "MIT" ]
permissive
hjones2199/Ruschm
c95cf94a25cc68892bcc73cfb3733eef61533780
32ff98e137a16f8da48d8beeef58e92c96a475b3
refs/heads/master
2023-06-11T03:36:39.351932
2021-06-22T17:57:18
2021-06-27T07:21:15
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,021
sld
grammar.sld
(define-syntax begin (syntax-rules () ((begin exp1 ... ) ((lambda () exp1 ... ))))) (define-syntax let (syntax-rules () ((let ((name val) ...) body ...) ((lambda (name ...) body ...) val ...)))) (define-syntax let* (syntax-rules () ((let* () body ...) (let () body ...)) ((let* ((name val)) body ...) (let ((name val)) body ...)) ((let* ((name1 val1) (name2 val2) ...) body ...) (let ((name1 val1)) (let* ((name2 val2) ...) body ...))))) (define-syntax cond (syntax-rules (else =>) ((cond (else result ...)) (begin result ...)) ((cond (test => result)) (let ((temp test)) (if temp (result temp)))) ((cond (test => result) clause ...) (let ((temp test)) (if temp (result temp) (cond clause ...)))) ((cond (test)) test) ((cond (test) clause ...) (let ((temp test)) (if temp temp (cond clause ...)))) ((cond (test result ...)) (if test (begin result ...))) ((cond (test result ...) clause ...) (if test (begin result ...) (cond clause ...))))) (define-syntax case (syntax-rules (else =>) ((case (key ...) clauses ...) (let ((atom-key (key ...))) (case atom-key clauses ...))) ((case key (else => result)) (result key)) ((case key (else result ...)) (begin result ...)) ((case key ((atoms ...) => result)) (if (not (null? (memv key '(atoms ...)))) (result key))) ((case key ((atoms ...) result ...)) (if (memv key '(atoms ...)) (begin result ...))) ((case key ((atoms ...) => result) clauses ...) (if (memv key '(atoms ...)) (result key) (case key clauses ...))) ((case key ((atoms ...) result ...) clauses ...) (if (memv key '(atoms ...)) (begin result ...) (case key clauses ...))))) (define-syntax and (syntax-rules () ((and) #t) ((and test) test) ((and test1 test2 ...) (if test1 (and test2 ...) #f)))) (define-syntax or (syntax-rules () ((or) #f) ((or test) test) ((or test1 test2 ...) (let ((x test1)) (if x x (or test2 ...)))))) (define-syntax when (syntax-rules () ((when test result1 result2 ...) (if test (begin result1 result2 ...))))) (define-syntax unless (syntax-rules () ((unless test result1 result2 ...) (if (not test) (begin result1 result2 ...)))))
true
1ff1f599606b0ada46dc0db5352df2d4cc2f4bf6
08b21a94e7d29f08ca6452b148fcc873d71e2bae
/src/tests.scm
65c8b39eb0dab0710c463c747904e9f67fa7c75c
[ "MIT" ]
permissive
rickbutton/loki
cbdd7ad13b27e275bb6e160e7380847d7fcf3b3a
7addd2985de5cee206010043aaf112c77e21f475
refs/heads/master
2021-12-23T09:05:06.552835
2021-06-13T08:38:23
2021-06-13T08:38:23
200,152,485
21
1
NOASSERTION
2020-07-16T06:51:33
2019-08-02T02:42:39
Scheme
UTF-8
Scheme
false
false
1,769
scm
tests.scm
(import (scheme base)) (import (scheme write)) (import (scheme load)) (import (srfi 64)) (import (loki compiler expander)) (import (rename (srfi 31 test) (run-tests run-tests-srfi-31))) (import (rename (srfi 64 test) (run-tests run-tests-srfi-64))) (import (rename (srfi 95 test) (run-tests run-tests-srfi-95))) (import (rename (srfi 113 test) (run-tests run-tests-srfi-113))) (import (rename (srfi 121 test) (run-tests run-tests-srfi-121))) (import (rename (srfi 128 test) (run-tests run-tests-srfi-128))) (import (rename (srfi 146 test) (run-tests run-srfi-146-tests))) (import (rename (srfi 146 hash test) (run-tests run-srfi-146-hash-tests))) (import (srfi 146 gleckler hamt-test)) (import (srfi 146 gleckler hamt-misc-test)) (import (srfi 146 gleckler hamt-map-test)) (import (srfi 146 gleckler vector-edit-test)) (import (rename (srfi 151 test) (run-tests run-tests-srfi-151))) (test-begin "loki") (display "loki tests!\n") (let ((runner (test-runner-current))) (run-tests-srfi-31 runner) (run-tests-srfi-64 runner) (run-tests-srfi-95 runner) (run-tests-srfi-113 runner) (run-tests-srfi-121 runner) (run-tests-srfi-128 runner) (run-srfi-146-tests runner) (run-srfi-146-hash-tests runner) (run-hamt-core-tests runner) (run-hamt-misc-tests runner) (run-hamt-map-tests runner) (run-vector-edit-tests runner) (run-tests-srfi-151 runner) ; r7rs test suite requires a toplevel ; TODO - this should be a relative path ; but because load is a primitive, not a macro ; we can't do the normal path resolution based on ; the identifier's source location ; instead, we will need to remember the current file ; during expansion and use that instead, which sucks (load "src/loki/compiler/lang/r7rs-tests.scm")) (test-end "loki")
false
0ff7ed289930673d387903a98d47f92707c4172d
3508dcd12d0d69fec4d30c50334f8deb24f376eb
/v8/src/compiler/midend/stackopt.scm
6df2699bda1aa2b70007f3895f65aae5d58c2efd
[]
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
35,291
scm
stackopt.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. |# ;;;; Stack optimization (reordering) ;;; package: (compiler midend) (declare (usual-integrations)) #| Big Note A This optimizer works by building a model of the current stack frame, with parent and child links mapping from the state of the stack frame at one point in time to the state earlier/later. It then attempts to make the frames similar by assigning the slots in the frame to contain the same object where possible, thus reducing shuffling. The bulk of the reordering calculation is contained in the procedures STACKOPT/REARRANGE! and STACKOPT/REARRANGE/PROCESS!. The algorithm is complicated by two issues: some elements of a stack frame have fixed locations that cannot be changed at a given point in the computation: values pushed for calls to primitives, and values pushed for passing the last arguments to unknown procedures with a large number of arguments. The former case is detectable because the call to MAKE-STACK-CLOSURE (which announces the new format of the stack frame) will not contain a LAMBDA expression in the CALL/%MAKE-STACK-CLOSURE/LAMBDA-EXPRESSION slot. The latter case is detected by looking at the vector of names available to the continuation (from the CALL/%FETCH-STACK-CLOSURE/VECTOR slot that must exist within the lambda-expresion) and comparing it with the names available at the call side in the CALL/%MAKE-STACK-CLOSURE/VECTOR slot. These will have a common prefix consisting of the values to be saved, followed in one case by the parameters being passed on the stack and in the other the values being passed to the continuation on the stack. Only the common prefix is subject to reordering, the other parts being fixed by the parameter passing convention. There is one unusual property of the stack model currently produced. Consider the case of a many-argument call to a procedure where the continuation receives many values. We produce a separate model for the stack frame on the call side (showing the values saved on the stack for use in the continuation plus the values being passed as parameters to the called procedure on the stack) and the stack frame on the continuation side (showing the values saved on the stack plus the values being supplied by the procedure to the continuation). We require the following property of any implementation of the reordering algorithm: the stack slot assignments provided for the saved values in these two frames must be identical -- the compiler is free to reorder them in any way, but the reordering must be the same on both sides of the call. This is in addition to the requirement that the slot assignments for the parameters and values are fixed by the calling sequence. THEOREM AND PROOF THEOREM: The stack slot assignments provided for the saved values in these two frames will be identical. We prove the following stronger property of the *CURRENT* algorithm, from which the theorem follows directly. THEOREM: For any frame with a single child in which the names of the unwired variables and the numbers of the unwired slots are the same in the parent and child, the slot assignments for these variables will be the same in the parent and the child. PROOF: Inductively on the number of unwired names/slots in the parent frame. If there are no unwired names/slots then the theorem follows trivially. We prove that wiring a name to a slot in either the parent or child frame preserves the invariant. Whenever an assignment transforms an unwired name to a wired name, the assignment is propagated to the parent and all children of the model in which the assignment occurs (see PROPAGATE in STACKOPT/REARRANGE/PROCESS!). For convenience, let us call the models PARENT and CHILD. We consider two cases: a: An assignment is generated in PARENT. It will be propagated to CHILD. By our induction hypothesis, the child will have both the name and the slot unwired, and will proceed to wire them together. b: An assignment is generated in CHILD. Conversely, it will be propagated to PARENT, where the induction hypothesis also implies that the name and slot are free, hence will be wired. End of Big Note A |# (define (stackopt/top-level program) (fluid-let ((stackopt/dbg-refs (stackopt/get-dbg-refs))) (stackopt/expr false program))) (define stackopt/dbg-refs) ; table from frame name to dbg info references (define-macro (define-stack-optimizer keyword bindings . body) (let ((proc-name (symbol-append 'STACKOPT/ keyword))) (call-with-values (lambda () (%matchup (cdr bindings) '(handler state) '(cdr form))) (lambda (names code) `(define ,proc-name (let ((handler (lambda ,(cons (car bindings) names) ,@body))) (named-lambda (,proc-name state form) (stackopt/remember ,code form)))))))) (define-stack-optimizer LOOKUP (state name) state ; ignored `(LOOKUP ,name)) (define-stack-optimizer LAMBDA (state lambda-list body) (define (wrap body) `(LAMBDA ,lambda-list ,body)) (cond ((form/match stackopt/fat-procedure-body-pattern body) => (lambda (result) (wrap (stackopt/fat-procedure state body result)))) (else (wrap (stackopt/expr false body))))) (define-stack-optimizer LET (state bindings body) `(LET ,(map (lambda (binding) (list (car binding) (stackopt/expr state (cadr binding)))) bindings) ,(stackopt/expr state body))) (define-stack-optimizer LETREC (state bindings body) `(LETREC ,(map (lambda (binding) (list (car binding) (stackopt/expr false (cadr binding)))) bindings) ,(stackopt/expr state body))) (define-stack-optimizer QUOTE (state object) state ; ignored `(QUOTE ,object)) (define-stack-optimizer DECLARE (state #!rest anything) state ; ignored `(DECLARE ,@anything)) (define-stack-optimizer IF (state pred conseq alt) `(IF ,(stackopt/expr state pred) ,(stackopt/expr state conseq) ,(stackopt/expr state alt))) (define-stack-optimizer BEGIN (state #!rest actions) (if (null? actions) `(BEGIN) (let ((actions* (reverse actions))) `(BEGIN ,@(stackopt/expr* state (reverse (cdr actions*))) ,(stackopt/expr state (car actions*)))))) ;; HAIR. ;; ;; When copying the program we make a copy of the frame vector at its ;; definition site and use that. Then we make sure that all ;; references to that frame variable have frame vector elements are ;; then EQ? to the copy. This ensures that if a big chunk of code ;; has been replicated then the frame vectors and hence stack models ;; for the two now separate chunks are distinct and do not interfere ;; but we still have the nice EQ? property between all vectors for ;; any particular frame. (define *stackopt/lexical-stack-frame-name* #F) (define *stackopt/lexical-stack-frame-vector* #F) ;; MORE HAIR ;; ;; These fluid bound variables are used solely for propogating the frame ;; information in <expr> below (this occurs when calling primitives): ;; ;; (CALL (LAMBDA (cont) <expr>) ;; (CALL %make-stack-closure ...) ;; ;; The problem is that <expr> may have free variables, including the ;; surrounding frame vector, but should have no model (because we do ;; not model what is on the other side of the continuation [usually we ;; dont know], Trying to model this would make things even trickier as ;; the machine continuation may be naturally kept in the stack (an ;; invisible offset) or in a register. ;; A better solution would be to separate the model tree from the ;; environment function of matching up the frame vectors for a ;; particular frame variable. (define-stack-optimizer CALL (state rator cont #!rest rands) (define (default) (with-letfied-nested-stack-closures rator cont rands (lambda (rator cont rands) (define (wrap lambda-special? cont*) `(CALL ,(if (and lambda-special? (LAMBDA/? rator) (null? rands) state) (fluid-let ((*stackopt/lexical-stack-frame-name* (stackopt/model/name state)) (*stackopt/lexical-stack-frame-vector* (stackopt/model/frame state))) (stackopt/expr state rator)) (stackopt/expr state rator)) ,cont* ,@(stackopt/expr* state rands))) (cond ((form/match stackopt/cont-pattern cont) => (lambda (result) (wrap #T (stackopt/call/can-see-both-frames state (call/%make-stack-closure/lambda-expression cont) result)))) ((call/%make-stack-closure? cont) (wrap #T (stackopt/call/terminal state cont))) (else (wrap #F (stackopt/expr state cont))))))) (define (fixup-vector) (let ((var (lookup/name (first rands))) ;rands = (closure offset 'name) (name (quote/text (third rands)))) (define (bad) (internal-error "Inconsistent %stack-closure-ref" (error-irritant/noise "\n; state: ") state (error-irritant/noise "\n; form: ") `(CALL ,rator ,cont ,@rands))) (define (good frame-vector) `(CALL ',%stack-closure-ref '#F (LOOKUP ,var) ',frame-vector ',name)) (cond ((and (not state) (eq? var *stackopt/lexical-stack-frame-name*)) (good *stackopt/lexical-stack-frame-vector*)) ((and state (eq? var (stackopt/model/name state))) (good (stackopt/model/frame state))) (else (bad))))) (if (QUOTE/? rator) (cond ((eq? (quote/text rator) %stack-closure-ref) (fixup-vector)) ((eq? (quote/text rator) %make-stack-closure) (internal-error "Explicit make-stack-closure") #F) (else (default))) (default))) (define (with-letfied-nested-stack-closures rator cont rands receiver-of-rator+cont+rands) ;; The loop does the `letifying' transformation until there are no ;; calls to %make-stack-closure in the top-level position. ;; (CALL <procedure> ;; (CALL 'make-stack-closure ;; #F ;; <lambda> ;; #<frame> ;; (CALL 'make-stack-closure #F ...) ;; ...) ;; ...) ;; Is transformed to ;; (CALL (LAMBDA (cont) ;; (CALL <procedure> ;; (CALL 'make-stack-closure ;; #F ;; <lambda> ;; #<frame> ;; (lookup cont) ;; ...) ;; ...)) ;; (CALL 'make-stack-closure #F ...)) ;; This kind of code occurs because we want to generate a continutaion ;; and then push it on the stack when callingprimitives. (let loop ((rator rator) (cont cont) (rands rands)) (if (and (call/%make-stack-closure? cont) (pair? (call/%make-stack-closure/values cont)) (call/%make-stack-closure? (first (call/%make-stack-closure/values cont)))) (let ((cont-var (new-continuation-variable))) (loop `(LAMBDA (,cont-var) (CALL ,rator (CALL ',%make-stack-closure '#F ,(call/%make-stack-closure/lambda-expression cont) ,(call/%make-stack-closure/vector cont) (LOOKUP ,cont-var) ,@(cdr (call/%make-stack-closure/values cont))) ,@rands)) (first (call/%make-stack-closure/values cont)) '() )) (receiver-of-rator+cont+rands rator cont rands)))) (define (stackopt/expr state expr) (if (not (pair? expr)) (illegal expr)) (case (car expr) ((QUOTE) (stackopt/quote state expr)) ((LOOKUP) (stackopt/lookup state expr)) ((LAMBDA) (stackopt/lambda state expr)) ((LET) (stackopt/let state expr)) ((DECLARE) (stackopt/declare state expr)) ((CALL) (stackopt/call state expr)) ((BEGIN) (stackopt/begin state expr)) ((IF) (stackopt/if state expr)) ((LETREC) (stackopt/letrec state expr)) (else (illegal expr)))) (define (stackopt/expr* state exprs) (map (lambda (expr) (stackopt/expr state expr)) exprs)) (define (stackopt/remember new old) (code-rewrite/remember new old)) (define stackopt/?lambda-list (->pattern-variable 'LAMBDA-LIST)) (define stackopt/?frame-name (->pattern-variable 'FRAME-VECTOR-NAME)) (define stackopt/?frame-vector (->pattern-variable 'FRAME-VECTOR)) (define stackopt/?call-side-frame-vector (->pattern-variable 'CALL-FRAME)) (define stackopt/?continuation-side-frame-vector (->pattern-variable 'CONT-FRAME)) (define stackopt/?body (->pattern-variable 'BODY)) (define stackopt/?closure-elts (->pattern-variable 'CLOSURE-ELTS)) (define stackopt/cont-pattern `(CALL (QUOTE ,%make-stack-closure) (QUOTE #F) (LAMBDA ,stackopt/?lambda-list (LET ((,stackopt/?frame-name (CALL (QUOTE ,%fetch-stack-closure) (QUOTE #F) (QUOTE ,stackopt/?continuation-side-frame-vector)))) ,stackopt/?body)) (QUOTE ,stackopt/?call-side-frame-vector) ,@stackopt/?closure-elts)) (define stackopt/fat-procedure-body-pattern `(LET ((,stackopt/?frame-name (CALL (QUOTE ,%fetch-stack-closure) (QUOTE #F) (QUOTE ,stackopt/?frame-vector)))) ,stackopt/?body)) (define (stackopt/fat-procedure state lambda-body match-result) ;;Following test wrong: (lambda () (subproblem) (lambda (a1 ... a100) ...)) ;;(if state ;; (internal-error "Model exists at non-continuation lambda!" state)) state (let* ((frame-vector (cadr (assq stackopt/?frame-vector match-result))) (frame-name (cadr (assq stackopt/?frame-name match-result))) (model (stackopt/model/make #F (vector-copy frame-vector) frame-name #T #T)) (form* (stackopt/expr model lambda-body))) (set-stackopt/model/form! model #F) (stackopt/reorder! model) form*)) (define (stackopt/call/can-see-both-frames state handler match-result) (define (first-mismatch v1 v2) (let ((length (min (vector-length v1) (vector-length v2)))) (let loop ((i 0)) (cond ((= i length) length) ((eq? (vector-ref v1 i) (vector-ref v2 i)) (loop (+ i 1))) (else i))))) (define (wire-from! model frame from) (let ((end (vector-length frame))) (do ((i from (+ i 1))) ((= i end) 'OK) (let ((var (vector-ref frame i))) (if (not (continuation-variable? var)) (stackopt/wire! model `((,var . ,i)))))))) ;; Handler for "standard" %make-stack-closure (those with a LAMBDA ;; expression) (let ((lambda-list (cadr (assq stackopt/?lambda-list match-result))) (frame-name (cadr (assq stackopt/?frame-name match-result))) (call-frame-vector (vector-copy (cadr (assq stackopt/?call-side-frame-vector match-result)))) (cont-frame-vector (vector-copy (cadr (assq stackopt/?continuation-side-frame-vector match-result)))) (body (cadr (assq stackopt/?body match-result))) (real-rands (cadr (assq stackopt/?closure-elts match-result)))) (let* ((call-model (stackopt/model/make state call-frame-vector frame-name #F #F)) (cont-model (if (eq? call-frame-vector cont-frame-vector) call-model (stackopt/model/make call-model cont-frame-vector frame-name #F #F))) ;; See Big Note A at the top of this file. (handler* `(LAMBDA ,lambda-list (LET ((,frame-name (CALL (QUOTE ,%fetch-stack-closure) (QUOTE #F) (QUOTE ,cont-frame-vector)))) ,(stackopt/expr cont-model body)))) (form* `(CALL (QUOTE ,%make-stack-closure) (QUOTE #F) ,(stackopt/remember handler* handler) (QUOTE ,call-frame-vector) ,@(stackopt/expr* state real-rands)))) (if (not (eq? call-model cont-model)) (let ((mismatch (first-mismatch call-frame-vector cont-frame-vector))) (wire-from! call-model call-frame-vector mismatch) (wire-from! cont-model cont-frame-vector mismatch) (set-stackopt/model/form! cont-model #F))) (stackopt/%call state call-model form*)))) (define (stackopt/call/terminal state cont) ;; Handler for CONT being the "push" %make-stack-closure (i.e. with ;; anything other than a LAMBDA expression) (let ((frame-vector (vector-copy (quote/text (call/%make-stack-closure/vector cont)))) (real-rands (call/%make-stack-closure/values cont)) (non-lambda (call/%make-stack-closure/lambda-expression cont))) (let* ((model (stackopt/model/make state frame-vector #F #T #F)) (form* `(CALL (QUOTE ,%make-stack-closure) (QUOTE #F) ,(stackopt/expr state non-lambda) (QUOTE ,frame-vector) ,@(stackopt/expr* state real-rands)))) (stackopt/%call state model form*)))) (define (stackopt/%call state model form*) (set-stackopt/model/form! model form*) (if (not state) (stackopt/reorder! model)) form*) ;; For now, this is a very simple rearranger. ;; The problem is really complicated (probably NP-complete), ;; and it's not clear how to even do a good heuristic. ;; The problem is simplified if we allow stack frames to have holes, ;; as C compilers do, since then each preserved variable can have a ;; home in the stack. The problem is garbage collection: ;; no-longer-used slots need to be cleared, and this is as costly as ;; reshuffling. (define (stackopt/reorder! model) (define (stackopt/model-intersection model) ;; Find the set of variables present in the model and all of its children (define (walk set models) (cond ((null? models) set) ((null? set) set) (else (walk (intersection set (vector->list (stackopt/model/frame (car models)))) (append (stackopt/model/children (car models)) (cdr models)))))) (walk (vector->list (stackopt/model/frame model)) (stackopt/model/children model))) (stackopt/rearrange! model (stackopt/constrain model (stackopt/model-intersection model) (let min-all ((model model)) ;; Calculate the smallest frame size that appears anywhere in ;; the tree of frame extensions (fold-right (lambda (model current-min) (min (min-all model) current-min)) (vector-length (stackopt/model/frame model)) (stackopt/model/children model))))) (stackopt/rewrite! model)) (define (stackopt/rewrite! model) ;; Rewrite the form for this model and those for all of its children ;; by calculating the new order of names in the frame and reordering ;; the value expressions to match the new order. (for-each stackopt/rewrite! (stackopt/model/children model)) (let* ((frame* (stackopt/model/frame model)) (frame (vector-copy frame*)) ; copy so we can see mutations (form (stackopt/model/form model))) (stackopt/update-frame! model) (if (and form (not (equal? frame* frame))) (let* ((names&values (map cons (vector->list frame) (call/%make-stack-closure/values form))) (values* (map (lambda (name*) (let ((place (assq name* names&values))) (if (not place) (stackopt/inconsistency model)) (cdr place))) (vector->list frame*)))) (stackopt/rewrite-dbg-frames! (stackopt/model/name model) frame*) (form/rewrite! form `(CALL ,(call/operator form) ,(call/continuation form) ,(call/%make-stack-closure/lambda-expression form) ,(call/%make-stack-closure/vector form) ,@values*)))))) (define (stackopt/get-dbg-refs) (let ((info (make-eq-hash-table))) (define (walk expr) (cond ((dbg/stack-closure-ref? expr) (let ((frame-var (vector-ref expr 1))) (hash-table/put! info frame-var (cons expr (hash-table/get info frame-var '()))))) ((dbg/heap-closure-ref? expr) (walk (vector-ref expr 1))) ((CALL/? expr) (for-each walk (call/operands expr))) (else unspecific))) (dbg-info/for-all-dbg-expressions! walk) info)) (define (stackopt/rewrite-dbg-frames! frame-var new-vector) (for-each (lambda (ref) (vector-set! ref 2 new-vector)) (hash-table/get stackopt/dbg-refs frame-var '()))) (define (stackopt/rearrange! model wired) (define (arrange-locally! model) ;; Generate the wiring for a model by performing a union of WIRED ;; with the wired elements of the model's frame (WIRED wins if a ;; name is wired in two different places?!) (let* ((wired* (let ((wired* (stackopt/model/wired model))) (if (not wired*) wired (append wired (list-transform-negative wired* (lambda (wired-pair) (assq (car wired-pair) wired))))))) (unwired (list-transform-negative (vector->list (stackopt/model/frame model)) (lambda (var) (assq var wired*))))) (set-stackopt/model/wired! model wired*) (set-stackopt/model/unwired! model unwired) (set-stackopt/model/n-unwired! model (length unwired)))) (define (max-all model) ;; Maximum number of unwired slots in this frame or any ;; [grand*]child frame (fold-right (lambda (model current-max) (max (max-all model) current-max)) (stackopt/model/n-unwired model) (stackopt/model/children model))) ;; Walk the model's frame and all of its (recursive) children. This ;; will add the WIRED set to all of the wired names of this frame ;; and its children. (let walk ((model model)) (arrange-locally! model) (for-each walk (stackopt/model/children model))) ;; If this model has children and they aren't all wired down by this ;; time, gyrate around filling in the unfilled slots. (if (not (null? (stackopt/model/children model))) (let ((max-unwired (max-all model))) (if (not (zero? max-unwired)) (let ((buckets (make-vector max-unwired '()))) (let insert! ((model model)) (for-each insert! (stackopt/model/children model)) (let ((n-unwired (stackopt/model/n-unwired model))) (if (not (zero? n-unwired)) (let ((index (- n-unwired 1))) (vector-set! buckets index (cons model (vector-ref buckets index))))))) (stackopt/rearrange/process! buckets)))))) (define (stackopt/rearrange/process! buckets) ;; BUCKETS is a vector long enough to hold an entry for each unwired ;; slot in the largest frame here or in one of the children. It ;; maps from number of open slots to models with that number of open ;; slots (off by one). That is, entry 0 has a list of all models ;; with one unwired slot,etc. (define (propagate model unwired index) ;; Do the assignment in the model itself, and then propagate it as ;; far up and down the tree as possible. (define (wire!? model unwired index) ;; Wire the name UNWIRED to offset INDEX in the MODEL if that slot ;; is available, and return a boolean indicating whether it was ;; done. (and (memq unwired (stackopt/model/unwired model)) (stackopt/free-index? model index) (let ((bucket (- (stackopt/model/n-unwired model) 1))) (stackopt/wire! model (list (cons unwired index))) (vector-set! buckets bucket (delq model (vector-ref buckets bucket))) ;; Move this model to a bucket indicating the next ;; available location to be filled. (if (not (zero? bucket)) (let ((bucket* (- bucket 1))) (vector-set! buckets bucket* (cons model (vector-ref buckets bucket*))))) true))) (define (try-up model unwired index) ;; Try to wire UNWIRED to offset INDEX in this MODEL and all of ;; its parents. Stops when it can't be wired or the top of the ;; frame tree is encountered. (let loop ((model model)) (and model (wire!? model unwired index) (loop (stackopt/model/parent model))))) (define (try-down model unwired index) ;; Try to wire UNWIRED to offset INDEX in this MODEL and all of ;; its descendents. Stops when it can't be wired any lower in ;; this branch of the frame tree. (let walk ((model model)) (and (wire!? model unwired index) (for-each walk (stackopt/model/children model))))) (if (not (wire!? model unwired index)) (internal-error "STACKOPT/REARRANGE/PROCESS!: Can't wire" model unwired index)) (try-up (stackopt/model/parent model) unwired index) (for-each (lambda (model*) (try-down model* unwired index)) (stackopt/model/children model))) (define (find-wired model models*) ;; Return the first model in MODELS* which has already decided on ;; a binding for one of the unwired variables in MODEL and for ;; which that same binding slot is available in MODEL; otherwise #F. (and (not (null? models*)) (let ((model* (car models*))) (or (list-search-positive (stackopt/model/wired model*) (lambda (wired*) (and (memq (car wired*) (stackopt/model/unwired model)) (stackopt/free-index? model (cdr wired*))))) (find-wired model (cdr models*)))))) (define (pick-to-wire model) ;; Assigns an unwired variable to a free index at random. (cons (pick-random (stackopt/model/unwired model)) (pick-random (stackopt/free-indices model)))) (define (phase-2) ;; For all of the frames that have more than one free slot, grab ;; the most highly constrained frame (fewest free slots), assign ;; an unwired variable, propagate, and repeat from phase-1 until ;; there are no models remaining. (let ((bucketlen (vector-length buckets))) (let loop ((i 1)) (and (< i bucketlen) (if (null? (vector-ref buckets i)) (loop (1+ i)) (let* ((model (car (vector-ref buckets i))) (children (stackopt/model/children model)) (to-wire (or (find-wired model (if (stackopt/model/parent model) (cons (stackopt/model/parent model) children) children)) (pick-to-wire model)))) (propagate model (car to-wire) (cdr to-wire)) (phase-1))))))) (define (phase-1) ;; For all of the models that have only one free slot available, ;; wire their first unwired variable to that slot and propagate ;; that choice up and down the tree. This may promote other ;; models to having only one free slot, so the iteration doesn't ;; terminate in the obvious manner. When all remaining models ;; have more than one free slot, go on to phase-2. (let ((bucket0 (vector-ref buckets 0))) (if (null? bucket0) (phase-2) (let* ((model (car bucket0)) (unwired (car (stackopt/model/unwired model))) (index (car (stackopt/free-indices model)))) (vector-set! buckets 0 (delq model bucket0)) (propagate model unwired index) (phase-1))))) (phase-1)) (define (stackopt/update-frame! model) ;; Calculate offsets for all elements in this model's frame by first ;; using the wired offsets and then filling in order from the ;; unwired list. (let* ((frame (stackopt/model/frame model)) (len (vector-length frame)) (frame* (make-vector len false))) (for-each (lambda (wired) (let ((name (car wired)) (index (cdr wired))) (if (vector-ref frame* index) (stackopt/inconsistency model) (vector-set! frame* index name)))) (stackopt/model/wired model)) (let loop ((i (- len 1)) (unwired (stackopt/model/unwired model))) (cond ((negative? i) (if (not (null? unwired)) (stackopt/inconsistency model))) ((vector-ref frame* i) ; This slot wired (loop (- i 1) unwired)) ((null? unwired) (stackopt/inconsistency model)) (else (vector-set! frame* i (car unwired)) (loop (- i 1) (cdr unwired))))) (stackopt/clobber! frame frame*))) (define (stackopt/free-index? model index) ;; #T iff the index-th entry in the frame is not in use for a wired ;; value. (let ((len (vector-length (stackopt/model/frame model)))) (and (< index len) (not (rassq index (stackopt/model/wired model)))))) (define (stackopt/free-indices model) ;; Return a list of all offsets in the frame that aren't currently ;; in use for a wired value. (let* ((len (vector-length (stackopt/model/frame model))) (frame* (make-vector len true))) (for-each (lambda (wired) (vector-set! frame* (cdr wired) false)) (stackopt/model/wired model)) (let loop ((index 0) (free '())) (cond ((= index len) free) ((vector-ref frame* index) (loop (+ index 1) (cons index free))) (else (loop (+ index 1) free)))))) (define (stackopt/wire! model pairs) ;; Each element of PAIRS is (<var> . <offset>) (let ((wired* (append pairs (stackopt/model/wired model))) (unwired* (delq* (map car pairs) (stackopt/model/unwired model)))) (set-stackopt/model/wired! model wired*) (set-stackopt/model/unwired! model unwired*) (set-stackopt/model/n-unwired! model (length unwired*)))) (define (stackopt/inconsistency model) (internal-error "Inconsistent wiring" model)) (define (stackopt/clobber! v1 v2) ;; Copy the values from v2 into v1 (sort of like "v1 := v2") (do ((i (- (vector-length v1) 1) (- i 1))) ((< i 0) 'done) (vector-set! v1 i (vector-ref v2 i)))) (define (stackopt/new-name prefix) (new-variable prefix)) (define-structure (stackopt/model (conc-name stackopt/model/) (constructor stackopt/model/%make (parent frame name))) (parent false read-only true) (frame false read-only true) ; Vector of variable names (name false read-only true) ; Frame variable name (wired '() read-only false) ; List mapping names to offsets (unwired '() read-only false) ; List of names, currently ; without offsets (form false read-only false) (children '() read-only false) (n-unwired false read-only false) (extended? false read-only false)) (define (stackopt/model/make parent frame name wire-all? dont-reorder?) ;; DONT-REORDER? is used to prevent moving continuations to the ;; front; it really implies more than just suppression of ;; reordering. This is basically a patch to avoid fixing a harder ;; problem: ignored-continuations are being closed over and passed ;; as procedure arguments. (let ((new (stackopt/model/%make parent frame name))) (if parent (set-stackopt/model/children! parent (cons new (stackopt/model/children parent)))) (call-with-values (lambda () (if dont-reorder? (values '() (vector->list frame)) (list-split (vector->list frame) continuation-variable?))) (lambda (cont-vars others) (cond ((null? cont-vars) 'OK) ((null? (cdr cont-vars)) (set-stackopt/model/wired! new `((,(car cont-vars) . 0)))) (else (internal-error "STACKOPT/MODEL/MAKE: multiple continuation variables" frame))) (if wire-all? (let* ((zero-counts (iota (length others))) (counts (if (null? cont-vars) zero-counts (map 1+ zero-counts)))) (set-stackopt/model/wired! new (append (stackopt/model/wired new) (map cons others counts))))))) new)) ;; This is more general than it needs to be, because it accomodates ;; partially wired frames. (define (stackopt/constrain model common sup-index) ;; MODEL is a model to be processed ;; COMMON is the list of variables that appears in the model's frame ;; and all of its descendent frames ;; SUP-INDEX is the size of the smallest frame appearing in ;; the tree of frames rooted in this model's frame. ;; ;; Returns a mapping from names in the COMMON set to fixed stack ;; offsets. This might not provide locations for all values, ;; because it treats a wiring in any frame as though it applied to ;; all frames. Later we will generate final assignments that allow ;; assignments in one frame configuration to be wired but will use ;; the same slot for another purpose in a different configuration. (define (walk model pairs) ;; Each element of PAIRS is (<name> <possible offsets for this name>) ;; Returns a similar list of pairs, but the possible offsets have ;; been corrected to account for wired down names. The entry for ;; a name may become '() if there's no place to put it (i.e. you ;; lose track of the name if it can't go anywhere). (if (null? pairs) pairs (fold-right walk (let ((wired (stackopt/model/wired model))) (if (not wired) pairs (let ((nogood (map cdr wired))) (append-map (lambda (pair) (let* ((name (car pair)) (place (assq name wired))) (cond ((not place) (let ((possible (difference (cadr pair) nogood))) (if (null? possible) '() ; Nowhere to go (list (list name possible))))) ; Anywhere but the wired locations ((memq (cdr place) (cadr pair)) (list (list name (list (cdr place))))) ; Wired location is free, so that's it (else '())))) ; Wired but slot's not free pairs)))) (stackopt/model/children model)))) (call-with-values (lambda () (list-split (walk model (map (lambda (common) (list common (iota sup-index))) common)) (lambda (pair) (referenced-continuation-variable? (car pair))))) (lambda (cont-variables rest) ;; At least the continuation variable must be shared if there are ;; any children frames, and the continuation must be in slot 0. (cond ((null? cont-variables) ;; This is no longer true. A better test would be that the ;; continuation variables must be shared across non-leaf models ;; (if (not (null? (stackopt/model/children model))) ;; (internal-error "No continuation variables shared" ;; model common)) (stackopt/constrain* rest)) ((not (null? (cdr cont-variables))) (internal-error "Too many continuation variables" model common)) ((not (memq 0 (cadr (car cont-variables)))) (internal-error "Unexpected offset for shared continuation" model (car cont-variables))) (else (stackopt/constrain* (cons (list (car (car cont-variables)) '(0)) rest))))))) (define (stackopt/constrain* pairs) ;; PAIRS maps names to possible stack offset locations ;; Returns a mapping from names to fixed stack offsets. This may ;; not provide locations for all values originally in PAIRS. (call-with-values (lambda () (list-split pairs (lambda (pair) (null? (cdr (cadr pair)))))) (lambda (wired free) ;; WIRED variables now have no other place they can go (let loop ((wired (map (lambda (pair) (cons (car pair) (car (cadr pair)))) wired)) (free free)) (if (null? free) wired ;; This is not necessarily a good choice (let* ((next (car free)) (index (list-search-negative (cadr next) (lambda (index) (rassq index wired))))) (loop (if (not index) wired (cons (cons (car next) index) wired)) (cdr free))))))))
false
afe2b885c26c8f7c832221a1fc14b9cc3970dcab
8981787979ca36cfb38070afec4c53a7dc7a3126
/e2a.ss
233adbade24ebe6941a5408a90d1764541db7687
[]
no_license
hernanre/CSSE304
c52750004bb981b0bbbca20ba3341945b9dcb5e6
26e88a35f136aa4bb9c76539cb706958db1db0bb
refs/heads/master
2021-12-15T08:30:35.067405
2017-08-05T15:28:12
2017-08-05T15:28:12
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
209
ss
e2a.ss
;c1: (define succ (lambda (ls) (if (null? ls) '(1) (let ([cur (+ 1 (car ls))]) (if (= cur 10) (cons 0 (succ (cdr ls))) (cons cur (cdr ls)))))))
false
4e031faf2673a362dd78b1b7eb582ac938fe3e56
9b2eb10c34176f47f7f490a4ce8412b7dd42cce7
/lib-runtime/selfboot/common/yuniconfig.scm
34cfa5f9b9358e5423d6e43a9e8bd64377abeb2c
[ "LicenseRef-scancode-public-domain", "CC0-1.0" ]
permissive
okuoku/yuni
8be584a574c0597375f023c70b17a5a689fd6918
1859077a3c855f3a3912a71a5283e08488e76661
refs/heads/master
2023-07-21T11:30:14.824239
2023-06-11T13:16:01
2023-07-18T16:25:22
17,772,480
36
6
CC0-1.0
2020-03-29T08:16:00
2014-03-15T09:53:13
Scheme
UTF-8
Scheme
false
false
3,589
scm
yuniconfig.scm
(define (%selfboot-yuniconfig-resolver-add-loadpath! p path) (p (list path))) (define (%selfboot-yuniconfig-gen-resolver impl yuniroot) (define cfgpath (string-append yuniroot "/config/config.scm")) (let* ((cfg (%selfboot-file->sexp-list cfgpath)) (libdirs (map (lambda (p) (string-append yuniroot "/" p)) (cdr (assoc '*library-directories* cfg)))) (libgrps (cdr (assoc '*library-groups* cfg))) (g1 (cdr (assoc 'GenRacket cfg))) (g2 (cdr (assoc 'GenR7RS cfg))) (g3 (cdr (assoc 'GenR6RSCommon cfg))) (implgroups (append g1 g2 g3))) (let ((mygroups (cdr (assoc impl implgroups)))) (define prefixes '()) (define (add-prefix! e) (cond ((pair? e) (unless (and (= (length e) 3) (eq? (cadr e) '=>)) (error "Unknown libent" e)) (let ((aliasname (car e)) (origname (caddr e))) (let ((p (assoc origname prefixes))) (cond (p (let ((d (cdr p))) (set-cdr! p (cons aliasname d)))) (else (set! prefixes (cons (list origname aliasname) prefixes))))))) (else (unless (symbol? e) (error "Unknown libent" e)) (let ((p (assoc e prefixes))) (unless p (set! prefixes (cons (list e e) prefixes))))))) (for-each (lambda (group) (let ((prefix (assoc group libgrps))) (unless prefix (error "Prefix not found!" group)) (let ((lis (cdr prefix))) (for-each add-prefix! lis)))) mygroups) (lambda (arg) (define (libname->path libname) (let ((n (reverse libname))) (let loop ((q (cdr n)) (cur (symbol->string (car n)))) (if (null? q) (string-append cur ".sls") (loop (cdr q) (string-append (symbol->string (car q)) "/" cur)))))) (define (try-lib libname) ;; #f / (ORIGNAME ALIASNAME DIR PTH) (let ((pth (libname->path libname))) (let loop ((q libdirs)) (and (not (null? q)) (let ((prefix (car q)) (next (cdr q))) ;(write (list 'TRYLIB: libname prefix pth)) (newline) (if (%selfboot-file-exists? (string-append prefix "/" pth)) (list arg libname prefix pth) (loop next))))))) (let ((a (car arg)) (d (cdr arg))) (cond ((string? a) (set! libdirs (cons a libdirs))) ((symbol? a) (let ((aliases (or (assoc a prefixes) (list a)))) (let loop ((q aliases)) (cond ((null? q) #f) (else (let ((a (car q)) (next (cdr q))) (let ((e (try-lib (cons a d)))) (or e (loop next))))))))))))))) (define (%selfboot-yuniconfig-get-runtime-list impl yuniroot) ;; => runtime file paths relative to yuniroot (define cfgpath (string-append yuniroot "/config/generic-runtime.scm")) (let ((cfg (%selfboot-file->sexp-list cfgpath))) (let ((generic (assoc 'generic cfg)) (additional (assoc impl cfg))) (if additional (append (cadr additional) (cadr generic) (caddr generic) (caddr additional)) '()))))
false
2127ad04e21c00b270d7fbcd3195db503a83acf5
c872e91f18e48b8571293d27469284199a4877fc
/a4.ss
eaa79b32dd5266d769554a5cd43c9086f739de60
[]
no_license
lamberce/Programming-Language-Concepts-GitHub
95afc0d0237a57c78a1d0aae1085ef4af3479256
585b78bbf6e3d4c8006badb9b376c6fa88d62ce4
refs/heads/master
2021-01-10T20:36:52.841958
2015-01-18T18:53:29
2015-01-18T18:53:29
29,436,770
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,316
ss
a4.ss
;;Chris Lambert ;;Assignment 4 ;;Problem #1 (define union (lambda (s1 s2) (create-domain-list (mergelists s1 s2) '()))) (define create-domain-list (lambda (x y) (cond [(equal? x '()) y] [(contains? (car x) y) (create-domain-list (cdr x) y)] [else (create-domain-list (cdr x) (cons (car x) y))]))) (define contains? (lambda (x y) (if (equal? y '()) #f (if (equal? x (car y)) #t (contains? x (cdr y)))))) (define mergelists (lambda (l1 l2) (if (equal? l2 '()) l1 (mergelists (cons (car l2) l1) (cdr l2))))) ;;Problem #2 (define reflexive? (lambda (x) (if (= (numbT (map pairs x)) (size (domain x))) #t #f))) (define pairs (lambda (x) (if (equal? (car x) (car (cdr x))) #t #f))) (define numbT (lambda (x) (if (equal? x '()) 0 (if (equal? (car x) #t) (+ 1 (numbT (cdr x))) (numbT (cdr x)))))) (define domain (lambda (x) (let ([x (map first x)]) (create-domain-list x '())))) (define first (lambda (x) (list (list-ref x 0)))) (define size (lambda (x) (if (equal? x '()) 0 (+ 1 (size (cdr x)))))) ;;Problem #3 (define matrix-ref (lambda (m row col) (list-ref (list-ref m row) col))) ;;Problem #4 (define matrix? (lambda (x) (cond [(not (or (pair? x) (null? x))) #f] [(= (numbT (map checkSubList? x)) (size x)) (if (= 1 (size (union (map size x) '()))) #t #f)] [else #f]))) (define checkSubList? (lambda (x) (if (or (pair? x)) #t #f))) (define size (lambda (x) (if (equal? x '()) 0 (+ 1 (size (cdr x)))))) ;;Problem #5 (define matrix-transpose (lambda (x) (colTrans x 0 0))) (define colTrans (lambda (x col row) (if (= (column-size x) col) '() (cons (rowTrans x col 0) (colTrans x (+ 1 col) 0))))) (define rowTrans (lambda (x col row) (if (= row (row-size x)) '() (cons (matrix-ref x row col) (rowTrans x col (+ row 1)))))) (define column-size (lambda (x) (size (car x)))) (define row-size (lambda (x) (size x))) ;;Problem #6 (define last (lambda (x) (if (equal? (cdr x) '()) (car x) (last (cdr x))))) ;;Problem #7 (define all-but-last (lambda (x) (if (equal? (cdr x) '()) '() (cons (car x) (all-but-last (cdr x))))))
false
45dbaaa8fd89998d45384df140dae360adc5b4e0
784dc416df1855cfc41e9efb69637c19a08dca68
/src/bootstrap/gerbil/compiler/optimize-call.ssxi.ss
72e905f3f799631cbba3cb06d0efada03eea6911
[ "LGPL-2.1-only", "Apache-2.0", "LGPL-2.1-or-later" ]
permissive
danielsz/gerbil
3597284aa0905b35fe17f105cde04cbb79f1eec1
e20e839e22746175f0473e7414135cec927e10b2
refs/heads/master
2021-01-25T09:44:28.876814
2018-03-26T21:59:32
2018-03-26T21:59:32
123,315,616
0
0
Apache-2.0
2018-02-28T17:02:28
2018-02-28T17:02:28
null
UTF-8
Scheme
false
false
851
ss
optimize-call.ssxi.ss
prelude: :gerbil/compiler/ssxi package: gerbil/compiler (begin (declare-method gxc#!struct-pred::t optimize-call gxc#!struct-pred::optimize-call #f) (declare-method gxc#!struct-cons::t optimize-call gxc#!struct-cons::optimize-call #f) (declare-method gxc#!struct-getf::t optimize-call gxc#!struct-getf::optimize-call #f) (declare-method gxc#!struct-setf::t optimize-call gxc#!struct-setf::optimize-call #f) (declare-method gxc#!lambda::t optimize-call gxc#!lambda::optimize-call #f) (declare-method gxc#!case-lambda::t optimize-call gxc#!case-lambda::optimize-call #f) (declare-method gxc#!kw-lambda::t optimize-call gxc#!kw-lambda::optimize-call #f) (declare-method gxc#!kw-lambda-primary::t optimize-call gxc#!kw-lambda-primary::optimize-call #f))
false
ddd59cb5150fe6be5a6a5fc51afba87b27c7c79e
08b21a94e7d29f08ca6452b148fcc873d71e2bae
/src/srfi/48.sld
c1d79bbc12949f3ec4fb89f0f2100a118760306d
[ "MIT" ]
permissive
rickbutton/loki
cbdd7ad13b27e275bb6e160e7380847d7fcf3b3a
7addd2985de5cee206010043aaf112c77e21f475
refs/heads/master
2021-12-23T09:05:06.552835
2021-06-13T08:38:23
2021-06-13T08:38:23
200,152,485
21
1
NOASSERTION
2020-07-16T06:51:33
2019-08-02T02:42:39
Scheme
UTF-8
Scheme
false
false
154
sld
48.sld
(define-library (srfi 48) (export format) (import (scheme base) (scheme char) (scheme complex) (scheme write)) (include "48.body.scm"))
false
5c74472deaa8d40331444a6ab913a70b17811d1f
d93901c1a9f4fc2641601da19b0ba872315f5f1a
/demo/chat_with_socketio_and_node/client.scm
12d39c8acd2dc7d5f10c0bb8bbc789e4fa482047
[ "MIT", "CC-BY-3.0" ]
permissive
biwascheme/biwascheme
9e5beb1cbb00df84b92c320ecfe89f19e242e6c5
1e9ea92bfd62bd5e6fe8dfc20d6bc4e1df39224a
refs/heads/main
2023-08-17T23:49:52.972194
2023-08-07T09:31:50
2023-08-07T09:31:50
2,171,254
613
119
MIT
2023-08-07T09:31:52
2011-08-08T02:40:34
JavaScript
UTF-8
Scheme
false
false
2,437
scm
client.scm
(load "socketio.scm") (js-load "/socket.io/socket.io.js" "io") (define (log-debug . args) (apply js-invoke (append (list (js-eval "console") "log") args))) (define *io* (js-eval "io")) (define *socket* (js-invoke *io* "connect")) (define (handle . args) (apply socketio-on (cons *socket* args))) (define (send . args) (apply socketio-emit (cons *socket* args))) (define (clear!) (element-empty! "#message") (element-focus! "#message")) (define (add-message! from msg) (element-append-child! "#lines" (element-new (list 'p (list 'b from) msg)))) (handle "connect" (lambda () (element-add-class-name "#chat" "connected") (element-focus! "#nick"))) (handle "announcement" (lambda (msg) (element-append-child! "#lines" (element-new (list 'p (list 'em msg)))))) (handle "nicknames" (lambda (nicknames) (element-empty! "#nicknames") (element-append-child! "#nicknames" (element-new '(span "Online: "))) (for-each (lambda (n) (element-append-child! "#nicknames" (element-new (list 'b n)))) (list-sort nicknames)))) (handle "user message" add-message!) (handle "reconnect" (lambda () (element-empty! "#lines") (add-message! "System" "Reconnected to the server"))) (handle "reconnecting" (lambda () (add-message! "System" "Attempting to reconnect to the server"))) (handle "error" (lambda (err) (if err (add-message! "System" err) (add-message! "System" "An unknown error occurred")))) (add-handler! "#set-nickname" "submit" (lambda () (send "nickname" (element-content "#nick") (lambda (taken) (if taken (element-show! "#nickname-err") (begin (element-hide! "#nickname-err") (clear!) (element-add-class-name "#chat" "nickname-set"))))) #f)) (add-handler! "#send-message" "submit" (lambda () (add-message! "me" (element-content "#message")) (send "user message" (element-content "#message")) (clear!) (js-invoke ($ "#lines") "scrollTop" 10000000) #f))
false
7936dfb1cbed169a0b829c0187e2c45efb075b75
c7d69c2477eceec0dabdf0510b395febf8094850
/scm/scratch.scm
f30afe205b6d2563395dabf58998c1bb19eec7bf
[]
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
3,276
scm
scratch.scm
(use cplusplus-object coops lolevel chickmunk srfi-13) (include "scratch-truck.scm") (include "scratch-labels.scm") ;; (define space (space-new)) ;; (define (*draw*) #f) (define (*draw*) #f (draw-shapes (space-shapes space)) (if #f ;; draw cog? (map (lambda (body) #f (ccDrawCircle (v->CCPoint (vsub (body-get-pos body) (body-get-centroid body)) ) 3 0 6 #f)) (space-bodies space )))) ;; #f if not touching, otherwise vector position (define *touch-down* #f) (add-handler 'touch-begin (lambda (t) (set! *touch-down* t))) (add-handler 'touch-ended (lambda (t) (set! *touch-down* #f))) (define (*update*) (space-step space (/ 1 120)) (space-step space (/ 1 120)) (if truck (begin (if *touch-down* (let ([thrust (if (>= (v.x *touch-down*) 450) -10.0 10.0)]) (for-each (lambda (wheel) (body-set-ang-vel wheel (fp+ (body-get-ang-vel wheel) thrust))) (list wf wr)))) ;; camera follows truck (let* ([cv (body-get-pos truck)] [camera.x (- 450 (v.x cv))] [camera.y (- 300 (v.y cv))]) (setPosition *scene* camera.x camera.y)))) ;; remove bodies that are off the screen (if #f (for-each (lambda (body) (for-each (lambda (shape) (space-remove-shape space shape)) (body-shapes body)) (space-remove-body space body)) (filter (lambda (body) (<= (v.y (body-get-pos body)) 0)) (space-bodies space)))) ) ;; (define *selection* '()) ;; (define *bodies* #f) ;; (define *body* #f) ;; ;;(use chickmunk) ;; ;;(define space (space-new)) ;; (define (*touch-begin* t) ;; (let ([cv (getLocation t)]) ;; (set! *selection* (space-point-query space cv #xFFFF 0)) ;; (set! *bodies* (map shape-get-body *selection* )) ;; (if (null? *bodies*) #f ;; (set! *body* (car *bodies*))) ;; (print "selection: " *selection* " --- " (map (cut shape-get-moment <> #f 0.0001) *selection*)) ;; ; (print (body-pos2world) ) ;; )) ;;(define pin-joint (pin-joint-new w1 (space-get-static-body space) (v 0 0) (v 400 400))) ;;(pin-joint-set-dist pin-joint 100) ;; (begin ;; (body-set-pos w1 (v 400 400)) ;; (body-set-pos w2 (v 400 400)) ;; (body-set-vel w1 (v 0 0)) ;; (body-set-vel w2 (v 0 0)) ;; (body-set-force w1 (v 0 0)) ;; (body-set-force w2 (v 0 0))) ;; (space-add-constraint space pin-joint) ;; (space-remove-constraint space pin-joint) ;; (pin-joint-get-dist pin-joint) ;; (pin-joint-get-anchr1 pin-joint) ;; (pin-joint-get-anchr2 pin-joint) ;; (define (*touch-moved* touch) #f ;; (let ([delta (getDelta touch)] ;; [cv (getLocation touch)]) ;; (map (lambda (b) (body-apply-impulse b (vmult delta 5.0) (vsub cv (body-get-pos b)))) *bodies* )) ;; ;; (print "delta: " (getDelta touch)) ;; ;; (setPosition *scene* ;; ;; (f32vector-ref (getLocation touch) 0) ;; ;; (f32vector-ref (getLocation touch) 1)) ;; #|(runAction *scene* (CCMoveBy::create 0 (new <CCPoint> ;; (f32vector-ref (getDelta touch) 0) ;; (f32vector-ref (getDelta touch) 1))) )|# ;; )
false
b3b13f52d2a9df91b3bed1e4e2985893684b088f
defeada37d39bca09ef76f66f38683754c0a6aa0
/System/system/text/regular-expressions/rx-interpreter.sls
578aa4b1fafa7621fb45a417ee06d9ecebe56fdf
[]
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
886
sls
rx-interpreter.sls
(library (system text regular-expressions rx-interpreter) (export new is? rx-interpreter? scan trace-rx?) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Text.RegularExpressions.RxInterpreter a ...))))) (define (is? a) (clr-is System.Text.RegularExpressions.RxInterpreter a)) (define (rx-interpreter? a) (clr-is System.Text.RegularExpressions.RxInterpreter a)) (define-method-port scan System.Text.RegularExpressions.RxInterpreter Scan (System.Text.RegularExpressions.Match System.Text.RegularExpressions.Regex System.String System.Int32 System.Int32)) (define-field-port trace-rx? #f #f (static:) System.Text.RegularExpressions.RxInterpreter trace_rx System.Boolean))
true
c174bfc96f8bf32c72092b69e1ac4b443439223e
943e73b33b7bc61fee44808cbd18f91c7ed1db7a
/scripts/tools.scm
3d07dc2931c331c92163bdc3ea3f1f9911929fd9
[ "BSD-3-Clause" ]
permissive
opt9/chicken-scheme
a631d3fb455c61312e0c9d30d791c78a6d99a7f6
1eb14684c26b7c2250ca9b944c6b671cb62cafbc
refs/heads/master
2020-03-09T15:41:06.499607
2009-07-25T23:49:53
2009-07-25T23:49:53
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
13,684
scm
tools.scm
;;;; tools.scm (use (srfi 1) posix utils files) (define *verbose* (##sys#fudge 13)) (define *dependencies* (make-hash-table string=?)) (define *variables* (make-hash-table string=?)) (define *actions* (make-hash-table string=?)) (define *pseudo-targets* '()) (define *sleep-delay* 2) (define *windows-shell* (memq (build-platform) '(mingw32 msvc))) ;;; Verbosity and output (define *tty* (and (##sys#tty-port? (current-output-port)) (not (equal? (getenv "EMACS") "t")) (not (equal? (getenv "TERM") "dumb")))) (define *tty-width* (or (and *tty* (not *windows-shell*) (with-input-from-pipe "stty size 2>/dev/null" (lambda () (read) (read)))) 72)) (define *info-message-escape* (if *tty* "\x1b[0m\x1b[2m" "")) (define *target-message-escape* (if *tty* "\x1b[0m\x1b[32m" "")) (define *error-message-escape* (if *tty* "\x1b[0m\x1b[31m" "")) (define *command-message-escape* (if *tty* "\x1b[0m\x1b[33m" "")) (define *reset-escape* (if *tty* "\x1b[0m" "")) (define (format-message msg #!optional (nl #t)) (if (or *verbose* (not *tty*)) ((if nl print print*) msg) (for-each (lambda (ln) (printf "\r\x1b[K~a~!" (if (>= (string-length ln) (sub1 *tty-width*)) (string-append (substring ln 0 (- *tty-width* 5)) "...") ln) ) ) (string-split msg "\n")) ) ) (define (message fstr . args) (when *verbose* (format-message (sprintf "~a* ~?~a " *info-message-escape* fstr args *reset-escape*)) ) ) (define (message* fstr . args) (when *verbose* (format-message (sprintf "~a* ~?~a " *info-message-escape* fstr args *reset-escape*) #f) ) ) (define (target-message fstr . args) (format-message (sprintf "~a~?~a " *target-message-escape* fstr args *reset-escape*))) (define (command-message fstr . args) (when *verbose* (format-message (sprintf "~a ~?~a " *command-message-escape* fstr args *reset-escape*))) ) (define (error-message fstr . args) (sprintf "~%~a~?~a~%" *error-message-escape* fstr args *reset-escape*)) (define (quit fstr . args) (display (apply error-message fstr args) (current-error-port)) (reset) ) (define (cleanup-output) (when (and (not *verbose*) *tty*) (printf "\r\x1b[0m\x1b[K~!") ) ) ;;; make-code stolen from PLT (define (find-matching-line str spec) (let ([match? (lambda (s) (string=? s str))]) (let loop ([lines spec]) (cond [(null? lines) #f] [else (let* ([line (car lines)] [names (if (string? (car line)) (list (car line)) (car line))]) (if (any match? names) line (loop (cdr lines))))])))) (define (form-error s p) (quit "~a: ~s" s p)) (define (line-error s p n) (quit "~a: ~s in line ~a" s p)) (define (check-spec spec) (and (or (list? spec) (form-error "specification is not a list" spec)) (or (pair? spec) (form-error "specification is an empty list" spec)) (every (lambda (line) (and (or (and (list? line) (<= 2 (length line) 3)) (form-error "list is not a list with 2 or 3 parts" line)) (or (or (string? (car line)) (and (list? (car line)) (every string? (car line)))) (form-error "line does not start with a string or list of strings" line)) (let ([name (car line)]) (or (list? (cadr line)) (line-error "second part of line is not a list" (cadr line) name) (every (lambda (dep) (or (string? dep) (form-error "dependency item is not a string" dep))) (cadr line))) (or (null? (cddr line)) (procedure? (caddr line)) (line-error "command part of line is not a thunk" (caddr line) name))))) spec))) (define (check-argv argv) (or (string? argv) (and (vector? argv) (every string? (vector->list argv))) (error "argument is not a string or string vector" argv))) (define (make/proc/helper spec argv) (check-spec spec) (check-argv argv) (letrec ([made '()] [exn? (condition-predicate 'exn)] [exn-message (condition-property-accessor 'exn 'message)] [make-file (lambda (s indent) (let ([line (find-matching-line s spec)] [date (and (not (member s *pseudo-targets*)) (file-exists? s) (file-modification-time s))]) (if line (let ([deps (cadr line)]) (for-each (let ([new-indent (string-append " " indent)]) (lambda (d) (make-file d new-indent))) deps) (let ([reason (or (not date) (any (lambda (dep) (unless (file-exists? dep) (quit "dependancy ~a was not made~%" dep)) (and (> (file-modification-time dep) date) dep)) deps))]) (when reason (let ([l (cddr line)]) (unless (null? l) (set! made (cons s made)) ((car l))))))) (when (not date) (quit "don't know how to make ~a" s)))))]) (cond [(string? argv) (make-file argv "")] [(equal? argv '#()) (make-file (caar spec) "")] [else (for-each (lambda (f) (make-file f "")) (vector->list argv))]) ) ) (define make/proc (case-lambda [(spec) (make/proc/helper spec '#())] [(spec argv) (make/proc/helper spec argv)])) ;;; Run subcommands (define (execute exps) (for-each (lambda (exp) (let ((cmd (string-intersperse (map ->string (flatten exps))))) (command-message "~A" cmd) (let ((s (system cmd))) (unless (zero? s) (quit (sprintf "invocation of command failed with non-zero exit-status ~a: ~a~%" s cmd) s) ) ) ) ) exps) ) (define-syntax run (syntax-rules () ((_ exp ...) (execute (list `exp ...))))) ;;; String and path helper functions (define (prefix dir . files) (if (null? files) (pathname-directory dir) (let ((files2 (map (cut make-pathname dir <>) (normalize files)))) (if (or (pair? (cdr files)) (pair? (car files))) files2 (car files2) ) ) ) ) (define (suffix suf . files) (if (null? files) (pathname-extension suf) (let ((files2 (map (cut pathname-replace-extension <> suf) (normalize files)))) (if (or (pair? (cdr files)) (pair? (car files))) files2 (car files2) ) ) ) ) (define (normalize fs) (delete-duplicates (map ->string (if (pair? fs) (flatten fs) (list fs) ) ) equal?) ) (define path make-pathname) ;;; "Stateful" build interface (define (build-clear) (set! *dependencies* (make-hash-table string=?)) (set! *actions* (make-hash-table string=?)) (set! *variables* (make-hash-table string=?)) ) (define (depends target . deps) (let ((deps (normalize deps))) (hash-table-update! *dependencies* target (lambda (old) (lset-union string=? old deps)) (lambda () deps) ) ) ) (define actions (let ((doaction (lambda (name target proc) (hash-table-update! *dependencies* target identity (constantly '())) (hash-table-set! *actions* target (lambda () (target-message "~a\t~a" name target) (proc) ) ) ) ) ) (case-lambda ((target proc) (doaction "build " target proc)) ((name target proc) (doaction name target proc)) ) ) ) (define (notfile . targets) (set! *pseudo-targets* (lset-union string=? *pseudo-targets* targets))) (define (clean-on-error t thunk) (handle-exceptions ex (begin (when (file-exists? t) (message "deleting ~a" t) (delete-file t) ) (abort ex) ) (thunk) ) ) (define (build #!optional (targets "all") #!key continuous (verbose *verbose*) ) (fluid-let ((*verbose* verbose)) (let* ((deps (hash-table->alist *dependencies*)) (wdeps (delete-duplicates (append-map cdr deps) string=?)) (targets (list->vector (normalize targets)) ) (ftable (and continuous (make-hash-table string=?)))) (when continuous (for-each (lambda (dep) (when (file-exists? dep) (hash-table-set! ftable dep (file-modification-time dep)))) wdeps)) (let loop () (make/proc (map (lambda (dep) (let ((target (car dep)) (deps (cdr dep))) (list target deps (eval `(lambda () (clean-on-error ',target (lambda () ((hash-table-ref/default *actions* ',target noop))))))))) deps) targets) (when continuous (watch-dependencies wdeps ftable) (loop))) (cleanup-output)))) (define (build-dump #!optional (port (current-output-port))) (with-output-to-port port (lambda () (message "dependencies:") (for-each show-dependencies (hash-table-keys *dependencies*)) (when (positive? (hash-table-size *variables*)) (message "variables:") (hash-table-walk *variables* (lambda (v x) (message " ~s:" v) (for-each (lambda (p) (message " ~a\t-> ~s~%" (car p) (cadr p))) x))) ) ) ) ) (define (show-dependencies target) (let ((i "")) (let loop ((t target)) (message "~a~a ~a" i t (if (member t *pseudo-targets*) "(p)" "")) (fluid-let ((i (string-append i " "))) (for-each loop (hash-table-ref/default *dependencies* t '())) ) ) ) ) ;;; Command line processing (define (build* . args) (let ((continuous #f) (targets '()) (debug #f) ) (let-values (((procs arglists) (partition procedure? args))) (let loop ((args (if (null? arglists) (command-line-arguments) (concatenate arglists))) ) (cond ((null? args) (when debug (build-dump)) (for-each (lambda (p) (p)) procs) (build (if (null? targets) "all" (reverse targets)) verbose: *verbose* continuous: continuous) ) (else (let ((x (car args))) (cond ((and (> (string-length x) 0) (char=? #\- (string-ref x 0))) (cond ((string=? "-v" x) (set! *verbose* #t) ) ((member x '("-h" "-help" "--help")) (usage 0) ) ((string=? "-c" x) (set! continuous #t) ) ((string=? "-d" x) (set! debug #t) ) (else (usage 1)) ) (loop (cdr args)) ) ((string-match "([-_A-Za-z0-9]+)=(.*)" x) => (lambda (m) (let* ((sym (string->symbol (cadr m)))) (if (##sys#symbol-has-toplevel-binding? sym) (let ((val (##sys#slot sym 0))) (if (or (boolean? val) (string? val) (symbol? val) (eq? (void) val)) (##sys#setslot sym 0 (caddr m)) (quit "variable `~a' already has a suspicious value" sym) ) ) (##sys#setslot sym 0 (caddr m)) ) (loop (cdr args)) ) ) ) (else (set! targets (cons x targets)) (loop (cdr args))))))))) ) ) (define (usage code) (print "usage: " (car (argv)) " [ -v | -c | -d | TARGET | VARIABLE=VALUE ] ...") (exit code) ) ;;; Check dependencies for changes (define (watch-dependencies deps tab) (let loop ((f #f)) (sleep *sleep-delay*) (cond ((any (lambda (dep) (and-let* (((file-exists? dep)) (ft (file-modification-time dep)) ((> ft (hash-table-ref/default tab dep 0)))) (hash-table-set! tab dep ft) (message "~a changed" dep) #t) ) deps)) (f (loop #t)) (else (message "waiting for changes ...") (loop #t))))) ;;; Other useful procedures (define -e file-exists?) (define -d (conjoin file-exists? directory?)) (define -x (conjoin file-exists? file-execute-access?)) (define cwd current-directory) (define (cd #!optional d) (if d (current-directory d) (getenv "HOME"))) (define (with-cwd dir thunk) (if (or (not dir) (equal? "." dir)) (thunk) (let ((old #f)) (dynamic-wind (lambda () (set! old (current-directory))) (lambda () (command-message "cd ~a" dir) (change-directory dir) (thunk) ) (lambda () (change-directory old) (command-message "cd ~a" old) ) ) ) ) ) (define (try-run code #!optional (msg "trying to compile and run some C code") (flags "") (cc "cc")) (let ((tmp (create-temporary-file "c"))) (with-output-to-file tmp (lambda () (display code))) (message* "~a ..." msg) (let ((r (zero? (system (sprintf "~a ~a ~a 2>/dev/null && ./a.out" cc tmp flags))))) (delete-file* tmp) (message (if r "ok" "failed")) r) ) ) (define (true? x) (and x (not (member x '("no" "false" "off" "0" ""))))) (define (simple-args #!optional (args (command-line-arguments)) (error error)) (define (assign var val) (##sys#setslot (string->symbol (string-append "*" var "*")) 0 (if (string? val) (or (string->number val) val) val))) (let loop ((args args) (vals '())) (cond ((null? args) (reverse vals)) ((string-match "(-{1,2})([-_A-Za-z0-9]+)(=)?\\s*(.+)?" (car args)) => (lambda (m) (let*-values (((next) (cdr args)) ((var val) (cond ((equal? "=" (fourth m)) (let ((opt (third m)) (val (fifth m))) (cond (val (values opt val)) (else (when (null? next) (error "missing argument for option" (car args)) ) (let ((x (car next))) (set! next (cdr next)) (values opt x))))) ) ((string? (second m)) (values (third m) #t)) (else (values #f #f)) ) ) ) (cond (var (assign var val) (loop next vals) ) (else (loop next (cons (car args) vals))))))) (else (loop (cdr args) (cons (car args) vals)))))) (define (yes-or-no? str . default) (let ((def (optional default #f))) (let loop () (printf "~%~A (yes/no) " str) (when def (printf "[~A] " def)) (flush-output) (let ((ln (read-line))) (cond ((eof-object? ln) (set! ln "abort")) ((and def (string=? "" ln)) (set! ln def)) ) (cond ((string-ci=? "yes" ln) #t) ((string-ci=? "no" ln) #f) (else (printf "~%Please enter \"yes\" or \"no\".~%") (loop) ) ) ) ) ) )
true
ca393c92459935cbb0dc254ce012fed1fa50bbe9
eef5f68873f7d5658c7c500846ce7752a6f45f69
/spheres/markup/internal/id/access-remote.scm
43115cad956d598a7647d610bca3351b6ec2765f
[ "MIT" ]
permissive
alvatar/spheres
c0601a157ddce270c06b7b58473b20b7417a08d9
568836f234a469ef70c69f4a2d9b56d41c3fc5bd
refs/heads/master
2021-06-01T15:59:32.277602
2021-03-18T21:21:43
2021-03-18T21:21:43
25,094,121
13
3
null
null
null
null
UTF-8
Scheme
false
false
11,932
scm
access-remote.scm
;; Uniform access to local and remote resources ;; Resolution for relative URIs in accordance with RFC 2396 ;; ;; This software is in Public Domain. ;; IT IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. ;; ;; Please send bug reports and comments to: ;; [email protected] Dmitry Lizorkin ;;------------------------------------------------------------------------------- ;;!! Accessing (remote) resources ;;! Whether the resource exists (generalization of FILE-EXISTS? predicate) ;; REQ-URI - a string representing a URI of the resource ;; This predicate doesn't have any side effects (define (resource-exists? req-uri) (cond ((string-prefix? "http://" req-uri) ; HTTP scheme is used in REQ-URI (with-exception-handler (lambda (x) #f) ; an uncaught exception occured during http transaction (lambda () (http-transaction "HEAD" req-uri (list (cons 'logger (lambda (port message . other-messages) #t))) (lambda (resp-code resp-headers resp-port) (close-input-port resp-port) (and (>= resp-code 200) (< resp-code 400))))))) (else ; a local file (file-exists? req-uri)))) ;;! Opens an input port for a resource ;; REQ-URI - a string representing a URI of the resource ;; An input port is returned if there were no errors. In case of an error, ;; the function returns #f and displays an error message as a side effect. ;; Doesn't raise any exceptions. (define (open-input-resource req-uri) (with-exception-handler (lambda (x) (display (string-append req-uri ": \n") (current-error-port)) (pp x) #f) (lambda () (cond ((string-prefix? "http://" req-uri) ; HTTP scheme is used in REQ-URI (http-transaction "GET" req-uri (list (cons 'logger (lambda (port message . other-messages) #t))) (lambda (resp-code resp-headers resp-port) (cond ((and (>= resp-code 200) (< resp-code 400)) resp-port) (else (close-input-port resp-port) (display (string-append req-uri ": resource not available: " resp-code "\n") (current-error-port)) #f))))) (else ; a local file (open-input-file req-uri)))))) ;;------------------------------------------------------------------------------- ;;!! Determining resource type ;;! Returns a file extenstion ;; filename - a string ;; File extension is returned in the form of a string (define (ar:file-extension filename) (let loop ((src (reverse (string->list filename))) (res '())) (cond ((null? src) ; no dot encountered => no extension "") ((char=? (car src) #\.) (list->string res)) (else (loop (cdr src) (cons (car src) res)))))) ;;! Determines the type of a resource ;; REQ-URI - a string representing a URI of the resource ;; For a local resource, its type is determined by its file extension ;; One of the following is returned: ;; #f - if the requested resource doesn't exist ;; 'xml - for a resource that is an XML document ;; 'html - for a resource that is an HTML document ;; 'unknown - for any other resource type (define (ar:resource-type req-uri) (cond ((string-prefix? "http://" req-uri) ; HTTP scheme is used in REQ-URI (with-exception-handler (lambda (x) #f) ; an uncaught exception occured during http transaction (lambda () (http-transaction "HEAD" req-uri (list (cons 'logger (lambda (port message . other-messages) #t))) (lambda (resp-code resp-headers resp-port) (close-input-port resp-port) (if (or (< resp-code 200) (>= resp-code 400)) #f ; Resource doesn't exist (let ((content-type (assq 'CONTENT-TYPE resp-headers))) (cond ((not content-type) ; no content type specified 'unknown) ((string-prefix? "text/xml" (cdr content-type)) 'xml) ((string-prefix? "text/html" (cdr content-type)) 'html) ((string-prefix? "text/plain" (cdr content-type)) 'plain) (else 'unknown))))))))) (else ; a local file (cond ((not (file-exists? req-uri)) ; file doesn't exist #f) ((assoc (ar:file-extension req-uri) '(("xml" . xml) ("html" . html) ("htm" . html))) => cdr) (else 'unknown))))) ;;------------------------------------------------------------------------------- ;;!! Working on absolute/relative URIs ;; This section is based on RFC 2396 ;; The URI and its components ;; URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ] ;; genericURI = <scheme>://<authority><path>?<query> ;; For a sertain subset of URI schemes, absoluteURI = genericURI ;; We will suppose this condition valid in this implementation ;;! Returns: (values scheme authority path query fragment) ;; If some component is not presented in the given URI, #f is returned for this ;; component. Note that the path component is always presented in the URI (define (ar:uri->components uri) (call-with-values (lambda () (cond ((string-index-right uri #\#) => (lambda (pos) (values (substring uri (+ pos 1) (string-length uri)) (substring uri 0 pos)))) (else (values #f uri)))) (lambda (fragment uri) (call-with-values (lambda () (cond ((string-index-right uri #\?) => (lambda (pos) (values (substring uri (+ pos 1) (string-length uri)) (substring uri 0 pos)))) (else (values #f uri)))) (lambda (query uri) (call-with-values (lambda () (cond ((string-contains uri "://") => (lambda (pos) (values (substring uri 0 (+ pos 3)) (substring uri (+ pos 3) (string-length uri))))) ((string-index uri #\:) => (lambda (pos) (values (substring uri 0 (+ pos 1)) (substring uri (+ pos 1) (string-length uri))))) (else (values #f uri)))) (lambda (scheme uri) (call-with-values (lambda () (cond ((not scheme) (values #f uri)) ((string-index uri #\/) => (lambda (pos) (values (substring uri 0 pos) (substring uri pos (string-length uri))))) (else (values #f uri)))) (lambda (authority path) (values scheme authority path query fragment)))))))))) ;;! Combines components into the URI (define (ar:components->uri scheme authority path query fragment) (apply string-append (append (if scheme (list scheme) '()) (if authority (list authority) '()) (list path) (if query (list "?" query) '()) (if fragment (list "#" fragment) '())))) ;;------------------------------------------------------------------------------- ;;!! Path and its path_segments ;; abs_path = "/" path_segments ;; path_segments = segment *( "/" segment ) ;;! Splits the given path into segments ;; Returns: (values root dir-lst filename) ;; dir-lst ::= (listof directory-name) ;; root - either an empty string, or "/" or drive-name (for Windows filesystems) (define (ar:path->segments path) (call-with-values (lambda () (let ((lng (string-length path))) (cond ((and (> lng 0) (char=? (string-ref path 0) #\/)) (values "/" (substring path 1 lng))) ((and (> lng 1) (char=? (string-ref path 1) #\:) (member (string-ref path 2) (list #\/ #\\))) (values (substring path 0 3) (substring path 3 lng))) (else (values "" path))))) (lambda (root rel-path) (let ((lst (xlink:string-split rel-path (list #\/ #\\)))) (if (null? lst) ; the relative path is empty (values root '() "") (let ((lst (reverse lst))) (values root (reverse (cdr lst)) (car lst)))))))) ;;! Combines path_segments into the path ;; backslash? - a boolean value: whether the backslach shall be used as a ;; delimiter between path_segments. If #f, straight slash is used (define (ar:segments->path root dir-lst filename backslash?) (let ((delim (if backslash? "\\" "/"))) (apply string-append (append (list root) (apply append (map (lambda (directory-name) (list directory-name delim)) dir-lst)) (list filename))))) ;;! Removes redundant segment combinations from the dir-lst ;; '("smth" "..") --> removed ;; '(".") --> removed ;; The algorithm is formally specified in RFC 2396, 5.2, step 6) (define (ar:normalize-dir-lst dir-lst) (cond ((null? dir-lst) dir-lst) ((string=? (car dir-lst) ".") (ar:normalize-dir-lst (cdr dir-lst))) ((string=? (car dir-lst) "..") (cons (car dir-lst) (ar:normalize-dir-lst (cdr dir-lst)))) (else (let ((processed (ar:normalize-dir-lst (cdr dir-lst)))) (cond ((null? processed) (list (car dir-lst))) ((string=? (car processed) "..") (cdr processed)) (else (cons (car dir-lst) processed))))))) ;;------------------------------------------------------------------------------- ;;!! Resolves a relative URI with respect to the base URI ;;! base-uri - base URI for the requiested one ;; Returns the resolved URI (define (ar:resolve-uri-according-base base-uri req-uri) (call-with-values (lambda () (ar:uri->components req-uri)) (lambda (req-scheme req-authority req-path req-query req-fragment) (if (or req-scheme req-authority) ; it is the absolute URI req-uri (call-with-values (lambda () (ar:path->segments req-path)) (lambda (req-root req-dir-lst req-filename) (if (> (string-length req-root) 1) ; absolute path from the disc drive req-uri (call-with-values (lambda () (ar:uri->components base-uri)) (lambda (base-scheme base-authority base-path base-query base-fragment) (if (string=? req-root "/") ; absolute path from server (ar:components->uri base-scheme base-authority req-path req-query req-fragment) ; else the requested URI is the relative URI (call-with-values (lambda () (ar:path->segments base-path)) (lambda (base-root base-dir-lst base-filename) (ar:components->uri base-scheme base-authority (ar:segments->path base-root (ar:normalize-dir-lst (append base-dir-lst req-dir-lst)) req-filename (and (not (string-index base-path #\/)) (string-index req-path #\\))) req-query req-fragment)))))))))))))
false
70f869a71be6838b111bfdecbbaedcdbb9de1154
9b2eb10c34176f47f7f490a4ce8412b7dd42cce7
/tests/lib/ident0.sps
4abf1d7ad4dd808723e0cc8f721429654fd4a35b
[ "LicenseRef-scancode-public-domain", "CC0-1.0" ]
permissive
okuoku/yuni
8be584a574c0597375f023c70b17a5a689fd6918
1859077a3c855f3a3912a71a5283e08488e76661
refs/heads/master
2023-07-21T11:30:14.824239
2023-06-11T13:16:01
2023-07-18T16:25:22
17,772,480
36
6
CC0-1.0
2020-03-29T08:16:00
2014-03-15T09:53:13
Scheme
UTF-8
Scheme
false
false
307
sps
ident0.sps
(import (yuni scheme) (yunitest mini) (yuni compat ident)) (define (getname) (let loop ((l (command-line))) (and (pair? l) (if (string=? "-IMPLNAME" (car l)) (cadr l) (loop (cdr l)))))) (check-equal (ident-impl) (string->symbol (getname))) (check-finish)
false
3c67d7cd80b327d21804590705cdb5220ccda535
ab05b79ab17619f548d9762a46199dc9eed6b3e9
/sitelib/ypsilon/gtk/table.scm
fa1b73f59b18ce416addce40661ce986d1b03769
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
lambdaconservatory/ypsilon
2dce9ff4b5a50453937340bc757697b9b4839dee
f154436db2b3c0629623eb2a53154ad3c50270a1
refs/heads/master
2021-02-28T17:44:05.571304
2017-12-17T12:29:00
2020-03-08T12:57:52
245,719,032
1
0
NOASSERTION
2020-03-07T23:08:26
2020-03-07T23:08:25
null
UTF-8
Scheme
false
false
4,022
scm
table.scm
#!nobacktrace ;;; Ypsilon Scheme System ;;; Copyright (c) 2004-2009 Y.FUJITA / LittleWing Company Limited. ;;; See license.txt for terms and conditions of use. (library (ypsilon gtk table) (export gtk_table_attach gtk_table_attach_defaults gtk_table_get_col_spacing gtk_table_get_default_col_spacing gtk_table_get_default_row_spacing gtk_table_get_homogeneous gtk_table_get_row_spacing gtk_table_get_type gtk_table_new gtk_table_resize gtk_table_set_col_spacing gtk_table_set_col_spacings gtk_table_set_homogeneous gtk_table_set_row_spacing gtk_table_set_row_spacings) (import (rnrs) (ypsilon ffi)) (define lib-name (cond (on-linux "libgtk-x11-2.0.so.0") (on-sunos "libgtk-x11-2.0.so.0") (on-freebsd "libgtk-x11-2.0.so.0") (on-openbsd "libgtk-x11-2.0.so.0") (on-darwin "Gtk.framework/Gtk") (on-windows "libgtk-win32-2.0-0.dll") (else (assertion-violation #f "can not locate GTK library, unknown operating system")))) (define lib (load-shared-object lib-name)) (define-syntax define-function (syntax-rules () ((_ ret name args) (define name (c-function lib lib-name ret name args))))) (define-syntax define-function/va_list (syntax-rules () ((_ ret name args) (define name (lambda x (assertion-violation 'name "va_list argument not supported")))))) ;; void gtk_table_attach (GtkTable* table, GtkWidget* child, guint left_attach, guint right_attach, guint top_attach, guint bottom_attach, GtkAttachOptions xoptions, GtkAttachOptions yoptions, guint xpadding, guint ypadding) (define-function void gtk_table_attach (void* void* unsigned-int unsigned-int unsigned-int unsigned-int int int unsigned-int unsigned-int)) ;; void gtk_table_attach_defaults (GtkTable* table, GtkWidget* widget, guint left_attach, guint right_attach, guint top_attach, guint bottom_attach) (define-function void gtk_table_attach_defaults (void* void* unsigned-int unsigned-int unsigned-int unsigned-int)) ;; guint gtk_table_get_col_spacing (GtkTable* table, guint column) (define-function unsigned-int gtk_table_get_col_spacing (void* unsigned-int)) ;; guint gtk_table_get_default_col_spacing (GtkTable* table) (define-function unsigned-int gtk_table_get_default_col_spacing (void*)) ;; guint gtk_table_get_default_row_spacing (GtkTable* table) (define-function unsigned-int gtk_table_get_default_row_spacing (void*)) ;; gboolean gtk_table_get_homogeneous (GtkTable* table) (define-function int gtk_table_get_homogeneous (void*)) ;; guint gtk_table_get_row_spacing (GtkTable* table, guint row) (define-function unsigned-int gtk_table_get_row_spacing (void* unsigned-int)) ;; GType gtk_table_get_type (void) (define-function unsigned-long gtk_table_get_type ()) ;; GtkWidget* gtk_table_new (guint rows, guint columns, gboolean homogeneous) (define-function void* gtk_table_new (unsigned-int unsigned-int int)) ;; void gtk_table_resize (GtkTable* table, guint rows, guint columns) (define-function void gtk_table_resize (void* unsigned-int unsigned-int)) ;; void gtk_table_set_col_spacing (GtkTable* table, guint column, guint spacing) (define-function void gtk_table_set_col_spacing (void* unsigned-int unsigned-int)) ;; void gtk_table_set_col_spacings (GtkTable* table, guint spacing) (define-function void gtk_table_set_col_spacings (void* unsigned-int)) ;; void gtk_table_set_homogeneous (GtkTable* table, gboolean homogeneous) (define-function void gtk_table_set_homogeneous (void* int)) ;; void gtk_table_set_row_spacing (GtkTable* table, guint row, guint spacing) (define-function void gtk_table_set_row_spacing (void* unsigned-int unsigned-int)) ;; void gtk_table_set_row_spacings (GtkTable* table, guint spacing) (define-function void gtk_table_set_row_spacings (void* unsigned-int)) ) ;[end]
true
a6fa1331906e57c2201999938ccb1487eaea8480
0768e217ef0b48b149e5c9b87f41d772cd9917f1
/sitelib/srfi/64/test-runner.body.scm
f8131ebcf0d4cfe98ad0764e67c676685fdb02ab
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
fujita-y/ypsilon
e45c897436e333cf1a1009e13bfef72c3fb3cbe9
62e73643a4fe87458ae100e170bf4721d7a6dd16
refs/heads/master
2023-09-05T00:06:06.525714
2023-01-25T03:56:13
2023-01-25T04:02:59
41,003,666
45
7
BSD-2-Clause
2022-06-25T05:44:49
2015-08-19T00:05:35
Scheme
UTF-8
Scheme
false
false
6,399
scm
test-runner.body.scm
;; Copyright (c) 2005, 2006, 2007, 2012, 2013 Per Bothner ;; Added "full" support for Chicken, Gauche, Guile and SISC. ;; Alex Shinn, Copyright (c) 2005. ;; Modified for Scheme Spheres by Álvaro Castro-Castilla, Copyright (c) 2012. ;; Support for Guile 2 by Mark H Weaver <[email protected]>, Copyright (c) 2014. ;; Refactored by Taylan Ulrich Bayırlı/Kammer, Copyright (c) 2014, 2015. ;; ;; 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. ;;; The data type (define-record-type <test-runner> (make-test-runner) test-runner? (result-alist test-result-alist test-result-alist!) (pass-count test-runner-pass-count test-runner-pass-count!) (fail-count test-runner-fail-count test-runner-fail-count!) (xpass-count test-runner-xpass-count test-runner-xpass-count!) (xfail-count test-runner-xfail-count test-runner-xfail-count!) (skip-count test-runner-skip-count test-runner-skip-count!) (total-count %test-runner-total-count %test-runner-total-count!) ;; Stack (list) of (count-at-start . expected-count): (count-list %test-runner-count-list %test-runner-count-list!) ;; Normally #f, except when in a test-apply. (run-list %test-runner-run-list %test-runner-run-list!) (skip-list %test-runner-skip-list %test-runner-skip-list!) (fail-list %test-runner-fail-list %test-runner-fail-list!) (skip-save %test-runner-skip-save %test-runner-skip-save!) (fail-save %test-runner-fail-save %test-runner-fail-save!) (group-stack test-runner-group-stack test-runner-group-stack!) ;; Note: on-test-begin and on-test-end are unrelated to the test-begin and ;; test-end forms in the execution library. They're called at the ;; beginning/end of each individual test, whereas the test-begin and test-end ;; forms demarcate test groups. (on-group-begin test-runner-on-group-begin test-runner-on-group-begin!) (on-test-begin test-runner-on-test-begin test-runner-on-test-begin!) (on-test-end test-runner-on-test-end test-runner-on-test-end!) (on-group-end test-runner-on-group-end test-runner-on-group-end!) (on-final test-runner-on-final test-runner-on-final!) (on-bad-count test-runner-on-bad-count test-runner-on-bad-count!) (on-bad-end-name test-runner-on-bad-end-name test-runner-on-bad-end-name!) (on-bad-error-type %test-runner-on-bad-error-type %test-runner-on-bad-error-type!) (aux-value test-runner-aux-value test-runner-aux-value!) (log-file %test-runner-log-file %test-runner-log-file!) (log-port %test-runner-log-port %test-runner-log-port!)) (define (test-runner-group-path runner) (reverse (test-runner-group-stack runner))) (define (test-runner-reset runner) (test-result-alist! runner '()) (test-runner-pass-count! runner 0) (test-runner-fail-count! runner 0) (test-runner-xpass-count! runner 0) (test-runner-xfail-count! runner 0) (test-runner-skip-count! runner 0) (%test-runner-total-count! runner 0) (%test-runner-count-list! runner '()) (%test-runner-run-list! runner #f) (%test-runner-skip-list! runner '()) (%test-runner-fail-list! runner '()) (%test-runner-skip-save! runner '()) (%test-runner-fail-save! runner '()) (test-runner-group-stack! runner '())) (define (test-runner-null) (define (test-null-callback . args) #f) (let ((runner (make-test-runner))) (test-runner-reset runner) (test-runner-on-group-begin! runner test-null-callback) (test-runner-on-group-end! runner test-null-callback) (test-runner-on-final! runner test-null-callback) (test-runner-on-test-begin! runner test-null-callback) (test-runner-on-test-end! runner test-null-callback) (test-runner-on-bad-count! runner test-null-callback) (test-runner-on-bad-end-name! runner test-null-callback) (%test-runner-on-bad-error-type! runner test-null-callback) (%test-runner-log-file! runner #f) (%test-runner-log-port! runner #f) runner)) ;;; State (define test-result-ref (case-lambda ((runner key) (test-result-ref runner key #f)) ((runner key default) (let ((entry (assq key (test-result-alist runner)))) (if entry (cdr entry) default))))) (define (test-result-set! runner key value) (let* ((alist (test-result-alist runner)) (entry (assq key alist))) (if entry (set-cdr! entry value) (test-result-alist! runner (cons (cons key value) alist))))) (define (test-result-remove runner key) (test-result-alist! runner (remove (lambda (entry) (eq? key (car entry))) (test-result-alist runner)))) (define (test-result-clear runner) (test-result-alist! runner '())) (define (test-runner-test-name runner) (or (test-result-ref runner 'name) "")) (define test-result-kind (case-lambda (() (test-result-kind (test-runner-get))) ((runner) (test-result-ref runner 'result-kind)))) (define test-passed? (case-lambda (() (test-passed? (test-runner-get))) ((runner) (memq (test-result-kind runner) '(pass xpass))))) ;;; Factory and current instance (define test-runner-factory (make-parameter #f)) (define (test-runner-create) ((test-runner-factory))) (define test-runner-current (make-parameter #f)) (define (test-runner-get) (or (test-runner-current) (error "test-runner not initialized - test-begin missing?"))) ;;; test-runner.scm ends here
false
c659b3786a4874b98eb378facff41c30cdba1a00
41aa3085fa3d145041d722d4ee2bdc1ccabed8ed
/sicp/lecture2b.scm
30ccdb8d1964a49882bc2699858dfac13c99ba05
[]
no_license
lfborjas/distractions
f4edfb4302a0794fd7a20e8cb20b66887076a307
a6b6bcd09270fa73233b05f3afb1800b977da9c3
refs/heads/master
2021-01-16T18:31:01.669105
2019-06-16T23:31:56
2019-06-16T23:31:56
1,132,897
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,436
scm
lecture2b.scm
(define (sum-rat x y) (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (*rat x y) (make-rat (* (numer x) (numer y)) (* (denom x) (denom y)))) ;make rational numbers simple from build time (define (make-rat x y) (let((g (gcd x y))) (cons (/ x g) (/ y g)))) (define (numer x) (car x)) (define (denom x) (cdr x)) (define make-point (lambda (x y) (cons x y))) (define (xcor v) (car v)) (define (ycor v) (cdr v)) (define make-seg (lambda (s e) (cons s e))) (define (seg-start s) (car s)) (define (seg-end s) (cdr s)) (define (midpoint s) (let ((a (seg-start s)) (b (seg-end s))) (make-point (average (xcor a) (xcor b)) (average (ycor a) (ycor b))))) ;TODO: write the length function ;redefining cons, car and cdr (pronounced could-r) (define (cons a b) ;return a procedure that takes an index and returns the element in that index (lambda (pick) (cond ((= pick 1) a) ((= pick 2) b)))) ;hence, car of a cons is just the cons-lambda called with one (define (car x) (x 1)) ;and cdr, the cons-lambda called with two! (define (cdr x) (x 2)) ;WOW: this guy illustrated the layered abstraction of data by demonstrating that cons ;cad and cdr can also be seen as abstracted methods
false
a65f2b6d5be2150248a77d7bcb850f5b326fd25b
6a7f1b0f65db6cd06fb817686b3e92e9e7c95596
/src/arc/as.scm
7f2b419a8e60e875dbadfb873d07b7b291443a3c
[ "Artistic-2.0" ]
permissive
conanite/rainbow
32338fb3badcffa9ac47d8dfe2bf7234052bee43
aa37d65548d5658aa3608cfe40a1a388d793b575
refs/heads/master
2016-09-05T13:51:39.958209
2010-10-12T09:08:41
2010-10-12T09:08:41
9,111
34
4
null
null
null
null
UTF-8
Scheme
false
false
243
scm
as.scm
; mzscheme -m -f as.scm ; (tl) ; (asv) ; http://localhost:8080 (require mzscheme) ; promise we won't redefine mzscheme bindings (require "ac.scm") (require "brackets.scm") (use-bracket-readtable) (aload "arc.arc") (aload "libs.arc") (tl)
false
fb8622e1d58b719afddeae2ee57181a5e8a4260f
f5083e14d7e451225c8590cc6aabe68fac63ffbd
/cs/01-Programming/cs61a/course/lectures/1.1/filter.scm
31ba7e29361e9d37d4fd95a46b66bf5bb41fefc5
[]
no_license
Phantas0s/playground
a362653a8feb7acd68a7637334068cde0fe9d32e
c84ec0410a43c84a63dc5093e1c214a0f102edae
refs/heads/master
2022-05-09T06:33:25.625750
2022-04-19T14:57:28
2022-04-19T14:57:28
136,804,123
19
5
null
2021-03-04T14:21:07
2018-06-10T11:46:19
Racket
UTF-8
Scheme
false
false
624
scm
filter.scm
;;;;; cs60a/lectures/1.3/filter.scm (define (evens nums) (cond ((empty? nums) '()) ((= (remainder (first nums) 2) 0) (se (first nums) (evens (bf nums))) ) (else (evens (bf nums))) )) (define (ewords sent) (cond ((empty? sent) '()) ((member? 'e (first sent)) (se (first sent) (ewords (bf sent))) ) (else (ewords (bf sent))) )) (define (pronouns sent) (cond ((empty? sent) '()) ((member? (first sent) '(I me you he she it him her we us they them)) (se (first sent) (pronouns (bf sent))) ) (else (pronouns (bf sent))) ))
false
3fcd87fc30796222f32dbe4864cc5347a354e6a2
4b480cab3426c89e3e49554d05d1b36aad8aeef4
/chapter-03/ex3.47.b-falsetru.scm
14b3a13592a8d41a2dda4a5be388f57742d1e17f
[]
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
907
scm
ex3.47.b-falsetru.scm
(define (clear! cell) (set-car! cell false)) (define (loop-test-and-set! cell) (if (test-and-set! cell) (loop-test-and-set! cell) (void))) (define (test-and-set! cell) (if (car cell) true (begin (set-car! cell true) false))) (define (make-semaphore n) (let ((n (list n)) (guard (list false))) (define (the-semaphore msg) (loop-test-and-set! guard) (cond [(eq? msg 'acquire) (if (= (car count) 0) (begin (clear! guard) (the-semaphore 'acquire)) (begin (set-car! count (sub1 (car count))) (clear! guard)))] [(eq? msg 'release) (begin (if (< (car count) n) (set-car! count (add1 (car count))) (void)) (mutex 'release))])) the-semaphore))
false
ed4adcc34eec13d638118ecdf025c4e978214408
b58f908118cbb7f5ce309e2e28d666118370322d
/src/97.scm
f31841d355651e1c3a55520c9b90e69c662fdc0b
[ "MIT" ]
permissive
arucil/L99
a9e1b7ad2634850db357f7cc292fa2871997d93d
8b9a3a8e7fb63efb2d13fab62cab2c1254a066d9
refs/heads/master
2021-09-01T08:18:39.029308
2017-12-26T00:37:55
2017-12-26T00:37:55
114,847,976
1
0
null
null
null
null
UTF-8
Scheme
false
false
2,288
scm
97.scm
;;; P97 (load "prelude.scm") (define (sudoku board) (let f ([state (make-state board)]) (let ([pos (next-hole state)]) (if pos (exists (lambda (num) (f (fill-hole state pos num))) (valid-nums state pos)) (get-solution state))))) (define (make-state board) board) (define (get-solution state) state) (define (next-hole state) (let f ([y 0] [rows state]) (if (null? rows) #f (let ([x (index-of 0 (car rows))]) (if (>= x 0) (cons x y) (f (add1 y) (cdr rows))))))) (define (index-of x ls) (let f ([i 0] [ls ls]) (cond [(null? ls) -1] [(equal? x (car ls)) i] [else (f (add1 i) (cdr ls))]))) (define (fill-hole state pos num) (list-subst (cdr pos) (list-subst (car pos) num (list-ref state (cdr pos))) state)) (define (list-subst i new ls) (cond [(null? ls) '()] [(zero? i) (cons new (cdr ls))] [else (cons (car ls) (list-subst (sub1 i) new (cdr ls)))])) (define (valid-nums state pos) (remove* (square-nums state pos) (remove* (list-ref state (cdr pos)) (remove* (map (lambda (row) (list-ref row (car pos))) state) '(1 2 3 4 5 6 7 8 9))))) (define (square-nums state pos) (let ([x0 (* 3 (quotient (car pos) 3))] [y0 (* 3 (quotient (cdr pos) 3))]) (let ([row1 (list-ref state y0)] [row2 (list-ref state (+ 1 y0))] [row3 (list-ref state (+ 2 y0))]) (list (list-ref row1 x0) (list-ref row1 (+ 1 x0)) (list-ref row1 (+ 2 x0)) (list-ref row2 x0) (list-ref row2 (+ 1 x0)) (list-ref row2 (+ 2 x0)) (list-ref row3 x0) (list-ref row3 (+ 1 x0)) (list-ref row3 (+ 2 x0)))))) (pretty-print (sudoku '((0 0 4 8 0 0 0 1 7) (6 7 0 9 0 0 0 0 0) (5 0 8 0 3 0 0 0 4) (3 0 0 7 4 0 1 0 0) (0 6 9 0 0 0 7 8 0) (0 0 1 0 6 9 0 0 5) (1 0 0 0 8 0 3 0 6) (0 0 0 0 0 6 0 9 1) (2 4 0 0 0 1 5 0 0))))
false
d631af12e363cb38b03d4084b3dc8fde55407eb6
b4fe4841131773bfc881ed9539d5d8509762b05c
/src/pffi/procedure.sls
09b2571f3ee480ea41da483ca328a61548fba107
[]
no_license
ktakashi/r6rs-pffi
6d0cf9b7c89ebf3a57fca81f8f5cb07769e742d1
d1aa1eae4d60677d3610611c711891136a03168a
refs/heads/master
2022-05-20T08:00:05.307243
2022-05-19T19:53:59
2022-05-19T19:53:59
35,493,751
44
9
null
2022-05-06T12:35:35
2015-05-12T14:41:35
Scheme
UTF-8
Scheme
false
false
3,184
sls
procedure.sls
;;; -*- mode:scheme; coding: utf-8; -*- ;;; ;;; src/pffi/procedure.sls - FFI Procedure ;;; ;;; Copyright (c) 2015 Takashi Kato <[email protected]> ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; #!r6rs (library (pffi procedure) (export foreign-procedure c-callback free-c-callback open-shared-object lookup-shared-object ;; primitive types ;; maybe these should be exported from ;; different library char unsigned-char short unsigned-short int unsigned-int long unsigned-long float double int8_t uint8_t int16_t uint16_t int32_t uint32_t int64_t uint64_t pointer callback void ___ size-of-char size-of-short size-of-int size-of-long size-of-float size-of-double size-of-pointer size-of-int8_t size-of-int16_t size-of-int32_t size-of-int64_t ) (import (rnrs) (pffi compat)) (define-syntax foreign-procedure (syntax-rules () ((_ lib (conv ...) ret name (args ...)) (make-c-function lib '(conv ...) ret 'name (list args ...))) ((_ lib ret name (args ...)) (make-c-function lib '() ret 'name (list args ...))))) (define-syntax c-callback (lambda (x) (syntax-case x (lambda) ((k ret ((type var) ...) (lambda (formals ...) body1 body ...)) (or (for-all bound-identifier=? #'(var ...) #'(formals ...)) (syntax-violation 'c-callback "invalid declaration" '#'x)) #'(k ret (type ...) (lambda (var ...) body1 body ...))) ((_ ret (args ...) proc) #'(make-c-callback ret (list args ...) proc))))) )
true
7cdf7c7df6481002159160f0ce12d00333897c4c
4b2aeafb5610b008009b9f4037d42c6e98f8ea73
/7/chapter.scm
f00db9577b0ffbcfb9490c7e41f785672ce32d36
[]
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
712
scm
chapter.scm
(require-extension syntax-case vector-lib (srfi 1 9)) (require '../srfi/srfi-70) (require '../7.1/section) (require '../2.1/section) (module chapter-7 (hoare-quicksort! hoare-partition! stooge-sort! tail-quicksort! tail-log-quicksort! median-of-three-quicksort! fuzzy-quicksort! make-interval interval->list) (import* srfi-70 exact-floor) (import* section-7.1 quicksort-general! partition-general! partition!) (import* section-2.1 insertion-sort) (include "../7/hoare-quicksort.scm") (include "../7/stooge-sort.scm") (include "../7/tail-quicksort.scm") (include "../7/median-of-three-quicksort.scm") (include "../7/fuzzy-sort.scm"))
false
47df5920fae29f627f43339ac317feba64d1b83b
08057c5b17633618982cdd1b4841f3fbc1ecacf5
/test.scm
604174481967f6f4a4a92506d6dead04536cf0c5
[ "BSD-2-Clause" ]
permissive
tabe/Gauche-magic
2e42e50dcac2b3ce0f3ad781bf81096257599040
09d5fa48939880c50bcbe2b697276943826c59ed
refs/heads/master
2020-04-08T19:24:35.348298
2008-07-17T01:34:17
2008-07-17T01:34:17
159,654,064
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,943
scm
test.scm
;;; -*- coding: euc-jp -*- ;;; ;;; test file.magic ;;; (use gauche.test) (use gauche.version) (test-start "file.magic") (use file.magic) (test-module 'file.magic) (test-section "constant") (define-syntax test*-constant (syntax-rules () ((_ (name value) ...) (begin (test* (symbol->string 'name) name value) ...)))) (test*-constant (MAGIC_NONE #x000) (MAGIC_DEBUG #x001) (MAGIC_SYMLINK #x002) (MAGIC_COMPRESS #x004) (MAGIC_DEVICES #x008) (MAGIC_MIME #x010) (MAGIC_CONTINUE #x020) (MAGIC_CHECK #x040) (MAGIC_PRESERVE_ATIME #x080) (MAGIC_RAW #x100) (MAGIC_ERROR #x200) ) (test-section "magic set") (define ms (magic-open 0)) (test* "magic-open" #t (is-a? ms <magic-set>)) (magic-load ms (default-magic-file)) (test* "magic-file" "ASCII C program text" (magic-file ms "file_magic.h")) (test* "magic-file" "ASCII C program text" (magic-file ms "file_magic.c")) (magic-close ms) (test-section "procedures") (call-with-magic-set (lambda (ms) (test* "call-with-magic-set(magic-file)" "Lisp/Scheme program text" (magic-file ms "file/magic.scm")) (test* "<magic-error>" #t (guard (e (else (condition-has-type? e <magic-error>))) (magic-file ms "no_such_file"))) )) (call-with-magic-set (lambda (ms) (test* "magic-check(empty)" *test-error* (magic-check ms "test/empty")) (test* "magic-check(trivial)" 0 (magic-check ms "test/trivial")) (test* "magic-compile" 0 (magic-compile ms "test/trivial"))) :flag MAGIC_CHECK) (test-section "errors") (call-with-magic-set (lambda (ms) (let ((e (guard (e (else e)) (magic-file ms "file_magic.h")))) (test* "<magic-error>" #t (condition-has-type? e <magic-error>)) (test* "slot message of <magic-error>" "no magic files loaded" (condition-ref e 'message)) (test* "slot no of <magic-error>" 0 (condition-ref e 'no)) )) :flag MAGIC_CHECK) (test-end) ;; Local variables: ;; mode: scheme ;; end:
true
a512e9b01ac363fc93964a92fe63b7dbabbf4f08
471a04fa9301455c51a890b8936cc60324a51f27
/srfi-lib/srfi/42/generators.scm
caf544c67d8432ed989c7046e4064f9e553308d5
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "MIT" ]
permissive
racket/srfi
e79e012fda6d6bba1a9445bcef461930bc27fde8
25eb1c0e1ab8a1fa227750aa7f0689a2c531f8c8
refs/heads/master
2023-08-16T11:10:38.100847
2023-02-16T01:18:44
2023-02-16T12:34:27
27,413,027
10
10
NOASSERTION
2023-09-14T14:40:51
2014-12-02T03:22:45
HTML
UTF-8
Scheme
false
false
18,496
scm
generators.scm
;;; ;;; NORMAL GENERATORS ;;; (module generators "mzscheme2.rkt" (provide (all-defined)) (require "expansion.scm") (require-for-syntax "expansion.scm") (require-for-template "mzscheme2.rkt") (define-generator :list (lambda (form-stx) (syntax-case form-stx (index) [(_ var (index i) expr ...) (add-index form-stx #'(_ var expr ...) #'i)] [(_ var expr1 expr2 expr ...) ; TODO IMPROVE: something better than append ? #'(_ var (append expr1 expr2 expr ...))] [(_ var expr) (begin (unless (identifier? #'var) (raise-syntax-error ':list "expected identifier, got " #'var)) ; (ob* oc* lb* ne1 ib* ic* ne2 ls*) (make-loop #'(() () ((xs expr)) (not (null? xs)) (((var) (car xs))) () #t ((cdr xs)))))] [_ (raise-syntax-error ':list "Expected either (:list <expr> ...) or (:list (index <var>) expr ...), got: " form-stx)]))) (define-generator (:integers form-stx) (syntax-case form-stx (index) [(_ var (index i)) ; (ob* oc* lb* ne1 ib* ic* ne2 ls*) (make-loop #'(() () ((var 0)) #t (((i) var)) () #t ((add1 var))))] [(_ var) ; (ob* oc* lb* ne1 ib* ic* ne2 ls*) (make-loop #'(() () ((var 0)) #t () () #t ((add1 var))))] [_ (raise-syntax-error ':integers "expected (:integers <var> (index <var>)) where (index <var>) is optional, got: " form-stx)])) (define (ec-:vector-filter vecs) ; filter zero-length vectors (if (null? vecs) '() (if (zero? (vector-length (car vecs))) (ec-:vector-filter (cdr vecs)) (cons (car vecs) (ec-:vector-filter (cdr vecs))) ))) ; The expansion below uses name-append to turn ; (:name var expr1 expr2 ...) ; into ; (:name var (name-append expr1 expr2 ...)) ; If your indexed sequence doesn't have an append operation ; (or it is too expensive to use) then use ; define-indexed-generator instead. (define-syntax (define-indexed-generator-with-append stx) (syntax-case stx () [(__ :name (name? name-ref name-length name-append name-type)) #'(define-generator (:name form-stx) (syntax-case form-stx (index) [(_ var (index i) expr (... ...)) (add-index form-stx #'(:name var expr (... ...)) #'i)] [(_ var expr) (begin (unless (identifier? #'var) (raise-syntax-error ':name "expected a variable to bind" #'var)) #'(:do (let ((seq expr) (len 0)) (set! len (name-length seq))) ((i 0)) (< i len) (let ((var (name-ref seq i)))) #t ((+ i 1)) ))] [(_ var expr (... ...)) #`(:name var (let ([es (list expr (... ...))]) (unless (andmap name? es) (error ':name (format "expected ~as, but got: ~~a " name-type) es)) ; TODO: use raise-syntax-error above (how?) (apply name-append es)))] [_ (raise-syntax-error ':name (format "expected (~a <var> (index i) <expr> <expr> ...) where (index i) is optional, got: " ':name) form-stx)]))])) (define-indexed-generator-with-append :string (string? string-ref string-length string-append "string")) (define-indexed-generator-with-append :bytes (bytes? bytes-ref bytes-length bytes-append "byte-string")) ; The expansion below basically turns ; (:name var expr1 expr2 ...) ; into (nested (: xs (list expr1 expr2 ...) ; (:name var xs)) ; except we need to write it as a do-loop. (define-syntax (define-indexed-generator-without-append stx) (syntax-case stx () [(__ :name (name? name-ref name-length name-type)) #'(define-generator (:name form-stx) (syntax-case form-stx (index) [(_ var (index i) expr (... ...)) (add-index form-stx #'(:name var expr (... ...)) #'i)] [(_ var expr) (begin (unless (identifier? #'var) (raise-syntax-error ':name "expected a variable to bind" #'var)) #`(:do (let ((seq expr) (len 0)) (set! len (name-length seq))) ((i 0)) (< i len) (let ((var #,(syntax/loc form-stx (name-ref seq i))))) #t ((+ i 1)) ))] [(_ var expr (... ...)) #'(:do (let ([es ; filter zero-length sequences away (let lp ([es (list expr (... ...))]) (cond [(null? es) '()] [(zero? (name-length (car es))) (lp (cdr es))] [else (cons (car es) (lp (cdr es)))]))] [current #f] [current-length 0])) ((k 0)) (if (< k current-length) #t (if (null? es) #f (begin (set! current (car es)) (set! es (cdr es)) (set! current-length (name-length current)) (set! k 0) #t))) (let ((var (name-ref current k)))) #t ((+ k 1)))] [_ (raise-syntax-error ':name (format "expected (~a <var> (index i) <expr> <expr> ...) where (index i) is optional, got: " ':name) form-stx)]))])) (define-indexed-generator-without-append :vector (vector? vector-ref vector-length "vector")) (define-generator (:range form-stx) (syntax-case form-stx (index) ; handle index variable and add optional args ((:range var (index i) arg1 arg ...) (add-index form-stx #'(:range var arg1 arg ...) #'i)) ((:range var arg1) #'(:range var 0 arg1 1) ) ((:range var arg1 arg2) #'(:range var arg1 arg2 1) ) ; special cases (partially evaluated by hand from general case) ((:range var 0 arg2 1) #'(:do (let ((b arg2)) (when (not (and (integer? b) (exact? b))) (error "arguments of :range are not exact integer " "(use :real-range?)" 0 b 1 ))) ((var 0)) (< var b) (let ()) #t ((+ var 1)) )) ((:range var 0 arg2 -1) #'(:do (let ((b arg2)) (when (not (and (integer? b) (exact? b))) (error "arguments of :range are not exact integer " "(use :real-range?)" 0 b 1 ))) ((var 0)) (> var b) (let ()) #t ((- var 1)) )) ((:range var arg1 arg2 1) #'(:do (let ((a arg1) (b arg2)) (when (not (and (integer? a) (exact? a) (integer? b) (exact? b) )) (error "arguments of :range are not exact integer " "(use :real-range?)" a b 1 )) ) ((var a)) (< var b) (let ()) #t ((+ var 1)) )) ((:range var arg1 arg2 -1) #'(:do (let ((a arg1) (b arg2) (s -1) (stop 0)) (when (not (and (integer? a) (exact? a) (integer? b) (exact? b) )) (error "arguments of :range are not exact integer " "(use :real-range?)" a b -1 )) ) ((var a)) (> var b) (let ()) #t ((- var 1)) )) ; the general case ((:range var arg1 arg2 arg3) #'(:do (let ((a arg1) (b arg2) (s arg3) (stop 0)) (when (not (and (integer? a) (exact? a) (integer? b) (exact? b) (integer? s) (exact? s) )) (error "arguments of :range are not exact integer " "(use :real-range?)" a b s )) (when (zero? s) (error "step size must not be zero in :range") ) (set! stop (+ a (* (max 0 (ceiling (/ (- b a) s))) s))) ) ((var a)) (not (= var stop)) (let ()) #t ((+ var s)) )))) (define-generator (:real-range form-stx) (syntax-case form-stx (index) ; add optional args and index variable ((:real-range var arg1) #'(:real-range var (index i) 0 arg1 1) ) ((:real-range var (index i) arg1) #'(:real-range var (index i) 0 arg1 1) ) ((:real-range var arg1 arg2) #'(:real-range var (index i) arg1 arg2 1) ) ((:real-range var (index i) arg1 arg2) #'(:real-range var (index i) arg1 arg2 1) ) ((:real-range var arg1 arg2 arg3) #'(:real-range var (index i) arg1 arg2 arg3) ) ; the fully qualified case ((:real-range var (index i) arg1 arg2 arg3) #'(:do (let ((a arg1) (b arg2) (s arg3) (istop 0)) (when (not (and (real? a) (real? b) (real? s))) (error "arguments of :real-range are not real" a b s) ) (when (and (exact? a) (or (not (exact? b)) (not (exact? s)))) (set! a (exact->inexact a)) ) (set! istop (/ (- b a) s)) ) ((i 0)) (< i istop) (let ((var (+ a (* s i))))) #t ((+ i 1)) )))) ; Comment: The macro :real-range adapts the exactness of the start ; value in case any of the other values is inexact. This is a ; precaution to avoid (list-ec (: x 0 3.0) x) => '(0 1.0 2.0). (define-generator (:char-range form-stx) (syntax-case form-stx (index) [(_ var (index i) expr1 expr2) (add-index form-stx #'(:char-range var expr1 expr2) #'i)] [(_ var expr1 expr2) #'(:do (let ((imax (char->integer expr2)))) ((i (char->integer expr1))) (<= i imax) (let ((var (integer->char i)))) #t ((+ i 1)) )] [_ (raise-syntax-error ':char-range "expected (:char-range <var> (index <var>) <expr> <expr>) where the index is optional, got: " form-stx)])) (define-generator (:port form-stx) (syntax-case form-stx (index) ((:port var (index i) arg1 arg ...) (add-index form-stx #'(:port var arg1 arg ...) #'i)) ((:port var arg) #'(:port var arg read) ) ((:port var arg1 arg2) #'(:do (let ((port arg1) (read-proc arg2))) ((var (read-proc port))) (not (eof-object? var)) (let ()) #t ((read-proc port)) )) (_ (raise-syntax-error ':port "expected (:port <var> (index i) <reader-expr>) where index is optional, and the <reader-expr> defaults to read, got:" form-stx)))) ;;; ;;; SPECIAL GENERATORS ;;; (define-generator (:let form-stx) (syntax-case form-stx (index) ; ($ loop ob* oc* lb* ne1 ib* ic* ne2 ls*) [(_ var (index i) expr) (make-loop #'(() () ((var expr) (i 0)) #t () () #f ()))] [(_ var expr) (make-loop #'(() () ((var expr)) #t () () #f ()))] [_ (raise-syntax-error ':let "expected (:let <var> <expr>) or (:let <var> (index <var>) <expr>), got:" form-stx)])) (require-for-syntax (lib "match.ss")) (define-generator (:parallel form-stx) ; TODO: Check that all subforms are generators (syntax-case form-stx (index) [(_ (index i) q ...) (add-index form-stx #'(_ q ...) #'i)] [(_ gen) (generator->loop #'gen)] [(_ gen1 gen2) (syntax-case (list (loop-stx (generator->loop #'gen1)) (loop-stx (generator->loop #'gen2))) () [(((ob ...) (oc ...) (lb ...) ne1 (ib ...) (ic ...) ne2 (ls ...)) ((ob2 ...) (oc2 ...) (lb2 ...) ne12 (ib2 ...) (ic2 ...) ne22 (ls2 ...))) (make-loop #'((ob ... ob2 ...) (oc ... oc2 ...) (lb ... lb2 ...) (and ne1 ne12) (ib ... ib2 ...) (ic ... ic2 ...) (and ne2 ne22) (ls ... ls2 ...)))])] [(_ gen1 gen2 gen3 ...) #'(:parallel (:parallel gen1 gen2) gen3 ...)])) (define-generator (:until form-stx) (syntax-case form-stx (index) [(_ gen test-expr) (unless (generator-clause? #'gen) (raise-syntax-error ':until "expected <generator> in " #'gen)) (syntax-case (loop-stx (generator->loop #'gen)) () [(obs ocs lbs ne1 ibs ics ne2 lss) (make-loop #'(obs ocs lbs ne1 ibs ics (and ne2 (not test-expr)) lss))])] [_ (raise-syntax-error ':until "expected (:until <generator> <expression>), got: " form-stx)])) (define-generator (:do form-stx) (syntax-case form-stx (let let-values) ; short form -> fill in default value [(_ ((lv le) ...) ne1? (expr ...)) #'(:do (let ()) ((lv le) ...) ne1? (let ()) #t (expr ...))] ; convert (let _) variants to (let-values _) [(_ (let ((on oe) ...) <oc> ...) (<lb> ...) <ne1?> (let ((in ie) ...) <ic> ...) <ne2?> (<ls> ...)) #'(_ (let-values (((on) oe) ...) <oc> ...) (<lb> ...) <ne1?> (let-values ([(in) ie] ...) <ic> ...) <ne2?> (<ls> ...))] [(_ (let ((on oe) ...) <oc> ...) (<lb> ...) <ne1?> ilet <ne2?> (<ls> ...)) #'(_ (let-values (((on) oe) ...) <oc> ...) (<lb> ...) <ne1?> ilet <ne2?> (<ls> ...))] [(_ olet (<lb> ...) <ne1?> (let ((in ie) ...) <ic> ...) <ne2?> (<ls> ...)) #'(_ olet (<lb> ...) <ne1?> (let-values ([(in) ie] ...) <ic> ...) <ne2?> (<ls> ...))] ; now both outer bindings and inner bindings must be let-values bindings [(_ olet lbs ne1? ilet ne2? lss) (begin ; check syntax of subforms (syntax-case #'olet (let-values) [(let-values (((i ...) e) ...) oc ...) 'ok] [_ (raise-syntax-error ':do (string-append "expected (let ((<id> <expr>) ...) <command> ...) or\n" "(let-values ([(<id> ...) <expr>] ...) <command> ...) , got ") #'olet)]) (syntax-case #'ilet (let-values) [(let-values (((i ...) e) ...) ic ...) 'ok] [_ (raise-syntax-error ':do (string-append "expected (let ((<id> <expr>) ...) <command> ...) or\n" "(let-values ([(<id> ...) <expr>] ...) <command> ...), got ") #'ilet)]) (syntax-case #'lbs () [((i b) ...) (for-each (lambda (i) (unless (identifier? i) (raise-syntax-error ':do "expected an identifier, got: " i))) (syntax->list #'(i ...)))] [_ (raise-syntax-error ':do "expected loop bindings of the form ((<id> <expr>) ...), got: " #'lbs)]) (syntax-case #'lss () [(expr ...) 'ok] [_ (raise-syntax-error "expected loop steppers: (<expr> ...), got: " #'lss)]) ; everything is ok (syntax-case form-stx (let-values) [(_ (let-values ([(oi ...) oe] ...) oc ...) lbs ne1? (let-values ([(ii ...) ie] ...) ic ...) ne2? lss) ; (ob* oc* lb* ne1 ib* ic* ne2 ls*) (make-loop #'((((oi ...) oe) ...) (oc ...) lbs ne1? (((ii ...) ie) ...) (ic ...) ne2? lss))]))] [_ (raise-syntax-error ':do "TODO fix message: expected (:do (let ((<id> <expr>) ...) <cmd> ...) <ne1?> (let ((<id> <expr>) ...) <cmd> ...) (<expr> ...)), got " form-stx)])) (define-generator (:while form-stx) (syntax-case form-stx () [(_ gen test) (begin (unless (generator-clause? #'gen) (raise-syntax-error ':while "expected a generator clause, got: " #'gen)) (let ([loop (generator->loop #'gen)]) (syntax-case (loop-stx loop) () [((ob ...) (oc ...) (lb ...) ne1 (((ib-var ...) ib-rhs) ...) (ic ...) ne2 (ls ...)) (with-syntax ([(ib-tmp ...) (generate-temporaries #'(ib-var ... ...))] [(false ...) (map (lambda (x) #'f) (syntax->list #'(ib-var ... ...)))]) ; this trickery is necessary to make ib-vars visible in test (make-loop #'((ob ... ((ib-tmp) #f) ...) (oc ...) (lb ...) (let ([ne1-val ne1]) (and ne1-val (let-values ([(ib-var ...) ib-rhs] ...) ic ... (set! ib-tmp ib-var) ... ... (and ne1-val test)))) (((ib-var ...) ib-tmp) ...) () ne2 (ls ...))))])))] [_ (raise-syntax-error ':while "expected (:while <generator> <expr>) got: " form-stx)])) )
true
2b0e1f87ec4121a7a0a42c6094780d6eb1f730b6
923209816d56305004079b706d042d2fe5636b5a
/test/http/header-field/if-match.scm
5689a2c84b7c8a498ad784880c03b1517fe07f59
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
tabe/http
4144cb13451dc4d8b5790c42f285d5451c82f97a
ab01c6e9b4e17db9356161415263c5a8791444cf
refs/heads/master
2021-01-23T21:33:47.859949
2010-06-10T03:36:44
2010-06-10T03:36:44
674,308
1
0
null
null
null
null
UTF-8
Scheme
false
false
1,466
scm
if-match.scm
#!r6rs (import (rnrs (6)) (http header-field if-match) (http assertion) (xunit)) (assert-parsing-successfully If-Match "If-Match: \"xyzzy\"" `(,(string->list "If-Match") #\: (#\space) ((() (#\" ((ctext #\x) (ctext #\y) (ctext #\z) (ctext #\z) (ctext #\y)) #\"))) )) (assert-parsing-successfully If-Match "If-Match: \"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\"" `(,(string->list "If-Match") #\: (#\space) ((() (#\" ((ctext #\x) (ctext #\y) (ctext #\z) (ctext #\z) (ctext #\y)) #\")) (() (#\" ((ctext #\r) (ctext #\2) (ctext #\d) (ctext #\2) (ctext #\x) (ctext #\x) (ctext #\x) (ctext #\x)) #\")) (() (#\" ((ctext #\c) (ctext #\3) (ctext #\p) (ctext #\i) (ctext #\o) (ctext #\z) (ctext #\z) (ctext #\z) (ctext #\z)) #\"))) )) (assert-parsing-successfully If-Match "If-Match: *" `(,(string->list "If-Match") #\: (#\space) #\* )) (report)
false
d42c9c2e21d6b08ecafa3230c7570fbb69b2bb6c
f6c954bac9db8e566fdd24249a4970dd759455eb
/PT-1300012785-2.27.scm
b856d2710892d92da6331115f73552088ea10039
[]
no_license
yangzhixuan/sicp_hw
247de20628128345d22b417b86b30ce981cdaa12
48b67ec630cf5b57954ae7e18e4c1d915db148b9
refs/heads/master
2021-01-13T02:16:57.495913
2014-05-14T07:49:23
2014-05-14T07:49:23
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
295
scm
PT-1300012785-2.27.scm
(define (deep-reverse l) (define (iter result rest) (cond ((null? rest) result) ((pair? (car rest)) (iter (cons (deep-reverse (car rest)) result) (cdr rest) )) (else (iter (cons (car rest) result) (cdr rest))))) (iter '() l))
false
06ecd9c62ee5644cc4aac70b9d30ee7bf5eddc2a
86559ead39bbcb6133ce9245f232c2dea94284e6
/lib/html.scm
2884e222577c569064fedb01208c833990f83367
[ "MIT" ]
permissive
memarc/SchemeBBS-GitLab
808f9700cb988ccae0a847782c0aa291ab2fbf16
fcd89a06789a12146fcca6f5cb40002a4c74964f
refs/heads/master
2023-08-28T22:33:20.943531
2020-06-11T13:16:46
2020-06-11T13:16:46
423,300,176
0
0
null
null
null
null
UTF-8
Scheme
false
false
5,168
scm
html.scm
;;; sxml to html converter, this file is part of SchemeBBS ;;; ;;; Copyright © 2015 David Thompson <[email protected]> ;;; Copyright © 2018 Florian Léger <[email protected]> ;;; ;;; This program is free software: you can redistribute it and/or ;;; modify it under the terms of the GNU Affero General Public License ;;; as published by the Free Software Foundation, either version 3 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 ;;; Affero General Public License for more details. ;;; ;;; You should have received a copy of the GNU Affero General Public ;;; License along with this program. If not, see ;;; <http://www.gnu.org/licenses/>. ;;; Commentary: ;; ;; SXML to HTML conversion. ;; adapted from Guile to MIT Scheme ;; original: https://dthompson.us/rendering-html-with-sxml-and-gnu-guile.html ;; ;;; Code: ;(load-option 'format) ;;; SRFI 26 - Notation for Specializing Parameters without Currying ;;; https://github.com/scheme-requests-for-implementation/srfi-26 ;;; (load "srfi/srfi-26.scm") ;;; simple linear pattern matcher ;;; http://okmij.org/ftp/Scheme/match-case-simple.scm ;;; (load "utils/match.scm") (define sxml->html) (let () ;;; from Alex Shinn's match.scm ;;; http://synthcode.com/scheme/match.scm (define-syntax match-lambda (syntax-rules () ((_ (pattern guard . body) ...) (lambda (expr) (match expr (pattern guard . body) ...))))) ;;; from SRFI 13 - String Librarie ;;; https://github.com/scheme-requests-for-implementation/srfi-13 (define (string-for-each proc s) (define end (string-length s)) (let loop ((i 0)) (if (< i end) (begin (proc (string-ref s i)) (loop (+ i 1)))))) (define %self-closing-tags '(area base br col command embed hr img input keygen link meta param source track wbr)) (define (self-closing-tag? tag) "Return #t if TAG is self-closing." (pair? (memq tag %self-closing-tags))) (define %escape-chars (alist->hash-table '((#\" . "quot") (#\& . "amp") (#\< . "lt") (#\> . "gt")))) (define (string->escaped-html s port) "Write the HTML escaped form of S to PORT." (define (escape c) (let ((escaped (hash-table/get %escape-chars c #f))) (if escaped (format port "&~a;" escaped) (display c port)))) (string-for-each escape s)) (define (object->escaped-html obj port) "Write the HTML escaped form of OBJ to PORT." (string->escaped-html (call-with-output-string (cut display obj <>)) port)) (define (attribute-value->html value port) "Write the HTML escaped form of VALUE to PORT." (if (string? value) (string->escaped-html value port) (object->escaped-html value port))) (define (attribute->html attr value port) "Write ATTR and VALUE to PORT." (format port "~a=\"" attr) (attribute-value->html value port) (display #\" port)) (define (element->html tag attrs body port) "Write the HTML TAG to PORT, where TAG has the attributes in the list ATTRS and the child nodes in BODY." (let* ((nl-before '(p div html head hr h1 h2 h3 h3 h5 h6 meta dl ul ol li dt dd pre table tr th td link title script center blockquote form address body thead tfoot tbody col colgroup fieldset)) (nl-after '(br)) (nlb? (or (and (memq tag nl-before) #\newline) "")) (nla? (or (and (memq tag nl-after) #\newline) ""))) (format port "~a<~a" nlb? (string-upcase (symbol->string tag))) (for-each (match-lambda ((,attr ,value) () (display #\space port) (attribute->html attr value port))) attrs) (if (and (null? body) (self-closing-tag? tag)) (format port ">~a" nla?) (begin (display #\> port) (for-each (cut sxml->html <> port) body) (format port "</~a>~a" (string-upcase (symbol->string tag)) nla?))))) (define (doctype->html doctype port) (format port "<!DOCTYPE ~a>" doctype)) (set! sxml->html (lambda (tree #!optional port) "Write the serialized HTML form of TREE to PORT." (let ((port (if (default-object? port) (current-output-port) port))) (match tree (() () '()) (('doctype ,type) () (doctype->html type port)) (('raw ,html) () ; Unescaped, raw HTML output (display html port)) ((,tag (@ . ,attrs) . ,body) (symbol? tag) (element->html tag attrs body port)) ((,tag . ,body) (symbol? tag) (element->html tag '() body port)) ((,nodes . ,rest) () (for-each (cut sxml->html <> port) (list nodes rest))) (,text (string? text) (string->escaped-html text port)) (,obj () (object->escaped-html obj port))))))) ; Render arbitrary Scheme objects, too.
true
98cea31b0c6560ab2b1a3237557307a7216888a4
9d7417f187812a477793ca23da844b34ab2a139d
/Graphikos/GraphikosTests/lib/ironscheme/files.sls
bfcf0638e1526db0c5c183aeda85b2474ce891c4
[ "MIT", "BSD-3-Clause" ]
permissive
simonmoriat/PLP
5ae19daba4925919b593b4a21dc91dec9de9a6ce
3d130acaa45239cdb289462a242a8c15836a39ca
refs/heads/master
2023-05-11T23:36:28.347462
2016-06-08T07:07:50
2016-06-08T07:07:50
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
4,033
sls
files.sls
#| License Copyright (c) 2007-2015 Llewellyn Pritchard All rights reserved. This source code is subject to terms and conditions of the BSD License. See docs/license.txt. |# (library (ironscheme files) (export file-copy file-move file-create-time file-access-time file-modified-time directory-exists? delete-directory directory-move create-directory get-files get-directories change-extension path-combine get-directory-name get-extension get-filename get-filename-without-extension get-full-path get-path-root get-random-filename get-temp-filename get-temp-path path-rooted? path-has-extension? invalid-filename-characters invalid-path-characters) (import (rnrs) (ironscheme contracts) (ironscheme clr)) (clr-using System.IO) (define/contract file-copy (case-lambda [(from to) (file-copy from to #f)] [(from:string to:string overwrite?:boolean) (clr-static-call File Copy from to overwrite?)])) (define/contract (file-move from:string to:string) (clr-static-call File Move from to)) (define/contract (file-create-time fn:string) (clr-static-call File GetCreationTime fn)) (define/contract (file-access-time fn:string) (clr-static-call File GetLastAccessTime fn)) (define/contract (file-modified-time fn:string) (clr-static-call File GetLastWriteTime fn)) (define/contract (directory-exists? fn:string) (clr-static-call Directory Exists fn)) (define/contract delete-directory (case-lambda [(dir) (delete-directory dir #f)] [(dir:string recursive?:boolean) (clr-static-call Directory Delete dir recursive?)])) (define/contract (directory-move from:string to:string) (clr-static-call Directory Move from to)) (define/contract (create-directory name:string) (clr-static-call Directory CreateDirectory name)) (define/contract get-files (case-lambda [(dir) (get-files dir "*")] [(dir:string pattern:string) (clr-static-call Directory GetFiles dir pattern)])) (define/contract get-directories (case-lambda [(dir) (get-directories dir "*")] [(dir:string pattern:string) (clr-static-call Directory GetDirectories dir pattern)])) (define/contract (change-extension path:string extension:string) (clr-static-call Path ChangeExtension path extension)) (define/contract (path-combine path1:string path2:string) (clr-static-call Path (Combine String String) path1 path2)) (define/contract (get-directory-name path:string) (clr-static-call Path GetDirectoryName path)) (define/contract (get-extension path:string) (clr-static-call Path GetExtension path)) (define/contract (get-filename path:string) (clr-static-call Path GetFileName path)) (define/contract (get-filename-without-extension path:string) (clr-static-call Path GetFileNameWithoutExtension path)) (define/contract (get-full-path path:string) (clr-static-call Path GetFullPath path)) (define/contract (get-path-root path:string) (clr-static-call Path GetPathRoot path)) (define (get-random-filename) (clr-static-call Path GetRandomFileName)) (define (get-temp-filename) (clr-static-call Path GetTempFileName)) (define (get-temp-path) (clr-static-call Path GetTempPath)) (define/contract (path-rooted? path:string) (clr-static-call Path IsPathRooted path)) (define/contract (path-has-extension? path:string) (clr-static-call Path HasExtension path)) (define (invalid-filename-characters) (string->list (clr-new String (clr-static-call Path GetInvalidFileNameChars)))) (define (invalid-path-characters) (string->list (clr-new String (clr-static-call Path GetInvalidPathChars)))))
false
10fcd08dc0c4b63676ec2b647011c0632922325e
f0916dac3f6f73d721db09e137ce6201efd027d2
/sitelib/rfc/jwe.scm
d600bbe8b47645896e59fb02e3b58012c50d5444
[ "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "MIT", "BSD-2-Clause" ]
permissive
christoff-buerger/sagittarius-scheme
b8b9289650b4245c1f4d8d92d03d6d8e8e0faacf
f2ac5bbc48a65ca89f036000e5a658a429e0a8b9
refs/heads/master
2021-11-12T12:26:17.738912
2021-10-28T10:06:47
2021-10-28T10:06:47
243,363,196
0
0
NOASSERTION
2020-02-26T20:52:02
2020-02-26T20:52:01
null
UTF-8
Scheme
false
false
8,889
scm
jwe.scm
;;; -*- mode:scheme; coding:utf-8; -*- ;;; ;;; rfc/jwe.scm - JSON Web Encryption (JWE) ;;; ;;; Copyright (c) 2021 Takashi Kato <[email protected]> ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; ;; ref: https://tools.ietf.org/html/rfc7516 #!nounbound (library (rfc jwe) (export jwe-header? jwe-header-builder (rename (jwe-header <jwe-header>) (jose-header-typ jwe-header-typ) (jose-header-cty jwe-header-cty) (jose-header-custom-parameters jwe-header-custom-parameters) (jose-crypto-header-alg jwe-header-alg) (jose-crypto-header-jku jwe-header-jku) (jose-crypto-header-jwk jwe-header-jwk) (jose-crypto-header-kid jwe-header-kid) (jose-crypto-header-x5u jwe-header-x5u) (jose-crypto-header-x5c jwe-header-x5c) (jose-crypto-header-x5t jwe-header-x5t) (jose-crypto-header-x5t-s256 jwe-header-x5t-s256) (jose-crypto-header-crit jwe-header-crit)) jwe-header-enc jwe-header-zip jwe-header->json jwe-header->json-string write-jwe-header json->jwe-header json-string->jwe-header read-jwe-header jwe-object? make-jwe-object (rename (jwe-object <jwe-object>)) jwe-object-header jwe-object-encrypted-key jwe-object-iv jwe-object-cipher-text jwe-object-authentication-tag (rename (jose-object-parts jwe-object-parts)) jwe:parse jwe:encrypt make-direct-encryptor ) (import (rnrs) (rfc jose) (rfc jwk) (rfc base64) (rfc hmac) (crypto) (math) (record accessor) (record builder) (sagittarius) (text json) (text json object-builder)) (define-record-type jwe-header (parent <jose-crypto-header>) (fields enc zip)) (define-syntax jwe-header-builder (make-record-builder jwe-header ((custom-parameters '() ->jose-header-custom-parameter)))) (define-record-type jwe-object (parent <jose-object>) (fields header encrypted-key ;; encrypted CEK, session key iv ;; initial vector cipher-text authentication-tag) (protocol (lambda (n) (case-lambda ((header encrypted-key iv cipher-text tag) ((n '()) header encrypted-key iv cipher-text tag)) ((parts header encrypted-key iv cipher-text tag) ((n parts) header encrypted-key iv cipher-text tag)))))) ;; internal use (define-record-type parsed-jwe-header (parent jwe-header) (fields parsed-base64-url) (protocol (lambda (n) (lambda (header parsed-base64-url) ((apply n (record->list header)) parsed-base64-url))))) ;; it'd be a bit weird order, but shouldn't matter (define jwe-header-object-builder (json-object-builder (make-jwe-header jose-crypto-header-object-builder ("enc" string->symbol) (? "zip" #f string->symbol)))) (define jwe-header-serializer (json-object-serializer (jose-crypto-header-serializer ("enc" jwe-header-enc symbol->string) (? "zip" #f jwe-header-zip symbol->string)))) (define json->jwe-header (make-json->header jwe-header-object-builder (lambda (obj custom-parameters) (if (jwe-header? obj) (jwe-header-builder (from obj) (custom-parameters custom-parameters)) (assertion-violation 'json->jwe-header "Something went wrong" obj))))) (define (read-jwe-header port) (json->jwe-header (json-read port))) (define (json-string->jwe-header json-string) (read-jwe-header (open-string-input-port json-string))) (define (jwe-header->json jwe-header) (object->json jwe-header jwe-header-serializer)) (define write-jwe-header (case-lambda ((jwe-header) (write-jwe-header jwe-header (current-output-port))) ((jwe-header port) (json-write/normalized (jwe-header->json jwe-header) port)))) (define (jwe-header->json-string jwe-header) (let-values (((out e) (open-string-output-port))) (write-jwe-header jwe-header out) (e))) (define (jwe-header->base64url jwe-header) (if (parsed-jwe-header? jwe-header) (parsed-jwe-header-parsed-base64-url jwe-header) (let ((json (jwe-header->json-string jwe-header))) (base64url-encode-string json)))) (define (jwe:parse s) (let ((part* (jose-split s))) (unless (= 5 (length part*)) (assertion-violation 'jwe:parse "Invalid JWE format, parts must be 5" part*)) (let ((header (base64url-decode-string (car part*)))) (apply make-jwe-object part* (make-parsed-jwe-header (json-string->jwe-header header) (car part*)) (map (lambda (s) (base64url-decode (string->utf8 s))) (cdr part*)))))) ;; (decryptor, jwe-object) -> bytevector (define (jwe:decrypt decryptor jwe-object) (decryptor (jwe-object-header jwe-object) (jwe-object-encrypted-key jwe-object) (jwe-object-iv jwe-object) (jwe-object-cipher-text jwe-object) (jwe-object-authentication-tag jwe-object))) ;; (encryptor, jwe-header, payload) -> jwe-object (define (jwe:encrypt encryptor jwe-header payload) (encryptor jwe-header payload)) (define (make-random-iv-generator prng) (lambda (size) (read-random-bytes prng size))) (define default-iv-generator (make-random-iv-generator (secure-random ChaCha20))) (define (make-direct-encryptor key :key (iv-generator default-iv-generator)) (cond ((symmetric-key? key) (lambda (jwe-header payload) (core-encryptor key #vu8() jwe-header payload iv-generator))) ((jwk:oct? key) (make-direct-encryptor (generate-secret-key AES (jwk->octet-key key)))) (else (assertion-violation 'make-direct-encryptor "Unsupported type" key)))) (define (core-encryptor key encrypted-key jwe-header payload iv-generator) (define enc (jwe-header-enc jwe-header)) (define encryption-cipher (get-encryptor enc key iv-generator)) (define aad (jwe-header->aad jwe-header)) (let-values (((iv cipher-text auth-tag) (encryption-cipher aad payload))) (make-jwe-object jwe-header encrypted-key iv cipher-text auth-tag))) (define (get-encryptor enc key iv-generator) (case enc ((A128CBC-HS256) (aes-hmac-encryptor key 128 SHA-256 iv-generator)) ((A192CBC-HS384) (aes-hmac-encryptor key 192 SHA-384 iv-generator)) ((A256CBC-HS512) (aes-hmac-encryptor key 256 SHA-512 iv-generator)) (else (assertion-violation 'get-cipher "Unsupported cipher type" enc)))) (define (aes-hmac-encryptor key key-size digest iv-generator) (define size/2 (div key-size 8)) (define raw-key (symmetric-key-raw-key key)) (define mac-key (bytevector-copy raw-key 0 size/2)) (define enc-key (generate-secret-key AES (bytevector-copy raw-key size/2))) (define iv (iv-generator 16)) (define mode-parameter (make-composite-parameter (make-iv-parameter iv) (make-mode-name-parameter MODE_CBC) (make-padding-parameter pkcs5-padder))) (define enc-cipher (make-cipher AES enc-key :mode-parameter mode-parameter)) ;; aad, payload -> (iv, cipher-text, auth-tag) (lambda (aad payload) (let ((cipher-text (cipher-encrypt enc-cipher payload)) (md (hash-algorithm HMAC :key mac-key :hash digest)) (auth-tag (make-bytevector size/2))) (hash-init! md) (hash-process! md aad) (hash-process! md iv) (hash-process! md cipher-text) (hash-process! md (aad-compute-length aad)) (hash-done! md auth-tag) (values iv cipher-text auth-tag)))) (define (jwe-header->aad jwe-header) (let ((b64 (jwe-header->base64url jwe-header))) (string->utf8 b64))) ;; 64 bits integer represents bits of aad length. ;; convert it to bytevector (define (aad-compute-length aad) (define len (bytevector-length aad)) (integer->bytevector (* len 8) 8)) )
true
5446483c2e9ffed79b2aeb3b699a71857a2e5524
4bd59493b25febc53ac9e62c259383fba410ec0e
/Scripts/Task/tokenize-a-string/scheme/tokenize-a-string-2.ss
7ac82ff81b4a597d86e5c212612c00b4cff0aeb1
[]
no_license
stefanos1316/Rosetta-Code-Research
160a64ea4be0b5dcce79b961793acb60c3e9696b
de36e40041021ba47eabd84ecd1796cf01607514
refs/heads/master
2021-03-24T10:18:49.444120
2017-08-28T11:21:42
2017-08-28T11:21:42
88,520,573
5
1
null
null
null
null
UTF-8
Scheme
false
false
144
ss
tokenize-a-string-2.ss
(define s "Hello,How,Are,You,Today") (define words (string-tokenize s (char-set-complement (char-set #\,)))) (define t (string-join words "."))
false
7ace00f60827f88831bcd558216d5cbac7541255
9d93392eddf3db2493c44d1363d7e8a3c6aa5bda
/predicate.scm
c819072f0bd7dbe125b966ecd0dc9105c8ae4eb6
[]
no_license
valvallow/liv
b2db1146a109bc716a896382ec4a2bc0530bfede
e3b7f9a2c6e7022516dd2315dcc5531977c679aa
refs/heads/master
2020-05-30T16:30:22.469334
2011-02-09T03:02:17
2011-02-09T03:02:17
867,480
1
0
null
null
null
null
UTF-8
Scheme
false
false
326
scm
predicate.scm
(define-module liv.predicate (export-all)) (select-module liv.predicate) (define-syntax coalesce (syntax-rules () ((_) #f) ((_ (exp val) x ...) (if exp val (coalesce x ...))))) (define-syntax if-true (syntax-rules () ((_ pred exp) (if pred exp #f)))) (provide "liv/predicate")
true
f2bf6a7cb4f075d44102f2d5db1bbb6b7837a2ee
b60cb8e39ec090137bef8c31ec9958a8b1c3e8a6
/test/R5RS/ad/btree.scm
566c2e4558cf8b33299aeddbebaa32288b402bcb
[]
no_license
acieroid/scala-am
eff387480d3baaa2f3238a378a6b330212a81042
13ef3befbfc664b77f31f56847c30d60f4ee7dfe
refs/heads/master
2021-01-17T02:21:41.692568
2021-01-15T07:51:20
2021-01-15T07:51:20
28,140,080
32
16
null
2020-04-14T08:53:20
2014-12-17T14:14:02
Scheme
UTF-8
Scheme
false
false
792
scm
btree.scm
(define (make-node key left right parent info) (list key left right parent info)) (define (key node) (list-ref node 0)) (define (left node) (list-ref node 1)) (define (right node) (list-ref node 2)) (define (parent node) (list-ref node 3)) (define (info node) (list-ref node 4)) (define (set-key! node key) (set-car! node key)) (define (set-left! node l) (set-car! (cdr node) l)) (define (set-right! node r) (set-car! (cddr node) r)) (define (set-parent! node p) (set-car! (cdddr node) p)) (define (set-info! node i) (set-car! (cddddr node) i)) (define null-tree '()) (define (null-tree? tree) (null? tree)) (define (is-leaf? node) (and (null-tree? (left node)) (null-tree? (right node)))) (define (is-root? node) (null-tree? (parent node)))
false
42c3fb350457634fc0580a06b8bb95d8e6174cd8
fca0221e2352708d385b790c665abab64e92a314
/redaction/benchmarks/MeroonV3-2008Mar01/coinst.scm
a5e3d91b9e1ed2cf7850f5eb895f309ddd3dfc19
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
sthilaid/memoire
a32fdb1f9add0cc0d97c095d11de0c52ae2ed2e2
9b26b0c76fddd5affaf06cf8aad2592b87f68069
refs/heads/master
2020-05-18T04:19:46.976457
2010-01-26T01:18:56
2010-01-26T01:18:56
141,195
1
2
null
null
null
null
UTF-8
Scheme
false
false
3,923
scm
coinst.scm
;;; $Id: coinst.scm,v 1.1 2005/02/25 22:19:37 lucier Exp lucier $ ;;; Copyright (c) 1990-96 by Christian Queinnec. All rights reserved. ;;; *********************************************** ;;; Small, Efficient and Innovative Class System ;;; Meroon ;;; Christian Queinnec ;;; Ecole Polytechnique & INRIA--Rocquencourt ;;; ************************************************ ;;; This file defines how to coinstantiate multiple objects at the same ;;; time with mutual references (a little like a letrec form). ;;; For instance, you can say: ;;; (co-instantiate ;;; (x Pair :left y :right x) ;;; (y Point) ) ;;; x and y are allocated, then x fields are initialized with the given ;;; definitions (x may use x and y), then y fields are initialized, then ;;; default initializations for x and y take place. Finally the first ;;; object, here x, is returned as value of the whole form. Note that ;;; initializations are processed from left to right so you can write ;;; (co-instantiate ;;; (x Pair :left y :right x) ;;; (y Point) ;;; (z Pair :right (Pair-left x)) ) ;;; ;;; The co-instantiate form is expanded into a begin form containing ;;; set! forms so you cannot use it at toplevel unless the variables are ;;; already globally defined. If you want them locally as with a letrec ;;; form, use the cousin macro: ;;; (with-co-instantiation ;;; ((x Pair :left y :right x) ;;; (y Point :x 33) ) ;;; body ) (define (process-co-instantiate-form definitions definer) (let* ((forms (map (lambda (def) (if (and (pair? def) (pair? (cdr def))) (process-co-instantiation-form (car def) (cadr def) (cddr def) ) (report-meroon-error 'Syntax 'co-instantiate "Missing parameters" def ) ) ) definitions )) (names (map car definitions)) ) `(begin ,@(map (lambda (name alloc+init) `(,definer ,name ,(car alloc+init)) ) names forms ) ,@(map cdr forms) ,(if (pair? names) (car names) #f) ) ) ) ;;; This function returns a pair of two forms: a raw allocation form ;;; and an initialization form. (define (process-co-instantiation-form name class-name parms) (process-co-instantiation name (symbol->class class-name (lambda (name) (report-meroon-error 'Syntax 'co-instantiate "Unknown class" name ) ) ) parms ) ) ;;; This is where the real work is done. This function is inspired from ;;; the process-instantiation function. (define (process-co-instantiation name class parms) (let* ((fields (careless-Class-fields class)) (class-name (symbol-concatenate (careless-Class-name class) '-class)) ;; content is a list of couples (field-size . field-content), ;; the process-initialization function just splits the parameters ;; for each field: (contents (process-initialization fields parms find-initialization )) ) (let ((index (gensym))) (cons `((careless-Class-allocator ,class-name) ,@(generate-whole-size fields contents) ) `(let ((,index 0)) ,@(generate-whole-initialization name index fields contents) (initialize! (fill-other-fields! ,name)) ) ) ) ) ) ;;; Make the co-defined objects local to a let form so the body can be ;;; evaluated in the right environment. (define (process-with-co-instantiation-form definitions body) (let ((initforms (process-co-instantiate-form definitions 'define))) `(let () ,@(cdr initforms) . ,body ) ) ) ;;; end of coinst.scm
false
c9362a529d9e01462f737880d68e050d5694b74d
5d5da19f36a1a200b2273e6da4f309e3ec0e3a82
/texture.scm
666573b5e5e0217686b7f04b043e1ecdaaf3fdfb
[ "MIT" ]
permissive
soma-arc/scheme-raytrace
84f0688b95899b8ca1c081aac9dd8ad5c0dff35b
c5802c6fdeb268b1df50b4c13d55f43c348f0120
refs/heads/master
2021-01-21T04:50:21.094182
2016-06-21T12:29:21
2016-06-21T12:29:21
54,718,758
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,541
scm
texture.scm
(define-module texture (use srfi-27) (use vec :prefix v:) (use perlin) (export-all)) (select-module texture) (define-inline (value tex u v p) ((vector-ref tex 0) u v p)) (define (constant-texture color) (vector (lambda (u v p) color))) (define (checker-texture even-tex odd-tex) (vector (lambda (u v p) (let ((sines (* (sin (* 10 (v:x p))) (sin (* 10 (v:y p))) (sin (* 10 (v:z p)))))) (if (< sines 0) (value odd-tex u v p) (value even-tex u v p)))))) (define (noise-texture sc) (vector (lambda (u v p) (v:scale (v:vec3 1 1 1) (noise (v:scale p sc)))))) (define (marble-texture sc) (vector (lambda (u v p) (v:scale (v:vec3 1 1 1) (* 0.5 (+ 1 (sin (+ (* sc (v:z p)) (* 10 (turb p)))))))))) (define (image-texture data nx ny) (vector (lambda (u v p) (let* ((i (* u nx)) (j (- (* (- 1 v) ny) 0.001)) (i (if (< i 0) 0 i)) (j (if (< j 0) 0 j)) (i (if (> i (- nx 1)) (- nx 1) i)) (j (if (> j (- ny 1)) (- ny 1) j))) (v:vec3 (/ (floor->exact (vector-ref data (+ (* 3 i) (* 3 nx j)))) 255) (/ (floor->exact (vector-ref data (+ (* 3 i) (* 3 nx j) 1))) 255) (/ (floor->exact (vector-ref data (+ (* 3 i) (* 3 nx j) 2))) 255))))))
false
e4588bcdf078f5ba0b7ecdf4d20eed035e4a3d5a
382706a62fae6f24855ab689b8b2d87c6a059fb6
/0.3/interpreter/src/protocol-pairing.scm
703fa01f20210e0db7bac9b887b559090f48bfb0
[ "Apache-2.0" ]
permissive
mstram/bard
ddb1e72a78059617403bea1842840bb9e979198e
340d6919603a30c7944fb66e04df0562180bc0bb
refs/heads/master
2021-01-21T00:12:27.174597
2014-07-10T13:20:39
2014-07-10T13:20:39
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
765
scm
protocol-pairing.scm
;;;; *********************************************************************** ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: protocol-pairing.scm ;;;; Project: Bard ;;;; Purpose: arranging values in pairs ;;;; Author: mikel evins ;;;; Copyright: 2012 by mikel evins ;;;; ;;;; *********************************************************************** (declare (extended-bindings)) (##include "type-signature-macros.scm") (##include "protocol-macros.scm") (define-protocol-function Pairing left signatures: (list (signature (Pair) #f (Anything)))) (define-primitive-method left (<pair>) car) (define-protocol-function Pairing right signatures: (list (signature (Pair) #f (Anything)))) (define-primitive-method right (<pair>) cdr)
false
215e3226c00dfeab623bf5277019f46e5f275de2
d51c8c57288cacf9be97d41079acc7c9381ed95a
/scsh/scheme/stringcoll.scm
48bf63888792cf3b21a372af0202f09b7a125872
[]
no_license
yarec/svm
f926315fa5906bd7670ef77f60b7ef8083b87860
d99fa4d3d8ecee1353b1a6e9245d40b60f98db2d
refs/heads/master
2020-12-13T08:48:13.540156
2020-05-04T06:42:04
2020-05-04T06:42:04
19,306,837
2
0
null
null
null
null
UTF-8
Scheme
false
false
6,910
scm
stringcoll.scm
;;; Copyright (c) 1994 by Olin Shivers ;;; String collectors ;;; =========================================================================== ;;; string-collector ;;; (make-string-collector) ;;; (collect-string! SC S) ;;; (clear-string-collector! SC) ;;; (string-collector->string SC) ;;; ;;; A string collector is a data structure that reduces the overhead of ;;; accumulating a large string in bits and pieces. It is basically a ;;; "chunk list," where a chunk is a string of at least 128 chars. In this ;;; way, the list overhead is kept under 2% of the whole data structure. ;;; When a new string is added to the collection, it is added to the current ;;; chunk. When the chunk reaches 128 chars, it is added to the chunk list, ;;; and a new chunk is started. If a large string is added to the collection, ;;; it is added as a chunk itself, so large strings are not split into small ;;; pieces. (Actually, a *copy* of the original large string is saved as a ;;; single chunk, so the collector's chunks are not shared with client data.) ;;; ;;; MAKE-STRING-COLLECTOR allocates a new string collector data structure. ;;; COLLECT-STRING! appends a string to the current collection. ;;; CLEAR-STRING-COLLECTOR! clears out accumulated strings from a collector. ;;; STRING-COLLECTOR->STRING converts a collector into a contiguous string. ;;; ;;; This facility makes it reasonably efficient to accumulate strings ;;; of any size in increments of any size. (define-record-type :string-collector (really-make-string-collector len chunks chunk chunk-left) string-collector? ;; How many chars have we accumulated? (len string-collector:len set-string-collector:len) ;; The chunk list. (chunks string-collector:chunks set-string-collector:chunks) ;; The current chunk being filled, if any. (chunk string-collector:chunk set-string-collector:chunk) ;; How many chars left to fill in the current chunk. (chunk-left string-collector:chunk-left set-string-collector:chunk-left)) (define (make-string-collector) (really-make-string-collector 0 '() #f 0)) (define (clear-string-collector! sc) (set-string-collector:len sc 0) (set-string-collector:chunks sc '()) (set-string-collector:chunk sc #f) sc) ;;; (COLLECT-STRING! sc s) ;;; ---------------------- ;;; S is a string. Append it to the string being collected in the ;;; string-collector SC. ;;; ;;; The algorithm: ;;; First, do nothing if S is the empty string. Otherwise: ;;; If there is a current chunk: ;;; Copy characters from S into it. ;;; If we filled up the chunk ;;; Put the chunk on the chunk list. ;;; Look at the remaining chars from S we haven't copied yet. ;;; If there a lot of characters left (>= 128) ;;; Save them as a single chunk on the chunk list. ;;; No current chunk. ;;; Else if there a just a few characters left (> 0, < 128) ;;; Start a new current chunk, copy the chars left into it. ;;; Else if there aren't any characters left ;;; No current chunk. ;;; ;;; If there is no current chunk: ;;; If there are a lot of characters in S (>= 128) ;;; Save a copy of S as a single chunk on the chunk list. ;;; Still no current chunk. ;;; Else if there are a few characters in S (> 0, < 128) ;;; Start a new current chunk, copy the S into it. (define (collect-string! sc s) (let ((slen (string-length s)) (chunk (string-collector:chunk sc)) (chunk-left (string-collector:chunk-left sc)) ;; Add the chunk C to the collector's chunk list. (push-chunk! (lambda (c) (set-string-collector:chunks sc (cons c (string-collector:chunks sc))))) ;; Copy nchars characters from src[j] to dest[i] ;; *Way* too much bounds checking going on in this loop. (copy-substring! (lambda (dest i src j nchars) (do ((i i (+ i 1)) (j j (+ j 1)) (nchars nchars (- nchars 1))) ((zero? nchars)) (string-set! dest i (string-ref src j)))))) (cond ((zero? slen)) ; Empty string, do nothing. (chunk (let ((ncopy (min slen chunk-left))) (copy-substring! chunk (- 128 chunk-left) s 0 ncopy) (if (> chunk-left slen) (set-string-collector:chunk-left sc (- chunk-left slen)) ;; Current chunk is full. (let ((s-left (- slen chunk-left))) (push-chunk! chunk) ; Push the current chunk. ;; Handle remaining chars from S that weren't copied into ;; the current chunk we just pushed: (cond ((>= s-left 128) ;; A lot more chars left. Push them as one chunk. (push-chunk! (substring s chunk-left slen)) (set-string-collector:chunk sc #f)) ((> s-left 0) ;; A few more chars left. Start a new chunk. (let ((new-chunk (make-string 128))) (copy-substring! new-chunk 0 s chunk-left s-left) (set-string-collector:chunk sc new-chunk) (set-string-collector:chunk-left sc (- 128 s-left)))) ;; No more chars left. No current chunk. (else (set-string-collector:chunk sc #f))))))) (else ; No current chunk. (if (>= slen 128) ; How many chars is S? (push-chunk! (string-copy s)) ; A lot. Push as one chunk. (let ((chunk (make-string 128))) ; Not many. Start a new chunk. (set-string-collector:chunk sc chunk) (copy-substring! chunk 0 s 0 slen) (set-string-collector:chunk-left sc (- 128 slen)))))) ;; We don't actually do anything with this, but we keep it updated anyway. (set-string-collector:len sc (+ (string-collector:len sc) slen)) sc)) ;;; A bummed version for collecting a single character. (define (collect-char! sc c) (let ((chunk (string-collector:chunk sc)) (chunk-left (string-collector:chunk-left sc))) (cond (chunk (string-set! chunk (- 128 chunk-left) c) (cond ((> chunk-left 1) (set-string-collector:chunk-left sc (- chunk-left 1))) (else (set-string-collector:chunks sc (cons chunk (string-collector:chunks sc))) (set-string-collector:chunk sc #f)))) (else (let ((new-chunk (make-string 128 c))) (set-string-collector:chunk-left sc 127) (set-string-collector:chunk sc new-chunk))))) ;; We don't actually do anything with this, but we keep it updated anyway. (set-string-collector:len sc (+ (string-collector:len sc) 1)) sc) ;;; Convert the data in the string-collector SC to a single contiguous ;;; string and return it. (define (string-collector->string sc) (let ((chunk (string-collector:chunk sc)) (chunks (string-collector:chunks sc))) (apply string-append (reverse (if chunk (cons (substring chunk 0 (- 128 (string-collector:chunk-left sc))) chunks) chunks))))) ;;; It's too bad we can't side-effect the string-collector's chunk list ;;; to be a single chunk after this coalescing operation, but we don't ;;; want to share the string we return -- the user might side-effect it.
false
8b58d6f7584e2dbad75abce2085ab53af0bd184a
df0ba5a0dea3929f29358805fe8dcf4f97d89969
/exercises/software-engineering/05/selection-sort.scm
35b2d21fe172cbdf13d98fbcb38f97469113b1b8
[ "MIT" ]
permissive
triffon/fp-2019-20
1c397e4f0bf521bf5397f465bd1cc532011e8cf1
a74dcde683538be031186cf18367993e70dc1a1c
refs/heads/master
2021-12-15T00:32:28.583751
2021-12-03T13:57:04
2021-12-03T13:57:04
210,043,805
14
31
MIT
2019-12-23T23:39:09
2019-09-21T19:41:41
Racket
UTF-8
Scheme
false
false
1,053
scm
selection-sort.scm
(define (minimum l) (apply min l)) (define (take-while p l) (if (or (null? l) (not (p (car l)))) '() (cons (car l) (take-while p (cdr l))))) (define (drop-while p l) (if (or (null? l) (not (p (car l)))) l (drop-while p (cdr l)))) (define (remove x l) (define (!=x y) (not (= y x))) (if (not (member x l)) l (append (take-while !=x l) (cdr (drop-while !=x l))))) (define (selection-sort l) (if (null? l) '() (let ((min-in-l (minimum l))) (cons min-in-l (selection-sort (remove min-in-l l)))))) (load "../testing/check.scm") (check (selection-sort '()) => '()) (check (selection-sort '(42)) => '(42)) (check (selection-sort '(6 6 6)) => '(6 6 6)) (check (selection-sort '(1 2 3 4 5 6)) => '(1 2 3 4 5 6)) (check (selection-sort '(6 5 4 3 2 1)) => '(1 2 3 4 5 6)) (check (selection-sort '(3 1 4 6 2 5)) => '(1 2 3 4 5 6)) (check (selection-sort '(5 2 5 1 5 2 3)) => '(1 2 2 3 5 5 5)) (check-report) (check-reset!)
false
a1a71a11715b5fc021c6dcbe4478a7177eddce31
5355071004ad420028a218457c14cb8f7aa52fe4
/1.2/e-1.16.scm
313f36e62e6ad8dd700723e877af64ea349ddf36
[]
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,370
scm
e-1.16.scm
; Exercise 1.16. ; ; Design a procedure that evolves an iterative exponentiation process that uses successive ; squaring and uses a logarithmic number of steps, as does fast-expt. ; (Hint: Using the observation that (b^(n/2))^2 = (b^2)^(n/2), keep, along with the exponent ; n and the base b, an additional state variable a, and define the state transformation in ; such a way that the product a bn is unchanged from state to state. At the beginning of ; the process a is taken to be 1, and the answer is given by the value of a at the end of the ; process. In general, the technique of defining an invariant quantity that remains unchanged ; from state to state is a powerful way to think about the design of iterative algorithms.) ; ; ----------------------------- ; ; We have to introduce product that will be passed through iterations, ; as suggested in the task. One porblem is that the way fast-expt in ; example is given it doesn't allow us to pass n to next iteration. By ; putting n out of squaring by transforming (b^(n/2))^2 => (b^2)^(n/2) ; we can write following procedure. ; (load "../common.scm") (define (expt b n) (fast-expt b n 1)) (define (fast-expt b n product) (cond ((= n 0) product) ((even? n) (fast-expt (square b) (/ n 2) product)) (else (fast-expt b (- n 1) (* product b))))) ; (display (expt 2 30)) ; (newline)
false
c6c7db5cbc4db5f0e71fd4c797b3eb7c27e20967
ea4e27735dd34917b1cf62dc6d8c887059dd95a9
/section1_3_exercise1_34.scm
27e398833fb887fa989cc69d19baeae310c7519f
[ "MIT" ]
permissive
feliposz/sicp-solutions
1f347d4a8f79fca69ef4d596884d07dc39d5d1ba
5de85722b2a780e8c83d75bbdc90d654eb094272
refs/heads/master
2022-04-26T18:44:32.025903
2022-03-12T04:27:25
2022-03-12T04:27:25
36,837,364
1
0
null
null
null
null
UTF-8
Scheme
false
false
603
scm
section1_3_exercise1_34.scm
(define (f g) (g 2)) (f square) (f (lambda (z) (* z (+ z 1)))) ;What will happen if the following is evaluated ; (f f) ; ;Clarifying the definition of f ; (define f (lambda (g) (g 2))) ; ;The expression (f f) turns into: ; ((lambda (g) (g 2) (lambda (g) (g 2)) ; ^ ^ \_______________/ ; | | | ; \___\____________/ ;The paremeter lambda is replaced in the body of the procedure ; ((lambda (g) (g 2)) 2) ; ^ | ; |_________| ;The parameter 2 is replaced in the body of the procedure ; (2 2) ; ^ ; |__ 2 is not applicable
false
3b73c55dd8ed242bbdd9a71c5d3da151b9880c34
4f17c70ae149426a60a9278c132d5be187329422
/scheme/r6rs/sorting.ss
86d829601ddb841cac73bbaa4c46e34345b3a9e2
[]
no_license
okuoku/yuni-core
8da5e60b2538c79ae0f9d3836740c54d904e0da4
c709d7967bcf856bdbfa637f771652feb1d92625
refs/heads/master
2020-04-05T23:41:09.435685
2011-01-12T15:54:23
2011-01-12T15:54:23
889,749
2
0
null
null
null
null
UTF-8
Scheme
false
false
113
ss
sorting.ss
(library (yuni scheme r6rs sorting) (export list-sort vector-sort vector-sort!) (import (yuni scheme r6rs)))
false
6bb48911d709de2ed65ac7224e09163372674e06
5927f3720f733d01d4b339b17945485bd3b08910
/tests/base64-test.scm
1fd660e6ce06ee48145dcea5cea4b35cae36ed27
[]
no_license
ashinn/hato
85e75c3b6c7ca7abca512dc9707da6db3b50a30d
17a7451743c46f29144ce7c43449eef070655073
refs/heads/master
2016-09-03T06:46:08.921164
2013-04-07T03:22:52
2013-04-07T03:22:52
32,322,276
5
0
null
null
null
null
UTF-8
Scheme
false
false
1,580
scm
base64-test.scm
(use test) (load "hato-base64.scm") (test-begin) (test "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=" (base64-encode-string "abcdefghijklmnopqrstuvwxyz")) (test "abcdefghijklmnopqrstuvwxyz" (base64-decode-string "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo")) (test "abcdefghijklmnopqrstuvwxyz" (base64-decode-string "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=")) (test "abcdefghijklmnopqrstuvwxyz" (base64-decode-string "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo==")) (test "abcdefghijklmnopqrstuvwxyz" (base64-decode-string "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=YWJjZGVm=")) (test "abcdefghijklmnopqrstuvwxyz" (base64-decode-string "YWJjZ\nGVmZ2\nhpamtsbW5\nvcHFyc3R1dnd4eXo=")) (test "abcdefghijklmnopqrstuvwxyz" (with-output-to-string (lambda () (base64-decode (open-input-string "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo"))))) (test "abcdefghijklmnopqrstuvwxyz" (with-output-to-string (lambda () (base64-decode (open-input-string "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo="))))) (test "abcdefghijklmnopqrstuvwxyz" (with-output-to-string (lambda () (base64-decode (open-input-string "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=="))))) (test "abcdefghijklmnopqrstuvwxyz" (with-output-to-string (lambda () (base64-decode (open-input-string "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=YWJjZGVm="))))) (test "abcdefghijklmnopqrstuvwxyz" (with-output-to-string (lambda () (base64-decode (open-input-string "YWJjZ\nGVmZ2\nhpamtsbW5\nvcHFyc3R1dnd4eXo="))))) (test-end)
false
12ebf2334b0715185c2ad5f9cbd52780c916d8bd
9b0c653f79bc8d0dc87526f05bdc7c9482a2e277
/1/1-36.ss
8b11a9672d3504af1c501b61ec1f43db03fdc053
[]
no_license
ndNovaDev/sicp-magic
798b0df3e1426feb24333658f2313730ae49fb11
9715a0d0bb1cc2215d3b0bb87c076e8cb30c4286
refs/heads/master
2021-05-18T00:36:57.434247
2020-06-04T13:19:34
2020-06-04T13:19:34
251,026,570
0
0
null
null
null
null
UTF-8
Scheme
false
false
432
ss
1-36.ss
(define (fp f fg) (define tolerance 0.0001) (define (close-enough? v1 v2) (< (abs (- v1 v2)) tolerance)) (define (try guess) (display guess) (newline) (let ((next (f guess))) (if (close-enough? guess next) next (try next)))) (try fg)) ; (display (fp (lambda (x) (/ (log 1000) (log x))) 3)) ;28 ; (display (fp (lambda (x) (/ (+ x (/ (log 1000) (log x))) 2)) 3)) ;7 (exit)
false
cad29f96077dc9ef8a13b8bd6946cb0f884ca17b
6cf2e78840970768168f583716e8826b1902dafa
/learning-functional/work-in-university/week-04/work-04-hr.scm
2f876947ce007c7197e7a3346f8a2b1e686f1ebf
[]
no_license
dianvaltodorov/learning-code
e4b3e5034c68cdf9d1e38f8b6a12af1d51d2e167
a92605345829e051c0b2420de6f3dfc1fe5eb65a
refs/heads/master
2021-01-17T12:24:58.618311
2016-02-02T17:48:55
2018-06-21T06:53:16
49,488,021
2
0
null
null
null
null
UTF-8
Scheme
false
false
1,286
scm
work-04-hr.scm
(define (accumulate start end next term comb initial) (define (helper current res) (if(> current end) res (helper (next current) (comb res (term current))))) (helper start initial)) (define (fact n) (accumulate 1 n (lambda (x) (+ x 1)) (lambda (x) x) * 1)) (define (pow x n) (accumulate 1 n (lambda (x) (+ x 1)) (lambda (_) x) * 1)) (define (variation n k) (/ (fact n) (fact (- n k)))) (define (combination n k) (/ (fact n) (* (fact k)(fact (- n k))))) (define (expo x) (accumulate 0 10000000 (lambda (x) (+ x 1)) (lambda (n) (/ (pow x n) (fact n))) + 0)) (define (sine x) (accumulate 0 100 (lambda (x) (+ x 1)) (lambda (n) (* (pow -1 n) (/ (pow x (+ (* 2 n) 1)) (fact (+ (* 2 n) 1))))) + 0)) (sine (/ 3.1415 2)) (sine 0) (define (cosine x) (accumulate 0 100 (lambda (x) (+ x 1)) (lambda (n) (* (pow -1 n) (/ (pow x (* 2 n)) (fact (* 2 n))))) + 0)) (define (prime? n) (accumulate )) ;(reverse n) ;(sqrt x)
false
247fd5530a810a5b9e610779c97d8a7d7e7f0f85
961ccc58c2ed4ed1d84a78614bedf0d57a2f2174
/lisp/pkhuong/codegen-patterns.scm
20b4e69d60f1c44d00cc2be6983230d561252423
[]
no_license
huangjs/mostly-lisp-code
96483b566b8fa72ab0b73bf0e21f48cdb80dab0d
9fe862dbb64f2a28be62bb1bd996238de018f549
refs/heads/master
2021-01-10T10:11:50.121705
2015-11-01T08:53:22
2015-11-01T08:53:22
45,328,850
0
0
null
null
null
null
UTF-8
Scheme
false
false
4,733
scm
codegen-patterns.scm
;;; Included from codegen.scm ;; this is actually special-cased by the codegen (define-pattern var ((node node read-var?) (type (expression-node-type node)) (reg (var-pseudo-reg node))) cost: 1 emit: (if (eq? type 'int) (make-move-int dst reg) (make-move-fp dst reg))) ;; and so is that... (define-pattern assign-var ((node node assign-var?) (var (assign-var-var node)) (reg (var-pseudo-reg var)) (val (assign-var-value node)) (int? (eq? 'int (expression-node-type val)))) dst: #f children: (val) cost: 1 nint: (if int? 1 0) nfp: (if int? 0 1) emit: (if int? (make-move-int reg val) (make-move-fp reg val))) (define-pattern constant ((node node read-constant?) (value (read-constant-value node))) cost: 1 emit: (if (integer? value) (make-load-constant-int dst value) (make-load-constant-fp dst value))) (define-pattern read-array ((node node read-array?) (int? (eq? 'int (expression-node-type node))) (array (read-array-array node)) (index (read-array-index node))) children: (array index) cost: 1 nint: 2 nfp: (if int? 0 1) emit: ((if int? make-move-int make-move-fp) dst (make-ea base: array index: index stride: 8))) (define-pattern read-array-constant-index ((node node read-array?) (int? (eq? 'int (expression-node-type node))) (array (read-array-array node)) (index (read-array-index node) (read-constant? index)) (index (read-constant-value index))) children: (array) cost: 1 nint: 2 nfp: (if int? 0 1) emit: ((if int? make-move-int make-move-fp) dst (make-ea base: array offset: (* 8 index)))) (define-pattern assign-array ((node node assign-array?) (array (assign-array-array node)) (index (assign-array-index node)) (value (assign-array-value node)) (int? (eq? 'int (expression-node-type value)))) dst: #f children: (array index value) cost: 3 nint: (if int? 3 2) nfp: (if int? 0 1) emit: ((if int? make-move-int make-move-fp) (make-ea base: array index: index stride: 8) value)) (define-pattern assign-array-constant-index ((node node assign-array?) (array (assign-array-array node)) (index (assign-array-index node) read-constant?) (index (read-constant-value index)) (value (assign-array-value node)) (int? (eq? 'int (expression-node-type value)))) dst: #f children: (array value) cost: 3 nint: (if int? 3 2) nfp: (if int? 0 1) emit: ((if int? make-move-int make-move-fp) (make-ea base: array offset: (* index 8)) value)) (define-pattern add ((node node +-expression?) (int? (eq? 'int (expression-node-type node))) (x (binary-expression-x node)) (y (binary-expression-y node))) children: (x y) cost: (if int? 1 2) nint: (if int? 2 0) nfp: (if int? 0 2) emit-form: (if int? make-add-int make-add-fp)) (define-pattern add-constant ((node node +-expression?) (type (expression-node-type node) (eq? 'int type)) (x (binary-expression-x node) read-constant?) (value (read-constant-value x)) (y (binary-expression-y node))) children: (y) cost: 1 nint: 1 emit: (make-add-int dst value y)) (define-pattern add-constant-mul-constant ((node node +-expression?) (type (expression-node-type node) (eq? 'int type)) (x (binary-expression-x node) read-constant?) (value (read-constant-value x)) (mul (binary-expression-y node) *-expression?) (multiplier (binary-expression-x mul) read-constant?) (multiplier (read-constant-value multiplier) (memq multiplier '(1 2 4 8))) (y (binary-expression-y mul))) children: (y) cost: 2 nint: 1 emit: (make-lea dst (make-ea index: y stride: multiplier offset: value))) (define-pattern mul ((node node *-expression?) (int? (eq? 'int (expression-node-type node))) (x (binary-expression-x node)) (y (binary-expression-y node))) children: (x y) cost: (if int? 3 6) nint: (if int? 2 0) nfp: (if int? 0 2) emit-form: (if int? make-mul-int make-mul-fp)) (define-pattern mul-constant-int ((node node *-expression?) (type (expression-node-type node) (eq? 'int type)) (x (binary-expression-x node) read-constant?) (value (read-constant-value x)) (y (binary-expression-y node))) children: (y) cost: 3 nint: 2 emit: (cond ((= value 2) ;; see AMD optimisation guide for all values (list (make-move-int dst y) (make-add-int dst dst dst))) ((memq value '(1 2 4 8)) (make-lea dst (make-ea index: y stride: value))) (#t (make-mul-int dst value y))))
false
d038ba4be0f016fa142da87eee3228a57b3c4a8c
b85062eadba845bd0e607f92f3d6f58707c3030c
/src/repl.ss
8dc11d54959261e5c4a214532d2879147c7ac8ab
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
guenchi/swish-win
a0bc94a0121bc3c69fe2ac79d312b7c953040f68
bab98dfa757dfd851d8cf5176fb3e88115f311f4
refs/heads/master
2020-06-04T17:45:00.654922
2018-04-02T18:40:46
2018-04-02T18:40:46
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
102
ss
repl.ss
(compile-imported-libraries #t) (include "swish/imports.ss") (include "init.ss") (hook-console-input)
false
bf7375b2781ea6b3b3b13299173b42763563f806
e1fc47ba76cfc1881a5d096dc3d59ffe10d07be6
/ch2/2.37.scm
2260c5b67e6865072ff6b7bb529381d1cbcc07e7
[]
no_license
lythesia/sicp-sol
e30918e1ebd799e479bae7e2a9bd4b4ed32ac075
169394cf3c3996d1865242a2a2773682f6f00a14
refs/heads/master
2021-01-18T14:31:34.469130
2019-10-08T03:34:36
2019-10-08T03:34:36
27,224,763
2
0
null
null
null
null
UTF-8
Scheme
false
false
576
scm
2.37.scm
(load "2.36.scm") (define (dot-product v w) (accumulate + 0 (map * v w)) ) (define (matrix-*-vector m v) (map (lambda (row) (dot-product row v)) m ) ) (define (transpose m) (accumulate-n cons '() m) ) (define (matrix-*-matrix m n) (let ((cols (transpose n))) (map (lambda (row) (matrix-*-vector cols row)) m ) ) ) ; test ; (define m (list '(1 2 3 4) '(4 5 6 6) '(6 7 8 9))) ; (define v '(1 2 3 4)) ; (display (matrix-*-vector m v))(newline) ; (display (transpose m))(newline) ; (display (matrix-*-matrix m (transpose m)))(newline)
false
0d8248b734d41f22cecb94d5daf8cda44f82e45c
eef5f68873f7d5658c7c500846ce7752a6f45f69
/test/structure-treap.scm
b780064e83566e56df698847d693142a674bc4f6
[ "MIT" ]
permissive
alvatar/spheres
c0601a157ddce270c06b7b58473b20b7417a08d9
568836f234a469ef70c69f4a2d9b56d41c3fc5bd
refs/heads/master
2021-06-01T15:59:32.277602
2021-03-18T21:21:43
2021-03-18T21:21:43
25,094,121
13
3
null
null
null
null
UTF-8
Scheme
false
false
7,810
scm
structure-treap.scm
; Verifying the treaps package ; ; IMPORT ; appropriate prelude: myenv.scm, myenv-bigloo.scm, myenv-scm.scm ; depending on your system ; catch-error.scm -- for procedure, for-syntax ; treap.scm ; ; $Id: vtreap.scm,v 1.2 2002/11/14 04:45:26 oleg Exp oleg $ (declare ; Compilation optimization options (block) (standard-bindings) (fixnum) ) ; Check out that the 'form' has failed indeed ; (as it was supposed to) (define-macro (must-have-failed form) `(assert (failed? (##catch-all (lambda (sig args) (error "catching " sig args)) (lambda () ,form))))) (cerr nl nl "--> Sorting of a set of numbers via a treap" nl) (let ((min-key -1) (max-key 10) (treap (make-treap (lambda (x y) (- x y)))) ; a hard-wired association between a key and a value (compute-assoc (lambda (key) (cons key (++ key))))) (cerr "\tloading a sequence [" min-key "," max-key "] in ascending order" nl) (assert (treap 'empty?)) (assert (zero? (treap 'size))) (assert (zero? (treap 'depth))) (do ((i min-key (++ i))) ((> i max-key)) (assert (not ((treap 'put!) i (cdr (compute-assoc i)))))) (treap 'debugprint) (cerr "\ttreap's depth is " (treap 'depth) nl) (assert (= (treap 'size) (++ (- max-key min-key)))) (assert (not (treap 'empty?))) (assert (equal? (treap 'get-min) (compute-assoc min-key))) (assert (equal? (treap 'get-max) (compute-assoc max-key))) (assert (equal? (treap 'get-min) ((treap 'get) min-key))) (assert (equal? (treap 'get-max) ((treap 'get) max-key))) (assert (equal? ((treap 'get) (++ min-key)) (compute-assoc (++ min-key)))) (assert (equal? ((treap 'get) (++ min-key) #f) (compute-assoc (++ min-key)))) ; check looking up of non-existing keys (assert (not ((treap 'get) (-- min-key) #f))) (assert (= 1 ((treap 'get) (++ max-key) (lambda () 1)))) (must-have-failed ((treap 'get) (-- min-key))) (cerr "\n\tclearing the treap and reloading the same seq in descending order" nl) (treap 'clear!) (assert (treap 'empty?)) (assert (zero? (treap 'size))) (assert (zero? (treap 'depth))) (must-have-failed ((treap 'get) min-key)) (must-have-failed (treap 'get-min)) (must-have-failed (treap 'get-max)) (do ((i max-key (-- i))) ((< i min-key)) (assert (not ((treap 'put!) i (cdr (compute-assoc i)))))) (treap 'debugprint) (cerr "\ttreap's depth is " (treap 'depth) nl) (assert (equal? (treap 'get-min) (compute-assoc min-key))) (assert (equal? (treap 'delete-min!) (compute-assoc min-key))) (assert (not ((treap 'get) min-key #f))) (assert (equal? (treap 'get-min) (compute-assoc (++ min-key)))) (assert (equal? (treap 'get-max) ((treap 'get) max-key))) (assert (equal? (treap 'delete-max!) (compute-assoc max-key))) (assert (not ((treap 'get) max-key #f))) (assert (equal? (treap 'get-max) ((treap 'get) (-- max-key)))) (assert (= (treap 'size) (+ -2 (++ (- max-key min-key))))) (cerr "\n\tremove the remaining treap elements one by one, from min to max" nl) (do ((i (++ min-key) (++ i))) ((> i (-- max-key))) (assert (equal? ((treap 'get) i #f) (compute-assoc i))) (assert (equal? (treap 'delete-min!) (compute-assoc i))) (assert (not ((treap 'get) i #f))) ) (assert (treap 'empty?)) (assert (zero? (treap 'size))) (assert (zero? (treap 'depth))) (must-have-failed ((treap 'for-each-ascending) (lambda (association) #t))) (must-have-failed ((treap 'for-each-descending) (lambda (association) #t))) (cerr "\n\tloading the treap again in a \"random\" order" nl) (do ((i min-key) (j max-key) (direction #t (not direction))) ((< j i)) (cond (direction (assert (not ((treap 'put!) i (cdr (compute-assoc i))))) (++! i)) (else (assert (not ((treap 'put!) j (cdr (compute-assoc j))))) (--! j)) )) (let* ((a-key (quotient (+ min-key max-key) 2)) (old-assoc (compute-assoc a-key)) (new-assoc (cons a-key #\a))) (cerr "\n\tchecking putting and deleting of an assoc with key " a-key nl) (assert (equal? ((treap 'get) a-key) old-assoc)) (assert (equal? ((treap 'put!) a-key (cdr new-assoc)) old-assoc)) (assert (equal? ((treap 'get) a-key) new-assoc)) (assert (equal? ((treap 'delete!) a-key) new-assoc)) (assert (not ((treap 'delete!) a-key #f))) (assert (equal? ((treap 'put!) a-key (cdr old-assoc)) #f)) (assert (equal? ((treap 'put!) a-key (cdr old-assoc)) old-assoc)) (assert (equal? ((treap 'get) a-key) old-assoc)) ) (assert (= (treap 'size) (++ (- max-key min-key)))) (cerr "\ttreap's depth is " (treap 'depth) nl) (assert (not (treap 'empty?))) (cerr "\tchecking traversing in the ascending order" nl) (let ((expected-key min-key)) ((treap 'for-each-ascending) (lambda (association) (assert (equal? association (compute-assoc expected-key))) (++! expected-key))) (assert (= expected-key (++ max-key)))) (cerr "\tchecking traversing in the descending order" nl) (let ((expected-key max-key)) ((treap 'for-each-descending) (lambda (association) (assert (equal? association (compute-assoc expected-key))) (--! expected-key))) (assert (= expected-key (-- min-key)))) ) (cerr nl "Done" nl) (cerr nl nl "--> Build a treap to map from digit strings to the numbers " "they represent" nl) (let ((lo 1) (hi 150) (treap (make-treap (lambda (x y) (if (string<? x y) -1 (if (string>? x y) 1 0))))) (min-key #f) ; to be computed later (max-key #f) ) (assert (treap 'empty?)) (assert (zero? (treap 'size))) (assert (zero? (treap 'depth))) (cerr "\tloading a sequence [" lo "," hi "] in an ascending number order" nl) (do ((i lo (++ i))) ((> i hi)) (let ((key (number->string i))) (assert (not ((treap 'put!) key i))) (cond ((not min-key) (set! min-key key) (set! max-key key)) ((string<? key min-key) (set! min-key key)) ((string>? key max-key) (set! max-key key)) ))) (cerr "\ttreap's depth is " (treap 'depth) nl) (assert (= (treap 'size) (++ (- hi lo)))) (assert (not (treap 'empty?))) (assert (equal? (treap 'get-min) (cons min-key (string->number min-key)))) (assert (equal? (treap 'get-max) (cons max-key (string->number max-key)))) (assert (equal? (treap 'get-min) ((treap 'get) min-key))) (assert (equal? (treap 'get-max) ((treap 'get) max-key))) (let* ((a-key-val (quotient (+ lo hi) 2)) (a-key (number->string a-key-val)) (old-assoc (cons a-key a-key-val)) (new-assoc (cons a-key #\a))) (cerr "\n\tchecking putting and deleting of an assoc with key " a-key nl) (assert (equal? ((treap 'get) a-key) old-assoc)) (assert (equal? ((treap 'put!) a-key (cdr new-assoc)) old-assoc)) (assert (equal? ((treap 'get) a-key) new-assoc)) (assert (equal? ((treap 'delete!) a-key) new-assoc)) (assert (not ((treap 'delete!) a-key #f))) (assert (equal? ((treap 'put!) a-key (cdr old-assoc)) #f)) (assert (equal? ((treap 'put!) a-key (cdr old-assoc)) old-assoc)) (assert (equal? ((treap 'get) a-key) old-assoc)) ) (assert (= (treap 'size) (++ (- hi lo)))) (let ((values-to-print 15) (printed 0)) (cerr "\n\tprinting out first " values-to-print " associations in the descending\n" "\torder of their string keys (but not the values themselves!)\n") ((treap 'for-each-descending) (lambda (association) (if (zero? printed) (assert (equal? association (cons max-key (string->number max-key))))) (if (< printed values-to-print) (cerr "\t\t" association nl) ) (++! printed))) (assert (= printed (treap 'size)))) ) (cerr nl "Done" nl) (cerr nl nl "All tests passed" nl)
false
62d6cf0b468d64a7a2a18ceece6417ab4b2d0403
92b8d8f6274941543cf41c19bc40d0a41be44fe6
/testsuite/command2.scm
d772935082dbf4ccc341771d0f0dcacaf1cbb957
[ "MIT" ]
permissive
spurious/kawa-mirror
02a869242ae6a4379a3298f10a7a8e610cf78529
6abc1995da0a01f724b823a64c846088059cd82a
refs/heads/master
2020-04-04T06:23:40.471010
2017-01-16T16:54:58
2017-01-16T16:54:58
51,633,398
6
0
null
null
null
null
UTF-8
Scheme
false
false
129
scm
command2.scm
;; Kawa-options: %F "a b" c (format #t "~w~%" (command-line)) ;; Output-pattern: [(]"java kawa.repl .*command2.scm" "a b" "c"[)]
false
5f5c949b216d6dcd50fe90b1a5578828213160b6
2b0dc0760baad4405f64b424345381f688173281
/compiler/src/test/scheme/includes/definea.scm
35f33ce0b57bd06bffe4fc630a2ca68ec0b7781c
[ "Apache-2.0" ]
permissive
abduld/llambda
f2e7daf0c9a302dafa29a2d4067bfae6d1ec8317
17e53a5ec15f2b09f2eb3304151af3dbbcfd7f32
refs/heads/master
2023-04-12T23:59:17.462698
2015-10-24T04:51:25
2015-10-24T04:51:25
45,697,748
0
0
NOASSERTION
2023-04-04T01:11:51
2015-11-06T17:50:04
Scala
UTF-8
Scheme
false
false
37
scm
definea.scm
(define a 1) (include "defineb.scm")
false
44caa0309a2190634012dd24ca406bda0ec20807
a5cff5beae635b13a1d67cb707856212fbbe32a5
/chapter3-self.scm
f9bcc1c3b741befc8914b9b6fe00a347d55c7aed
[]
no_license
abelard2008/plai
f6c1b2fa17d224579e8ec6e08d74e5f6fa80d5ed
b7de61a647a555f0355fc1d9617e80d6af27907d
refs/heads/master
2020-12-10T21:26:24.032181
2020-01-16T10:47:20
2020-01-16T10:47:20
233,715,673
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,692
scm
chapter3-self.scm
#lang plai (define-type WAE [num (n number?)] [add (lhs WAE?) (rhs WAE?)] [with (name symbol?) (named-expr WAE?) (body WAE?)] [id (name symbol?)]) (define (parse sexp) (cond [(number? sexp) (num sexp)] [(list? sexp) (case (first sexp) [(+) (add (parse (second sexp)) (parse (third sexp)))] [(with) (with (first (second sexp)) (parse (second (second sexp))) (parse (third sexp)))])] [(symbol? sexp) (id sexp)])) (test (parse '(with (x 5) (+ x x))) (with 'x (num 5) (add (id 'x) (id 'x)))) (define (subst i v sexp) (type-case WAE sexp [num (n) sexp] [add (lhs rhs) (add (subst i v lhs) (subst i v rhs))] [with (name named-sexp body) (if (symbol=? name i) (with name (subst i v named-sexp) body) (with name (subst i v named-sexp) (subst i v body)))] [id (name) (if (symbol=? name i) v sexp)])) (test (subst 'x (num 5) (add (id 'x) (id 'x))) (add (num 5) (num 5))) (define (calc sexp) (type-case WAE sexp [num (n) n] [add (lhs rhs) (+ (calc lhs) (calc rhs))] [with (name named-sexp body) (calc (subst name (num (calc named-sexp)) body))] [id (name) (error 'calc "free identifier")])) (test (calc (parse '(with (x 5) (+ x x)))) 10) (test (calc (parse '(with (x 5) (with (y 6) (+ x y))))) 11)
false
3dc1d9fc2359060c42b8ebb062a5ba849660fd38
669b06943e802449ed812bfafec9eec2c50647da
/deps/share/guile/site/2.2/chickadee/render/shader.scm
52dfc30b3d006fb5c968a1f5beff6c63ddf30103
[]
no_license
bananaoomarang/chickadee-game
f9dcdb8b2e2b3b1909d30af52c1e6a7c16b27194
8733941202243956252b19a1a3ceb35a84b61e56
refs/heads/master
2020-06-04T17:35:32.420313
2019-06-24T22:59:04
2019-06-24T22:59:04
192,126,835
1
1
null
null
null
null
UTF-8
Scheme
false
false
13,301
scm
shader.scm
;;; Chickadee Game Toolkit ;;; Copyright © 2016 David Thompson <[email protected]> ;;; ;;; Chickadee is free software: you can redistribute it and/or modify ;;; it under the terms of the GNU General Public License as published ;;; by the Free Software Foundation, either version 3 of the License, ;;; or (at your option) any later version. ;;; ;;; Chickadee 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, see ;;; <http://www.gnu.org/licenses/>. (define-module (chickadee render shader) #:use-module (ice-9 rdelim) #:use-module (ice-9 match) #:use-module (oop goops) #:use-module (system foreign) #:use-module (rnrs bytevectors) #:use-module (rnrs io ports) #:use-module (srfi srfi-1) #:use-module (srfi srfi-4) #:use-module (srfi srfi-9) #:use-module (srfi srfi-9 gnu) #:use-module (gl) #:use-module (chickadee math matrix) #:use-module (chickadee math vector) #:use-module (chickadee render color) #:use-module (chickadee render gl) #:use-module (chickadee render gpu) #:use-module (chickadee render texture) #:export (make-shader shader? null-shader load-shader strings->shader shader-uniform shader-uniforms shader-attributes uniform? uniform-name uniform-type uniform-value uniform-default-value set-uniform-value! attribute? attribute-name attribute-location attribute-type *shader-state*)) (define-record-type <shader> (%make-shader id attributes uniforms) shader? (id shader-id) (attributes shader-attributes) (uniforms shader-uniforms)) (define-record-type <uniform> (make-uniform name location type value setter) uniform? (name uniform-name) (location uniform-location) (type uniform-type) (value uniform-value %set-uniform-value!) (setter uniform-setter)) (define-record-type <attribute> (make-attribute name location type) attribute? (name attribute-name) (location attribute-location) (type attribute-type)) (define null-shader (%make-shader 0 (make-hash-table) (make-hash-table))) (define <<shader>> (class-of null-shader)) (define-method (gpu-finalize (shader <<shader>>)) (gl-delete-program (shader-id shader))) (define (apply-shader shader) (gl-use-program (shader-id shader))) (define *shader-state* (make-gpu-state apply-shader null-shader)) (define (shader-compiled? id) (let ((status (make-u32vector 1))) (gl-get-shaderiv id (version-2-0 compile-status) (bytevector->pointer status)) (= (u32vector-ref status 0) 1))) (define (shader-linked? id) (let ((status (make-u32vector 1))) (gl-get-programiv id (version-2-0 link-status) (bytevector->pointer status)) (= (u32vector-ref status 0) 1))) (define (info-log length-proc log-proc id) (let ((log-length-bv (make-u32vector 1))) (length-proc id (version-2-0 info-log-length) (bytevector->pointer log-length-bv)) (u32vector-ref log-length-bv 0) ;; Add one byte to account for the null string terminator. (let* ((log-length (u32vector-ref log-length-bv 0)) (log (make-u8vector (1+ log-length)))) (log-proc id log-length %null-pointer (bytevector->pointer log)) (utf8->string log)))) (define (compilation-error id) (info-log gl-get-shaderiv gl-get-shader-info-log id)) (define (linking-error id) (info-log gl-get-programiv gl-get-program-info-log id)) (define (uniform-count id) (let ((bv (make-u32vector 1))) (gl-get-programiv id (arb-shader-objects active-uniforms) (bytevector->pointer bv)) (u32vector-ref bv 0))) (define (utf8->string* bv length) (let ((bv* (make-bytevector length))) (bytevector-copy! bv 0 bv* 0 length) (utf8->string bv*))) (define (set-boolean-uniform! location bool) (gl-uniform1i location (if bool 1 0))) (define (set-integer-uniform! location n) (gl-uniform1i location n)) (define (set-unsigned-integer-uniform! location n) (gl-uniform1ui location n)) (define (set-float-uniform! location n) (gl-uniform1f location n)) (define (set-float-vector2-uniform! location v) (gl-uniform2fv location 1 (vec2->pointer v))) (define (set-float-vector3-uniform! location v) (gl-uniform3fv location 1 (vec3->pointer v))) (define (set-float-vector4-uniform! location v) (if (color? v) (gl-uniform4f location (color-r v) (color-g v) (color-b v) (color-a v)) #f ;; (gl-uniform4f location (vx v) (vy v) (vz v) (vw v)) )) ;; (define (set-integer-vector2-uniform! location v) ;; (gl-uniform2i location (vx v) (vy v))) ;; (define (set-integer-vector3-uniform! location v) ;; (gl-uniform3i location (vx v) (vy v) (vz v))) ;; (define (set-integer-vector4-uniform! location v) ;; (gl-uniform4i location (vx v) (vy v) (vz v) (vw v))) (define (set-float-matrix4-uniform! location m) (gl-uniform-matrix4fv location 1 #f ((@@ (chickadee math matrix) matrix4-ptr) m))) (define (set-sampler-2d-uniform! location texture-unit) (gl-uniform1i location texture-unit)) (define (gl-type->symbol type) (cond ((= type (version-2-0 bool)) 'bool) ((= type (data-type int)) 'int) ((= type (data-type unsigned-int)) 'unsigned-int) ((= type (data-type float)) 'float) ((= type (version-2-0 float-vec2)) 'float-vec2) ((= type (version-2-0 float-vec3)) 'float-vec3) ((= type (version-2-0 float-vec4)) 'float-vec4) ;; ((= type (version-2-0 int-vec2)) 'int-vec2) ;; ((= type (version-2-0 int-vec3)) 'int-vec3) ;; ((= type (version-2-0 int-vec4)) 'int-vec4) ((= type (version-2-0 float-mat4)) 'mat4) ((= type (version-2-0 sampler-2d)) 'sampler-2d) (else (error "unsupported OpenGL type" type)))) (define %default-mat4 (make-identity-matrix4)) (define (default-uniform-value type) (match type ('bool #f) ('int 0) ('unsigned-int 0) ('float 0.0) ('float-vec2 #v(0.0 0.0)) ('float-vec3 #v(0.0 0.0 0.0)) ('float-vec4 (make-color 0.0 0.0 0.0 0.0)) ;; ('int-vec2 (vector2 0 0)) ;; ('int-vec3 (vector3 0 0 0)) ;; ('int-vec4 (vector4 0 0 0 0)) ('mat4 %default-mat4))) (define (uniform-setter-for-type type) ;; TODO: Handle more data types, notably matrices. (match type ('bool set-boolean-uniform!) ('int set-integer-uniform!) ('unsigned-int set-unsigned-integer-uniform!) ('float set-float-uniform!) ('float-vec2 set-float-vector2-uniform!) ('float-vec3 set-float-vector3-uniform!) ('float-vec4 set-float-vector4-uniform!) ;; ('int-vec2 set-integer-vector2-uniform!) ;; ('int-vec3 set-integer-vector3-uniform!) ;; ('int-vec4 set-integer-vector4-uniform!) ('mat4 set-float-matrix4-uniform!) ('sampler-2d set-sampler-2d-uniform!))) (define (extract-uniforms id) (let ((total (uniform-count id)) (table (make-hash-table))) (let loop ((i 0) (texture-unit 0)) (unless (= i total) (let ((length-bv (make-u32vector 1)) (size-bv (make-u32vector 1)) (type-bv (make-u32vector 1)) (name-bv (make-bytevector 255))) (gl-get-active-uniform id i (bytevector-length name-bv) (bytevector->pointer length-bv) (bytevector->pointer size-bv) (bytevector->pointer type-bv) (bytevector->pointer name-bv)) (let* ((length (u32vector-ref length-bv 0)) (name (utf8->string* name-bv length)) (location (gl-get-uniform-location id name)) (size (u32vector-ref size-bv 0)) (type (gl-type->symbol (u32vector-ref type-bv 0))) (sampler? (eq? type 'sampler-2d)) (default (if sampler? texture-unit (default-uniform-value type))) (setter (uniform-setter-for-type type))) ;; TODO: Handle uniform arrays. (unless (= size 1) (error "unsupported uniform size" name size)) (hash-set! table name (make-uniform name location type default setter)) (loop (1+ i) (if sampler? (1+ texture-unit) texture-unit)))))) table)) (define (attribute-count id) (let ((bv (make-u32vector 1))) (gl-get-programiv id (arb-shader-objects active-attributes) (bytevector->pointer bv)) (u32vector-ref bv 0))) (define (extract-attributes id) (let ((total (attribute-count id)) (table (make-hash-table))) (let loop ((i 0)) (unless (= i total) (let ((length-bv (make-u32vector 1)) (size-bv (make-u32vector 1)) (type-bv (make-u32vector 1)) (name-bv (make-bytevector 255))) (gl-get-active-attrib id i (bytevector-length name-bv) (bytevector->pointer length-bv) (bytevector->pointer size-bv) (bytevector->pointer type-bv) (bytevector->pointer name-bv)) (let* ((length (u32vector-ref length-bv 0)) (name (utf8->string* name-bv length)) (size (u32vector-ref size-bv 0)) (type (gl-type->symbol (u32vector-ref type-bv 0))) (location (gl-get-attrib-location id name))) (unless (= size 1) (error "unsupported attribute size" name size)) (hash-set! table name (make-attribute name location type)))) (loop (1+ i)))) table)) (define (make-shader vertex-port fragment-port) "Read GLSL source from VERTEX-PORT and FRAGMENT-PORT and compile them into a GPU shader program." (define (make-shader-stage type port) (let ((id (gl-create-shader type)) (source (get-bytevector-all port))) (gl-shader-source id 1 (bytevector->pointer (u64vector (pointer-address (bytevector->pointer source)))) (bytevector->pointer (u32vector (bytevector-length source)))) (gl-compile-shader id) (unless (shader-compiled? id) (let ((error-log (compilation-error id))) (gl-delete-shader id) ; clean up GPU resource. (error "failed to compile shader" error-log))) id)) (let ((vertex-id (make-shader-stage (version-2-0 vertex-shader) vertex-port)) (fragment-id (make-shader-stage (version-2-0 fragment-shader) fragment-port)) (id (gl-create-program))) (gl-attach-shader id vertex-id) (gl-attach-shader id fragment-id) (gl-link-program id) (unless (shader-linked? id) (let ((error-log (linking-error id))) (gl-delete-program id) (error "failed to link shader" error-log))) (gl-delete-shader vertex-id) (gl-delete-shader fragment-id) (gpu-guard (%make-shader id (extract-attributes id) (extract-uniforms id))))) (define (load-shader vertex-source-file fragment-source-file) "Compile the GLSL source code within VERTEX-SOURCE-FILE and FRAGMENT-SOURCE-FILE into a GPU shader program." (call-with-input-file vertex-source-file (lambda (vertex-port) (call-with-input-file fragment-source-file (lambda (fragment-port) (make-shader vertex-port fragment-port)))))) (define (strings->shader vertex-source fragment-source) "Compile VERTEX-SOURCE, the GLSL code for the vertex shader, and FRAGMENT-SOURCE, the GLSL code for the fragment shader, into a GPU shader program." (call-with-input-string vertex-source (lambda (vertex-port) (call-with-input-string fragment-source (lambda (fragment-port) (make-shader vertex-port fragment-port)))))) (define (shader-uniform shader name) "Return the metadata for the uniform NAME in SHADER." (let ((uniform (hash-ref (shader-uniforms shader) name))) (or uniform (error "no such uniform" name)))) (define (set-uniform-value! uniform x) "Change the value of UNIFORM to X. This procedure assumes that the shader where UNIFORM is defined is currently bound in the OpenGL context. The behavior of this procedure under any other circumstance is undefined." ((uniform-setter uniform) (uniform-location uniform) x) (%set-uniform-value! uniform x)) (define (uniform-default-value uniform) "Return the default value of UNIFORM." (default-uniform-value (uniform-type uniform)))
false
ab7084b6abd28ac39736574849832c8c5fdd6b12
7666204be35fcbc664e29fd0742a18841a7b601d
/code/4-09.scm
3519017d9e13615697e182e492c07876fae84e7a
[]
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
1,046
scm
4-09.scm
#| (define i 0) (while (< i 10) (display i) (set! i (+ i 1))) |# (include "4.1.scm") (define (while? exp) (tagged-list? exp 'while)) (define (while-condition exp) (cadr exp)) (define (while-body exp) (cddr exp)) (define (eval-while exp env) (let ((condition (while-condition exp)) (body (sequence->exp (while-body exp)))) (define (loop) (if (true? (eval condition env)) (begin (eval body env) (loop)))) (loop))) (define (while->combination exp) ; (begin (define (loop) (if condition (begin body (loop)))) (loop)) (sequence->exp (list (list 'define (list 'loop) (make-if (while-condition exp) (sequence->exp (append (while-body exp) (list 'loop))) 'end-of-while)) (list 'loop)))) ; eval: ; ((while? exp) (eval-while exp env)) ; OR ; ((while? exp) (eval (while-condition exp) env))
false
9807b9c4b889e84812640dcc1241a160313079d3
b7f6929575ae60469e07b132f8bc843922e16abd
/gambit/macros.scm
9190ff992a7f97d3307743e16c40b6071632b065
[ "MIT" ]
permissive
shima3/sch-script
2136048cdcb0e9ec42b228819447a3a9859a73b3
fa1e8ec5ee161a8b5702af68cc3d7ecd5376378b
refs/heads/master
2021-01-23T06:20:59.407358
2020-08-04T15:43:18
2020-08-04T15:43:18
86,357,889
0
0
null
null
null
null
UTF-8
Scheme
false
false
276
scm
macros.scm
(define-macro (define-record Name . Fields) (cons 'define-record-type (cons Name (cons (cons (string->symbol (string-append "make-" (symbol->string Name))) Fields) (cons (string->symbol (string-append (symbol->string Name) "?")) (map list Fields))))) )
false
dabf30f5226b486dd64638ec30b70013e7daf049
9345867d5616f00e9add07095db49e97fcc1cf02
/vim/xire/compiler.scm
432a8b9ba346082c78ae9ba31fe35436872936b8
[ "MIT" ]
permissive
kana/vim-xire
91eb2cf417d68b9e598f992c6b5442f72a928594
e4e97d8926fcdf1488d3e59a85a4af0253a5de01
refs/heads/master
2016-09-06T06:17:05.007579
2011-12-07T12:46:17
2011-12-07T12:46:17
588,299
1
0
null
null
null
null
UTF-8
Scheme
false
false
4,052
scm
compiler.scm
(define-module vim.xire.compiler (export ; Public API transform-value xire-translate ; Semi-public API for advanced usage. xire-compile xire-compile-expr xire-compile-forms ; Not public, but exported to test. ; Not public, but exported to avoid some problems. match ; See [MATCHQ]. )) (select-module vim.xire.compiler) (use gauche.parameter) (use text.tree) (use util.list) (use util.match) (use vim.xire.compiler.pass-1) (use vim.xire.compiler.pass-final) (use vim.xire.iform) (use vim.xire.util) ;;; Compiler ;;; ======== ;; Translate Xire script into Vim script. Xire script is read from INPUT-PORT ;; and resulting Vim script is written into OUTPUT-PORT. (define (xire-translate input-port output-port :key (env (copy-env)) (scheme-env (let1 m (make-module #f) (eval '(use vim.xire) m) m))) (define compiled-vim-script-tree (list)) (define (finish) (write-tree (reverse compiled-vim-script-tree) output-port)) (define ctx (make-root-ctx)) (define (optimize iform) ; Currently there is no optimization. ; More passes will be added in future. iform) (parameterize ([xire-env env]) (let loop () (match (read input-port) [(? eof-object?) (finish)] [(and ((or 'defexpr 'defmacro 'defstmt) . _) form) (eval form scheme-env) (loop)] [('scheme . scheme-exprs) (eval `(begin ,@scheme-exprs) scheme-env) (loop)] [form (push! compiled-vim-script-tree (pass-final (optimize (xire-compile form ctx)))) (loop)])))) ;; Compile a Xire script FORM then return a resulting Vim script in IForm. (define (xire-compile form ctx) (pass-1 form ctx)) ;; Compile a Xire script EXPR then return a resulting Vim script in IForm. ;; This is an abbreviated form of xire-compile for typical use. (define (xire-compile-expr expr ctx) (xire-compile expr (if (expr-ctx? ctx) ctx (make-expr-ctx ctx)))) ;; Compile a list of Xire script FORMS then return a resulting Vim script in ;; IForm. This is an abbreviated form of xire-compile for typical use. (define (xire-compile-forms forms ctx) (map (cut xire-compile <> ctx) forms)) (define (transform-value form-or-forms manyp type upper-ctx) (define (fail detail) (errorf "Invalid usage (~a): (transform-value ~s ~s ~s ~s)" detail form-or-forms manyp type upper-ctx)) (define (transform-form form) (cond [(eq? type 'expr) (xire-compile-expr form upper-ctx)] [(or (eq? type 'form) (eq? type 'qexpr) (eq? type 'qstmt)) form] [(eq? type 'qsym) (when (not (symbol? form)) (fail "invalid form for this type")) form] [(eq? type 'stmt) (xire-compile form (if (stmt-ctx? upper-ctx) upper-ctx (make-stmt-ctx upper-ctx)))] [(eq? type 'sym) (when (not (symbol? form)) (fail "invalid form for this type")) (xire-compile-expr form upper-ctx)] [else (fail "invalid type")])) (if manyp (map transform-form form-or-forms) (transform-form form-or-forms))) ;;; Magic ;;; ===== ;; Code which defines high-level Xire macro has to bind MATCH to the macro ;; defined in util.match, because the syntax to define high-level Xire macro ;; is implemented with DEFINE-MACRO (built-in) and MATCH (util.match). This ;; restriction is a bit annoying for development. ;; ;; [MATCHQ] NB: To avoid writing extra (use util.match) in user code, ;; MATCH (vim.xire.compiler) is bound to the same macro as MATCH (util.match), ;; and MATCH (vim.xire.compiler) is exported. (define match match) ;;; __END__
false
ae9025a85429e55cfdcca131def4d56b1204dc6a
a0c856484b0cafd1d7c428fb271a820dd19be577
/lab6/lab6.scm
2c88f5bcafe274cae17c29b02ab58416efe206d3
[]
no_license
ctreatma/scheme_exercises
b13ba7743dfd28af894eb54429297bad67c14ffa
94b4e8886b2500a7b645e6dc795c0d239bf2a3bb
refs/heads/master
2020-05-19T07:30:58.538798
2012-12-03T23:12:22
2012-12-03T23:12:22
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,870
scm
lab6.scm
;Charles Treatman ;Lab 6 (require (lib "compat.ss")) (require (lib "eopl.ss" "eopl")) ;Exercise 2 (define list-of-ex-2? (lambda (lat) (andmap ex-2? lat))) (define-datatype ex-2 ex-2? (lit-exp (datum number?)) (var-exp (id symbol?)) (lambda-exp (ids list?) (body ex-2?)) (app-exp (rator ex-2?) (rands list-of-ex-2?)) (if-exp (test-exp ex-2?) (then-exp ex-2?) (else-exp ex-2?))) (define parse-2 (lambda (datum) (cond ((number? datum) (lit-exp datum)) ((symbol? datum) (var-exp datum)) ((pair? datum) (if (eqv? (car datum) 'if) (if-exp (parse-2 (cadr datum)) (parse-2 (caddr datum)) (parse-2 (cadddr datum))) (if (eqv? (car datum) 'lambda) (lambda-exp (cadr datum) (parse-2 (caddr datum))) (app-exp (parse-2 (car datum)) (map parse-2 (cdr datum)))))) (else (error 'parse-2 "Invalid concrete syntax ~s" datum))))) (define unparse-2 (lambda (exp) (cases ex-2 exp (lit-exp (datum) datum) (var-exp (id) id) (lambda-exp (ids body) (list 'lambda ids (unparse-2 body))) (app-exp (rator rands) (cons (unparse-2 rator) (map unparse-2 rands))) (if-exp (test-exp then-exp else-exp) (list 'if (unparse-2 test-exp) (unparse-2 then-exp) (unparse-2 else-exp))))))
false
fc0d8e05920927be6c212784b5595950400859e0
2ff2fa5117000f0a5d0a755481e755133978c61c
/scenes/poly.scm
c1ddc24449c86cdf7b26c1de566d6b55b48fecab
[]
no_license
ChrisBlom/dendrite
d9d2665b4d0ec933ff7b48a202aa83781974c621
a40ba97061020f04452da7ef640e2d81f00b9a55
refs/heads/master
2022-07-19T00:14:34.093545
2022-07-02T18:15:23
2022-07-02T18:17:00
180,216,617
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,574
scm
poly.scm
(use (prefix chipmunk cp:) ringbuffer clojurian-syntax srfi-42 gl-math) (define wsz 5.) (define (circle-ring n) (let ([b (list->ringbuffer (list-ec (:range i 0 n) (let ([angle (* i (/ n) pi 2)]) (cons (* 2 (sin angle)) (* 2 (cos angle))))))]) (list-ec (:range j 0 n) `(,(ringbuffer-get b j) ,(ringbuffer-get b (+ 1 j)))))) (define the-damping 0.5) (comment (load-scene "1")) (define outer-count 32) (define inner-count 16) (define dbg #f) (define (init-scene scene-node space) (define stiffness 50.) ;; walls (cp:space-add-shapes space (doto (fixed-line-segment space (cp:v (- wsz) (- wsz)) (cp:v (- wsz) wsz) radius: 0.4) (cp:shape-set-elasticity 0.95) (cp:shape-set-friction 0.1)) (doto (fixed-line-segment space (cp:v (- wsz) wsz) (cp:v wsz wsz) radius: 0.4) (cp:shape-set-elasticity 0.95) (cp:shape-set-friction 0.1)) (doto (fixed-line-segment space (cp:v wsz wsz) (cp:v wsz (- wsz)) radius: 0.4) (cp:shape-set-elasticity 0.95) (cp:shape-set-friction 0.1)) (doto (fixed-line-segment space (cp:v wsz (- wsz)) (cp:v (- wsz) (- wsz)) radius: 0.4) (cp:shape-set-elasticity 0.95) (cp:shape-set-friction 0.1))) (define edges-outer (list-ec (:list x (circle-ring outer-count)) (let* ([start (first x)] [end (second x)] [start-pos (cp:v (car start) (cdr start))] [end-pos (cp:v (car end) (cdr end))] [center-pos (cp:vlerp start-pos end-pos 0.5)] [mass 0.3] [radius 0.2] [body-center (cp:body-new (cp:moment-for-segment mass start-pos end-pos radius) mass)] [shape (cp:circle-shape-new body-center radius cp:v0)]) (set! (cp:body-position body-center) center-pos) (cp:space-add-body space body-center) (cp:space-add-shape space shape) (let* ([n (new-node scene-node #:render (lambda (node projection-matrix view-matrix ctx-matrix) ((*render-circle-shape*) node projection-matrix view-matrix shape)) #:body body-center #:shape shape #:color (vector 1 0 0))]) n)))) ;; (define a ;; (let ([r (list->ringbuffer edges-outer)]) ;; (list-ec (:range j 0 (length edges-outer)) ;; (let ([a (ringbuffer-get r j)] ;; [b (ringbuffer-get r (+ 1 j))]) ;; (add-line a b) ;; )))) ;; -1 1 1 1 ;; ;; ;; -1 -1 1 -1 (let* ([mass 200.0] [radius 0.05] [v (list (cp:v -4 0.25) (cp:v 4 0.25) (cp:v 4 -0.25) (cp:v -4 -0.25))] [body (cp:body-new mass (cp:moment-for-polygon mass v cp:v0 radius))] [shape (cp:create-polygon-shape body v cp:transform-identity radius)]) (set! (cp:shape-elasticity shape) 0.95) (set! (cp:shape-friction shape) 0.2) (cp:space-add-body space body) (cp:space-add-shape space shape) (new-node scene-node #:render (lambda (node projection-matrix view-matrix ctx-matrix) ((*render-poly*) node projection-matrix view-matrix ctx-matrix)) #:render-init (lambda (node) (let ([mesh (poly-mesh v)]) (mesh-make-vao! mesh `((position . ,(gl:get-attrib-location (cell-get program-poly) "position")) (color . ,(gl:get-attrib-location (cell-get program-poly) "color")))) (node-mesh-set! node mesh))) #:body body #:shape shape)) (list "poly" scene-node space)) (comment ; (cp:space-constraints space) ) (cp:varray (cp:v -1 1) (cp:v 1 1) (cp:v 1 -1) (cp:v -1 -1))
false
aaf9c3c85b7c7024428b02a8fd23620a1b398f6c
ab2b756cdeb5aa94b8586eeb8dd5948b7f0bba27
/src/lisp/tests/eqs_test.scm
68e835a047b60122bf7c219ad31d8a7d7069def2
[]
no_license
stjordanis/chalang
48ff69d8bc31da1696eae043e66c628f41035b5a
a728e6bb9a60ac6eca189ee7d6873a891825fa9a
refs/heads/master
2021-07-31T22:26:45.299432
2021-03-09T13:06:56
2021-03-09T13:06:56
142,876,387
0
0
null
2018-07-30T13:03:00
2018-07-30T13:03:00
null
UTF-8
Scheme
false
false
146
scm
eqs_test.scm
(import (core/eqs.scm)) ; compile time (macro A () (= 5 5)) (A) (macro B () (= () ())) (B) ; run time (= 6 6) (= nil nil) and and and %0
false
13510ea4bec33db2a615da929639d31afa2b918a
a8e69b82efa3125947b3af219d8f14335e52d057
/combined-dynamic-ordering-with-application-and-lookup-optimizations-ml-infer-evalo.scm
f45b1207058e5042916b435031ca4eeac5a160e7
[ "MIT" ]
permissive
ArunGant8/n-grams-for-synthesis
ad3f14bb082c1220fcea5cfb69029953a2501508
b53b071e53445337d3fe20db0249363aeb9f3e51
refs/heads/master
2023-04-06T05:51:47.903781
2020-05-26T17:09:14
2020-05-26T17:09:14
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
488
scm
combined-dynamic-ordering-with-application-and-lookup-optimizations-ml-infer-evalo.scm
(define *output-table-file-name* "tmp/combined-dynamic-ordering-with-application-and-lookup-optimizations-ml-infer-evalo-table.scm") (define allow-incomplete-search? #f) (define lookup-optimization? #t) (load "mk-vicare.scm") (load "mk.scm") (load "test-check.scm") (load "combined-app-optimiztion-ml-infer-evalo.scm") (load "combined-construct-ordering-ml-infer-evalo.scm") (load "combined-simplified-dynamic-ml-infer-evalo.scm") (load "combined-simplified-tests-ml-infer-evalo.scm")
false
bb88655441a753e711dad372f7f014d591149e27
c95b424d826780d088a1e797db26717c8b335669
/view.sch
79b8201bfd75093a6d2fc769ef9eda5edd8e052c
[]
no_license
kdltr/ezd
c6bb38ef25c22030f09dc4be9bc2bdec2a575242
2e372a159903d674d29b5b3f32e560d35fcac397
refs/heads/master
2021-01-13T17:02:40.005029
2020-01-26T11:09:23
2020-01-26T11:11:28
76,651,078
7
1
null
null
null
null
UTF-8
Scheme
false
false
4,033
sch
view.sch
;;; A VIEW object maps a DRAWING onto a WINDOW object. ;* Copyright 1990-1993 Digital Equipment Corporation ;* All Rights Reserved ;* ;* Permission to use, copy, and modify this software and its documentation is ;* hereby granted only under the following terms and conditions. Both the ;* above copyright notice and this permission notice must appear in all copies ;* of the software, derivative works or modified versions, and any portions ;* thereof, and both notices must appear in supporting documentation. ;* ;* Users of this software agree to the terms and conditions set forth herein, ;* and hereby grant back to Digital a non-exclusive, unrestricted, royalty-free ;* right and license under any changes, enhancements or extensions made to the ;* core functions of the software, including but not limited to those affording ;* compatibility with other hardware or software environments, but excluding ;* applications which incorporate this software. Users further agree to use ;* their best efforts to return to Digital any such changes, enhancements or ;* extensions that they make and inform Digital of noteworthy uses of this ;* software. Correspondence should be provided to Digital at: ;* ;* Director of Licensing ;* Western Research Laboratory ;* Digital Equipment Corporation ;* 250 University Avenue ;* Palo Alto, California 94301 ;* ;* This software may be distributed (but not offered for sale or transferred ;* for compensation) to third parties, provided such third parties agree to ;* abide by the terms and conditions of this notice. ;* ;* THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL ;* WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF ;* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT ;* CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL ;* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR ;* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ;* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS ;* SOFTWARE. (define-external VIEW-MODULE-INIT top-level) (define-external MAKE-VIEW top-level) (define-in-line-structure-access VIEW drawing-name window-name clip-minx clip-miny clip-maxx clip-maxy #f #f user->x user->y user->lw x->user y->user user->width user->height width->user height->user originx originy scalex scaley scalelw new bb-head bb-tail stipple-x stipple-y new-transform) (define-external VIEW-DRAWING top-level) (define-external VIEW-WINDOW top-level) (define-external *CURRENT-VIEW* top-level) (define-external *WINDOW* top-level) (define-external *WIDTH* top-level) (define-external *HEIGHT* top-level) (define-external *NAME* top-level) (define-external *FOREGROUND-NAME* top-level) (define-external *BACKGROUND-NAME* top-level) (define-external *FOREGROUND* top-level) (define-external *BACKGROUND* top-level) (define-external *XWINDOW* top-level) (define-external USER->X top-level) (define-external USER->Y top-level) (define-external USER->LW top-level) (define-external X->USER top-level) (define-external Y->USER top-level) (define-external USER->WIDTH top-level) (define-external USER->HEIGHT top-level) (define-external WIDTH->USER top-level) (define-external HEIGHT->USER top-level) (define-external SET-VIEW top-level) (define-external CLIP-BBL-TO-VIEW top-level) (define-external PARTITION-VIEWS top-level) (define-external CV-GC top-level) (define-external POINTS->PIXELS top-level) (define-external WINDOW-DRAWING->VIEW top-level) (define-external DELETE-VIEW top-level) (define-external HANDLE-VISIBLE-EVENTS top-level) (define-external TRANSFORM-VIEWS top-level) (define-external REDRAW-A-VIEW top-level)
false
2009c407b21d289daa2e3b38edfe4328a931b1d2
a8e69b82efa3125947b3af219d8f14335e52d057
/interp-app-optimization.scm
c4a1eab174d3d0c48efc7d0e7c69846e74498652
[ "MIT" ]
permissive
ArunGant8/n-grams-for-synthesis
ad3f14bb082c1220fcea5cfb69029953a2501508
b53b071e53445337d3fe20db0249363aeb9f3e51
refs/heads/master
2023-04-06T05:51:47.903781
2020-05-26T17:09:14
2020-05-26T17:09:14
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,129
scm
interp-app-optimization.scm
(load "interp-core.scm") (set! app-evalo (lambda (expr env val) (fresh (rator x* rands body env^ a* res) (== `(,rator . ,rands) expr) ;; Multi-argument (eval-expo rator env `(closure (lambda ,x* ,body) ,env^) 'app-rator) ;;(eval-randso rands env a*) (ext-env*o x* a* env^ res) ;;(eval-expo body res val 'lambda) (eval-application rands env a* (eval-expo body res val 'lambda)) ))) (define-syntax let/vars (syntax-rules () ((_ _ () body) body) ((_ _ () body ...) (begin body ...)) ((_ st (qvar ...) body ...) (let ((scope (subst-scope (state-S st)))) (let ((qvar (var scope)) ...) body ...))))) (define (list-split-ground st xs) (let loop ((rprefix '()) (xs xs)) (let ((tm (walk xs (state-S st)))) (if (pair? tm) (loop (cons (walk (car tm) (state-S st)) rprefix) (cdr tm)) (values rprefix xs))))) (define (eval-application rands aenv a* body-goal) (define succeed unit) (lambdag@ (st) (let-values (((rrands rands-suffix) (list-split-ground st rands))) (let-values (((ggoals vgoals args-suffix) (let loop ((rands (reverse rrands)) (ggoals succeed) (vgoals succeed) (args a*)) (if (null? rands) (values ggoals vgoals args) (let ((rand (car rands))) (let/vars st (args-rest) (let ((goal (fresh (arg) (== `(,arg . ,args-rest) args) (eval-expo rand aenv arg 'app-rand*)))) (if (var? rand) (loop (cdr rands) ggoals (fresh () vgoals goal) args-rest) (loop (cdr rands) (fresh () ggoals goal) vgoals args-rest))))))))) ((fresh () ggoals ; try ground arguments first body-goal ; then the body vgoals ; then fill in unbound arguments ; any unbound final segment of arguments (eval-randso rands-suffix aenv args-suffix)) st)))))
true
e2b4f04f8296cdd7adca0b2748b177f2740fd01a
0bc4163b3571382861380e47eef4aa1afc862024
/scripts_sdf/demo_torus.scm
44603fd251f1dd3449002740c86a07b134fbe3de
[]
no_license
mjgordon/fluxcadd
49f7c633d4430d98cfa0f24485bfc737fac1a321
afedf70e8a9b43563bb3fe5fdc2265260f4a981b
refs/heads/master
2023-07-21T10:19:36.544424
2023-07-08T00:19:06
2023-07-08T00:19:06
84,756,384
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,023
scm
demo_torus.scm
(let* ((material-ground (Material. (Color. "444455") 0)) (material-torus (Material. (Color. "EEEEDD") 0)) (material-sphere (Material. (Color. "FF0000") 0))) (set-camera-position -70.0 46.0 170.0) (set-camera-target 1.0 10.0 42.0) (set-scene-sdf (SDFPrimitiveGroundPlane. 0 material-ground)) (with-sdf scene-sdf (bool-union (SDFPrimitiveTorus. (.m32 (Matrix4d.) 20.0) 50.0 10.0 material-torus)) (bool-union (SDFPrimitiveCross. (Vector3d. 0.0 0.0 0.0) 1.0 material-torus)) (bool-union (SDFPrimitiveCross. (Vector3d. 0.0 0.0 10.0) 2.0 material-sphere)) (bool-union (SDFPrimitiveCross. (Vector3d. 10.0 0.0 10.0) 2.0 material-sphere)) (bool-union (SDFPrimitiveCross. (Vector3d. 20.0 0.0 10.0) 2.0 material-sphere)) (bool-union (SDFPrimitiveCross. (Vector3d. 30.0 0.0 10.0) 2.0 material-sphere)) (bool-union (SDFPrimitiveCross. (Vector3d. 40.0 0.0 10.0) 2.0 material-sphere)) (bool-union (SDFPrimitiveCross. (Vector3d. 50.0 0.0 10.0) 2.0 material-sphere))))
false
3331c7eda70679dd31b9a7f2884ef9cac5bdf6d2
bdcc255b5af12d070214fb288112c48bf343c7f6
/slib-tests/diff-test.sps
5a3097088ea495dfaad353976f539826d45f1571
[]
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
434
sps
diff-test.sps
#!chezscheme (import (scheme base) (slib diff) (only (srfi 63) array->list) (surfage s64 testing)) (test-begin "slib-diff") (test-equal (diff:longest-common-subsequence "fghiejcklm" "fgehijkpqrlm") "fghijklm") (test-equal (diff:edit-length "fghiejcklm" "fgehijkpqrlm") 6) (test-equal (array->list (diff:edits "fghiejcklm" "fgehijkpqrlm")) '(3 -5 -7 8 9 10)) (test-end)
false
522d91849fbc370c0f7aafeb99a9eba5a872d19b
9d7417f187812a477793ca23da844b34ab2a139d
/Graphikos/Graphikos/lib/ironscheme/typed/parsing.sls
528cb444b1bfd0914524745483fd1b6d4661cae7
[ "MIT", "BSD-3-Clause" ]
permissive
simonmoriat/PLP
5ae19daba4925919b593b4a21dc91dec9de9a6ce
3d130acaa45239cdb289462a242a8c15836a39ca
refs/heads/master
2023-05-11T23:36:28.347462
2016-06-08T07:07:50
2016-06-08T07:07:50
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,009
sls
parsing.sls
#| License Copyright (c) 2007-2015 Llewellyn Pritchard All rights reserved. This source code is subject to terms and conditions of the BSD License. See docs/license.txt. |# (library (ironscheme typed parsing) (export : -> parse-lambda-clause parse-type parse-arg-type parse-name-type-expr) (import (ironscheme) (ironscheme syntax utils) (ironscheme typed parsing-helper)) (define-syntax : (lambda (x) (define (parse type) (syntax-case type (->) [(arg ... -> ret) (with-syntax (((arg ...) (map parse-type #'(arg ...))) (ret (parse-type #'ret))) #'((arg ...) ret))] [(type arg ...) (with-syntax (((arg ...) (map parse-type #'(arg ...)))) #'(type arg ...))] [type #'type])) (syntax-case x () [(_ id type) (identifier? #'id) (with-syntax [(type-spec-id (syntax-format ":~a" #'id #'id)) (type (parse #'type))] #'(define-syntax type-spec-id (make-compile-time-value 'type)))]))) (define (parse-lambda-clause x) (syntax-case x (->) [((arg ... -> ret-type) b b* ...) (with-syntax ((((id type) ...) (map parse-arg-type #'(arg ...)))) (with-syntax (((type ...) (map parse-type #'(type ...))) (ret-type (parse-type #'ret-type))) #'((id ...) ((type ...) ret-type) b b* ...)))] [((arg ...) b b* ...) (parse-lambda-clause #'((arg ... -> Object) b b* ...))])) (define (parse-arg-type x) (syntax-case x (:) [(arg : type) (identifier? #'arg) #'(arg type)] [arg (identifier? #'arg) #'(arg Object)])) (define (parse-name-type-expr x) (syntax-case x (:) [(arg expr) (with-syntax ((arg (parse-arg-type #'arg))) #'(arg expr))])))
true
0805c0c92f340c30594fe65b50443f7125c862a6
fcbc669200213fd71e3e83737387e1f508c9aa65
/lang/scheme/test_stat.scm
601eb2764c3cad811324ccdd68f11de88a99619a
[]
no_license
moguonyanko/moglabo
84e138a35b5ef4e22f45ad615f839ba3cd536e7c
b03bdd7e68d4c32b48e8f114bd793b77dd047ac5
refs/heads/master
2023-09-04T07:25:27.589619
2023-09-01T16:58:54
2023-09-01T16:58:54
4,608,440
0
2
null
null
null
null
UTF-8
Scheme
false
false
342
scm
test_stat.scm
;2012/09/18 moguonyanko ;Test module for stat (load "./stat.scm") (define (assert-equal? a b) ;Check result at test (if (equal? a b) (print "OK!") (print "fail...")) (define (base-stat-test) ;Base statistics procedures test (define (test-sum) (sum `(1 2 3 4 5)) ) ) (define (all-run-test) (base-stat-test) ) ;(all-run-test)
false
abd697b1cfbf4d4b3d79567233ca3406be376822
21a0aae6aa21eda01180304533d124ceec11b8aa
/backprop1081.scm
be08dff22b6efe98d0bb9d901344ea86d0f0285d
[]
no_license
Hamayama/backprop-test
04be4ea789b1ae465a81a6f93f5957e579a0e58f
bb9955f548c895baef4bd5c5bb8eb46901ea959e
refs/heads/master
2020-04-26T04:44:15.245372
2019-06-17T21:21:37
2019-06-17T21:21:37
173,311,807
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,595
scm
backprop1081.scm
;; -*- coding: utf-8 -*- ;; ;; backprop1081.scm ;; 2019-4-20 v2.51 ;; ;; <内容> ;; パラメータ設定ファイル ;; 学習する関数を mod(x, 2) - 1 にした (のこぎり波) ;; (define outfile "backprop_result1081.txt") ; 出力ファイル名 (define input-data-0 (lrange 0 2pi 0.1)) ; 入力(リスト) (define correct-data-0 (map ; 正解(リスト) (lambda (x1) (- (mod (/. (- x1 pi) pi) 2) 1)) input-data-0)) (define n-data (length input-data-0)) ; データ数 (define input-data (apply f2-array ; 入力(行列(1 x n-data)) 0 1 0 n-data ;; (入力の範囲を -1.0~1.0 に変換) (range-conv input-data-0 0 2pi -1.0 1.0))) (define correct-data (apply f2-array ; 正解(行列(1 x n-data)) 0 1 0 n-data correct-data-0)) (define n-in 1) ; 入力層のニューロン数 (define n-mid 10) ; 中間層のニューロン数 (define n-out 1) ; 出力層のニューロン数 (define ml-num 2) ; 中間層の数 (define ml-func 'relu) ; 中間層の活性化関数の選択(sigmoid / relu / tanh) (define wb-width 0.01) ; 重みとバイアスの幅 (define eta 0.05) ; 学習係数 (define epoch 4001) ; エポック数 (define interval 200) ; 経過の表示間隔
false
1e4b67fd1e34b09d3635bdddfb5b6b1f22721fd4
9b2eb10c34176f47f7f490a4ce8412b7dd42cce7
/lib-compat/chicken-yuni/compat/hashtables.sls
193385d5722343210c0e5d0976be096f4526b235
[ "LicenseRef-scancode-public-domain", "CC0-1.0" ]
permissive
okuoku/yuni
8be584a574c0597375f023c70b17a5a689fd6918
1859077a3c855f3a3912a71a5283e08488e76661
refs/heads/master
2023-07-21T11:30:14.824239
2023-06-11T13:16:01
2023-07-18T16:25:22
17,772,480
36
6
CC0-1.0
2020-03-29T08:16:00
2014-03-15T09:53:13
Scheme
UTF-8
Scheme
false
false
2,865
sls
hashtables.sls
(library (chicken-yuni compat hashtables) (export ;; Yuni extension ; Constructors make-integer-hashtable make-string-hashtable make-symbol-hashtable hashtable-for-each hashtable-fold ;; 13.1 Constructors make-eq-hashtable make-eqv-hashtable make-hashtable ;; 13.2 Procedures hashtable? hashtable-size hashtable-ref hashtable-set! hashtable-delete! hashtable-contains? hashtable-update! hashtable-copy hashtable-clear! hashtable-keys hashtable-entries ;; 13.3 Inspection hashtable-equivalence-function hashtable-hash-function hashtable-mutable? ;; 13.4 Hash functions equal-hash string-hash string-ci-hash symbol-hash ) (import (yuni scheme) (srfi 69)) (define (make-hashtable h e) ;; FIXME: Support parameter k (make-hash-table e h)) (define (make-eq-hashtable) (make-hash-table eq? hash-by-identity)) (define (make-eqv-hashtable) (make-hash-table eqv? hash-by-identity)) (define (make-integer-hashtable) (make-hash-table = hash)) (define (make-string-hashtable) (make-hash-table string=? string-hash)) (define (make-symbol-hashtable) (make-hash-table symbol=? symbol-hash)) (define (hashtable-for-each . _) (error "unimpl")) (define (hashtable-fold . _) (error "unimpl")) (define hashtable? hash-table?) (define (hashtable-size h) (error "unimpl")) (define hashtable-ref (case-lambda ((h obj val) (hash-table-ref/default h obj val)) ((h obj) (hash-table-ref h obj)))) (define (hashtable-set! h obj1 obj2) (hash-table-set! h obj1 obj2)) (define (hashtable-delete! h obj1) (hash-table-delete! h obj1)) (define (hashtable-contains? . _) (error "unimpl")) (define (hashtable-update! . _) (error "unimpl")) (define (hashtable-copy . _) (error "unimpl")) (define (hashtable-clear! . _) (error "unimpl")) (define (hashtable-keys h) (list->vector (hash-table-keys h))) (define (hashtable-entries h) (let* ((len (hash-table-size h)) (k (make-vector len)) (v (make-vector len)) (cnt 0)) (hash-table-walk h (lambda (kk vv) (vector-set! k cnt kk) (vector-set! v cnt vv) (set! cnt (+ 1 cnt)))) (values k v))) (define (hashtable-equivalence-function . _) (error "unimpl")) (define (hashtable-hash-function . _) (error "unimpl")) (define (hashtable-mutable? . _) (error "unimpl")) (define equal-hash hash-by-identity) ; string-hash ; string-ci-hash (define symbol-hash hash-by-identity) )
false
e0332e333bc0a8c8990e1a1b1bb8b9637ec83652
222b42ba803bfecd4ec31166dd2be107a840f2bd
/undone/unsortedmacro/r4rs-low-macro-1.0/r4rs.scm
3116859005289cb7b37d2ce3c20db9c7aacecbb0
[]
no_license
ab3250/ablib
83512c2c2cadd0eb49ad534548c058e3ed119d4c
887c8661ce99e8edfe89bcf707400e55c3943dd4
refs/heads/master
2023-06-12T13:36:49.487467
2021-07-11T13:29:45
2021-07-11T13:29:45
384,955,137
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,850
scm
r4rs.scm
;; R4RS examples (symbol? (syntax x)) (let-syntax ((car (lambda (x) (syntax car)))) ((car) '(0))) (let-syntax ((quote-quote (lambda (x) (list (syntax quote) 'quote)))) (quote-quote)) (let-syntax ((quote-quote (lambda (x) (list 'quote 'quote)))) (quote-quote)) (let-syntax ((quote-me (lambda (x) (list (syntax quote) x)))) (quote-me please)) (let ((x 0)) (let-syntax ((alpha (lambda (e) (syntax x)))) (alpha))) (let ((x 0)) (let-syntax ((alpha (lambda (x) (syntax x)))) (alpha))) (let-syntax ((alpha (let-syntax ((beta (syntax-rules () ((beta) 0)))) (lambda (x) (syntax (beta)))))) (alpha)) (let-syntax ((alpha (syntax-rules () ((alpha) 0)))) (let-syntax ((beta (lambda (x) (alpha)))) (beta))) (let ((list 0)) (let-syntax ((alpha (lambda (x) (list 0)))) (alpha))) (identifier? (syntax x)) (identifier? (quote x)) (identifier? 3) (identifier? (unwrap-syntax (syntax x))) (identifier? (car (unwrap-syntax (syntax (x))))) (unwrap-syntax (cdr (unwrap-syntax (syntax (x))))) (free-identifier=? (syntax x) (syntax x)) (free-identifier=? (syntax x) (syntax y)) (let ((x (syntax x))) (free-identifier=? x (syntax x))) (let-syntax ((alpha (lambda (x) (free-identifier=? (car (unwrap-syntax x)) (syntax alpha))))) (alpha)) (letrec-syntax ((alpha (lambda (x) (free-identifier=? (car (unwrap-syntax x)) (syntax alpha))))) (alpha)) (bound-identifier=? (syntax x) (syntax x)) (letrec-syntax ((alpha (lambda (x) (bound-identifier=? (car (unwrap-syntax x)) (syntax alpha))))) (alpha)) (symbol? (identifier->symbol (syntax x))) (identifier->symbol (syntax x)) (identifier->symbol (generate-identifier 'x)) (bound-identifier=? (generate-identifier 'x) (generate-identifier 'x))
false
6da43cd8aeb8b18766b182f719ea613b2303aae0
5355071004ad420028a218457c14cb8f7aa52fe4
/1.2/1.2.scm
a31daab2d827eac47eef3622b7434ce55f5f5275
[]
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
7,189
scm
1.2.scm
; One of the trivial problems which can describe the difference between ; recursive and iterative processes is calculation of factorial ; ; n! = n*(n-1)*(n-2)*...*3*2*1 ; ; This can be recursivelly defined and executed like this ; (load "../common.scm") (define (factorial n) (if (= n 1) 1 (* n (factorial (- n 1))))) ; (display (factorial 6)) ; 720 ; (newline) ; By doing substitution we see the shape of the process ; ; (factorial 6) ; (* 6 (factorial 5)) ; (* 6 (* 5 (factorial 4))) ; (* 6 (* 5 (* 4 (factorial 3)))) ; (* 6 (* 5 (* 4 (* 3 (factorial 2))))) ; (* 6 (* 5 (* 4 (* 3 (* 2 (factorial 1)))))) ; (* 6 (* 5 (* 4 (* 3 (* 2 1))))) ; (* 6 (* 5 (* 4 (* 3 2)))) ; (* 6 (* 5 (* 4 6))) ; (* 6 (* 5 24)) ; (* 6 120) ; 720 ; ; We can see that representation of this process shows growth in two ; dimensions ; ; Number of steps required to finish ; Number of elements that have to be saved for later execution ; ; For this process we see that if we add one more element we ahve to add ; two more steps so order of growth is O(2n) ~ O(n) ; ; Here we see as well that we need to save n number of elements for ; input of size n, so we say that it grows in space with O(n). ; ; For process with growth of ; time = O(n) ; space = O(n) ; ; we say it is `linear recursive` ; We can have as well different approach to calculating factorial (define (fact-iter product counter max-count) (if (> counter max-count) product (fact-iter (* product counter) (+ counter 1) max-count))) (define (factorial n) (fact-iter 1 1 n)) ; (display (factorial 6)) ; 720 ; (newline) ; Shape of this process is completelly different if we do substitution ; ; (factorial 6) ; (fact-iter 1 1 6) ; (fact-iter 1 2 6) ; (fact-iter 2 3 6) ; (fact-iter 6 4 6) ; (fact-iter 24 5 6) ; (fact-iter 120 6 6) ; (fact-iter 720 7 6) ; 720 ; here we see that process is linear in time = O(n) and space is ; constant since we do not have to remember any of the values for the ; next computation ; ; This kind of process is called `linear iteration` ; ; Tree recursion is one common pattern of recursive computation. ; Definition of fibonnaci sequence expains it ; (define (fib n) (cond ((= n 0) 0) ((= n 1) 1) (else (+ (fib (- n 1)) (fib (- n 2)))))) ; (display (fib 5)) ; (newline) ; One thing to see here is how for every call of fibonnaci we have 2 ; more calls spawned during recursion. Here number of steps needed ; to calculate grow exponentially and space grows only linearly. ; ; fib 5 ; / \ ; fib 4 fib 3 .... ; / \ ; fib 3 fib 2 ; / \ ..... ; fib 2 fib 1 ; / \ ; fib 1 fib 0 ; ; This part of the tree is presenting what is happening with the ; recursion. We can see that number of computations (width) is growing ; rapidly with the size of n while number of elements needed to be ; remembered (height) are growing slower and linear with size of the ; input. ; ; time(n) = Fib(n+1) ~ O(Phi^n) ; sace = O(n) ; ; ; Fibonacci sequence can be defined as well through a iterative process. (define (fib n) (fib-iter 0 1 n)) (define (fib-iter a b count) (if (= count 0) a (fib-iter b (+ a b) (- count 1)))) ; (display (fib 100)) ; (newline) ; ; Calculating all the ways to return a change with the given list of ; money amounts is a bit more complicated recursive process. (define (count-change amount) (cc amount 5)) (define (cc amount kinds-of-coins) (cond ((= amount 0) 1) ((or (< amount 0) (= kinds-of-coins 0)) 0) (else (+ (cc amount (- kinds-of-coins 1)) (cc (- amount (first-denomination kinds-of-coins)) kinds-of-coins))))) (define (first-denomination kinds-of-coins) (cond ((= kinds-of-coins 1) 1) ((= kinds-of-coins 2) 5) ((= kinds-of-coins 3) 10) ((= kinds-of-coins 4) 25) ((= kinds-of-coins 5) 50))) ; (display (count-change 11)) ; (newline) ; ; This will take a while until it resolves to 292 ways to change 100 ; with denominations of 50, 25, 10, 5 and 1 ; 1.2.4 Exponantion ; ; Linear recursive process for exponantion of number to n-th exponent. ; b^n = b*b^(n-1), b^0 = 1 (define (expt b n) (if (= n 0) 1 (* b (expt b (- n 1))))) ; (display (expt 2 3)) ; (newline) ; ; This can be implemented as linearly iterative process as well, with ; help of one more variable to transfer current state to next round ; (define (expt b n) (expt-iter b n 1)) (define (expt-iter b count product) (if (= count 0) product (expt-iter b (- count 1) (* product b)))) ; (display (expt 2 32)) ; (newline) ; ; This version is time-wise linear O(n) and space-wise constant O(1) ; But that means for calculating b^1000 it will take 1000 steps to ; calculate the number. ; ; We can do better than this with following algoithm which is based on ; general approach to half the size of the problem on every iteration. ; ; b^n = (b^(n/2))^2 - if n is even ; b^n = b * b^(n-1) - if n is odd ; (define (even? n) (= (remainder n 2) 0)) (define (fast-expt b n) (cond ((= n 0) 1) ((even? n) (square (fast-expt b (/ n 2)))) (else (* b (fast-expt b (- n 1)))))) ; (display (expt 2 33)) ; (newline) ; 1.2.6 Testing for primality ; ; Searching for primary number naturally comes with the idea to find all ; divisors and then check of there are only two of them. Using some ; helper math which says, if n is not prime it must have a divisor ; less than or equal to n, we can write O(sqrt(n)) method for testing for primality. ; (define (divides? a b) (= (remainder b a) 0)) (define (smallest-divisor n) (find-divisor n 2)) (define (find-divisor n test-divisor) (cond ((> (square test-divisor) n) n) ((divides? test-divisor n) test-divisor) (else (find-divisor n (+ test-divisor 1))))) (define (prime? n) (= n (smallest-divisor n))) ; Another way to implement test for primality is by implementing ; Fermat's Little theorem which is ; ; Fermat's Little Theorem: If n is a prime number and a is any ; positive integer less than n, then a raised to the nth power is congruent to a modulo n. ; ; To implement the Fermat test, we need a procedure that computes the exponential of a number modulo another number: (define (expmod base exp m) (cond ((= exp 0) 1) ((even? exp) (remainder (square (expmod base (/ exp 2) m)) m)) (else (remainder (* base (expmod base (- exp 1) m)) m)))) ; based on this Fermat test is (define (fermat-test n) (define (try-it a) (= (expmod a n n) a)) (try-it (+ 1 (random (- n 1))))) ; (display (fermat-test 12323)) ; (newline) ; This test is probabilistic and can be fooled so we can execute several ; times to prove it with different values for a. (define (fast-prime? n times) (cond ((= times 0) true) ((fermat-test n) (fast-prime? n (- times 1))) (else false))) ; (display (fast-prime? 1232312323 10)) ; (newline)
false
3c646d3c4d2c7b1e9858a84ddaf3fe7b3accbb77
7053803109172ee3fe36594257fb9f323f860c9a
/chapters/3/3.55.scm
641411475438d27b0fe21d6c893aa298e6633980
[]
no_license
david-davidson/SICP
0c7c38a11b11ef70146f4a511e4ac8d7c0651b82
393932a507afdc35cb99451ef53a059e72f71eb1
refs/heads/main
2021-06-14T00:36:59.503919
2021-05-28T01:54:39
2021-05-28T01:55:42
195,283,241
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,760
scm
3.55.scm
#| Problem: define a procedure `partial-sums` that takes a stream S and returns the stream whose elements are S0, S0 + S1, S0 + S1 + S2... e.g., the stream of integers should return 1, 1 + 2, 1 + 2 + 3... (that is, 1, 3, 6...) |# ; -------------------------------------------------------------------------------------------------- ; Couple helpers: ; -------------------------------------------------------------------------------------------------- (define (integers-starting-from n) (cons-stream n (integers-starting-from (+ n 1)))) (define integers (integers-starting-from 1)) (define (add-streams seq1 seq2) (stream-map + seq1 seq2)) ; -------------------------------------------------------------------------------------------------- ; The trick here is that a given item in the response -- say, `S0 + S1 + S2` -- is basically the ; _previous item_ in the response (here, `S0 + S1`) plus `S2`. We don't have to do all those ; additions for each entry; we just have to add the _previous_ entry in the response stream and the ; _latest_ entry in the input stream. ; ; This lets us use the `add-streams` trick, plus a response stream defined in terms of itself. Note ; that for the element-wise addition to work, we need to offset the input stream by one (with ; `(stream-cdr seq)`): that way, we get the latest + previous pairing, not latest + latest. ; -------------------------------------------------------------------------------------------------- (define (partial-sums seq) (define sums (cons-stream (stream-car seq) (add-streams sums (stream-cdr seq)))) sums) ; (stream-ref (partial-sums integers) 0) => 1 ; (stream-ref (partial-sums integers) 1) => 3 ; (stream-ref (partial-sums integers) 2) => 6
false
feb59409f6d6087881a3f2b554db1d002d9d2e04
746e3020868df770371fe7aa6a4e3fca99c014f8
/v3/first.scm
4da7baa1db1136f1fba1d8b2ab7fb3ddeede122b
[]
no_license
hiy0ki/gauche-practice
32c8586739c485e2b301f6c4fbe555ae8bfab20b
3dbeab66cda405825149d14f057bf9bc60d3c27a
refs/heads/master
2022-05-06T00:18:40.045511
2022-04-07T21:20:22
2022-04-07T21:20:22
133,526,619
0
0
null
null
null
null
UTF-8
Scheme
false
false
35
scm
first.scm
#!/usr/local/bin/gosh (+ 1 2)
false
e35874b67a36f987d543660e398fda30be90a573
1384f71796ddb9d11c34c6d988c09a442b2fc8b2
/examples/playlist2m3u
a599e654c5ae8eff78f60371639e6292915fc2ad
[]
no_license
ft/xmms2-guile
94c2479eec427a370603425fc9e757611a796254
29670e586bf440c20366478462f425d5252b953c
refs/heads/master
2021-07-08T07:58:15.066996
2020-10-12T01:24:04
2020-10-12T01:24:04
74,858,831
1
2
null
null
null
null
UTF-8
Scheme
false
false
1,117
playlist2m3u
;; -*- scheme-*- ;; This example connects to the default xmms2 server, fetches the contents of ;; the currently active playlists and prints a list of file-names to stdout. (use-modules (ice-9 binary-ports) (xmms2 client) (xmms2 client synchronous) (xmms2 constants) (xmms2 fetch-spec) (xmms2 ipc collection) (xmms2 ipc playlist) (xmms2 types) (xmms2 values)) (define (main c id cookie) (let* ((pl (request->value c (ipc-list-entries NAME-OF-ACTIVE-PLAYLIST))) (fl (request->value c (ipc-query (collection (id-list (| pl))) (fetch-spec #:type metadata #:aggregate list #:get (value) #:fields (url)))))) (map (lambda (f) (put-bytevector (current-output-port) (decode-and-strip f)) (newline)) fl))) (with-xmms2-connection #:handler main #:client "playlist2m3u")
false
8b1a4c27d51c8ab93b673dc26c9b290c915628b1
25a487e394b2c8369f295434cf862321c26cd29c
/lib/loitsu/clos/std-protocols/allocate-instance.sls
dedaeb8d2b286a5858b3a9747cbb1c5b5537091e
[]
no_license
mytoh/loitsu
b11e1ed9cda72c0a0b0f59070c9636c167d01a2c
d197cade05ae4acbf64c08d1a3dd9be6c42aac58
refs/heads/master
2020-06-08T02:00:50.563515
2013-12-17T10:23:04
2013-12-17T10:23:04
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,383
sls
allocate-instance.sls
;; ************************************************************************* ;; Copyright (c) 1992 Xerox Corporation. ;; All Rights Reserved. ;; ;; Use, reproduction, and preparation of derivative works are permitted. ;; Any copy of this software or of any derivative work must include the ;; above copyright notice of Xerox Corporation, this paragraph and the ;; one after it. Any distribution of this software or derivative works ;; must comply with all applicable United States export control laws. ;; ;; This software is made available AS IS, and XEROX CORPORATION DISCLAIMS ;; ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE ;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR ;; PURPOSE, AND NOTWITHSTANDING ANY OTHER PROVISION CONTAINED HEREIN, ANY ;; LIABILITY FOR DAMAGES RESULTING FROM THE SOFTWARE OR ITS USE IS ;; EXPRESSLY DISCLAIMED, WHETHER ARISING IN CONTRACT, TORT (INCLUDING ;; NEGLIGENCE) OR STRICT LIABILITY, EVEN IF XEROX CORPORATION IS ADVISED ;; OF THE POSSIBILITY OF SUCH DAMAGES. ;; ************************************************************************* ;; ;; port to R6RS -- 2007 Christian Sloma ;; (library (loitsu clos std-protocols allocate-instance) (export class-allocate-instance entity-class-allocate-instance) (import (only (rnrs) define let* let if null? begin car cdr + quote) (loitsu clos private allocation) (loitsu clos slot-access)) (define (class-allocate-instance class) (shared-allocate-instance class really-allocate-instance)) (define (entity-class-allocate-instance entity-class) (shared-allocate-instance entity-class really-allocate-entity-instance)) (define (shared-allocate-instance class really-allocate) (let* ((field-count (slot-ref class 'number-of-fields)) (field-inits (slot-ref class 'field-initializers)) (new-object (really-allocate class field-count))) (let loop ((inits field-inits) (index 0)) (if (null? inits) new-object (begin (instance-set! new-object index ((car inits))) (loop (cdr inits) (+ index 1))))))) ) ;; library (clos std-protocols allocate-instance)
false
dc58eca3d855d620b5fb80b69fe0b67915e7a0e1
ce567bbf766df9d98dc6a5e710a77870753c7d29
/ch1/17.scm
0b320d7c72e589e84e53a10ffe2ee6255450e445
[]
no_license
dott94/eopl
1cbe2d98c948689687f88e514579e66412236fc9
47fadf6f2aa6ca72c831d6e2e2eccbe673129113
refs/heads/master
2021-01-18T06:42:35.921839
2015-01-21T07:06:43
2015-01-21T07:06:43
30,055,972
1
0
null
2015-01-30T04:21:42
2015-01-30T04:21:42
null
UTF-8
Scheme
false
false
296
scm
17.scm
(load "../libs/init.scm") (define down (lambda (list) (if (null? list) '() (cons (cons (car list) '()) (down (cdr list)))))) (equal?? (down '(a b)) '((a) (b))) (equal?? (down '(a)) '((a))) (equal?? (down '(a (more (complicated)) object)) '((a) ((more (complicated))) (object)))
false
ad5dc3120d62bd14a89291d0c338908dbcb13cf2
6e359a216e1e435de5d39bc64e75998945940a8c
/ex4.3.scm
dafee8a1dfcd8588d29d2fd7227c97691cf1d3c5
[]
no_license
GuoDangLang/SICP
03a774dd4470624165010f65c27acc35d844a93d
f81b7281fa779a9d8ef03997214e47397af1a016
refs/heads/master
2021-01-19T04:48:22.891605
2016-09-24T15:26:57
2016-09-24T15:26:57
69,106,376
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,815
scm
ex4.3.scm
(define (assoc key records) (cond ((null? records) false) ((eq? (caar records) key) (car records)) (else (assoc key (cdr records))))) (define (make-table) (let ((local-table (list '*table*))) (define (lookup k1 k2) (let ((subtable (assoc k1 (cdr local-table)))) (if subtable (let ((record (assoc k2 (cdr subtable)))) (if record (cdr record) false))) false)) (define (insert! k1 k2 value) (let ((subtable (assoc k1 (cdr local-table)))) (if subtable (let ((record (assoc k2 (cdr subtable)))) (if record (set-cdr! record value) (set-cdr! subtable (cons (cons k2 value) (cdr subtable))))) (set-cdr! local-table (cons (list k1 (cons k2 value)) (cdr local-table))))) 'ok) (define (dispatch m) (cond ((eq? m 'lookup-proc) lookup) ((eq? m 'insert-proc!) insert!) (else (error "Unkown operation -- TABLE" m)))) dispatch)) (define evaluator (make-table)) (define get (evaluator 'lookup-proc)) (define put (evaluator 'insert-proc!)) (define (install-evaluator-package) (put 'eval 'quote (lambda (x) (text-of-quotation x))) (put 'eval 'define eval-definition) (put 'eval 'set! eval-assignment) (put 'eval 'if eval-if) (put 'eval 'lambda (lambda (x y) (make-procedure (lambda-parameters x) (lambda-body x) y))) (put 'eval 'begin (lambda (x y) (eval-sequence (begin-sequence x) y))) (put 'eval 'cond (lambda (x y) (eval (cond->if x) y))) 'ok) (define (eval exp env) (cond ((self-evaluating? exp) exp) ((variable? exp) (lookup-variable-value exp env)) ((get 'eval (car exp)) (apply (get 'op (car expr) exp env))) ((application? exp) (apply (eval (operator exp) env) (list-of-value (operands expr) env))) (else (error "Unkonw expression type -- EVAL" exp))))
false
4fdef2d95e6b126e8e963794159878cd61371de0
dde6f1cc65c21d5b902da10388e5899c7860ce64
/chicken/utilities.run.import.scm
131eea57f002d8bb6922371b29d377981dd61eb3
[]
no_license
alaricsp/api.scheme.org
2a37961035a057870ec52325a2046e56d862a1c9
97c48a93753ddd7dc3f5e17bb4f3854dd1f42e7f
refs/heads/master
2023-01-31T10:44:52.845579
2020-12-18T12:32:28
2020-12-18T12:32:28
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
49
scm
utilities.run.import.scm
(import (r7rs)) (include "../utilities/run.sld")
false
927bf933d66b3b1f9e3b842db0cce3e9a060f263
f8f1f7d45998db2c9b27bd5197b512f32eaa07aa
/scheme.load.scm
aab5adef6a0df1583610e9e88be0e2643a2e80a1
[ "BSD-2-Clause" ]
permissive
spurious/chicken5-r7rs-svn
fe386df66560b1783cb59d14e529374d1ccb64fe
d56aabd87224db524c64fd53d44f99649aa1dc9f
refs/heads/master
2023-04-19T03:13:18.228770
2021-04-14T19:42:11
2021-04-14T19:42:11
365,430,922
0
0
null
null
null
null
UTF-8
Scheme
false
false
360
scm
scheme.load.scm
(module scheme.load (load) (import chicken.base chicken.type) (import (rename scheme (load %load) (eval %eval))) (: load (string #!optional (struct environment) -> undefined)) (define load (case-lambda ((filename) (%load filename)) ((filename environment) (%load filename (lambda (exp) (%eval exp environment)))))))
false
6753aa76785591d4b4013153a530b67695cdcba3
defeada37d39bca09ef76f66f38683754c0a6aa0
/mscorlib/system/runtime/remoting/messaging/method-call.sls
f8cf7b74d5c4146f950d7ab8d582d3acb389b4fa
[]
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,317
sls
method-call.sls
(library (system runtime remoting messaging method-call) (export new is? method-call? get-in-arg-name get-in-arg root-set-object-data init header-handler get-object-data get-arg get-arg-name resolve-method arg-count args has-var-args? in-arg-count in-args logical-call-context method-base method-name method-signature properties type-name uri-get uri-set! uri-update!) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Runtime.Remoting.Messaging.MethodCall a ...))))) (define (is? a) (clr-is System.Runtime.Remoting.Messaging.MethodCall a)) (define (method-call? a) (clr-is System.Runtime.Remoting.Messaging.MethodCall a)) (define-method-port get-in-arg-name System.Runtime.Remoting.Messaging.MethodCall GetInArgName (System.String System.Int32)) (define-method-port get-in-arg System.Runtime.Remoting.Messaging.MethodCall GetInArg (System.Object System.Int32)) (define-method-port root-set-object-data System.Runtime.Remoting.Messaging.MethodCall RootSetObjectData (System.Void System.Runtime.Serialization.SerializationInfo System.Runtime.Serialization.StreamingContext)) (define-method-port init System.Runtime.Remoting.Messaging.MethodCall Init (System.Void)) (define-method-port header-handler System.Runtime.Remoting.Messaging.MethodCall HeaderHandler (System.Object System.Runtime.Remoting.Messaging.Header[])) (define-method-port get-object-data System.Runtime.Remoting.Messaging.MethodCall GetObjectData (System.Void System.Runtime.Serialization.SerializationInfo System.Runtime.Serialization.StreamingContext)) (define-method-port get-arg System.Runtime.Remoting.Messaging.MethodCall GetArg (System.Object System.Int32)) (define-method-port get-arg-name System.Runtime.Remoting.Messaging.MethodCall GetArgName (System.String System.Int32)) (define-method-port resolve-method System.Runtime.Remoting.Messaging.MethodCall ResolveMethod (System.Void)) (define-field-port arg-count #f #f (property:) System.Runtime.Remoting.Messaging.MethodCall ArgCount System.Int32) (define-field-port args #f #f (property:) System.Runtime.Remoting.Messaging.MethodCall Args System.Object[]) (define-field-port has-var-args? #f #f (property:) System.Runtime.Remoting.Messaging.MethodCall HasVarArgs System.Boolean) (define-field-port in-arg-count #f #f (property:) System.Runtime.Remoting.Messaging.MethodCall InArgCount System.Int32) (define-field-port in-args #f #f (property:) System.Runtime.Remoting.Messaging.MethodCall InArgs System.Object[]) (define-field-port logical-call-context #f #f (property:) System.Runtime.Remoting.Messaging.MethodCall LogicalCallContext System.Runtime.Remoting.Messaging.LogicalCallContext) (define-field-port method-base #f #f (property:) System.Runtime.Remoting.Messaging.MethodCall MethodBase System.Reflection.MethodBase) (define-field-port method-name #f #f (property:) System.Runtime.Remoting.Messaging.MethodCall MethodName System.String) (define-field-port method-signature #f #f (property:) System.Runtime.Remoting.Messaging.MethodCall MethodSignature System.Object) (define-field-port properties #f #f (property:) System.Runtime.Remoting.Messaging.MethodCall Properties System.Collections.IDictionary) (define-field-port type-name #f #f (property:) System.Runtime.Remoting.Messaging.MethodCall TypeName System.String) (define-field-port uri-get uri-set! uri-update! (property:) System.Runtime.Remoting.Messaging.MethodCall Uri System.String))
true
ce66439864994546cad3cdd487efd4f8429d981b
defeada37d39bca09ef76f66f38683754c0a6aa0
/mscorlib/mono/security/x509/x509-extension.sls
fa4e3e6b0de8d5673b6bcd249c90fad3deb2ac19
[]
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,760
sls
x509-extension.sls
(library (mono security x509 x509-extension) (export new is? x509-extension? get-hash-code to-string get-bytes equals? asn1 oid critical?-get critical?-set! critical?-update! name value) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new Mono.Security.X509.X509Extension a ...))))) (define (is? a) (clr-is Mono.Security.X509.X509Extension a)) (define (x509-extension? a) (clr-is Mono.Security.X509.X509Extension a)) (define-method-port get-hash-code Mono.Security.X509.X509Extension GetHashCode (System.Int32)) (define-method-port to-string Mono.Security.X509.X509Extension ToString (System.String)) (define-method-port get-bytes Mono.Security.X509.X509Extension GetBytes (System.Byte[])) (define-method-port equals? Mono.Security.X509.X509Extension Equals (System.Boolean System.Object)) (define-field-port asn1 #f #f (property:) Mono.Security.X509.X509Extension ASN1 Mono.Security.ASN1) (define-field-port oid #f #f (property:) Mono.Security.X509.X509Extension Oid System.String) (define-field-port critical?-get critical?-set! critical?-update! (property:) Mono.Security.X509.X509Extension Critical System.Boolean) (define-field-port name #f #f (property:) Mono.Security.X509.X509Extension Name System.String) (define-field-port value #f #f (property:) Mono.Security.X509.X509Extension Value Mono.Security.ASN1))
true
49e37bce2cfe0eb005e0356df65501463f96fe82
a70301d352dcc9987daf2bf12919aecd66defbd8
/mredtalk2/spin-display.scm
bf5a4bd3903db6458347e74a7b4aee191899ca89
[]
no_license
mflatt/talks
45fbd97b1ca72addecf8f4b92053b85001ed540b
7abfdf9a9397d3d3d5d1b4c107ab6a62d0ac1265
refs/heads/master
2021-01-19T05:18:38.094408
2020-06-04T16:29:25
2020-06-04T16:29:25
87,425,078
2
2
null
null
null
null
UTF-8
Scheme
false
false
1,180
scm
spin-display.scm
(module spin-display mzscheme (require (lib "mred.ss" "mred") (lib "class.ss") (lib "math.ss")) (provide rotate-a-little) (define degree 0) (define white-brush (send the-brush-list find-or-create-brush "white" 'solid)) (define orange-brush (send the-brush-list find-or-create-brush "orange" 'solid)) (define orange-pen (send the-pen-list find-or-create-pen "orange" 2 'solid)) (define-values (display-w display-h) (get-display-size)) (define f (new frame% [label "Spinner"] [x (- display-w 200)] [y (- display-h 170)] [style '(hide-menu-bar)])) (define c (instantiate canvas% (f) [min-width 100] [min-height 100] [paint-callback (lambda (c dc) (send dc set-smoothing 'aligned) (send dc set-brush white-brush) (send dc set-pen orange-pen) (send dc draw-ellipse 0 0 100 100) (send dc set-brush orange-brush) (send dc draw-arc 0 0 100 100 (- degree 0.1) (+ degree 0.1)))])) (send f show #t) (define (rotate-a-little) (set! degree (- degree 0.05)) (send c refresh)))
false
0a244f226276d733346d0fc4b9b5222b259a8e9f
ce567bbf766df9d98dc6a5e710a77870753c7d29
/ch3/05.scm
a7982dc5f37a4a5e3938b530a7af14e57f7879f0
[]
no_license
dott94/eopl
1cbe2d98c948689687f88e514579e66412236fc9
47fadf6f2aa6ca72c831d6e2e2eccbe673129113
refs/heads/master
2021-01-18T06:42:35.921839
2015-01-21T07:06:43
2015-01-21T07:06:43
30,055,972
1
0
null
2015-01-30T04:21:42
2015-01-30T04:21:42
null
UTF-8
Scheme
false
false
37
scm
05.scm
;; same as 04, :( a bug of this book
false
7c864aaef1eb976f88ceac9733d54706f99d94a2
1dfe3abdff4803aee6413c33810f5570d0061783
/.chezscheme_libs/spells/delimited-control.sls
3d02b13cdf18fecf79016585a33e00e028111acd
[]
no_license
Saigut/chezscheme-libs
73cb315ed146ce2be6ae016b3f86cf3652a657fc
1fd12abbcf6414e4d50ac8f61489a73bbfc07b9d
refs/heads/master
2020-06-12T14:56:35.208313
2016-12-11T08:51:15
2016-12-11T08:51:15
75,801,338
6
2
null
null
null
null
UTF-8
Scheme
false
false
3,131
sls
delimited-control.sls
#!r6rs ;;; delimited-control.sls --- Delimited-control operators ;; Copyright (C) 2009, 2011, 2015 Andreas Rottmann <[email protected]> ;; Author: Andreas Rottmann <[email protected]> ;; This program is free software, you can redistribute it and/or ;; modify it under the terms of the new-style BSD license. ;; You should have received a copy of the BSD license along with this ;; program. If not, see <http://www.debian.org/misc/bsd.license>. ;;; Commentary: ;; Code taken from http://okmij.org/ftp/Scheme/delim-control-n.scm; ;; - Changed to use R6RS records instead of mutable pairs ;; - Use macrology to define all 4 operator pairs ;;; Code: ;;@ Delimited control operators. (library (spells delimited-control) (export abort prompt control shift reset prompt0 control0 shift0 reset0) (import (rnrs base) (rnrs records syntactic)) ; This is one single global mutable cell (define holes '()) (define (hole-push! hole) (set! holes (cons hole holes))) (define (hole-pop!) (let ((hole (car holes))) (set! holes (cdr holes)) hole)) (define-record-type (cell cell-new cell?) (fields (immutable v cell-ref) (immutable mark cell-marked?))) ; Essentially this is the ``return from the function'' (define (abort-top! v) ((cell-ref (hole-pop!)) v)) (define (unwind-till-marked! who keep?) (if (null? holes) (assertion-violation who "No prompt set")) (let ((hole (hole-pop!))) (if (cell-marked? hole) ; if marked, it's prompt's hole (begin (hole-push! ; put it back (if keep? hole (cell-new (cell-ref hole) #f))) ; make the hole non-delimiting '()) (cons hole (unwind-till-marked! who keep?))))) (define (prompt* thunk) (call-with-current-continuation (lambda (outer-k) (hole-push! (cell-new outer-k #t)) ; it's prompt's hole (abort-top! (thunk))))) (define (make-control* who shift? keep?) (lambda (f) (call-with-current-continuation (lambda (k-control) (let* ((holes-prefix (reverse (unwind-till-marked! who keep?))) (invoke-subcont (lambda (v) (call-with-current-continuation (lambda (k-return) (hole-push! (cell-new k-return shift?)) (for-each hole-push! holes-prefix) (k-control v)))))) (abort-top! (f invoke-subcont))))))) (define-syntax define-operators (syntax-rules () ((_ (control* control prompt) shift? keep?) (begin (define control* (make-control* 'control shift? keep?)) ;; Some syntactic sugar (define-syntax prompt (syntax-rules () ((prompt e) (prompt* (lambda () e))))) (define-syntax control (syntax-rules () ((control k e) (control* (lambda (k) e))))))))) (define-operators (shift* shift reset) #t #t) (define-operators (shift0* shift0 reset0) #t #f) (define-operators (control* control prompt) #f #t) (define-operators (control0* control0 prompt0) #f #f) (define (abort v) (control* (lambda (k) v))) )
true
d117e6bf4ab945b781be92bd71fe63599c5b4856
e0b29bfd6139cb1b7039b1bcb191c1f948243c61
/code/stages/parse.scm
f2836a286b4985bb1e1f9dbf25460f7b1a76dcb8
[]
no_license
acotis/serial-predicate-engine
6c33d2c8f4552f1bfcc7fcf8b405868e82148ee6
9e02baf711c0b7402da2eeb50b8644bf7b6e415f
refs/heads/master
2021-07-13T13:45:49.597227
2019-01-03T01:44:37
2019-01-03T01:44:37
147,992,280
2
1
null
2023-01-10T20:05:08
2018-09-09T04:16:13
Scheme
UTF-8
Scheme
false
false
3,278
scm
parse.scm
#!/usr/bin/guile !# ;; File: parse.scm ;; Purpose: Turn a list of cmavo & roots into a tree-structure ;; representing a composite. ;; Input: (to ru "gi" "pai" to "hui") ;; Output: (ru ("gi" "pai") "hui") (load "../utilities.scm") (use-modules (srfi srfi-1)) ;; RU ;; Replace last instance of ...p1 RU p2... with ...(RU p1 p2)... (define (fold-last-ru com) (cond ((> (count is-RU? com) 1) (cons (car com) (fold-last-ru (cdr com)))) ((not (is-RU? (cadr com))) (cons (car com) (fold-last-ru (cdr com)))) (#t (cons (list (cadr com) (car com) (caddr com)) (cdddr com))))) ;; MU ;; Fold all instances of ...MU p1... into ...(MU p1)... ;; Note that this only replaces innermost instances of MU, ;; so you still may need to call this function more than once (define (fold-inner-mu com) (if (not (member 'mu com)) com (if (and (eq? 'mu (car com)) (not (eq? 'mu (cadr com)))) (cons (list (car com) (cadr com)) (fold-inner-mu (cddr com))) (cons (car com) (fold-inner-mu (cdr com)))))) ;; TO RU ;; Split the highest-level (A to ru B to C) into ;; ((A) (to ru (B) (C))). (define (before-first-to com) (if (eq? 'to (car com)) '() (cons (car com) (before-first-to (cdr com))))) (define (find-top-level com level) (if (= 0 level) com (find-top-level (cdr com) (if (eq? 'to (car com)) (if (is-RU? (cadr com)) (+ level 1) (- level 1)) level)))) (define (fork-toru com) (let* ((before (before-first-to com)) (after (drop com (length before))) (under (drop after 2)) (branch-b (find-top-level under 1)) (branch-a (drop-right under (+ 1 (length branch-b))))) (list before (list 'to (cadr after) branch-a branch-b)))) ;; Parse a composite into a parse-form ;; i.e. ("jai") -> "jai" ;; ("dua" "mai") -> (xy "dua" "mai") ;; (to ru "kuai" to "tua") -> (ru "kuai" "tua") (define (parse-composite com) (cond ( ;; Parse outermost TO RU ... TO ... construction (member 'to com) (let* ((fork (fork-toru com)) (before (car fork)) (toru (cadr fork))) (parse-composite (append before (list (list (cadr toru) (parse-composite (caddr toru)) (parse-composite (cadddr toru)))))))) ;; Fold innermost MU particles ((member 'mu com) (parse-composite (fold-inner-mu com))) ;; Fold last RU pairing ((any is-RU? com) (parse-composite (fold-last-ru com))) ;; If only one parse-form, return unchanged ((= 1 (length com)) (car com)) ;; If multiple parse-forms, serialize (#t (list 'xy (car com) (parse-composite (cdr com)))))) ;; Perform the "parse" stage on the output of the "read" stage. (define (stage-parse read-output) (parse-composite read-output))
false
654d8926bbe5c99ebf38a168c21c121636a32f72
25eb3a6367cb612c54241f1a9c0418d56274c18b
/test/dreme/if-tests.scm
df2d2018873b3f295af3c8b3bbad0e44f8493d1f
[ "Apache-2.0" ]
permissive
mattryall/dreme
479e47f6047598f680b32def073f6fd9dccc50c2
fba365ccc80006c863c689b46174d03b83f6bb67
refs/heads/master
2020-04-09T06:57:12.436355
2020-02-03T23:52:17
2020-02-03T23:52:17
160,134,235
0
1
null
null
null
null
UTF-8
Scheme
false
false
1,018
scm
if-tests.scm
( (ifTrueValue (if #t #t #f) #t) (ifFalseValue (if #f #t #f) #f) (ifOnlyTrueValue (if #t #t) #t) (ifZeroValue (if 0 #t #f) #t) (ifNonZeroValue (if 1 #t #f) #t) (greaterThanTrue (> 3 2) #t) (greaterThanFalse (> 2 3) #f) (greaterThanEqualArgs (> 2 2) #f) (greaterThanManyArgsTrue (> 3 2 0) #t) (greaterThanManyArgsFalse (> 3 2 5) #f) (lessThanTrue (< -1 2) #t) (lessThanFalse (< 2 -3) #f) (lessThanEqualArgs (< 2 2) #f) (lessThanManyArgsTrue (< 1 2 5) #t) (lessThanManyArgsFalse (< 2 3 2) #f) (isEqual (= 1 1) #t) (isNotEqual (= 1 2) #f) (isEqualDifference (= (- 2 1) 1) #t) (isEqualSum (= (+ 2 1) 3) #t) (elseNotProvided (if #f (+ 2 4)) #<unspecified>) (conditionEvaluatedOnceOnly (begin (define x 0) (let ((inc (lambda () (set! x (+ x 1)) #t))) (if (inc) #t #f) x)) 1) ; (inc) should only be evaluated once )
false
e3883f804d33a219130b22d84239f58113107170
9face33c879099287ece1b2c75d1b462b9efe565
/anotados/aula3.scm
3801dc616b3184a87e9e48ad9613e34cb1ed858e
[]
no_license
ramalho/mac316
ebf02aba99c67d58a1a23f8852e8c41d4b4fb101
4c925557064c788c4d29e3408a6b1d327386d98b
refs/heads/master
2020-05-31T18:14:31.154370
2009-06-17T19:57:06
2009-06-17T19:57:06
156,354
2
0
null
null
null
null
UTF-8
Scheme
false
false
3,893
scm
aula3.scm
;LR| Neste arquivo o Prof. Gubi colocou vários comentários e perguntas. ;LR| Os comentários que indicam páginas no livro PLAI e aqueles marcados ;LR| com ;LR| são meus (Luciano Ramalho) ;LR| Para facilitar a leitura do código, coloquei prefixos nos identificadores ;LR| das variantes dos dois tipos definidos com define-type: ;LR| - tipo FunDef, prefixo $ ;LR| - tipo F1WAE, prefixo % ; definição de função ; PLAI section 4.1, p. 28 (define-type FunDef [$fundef (fun-name symbol?) (arg-name symbol?) (body F1WAE?)]) ; o que acontece se usarmos WAE aqui??? ; expressão aceita pela linguagem ; PLAI section 4.1, p. 28 (define-type F1WAE [%num (n number?)] [%add (lhs F1WAE?) (rhs F1WAE?)] [%sub (lhs F1WAE?) (rhs F1WAE?)] [%with (name symbol?) (named-expr F1WAE?) (body F1WAE?)] [%id (name symbol?)] [%app (fun-name symbol?) ; chamada de função (arg-expr F1WAE?)]) ; melhor F1WAE ou WAE??? ; interp : F1WAE list-of-FunDef -> number ; PLAI section 4.1, p. 28-29 (define (interp a-wae defs) (type-case F1WAE a-wae [%num (n) n] [%add (l r) (+ (interp l defs) (interp r defs))] [%sub (l r) (- (interp l defs) (interp r defs))] [%with (bound-id named-expr body-expr) (interp (subst body-expr bound-id ;(%num (interp named-expr defs))) ; LR| errado como no PLAI (interp named-expr defs)) ;LR| corrigido defs)] [%id (name) (error 'interp "free variable")] ; por que o aviso de erro??? [%app (fname arg-expr) (local [(define f (find-def fname defs))] (interp (subst ($fundef-body f) ; corpo de f ($fundef-arg-name f) ; argumento formal de f ;LR| linha abaixo diferente em PLAI (interp arg-expr defs)) ; valor do argumento defs))] ) ) ;LR| As linhas marcadas como "diferente em PLAI" estão erradas no livro. ;LR| No primeiro caso, a linha no livro é: ;LR| (%num (interp named-expr defs))) ;LR| Isso faz com que o interp devolva a representação de número (%num) da ;LR| nossa linguagem, mas o contrato diz F1WAE list-of-FunDef -> number ;LR| ou seja, o interp tem que devolver números de Scheme. ;LR| Note que as variantes %add e %sub tratam o resultado da chamada recursiva ;LR| de interp como número, usando os operadores + e - de Scheme. ;LR| E a variante %num devolve o valor do campo n de %num, que é um número ;LR| (veja definição de F1WAE). ;LR| A outra linha diferente tem o mesmo erro no livro: constrói um %num. ; find-def : sym list-of-FunDef -> FunDef (define (find-def fname l) (cond [(empty? l) (error "no such function")] [else (if (symbol=? fname ($fundef-fun-name (first l))) (first l) (find-def fname (rest l)))])) ; É verdade que find-def faz uma busca de complexidade exponencial??? ; subst : F1WAE sym num -> F1WAE (define (subst a-wae sub-id val) (type-case F1WAE a-wae [%num (n) a-wae] [%add (l r) (%add (subst l sub-id val) (subst r sub-id val))] [%sub (l r) (%sub (subst l sub-id val) (subst r sub-id val))] [%with (bound-id named-expr body-expr) (%with bound-id (subst named-expr sub-id val) (if (symbol=? bound-id sub-id) ; qual a razão deste teste??? body-expr (subst body-expr sub-id val)))] [%id (name) (if (symbol=? name sub-id) ; e deste??? (%num val) a-wae)] ; a-wae?? isso está correto? ; o que tem em a-wae nesse caso??? [%app (fname arg-expr) (%app fname (subst arg-expr sub-id val))])) ; o que faz este subst??? ;LR| movi os testes para o arquivo aula3-tests.scm
false
738bb4295004b0a67181a6f9089f34de0c969e86
120324bbbf63c54de0b7f1ca48d5dcbbc5cfb193
/packages/srfi/%3a6/basic-string-ports.sls
c46e352114e4c81c0a1ffd7350a3a5f9fa18ad83
[ "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
411
sls
basic-string-ports.sls
#!r6rs ;; Copyright 2010 Derick Eddington. My MIT-style license is in the file named ;; LICENSE from the original collection this file is distributed with. (library (srfi :6 basic-string-ports) (export (rename (open-string-input-port open-input-string)) open-output-string get-output-string) (import (only (rnrs io ports) open-string-input-port) (srfi :6 basic-string-ports compat)) )
false
78b31fcff5936eb0c9e0fd3aed8abbc32e438867
7301b8e6fbd4ac510d5e8cb1a3dfe5be61762107
/ex-3.22.scm
4c33307108752a763625893d97fe2e94277d8290
[]
no_license
jiakai0419/sicp-1
75ec0c6c8fe39038d6f2f3c4c6dd647a39be6216
974391622443c07259ea13ec0c19b80ac04b2760
refs/heads/master
2021-01-12T02:48:12.327718
2017-01-11T12:54:38
2017-01-11T12:54:38
78,108,302
0
0
null
2017-01-05T11:44:44
2017-01-05T11:44:44
null
UTF-8
Scheme
false
false
1,996
scm
ex-3.22.scm
;;; Exercise 3.22. Instead of representing a queue as a pair of pointers, we ;;; can build a queue as a procedure with local state. The local state will ;;; consist of pointers to the beginning and the end of an ordinary list. Thus, ;;; the make-queue procedure will have the form ;;; ;;; (define (make-queue) ;;; (let ((front-ptr ...) ;;; (rear-ptr ...)) ;;; <definitions of internal procedures> ;;; (define (dispatch m) ...) ;;; dispatch)) ;;; ;;; Complete the definition of make-queue and provide implementations of the ;;; queue operations using this representation. (define (make-queue) (let ([front-ptr '()] [rear-ptr '()]) (define (empty-queue?) (null? front-ptr)) (define (front-queue) (cond [(empty-queue?) (error "FRONT-QUEUE called with an empty queue")] [else (car front-ptr)])) (define (insert-queue! item) (let ([new-pair (cons item '())]) (cond [(empty-queue?) (set! front-ptr new-pair) (set! rear-ptr new-pair)] [else (set-cdr! rear-ptr new-pair) (set! rear-ptr new-pair)]))) (define (delete-queue!) (cond [(empty-queue?) (error "DELETE-QUEUE! called with an empty queue")] [else (set! front-ptr (cdr front-ptr))])) (define (dispatch m) (cond [(eq? m 'empty-queue?) empty-queue?] [(eq? m 'front-queue) front-queue] [(eq? m 'insert-queue!) insert-queue!] [(eq? m 'delete-queue!) delete-queue!] [else (error "Unknown message -- " m)])) dispatch)) (define q (make-queue)) ((q 'insert-queue!) 'a) ((q 'insert-queue!) 'b) ((q 'insert-queue!) 'c) (print q) (print ((q 'front-queue))) ((q 'delete-queue!)) (print ((q 'front-queue))) ((q 'delete-queue!)) (print ((q 'front-queue))) (print ((q 'empty-queue?))) ((q 'delete-queue!)) (print q) (print ((q 'empty-queue?)))
false
951911266dcf0c60721e87887047e2f526edb5c5
b66a38943027a0fbd94e1c454ef6744795b83ef5
/sxmpp_mod.scm
8a026ae7b77f49efa51d9005d9c42adb11e7b2eb
[]
no_license
macrofag/schemobot
4a75df45f846a297f096079be5f87634146615ad
b83236eb7cafe0dcaf8fe95c67e73e79acdb072f
refs/heads/master
2021-01-25T08:48:39.150126
2010-02-20T18:16:17
2010-02-20T18:16:17
527,673
1
0
null
null
null
null
UTF-8
Scheme
false
false
12,017
scm
sxmpp_mod.scm
;;; A basic XMPP library which should conform to RFCs 3920 and 3921 ;;; ;;; Copyright (C) 2009 FoAM vzw. ;;; ;;; This package 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 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 ;;; Lesser General Public License for more details. ;;; ;;; You can find a copy of the GNU Lesser General Public License at ;;; http://www.gnu.org/licenses/lgpl-3.0.html. ;;; ;;; Authors ;;; ;;; nik gaffney <[email protected]> ;;; ;;; Requirements ;;; ;;; PLT for now. TLS requires a version of PLT > 4.1.5.3 ;;; ;;; Commentary ;;; ;;; Still a long way from implementing even a minimal subset of XMPP ;;; ;;; features implemented ;;; - plaintext sessions on port 5222 ;;; - "old sytle" ssl sessions on port 5223 (default) ;;; - authenticate using an existing account ;;; - send messages (rfc 3921 sec.4) ;;; - send presence (rfc 3921 sec.5) ;;; - parse (some) xml reponses from server ;;; - handlers for responses ;;; ;;; features to implement ;;; - account creation ;;; - managing subscriptions (rfc 3921 sec.6) ;;; - rosters (rfc 3921 sec.7) ;;; - plaintext/tls/sasl negotiation (rfc 3920 sec.5 & 6) ;;; - encrypted connections using tls on port 5222 ;;; - correct namespaces in sxml ;;; - message types ;;; - maintain session ids ;;; - maintain threads ;;; - error handling ;;; - events ;;; - [...] ;;; - rfc 3920 ;;; - rfc 3921 ;;; ;;; bugs and/or improvements ;;; - PLaneT installable ;;; - 'send' using call/cc vs 'parameter' i/o ports ;;; - coroutines for sasl negotiation ;;; - read-async & repsonse-handler ;;; - ssax:xml->sxml or lazy:xml->sxml ;;; - default handlers ;;; - syntax for defining sxpath based handlers ;;; - improve parsing ;;; - chatbot exmples ;;; (module sxmpp_mod scheme (require (planet lizorkin/sxml:2:1/sxml)) ;; encoding xml (require (planet lizorkin/ssax:2:0/ssax)) ;; decoding xml (require mzlib/os) ;; hostname (require scheme/tcp) ;; networking (require openssl) ;; ssl/tls (require srfi/13) ;; jid decoding (provide (all-defined-out)) ;;;;;;;;;;; ; ;;;; ; ;;; ; ; ;; ; ;; ;; networking ;; ;;;;;; ;; ;; ; ; ; ; (define port 5222) (define ssl-port 5223) (define (open-connection machine port handler) (let-values (((in out) (tcp-connect machine port))) (handler in out) (close-output-port out) (close-input-port in))) (define (open-ssl-connection machine port handler) (let-values (((in out) (ssl-connect machine port 'tls))) (handler in out) (close-output-port out) (close-input-port in))) (define (read-async in) (bytes->string/utf-8 (list->bytes (read-async-bytes in)))) (define (read-async-bytes in) (let ((bstr '())) (when (sync/timeout 0 in) (set! bstr (cons (read-byte in) (read-async-bytes in)))) bstr)) (define ssxml srl:sxml->xml-noindent) ;;;;;; ; ; ; ; ;; ;;;;;; ; ;; ;; XMPP stanzas ;; ;;;;;;;;;; ;;; ; ;; ; ; ;; intialization (define (xmpp-stream host) (string-append "<?xml version='1.0'?><stream:stream xmlns:stream='http://etherx.jabber.org/streams' to='" host "' xmlns='jabber:client' >")) ;; version='1.0' is a MUST for SASL on 5222 but NOT for ssl on 5223 ;; authentication (define (xmpp-auth username password resource) (ssxml `(iq (@ (type "set") (id "auth")) (query (@ (xmlns "jabber:iq:auth")) (username ,username) (password ,password) (resource ,resource))))) (define (xmpp-session host) (ssxml `(iq (@ (to ,host) (type "set") (id "session")) (session (@ (xmlns "urn:ietf:params:xml:ns:xmpp-session")))))) ;; messages (define (message to body) (ssxml `(message (@ (to ,to)) (body ,body)))) ;; presence (define (presence #:from (from "") #:to (to "") #:type (type "") #:show (show "") #:status (status "")) (cond ((not (string=? status "")) (ssxml `(presence (@ (type "probe")) (status ,status)))) ((string=? type "") "<presence/>") (else (ssxml `(presence (@ (type ,type))))))) ;; queries (define (iq body #:from (from "") #:to (to "") #:type (type "") #:id (id "")) (ssxml `(iq (@ (to ,to) (type ,type) ,body)))) ;; curried stanza disection (sxml stanza -> string) (define ((sxpath-element xpath) stanza) (let ((node ((sxpath xpath) stanza))) (if (empty? node) "" (car node)))) ;; message (define message-from (sxpath-element "message/@from/text()")) (define message-to (sxpath-element "message/@to/text()")) (define message-id (sxpath-element "message/@id/text()")) (define message-type (sxpath-element "message/@type/text()")) (define message-body (sxpath-element "message/body/text()")) (define message-subject (sxpath-element "message/subject/text()")) ;; info/query (define iq-type (sxpath-element "iq/@type/text()")) (define iq-id (sxpath-element "iq/@id/text()")) (define iq-error-type (sxpath-element "iq/error/@type/text()")) (define iq-error-text (sxpath-element "iq/error/text()")) (define iq-error (sxpath-element "iq/error")) ;; presence (define presence-show (sxpath-element "presence/show/text()")) (define presence-from (sxpath-element "presence/@from/text()")) (define presence-status (sxpath-element "presence/status/text()")) ;;;;;;;;;; ; ; ; ;; ; ;; ;; rosters ;; ;;;;;; ; ;; ; ;;;; ;; ; ;;; ; ;; ;; tls & sasl ;; - http://xmpp.org/rfcs/rfc3920.html#tls ;; - http://xmpp.org/rfcs/rfc3920.html#sasl ;; ;;;; ;; (define session->tls? #f) ;; changes state when a tls proceed is recived ;; moved to xmpp-sasl until it 'works' ;;;;;;;;; ; ;; ; ; ;; ;; ; ; ;; ;; parsing & message/iq/error handlers ;; - minimal parsing ;; - handlers match on a tag (eg. 'message) ;; - handlers are called with a single relevant xmpp stanza ;; ;;;;;; ;; ; ; ;; ; (define xmpp-handlers (make-hash)) ;; a hash of tags and functions (possibly extend to using sxpaths) (define (set-xmpp-handler type fcn) (dict-set! xmpp-handlers type fcn)) (define (remove-xmpp-handler type fcn) (dict-remove! xmpp-handlers type fcn)) (define (run-xmpp-handler type sz) (let ((fcn (dict-ref xmpp-handlers type #f))) (when fcn (begin (display (format "attempting to run handler ~a.~%" fcn)) (fcn sz))))) ;; no real parsing yet. dispatches any received xml stanzas as sxml (define (parse-xmpp-response str) (when (> (string-length str) 0) (let ((sz (ssax:xml->sxml (open-input-string (clean str)) '()))) ;;(let ((sz (lazy:xml->sxml (open-input-string str) '()))) (cond ((equal? '(null) (cadr sz)) (newline)) ((equal? 'message (caadr sz)) (run-xmpp-handler 'message sz)) ((equal? 'iq (caadr sz)) (run-xmpp-handler 'iq sz)) ((equal? 'presence (caadr sz)) (run-xmpp-handler 'presence sz)) (else (run-xmpp-handler 'other sz)))))) (define (raw-xmpp-response str) (when (> (string-length str) 0) (let ((sz (ssax:xml->sxml (open-input-string (clean str)) '()))) ;;(let ((sz (lazy:xml->sxml (open-input-string str) '()))) sz))) ;; example handlers to print stanzas or their contents (define (print-message sz) (display (format "a ~a message from ~a which says '~a.'~%" (message-type sz) (message-from sz) (message-body sz)))) (define (print-iq sz) (display (format "an iq response of type '~a' with id '~a.'~%" (iq-type sz) (iq-id sz)))) (define (print-presence sz) (display (format " p-r-e-s-e-n-e-c--> ~a is ~a" (presence-from sz) (presence-status)))) (define (print-stanza sz) (display (format "? ?? -> ~%~a~%" sz))) ;; QND hack to filter out anything not a message, iq or presence (define (clean str) (let ((test (substring str 0 3))) (cond ((string-ci=? test "<me") str) ((string-ci=? test "<iq") str) ((string-ci=? test "<pr") str) ((string-ci=? test "<ur") str) (else (display (format "~%recieved: ~a ~%parsed as <null/>~%~%" str)) "<null/>")))) ;; response handler (define (xmpp-response-handler in) (thread (lambda () (let loop () (parse-xmpp-response (read-async in)) (sleep 0.1) ;; slight delay to avoid a tight loop (loop))))) ;; jid splicing (assuming the jid is in the format user@host/resource) (define (jid-user jid) (string-take jid (string-index jid #\@))) (define (jid-host jid) (let* ((s (string-take-right jid (- (string-length jid) (string-index jid #\@) 1))) (v (string-index s #\/))) (if v (string-take s v) s ))) (define (jid-resource jid) (let ((r (jid-resource-0 jid))) (if (void? r) (gethostname) r))) (define (jid-resource-0 jid) (let ((v (string-index jid #\/))) (when v (string-take-right jid (- (string-length jid) v 1))))) (define (cut-resource jid) (let ((v (string-index jid #\/))) (if v (string-take jid v) jid))) ;;;; ;; ; ; ;; ;; ;;;; ; ;; ;; interfaces ;; ;;;;; ;; ;;;; ; ;; ; (define xmpp-in-port (make-parameter (current-input-port))) (define xmpp-out-port (make-parameter (current-output-port))) (define (send str) (printf "sending iO: ~a ~%~%" str) (fprintf (xmpp-out-port) "~A~%" str) (flush-output (xmpp-out-port))) (define-syntax with-xmpp-ports (syntax-rules () ((_ jid pass (in out) form . forms) (let ((host (jid-host jid)) (user (jid-user jid)) (resource (jid-resource jid))) (let-values (((in out) (ssl-connect host ssl-port 'tls))) (parameterize ((xmpp-in-port in) (xmpp-out-port out)) (file-stream-buffer-mode out 'line) (send (xmpp-stream host)) (send (xmpp-session host)) (send (xmpp-auth user pass resource)) (send (presence)) (send (presence #:status "Available")) (begin form . forms) (close-output-port out) (close-input-port in))))))) (define-syntax with-xmpp-session (syntax-rules () ((_ jid pass form . forms) (let ((host (jid-host jid)) (user (jid-user jid)) (resource (jid-resource jid))) (let-values (((in out) (ssl-connect host ssl-port 'tls))) ;;(tcp-connect host port))) (parameterize ((xmpp-in-port in) (xmpp-out-port out)) (file-stream-buffer-mode out 'line) (xmpp-response-handler in) (send (xmpp-stream host)) (send (xmpp-session host)) ;(starttls in out) (send (xmpp-auth user pass resource)) (send (presence)) (send (presence #:status "Available")) (begin form . forms) (close-output-port out) (close-input-port in))))))) ) ;; end module
true
690db931ca9e27333b5d55f2f9df700be6ac07e7
2fc7c18108fb060ad1f8d31f710bcfdd3abc27dc
/attic/find-help-path.scm
486ed5c3e73846f4961ccb776e2d416d559b63a1
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-warranty-disclaimer", "CC0-1.0" ]
permissive
bakul/s9fes
97a529363f9a1614a85937a5ef9ed6685556507d
1d258c18dedaeb06ce33be24366932143002c89f
refs/heads/master
2023-01-24T09:40:47.434051
2022-10-08T02:11:12
2022-10-08T02:11:12
154,886,651
68
10
NOASSERTION
2023-01-25T17:32:54
2018-10-26T19:49:40
Scheme
UTF-8
Scheme
false
false
643
scm
find-help-path.scm
; Scheme 9 from Empty Space, Unix Function Library ; By Nils M Holm, 2010, 2018 ; In the public domain ; ; (find-help-path) ==> string | #f ; ; Returns the directory in which the online help pages are stored ; of #F when the pages cannot be located. ; ; (Example): (find-help-path) ==> "/usr/local/share/s9fes/help" (require-extension sys-unix) (define (find-help-path) (let loop ((dirs *library-path*)) (if (null? dirs) #f (let ((path (string-append (car dirs) "/help"))) (if (and (file-exists? path) (sys:stat-directory? path)) path (loop (cdr dirs)))))))
false
49d3101557ee58b742eb439602335c47a1462128
943e73b33b7bc61fee44808cbd18f91c7ed1db7a
/expand.scm
d9164caa25886c5a05db1237658b9853abb72dc5
[ "BSD-3-Clause" ]
permissive
opt9/chicken-scheme
a631d3fb455c61312e0c9d30d791c78a6d99a7f6
1eb14684c26b7c2250ca9b944c6b671cb62cafbc
refs/heads/master
2020-03-09T15:41:06.499607
2009-07-25T23:49:53
2009-07-25T23:49:53
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
55,843
scm
expand.scm
;;;; expand.scm ; ; Copyright (c) 2008-2009, The Chicken Team ; 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 author 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 HOLDERS 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. (declare (unit expand) (disable-interrupts) (fixnum) (hide match-expression macro-alias module-indirect-exports d dd dm dc map-se merge-se lookup check-for-redef) ) (set! ##sys#features (append '(#:hygienic-macros #:syntax-rules) ##sys#features)) (define (d arg1 . more) (when (##sys#fudge 13) (if (null? more) (pp arg1) (apply print arg1 more))) ) (define dd d) (define dm d) (define dc d) (cond-expand ((not debugbuild) (declare (no-bound-checks) (no-procedure-checks))) (else)) (begin (define-syntax dd (syntax-rules () ((_ . _) (void)))) (define-syntax dm (syntax-rules () ((_ . _) (void)))) (define-syntax dc (syntax-rules () ((_ . _) (void)))) ) ;;; Syntactic environments (define ##sys#current-environment (make-parameter '())) (define ##sys#current-meta-environment (make-parameter '())) (define (lookup id se) (cond ((assq id se) => cdr) ((##sys#get id '##core#macro-alias)) (else #f))) (define (macro-alias var se) (if (or (##sys#qualified-symbol? var) (let* ((str (##sys#slot var 1)) (len (##sys#size str))) (and (fx> len 0) (char=? #\# (##core#inline "C_subchar" str 0))))) var (let* ((alias (gensym var)) (ua (or (lookup var se) var))) (##sys#put! alias '##core#macro-alias ua) (##sys#put! alias '##core#real-name var) (dd "aliasing " alias " (real: " var ") to " (if (pair? ua) '<macro> ua)) alias) ) ) #+debugbuild (define (map-se se) (map (lambda (a) (cons (car a) (if (symbol? (cdr a)) (cdr a) '<macro>))) se)) (define (##sys#strip-syntax exp #!optional se alias) ;; if se is given, retain bound vars (let ((seen '())) (let walk ((x exp)) (cond ((assq x seen) => cdr) ((symbol? x) (let ((x2 (if se (lookup x se) (get x '##core#macro-alias) ) ) ) (cond ((get x '##core#real-name)) ((and alias (not (assq x se))) (##sys#alias-global-hook x #f)) ((not x2) x) ((pair? x2) x) (else x2)))) ((pair? x) (let ((cell (cons #f #f))) (set! seen (cons (cons x cell) seen)) (set-car! cell (walk (car x))) (set-cdr! cell (walk (cdr x))) cell)) ((vector? x) (let* ((len (##sys#size x)) (vec (make-vector len))) (set! seen (cons (cons x vec) seen)) (do ((i 0 (fx+ i 1))) ((fx>= i len) vec) (##sys#setslot vec i (##sys#slot x i))))) (else x))))) (define strip-syntax ##sys#strip-syntax) ;;; Macro handling (define ##sys#macro-environment (make-parameter '())) (define ##sys#chicken-macro-environment '()) ; used later in chicken.import.scm (define ##sys#chicken-ffi-macro-environment '()) ; used later in foreign.import.scm ; Workalike of '##sys#environment?' for syntactic environments (define (##sys#syntactic-environment? obj) (define (simple-environment? obj) (and (list? obj) (or (null? obj) (simple-environment-entry? (car obj)) #; ;enough already (call-with-current-continuation (lambda (return) (##sys#for-each (lambda (x) (unless (simple-environment-entry? x) (return #f) ) ) obj) #t ) ) ) ) ) (define (simple-environment-entry? obj) (and (pair? obj) (symbol? (car obj)) (symbol? (cdr obj)) ) ) (define (macro-environment? obj) (and (list? obj) (or (null? obj) (macro-environment-entry? (car obj)) #; ;enough already (call-with-current-continuation (lambda (return) (##sys#for-each (lambda (x) (unless (macro-environment-entry? x) (return #f) ) ) obj) #t ) ) ) ) ) (define (macro-environment-entry? obj) (and (pair? obj) (= 3 (length obj)) (symbol? (car obj)) (list? (cadr obj)) #;(##sys#syntactic-environment? (cadr x)) ;enough already (procedure? (caddr obj)) ) ) (or (simple-environment? obj) (macro-environment? obj) ) ) ; Workalike of '##sys#environment-symbols' for syntactic environments ; (I think :-) (define (##sys#syntactic-environment-symbols env pred) (define (try-alias id) (or (##sys#get id '##core#real-name) (let ((alias (##sys#get id '##core#macro-alias))) (cond ((not alias) id) ((pair? alias) id) (else alias) ) ) ) ) (let ((syms '())) (##sys#for-each (lambda (cell) (let ((id (car cell))) (cond ((pred id) (set! syms (cons id syms)) ) ((try-alias id) => (lambda (name) (when (pred name) (set! syms (cons name syms))) ) ) ) ) ) env) syms ) ) (define (##sys#extend-macro-environment name se handler) (let ((me (##sys#macro-environment))) (cond ((lookup name me) => (lambda (a) (set-car! a se) (set-car! (cdr a) handler) ) ) (else (##sys#macro-environment (cons (list name se handler) me)))))) (define (##sys#copy-macro old new) (let ((def (lookup old (##sys#macro-environment)))) (apply ##sys#extend-macro-environment new def) ) ) (define (##sys#macro? sym #!optional (senv (##sys#current-environment))) (or (let ((l (lookup sym senv))) (pair? l)) (and-let* ((l (lookup sym (##sys#macro-environment)))) (pair? l)))) (define (##sys#unregister-macro name) (##sys#macro-environment ;; this builds up stack, but isn't used often anyway... (let loop ((me (##sys#macro-environment)) (me2 '())) (cond ((null? me) '()) ((eq? name (caar me)) (cdr me)) (else (cons (car me) (loop (cdr me)))))))) (define (##sys#undefine-macro! name) (##sys#unregister-macro name) ) ;; The basic macro-expander (define (##sys#expand-0 exp dse cs?) (define (call-handler name handler exp se cs) (dd "invoking macro: " name) (dd `(STATIC-SE: ,@(map-se se))) (handle-exceptions ex ;; modify error message in condition object to include ;; currently expanded macro-name (##sys#abort (if (and (##sys#structure? ex 'condition) (memv 'exn (##sys#slot ex 1)) ) (##sys#make-structure 'condition (##sys#slot ex 1) (let copy ([ps (##sys#slot ex 2)]) (if (null? ps) '() (let ([p (car ps)] [r (cdr ps)]) (if (and (equal? '(exn . message) p) (pair? r) (string? (car r)) ) (cons '(exn . message) (cons (string-append "during expansion of (" (##sys#slot name 1) " ...) - " (car r) ) (cdr r) ) ) (copy r) ) ) ) ) ) ex) ) (let ((exp2 (if cs (fluid-let ((##sys#syntax-rules-mismatch (lambda (input) exp))) ; a bit of a hack (handler exp se dse)) (handler exp se dse))) ) (when (and (not cs) (eq? exp exp2)) (##sys#syntax-error-hook (string-append "syntax transformer for `" (symbol->string name) "' returns original form, which would result in endless expansion") exp)) (dd `(,name --> ,exp2)) exp2))) (define (expand head exp mdef) (dd `(EXPAND: ,head ,(cond ((get head '##core#macro-alias) => (lambda (a) (if (symbol? a) a '<macro>)) ) (else '_)) ,exp ,(if (pair? mdef) `(SE: ,@(map-se (car mdef))) mdef))) (cond ((not (list? exp)) (##sys#syntax-error-hook "invalid syntax in macro form" exp) ) ((pair? mdef) (values ;; force ref. opaqueness by passing dynamic se [what is this comment meaning? I forgot] (call-handler head (cadr mdef) exp (car mdef) #f) #t)) (else (values exp #f)) ) ) (let loop ((exp exp)) (if (pair? exp) (let ((head (car exp)) (body (cdr exp)) ) (if (symbol? head) (let ((head2 (or (lookup head dse) head))) (unless (pair? head2) (set! head2 (or (lookup head2 (##sys#macro-environment)) head2)) ) (cond [(memq head2 '(let ##core#let)) (##sys#check-syntax 'let body '#(_ 2) #f dse) (let ([bindings (car body)]) (cond [(symbol? bindings) ; expand named let (##sys#check-syntax 'let body '(_ #((variable _) 0) . #(_ 1)) #f dse) (let ([bs (cadr body)]) (values `(##core#app (##core#letrec ([,bindings (##core#loop-lambda ,(map (lambda (b) (car b)) bs) ,@(cddr body))]) ,bindings) ,@(##sys#map cadr bs) ) #t) ) ] [else (values exp #f)] ) ) ] [(and (memq head2 '(set! ##core#set!)) ; "setter" syntax (pair? body) (pair? (car body)) ) (let ([dest (car body)]) (##sys#check-syntax 'set! body '(#(_ 1) _) #f dse) (values (append (list (list '##sys#setter (car dest))) (cdr dest) (cdr body) ) #t) ) ] ((and cs? (symbol? head2) (##sys#get head2 '##compiler#compiler-syntax)) => (lambda (cs) (let ((result (call-handler head (car cs) exp (cdr cs) #t))) (cond ((eq? result exp) (expand head exp head2)) (else (when ##sys#compiler-syntax-hook (##sys#compiler-syntax-hook head result)) (loop result)))))) [else (expand head exp head2)] ) ) (values exp #f) ) ) (values exp #f) ) ) ) (define ##sys#compiler-syntax-hook #f) (define ##sys#enable-runtime-macros #f) (define (##sys#module-rename sym prefix) (##sys#string->symbol (string-append (##sys#slot prefix 1) "#" (##sys#slot sym 1) ) ) ) (define (##sys#alias-global-hook sym assign) (define (mrename sym) (cond ((##sys#current-module) => (lambda (mod) (dm "(ALIAS) global alias " sym " in " (module-name mod)) (unless assign (##sys#register-undefined sym mod)) (##sys#module-rename sym (module-name mod)))) (else sym))) (cond ((##sys#qualified-symbol? sym) sym) ((##sys#get sym '##core#primitive) => (lambda (p) (dm "(ALIAS) primitive: " p) p)) ((##sys#get sym '##core#aliased) (dm "(ALIAS) marked: " sym) sym) ((assq sym (##sys#current-environment)) => (lambda (a) (dm "(ALIAS) in current environment: " sym) (let ((sym2 (cdr a))) (if (pair? sym2) ; macro (*** can this be?) (mrename sym) (or (##sys#get sym2 '##core#primitive) sym2))))) (else (mrename sym)))) ;;; User-level macroexpansion (define (##sys#expand exp #!optional (se (##sys#current-environment)) cs?) (let loop ((exp exp)) (let-values (((exp2 m) (##sys#expand-0 exp se cs?))) (if m (loop exp2) exp2) ) ) ) (define expand ##sys#expand) ;;; Extended (DSSSL-style) lambda lists ; ; Assumptions: ; ; 1) #!rest must come before #!key ; 2) default values may refer to earlier variables ; 3) optional/key args may be either variable or (variable default) ; 4) an argument marker may not be specified more than once ; 5) no special handling of extra keywords (no error) ; 6) default value of optional/key args is #f ; 7) mixing with dotted list syntax is allowed (define (##sys#extended-lambda-list? llist) (let loop ([llist llist]) (and (pair? llist) (case (##sys#slot llist 0) [(#!rest #!optional #!key) #t] [else (loop (cdr llist))] ) ) ) ) (define ##sys#expand-extended-lambda-list (let ([reverse reverse] [gensym gensym] ) (lambda (llist0 body errh se) (define (err msg) (errh msg llist0)) (define (->keyword s) (string->keyword (##sys#slot s 1))) (let ([rvar #f] [hasrest #f] (%let* (macro-alias 'let* se)) (%lambda '##core#lambda) (%opt (macro-alias 'optional se)) (%let-optionals (macro-alias 'let-optionals se)) (%let-optionals* (macro-alias 'let-optionals* se)) (%let (macro-alias 'let se))) (let loop ([mode 0] ; req=0, opt=1, rest=2, key=3, end=4 [req '()] [opt '()] [key '()] [llist llist0] ) (cond [(null? llist) (values (if rvar (##sys#append (reverse req) rvar) (reverse req)) (let ([body (if (null? key) body `((,%let* ,(map (lambda (k) (let ([s (car k)]) `(,s (##sys#get-keyword ',(->keyword s) ,rvar ,@(if (pair? (cdr k)) `((,%lambda () ,@(cdr k))) '() ) ) ) ) ) (reverse key) ) ,@body) ) ) ] ) (cond [(null? opt) body] [(and (not hasrest) (null? key) (null? (cdr opt))) `((,%let ([,(caar opt) (,%opt ,rvar ,(cadar opt))]) ,@body) ) ] [(and (not hasrest) (null? key)) `((,%let-optionals ,rvar ,(reverse opt) ,@body))] [else `((,%let-optionals* ,rvar ,(##sys#append (reverse opt) (list (or hasrest rvar))) ,@body))] ) ) ) ] [(symbol? llist) (if (fx> mode 2) (err "rest argument list specified more than once") (begin (unless rvar (set! rvar llist)) (set! hasrest llist) (loop 4 req opt '() '()) ) ) ] [(not (pair? llist)) (err "invalid lambda list syntax") ] [else (let* ((var (car llist)) (x (or (and (symbol? var) (not (eq? 3 mode)) (lookup var se)) var)) (r (cdr llist))) (case x [(#!optional) (unless rvar (set! rvar (macro-alias 'tmp se))) (if (eq? mode 0) (loop 1 req '() '() r) (err "`#!optional' argument marker in wrong context") ) ] [(#!rest) (if (fx<= mode 1) (if (and (pair? r) (symbol? (car r))) (begin (if (not rvar) (set! rvar (car r))) (set! hasrest (car r)) (loop 2 req opt '() (cdr r)) ) (err "invalid syntax of `#!rest' argument") ) (err "`#!rest' argument marker in wrong context") ) ] [(#!key) (if (not rvar) (set! rvar (macro-alias 'tmp se))) (if (fx<= mode 3) (loop 3 req opt '() r) (err "`#!key' argument marker in wrong context") ) ] [else (cond [(symbol? var) (case mode [(0) (loop 0 (cons var req) '() '() r)] [(1) (loop 1 req (cons (list var #f) opt) '() r)] [(2) (err "invalid lambda list syntax after `#!rest' marker")] [else (loop 3 req opt (cons (list var) key) r)] ) ] [(and (list? var) (eq? 2 (length var))) (case mode [(0) (err "invalid required argument syntax")] [(1) (loop 1 req (cons var opt) '() r)] [(2) (err "invalid lambda list syntax after `#!rest' marker")] [else (loop 3 req opt (cons var key) r)] ) ] [else (err "invalid lambda list syntax")] ) ] ) ) ] ) ) ) ) ) ) ;;; Expansion of bodies (and internal definitions) (define ##sys#canonicalize-body (let ([reverse reverse] [map map] ) (lambda (body #!optional (se (##sys#current-environment)) cs?) (define (fini vars vals mvars mvals body) (if (and (null? vars) (null? mvars)) (let loop ([body2 body] [exps '()]) (if (not (pair? body2)) (cons '##core#begin body) ; no more defines, otherwise we would have called `expand' (let ([x (car body2)]) (if (and (pair? x) (let ((d (car x))) (and (symbol? d) (or (eq? (or (lookup d se) d) 'define) (eq? (or (lookup d se) d) 'define-values)))) ) (cons '##core#begin (##sys#append (reverse exps) (list (expand body2)))) (loop (cdr body2) (cons x exps)) ) ) ) ) (let* ((vars (reverse vars)) (result `(##core#let ,(##sys#map (lambda (v) (##sys#list v (##sys#list '##core#undefined))) (apply ##sys#append vars mvars) ) ,@(map (lambda (v x) `(##core#set! ,v ,x)) vars (reverse vals)) ,@(map (lambda (vs x) (let ([tmps (##sys#map gensym vs)]) `(##sys#call-with-values (##core#lambda () ,x) (##core#lambda ,tmps ,@(map (lambda (v t) `(##core#set! ,v ,t)) vs tmps) ) ) ) ) (reverse mvars) (reverse mvals) ) ,@body) ) ) (dd `(BODY: ,result)) result))) (define (fini/syntax vars vals mvars mvals body) (fini vars vals mvars mvals (let loop ((body body) (defs '()) (done #f)) (cond (done `((,(macro-alias 'letrec-syntax se) ,(map cdr (reverse defs)) ,@body) )) ((not (pair? body)) (loop body defs #t)) ((and (list? (car body)) (>= 3 (length (car body))) (symbol? (caar body)) (eq? 'define-syntax (or (lookup (caar body) se) (caar body)))) (let ((def (car body))) (loop (cdr body) (cons (if (pair? (cadr def)) `(define-syntax ,(caadr def) (,(macro-alias 'lambda se) ,(cdadr def) ,@(cddr def))) def) defs) #f))) (else (loop body defs #t)))))) (define (expand body) (let loop ([body body] [vars '()] [vals '()] [mvars '()] [mvals '()]) (if (not (pair? body)) (fini vars vals mvars mvals body) (let* ((x (car body)) (rest (cdr body)) (exp1 (and (pair? x) (car x))) (head (and exp1 (symbol? exp1) (or (lookup exp1 se) exp1)))) (cond [(not (symbol? head)) (fini vars vals mvars mvals body)] [(eq? 'define head) (##sys#check-syntax 'define x '(define _ . #(_ 0)) #f se) (let loop2 ([x x]) (let ([head (cadr x)]) (cond [(not (pair? head)) (##sys#check-syntax 'define x '(define variable . #(_ 0)) #f se) (loop rest (cons head vars) (cons (if (pair? (cddr x)) (caddr x) '(##core#undefined) ) vals) mvars mvals) ] [(pair? (car head)) (##sys#check-syntax 'define x '(define (_ . lambda-list) . #(_ 1)) #f se) (loop2 (cons (macro-alias 'define se) (##sys#expand-curried-define head (cddr x) se))) ] [else (##sys#check-syntax 'define x '(define (variable . lambda-list) . #(_ 1)) #f se) (loop rest (cons (car head) vars) (cons `(##core#lambda ,(cdr head) ,@(cddr x)) vals) mvars mvals) ] ) ) ) ] ((eq? 'define-syntax head) (##sys#check-syntax 'define-syntax x '(define-syntax _ . #(_ 1)) se) (fini/syntax vars vals mvars mvals body) ) [(eq? 'define-values head) (##sys#check-syntax 'define-values x '(define-values #(_ 0) _) #f se) (loop rest vars vals (cons (cadr x) mvars) (cons (caddr x) mvals)) ] [(eq? 'begin head) (##sys#check-syntax 'begin x '(begin . #(_ 0)) #f se) (loop (##sys#append (cdr x) rest) vars vals mvars mvals) ] ((or (memq head vars) (memq head mvars)) (fini vars vals mvars mvals body)) [else (let ([x2 (##sys#expand-0 x se cs?)]) (if (eq? x x2) (fini vars vals mvars mvals body) (loop (cons x2 rest) vars vals mvars mvals) ) ) ] ) ) ) ) ) (expand body) ) ) ) ;;; A simple expression matcher (define match-expression (lambda (exp pat vars) (let ((env '())) (define (mwalk x p) (cond ((not (pair? p)) (cond ((assq p env) => (lambda (a) (equal? x (cdr a)))) ((memq p vars) (set! env (cons (cons p x) env)) #t) (else (eq? x p)) ) ) ((pair? x) (and (mwalk (car x) (car p)) (mwalk (cdr x) (cdr p)) ) ) (else #f) ) ) (and (mwalk exp pat) env) ) ) ) ;;; Expand "curried" lambda-list syntax for `define' (define (##sys#expand-curried-define head body se) (let ((name #f)) (define (loop head body) (if (symbol? (car head)) (begin (set! name (car head)) `(##core#lambda ,(cdr head) ,@body) ) (loop (car head) `((##core#lambda ,(cdr head) ,@body)) ) )) (let ([exp (loop head body)]) (list name exp) ) ) ) ;;; General syntax checking routine: (define ##sys#line-number-database #f) (define ##sys#syntax-error-culprit #f) (define (##sys#syntax-error-hook . args) (apply ##sys#signal-hook #:syntax-error (##sys#strip-syntax args))) (define syntax-error ##sys#syntax-error-hook) (define (##sys#syntax-rules-mismatch input) (##sys#syntax-error-hook "no rule matches form" input)) (define (get-line-number sexp) (and ##sys#line-number-database (pair? sexp) (let ([head (car sexp)]) (and (symbol? head) (cond [(##sys#hash-table-ref ##sys#line-number-database head) => (lambda (pl) (let ([a (assq sexp pl)]) (and a (cdr a)) ) ) ] [else #f] ) ) ) ) ) (define ##sys#check-syntax (let ([string-append string-append] [keyword? keyword?] [get-line-number get-line-number] [symbol->string symbol->string] ) (lambda (id exp pat #!optional culprit (se (##sys#current-environment))) (define (test x pred msg) (unless (pred x) (err msg)) ) (define (err msg) (let* ([sexp ##sys#syntax-error-culprit] [ln (get-line-number sexp)] ) (##sys#syntax-error-hook (if ln (string-append "(" (symbol->string id) ") in line " (number->string ln) " - " msg) (string-append "(" (symbol->string id) ") " msg) ) exp) ) ) (define (lambda-list? x) (or (##sys#extended-lambda-list? x) (let loop ((x x)) (cond ((null? x)) ((symbol? x) (not (keyword? x))) ((pair? x) (let ((s (car x))) (and (symbol? s) (loop (cdr x)) ) ) ) (else #f) ) ) ) ) (define (proper-list? x) (let loop ((x x)) (cond ((eq? x '())) ((pair? x) (loop (cdr x))) (else #f) ) ) ) (when culprit (set! ##sys#syntax-error-culprit culprit)) (let walk ((x exp) (p pat)) (cond ((vector? p) (let* ((p2 (vector-ref p 0)) (vlen (##sys#size p)) (min (if (fx> vlen 1) (vector-ref p 1) 0) ) (max (cond ((eq? vlen 1) 1) ((fx> vlen 2) (vector-ref p 2)) (else 99999) ) ) ) (do ((x x (cdr x)) (n 0 (fx+ n 1)) ) ((eq? x '()) (if (fx< n min) (err "not enough arguments") ) ) (cond ((fx>= n max) (err "too many arguments") ) ((not (pair? x)) (err "not a proper list") ) (else (walk (car x) p2) ) ) ) ) ) ((##sys#immediate? p) (if (not (eq? p x)) (err "unexpected object")) ) ((symbol? p) (case p ((_) #t) ((pair) (test x pair? "pair expected")) ((variable) (test x symbol? "identifier expected")) ((symbol) (test x symbol? "symbol expected")) ((list) (test x proper-list? "proper list expected")) ((number) (test x number? "number expected")) ((string) (test x string? "string expected")) ((lambda-list) (test x lambda-list? "lambda-list expected")) (else (test x (lambda (y) (let ((y2 (and (symbol? y) (lookup y se)))) (eq? (if (symbol? y2) y2 y) p))) "missing keyword")) ) ) ((not (pair? p)) (err "incomplete form") ) ((not (pair? x)) (err "pair expected")) (else (walk (car x) (car p)) (walk (cdr x) (cdr p)) ) ) ) ) ) ) ;;; explicit-renaming transformer (define (er-macro-transformer x) x) (define ((##sys#er-transformer handler) form se dse) (let ((renv '())) ; keep rename-environment for this expansion (define (rename sym) (cond ((assq sym renv) => (lambda (a) (dd `(RENAME/RENV: ,sym --> ,(cdr a))) (cdr a))) ((lookup sym se) => (lambda (a) (cond ((symbol? a) (dd `(RENAME/LOOKUP: ,sym --> ,a)) a) (else (let ((a2 (macro-alias sym se))) (dd `(RENAME/LOOKUP/MACRO: ,sym --> ,a2)) (set! renv (cons (cons sym a2) renv)) a2))))) (else (let ((a (macro-alias sym se))) (dd `(RENAME: ,sym --> ,a)) (set! renv (cons (cons sym a) renv)) a)))) (define (compare s1 s2) (let ((result (if (and (symbol? s1) (symbol? s2)) (let ((ss1 (or (##sys#get s1 '##core#macro-alias) (lookup2 1 s1 dse) s1) ) (ss2 (or (##sys#get s2 '##core#macro-alias) (lookup2 2 s2 dse) s2) ) ) (cond ((symbol? ss1) (cond ((symbol? ss2) (eq? (or (##sys#get ss1 '##core#primitive) ss1) (or (##sys#get ss2 '##core#primitive) ss2))) ((assq ss1 (##sys#macro-environment)) => (lambda (a) (eq? (cdr a) ss2))) (else #f) ) ) ((symbol? ss2) (cond ((assq ss2 (##sys#macro-environment)) => (lambda (a) (eq? ss1 (cdr a)))) (else #f))) (else (eq? ss1 ss2)))) (eq? s1 s2))) ) (dd `(COMPARE: ,s1 ,s2 --> ,result)) result)) (define (lookup2 n sym dse) (let ((r (lookup sym dse))) (dd " (lookup/DSE " (list n) ": " sym " --> " (if (and r (pair? r)) '<macro> r) ")") r)) (handler form rename compare) ) ) ;;; Macro definitions: (define (##sys#expand-import x r c import-env macro-env meta? loc) (let ((%only (r 'only)) (%rename (r 'rename)) (%except (r 'except)) (%prefix (r 'prefix))) (define (resolve sym) (or (lookup sym '()) sym)) ;*** empty se? (define (tostr x) (cond ((string? x) x) ((keyword? x) (##sys#string-append (##sys#symbol->string x) ":")) ; why not? ((symbol? x) (##sys#symbol->string x)) ((number? x) (number->string x)) (else (syntax-error loc "invalid prefix" )))) (define (import-name spec) (let* ((mname (resolve spec)) (mod (##sys#find-module mname #f))) (unless mod (let ((il (##sys#find-extension (string-append (symbol->string mname) ".import") #t))) (cond (il (parameterize ((##sys#current-module #f) (##sys#current-environment '()) (##sys#current-meta-environment (##sys#current-meta-environment)) (##sys#macro-environment (##sys#meta-macro-environment))) (##sys#load il #f #f)) (set! mod (##sys#find-module mname))) (else (syntax-error loc "cannot import from undefined module" mname))))) (let ((vexp (module-vexports mod)) (sexp (module-sexports mod))) (cons vexp sexp)))) (define (import-spec spec) (cond ((symbol? spec) (import-name spec)) ((or (not (list? spec)) (< (length spec) 2)) (syntax-error loc "invalid import specification" spec)) (else (let* ((s (car spec)) (imp (import-spec (cadr spec))) (impv (car imp)) (imps (cdr imp))) (cond ((c %only (car spec)) (##sys#check-syntax loc spec '(_ _ . #(symbol 0))) (let ((ids (map resolve (cddr spec)))) (let loop ((ids ids) (v '()) (s '())) (cond ((null? ids) (cons v s)) ((assq (car ids) impv) => (lambda (a) (loop (cdr ids) (cons a v) s))) ((assq (car ids) imps) => (lambda (a) (loop (cdr ids) v (cons a s)))) (else (loop (cdr ids) v s)))))) ((c %except (car spec)) (##sys#check-syntax loc spec '(_ _ . #(symbol 0))) (let ((ids (map resolve (cddr spec)))) (let loop ((impv impv) (v '())) (cond ((null? impv) (let loop ((imps imps) (s '())) (cond ((null? imps) (cons v s)) ((memq (caar imps) ids) (loop (cdr imps) s)) (else (loop (cdr imps) (cons (car imps) s)))))) ((memq (caar impv) ids) (loop (cdr impv) v)) (else (loop (cdr impv) (cons (car impv) v))))))) ((c %rename (car spec)) (##sys#check-syntax loc spec '(_ _ . #((symbol symbol) 0))) (let loop ((impv impv) (imps imps) (v '()) (s '()) (ids (cddr spec))) (cond ((null? impv) (cond ((null? imps) (for-each (lambda (id) (##sys#warn "renamed identifier not imported" id) ) ids) (cons v s)) ((assq (caar imps) ids) => (lambda (a) (loop impv (cdr imps) v (cons (cons (cadr a) (cdar imps)) s) (##sys#delq a ids)))) (else (loop impv (cdr imps) v (cons (car imps) s) ids)))) ((assq (caar impv) ids) => (lambda (a) (loop (cdr impv) imps (cons (cons (cadr a) (cdar impv)) v) s (##sys#delq a ids)))) (else (loop (cdr impv) imps (cons (car impv) v) s ids))))) ((c %prefix (car spec)) (##sys#check-syntax loc spec '(_ _ _)) (let ((pref (tostr (caddr spec)))) (define (ren imp) (cons (##sys#string->symbol (##sys#string-append pref (##sys#symbol->string (car imp))) ) (cdr imp) ) ) (cons (map ren impv) (map ren imps)))) (else (syntax-error loc "invalid import specification" spec))))))) (##sys#check-syntax loc x '(_ . #(_ 1))) (let ((cm (##sys#current-module))) (when cm ;; save import form (if meta? (set-module-meta-import-forms! cm (append (module-meta-import-forms cm) (cdr x))) (set-module-import-forms! cm (append (module-import-forms cm) (cdr x))))) (for-each (lambda (spec) (let* ((vs (import-spec spec)) (vsv (car vs)) (vss (cdr vs))) (dd `(IMPORT: ,loc)) (dd `(V: ,(if cm (module-name cm) '<toplevel>) ,(map-se vsv))) (dd `(S: ,(if cm (module-name cm) '<toplevel>) ,(map-se vss))) (##sys#mark-imported-symbols vsv) ; mark imports as ##core#aliased (for-each (lambda (imp) (let ((id (car imp)) (aid (cdr imp))) (and-let* ((a (assq id (import-env))) ((not (eq? aid (cdr a))))) (##sys#warn "re-importing already imported identifier" id)))) vsv) (for-each (lambda (imp) (and-let* ((a (assq (car imp) (macro-env))) ((not (eq? (cdr imp) (cdr a))))) (##sys#warn "re-importing already imported syntax" (car imp))) ) vss) (import-env (append vsv (import-env))) (macro-env (append vss (macro-env))))) (cdr x)) '(##core#undefined)))) (##sys#extend-macro-environment 'import '() (##sys#er-transformer (cut ##sys#expand-import <> <> <> ##sys#current-environment ##sys#macro-environment #f 'import) ) ) (##sys#extend-macro-environment 'import-for-syntax '() (##sys#er-transformer (cut ##sys#expand-import <> <> <> ##sys#current-meta-environment ##sys#meta-macro-environment #t 'import-for-syntax) ) ) (define ##sys#initial-macro-environment (##sys#macro-environment)) (##sys#extend-macro-environment 'define '() (##sys#er-transformer (lambda (form r c) (let loop ((form (cdr form))) (let ((head (car form)) (body (cdr form)) ) (cond ((not (pair? head)) (##sys#check-syntax 'define head 'symbol) (##sys#check-syntax 'define body '#(_ 0 1)) (##sys#register-export head (##sys#current-module)) `(##core#set! ,head ,(if (pair? body) (car body) '(##core#undefined))) ) ((pair? (car head)) (##sys#check-syntax 'define head '(_ . lambda-list)) (##sys#check-syntax 'define body '#(_ 1)) (loop (##sys#expand-curried-define head body '())) ) ;*** '() should be se (else (##sys#check-syntax 'define head '(symbol . lambda-list)) (##sys#check-syntax 'define body '#(_ 1)) (##sys#register-export (car head) (##sys#current-module)) `(##core#set! ,(car head) (,(r 'lambda) ,(cdr head) ,@body))) ) ) ) ) ) ) (##sys#extend-macro-environment 'and '() (##sys#er-transformer (lambda (form r c) (let ((body (cdr form))) (if (null? body) #t (let ((rbody (cdr body)) (hbody (car body)) ) (if (null? rbody) hbody `(,(r 'if) ,hbody (,(r 'and) ,@rbody) #f) ) ) ) ) ) ) ) (##sys#extend-macro-environment 'or '() (##sys#er-transformer (lambda (form r c) (let ((body (cdr form))) (if (null? body) #f (let ((rbody (cdr body)) (hbody (car body))) (if (null? rbody) hbody (let ((tmp (r 'tmp))) `(,(r 'let) ((,tmp ,hbody)) (,(r 'if) ,tmp ,tmp (,(r 'or) ,@rbody)) ) ) ) ) ) ) ) ) ) (##sys#extend-macro-environment 'cond '() (##sys#er-transformer (lambda (form r c) (let ((body (cdr form)) (%let (r 'let)) (%if (r 'if)) (%=> (r '=>)) (%or (r 'or)) (%else (r 'else)) (%lambda (r 'lambda))) (let expand ((clauses body)) (if (not (pair? clauses)) '(##core#undefined) (let ((clause (car clauses)) (rclauses (cdr clauses)) ) (##sys#check-syntax 'cond clause '#(_ 1)) (cond ((c %else (car clause)) `(##core#begin ,@(cdr clause))) ((null? (cdr clause)) `(,%or ,(car clause) ,(expand rclauses))) ((c %=> (cadr clause)) (let ((tmp (r 'tmp))) `(,%let ((,tmp ,(car clause))) (,%if ,tmp (,(caddr clause) ,tmp) ,(expand rclauses) ) ) ) ) ((and (list? clause) (fx= (length clause) 4) (c %=> (caddr clause))) (let ((tmp (r 'tmp))) `(##sys#call-with-values (,%lambda () ,(car clause)) (,%lambda ,tmp (if (##sys#apply ,(cadr clause) ,tmp) (##sys#apply ,(cadddr clause) ,tmp) ,(expand rclauses) ) ) ) ) ) (else `(,%if ,(car clause) (##core#begin ,@(cdr clause)) ,(expand rclauses) ) ) ) ) ) ) ) ) )) (##sys#extend-macro-environment 'case '() (##sys#er-transformer (lambda (form r c) (##sys#check-syntax 'case form '(_ _ . #(_ 0))) (let ((exp (cadr form)) (body (cddr form)) ) (let ((tmp (r 'tmp)) (%if (r 'if)) (%or (r 'or)) (%else (r 'else))) `(let ((,tmp ,exp)) ,(let expand ((clauses body)) (if (not (pair? clauses)) '(##core#undefined) (let ((clause (car clauses)) (rclauses (cdr clauses)) ) (##sys#check-syntax 'case clause '#(_ 1)) (if (c %else (car clause)) `(##core#begin ,@(cdr clause)) `(,%if (,%or ,@(##sys#map (lambda (x) `(##sys#eqv? ,tmp ',x)) (car clause))) (##core#begin ,@(cdr clause)) ,(expand rclauses) ) ) ) ) ) ) ) ) ) ) ) (##sys#extend-macro-environment 'let* '() (##sys#er-transformer (lambda (form r c) (##sys#check-syntax 'let* form '(_ #((symbol _) 0) . #(_ 1))) (let ((bindings (cadr form)) (body (cddr form)) (%let (r 'let))) (let expand ((bs bindings)) (if (eq? bs '()) `(,%let () ,@body) `(,%let (,(car bs)) ,(expand (cdr bs))) ) ) ) ) ) ) (##sys#extend-macro-environment 'do '() (##sys#er-transformer (lambda (form r c) (##sys#check-syntax 'do form '(_ #((symbol _ . #(_)) 0) . #(_ 1))) (let ((bindings (cadr form)) (test (caddr form)) (body (cdddr form)) (dovar (r 'doloop)) (%let (r 'let)) (%if (r 'if))) `(,%let ,dovar ,(##sys#map (lambda (b) (list (car b) (car (cdr b)))) bindings) (,%if ,(car test) ,(let ((tbody (cdr test))) (if (eq? tbody '()) '(##core#undefined) `(##core#begin ,@tbody) ) ) (##core#begin ,(if (eq? body '()) '(##core#undefined) `(,%let () ,@body) ) (##core#app ,dovar ,@(##sys#map (lambda (b) (if (eq? (cdr (cdr b)) '()) (car b) (car (cdr (cdr b))) ) ) bindings) ) ) ) ) ) ) ) ) (##sys#extend-macro-environment 'quasiquote '() (##sys#er-transformer (lambda (form r c) (let ((%quote (r 'quote)) (%quasiquote (r 'quasiquote)) (%unquote (r 'unquote)) (%unquote-splicing (r 'unquote-splicing))) (define (walk x n) (simplify (walk1 x n))) (define (walk1 x n) (cond ((vector? x) `(##sys#list->vector ,(walk (vector->list x) n)) ) ((not (pair? x)) `(,%quote ,x)) (else (let ((head (car x)) (tail (cdr x))) (cond ((c %unquote head) (if (pair? tail) (let ((hx (car tail))) (if (eq? n 0) hx (list '##sys#list `(,%quote ,%unquote) (walk hx (fx- n 1)) ) ) ) `(,%quote ,%unquote) ) ) ((c %quasiquote head) (if (pair? tail) `(##sys#list (,%quote ,%quasiquote) ,(walk (car tail) (fx+ n 1)) ) (list '##sys#cons (list %quote %quasiquote) (walk tail n)) ) ) ((pair? head) (let ((hx (car head)) (tx (cdr head))) (if (and (c hx %unquote-splicing) (pair? tx)) (let ((htx (car tx))) (if (eq? n 0) `(##sys#append ,htx ,(walk tail n) ) `(##sys#cons (##sys#list %unquote-splicing ,(walk htx (fx- n 1)) ) ,(walk tail n) ) ) ) `(##sys#cons ,(walk head n) ,(walk tail n)) ) ) ) (else `(##sys#cons ,(walk head n) ,(walk tail n)) ) ) ) ) ) ) (define (simplify x) (cond ((match-expression x '(##sys#cons a '()) '(a)) => (lambda (env) (simplify `(##sys#list ,(##sys#slot (assq 'a env) 1)))) ) ((match-expression x '(##sys#cons a (##sys#list . b)) '(a b)) => (lambda (env) (let ([bxs (assq 'b env)]) (if (fx< (length bxs) 32) (simplify `(##sys#list ,(##sys#slot (assq 'a env) 1) ,@(cdr bxs) ) ) x) ) ) ) ((match-expression x '(##sys#append a '()) '(a)) => (lambda (env) (##sys#slot (assq 'a env) 1)) ) (else x) ) ) (##sys#check-syntax 'quasiquote form '(_ _)) (walk (cadr form) 0) ) ) ) ) (##sys#extend-macro-environment 'delay '() (##sys#er-transformer (lambda (form r c) (##sys#check-syntax 'delay form '(_ _)) `(##sys#make-promise (lambda () ,(cadr form)))))) (##sys#extend-macro-environment 'cond-expand '() (##sys#er-transformer (lambda (form r c) (let ((clauses (cdr form)) (%or (r 'or)) (%not (r 'not)) (%else (r 'else)) (%and (r 'and))) (define (err x) (##sys#error "syntax error in `cond-expand' form" x (cons 'cond-expand clauses)) ) (define (test fx) (cond ((symbol? fx) (##sys#feature? fx)) ((not (pair? fx)) (err fx)) (else (let ((head (car fx)) (rest (cdr fx))) (cond ((c %and head) (or (eq? rest '()) (if (pair? rest) (and (test (car rest)) (test `(,%and ,@(cdr rest))) ) (err fx) ) ) ) ((c %or head) (and (not (eq? rest '())) (if (pair? rest) (or (test (car rest)) (test `(,%or ,@(cdr rest))) ) (err fx) ) ) ) ((c %not head) (not (test (cadr fx)))) (else (err fx)) ) ) ) ) ) (let expand ((cls clauses)) (cond ((eq? cls '()) (##sys#apply ##sys#error "no matching clause in `cond-expand' form" (map (lambda (x) (car x)) clauses) ) ) ((not (pair? cls)) (err cls)) (else (let ((clause (car cls)) (rclauses (cdr cls)) ) (if (not (pair? clause)) (err clause) (let ((id (car clause))) (cond ((c id %else) (let ((rest (cdr clause))) (if (eq? rest '()) '(##core#undefined) `(##core#begin ,@rest) ) ) ) ((test id) `(##core#begin ,@(cdr clause))) (else (expand rclauses)) ) ) ) ) ) ) ) ) ) ) ) (##sys#extend-macro-environment 'require-library '() (##sys#er-transformer (lambda (x r c) (let ((ids (cdr x))) `(##core#require-extension ,ids #f) ) ) ) ) (##sys#extend-macro-environment 'require-extension '() (##sys#er-transformer (lambda (x r c) (let ((ids (cdr x))) `(##core#require-extension ,ids #t) ) ) ) ) (##sys#extend-macro-environment 'module '() (##sys#er-transformer (lambda (x r c) (##sys#check-syntax 'module x '(_ symbol _ . #(_ 0))) `(##core#module ,(cadr x) ,(if (eq? '* (strip-syntax (caddr x))) #t (caddr x)) ,@(cdddr x))))) (##sys#extend-macro-environment 'begin-for-syntax '() (##sys#er-transformer (lambda (x r c) (##sys#check-syntax 'begin-for-syntax x '(_ . #(_ 0))) (##sys#register-meta-expression `(##core#begin ,@(cdr x))) `(##core#elaborationtimeonly (##core#begin ,@(cdr x)))))) (##sys#extend-macro-environment 'export '() (##sys#er-transformer (lambda (x r c) (let ((exps (cdr x)) (mod (##sys#current-module))) (unless mod (syntax-error 'export "`export' used outside module body")) (for-each (lambda (exp) (when (and (not (symbol? exp)) (let loop ((iexp exp)) (cond ((null? iexp) #f) ((not (pair? iexp)) #t) ((not (symbol? (car iexp))) #t) (else (loop (cdr iexp)))))) (syntax-error 'export "invalid export syntax" exp (module-name mod)))) exps) (set-module-export-list! mod (append (module-export-list mod) (map ##sys#strip-syntax exps))) '(##sys#void))))) ;;; syntax-rules (include "synrules.scm") ;;; the base macro environment ("scheme", essentially) (define (##sys#macro-subset me0 #!optional parent-env) (let ((se (let loop ((me (##sys#macro-environment))) (if (or (null? me) (eq? me me0)) '() (cons (car me) (loop (cdr me))))))) (##sys#fixup-macro-environment se parent-env))) (define (##sys#fixup-macro-environment se #!optional parent-env) (let ((se2 (if parent-env (##sys#append se parent-env) se))) (for-each ; fixup se (lambda (sdef) (when (pair? (cdr sdef)) (set-car! (cdr sdef) (if (null? (cadr sdef)) se2 (##sys#append (cadr sdef) se2))))) se) se)) (define ##sys#default-macro-environment (##sys#fixup-macro-environment (##sys#macro-environment))) ;;; low-level module support (define ##sys#meta-macro-environment (make-parameter (##sys#macro-environment))) (define ##sys#current-module (make-parameter #f)) (declare (hide make-module module? %make-module module-name module-vexports module-sexports set-module-vexports! set-module-sexports! module-export-list set-module-export-list! module-defined-list set-module-defined-list! module-import-forms set-module-import-forms! module-meta-import-forms set-module-meta-import-forms! module-exist-list set-module-exist-list! module-meta-expressions set-module-meta-expressions! module-defined-syntax-list set-module-defined-syntax-list!)) (define-record-type module (%make-module name export-list defined-list exist-list defined-syntax-list undefined-list import-forms meta-import-forms meta-expressions vexports sexports) module? (name module-name) ; SYMBOL (export-list module-export-list set-module-export-list!) ; (SYMBOL | (SYMBOL ...) ...) (defined-list module-defined-list set-module-defined-list!) ; ((SYMBOL . VALUE) ...) - *exported* value definitions (exist-list module-exist-list set-module-exist-list!) ; (SYMBOL ...) - only for checking refs to undef'd (defined-syntax-list module-defined-syntax-list set-module-defined-syntax-list!) ; ((SYMBOL . VALUE) ...) (undefined-list module-undefined-list set-module-undefined-list!) ; (SYMBOL ...) (import-forms module-import-forms set-module-import-forms!) ; (SPEC ...) (meta-import-forms module-meta-import-forms set-module-meta-import-forms!) ; (SPEC ...) (meta-expressions module-meta-expressions set-module-meta-expressions!) ; (EXP ...) (vexports module-vexports set-module-vexports!) ; (SYMBOL . SYMBOL) (sexports module-sexports set-module-sexports!) ) ; ((SYMBOL SE TRANSFORMER) ...) (define ##sys#module-name module-name) (define (##sys#module-exports m) (values (module-export-list m) (module-vexports m) (module-sexports m))) (define (make-module name explist vexports sexports) (%make-module name explist '() '() '() '() '() '() '() vexports sexports)) (define (##sys#find-module name #!optional (err #t)) (cond ((assq name ##sys#module-table) => cdr) (err (error 'import "module not found" name)) (else #f))) (declare (not inline ##sys#toplevel-definition-hook)) (define (##sys#toplevel-definition-hook sym mod exp val) #f) (define (##sys#register-meta-expression exp) (and-let* ((mod (##sys#current-module))) (set-module-meta-expressions! mod (cons exp (module-meta-expressions mod))))) (define (check-for-redef sym env senv) (and-let* ((a (assq sym env))) (##sys#warn "redefinition of imported value binding" sym) ) (and-let* ((a (assq sym senv))) (##sys#warn "redefinition of imported syntax binding" sym))) (define (##sys#register-export sym mod) (when mod (let ((exp (or (eq? #t (module-export-list mod)) (##sys#find-export sym mod #t))) (ulist (module-undefined-list mod))) (##sys#toplevel-definition-hook ; in compiler, hides unexported bindings (##sys#module-rename sym (module-name mod)) mod exp #f) (when (memq sym ulist) (set-module-undefined-list! mod (##sys#delq sym ulist))) (check-for-redef sym (##sys#current-environment) (##sys#macro-environment)) (set-module-exist-list! mod (cons sym (module-exist-list mod))) (when exp (dm "defined: " sym) (set-module-defined-list! mod (cons (cons sym #f) (module-defined-list mod)))))) ) (define (##sys#register-syntax-export sym mod val) (when mod (let ((exp (or (eq? #t (module-export-list mod)) (##sys#find-export sym mod #t))) (ulist (module-undefined-list mod)) (mname (module-name mod))) (when (memq sym ulist) (##sys#warn "use of syntax precedes definition" sym)) (check-for-redef sym (##sys#current-environment) (##sys#macro-environment)) (dm "defined syntax: " sym) (when exp (set-module-defined-list! mod (cons (cons sym val) (module-defined-list mod))) ) (set-module-defined-syntax-list! mod (cons (cons sym val) (module-defined-syntax-list mod)))))) (define (##sys#register-undefined sym mod) (when mod (let ((ul (module-undefined-list mod))) (unless (memq sym ul) (set-module-undefined-list! mod (cons sym ul)))))) (define (##sys#register-module name explist #!optional (vexports '()) (sexports '())) (let ((mod (make-module name explist vexports sexports))) (set! ##sys#module-table (cons (cons name mod) ##sys#module-table)) mod) ) (define (##sys#mark-imported-symbols se) (for-each (lambda (imp) (when (and (symbol? (cdr imp)) (not (eq? (car imp) (cdr imp)))) (dm `(MARKING: ,(cdr imp))) (##sys#put! (cdr imp) '##core#aliased #t))) se)) (define (module-indirect-exports mod) (let ((exports (module-export-list mod)) (mname (module-name mod)) (dlist (module-defined-list mod))) (define (indirect? id) (let loop ((exports exports)) (and (not (null? exports)) (or (and (pair? (car exports)) (memq id (cdar exports))) (loop (cdr exports)))))) (define (warn msg id) (##sys#warn (string-append msg " in module `" (symbol->string mname) "'") id)) (if (eq? #t exports) '() (let loop ((exports exports)) ; walk export list (cond ((null? exports) '()) ((symbol? (car exports)) (loop (cdr exports))) ; normal export (else (let loop2 ((iexports (cdar exports))) ; walk indirect exports for a given entry (cond ((null? iexports) (loop (cdr exports))) ((assq (car iexports) (##sys#macro-environment)) (warn "indirect export of syntax binding" (car iexports)) (loop2 (cdr iexports))) ((assq (car iexports) dlist) => ; defined in current module? (lambda (a) (cons (cons (car iexports) (or (cdr a) (##sys#module-rename (car iexports) mname))) (loop2 (cdr iexports))))) ((assq (car iexports) (##sys#current-environment)) => (lambda (a) ; imported in current env. (cond ((symbol? (cdr a)) ; not syntax (cons (cons (car iexports) (cdr a)) (loop2 (cdr iexports))) ) (else (warn "indirect reexport of syntax" (car iexports)) (loop2 (cdr iexports)))))) (else (warn "indirect export of unknown binding" (car iexports)) (loop2 (cdr iexports))))))))))) (define (merge-se . ses) ; later occurrences take precedence to earlier ones (let ((se (apply append ses))) (dm "merging " (length ses) " se's with total length of " (length se)) (let ((se2 (let loop ((se se)) (cond ((null? se) '()) ((assq (caar se) (cdr se)) (loop (cdr se))) (else (cons (car se) (loop (cdr se)))))))) (dm " merged has length " (length se2)) se2))) (define (##sys#compiled-module-registration mod) (let ((dlist (module-defined-list mod)) (mname (module-name mod)) (ifs (module-import-forms mod)) (sexports (module-sexports mod)) (mifs (module-meta-import-forms mod))) `(,@(if (pair? ifs) `((eval '(import ,@ifs))) '()) ,@(if (pair? mifs) `((import ,@mifs)) '()) ,@(reverse (map ##sys#strip-syntax (module-meta-expressions mod))) (##sys#register-compiled-module ',(module-name mod) (list ,@(map (lambda (ie) (if (symbol? (cdr ie)) `'(,(car ie) . ,(cdr ie)) `(list ',(car ie) '() ,(cdr ie)))) (module-indirect-exports mod))) ',(module-vexports mod) (list ,@(map (lambda (sexport) (let* ((name (car sexport)) (a (assq name dlist))) (cond ((pair? a) `(cons ',(car sexport) ,(##sys#strip-syntax (cdr a)))) (else (dm "re-exported syntax" name mname) `',name)))) sexports)) (list ,@(if (null? sexports) '() ; no syntax exported - no more info needed (let loop ((sd (module-defined-syntax-list mod))) (cond ((null? sd) '()) ((assq (caar sd) sexports) (loop (cdr sd))) (else (let ((name (caar sd))) (cons `(cons ',(caar sd) ,(##sys#strip-syntax (cdar sd))) (loop (cdr sd))))))))))))) (define (##sys#register-compiled-module name iexports vexports sexports #!optional (sdefs '())) (define (find-reexport name) (let ((a (assq name (##sys#macro-environment)))) (if (and a (pair? (cdr a))) a (##sys#error 'import "cannot find implementation of re-exported syntax" name)))) (let* ((sexps (map (lambda (se) (if (symbol? se) (find-reexport se) (list (car se) #f (##sys#er-transformer (cdr se))))) sexports)) (iexps (map (lambda (ie) (if (pair? (cdr ie)) (list (car ie) (cadr ie) (##sys#er-transformer (caddr ie))) ie)) iexports)) (nexps (map (lambda (ne) (list (car ne) #f (##sys#er-transformer (cdr ne)))) sdefs)) (mod (make-module name '() vexports sexps)) (senv (merge-se (##sys#macro-environment) (##sys#current-environment) iexps vexports sexps nexps))) (##sys#mark-imported-symbols iexps) (for-each (lambda (sexp) (set-car! (cdr sexp) senv)) sexps) (for-each (lambda (iexp) (when (pair? (cdr iexp)) (set-car! (cdr iexp) senv))) iexps) (for-each (lambda (nexp) (set-car! (cdr nexp) senv)) nexps) (set! ##sys#module-table (cons (cons name mod) ##sys#module-table)) mod)) (define (##sys#primitive-alias sym) (let ((palias (##sys#string->symbol (##sys#string-append "#%" (##sys#slot sym 1))))) (##sys#put! palias '##core#primitive sym) palias)) (define (##sys#register-primitive-module name vexports #!optional (sexports '())) (let* ((me (##sys#macro-environment)) (mod (make-module name '() (map (lambda (ve) (if (symbol? ve) (cons ve (##sys#primitive-alias ve)) ve)) vexports) (map (lambda (se) (if (symbol? se) (or (assq se me) (##sys#error "unknown macro referenced while registering module" se name)) se)) sexports)))) (set! ##sys#module-table (cons (cons name mod) ##sys#module-table)) mod)) (define (##sys#find-export sym mod indirect) (let ((exports (module-export-list mod))) (let loop ((xl (if (eq? #t exports) (module-exists-list mod) exports))) (cond ((null? xl) #f) ((eq? sym (car xl))) ((pair? (car xl)) (or (eq? sym (caar xl)) (and indirect (memq sym (cdar xl))) (loop (cdr xl)))) (else (loop (cdr xl))))))) (define (##sys#finalize-module mod) (let* ((explist (module-export-list mod)) (name (module-name mod)) (dlist (module-defined-list mod)) (elist (module-exist-list mod)) (missing #f) (sdlist (map (lambda (sym) (assq (car sym) (##sys#macro-environment))) (module-defined-syntax-list mod))) (sexports (if (eq? #t explist) sdlist (let loop ((me (##sys#macro-environment))) (cond ((null? me) '()) ((##sys#find-export (caar me) mod #f) (cons (car me) (loop (cdr me)))) (else (loop (cdr me))))))) (vexports (let loop ((xl (if (eq? #t explist) elist explist))) (if (null? xl) '() (let* ((h (car xl)) (id (if (symbol? h) h (car h)))) (if (assq id sexports) (loop (cdr xl)) (cons (cons id (let ((def (assq id dlist))) (if (and def (symbol? (cdr def))) (cdr def) (let ((a (assq id (##sys#current-environment)))) (cond ((and a (symbol? (cdr a))) (dm "reexporting: " id " -> " (cdr a)) (cdr a)) ((not def) (set! missing #t) (##sys#warn (string-append "exported identifier for module `" (symbol->string name) "' has not been defined") id) #f) (else (##sys#module-rename id name))))))) (loop (cdr xl))))))))) (for-each (lambda (u) (unless (memq u elist) (set! missing #t) (##sys#warn "reference to possibly unbound identifier" u) (and-let* ((a (##sys#get u '##core#db))) (if (= 1 (length a)) (##sys#warn (string-append " suggesting: `(import " (symbol->string (cadar a)) ")'")) (##sys#warn (string-append " suggesting one of:\n" (let loop ((lst a)) (if (null? lst) "" (string-append "Warning: `(import " (symbol->string (cadar lst)) ")'\n" (loop (cdr lst))))))))))) (module-undefined-list mod)) (when missing (##sys#error "module unresolved" name)) (let* ((exports (map (lambda (exp) (cond ((symbol? (cdr exp)) exp) ((assq (car exp) (##sys#macro-environment))) (else (##sys#error "(internal) indirect export not found" (car exp)))) ) (module-indirect-exports mod))) (new-se (merge-se (##sys#macro-environment) (##sys#current-environment) exports))) (##sys#mark-imported-symbols exports) (for-each (lambda (m) (let ((se (merge-se (cadr m) new-se))) (dm `(FIXUP: ,(car m) ,@(map-se se))) (set-car! (cdr m) se))) sdlist) (dm `(EXPORTS: ,(module-name mod) (DLIST: ,@dlist) (SDLIST: ,@(map-se sdlist)) (IEXPORTS: ,@(map-se exports)) (VEXPORTS: ,@(map-se vexports)) (SEXPORTS: ,@(map-se sexports)))) (set-module-vexports! mod vexports) (set-module-sexports! mod sexports)))) (define ##sys#module-table '())
true
71c768fdb7aef4348ee2d357001922a097836cda
ae76253c0b7fadf8065777111d3aa6b57383d01b
/chap4/exec-4.71.ss
1a7336bdf3364cac1c0bd6989aeb8f41182ea659
[]
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
172
ss
exec-4.71.ss
(assert! (marriage jack mary)) (assert! (marriage tom nacy)) (assert! (marriage louis hellen)) (assert! (rule (marriage ?a ?b) (marriage ?b ?a))) (marriage jack ?w)
false