blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
171
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
d12ae5a1cdfbcec73784ed265983347766cbbd78
d6ba773f1c822a5003692c47a6d2b645e47c0907
/formula/postgresql.scm
4d9d288e755790355d79a49039490ba1cdbb5be4
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
ktakashi/r7rs-postgresql
a2d93e39cd95c0cf659e8336f5aaf62ad61f4f75
94fdaeccee6caa5e9562a8f231329e59ce15aae7
refs/heads/master
2020-04-06T13:13:50.481891
2017-12-11T20:09:43
2017-12-11T20:09:43
26,015,242
23
3
null
2015-02-04T19:40:18
2014-10-31T12:26:02
Scheme
UTF-8
Scheme
false
false
398
scm
postgresql.scm
(formula (description "R7RS PostgreSQL") (version "master") (homepage :url "https://github.com/ktakashi/r7rs-postgresql") (author :name "Takashi Kato" :email "[email protected]") (source :type tar :compression gzip :url "https://github.com/ktakashi/r7rs-postgresql/archive/master.tar.gz") (install (directories ("lib"))) (tests (test :file "test.scm" :style srfi-64 :loadpath "lib")))
false
ed8238674c9efe79f173569653e02a9b29f14551
11150f2821f9bde74eeb9460149d452e6e689438
/fun/project-euler/020.scm
ef00d9c496836868e013f6fd737384e73fc1c231
[]
no_license
doug16rogers/dr
a644e3379ddf586e677348225cde9475e654d277
2e32fa6eae310cfc0723d88add53249c7d82271b
refs/heads/master
2023-06-23T08:33:33.696720
2018-10-10T15:12:00
2018-10-10T15:12:00
5,799,618
3
1
null
2012-10-24T23:50:11
2012-09-13T19:16:21
Emacs Lisp
UTF-8
Scheme
false
false
645
scm
020.scm
; Project Euler Problem 20 ; There's probably a clever way to do this. Certainly factors of powers of 10 ; could be removed. But I don't see anything else. One could easily calculate ; the sum mod 9 of the digits. ; I used Scheme to calculate 100! then sum the digits. (define (fact n) (if (= 1 n) 1 (* n (fact (- n 1))))) (fact 100) ; 9332621544394415268169923885626670049071596826438162146859296389 ; 5217599993229915608941463976156518286253697920827223758251185210 ; 916864000000000000000000000000 (define (sumdigits n) (if (= n 0) 0 (+ (modulo n 10) (sumdigits (floor (/ n 10)))))) (sumdigits (fact 100)) ; 648
false
4955aef811b7933714e31e3e9c66ec34b0332cbb
d074b9a2169d667227f0642c76d332c6d517f1ba
/sicp/ch_1/exercise.1.45.scm
89f3cd0ae4699a58235930b7a49d0aae024f5994
[]
no_license
zenspider/schemers
4d0390553dda5f46bd486d146ad5eac0ba74cbb4
2939ca553ac79013a4c3aaaec812c1bad3933b16
refs/heads/master
2020-12-02T18:27:37.261206
2019-07-14T15:27:42
2019-07-14T15:27:42
26,163,837
7
0
null
null
null
null
UTF-8
Scheme
false
false
1,103
scm
exercise.1.45.scm
#lang racket/base ;;; Exercise 1.45: ;; We saw in section *Note 1-3-3:: that attempting to compute square ;; roots by naively finding a fixed point of y |-> x/y does not ;; converge, and that this can be fixed by average damping. The same ;; method works for finding cube roots as fixed points of the ;; average-damped y |-> x/y^2. Unfortunately, the process does not ;; work for fourth roots--a single average damp is not enough to make ;; a fixed-point search for y |-> x/y^3 converge. On the other hand, ;; if we average damp twice (i.e., use the average damp of the average ;; damp of y |-> x/y^3) the fixed-point search does converge. Do some ;; experiments to determine how many average damps are required to ;; compute nth roots as a fixed-point search based upon repeated ;; average damping of y |-> x/y^(n-1). Use this to implement a simple ;; procedure for computing nth roots using `fixed-point', ;; `average-damp', and the `repeated' procedure of *Note Exercise ;; 1-43::. Assume that any arithmetic operations you need are ;; available as primitives. ;; aja says we should skip this one
false
9873fe5885d0fb4a958f1de70b39a2a9be3b82ef
2bcf33718a53f5a938fd82bd0d484a423ff308d3
/programming/sicp/ch4/ex-4.17.scm
251852dc9ea0fb8048ab0cc516e32ed4a6e803d8
[]
no_license
prurph/teach-yourself-cs
50e598a0c781d79ff294434db0430f7f2c12ff53
4ce98ebab5a905ea1808b8785949ecb52eee0736
refs/heads/main
2023-08-30T06:28:22.247659
2021-10-17T18:27:26
2021-10-17T18:27:26
345,412,092
0
0
null
null
null
null
UTF-8
Scheme
false
false
882
scm
ex-4.17.scm
#lang sicp ;; https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-26.html#%_thm_4.17 ;; When definitions are scanned out, there is an extra frame because the scanning process creates a let expression, which is then evaluated as a lambda, causing the creation of another enviornment frame. This cannot affect the interpretation of the program because the new--nested, inner frame--insulates the let definitions from the outer environment. ;; ;; To avoid creating the extra frame, all internal definitions must occur before the body of the outer procedure is evaluated. Otherwise we have no guarantee that the internal defines would be correctly bound in the environment used to evaluate the procedure body. When we scan them out the extra frame takes care of this by setting any yet-undefined references to '*unassigned*, allowing them to be filled in later.
false
901ace4dc3be7e95e9fe9171db33c71452703d40
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
/sitelib/peg/derived.scm
042e0e0ded102d89e718bced8b1a91573956433e
[ "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "MIT", "BSD-2-Clause" ]
permissive
ktakashi/sagittarius-scheme
0a6d23a9004e8775792ebe27a395366457daba81
285e84f7c48b65d6594ff4fbbe47a1b499c9fec0
refs/heads/master
2023-09-01T23:45:52.702741
2023-08-31T10:36:08
2023-08-31T10:36:08
41,153,733
48
7
NOASSERTION
2022-07-13T18:04:42
2015-08-21T12:07:54
Scheme
UTF-8
Scheme
false
false
6,361
scm
derived.scm
;;; -*- mode:scheme; coding:utf-8 -*- ;;; ;;; peg/derived.scm - PEG syntax sugers et al ;;; ;;; Copyright (c) 2017 Takashi Kato <[email protected]> ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; #!nounbound (library (peg derived) (export $bind $do $let* $let $optional $repeat $parameterize $lazy $guard $if $when $unless $cond else $peek-match $eqv?) (import (rnrs) (rnrs r5rs) (core inline) (peg primitives) (srfi :39 parameters)) (define ($$bind p f) (lambda (l) (let-values (((s v nl) (p l))) (if (parse-success? s) ((f v) nl) (values s v l))))) (define-syntax $bind (lambda (x) (syntax-case x () ((_ p? f?) #'(let ((p p?) (f f?)) (lambda (l) (let-values (((s v nl) (p l))) (if (parse-success? s) ((f v) nl) (values s v l)))))) (k (identifier? #'k) #'$$bind)))) ;; $do clause ... body ;; clause := (var parser) ;; | (parser) ;; | parser (define-syntax $do (syntax-rules () ((_ body) body) ((_ (var parser) clause rest ...) ($bind parser (lambda (var) ($do clause rest ...)))) ((_ (parser) clause rest ...) ($bind parser (lambda (_) ($do clause rest ...)))) ((_ parser clause rest ...) ($bind parser (lambda (_) ($do clause rest ...)))))) ;; $let* (bind ...) body ;; bind := (var parser) ;; | (parser) ;; | parser ;; almost the same as $do but more explicit (I think) (define-syntax $let* (syntax-rules () ((_ () body0 body* ...) ($seq body0 body* ...)) ((_ ((var parser) bind* ...) body ...) ($bind parser (lambda (var) ($let* (bind* ...) body ...)))) ((_ ((parser) bind* ...) body ...) ($bind parser (lambda (_) ($let* (bind* ...) body ...)))) ((_ (parser bind* ...) body ...) ($bind parser (lambda (_) ($let* (bind* ...) body ...)))))) ;; $let (bind ...) body ;; bind := (var parser) ;; | (parser) ;; | parser ;; analogy of let* but better performance (define-syntax $let (syntax-rules () ((_ () body0 body* ...) ($seq body0 body* ...)) ;; short cut ((_ (bind bind* ...) body* ...) ($let "collect" (bind bind* ...) (body* ...) ())) ((_ "collect" ((var parser) bind* ...) body ((v t p) ...)) ($let "collect" (bind* ...) body ((v t p) ... (var tmp parser)))) ((_ "collect" ((parser) bind* ...) body ((v t p) ...)) ($let "collect" (bind* ...) body ((v t p) ... (var tmp parser)))) ((_ "collect" (parser bind* ...) body ((v t p) ...)) ($let "collect" (bind* ...) body ((v t p) ... (var tmp parser)))) ((_ "collect" () (body0 body* ...) ((v t p) ...)) (let ((t p) ...) ;; bind parser ($let* ((v t) ...) body0 body* ...))))) (define ($$optional parser . maybe-fallback) (define fallback (if (null? maybe-fallback) #f (car maybe-fallback))) ($do (r ($many parser 0 1)) ($return (if (null? r) fallback (car r))))) (define-syntax $optional (lambda (x) (syntax-case x () ((_ parser) #'($optional parser #f)) ((_ parser fallback) #'($do (r ($many parser 0 1)) ($return (if (null? r) fallback (car r))))) (k (identifier? #'k) #'$$optional)))) (define-inline ($repeat parser n) ($many parser n n)) (define-syntax $parameterize (syntax-rules () ((_ ((p c) ...) parser0 parser* ...) (let ((e ($seq parser0 parser* ...))) (lambda (l) (parameterize ((p c) ...) (e l))))))) (define-syntax $lazy (syntax-rules () ((_ parser) (let ((p (delay parser))) (lambda (l) ((force parser) l)))))) (define-syntax $guard (syntax-rules () ((_ (e (pred clause) ...) body) (let ((parser body)) (lambda (l) (guard (e (pred (clause l)) ...) (parser l))))))) (define-syntax $if (syntax-rules () ((_ pred consequence alternative) (let ((c consequence) (a alternative)) (lambda (l) (if pred (c l) (a l))))))) (define-syntax $when (syntax-rules () ((_ pred body) ($if pred body ($expect 'pred))))) (define-syntax $unless (syntax-rules () ((_ pred body) ($when (not pred) body)))) (define-syntax $cond (syntax-rules (else) ((_ "emit" ((pred val) ...)) (lambda (input) (cond (pred (val input)) ...))) ((_ "collect" (p&c ...) ()) ($cond "emit" (p&c ...))) ((_ "collect" (p&c ...) ((else alternative))) (let ((tmp alternative)) ($cond "emit" (p&c ... (else tmp))))) ((_ "collect" (p&c ...) ((pred consequence) rest ...)) (let ((tmp consequence)) ($cond "collect" (p&c ... (pred tmp)) (rest ...)))) ((_ clause ...) ($cond "collect" () (clause ...))))) (define-syntax $peek-match (syntax-rules () ((_ parser consequence alternative) (let ((peek ($peek parser))) (lambda (input) (let-values (((s v n) (peek input))) (if (parse-success? s) (consequence input) (alternative input)))))))) (define-inline ($eqv? v) ($satisfy (lambda (c) (eqv? c v)) v)) )
true
4b54e3bf82175a0fdfd80616210f43639119b7d2
defeada37d39bca09ef76f66f38683754c0a6aa0
/System.Xml.Linq/system/xml/linq/xchildren-iterator.sls
fbd519c0d4d683ceff0041f3c595c91a1cecffcd
[]
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
668
sls
xchildren-iterator.sls
(library (system xml linq xchildren-iterator) (export new is? xchildren-iterator? get-enumerator) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Xml.Linq.XChildrenIterator a ...))))) (define (is? a) (clr-is System.Xml.Linq.XChildrenIterator a)) (define (xchildren-iterator? a) (clr-is System.Xml.Linq.XChildrenIterator a)) (define-method-port get-enumerator System.Xml.Linq.XChildrenIterator GetEnumerator ("System.Collections.Generic.IEnumerator`1[[System.Object, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")))
true
03ce74b7eb3ad82ffd4d5e46b6f088b3165caa47
120324bbbf63c54de0b7f1ca48d5dcbbc5cfb193
/packages/slib/schmooz.scm
55103b9596aaef517246b582f1131963e715f488
[ "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
20,487
scm
schmooz.scm
;;; "schmooz.scm" Program for extracting texinfo comments from Scheme. ;;; Copyright (C) 1998, 2000 Radey Shouman and Aubrey Jaffer. ; ;Permission to copy this software, to modify it, to redistribute it, ;to distribute modified versions, and to use it for any purpose is ;granted, subject to the following restrictions and understandings. ; ;1. Any copy made of this software must include this copyright notice ;in full. ; ;2. I have made no warranty or representation that the operation of ;this software will be error-free, and I am under no obligation to ;provide any services, by way of maintenance, update, or otherwise. ; ;3. In conjunction with products arising from the use of this ;material, there shall be no use of my name in any advertising, ;promotional, or sales literature without prior written consent in ;each case. (require 'common-list-functions) ;some (require 'string-search) (require 'fluid-let) (require 'line-i/o) ;read-line (require 'filename) ;;(require 'debug) (set! *qp-width* 100) (define qreport qpn) ;;; REPORT an error or warning (define report (lambda args (display *scheme-source-name*) (display ": In function `") (display *procedure*) (display "': ") (newline) (display *derived-txi-name*) (display ": ") (display *output-line*) (display ": warning: ") (apply qreport args))) (define qreport (lambda args (for-each (lambda (x) (write x) (display #\space)) args) (newline))) ;;; This allows us to test without generating files (define *scheme-source* (current-input-port)) (define *scheme-source-name* "stdin") (define *derived-txi* (current-output-port)) (define *derived-txi-name* "?") (define *procedure* #f) (define *output-line* 0) (define CONTLINE -80) ;;; OUT indents and displays the arguments (define (out indent . args) (cond ((>= indent 0) (newline *derived-txi*) (set! *output-line* (+ 1 *output-line*)) (do ((j indent (- j 8))) ((> 8 j) (do ((i j (- i 1))) ((>= 0 i)) (display #\space *derived-txi*))) (display #\ *derived-txi*)))) (for-each (lambda (a) (cond ((symbol? a) (display a *derived-txi*)) ((string? a) (display a *derived-txi*) ; (cond ((string-index a #\newline) ; (set! *output-line* (+ 1 *output-line*)) ; (report "newline in string" a))) ) (else (display a *derived-txi*)))) args)) ;; LINE is a string, ISTRT the index in LINE at which to start. ;; Returns a list (next-char-number . list-of-tokens). ;; arguments look like: ;; "(arg1 arg2)" or "{arg1,arg2}" or the whole line is split ;; into whitespace separated tokens. (define (parse-args line istrt) (define (tok1 istrt close sep? splice) (let loop-args ((istrt istrt) (args '())) (let loop ((iend istrt)) (cond ((>= iend (string-length line)) (if close (slib:error close "not found in" line) (cons iend (reverse (if (> iend istrt) (cons (substring line istrt iend) args) args))))) ((eqv? close (string-ref line iend)) (cons (+ iend 1) (reverse (if (> iend istrt) (cons (substring line istrt iend) args) args)))) ((sep? (string-ref line iend)) (let ((arg (and (> iend istrt) (substring line istrt iend)))) (if (equal? arg splice) (let ((rest (tok1 (+ iend 1) close sep? splice))) (cons (car rest) (append args (cadr rest)))) (loop-args (+ iend 1) (if arg (cons arg args) args))))) (else (loop (+ iend 1))))))) (let skip ((istrt istrt)) (cond ((>= istrt (string-length line)) (cons istrt '())) ((char-whitespace? (string-ref line istrt)) (skip (+ istrt 1))) ((eqv? #\{ (string-ref line istrt)) (tok1 (+ 1 istrt) #\} (lambda (c) (eqv? c #\,)) #f)) ((eqv? #\( (string-ref line istrt)) (tok1 (+ 1 istrt) #\) char-whitespace? ".")) (else (tok1 istrt #f char-whitespace? #f))))) ;; Substitute @ macros in string LINE. ;; Returns a list, the first element is the substituted version ;; of LINE, the rest are lists beginning with '@dfn or '@args ;; and followed by the arguments that were passed to those macros. ;; MACS is an alist of (macro-name . macro-value) pairs. (define (substitute-macs line macs) (define (get-word i) (let loop ((j (+ i 1))) (cond ((>= j (string-length line)) (substring line i j)) ((or (char-alphabetic? (string-ref line j)) (char-numeric? (string-ref line j))) (loop (+ j 1))) (else (substring line i j))))) (let loop ((istrt 0) (i 0) (res '())) (cond ((>= i (string-length line)) (list (apply string-append (reverse (cons (substring line istrt (string-length line)) res))))) ((char=? #\@ (string-ref line i)) (let* ((w (get-word i)) (symw (string->symbol w))) (cond ((eq? '@cname symw) (let ((args (parse-args line (+ i (string-length w))))) (cond ((and args (= 2 (length args))) (loop (car args) (car args) (cons (string-append "@code{" (cadr args) "}") (cons (substring line istrt i) res)))) (else (report "@cname wrong number of args" line) (loop istrt (+ i (string-length w)) res))))) ((eq? '@dfn symw) (let* ((args (parse-args line (+ i (string-length w)))) (inxt (car args)) (rest (loop inxt inxt (cons (substring line istrt inxt) res)))) (cons (car rest) (cons (cons '@dfn (cdr args)) (cdr rest))))) ((eq? '@args symw) (let* ((args (parse-args line (+ i (string-length w)))) (inxt (car args)) (rest (loop inxt inxt res))) (cons (car rest) (cons (cons '@args (cdr args)) (cdr rest))))) ((assq symw macs) => (lambda (s) (loop (+ i (string-length w)) (+ i (string-length w)) (cons (cdr s) (cons (substring line istrt i) res))))) (else (loop istrt (+ i (string-length w)) res))))) (else (loop istrt (+ i 1) res))))) (define (sexp-def sexp) (and (pair? sexp) (memq (car sexp) '(DEFINE DEFVAR DEFCONST DEFINE-SYNTAX DEFMACRO)) (car sexp))) (define def->var-name cadr) (define (def->args sexp) (define name (cadr sexp)) (define (body forms) (if (pair? forms) (if (null? (cdr forms)) (form (car forms)) (body (cdr forms))) #f)) (define (form sexp) (if (pair? sexp) (case (car sexp) ((LAMBDA) (cons name (cadr sexp))) ((BEGIN) (body (cdr sexp))) ((LET LET* LETREC) (if (or (null? (cadr sexp)) (pair? (cadr sexp))) (body (cddr sexp)) (body (cdddr sexp)))) ;named LET (else #f)) #f)) (case (car sexp) ((DEFINE) (if (pair? name) name (form (caddr sexp)))) ((DEFINE-SYNTAX) (case (caaddr sexp) ((SYNTAX-RULES) (caaddr (caddr sexp))) (else '()))) ((DEFMACRO) (cons (cadr sexp) (caddr sexp))) ((DEFVAR DEFCONST) #f) (else (slib:error 'schmooz "doesn't look like definition" sexp)))) ;; Generate alist of argument macro definitions. ;; If ARGS is a symbol or string, then the definitions will be used in a ;; `defvar', if ARGS is a (possibly improper) list, they will be used in ;; a `defun'. (define (scheme-args->macros args) (define (arg->string a) (if (string? a) a (symbol->string a))) (define (arg->macros arg i) (let ((s (number->string i)) (m (string-append "@var{" (arg->string arg) "}"))) (list (cons (string->symbol (string-append "@" s)) m) (cons (string->symbol (string-append "@arg" s)) m)))) (let* ((fun? (pair? args)) (arg0 (if fun? (car args) args)) (args (if fun? (cdr args) '()))) (let ((m0 (string-append (if fun? "@code{" "@var{") (arg->string arg0) "}"))) (append (list (cons '@arg0 m0) (cons '@0 m0)) (let recur ((i 1) (args args)) (cond ((null? args) '()) ((or (symbol? args) ;Rest list (string? args)) (arg->macros args i)) (else (append (arg->macros (car args) i) (recur (+ i 1) (cdr args)))))))))) ;; Extra processing to be done for @dfn (define (out-cindex arg) (out 0 "@cindex " arg)) ;; ARGS looks like the cadr of a function definition: ;; (fun-name arg1 arg2 ...) (define (schmooz-fun defop args body xdefs) (define (out-header args op) (let ((fun (car args)) (args (cdr args))) (out 0 #\@ op #\space fun) (let loop ((args args)) (cond ((null? args)) ((symbol? args) (loop (symbol->string args))) ((string? args) (out CONTLINE " " (let ((n (- (string-length args) 1))) (if (eqv? #\s (string-ref args n)) (substring args 0 n) args)) " @dots{}")) ((pair? args) (out CONTLINE " " (if (or (eq? '... (car args)) (equal? "..." (car args))) "@dots{}" (car args))) (loop (cdr args))) (else (slib:error 'schmooz-fun args)))))) (let* ((mac-list (scheme-args->macros args)) (ops (case defop ((DEFINE-SYNTAX) '("defspec" "defspecx" "defspec")) ((DEFMACRO) '("defmac" "defmacx" "defmac")) (else (if (and (symbol? (car args)) (char=? (string-ref (symbol->string (car args)) (+ -1 (string-length (symbol->string (car args))))) #\!)) '("deffn {Procedure}" "deffnx {Procedure}" "deffn") '("defun" "defunx" "defun")))))) (define in-body? #f) (out-header args (car ops)) (let loop ((xdefs xdefs)) (cond ((pair? xdefs) (out-header (car xdefs) (cadr ops)) (loop (cdr xdefs))))) (for-each (lambda (subl) ;;(print 'in-body? in-body? 'subl subl) (out 0 (car subl)) (for-each (lambda (l) (case (car l) ((@dfn) (out-cindex (cadr l))) ((@args) (cond (in-body? (out 0 "@end " (caddr ops)) (set! in-body? #f) (out-header (cons (car args) (cdr l)) (car ops))) (else (out-header (cons (car args) (cdr l)) (cadr ops))))))) (cdr subl)) (if (not (equal? "" (car subl))) (set! in-body? #t))) (map (lambda (bl) (substitute-macs bl mac-list)) body)) (out 0 "@end " (caddr ops)) (out 0) (out 0))) (define (schmooz-var defop name body xdefs) (let* ((mac-list (scheme-args->macros name))) (out 0 "@defvar " name) (let loop ((xdefs xdefs)) (cond ((pair? xdefs) (out 0 "@defvarx " (car xdefs)) (loop (cdr xdefs))))) (for-each (lambda (subl) (out 0 (car subl)) (for-each (lambda (l) (case (car l) ((@dfn) (out-cindex (cadr l))) (else (report "bad macro" l)))) (cdr subl))) (map (lambda (bl) (substitute-macs bl mac-list)) body)) (out 0 "@end defvar") (out 0))) (define (schmooz:read-word port) (do ((chr (peek-char port) (peek-char port))) ((not (and (char? chr) (char-whitespace? chr)))) (read-char port)) (do ((chr (peek-char port) (peek-char port)) (str "" (string-append str (string chr)))) ((not (and (char? chr) (not (char-whitespace? chr)))) str) (read-char port))) (define (pathname->local-filename path) (define vic (pathname->vicinity path)) (define plen (string-length path)) (let ((vlen (string-length vic))) (if (and (substring? vic path) (< vlen plen)) (in-vicinity (user-vicinity) (substring path vlen plen)) (slib:error 'pathname->local-filename path)))) ;;;@ SCHMOOZ files. (define schmooz (let* ((scheme-file? (filename:match-ci?? "*??scm")) (txi-file? (filename:match-ci?? "*??txi")) (texi-file? (let ((tex? (filename:match-ci?? "*??tex")) (texi? (filename:match-ci?? "*??texi"))) (lambda (filename) (or (txi-file? filename) (tex? filename) (texi? filename))))) (txi->scm (filename:substitute?? "*txi" "*scm")) (scm->txi (filename:substitute?? "*scm" "*txi"))) (define (schmooz-texi-file file) (call-with-input-file file (lambda (port) (do ((pos (find-string-from-port? "@include" port) (find-string-from-port? "@include" port))) ((not pos)) (let ((fname (schmooz:read-word port))) (cond ((equal? "" fname)) ((not (txi-file? fname))) ((not (file-exists? (txi->scm fname)))) (else (schmooz (txi->scm fname))))))))) (define (schmooz-scm-file file txi-name) (display "Schmoozing ") (write file) (display " -> ") (write txi-name) (newline) (fluid-let ((*scheme-source* (open-input-file file)) (*scheme-source-name* file) (*derived-txi* (open-output-file txi-name)) (*derived-txi-name* txi-name)) (set! *output-line* 1) (cond ((scheme-file? file)) (else (find-string-from-port? ";" *scheme-source* #\;) (read-line *scheme-source*))) (schmooz-tops schmooz-top) (close-input-port *scheme-source*) (close-output-port *derived-txi*))) (lambda files (for-each (lambda (file) (define sl (string-length file)) (cond ((texi-file? file) (schmooz-texi-file file)) ((scheme-file? file) (schmooz-scm-file file (pathname->local-filename (scm->txi file)))) (else (schmooz-scm-file file (pathname->local-filename (string-append file ".txi")))))) files)))) ;;; SCHMOOZ-TOPS - schmooz top level forms. (define schmooz-tops (let ((semispaces (cons slib:tab '(#\space #\;)))) (lambda (schmooz-top) (let ((doc-lines '()) (doc-args #f)) (define (skip-ws line istrt) (do ((i istrt (+ i 1))) ((or (>= i (string-length line)) (not (memv (string-ref line i) semispaces))) (substring line i (string-length line))))) (define (tok1 line) (let loop ((i 0)) (cond ((>= i (string-length line)) line) ((or (char-whitespace? (string-ref line i)) (memv (string-ref line i) '(#\; #\( #\{))) (substring line 0 i)) (else (loop (+ i 1)))))) (define (read-cmt-line) (cond ((eqv? #\; (peek-char *scheme-source*)) (read-char *scheme-source*) (read-cmt-line)) (else (read-line *scheme-source*)))) (define (read-meta-cmt) (let skip ((metarg? #f)) (let ((c (read-char *scheme-source*))) (case c ((#\newline) (if metarg? (skip #t))) ((#\\) (skip #t)) ((#\!) (cond ((eqv? #\# (peek-char *scheme-source*)) (read-char *scheme-source*) (if #f #f)) (else (skip metarg?)))) (else (if (char? c) (skip metarg?) c)))))) (define (lp c) (cond ((eof-object? c) (cond ((pair? doc-lines) (report "No definition found for @body doc lines" (reverse doc-lines))))) ((eqv? c #\newline) (read-char *scheme-source*) (set! *output-line* (+ 1 *output-line*)) ;;(newline *derived-txi*) (lp (peek-char *scheme-source*))) ((char-whitespace? c) (write-char (read-char *scheme-source*) *derived-txi*) (lp (peek-char *scheme-source*))) ((char=? c #\;) (c-cmt c)) ((char=? c #\#) (read-char *scheme-source*) (if (eqv? #\! (peek-char *scheme-source*)) (read-meta-cmt) (report "misread sharp object" (peek-char *scheme-source*))) (lp (peek-char *scheme-source*))) (else (sx)))) (define (sx) (let* ((s1 (read *scheme-source*)) ;;Read all forms separated only by single newlines ;;and trailing whitespace. (ss (let recur () (let ((c (peek-char *scheme-source*))) (cond ((eof-object? c) '()) ((eqv? c #\newline) (read-char *scheme-source*) (if (eqv? #\( (peek-char *scheme-source*)) (let ((s (read *scheme-source*))) (cons s (recur))) '())) ((char-whitespace? c) (read-char *scheme-source*) (recur)) (else '())))))) (cond ((eof-object? s1)) (else (schmooz-top s1 ss (reverse doc-lines) doc-args) (set! doc-lines '()) (set! doc-args #f) (lp (peek-char *scheme-source*)))))) (define (out-cmt line) (let ((subl (substitute-macs line '()))) (display (car subl) *derived-txi*) (for-each (lambda (l) (case (car l) ((@dfn) (out-cindex (cadr l))) (else (report "bad macro" line)))) (cdr subl)) (newline *derived-txi*))) ;;Comments not transcribed to generated Texinfo files. (define (c-cmt c) (cond ((eof-object? c) (lp c)) ((eqv? #\; c) (read-char *scheme-source*) (c-cmt (peek-char *scheme-source*))) ;; Escape to start Texinfo comments ((eqv? #\@ c) (let* ((line (read-line *scheme-source*)) (tok (tok1 line))) (cond ((or (string=? tok "@body") (string=? tok "@text")) (set! doc-lines (cons (skip-ws line (string-length tok)) doc-lines)) (body-cmt (peek-char *scheme-source*))) ((string=? tok "@args") (let ((args (parse-args line (string-length tok)))) (set! doc-args (cdr args)) (set! doc-lines (cons (skip-ws line (car args)) doc-lines))) (body-cmt (peek-char *scheme-source*))) (else (out-cmt (if (string=? tok "@") (skip-ws line 1) line)) (doc-cmt (peek-char *scheme-source*)))))) ;; Transcribe the comment line to C source file. (else (read-line *scheme-source*) (lp (peek-char *scheme-source*))))) ;;Comments incorporated in generated Texinfo files. ;;Continue adding lines to DOC-LINES until a non-comment ;;line is reached (may be a blank line). (define (body-cmt c) (cond ((eof-object? c) (lp c)) ((eqv? #\; c) (set! doc-lines (cons (read-cmt-line) doc-lines)) (body-cmt (peek-char *scheme-source*))) ((eqv? c #\newline) (read-char *scheme-source*) (lp (peek-char *scheme-source*))) ;; Allow whitespace before ; in doc comments. ((char-whitespace? c) (read-char *scheme-source*) (body-cmt (peek-char *scheme-source*))) (else (lp (peek-char *scheme-source*))))) ;;Comments incorporated in generated Texinfo files. ;;Transcribe comments to current position in Texinfo file ;;until a non-comment line is reached (may be a blank line). (define (doc-cmt c) (cond ((eof-object? c) (lp c)) ((eqv? #\; c) (out-cmt (read-cmt-line)) (doc-cmt (peek-char *scheme-source*))) ((eqv? c #\newline) (read-char *scheme-source*) (newline *derived-txi*) (lp (peek-char *scheme-source*))) ;; Allow whitespace before ; in doc comments. ((char-whitespace? c) (read-char *scheme-source*) (doc-cmt (peek-char *scheme-source*))) (else (newline *derived-txi*) (lp (peek-char *scheme-source*))))) (lp (peek-char *scheme-source*)))))) (define (schmooz-top-doc-begin def1 defs doc proc-args) (let ((op1 (sexp-def def1))) (cond ((not op1) (or (null? doc) (report "SCHMOOZ: no definition found for Texinfo documentation" doc (car defs)))) (else (let* ((args (def->args def1)) (args (if proc-args (cons (if args (car args) (def->var-name def1)) proc-args) args))) (let loop ((ss defs) (smatch (list (or args (def->var-name def1))))) (if (null? ss) (let ((smatch (reverse smatch))) ((if args schmooz-fun schmooz-var) op1 (car smatch) doc (cdr smatch))) (if (eq? op1 (sexp-def (car ss))) (let ((a (def->args (car ss)))) (loop (cdr ss) (if args (if a (cons a smatch) smatch) (if a smatch (cons (def->var-name (car ss)) smatch))))))))))))) ;;; SCHMOOZ-TOP - schmooz top level form sexp1 ... (define (schmooz-top sexp1 sexps doc proc-args) (cond ((not (pair? sexp1))) ((pair? sexps) (if (pair? doc) (schmooz-top-doc-begin sexp1 sexps doc proc-args)) (set! doc '())) (else (case (car sexp1) ((LOAD REQUIRE) ;If you redefine load, you lose #f) ((BEGIN) (schmooz-top (cadr sexp1) '() doc proc-args) (set! doc '()) (for-each (lambda (s) (schmooz-top s '() doc #f)) (cddr sexp1))) ((DEFVAR DEFINE DEFCONST DEFINE-SYNTAX DEFMACRO) (let* ((args (def->args sexp1)) (args (if proc-args (cons (if args (car args) (cadr sexp1)) proc-args) args))) (cond (args (set! *procedure* (car args)) (cond ((pair? doc) (schmooz-fun (car sexp1) args doc '()) (set! doc '())))) (else (cond ((pair? doc) (schmooz-var (car sexp1) (cadr sexp1) doc '()) (set! doc '())))))))))) (or (null? doc) (report "SCHMOOZ: no definition found for Texinfo documentation" doc sexp1)) (set! *procedure* #f))
false
a2382e552cca8d01948abd39c1aa48879240293c
2ff77aed2df384e78c210ef28f607c23352e5b8d
/examples/10-openglcubes/lesson05.scm
a92a22b6cc8fc2f7816fc0b73b15be46a9a010eb
[ "Apache-2.0" ]
permissive
rafleon/KawaDroid
14d65fb74686c421cab4ca9785266daa321ffacc
5b218826146320f442a55e20171875cb208c7b56
refs/heads/master
2020-12-24T15:58:15.249818
2015-05-12T05:07:51
2015-05-12T05:07:51
33,094,259
18
3
null
null
null
null
UTF-8
Scheme
false
false
2,152
scm
lesson05.scm
(require 'android-defs) (require 'srfi-1) (define-alias gl10 javax.microedition.khronos.opengles.GL10) (define-alias egl-config javax.microedition.khronos.egl.EGLConfig) (define-alias renderer android.opengl.GLSurfaceView$Renderer) (define-alias glu android.opengl.GLU) (define-simple-class lesson05 (renderer) ;; an all-purpose state variable (mys::gnu.lists.Pair access: 'private init: '(0 0 0 0)) ;; I was getting ClassCastException, so I set them to Object. (pyramid :: Object) (pyramid2 :: Object) (cube :: Object) (cube2 :: Object) ((*init*) (set! pyramid (Pyramid)) (set! pyramid2 (Pyramid)) (set! cube (Cube)) (set! cube2 (Cube))) ((onSurfaceCreated (gl :: gl10) (config :: egl-config)) :: void (gl:glShadeModel gl10:GL_SMOOTH) (gl:glClearColor 0.0 0.0 0.0 0.5) (gl:glClearDepthf 1.0) (gl:glEnable gl10:GL_DEPTH_TEST) (gl:glDepthFunc gl10:GL_LEQUAL) (gl:glHint gl10:GL_PERSPECTIVE_CORRECTION_HINT gl10:GL_NICEST)) ((onDrawFrame (gl :: gl10)) :: void (gl:glClear (bitwise-ior gl10:GL_COLOR_BUFFER_BIT gl10:GL_DEPTH_BUFFER_BIT)) (gl:glLoadIdentity) (gl:glTranslatef 0.8 -1.0 -7.0) (gl:glScalef 0.5 0.5 0.5) (gl:glRotatef (first mys) 0.0 1.0 1.0) (cube:draw gl) (gl:glLoadIdentity) (gl:glTranslatef -0.8 1.0 -7.0) (gl:glScalef 0.5 0.5 0.5) (gl:glRotatef (second mys) 1.0 0.0 1.0) (cube2:draw gl) (gl:glLoadIdentity) (gl:glTranslatef 0.8 1.0 -6.0) (gl:glScalef 0.5 0.5 0.5) (gl:glRotatef (third mys) 0.3 1.0 0.0) (pyramid:draw gl) (gl:glLoadIdentity) (gl:glTranslatef -0.8 -1.0 -6.0) (gl:glScalef 0.5 0.5 0.5) (gl:glRotatef (fourth mys) 0.0 0.9 0.3) (pyramid2:draw gl)) ((onSurfaceChanged (gl :: gl10) (width :: int) (height :: int)) :: void (set! height (if (= height 0) 1 height)) (gl:glViewport 0 0 width height) (gl:glMatrixMode gl10:GL_PROJECTION) (gl:glLoadIdentity) (glu:gluPerspective gl 45 (/ (as float width) (as float height)) 0.1 100.0) (gl:glMatrixMode gl10:GL_MODELVIEW) (gl:glLoadIdentity)) ((setState (news::gnu.lists.Pair))::void (set! mys news)) ((getState)::gnu.lists.Pair mys) )
false
9ee2ffe08d4cebab9196d32244fc68a56f07fb62
8c4c89fe51548176e8dbe8a736066e6d00e09c44
/scratch/article.scm
96af8e68109d5837501e0a5c1650d82fdca11665
[ "BSD-3-Clause" ]
permissive
caelia/civet
f5b59c979a035a18cba9beae2043e02ccddcbc9d
2b93395539207f7c531f89887207fcf9e3651985
refs/heads/master
2023-08-19T08:57:55.135790
2013-10-09T12:14:48
2013-10-09T12:14:48
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
809
scm
article.scm
(use civet) (define my-vars '((urlScheme . "http") (hostName . "blog.therebetygers.net") (articleID . "deadbeef") (jquerySrc . "/scripts/jquery.js") (bodyMD . "Some Markdown") (canEdit . #t) (bodyClasses . "SingleArticle BlogPost") (htmlTitle . "Article Pagina") (seriesTitle . "Legendary Cheeses") (partNo . "41") (articleTitle . "Gjetost") (articleSubTitle . "It's sweet-ish but not Swedish--it's Norwegian!") (articleBody . "Yes indeed, bla bla bla and so on.") (currentPath . "/road/to/nowhere") (copyrightYear . "2012-2013") (authorName . "A. Nonny Mouse") (rightsStatement . "All rights reserved."))) (define my-context (make-context vars: my-vars)) (render "article.html" my-context file: "article1.html") ; (process-template-set "article.html" my-context)
false
e9dbc525bf18052aec57b7c7370b87beaf7236b7
21981ae61e2255ea40e34084a774c3400e2e6c96
/src/on-lisp.scm
331e99d47b49c944868823c4772cc46dfc41c3dd
[]
no_license
DalekBaldwin/on-lisp
b2a62bbdbf965549a5404ac093e07e4891784f49
b13e8b6e956bef45c4fd7194a062c27555268048
refs/heads/master
2022-11-22T02:25:01.040867
2015-05-14T21:09:51
2015-05-14T21:09:51
13,301,961
346
52
null
2022-11-20T00:19:35
2013-10-03T15:27:41
Common Lisp
UTF-8
Scheme
false
false
5,871
scm
on-lisp.scm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Chapter 20 - Continuations ;; p. 264 (define (dft tree) (cond ((null? tree) ()) ((not (pair? tree)) (write tree)) (else (dft (car tree)) (dft (cdr tree))))) (define *saved* ()) (define (dft-node tree) (cond ((null? tree) (restart)) ((not (pair? tree)) tree) (else (call-with-current-continuation (lambda (cc) (set! *saved* (cons (lambda () (cc (dft-node (cdr tree)))) *saved*)) (dft-node (car tree))))))) (define (restart) (if (null? *saved*) 'done (let ((cont (car *saved*))) (set! *saved* (cdr *saved*)) (cont)))) (define (dft2 tree) (set! *saved* ()) (let ((node (dft-node tree))) (cond ((eq? node 'done) ()) (else (write node) (restart))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Chapter 22 - Nondeterminism ;; p. 290 ;; deterministic (define (descent n1 n2) (if (eq? n1 n2) (list n2) (let ((p (try-paths (kids n1) n2))) (if p (cons n1 p) #f)))) (define (try-paths ns n2) (if (null? ns) #f (or (descent (car ns) n2) (try-paths (cdr ns) n2)))) ;; nondeterministic (define (descent n1 n2) (cond ((eq? n1 n2) (list n2)) ((null? (kids n1)) (fail)) (else (cons n1 (descent (choose (kids n1)) n2))))) ;; p. 291 (define (two-numbers) (list (choose '(0 1 2 3 4 5)) (choose '(0 1 2 3 4 5)))) (define (parlor-trick sum) (let ((nums (two-numbers))) (if (= (apply + nums) sum) `(the sum of ,@nums) (fail)))) ;; p. 293 (define *paths* ()) (define failsym '@) (define (choose choices) (if (null? choices) (fail) (call-with-current-continuation (lambda (cc) (set! *paths* (cons (lambda () (cc (choose (cdr choices)))) *paths*)) (car choices))))) ;;(define (choose choices) ;; (if (null? choices) ;; (fail) ;; (call-with-current-continuation ;; (lambda (cc) ;; (push *paths* ;; (lambda () (cc (choose (cdr choices))))) ;; (car choices))))) (define fail) (call-with-current-continuation (lambda (cc) (set! fail (lambda () (if (null? *paths*) (cc failsym) (let ((p1 (car *paths*))) (set! *paths* (cdr *paths*)) (p1))))))) ;;(call-with-current-continuation ;; (lambda (cc) ;; (define (fail) ;; (if (null? *paths*) ;; (cc failsym) ;; ((pop *paths*)))))) ;; p. 300 ;; exhaustive search (define (find-boxes) (set! *paths* ()) (let ((city (choose '(la ny bos)))) (newline) (let* ((store (choose '(1 2))) (box (choose '(1 2)))) (let ((triple (list city store box))) (display triple) (if (coin? triple) (display 'c)) (fail))))) (define (coin? x) (member x '((la 1 2) (ny 1 1) (bos 2 2)))) ;; p. 301 (define (mark) (set! *paths* (cons fail *paths*))) ;; http://www.paulgraham.com/onlisperrata.html: ;; p. 301 In Figure 22.9, equal? should be eq?. Caught by Francois-Rene Rideau. (define (cut) (cond ((null? *paths*)) ((eq? (car *paths*) fail) (set! *paths* (cdr *paths*))) (else (set! *paths* (cdr *paths*)) (cut)))) ;; pruned search (define (find-boxes) (set! *paths* ()) (let ((city (choose '(la ny bos)))) (mark) (newline) (let* ((store (choose '(1 2))) (box (choose '(1 2)))) (let ((triple (list city store box))) (display triple) (if (coin? triple) (begin (cut) (display 'c))) (fail))))) ;; p. 303 ;; deterministic (define (path node1 node2) (bf-path node2 (list (list node1)))) (define (bf-path dest queue) (if (null? queue) '@ (let* ((path (car queue)) (node (car path))) (if (eq? node dest) (cdr (reverse path)) (bf-path dest (append (cdr queue) (map (lambda (n) (cons n path)) (neighbors node)))))))) ;; nondeterministic (define (path node1 node2) (cond ((null? (neighbors node1)) (fail)) ((memq node2 (neighbors node1)) (list node2)) (else (let ((n (true-choose (neighbors node1)))) (cons n (path n node2)))))) ;; p. 304 (define *paths* ()) (define failsym '@) (define (true-choose choices) (call-with-current-continuation (lambda (cc) (set! *paths* (append *paths* (map (lambda (choice) (lambda () (cc choice))) choices))) (fail)))) ;;(define *choice-pts* (make-symbol-table)) ;;(define-syntax (true-choose choices) ;; `(choose-fn ,choices ',(generate-symbol t))) ;;(define (choose-fn choices tag) ;; (if (null? choices) ;; (fail) ;; (call-with-current-continuation ;; (lambda (cc) ;; (push *paths* ;; (lambda () (cc (choose-fn (cdr choices) ;; tag)))) ;; (if (mem equal? (car choices) ;; (table-entry *choice-pts* tag)) ;; (fail) ;; (car (push (table-entry *choice-pts* tag) ;; (car choices)))))))) (define fail) (call-with-current-continuation (lambda (cc) (set! fail (lambda () (if (null? *paths*) (cc failsym) (let ((p1 (car *paths*))) (set! *paths* (cdr *paths*)) (p1)))))))
true
e3de166dceaff6555521a34eb35ff5d810abdd16
6b961ef37ff7018c8449d3fa05c04ffbda56582b
/bbn_cl/mach/zcomp/rtlgen/rgstmt.scm
5fa52a403371757f8782552b2f2edcb8a620ebd4
[]
no_license
tinysun212/bbn_cl
7589c5ac901fbec1b8a13f2bd60510b4b8a20263
89d88095fc2a71254e04e57cf499ae86abf98898
refs/heads/master
2021-01-10T02:35:18.357279
2015-05-26T02:44:00
2015-05-26T02:44:00
36,267,589
4
3
null
null
null
null
UTF-8
Scheme
false
false
8,464
scm
rgstmt.scm
#| -*-Scheme-*- $Header: rgstmt.scm,v 1.3 88/12/15 10:21:56 las Exp $ $MIT-Header: rgstmt.scm,v 4.3 88/03/14 20:55:03 GMT jinx Exp $ Copyright (c) 1987 Massachusetts Institute of Technology This material was developed by the Scheme project at the Massachusetts Institute of Technology, Department of Electrical Engineering and Computer Science. Permission to copy this software, to redistribute it, and to use it for any purpose is granted, subject to the following restrictions and understandings. 1. Any copy made of this software must include this copyright notice in full. 2. Users of this software agree to make their best efforts (a) to return to the MIT Scheme project any improvements or extensions that they make, so that these may be included in future releases; and (b) to inform MIT of noteworthy uses of this software. 3. All materials developed as a consequence of the use of this software shall duly acknowledge such use, in accordance with the usual standards of acknowledging credit in academic research. 4. MIT has made no warrantee or representation that the operation of this software will be error-free, and MIT is under no obligation to provide any services, by way of maintenance, update, or otherwise. 5. In conjunction with products arising from the use of this material, there shall be no use of the name of the Massachusetts Institute of Technology nor of any adaptation thereof in any advertising, promotional, or sales literature without prior written consent from MIT in each case. |# ;;;; RTL Generation: Statements (declare (usual-integrations)) ;;;; Assignments (define (generate/assignment assignment) (let ((block (assignment-block assignment)) (lvalue (assignment-lvalue assignment)) (rvalue (assignment-rvalue assignment)) (offset (node/offset assignment))) (if (lvalue-integrated? lvalue) (make-null-cfg) (generate/rvalue rvalue offset scfg*scfg->scfg! (lambda (expression) (find-variable block lvalue offset (lambda (locative) (rtl:make-assignment locative expression)) (lambda (environment name) (rtl:make-interpreter-call:set! environment (intern-scode-variable! block name) expression)) (lambda (name) (generate/cached-assignment name expression)))))))) (define (generate/cached-assignment name value) (let* ((temp (rtl:make-pseudo-register)) (cell (rtl:make-fetch temp)) (contents (rtl:make-fetch cell)) (n1 (rtl:make-assignment temp (rtl:make-assignment-cache name)))) ;; n1 MUST be bound before the rest. It flags temp as a ;; register that contains an address. (let ((n2 (rtl:make-type-test (rtl:make-object->type contents) (ucode-type reference-trap))) (n3 (rtl:make-unassigned-test contents)) (n4 (rtl:make-assignment cell value)) (n5 (rtl:make-interpreter-call:cache-assignment cell value)) ;; Copy prevents premature control merge which confuses CSE (n6 (rtl:make-assignment cell value))) (scfg-next-connect! n1 n2) (pcfg-consequent-connect! n2 n3) (pcfg-alternative-connect! n2 n4) (pcfg-consequent-connect! n3 n6) (pcfg-alternative-connect! n3 n5) (make-scfg (cfg-entry-node n1) (hooks-union (scfg-next-hooks n4) (hooks-union (scfg-next-hooks n5) (scfg-next-hooks n6))))))) (define (generate/definition definition) (let ((block (definition-block definition)) (lvalue (definition-lvalue definition)) (rvalue (definition-rvalue definition)) (offset (node/offset definition))) (generate/rvalue rvalue offset scfg*scfg->scfg! (lambda (expression) (transmit-values (find-definition-variable block lvalue offset) (lambda (environment name) (rtl:make-interpreter-call:define environment name expression))))))) ;;;; Virtual Returns (define (generate/virtual-return return) (let ((operator (virtual-return-operator return)) (operand (virtual-return-operand return)) (offset (node/offset return))) (if (virtual-continuation/reified? operator) (generate/trivial-return (virtual-return-block return) (virtual-continuation/reification operator) operand offset) (enumeration-case continuation-type (virtual-continuation/type operator) ((EFFECT) (make-null-cfg)) ((REGISTER VALUE) (operand->register operand offset (virtual-continuation/register operator))) ((PUSH) (let ((block (virtual-continuation/block operator))) (cond ((rvalue/block? operand) (rtl:make-push (rtl:make-environment (block-ancestor-or-self->locative block operand offset)))) ((rvalue/continuation? operand) ;; This is a pun set up by the FG generator. (generate/continuation-cons block operand)) (else (operand->push operand offset))))) (else (error "Unknown continuation type" return)))))) (define (operand->push operand offset) (generate/rvalue operand offset scfg*scfg->scfg! rtl:make-push)) (define (operand->register operand offset register) (generate/rvalue operand offset scfg*scfg->scfg! (lambda (expression) (rtl:make-assignment register expression)))) (define (generate/continuation-cons block continuation) (let ((closing-block (continuation/closing-block continuation))) (scfg-append! (if (ic-block? closing-block) (rtl:make-push (rtl:make-fetch register:environment)) (make-null-cfg)) (if (block/dynamic-link? closing-block) (rtl:make-push-link) (make-null-cfg)) (if (continuation/always-known-operator? continuation) (make-null-cfg) (begin (enqueue-continuation! continuation) (rtl:make-push-return (continuation/label continuation))))))) (define (generate/pop pop) (rtl:make-pop (continuation*/register (pop-continuation pop)))) ;;;; Predicates (define (generate/true-test true-test) (generate/predicate (true-test-rvalue true-test) (pnode-consequent true-test) (pnode-alternative true-test) (node/offset true-test))) (define (generate/predicate rvalue consequent alternative offset) (if (rvalue/unassigned-test? rvalue) (generate/unassigned-test rvalue consequent alternative offset) (let ((value (rvalue-known-value rvalue))) (if value (generate/known-predicate value consequent alternative) (pcfg*scfg->scfg! (generate/rvalue rvalue offset scfg*pcfg->pcfg! rtl:make-true-test) (generate/node consequent) (generate/node alternative)))))) (define (generate/known-predicate value consequent alternative) (generate/node (if (and (constant? value) (false? (constant-value value))) alternative consequent))) (define (generate/unassigned-test rvalue consequent alternative offset) (let ((block (unassigned-test-block rvalue)) (lvalue (unassigned-test-lvalue rvalue))) (let ((value (lvalue-known-value lvalue))) (cond ((not value) (pcfg*scfg->scfg! (find-variable block lvalue offset (lambda (locative) (rtl:make-unassigned-test (rtl:make-fetch locative))) (lambda (environment name) (scfg*pcfg->pcfg! (rtl:make-interpreter-call:unassigned? environment name) (rtl:make-true-test (rtl:interpreter-call-result:unassigned?)))) generate/cached-unassigned?) (generate/node consequent) (generate/node alternative))) ((and (rvalue/constant? value) (scode/unassigned-object? (constant-value value))) (generate/node consequent)) (else (generate/node alternative)))))) (define (generate/cached-unassigned? name) (let* ((temp (rtl:make-pseudo-register)) (cell (rtl:make-fetch temp)) (reference (rtl:make-fetch cell)) (n1 (rtl:make-assignment temp (rtl:make-variable-cache name)))) ;; n1 MUST be bound before the rest. It flags temp as a ;; register that contains an address. (let ((n2 (rtl:make-type-test (rtl:make-object->type reference) (ucode-type reference-trap))) (n3 (rtl:make-unassigned-test reference)) (n4 (rtl:make-interpreter-call:cache-unassigned? cell)) (n5 (rtl:make-true-test (rtl:interpreter-call-result:cache-unassigned?)))) (scfg-next-connect! n1 n2) (pcfg-consequent-connect! n2 n3) (pcfg-alternative-connect! n3 n4) (scfg-next-connect! n4 n5) (make-pcfg (cfg-entry-node n1) (hooks-union (pcfg-consequent-hooks n3) (pcfg-consequent-hooks n5)) (hooks-union (pcfg-alternative-hooks n2) (pcfg-alternative-hooks n5))))))
false
3f2b799a4693b5406fa4cd3d7d72ea59bffb4b6e
d369542379a3304c109e63641c5e176c360a048f
/brice/Chapter2/exercise-2.38.scm
ac21766b8baf35bbdd3ca608b6c69f6a9e5413c9
[]
no_license
StudyCodeOrg/sicp-brunches
e9e4ba0e8b2c1e5aa355ad3286ec0ca7ba4efdba
808bbf1d40723e98ce0f757fac39e8eb4e80a715
refs/heads/master
2021-01-12T03:03:37.621181
2017-03-25T15:37:02
2017-03-25T15:37:02
78,152,677
1
0
null
2017-03-25T15:37:03
2017-01-05T22:16:07
Scheme
UTF-8
Scheme
false
false
1,463
scm
exercise-2.38.scm
#lang racket (require "../utils.scm") (require "../meta.scm") (title "Exercise 2.38") (provide fold-left) ; Exercise 2.38. The accumulate procedure is also known as fold-right, ; because it combines the first element of the sequence with the result ; of combining all the elements to the right. There is also a fold-left, ; which is similar to fold-right, except that it combines elements ; working in the opposite direction: (define (fold-left op initial sequence) (define (iter result rest) (if (null? rest) result (iter (op result (car rest)) (cdr rest)))) (iter initial sequence)) ; What are the values of (assertequal? "We understand foldr with numbers" (foldr / 1 (list 1 2 3)) (/ 1 (/ 2 (/ 3 1)))) (assertequal? "We understand fold-left with numbers" (fold-left / 1 (list 1 2 3)) (/ 1 1 2 3)) (assertequal? "We understand foldr with lists" (foldr list nil (list 1 2 3)) (list 1 (list 2 (list 3 nil)))) (assertequal? "We understand fold-left with lists" (fold-left list nil (list 1 2 3)) (list (list (list nil 1) 2) 3)) ; Give a property that op should satisfy to guarantee that fold-right and ; fold-left will produce the same values for any sequence. (prn " For fold-left and fold-right to produce the same value `a op b` and `b op a` should also produce the same values ie, the operator should be commutative.") (prn " Note: the book's `fold-left` is *not* analogous to scheme's `foldl`!")
false
3809eb1c4182020d8543fc7de370ec6324060a62
d074b9a2169d667227f0642c76d332c6d517f1ba
/sicp/ch_3/exercise.3.18.scm
4ec31934d548b1b2e469ce763ad4483fadc00f2a
[]
no_license
zenspider/schemers
4d0390553dda5f46bd486d146ad5eac0ba74cbb4
2939ca553ac79013a4c3aaaec812c1bad3933b16
refs/heads/master
2020-12-02T18:27:37.261206
2019-07-14T15:27:42
2019-07-14T15:27:42
26,163,837
7
0
null
null
null
null
UTF-8
Scheme
false
false
1,050
scm
exercise.3.18.scm
#lang racket/base (require "../lib/test.rkt") (require rnrs/mutable-pairs-6) ;;; Exercise 3.18 ;; Write a procedure that examines a list and determines whether it ;; contains a cycle, that is, whether a program that tried to find the ;; end of the list by taking successive `cdr's would go into an ;; infinite loop. *Note Exercise 3-13:: constructed such lists. (define cdr-cycle '(a b c)) (set-cdr! (cddr cdr-cycle) cdr-cycle) (define car-cycle '(a b c)) (set-car! car-cycle car-cycle) (define (cyclic? x) (let ((visited '())) (define (iterate l) (define (test f) (let ((cell (f l))) (and (pair? cell) (or (memq cell visited) (begin (set! visited (cons cell visited)) (and (iterate cell) #t)))))) (if (null? l) #f (or (test car) (test cdr)))) (iterate x))) (test-group "3.18" (test #f (cyclic? '(a b c))) (test #t (cyclic? car-cycle)) (test #t (cyclic? cdr-cycle)))
false
2052b0a5983af55840275c7549dd2cfa5d91a17f
f033ff2c78c89e2d7d24d7b8e711fa6d1b230142
/ccc/concurrent/tests/module1.scm
38d4911eb10a8b7f435d30e1171b54c285b8f99f
[]
no_license
zane/research
3cb47d47bb2708f6e83ee16cef89647a47db139d
8b4ecfe6035fe30c9113f3add380c91598f7262a
refs/heads/master
2021-01-01T19:09:58.166662
2009-12-16T16:53:57
2009-12-16T16:53:57
62,193
1
0
null
null
null
null
UTF-8
Scheme
false
false
153
scm
module1.scm
(module module1 scheme (provide my-list) (require scheme/mpair) (define my-list (begin (printf "hi") (mcons 3 null))))
false
935bc3009daa1abf491b908cf131fbba1a12ff0f
dbfef02df59ad4c3569e134e6d747bda51ebe828
/offby1/histogram.ss
549e340fe5507e54ae9569e008b5ccdba180d135
[]
no_license
offby1/plt-collects
41c8dc3dfccfa02acb78fd9191405f5d2f8fce27
6f6cd468d4db728afc1f8decf1346501c258c6ba
refs/heads/master
2021-01-10T20:58:01.060056
2011-06-18T22:52:10
2011-06-18T22:52:10
94,649
1
0
null
null
null
null
UTF-8
Scheme
false
false
1,095
ss
histogram.ss
#! /bin/sh #| Hey Emacs, this is -*-scheme-*- code! #$Id$ exec mzscheme --require "$0" --main -- ${1+"$@"} |# #lang scheme (require (planet schematics/schemeunit:3) (planet schematics/schemeunit:3/text-ui)) (provide list->histogram main) (define (list->histogram l) (hash-map (for/fold ([rv (make-immutable-hash '())]) ([elt (in-list l)]) (hash-update rv elt add1 0)) cons)) ;; makes it easier to test, if we know the order in which the pairs ;; appear. Note that the mzlib "sort" function, happily, is stable. (define (cdr-sort l) (sort l < #:key cdr)) (define (main . args) (exit (run-tests (test-suite "The one and only suite" (test-case "duh" (check-equal? (cdr-sort (list->histogram '(1 2 3 2 0 1 1 1 1 1 1))) '((0 . 1) (3 . 1) (2 . 2) (1 . 7)))) (test-case "non-numbers" (check-equal? (cdr-sort (list->histogram '((1 . 2) (2 . 1) (1 . 2)))) '(((2 . 1) . 1) ((1 . 2) . 2))))))))
false
ada42046729b5b102b9cce67c28b841dc86d32a8
b26941aa4aa8da67b4a7596cc037b92981621902
/SICP/done/2-83-test.scm
3fee4047c644942fd2235ad312f9a1d1f0c41b24
[]
no_license
Alaya-in-Matrix/scheme
a1878ec0f21315d5077ca1c254c3b9eb4c594c10
bdcfcf3367b664896e8a7c6dfa0257622493e184
refs/heads/master
2021-01-01T19:42:32.633019
2015-01-31T08:24:02
2015-01-31T08:24:02
22,753,765
0
0
null
null
null
null
UTF-8
Scheme
false
false
181
scm
2-83-test.scm
(load "sicp.scm") (install-package) (define n (make-scheme-number 3)) (define r (make-rational 3 23)) (define c (make-complex-from-real-imag 3 4)) (define x (make-real 3.14))
false
9337455bc853804a256cf7ab11e5471163b50dea
4bd59493b25febc53ac9e62c259383fba410ec0e
/Scripts/Task/comments/scheme/comments.ss
01035ebfb2d4e8544ee40c6dd338e8ecbbfb20fd
[]
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
228
ss
comments.ss
; Basically the same as Common Lisp ; While R5RS does not provide block comments, they are defined in SRFI-30, as in Common Lisp : #| comment ... #| nested comment ... |# |# ; See http://srfi.schemers.org/srfi-30/srfi-30.html
false
d4b58eb7aa45949ec4017c39dae37b7b6e02e490
cca999903bc2305da28e598c46298e7d31dbdef5
/src/web/collections/bootstrap2015/bootstrap-tilt-teachpack.ss
7afb37765c6e73d08b1deef20d56cfd15ea8c562
[ "Apache-2.0" ]
permissive
ds26gte/kode.pyret.org
211183f7045f69cf998a8ebd8a9373cd719d29a1
534f2d4b61a6d6c650a364186a4477a52d1cd986
refs/heads/master
2021-01-11T14:56:43.120765
2018-05-02T22:27:55
2018-05-02T22:27:55
80,234,747
0
0
null
null
null
null
UTF-8
Scheme
false
false
20,825
ss
bootstrap-tilt-teachpack.ss
(provide play make-game *score* *player-x* *player-y*) ;; SETTINGS (define WIDTH 640) (define HEIGHT 480) (define EXPLOSION-COLOR "gray") (define TITLE-COLOR (box "white")) (define BACKGROUND (box(rectangle WIDTH HEIGHT "solid" "black"))) (define (spacing) (random 200)) (define *target-increment* 20) (define *danger-increment* -50) (define LOSS-SCORE 0) (define GAMEOVER_IMG (bitmap/url "http://www.wescheme.org/images/teachpacks2012/gameover.png")) ;; Globals available to the students: (define *score* (box 0)) (define *player-x* (box 0)) (define *player-y* (box 0)) ;; Student debugging: (define *line-length* (box (lambda(a b) 0))) (define *distance* (box (lambda(px cx py cy) 0))) (define *distances-color* (box "")) ; how tolerant are we of tilt events? (only used in tilt teachpack) (define TOLERANCE 20) (define -TOLERANCE (- TOLERANCE)) ;; People hold devices at a beta tilt of around 40 degrees. (define RESTING-TOP-DOWN-ORIENTATION 40) ;fit-image-to: number number image -> image ;ensures the image is of size first number by second number, may crop the given image (define (fit-image-to w h an-image) (cond [(= (image-width an-image) (* (/ w h) (image-height an-image))) (scale (/ w (image-width an-image)) an-image)] [(> (image-width an-image) (* (/ w h) (image-height an-image))) (scale (/ w (* (/ w h) (image-height an-image))) (crop 0 0 (* (/ w h) (image-height an-image)) (image-height an-image) an-image))] [(< (image-width an-image) (* (/ w h) (image-height an-image))) (scale (/ w (image-width an-image)) (crop 0 0 (image-width an-image) (* (/ h w) (image-width an-image)) an-image))] )) ; cull : Listof Beings -> Listof Beings ; get rid of every being that's even one pixel offscreen (define (cull beings) (filter (lambda (b) (and (> (being-x b) 0) (< (being-x b) WIDTH) (> (being-y b) 0) (< (being-y b) HEIGHT))) beings)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Game Structures ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; A being is a (make-being Posn Image) (define-struct being [posn costume]) ; A World is a (make-world (Being list) (Being list) (Being list) Being Image Number String Integer) (define-struct world [dangers shots targets player bg score title timer]) ; some easy accessor shortcuts (define being-x (compose posn-x being-posn)) (define being-y (compose posn-y being-posn)) ; Convert world position to screen position. (define (posn->point posn) (make-posn (posn-x posn) (+ HEIGHT (- (posn-y posn))))) ; world-not-mutators (define (world-with-dangers w d) (make-world d (world-shots w) (world-targets w) (world-player w) (world-bg w) (world-score w) (world-title w) (world-timer w))) (define (world-with-shots w s) (make-world (world-dangers w) s (world-targets w) (world-player w) (world-bg w) (world-score w) (world-title w) (world-timer w))) (define (world-with-targets w t) (make-world (world-dangers w) (world-shots w) t (world-player w) (world-bg w) (world-score w) (world-title w) (world-timer w))) (define (world-with-player w p) (make-world (world-dangers w) (world-shots w) (world-targets w) p (world-bg w) (world-score w) (world-title w) (world-timer w))) (define (world-with-score w s) (make-world (world-dangers w) (world-shots w) (world-targets w) (world-player w) (world-bg w) s (world-title w) (world-timer w))) (define (world-with-timer w t) (make-world (world-dangers w) (world-shots w) (world-targets w) (world-player w) (world-bg w) (world-score w) (world-title w) t)) ; add-informative-triangle : Number Number String Image -> Image (define (add-informative-triangle cx cy color background) (let* ((player-point (posn->point (make-posn (unbox *player-x*) (unbox *player-y*)))) (px (posn-x player-point)) (py (posn-y player-point))) (if (and (= px cx) (= py cy)) background ;; don't inform about the player itself (let ((dx (- cx px)) (dy (- cy py)) (n->s (lambda (num) (number->string (inexact->exact (round num)))))) (place-image (text (n->s ((unbox *line-length*) cx px)) 12 color) (- cx (/ dx 2)) cy (place-image (line dx 0 color) (- cx (/ dx 2)) cy (place-image (text (n->s ((unbox *line-length*) cy py)) 12 color) px (- cy (/ dy 2)) (place-image (line 0 dy color) px (- cy (/ dy 2)) (place-image (text (n->s ((unbox *distance*) px py cx cy)) 12 color) (- cx (/ dx 2)) (- cy (/ dy 2)) (place-image (line dx dy color) (- cx (/ dx 2)) (- cy (/ dy 2)) background)))))))))) ; draw-being : Being Image -> Image ; place a being at their screen location, on the BG, in their costume (define (draw-being being background) (let* ((screen-point (posn->point (being-posn being))) (cx (posn-x screen-point)) (cy (posn-y screen-point)) (dbg-bkgnd (if (not (string=? (unbox *distances-color*) "")) (add-informative-triangle cx cy (unbox TITLE-COLOR) background) background))) (place-image (being-costume being) cx cy dbg-bkgnd))) ; draw-world : World -> Image ; draw the world, using either a player's costume or an explosion for the player (define (draw-world w) (let* ((score-string (string-append (world-title w) " score:" (number->string (world-score w)))) (player (if (> (world-timer w) 0) (make-being (being-posn (world-player w)) (radial-star 7 (* 1.5 (world-timer w)) (* .25 (world-timer w)) "solid" EXPLOSION-COLOR)) (world-player w))) (all-beings (append (world-targets w) (world-dangers w) (world-shots w) (list player)))) (begin (set-box! *player-x* (posn-x (being-posn (world-player w)))) (set-box! *player-y* (posn-y (being-posn (world-player w)))) (set-box! *score* (world-score w)) (if (<= (world-score w) 0) GAMEOVER_IMG (place-image (text/font score-string 18 (unbox TITLE-COLOR) #f "default" "italic" "bold" '#t) (quotient (image-width (unbox BACKGROUND)) 2) 20 (foldl draw-being (unbox BACKGROUND) all-beings)))))) ; wrap-update : (Number->Number or Number Number -> Posn) (list String) -> (Being -> Being) ; wrap the update function to ensure that it takes and returns a Being (define (wrap-update f) (cond [(= (procedure-arity f) 1) (lambda (b) (make-being (make-posn (f (being-x b)) (being-y b)) (being-costume b)))] [(= (procedure-arity f) 2) (lambda (b) (let ((new-posn (f (being-x b) (being-y b)))) (if (posn? new-posn) (make-being new-posn (being-costume b)) (begin (error "update-danger or update-target has been changed to accept an x- and y-coordinate, but is not returning a Posn.\n") new-posn))))])) ; reset : Being (Being->Being) -> Being ; returns a new being with the same costume, entering from the correct direction (define (reset being f) (let* ((next-posn (being-posn (f (make-being (make-posn 1 1) #f)))) (next-x (- (posn-x next-posn) 1)) (next-y (- (posn-y next-posn) 1)) (random-posn (if (> (abs next-y) (abs next-x)) (if (< next-y 0) (make-posn (random WIDTH) (+ (spacing) HEIGHT)) (make-posn (random WIDTH) (* (spacing) -1))) (if (< next-x 0) (make-posn (+ (spacing) WIDTH) (random HEIGHT)) (make-posn (* (spacing) -1) (random HEIGHT)))))) (make-being random-posn (being-costume being)))) (define (make-game title title-color background dangerImgs update-danger targetImgs update-target playerImg update-player projectileImgs update-projectile show-distances line-length distance collide onscreen) (list title title-color background dangerImgs update-danger targetImgs update-target playerImg update-player projectileImgs update-projectile show-distances line-length distance collide onscreen)) (define (play game) (apply animate/proc game)) (define (flatten x) (cond ((null? x) '()) ((not (pair? x)) (list x)) (else (append (flatten (car x)) (flatten (cdr x)))))) ; animate/proc:String Image (Image list) (Image list) Image ; (Being -> Being) (Being -> Being) (Being -> Being) ; (Being Being -> Boolean) (Being -> Boolean) -> Boolean ; takes in World components, updating functions and geometry functions and starts the universe (define (animate/proc title title-color background dangerImgs update-danger* targetImgs update-target* playerImg update-player* projectileImg update-projectile* distances-color line-length distance collide*? onscreen*?) (begin ;; error-checking (unless (string? title) (display "ERROR: TITLE must be defined as a string.\n")) (unless (string? title-color) (display "ERROR: TITLE-COLOR must be defined as a string.\n")) (unless (string? distances-color) (display "ERROR: *distances-color* must be defined as a string.\n")) (unless (string? title-color) (display "ERROR: TITLE-COLOR must be defined as a string.\n")) (unless (image? background) (display "ERROR: BACKGROUND must be defined as an image\n.")) (unless (image? playerImg) (display "ERROR: PLAYER must be defined as an image\n.")) (unless (image? projectileImg) (display "ERROR: mystery must be defined as an image\n.")) (unless (andmap image? (flatten (list dangerImgs))) (display "ERROR: DANGERs must be defined as images.\n")) (unless (andmap image? (flatten (list targetImgs))) (display "ERROR: TARGETs must be defined as images.\n")) (unless (procedure? update-danger*) (display "ERROR: update-danger must be defined as a function\n.")) (unless (procedure? update-target*) (display "ERROR: update-target must be defined as a function\n.")) (unless (procedure? update-player*) (display "ERROR: update-player must be defined as a function\n.")) (unless (procedure? update-projectile*)(display "ERROR: update-mystery must be defined as a function\n.")) (unless (procedure? update-player*) (display "ERROR: update-player must be defined as a function\n.")) (unless (procedure? line-length) (display "ERROR: line-length must be defined as a function\n.")) (unless (procedure? distance) (display "ERROR: distance must be defined as a function\n.")) (unless (procedure? collide*?) (display "ERROR: collide? must be defined as a function\n.")) (unless (procedure? onscreen*?) (display "ERROR: onscreen? must be defined as a function\n.")) ;; check for arity (unless (or (= (procedure-arity update-danger*) 1) (= (procedure-arity update-danger*) 2)) (display (string-append "ERROR: expected update-danger to consume one or two inputs, but instead it consumes " (number->string (procedure-arity update-danger*)) " inputs"))) (unless (or (= (procedure-arity update-target*) 1) (= (procedure-arity update-target*) 2)) (display (string-append "ERROR: expected update-target to consume one or two inputs, but instead it consumes " (number->string (procedure-arity update-target*)) " inputs"))) (unless (or (= (procedure-arity update-projectile*) 1) (= (procedure-arity update-projectile*) 2)) (display (string-append "ERROR: expected update-projectile to consume one or two inputs, but instead it consumes " (number->string (procedure-arity update-projectile*)) " inputs"))) (unless (or (= (procedure-arity update-player*) 2) (= (procedure-arity update-player*) 3)) (display (string-append "ERROR: expected update-player to consume two or three inputs, but instead it consumes " (number->string (procedure-arity update-player*)) " inputs"))) (unless (= (procedure-arity line-length) 2) (display (string-append "ERROR: expected line-length to consume two inputs, but instead it consumes " (number->string (procedure-arity line-length)) " inputs"))) (unless (= (procedure-arity distance) 4) (display (string-append "ERROR: expected distance to consume four inputs, but instead it consumes " (number->string (procedure-arity distance)) " inputs"))) (unless (= (procedure-arity collide*?) 4) (display (string-append "ERROR: expected collide? to consume four inputs, but instead it consumes " (number->string (procedure-arity collide*?)) " inputs"))) (unless (or (= (procedure-arity onscreen*?) 1) (= (procedure-arity onscreen*?) 2)) (display (string-append "ERROR: expected onscreen? to consume one or two inputs, but instead it consumes " (number->string (procedure-arity onscreen*?)) " inputs"))) ;; store important values (set-box! TITLE-COLOR title-color) (set-box! BACKGROUND (fit-image-to WIDTH HEIGHT background)) (set-box! *line-length* line-length) (set-box! *distance* distance) (set-box! *distances-color* distances-color) (let* ((player (make-being (make-posn (/ WIDTH 2) (/ HEIGHT 2)) playerImg)) ; normalize all user functions to use Beings, not x/y coords (update-danger (wrap-update update-danger*)) (update-target (wrap-update update-target*)) (update-projectile (wrap-update update-projectile*)) (update-player (lambda (p k)(make-being (if (= (procedure-arity update-player*) 2) (make-posn (being-x p) (update-player* (being-y p) k)) (let ((new-posn (update-player* (being-x p) (being-y p) k))) (if (posn? new-posn) new-posn (begin (error "update-player has been changed to accept an x- and y-coordinate, but is not returning a Posn.\n") new-posn)))) (being-costume p)))) (onscreen? (if (= (procedure-arity onscreen*?) 1) (lambda (b) (onscreen*? (being-x b))) (lambda (b) (onscreen*? (being-x b) (being-y b))))) (collide? (lambda (b1 b2) (collide*? (being-x b1) (being-y b1) (being-x b2) (being-y b2)))) ; did a being collide with any of it's enemies? (hit-by? (lambda (b enemies) (ormap (lambda (e) (collide? b e)) enemies))) ; reset if a character hit an enemy or went offscreen, update otherwise (reset-chars (lambda (chars enemies update) (map (lambda (b) (if (and (onscreen? b) (not (hit-by? b enemies))) (update b) (reset b update))) chars))) ; initialize lists of shots, targets, and dangers using "reset" (targets (map (lambda (img) (reset (make-being (make-posn 0 0) img) update-target)) (flatten (list targetImgs)))) (dangers (map (lambda (img) (reset (make-being (make-posn 0 0) img) update-danger)) (flatten (list dangerImgs)))) (shots '()) ; initialize the world, using a starting score of 100 and the explosion set to 0 (world (make-world dangers shots targets player background 100 title 0)) ; keypress : World String -> World (keypress (lambda(w key) (cond [(and (string=? key " ") (<= (world-score w) LOSS-SCORE)) world] [(<= (world-score w) LOSS-SCORE) w] [(string=? key "release") w] [(string=? key "escape") (world-with-timer w -1)] [(and (string=? key " ") (or (> (procedure-arity update-projectile*) 1) (not (= (update-projectile* 100) 100)))) (world-with-shots w (cons (make-being (make-posn (unbox *player-x*) (unbox *player-y*)) projectileImg) (world-shots w)))] [else (world-with-player w (update-player (world-player w) key))]))) ; update-world : World -> World (update-world (lambda (w) (let* ((player (world-player w)) (bg (world-bg w)) (title (world-title w)) (timer (world-timer w)) ; dangers and targets can be shot, shots and the player can be hit (shootables (append (world-dangers w) (world-targets w))) (hitables (cons player (world-shots w))) ; reset characters that've been hit or shot, update those that haven't, ; and cull projectiles that have gone offscreen (dangers (reset-chars (world-dangers w) hitables update-danger)) (targets (reset-chars (world-targets w) hitables update-target)) (projectiles (reset-chars (cull (world-shots w)) shootables update-projectile)) ; get points for shooting down dangers (score (+ (world-score w) (if (ormap (lambda(s) (hit-by? s (world-dangers w))) (world-shots w)) *target-increment* 0)))) ; check for gameover, collisions with the *original* dangers / targets (cond [(<= (world-score w) LOSS-SCORE) w] [(> (world-timer w) 0) (make-world dangers projectiles targets player bg score title (- timer 10))] [(hit-by? player (world-dangers w)) (make-world dangers projectiles targets player bg (+ score *danger-increment*) title 100)] [(hit-by? player (world-targets w)) (make-world dangers projectiles targets player bg (+ score *target-increment*) title (world-timer w))] [else (make-world dangers projectiles targets player bg score title timer)])) )) ; tilt/tap -- only used in tilt teachpack (tilt (lambda (w x y) (cond [(> x TOLERANCE) (keypress w "right")] [(< x -TOLERANCE) (keypress w "left")] [(> (- y RESTING-TOP-DOWN-ORIENTATION) TOLERANCE) (keypress w "down")] [(< (- y RESTING-TOP-DOWN-ORIENTATION) -TOLERANCE) (keypress w "up")] [else w]))) (tap (lambda (w x y) (keypress w " ")))) (big-bang world (stop-when (lambda(w) (= (world-timer w) -1))) (on-tick update-world .1) (to-draw draw-world) ;(on-key keypress) (on-tilt tilt) (on-tap tap) ))))
false
7c782c04a3bcbf9547c3edaef9201d90286a0f8c
4fd95c081ccef6afc8845c94fedbe19699b115b6
/chapter_4/4.2.scm
111fb66b7f4f8dcfda9ca2f507ca867f46a2c18a
[ "MIT" ]
permissive
ceoro9/sicp
61ff130e655e705bafb39b4d336057bd3996195d
7c0000f4ec4adc713f399dc12a0596c770bd2783
refs/heads/master
2020-05-03T09:41:04.531521
2019-08-08T12:14:35
2019-08-08T12:14:35
178,560,765
1
0
null
null
null
null
UTF-8
Scheme
false
false
469
scm
4.2.scm
; A) ; > A procedure application is any compound expression that is not one of the above expression types. ; Since we place application clause before definition, ; evaluation of (define x 3) expression will be caught by ; application handler and it will try to call define method ; on x and 3 arguments resulting in inappropriate behavior. ; ; B) (define (application? exp) (tagged-list exp 'call)) (define (operator exp) (car exp)) (define (operands exp) (cdr exp))
false
cd6f1a8dda1fe5ca544091f0c3952e1b93295560
309e1d67d6ad76d213811bf1c99b5f82fa2f4ee2
/A10.ss
8467cc39521bbf6d43db86552a1682880b7ac58c
[]
no_license
lix4/CSSE304-Programming-Language-Concept-Code
d8c14c18a1baa61ab5d3df0b1ac650bdebc59526
dd94262865d880a357e85f6def697661e11c8e7a
refs/heads/master
2020-08-06T02:50:53.307301
2016-11-12T03:03:56
2016-11-12T03:03:56
73,528,000
1
1
null
null
null
null
UTF-8
Scheme
false
false
2,379
ss
A10.ss
;;Xiwen Li ;;Assignment 10 ;;1 (define free-vars (lambda (exp) (cond [(symbol? exp) (list exp)] [(equal? (car exp) 'lambda) (cond [(symbol? (caddr exp)) (if (member? (caddr exp) (cadr exp)) '() (list (caddr exp)))] [(equal? (caaddr exp) 'lambda) (free-vars (caddr exp))] [else (free-vars-rec (caddr exp) (cadr exp))])] [else (if (and (symbol? (car exp)) (equal? (car exp) (cadr exp))) (list (car exp)) (append (free-vars (car exp)) (free-vars (cadr exp))))]))) (define free-vars-rec (lambda (ls target) (cond [(null? ls) '()] [(equal? (car ls) target) (free-vars-rec (cdr ls) target)] [else (append (list (car ls)) (free-vars-rec (cdr ls) target))]))) (define bound-vars (lambda (exp) (cond [(symbol? exp) exp] [(equal? (car exp) 'lambda) (let ([dels (cadr exp)] [body (caddr exp)]) (cond [(symbol? body) (if (member? body dels) (list body) '())] [(equal? (car body) 'lambda) (bound-vars body)] [(equal? (caadr body) 'lambda) (bound-vars (cadr body))] [else (bound-vars-rec body dels)]))] [else (if (symbol? (car exp)) (bound-vars (cadr exp)) (append (bound-vars (car exp)) (bound-vars (cadr exp))))]))) (define bound-vars-rec (lambda (ls target) (cond [(null? ls) '()] [(equal? (car ls) target) (append (list (car ls)) (bound-vars-rec (cdr ls) target))] [else (bound-vars-rec (cdr ls) target)]))) (define member? (lambda (target ls) (cond [(null? ls) #f] [(equal? (car ls) target) #t] [else (member? target (cdr ls))]))) ;;2 (define occurs-free? (lambda (var exp) (cond [(symbol? exp) (eqv? var exp)] [(eqv? (car exp) 'lambda) (and (not (eqv? (caadr exp) var)) (occurs-free? var (caddr exp)))] [else (or (occurs-free? var (car exp)) (occurs-free? var (cadr exp)))]))) (define occurs-bound? (lambda (var exp) (cond [(symbol? exp) #f] [(eqv? (car exp) 'lambda) (or (occurs-bound? var (caddr exp)) (and (eqv? (caadr exp) var) (occurs-free? var (caddr exp))))] [else (or (occurs-bound? var (car exp)) (occurs-bound? var (cadr exp)))])))
false
43907dd93d83bffe37a16e813788b9811ec21176
e358b0cf94ace3520adff8d078a37aef260bb130
/simple/1.39.scm
430ed7fc161ef7abc3c0c62f388682d7f3e05b1b
[]
no_license
dzhus/sicp
784766047402db3fad4884f7c2490b4f78ad09f8
090fa3228d58737d3558f2af5a8b5937862a1c75
refs/heads/master
2021-01-18T17:28:02.847772
2020-05-24T19:15:57
2020-05-24T20:56:00
22,468,805
0
0
null
null
null
null
UTF-8
Scheme
false
false
266
scm
1.39.scm
(define (tan-cf k x) (define (N x) (- (* x x))) (define (D i) (- (* 2 i) 1)) (define (frac i result) (if (= i 0) result (frac (- i 1) (/ (N x) (+ (D i) result))))) (- (/ (frac k 0) x))) (define (tan-frac x) (tan-cf 100 x))
false
caf1bebeca2e8c8878b4304faece16f8333e2c94
ac2a3544b88444eabf12b68a9bce08941cd62581
/tests/unit-tests/04-list/iota.scm
ecba6619ae2198590b1064b172868e344df4774a
[ "Apache-2.0", "LGPL-2.1-only" ]
permissive
tomelam/gambit
2fd664cf6ea68859d4549fdda62d31a25b2d6c6f
d60fdeb136b2ed89b75da5bfa8011aa334b29020
refs/heads/master
2020-11-27T06:39:26.718179
2019-12-15T16:56:31
2019-12-15T16:56:31
229,341,552
1
0
Apache-2.0
2019-12-20T21:52:26
2019-12-20T21:52:26
null
UTF-8
Scheme
false
false
1,209
scm
iota.scm
(include "#.scm") (define bool #f) (check-equal? (iota 0) '()) (check-equal? (iota 1) '(0)) (check-equal? (iota 2) '(0 1)) (check-equal? (iota 3) '(0 1 2)) (check-equal? (iota 4) '(0 1 2 3)) (check-equal? (iota 4 3) '(3 4 5 6)) (check-equal? (iota 4 10 2) '(10 12 14 16)) (check-equal? (iota 4 10 -1) '(10 9 8 7)) (check-equal? (iota 4 10 0.5) '(10 10.5 11.0 11.5)) (check-equal? (iota 4 10 0) '(10 10 10 10)) (check-equal? (iota 4 10 0.0) '(10 10.0 10.0 10.0)) (check-equal? (iota 4 10.0 1) '(10.0 11.0 12.0 13.0)) (check-tail-exn type-exception? (lambda () (iota bool))) (check-tail-exn type-exception? (lambda () (iota bool 0))) (check-tail-exn type-exception? (lambda () (iota 0 bool))) (check-tail-exn type-exception? (lambda () (iota bool 0 0))) (check-tail-exn type-exception? (lambda () (iota 0 bool 0))) (check-tail-exn type-exception? (lambda () (iota 0 0 bool))) (check-tail-exn range-exception? (lambda () (iota -1))) (check-tail-exn range-exception? (lambda () (iota -1 0))) (check-tail-exn range-exception? (lambda () (iota -1 0 0))) (check-tail-exn wrong-number-of-arguments-exception? (lambda () (iota))) (check-tail-exn wrong-number-of-arguments-exception? (lambda () (iota 0 0 0 0)))
false
4b91648ca4bd32196d346e5349ca73554c1352d8
9b2eb10c34176f47f7f490a4ce8412b7dd42cce7
/lib-compat/yunife-yunivm/runtime/let.sls
750df505f017443fcfe04fcdd2caa832a75ad19e
[ "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
960
sls
let.sls
;; Convert Scheme let syntaxes into yunivm letrec* (library (yunife-yunivm runtime let) (export let let* letrec) (import (yunivm-core-syntax)) ;; FIXME: fake (define-syntax letrec (syntax-rules () ((_ args ...) (letrec* args ...)))) (define-syntax let* (syntax-rules () ((_ () body0 body1 ...) (letrec* () body0 body1 ...)) ((_ ((var0 code0)) body0 body1 ...) (letrec* ((var0 code0)) body0 body1 ...)) ((_ ((var0 code0) (var1 code1) ...) body0 body1 ...) (let ((var0 code0)) (let* ((var1 code1) ...) body0 body1 ...))))) (define-syntax let (syntax-rules () ((_ () body0 body1 ...) (letrec* () body0 body1 ...)) ((_ ((var code) ...) body0 body1 ...) ((lambda (var ...) body0 body1 ...) code ...)) ((_ name ((var code) ...) body0 body1 ...) (letrec* ((name (lambda (var ...) body0 body1 ...))) (name code ...))))) )
true
c7075f20256d32a82cb2262b4dadcb1bcbcfba96
bde67688a401829ffb4a5c51394107ad7e781ba1
/test-taco2.scm
d2ad48d3945b452d536638b32963f5ba0958fe25
[]
no_license
shkmr/taco
1fad9c21284e12c9aae278f2e06de838363c3db9
8bbea1a4332d6d6773a3d253ee6c2c2f2bcf2b05
refs/heads/master
2021-01-10T03:50:55.411877
2016-08-11T03:37:53
2016-08-11T03:37:53
48,963,008
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,796
scm
test-taco2.scm
(use gauche.test) (test-start "taco2") (use taco2) (test-module 'taco2) (define taco.out (open-output-file "taco2.out")) (define *undef* (if #f #t)) (define (run-test in out) (test in out (lambda () (with-output-to-port taco.out (lambda () (guard (e ((is-a? e <error>) (cons 'ERROR (ref e 'message))) (else (error "Unexpected exception"))) (taco2-eval-string in))))))) (define simple1 "\ # Simple stmt { 1 2 3 } ") (define simple2 "\ { 1 2 3 } ") (define simple3 "\ { 1 2 3 } ") (define simple4 "\ { 1 2+3 } ") (define simple5 "\ {1 2+3} ") (define print1 "\ print 1 ") (define print2 "\ print \"hello, world\n\" ") (define print3 "\ print 1,2,3 ") (define print4 "\ A=1 B=2 print \"A=\", A, \", B=\", B, \"\n\" ") (test-section "simple expr") (run-test "1\n" 1) (run-test "1+1\n" 2) (run-test "(1+2)*3\n" 9) (run-test "3*(3+2*(4+5))\n" 63) (run-test simple1 3) (run-test simple2 3) (run-test simple3 3) (run-test simple4 5) (run-test simple5 5) (test-section "funcall. check taco2.out for compiled codes.") (run-test print1 *undef*) (run-test print2 *undef*) (run-test print3 *undef*) (run-test "A\n" '(ERROR . "unknown global A\n")) (run-test print4 *undef*) (run-test "A\n" 1) (test-section "conditional. check taco2.out for compiled codes.") (run-test "if (1==0) 20\n" #f) (run-test "if (1!=0) 10\n" 10) (run-test "if (1!=1) 10 else 20\n" 20) (run-test "if (1==1) 10 else 20\n" 10) (run-test "if (1==0) print(20)\n" #f) (run-test "if (1!=0) print(10)\n" *undef*) (run-test "if (1!=1) print(10) else print (20)\n" *undef*) (run-test "if (1==1) print(10) else print (20)\n" *undef*) (test-section "function. check taco2.out for compiled codes.") (run-test "\ func fact(1) { if ($1 == 0) { return 1 } else { return $1*fact($1 - 1) } } fact(5) " 120) (run-test "\ func fact2(1) { if ($1 == 0) return 1 else return $1*fact($1 - 1) } fact2(5) " 120) (run-test "\ func ack(2) { print $1, \" \", $2, \"\\n\" if ($1 == 0) return $2+1 if ($2 == 0) return ack($1-1, 1) return ack($1-1, ack($1, $2-1)) } ack(2,2) " 7) (run-test "\ func tak(3) { print $1, \" \", $2, \" \" , $3,\"\\n\" if ($1 <= $2) { return $3 } else { return tak(tak($1-1, $2, $3), tak($2-1, $3, $1), tak($3-1, $1, $2)) } } tak(7,5,3) " 4) (close-port taco.out) ;; If you don't want `gosh' to exit with nonzero status even if ;; the test fails, pass #f to :exit-on-failure. (test-end :exit-on-failure #t) ;; EOF
false
3ca61fabd60b30e8c566c7d25a008b4a5c64e0c6
45b0335564f2f65b8eea1196476f6545ec7ac376
/local-form.scm
6767a9d9635c697d5bd41106ab695d1e1d0655fb
[ "MIT" ]
permissive
dannypsnl-fork/nanopass
cbc252bb36054550191f16c2353126464268de7c
80e0344a1f143832a75d798be903e05b5dbdd079
refs/heads/master
2021-12-12T16:14:13.733284
2017-02-02T05:17:05
2017-02-02T05:17:05
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,013
scm
local-form.scm
; From: ;; (begin ;; (foo) ;; (define a (lambda () 1)) ;; (define b (lambda () 2)) ;; (a)) ; To: ;; ((lambda (a b) ;; (foo) ;; (set! a (lambda () 1)) ;; (set! b (lambda () 2)) ;; (a)) ;; #f #f) (define local-form (lambda (exp) (if (not (begin-exp? exp)) exp (let ([vars (defined-vars (cdr exp))]) `((lambda ,vars ,@(replace-define (cdr exp))) ,@(map (lambda (v) #f) vars)))))) (define defined-vars (lambda (exps) (fold (lambda (exp vars) (if (define-exp? exp) (cons (cadr exp) vars) vars)) '() exps))) (define replace-define (lambda (exps) (map (lambda (exp) (if (define-exp? exp) `(set! ,@(cdr exp)) exp)) exps))) (define exp? (lambda (exp sym) (and (pair? exp) (eq? (car exp) sym)))) (define begin-exp? (lambda (exp) (exp? exp 'begin))) (define define-exp? (lambda (exp) (exp? exp 'define)))
false
b108953e76967c4a0a330f3f5ce21c13010e3894
bef204d0a01f4f918333ce8f55a9e8c369c26811
/src/tspl-6-Operations-on-Objects/6.13-Hashtables.ss
f9de55e69894014e76ccf875df28d29d8ce8060a
[ "MIT" ]
permissive
ZRiemann/ChezSchemeNote
56afb20d9ba2dd5d5efb5bfe40410a5f7bb4e053
70b3dca5d084b5da8c7457033f1f0525fa6d41d0
refs/heads/master
2022-11-25T17:27:23.299427
2022-11-15T07:32:34
2022-11-15T07:32:34
118,701,405
5
0
null
null
null
null
UTF-8
Scheme
false
false
1,822
ss
6.13-Hashtables.ss
#!/usr/bin/scheme --script (display " ================================================================================ Section 6.3.Hashtables ") (define ht1 (make-eq-hashtable)) (define ht2 (make-eq-hashtable 32)) (define ht (make-hashtable string-hash string=?)) (hashtable-mutable? (make-eq-hashtable)) <graphic> #t (hashtable-mutable? (hashtable-copy (make-eq-hashtable))) <graphic> #f (define ht (make-eq-hashtable)) (hashtable-hash-function ht) <graphic> #f (eq? (hashtable-equivalence-function ht) eq?) <graphic> #t (define ht (make-hashtable string-hash string=?)) (eq? (hashtable-hash-function ht) string-hash) <graphic> #t (eq? (hashtable-equivalence-function ht) string=?) <graphic> #t (define ht (make-eq-hashtable)) (hashtable-hash-function ht) <graphic> #f (eq? (hashtable-equivalence-function ht) eq?) <graphic> #t (define ht (make-hashtable string-hash string=?)) (eq? (hashtable-hash-function ht) string-hash) <graphic> #t (eq? (hashtable-equivalence-function ht) string=?) <graphic> #t (define p1 (cons 'a 'b)) (define p2 (cons 'a 'b)) (define eqht (make-eq-hashtable)) (hashtable-set! eqht p1 73) (hashtable-ref eqht p1 55) <graphic> 73 ;; (hashtable-ref eqht p2 55) <graphic> 55 (define equalht (make-hashtable equal-hash equal?)) (hashtable-set! equalht p1 73) (hashtable-ref equalht p1 55) <graphic> 73 ;; equal? (a . b) (a . b) => #t (hashtable-ref equalht p2 55) <graphic> 73 (define ht (make-eq-hashtable)) (define p1 (cons 'a 'b)) (define p2 (cons 'a 'b)) (hashtable-set! ht p1 73) (hashtable-contains? ht p1) <graphic> #t (hashtable-contains? ht p2) <graphic> #f (define ht (make-eq-hashtable)) (hashtable-update! ht 'a (lambda (x) (* x 2)) 55) (hashtable-ref ht 'a 0) <graphic> 110 (hashtable-update! ht 'a (lambda (x) (* x 2)) 0) (hashtable-ref ht 'a 0) <graphic> 220
false
37cf018fbc3d6960ad92eba7a33dc45d6d8394f3
6f86602ac19983fcdfcb2710de6e95b60bfb0e02
/exercises/practice/word-count/word-count.scm
139b09d74a2a490c476a8ef3194b8918f8ed0b70
[ "MIT", "CC-BY-SA-3.0" ]
permissive
exercism/scheme
a28bf9451b8c070d309be9be76f832110f2969a7
d22a0f187cd3719d071240b1d5a5471e739fed81
refs/heads/main
2023-07-20T13:35:56.639056
2023-07-18T08:38:59
2023-07-18T08:38:59
30,056,632
34
37
MIT
2023-09-04T21:08:27
2015-01-30T04:46:03
Scheme
UTF-8
Scheme
false
false
66
scm
word-count.scm
(import (rnrs)) (define (word-count sentence) 'implement-me!)
false
c0c7d25b62046b229f22de0c46c253b5565a9761
a66514d577470329b9f0bf39e5c3a32a6d01a70d
/nanomsg/remote-repl
49c62bb133a6bfbb6ef0433d398f7f84b8e7bae8
[ "Apache-2.0" ]
permissive
ovenpasta/thunderchez
2557819a41114423a4e664ead7c521608e7b6b42
268d0d7da87fdeb5f25bdcd5e62217398d958d59
refs/heads/trunk
2022-08-31T15:01:37.734079
2021-07-25T14:59:53
2022-08-18T09:33:35
62,828,147
149
29
null
2022-08-18T09:33:37
2016-07-07T18:07:23
Common Lisp
UTF-8
Scheme
false
false
2,288
remote-repl
#! /usr/bin/env scheme-script ;; -*- mode: scheme -*- ;; ;; Copyright 2016 Aldo Nicolas Bruno ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ; example of remote REPL ; you can use any transport, tcp:// ipc:// websocket inproc ; see http://nanomsg.org/v1.0.0/nanomsg.7.html ; and nanomsg.sls for details ; ; ./local-repl tcp://127.0.0.1:12345 ; ABC ; ; meanwhile in another terminal... ; ./remote-repl tcp://127.0.0.1:12345 ; > (+ 1 2) ; 3 ; > (printf "ABC~n") --> will print ABC on the local repl process ; ; The nice thing is that you can scale to any protocol and ; that it can be integrated in an event/main loop ; it uses non-blocking (read) and you invoke (my-local-repl) until => #f ; ; TODO: add a command for local exit. #!eof object will only close the remote ; connection.... #!chezscheme (import (chezscheme) (nanomsg)) (nanomsg-library-init) (define argv (command-line-arguments)) (define sock (nn-socket AF_SP NN_REQ)) (define eid (cond [(null? argv) (nn-connect sock "tcp://localhost:9888")] [else (nn-connect sock (car argv))])) (call/cc (lambda (return) (let loop () (guard (e (else (printf "error in remote-repl: on ~d: ~d with irritants ~d~n" (if (who-condition? e) (condition-who e) 'unknown) (if (message-condition? e) (condition-message e) "") (if (irritants-condition? e) (condition-irritants e) "")))) (printf "> ") (nn-send sock (string->utf8 (call-with-string-output-port (lambda (p) (let ([token (read)]) (if (eof-object? token) (return #f) (write token p)))))) 0) (let ([buf (box #t)]) (nn-recv sock buf NN_MSG 0) (let ([s (utf8->string (unbox buf))]) (printf "~d" (if (string=? "#<void>\n" s) "" s))))) (loop))))
false
3e8275101c7bc0822ae0dded76f00fe858eed6fa
f04768e1564b225dc8ffa58c37fe0213235efe5d
/Assignment13/13.ss
b88028a6bf1bc6393a0fa8f65b918e64f0c33f34
[]
no_license
FrancisMengx/PLC
9b4e507092a94c636d784917ec5e994c322c9099
e3ca99cc25bd6d6ece85163705b321aa122f7305
refs/heads/master
2021-01-01T05:37:43.849357
2014-09-09T23:27:08
2014-09-09T23:27:08
23,853,636
1
0
null
null
null
null
UTF-8
Scheme
false
false
5,015
ss
13.ss
;(load "chez-init.ss") ; remove this isf using Dr. Scheme EoPL language (define-datatype expression expression? ; based on the simple expression grammar, EoPL-2 p6 (vec-exp (id vector?) ) (num-exp (id number?) ) (var-exp (id symbol?)) (lambda-exp (arg sym-ls?) (body list?)) (app-exp (rator expression?) (rand list?)) (if-else-exp (condition expression?) (t-body expression?) (f-body expression?) ) (if-exp (condition expression?) (body expression?) ) (let-exp (type symbol?) (assign list?) (body list?) ) (set-exp (var symbol?) (body expression?) ) ) (define (sym-ls? arg) (if (or (symbol? arg) (list? arg)) #t #f) ) (define parse-exp (lambda (datum) (cond ((vector? datum) (vec-exp datum)) ((number? datum) (num-exp datum)) ((symbol? datum) (var-exp datum)) ((not (list? datum)) (eopl:error 'parse-exp "expression ~s is not a proper list" datum)) ((pair? datum) (cond ((eqv? (car datum) 'lambda) (parse-lambda datum)) ((eqv? (car datum) 'if) (parse-if datum)) ((or (eqv? (car datum) 'let) (eqv? (car datum) 'let*) (eqv? (car datum) 'letrec)) (parse-let datum)) ((eqv? (car datum) 'set!) (parse-set datum)) (else (app-exp (parse-exp (car datum)) (map parse-exp (cdr datum))))) ) (else (eopl:error 'parse-exp "Invalid concrete syntax ~s" datum))))) (define (parse-set datum) (if (equal? (length datum) 3) (set-exp (cadr datum) (parse-exp (caddr datum))) (eopl:error 'parse-exp "set! expression ~s does not have (only) variable and expression" datum)) ) (define (parse-lambda datum) (if (>= (length datum) 3) (if (list? (cadr datum)) (lambda-exp (parse-lambda-args (cadr datum)) (map parse-exp (cddr datum))) (lambda-exp (cadr datum) (map parse-exp (cddr datum)))) (eopl:error 'parse-exp "lambda-expression: incorrect length ~s" datum) )) (define (parse-lambda-args arg) (if (symbol? arg) arg (if (andmap symbol? arg) arg (eopl:error 'parse-exp "lambda's formal arguments ~s must all be symbols" arg))) ) (define (parse-if datum) (cond ((equal? (length datum) 3) (if-exp (parse-exp (cadr datum)) (parse-exp (caddr datum)))) ((equal? (length datum) 4) (if-else-exp (parse-exp (cadr datum)) (parse-exp (caddr datum)) (parse-exp (cadddr datum)))) (else (eopl:error 'parse-exp "if-expression ~s does not have (only) test, then, and else" datum)) ) ) (define (parse-let datum) (cond ((>= (length datum) 3) (if (parse-let-assign datum) (let-exp (car datum) (cadr datum) (map parse-exp (cddr datum))) (eopl:error 'parse-exp "~s-expression has incorrect length ~s" (car datum) datum))) (else (eopl:error 'parse-exp "~s-expression has incorrect length ~s" (car datum) datum)) ) ) (define (parse-let-assign assign) (if (not (list? (cadr assign))) (eopl:error 'parse-exp "declarations in ~s-expression not a list ~s" (car assign) assign) (if (andmap list? (cadr assign)) (if (andmap two? (cadr assign)) (if (map parse-exp (map cadr (cadr assign))) (if (andmap symbol? (map car (cadr assign))) #t (eopl:error 'parse-exp "vars in ~s-exp must be symbols ~s" (car assign) assign)) ) (eopl:error 'parse-exp "declaration in ~s-exp must be a list of length 2 ~s" (car assign) assign)) (eopl:error 'parse-exp "declaration in ~s-exp is not a proper list ~s" (car assign) assign))) ) (define (two? list) (if (equal? (length list) 2) #t #f) ) (define unparse-exp ; an inverse for parse-exp (lambda (exp) (cases expression exp (vec-exp (id) id) (num-exp (id) id) (var-exp (id) id) (lambda-exp (arg body) (append (list 'lambda arg) (map unparse-exp body))) (if-else-exp (condition t-body f-body) (list 'if (unparse-exp condition) (unparse-exp t-body) (unparse-exp f-body)) ) (if-exp (condition body) (list 'if (unparse-exp condition) (unparse-exp body)) ) (let-exp (type assign body) (append (list type assign) (map unparse-exp body)) ) (set-exp (var body) (list 'set var (unparse-exp body)) ) (app-exp (rator rand) (append (list (unparse-exp rator)) (map unparse-exp rand)))))) (define occurs-free? ; in parsed expression (lambda (var exp) (cases expression exp (var-exp (id) (eqv? id var)) (lambda-exp (id body) (and (not (eqv? id var)) (occurs-free? var body))) (app-exp (rator rand) (or (occurs-free? var rator) (occurs-free? var rand))))))
false
c6538551194ec802caf2330a41216149c6a6312b
4f30ba37cfe5ec9f5defe52a29e879cf92f183ee
/src/tests/n2s2.scm
d4f2286c57976d9bd52f082d304c00fd75bcd8b7
[ "MIT" ]
permissive
rtrusso/scp
e31ecae62adb372b0886909c8108d109407bcd62
d647639ecb8e5a87c0a31a7c9d4b6a26208fbc53
refs/heads/master
2021-07-20T00:46:52.889648
2021-06-14T00:31:07
2021-06-14T00:31:07
167,993,024
8
1
MIT
2021-06-14T00:31:07
2019-01-28T16:17:18
Scheme
UTF-8
Scheme
false
false
7,309
scm
n2s2.scm
(define (quotient2 numerator denominator) (define (sign x) (cond ((zero? x) 0) ((negative? x) -1) (else 1))) (define (iter-fast result remainder denominator depth last-depth) ;(display (list 'iter-fast result remainder denominator depth last-depth)) ;(newline) (let ((next (* denominator depth))) (if (> next depth) ; this is a multiply overflow (if (< next remainder) (iter-fast (+ result depth) (- remainder next) denominator next depth) (iter-slow result remainder denominator)) (if (< depth remainder) (iter-fast (+ result last-depth) ; depth can't get bigger, so keep iterating at current depth (- remainder depth) denominator depth last-depth) (iter-slow result remainder denominator) )))) (define (iter-slow result remainder denominator) (if (< remainder denominator) (begin ;(display (list 'iter-slow-result result)) ;(newline) result) (iter-fast (+ result 1) (- remainder denominator) denominator 1 0))) (let ((result (iter-fast 0 (abs numerator) (abs denominator) 1 0))) (if (= (sign numerator) (sign denominator)) result (- 0 result)))) (define (remainder2 numerator denominator) (let ((q (quotient2 numerator denominator))) (- numerator (* q denominator)))) (define (number->string2 z . args) (define (x86-32-bit-intconst x) (if (>= x 0) (number->string2 x 16) (let ((bin (string->list (number->string2 (- x) 2)))) (define (fix-bin) ;; needed to detect overflow when there is no tower (if (and (pair? bin) (char=? (car bin) #\-)) (cdr bin) bin)) ;(display "bin: ") ;(display bin) ;(newline) (let ((fixed-bin (fix-bin))) ;(display "fixed-bin: ") ;(display fixed-bin) ;(newline) (let loop ((len (length fixed-bin)) (res fixed-bin)) ;(display "loop len:") ;(display len) ;(newline) (if (< len 32) (loop (+ len 1) (cons #\0 res)) (let ((negated (map (lambda (x) (if (char=? x #\0) 1 0)) res))) ;(display "negated: ") ;(display negated) ;(newline) (let ((neg-rev (reverse negated))) (let ((twos-comp (let add-1 ((cur neg-rev)) (if (null? cur) (reverse neg-rev) (if (= 0 (car cur)) (begin (set-car! cur 1) (reverse neg-rev)) (begin (set-car! cur 0) (add-1 (cdr cur)))))))) ;(display "twos-comp: ") ;(display twos-comp) ;(newline) (let loop2 ((res '()) (data twos-comp)) (if (null? data) (list->string (reverse res)) (let* ((x (car data)) (x2 (cdr data)) (y (car x2)) (y2 (cdr x2)) (z (car y2)) (z2 (cdr y2)) (w (car z2)) (w2 (cdr z2))) ;(display "x:") ;(display x) ;(display " y:") ;(display y) ;(display " z:") ;(display z) ;(display " w:") ;(display w) ;(newline) ;(display w2) ;(newline) (loop2 (cons (list-ref '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9 #\a #\b #\c #\d #\e #\f) (+ (* 8 x) (* 4 y) (* 2 z) w)) res) w2))))))))))))) (define chars "0123456789abcdef") ;; Note that R5RS defines number->string as a procedure and not a ;; library procedure. However right now we provide only a simple ;; integer implementation as a library procedure. (define (iter x result radix) ;(display (list 'iter x result radix)) ;(newline) (if (zero? x) (if (null? result) (list->string (list #\0)) (list->string result)) (iter (quotient2 x radix) (cons (string-ref chars (remainder2 x radix)) result) radix))) (define (inner x radix) (if (= x -2147483648) (case radix ((2) "-10000000000000000000000000000000") ((8) "-20000000000") ((10) "-2147483648") ((16) "-80000000") (else (error "number->string - Invalid radix specified" radix))) (let ((s (iter (abs x) '() radix))) (if (negative? x) (string-append "-" s) s)))) (cond ((null? args) (inner z 10)) ((or (not (null? (cdr args))) (not (integer? (car args))) (case (car args) ((2 8 10 16) #f) (else #t))) (error "number->string Invalid radix specified" args)) (else (if (and (< z 0) (= 16 (car args))) (x86-32-bit-intconst z) (inner z (car args)))))) (display (number->string2 3123)) ; 3123 (newline) (display (number->string2 0)) ; 0 (newline) (display (number->string2 -1)) ; -1 (newline) (display (number->string2 -3123)) ; -3123 (newline) (display (number->string2 #x8000ffff 16)) ; 8000ffff (-2147418113) (newline) (display (number->string2 #xf000000f 16)) ; f000000f (newline) (display (number->string2 -2147483648)) ; -2147483648 (newline) (display (number->string2 -2147483648 2)) ; -10000000000000000000000000000000 (newline) (display (number->string2 -2147483648 8)) ; -20000000000 (newline) (display (number->string2 -2147483648 10)) ; -2147483648 (newline) (display (number->string2 -2147483648 16)) ; -80000000 (newline) (display (number->string2 -2147483647)) ; -2147483647 (newline) (display (number->string2 -2147483647 2)) ; -1111111111111111111111111111111 (newline) (display (number->string2 -2147483647 8)) ; -17777777777 (newline) (display (number->string2 -2147483647 10)) ; -2147483647 (newline) (display (number->string2 -2147483647 16)) ; -7fffffff (newline) (display (number->string2 #x8000ffff 10)) ; -2147418113 (newline)
false
cdcde896dde412d7d0a2e8658c4f24a7f792e2eb
d369542379a3304c109e63641c5e176c360a048f
/brice/Chapter2/exercise-2.32.scm
e1d72cb61f0f5de8103f6ba647d72b0a590ab738
[]
no_license
StudyCodeOrg/sicp-brunches
e9e4ba0e8b2c1e5aa355ad3286ec0ca7ba4efdba
808bbf1d40723e98ce0f757fac39e8eb4e80a715
refs/heads/master
2021-01-12T03:03:37.621181
2017-03-25T15:37:02
2017-03-25T15:37:02
78,152,677
1
0
null
2017-03-25T15:37:03
2017-01-05T22:16:07
Scheme
UTF-8
Scheme
false
false
825
scm
exercise-2.32.scm
#lang racket (require "../utils.scm") (require "../meta.scm") (title "Exercise 2.32") ; Exercise 2.32. We can represent a set as a list of distinct ; elements, and we can represent the set of all subsets of the ; set as a list of lists. For example, if the set is (1 2 3), ; then the set of all subsets is ; ; (() (3) (2) (2 3) (1) (1 3) (1 2) (1 2 3)) ; ; Complete the following definition of a procedure that generates ; the set of subsets of a set and give a clear explanation of ; why it works: (define (subsets s) (if (null? s) (list nil) (let ((rest (subsets (cdr s)))) (append rest (map (lambda (xs) (cons (car s) xs)) rest))))) (let* ( (A '(1 2 3)) (B '(() (3) (2) (2 3) (1) (1 3) (1 2) (1 2 3)))) (prn (subsets A)) (assert "We can find the superset" (equal? (subsets A) B)) )
false
9b29f78b2622cae575c19a1b1b6ab5b93ad8fc55
c369eb130ec92b2f313c55e62c30c68c7e6710ae
/src/ru/mik/tenorequal/ads-manager.scm
0d183d68a08ae9357650f8b2e0d51e89bb1c5c26
[]
no_license
VyacheslavMik/10-or-equal
80d1e307512e1ed4dbe20011850d79fbd61a022d
adf63d3ddc39c154c3d10b885ea6f72777da0041
refs/heads/master
2020-03-18T11:20:23.717377
2018-05-24T05:31:07
2018-05-24T05:31:07
134,665,037
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,649
scm
ads-manager.scm
;; (import (class android.content Context)) ;; (import (class com.google.android.gms.ads AdListener AdRequest InterstitialAd)) ;; (import (class android.os Handler)) ;; (import (class java.lang System Runnable)) ;; ;; (define show-delay 300) ;; (define show-delay 30) ;; (define handler ::Handler #!null) ;; (define runnable ::Runnable #!null) ;; (define ad-showing-time 0) ;; (define interstitial-ad ::InterstitialAd #!null) ;; (define is-init? #f) ;; (define init-ad ;; (lambda ((context ::Context)) ;; (unless is-init? ;; (set! is-init? #t) ;; (set! handler (Handler)) ;; (set! interstitial-ad (InterstitialAd context)) ;; (interstitial-ad:setAdUnitId "ca-app-pub-3551700581852685/8610756454") ;; (interstitial-ad:setAdListener (object (AdListener) ;; ((onAdClosed) ;; (load-ad)))) ;; (load-ad)))) ;; (define show-ad ;; (lambda () ;; (let ((delay (/ (- (System:nanoTime) ad-showing-time) 1000000000))) ;; (when (> delay show-delay) ;; (if interstitial-ad:isLoaded ;; (begin ;; (interstitial-ad:show) ;; (set! ad-showing-time (System:nanoTime))) ;; (request-new-interstitial)))))) ;; (define load-ad ;; (lambda () ;; (when (eq? runnable #!null) ;; (set! runnable (object (Runnable) ;; ((run) ;; (request-new-interstitial) ;; (set! runnable #!null)))) ;; (handler:post runnable)))) ;; (define request-new-interstitial ;; (lambda () ;; (let ((ad-request (((AdRequest:Builder):addTestDevice AdRequest:DEVICE_ID_EMULATOR):build))) ;; (interstitial-ad:loadAd ad-request))))
false
9f00f126d3a8e5c48b41a06b468079f81963185b
6f3f05f766d05c5c1f377cd76c2cd7ebcb66da73
/c/scheme/tests.scm
c271964e16201df629c463ff248664e733bb4d72
[]
no_license
schakalsynthetc/fog-inferno
3ecb6667402a8ac79056387237068abdd8b729c3
9f707615f576031512ce556cf7c192da606a454a
refs/heads/master
2022-02-26T22:29:01.070903
2019-10-17T01:47:43
2019-10-17T01:47:43
215,670,317
1
0
null
2022-02-12T22:52:33
2019-10-17T00:36:19
JavaScript
UTF-8
Scheme
false
false
22,059
scm
tests.scm
(display "Simple factorial test: answers 120 and 2432902008176640000\n") (define fact (lambda (n) (if (= n 0) 1 (* n (fact (- n 1)))))) (write (fact 5)) (newline) (write (fact 20)) (newline) (display "Quote tests\n") (display "ans: a ") (write (quote a)) (newline) (display "ans: #(a b c) ") (write (quote #(a b c))) (newline) (display "ans: (+ 1 2) ") (write (quote (+ 1 2))) (newline) (display "ans: a ") (write 'a) (newline) (display "ans: #(a b c)) ") (write '#(a b c)) (newline) (display "ans: () ") (write '()) (newline) (display "ans: (+ 1 2) ") (write '(+ 1 2)) (newline) (display "ans: (quote a) ") (write '(quote a)) (newline) (display "ans: (quote a) ") (write ''a) (newline) (display "ans: \"abc\" ") (write '"abc") (newline) (display "ans: \"abc\" ") (write "abc") (newline) (display "ans: 145932 ") (write '145932) (newline) (display "ans: 145932 ") (write 145932) (newline) (display "ans: #t ") (write '#t) (newline) (display "ans: #t ") (write #t) (newline) (display "\n\nSimple procedure call\n") (display "ans: 7 ") (write (+ 3 4)) (newline) (display "Operator expression: ((if #f + *) 3 4)\n") (display "ans: 12 ") (write ((if #f + *) 3 4)) (newline) (display "\n\nLambda expressions:\n") (display "ans: 8 ") (write ((lambda (x) (+ x x)) 4)) (newline) (display "ans: 3 ") (define reverse-subtract (lambda (x y) (- y x))) (write (reverse-subtract 7 10)) (newline) (display "ans: 10 ") (define add4 (let ((x 4)) (lambda (y) (+ x y)))) (write (add4 6)) (newline) (display "ans: (3 4 5 6) ") (write ((lambda x x) 3 4 5 6)) (newline) (display "ans: (5 6) ") (write ((lambda (x y . z) z) 3 4 5 6)) (newline) (display "\n\nif tests:\n") (display "ans: yes ") (write (if (> 3 2) 'yes 'no)) (newline) (display "ans: no ") (write (if (> 2 3) 'yes 'no)) (newline) (display "ans: 1 ") (write (if (> 3 2) (- 3 2) (+ 3 2))) (newline) (display "\n\nset!:\n") (display "ans: 3 ") (define x 2) (write (+ x 1)) (newline) (display "ans: 5 ") (set! x 4) (write (+ x 1)) (newline) (display "\n\ncond:\n") (display "ans: greater ") (write (cond ((> 3 2) ' greater) ((< 3 2) 'less))) (newline) (display "ans: equal ") (write (cond ((> 3 3) 'greater) ((< 3 3) 'less) (else 'equal))) (newline) (display "ans: 2 ") (write (cond ((assv 'b '((a 2) (b 2))) => cadr) (else #f))) (newline) (display "\n\ncase:\n") (display "ans: composite ") (write (case (* 2 3) ((2 3 5 7) 'prime) ((1 4 6 8 9) 'composite))) (newline) (display "ans: uspecifiecified ") (write (case (car '(c d)) ((a) 'a) ((b) 'b))) (newline) (display "ans: consonant ") (write (case (car '(c d)) ((a e i o u) 'vowel) ((w y) 'semivowel) (else 'consonant))) (newline) (display "\n\nand:\n") (display "ans: #t ") (write (and (= 2 2) (> 2 1))) (newline) (display "ans: #f ") (write (and (= 2 2) (< 2 1))) (newline) (display "ans: (f g) ") (write (and 1 2 'c '(f g))) (newline) (display "ans: #t ") (write (and)) (newline) (display "\n\nor:\n") (display "ans: #t ") (write (or (= 2 2) (> 2 1))) (newline) (display "ans: #t ") (write (or (= 2 2) (< 2 1))) (newline) (display "ans: #f ") (write (or #f #f #f)) (newline) (display "ans: (b c) ") (write (or (memq 'b '(a b c)) (/ 3 0))) (newline) (display "\n\nlet, let*, letrec:\n") (display "ans: 6 ") (write (let ((x 2) (y 3)) (* x y))) (newline) (display "ans: 35 ") (write (let ((x 2) (y 3)) (let ((x 7) (z (+ x y))) (* z x)))) (newline) (display "ans: 70 ") (write (let ((x 2) (y 3)) (let* ((x 7) (z (+ x y))) (* z x)))) (newline) (display "ans: #t ") (write (letrec ((even? (lambda (n) (if (zero? n) #t (odd? (- n 1))))) (odd? (lambda (n) (if (zero? n) #f (even? (- n 1)))))) (even? 88))) (newline) (display "\n\nbegin:\n") (display "ans: 6 ") (define x 0) (write (begin (set! x 5) (+ x 1))) (newline) (display "ans: unspecified and outputs \"4 plus 1 equals 5\"\n") (write (begin (display "4 plus one equal ") (display (+ 4 1)))) (newline) (display "\n\ndo:\n") (display "ans: #(0 1 2 3 4) ") (write (do ((vec (make-vector 5)) (i 0 (+ i 1))) ((= i 5) vec) (vector-set! vec i i)) ) (newline) (display "ans: 25 ") (write (let ((x '(1 3 5 7 9))) (do ((x x (cdr x)) (sum 0 (+ sum (car x)))) ((null? x) sum))) ) (newline) (display "\n\nnamed let:\n") (display "ans: ((6 1 3) (-5 -2)) ") (write (let loop ((numbers '(3 -2 1 6 -5)) (nonneg '()) (neg '())) (cond ((null? numbers) (list nonneg neg)) ((>= (car numbers) 0) (loop (cdr numbers) (cons (car numbers) nonneg) neg)) ((< (car numbers) 0) (loop (cdr numbers) nonneg (cons (car numbers) neg))))) ) (newline) (display "\n\nquasiquote:\n") (display "ans: (list 3 4) ") (write `(list ,(+ 1 2) 4)) (newline) (display "ans: (a 3 4 5 6 b) ") (write `(a ,(+ 1 2) ,@(map abs '(4 -5 6)) b)) (newline) (display "ans: ((foo 7) . cons) ") (write `((foo ,(- 10 3)) ,@(cdr '(c)) . ,(car '(cons)))) (newline) (display "ans: #(10 5 2 4 3 8) ") (write `#(10 5 ,(sqrt 4) ,@(map sqrt '(16 9)) 8)) (newline) (display "ans: (a `(b ,(+ 1 2) ,(foo 4 d) e) f) ") (write `(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f)) (newline) (display "ans: (a `(b ,x ,'y d) e) ") (write (let ((name1 'x) (name2 'y)) `(a `(b ,,name1 ,',name2 d) e))) (newline) (display "ans: (list 3 4) ") (write (quasiquote (list (unquote (+ 1 2)) 4))) (newline) (display "ans: `(list ,(+ 1 2) 4) ") (write '(quasiquote (list (unquote (+ 1 2)) 4))) (newline) (display "\n\nTop level definitions:\n") (display "ans: 6 ") (define add3 (lambda (x) (+ x 3))) (write (add3 3)) (newline) (display "ans: 1 ") (define first car) (write (first '(1 2))) (newline) (display "\n\nInternal definitions:\n") (display "ans: 45 ") (write (let ((x 5)) (define foo (lambda (y) (bar x y))) (define bar (lambda (a b) (+ (* a b) a))) (foo (+ x 3)))) (newline) (display "ans: 45 ") (write (let ((x 5)) (letrec ((foo (lambda (y) (bar x y))) (bar (lambda (a b) (+ (* a b) a)))) (foo (+ x 3))))) (newline) (display "\n\nEquivalence predicates:\n") (display "eqv?\n") (display "ans: #t ") (write (eqv? 'a 'a)) (newline) (display "ans: #f ") (write (eqv? 'a 'b)) (newline) (display "ans: #t ") (write (eqv? 2 2)) (newline) (display "ans: #t ") (write (eqv? '() '())) (newline) (display "ans: #t ") (write (eqv? 100000000 100000000)) (newline) (display "ans: #f ") (write (eqv? (cons 1 2) (cons 1 2))) (newline) (display "ans: #f ") (write (eqv? (lambda () 1) (lambda () 2))) (newline) (display "ans: #f ") (write (eqv? #f 'nil)) (newline) (display "ans: #t ") (write (let ((p (lambda (x) x))) (eqv? p p))) (newline) (display "ans: unspecified ") (write (eqv? "" "")) (newline) (display "ans: unspecified ") (write (eqv? '#() '#())) (newline) (display "ans: unspecified ") (write (eqv? (lambda (x) x) (lambda (x) x))) (newline) (display "ans: unspecified ") (write (eqv? (lambda (x) x) (lambda (y) y))) (newline) (display "ans: #t ") (define gen-counter (lambda () (let ((n 0)) (lambda () (set! n (+ n 1)) n)))) (write (let ((g (gen-counter))) (eqv? g g))) (newline) (display "ans: #f ") (write (eqv? (gen-counter) (gen-counter))) (newline) (display "ans: #t ") (define gen-loser (lambda () (let ((n 0)) (lambda () (set! n (+ n 1)) 27)))) (write (let ((g (gen-loser))) (eqv? g g))) (newline) (display "ans: unspecified ") (write (eqv? (gen-loser) (gen-loser))) (newline) (display "ans: unspecified ") (write (letrec ((f (lambda () (if (eqv? f g) 'both 'f))) (g (lambda () (if (eqv? f g) 'both 'g)))) (eqv? f g))) (newline) (display "ans: #f ") (write (letrec ((f (lambda () (if (eqv? f g) 'f 'both))) (g (lambda () (if (eqv? f g) 'g 'both)))) (eqv? f g))) (newline) (display "ans: unspecified ") (write (eqv? '(a) '(a))) (newline) (display "ans: unspecified ") (write (eqv? "a" "a")) (newline) (display "ans: unspecified ") (write (eqv? '(b) (cdr '(a b)))) (newline) (display "ans: #t ") (write (let ((x '(a))) (eqv? x x))) (newline) (display "eq?\n") (display "ans: #t ") (write (eq? 'a 'a)) (newline) (display "ans: unspecified ") (write (eq? '(a) '(a))) (newline) (display "ans: #f ") (write (eq? (list 'a) (list 'a))) (newline) (display "ans: unspecified ") (write (eq? "a" "a")) (newline) (display "ans: unspecified ") (write (eq? "" "")) (newline) (display "ans: #t ") (write (eq? '() '())) (newline) (display "ans: unspecified ") (write (eq? 2 2)) (newline) (display "ans: unspecified ") (write (eq? #\A #\A)) (newline) (display "ans: #t ") (write (eq? car car)) (newline) (display "ans: unspecified ") (write (let ((n (+ 2 3))) (eq? n n))) (newline) (display "ans: #t ") (write (let ((x '(a))) (eq? x x))) (newline) (display "ans: #t ") (write (let ((x '#())) (eq? x x))) (newline) (display "ans: #t ") (write (let ((p (lambda (x) x))) (eq? p p))) (newline) (display "equal?\n") (display "ans: #t ") (write (equal? 'a 'a)) (newline) (display "ans: #t ") (write (equal? '(a) '(a))) (newline) (display "ans: #t ") (write (equal? '(a (b) c) '(a (b) c))) (newline) (display "ans: #t ") (write (equal? "abc" "abc")) (newline) (display "ans: #t ") (write (equal? 2 2)) (newline) (display "ans: #t ") (write (equal? (make-vector 5 'a) (make-vector 5 'a))) (newline) (display "ans: unspecified ") (write (equal? (lambda (x) x) (lambda (y) y))) (newline) (display "\n\nNumerical operations:\n") (display "classification predicates\n") (display "ans: #t ") (write (complex? 3)) (newline) (display "ans: #t ") (write (real? 3)) (newline) (display "ans: #t ") (write (real? #e1e10)) (newline) (display "ans: #t ") (write (rational? 6/10)) (newline) (display "ans: #t ") (write (rational? 6/3)) (newline) (display "ans: #t ") (write (integer? 3.0)) (newline) (display "ans: #t ") (write (integer? 8/4)) (newline) (display "max\n") (display "ans: 4 ") (write (max 3 4)) (newline) (display "ans: 4.0 ") (write (max 3.9 4)) (newline) (display "basic arithmetic\n") (display "ans: 7 ") (write (+ 3 4)) (newline) (display "ans: 3 ") (write (+ 3)) (newline) (display "ans: 0 ") (write (+)) (newline) (display "ans: 4 ") (write (* 4)) (newline) (display "ans: 1 ") (write (*)) (newline) (display "ans: -1 ") (write (- 3 4)) (newline) (display "ans: -6 ") (write (- 3 4 5)) (newline) (display "ans: -3 ") (write (- 3)) (newline) (display "ans: 3/20 ") (write (/ 3 4 5)) (newline) (display "ans: 1/3 ") (write (/ 3)) (newline) (display "integer division, remainder,modulo\n") (display "ans: 1 ") (write (modulo 13 4)) (newline) (display "ans: 1 ") (write (remainder 13 4)) (newline) (display "ans: 3 ") (write (modulo -13 4)) (newline) (display "ans: -1 ") (write (remainder -13 4)) (newline) (display "ans: -3 ") (write (modulo 13 -4)) (newline) (display "ans: 1 ") (write (remainder 13 -4)) (newline) (display "ans: -1 ") (write (modulo -13 -4)) (newline) (display "ans: -1 ") (write (remainder -13 -4)) (newline) (display "ans: -1.0 ") (write (remainder -13 -4.0)) (newline) (display "gcd, lcm\n") (display "ans: 4 ") (write (gcd 32 -36)) (newline) (display "ans: 0 ") (write (gcd)) (newline) (display "ans: 288 ") (write (lcm 32 -36)) (newline) (display "ans: 288.0 ") (write (lcm 32.0 -36)) (newline) (display "ans: 1 ") (write (lcm)) (newline) (display "numerator, denominator\n") (display "ans: 3 ") (write (numerator (/ 6 4))) (newline) (display "ans: 2 ") (write (denominator (/ 6 4))) (newline) (display "ans: 2.0 ") (write (denominator (exact->inexact (/ 6 4)))) (newline) (display "floor, ceiling, truncate, round\n") (display "ans: -5.0 ") (write (floor -4.3)) (newline) (display "ans: -4.0 ") (write (ceiling -4.3)) (newline) (display "ans: -4.0 ") (write (truncate -4.3)) (newline) (display "ans: -4.0 ") (write (round -4.3)) (newline) (display "ans: 3.0 ") (write (floor 3.5)) (newline) (display "ans: 4.0 ") (write (ceiling 3.5)) (newline) (display "ans: 3.0 ") (write (truncate 3.5)) (newline) (display "ans: 4.0 (inexact) ") (write (round 3.5)) (newline) (display "ans: 4 (exact) ") (write (round 7/2)) (newline) (display "ans: 7 ") (write (round 7)) (newline) (display "\n\nrationalize:\n") (display "ans: 1/3 (exact) ") (write (rationalize (inexact->exact .3) 1/10)) (newline) (display "ans: #i1/3 (inexact) ") (write (rationalize .3 1/10)) (newline) (display "\n\nstring->number\n") (display "ans: 100 ") (write (string->number "100")) (newline) (display "ans: 256 ") (write (string->number "100" 16)) (newline) (display "ans: 100.0 ") (write (string->number "1e2")) (newline) (display "\n\nBoolean operations:\n") (display "ans: #t ") (write #t) (newline) (display "ans: #f ") (write #f) (newline) (display "ans: #f ") (write '#f) (newline) (display "ans: #f ") (write (not #t)) (newline) (display "ans: #f ") (write (not 3)) (newline) (display "ans: #f ") (write (not (list 3))) (newline) (display "ans: #t ") (write (not #f)) (newline) (display "ans: #f ") (write (not '())) (newline) (display "ans: #f ") (write (not (list))) (newline) (display "ans: #f ") (write (not 'nil)) (newline) (display "ans: #t ") (write (boolean? #f)) (newline) (display "ans: #f ") (write (boolean? 0)) (newline) (display "ans: #f ") (write (boolean? '())) (newline) (display "\n\nList operations:\n") (display "define/set:\n") (display "ans: (a b c) ") (define x (list 'a 'b 'c)) (define y x) (write y) (newline) (display "ans: #t ") (write (list? y)) (newline) (display "ans: unspecified ") (write (set-cdr! x 4)) (newline) (display "ans: (a . 4) ") (write x) (newline) (display "ans: #t ") (write (eqv? x y)) (newline) (display "ans: (a . 4) ") (write y) (newline) (display "ans: #f ") (write (list? y)) (newline) ;(display "ans: unspecified ") (write (set-cdr! x x)) (newline) ;(display "ans: #f ") (write (list? x)) (newline) (display "predicates:\n") (display "ans: #t ") (write (pair? '(a . b))) (newline) (display "ans: #t ") (write (pair? '(a b c))) (newline) (display "ans: #f ") (write (pair? '())) (newline) (display "ans: #f ") (write (pair? '#(a b))) (newline) (display "cons, car, cdr\n") (display "ans: (a) ") (write (cons 'a '())) (newline) (display "ans: ((a) b c d) ") (write (cons '(a) '(b c d))) (newline) (display "ans: (\"a\" b c) ") (write (cons "a" '(b c))) (newline) (display "ans: (a . 3) ") (write (cons 'a 3)) (newline) (display "ans: ((a b) . c) ") (write (cons '(a b) 'c)) (newline) (display "ans: a ") (write (car '(a b c))) (newline) (display "ans: (a) ") (write (car '((a) b c))) (newline) (display "ans: 1 ") (write (car '(1 . 2))) (newline) (display "ans: error ") (write (car '())) (newline) (display "ans: (b c d) ") (write (cdr '((a) b c d))) (newline) (display "ans: 2 ") (write (cdr '(1 . 2))) (newline) (display "ans: error ") (write (cdr '())) (newline) (display "set-car!\n") (display "ans: unspecified ") (define (f) (list 'not-a-constant-list)) (define (g) '(constant-list)) (write (set-car! (f) 3)) (newline) (display "ans: error ") (write (set-car! (g) 3)) (newline) (display "list?\n") (display "ans: #t ") (write (list? '(a b c))) (newline) (display "ans: #t ") (write (list? '())) (newline) (display "ans: #f ") (write (list? '(a . b))) (newline) (display "ans: #f ") (write (let ((x (list 'a))) (set-cdr! x x) (list? x))) (newline) (display "list\n") (display "ans: (a 7 c) ") (write (list 'a (+ 3 4) 'c)) (newline) (display "ans: () ") (write (list)) (newline) (display "length\n") (display "ans: 3 ") (write (length '(a b c))) (newline) (display "ans: 3 ") (write (length '(a (b) (c d e)))) (newline) (display "ans: 0 ") (write (length '())) (newline) (display "append\n") (display "ans: (x y) ") (write (append '(x) '(y))) (newline) (display "ans: (a b c d) ") (write (append '(a) '(b c d))) (newline) (display "ans: (a (b) (c)) ") (write (append '(a (b)) '((c)))) (newline) (display "ans: (a b c . d) ") (write (append '(a b) '(c . d))) (newline) (display "ans: a ") (write (append '() 'a)) (newline) (display "reverse\n") (display "ans: (c b a) ") (write (reverse '(a b c))) (newline) (display "ans: ((e (f)) d (b c) a) ") (write (reverse '(a (b c) d (e (f))))) (newline) (display "list-ref\n") (display "ans: c ") (write (list-ref '(a b c d) 2)) (newline) (display "ans: c ") (write (list-ref '(a b c d) (inexact->exact (round 1.8)))) (newline) (display "memq, memv, member\n") (display "ans: (a b c) ") (write (memq 'a '(a b c))) (newline) (display "ans: (b c) ") (write (memq 'b '(a b c))) (newline) (display "ans: #f ") (write (memq 'a '(b c d))) (newline) (display "ans: #f ") (write (memq (list 'a) '(b (a) c))) (newline) (display "ans: ((a) c) ") (write (member (list 'a) '(b (a) c))) (newline) (display "ans: unspecified ") (write (memq 101 '(100 101 102))) (newline) (display "ans; (101 102) ") (write (memv 101 '(100 101 102))) (newline) (display "assq, assv, assoc\n") (display "ans: (a 1) ") (define e '((a 1) (b 2) (c 3))) (write (assq 'a e)) (newline) (display "ans: (b 2) ") (write (assq 'b e)) (newline) (display "ans: #f ") (write (assq 'd e)) (newline) (display "ans: #f ") (write (assq (list 'a) '(((a)) ((b)) ((c))))) (newline) (display "ans: ((a)) ") (write (assoc (list 'a) '(((a)) ((b)) ((c))))) (newline) (display "ans: unspecified ") (write (assq 5 '((2 3) (5 7) (11 13)))) (newline) (display "ans: (5 7) ") (write (assv 5 '((2 3) (5 7) (11 13)))) (newline) (display "\n\nSymbols:\n") (display "symbol?\n") (display "ans: #t ") (write (symbol? 'foo)) (newline) (display "ans: #t ") (write (symbol? (car '(a b)))) (newline) (display "ans: #f ") (write (symbol? "bar")) (newline) (display "ans: #t ") (write (symbol? 'nil)) (newline) (display "ans: #f ") (write (symbol? '())) (newline) (display "ans: #f ") (write (symbol? #f)) (newline) (display "symbol->string\n") (display "ans: \"flying-fish\" ") (write (symbol->string 'flying-fish)) (newline) (display "ans: \"martin\" ") (write (symbol->string 'Martin)) (newline) (display "ans: \"Malvina\" ") (write (symbol->string (string->symbol "Malvina"))) (newline) (display "string->symbol\n") (display "ans: mISSISSIppi ") (write (string->symbol "mISSISSIppi")) (newline) (display "ans: #f ") (write (eq? 'bitBlt (string->symbol "bitBlt"))) (newline) (display "ans: #t ") (write (eq? 'JollyWog (string->symbol (symbol->string 'JollyWog)))) (newline) (display "ans: #t ") (write (string=? "K. Harper, M.D." (symbol->string (string->symbol "K. Harper, M.D.")))) (newline) (display "\n\nCharacters:\n") (display "ans: #t ") (write (char-ci=? #\A #\a)) (newline) (display "\n\nStrings:\n") (display "ans: unspecified ") (define (f) (make-string 3 #\*)) (define (g) "***") (write (string-set! (f) 0 #\?)) (newline) (display "ans: error ") (write (string-set! (g) 0 #\?)) (newline) (display "ans: error ") (write (string-set! (symbol->string 'immutable) 0 #\?)) (newline) (display "\n\nVectors:\n") (display "ans: #(a b c) ") (write (vector 'a 'b 'c)) (newline) (display "ans: 8 ") (write (vector-ref '#(1 1 2 3 5 8 13 21) 5)) (newline) (display "ans: 13 ") (write (vector-ref '#(1 1 2 3 5 8 13 21) (let ((i (round (* 2 (acos -1))))) (if (inexact? i) (inexact->exact i) i)))) (newline) (display "ans: #(0 (\"Sue\" \"Sue\") \"Anna\") ") (write (let ((vec (vector 0 '(2 2 2 2) "Anna"))) (vector-set! vec 1 '("Sue" "Sue")) vec)) (newline) (display "ans: error ") (write (vector-set! '#(0 1 2) 1 "doe")) (newline) (display "ans: (dah dah didah) ") (write (vector->list '#(dah dah didah))) (newline) (display "ans: #(dididit dah) ") (write (list->vector '(dididit dah))) (newline) (display "\n\nControl features:\n") (display "procedure?\n") (display "ans: #t ") (write (procedure? car)) (newline) (display "ans: #f ") (write (procedure? 'car)) (newline) (display "ans: #t ") (write (procedure? (lambda (x) (* x x)))) (newline) (display "ans: #f ") (write (procedure? '(lambda (x) (* x x)))) (newline) (display "apply\n") (display "ans: 7 ") (write (apply + (list 3 4))) (newline) (display "ans: 30 ") (define compose (lambda (f g) (lambda args (f (apply g args))))) (write ((compose sqrt *) 12 75)) (newline) (display "map\n") (display "ans: (b e h) ") (write (map cadr '((a b) (d e) (g h)))) (newline) (display "ans: (1 4 27 256 3125) ") (write (map (lambda (n) (expt n n)) '(1 2 3 4 5))) (newline) (display "ans: (5 7 9) ") (write (map + '(1 2 3) '(4 5 6))) (newline) (display "ans: (1 2) or (2 1) ") (write (let ((count 0)) (map (lambda (ignored) (set! count (+ count 1)) count) '(a b)))) (newline) (display "for-each\n") (display "ans: #(0 1 4 9 16) ") (write (let ((v (make-vector 5))) (for-each (lambda (i) (vector-set! v i (* i i))) '(0 1 2 3 4)) v)) (newline) (display "delay/force\n") (display "ans: 3 ") (write (force (delay (+ 1 2)))) (newline) (display "ans: (3 3) ") (write (let ((p (delay (+ 1 2)))) (list (force p) (force p))) ) (newline) (display "ans: 2 ") (define a-stream (letrec ((next (lambda (n) (cons n (delay (next (+ n 1))))))) (next 0))) (define head car) (define tail (lambda (stream) (force (cdr stream)))) (write (head (tail (tail a-stream))) ) (newline) (define count 0) (define p (delay (begin (set! count (+ count 1)) (if (> count x) count (force p))))) (define x 5) (display "ans: [promise] ") (write p) (newline) (display "ans: 6 ") (write (force p)) (newline) (display "ans: [promise] ") (write p) (newline) (display "ans: 6 ") (write (begin (set! x 100) (force p))) (newline)
false
09d62c225cb8a599c8a2a920d379cff45c2c2f04
f6ebd0a442b29e3d8d57f0c0935fd3e104d4e867
/ch02/2.1/ex-2-1-okie.scm
d0908b2d0494faad9c9d6780eed712d463d2ee4e
[]
no_license
waytai/sicp-2
a8e375d43888f316a063d280eb16f4975b583bbf
4cdc1b1d858c6da7c9f4ec925ff4a724f36041cc
refs/heads/master
2021-01-15T14:36:22.995162
2012-01-24T12:21:30
2012-01-24T12:21:30
23,816,705
1
0
null
null
null
null
UTF-8
Scheme
false
false
12,193
scm
ex-2-1-okie.scm
(define (linear-combination a b x y) (+ (* a x) (* b y))) (define x (cons 1 2)) (car x) (cdr x) ; 2 (define x (cons 1 2)) (define y (cons 3 4)) (define z (cons x y)) (car (car z)) ; 1 (define (make-rat n d) (cons n d)) (define (numer x) (car x)) (define (denom x) (cdr x)) (define (add-rat x y) (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (mult-rat x y) (make-rat (* (car x) (car y)) (* (cdr x) (cdr y)))) (define (print-rat x) (newline) (display (numer x)) (display "/") (display (denom x))) (define one-half (make-rat 1 2)) (print-rat one-half) (define one-third (make-rat 1 3)) (print-rat (add-rat one-half one-third)) (print-rat (mult-rat one-half one-third)) (print-rat (add-rat one-third one-third)) (define (make-rat n d) (let ((g (gcd n d))) (cons (/ n g) (/ d g)))) ;; ex 2.1 (define (deter-sign n d) (cond ((< 0 (* n d)) (if (< n 0) (make-rat (- n) (- d)) (make-rat n d))) (else (if (> n 0) (make-rat (- n) (- d)) (make-rat n d))))) (print-rat (deter-sign -1 -2)) ;1/2> (print-rat (deter-sign -1 -2)) ;1/2> (print-rat (deter-sign 1 -2)) ;-1/2> ;; ex 2.2 (define (print-point p) (newline) (display "(") (display (x-point p)) (display ",") (display (y-point p)) (display ")")) (define (x-point point) (car point)) (define (y-point point) (cdr point)) (define (make-point x y) (cons x y)) (define (make-segment start end) (cons start end)) (define (start-segment segment) (car segment)) (define (end-segment segment) (cdr segment)) (define (midpoint-segment segment) (make-point (/ (+ (car (start-segment segment)) (car (end-segment segment))) 2) (/ (+ (cdr (start-segment segment)) (cdr (end-segment segment))) 2))) (print-point (midpoint-segment (make-segment (make-point 1 2) (make-point 9 10)))) ; (5,6) ;; ex 2.3 ; second (define (make-point x y) (cons x y)) (define (make-size w h) (cons w h)) (define (make-rectangle p s) (cons p s)) (define (size-of-rectangle rect) (let ((size (cdr rect))) (* (car size) (cdr size)))) (define (boundary-of-rectangle rect) (let ((size (cdr rect))) (* (+ (car size) (cdr size)) 2))) (define (print-rectangle rect) (newline) (display "(size:") (display (size-of-rectangle rect)) (display ",boundary:") (display (boundary-of-rectangle rect)) (display ")")) ;; 2.1.3 (define (cons x y) (define (dispatch m) (cond ((= m 0) x) ((= m 1) y) (else (error "Argument not 0 or 1 -- CONS" m)))) dispatch) (define (car z) (z 0)) (define (cdr z) (z 1)) ; if (cons x y) -> z ; (car (cons x y) 0) ;; ex 2.4 (define (my-cons x y) (lambda (m) (m x y))) (define (my-cdr z) (z (lambda (p q) q))) (define (my-car z) (z (lambda (p q) p))) ((lambda (m) (m 1 2)) (lambda (p q) p)) ((lambda (p q) p) 1 2) ;; 1 ;; ex 2.5 ;; x = 2^a * 3^b ;; log x = log2(2^a*3^b) ;; log2(2^a) + log2(3^b) ;; log x = a + b*log2(3) (define (my-cons a b) (* (expt 2 a) (expt 3 b))) (define (devide? n d) (if (= 0 (remainder n d)) #t #f)) (define (find-exp x e i) (if (devide? x e) (find-exp (/ x e) e (+ i 1)) i)) (define (my-car x) (find-exp x 2 0)) (define (my-cdr x) (find-exp x 3 0)) ;; ex 2.6 (define zero (lambda (f) (lambda (x) x))) (define (add-1 n) (lambda (f) (lambda (x) (f ((n f) x))))) (define one (add-1 zero) ;==> (lambda (f) (lambda (x) (f ((zero f) x)))) (lambda (f) (lambda (x) (f x))) (define two (add-1 one) ;==> (lambda (f) (lambda (x) (f ((one f) x)))) (lambda (f) (lambda (x) (f (f x)))) ;; text 2.1.4 (define (add-interval x y) (make-interval (+ (lower-bound x) (lower-bound y)) (+ (upper-bound x) (upper-bound y)))) (define (mul-interval x y) (let ((p1 (* (lower-bound x) (lower-bound y))) (p2 (* (lower-bound x) (upper-bound y))) (p3 (* (upper-bound x) (lower-bound y))) (p4 (* (upper-bound x) (upper-bound y)))) (make-interval (min p1 p2 p3 p4) (max p1 p2 p3 p4)))) (define (div-interval x y) (mul-interval x (make-interval (/ 1.0 (upper-bound y)) (/ 1.0 (lower-bound y))))) ;; ex 2.7 ;(define (make-interval a b) (cons a b)) (define (make-interval lower upper) (cons lower upper)) (define (upper-bound x) (cdr x)) (define (lower-bound x) (car x)) (define x (make-interval -1.5 1.5)) (define y (make-interval 0.0 10.0)) (add-interval x y) ;; ex 2.8 (define (sub-interval x y) (make-interval (- (lower-bound x) (upper-bound y)) (- (upper-bound x) (lower-bound y)))) (sub-interval x y) ;; ex 2.9 (define (interval-width x) (/ (- (upper-bound x) (lower-bound x)) 2)) (interval-width x) (= (interval-width (add-interval x y)) (+ (interval-width x) (interval-width y))) (= (interval-width (mul-interval x y)) (* (interval-width x) (interval-width y))) ;; ex 2.10 (define (div-interval x y) (if (>= 0 (* (lower-bound y) (upper-bound y))) (error "devide by interval containing zero!") (mul-interval x (make-interval (/ 1.0 (upper-bound y)) (/ 1.0 (lower-bound y)))))) (div-interval x y) (div-interval y x) ;; ex 2.11 ;; (define (mul-interval x y) ;; (let ((p1 (* (lower-bound x) (lower-bound y))) ;; (p2 (* (lower-bound x) (upper-bound y))) ;; (p3 (* (upper-bound x) (lower-bound y))) ;; (p4 (* (upper-bound x) (upper-bound y)))) ;; (make-interval (min p1 p2 p3 p4) ;; (max p1 p2 p3 p4)))) ;; ;; x y ;; 1. ++ ++ ;; 2. ++ -+ ;; 3. ++ -- ;; 4. -+ ++ ;; 5. -+ -+ ;; 6. -+ -- ;; 7. -- ++ ;; 8. -- -+ ;; 9. -- -- (define (mul-interval) (let ((lx (lower-bound x)) (ux (upper-bound x)) (ly (lower-bound y)) (uy (upper-bound y))) (cond ;; 1. ++ ++ ((and (>= lx 0) (>= ux 0) (>= ly 0) (>= uy 0)) (make-interval (* lx ly) (* ux uy))) ;; 2. ++ -+ ((and (>= lx 0) (>= ux 0) (< ly 0) (>= uy 0)) (make-interval (* lx ly) (* ux uy))) ;; 3. ++ -- ((and (>= lx 0) (>= ux 0) (< ly 0) (< uy 0)) (make-interval (* ux ly) (* lx uy))) ;; 4. -+ ++ ((and (>= lx 0) (>= ux 0) (< ly 0) (>= uy 0)) (make-interval (* lx ly) (* ux uy))) ;; 5. -+ -+ ((and (< lx 0) (>= ux 0) (< ly 0) (>= uy 0)) (make-interval (min (* lx uy) (* ux ly)) (max (* lx ly) (* ux uy)))) ;; 6. -+ -- ((and (< lx 0) (>= ux 0) (< ly 0) (< uy 0)) (make-interval (* ux uy) (* lx uy))) ;; 7. -- ++ ((and (< lx 0) (< ux 0) (>= ly 0) (>= uy 0)) (make-interval (* ux ly) (* lx uy))) ;; 8. -- -+ ((and (< lx 0) (< ux 0) (< ly 0) (>= uy 0)) (make-interval (* lx uy) (* ux ly))) ;; 9. -- -- ((and (< lx 0) (< ux 0) (< ly 0) (< uy 0)) (make-interval (* ux uy) (* lx ly))) ))) ;; text (define (make-center-width c w) (make-interval (- c w) (+ c w))) (define (center i) (/ (+ (upper-bound i) (lower-bound i)) 2)) (define (width i) (/ (- (upper-bound i ) (lower-bound i)) 2)) ;; ex 2.12 (define (make-center-percent c p) (let ((width (/ (* c p) 100))) (make-center-width c width))) (define (percent x) (* 100 (/ (width x) (center x)))) (define z (make-center-percent 3.5 10)) ;; ex 2.13 ;; Assume that all numbers are plus. (define x (make-center-percent 10 0.00000001)) (define y (make-center-percent 50 0.00000001)) (define dz1 (percent (mul-interval x y))) ;; z + dz = (x + dx) * (y + dy) ;; z + dz = xy + xdy + ydx + dxdy ;; dx << x, dy << y ;; z + dz = xy + xdy + ydx ;; dz = xdy + ydx (define dz (+ (* (center x) (percent y)) (* (center x) (percent y)))) ;; text (define r1 (make-center-percent 10 5)) (define r2 (make-center-percent 5 1)) (define (par1 r1 r2) (div-interval (mul-interval r1 r2) (add-interval r1 r2))) (define (par2 r1 r2) (let ((one (make-interval 1 1 ))) (div-interval one (add-interval (div-interval one r1) (div-interval one r2))))) ;; 2.14 (define r1 (make-center-percent 10 0.005)) (define r2 (make-center-percent 5 0.00001)) (define rAA (div-interval r1 r1)) (define rAB (div-interval r1 r2)) ;; R1R2 (R1+d1) (R2+d2) ;; ------ = ---------------- ;; R1 + R2 (R1+d1) + (R2+d2) ;; 1 1 (R1+d1) (R2+d2) ;;---------- = -------------- != ---------------- ;; 1 1 1 1 (R2+d2) + (R1+d1) ;;---- + ---- ----- + ----- ;; R1 R2 R1+d1 R2+d2 ;; ;; Of course not. After all, it’s just two intervals divided one by another, and all the rules apply. No wonder Lem is getting different answers – he is ;; using two different formulas! ;; 2.15 ;; interval arithmetic system (define a (make-interval 2 4)) (define b (make-interval -2 0)) (define c (make-interval 3 8)) ;; x = a(b + c), y = ab + ac (define x (mul-interval a (add-interval b c))) (define y (add-interval (mul-interval a b) (mul-interval a c))) ;; Solution 1 ;;This is a combined answer to both exercises: ;;Eva Lu Ator is right, and an example can be seen in the computation done in the previous exercise – par2 produces tighter bounds than par1. To understand why this is so, I will try to explain the problems with interval arithmetic (answer to 2.16): ;; In doing arithmetic, we rely on some laws to hold without giving them much thought. Speaking mathematically, the real numbers are fields. For example, we expect to have an inverse element for addition – for each element A to have an element A’ so that A + A’ = 0. It is easy to check that this doesn’t hold for intervals! An inverse element for multiplication also doesn’t exist (this is the problem we saw in exercise 2.14). The distributive law doesn’t hold – consider the expression [1,2] * ([-3,-2] + [3,4]) – it makes a difference whether you do the additions or the multiplication first. ;; To solve these problems at least for the simple arithmetic package we’re developing, I think we need to define the concept of identity for an interval. Operations must be able to identify if two operators are identical, and adjust the results accordingly. ;; Soluation 2 ;; 2.15 ;; Eva is right. Program par2 is better than program par1. As we have observed in SICP Exercise 2.14, Alyssa’s system will produce big errors when computing expressions such as A/A. The reason is the following. When an interval A appears twice in an expression, they should not behave independently. They are correlated. In fact, they are the same unit in a system. So if the real value of A is , both A‘s should have the same value in a good system. However, Alyssa’s program treats them independently. In Alyssa’s system, one A may have a value of , whereas the other A may have a value of . Therefore we conclude that Alyssa’s system is flawed. ;; 2.16 ;; We have observed in SICP Exercise 2.14 and 2.15 that equivalent algebraic expressions may lead to different answers. I think it is because an interval that appears multiple times in an expression will behave independently though they should behave exactly the same way. ;;Can we devise an interval-arithmetic package that does not have this shortcoming? The authors of SICP warned us of the difficulty of this problem. But talk is cheap. So I will still try to say something. ;;We should take Eva Lu Ator’s suggestion (SICP Exercise 2.15) to avoid repeated appearance of intervals. ;;Remember the Taylor expansion: . Maybe we could design a system which utilizes the Taylor expansion, assuming that percentage tolerances are small. To compute the resulting center of an expression, we perform normal arithmetics on the centers of argument intervals. Then we compute the partial derivatives by varying the value of one interval while keeping the others fixed. Finally we combine the partial derivatives and percentage tolerances together to obtain the resulting percentage tolerance. ;;For really complicated systems, we could also perform Monte carlo simulations to get an answer that is good enough.
false
27407ebb1a29af6293128ba6c2ef2e6a806c5286
4bd59493b25febc53ac9e62c259383fba410ec0e
/Scripts/Task/guess-the-number/scheme/guess-the-number.ss
0af541352b30d2f56051382875ffeb398f804e34
[]
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
217
ss
guess-the-number.ss
(define (guess) (define number (random 11)) (display "Pick a number from 1 through 10.\n> ") (do ((guess (read) (read))) ((= guess number) (display "Well guessed!\n")) (display "Guess again.\n")))
false
ffa3c333a159dc4892644da9f0dbeb5f919f1945
46244bb6af145cb393846505f37bf576a8396aa0
/sicp/3_70.scm
f735b0ed40c1dd4f9e8d31047cf151eb342010be
[]
no_license
aoeuidht/homework
c4fabfb5f45dbef0874e9732c7d026a7f00e13dc
49fb2a2f8a78227589da3e5ec82ea7844b36e0e7
refs/heads/master
2022-10-28T06:42:04.343618
2022-10-15T15:52:06
2022-10-15T15:52:06
18,726,877
4
3
null
null
null
null
UTF-8
Scheme
false
false
1,957
scm
3_70.scm
; Exercise 3.70. It would be nice to be able to generate streams in which the pairs ; appear in some useful order, rather than in the order that results from an ad hoc ; interleaving process. We can use a technique similar to the merge procedure of ; exercise 3.56, if we define a way to say that one pair of integers ; is ``less than'' another. One way to do this is to define a ``weighting function'' ; W(i,j) and stipulate that (i1,j1) is less than (i2,j2) if W(i1,j1) < W(i2,j2). ; Write a procedure merge-weighted that is like merge, except that merge-weighted takes ; an additional argument weight, which is a procedure that computes the weight of a pair, ; and is used to determine the order in which elements should appear in the resulting merged ; stream.69 Using this, generalize pairs to a procedure weighted-pairs that takes two streams, ; together with a procedure that computes a weighting function, and generates the stream of pairs, ; ordered according to weight. Use your procedure to generate ; a. the stream of all pairs of positive integers (i,j) with i < j ordered according to the sum i + j ; b. the stream of all pairs of positive integers (i,j) with i < j, where neither i nor j is divisible by 2, 3, or 5, and the pairs are ordered according to the sum 2 i + 3 j + 5 i j. (define (merge s1 s2 weight) (cond ((stream-null? s1) s2) ((stream-null? s2) s1) (else (let ((s1car (stream-car s1)) (s2car (stream-car s2))) (cond ((< (weight s1car) (weight s2car)) (cons-stream s1car (merge (stream-cdr s1) s2))) (else (cons-stream s2car (merge s1 (stream-cdr s2))))))))) (define (pairs s t) (cons-stream (list (stream-car s) (stream-car t)) (merge (stream-map (lambda (x) (list (stream-car s) x)) (stream-cdr t)) (pairs (stream-cdr s) (stream-cdr t)) (lambda (x) (+ (car x) (cadr x))))))
false
2e6eda65bac83592ed4b063d9b598d27ac848f5b
8a0660bd8d588f94aa429050bb8d32c9cd4290d5
/sitelib/archive/tar.scm
fc40b77230522d813e7d7aabe1fb4e23b1c14faa
[ "BSD-2-Clause" ]
permissive
david135/sagittarius-scheme
dbec76f6b227f79713169985fc16ce763c889472
2fbd9d153c82e2aa342bfddd59ed54d43c5a7506
refs/heads/master
2016-09-02T02:44:31.668025
2013-12-21T07:24:08
2013-12-21T07:24:08
32,497,456
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,495
scm
tar.scm
;;; -*- mode:scheme; coding:utf-8; -*- ;;; ;;; archive/tar.scm - Generic tar interface. ;;; ;;; Copyright (c) 2010-2013 Takashi Kato <[email protected]> ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; (library (archive tar) (export) (import (rnrs) (clos user) (archive interface) (archive core tar) (sagittarius) (sagittarius object) (sagittarius control)) (define-class <tar-archive-input> (<archive-input>) ((current :init-value #f))) (define-class <tar-archive-output> (<archive-output>) ()) (define-class <tar-archive-entry> (<archive-entry>) ((input :init-keyword :input :init-value #f) (header :init-keyword :header) (file :init-keyword :file :init-value #f))) (define-method next-entry! ((in <tar-archive-input>)) (when (~ in 'current) ;; skip (let1 c (~ in 'current) (skip-file (~ in 'source) (~ c 'header)))) (let1 header (get-header-record (~ in 'source)) (if (eof-object? header) #f (rlet1 e (make <tar-archive-entry> :name (header-fulpath header) :type (if (eq? (header-typeflag header) 'directory) 'directory ;; might be symbolic link or so but ignore... 'file) :input in :header header) (set! (~ in 'current) e))))) (define-method extract-entry ((e <tar-archive-entry>) (out <port>)) (rlet1 r (extract-to-port (~ e 'input 'source) (~ e 'header) out) (set! (~ e 'input 'current) #f))) (define-method create-entry ((out <tar-archive-output>) file) (make <tar-archive-entry> :name file :file file :type (if (and (file-exists? file) (file-directory? file)) 'directory 'type))) (define-method append-entry! ((out <tar-archive-output>) (e <tar-archive-entry>)) (append-file (~ out 'sink) (~ e 'file))) (define-method finish! ((out <tar-archive-output>)) (set! (~ out 'sink) #f)) (define-method make-archive-input ((type (eql 'tar)) (source <port>)) (make <tar-archive-input> :source source)) (define-method make-archive-output ((type (eql 'tar)) (sink <port>)) (make <tar-archive-output> :sink sink)) )
false
eead8c2590f236cf4e1d61d9599ecccd257750fa
51d30de9d65cc3d5079f050de33d574584183039
/attic/untyped-ideas/concept.scm
73dffc07843a239abb982d6c1a65e1a6b4cef5d7
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
langmartin/ykk
30feb00265d603ef765b5c664d2f759be34b7b89
dd6e441dddd5b6363ee9adbbdd0f346c1522ffcf
refs/heads/master
2016-09-05T20:01:19.353224
2009-12-10T16:25:55
2009-12-10T16:25:55
408,478
0
1
null
null
null
null
UTF-8
Scheme
false
false
2,823
scm
concept.scm
;; ,open srfi-1 ;; ,open big-util ;; ,open nondeterminism (define (identity x) x) (define (intersperse-too-much lst el) (fold-right (lambda (x tail) (cons el (cons x tail))) '() lst)) (define (intersperse lst el) (cdr (intersperse-too-much lst el))) (define (map* f lst) (if (null? lst) '() (let ((head (car lst)) (tail (cdr lst))) (let ((head1 (f head)) (tail1 (map* f tail))) (if (and (eq? head1 head) (eq? tail1 tail)) lst (cons head1 tail1)))))) (define (depth-first handle tree) (cond ((null? tree) tree) ((handle tree) => (lambda (new-tree) new-tree)) ((not (pair? tree)) tree) (else (let ((mapped (map* (lambda (kid) (depth-first handle kid)) tree))) (if (eq? mapped tree) tree mapped))))) ;; (define (eval* tree env) ;; (if (atom? tree) ;; tree ;; (let ((head (car tree)) ;; (tail (cdr tree))) ;; (cond ((eq? head 'let) ;; (eval* ;; (cdr tail) ;; (env-push env (car tail)))) ;; ((self-eval? head) ;; head) ;; ((symbol? head) ;; (cond ((env-look head env) => ;; identity) ;; (else (error "undefined")))) ;; ((pair? head) ;; (eval* head env)))))) ;; (define (self-eval? x) ;; (or (string? x) ;; (number? x) ;; (char? x))) ;; (define (env-push env bindings) ;; (cons (eval* (make-alist bindings) env) ;; env)) ;; (define (make-alist lst) ;; (cons 'list ;; (map (lambda (pair) ;; (cons 'cons pair)) ;; lst))) ;; (define (env-look sym env) ;; (call-with-current-continuation ;; (lambda (found) ;; (for-each (lambda (x) ;; (cond ((assq x sym) => ;; (lambda (pair) ;; (found (cdr pair)))))) ;; env) ;; #f))) ;; (define (evaluate tree) ;; (eval (eval* tree '()) ;; (scheme-report-environment 5))) (depth-first (lambda (tree) (if ))) (define *tree* (with-input-from-file "data.scm" read)) (lookup '(1 2 3) '(1 2)) (lookup *tree* '(define news-articles)) (define (path . path) (eval (lookup *tree* (cons 'letrec (intersperse-too-much path 'define))) (scheme-report-environment 5))) (define (post data . path) (set! *tree* (depth-first (lambda (tree) (if (eq? tree (lookup tree path)) data #f)) *tree*)))
false
fdcd31c4d7d71e2703171bf64f896d6e10599f62
6838bac9a2c58698df1ed964b977ac0ab8ee6c55
/legacy/quine.scm
25fba26aca39d7f78d9ba76ca896c28d136bde6f
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
jpt4/nocko
4be73b1945927bcb50fd16ebffa35736aa9a9d07
d12d569adc0c39e4fc5cfdbdd8c4b833f493cee2
refs/heads/master
2023-06-07T21:38:15.084127
2023-06-02T03:59:31
2023-06-02T03:59:31
36,998,031
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,653
scm
quine.scm
;; UTC20150507 nocko quine jpt4 #| symbolic derivation *[a 9 b c] *[a1 9 a2 [a3 a4] a5] *[*[a1 [a3 a4] a5] /[a2 *[a1 [a3 a4] a5]]] *[[*[a1 a3 a4] *[a1 a5]] /[a2 [*[a1 a3 a4] *[a1 a5]]]] *[[a1 9 a2 [a3 a4] a5] 9 a2 [a3 a4] a5] *[[*[[a1 9 a2 [a3 a4] a5] a3 a4] *[[a1 9 a2 [a3 a4] a5] a5]] /[a2 [*[[a1 9 a2 [a3 a4] a5] a3 a4] *[[a1 9 a2 [a3 a4] a5] a5]]]] *[[*[[a1 9 a2 [0 1] a5] 0 1] *[[a1 9 a2 [0 1] a5] a5]] /[a2 [*[[a1 9 a2 [0 1] a5] 0 1] *[[a1 9 a2 [0 1] a5] a5]]]] *[[[a1 9 a2 [0 1] a5] *[[a1 9 a2 [0 1] a5] a5]] /[a2 [[a1 9 a2 [0 1] a5] *[[a1 9 a2 [0 1] a5] a5]]]] *[[[a1 9 a2 [0 1] a5] *[[a1 9 a2 [0 1] a5] a5]] /[a2 [[a1 9 a2 [0 1] a5] *[[a1 9 a2 [0 1] a5] a5]]]] *[[*[[a1 9 a2 [0 1] [0 3]] 0 1] *[[a1 9 a2 [0 1] [0 3]] [0 3]]] /[a2 [*[[a1 9 a2 [0 1] a5] 0 1] *[[a1 9 a2 [0 1] a5] a5]]]] *[[[a1 9 a2 [0 1] [0 3]] [9 a2 [0 1] [0 3]]] /[4 [[a1 9 a2 [0 1] [0 3]] [9 a2 [0 1] [0 3]]]]] *[[[[0 2] 9 4 [0 1] [0 3]] [9 4 [0 1] [0 3]]] /[4 [[[0 2] 9 4 [0 1] [0 3]] [9 4 [0 1] [0 3]]]]] *[[[[0 2] 9 4 [0 1] [0 3]] [9 4 [0 1] [0 3]]] [0 2]] [[[0 2] 9 4 [0 1] [0 3]] [9 4 [0 1] [0 3]]] (nock i) = i, where i is: [[[(num (0)) (num (1))] [(num (1 0 0 1)) [(num (0 0 1)) [[(num (0)) (num (1))] [(num (0)) (num (1 1))]]]]] [(num (1 0 0 1)) [(num (0 0 1)) [[(num (0)) (num (1))] [(num (0)) (num (1 1))]]]]] |# ;; nocko native quine encoding (define quineo '[[[(num (0)) (num (1))] [(num (1 0 0 1)) [(num (0 0 1)) [[(num (0)) (num (1))] [(num (0)) (num (1 1))]]]]] [(num (1 0 0 1)) [(num (0 0 1)) [[(num (0)) (num (1))] [(num (0)) (num (1 1))]]]]]) ;; nock decimal encoding (define quine (rbin-to-dec quineo))
false
a3e60b86f8a5ae0a2a524ed8e480f9241f13daf3
382770f6aec95f307497cc958d4a5f24439988e6
/projecteuler/073/073-imp3.scm
8362ca2ef708976700d8cc3d58389f12782d424f
[ "Unlicense" ]
permissive
include-yy/awesome-scheme
602a16bed2a1c94acbd4ade90729aecb04a8b656
ebdf3786e54c5654166f841ba0248b3bc72a7c80
refs/heads/master
2023-07-12T19:04:48.879227
2021-08-24T04:31:46
2021-08-24T04:31:46
227,835,211
1
0
null
null
null
null
UTF-8
Scheme
false
false
1,818
scm
073-imp3.scm
(define range 10000) (define sievebound (quotient (- range 1) 2)) (define crosslimit (quotient (- (exact (floor (sqrt range))) 1) 2)) (define prime (make-bytevector sievebound 1)) (define prime-ref (lambda (pme i) (bytevector-u8-ref pme (- i 1)))) (define prime-set! (lambda (pme i arg) (bytevector-u8-set! pme (- i 1) arg))) (let filt ([i 1]) (cond ((> i sievebound)) ((= (prime-ref prime i) 1) (let f ([j (* 2 i (+ i 1))]) (cond ((> j sievebound) (filt (+ i 1))) (else (prime-set! prime j 0) (f (+ j (+ (* i 2) 1))))))) (else (filt (+ i 1))))) (define prime-r? (lambda (n) (cond ((<= n 0) #f) ((= n 1) #f) ((= n 2) #t) ((= (remainder n 2) 0) #f) ((= (prime-ref prime (/ (- n 1) 2)) 1) #t) (else #f)))) (define prime-len (let f ([i 1] [count 0]) (cond ((= i range) count) ((prime-r? i) (f (+ i 1) (+ count 1))) (else (f (+ i 1) count))))) (define prime-vec (let ([vec (make-vector prime-len 0)]) (let f ([i 1] [j 0]) (cond ((= i range) vec) ((prime-r? i) (vector-set! vec j i) (f (+ i 1) (+ j 1))) (else (f (+ i 1) j)))))) (define F (lambda (m) (let ([q (quotient m 6)] [r (remainder m 6)]) (let ([apart (if (= r 5) 1 0)]) (+ (* q (+ (* q 3) (- 2) r )) apart))))) (let pro ([limit range] [index 0] [count (F range)]) (cond ((and (< index prime-len) (<= (* 5 (vector-ref prime-vec index)) limit)) (let ([newlimit (quotient limit (vector-ref prime-vec index))]) (pro limit (+ index 1) (- count (pro newlimit (+ index 1) (F newlimit)))))) (else count))) #| (time (let pro ...)) no collections 0.000000000s elapsed cpu time 0.000057276s elapsed real time 0 bytes allocated 5066251 |#
false
182b98407ee78ee0f142a9d6a573918c4bd55ce0
be32518c6f54b0ab1eaf33f53405ac1d2e1023c2
/np/lang/macros/test/partitioning/nonterminals/test-errors-extension-addition.ss
51af83415393312a9975c4e33ac542b1c9b460fb
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
ilammy/np
7990302bc30fe7802a7f4fc33d8fa7449ef8b011
0e3cbdea0eb2583f9b272d97bc408011af6a7947
refs/heads/master
2016-09-05T17:11:03.893011
2015-06-13T16:37:39
2015-06-13T16:37:39
23,740,287
1
0
null
2015-06-13T16:39:43
2014-09-06T17:19:46
Scheme
UTF-8
Scheme
false
false
13,400
ss
test-errors-extension-addition.ss
(import (scheme base) (np lang macros partitioning) (np lang macros test utils) (sr ck) (sr ck kernel) (te base) (te conditions assertions) (te utils verify-test-case)) ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; (define-test-case (nonterminals:extension-addition:invalid-syntax "Partitioning of extension nonterminal addition forms: invalid nonterminal syntax") (define-test ("atom") (assert-syntax-error ("Invalid syntax of the nonterminal" lang 42) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ 42)) ) )) ) ) (define-test ("clause 1") (assert-syntax-error ("Invalid syntax of the nonterminal" lang (Number)) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Number))) ) )) ) ) (define-test ("clause 2") (assert-syntax-error ("Invalid syntax of the nonterminal" lang (Number pred)) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Number pred))) ) )) ) ) (define-test ("empty list") (assert-syntax-error ("Invalid syntax of the nonterminal" lang ()) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ ())) ) )) ) ) (define-test ("irregular list 1") (assert-syntax-error ("Invalid syntax of the nonterminal" lang (Number . HA-HA!)) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Number . HA-HA!))) ) )) ) ) (define-test ("irregular list 2") (assert-syntax-error ("Invalid syntax of the nonterminal" lang (Number pred . HA-HA!)) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Number pred . HA-HA!))) ) )) ) ) (define-test ("vector") (assert-syntax-error ("Invalid syntax of the nonterminal" lang #(Number (num) n)) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ #(Number (num) n))) ) )) ) ) ) (verify-test-case! nonterminals:extension-addition:invalid-syntax) ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; (define-test-case (nonterminals:extension-addition:meta-var-names "Partitioning of extension nonterminal addition forms: meta variable names") (define-test ("boolean") (assert-syntax-error ("Name of the meta-variable must be an identifier" lang Number #f) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Number (#f) n))) ) )) ) ) (define-test ("char") (assert-syntax-error ("Name of the meta-variable must be an identifier" lang Number #\A) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Number (#\A) n))) ) )) ) ) (define-test ("empty list") (assert-syntax-error ("Name of the meta-variable must be an identifier" lang Number ()) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Number (()) n))) ) )) ) ) (define-test ("irregular list") (assert-syntax-error ("Name of the meta-variable must be an identifier" lang Number (a . d)) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Number Pred? ((a . d)) n1 n2))) ) )) ) ) (define-test ("list") (assert-syntax-error ("Name of the meta-variable must be an identifier" lang Number (+ x)) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Number ((+ x)) n))) ) )) ) ) (define-test ("number") (assert-syntax-error ("Name of the meta-variable must be an identifier" lang Number 52) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Number (52) n))) ) )) ) ) (define-test ("string") (assert-syntax-error ("Name of the meta-variable must be an identifier" lang Number "Look") ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Number ("Look") n))) ) )) ) ) (define-test ("vector") (assert-syntax-error ("Name of the meta-variable must be an identifier" lang Number #(9)) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Number (#(9)) n))) ) )) ) ) ) (verify-test-case! nonterminals:extension-addition:meta-var-names) ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; (define-test-case (nonterminals:extension-addition:meta-var-syntax "Partitioning of extension nonterminal addition forms: meta variable syntax") (define-test ("atom") (assert-syntax-error ("Invalid syntax of the nonterminal" lang (Number SURPRISE! n)) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Number SURPRISE! n))) ) )) ) ) (define-test ("irregular list") (assert-syntax-error ("Invalid syntax of the nonterminal" lang (Number (a . d) n)) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Number (a . d) n))) ) )) ) ) (define-test ("vector") (assert-syntax-error ("Invalid syntax of the nonterminal" lang (Number a #(b) n)) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Number a #(b) n))) ) )) ) ) ) (verify-test-case! nonterminals:extension-addition:meta-var-syntax) ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; (define-test-case (nonterminals:extension-addition:name "Partitioning of extension nonterminal addition forms: nonterminal names") (define-test ("boolean") (assert-syntax-error ("Name of the nonterminal must be an identifier" lang (#t (some vars)) #t) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (#t (some vars) production1))) ) )) ) ) (define-test ("char") (assert-syntax-error ("Name of the nonterminal must be an identifier" lang (#\b (some vars)) #\b) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (#\b (some vars) production1))) ) )) ) ) (define-test ("empty list") (assert-syntax-error ("Name of the nonterminal must be an identifier" lang (() (var)) ()) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (() (var) production1 (production2 production3)))) ) )) ) ) (define-test ("irregular list") (assert-syntax-error ("Name of the nonterminal must be an identifier" lang ((car . cdr) pred? ()) (car . cdr)) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ ((car . cdr) pred? () production1))) ) )) ) ) (define-test ("list") (assert-syntax-error ("Name of the nonterminal must be an identifier" lang ((some list) pred? (some vars)) (some list)) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ ((some list) pred? (some vars) production1))) ) )) ) ) (define-test ("number") (assert-syntax-error ("Name of the nonterminal must be an identifier" lang (-1 (some vars)) -1) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (-1 (some vars) production1))) ) )) ) ) (define-test ("string") (assert-syntax-error ("Name of the nonterminal must be an identifier" lang ("to" (some vars)) "to") ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ ("to" (some vars) production1))) ) )) ) ) (define-test ("vector") (assert-syntax-error ("Name of the nonterminal must be an identifier" lang (#(1) (some vars)) #(1)) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (#(1) (some vars) production1))) ) )) ) ) ) (verify-test-case! nonterminals:extension-addition:name) ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; (define-test-case (nonterminals:extension-addition:predicate "Partitioning of extension nonterminal addition forms: predicate names") (define-test ("boolean") (assert-syntax-error ("Name of the nonterminal predicate must be an identifier" lang (Nonterminal #f (var1 var2)) #f) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Nonterminal #f (var1 var2) (p p)))) ) )) ) ) (define-test ("char") (assert-syntax-error ("Name of the nonterminal predicate must be an identifier" lang (Nonterminal #\c (var1 var2)) #\c) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Nonterminal #\c (var1 var2) (p p)))) ) )) ) ) (define-test ("irregular list") (assert-syntax-error ("Name of the nonterminal predicate must be an identifier" lang (Nonterminal (a . d) ()) (a . d)) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Nonterminal (a . d) () "technically incorrect production"))) ) )) ) ) (define-test ("number") (assert-syntax-error ("Name of the nonterminal predicate must be an identifier" lang (Nonterminal 6 (var1 var2)) 6) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Nonterminal 6 (var1 var2) (p p)))) ) )) ) ) (define-test ("string") (assert-syntax-error ("Name of the nonterminal predicate must be an identifier" lang (Nonterminal "the" (var1 var2)) "the") ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Nonterminal "the" (var1 var2) (p p)))) ) )) ) ) (define-test ("vector") (assert-syntax-error ("Name of the nonterminal predicate must be an identifier" lang (Nonterminal #(x y z) (var1 var2)) #(x y z)) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Nonterminal #(x y z) (var1 var2) (p p)))) ) )) ) ) ) (verify-test-case! nonterminals:extension-addition:predicate) ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; (define-test-case (nonterminals:extension-addition:syntax "Partitioning of extension nonterminal addition forms: extension syntax") (define-test ("atom") (assert-syntax-error ("Invalid syntax of the nonterminal extension" lang (+ . right-away)) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ . right-away)) ) )) ) ) (define-test ("empty list") (assert-syntax-error ("At least one nonterminal should be specified for addition" lang (+)) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+)) ) )) ) ) (define-test ("irregular list") (assert-syntax-error ("Invalid syntax of the nonterminal extension" lang (+ (Number (n) n n) . random)) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Number (n) n n) . random)) ) )) ) ) (define-test ("vector") (assert-syntax-error ("Invalid syntax of the nonterminal extension" lang (+ . #(Number pp (n) p))) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ . #(Number pp (n) p))) ) )) ) ) ) (verify-test-case! nonterminals:extension-addition:syntax) ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; (define-test-case (nonterminals:extension-addition:production:syntax "Partitioning of extension nonterminal addition forms: productions syntax") (define-test ("atom") (assert-syntax-error ("Invalid syntax of the nonterminal" lang (Nonterminal p () . sudden-atom)) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Nonterminal p () . sudden-atom))) ) )) ) ) (define-test ("empty list") (assert-syntax-error ("At least one production should be specified for a nonterminal" lang Nonterminal) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Nonterminal (nt)))) ) )) ) ) (define-test ("irregular list") (assert-syntax-error ("Invalid syntax of the nonterminal" lang (Nonterminal () foo . bar)) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Nonterminal () foo . bar))) ) )) ) ) (define-test ("vector") (assert-syntax-error ("Invalid syntax of the nonterminal" lang (Nonterminal (nt) . #())) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Nonterminal (nt) . #()))) ) )) ) ) ) (verify-test-case! nonterminals:extension-addition:production:syntax) ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; (define-test-case (nonterminals:extension-addition:production:vector "Partitioning of extension nonterminal addition forms: productions no-vector tests") (define-test ("nested") (assert-syntax-error ("Invalid syntax of the production: vector patterns are not allowed" lang Nonterminal (some (deep list #(123))) #(123)) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Nonterminal () foo bar (some (deep list #(123)))))) ) )) ) ) (define-test ("toplevel") (assert-syntax-error ("Invalid syntax of the production: vector patterns are not allowed" lang Nonterminal #(vector!)) ($ ($quote ($partition-extension-nonterminal-definitions 'lang '((+ (Nonterminal () foo bar #(vector!)))) ) )) ) ) ) (verify-test-case! nonterminals:extension-addition:production:vector)
false
1daf45dbce8e26f6b71bc91296ba2474d3e4b29f
9bcae16e77a91dc8dc3738d52398dc960a6d60d4
/oblig3A/oblig3a.scm
54f829295088b898052becd57fadd13024644491
[ "MIT" ]
permissive
Pilasilda/INF2810
a0a5cd56b122fb9b41ab10d6cc9fcac646fae0a3
89a90eacdd1614067ecda5f805a958af21709d5d
refs/heads/master
2020-05-06T13:24:08.135028
2019-04-08T11:28:07
2019-04-08T11:28:07
180,134,401
0
0
null
null
null
null
UTF-8
Scheme
false
false
6,546
scm
oblig3a.scm
(load "prekode3a.scm") ;Obligatorisk oppgave for Trucmy Ngo Bao og Pilasilda A.George '--Oppgave1A&1B-- (define tabel1 (make-table)) (define (mem melding proc) ;definerer mem som sender med melding og proc som argument (define (memoize) ;definerer memoize (let ((table (make-table))) ;oppretter tabellen verdiene skal legges i (lambda args ;opretter lambda-uttrykk med argumenter uavhengig av hvor mange som sendes inn, derfor args (let ((prev (lookup args table))) ;lookup returnerer true eller false om verdiene finnes eller ikke, args gir svaret av fib som er definert i lambda, table er tabellen som verdiene skal lagres i. ;I prev lagres alle verdiene som er i parantesen (or prev (let ((resultat (apply proc args))) ;Slår sammen fib verdiene (ex. computing 3 2 1 0) og svar av fib legger dette i resultat (insert! args resultat table) resultat)))))) ;legger til verdi i tabellen (define (unmemoize) ;definerer prosedyren unmemoize (or (lookup proc tabel1) proc)) ;lookup returner som sagt true eller false så hvis verdien finnes i tabellen så returneres true hvis ikke false ;proc er fib, proc verdien returneres som altså er fib verdiene (cond ((equal? melding 'memoize) ;en sjekk som tester om meldingen er lik 'memoize (let ((previous proc) ;lar "previous" være prosedyren som tas inn i kallet på memoize og "new" være memoize prosedyrer (new (memoize))) (insert! new previous tabel1) new)) ;inserter kallet på memoize (new) som nøkkel og prosedyren som tas inn som tas inn (previous) som verdi ;før let'en avsluttes, returneres new som er kallet på memoize ((equal? melding 'unmemoize) (unmemoize)))) ;hvis meldingen er lik 'unmemoize kalles unmem prosedyren ;Kall fra oppgavetekst (set! fib(mem 'memoize fib)) (fib 3) (fib 3) (fib 3) (fib 3) (fib 2) (fib 4) (set! fib(mem 'unmemoize fib)) (fib 3) ;Kall fra oppgavetekst (set! test-proc (mem 'memoize test-proc)) (test-proc) (test-proc) (test-proc 40 41 42 43 44) (test-proc 40 41 42 43 44) (test-proc 42 43 44) '--Oppgave1C-- ;Kall fra oppgavetekst (define mem-fib(mem 'memoize fib)) (mem-fib 3) (mem-fib 3) (mem-fib 2) (mem-fib 1) #|Det som skjer ved kall på (mem-fib) er at kun det første resultatet av kallet blir skrevet ut, så hvis vi kaller på (mem-fib 3), så er det kun (fib 3) som lagres i cachen, ikke (fib 2) eller (fib 1) som i det forste eksempelet. Årsaken til dette er at vi ikke endrer bindingen(-) i fib prosedyren, i det første eksemplet setter vi fib til å være (mem 'unmemoize fib) f.eks. men det gjør vi ikke i dette eksempelet. Dermed vil prosedyren kun memoisere verdien som blir sendt inn men de resterende kallene på fib prosedyren. |# '--Oppgave1D ;;Hjelpemetode (define (hjelp argdefs args proc) (apply proc (map (lambda (argdef) (let loop ((args args)) (cond ((null? args) (cadr argdef)) ((eq? (car argdef) (car args)) (cadr args)) (else (loop (cdr args)))))) argdefs))) ;;Greet-metoden (define (greet . args) (hjelp '((time "day")(title "friend")) args (lambda (time title) (display "good ") (cond (time (display time) (display " ") (display title))) (newline)))) (greet) ;kaller paa greet (greet 'time "evening") ;kaller paa greet og sender meg evening som argument, 'time er den navngitte argumentet (greet 'title "sir" 'time "morning");forste som vises er good, saa kalles buffer i greet da hopper vi til den prosedyren, (greet 'time "afternoon" 'title "dear") '--Oppgave2A-- (define (list-to-stream list) (if (stream-null? list) the-empty-stream (cons-stream (stream-car list) (stream-cdr list)))) ;(list-to-stream '(1 2 3 4 5)) ;; (define (stream-to-list stream . n) (define (stl stream i) (if (or (= i 0) (stream-null? stream)) the-empty-stream (cons (stream-car stream) (stl (stream-cdr stream) (- i 1))))) (stl stream (if (null? n) 15 (car n)))) ;(stream-to-list (stream-interval 10 20)) (define (show-stream stream . n) (define (ss-rec stream i) (cond ((= i 0) (display "...\n")) ((stream-null? stream) (newline)) (else (display (stream-car stream)) (display " ") (ss-rec (stream-cdr stream) (- i 1))))) (ss-rec stream (if (null? n) 15 (car n)))) ;; ;(show-stream nats 15) ;(stream-to-list nats 10) '--Oppgave2B-- (define (stream-map proc . argstreams) (if (stream-null? (car argstreams)) the-empty-stream (cons-stream (apply proc (map stream-car argstreams)) (apply stream-map (cons proc (map stream-cdr argstreams)))))) '--Oppgave2C-- ;;En av problemene som kan oppstaa er naar man bruker strommer i memq, fordi strommene er uendelige og vil derfor fore til at man potensielt ikke faar avsluttet prosedyren. ;;Dermed faar man ikke ut noen svar. '--Oppgave2D-- (define (remove-duplicates stream) (if (stream-null? stream) the-empty-stream (cons-stream (stream-car stream) (remove-duplicates (stream-filter (lambda(x) (not (eq? x (stream-car stream)))) (stream-cdr stream)))))) '--Oppgave2E-- (define x (stream-map show (stream-interval 0 10))) ;bare forste element skrives ut her er 0 det forste elementet i intervallet og skrives dermed ut (stream-ref x 5) ;tallene mellom 1-5 skrives ut fordi stream ref skriver ut. Men verdien 0 har allerede blitt skrevet ut tidligere som vil si memoizert derfor skrives kun 1-5 ut (stream-ref x 7) ;her skrive tallet 6 og 7 ut, fordi de andre verdiene har allerede blitt skrevet ut, 1-5 er skrevet ut tidligere saa kun 6 og 7 skrives ut. '--Oppgave2F-- (define (mul-streams s1 s2) (cons-stream (* (stream-car s1)(stream-car s2)) (mul-streams (stream-cdr s1)(stream-cdr s2)))) '--Oppgave2G-- (define (add-streams s1 s2) (stream-map + s1 s2)) (define ones (cons-stream 1 ones)) (define integers (cons-stream 1 (add-streams ones integers))) (define factorials (cons-stream 1 (mul-streams factorials integers))) (stream-ref factorials 5)
false
39d0fe324c9f2986fb2e28d237a2a02f01685ade
de21ee2b90a109c443485ed2e25f84daf4327af3
/exercise/section2/2.41.scm
cf91d4e76f3442a208a4d105e22c14856001b1b6
[]
no_license
s-tajima/SICP
ab82518bdc0551bb4c99447ecd9551f8d3a2ea1d
9ceff8757269adab850d01f238225d871748d5dc
refs/heads/master
2020-12-18T08:56:31.032661
2016-11-10T11:37:52
2016-11-10T11:37:52
18,719,524
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,141
scm
2.41.scm
;= Question ============================================================================= ; ; 問題 2.41 ; ; 与えられた整数nに対し, ; nより小さいか等しい相異る正の整数i, j, kの順序づけられた三つ組で, ; 和が与えられた整数sになるものをすべて見つけよ. ; ;= Prepared ============================================================================= (define (accumulate op initial sequence) (if (null? sequence) initial (op (car sequence) (accumulate op initial (cdr sequence))))) (define (enumerate-interval low high) (if (> low high) () (cons low (enumerate-interval (+ low 1) high)))) ;(accumulate append ; () ; (map (lambda (i) ; (map (lambda (j) (list i j)) ; (enumerate-interval 1 (- i 1)))) ; (enumerate-interval 1 n))) (define (flatmap proc seq) (accumulate append () (map proc seq))) (define (permutations s) (if (null? s) ; 空集合? (list ()) ; 空集合を含むリスト (flatmap (lambda (x) (map (lambda (p) (cons x p)) (permutations (remove x s)))) s))) (define (remove item sequence) (filter (lambda (x) (not (= x item))) sequence)) ;= Answer =============================================================================== (define (s-sum? trio s) (= (+ (car trio) (cadr trio) (caddr trio)) s)) (define (make-trios-sum trio) (list (car trio) (cadr trio) (caddr trio) (+ (car trio) (cadr trio) (caddr trio)))) (define (unique-trios n) (flatmap (lambda (i) (flatmap (lambda (j) (map (lambda (k) (list i j k)) (enumerate-interval 1 (- j 1)))) (enumerate-interval 1 (- i 1)))) (enumerate-interval 1 n))) (define (sum-trios n s) (map make-trios-sum (filter (lambda (trio) (s-sum? trio s)) (unique-trios n)))) (print (sum-trios 9 10))
false
5ee6b69c6fc5645423200736d5ac99cae1d94f6d
b9eb119317d72a6742dce6db5be8c1f78c7275ad
/bridge/play-card.ss
0b613069aa92c4717390a9b0e2be538397482b47
[]
no_license
offby1/doodles
be811b1004b262f69365d645a9ae837d87d7f707
316c4a0dedb8e4fde2da351a8de98a5725367901
refs/heads/master
2023-02-21T05:07:52.295903
2022-05-15T18:08:58
2022-05-15T18:08:58
512,608
2
1
null
2023-02-14T22:19:40
2010-02-11T04:24:52
Scheme
UTF-8
Scheme
false
false
1,828
ss
play-card.ss
(module play-card mzscheme (require (lib "list.ss" "srfi" "1") (lib "trace.ss") "auction.ss" "card.ss" "deck.ss" "hand.ss" "play-history.ss") (print-struct #t) (provide play-card) (define (play-card vulnerability auction-so-far dealer my-hand plays-so-far) (history-ref (best-course-of-play-from-prefix my-hand plays-so-far) (history-length plays-so-far))) ;(trace play-card) (define (best-course-of-play-from-prefix my-hand plays-so-far) (if (= (hand-length my-hand) 1) (history-add plays-so-far (first (hand->list my-hand))) (let ((c (first (legal-plays my-hand plays-so-far)))) (best-course-of-play-from-prefix (without-card c my-hand) (history-add plays-so-far c))))) ;(trace best-course-of-play-from-prefix) (define (legal-plays my-hand plays-so-far) (case (hand-length my-hand) ((0 1) (error "This isn't supposed to happen.")) (else (list (hand-ref my-hand 0) (hand-ref my-hand 1)))) ) ;(trace legal-plays) (random-seed 0) ;; a little exercise (let* ((a (make-auction 'east)) (all-hands (shuffled-deck)) (my-hand (holding all-hands 'south))) (auction-add! a 'pass) (auction-add! a 'pass) (auction-add! a '(1 diamond)) (auction-add! a 'pass) (auction-add! a 'pass) (auction-add! a 'pass) (let loop ((history (make-empty-history)) (my-hand my-hand)) (if (zero? (hand-length my-hand)) (printf "OK, we're done~n") ;TODO: compute score (let ((c (play-card 'dunno a 'east my-hand history))) (printf "~a~n" (card->string c)) (loop (history-add history c) (without-card c my-hand)))))) )
false
b42fb58f4784244e03d2241dc9b4211d3506c226
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
/sitelib/net/http-client/connection.scm
10afbc3a476f6372224a9b9249acc6df7ff231ce
[ "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "MIT", "BSD-2-Clause" ]
permissive
ktakashi/sagittarius-scheme
0a6d23a9004e8775792ebe27a395366457daba81
285e84f7c48b65d6594ff4fbbe47a1b499c9fec0
refs/heads/master
2023-09-01T23:45:52.702741
2023-08-31T10:36:08
2023-08-31T10:36:08
41,153,733
48
7
NOASSERTION
2022-07-13T18:04:42
2015-08-21T12:07:54
Scheme
UTF-8
Scheme
false
false
7,103
scm
connection.scm
;;; -*- mode:scheme;coding:utf-8 -*- ;;; ;;; net/http-client/connection.scm - Base connection for HTTP client ;;; ;;; Copyright (c) 2021 Takashi Kato <[email protected]> ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; #!nounbound (library (net http-client connection) (export make-http-connection http-connection? (rename (http-connection <http-connection>)) http-connection-node http-connection-service http-connection-socket-options http-connection-socket http-connection-input http-connection-output http-connection-context-data http-logging-connection? (rename (http-logging-connection <http-logging-connection>)) make-http-logging-connection http-logging-connection-logger http-connection-open? http-connection-open! http-connection-close! http-connection-send-header! http-connection-send-data! http-connection-receive-header! http-connection-receive-data! ;; for internal or extra http version http-connection-context? (rename (http-connection-context <http-connection-context>)) http-connection-write-log) (import (rnrs) (net socket) (net http-client logging) (sagittarius) ;; for sagittarius-version (srfi :39 parameters)) (define-record-type http-connection-context) (define-record-type http-connection (fields node service socket-options header-sender data-sender header-receiver data-receiver (mutable socket) (mutable input) (mutable output) context-data) (protocol (lambda (p) (lambda (node service option socket header-sender data-sender header-receiver data-receiver data) (unless (or (not socket) (or (socket? socket) (tls-socket? socket))) (assertion-violation 'make-http-connection "Socket or #f is required" socket)) (unless (socket-options? option) (assertion-violation 'make-http-connection "<socket-options> is required" option)) (unless (http-connection-context? data) (assertion-violation 'make-http-connection "<http-connection-context> is required" data)) (p node service option header-sender data-sender header-receiver data-receiver socket (and socket (socket-input-port socket)) (and socket (socket-output-port socket)) data))))) (define-record-type http-logging-connection (parent http-connection) (fields logger) (protocol (lambda (n) (lambda (conn logger) (let ((c ((n (http-connection-node conn) (http-connection-service conn) (http-connection-socket-options conn) (http-connection-socket conn) (http-connection-header-sender conn) (http-connection-data-sender conn) (http-connection-header-receiver conn) (http-connection-data-receiver conn) (http-connection-context-data conn)) logger))) (let ((in (http-connection-input c)) (out (http-connection-output c))) (http-connection-input-set! c (->logging-input-port in logger)) (http-connection-output-set! c (->logging-output-port out logger))) c))))) (define-syntax http-connection-write-log (syntax-rules () ((_ conn exp ...) (let ((c conn)) (when (http-logging-connection? c) (http-connection-logger-write-log (http-client-logger-connection-logger (http-logging-connection-logger c)) exp ...)))))) (define (->logging-input-port in logger) (define wire-logger (http-client-logger-wire-logger logger)) (define (read! bv start count) (let ((ret (get-bytevector-n! in bv start count))) (http-wire-logger-write-log wire-logger "IN" (bytevector-copy bv start (+ start ret))) ret)) (define (close) (close-port in)) (define (ready) (port-ready? in)) (make-custom-binary-input-port "logging-binary-input-port" read! #f #f close ready)) (define (->logging-output-port out logger) (define wire-logger (http-client-logger-wire-logger logger)) (define (write! bv start count) (http-wire-logger-write-log wire-logger "OUT" (bytevector-copy bv start (+ start count))) (put-bytevector out bv start count) count) (define (close) (close-port out)) (make-custom-binary-output-port "logging-binary-output-port" write! #f #f close)) (define (http-connection-open? conn) (and (http-connection-socket conn) #t)) ;; Maybe for reconnect? (define (http-connection-open! conn) (unless (http-connection-open? conn) (let ((socket (socket-options->client-socket (http-connection-socket-options conn) (http-connection-node conn) (http-connection-service conn)))) (http-connection-socket-set! conn socket) (http-connection-input-set! conn (socket-input-port socket)) (http-connection-output-set! conn (socket-output-port socket)))) conn) (define (http-connection-close! conn) (when (http-connection-open? conn) (let ((socket (http-connection-socket conn)) (input (http-connection-input conn)) (output (http-connection-output conn))) (close-port input) (close-port output) (socket-shutdown socket SHUT_RDWR) (socket-close socket) (http-connection-socket-set! conn #f) (http-connection-input-set! conn #f) (http-connection-output-set! conn #f))) conn) (define (http-connection-send-header! conn request) ((http-connection-header-sender conn) conn request)) (define (http-connection-send-data! conn request) ((http-connection-data-sender conn) conn request)) (define (http-connection-receive-header! conn request) ((http-connection-header-receiver conn) conn request)) (define (http-connection-receive-data! conn request) ((http-connection-data-receiver conn) conn request)) )
true
e62da1742e606b23284135f58a56d86f0d7378d8
f5b99d59741af88067a78383cf2df94c06fe3710
/sicp/chap2/2.2.ss
137e036aec54e1ee4b110b51e79d669c88cd58eb
[ "MIT" ]
permissive
shouya/thinking-dumps
53921a23ff62dd6aa0580cec6da26b11b83dd818
6191a940f3fca4661a6f01663ef38b8ce57c9018
refs/heads/master
2023-06-08T17:53:34.143893
2023-06-04T15:41:18
2023-06-04T15:41:18
22,285,392
24
3
MIT
2022-06-11T12:23:49
2014-07-26T11:40:12
Coq
UTF-8
Scheme
false
false
1,039
ss
2.2.ss
(define (print-point p) (display "(") (display (x-point p)) (display ",") (display (y-point p)) (display ")")) (define (print-point-newline p) (print-point p) (newline)) ; Have fun :) (define (make-point x y) (lambda (q) (if q x y))) (define (x-point p) (p #t)) (define (y-point p) (p #f)) (define (make-segment p1 p2) (cons p1 p2)) (define (start-segment seg) (car seg)) (define (end-segment seg) (cdr seg)) (define (midpoint-segment seg) (make-point (/ (+ (x-point (start-segment seg)) (x-point (end-segment seg))) 2) (/ (+ (y-point (start-segment seg)) (y-point (end-segment seg))) 2))) (define (print-segment seg) (print-point (start-segment seg)) (display "-") (print-point (end-segment seg))) (define (print-segment-newline seg) (print-segment seg) (newline)) ; Test cases (let ((seg (make-segment (make-point 1 2) (make-point 3 4)))) (print-segment-newline seg) (print-point-newline (midpoint-segment seg)))
false
ac57bacee80e2449cbb82e6231c7101d3700880f
a74932f6308722180c9b89c35fda4139333703b8
/edwin48/wincom.scm
7ffe28abf7cc2f21c39700bd86c40d880f08d75a
[]
no_license
scheme/edwin48
16b5d865492db5e406085e8e78330dd029f1c269
fbe3c7ca14f1418eafddebd35f78ad12e42ea851
refs/heads/master
2021-01-19T17:59:16.986415
2014-12-21T17:50:27
2014-12-21T17:50:27
1,035,285
39
10
null
2022-02-15T23:21:14
2010-10-29T16:08:55
Scheme
UTF-8
Scheme
false
false
22,807
scm
wincom.scm
#| -*-Scheme-*- $Id: wincom.scm,v 1.139 2008/01/30 20:02:07 cph Exp $ Copyright (C) 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Massachusetts Institute of Technology This file is part of MIT/GNU Scheme. MIT/GNU Scheme is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. MIT/GNU Scheme is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MIT/GNU Scheme; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. |# ;;;; Window Commands (define-variable window-min-width "Delete any window less than this wide. Do not set this variable below 2." 2 (lambda (object) (and (exact-integer? object) (>= object 2)))) (define-variable window-min-height "Delete any window less than this high. The modeline is not included in this figure. Do not set this variable below 1." 1 (lambda (object) (and (exact-integer? object) (>= object 1)))) (define-variable next-screen-context-lines "Number of lines of continuity when scrolling by screenfuls." 2 exact-nonnegative-integer?) (define-variable use-multiple-frames "If true, commands try to use multiple frames rather than multiple windows. Has no effect unless multiple-frame support is available." #f boolean?) (define edwin-variable$use-multiple-screens edwin-variable$use-multiple-frames) (define-variable pop-up-windows "True enables the use of pop-up windows." #t boolean?) (define-variable preserve-window-arrangement "True means commands that normally change the window arrangement do not." #f boolean?) (define-variable split-height-threshold "Pop-up windows would prefer to split the largest window if this large. If there is only one window, it is split regardless of this value." 500 exact-nonnegative-integer?) (define-command redraw-display "Redraws the entire display from scratch." () (lambda () (update-screens! #t))) (define-command recenter "Choose new window putting point at center, top or bottom. With no argument, chooses a window to put point at the center \(cursor-centering-point says where). An argument gives the line to put point on; negative args count from the bottom." "P" (lambda (argument) (let ((window (selected-window))) (if (not argument) (begin (window-scroll-y-absolute! window (window-y-center window)) (window-redraw! window) (update-selected-screen! #t)) (window-scroll-y-absolute! window (modulo (if (command-argument-multiplier-only? argument) (window-y-center window) (command-argument-value argument)) (window-y-size window))))))) (define-command move-to-window-line "Position point relative to window. With no argument, position at text at center of window. An argument specifies screen line; zero means top of window, negative means relative to bottom of window." "P" (lambda (argument) (let ((window (selected-window))) (let ((mark (or (window-coordinates->mark window 0 (if (not argument) (window-y-center window) (modulo (command-argument-value argument) (window-y-size window)))) (window-coordinates->mark window 0 (window-mark->y window (buffer-end (window-buffer window))))))) (set-current-point! (if (group-start? mark) (group-start mark) mark)))))) (define-command home-cursor "Position point at upper-left corner of window." () (lambda () (let ((mark (window-coordinates->mark (selected-window) 0 0))) (set-current-point! (if (group-start? mark) (group-start mark) mark))))) (define-command scroll-up "Move down to display next screenful of text. With argument, moves window down that many lines (negative moves up). Just minus as an argument moves up a full screen." "P" (lambda (argument) (let ((window (selected-window))) (scroll-window window (standard-scroll-window-argument window argument 1))))) (define-command scroll-down "Move up to display previous screenful of text. With argument, moves window up that many lines (negative moves down). Just minus as an argument moves down a full screen." "P" (lambda (argument) (let ((window (selected-window))) (scroll-window window (standard-scroll-window-argument window argument -1))))) (define-command scroll-up-several-screens "Move down to display next screenful of text. With argument, move window down that many screenfuls (negative moves up). Just minus as an argument moves up a full screen." "P" (lambda (argument) (let ((window (selected-window))) (scroll-window window (multi-scroll-window-argument window argument 1))))) (define-command scroll-down-several-screens "Move up to display previous screenful of text. With argument, move window down that many screenfuls (negative moves down). Just minus as an argument moves down full screen." "P" (lambda (argument) (let ((window (selected-window))) (scroll-window window (multi-scroll-window-argument window argument -1))))) (define-command scroll-other-window "Scroll text of next window up ARG lines, or near full screen if no arg." "P" (lambda (argument) (let ((window (or (and (typein-window? (selected-window)) (weak-car *minibuffer-scroll-window*)) (other-window-interactive 1)))) (scroll-window window (standard-scroll-window-argument window argument 1))))) (define-command scroll-other-window-down "Scroll text of next window down ARG lines, or near full screen if no arg." "P" (lambda (argument) (let ((window (or (and (typein-window? (selected-window)) (weak-car *minibuffer-scroll-window*)) (other-window-interactive 1)))) (scroll-window window (standard-scroll-window-argument window argument -1))))) (define-command scroll-other-window-several-screens "Scroll other window up several screenfuls. Specify the number as a numeric argument, negative for down. The default is one screenful up. Just minus as an argument means scroll one screenful down." "P" (lambda (argument) (let ((window (or (and (typein-window? (selected-window)) (weak-car *minibuffer-scroll-window*)) (other-window-interactive 1)))) (scroll-window window (multi-scroll-window-argument window argument 1))))) (define* (scroll-window window n (limit editor-error)) (if (window-mark-visible? window ((if (negative? n) buffer-start buffer-end) (window-buffer window))) (limit) (window-scroll-y-relative! window n))) (define (standard-scroll-window-argument window argument factor) (* factor (let ((quantum (- (window-y-size window) (ref-variable next-screen-context-lines)))) (cond ((not argument) quantum) ((command-argument-negative-only? argument) (- quantum)) (else (command-argument-value argument)))))) (define (multi-scroll-window-argument window argument factor) (* factor (let ((quantum (- (window-y-size window) (ref-variable next-screen-context-lines)))) (cond ((not argument) quantum) ((command-argument-negative-only? argument) (- quantum)) (else (* (command-argument-value argument) quantum)))))) (define-command what-cursor-position "Print info on cursor position (on screen and within buffer)." () (lambda () (let ((buffer (selected-buffer)) (point (current-point))) (let ((position (mark-index point)) (total (group-length (buffer-group buffer)))) (message (if (group-end? point) "" (let ((char (mark-right-char point))) (let ((n (char->ascii char))) (string-append "Char: " (key-name char) " (" (if (zero? n) "" "0") (number->string n 8) ") ")))) "point=" (+ position 1) " of " total "(" (if (zero? total) 0 (integer-round (* 100 position) total)) "%) " (let ((group (mark-group point))) (let ((start (group-start-index group)) (end (group-end-index group))) (if (and (zero? start) (= end total)) "" (string-append "<" (number->string start) " - " (number->string end) "> ")))) "x=" (mark-column point)))))) ;;;; Multiple Windows (define-command split-window-vertically "Split current window into two windows, one above the other. This window becomes the uppermost of the two, and gets ARG lines. No arg means split equally." "P" (lambda (argument) (disallow-typein) (window-split-vertically! (selected-window) (command-argument-value argument)))) (define-command split-window-horizontally "Split current window into two windows side by side. This window becomes the leftmost of the two, and gets ARG lines. No arg means split equally." "P" (lambda (argument) (disallow-typein) (window-split-horizontally! (selected-window) (command-argument-value argument)))) (define-command enlarge-window "Makes current window ARG lines bigger." "p" (lambda (argument) (disallow-typein) (window-grow-vertically! (selected-window) argument))) (define-command shrink-window "Makes current window ARG lines smaller." "p" (lambda (argument) (disallow-typein) (window-grow-vertically! (selected-window) (- argument)))) (define-command shrink-window-if-larger-than-buffer "Shrink the WINDOW to be as small as possible to display its contents. Do nothing if the buffer contains more lines than the present window height, or if some of the window's contents are scrolled out of view, or if the window is the only window of its frame." () (lambda () (shrink-window-if-larger-than-buffer (selected-window)))) (define-command enlarge-window-horizontally "Makes current window ARG columns wider." "p" (lambda (argument) (disallow-typein) (window-grow-horizontally! (selected-window) argument))) (define-command shrink-window-horizontally "Makes current window ARG columns narrower." "p" (lambda (argument) (disallow-typein) (window-grow-horizontally! (selected-window) (- argument)))) (define-command delete-window "Delete the current window from the screen." () (lambda () (let ((window (selected-window))) (if (and (window-has-no-neighbors? window) (use-multiple-screens?) (other-screen (selected-screen) 1 #t)) (delete-screen! (selected-screen)) (window-delete! window))))) (define-command delete-other-windows "Make the current window fill the screen." () (lambda () (delete-other-windows (selected-window)))) (define-command kill-buffer-and-window "Kill the current buffer and delete the window it was in." () (lambda () (kill-buffer-interactive (current-buffer)) (window-delete! (selected-window)))) (define-command other-window "Select the ARG'th different window." "p" (lambda (argument) (select-window (other-window-interactive argument)))) (define (other-window-interactive n) (let ((window (let ((window (other-window n))) (if (selected-window? window) (and (use-multiple-screens?) (let ((screen (other-screen (selected-screen)))) (and screen (screen-selected-window screen)))) window)))) (if (not window) (editor-error "No other window")) window)) (define (disallow-typein) (if (typein-window? (selected-window)) (editor-error "Not implemented for typein window"))) (define (use-multiple-screens?) (and (ref-variable use-multiple-frames) (multiple-screens?))) (define (select-buffer-other-window buffer) (let ((window (selected-window)) (use-window (lambda (window) (select-buffer buffer window) (select-window window)))) (let loop ((windows (buffer-windows buffer))) (cond ((null? windows) (let ((window* (next-visible-window window #f))) (cond (window* (use-window window*)) ((use-multiple-screens?) (select-buffer-other-screen buffer)) (else (use-window (window-split-vertically! window #f)))))) ((and (not (eq? (car windows) window)) (window-visible? (car windows))) (select-window (car windows))) (else (loop (cdr windows))))))) (define* (select-buffer-other-screen buffer (screen #f)) (if (multiple-screens?) (let ((screen (other-screen (if (not screen) (selected-screen) screen)))) (if screen (let ((window (screen-selected-window screen))) (select-window window) (select-buffer buffer window)) (make-screen buffer))) (editor-error "Display doesn't support multiple screens"))) (define (shrink-window-if-larger-than-buffer window) (if (not (window-has-no-neighbors? window)) (let ((buffer (window-buffer window))) (let ((current-height (window-y-size window)) (min-height (+ (- (window-mark->y window (buffer-end buffer)) (window-mark->y window (buffer-start buffer))) 1)) (max-height (and (eq? window (weak-car *previous-popped-up-window*)) (weak-cdr *previous-popped-up-window*)))) (cond ((< 0 min-height current-height) (adjust-window-height! window min-height)) ((and max-height (> min-height current-height) (< current-height max-height)) (adjust-window-height! window (min min-height max-height)))))))) (define (adjust-window-height! window new-height) (with-variable-value! (ref-variable-object window-min-height) 1 (lambda () (window-grow-vertically! window (- new-height (window-y-size window)))))) ;;;; Pop-up Buffers (define-command kill-pop-up-buffer "Kills the most recently popped up buffer, if one exists. Also kills any pop up window it may have created." () (lambda () (kill-pop-up-buffer #t))) (define (cleanup-pop-up-buffers thunk) (fluid-let ((*previous-popped-up-window* (weak-cons #f #f)) (*previous-popped-up-buffer* (weak-cons #f #f)) (*minibuffer-scroll-window* (weak-cons #f #f)) (*pop-up-buffer-window-alist* (map (lambda (window) (weak-cons window (window-buffer window))) (window-list)))) (dynamic-wind (lambda () unspecific) thunk (lambda () (kill-pop-up-buffer #f))))) (define (kill-pop-up-buffer error-if-none?) (let ((window (weak-car *previous-popped-up-window*))) (if window (begin (weak-set-car! *previous-popped-up-window* #f) (if (and (window-live? window) (not (window-has-no-neighbors? window))) (window-delete! window))))) (let ((buffer (weak-car *previous-popped-up-buffer*))) (cond ((and buffer (buffer-alive? buffer)) (for-each (lambda (window) (let ((entry (weak-assq window *pop-up-buffer-window-alist*))) (if entry (select-buffer-no-record (weak-cdr entry) window)))) (buffer-windows buffer)) (weak-set-car! *previous-popped-up-buffer* #f) (kill-buffer-interactive buffer)) (error-if-none? (editor-error "No previous pop up buffer."))))) (define (maybe-kill-pop-up-buffer buffer) (if (and buffer (eq? buffer (popped-up-buffer))) (kill-pop-up-buffer #f))) (define (popped-up-buffer) (weak-car *previous-popped-up-buffer*)) (define (keep-pop-up-buffer buffer) (if (or (not buffer) (eq? buffer (weak-car *previous-popped-up-buffer*))) (begin (weak-set-car! *previous-popped-up-window* #f) (weak-set-car! *previous-popped-up-buffer* #f)))) (define (pop-up-buffer-option options name default) (let loop ((options options)) (if (pair? options) (let ((option (car options))) (cond ((eq? name option) #t) ((and (pair? option) (eq? name (car option)) (pair? (cdr option)) (null? (cddr option))) (cadr option)) (else (loop (cdr options))))) default))) (define *previous-popped-up-window* (weak-cons #f #f)) (define *previous-popped-up-buffer* (weak-cons #f #f)) (define *minibuffer-scroll-window* (weak-cons #f #f)) (define *pop-up-buffer-window-alist* '()) (define* (pop-up-buffer buffer (select? #f) (options '())) ;; If some new window is created by this procedure, it is returned ;; as the value. Otherwise the value is false. (let* ((screen (pop-up-buffer-option options 'SCREEN (selected-screen))) (selected (screen-selected-window screen))) (define (pop-up-window window) (let ((window (window-split-vertically! window (pop-up-buffer-option options 'HEIGHT #f)))) (weak-set-car! *previous-popped-up-window* window) (weak-set-cdr! *previous-popped-up-window* (window-y-size window)) (pop-into-window window) window)) (define (pop-into-window window) (select-buffer buffer window) (maybe-record-window window)) (define (maybe-record-window window) (weak-set-car! *minibuffer-scroll-window* window) (if select? (select-window window)) (and (eq? window (weak-car *previous-popped-up-window*)) window)) (define (find-visible-window buffer) (let loop ((windows (buffer-windows buffer))) (and (pair? windows) (let ((window (car windows))) (if (and (window-visible? window) (eq? (window-screen window) screen) (not (and (pop-up-buffer-option options 'NOT-CURRENT-WINDOW #f) (eq? window selected)))) window (loop (cdr windows))))))) (if (< (ref-variable window-min-height) 2) (set-variable! window-min-height 2)) (weak-set-car! *previous-popped-up-buffer* buffer) (let ((window (find-visible-window buffer))) (if window (begin (set-window-point! window (buffer-point buffer)) (maybe-record-window window)) (let ((limit (* 2 (ref-variable window-min-height)))) (if (< (ref-variable split-height-threshold) limit) (set-variable! split-height-threshold limit)) (cond ((and (use-multiple-screens?) (other-screen screen)) => (lambda (screen) (pop-into-window (screen-selected-window screen)))) ((ref-variable preserve-window-arrangement) (pop-into-window (largest-window screen))) ((not (ref-variable pop-up-windows)) (pop-into-window (lru-window screen))) ((use-multiple-screens?) (maybe-record-window (screen-selected-window (make-screen buffer)))) (else (let ((window (largest-window screen))) (if (and (>= (window-y-size window) (ref-variable split-height-threshold)) (not (window-has-horizontal-neighbor? window))) (pop-up-window window) (let ((window (lru-window screen))) (if (and (or (eq? window selected) (and (typein-window? selected) (eq? window (window1+ window)))) (>= (window-y-size window) limit)) (pop-up-window window) (pop-into-window window)))))))))))) (define (get-buffer-window buffer) (let loop ((windows (buffer-windows buffer))) (and (not (null? windows)) (if (window-visible? (car windows)) (car windows) (loop (cdr windows)))))) (define (largest-window screen) (let ((start (screen-window0 screen))) (let loop ((window (window1+ start)) (largest start) (largest-area (* (window-x-size start) (window-y-size start)))) (if (eq? window start) largest (let ((area (* (window-x-size window) (window-y-size window)))) (if (> area largest-area) (loop (window1+ window) window area) (loop (window1+ window) largest largest-area))))))) (define (lru-window screen) (let ((start (screen-window0 screen))) (define (search-full-width window smallest smallest-time) (let ((next (window1+ window)) (time (window-select-time window))) (let ((consider-window? (and (not (window-has-horizontal-neighbor? window)) (or (not smallest) (< time smallest-time))))) (if (eq? window start) (if consider-window? window (or smallest (search-all next start (window-select-time start)))) (if consider-window? (search-full-width next window time) (search-full-width next smallest smallest-time)))))) (define (search-all window smallest smallest-time) (if (eq? window start) smallest (let ((time (window-select-time window))) (if (< time smallest-time) (search-all (window1+ window) window time) (search-all (window1+ window) smallest smallest-time))))) (search-full-width (window1+ start) #f #f))) (define (delete-other-windows start) (let loop ((window (window1+ start))) (if (not (eq? window start)) (begin (window-delete! window) (loop (window1+ window)))))) (define-command toggle-screen-width "Restrict the editor's width on the screen. With no argument, restricts the width to 80 columns, unless it is already restricted, in which case it undoes the restriction. With \\[universal-argument] only, undoes all restrictions. Otherwise, the argument is the number of columns desired." "P" (lambda (argument) (let ((screen (selected-screen))) (let ((window (screen-root-window screen))) (send window ':set-size! (let ((x-size (screen-x-size screen))) (cond ((command-argument-multiplier-only? argument) x-size) ((not argument) (let ((x-size* (window-x-size window))) (if (< x-size* x-size) x-size (min 80 x-size)))) (else (let ((argument (command-argument-value argument))) (if (< argument 10) (editor-error "restriction too small: " argument)) (min x-size argument))))) (screen-y-size screen))) (update-screen! screen #t)))) (define-command compare-windows "Compare text in current window with text in next window. Compares the text starting at point in each window, moving over text in each one as far as they match." () (lambda () (let ((w1 (selected-window)) (w2 (other-window-interactive 1))) (let ((p1 (window-point w1))) (let loop ((s1 p1) (s2 (window-point w2)) (length 1024)) (if (> length 0) (let ((e1 (mark+ s1 length #f)) (e2 (mark+ s2 length #f))) (if (and e1 e2 (if (= length 1) (char=? (extract-right-char s1) (extract-right-char s2)) (string=? (extract-string s1 e1) (extract-string s2 e2)))) (loop e1 e2 length) (loop s1 s2 (quotient length 2)))) (begin (set-window-point! w1 s1) (set-window-point! w2 s2) (if (mark= s1 p1) (editor-beep)))))))))
false
574e285bb61ef7105d007ad7d022314170a31156
951b7005abfe3026bf5b3bd755501443bddaae61
/平方根2.scm
0247f602d5cbb97b78284dcc7831770ca967b0db
[]
no_license
WingT/scheme-sicp
d8fd5a71afb1d8f78183a5f6e4096a6d4b6a6c61
a255f3e43b46f89976d8ca2ed871057cbcbb8eb9
refs/heads/master
2020-05-21T20:12:17.221412
2016-09-24T14:56:49
2016-09-24T14:56:49
63,522,759
2
0
null
null
null
null
UTF-8
Scheme
false
false
290
scm
平方根2.scm
(define (fixed-point f guess) (define next (f guess)) (if (< (abs (- guess next)) 0.00001) guess (fixed-point f next))) (define (average-damp f) (lambda (x) (/ (+ x (f x)) 2))) (define (squareroot x) (fixed-point (average-damp (lambda (y) (/ x y))) 1.0)) (squareroot 2)
false
d5c4c7f57639d8fbf936449090186d50ea8be892
495be054a7d58871a0a975ad90dcd3f9ad04ffe4
/ch4.2-lazy-evaluator/ch4.2.scm
be5e981eb0b3485d85e1e5bb684e5f3fabd1b115
[]
no_license
Galaxy21Yang/sicp
cd0b646aabc693f9bad46fac880ff2f50ac667ba
17990996ad4b8906ff3d27219d23033ca44753a0
refs/heads/master
2020-12-03T05:35:32.987780
2015-09-25T09:18:57
2015-09-25T09:18:57
43,195,037
13
5
null
2015-09-26T06:30:45
2015-09-26T06:30:45
null
UTF-8
Scheme
false
false
1,215
scm
ch4.2.scm
(define (try a b) (if (= a 0) 1 b)) ; => ok (try 0 (/ 1 0)) ; => 10 ;;; ex 4.27 (define count 0) (define (id x) (set! count (+ count 1)) x) (define w (id (id 10))) ;; > count => ??? ;; > w => ??? ;; > count => ??? ;;; ex 4.29 (define count 0) (define (id x) (set! count (+ count 1)) x) (define (square x) (* x x)) ;; > (square (id 10)) ;; => ??? ;; > count ;; => ??? ;;; ex 4.30 ;; original (define (eval-sequence exps env) (cond ((last-exp? exps) (eval (first-exp exps) env)) (else (eval (first-exp exps) env) (eval-sequence (rest-exps exps) env)))) ;; Cy's proposal (define (eval-sequence exps env) (cond ((last-exp? exps) (eval (first-exp exps) env)) (else (actual-value (first-exp exps) env) (eval-sequence (rest-exps exps) env)))) ;; a. (define (for-each proc items) (if (null? items) 'done (begin (proc (car items)) (for-each proc (cdr items))))) (for-each (lambda (x) (newline) (display x)) (list 57 321 88)) ;; => 57 ;; => 321 ;; => 88 ;; b. (define (p1 x) (set! x (cons x '(2))) x) (define (p2 x) (define (p e) e x) (p (set! x (cons x '(2))))) ;; (p1 1) => ??? ;; (p2 1) => ???
false
12452f16a5cedff483654618ed3b0268eac6d88c
defeada37d39bca09ef76f66f38683754c0a6aa0
/UnityEngine/unity-engine/mesh-renderer.sls
a4044844799183c72d072f4525c5dd896ee645e9
[]
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
722
sls
mesh-renderer.sls
(library (unity-engine mesh-renderer) (export new is? mesh-renderer? additional-vertex-streams-get additional-vertex-streams-set! additional-vertex-streams-update!) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new UnityEngine.MeshRenderer a ...))))) (define (is? a) (clr-is UnityEngine.MeshRenderer a)) (define (mesh-renderer? a) (clr-is UnityEngine.MeshRenderer a)) (define-field-port additional-vertex-streams-get additional-vertex-streams-set! additional-vertex-streams-update! (property:) UnityEngine.MeshRenderer additionalVertexStreams UnityEngine.Mesh))
true
bbc7a1a984de9ee589c989f94666642fac8f3743
6f721c7ab6fe315b2160e9665b19eab1b451568e
/ex3.22.scm
c3b6cc17bd9eae655d7ba95083b7bf019a6c1038
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
imrehorvath/SICP
7d76de693a3fc6a00adcf4d2191aad6d0196aec4
713ec57a9176c3ebd00b1ed804ad1e3cbade20df
refs/heads/master
2021-06-22T15:19:57.682197
2021-02-18T16:26:08
2021-02-18T16:26:08
29,239,860
0
0
null
null
null
null
UTF-8
Scheme
false
false
961
scm
ex3.22.scm
(define (make-queue) (let ((front-ptr '()) (rear-ptr '())) (define (empty?) (null? front-ptr)) (define (insert item) (let ((new-pair (cons item '()))) (cond ((empty?) (set! front-ptr new-pair) (set! rear-ptr new-pair) (cons front-ptr rear-ptr)) (else (set-cdr! rear-ptr new-pair) (set! rear-ptr new-pair) (cons front-ptr rear-ptr))))) (define (dispatch m) (cond ((eq? m 'front) (if (empty?) (error "FRONT called on an empty queue") (car front-ptr))) ((eq? m 'insert) insert) ((eq? m 'delete) (if (empty?) (error "DELETE! called on an empty queue") (begin (set! front-ptr (cdr front-ptr)) (cons front-ptr rear-ptr)))) (else (error "Undefined operation -- QUEUE" m)))) dispatch)) (define (front-queue queue) (queue 'front)) (define (insert-queue! queue item) ((queue 'insert) item)) (define (delete-queue! queue) (queue 'delete))
false
3471a7edf7f4ed20484b94e90a10e5c380898c8e
a74932f6308722180c9b89c35fda4139333703b8
/edwin48/comman.scm
493a66dfc21a687cc2f140ea5737743d3899a929
[]
no_license
scheme/edwin48
16b5d865492db5e406085e8e78330dd029f1c269
fbe3c7ca14f1418eafddebd35f78ad12e42ea851
refs/heads/master
2021-01-19T17:59:16.986415
2014-12-21T17:50:27
2014-12-21T17:50:27
1,035,285
39
10
null
2022-02-15T23:21:14
2010-10-29T16:08:55
Scheme
UTF-8
Scheme
false
false
2,902
scm
comman.scm
#| -*-Scheme-*- $Id: comman.scm,v 1.92 2008/01/30 20:01:59 cph Exp $ Copyright (C) 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Massachusetts Institute of Technology This file is part of MIT/GNU Scheme. MIT/GNU Scheme is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. MIT/GNU Scheme is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MIT/GNU Scheme; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. |# ;;;; Commands and Variables (define-record-type* command (%make-command) (name %description interactive-specification procedure)) (define (command-description command) (let ((desc (command-%description command))) (if (description? desc) desc (let ((new (->doc-string (symbol-name (command-name command)) desc))) (if new (set-command-%description! command new)) new)))) (define (command-name-string command) (editor-name/internal->external (symbol-name (command-name command)))) (define (editor-name/internal->external string) string) (define (editor-name/external->internal string) string) (define (make-command name description specification procedure) (let* ((sname (symbol-name name)) (command (or (string-table-get editor-commands sname) (let ((command (%make-command))) (string-table-put! editor-commands sname command) command)))) (set-command-name! command name) (set-command-%description! command (doc-string->posn sname description)) (set-command-interactive-specification! command specification) (set-command-procedure! command procedure) command)) (define editor-commands (make-string-table 500)) (define* (name->command name (if-undefined 'INTERN)) (or (string-table-get editor-commands (symbol-name name)) (case if-undefined ((#F) #f) ((ERROR) (error "Undefined command:" name)) ((INTERN) (letrec ((command (make-command name "undefined command" '() (lambda () (editor-error "Undefined command:" name))))) command)) (else (error:bad-range-argument if-undefined 'NAME->COMMAND))))) (define (->command object) (if (command? object) object (name->command object))) (define (copy-command new-name command) (make-command new-name (command-%description command) (command-interactive-specification command) (command-procedure command)))
false
3915032b56c8b33e051595db361f75b83eaa2894
defeada37d39bca09ef76f66f38683754c0a6aa0
/mscorlib/system/gc.sls
31e3f9a1a6eb64c9874b8e7b82521ee7cde52ffd
[]
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,920
sls
gc.sls
(library (system gc) (export is? gc? collection-count keep-alive remove-memory-pressure get-generation re-register-for-finalize wait-for-pending-finalizers suppress-finalize add-memory-pressure get-total-memory collect max-generation) (import (ironscheme-clr-port)) (define (is? a) (clr-is System.GC a)) (define (gc? a) (clr-is System.GC a)) (define-method-port collection-count System.GC CollectionCount (static: System.Int32 System.Int32)) (define-method-port keep-alive System.GC KeepAlive (static: System.Void System.Object)) (define-method-port remove-memory-pressure System.GC RemoveMemoryPressure (static: System.Void System.Int64)) (define-method-port get-generation System.GC GetGeneration (static: System.Int32 System.WeakReference) (static: System.Int32 System.Object)) (define-method-port re-register-for-finalize System.GC ReRegisterForFinalize (static: System.Void System.Object)) (define-method-port wait-for-pending-finalizers System.GC WaitForPendingFinalizers (static: System.Void)) (define-method-port suppress-finalize System.GC SuppressFinalize (static: System.Void System.Object)) (define-method-port add-memory-pressure System.GC AddMemoryPressure (static: System.Void System.Int64)) (define-method-port get-total-memory System.GC GetTotalMemory (static: System.Int64 System.Boolean)) (define-method-port collect System.GC Collect (static: System.Void System.Int32 System.GCCollectionMode) (static: System.Void System.Int32) (static: System.Void)) (define-field-port max-generation #f #f (static: property:) System.GC MaxGeneration System.Int32))
false
797e1a30288dd27563ba69f6c6f651f4650b1db1
b0c1935baa1e3a0b29d1ff52a4676cda482d790e
/tests/t-eval.scm
908774747b6e340c74a00122ea9819307a239ce7
[ "MIT" ]
permissive
justinethier/husk-scheme
35ceb8f763a10fbf986340cb9b641cfb7c110509
1bf5880b2686731e0870e82eb60529a8dadfead1
refs/heads/master
2023-08-23T14:45:42.338605
2023-05-17T00:30:56
2023-05-17T00:30:56
687,620
239
28
MIT
2023-05-17T00:30:07
2010-05-26T17:02:56
Haskell
UTF-8
Scheme
false
false
333
scm
t-eval.scm
;; ;; husk-scheme ;; http://github.com/justinethier/husk-scheme ;; ;; Written by Justin Ethier ;; ;; Test cases for eval ;; (unit-test-start "eval") (assert/equal (eval '(* 7 3)) 21) (assert/equal (let ((f (eval '(lambda (f x) (f x x))))) (f + 10)) 20) (unit-test-handler-results)
false
e92a6573f0c3a3dfbd28572d723dafde5929f03a
5a68949704e96b638ca3afe335edcfb65790ca20
/quasiquote/let-star.scm
24c6a2b9f1a73db138f233fca0a0e74cdd1a55b0
[]
no_license
terryc321/lisp
2194f011f577d6b941a0f59d3c9152d24db167b2
36ca95c957eb598facc5fb4f94a79ff63757c9e5
refs/heads/master
2021-01-19T04:43:29.122838
2017-05-24T11:53:06
2017-05-24T11:53:06
84,439,281
2
0
null
null
null
null
UTF-8
Scheme
false
false
1,300
scm
let-star.scm
;; klet ;; let in core syntax ;; apply cps conversion to get klet ;; define the macro initially as a function ;; then run the function over the let form we want to convert ;; assume not nested let otherwise we need an expression walker ;; ;; "LOADED let-star.scm -- nothing defined yet tho. " ;; (let* ((a 1) ;; (b 2) ;; (c 3)) ;; (list a b c)) ;; ((lambda (a) ((lambda (b) ((lambda (c) (list a b c)) (+ b 1))) (+ a 1))) 1) ;; ((lambda (a) ((lambda (b) ((lambda (c) (list a b c)) 3))2)) 1) ;; implicit begin on the variable arguments ;; implicit begin in the body of let-star ;; in defining let-rewrite we would want to use let also , interesting. ;; has to have atleast 3 parts ;; LET keyword , ARGs , BODY (define (klet-star-rewrite exp) (klet-star-rewrite2 (cadr exp) (cddr exp))) (define (klet-star-rewrite2 args body) (cond ((null? args) (cons (quote begin) body)) (else (list (append (list (quote lambda) (list (caar args))) (list (klet-star-rewrite2 (cdr args) body))) (cons (quote begin) (cdar args)))))) (klet-star-rewrite '(klet* ((a 1) (b 2) (c 3)) (list a b c))) (klet-star-rewrite '(klet* ((a 1 2 3) (b 4 5 6) (c 7 8 9)) (list a b c) (list a b c) (list c b a)))
false
0b43cae048073bd5bb845f6daa5a3285187e4b11
ac2a3544b88444eabf12b68a9bce08941cd62581
/tests/unit-tests/02-flonum/flnegativep.scm
7a13fe3b17b3e19df5315d8c4bf35c0f45375420
[ "Apache-2.0", "LGPL-2.1-only" ]
permissive
tomelam/gambit
2fd664cf6ea68859d4549fdda62d31a25b2d6c6f
d60fdeb136b2ed89b75da5bfa8011aa334b29020
refs/heads/master
2020-11-27T06:39:26.718179
2019-12-15T16:56:31
2019-12-15T16:56:31
229,341,552
1
0
Apache-2.0
2019-12-20T21:52:26
2019-12-20T21:52:26
null
UTF-8
Scheme
false
false
750
scm
flnegativep.scm
(include "#.scm") (check-eqv? (##flnegative? -inf.0) #t) (check-eqv? (##flnegative? +inf.0) #f) (check-eqv? (##flnegative? 0.0) #f) (check-eqv? (##flnegative? -0.0) #f) (check-eqv? (##flnegative? -1.0) #t) (check-eqv? (##flnegative? 1.0) #f) (check-eqv? (flnegative? -inf.0) #t) (check-eqv? (flnegative? +inf.0) #f) (check-eqv? (flnegative? 0.0) #f) (check-eqv? (flnegative? -0.0) #f) (check-eqv? (flnegative? -1.0) #t) (check-eqv? (flnegative? 1.0) #f) (check-tail-exn wrong-number-of-arguments-exception? (lambda () (flnegative?))) (check-tail-exn wrong-number-of-arguments-exception? (lambda () (flnegative? 1.0 2.0))) (check-tail-exn type-exception? (lambda () (flnegative? 1))) (check-tail-exn type-exception? (lambda () (flnegative? 1/2)))
false
0ae15f6f315ec2968e2ce697a4e81809146e884d
f916d100a0510989b96deaa9d2d2f90d86ecc399
/slib/trnscrpt.scm
45d884e9215b0ed806d81d22461f82a7252a370d
[]
no_license
jjliang/UMB-Scheme
12fd3c08c420715812f933e873110e103236ca67
d8479f2f2eb262b94be6040be5bd4e0fca073a4f
refs/heads/master
2021-01-20T11:19:37.800439
2012-09-27T22:13:50
2012-09-27T22:13:50
5,984,440
2
0
null
null
null
null
UTF-8
Scheme
false
false
2,264
scm
trnscrpt.scm
; "trnscrpt.scm", transcript functions for Scheme. ; Copyright (c) 1992, 1993, 1995 Aubrey Jaffer ; ;Permission to copy this software, to redistribute it, and to use it ;for any purpose is granted, subject to the following restrictions and ;understandings. ; ;1. Any copy made of this software must include this copyright notice ;in full. ; ;2. I have made no warrantee or representation that the operation of ;this software will be error-free, and I am under no obligation to ;provide any services, by way of maintenance, update, or otherwise. ; ;3. In conjunction with products arising from the use of this ;material, there shall be no use of my name in any advertising, ;promotional, or sales literature without prior written consent in ;each case. (define transcript:port #f) (define (transcript-on filename) (set! transcript:port (open-output-file filename))) (define (transcript-off) (if (output-port? transcript:port) (close-output-port transcript:port)) (set! transcript:port #f)) (define read-char (let ((read-char read-char) (write-char write-char)) (lambda opt (let ((ans (apply read-char opt))) (cond ((eof-object? ans)) ((output-port? transcript:port) (write-char ans transcript:port))) ans)))) (define read (let ((read read) (write write) (newline newline)) (lambda opt (let ((ans (apply read opt))) (cond ((eof-object? ans)) ((output-port? transcript:port) (write ans transcript:port) (if (eqv? #\newline (apply peek-char opt)) (newline transcript:port)))) ans)))) (define write-char (let ((write-char write-char)) (lambda (obj . opt) (apply write-char obj opt) (if (output-port? transcript:port) (write-char obj transcript:port))))) (define write (let ((write write)) (lambda (obj . opt) (apply write obj opt) (if (output-port? transcript:port) (write obj transcript:port))))) (define display (let ((display display)) (lambda (obj . opt) (apply display obj opt) (if (output-port? transcript:port) (display obj transcript:port))))) (define newline (let ((newline newline)) (lambda opt (apply newline opt) (if (output-port? transcript:port) (newline transcript:port)))))
false
1fb9a9ce9f73851712e2a261cdde9663ad7d3b0a
382770f6aec95f307497cc958d4a5f24439988e6
/projecteuler/022/022.scm
4faa7a357d9aa4098d2e334357aac5f4eac9e797
[ "Unlicense" ]
permissive
include-yy/awesome-scheme
602a16bed2a1c94acbd4ade90729aecb04a8b656
ebdf3786e54c5654166f841ba0248b3bc72a7c80
refs/heads/master
2023-07-12T19:04:48.879227
2021-08-24T04:31:46
2021-08-24T04:31:46
227,835,211
1
0
null
null
null
null
UTF-8
Scheme
false
false
610
scm
022.scm
(define nameport (open-input-file "p022_names.txt")) (define strlst (call-with-port nameport (lambda (po) (let loop ([str (get-datum po)] [lst '()]) (cond ((eof-object? str) lst) (else (get-char po) (loop (get-datum po) (cons str lst)))))))) (define order-ls (list-sort string<? strlst)) (let pro ([index 1] [ls order-ls] [sum 0]) (cond ((null? ls) sum) (else (let ([new-ls (string->list (car ls))]) (pro (+ index 1) (cdr ls) (+ sum (* index (apply + (map (lambda (x) (- (char->integer x) (char->integer #\A) -1)) new-ls)))))))))
false
e7082ab45acfc4ec51fb1376c1f80f3bfd28db82
665da87f9fefd8678b0635e31df3f3ff28a1d48c
/examples/threading/many-writers.scm
a6dd33e013b587451a4f0df63f9792bc657ad1ef
[ "MIT" ]
permissive
justinethier/cyclone
eeb782c20a38f916138ac9a988dc53817eb56e79
cc24c6be6d2b7cc16d5e0ee91f0823d7a90a3273
refs/heads/master
2023-08-30T15:30:09.209833
2023-08-22T02:11:59
2023-08-22T02:11:59
31,150,535
862
64
MIT
2023-03-04T15:15:37
2015-02-22T03:08:21
Scheme
UTF-8
Scheme
false
false
494
scm
many-writers.scm
;; Simple example demonstrating many threads concurrently writing data to stdout (import (scheme base) (scheme read) (scheme write) (srfi 18)) (define (write-forever val) (display val) (write-forever val)) (define (make-writer val) (lambda () (write-forever val))) (thread-start! (make-thread (make-writer "thread 1"))) (thread-start! (make-thread (make-writer 'thread-2))) (thread-start! (make-thread (make-writer 'thread-3))) ((make-writer 'main)) ;(read)
false
6cc2ae92ddfe4ce0047f92cf98c087fed0bfd63f
e1fc47ba76cfc1881a5d096dc3d59ffe10d07be6
/ch2/2.67.scm
bb620d4977024990f67b545b1fa60db7af0741d3
[]
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
291
scm
2.67.scm
(load "2.03.04.scm") (define tree (make-code-tree (make-leaf 'A 4) (make-code-tree (make-leaf 'B 2) (make-code-tree (make-leaf 'D 1) (make-leaf 'C 1) ) ) ) ) (define msg '(0 1 1 0 0 1 0 1 0 1 1 1 0)) (display (decode msg tree))(newline)
false
c71f41e23901736fb5972f84225fb38e9eb8f603
46244bb6af145cb393846505f37bf576a8396aa0
/sicp/2_51.scm
23b8e9505b8ed6601ca664404be465b879884b05
[]
no_license
aoeuidht/homework
c4fabfb5f45dbef0874e9732c7d026a7f00e13dc
49fb2a2f8a78227589da3e5ec82ea7844b36e0e7
refs/heads/master
2022-10-28T06:42:04.343618
2022-10-15T15:52:06
2022-10-15T15:52:06
18,726,877
4
3
null
null
null
null
UTF-8
Scheme
false
false
1,791
scm
2_51.scm
#lang racket ; Exercise 2.51. Define the below operation for painters. Below takes two painters as arguments. ; The resulting painter, given a frame, draws with the first painter in the bottom of the frame ; and with the second painter in the top. Define below in two different ways ; -- first by writing a procedure that is analogous to the beside procedure given above, ; and again in terms of beside and suitable rotation operations (from exercise 2.50). (define (beside painter1 painter2) (let ((split-point (make-vect 0.5 0.0))) (let ((paint-left (transform-painter painter1 (make-vect 0.0 0.0) split-point (make-vect 0.0 1.0))) (paint-right (transform-painter painter2 split-point (make-vect 1.0 0.0) (make-vect 0.5 1.0)))) (lambda (frame) (paint-left frame) (paint-right frame))))) ; so the below is (define (below painter1 painter2) (let ((split-point (make-vert 0.0 0.5))) (let ((paint-bottom (tarnsform-painter painter1 (make-vert 0.0 0.0) (make-vert 0.0 1.0) split-point)) (paint-up (transform-painter pointer2 split-point (make-vert 0.0 1.0) (make-vert 1.0 0.0)))) (lambda (frame) (paint-bottom frame) (paint-up frame))))) ; the beside and rotate solution (define (below p-down p-up) (let ((p-left (rotate90 p-up)) (p-right (rotate90 p-down))) (rotate270 (beside p-left p-right))))
false
056428b3b7e9473e80b251dbcccdb88145730315
29fdc68ecadc6665684dc478fc0b6637c1293ae2
/examples/blog/blog.scm
4be21439457beea865c10a3f071a3c564d2106ed
[ "MIT" ]
permissive
shirok/WiLiKi
5f99f74551b2755cb4b8deb4f41a2a770138e9dc
f0c3169aabd2d8d410a90033d44acae548c65cae
refs/heads/master
2023-05-11T06:20:48.006068
2023-05-05T18:29:48
2023-05-05T18:30:12
9,766,292
20
6
MIT
2018-10-07T19:15:09
2013-04-30T07:40:21
Scheme
UTF-8
Scheme
false
false
34,710
scm
blog.scm
;; -*- coding: utf-8 -*- ;; Simple blog app sample based on WiLiKi #| Setup: - Put this file in gosh's load path. - Prepare a password file by wiliki-passwd command. It is used for authentication. - Create a cgi script something like this. #!/path/to/gosh (use wiliki) (use blog) (define (main args) (wiliki-main (make <blog> ;; Options specific to <blog> :author "YourName" :login-command "something" :auth-db-path "/path/to/passwd-file" ;; Usual WiKiKi options. Don't set :editable?, for it is set by ;; 'initialize' method of <blog>. :db-path "/path/to/blog-file.dbm" :log-file "blog-file.log" :event-log-file "blog-events.log" :top-page "My Blog" :title "My Blog" :description "My Blog" :style-sheet "blog.css" :language 'jp :charsets '((jp . utf-8) (en . utf-8)) :image-urls '((#/^http:\/\/[-\w.]*amazon.com\// allow) (#/^\// allow)) :debug-level 1 ))) - 'Login-command' value is used to access the login screen. To add and edit blog contents, you have to log in first. Use the following url, where substituting LOGIN-COMMAND to the word you give in this option, to get to the login form. http://your-path-to-cgi-script/?c=LOGIN-COMMAND This allows each blog script to have different url for login form, making automated login attack more difficult. - 'Auth-db-path' option points to the file created by wiliki-passwd command, which contains username and hashed password pairs. Caveat: Currently we assume <blog> instance is created for every request. See the 'initialize' method of <blog>. |# ;; An blog entry is just a wiki page with the following name: ;; YYYYMMDD[C]-TITLE ;; 'C' is #\a, #\b, #\c, ... just to make sorting easier when there's ;; more than one entry per day. (define-module blog (use srfi-1) (use srfi-13) (use srfi-19) (use srfi-42) (use rfc.cookie) (use rfc.uri) (use rfc.http) (use www.cgi) (use text.tree) (use text.html-lite) (use util.match) (use util.list) (use file.util) (use wiliki) (use wiliki.auth :prefix auth:) (use wiliki.parse) (use wiliki.page) (use wiliki.edit) (use wiliki.rss) (use wiliki.log) (export <blog> blog-option-ref)) (select-module blog) ;;; ;;; Authentication ;;; ;; Authentication is handled by a special command, whose name is ;; given to the initarg option of <blog> object. This will make it ;; difficult for automated login attempt. (define (register-login-action command) ($ (with-module wiliki.core wiliki-action-add!) (string->symbol command) (^[pagename params] (let ([user (cgi-get-parameter "user" params)] [pass (cgi-get-parameter "pass" params)]) (if (auth:auth-valid-password? user pass) (let1 sess (auth:auth-new-session user) `(,(cgi-header :status 302 :location (cgi-get-metavariable "SCRIPT_NAME") :cookies (construct-cookie-string `(("sess" ,sess :max-age 20000000 :path "/")))))) `(,(cgi-header) ,(html:html (html:head (html:title "Login")) (html:body ($ html:form :action "" :method "POST" (html:input :type "hidden" :name "c" :value command) (html:table (html:tr (html:td "Name") (html:td (html:input :type "text" :name "user"))) (html:tr (html:td "Password") (html:td (html:input :type "text" :name "pass"))) (html:tr (html:td (html:input :type "submit" :name "submit" :value "login"))))))))))))) (define (authenticated?) (and-let* ([v (cgi-get-metavariable "HTTP_COOKIE")] [c (parse-cookie-string v)] [e (assoc "sess" c)]) (guard (e [(auth:<auth-failure> e) #f]) (auth:auth-get-session (cadr e))))) ;;; ;;; New entry ;;; (define (new-entry-button) `((form (@ (method POST) (action ,(wiliki:url)) (style "margin:0pt; padding:0pt")) (input (@ (type hidden) (name p) (value "NewEntry"))) (input (@ (type submit) (class navi-button) (value "New")))))) (define-virtual-page (#/^NewEntry$/ (_)) (let* ([now (date->string (current-date) "~Y~m~d")] [pgs (wiliki:db-search (^(k v) (string-prefix? now k)) (^(a b) (string>? (car a) (car b))))] [suffix (match pgs [() ""] ;first entry of the day [((key . _) . _) (pick-next-suffix key)])]) (if (authenticated?) `((h2 "Create new entry") (form (@ (method POST) (action ,(wiliki:url))) (input (@ (type hidden) (name c) (value n))) (input (@ (type text) (name p) (value ,#"~|now|~|suffix|-") (size 50))) (input (@ (type submit) (name submit) (value "Create"))))) '()))) (define (pick-next-suffix key) (rxmatch-case key [#/^\d{8}([a-z])/ (#f c) (integer->char (+ (char->integer (string-ref c 0)) 1))] [else #\a])) ;;; ;;; Title extraction ;;; (define (entry-title page-key page-content) (define (trim s) (with-string-io s (^() (let loop ([i 0]) (let1 c (read-char) (cond [(eof-object? c)] [(< i 20) (write-char c) (loop (+ i 1))] ;soft limit [(>= i 40) (display "...")] ;hard limit [(char-set-contains? #[[:alpha:]] c) (write-char c) (loop (+ i 1))] [else (display "...")])))))) (cond [(#/^\d{8}/ page-key) (let1 line (with-input-from-string page-content read-line) (rxmatch-if (#/^\* (.*)/ line) (_ item) (tree->string (wiliki-remove-markup item)) (trim (tree->string (wiliki-remove-markup line)))))] [else page-key])) ;;; ;;; Index ;;; ;; index : (tree next-link prev-link) ;; tree : ((year yearly ...) ....) ;; yearly : ((month monthly ...) ...) ;; monthly : ((day #(key title fwd back)) ...) (define (make-index-entry key title) (vector key title #f #f)) (define (index-entry-key e) (vector-ref e 0)) (define index-entry-title (getter-with-setter (^e (vector-ref e 1)) (^(e v) (vector-set! e 1 v)))) (define index-entry-next (getter-with-setter (^e (vector-ref e 2)) (^(e v) (vector-set! e 2 v)))) (define index-entry-prev (getter-with-setter (^e (vector-ref e 3)) (^(e v) (vector-set! e 3 v)))) (define *index-store* " blog-index") (define (decompose-key key) (cond [(#/^(\d\d\d\d)(\d\d)(\d\d)/ key) => (^m (list (x->integer(m 1)) (x->integer(m 2)) (x->integer(m 3))))] [else #f])) (define (build-index) (define root (list #f)) (define (ensure-year year) (or (assv year root) (rlet1 node (list year) (push! (cdr root) node)))) (define (ensure-year-month year month) (let1 ynode (ensure-year year) (or (assv month ynode) (rlet1 node (list month) (push! (cdr ynode) node))))) (define (ensure-year-month-day year month day) (let1 mnode (ensure-year-month year month) (or (assv day mnode) (rlet1 node (list day) (push! (cdr mnode) node))))) (define (ensure-entry year month day key title) (let1 dnode (ensure-year-month-day year month day) (or (find (^e (equal? key (index-entry-key e))) (cdr dnode)) (rlet1 entry (make-index-entry key title) (push! (cdr dnode) entry))))) (define (build-tree) (wiliki:db-for-each (^(key content) (match (decompose-key key) [(y m d) (let1 in (open-input-string content) (read in) ;discard metadata (ensure-entry y m d key (entry-title key (get-remaining-input-string in))))] [_ #f])))) (define (build-links) (let ([first #f] [prev #f]) (let1 last (fold-ec prev (:list ynode (sort-by (cdr root) car)) (:list mnode (sort-by (cdr ynode) car)) (:list dnode (sort-by (cdr mnode) car)) (:list entry (sort-by (cdr dnode) index-entry-key)) entry (^(entry prev) (if prev (set! (index-entry-next prev) entry) (set! first entry)) (set! (index-entry-prev entry) prev) entry)) (list first last)))) (build-tree) (cons (cdr root) (build-links))) (define (save-index) (wiliki:db-raw-put! *index-store* (write-to-string (blog-index) write/ss))) (define (read-index) (read-from-string (wiliki:db-raw-get *index-store* "(() #f #f)"))) (define blog-index (let1 promise (delay (read-index)) (case-lambda [() (force promise)] [(new) (set! promise (delay new))]))) (define blog-index-root (getter-with-setter (^() (car (blog-index))) (^v (set-car! (blog-index) v)))) (define blog-index-first (getter-with-setter (^() (cadr (blog-index))) (^v (set! (cadr (blog-index)) v)))) (define blog-index-last (getter-with-setter (^() (caddr (blog-index))) (^v (set! (caddr (blog-index)) v)))) (define (get-index-entry key :optional (create #f)) (match (and key (decompose-key key)) [(y m d) (and-let* ([ynode (or (assv y (blog-index-root)) (and create (rlet1 z (list y) (set! (blog-index-root) (cons z (blog-index-root))))))] [mnode (or (assv m (cdr ynode)) (and create (rlet1 z (list m) (push! (cdr ynode) z))))] [dnode (or (assv d (cdr mnode)) (and create (rlet1 z (list d) (push! (cdr mnode) z))))]) (or (find (^e (equal? key (index-entry-key e))) (cdr dnode)) (and create (rlet1 e (make-index-entry key "") (push! (cdr dnode) e) (update-blog-index-links! key e)))))] [_ #f])) (define (update-blog-index-links! key e) (let1 last (blog-index-last) ;adjust prev/next links (if (not last) (begin (set! (blog-index-first) e) (set! (blog-index-last) e)) (let loop ([last last]) (cond [(not last) (set! (index-entry-next e) (blog-index-first)) (set! (blog-index-first) e)] [(string>=? key (index-entry-key last)) (if-let1 n (index-entry-next last) (begin (set! (index-entry-prev n) e) (set! (index-entry-next e) n)) (set! (blog-index-last) e)) (set! (index-entry-prev e) last) (set! (index-entry-next last) e)] [else (loop (index-entry-prev last))]))))) (define (rebuild-index-button) `((form (@ (method POST) (action ,(wiliki:url)) (style "margin:0pt; padding:0pt")) (input (@ (type hidden) (name c) (value rebuild-index))) (input (@ (type submit) (class navi-button) (value "Rebuild Index")))))) (define (show-index-button) `((form (@ (method POST) (action ,(wiliki:url)) (style "margin:0pt; padding:0pt")) (input (@ (type hidden) (name c) (value show-index))) (input (@ (type submit) (class navi-button) (value "Show Index")))))) (define (manage-comments-button) `((form (@ (method GET) (action ,(build-path (wiliki:url) "ManageComments:0")) (style "margin:0pt; padding:0pt")) (input (@ (type submit) (class navi-button) (value "Manage Comments")))))) (define-wiliki-action rebuild-index :write (pagename) (when (authenticated?) (blog-index (build-index)) (save-index) (blog-recent-entries-update!) (blog-recent-comments-update!)) (wiliki:redirect-page pagename)) (define-wiliki-action show-index :read (_) (wiliki:std-page (make <blog-page> :title "Index" :content (cond [(authenticated?) (match-let1 (root first last) (read-index) (define (ent entry) `(li (a (@ (href ,#"~(wiliki:url)/~(index-entry-key entry)")) ,(index-entry-key entry)" : ",(index-entry-title entry)))) (define (d-ent dnode) `(li ,(x->string (car dnode)) (ul ,@(map ent (sort-by (cdr dnode) index-entry-key))))) (define (m-ent mnode) `(li ,(x->string (car mnode)) (ul ,@(map d-ent (sort-by (cdr mnode) car))))) (define (y-ent ynode) `(li ,(x->string (car ynode)) (ul ,@(map m-ent (sort-by (cdr ynode) car))))) `((ul ,@(map y-ent (sort-by root car)))))] [else `(p "Only the blog author can do this action.")])))) ;;; ;;; Recent entries/comments ;;; (define *recent-entries* " recent-entries") (define *recent-comments* " recent-comments") (define (blog-recent-entries) (read-from-string (wiliki:db-raw-get *recent-entries* "()"))) (define (blog-recent-entry-add! key title) (let1 es (remove (^(e) (equal? (caar e) key)) (blog-recent-entries)) (wiliki:db-raw-put! *recent-entries* (write-to-string (take* (acons (cons key title) (sys-time) es) 50))))) (define (blog-recent-entries-update!) (let1 es (wiliki:db-fold (lambda (k v es) (rxmatch-case k [#/^\d{8}/ () (let1 p (wiliki:db-record->page (wiliki) k v) (cons (acons k (entry-title k (~ p'content)) (~ p'mtime)) es))] [else es])) '()) (wiliki:db-raw-put! *recent-entries* (write-to-string (take* (sort-by es caar string>?) 50))))) (define-virtual-page (#/^RecentEntries$/ (_)) ;for check `((h2 "Recent Entries") (ul ,@(map (lambda (e) `(li ,(write-to-string e))) (blog-recent-entries))))) (define (blog-recent-comments) (read-from-string (wiliki:db-raw-get *recent-comments* "()"))) (define (blog-recent-comment-add! key page) (if-let1 info (extract-comment-info key page) (wiliki:db-raw-put! *recent-comments* (write-to-string (cons info (blog-recent-comments)))))) (define (blog-recent-comments-update!) (let1 es (wiliki:db-fold (lambda (k v es) (if-let1 info (extract-comment-info k (wiliki:db-record->page (wiliki) k v)) (cons info es) es)) '()) (wiliki:db-raw-put! *recent-comments* (write-to-string (take* (sort-by es cadddr >) 50))))) (define (extract-comment-info key page) (rxmatch-if (#/^\|comments:(.*)::\d{3,}$/ key) (_ main-key) (and-let* ([main (wiliki:db-get main-key)] [title (entry-title main-key (~ main'content))] [poster (extract-comment-poster page)]) (list main-key title poster (~ page'ctime))) #f)) (define (extract-comment-poster page) (rxmatch-case (with-input-from-string (~ page'content) read-line) [#/^\* (.*) \(\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}:\d{2}\):/ (_ who) who] [else #f])) (define-reader-macro (recent-comments) (define n 7) `((ul (@ (class recent-comments)) ,@(map (^e (match-let1 (key title poster time) e `(li ,poster " on " (a (@ (href ,#"~(wiliki:url)/~key")) ,title) " (" ,(sys-strftime "%Y/%m/%d" (sys-localtime time)) ")"))) (take* (blog-recent-comments) n))))) ;;; ;;; Hooking DB ;;; (define-class <blog> (<wiliki>) ((author :init-keyword :author :init-value "Anonymous") ;; Set a command name to show log in page (avoid conflicting existing ;; wiliki commands) (login-command :init-keyword :login-command :init-value #f) ;; Set path for wiliki password db (auth-db-path :init-keyword :auth-db-path :init-value #f) ;; Miscellaneous customization parameters (alist) ;; Would be used by macros, e.g. amazon-affiliate-id (blog-options :init-keyword :options :init-value '()) )) (define-class <blog-page> (<wiliki-page>) ()) (define-method initialize ((self <blog>) initargs) (next-method) ;; Authentication setup ;; NB: Currently we assume <blog> instance is created every time ;; script is called (like in cgi script), so that we can check session ;; cookie here to set the editable? slot. This assumption breaks if ;; blog script is loaded once and serves multiple requests. It should be ;; fixed in WiLiKi side to allow editable? slot value is recalculated ;; for each request. (auth:auth-db-path (~ self'auth-db-path)) (if-let1 login-command (~ self'login-command) (register-login-action (~ self'login-command))) (set! (~ self'editable?) (if (authenticated?) #t 'limited)) ;; Some other setup (rss-item-description 'html) (rss-url-format 'path) (rss-source (cut take* (blog-recent-entries) <>)) (wiliki:formatter (make <blog-formatter>))) (define-method wiliki:page-class ((self <blog>)) <blog-page>) (define-method wiliki:db-put! (key (page <blog-page>) . opts) (begin0 (next-method) (match (decompose-key key) [(y m d) (let* ([e (get-index-entry key #t)] [title (entry-title key (~ page'content))]) (set! (index-entry-title e) title) (save-index) (blog-recent-entry-add! key title))] [_ (blog-recent-comment-add! key page)]))) (define-method blog-option-ref ((self <blog>) key :optional (fallback #f)) (assq-ref (~ self'blog-options) key fallback)) ;;; ;;; Parts ;;; ;; Maybe Entry, Int, (Entry -> Entry) -> Maybe Entry (define (drop-entries entry count advance) (cond [(not entry) #f] [(zero? count) entry] [else (drop-entries (advance entry) (- count 1) advance)])) ;; Maybe Entry, Int, (Entry -> Entry) -> [Entry] (define (take-entries entry count advance) (let loop ([entry entry] [count count] [r '()]) (if (or (not entry) (zero? count)) (reverse r) (loop (advance entry) (- count 1) (cons entry r))))) ;; Maybe Entry, (Entry -> Bool), (Entry -> Entry) -> [Entry] (define (span-entries entry pred advance) (define (scan-out entry) (cond [(not entry) '()] [(pred entry) (scan-in (advance entry) (list entry))] [else (scan-out (advance entry))])) (define (scan-in entry r) (cond [(not entry) (reverse r)] [(pred entry) (scan-in (advance entry) (cons entry r))] [else (reverse r)])) (scan-out entry)) (define (entry-header entry :key (show-navi #t)) (define (entry-anchor e) `(a (@ (href ,#"~(wiliki:url)/~(index-entry-key e)")) ,(if (string-null? (index-entry-title e)) (index-entry-key e) (index-entry-title e)))) (define (entry-navi) (cond-list [show-navi `(div (@ (class entry-navi)) ,@(cond-list [(index-entry-prev entry)=> @(^p `("< " ,(entry-anchor p)))] [#t " | "] [(index-entry-next entry)=> @(^n `(,(entry-anchor n) " >"))]))])) (let1 key (index-entry-key entry) (rxmatch-let (#/^(\d\d\d\d)(\d\d)(\d\d)/ key) (_ y m d) `(,@(entry-navi) (h1 (@ (class entry-date)) ,#"~|y|/~|m|/~|d|") (div (@ (class permalink)) (a (@(href ,#"~(wiliki:url)/~key")) "#permalink")))))) (define (show-n-entries entries) (define dummy-page (make <blog-page>)) ;to make comment macro use compact form (map (^e `(div (@ (class n-entry-show)) ,@(entry-header e :show-navi #f) ,@(let1 p (wiliki:db-get (index-entry-key e) #f) (parameterize ([wiliki:page-stack (cons dummy-page (wiliki:page-stack))]) (wiliki:format-content p))))) entries)) (define (show-more-entry-link start) `(p (a (@ (href ,#"~(wiliki:url)/Browse/~start")) "More entries ..."))) (define (show-archive-links entries) `((ul ,@(map (^e `(li (a (@ (href ,#"~(wiliki:url)/~(index-entry-key e)")) ,(let1 ymd (decompose-key (index-entry-key e)) (apply format "~4d/~2,'0d/~2,'0d" ymd)) " : " ,(index-entry-title e)))) entries)))) (define (show-yearly-links hilite-year) `((p (@ (class "archive-year-links")) ,@(map (^y `(span (@ (class ,(if (eqv? y hilite-year) "archive-year-link-hi" "archive-year-link-lo"))) (a (@ (href ,#"~(wiliki:url)/Archive/~y")) ,(x->string y)))) (sort (map car (blog-index-root)) >))))) (define-reader-macro (recent-entries) (define n 10) `((ul (@ (class recent-entries)) ,@(map (^e `(li (a (@ (href ,#"~(wiliki:url)/~(index-entry-key e)")) ,(index-entry-title e)))) (take-entries (blog-index-last) n index-entry-prev))) (p (a (@ (href ,#"~(wiliki:url)/Archive/l0")) "More...")))) (define *entries-in-page* 5) (define *archive-links-in-page* 50) (define-reader-macro (top-page-contents) (let1 es (take-entries (blog-index-last) *entries-in-page* index-entry-prev) `(,@(show-n-entries es) ,@(cond-list [(= (length es) *entries-in-page*) (show-more-entry-link *entries-in-page*)])))) (define-virtual-page (#/^Browse\/(\d+)/ (_ start)) (define s (x->integer start)) (define n *entries-in-page*) (let1 es (take-entries (drop-entries (blog-index-last) s index-entry-prev) n index-entry-prev) `(,@(show-n-entries es) ,@(cond-list [(= (length es) n) (show-more-entry-link (+ s n))])))) (define-virtual-page (#/^Archive\/l(\d+)/ (_ start)) (define s (x->integer start)) (define n *archive-links-in-page*) (let1 es (take-entries (drop-entries (blog-index-last) s index-entry-prev) n index-entry-prev) `(,@(show-yearly-links #f) ,@(show-archive-links es) ,@(cond-list [(= (length es) n) `(a (@ (href ,#"~(wiliki:url)/Archive/l~(+ s n)")) "More...")])))) (define-virtual-page (#/^Archive\/(\d{4})/ (_ year)) (define rx (string->regexp #"^~year")) (let1 es (span-entries (blog-index-last) (^e (rx (index-entry-key e))) index-entry-prev) `(,@(show-yearly-links (x->integer year)) ,@(show-archive-links es)))) ;;; ;;; Miscellaneous (not specific for blog features) ;;; (define-reader-macro (chaton-badge room-uri) `((script (@ (type "text/javascript") (src ,#"~|room-uri|/b") (charset "utf-8"))))) (define-reader-macro (amazon-affiliate asin . opts) (define aid (blog-option-ref (wiliki) 'amazon-affiliate-id)) (define aid-us (blog-option-ref (wiliki) 'amazon-affiliate-id-us)) (let-macro-keywords* opts ([domain "jp"][float "left"]) (if (equal? domain "us") #"<div class=\"amazon\" style=\"float:~|float|;\"><iframe src=\"http://rcm.amazon.com/e/cm?\ t=~|aid-us|&o=1&p=8&l=as1&asins=~|asin|&\ fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&\ bc1=000000&bg1=FFFFFF&f=ifr\" style=\"width:120px;height:240px;\" \ scrolling=\"no\" marginwidth=\"0\" marginheight=\"0\" \ frameborder=\"0\"></iframe></div>" #"<div class=\"amazon\" style=\"float:~|float|;\"><iframe src=\"http://rcm-jp.amazon.co.jp/e/cm?\ lt1=_blank&bc1=000000&IS2=1&nou=1&bg1=FFFFFF&\ fc1=000000&lc1=0000FF&t=~|aid|&\ o=9&p=8&l=as1&m=amazon&f=ifr&asins=~|asin|\" \ style=\"width:120px;height:240px;\" \ scrolling=\"no\" marginwidth=\"0\" marginheight=\"0\" \ frameborder=\"0\"></iframe></div>"))) (define-reader-macro (amazon-affiliate-link asin text) (define aid (blog-option-ref (wiliki) 'amazon-affiliate-id)) #"<a href=\"http://www.amazon.co.jp/gp/product/~|asin|?\ ie=UTF8&tag=~|aid|&linkCode=as2&camp=247&\ creative=1211&creativeASIN=,|asin|\">~|text|</a>\ <img src=\"http://www.assoc-amazon.jp/e/ir?t=~|aid|&\ l=as2&o=9&a=~|asin|\" width=\"1\" height=\"1\" border=\"0\" \ alt=\"\" style=\"border:none !important; margin:0px !important;\" />") (define-reader-macro (gist id) (if (#/^[\da-fA-F]+$/ id) #"<div style='font-size:75%'><a style=\"background-color: #ececec;\" href=\"https://gist.github.com/~|id|\">https://gist.github.com/~|id|</a><script src=\"https://gist.github.com/~|id|.js\"> </script><noscript><a href=\"https://gist.github.com/~|id|\">https://gist.github.com/~|id|</a></noscript></div>" "")) (define-reader-macro (google-map title . params) (let-macro-keywords* params ([width 640] [height 480] [frameborder 0] [scrolling "no"] [marginheight 0] [marginwidth 0] [msa 0] [msid #f] [hl "en"] [ie "UFT-8"] [t "h"] [ll #f] [spn #f] [z #f]) (unless (and ll spn z) (error "You need ll, spn and z parameters")) (let* ([q `((msa ,msa) ,@(if msid `((msid ,msid)) '()) (hl ,hl) (ie ,ie) (t ,t) (ll ,ll) (spn ,spn) (z ,z))] [prefix "http://maps.google.com/maps/ms"] [path1 (http-compose-query prefix `(,@q (output "embed")))] [path2 (http-compose-query prefix `(,@q (source "embed")))]) `((iframe (@ (width ,width) (height ,height) (frameborder ,frameborder) (scrolling ,scrolling) (marginheight ,marginheight) (marginwidth ,marginwidth) (src ,path1))) (br) (small "View " (a (@ (href ,path2) (style "color:#0000FF;text-align:left")) ,title) " in a larger map"))))) ;;; ;;; Page layout ;;; (define-class <blog-formatter> (<wiliki-formatter>) ()) (define-method wiliki:format-head-title ((fmt <blog-formatter>) page . opts) (cond [(get-index-entry (~ page'key)) => (^e #"~(~ (wiliki)'title) - ~(index-entry-title e)")] [else (~ page'title)])) (define-method wiliki:format-page-header ((fmt <blog-formatter>) page . opts) (define (td x) (list 'td x)) (cond-list [(authenticated?) `(div (@ (style "font-size:80%;")) (table (tr (td ,@(new-entry-button)) ,@(cond-list [(wiliki:edit-link page) => td] [(wiliki:history-link page) => td] [(wiliki:all-link page) => td] ) (td ,@(rebuild-index-button)) (td ,@(show-index-button)) (td ,@(manage-comments-button)) (td ,@(wiliki:search-box)))))] [#t `(h1 (@ (class "blog-title")) (a (@ (href ,(wiliki:url))) ,(~ (wiliki)'title)))] )) (define-method wiliki:format-page-footer ((fmt <blog-formatter>) page . opts) `((hr) (div (@ (class "footer")) (a (@ (rel "license") (href "http://creativecommons.org/licenses/by/3.0/")) (img (@ (alt "Creative Commons License") (style "border-width:0") (src "http://i.creativecommons.org/l/by/3.0/88x31.png")))) (br) "This work by " (a (@ (xmlns:cc "http://creativecommons.org/ns#") (href ,(wiliki:url :full)) (property "cc:attributionName") (rel "cc:attributionURL")) ,(~ (wiliki)'author)) " is licensed under a " (a (@ (rel "license") (href "http://creativecommons.org/licenses/by/3.0/")) "Creative Commons Attribution 3.0 Unported License") (br) "Last modified : " ,(wiliki:format-time (ref page 'mtime)) (br) (a (@ (href "http://practical-scheme.net/wiliki/wiliki.cgi")) "WiLiKi " ,(wiliki:version)) " running on " (a (@ (href "http://practical-scheme.net/gauche/")) "Gauche ",(gauche-version))))) (define-method wiliki:format-page-content ((fmt <blog-formatter>) page . opts) (let1 index-entry (get-index-entry (~ page'key)) `((table (@ (border 0) (cellspacing 8) (width "100%") (class "content-table")) (tr (td (@ (class "menu-strip") (valign "top")) ,@(wiliki:get-formatted-page-content "_SidePane") ) (td (@ (class "main-pane") (valign "top")) (div (@ (class "content")) ,@(cond-list [index-entry @ (entry-header index-entry)]) ,@(wiliki:format-content page)) )))))) ;;; ;;; Comment management ;;; (define-virtual-page (#/^ManageComments:(\d+)$/ (_ s)) ;; Search log files and pick a new comment entries. ;; Returns ((page . ip) ...). The second value is a flag to indicate ;; there's more entries. (define (pick-comments start count) (let loop ([entries ($ filter-map (^[ls] (and (string-prefix? "A" (cadr ls)) (read-from-string #"(~(car ls))"))) $ wiliki-log-pick-from-file #/^\|comments:/ $ wiliki:log-file-path $ wiliki)] [r '()] [s 0] [c 0]) (if (> c count) (values (reverse r) #t) (match entries [() (values (reverse r) #f)] [((_ pagename _ ip . _) . rest) (if-let1 page (wiliki:db-get pagename) (if (>= s start) (loop rest (acons page ip r) (+ s 1) (+ c 1)) (loop rest r (+ s 1) c)) (loop rest r s c))])))) ;; Take (page . ip) and renders one entry of the comment. (define (comment-entry page&ip) (rxmatch-let (#/^\|comments:(.*)::\d+$/ (~(car page&ip)'key)) (_ parent-key) `(div (@ (class "manage-comment-entry")) (div (@ (class "comment-past")) (p (@ (class "comment-entry-title")) (input (@ (type checkbox) (name ,(~(car page&ip)'key)) (id ,(~(car page&ip)'key)))) (label (@ (for ,(~(car page&ip)'key))) "Comment for " ,(parent-page-link parent-key) " from " ,(ip-ban-link (cdr page&ip)))) ,@(parameterize ([wiliki:reader-macros '()]) (wiliki:format-content (car page&ip))))))) (define (ip-ban-link ipaddr) `(a (@ (href ,(wiliki:url "c=manage-comment-del&from-ip=~a" ipaddr))) ,ipaddr)) (define (parent-page-link parent-key) (let1 parent-page (wiliki:db-get parent-key) (if parent-page `(a (@ (href ,(wiliki:url "~a" (~ parent-page'key)))) ,(entry-title (~ parent-page'key) (~ parent-page'content))) (format "~s (deleted)" parent-key)))) ;; body (let1 start (x->integer s) (if (authenticated?) (receive (page&ips more?) (pick-comments start 30) `((h2 "Manage comments") (form (@ (method "POST")) (input (@ (type hidden) (name c) (value "manage-comment-del"))) (input (@ (type submit) (name s) (value "Delete marked comments"))) ,@(map comment-entry page&ips) ,@(if more? `((p (a (@ (href ,(wiliki:url "ManageComments:~d" (+ start 30)))) "More..."))) '())))) '()))) (define-wiliki-action manage-comment-del :write (pagename params (from-ip :default #f) (confirm :default #f)) (define (comment-entry key) `(div (@ (class manage-comment-entry)) (div (@ (class comment-past)) ,@(wiliki:get-formatted-page-content key)))) (define (keys-to-delete) (if from-ip (keys-of-comments-from-ip from-ip) (filter #/^\|comments:/ (map car params)))) (define (keys-of-comments-from-ip from-ip) ($ (cut take* <> 30) $ filter-map (match-lambda [(_ pagename _ ip . _) (and (equal? ip from-ip) (wiliki:db-exists? pagename) pagename)]) $ filter-map (^[ls] (and (string-prefix? "A" (cadr ls)) (read-from-string #"(~(car ls))"))) $ wiliki-log-pick-from-file #/^\|comments:/ $ wiliki:log-file-path $ wiliki)) (let1 page-keys (keys-to-delete) (if confirm (begin (dolist [page page-keys] (cmd-commit-edit page "" #f "Batch deletion by the Comment Manager" #t #t)) (wiliki:redirect-page "ManageComments:0")) (wiliki:std-page (make <blog-page> :title "Manage Comments - Confirm" :content `((h2 "Delete these comments?") ,@(parameterize ([wiliki:reader-macros '()]) (map comment-entry page-keys)) (form (@ (method POST)) (input (@ (type hidden) (name c) (value "manage-comment-del"))) (input (@ (type hidden) (name confirm) (value "ok"))) (input (@ (type submit) (name s) (value "Yes, delete them."))) ,@(map (^k `(input (@ (type hidden) (name ,k) (value "yes")))) page-keys)) )))))) ;; Local variables: ;; mode: scheme ;; end:
false
2d7fa747b236abfef8a89da8238ccfba004817c6
3508dcd12d0d69fec4d30c50334f8deb24f376eb
/v8/src/compiler/rtlopt/rcsesr.scm
d7fba067ca0fdd65f28cb259e6a538b1efc14b47
[]
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
3,483
scm
rcsesr.scm
#| -*-Scheme-*- Copyright (c) 1987-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. |# ;;;; RTL Common Subexpression Elimination: Stack References (declare (usual-integrations)) (define *stack-offset*) (define *stack-reference-quantities*) (define-integrable (memory->stack-offset offset) ;; Assume this operation is a self-inverse. (stack->memory-offset offset)) (define (stack-push? expression) (and (rtl:pre-increment? expression) (interpreter-stack-pointer? (rtl:address-register expression)) (= -1 (memory->stack-offset (rtl:address-number expression))))) (define (stack-pop? expression) (and (rtl:post-increment? expression) (interpreter-stack-pointer? (rtl:address-register expression)) (= 1 (memory->stack-offset (rtl:address-number expression))))) (define (stack-reference? expression) (and (rtl:offset? expression) (interpreter-stack-pointer? (rtl:address-register expression)))) (define (stack-reference-quantity expression) (let ((n (+ *stack-offset* (rtl:machine-constant-value (rtl:offset-offset expression))))) (let ((entry (ass= n *stack-reference-quantities*))) (if entry (cdr entry) (let ((quantity (new-quantity false))) (set! *stack-reference-quantities* (cons (cons n quantity) *stack-reference-quantities*)) quantity))))) (define (set-stack-reference-quantity! expression quantity) (let ((n (+ *stack-offset* (rtl:machine-constant-value (rtl:offset-offset expression))))) (let ((entry (ass= n *stack-reference-quantities*))) (if entry (set-cdr! entry quantity) (set! *stack-reference-quantities* (cons (cons n quantity) *stack-reference-quantities*))))) unspecific) (define (stack-pointer-adjust! offset) (let ((offset (memory->stack-offset offset))) (if (positive? offset) ;i.e. if a pop (stack-region-invalidate! 0 offset))) (set! *stack-offset* (+ *stack-offset* offset)) (stack-pointer-invalidate!)) (define-integrable (stack-pointer-invalidate!) (register-expression-invalidate! (interpreter-stack-pointer))) (define-integrable (stack-invalidate!) (set! *stack-reference-quantities* '())) (define (stack-region-invalidate! start end) (let loop ((i start) (quantities *stack-reference-quantities*)) (if (< i end) (loop (1+ i) (del-ass=! (+ *stack-offset* (stack->memory-offset i)) quantities)) (set! *stack-reference-quantities* quantities)))) (define (stack-reference-invalidate! expression) (expression-invalidate! expression) (set! *stack-reference-quantities* (del-ass=! (+ *stack-offset* (rtl:machine-constant-value (rtl:offset-offset expression))) *stack-reference-quantities*))) (define ass= (association-procedure = car)) (define del-ass=! (delete-association-procedure list-deletor! = car))
false
8b9c6e6bbdbd1411323bd04bb3664f271b99b862
6b1b5aec0c6f9f61afcd743a2c4eaf9616170f10
/cs154/lab4/110040083-assignment4.ss
1e9c0bf81eab40c7dbbe46864945082583f4695d
[]
no_license
mridulravi/personal-projects
56296fd2bdd761c9943334e6bb4b2b3f92940337
dcbde64baf0020dcfa8faf7e08ba7377ff884acd
refs/heads/master
2020-04-02T05:13:04.755512
2016-07-31T14:57:05
2016-07-31T14:57:05
64,591,612
0
0
null
null
null
null
UTF-8
Scheme
false
false
8,173
ss
110040083-assignment4.ss
#lang racket (require racket/mpair) (require compatibility/mlist) ;(require racket/vector) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;Problem : 2 (define timer% (class object% (init-field (list-of-actions '())) (init-field (list-of-credit-card-actions '())) (super-new) (define/public (add-to-list action) (set! list-of-actions (cons action list-of-actions))) (define/public (add-to-credit-card-list action) (set! list-of-credit-card-actions (cons action list-of-credit-card-actions))) (define/public (process-accounts-tick) (call-each list-of-actions)) (define/public (process-credit-card-tick) (call-each list-of-credit-card-actions)) (define (call-each procedures) (cond ((not (null? procedures)) (begin ((car procedures)) (call-each (cdr procedures)))))))) (define this-timer (new timer%)) (define account% (class object% (init-field passwd) (init-field balance) (init-field interest-rate) (super-new) (define/public (show password) (if (eq? password passwd) balance "Incorrect Passwd")) (define/public (withdraw amount password) (if (eq? password passwd) (if (<= amount balance) (set! balance (- balance amount)) "Insufficient funds") "Incorrect Passwd")) (define/public (deposit amount) (set! balance (+ balance amount))) (define (pay-interest) (set! balance (+ balance (* balance interest-rate)))) (send this-timer add-to-list pay-interest))) (define credit-card% (class object% (init-field acct) (init-field passwd) (define temp 0) (super-new) (define/public (make-purchase amount) (set! temp amount)) (define/public (clear-outstanding-amount) (begin (send acct withdraw temp passwd) (set! temp 0) )) (define (pay-fine) (if (= temp 0) (set! temp 0) (set! temp (+ temp (* temp 0.2))))) (send this-timer add-to-credit-card-list pay-fine))) (define joint-account% (class object% (init-field account) (init-field passwd) (init-field new-passwd) (super-new) (define/public (show password) (if (eq? password new-passwd) (send account show passwd) "Incorrect Passwd")) (define/public (withdraw amount password) (if (eq? password new-passwd) (send account withdraw amount passwd) "Incorrect Passwd")) (define/public (deposit amount) (send account deposit amount)))) (define my-account (new account% (passwd "amitabha") (balance 1000) (interest-rate 0.05))) (define my-card (new credit-card% (acct my-account) (passwd "amitabha"))) (define another-account (new account% (passwd "abcd") (balance 5000) (interest-rate 0.1))) (define another-card (new credit-card% (acct another-account) (passwd "abcd"))) (define jnt-account (new joint-account% (account my-account) (passwd "amitabha") (new-passwd "xyz"))) (define jnt-card (new credit-card% (acct jnt-account) (passwd "xyz"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;Problem : 1 (define (foldr f id l) (if (null? l) id (f (car l) (foldr f id (cdr l))))) (define (concat l) (foldr append `() l)) (define-syntax lc (syntax-rules (: <- @) [(lc exp : var <- lexp) (map (lambda (var) exp) lexp)] [(lc exp : @ guard) (if guard (list exp) `())] [(lc exp : @ guard qualifier ...) (concat (lc (lc exp : qualifier ...) : guard))] [(lc exp : var <- lexp qualifier ...) (concat (lc (lc exp : qualifier ... ) : var <- lexp))])) (define storable% (class object% (super-new) (define/public (read) (error "Should be overridden")) (define/public (write) (error "Should be overridden")) (define/public (print) (error "Should be overridden")))) (define register-bank% (class storable% (init-field reg-names-list) (define m-list-reg (list->mlist (lc (mcons x 0) : x <- reg-names-list))) (super-new) (define/override (read reg) (read-h reg m-list-reg)) (define (read-h r l) (if (eq? (mcar (mcar l)) r) (mcdr (mcar l)) (read-h r (mcdr l)))) (define/override (write reg-val) (write-h reg-val m-list-reg)) (define (write-h r-v l) (if (eq? (mcar (mcar l)) (mcar r-v)) (set-mcdr! (mcar l) (mcdr r-v)) (write-h r-v (mcdr l)))) (define/override (print) (display "Registers:") (newline) (newline) (display m-list-reg) (newline) (newline)))) (define memory% (class storable% (init-field size) (define mem (make-vector size 0)) (super-new) (define/override (print) (display "Memory:") (newline) (newline) (display mem) (newline) (newline)) (define/override (write pos val) (vector-set! mem pos val)) (define/override (read pos) (vector-ref mem pos)))) (define processor% (class object% (init-field mem-size) (init-field reg-names) (init-field inst-set) (define registerb (make-object register-bank% reg-names)) (define memory (make-object memory% mem-size)) (super-new) (define/public (execute prog) (cond [(null? prog) "Done"] [(eq? (caar prog) 'load) (begin (send registerb write (mcons (cadar prog) (caddar prog))) (send memory print) (send registerb print) (execute (cdr prog)))] [(eq? (caar prog) 'store) (begin (send memory write (cadar prog) (send registerb read (caddar prog))) (send memory print) (send registerb print) (execute (cdr prog)))] [else (begin (send registerb write (mcons (cadar prog) (if (= 2 (length (cdar prog))) (car (lc ((cadr x) (send registerb read (cadar prog)) (send registerb read (caddar prog))) : x <- inst-set @ (eq? (car x) (caar prog)))) (car (lc ((cadr x) (send registerb read (cadar prog))) ;(send registerb read (caddar prog))) : x <- inst-set @ (eq? (car x) (caar prog))))))) (send memory print) (send registerb print) (execute (cdr prog)))])))) (define as2013 (new processor% [mem-size 32] [reg-names (list 'r1 'r2 'r3 'r4)] [inst-set (list (list 'add (lambda (val1 val2) (+ val1 val2))) (list 'mul (lambda (val1 val2) (* val1 val2))) (list 'incr (lambda (val) (+ val 1))))])) (define sample-prog (list (list 'load 'r2 15) ;Put in register r2 the number 15 (list 'load 'r1 5) (list 'store 1 'r1) (list 'add 'r1 'r2) ;Add r1 and r2, the result goes to r1 (list 'load 'r3 2) ;Put in register r3 the number 2 (list 'incr 'r3) ;Increment contents of r4 by 1 (list 'mul 'r3 'r2) ;Multiply r3 and r2, the result goes to r3 (list 'add 'r1 'r3) ;Add r1 and r3, the result goes to r1 (list 'store 1 'r1))) ;(send as2013 execute sample-prog)
true
fe9daaea4c14bdaa606f07fda7818edf4606cfb7
00466b7744f0fa2fb42e76658d04387f3aa839d8
/sicp/chapter3/3.3/digital-circuits.scm
f3b9a0fd0a987b990fda2da9a572cc9d982faca5
[ "WTFPL" ]
permissive
najeex/stolzen
961da2b408bcead7850c922f675888b480f2df9d
bb13d0a7deea53b65253bb4b61aaf2abe4467f0d
refs/heads/master
2020-09-11T11:00:28.072686
2015-10-22T21:35:29
2015-10-22T21:35:29
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
4,971
scm
digital-circuits.scm
#lang scheme (require "agenda.scm") ; ; wire ; (define (call-each procedures) (if (null? procedures) (void) (begin ((mcar procedures)) (call-each (mcdr procedures))) ) ) (define (make-wire) (let ((signal-value 0) (action-procedures null)) (define (set-my-signal! new-value) (if (not (= signal-value new-value)) (begin (set! signal-value new-value) (call-each action-procedures)) (void) ) ) (define (accept-action-procedure! proc) (set! action-procedures (mcons proc action-procedures)) (proc) ) (define (dispatch m) (cond ((eq? m 'get-signal) signal-value) ((eq? m 'set-signal!) set-my-signal!) ((eq? m 'add-action!) accept-action-procedure!) (else (error "Unknown operation -- WIRE" m))) ) dispatch ) ) (define (get-signal wire) (wire 'get-signal) ) (define (set-signal! wire new-value) ((wire 'set-signal!) new-value) ) (define (add-action! wire proc) ((wire 'add-action!) proc) ) ; ; agenda ; (define the-agenda (make-agenda)) (define (after-delay delay action) (add-to-agenda! (+ delay (current-time the-agenda)) action the-agenda) ) (define (propagate) (if (empty-agenda? the-agenda) (void) (let ((first-item (first-agenda-item the-agenda))) (first-item) (remove-first-agenda-item! the-agenda) (propagate) ) ) ) (define (probe name wire) (add-action! wire (lambda () (display name) (display " ") (display (current-time the-agenda)) (display " New-value = ") (display (get-signal wire)) (newline) ) ) ) ; ; gates ; (define inverter-delay 2) (define and-gate-delay 3) (define or-gate-delay 5) (define (or-gate in1 in2 output) (define (or-action-procedure) (let ((new-value (logical-or (get-signal in1) (get-signal in2)))) (after-delay or-gate-delay (lambda () (set-signal! output new-value))) ) ) (add-action! in1 or-action-procedure) (add-action! in2 or-action-procedure) (void) ) (define (logical-or s1 s2) (cond ((and (= s1 1) (= s2 1)) 1) ((and (= s1 0) (= s2 1)) 1) ((and (= s1 1) (= s2 0)) 1) ((and (= s1 0) (= s2 0)) 0) (else (error "Invalid signals" (list s1 s2))) ) ) (define (and-gate in1 in2 output) (define (and-action-procedure) (let ((new-value (logical-and (get-signal in1) (get-signal in2)))) (after-delay and-gate-delay (lambda () (set-signal! output new-value))) ) ) (add-action! in1 and-action-procedure) (add-action! in2 and-action-procedure) (void) ) (define (logical-and s1 s2) (cond ((and (= s1 1) (= s2 1)) 1) ((and (= s1 0) (= s2 1)) 0) ((and (= s1 1) (= s2 0)) 0) ((and (= s1 0) (= s2 0)) 0) (else (error "Invalid signals" (list s1 s2))) ) ) (define (inverter in1 out1) (define (invert-input) (let ((new-value (logical-not (get-signal in1)))) (after-delay inverter-delay (lambda () (set-signal! out1 new-value))) ) ) (add-action! in1 invert-input) (void) ) (define (logical-not s) (cond ((= s 0) 1) ((= s 1) 0) (else (error "Invalid signal" s)) ) ) ; ; adder ; (define (half-adder in1 in2 out1 out2) (let ((im1 (make-wire)) (im2 (make-wire))) (or-gate in1 in2 im1) (and-gate in1 in2 out2) (inverter out2 im2) (and-gate im1 im2 out1) (void) ) ) (define (full-adder in1 in2 c-in sum c-out) (let ((s (make-wire)) (c1 (make-wire)) (c2 (make-wire))) (half-adder in2 c-in s c1) (half-adder in1 s sum c2) (or-gate c1 c2 c-out) (void) ) ) (define input-1 (make-wire)) (define input-2 (make-wire)) (define sum (make-wire)) (define carry (make-wire)) (probe 'sum sum) (probe 'carry carry) (half-adder input-1 input-2 sum carry) (set-signal! input-1 1) (propagate) (set-signal! input-2 1) (propagate) ; ex 3.31 ; The agenda table will be empty and no actions will be taken.
false
6717a56512a1b2deb24277e60f608993a4c60f93
c3523080a63c7e131d8b6e0994f82a3b9ed901ce
/hertfordstreet/functionalstuff/youcouldhaveinventedmonads-debuggablefunctions.scm
d770e8a89f0fdfb95688b260f6558300da06d71e
[]
no_license
johnlawrenceaspden/hobby-code
2c77ffdc796e9fe863ae66e84d1e14851bf33d37
d411d21aa19fa889add9f32454915d9b68a61c03
refs/heads/master
2023-08-25T08:41:18.130545
2023-08-06T12:27:29
2023-08-06T12:27:29
377,510
6
4
null
2023-02-22T00:57:49
2009-11-18T19:57:01
Clojure
UTF-8
Scheme
false
false
1,965
scm
youcouldhaveinventedmonads-debuggablefunctions.scm
#lang scheme ;first example debuggable functions (define (square x) (list "squaring; " (* x x))) (define (cube x) (list "cubing; " (* x x x))) ;difficult to compose these functions (let* ((x (square 5)) (s (car x)) (y (cadr x))) (let* ((q (cube y)) (t (string-append (car q) s)) (z (cadr q))) (list t z))) ;here's one way (define (combine square cube x) (let* ((a (cube x)) (text1 (car a)) (result1 (cadr a))) (let* ((b (square result1)) (text2 (car b)) (result2 (cadr b))) (list (string-append text1 text2) result2)))) ;now we can write (combine square cube 2) ;but I can't see how to do (cube (square (cube 3))) ;bind function takes a debuggable and turns it into (debuggable output)-> (debuggable output) (define (bind f) (lambda (l) (let* ((string (car l)) (value (cadr l))) (let* ((fval (f value)) (string2 (car fval)) (result2 (cadr fval))) (list (string-append string string2) result2))))) ;and this allows relatively trouble free composition ((bind cube) (square 4)) ((bind square) ((bind cube) (square 4))) ((bind cube) ((bind cube) ((bind cube) (square 3)))) ;what does the identity debuggable function look like? (define (unit x) (list "" x)) (square 5) ((bind unit) (square 5)) ((bind square) (unit 5)) ;we can lift any function into a debuggable one (define (lift f) (lambda (x) (list "" (f x)))) ((lift sin) 2) ((bind square) ((lift sin) 1)) (sin (cos 2)) ;lifting a composition ((lift (lambda (x) (sin (cos x)))) 2) ;is the same as bind-composing two lifts ((bind (lift sin)) ((lift cos) 2)) ;sin of cos of square of cube of sin of x can now be expressed: ((bind (lift sin)) ((bind (lift cos)) ((bind square) ((bind cube) ((lift sin) 2))))) ;which should be a debugging version of (sin (cos ((lambda (x) (* x x)) ((lambda (x) (* x x x)) (sin 2)))))
false
bc4659d5ddd9e877600e05071c15f4375353a319
6f86602ac19983fcdfcb2710de6e95b60bfb0e02
/exercises/practice/forth/test.scm
878960247bed872dd978018fb8177e3bc3a03cfb
[ "MIT", "CC-BY-SA-3.0" ]
permissive
exercism/scheme
a28bf9451b8c070d309be9be76f832110f2969a7
d22a0f187cd3719d071240b1d5a5471e739fed81
refs/heads/main
2023-07-20T13:35:56.639056
2023-07-18T08:38:59
2023-07-18T08:38:59
30,056,632
34
37
MIT
2023-09-04T21:08:27
2015-01-30T04:46:03
Scheme
UTF-8
Scheme
false
false
4,831
scm
test.scm
(load "test-util.ss") (define test-cases `((test-success "numbers just get pushed onto the stack" equal? forth '(("1 2 3 4 5")) '(5 4 3 2 1)) (test-success "can add two numbers" equal? forth '(("1 2 +")) '(3)) (test-error "errors if there is nothing on the stack" forth '(("+"))) (test-error "errors if there is only one value on the stack" forth '(("1 +"))) (test-success "can subtract two numbers" equal? forth '(("3 4 -")) '(-1)) (test-error "errors if there is nothing on the stack" forth '(("-"))) (test-error "errors if there is only one value on the stack" forth '(("1 -"))) (test-success "can multiply two numbers" equal? forth '(("2 4 *")) '(8)) (test-error "errors if there is nothing on the stack" forth '(("*"))) (test-error "errors if there is only one value on the stack" forth '(("1 *"))) (test-success "can divide two numbers" equal? forth '(("12 3 /")) '(4)) (test-success "performs integer division" equal? forth '(("8 3 /")) '(2)) (test-error "errors if dividing by zero" forth '(("4 0 /"))) (test-error "errors if there is nothing on the stack" forth '(("/"))) (test-error "errors if there is only one value on the stack" forth '(("1 /"))) (test-success "addition and subtraction" equal? forth '(("1 2 + 4 -")) '(-1)) (test-success "multiplication and division" equal? forth '(("2 4 * 3 /")) '(2)) (test-success "copies a value on the stack" equal? forth '(("1 dup")) '(1 1)) (test-success "copies the top value on the stack" equal? forth '(("1 2 dup")) '(2 2 1)) (test-error "errors if there is nothing on the stack" forth '(("dup"))) (test-success "removes the top value on the stack if it is the only one" equal? forth '(("1 drop")) '()) (test-success "removes the top value on the stack if it is not the only one" equal? forth '(("1 2 drop")) '(1)) (test-error "errors if there is nothing on the stack" forth '(("drop"))) (test-success "swaps the top two values on the stack if they are the only ones" equal? forth '(("1 2 swap")) '(1 2)) (test-success "swaps the top two values on the stack if they are not the only ones" equal? forth '(("1 2 3 swap")) '(2 3 1)) (test-error "errors if there is nothing on the stack" forth '(("swap"))) (test-error "errors if there is only one value on the stack" forth '(("1 swap"))) (test-success "copies the second element if there are only two" equal? forth '(("1 2 over")) '(1 2 1)) (test-success "copies the second element if there are more than two" equal? forth '(("1 2 3 over")) '(2 3 2 1)) (test-error "errors if there is nothing on the stack" forth '(("over"))) (test-error "errors if there is only one value on the stack" forth '(("1 over"))) (test-success "can consist of built-in words" equal? forth '((": dup-twice dup dup ;" "1 dup-twice")) '(1 1 1)) (test-success "execute in the right order" equal? forth '((": countup 1 2 3 ;" "countup")) '(3 2 1)) (test-success "can override other user-defined words" equal? forth '((": foo dup ;" ": foo dup dup ;" "1 foo")) '(1 1 1)) (test-success "can override built-in words" equal? forth '((": swap dup ;" "1 swap")) '(1 1)) (test-success "can override built-in operators" equal? forth '((": + * ;" "3 4 +")) '(12)) (test-success "can use different words with the same name" equal? forth '((": foo 5 ;" ": bar foo ;" ": foo 6 ;" "bar foo")) '(6 5)) (test-success "can define word that uses word with the same name" equal? forth '((": foo 10 ;" ": foo foo 1 + ;" "foo")) '(11)) (test-error "cannot redefine numbers" forth '((": 1 2 ;"))) (test-error "errors if executing a non-existent word" forth '(("foo"))) (test-success "DUP is case-insensitive" equal? forth '(("1 DUP Dup dup")) '(1 1 1 1)) (test-success "DROP is case-insensitive" equal? forth '(("1 2 3 4 DROP Drop drop")) '(1)) (test-success "SWAP is case-insensitive" equal? forth '(("1 2 SWAP 3 Swap 4 swap")) '(1 4 3 2)) (test-success "OVER is case-insensitive" equal? forth '(("1 2 OVER Over over")) '(1 2 1 2 1)) (test-success "user-defined words are case-insensitive" equal? forth '((": foo dup ;" "1 FOO Foo foo")) '(1 1 1 1)) (test-success "definitions are case-insensitive" equal? forth '((": SWAP DUP Dup dup ;" "1 swap")) '(1 1 1 1)))) (run-with-cli "forth.scm" (list test-cases))
false
9279c60b6e0d2934300ad7bee06a7e44295a88d6
f4aa970bfe8ad35285babbbc5eefc131ff630cf4
/contrib/duy-nguyen/srfi/159/base.sld
aa2a1c8ec6f0d5bc57f61f23622df59f7b70199a
[]
no_license
scheme-requests-for-implementation/srfi-159
9e7df89dc7bb180a7fa4ebc394271a5ab91ccbe8
8d23d6f0d7bc5f86ff6b4dba43468930e7ec59ab
refs/heads/master
2021-06-03T16:26:47.300320
2020-08-02T15:22:26
2020-08-02T15:22:26
101,005,980
1
2
null
2020-02-23T00:40:38
2017-08-22T01:09:33
HTML
UTF-8
Scheme
false
false
650
sld
base.sld
(define-library (srfi 159 base) (export call-with-output displayed each each-in-list escaped fitted fitted/both fitted/right fl fn forked joined joined/dot joined/last joined/prefix joined/range joined/suffix maybe-escaped nl nothing numeric numeric/comma numeric/fitted numeric/si padded padded/both padded/right pretty pretty-simply show space-to tab-to trimmed trimmed/both trimmed/lazy trimmed/right with with! written written-simply) (import (srfi 159 internal base) (srfi 159 internal pretty) (srfi 159 internal util)))
false
c928fa2c6226ad5323164a644055ed14bdbc6e67
be06d133af3757958ac6ca43321d0327e3e3d477
/99problems/14.scm
82f7d06a5ac0f59c024ad140529a2bfd9b73a999
[]
no_license
aoyama-val/scheme_practice
39ad90495c4122d27a5c67d032e4ab1501ef9c15
f133d9326699b80d56995cb4889ec2ee961ef564
refs/heads/master
2020-03-13T12:14:45.778707
2018-04-26T07:12:06
2018-04-26T07:12:06
131,115,150
0
0
null
null
null
null
UTF-8
Scheme
false
false
317
scm
14.scm
(define (adjacent? x y lis) (cond ((null? lis) #f) ((and (not (null? (cdr lis))) (equal? (car lis) x) (equal? (cadr lis) y)) #t) (else (adjacent? x y (cdr lis))))) (print (adjacent? 'a 'b '(a b c d e f))) ; #t (print (adjacent? 'e 'f '(a b c d e f))) ; #t (print (adjacent? 'f 'e '(a b c d e f))) ; #f
false
dd0f418504f646e0b2eefcbe258b3cad8a3f6d86
bdcc255b5af12d070214fb288112c48bf343c7f6
/nltk/dfsa.sls
59f46f8fbbc6ccb2dbf8773886ba1da1ccf48ba0
[]
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
19,443
sls
dfsa.sls
#!chezscheme ;;; dfsa.sls ;;; Time-stamp: <2010-04-01 09:50:00 dcavar> ;;; ;;; Copyright (C) 2010 by Damir Ćavar and Peter Garžina ;;; ;;; This library is free software; you can redistribute it ;;; and/or modify it under the terms of the GNU Lesser ;;; General Public License as published by the Free Software ;;; Foundation; either version 2.1 of the License, or (at ;;; your option) any later version. ;;; The Scheme NLTK is distributed in the hope that it will be ;;; useful, but WITHOUT ANY WARRANTY; without even the ;;; implied warranty of MERCHANTABILITY or FITNESS FOR A ;;; PARTICULAR PURPOSE. See the GNU Lesser General Public ;;; License for more details. ;;; You should have received a copy of the GNU Lesser ;;; General Public License along with Web testing; if not, ;;; write to the Free Software Foundation, Inc., 59 Temple ;;; Place, Suite 330, Boston, MA 02111-1307 USA ;;; Author: Damir Ćavar <[email protected]> and Petar Garžina <[email protected]> ;; ;; Packaged for R7RS Scheme by Peter Lane, 2017 ;; ;; Commentary: ;; Bug: we do not eliminate merged state sub-automata completely in the minimization ;; procedure, this needs to be fixed ASAP ;; Example: Check the extended test-dfsa.scm script for the last DOT output, where ;; the unnexxesary subtrees are still present! ;; (library (nltk dfsa) (export reverse-transitions ; ! state-symbol ; ! dfsa-accept? dfsa-has-transitions? dfsa-transitions-count dfsa-states-count dfsa-final-states-count dfsa-is-final-state? dfsa? make-dfsa dfsa-finalstates dfsa-finalstates-set! dfsa-alphabet dfsa-alphabet-set! dfsa-states dfsa-states-set! dfsa-transitions dfsa-transitions-set! dfsa-startstate dfsa-startstate-set! dfsa->dot dfsa-add-state! dfsa-set-finalstate! dfsa-add-symbol! dfsa-add-transition! dfsa-get-transition dfsa-all-transitions sequence->dfsa sequence-list->dfsa dfsa-minimize! dfsa-union dfsa-concatenate) (import (scheme base) (scheme case-lambda) (scheme write) (nltk sequence) (scheme list) (scheme comparator) (scheme hash-table)) (begin (define dfsa-accept? (lambda (automaton seq) (let ((myseq (cond ((vector? seq) (vector->list seq)) ((string? seq) (string->list seq)) ((list? seq) seq) (else (error "invalid seq")))) (trans (dfsa-transitions automaton))) (let loop ((state (dfsa-startstate automaton)) (symbols myseq)) (cond ((null? symbols) (if (dfsa-is-final-state? automaton state) #t #f)) ((hash-table-contains? trans (vector state (car symbols))) (loop (hash-table-ref/default trans (vector state (car symbols)) -1) (cdr symbols))) (else #f)))))) (define dfsa-has-transitions? (lambda (automaton) (if (> (hash-table-size (dfsa-transitions automaton)) 0) #t #f))) (define dfsa-transitions-count (lambda (automaton) (hash-table-size (dfsa-transitions automaton)))) (define dfsa-states-count (lambda (automaton) (length (dfsa-states automaton)))) (define dfsa-final-states-count (lambda (automaton) (length (dfsa-finalstates automaton)))) (define dfsa-is-final-state? (lambda (automaton state) (if (member state (dfsa-finalstates automaton)) #t #f))) (define-record-type <dfsa> (%dfsa finalstates alphabet states transitions startstate) dfsa? (finalstates dfsa-finalstates dfsa-finalstates-set!) (alphabet dfsa-alphabet dfsa-alphabet-set!) (states dfsa-states dfsa-states-set!) (transitions dfsa-transitions dfsa-transitions-set!) (startstate dfsa-startstate dfsa-startstate-set!)) (define (make-dfsa) (%dfsa '() '() '( 0 ) (make-hash-table (make-default-comparator)) 0)) ; returns a string for an automaton (define dfsa->dot (lambda (automaton) ; transitions start-state final-states states) (if (dfsa? automaton) (let ((port (open-output-string))) (call-with-port port (lambda (p) (display "digraph fsa {" p)(newline p) (display "rankdir=LR;" p)(newline p) (display "node ( shape=doublecircle )" p)(newline p) (for-each (lambda (st) (display st p) (display " " p)) (dfsa-finalstates automaton)) (display ";" p)(newline p) (display "node ( shape = circle );" p)(newline p) (let-values (((keys values) (dfsa-all-transitions automaton))) (vector-for-each (lambda (key value) (display (vector-ref key 0) p) (display " -> " p) (display value p) (display " ( label=" p) (display (string (vector-ref key 1)) p) (display " );" p)(newline p)) keys values)) (display "}" p)(newline p) (get-output-string port)))) ""))) (define dfsa-add-state! (lambda (automaton state) (cond ((dfsa? automaton) (let ((states (dfsa-states automaton))) (cond ((not (member state states)) (dfsa-states-set! automaton (append states (list state)))))))))) (define dfsa-set-finalstate! (lambda (automaton state) (cond ((dfsa? automaton) (let ((states (dfsa-finalstates automaton))) (cond ((not (member state states)) (dfsa-finalstates-set! automaton (append states (list state)))))))))) (define dfsa-add-symbol! (lambda (automaton symb) (cond ((dfsa? automaton) (let ((symbols (dfsa-alphabet automaton))) (cond ((not (member symb symbols)) (dfsa-alphabet-set! automaton (append symbols (list symb)))))))))) (define dfsa-add-transition! (lambda (automaton from-state symb to-state . weight) (cond ((dfsa? automaton) (let ((transitions (dfsa-transitions automaton)) (state-symb (vector from-state symb))) (let ((goal (hash-table-ref/default transitions state-symb #f)) (new-goal (if (null? weight) to-state (append (list to-state) weight)))) (cond ((not goal) (hash-table-set! transitions state-symb new-goal)) (else (cond ((list? goal) (cond ((not (member to-state goal)) (hash-table-set! transitions state-symb (append goal (list new-goal)))))))))) (dfsa-transitions-set! automaton transitions)))))) (define dfsa-get-transition (lambda (automaton from-state symb) (cond ((dfsa? automaton) (hash-table-ref/default (dfsa-transitions automaton) (vector from-state symb) -1))))) (define dfsa-all-transitions (lambda (automaton) (if (dfsa? automaton) (values (apply vector (hash-table-keys (dfsa-transitions automaton))) (apply vector (hash-table-values (dfsa-transitions automaton)))) (error "dfsa-all-transitions expected a dfsa")))) (define sequence->dfsa (case-lambda ((sequence) (sequence->dfsa sequence (make-dfsa))) ((sequence automaton) (sequence->dfsa sequence automaton '() )) ((sequence automaton goalstates) (sequence->dfsa sequence automaton goalstates '() )) ((sequence automaton goalstates string-classes) (let ((sequence (cond ((string? sequence) (list->vector (string->list sequence))) ((list? sequence) (list->vector sequence)) (else (error "sequence must be a string or a list"))))) (cond ((vector? sequence) (let ((current-state (dfsa-startstate automaton))) (for-each (lambda (symbol-index) (let* ((current-symbol (vector-ref sequence symbol-index)) (key (cons current-state current-symbol)) (state (dfsa-get-transition automaton current-state current-symbol))) (cond ((= state -1) (let ((newstate (if (> (length (dfsa-states automaton)) 1) (+ (apply max (dfsa-states automaton)) 1) (+ (car (dfsa-states automaton) ) 1)))) ; add new transition (dfsa-add-transition! automaton current-state current-symbol newstate) ; add symbol to alphabet (dfsa-add-symbol! automaton current-symbol) ; add new state to automaton (dfsa-add-state! automaton newstate) ; make newstate the current-state (set! current-state newstate) )) (else (begin (set! current-state state)))))) (enum-list (vector-length sequence))) ; add current-state to FinalStates at the end of the word (dfsa-set-finalstate! automaton current-state))) (else (error "Sequence not a vector"))) automaton)))) (define sequence-list->dfsa (case-lambda ((sequence-list) (sequence-list->dfsa sequence-list (make-dfsa))) ((sequence-list automaton) (begin (for-each (lambda (token) (sequence->dfsa token automaton)) sequence-list) automaton)))) ; key = goal state ; value = list of transitions to key (define reverse-transitions (lambda (automaton) (let ((goals-transitions (make-hash-table (make-default-comparator)))) (let-values (((keys values) (values (apply vector (hash-table-keys (dfsa-transitions automaton))) (apply vector (hash-table-values (dfsa-transitions automaton)))))) (vector-for-each (lambda (key value) (let ((new-value (hash-table-ref/default goals-transitions value '()))) (hash-table-set! goals-transitions value (append new-value (list key))))) keys values)) goals-transitions))) (define state-symbol (lambda (automaton) (let ((stsym (make-hash-table (make-default-comparator)))) (vector-for-each (lambda (key) (hash-table-set! stsym (vector-ref key 0) (append (hash-table-ref/default stsym (vector-ref key 0) '()) (list (vector-ref key 1))))) (apply vector (hash-table-keys (dfsa-transitions automaton)))) stsym))) (define dfsa-minimize! (lambda (automaton) (let ((goal-trans (reverse-transitions automaton)) (state-emit-symbols (state-symbol automaton)) (trans (dfsa-transitions automaton)) (str-res (make-hash-table (make-default-comparator)))) ; merge all absolutely final states into one (let ((absolute-final-states (filter (lambda (el) (if (null? (hash-table-ref/default state-emit-symbols el '())) #t #f)) (dfsa-finalstates automaton)))) (dfsa-merge-states! automaton (car absolute-final-states) (do ((x (cdr absolute-final-states) (cdr x)) (res '() (append res (hash-table-ref/default goal-trans (car x) '())))) ((null? x) res)) (cdr absolute-final-states) '()) (for-each ; change tranisitions to point to the new final state (lambda (state) (hash-table-set! goal-trans (car absolute-final-states) (append (hash-table-ref/default goal-trans (car absolute-final-states) '()) (hash-table-ref/default goal-trans state '()))) (hash-table-delete! goal-trans state) (hash-table-delete! state-emit-symbols state)) (cdr absolute-final-states)) ; start from the absolutely final state and try to merge states (let loop1 ((agenda (list (car absolute-final-states)))) (unless (null? agenda) (let* ((current-final (car agenda)) (entering-states (remove-duplicates (map (lambda (el) (vector-ref el 0)) (hash-table-ref/default goal-trans current-final '()))))) (for-each (lambda (key) (hash-table-delete! str-res key)) (hash-table-keys str-res)) (for-each (lambda (elem) ; str-res has strings as keys, list of states from to current-final as value (let ((symbs (hash-table-ref/default state-emit-symbols elem '()))) (hash-table-set! str-res symbs (append (hash-table-ref/default str-res symbs '()) (list elem))))) entering-states) ; (vector-for-each ; find the str-res entry with more than one val (lambda (key) (let ((val (hash-table-ref/default str-res key '()))) (when (> (length val) 1) (let ((finals (filter (lambda (el) (if (dfsa-is-final-state? automaton el) #t #f)) val)) (nonfinals (filter (lambda (el) (if (dfsa-is-final-state? automaton el) #f #t)) val))) (for-each (lambda (statelist) (when (> (length statelist) 1) ; merge other states to the first ; get all states that connect to any of the other states, but the first ; make them all transite into the first (let ((remstates (cdr statelist))) (dfsa-merge-states! automaton (car statelist) (do ((x (cdr statelist) (cdr x)) (res '() (append res (hash-table-ref/default goal-trans (car x) '())))) ((null? x) res)) remstates (filter (lambda (elem) (if (member (vector-ref elem 0) remstates) #t #f)) (hash-table-ref/default goal-trans (car agenda) '()))) (display "Merged states: ") (display statelist)(newline)) (for-each (lambda (state) ; change goal-trans (hash-table-set! goal-trans (car statelist) (append (hash-table-ref/default goal-trans (car statelist) '()) (hash-table-ref/default goal-trans state '()))) (hash-table-delete! goal-trans state) (hash-table-delete! state-emit-symbols state)) (cdr statelist)) ; add first of statelist to agenda (unless (member (car statelist) agenda) (set! agenda (append agenda (list (car statelist))))))) (list finals nonfinals)))))) (apply vector (hash-table-keys str-res))) (loop1 (cdr agenda))))))) automaton)) (define dfsa-merge-states! (lambda (aut to-state trans-list state-list remtrans) (display "in dfsa-merge-states!")(newline) (display "to-state: ")(display to-state)(newline) (display "trans-list: ")(display trans-list)(newline) (display "state-list: ")(display state-list)(newline) (display "remtrans: ")(display remtrans)(newline) ; remove from list of final states (dfsa-finalstates-set! aut (filter (lambda (el) (if (member el state-list) #f #t)) (dfsa-finalstates aut))) ; remove from list of states (dfsa-states-set! aut (filter (lambda (el) (if (member el state-list) #f #t)) (dfsa-states aut))) ; change transitions to point to the new final state (let ((trans (dfsa-transitions aut))) (for-each (lambda (transition) (hash-table-set! trans transition to-state)) trans-list) (for-each (lambda (transition) (hash-table-delete! trans transition)) remtrans)))) ;; Not implemented ; (define dfsa-serialize ; (lambda (automaton port) ; #t)) ; (define dfsa-deserialize ; (lambda (automaton-port) ; #t)) ;; TODO: these do nothing (define dfsa-union (lambda (fsa1 fsa2) fsa1)) (define dfsa-concatenate (lambda (fsa1 fsa2) fsa1)) ))
false
8cf674bb4c9257ffd77eebba3ac806571f3cae82
0bb7631745a274104b084f6684671c3ee9a7b804
/lib/gambit/prim/special-forms.sld
dd07e88429d4050263707f35a9f0e87e3399f0bc
[ "Apache-2.0", "LGPL-2.1-only", "LicenseRef-scancode-free-unknown", "GPL-3.0-or-later", "LicenseRef-scancode-autoconf-simple-exception" ]
permissive
feeley/gambit
f87fd33034403713ad8f6a16d3ef0290c57a77d5
7438e002c7a41a5b1de7f51e3254168b7d13e8ba
refs/heads/master
2023-03-17T06:19:15.652170
2022-09-05T14:31:53
2022-09-05T14:31:53
220,799,690
0
1
Apache-2.0
2019-11-10T15:09:28
2019-11-10T14:14:16
null
UTF-8
Scheme
false
false
1,105
sld
special-forms.sld
;;;============================================================================ ;;; File: "special-forms.sld" ;;; Copyright (c) 1994-2021 by Marc Feeley, All Rights Reserved. ;;;============================================================================ ;;; Special-forms. (define-library (special-forms) (namespace "##") (export ;; r4rs and begin case cond define delay do if lambda let let* letrec or quasiquote quote set! ;; r5rs define-syntax ;;let-syntax ;; not implemented ;;letrec-syntax ;; not implemented syntax-rules ;; r7rs case-lambda cond-expand define-library define-record-type delay-force guard include include-ci let*-values let-values letrec* letrec*-values letrec-values parameterize syntax-error unless when ;; gambit c-declare c-define c-define-type c-initialize c-lambda declare define-cond-expand-feature define-macro define-structure define-type define-type-of-thread define-values future import namespace r7rs-guard receive six.infix syntax syntax-case this-source-file time )) ;;;============================================================================
true
d55ac386fe6045900bdd46c83920ba2b0374071a
51d30de9d65cc3d5079f050de33d574584183039
/http/http.scm
1967f7a24c7b7365d61b9f0ac4bfcc92c13d198c
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
langmartin/ykk
30feb00265d603ef765b5c664d2f759be34b7b89
dd6e441dddd5b6363ee9adbbdd0f346c1522ffcf
refs/heads/master
2016-09-05T20:01:19.353224
2009-12-10T16:25:55
2009-12-10T16:25:55
408,478
0
1
null
null
null
null
UTF-8
Scheme
false
false
8,589
scm
http.scm
(define crlf "\r\n") (define (output-debug . args) (let ((real (current-output-port)) (body (let-string-output-port (apply output args)))) (display body real) (let-current-output-port (current-error-port) (output "output-debug\n" body "\n\n")))) (define-record-type :server-exec (http-server-exec% thunk output) http-server-exec? (thunk exec-thunk) (output exec-output)) (define (http-server-exec thunk . out) (http-server-exec% thunk out)) (define (http-server-close) (http-server-exec (lambda () #t))) (define (exec thunk) ((thunk))) (define (http-server ip port handler) (let ((socket (open-socket port))) (dynamic-wind (lambda () #t) (lambda () (socket-port-number socket) ; make sure it's open (let lp () (let ((result (call-with-values (lambda () (socket-accept socket)) handler))) (if (http-server-exec? result) (exec (exec-thunk result)) ; extra points if this makes sense (lp))))) (lambda () (close-socket socket))))) ;;;; HTTP Client (define-syntax let-http-response (syntax-rules () ((_ (code message) body ...) (list (list code " " message crlf) body ...)) ((_ code (headers ...) body ...) (list (list code " " (lookup-http-code-text code)) (let-headers (headers ...) body ...))))) (define-syntax let-headers (syntax-rules () ((_ () body ...) (list body ...)) ((_ ((key val) (k1 v1) ...) body ...) (let ((key val)) (cons (list 'key ": " val crlf) (let-headers ((k1 v1) ...) body ...)))))) (assert (let-headers ((foo 3) (bar foo)) 5) => '((foo ": " 3 "\r\n") (bar ": " 3 "\r\n") 5)) (define (vector->content-length vec) (let ((len (byte-vector-length vec))) (if (zero? len) crlf (list (list 'content-length ": " len crlf crlf) (lambda () (write-block vec 0 len (current-output-port))))))) (define (begin-content-length . body) (vector->content-length (let-u8-output-port (output body)))) (define-syntax let-header-data (syntax-rules () ((_ ((key val) ...)) (let-header-data (key val) ...)) ((_) '()) ((_ (key val) (key1 val1) ...) (letrec ((key val)) (cons (cons 'key val) (let-header-data (key1 val1) ...)))))) (define (header-reduce . header-lists) (map (lambda (pair) (let ((sym val (uncons pair))) (list sym ": " val crlf))) (reverse (apply fold-append (lambda (pair acc) (if (assq (car pair) acc) acc (cons pair acc))) '() header-lists)))) (define (http-keepalive? headers) (or (and-let* ((conn (header-assoc 'connection headers))) (not (string=? "close" conn))) (and-let* ((conn (header-assoc 'proxy-connection headers))) (string=? "keep-alive" conn)))) (assert (let-string-output-port (output (let-http-response (200 "Ok") (let-headers ((user-agent "scheme48") (host "coptix.com")) (let-headers ((content-type "text/plain")) (begin-content-length "Some text goes here.")))))) => "200 Ok\r user-agent: scheme48\r host: coptix.com\r content-type: text/plain\r content-length: 20\r \r Some text goes here.") (define (http-form-post/method method url) (receive (input output) (proxy-client "HTTP/1.1" method url '() (let-headers ((content-type "text/x-url-form-encoded")) (begin-content-length (url-parameter-string url)))) (close-output-port output) input)) (define (http-form-post url-rec) (http-form-post/method "POST" url-rec)) (define (http-get/method method url) (receive (input output) (proxy-client "HTTP/1.1" method url (header-cons 'accept "*" header-null) crlf) (close-output-port output) input)) (define (http-get url) (http-get/method "GET" url)) (define (http-get->mime url) (let ((port (http-get/method "GET" url))) (call/http-version port (lambda (version code text) (stream-car (port->mime-stream port)))))) (define-syntax let-http-request (syntax-rules () ((_ (get ...) body ...) (list (list get ...) body ...)))) ;;;; proxy (define *client-keep-alive* (make-string-table)) (define (store-client-connection host in out) (table-set! *client-keep-alive* host (cons in out))) (define (fetch-client-connection host) (and-let* ((found (table-ref *client-keep-alive* host))) (values (car found) (cdr found)))) (define (proxy-client-headers url) (let-header-data ((host (url-host url)) (connection "close") (accept-encoding "identity")))) (define *proxy-client-filter* '(keep-alive)) (define (client-connect host port) (let ((conn (table-ref *client-keep-alive* host))) (if conn (values (car conn) (cdr conn)) (socket-client host port)))) (define (proxy-client version method path headers body) (let* ((url (if (url? path) path (parse-url path))) (host (url-host url)) (port (url-port url))) (receive (input-port output-port) (client-connect host port) (let-current-output-port output-port (let ((getp (and (url-parameters? url) (cons #\? (url-parameter-string url))))) (output (let-http-request (method " " (url-path url) getp " " version crlf) (header-filter *proxy-client-filter* (header-reduce (proxy-client-headers url) headers))) body) (force-output (current-output-port)) (values input-port output-port)))))) (define (proxy-mime port) (stream-car (port->mime-stream port))) (define (proxy-req-body mime) (list crlf (lambda () (proxy-body mime)))) (define *proxy-reply-headers* (let-header-data ((transfer-encoding "identity")))) (define (proxy-body mime) (duct-for-each display ((d/characters) (mime->byte-duct mime))) (force-output (current-output-port))) (define (proxy-client-handler thunk) (with-exception-catcher (lambda (c propagate) (let-http-response (500 "Proxy Failure") (let-headers ((content-type "text/plain")) (begin-content-length "500\n" "https requests are not yet supported.\n" "non-existent hostname?\n" (condition-stuff c))))) thunk)) (define (proxy-handler version method path port) (let* ((url (parse-url path)) (host (url-host url)) ; proxy req include the host (mime (proxy-mime port)) (head (mime-headers mime))) (proxy-client-handler (lambda () (receive (input output) (proxy-client version method url head (proxy-req-body mime)) (call/http-version input (lambda (version code text) (let* ((mime (proxy-mime input)) (head (mime-headers mime))) (let-http-response (code text) (header-reduce *proxy-reply-headers* head) (begin-content-length (proxy-body mime) (if (and #f (http-keepalive? head)) ; disabled (store-client-connection host input output) (begin (close-output-port output) (close-input-port input))))))))))))) (define (proxy-handler-wrapper) (lambda (input-port output-port) (call/http-version input-port (lambda (method path version) (perform-standard-output (proxy-handler version method path input-port) version input-port output-port))))) (define (proxy-server . debugging-flag) (http-server 'ip 3128 (if (null? debugging-flag) proxy-handler-wrapper (let-multithreaded proxy-handler)))) ;;;; Manual tests (they have side effects, and rely on url content ;; (define (test-get-coptix) ;; (let ((p (http-get "http://coptix.com"))) ;; (begin1 ;; (read-line p #f) ;; (close-input-port p)))) ;; (define (test-proxy) ;; (let-string-ports ;; *request* ;; (output-response ;; (current-output-port) ;; "HTTP/1.1" ;; (proxy-handler ;; "HTTP/1.1" "GET" "/index" (current-input-port)))))
true
b5a7b731b192f09f32511f1ff581f435058ca923
defeada37d39bca09ef76f66f38683754c0a6aa0
/System/system/code-dom/code-parameter-declaration-expression-collection.sls
90158ff076fb59ee19ecfcf9f4154dc178e6b908
[]
no_license
futsuki/ironscheme-port
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
4e7a81b0fbeac9a47440464988e53fb118286c54
refs/heads/master
2016-09-06T17:13:11.462593
2015-09-26T18:20:40
2015-09-26T18:20:40
42,757,369
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,473
sls
code-parameter-declaration-expression-collection.sls
(library (system code-dom code-parameter-declaration-expression-collection) (export new is? code-parameter-declaration-expression-collection? insert add-range index-of add contains? remove copy-to item-get item-set! item-update!) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.CodeDom.CodeParameterDeclarationExpressionCollection a ...))))) (define (is? a) (clr-is System.CodeDom.CodeParameterDeclarationExpressionCollection a)) (define (code-parameter-declaration-expression-collection? a) (clr-is System.CodeDom.CodeParameterDeclarationExpressionCollection a)) (define-method-port insert System.CodeDom.CodeParameterDeclarationExpressionCollection Insert (System.Void System.Int32 System.CodeDom.CodeParameterDeclarationExpression)) (define-method-port add-range System.CodeDom.CodeParameterDeclarationExpressionCollection AddRange (System.Void System.CodeDom.CodeParameterDeclarationExpressionCollection) (System.Void System.CodeDom.CodeParameterDeclarationExpression[])) (define-method-port index-of System.CodeDom.CodeParameterDeclarationExpressionCollection IndexOf (System.Int32 System.CodeDom.CodeParameterDeclarationExpression)) (define-method-port add System.CodeDom.CodeParameterDeclarationExpressionCollection Add (System.Int32 System.CodeDom.CodeParameterDeclarationExpression)) (define-method-port contains? System.CodeDom.CodeParameterDeclarationExpressionCollection Contains (System.Boolean System.CodeDom.CodeParameterDeclarationExpression)) (define-method-port remove System.CodeDom.CodeParameterDeclarationExpressionCollection Remove (System.Void System.CodeDom.CodeParameterDeclarationExpression)) (define-method-port copy-to System.CodeDom.CodeParameterDeclarationExpressionCollection CopyTo (System.Void System.CodeDom.CodeParameterDeclarationExpression[] System.Int32)) (define-field-port item-get item-set! item-update! (property:) System.CodeDom.CodeParameterDeclarationExpressionCollection Item System.CodeDom.CodeParameterDeclarationExpression))
true
b939b4baca92de7ba203682db4025c1b955bd6fd
26aaec3506b19559a353c3d316eb68f32f29458e
/modules/timestamp/query.scm
8c44a8b7849c20cfe2b124282c1d4bacd94e17ef
[ "BSD-3-Clause" ]
permissive
mdtsandman/lambdanative
f5dc42372bc8a37e4229556b55c9b605287270cd
584739cb50e7f1c944cb5253966c6d02cd718736
refs/heads/master
2022-12-18T06:24:29.877728
2020-09-20T18:47:22
2020-09-20T18:47:22
295,607,831
1
0
NOASSERTION
2020-09-15T03:48:04
2020-09-15T03:48:03
null
UTF-8
Scheme
false
false
7,323
scm
query.scm
#| LambdaNative - a cross-platform Scheme framework Copyright (c) 2009-2015, University of British Columbia 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 University of British Columbia 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |# ;; Timestamp query related functions (c-declare #<<end-of-c-declare #include <string.h> #include <openssl/ts.h> static TS_REQ *createTSQ(unsigned char *hash, int len){ // Get proper type const EVP_MD *md = NULL; if (len==SHA512_DIGEST_LENGTH) md=EVP_sha512(); else if (len==SHA256_DIGEST_LENGTH) md=EVP_sha256(); else if (len==SHA_DIGEST_LENGTH) md=EVP_sha1(); else return 0; // Define structures TS_REQ *ts_req = TS_REQ_new(); X509_ALGOR *algo = X509_ALGOR_new(); TS_MSG_IMPRINT *msg_imprint = TS_MSG_IMPRINT_new(); if (ts_req==NULL || algo==NULL || msg_imprint==NULL) return 0; // Set request version and add hash algorithm identifier TS_REQ_set_version(ts_req, 1); algo->algorithm = OBJ_nid2obj(EVP_MD_type(md)); algo->parameter = ASN1_TYPE_new(); if (algo->algorithm == NULL || algo->parameter == NULL) return 0; algo->parameter->type = V_ASN1_NULL; if (!TS_MSG_IMPRINT_set_algo(msg_imprint, algo)) return 0; // Add the hash if (!TS_MSG_IMPRINT_set_msg(msg_imprint, hash, len)) return 0; if (!TS_REQ_set_msg_imprint(ts_req, msg_imprint)) return 0; // Add the nonce ASN1_INTEGER *nonce_asn1 = ASN1_INTEGER_new(); time_t t; srand((unsigned) time(&t)); ASN1_INTEGER_set(nonce_asn1, rand()); if (!TS_REQ_set_nonce(ts_req, nonce_asn1)) return 0; // Add the certificate request if (!TS_REQ_set_cert_req(ts_req, 1)) return 0; // Cleanup and return request TS_MSG_IMPRINT_free(msg_imprint); X509_ALGOR_free(algo); ASN1_INTEGER_free(nonce_asn1); return ts_req; } int get_tsq(unsigned char* hash, int hashlen, unsigned char* result){ TS_REQ *query = createTSQ(hash,hashlen); int len = i2d_TS_REQ(query,NULL); i2d_TS_REQ(query,&result); TS_REQ_free(query); return len; } int get_tsq_version(unsigned char *tsq, int len){ int ret=0; const unsigned char *t = tsq; TS_REQ *ts_req = TS_REQ_new(); d2i_TS_REQ(&ts_req, &t, len); if (ts_req==NULL) return 0; ret=TS_REQ_get_version(ts_req); TS_REQ_free(ts_req); return ret; } int get_tsq_nonce(unsigned char *tsq, int len){ int ret=0; const unsigned char *t = tsq; TS_REQ *ts_req = TS_REQ_new(); d2i_TS_REQ(&ts_req, &t, len); if (ts_req==NULL) return 0; const ASN1_INTEGER *nonce = TS_REQ_get_nonce(ts_req); ret = ASN1_INTEGER_get(nonce); TS_REQ_free(ts_req); return ret; } int get_tsq_msg(unsigned char *tsq, int len, unsigned char *msg){ int ret=0; const unsigned char *t = tsq; TS_REQ *ts_req = TS_REQ_new(); d2i_TS_REQ(&ts_req, &t, len); if (ts_req==NULL) return 0; TS_MSG_IMPRINT *msg_imprint = TS_REQ_get_msg_imprint(ts_req); ASN1_OCTET_STRING *str = TS_MSG_IMPRINT_get_msg(msg_imprint); ret = ASN1_STRING_length(str); unsigned char *data = ASN1_STRING_data(str); int i; for (i=0;i<ret;i++){ msg[i]=data[i]; } TS_REQ_free(ts_req); return ret; } int get_tsq_policy(unsigned char *tsq, int len, unsigned char *msg){ int ret=0; const unsigned char *t = tsq; TS_REQ *ts_req = TS_REQ_new(); d2i_TS_REQ(&ts_req, &t, len); if (ts_req==NULL) return 0; ASN1_OBJECT *policy_id = TS_REQ_get_policy_id(ts_req); if (policy_id == NULL){ msg = ""; ret = 0; } else { char obj_txt[128]; ret = OBJ_obj2txt(obj_txt, sizeof(obj_txt), policy_id, 0); int i; for (i=0;i<ret;i++){ msg[i]=obj_txt[i]; } } TS_REQ_free(ts_req); return ret; } end-of-c-declare ) ;; Scheme bindings (define (timestamp:gettsq hash) (let* ((v (make-u8vector 100)) (f ((c-lambda (scheme-object int scheme-object) int "___result= get_tsq(___CAST(unsigned char*,___BODY_AS(___arg1,___tSUBTYPED)),___arg2, ___CAST(unsigned char*,___BODY_AS(___arg3,___tSUBTYPED)));") hash (u8vector-length hash) v))) (if f (subu8vector v 0 f) #f) )) (define (timestamp-tsq-generate-sha512sum sha) (if (u8vector? sha) (timestamp:gettsq sha) #f)) (define (timestamp-tsq-generate filename) (if (string? filename) (timestamp-tsq-generate-sha512sum (sha512sum filename)) #f)) (define (timestamp-tsq-save filename tsq) (if (and (string? filename) (u8vector? tsq)) (let ((fname (string-append filename ".tsq"))) (u8vector->file tsq fname) (file-exists? fname) ) #f ) ) (define (timestamp-tsq-load filename) (let ((split (string-split filename #\.))) (if (and (fx>= (length split) 2) (string=? (car (reverse split)) "tsq")) (file->u8vector filename) #f ) )) (define (timestamp-tsq-getversion tsq) ((c-lambda (scheme-object int) int "___result= get_tsq_version(___CAST(unsigned char*,___BODY_AS(___arg1,___tSUBTYPED)),___arg2);") tsq (u8vector-length tsq)) ) (define (timestamp-tsq-getpolicy tsq) (let* ((v (make-u8vector 128)) (f ((c-lambda (scheme-object int scheme-object) int "___result= get_tsq_policy(___CAST(unsigned char*,___BODY_AS(___arg1,___tSUBTYPED)),___arg2, ___CAST(unsigned char*,___BODY_AS(___arg3,___tSUBTYPED)));") tsq (u8vector-length tsq) v))) (if f (u8vector->string (subu8vector v 0 f)) #f) )) (define (timestamp-tsq-getnonce tsq) ((c-lambda (scheme-object int) int "___result= get_tsq_nonce(___CAST(unsigned char*,___BODY_AS(___arg1,___tSUBTYPED)),___arg2);") tsq (u8vector-length tsq)) ) (define (timestamp-tsq-getmessage tsq) (let* ((v (make-u8vector 100)) (f ((c-lambda (scheme-object int scheme-object) int "___result= get_tsq_msg(___CAST(unsigned char*,___BODY_AS(___arg1,___tSUBTYPED)),___arg2, ___CAST(unsigned char*,___BODY_AS(___arg3,___tSUBTYPED)));") tsq (u8vector-length tsq) v))) (if f (subu8vector v 0 f) #f) )) ;; eof
false
3f82f25962747e359a2689186399d1cf61e843d7
ab05b79ab17619f548d9762a46199dc9eed6b3e9
/sitelib/ypsilon/pango/tab.scm
8f0f31ba026ee359a478f839ef689659fc6571a2
[ "BSD-2-Clause" ]
permissive
lambdaconservatory/ypsilon
2dce9ff4b5a50453937340bc757697b9b4839dee
f154436db2b3c0629623eb2a53154ad3c50270a1
refs/heads/master
2021-02-28T17:44:05.571304
2017-12-17T12:29:00
2020-03-08T12:57:52
245,719,032
1
0
NOASSERTION
2020-03-07T23:08:26
2020-03-07T23:08:25
null
UTF-8
Scheme
false
false
3,043
scm
tab.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 pango tab) (export pango_tab_align_get_type pango_tab_array_copy pango_tab_array_free pango_tab_array_get_positions_in_pixels pango_tab_array_get_size pango_tab_array_get_tab pango_tab_array_get_tabs pango_tab_array_get_type pango_tab_array_new pango_tab_array_new_with_positions pango_tab_array_resize pango_tab_array_set_tab) (import (rnrs) (ypsilon ffi)) (define lib-name (cond (on-linux "libpango-1.0.so.0") (on-sunos "libpango-1.0.so.0") (on-freebsd "libpango-1.0.so.0") (on-openbsd "libpango-1.0.so.0") (on-darwin "Gtk.framework/Gtk") (on-windows "libpango-1.0-0.dll") (else (assertion-violation #f "can not locate Pango 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))))) ;; GType pango_tab_align_get_type (void) (define-function unsigned-long pango_tab_align_get_type ()) ;; PangoTabArray* pango_tab_array_copy (PangoTabArray* src) (define-function void* pango_tab_array_copy (void*)) ;; void pango_tab_array_free (PangoTabArray* tab_array) (define-function void pango_tab_array_free (void*)) ;; gboolean pango_tab_array_get_positions_in_pixels (PangoTabArray* tab_array) (define-function int pango_tab_array_get_positions_in_pixels (void*)) ;; gint pango_tab_array_get_size (PangoTabArray* tab_array) (define-function int pango_tab_array_get_size (void*)) ;; void pango_tab_array_get_tab (PangoTabArray* tab_array, gint tab_index, PangoTabAlign* alignment, gint* location) (define-function void pango_tab_array_get_tab (void* int void* void*)) ;; void pango_tab_array_get_tabs (PangoTabArray* tab_array, PangoTabAlign** alignments, gint** locations) (define-function void pango_tab_array_get_tabs (void* void* void*)) ;; GType pango_tab_array_get_type (void) (define-function unsigned-long pango_tab_array_get_type ()) ;; PangoTabArray* pango_tab_array_new (gint initial_size, gboolean positions_in_pixels) (define-function void* pango_tab_array_new (int int)) ;; PangoTabArray* pango_tab_array_new_with_positions (gint size, gboolean positions_in_pixels, PangoTabAlign first_alignment, gint first_position, ...) (define-function void* pango_tab_array_new_with_positions (int int int int ...)) ;; void pango_tab_array_resize (PangoTabArray* tab_array, gint new_size) (define-function void pango_tab_array_resize (void* int)) ;; void pango_tab_array_set_tab (PangoTabArray* tab_array, gint tab_index, PangoTabAlign alignment, gint location) (define-function void pango_tab_array_set_tab (void* int int int)) ) ;[end]
true
7d1bdffafde2779339a065bbda530e25f2320ba9
9c36ed1e52d7712599a8cb0e80fd5ac94d328bd3
/bench/regression.fpcore
97612c07d35c3cd73bd0efca43704bc0936e6e2b
[ "MIT" ]
permissive
oflatt/herbie
e7db30968537f9b03430056408babbcca77f411f
cecba081914fb685fcd962a95c6d6fcaa7f063ad
refs/heads/master
2021-07-30T03:37:47.191038
2021-07-23T19:10:19
2021-07-23T19:10:19
211,983,144
0
0
NOASSERTION
2019-10-01T00:26:43
2019-10-01T00:26:43
null
UTF-8
Scheme
false
false
1,417
fpcore
regression.fpcore
; -*- mode: scheme -*- ; This is a cool example that fails in cases of overflow (FPCore (lo hi x) :pre (and (< lo -1e308) (> hi 1e308)) :precision binary64 (/ (- x lo) (- hi lo))) ; These once crashed Herbie (FPCore (x y z a) :name "tan-example" :pre (and (or (== x 0) (<= 0.5884142 x 505.5909)) (or (<= -1.796658e+308 y -9.425585e-310) (<= 1.284938e-309 y 1.751224e+308)) (or (<= -1.776707e+308 z -8.599796e-310) (<= 3.293145e-311 z 1.725154e+308)) (or (<= -1.796658e+308 a -9.425585e-310) (<= 1.284938e-309 a 1.751224e+308))) (+ x (- (tan (+ y z)) (tan a)))) (FPCore (x c s) :name "mixedcos" (/ (cos (* 2 x)) (* (pow c 2) (* (* x (pow s 2)) x)))) (FPCore (x) :pre (or (== x 0) (== x 10)) x) ; These should yield the same result (FPCore (r a b) :name "rsin A" (/ (* r (sin b)) (cos (+ a b)))) (FPCore (r a b) :name "rsin B" (* r (/ (sin b) (cos (+ a b))))) ; These should yield the same result (FPCore (x) :name "sqrt A" (sqrt (+ (* x x) (* x x)))) (FPCore (x) :name "sqrt B" (sqrt (* (* 2 x) x))) (FPCore (x) :name "sqrt C" (sqrt (* 2 (* x x)))) (FPCore (x) :name "sqrt D" (sqrt (* 2 (pow x 2)))) (FPCore (x) :name "sqrt E" (sqrt (+ (pow x 2) (pow x 2)))) ; This used to cause crashes (FPCore (w l) :name "exp-w crasher" (* (exp (- w)) (pow l (exp w)))) (FPCore (x) :name "expfmod" (* (fmod (exp x) (sqrt (cos x))) (exp (- x))))
false
4dc38e1be6173e15cc0e218fe6f94043f4aa74ee
6b8bee118bda956d0e0616cff9ab99c4654f6073
/suda-ex/srfi-25-apps/typed-srfi-25-testuntyped.ss
ec14afdc259591dff99eb456e4976f577ecab80e
[]
no_license
skchoe/2012.Functional-GPU-Programming
b3456a92531a8654ae10cda622a035e65feb762d
56efdf79842fc465770214ffb399e76a6bbb9d2a
refs/heads/master
2016-09-05T23:42:36.784524
2014-05-26T17:53:34
2014-05-26T17:53:34
20,194,204
1
0
null
null
null
null
UTF-8
Scheme
false
false
436
ss
typed-srfi-25-testuntyped.ss
#lang scheme (require "srfi-25/array.ss") (include "srfi-25/example/play.scm") (define shap_ (shape 0 3 0 3)) (define shap2_ (shape 0 1 0 2 0 2)) (play shap_) (define Arr1 (make-array shap_ 100)) (define Arr2 (make-array shap2_ 200)) (define Arr3 (make-array shap_ 300)) (define Arr4 (make-array shap_ 400)) (define (proc_ a) (+ 1 a)) (define new_Arr (array-map (shape 0 1 0 2) proc_ Arr3 Arr4)) (play new_Arr)
false
4bb5b8a9b16d9dba6b053ad380845410ac57f766
a2bc20ee91471c8116985e0eb6da1d19ab61f6b0
/exercise_8_6/keep-matching-items-rec.scm
2792a4b079bf403887198fe9538e908d3f3dc72f
[]
no_license
cthulhu-irl/my-scheme-practices
6209d01aa1497971a5b970ab8aa976bb3481e9c9
98867870b0cb0306bdeb209d076bdc80e2e0e8cc
refs/heads/master
2022-09-22T15:19:48.798783
2020-06-06T14:16:07
2020-06-06T14:16:07
265,855,102
0
0
null
null
null
null
UTF-8
Scheme
false
false
402
scm
keep-matching-items-rec.scm
(define (keep-matching-items proc ls) (if (null? ls) '() (let ((first (car ls)) (rest (cdr ls))) (if (proc first) (cons first (keep-matching-items proc rest)) (keep-matching-items proc rest))))) (define (my-filter proc ls) (keep-matching-items proc ls)) (format #t "(my-filter even? '(1 2 3 4)): ~a\n" (my-filter even? '(1 2 3 4)))
false
e49909f800966b508d9aa33d281cc24e167d292f
516d588aede7345408f2a4df414aff2762eef2cf
/test/test-massoc
c40c37ea5ed96d224a581e5cf1afbc4a34c2f0b1
[]
no_license
tisannai/tuile
a29be5efe795d60525eb9e2c534f29a8dc5544ba
849d3595a21cb0418e46dc77e55382401e670481
refs/heads/master
2023-09-03T02:00:25.405667
2023-08-16T20:26:16
2023-08-16T20:26:16
229,030,435
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,840
test-massoc
#!/usr/bin/guile -s !# (use-modules (srfi srfi-64)) (use-modules (tuile pr)) (add-to-load-path "..") (use-modules (tuile massoc)) (test-begin "massoc") (define ma (make-massoc)) (test-assert "make massoc" (equal? '(()) ma)) (test-assert "copy empty massoc" (massoc-empty? (massoc-copy ma))) (test-assert "has key for empty massoc" (equal? #f (massoc-has-key? ma 'foo))) (test-assert "keys of empty massoc" (equal? '() (massoc-keys ma))) (test-assert "values of empty massoc" (equal? '() (massoc-values ma))) (test-assert "reference empty massoc" (unspecified? (massoc-ref ma 'any))) ;; Add one key-value pair to massoc. (massoc-add! ma 'foo 'bar) (test-assert "has key for one-item massoc" (equal? '(foo . bar) (massoc-has-key? ma 'foo))) (test-assert "keys of one-item massoc" (equal? '(foo) (massoc-keys ma))) (test-assert "values of one-item massoc" (equal? '(bar) (massoc-values ma))) (test-assert "reference one-item massoc with matching key" (equal? 'bar (massoc-ref ma 'foo))) (test-assert "reference one-item massoc with non-matching key" (equal? #f (massoc-ref ma 'bar))) (test-assert "assign value to existing key" (equal? 'dii (massoc-ref (massoc-val! ma 'foo 'dii) 'foo))) (test-assert "set value to existing key" (equal? 'bar (massoc-ref (massoc-set! ma 'foo 'bar) 'foo))) (test-assert "set value to non-existing key" (equal? 'haa (massoc-ref (massoc-set! ma 'jii 'haa) 'jii))) (test-assert "update value of existing key" (equal? 'dii (massoc-ref (massoc-update! ma 'foo (lambda (val) 'dii)) 'foo))) (define ma2 (massoc-copy ma)) (test-assert "update value of non-existing key" (equal? ma2 (massoc-update! ma 1 (lambda (val) (+ val 1))))) (test-assert "delete non-first entry" (equal? '((jii . haa)) (massoc-del! ma 'foo))) (test-assert "delete first entry" (equal? '(()) (massoc-del! ma 'jii))) (test-assert "repeated additions" (equal? 'bar (massoc-ref (massoc-repeat! ma massoc-add! '((foo . bar) (dii . duu))) 'foo))) (test-assert "repeated removals" (equal? (make-massoc) (massoc-repeat! ma (lambda (ma k v) (massoc-del! ma k)) '((foo . bar) (dii . duu))))) (test-assert "copy empty massoc" (equal? (make-massoc) (massoc-copy ma))) (test-end)
false
65cb26dfdf1ab1396d2dc3bfbd7a1af98b819049
defeada37d39bca09ef76f66f38683754c0a6aa0
/System.Transactions/system/transactions/enlistment.sls
edf106c08326af82c4509d84ff56abd869158a2c
[]
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
332
sls
enlistment.sls
(library (system transactions enlistment) (export is? enlistment? done) (import (ironscheme-clr-port)) (define (is? a) (clr-is System.Transactions.Enlistment a)) (define (enlistment? a) (clr-is System.Transactions.Enlistment a)) (define-method-port done System.Transactions.Enlistment Done (System.Void)))
false
c1a48194560803db25a8bc78636637932fe7a96b
ee10242f047e9b4082a720c48abc7d94fe2b64a8
/bs-build.sch
e0d6ddbc995606cb37ef5fd39074e7e39ecc88fc
[ "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
129
sch
bs-build.sch
;; Builds a standalone bs executable (require 'bs-lib) (save-image "bs" :executable #t :toplevel process-args-img :compress #t)
false
10741610c549acddc7e1a8e5f222d4571e91d988
c74dcb1facbd920d762017345171f47f8e41d0c5
/chapter_2/2.46.scm
54ced8c14884d4dac3bdb4db9ad83c0e5b2d800b
[]
no_license
akash-akya/sicp-exercises
5125c1118c7f0e4400cb823508797fb67c745592
c28f73719740c2c495b7bc38ee8b790219482b67
refs/heads/master
2021-06-15T19:12:47.679967
2019-08-03T14:03:20
2019-08-03T14:03:20
136,158,517
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,081
scm
2.46.scm
#lang sicp ;; Exercise 2.46: A two-dimensional vector v running from the origin ;; to a point can be represented as a pair consisting of an x ;; -coordinate and a y -coordinate. Implement a data abstraction for ;; vectors by giving a constructor make-vect and corresponding ;; selectors xcor-vect and ycor-vect. In terms of your selectors and ;; constructor, implement procedures add-vect, sub-vect, and ;; scale-vect that perform the operations vector addition, vector ;; subtraction, and multiplying a vector by a scalar: ;; (x1,y1) + (x2,y2) = (x1+x2, y1+y2), ;; (x1,y1) − (x2,y2) = (x1−x2, y1−y2), ;; s⋅(x,y) = (sx,sy) (define (make-vect x y) (cons x y)) (define (xcor-vect v) (car v)) (define (ycor-vect v) (cdr v)) (define (add-vect a b) (cons (+ (xcor-vect a) (xcor-vect b)) (+ (ycor-vect a) (ycor-vect b)))) (define (sub-vect a b) (cons (- (xcor-vect a) (xcor-vect b)) (- (ycor-vect a) (ycor-vect b)))) (define (scale-vect s a) (cons (* (xcor-vect a) s) (+ (ycor-vect a) s)))
false
8773ebb909370bd6ebe16834579bba70b358707c
1645add1bc3f780e0deaf3ca323b263037065c8f
/tests/selmaho/si.scm
5d01e777e69bd9f02657b11e22977eb3c6557c32
[ "ISC" ]
permissive
alanpost/jbogenturfahi
b4c57e80000d30bc6c0dff54ee780264a201006e
7a6b50eb13ab5bd4d0d6122638c4a63a55e59aef
refs/heads/master
2020-12-24T14:27:34.229766
2013-01-04T19:38:49
2013-01-04T19:38:49
1,044,613
3
1
null
null
null
null
UTF-8
Scheme
false
false
6,527
scm
si.scm
;;;; ;;;; jbogenturfahi - lo lojbo ke pe'a jajgau ratcu ke'e genturfa'i ;;;; `-> A Lojban grammar parser ;;;; ;;;; Copyright (c) 2010 ".alyn.post." <[email protected]> ;;;; ;;;; Permission to use, copy, modify, and/or distribute this software for any ;;;; purpose with or without fee is hereby granted, provided that the above ;;;; copyright notice and this permission notice appear in all copies. ;;;; ;;;; THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES ;;;; WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF ;;;; MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ;;;; ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;;;; WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ;;;; ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF ;;;; OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ;;;; (define (si) ; test si handling for all gismu ; (define (gismu-si gismu) (define (gismu=? valsi) (string=? gismu valsi)) (let ((gismu-si-gismu (string-append gismu " si " gismu))) (mapti `(text (si-clause (gismu ,(? gismu=? _)) (SI-clause (cmavo (SI "si")))) (paragraphs (paragraph (sentence (selbri (BRIVLA-clause (gismu ,(? gismu=? _)))))))) gismu-si-gismu))) ; test si handling for all cmavo ; (define (cmavo-si selmaho cmavo) (define (selmaho=? valsi) (string=? selmaho (symbol->string valsi))) (define (cmavo=? valsi) (string=? cmavo valsi)) (let ((cmavo-si (string-append cmavo " si"))) (case (string->symbol selmaho) ; FAhO termnates the text before SI erases it. ; ((FAhO) (mapti '(text (FAhO-clause (cmavo (FAhO "fa'o")))) cmavo-si)) ; SA swallows back to the beginning of text before ; SI can erase it. ; ((SA) (mapti '(text (si-clause (SA-clause (cmavo (SA "sa"))) (SI-clause (cmavo (SI "si"))))) cmavo-si)) ; Each of these clauses run individually, both acting ; as if they are at the beginning of the text. ; ((SI) (mapti '(text (SI-clause (cmavo (SI "si"))) (SI-clause (cmavo (SI "si")))) cmavo-si)) ; Each of these clauses run individually, both acting ; as if they are at the beginning of the text. ; ((SU) (mapti '(text (su-clause (SU-clause (cmavo (SU "su")))) (SI-clause (cmavo (SI "si")))) cmavo-si)) ; ZO quotes SI. ; ((ZO) (mapti '(text (paragraphs (paragraph (term (sumti (ZO-clause (cmavo (ZO "zo")) (cmavo (SI "si")))))))) cmavo-si)) ; everything else is erased by SI. ; (else (mapti `(text (si-clause (cmavo ,((? selmaho=? _) (? cmavo=? _))) (SI-clause (cmavo (SI "si"))))) cmavo-si))))) ; SI at the beginning of the text is not in error, but has no ; effect. ; (mapti '(text (SI-clause (cmavo (SI "si")))) "si") (mapti '(text (SI-clause (cmavo (SI "si"))) (SI-clause (cmavo (SI "si")))) "si si") (mapti '(text (SI-clause (cmavo (SI "si"))) (SI-clause (cmavo (SI "si"))) (SI-clause (cmavo (SI "si")))) "si si si") ; bu by itself is not grammatical, but si can erase it. ; (mapti '(text (si-clause (cmavo (BU "bu")) (SI-clause (cmavo (SI "si"))))) "bu si") ; ; broda bu is a single word. ; ; ; (mapti ; '(text (si-clause (cmavo (BU "bu")) ; (SI-clause (cmavo (SI "si"))))) ; "broda bu si") ; ; LOhU ... LEhU is a single word for purposes of SI erasure. ; ; ; (mapti ; '(text (si-clause ; (any-string (cmavo (LOhU "lo'u")) ; (cmavo (LEhU "le'u"))) ; (SI-clause (cmavo (SI "si"))))) ; ; "lo'u le'u si") ; {zei si} is an ungrammatical use of zei, but it is still ; treated as a single word, just like {bu si}. ; (mapti '(text (si-clause (cmavo (ZEI "zei")) (SI-clause (cmavo (SI "si"))))) "zei si") ; zei is a single word for purposes of si. ; (mapti '(text (si-clause (brivla (gismu "broda") (ZEI-clause (cmavo (ZEI "zei"))) (gismu "brode")) (SI-clause (cmavo (SI "si"))))) "broda zei brode si") (mapti '(text (si-clause (brivla (gismu "broda") (ZEI-clause (cmavo (ZEI "zei"))) (gismu "brode") (ZEI-clause (cmavo (ZEI "zei"))) (gismu "brodi")) (SI-clause (cmavo (SI "si"))))) "broda zei brode zei brodi si") (mapti '(text (si-clause (brivla (gismu "broda") (ZEI-clause (cmavo (ZEI "zei"))) (gismu "brode") (ZEI-clause (cmavo (ZEI "zei"))) (gismu "brodi") (ZEI-clause (cmavo (ZEI "zei"))) (gismu "brodo")) (SI-clause (cmavo (SI "si"))))) "broda zei brode zei brodi zei brodo si") ; {zo si} is the word {si}, but {zo si si} erases it. ; (mapti '(text (paragraphs (paragraph (term (sumti (ZO-clause (cmavo (ZO "zo")) (cmavo (SI "si")))))))) "zo si") (mapti '(text (si-clause (any-word (cmavo (ZO "zo")) (cmavo (SI "si"))) (SI-clause (cmavo (SI "si"))))) "zo si si") (let ((rodacmavo (cmavo:gen-select-list))) (map-apply cmavo-si (rodacmavo))) (let ((rodagismu (gismu:gen-select-list))) (map (compose gismu-si car) (rodagismu))) 0) (test-group "selma'o SI" (si))
false
f17ace14f1d4b5188128fe5dd320bf49ae7184ad
ca3425fbd3bef3cd7adeb7b1f61f00afd097927f
/planet/galore.plt/2/2/list-set.scm
f259503db1c30475e5ea2d1b5307bc8d3e1a95d6
[]
no_license
soegaard/little-helper
b330ec4382b958cd83b65e93c27581f5dc941c97
26249c688e5adf1e2535c405c6289030eff561b4
refs/heads/master
2021-01-16T18:06:35.491073
2011-08-11T23:00:56
2011-08-11T23:00:56
2,187,791
10
0
null
null
null
null
UTF-8
Scheme
false
false
11,118
scm
list-set.scm
;;; list-set.scm -- Jens Axel Søgaard (module list-set mzscheme ;(print-struct #t) (require (lib "67.ss" "srfi") ; compare (all-except (lib "list.ss") empty empty? remove remove*) (lib "26.ss" "srfi") (lib "42.ss" "srfi")) ;; an LSET consists of a compare functions ;; and a sorted (w.r.t to the compare function) ;; list of elements (define-struct lset (compare elements) (make-inspector)) ; set? : object -> boolean (define (set? o) (lset? o)) ; empty : [compare] -> set (define empty (case-lambda [() (empty (current-compare))] [(cmp) (make-lset cmp '())])) ; empty? : set -> boolean (define (empty? s) (null? (lset-elements s))) ; find-min : set -> element (define (find-min s) (when (empty? s) (error 'find-min "an empty set does not have a minimum element")) (car (lset-elements s))) (define (delete-min s) (delete (find-min s) s)) ; singleton : [compare] element -> set (define singleton (case-lambda [(x) (singleton (current-compare) x)] [(cmp x) (make-lset cmp (list x))])) ; elements : set -> list (define (elements s) (lset-elements s)) ; select : set -> element (define (select s) (if (empty? s) (error 'select "can't select an element from an empty set") (car (lset-elements s)))) ; size : set -> integer (define (size s) (length (elements s))) ; list-sorted? : compare list -> boolean (define (list-sorted? cmp xs) (or (null? xs) (null? (cdr xs)) (and (if<=? cmp (car xs) (cadr xs)) (list-sorted? cmp (cdr xs))))) ; list-merge : compare list list -> list ; merge two cmp-sorted lists (define (list-merge cmp xs ys) (cond [(null? xs) ys] [(null? ys) xs] [else (let ([x (car xs)] [y (car ys)]) (if<=? (cmp x y) (cons x (list-merge cmp (cdr xs) ys)) (cons y (list-merge cmp xs (cdr ys)))))])) ; list-split : list -> list list ; splits a list xs into two lists ys and zs, ; s.t. ys and zs are half as long as xs ; and (append ys zs) is a permutation of xs (define (list-split xs) (cond [(null? xs) (values '() '())] [(null? (cdr xs)) (values xs '())] [else (let-values ([(ys zs) (list-split (cddr xs))]) (values (cons (car xs) ys) (cons (cadr xs) zs)))])) ; list-sort : compare list -> list (define (list-sort cmp xs) (cond [(null? xs) '()] [(null? (cdr xs)) xs] [else (let-values ([(ys zs) (list-split xs)]) (list-merge cmp (list-sort cmp ys) (list-sort cmp zs)))])) (define (union s1 s2) (let ([cmp (lset-compare s1)]) (make-lset cmp (list-union cmp (elements s1) (elements s2))))) (define (union/combiner s1 s2 combine) (let ([cmp (lset-compare s1)]) (make-lset cmp (list-union/combiner cmp (elements s1) (elements s2) combine)))) (define (intersection s1 s2) (let ([cmp (lset-compare s1)]) (make-lset cmp (list-intersection cmp (elements s1) (elements s2))))) (define (intersection/combiner s1 s2 combine) (let ([cmp (lset-compare s1)]) (make-lset cmp (list-intersection/combiner cmp (elements s1) (elements s2) combine)))) (define (difference s1 s2) (let ([cmp (lset-compare s1)]) (make-lset cmp (list-difference cmp (elements s1) (elements s2))))) (define (subset? s1 s2) (let ([cmp (lset-compare s1)]) (list-subset? cmp (elements s1) (elements s2)))) (define (equal=? s1 s2) (let ([cmp (lset-compare s1)]) (list-equal=? cmp (elements s1) (elements s2)))) ; list-union : compare list list -> list (define (list-union cmp xs ys) (list-union/combiner cmp xs ys (lambda (x y) x))) ; list-union/combiner : compare list list (element element -> element) -> list (define (list-union/combiner cmp xs ys combine) ; xs and ys are cmp-sorted (cond [(null? xs) ys] [(null? ys) xs] [else (let ([x (car xs)] [y (car ys)]) (if3 (cmp x y) (cons x (list-union/combiner cmp (cdr xs) ys combine)) (cons (combine x y) (list-union/combiner cmp (cdr xs) (cdr ys) combine)) (cons y (list-union/combiner cmp xs (cdr ys) combine))))])) ; list-intersection : compare list list -> list (define (list-intersection cmp xs ys) (list-intersection/combiner cmp xs ys (lambda (x y) x))) ; list-intersection/combiner : compare list list (element element -> element) -> list (define (list-intersection/combiner cmp xs ys combine) ; xs and ys are cmp-sorted (cond [(null? xs) '()] [(null? ys) '()] [else (let ([x (car xs)] [y (car ys)]) (if3 (cmp x y) (list-intersection/combiner cmp (cdr xs) ys combine) (cons (combine x y) (list-intersection/combiner cmp (cdr xs) (cdr ys) combine)) (list-intersection/combiner cmp xs (cdr ys) combine)))])) ; list-difference : compare list list -> list (define (list-difference cmp xs ys) ; xs and ys are cmp-sorted (cond [(null? ys) xs] [(null? xs) '()] [else (let ([x (car xs)] [y (car ys)]) (if3 (cmp x y) (cons x (list-difference cmp (cdr xs) ys)) (list-difference cmp (cdr xs) (cdr ys)) (list-difference cmp xs (cdr ys))))])) ; list-insert : compare element list -> list ; given x and the cmp-sorted list xs, ; returns (sort cmp (cons x xs)) (define (list-insert cmp x xs) ; insert x into xs, which is sorted w.r.t. cmp (cond [(null? xs) (list x)] [else (let ([y (car xs)]) (if3 (cmp x y) (cons x xs) (cons x (cdr xs)) ; keep the last representative (cons y (list-insert cmp x (cdr xs)))))])) ; list-insert/combiner : compare element list (element element -> element) -> list ; given x and the cmp-sorted list xs, ; returns (sort cmp (cons x xs)) (define (list-insert/combiner cmp x xs combine) ; insert x into xs, which is sorted w.r.t. cmp (cond [(null? xs) (list x)] [else (let ([y (car xs)]) (if3 (cmp x y) (cons x xs) (cons (combine x y) (cdr xs)) (cons y (list-insert/combiner cmp x (cdr xs) combine))))])) (define (list-subset? cmp xs ys) (cond [(null? xs) #t] [(null? ys) #f] [else (let ([x (car xs)] [y (car ys)]) (if3 (cmp x y) #f (list-subset? cmp (cdr xs) (cdr ys)) (list-subset? cmp xs (cdr ys))))])) (define (list-equal=? cmp xs ys) (cond [(and (null? xs) (null? ys)) #t] [(null? xs) #f] [(null? ys) #f] [(cmp (car xs) (car ys)) (list-equal=? cmp (cdr xs) (cdr ys))] [else #f])) (define member? (case-lambda [(x s) (list-member? (lset-compare s) x (lset-elements s))] [(cmp x s) (if (eq? cmp (lset-compare s)) (member? x s) (member? x (list-sort cmp s)))])) (define get (case-lambda [(x s) (list-get (lset-compare s) x (lset-elements s))] [(cmp x s) (if (eq? cmp (lset-compare s)) (get x s) (get x (list-sort cmp s)))])) (define (insert x s) (let ([cmp (lset-compare s)]) (make-lset cmp (list-insert cmp x (lset-elements s))))) (define (insert/combiner x s combine) (let ([cmp (lset-compare s)]) (make-lset cmp (list-insert/combiner cmp x (lset-elements s) combine)))) (define (insert* xs s) (foldl insert s xs)) (define (insert*/combiner xs s combine) (foldl (lambda (x s) (insert/combiner x s combine)) s xs)) (define (list-member? cmp x xs) (and (not (null? xs)) (or (=? cmp x (car xs)) (and (not (<? cmp x (car xs))) (list-member? cmp x (cdr xs)))))) (define (list-get cmp x xs) (cond [(null? xs) #f] [else (if3 (cmp x (car xs)) #f (car xs) (list-get cmp x (cdr xs)))])) (define (delete x s) (difference s (singleton (lset-compare s) x))) (define (delete-all x s) (delete x s)) (define (delete* xs s) (difference s (list->set (lset-compare s) xs))) (define (fold f init s) (foldl f init (lset-elements s))) (define (list-remove-duplicates cmp xs) ; removes removes duplicates from an sorted list (cond [(null? xs) xs] [(null? (cdr xs)) xs] [(=? cmp (car xs) (cadr xs)) (list-remove-duplicates cmp (cdr xs))] [else (cons (car xs) (list-remove-duplicates cmp (cdr xs)))])) (define list->set (case-lambda [(xs) (list->set (current-compare) xs)] [(cmp xs) (foldl insert (empty cmp) xs)])) (define list->set/combiner (case-lambda [(xs combine) (list->set (current-compare) xs combine)] [(cmp xs combine) (foldl (lambda (x s) (insert/combiner x s combine)) (empty cmp) xs)])) (define (set . xs) (list->set xs)) ;; support for srfi-42 (define-syntax set-ec (syntax-rules () [(_ cmp etc1 etc ...) (fold-ec (empty cmp) etc1 etc ... insert)])) (define-syntax :set (syntax-rules (index) ((:set cc var (index i) arg) (:parallel cc (:stack var arg) (:integers i)) ) ((:set cc var arg) (:do cc (let ()) ((t (lset-elements arg))) (not (null? t)) (let ((var (car t)))) #t ((cdr t)) )))) (define (:set-dispatch args) (cond [(null? args) 'set] [(and (= (length args) 1) (set? (car args))) (:generator-proc (:set (car args)))] [else #f])) (:-dispatch-set! (dispatch-union (:-dispatch-ref) :set-dispatch)) ;;; PROVIDE SET FUNCTIONS (require "signatures/set-signature.scm") (provide-set) )
true
f1fac8646ba49046d2ff5c45c611614891e5f0ab
ae8b793a4edd1818c3c8b14a48ba0053ac5d160f
/Applications/mixins.scm
9108a5ddbe9af26bcb5411e15d42856920cc348a
[]
no_license
experimentsin/telosis
e820d0752f1b20e2913f6f49c0e2a4023f5eda97
4b55140efa8fc732291d251f18f1056dc700442f
refs/heads/master
2020-04-19T08:32:05.037165
2013-07-13T18:59:36
2013-07-13T18:59:36
11,391,770
1
0
null
null
null
null
UTF-8
Scheme
false
false
2,867
scm
mixins.scm
;; Approximation of Harry's mixins. We get most of this for free from the ;; default simple MI behaviour. (define-metaclass <base-class> (<class>) () predicate base-class?) (define-method (compatible-superclass? (sub <base-class>) (sup <class>)) #t) (define-method (compatible-superclasses? (c <base-class>) supers) (when (null? supers) (telos-error "Base classes must have at least one superclass" c supers)) (let* ((len (length supers)) (mix (rest supers)) (base (first supers))) (unless (all? mixin-class? mix) (telos-error "Non-mixin class in mixin superclass position" c mix)) (when (mixin-class? base) (telos-error "Mixin class in base class position" c base)) (call-next-method))) (define-metaclass <mixin-class> (<abstract-class>) () predicate mixin-class?) (define-method (allocate (mc <mixin-class>) init-list) ;; The inherited method from <abstract-class> outlaws this but I want a ;; more specific error message. (telos-error "Attempted to allocate a direct instance of a mixin class" mc)) (define-method (compatible-superclass? (sub <mixin-class>) (sup <class>)) (eq? sup <object>)) (define-method (compatible-superclass? (sub <mixin-class>) (sup <mixin-class>)) #t) ;; Macros... (define-telos-syntax (define-base-class name supers slots . class-ops) `(define-class ,name ,(reverse supers) ,slots metaclass <base-class> ,@class-ops)) (define-telos-syntax (define-mixin-class name supers slots . class-ops) `(define-class ,name ,supers ,slots metaclass <mixin-class> ,@class-ops)) ;; --- ;; Tests (ugh)... ;;; Define a base-class Point: (define-base-class <Point> (<object>) ((x initform 0 accessor point-x) (y initform 0 accessor point-y)) initargs (x y)) ;;; Define a mixin-class colored (independent from Point): (define-mixin-class <colored> () ((color initform 'black)) initargs (color)) (define-generic (color-of (obj <colored>)) method (((obj <object>)) 'gray) method (((obj <colored>)) (slot-value obj 'color))) (define-generic (change-color (obj <colored>) color) method (((obj <object>) color) (telos-warning "Can't change the color of an uncolored object" obj color) 'gray) method (((obj <colored>) color) (set-slot-value! obj 'color color))) ;;; Define a mixin-class green-colored: (define-mixin-class <green-colored> (<colored>) (((specialise color) initform 'green))) (define-method (change-color (obj <green-colored>) color) (unless (eq? color 'green) (telos-warning "Wrong color for a green-colored object" obj color)) 'green) ;;; Define some special Point classes: (define-base-class <colored-Point> (<colored> <Point>) ()) (define-base-class <green-Point> (<green-colored> <Point>) ())
false
6bb89a8b7aa552f1e97ba824fc645d0c7e51e99e
5355071004ad420028a218457c14cb8f7aa52fe4
/1.3/e-1.31.scm
2d9cbb1cd655bdc6c40c063628e3707bca63a8bc
[]
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,653
scm
e-1.31.scm
; Exercise 1.31 ; ; a. The sum procedure is only the simplest of a vast number of similar abstractions ; that can be captured as higher-order procedures. Write an analogous procedure ; called product that returns the product of the values of a function at points over ; a given range. Show how to define factorial in terms of product. Also use product ; to compute approximations to value of pi using the formula. ; ; pi 2 * 4 * 4 * 6 * 6 * 8 ... ; -- = ------------------------- ; 4 3 * 3 * 5 * 5 * 7 * 7 ... ; ; b. If your product procedure generates a recursive process, write one that generates ; an iterative process. If it generates an iterative process, write one that generates ; a recursive process. ; ; ---------------------------------------------------------------------------------- ; (load "../common.scm") ; definition of the product (define (product term a next b) (if (> a b) 1 (* (term a) (product term (next a) next b)))) (define (fact n) (define (identity x) x) (define (next x) (+ x 1)) (product identity 1 next n)) ; (display (fact 10)) ; 3628800 ; (newline) (define (pi n) (define (next x) (+ x 2)) (* 4.0 (/ (* 2 (product square 4 next (- n 2)) n ) (product square 3 next n)))) ; (display (pi 400)) ; approximates to 3.14 ; (newline) ; iterative process definition (define (product term a next b) (define (iter a result) (if (> a b) result (iter (next a) (* result (term a))))) (iter a 1)) ; Now we can execute approximation of pi with better precision since we use less memory ; (display (pi 4000)) ; ; (newline)
false
a373de66571813e894b464b3fd01effb5475071c
ac2a3544b88444eabf12b68a9bce08941cd62581
/contrib/GambitREPL/zlib#.scm
8a6efbcc20a454d8fe5dab0898eebe4c30a15ceb
[ "Apache-2.0", "LGPL-2.1-only" ]
permissive
tomelam/gambit
2fd664cf6ea68859d4549fdda62d31a25b2d6c6f
d60fdeb136b2ed89b75da5bfa8011aa334b29020
refs/heads/master
2020-11-27T06:39:26.718179
2019-12-15T16:56:31
2019-12-15T16:56:31
229,341,552
1
0
Apache-2.0
2019-12-20T21:52:26
2019-12-20T21:52:26
null
UTF-8
Scheme
false
false
506
scm
zlib#.scm
;;;============================================================================ ;;; File: "zlib#.scm" ;;; Copyright (c) 2006-2012 by Marc Feeley, All Rights Reserved. ;;;============================================================================ (##namespace ("zlib#" gzip-genport deflate-genport gzip-u8vector gunzip-genport inflate-genport gunzip-u8vector make-zlib-condition zlib-condition? zlib-condition-msg )) ;;;============================================================================
false
f95be48d12d4795abd9937593f231319e354bae8
b1e061ea9c3c30f279231258d319f9eb6d57769e
/3.5.scm
b131642b237cd4eac63b5e498aff68d07ff0bf0e
[]
no_license
wat-aro/SICP
6be59d4e69e838cd789750b2df9e0aafd365552e
df5369189cae95eb6f2004af17359a72791e0aad
refs/heads/master
2021-01-21T13:03:11.818682
2016-04-27T08:33:08
2016-04-27T08:33:08
52,417,381
0
0
null
null
null
null
UTF-8
Scheme
false
false
23,797
scm
3.5.scm
(define true #t) (define false #f) ;; 3.5.1 (define (sum-primes a b) (define (iter count accum) (cond ((> count b) accum) ((prime? count) (iter (+ count 1) (+ count accum))) (else (iter (+ count 1) accum)))) (iter a 0)) (define (sum-primes a b) (accumulate + 0 (filter prime? (enumerate-interval a b)))) (define (stream-ref s n) (if (= n 0) (stream-car s) (stream-ref (stream-cdr s) (- n 1)))) (define (stream-for-each proc s) (if (stream-null? s) 'done (begin (proc (stream-car s)) (stream-for-each proc (stream-cdr s))))) (define (display-stream s) (stream-for-each display-line s)) (define (display-line x) (newline) (display x)) (define (stream-car stream) (car stream)) (define (stream-cdr stream) (force (cdr stream))) (define (stream-null? stream) (null? stream)) (define the-empty-stream '()) ;; (define (delay exp) ;; (memo-proc (lambda () exp))) (define-syntax delay (syntax-rules () ((_ exp) (memo-proc (lambda () exp))))) ;; (define (cons-stream a b) ;; (cons a ;; (lambda () b))) ;; (define (cons-stream a b) ;; (cons a (delay b))) (define-syntax cons-stream (syntax-rules () ((_ a b) (cons a (delay b))))) (define (stream-enumerate-interval low high) (if (> low high) the-empty-stream (cons-stream low (stream-enumerate-interval (+ low 1) high)))) (define (stream-filter pred stream) (cond ((stream-null? stream) the-empty-stream) ((pred (stream-car stream)) (cons-stream (stream-car stream) (stream-filter pred (stream-cdr stream)))) (else (stream-filter pred (stream-cdr stream))))) (define (force delayed-object) (delayed-object)) (define (memo-proc proc) (let ((already-run? false) (result false)) (lambda () (if (not already-run?) (begin (set! result (proc)) (set! already-run? true) result) result)))) ;; 3.50 (define (stream-map proc . argstreams) (if (stream-null? (car argstreams)) the-empty-stream (cons-stream (apply proc (map stream-car argstreams)) (apply stream-map (cons proc (map stream-cdr argstreams)))))) ;; 3.51 (define (show x) (display-line x) x) ;; 3.52 (define sum 0) (define (accum x) (set! sum (+ sum x)) sum) ;; (define x (stream-map show (stream-enumerate-interval 0 10))) (define seq (stream-map accum (stream-enumerate-interval 1 20))) (define y (stream-filter even? seq)) (define z (stream-filter (lambda (x) (= (remainder x 5) 0)) seq)) #| (stream-ref y 7) (display-stream z) メモ化しているためにseqを何回呼び出してもsumに何度も加算されることがない. メモ化していない場合はseqを参照するたびにsumに加算されていく. |# ;; 3.5.2 無限ストリーム (define (integers-starting-from n) (cons-stream n (integers-starting-from (+ n 1)))) (define integers (integers-starting-from 1)) (define (divisible? x y) (= (remainder x y) 0)) (define no-sevens (stream-filter (lambda (x) (not (divisible? x 7))) integers)) (stream-ref no-sevens 100) (define (fibgen a b) (cons-stream a (fibgen b (+ a b)))) (define fibs (fibgen 0 1)) (define (sieve stream) (cons-stream (stream-car stream) (sieve (stream-filter (lambda (x) (not (disible? x (stream-car stream)))) (stream-cdr stream))))) (define primes (sieve (integers-starting-from 2))) (define (sieve stream) (cons-stream (stream-car stream) (sieve (stream-filter (lambda (x) (not (divisible? x (car stream)))) (stream-cdr stream))))) (define primes (sieve (integers-starting-from 2))) (define ones (cons-stream 1 ones)) (define (add-streams s1 s2) (stream-map + s1 s2)) (define integers (cons-stream 1 (add-streams ones integers))) (define fibs (cons-stream 0 (cons-stream 1 (add-streams (stream-cdr fibs) fibs)))) (define (scale-stream stream factor) (stream-map (lambda (x) (* x factor)) stream)) (define double (cons-stream 1 (scale-stream double 2))) (define primes (cons-stream 2 (stream-filter prime? (integers-starting-from 3)))) (define (prime? n) (define (iter ps) (cond ((> (square (stream-car ps)) n) true) ((divisible? n (stream-car ps)) false) (else (iter (stream-cdr ps))))) (iter primes)) ;; 3.53 (define s (cons-stream 1 (add-streams s s))) ;; 2^nのストリーム ;; 3.54 (define (mul-streams s1 s2) (stream-map * s1 s2)) (define factorials (cons-stream 1 (mul-streams factorials (integers-starting-from 1)))) ;; 3.55 (define (partial-sums stream) (cons-stream (stream-car stream) (add-streams (stream-cdr stream) (partial-sums stream)))) (define sum-integers (partial-sums integers)) ;; 3.56 (define (merge s1 s2) (cond ((stream-null? s1) s2) ((stream-null? s2) s1) (else (let ((s1car (stream-car s1)) (s2car (stream-car s2))) (cond ((< s1car s2car) (cons-stream s1car (merge (stream-cdr s1) s2))) ((> s1car s2car) (cons-stream s2car (merge s1 (stream-cdr s2)))) (else (cons-stream s1car (merge (stream-cdr s1) (stream-cdr s2))))))))) (define S (cons-stream 1 (merge (scale-stream S 2) (merge (scale-stream S 3) (scale-stream S 5))))) ;; 3.57 (define fibs (cons-stream 0 (cons-stream 1 (add-streams (stream-cdr fibs) fibs)))) #| メモ化しているので(add-streams (stream-cdr fibs) fibs)の部分で加算が一回行われるだけで済んでいる. これがメモ化していない場合はfibsの値も(stream-cdr fibs)の値も0番目と1番目の値から加算して求めなくてはならない. |# ;; 3.58 (define (expand num den radix) (cons-stream (quotient (* num radix) den) (expand (remainder (* num radix) den) den radix))) #| (/ num den)を表す少数を生成する. (expand 1 7 10)は 1 4 2 8 5 7 (expand 3 8 10)は 3 7 5 0 つまり0.375で割り切れる. |# ;; 3.59 ;; a ;; 引数としてべき級数を表現するストリームをとり,級数の積分の定数項を除いた項の係数のストリーム (define (integrate-series stream) (stream-map / stream integers)) ;; b (define exp-series (cons-stream 1 (integrate-series exp-series))) ;; 余弦の微分は正弦なので ;; cos xの微分は-sin x (define cosine-series (cons-stream 0 (stream-map - (integrate-series sine-series)))) ;; 正弦の微分は余弦 ;; sin xの微分は cos x (define sine-series (cons-stream 1 (integrate-series cosine-series))) ;; 3.60 (define (stream-head s n) (let iter ((s s) (n n)) (if (zero? n) 'done (begin (display (stream-car s)) (newline) (iter (stream-cdr s) (- n 1)))))) (define (mul-series s1 s2) (cons-stream (* (stream-car s1) (stream-car s2)) (add-streams (scale-stream (stream-cdr s2) (stream-car s1)) (mul-series (stream-cdr s1) s2)))) (define circles (add-streams (mul-series sine-series sine-series) (mul-series cosine-series cosine-series))) ;; 3.61 (define (invert-unit-series stream) (cons-stream 1 (mul-series (scale-stream (stream-cdr s1) -1) (invert-unit-series stream)))) ;; 3.62 (define (div-stream s1 s2) (if (= s2 0) (error "ZERO-DIVISOR" s2) (mul-streams s1 (invert-unit-series s2)))) ;; 3.5.3 (define (sqrt-stream x) (define guesses (cons-stream 1.0 (stream-map (lambda (guess) (sqrt-improve guess x)) guesses))) guesses) (define (pi-summands n) (cons-stream (/ 1.0 n) (stream-map - (pi-summands (+ n 2))))) (define pi-stream (scale-stream (partial-sums (pi-summands 1)) 4)) (define (euler-transform s) (let ((s0 (stream-ref s 0)) (s1 (stream-ref s 1)) (s2 (stream-ref s 2))) (cons-stream (- s2 (/ (square (- s2 s1)) (+ s0 (* -2 s1) s2))) (euler-transform (stream-cdr s))))) (define (make-tableau transform s) (cons-stream s (make-tableau transform (transform s)))) (define (accelerated-sequence transform s) (stream-map stream-car (make-tableau transform s))) ;; 3.63 (define (sqrt-stream x) (cons-stream 1.0 (stream-map (lambda (guess) (sqrt-improve guess x)) (sqrt-stream x)))) ;; 3.64 (define (sqrt-improve guess x) (average guess (/ x guess))) (define (average x y) (/ (+ x y) 2)) (define (stream-limit s tolerance) (let ((s1 (stream-car s)) (s2 (stream-car (stream-cdr s)))) (if (> tolerance (abs (- s1 s2))) s2 (stream-limit (stream-cdr s) tolerance)))) (define (sqrt x tolerance) (stream-limit (sqrt-stream x) tolerance)) ;; 3.65 (define (ln2-summands n) (cons-stream (/ 1.0 n) (stream-map - (ln2-summands (+ n 1))))) (define ln2-stream (partial-sums (ln2-summands 1))) (define (interleave s1 s2) (if (stream-null? s1) s2 (cons-stream (stream-car s1) (interleave s2 (stream-cdr s1))))) (define (pairs s t) (cons-stream (list (stream-car s) (stream-car t)) (interleave (stream-map (lambda (x) (list (stream-car s) x)) (stream-cdr t)) (pairs (stream-cdr s) (stream-cdr t))))) (define (stream-append s1 s2) (if (stream-null? s1) s2 (cons-stream (stream-car s1) (stream-append (stream-cdr s1) s2)))) ;; 3.67 ;; interleave (define (pairs s t) (cons-stream (list (stream-car s) (stream-car t)) (interleave (interleave (stream-map (lambda (x) (list (stream-car s) x)) (stream-cdr t)) (stream-map (lambda (x) (list x (stream-car s))) (stream-cdr t))) (pairs (stream-cdr s) (stream-cdr t))))) ;; 三つのストリームを混ぜるinterleave (define (interleave3 s1 s2 s3) (if (stream-null? s1) (interleave s2 s3) (cons-stream (stream-car s1) (interleave3 s2 s3 (stream-cdr s1))))) ;; interleave3を使う (define (pairs s t) (cons-stream (list (stream-car s) (stream-car t)) (interleave3 (stream-map (lambda (x) (list (stream-car s) x)) (stream-cdr t)) (stream-map (lambda (x) (list x (stream-car s))) (stream-cdr t)) (pairs (stream-cdr s) (stream-cdr t))))) ;; 3.68 #| (define (pairs s t) (interleave (stream-map (lambda (x) (list (stream-car s) x)) t) (pairs (stream-cdr s) (stream-cdr t)))) |# ;; 3.69 (define (triples s t u) (cons-stream (list (stream-car s) (stream-car t) (stream-car u)) (interleave (interleave (stream-map (lambda (x) (cons (stream-car s) x)) (pairs (stream-cdr t) (stream-cdr u))) (stream-map (lambda (x) (list (stream-car s) (stream-car t) x)) (stream-cdr u))) (triples (stream-cdr s) (stream-cdr t) (stream-cdr u))))) (define pythagoras (stream-filter (lambda (x) (= (+ (square (car x)) (square (cadr x))) (square (caddr x)))) (triples integers integers integers))) ;; 3.70 ;; mergeを参考にして重みをつけてmerge-weightedを定義する (define (merge s1 s2) (cond ((stream-null? s1) s2) ((stream-null? s2) s1) (else (let ((s1car (stream-car s1)) (s2car (stream-car s2))) (cond ((< s1car s2car) (cons-stream s1car (merge (stream-cdr s1) s2))) ((> s1car s2car) (cons-stream s2car (merge s1 (stream-cdr s2)))) (else (cons-stream s1car (merge (stream-cdr s1) (stream-cdr s2))))))))) (define (merge-weighted s1 s2 weight) (cond ((stream-null? s1) s2) ((stream-null? s2) s1) (else (let ((s1car (stream-car s1)) (s2car (stream-car s2))) (let ((w1 (weight s1car)) (w2 (weight s2car))) (cond ((< w1 w2) (cons-stream s1car (merge-weighted (stream-cdr s1) s2 weight))) (else (cons-stream s2car (merge-weighted s1 (stream-cdr s2) weight))))))))) ;; pairsを参考にweighted-pairsを定義する (define (pairs s t) (cons-stream (list (stream-car s) (stream-car t)) (interleave (stream-map (lambda (x) (list (stream-car s) x)) (stream-cdr t)) (pairs (stream-cdr s) (stream-cdr t))))) (define (weighted-pairs s t weight) (cons-stream (list (stream-car s) (stream-car t)) (merge-weighted (stream-map (lambda (x) (list (stream-car s) x)) (stream-cdr t)) (weighted-pairs (stream-cdr s) (stream-cdr t) weight) weight))) (define i+j (weighted-pairs integers integers (lambda (x) (+ (car x) (cadr x))))) (define 2i+3j+5ij (weighted-pairs integers integers (lambda (x) (+ (* 2 (car x)) (* 3 (cadr x)) (* 5 (car x) (cadr x)))))) ;; 重みづけがちゃんと機能しているかを確認する (define (stream-head-weight s n weight) (let iter ((s s) (n n)) (if (zero? n) 'done (begin (display (stream-car s)) (display " : ") (display (weight (stream-car s))) (newline) (iter (stream-cdr s) (- n 1)))))) ;; 3.71 (define (sum-cube x) (let ((a (car x)) (b (cadr x))) (+ (* a a a) (* b b b)))) (define (ramanujan stream) (let ((s1 (stream-car stream)) (s2 (stream-car (stream-cdr stream)))) (let ((weight1 (sum-cube s1)) (weight2 (sum-cube s2))) (cond ((= weight1 weight2) (cons-stream weight1 (ramanujan (stream-cdr stream)))) (else (ramanujan (stream-cdr stream))))))) (define ramanujan-number (ramanujan (weighted-pairs integers integers sum-cube))) ;; 3.72 (define (sum-square x) (let ((a (car x)) (b (cadr x))) (+ (* a a) (* b b)))) (define (triple-way-sum-square stream) (let ((s1 (stream-car stream)) (s2 (stream-car (stream-cdr stream))) (s3 (stream-car (stream-cdr (stream-cdr stream))))) (let ((w1 (sum-square s1)) (w2 (sum-square s2)) (w3 (sum-square s3))) (cond ((= w1 w2 w3) (cons-stream w1 (triple-way-sum-square (stream-cdr (stream-cdr stream))))) (else (triple-way-sum-square (stream-cdr stream))))))) (define triple-way-sum-square-number (triple-way-sum-square (weighted-pairs integers integers sum-square))) ;; 信号としてのストリーム (define (integral integrand initial-value dt) (define int (cons-stream initial-value (add-streams (scale-stream integrand dt) int))) int) ;; 3.73 (define (RC R C dt) (lambda (i v0) (add-streams (scale-stream i R) (integral (scale-stream i (/ 1 C)) vo dt)))) ;; 3.74 (define (make-zero-crossings input-stream last-value) (cons-stream (sign-change-detector (stream-car input-stream) last-value) (make-zero-crossings (stream-cdr input-stream) (stream-car input-stream)))) (define zero-crossings (make-zero-crossings sense-data 0)) (define (stream-map proc . argstreams) (if (stream-null? (car argstreams)) the-empty-stream (cons-stream (apply proc (map stream-car argstreams)) (apply stream-map (cons proc (map stream-cdr argstreams)))))) (define zero-crossings (stream-map sign-change-detector sense-data (cons-stream 0 zero-crossings))) (define (sign-change-detector scar last) (cond ((and (<= 0 last) (< scar 0)) -1) ((and (< last 0) (<= 0 scar)) 1) (else 0))) ;; 3.75 #| (define (make-zero-crossings input-stream last-value) (let ((avpt (/ (+ (stream-car input-stream) last-value) 2))) (cons-stream (sign-change-detector avpt last-value) (make-zero-crossings (stream-cdr input-stream) avpt)))) ;; s1 s2 s3という順番でストリームが流れてくる時,この手続きでは ;; s1とs2の平均a1をとり,次のs3のところでa1とs3の平均を取る. ;; s2とs3の平均をとって欲しいので引数を一つ増やす. (define (make-zero-crossings input-stream last-value last-avpt) (let* ((s1 (stream-car input-stream)) (avpt (/ (+ s1 last-value) 2))) (cons-stream (sign-change-detector avpt last-avpt) (make-zero-crossings (stream-cdr input-stream) s1 avpt)))) |# ;; 3.76 (define (smooth stream) (cons-stream (average (car stream) 0) (stream-map average (stream-cdr stream) stream))) (define (make-zero-crossings sense-data) (let ((smooth-data (smooth sense-data))) (stream-map sign-change-detector smooth-data (cons-stream 0 smooth-data)))) ;; 3.5.4 (define int (cons-stream initial-value (add-streams (scale-stream integrand dt) int))) (define (integral delayed-integrand initial-value dt) (define int (cons-stream initial-value (let ((integrand (force delayed-integrand))) (add-streams (scale-stream integrand dt) int)))) int) (define (solve f y0 dt) (define y (integral (delay dy) y0 dt)) (define dy (stream-map f y)) y) ;; 3.77 (define (integral integrand initial-value dt) (cons-stream initial-value (if (stream-null? integrand) the-empty-stream (integral (stream-cdr integrand) (+ (* dt (stream-car integrand)) initial-value) dt)))) (define (integral delayed-integrand initial-value dt) (cons-stream initial-value (let ((integrand (force delayed-integrand))) (if (stream-null? integrand) the-empty-stream (integral (delay (stream-cdr integrand)) (+ (* dt (stream-car integrand)) initial-value) dt))))) ;; 3.78 (define (solve-2nd a b dt y0 dy0) (define y (integral (delay dy) y0 dt)) (define dy (integral (delay ddy) dy0 dt)) (define ddy (add-streams (scale-stream dy a) (scale-stream y b))) y) ;; 3.79 (define (solve-2nd f dt h0 dy0) (define y (integral (delay dy) y0 dt)) (define dy (integral (delay ddy) dy0 dt)) (define ddy (stream-map f y dy)) y) ;; 3.80 (define (RC R C dt) (lambda (i v0) (add-streams (scale-stream i R) (integral (scale-stream i (/ 1 C)) vo dt)))) (define (integral delayed-integrand initial-value dt) (cons-stream initial-value (let ((integrand (force delayed-integrand))) (if (stream-null? integrand) the-empty-stream (integral (delay (stream-cdr integrand)) (+ (* dt (stream-car integrand)) initial-value) dt))))) (define (RLC R L C dt) (lambda (vC0 iL0) (define vC (integral (delay dvC) vC0 dt)) (define iL (integral (delay diL) iL0 dt)) (define dvC (scale-stream iL (/ -1 C))) (define diL (add-streams (scale-stream iL (- (/ R L))) (scale-stream vC (/ 1 L)))) (stream-map (lambda (x y) (cons x y)) vC iL))) (define RLC1 (RLC 1 1 0.2 0.1)) ;; 3.5.5 (define (rand (let ((x random-init)) (lambda () (set! x (rand-update x)) x)))) (use srfi-27) (define random-init 100) (define (rand-update x) (modulo (+ (* x 1103515245) 12345) 2147483647)) (define random-numbers (cons-stream random-init (stream-map rand-update random-numbers))) (define cesaro-stream (map-successive-pairs (lambda (r1 r2) (= (gcd r1 r2) 1)) random-numbers)) (define (map-successive-pairs f s) (cons-stream (f (stream-car s) (stream-car (stream-cdr s))) (map-successive-pairs f (stream-cdr (stream-cdr s))))) (define (monte-carlo experiment-stream passed failed) (define (next passed failed) (cons-stream (/ passed (+ passed failed)) (monte-carlo (stream-cdr experiment-stream) passed failed))) (if (stream-car experiment-stream) (next (+ passed 1) failed) (next passed (+ failed 1)))) ;; これを評価すると0割でエラー ;; monte-carloで一回でもtrueが出ないと分子が増えなくて0になる. (define pi (stream-map (lambda (p) (sqrt (/ 6 p))) (monte-carlo cesaro-stream 0 0))) ;; 3.81 (use srfi-19) (define (rand-update x) (modulo (+ (* x 1103515245) 12345) 2147483647)) ;; 命令のストリームを引数にとる (define (rand stream) (define (randoming s) (if (number? s) (random-update (time-nanosecond (current-time))) (random-update s))) (define random-stream (if (stream-null? stream) the-empty-stream (let ((s1 (stream-car stream))) (cons-stream (if (number? s1) (rand-update s1) (rand-update (time-nanosecond (current-time)))) (stream-map randoming random-stream))))) random-stream) ;; 3.82 (define (random-in-range x1 x2) (+ x1 (random-integer (- x2 x1)))) (define (estimate-integral p x1 x2 y1 y2) (stream-map (lambda (n) (* n (- x2 x1) (- y2 y1))) (monte-carlo (stream-map p (stream-map (lambda (x) (random-in-range x1 x2)) integers) (stream-map (lambda (x) (random-in-range y1 y2)) integers)) 0.0 0.0))) (define (make-simplified-withdraw balance) (lambda (amount) (set! balance (- balance amount)) balance)) (define (stream-withdraw balance amount-stream) (cons-stream balance (stream-withdraw (-balance (stream-car amount-stream)) (stream-cdr amount-stream))))
true
bd0079828df07891935b3ea791391d868be899f7
f08220a13ec5095557a3132d563a152e718c412f
/logrotate/skel/usr/share/guile/2.0/ice-9/list.scm
1b898a36886de84d2f1515cd92e4a6b90ede198f
[ "Apache-2.0" ]
permissive
sroettger/35c3ctf_chals
f9808c060da8bf2731e98b559babd4bf698244ac
3d64486e6adddb3a3f3d2c041242b88b50abdb8d
refs/heads/master
2020-04-16T07:02:50.739155
2020-01-15T13:50:29
2020-01-15T13:50:29
165,371,623
15
5
Apache-2.0
2020-01-18T11:19:05
2019-01-12T09:47:33
Python
UTF-8
Scheme
false
false
1,319
scm
list.scm
;;;; List functions not provided in R5RS or srfi-1 ;;; Copyright (C) 2003, 2006 Free Software Foundation, Inc. ;;; ;;;; This library is free software; you can redistribute it and/or ;;;; modify it under the terms of the GNU Lesser General Public ;;;; License as published by the Free Software Foundation; either ;;;; version 3 of the License, or (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; Lesser General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Lesser General Public ;;;; License along with this library; if not, write to the Free Software ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA (define-module (ice-9 list) :export (rassoc rassv rassq)) (define (generic-rassoc key alist =) (let loop ((ls alist)) (and (not (null? ls)) (if (= key (cdar ls)) (car ls) (loop (cdr ls)))))) (define (rassoc key alist . =) (generic-rassoc key alist (if (null? =) equal? (car =)))) (define (rassv key alist) (generic-rassoc key alist eqv?)) (define (rassq key alist) (generic-rassoc key alist eq?))
false
c940c79fe1c643b3ddd943ce2597b0c78687b47e
757b4590bf0dd48a8d6131c1c2247d9c01946233
/transformation-from-direct-mk/3/tests.scm
70081c34083f57aae24a0136a7cac6ae31d94d0f
[]
no_license
localchart/relational-cesk
f9f52872050280f941a471ce2746c536539be08c
c2c7d27bc85bb7ca403c9f6d80d07d7cb00a3a77
refs/heads/master
2020-12-26T00:07:54.263812
2013-07-15T21:45:01
2013-07-15T21:45:01
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
5,143
scm
tests.scm
(load "interp.scm") (define-syntax test-check (syntax-rules () ((_ title tested-expression expected-result) (begin (printf "Testing ~s\n" title) (let* ((expected expected-result) (produced tested-expression)) (or (equal? expected produced) (errorf 'test-check "Failed: ~a~%Expected: ~a~%Computed: ~a~%" 'tested-expression expected produced))))))) (define quinec '((lambda (x) (list x (list (quote quote) x))) (quote (lambda (x) (list x (list (quote quote) x)))))) (define replace* (lambda (al x) (cond [(null? x) '()] [(symbol? x) (cond [(assq x al) => cdr] [else x])] [(pair? x) (cons (replace* al (car x)) (replace* al (cdr x)))] [(boolean? x) x] [(string? x) x] [else (error 'replace* (format "unknown expression type: ~a\n" x))]))) (define replace-respect-quote* (lambda (al x) (cond [(null? x) '()] [(symbol? x) (cond [(assq x al) => cdr] [else x])] [(pair? x) (if (eq? (car x) 'quote) x (cons (replace-respect-quote* al (car x)) (replace-respect-quote* al (cdr x))))] [(boolean? x) x] [(string? x) x] [else (error 'replace-respect-quote* (format "unknown expression type: ~a\n" x))]))) (test-check "var-1" (run* (q) (eval-expo 'y '((y . 5)) '((5 . (closure z z ()))) q)) '(((closure z z ()) . ((5 . (closure z z ())))))) (test-check "lambda-1" (run* (q) (eval-expo '(lambda (x) x) '() '() q)) '(((closure x x ()) . ()))) (test-check "lambda-2" (run* (q) (eval-expo '(lambda (x) (lambda (y) (x y))) '() '() q)) '(((closure x (lambda (y) (x y)) ()) . ()))) (test-check "quote-1" (run* (q) (eval-expo '(quote (lambda (x) x)) '() '() q)) '(((lambda (x) x) . ()))) (test-check "app-1" (run* (q) (eval-expo '((lambda (x) x) (lambda (y) y)) '() '() q)) '((((closure y y ()) . ((_.0 . (closure y y ())))) (num _.0)))) (test-check "extend-3" (run* (q) (eval-expo '((lambda (quote) (quote (lambda (x) x))) (lambda (y) y)) '() '() q)) '((((closure x x ((quote . _.0))) . ((_.1 . (closure x x ((quote . _.0)))) (_.0 . (closure y y ())))) (=/= ((_.0 _.1))) (num _.0 _.1)))) (test-check "quinec" (run* (q) (eval-expo quinec '() '() q)) '(((((lambda (x) (list x (list 'quote x))) '(lambda (x) (list x (list 'quote x)))) . ((_.0 . (lambda (x) (list x (list 'quote x)))))) (num _.0)))) ;;; (test-check "improved-lookupo-0" (run 1 (q) (lookupo 'x '() '() q)) '()) (test-check "improved-lookupo-1" (run 1 (q) (lookupo 'x '((w . 0) (x . 1) (y . 2)) '((0 . foo) (1 . bar) (2 . baz)) q)) '(bar)) (test-check "improved-lookupo-2" (run* (q) (lookupo 'x '((w . 0) (x . 1) (y . 2)) '((0 . foo) (1 . bar) (2 . baz)) q)) '(bar)) (test-check "improved-lookupo-6" (run 1 (q) (lookupo q '((w . 0) (x . 1) (y . 2)) '((0 . foo) (1 . bar) (2 . baz)) 'foo)) '(w)) (test-check "improved-lookupo-7" (run 2 (q) (lookupo q '((w . 0) (x . 1) (y . 2)) '((0 . foo) (1 . bar) (2 . baz)) 'foo)) '(w)) (test-check "improved-lookupo-8" (run 1 (q) (lookupo q '((w . 0) (x . 1) (y . 2)) '((0 . foo) (1 . bar) (2 . baz)) 'quux)) '()) (test-check "improved-lookupo-9" (run 1 (q) (lookupo 'x '((w . 0) (y . 2)) '((0 . foo) (1 . bar) (2 . baz)) q)) '()) (test-check "improved-lookupo-10" (run 1 (q) (lookupo 'x '((w . 0) (x . 1) (y . 2)) '((0 . foo) (2 . baz)) q)) '()) (test-check "improved-lookupo-12" (run 1 (q) (lookupo 'x '((w . 0) (x . 1) (y . 2)) `((1 . foo) . ,q) 'baz)) '()) (test-check "improved-lookupo-13" ;;; this test-check diverges using naive lookupo (run 1 (q) (lookupo 'x `((w . 0) . ,q) '((1 . foo) (2 . bar)) 'baz)) '()) (test-check "improved-lookupo-13a" (run* (q) (lookupo 'x `((w . 0) . ,q) '((1 . foo) (2 . bar)) 'bar)) '(((x . 2) . _.0))) (test-check "improved-lookupo-14" (run 1 (q) (fresh (rest-e rest-s) (lookupo 'w `((w . 0) . ,rest-e) `((0 . foo) . ,rest-s) 'baz) (== `(,rest-e ,rest-s) q))) '()) ;;; (test-check "quinec-backwards-1" (run 5 (q) (eval-expo q '() '() quinec)) '('((lambda (x) (list x (list 'quote x))) '(lambda (x) (list x (list 'quote x)))) (list '(lambda (x) (list x (list 'quote x))) ''(lambda (x) (list x (list 'quote x)))) (((lambda (_.0) '((lambda (x) (list x (list 'quote x))) '(lambda (x) (list x (list 'quote x))))) '_.1) (=/= ((_.0 quote))) (sym _.0) (absento (closure _.1))) (((lambda (_.0) _.0) '((lambda (x) (list x (list 'quote x))) '(lambda (x) (list x (list 'quote x))))) (sym _.0)) (((lambda (_.0) '((lambda (x) (list x (list 'quote x))) '(lambda (x) (list x (list 'quote x))))) (list)) (=/= ((_.0 quote))) (sym _.0)))) (test-check "quinec-backwards-2" (run 1 (q) (eval-expo q '() '() quinec) (== quinec q)) '(((lambda (x) (list x (list 'quote x))) '(lambda (x) (list x (list 'quote x)))))) (test-check "intro-2" ;;; appears to diverge, due to lookupo (run 1 (q) (eval-expo q '() '() q)) '??? )
true
fb23e5f13c7d192f01db6d9e23b51d873005f048
4e64a8ed146a67f0d35d34a3c2d7af266d35e1eb
/scheme/scheme_files/test_cons.scm
539febd19dd0d8ee4147c54cf9aacc6e48329529
[]
permissive
svenkeidel/sturdy
0900f427f8df1731be009ee4f18051e1e93356b4
4962b9fbe0dab0a7b07f79fe843f4265c782e007
refs/heads/master
2023-07-05T22:00:22.524391
2023-06-23T04:05:50
2023-06-23T04:06:14
126,147,527
55
8
BSD-3-Clause
2023-05-22T10:18:35
2018-03-21T08:34:54
Pascal
UTF-8
Scheme
false
false
65
scm
test_cons.scm
(include-equals) (equal? (cdr (cdr '(2 3))) (cdr (cdr '(3 4))))
false
4c2aa79077473917b08730daa0f160a8d86d26d8
7301b8e6fbd4ac510d5e8cb1a3dfe5be61762107
/ex-4.1.scm
6dd969d08c8b0e6ad54b1eb9213fdf33c13a9249
[]
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,399
scm
ex-4.1.scm
;;; Exercise 4.1. Notice that we cannot tell whether the metacircular ;;; evaluator evaluates operands from left to right or from right to left. Its ;;; evaluation order is inherited from the underlying Lisp: If the arguments to ;;; cons in list-of-values are evaluated from left to right, then ;;; list-of-values will evaluate operands from left to right; and if the ;;; arguments to cons are evaluated from right to left, then list-of-values ;;; will evaluate operands from right to left. ;;; ;;; Write a version of list-of-values that evaluates operands from left to ;;; right regardless of the order of evaluation in the underlying Lisp. Also ;;; write a version of list-of-values that evaluates operands from right to ;;; left. ;; The original version. (define (list-of-values exps env) (if (no-operands? exps) '() (cons (eval (first-operand exps) env) (list-of-values (rest-operands exps) env)))) ;; Left-to-right version. (define (list-of-values exps env) (if (no-operands? exps) '() (let ((first-value (eval (first-operand exps) env))) (cons first-value (list-of-values (rest-operands exps) env))))) ;; Right-to-left version. (define (list-of-values exps env) (if (no-operands? exps) '() (let ((rest-values (list-of-values (rest-operands exps) env))) (cons (eval (first-operand exps) env) rest-values))))
false
5920d7b2af0d62102fc53f1627e087bfdb2287a0
ece1c4300b543df96cd22f63f55c09143989549c
/Chapter3/Exercise3.18.scm
e4a5ed92255dc5255fa4ed2ed1910688faa22bd5
[]
no_license
candlc/SICP
e23a38359bdb9f43d30715345fca4cb83a545267
1c6cbf5ecf6397eaeb990738a938d48c193af1bb
refs/heads/master
2022-03-04T02:55:33.594888
2019-11-04T09:11:34
2019-11-04T09:11:34
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,122
scm
Exercise3.18.scm
; Exercise 3.18: Write a procedure that examines a list and determines whether it contains a cycle, that is, whether a program that tried to find the end of the list by taking successive cdrs would go into an infinite loop. Exercise 3.13 constructed such lists. #lang planet neil/sicp (define (last-pair x) (if (null? (cdr x)) x (last-pair (cdr x)))) (define (make-cycle x) (set-cdr! (last-pair x) x) x) (define z (make-cycle (list 'a 'b 'c))) (define (cycle? x) (define marked_list '()) (define (cycle_inner x) (cond ((not (pair? x)) false) ((member x marked_list) true) (else (begin (set! marked_list (cons x marked_list)) (or (cycle_inner (cdr x)) (cycle_inner (car x))))))) (cycle_inner x)) (define x '(a b c)) (define y '(d e f)) (set-car! (cdr x) y) (set-car! x (cdr x)) (set-cdr! (last-pair y) (cdr y)) (cycle? (list 'a 'b 'c 'd)) (cycle? z) (cycle? x) (cycle? y) ; Welcome to DrRacket, version 6.7 [3m]. ; Language: SICP (PLaneT 1.18); memory limit: 128 MB. ; #f ; #t ; #t ; #t ; >
false
1ee709c326b26126fb965dd4eb76913c93fd05f3
a7a99f1f9124d23b04558fdac002f9153079b9c0
/sine/env-lexical.ss
4b9b81d9d35025337f8afc3870a09084cf383fa8
[]
no_license
stuhlmueller/sine
a451c3803283de220f3475dba4c6c1fcde883822
ce6ec938e8f46c31925f23b557284405c1ba0b11
refs/heads/master
2016-09-06T10:23:19.360983
2012-07-20T21:09:59
2012-07-20T21:10:11
3,517,254
4
0
null
null
null
null
UTF-8
Scheme
false
false
2,305
ss
env-lexical.ss
#!r6rs ;; Environments with lexical addressing based on mit-church/sicp (library (sine env-lexical) (export the-empty-environment extend-environment lookup-variable-value-and-id lookup-value-by-id lookup-variable-id) (import (rnrs) (scheme-tools srfi-compat :1) (scheme-tools srfi-compat :43) (scheme-tools value-number)) ;; -------------------------------------------------------------------- ;; Frame ADT (compressed) (define (make-frame variables values) (&vector (compress-recursive (list->vector variables)) (apply &vector values))) (define (first-frame &env) (&car &env)) (define (frame-variables frame) (&vector-ref frame 0)) (define (frame-values frame) (&vector-ref frame 1)) ;; -------------------------------------------------------------------- ;; Environment ADT (compressed) (define the-empty-environment (compress-null '())) (define (enclosing-environment env) (&cdr env)) (define (extend-environment vars vals &base-env) (&cons (make-frame vars vals) &base-env)) ;; -------------------------------------------------------------------- ;; Variable lookup ;; ;; Address is (frame-loc . var-loc) (define (lookup-variable-value-and-id var &top-env) (let ([frame-loc 0]) (define (env-loop &env) (define (find-var vars &vals) (let ([var-index (vector-index (lambda (v) (eq? v var)) vars)]) (if (not var-index) (begin (set! frame-loc (+ frame-loc 1)) (env-loop (enclosing-environment &env))) (cons (&vector-ref &vals var-index) (cons frame-loc var-index))))) (if (eq? &env the-empty-environment) (raise-continuable "Unbound variable") (let ([&frame (first-frame &env)]) (find-var (&expand-recursive (frame-variables &frame)) (frame-values &frame))))) (env-loop &top-env))) (define (lookup-value-by-id address &env) (&vector-ref (frame-values (&list-ref/n &env (car address))) (cdr address))) (define (lookup-variable-id var &env) (let ((value-and-id (lookup-variable-value-and-id var &env))) (cdr value-and-id))) )
false
449575e200e4311de885a3b94e3f7105e7f1c738
984b20c7a66129447883a52132ed1298479e4deb
/select-coord.scm
3c2c2c7d9c44edd63f0450ab50ae38333aa5979a
[]
no_license
TAEB/bridey
e4bf76f9e663e67f1c1a0a5758d2d849ca4d1886
c28f47e31c235dfdef83edc645dd301f41895338
refs/heads/master
2021-01-15T10:47:44.534210
2008-04-04T22:07:46
2008-04-04T22:07:46
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,953
scm
select-coord.scm
(define (select-coord from to) (define (lim-x n) (if (> n 80) 80 (if (< n 0) 0 n))) (define (lim-y n) (if (> n 24) 24 (if (< n 0) 0 n))) (define (distance a b) (max (abs (- (car a) (car b))) (abs (- (cadr a) (cadr b))))) (define (path-to from to) (let ((dis (distance from to)) (dx (- (car to) (car from))) (dy (- (cadr to) (cadr from)))) (map list (append (make-list (abs dx) (if (zero? dx) 0 (/ dx (abs dx)))) (make-list (- dis (abs dx)) 0)) (append (make-list (abs dy) (if (zero? dy) 0 (/ dy (abs dy)))) (make-list (- dis (abs dy)) 0))))) (define (dir->vi-char dir) (let ((dx (car dir)) (dy (cadr dir))) (cond ((and (= dx 0) (= dy 0)) #f) ((= dx 0) (if (> dy 0) #\j #\k)) ((= dy 0) (if (> dx 0) #\l #\h)) ((> dx 0) (if (> dy 0) #\n #\u)) ((< dx 0) (if (> dy 0) #\b #\y))))) (let* ((old-x (car from)) (old-y (cadr from)) (new-x (car to)) (new-y (cadr to)) (dx (- new-x old-x)) (dy (- new-y old-y)) (left-x (floor (/ dx 8))) (right-x (ceiling (/ dx 8))) (upper-y (floor (/ dy 8))) (lower-y (ceiling (/ dy 8))) (x1 (lim-x (+ old-x (* 8 left-x)))) (x2 (lim-x (+ old-x (* 8 right-x)))) (y1 (lim-y (+ old-y (* 8 upper-y)))) (y2 (lim-y (+ old-y (* 8 lower-y)))) ; (coord keystrokes) (nw (list (list x1 y1) (path-to '(0 0) (list left-x upper-y)))) (ne (list (list x2 y1) (path-to '(0 0) (list right-x upper-y)))) (sw (list (list x1 y2) (path-to '(0 0) (list left-x lower-y)))) (se (list (list x2 y2) (path-to '(0 0) (list right-x lower-y)))) ; (keystrokes keystrokes) (paths (map (lambda (e) (list (cadr e) (path-to (car e) to))) (list nw ne sw se))) (path (apply min-p (lambda (a b) (< (length (apply append a)) (length (apply append b)))) paths)) (keystrokes (append (map (compose char-upcase dir->vi-char) (car path)) (map dir->vi-char (cadr path))))) (list->string keystrokes)))
false
5b5dd1654809d5663c3305fc9ab8b56370c70495
50be237574bb300dfc5e29e2051e442ba0bf328b
/i3-core.scm
3265a29ae344cb6eb7fd85a6e41a60cba1fd52ba
[]
no_license
stapelberg/i3-egg
0f7dea9e81b412369875e70cf37b85b53984325c
645f7269e7598312fa9772b75fa4f2e99f3c6ce7
refs/heads/master
2021-01-10T03:01:06.925893
2013-08-18T14:05:55
2013-08-18T14:05:55
51,696,671
0
0
null
null
null
null
UTF-8
Scheme
false
false
8,280
scm
i3-core.scm
;; We need this lookup table for event type to event name, because i3 ;; uses event names when subscribing but event types when ;; delivering. Hopefully we can get rid of this in future versions :). (define-constant i3-event-name-to-type '(("workspace" . 0) ("output" . 1) ("mode" . 2))) ;; tell medea to always use lists for arrays, not vectors (json-parsers (alist-cons 'array identity (json-parsers))) (define (i3-socket-path) (string-trim-right (capture "i3 --get-socketpath"))) ;; writes a 32-bit unsigned integer (define (write-u32 val) (write-u8vector (blob->u8vector/shared (u32vector->blob/shared (u32vector val))))) (define (read-u32) (u32vector-ref (blob->u32vector (u8vector->blob (read-u8vector 4))) 0)) (define-record i3-conn cmd-fd event-fd evmutex event-thread callbacks) ;; Alias for i3-conn? because the module can be used with a ;; user-specified prefix. (define connection? i3-conn?) (define (connect) @("Connects to i3 running on the display specified by the environment variable {{DISPLAY}}." (@to "connection")) (let ((cmd-fd (socket af/unix sock/stream)) (event-fd (socket af/unix sock/stream))) (socket-connect cmd-fd (unix-address (i3-socket-path))) (socket-connect event-fd (unix-address (i3-socket-path))) (let ((conn (make-i3-conn cmd-fd event-fd (make-mutex) ;; Thread will be filled in after the record is ;; created, because it uses the connection. #f '()))) (i3-conn-event-thread-set! conn (thread-start! (lambda () (read-events conn)))) conn))) (define (process-events-forever conn) (thread-join! (i3-conn-event-thread conn))) (define (i3-format-ipc-message payload type) (with-output-to-string (lambda () (display "i3-ipc") (write-u32 (string-length payload)) (write-u32 type) (display payload)))) ;; Reads one message from the specified socket, then returns the ;; reply and its type. (define (i3-read-one-message sock) (socket-receive sock (string-length "i3-ipc")) (let* ((reply-length (with-input-from-string (socket-receive sock 4) read-u32)) (reply-type (with-input-from-string (socket-receive sock 4) read-u32)) (reply (read-json (socket-receive sock reply-length)))) (values reply reply-type))) (define (cmd conn msg #!optional (type 0)) @("Sends the given MSG to i3, by default as command." (conn "A connection to i3, created with [[#connect|(connect)]].") (msg "The payload of the message, e.g. a command when {{type}} is 0.") (type "The numeric message type, “COMMAND” (0) by default. See also [[http://i3wm.org/docs/ipc.html#_sending_messages_to_i3]] for message types.") (@to "reply + reply-type") (@example-no-eval "Change focus to the window to the right:" (cmd (connect) "focus right"))) (let ((sock (i3-conn-cmd-fd conn))) (socket-send-all sock (i3-format-ipc-message msg type)) (i3-read-one-message sock))) ;; Forever reads events from the event file descriptor and dispatches ;; them to callback handlers. (define (read-events conn) (let ((events-fd (i3-conn-event-fd conn)) (mutex (i3-conn-evmutex conn))) (let loop () (thread-wait-for-i/o! (socket-fileno events-fd) #:input) (mutex-lock! mutex) (receive (reply reply-type) (i3-read-one-message events-fd) ;; For events, the highest bit is 1, the rest is the event ID. (let* ((event-type (bitwise-and #x7F reply-type)) (callbacks (i3-conn-callbacks conn)) (callback (alist-ref event-type callbacks eqv? (lambda (unused) (format #t "no callback for event"))))) (callback reply))) (mutex-unlock! mutex) (loop)))) (define (subscribe conn event thunk) @("Subscribes to the specified EVENT (e.g. \"workspace\") and calls THUNK when an event arrives.") (i3-conn-callbacks-set! conn (alist-update! ;; Map the event name to its type here so that comparisons are ;; easier later on. (alist-ref event i3-event-name-to-type string=?) thunk (i3-conn-callbacks conn))) ;; We cannot use i3-command here since that uses the wrong ;; connection. (let ((sock (i3-conn-event-fd conn)) (mutex (i3-conn-evmutex conn))) (mutex-lock! mutex) (socket-send-all sock (i3-format-ipc-message (json->string (vector event)) 2)) (i3-read-one-message sock) (mutex-unlock! mutex))) (define (tree conn) @("Convenience function to get the layout tree from i3. See [[http://i3wm.org/docs/ipc.html#_tree_reply]] for the reply format." (conn "A connection to i3, created with [[#connect|(connect)]].") (@to "reply + reply-type") (@example-no-eval "Return a list of all Chrome windows:" (filter-containers (lambda (con) (string-suffix? " - Google Chrome" (alist-ref 'name con))) (tree (connect))))) (cmd conn "" 4)) (define (workspaces conn) @("Convenience function to get the workspaces from i3. See [[http://i3wm.org/docs/ipc.html#_workspaces_reply]] for the reply format." (conn "A connection to i3, created with [[#connect|(connect)]]") (@to "reply + reply-type")) (cmd conn "" 1)) ;; returns the name of the currently focused workspace by filtering ;; the list of workspaces for the one which has focused == true (define (i3-get-focused-workspace-name conn) (alist-ref 'name (find (cut alist-ref 'focused <>) (workspaces conn)))) (define (filter-containers predicate tree) @("Returns a list containing all containers for which the given predicate returns #t." (predicate "Predicate which is evaluated for each i3 container. Only containers for which the predicate returns #t are included in the return list") (tree "(Part of) a list of containers as returned by [[#tree|(tree)]].") (@to "list") (@example-no-eval "Return a list of all Chrome windows:" (filter-containers (lambda (con) (string-suffix? " - Google Chrome" (alist-ref 'name con))) (tree (connect))))) (if (null? tree) '() (append (if (predicate tree) (list tree) (list)) (apply append (filter-map (lambda (node) (filter-containers predicate node)) (cdr (assoc 'nodes tree))))))) ;; besser: (define i3-output-containers (by-type …)) (define-syntax container-getter-by-type (syntax-rules () ((_ name con-type) (define (name tree) (filter-containers (lambda (con) (= (alist-ref 'type con) con-type)) tree))))) ;; XXX: comparing type with the magic number 4 is unclean and will ;; break once this field is properly exported by i3 (container-getter-by-type i3-output-containers 1) (container-getter-by-type i3-workspace-containers 4) (define (descend-focused stop-predicate tree) @("Descends the focused containers of the given TREE, stopping at the first container which satisfies STOP-PREDICATE." (stop-predicate "Processing stops when this predicate first returns true. The return value is the container with which this predicate was evaluated.") (tree "(Part of) a list of containers as returned by [[#tree|(tree)]].") (@to "alist")) (if (stop-predicate tree) tree (if (null? (alist-ref 'focus tree)) tree (descend-focused stop-predicate (let ((focused-id (first (alist-ref 'focus tree)))) (find (lambda (con) (= (alist-ref 'id con) focused-id)) (append (alist-ref 'nodes tree) (alist-ref 'floating_nodes tree)))))))) (define (focused-con tree) @("Returns the currently focused container." (tree "(Part of) a list of containers as returned by [[#tree|(tree)]].") (@to "alist") (@example-no-eval "Print the name of the currently focused window:" (format #t "~A~N" (alist-ref 'name (focused-con (tree (connect)))))) (@example-no-eval "Print the name of the focused window of workspace 1:" (let ((ws-1 (first (filter-containers (lambda (con) (and (= (alist-ref 'type con) 4) (string= (alist-ref 'name con) "1"))) (tree (connect)))))) (format #t "~A~N" (focused-con ws-1))))) (descend-focused (lambda (con) (null? (alist-ref 'nodes con))) tree))
true
b276a2295b965fdea992c18bfc43f6ce172b4a45
0bdfa3fdb0467776e4e06a41c683b01d2b8902fd
/src/web-application/server-helper.ss
74624d4a3d02d57efafc0d6ceb53c91faaca8dc1
[]
no_license
VijayEluri/moby-scheme
e792d818dfec2c26fbc04451119eaab8556bb786
e2aa51b61a0d95499b71ef5d844e5eeecafb839d
refs/heads/master
2020-05-20T10:59:09.974728
2009-07-09T19:12:04
2009-07-09T19:12:04
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,463
ss
server-helper.ss
#lang scheme (require web-server/http/request-structs web-server/http/response-structs scheme/contract) ;; make-input-port-response: string input-port -> response (define (make-input-port-response filename ip) (let* ([CHUNK-SIZE (expt 2 16)] [headers (list (make-header #"Content-Disposition" (bytes-append #"attachment; filename=\"" ;; fixme: we need to escape filename (string->bytes/utf-8 filename) #"\"")))]) (make-response/incremental 200 "Okay" (current-seconds) #"application/octet-stream" headers (lambda (send/bytes) (let loop () (let ([chunk (read-bytes CHUNK-SIZE ip)]) (cond [(eof-object? chunk) (void)] [else (send/bytes chunk) (loop)]))))))) (provide/contract [make-input-port-response (string? input-port? . -> . response/basic?)])
false
7ff1d179c540f648c747d2a7121551a325a9092c
f5083e14d7e451225c8590cc6aabe68fac63ffbd
/cs/01-Programming/cs61a/course/extra/cs61as/library/animal.scm
64bbcfc4a132d90a43d434e185534febe862d6f5
[]
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
1,863
scm
animal.scm
(define (make-branch q y n) (list 'branch q y n)) (define (make-leaf a) (list 'leaf a)) (define (type node) (car node)) ; all nodes (define (leaf? node) (eq? (type node) 'leaf)) (define (branch? node) (eq? (type node) 'branch)) (define (answer node) (cadr node)) ; leaf nodes (define (question node) (cadr node)) ; branch nodes (define (yespart node) (caddr node)) (define (nopart node) (cadddr node)) (define (set-yes! node x) (set-car! (cddr node) x)) (define (set-no! node x) (set-car! (cdddr node) x)) (define animal-tree (make-leaf 'rabbit)) (define (animal-game) (print "Think of an animal. I'll guess it.") (animal animal-tree (lambda (x) (set! animal-tree x)))) (define (animal node setter) (if (branch? node) (if (yorn (question node)) (animal (yespart node) (lambda (new) (set-yes! node new))) (animal (nopart node) (lambda (new) (set-no! node new)))) (if (yorn (word "Is it " (a/an (answer node)) "?")) "I win!!!" (begin (display "I give up, what is it? ") (flush) (let ((correct (read))) (newline) (display "Please tell me a question whose ") (display "answer is YES for ") (display (a/an correct)) (newline) (display "and NO for ") (display (a/an (answer node))) (display ".") (newline) (display "Enclose the question in quotation marks.") (newline) (let ((newquest (read))) (setter (make-branch newquest (make-leaf correct) node)) "Thanks. Now I know better.")))))) (define (yorn question) (display question) (display " ") (flush) (let ((yn (read))) (cond ((eq? (first yn) 'y) #t) ((eq? (first yn) 'n) #f) (else (print "Please type YES or NO.") (yorn question))))) (define (a/an wd) (if (member? (first wd) 'aeiou) (word "an " wd) (word "a " wd)))
false
2387729bbf6dca51e3edcb1a9addaf3db44ff222
9b2eb10c34176f47f7f490a4ce8412b7dd42cce7
/lib-compat/chez-r7b/i9.sls
7a299fc5dc6e15cf95c98a71fda6c9b4a7a7fad6
[ "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
1,759
sls
i9.sls
(library (chez-r7b i9) (export define-record-type) (import (except (rnrs) define-record-type) (rename (rnrs) (define-record-type define-record-type:r6))) (define-syntax define-record-type (lambda (x) (syntax-case x () ((_ nam (ctr formal ...) pred (fieldname fieldparam ...) ...) (with-syntax (((r6-fields ...) ;; Construct immutable or mutable fields depends on clause length (map (lambda (c) (if (= 2 (length c)) (quasisyntax (immutable . (unsyntax c))) (quasisyntax (mutable . (unsyntax c))))) (syntax ((fieldname fieldparam ...) ...)))) ((unreferenced ...) ;; Unreferenced names inside constructor formals (fold-left (lambda (cur e) (if (not (find (lambda (h) (bound-identifier=? e h)) (syntax (formal ...)))) (cons e cur) cur)) '() (syntax (fieldname ...))))) (syntax (define-record-type:r6 (nam ctr pred) ;; Constructor (protocol (lambda (c) (lambda (formal ...) ;; Instantiate unreferenced vars ;; with undefined value (define unreferenced) ... (c fieldname ...)))) ;; Fields (fields r6-fields ...) ;; FIXME: Is that true? (sealed #t)))))))) )
true
b31c4f98eadce705c6ca683fb851f5fa324e3ec5
eef5f68873f7d5658c7c500846ce7752a6f45f69
/spheres/net/sack-server.sld
c0dce952b23defa00490caca199e247e3a86b340
[ "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
707
sld
sack-server.sld
;;!!! Sack HTTP server middleware ;; ;; Copyright (C) 2008-2009 Per Eckerdal, 2010-2013 Mikael More, 2005-2007 Marc Feeley. (define-library (spheres/net sack-server) (export sack-start!) (import (spheres/core exception) ;; string-downcase! string-downcase reverse-list->string string-prefix? (spheres/string string) ;; string-split-char (spheres/string string-extra) ;; string->utf8-vector (spheres/string u8vector) (spheres/structure token-table) (spheres/os date-format) (spheres/net/sack uri) (spheres/net/sack http-util) (spheres/net/sack io-primitives)) (include "sack-server.scm"))
false