blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
171
content_id
stringlengths
40
40
detected_licenses
listlengths
0
8
license_type
stringclasses
2 values
repo_name
stringlengths
6
82
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
13 values
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
1.59k
594M
star_events_count
int64
0
77.1k
fork_events_count
int64
0
33.7k
gha_license_id
stringclasses
12 values
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_language
stringclasses
46 values
src_encoding
stringclasses
14 values
language
stringclasses
2 values
is_vendor
bool
2 classes
is_generated
bool
1 class
length_bytes
int64
4
7.87M
extension
stringclasses
101 values
filename
stringlengths
2
149
content
stringlengths
4
7.87M
has_macro_def
bool
2 classes
857becd91caf79a74a2430b6ed820c4412a9965c
4f30ba37cfe5ec9f5defe52a29e879cf92f183ee
/src/sasm/parse/constant-operand.scm
30107107fced5f9e5c0d225f60a434ba1402564f
[ "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
827
scm
constant-operand.scm
(need sasm/parse/syntax) (need sasm/sasm-ast) (define (sasm-parse-constant-operand expression) (sasm-parse-by-case expression (sasm-syntax-case :pattern (const (,integer? constant-integer)) :rewrite (constant-integer) (sasm-ast-node <integer-constant-operand> (:integer-value constant-integer))) (sasm-syntax-case :pattern (const (,symbol? label)) :rewrite (label) (sasm-ast-node <label-constant-operand> (:label-value label) (:referenced-symbol label) (:resolved-symbol #f))) (sasm-syntax-case :pattern (const (,string? constant-string)) :rewrite (constant-string) (sasm-ast-node <string-constant-operand> (:string-value constant-string))) ))
false
0ff2cb0a184bf1e9b34b4000b1bd8c732be9b5fc
4f105bc5e2fd871d7de67b58498b042fe083c20c
/posix-safe-mem.meta
a13176396e78135d7ceffdffbffb233bdb3c9e8e
[ "BSD-2-Clause" ]
permissive
dleslie/posix-safe-mem-egg
1ad4dd39700ca67b3aaaefbdc99f83bc71b87bc4
4e758e52e2751e3e07275ba6b48918b408fba666
refs/heads/master
2016-08-03T02:33:14.495233
2013-06-22T16:46:28
2013-06-22T16:46:28
10,591,968
1
0
null
null
null
null
UTF-8
Scheme
false
false
190
meta
posix-safe-mem.meta
;;;; -*- Scheme -*- ((license "BSD3") (category io) (author "Daniel J. Leslie") (synopsis "POSIX Safe Memory") (needs posix posix-shm posix-semaphore miscmacros uuid) (doc-from-wiki))
false
31e142e72c4b071bcee83f5f159317cb5def456d
4b5dddfd00099e79cff58fcc05465b2243161094
/chapter_5/exercise_5_22.scm
67e3b6acf4aab21797504c2d7639174695c5f5b2
[ "MIT" ]
permissive
hjcapple/reading-sicp
c9b4ef99d75cc85b3758c269b246328122964edc
f54d54e4fc1448a8c52f0e4e07a7ff7356fc0bf0
refs/heads/master
2023-05-27T08:34:05.882703
2023-05-14T04:33:04
2023-05-14T04:33:04
198,552,668
269
41
MIT
2022-12-20T10:08:59
2019-07-24T03:37:47
Scheme
UTF-8
Scheme
false
false
2,243
scm
exercise_5_22.scm
#lang sicp ;; P378 - [练习 5.22] ;; 将练习 3.12 的代码,转换成寄存器机器 (#%require "ch5-regsim.scm") (define (append x y) (if (null? x) y (cons (car x) (append (cdr x) y)))) (define append-machine (make-machine '(x y result continue) (list (list 'null? null?) (list 'car car) (list 'cdr cdr) (list 'cons cons)) '( (assign continue (label append-done)) append-loop (test (op null?) (reg x)) (branch (label null-x)) (save continue) (save x) (assign continue (label after-append-cdr)) (assign x (op cdr) (reg x)) (goto (label append-loop)) after-append-cdr (restore x) (restore continue) (assign x (op car) (reg x)) (assign result (op cons) (reg x) (reg result)) (goto (reg continue)) null-x (assign result (reg y)) (goto (reg continue)) append-done ))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (append! x y) (set-cdr! (last-pair x) y) x) (define (last-pair x) (if (null? (cdr x)) x (last-pair (cdr x)))) (define append!-machine (make-machine '(x y result cdr-x iter-x) (list (list 'null? null?) (list 'cdr cdr) (list 'set-cdr! set-cdr!)) '( (assign iter-x (reg x)) loop (assign cdr-x (op cdr) (reg iter-x)) (test (op null?) (reg cdr-x)) (branch (label do-append)) (assign iter-x (reg cdr-x)) (goto (label loop)) do-append (perform (op set-cdr!) (reg iter-x) (reg y)) (assign result (reg x)) ))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define x (list 'a 'b)) (define y (list 'c 'd)) ;; (define z (append x y)) (set-register-contents! append-machine 'x x) (set-register-contents! append-machine 'y y) (start append-machine) (define z (get-register-contents append-machine 'result)) z ; (a b c d) (cdr x) ; (b) ;; (define w (append! x y)) (set-register-contents! append!-machine 'x x) (set-register-contents! append!-machine 'y y) (start append!-machine) (define w (get-register-contents append!-machine 'result)) w ; (a b c d) (cdr x) ; (b c d)
false
dfe18e4c9fd7833fed90b8828b47bd72fc3b8235
defeada37d39bca09ef76f66f38683754c0a6aa0
/System/system/net/web-exception.sls
2e2a32957bf2e5fdc51e73f6d245d2bff92743e6
[]
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
862
sls
web-exception.sls
(library (system net web-exception) (export new is? web-exception? get-object-data response status) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Net.WebException a ...))))) (define (is? a) (clr-is System.Net.WebException a)) (define (web-exception? a) (clr-is System.Net.WebException a)) (define-method-port get-object-data System.Net.WebException GetObjectData (System.Void System.Runtime.Serialization.SerializationInfo System.Runtime.Serialization.StreamingContext)) (define-field-port response #f #f (property:) System.Net.WebException Response System.Net.WebResponse) (define-field-port status #f #f (property:) System.Net.WebException Status System.Net.WebExceptionStatus))
true
0e52d01bdf415e372798574a92714d1b780e042a
4b480cab3426c89e3e49554d05d1b36aad8aeef4
/chapter-02/ex2.36-obsidian.scm
9bfb441480ef5e6cc3e451d32e5795185332eb13
[]
no_license
tuestudy/study-sicp
a5dc423719ca30a30ae685e1686534a2c9183b31
a2d5d65e711ac5fee3914e45be7d5c2a62bfc20f
refs/heads/master
2021-01-12T13:37:56.874455
2016-10-04T12:26:45
2016-10-04T12:26:45
69,962,129
0
0
null
null
null
null
UTF-8
Scheme
false
false
371
scm
ex2.36-obsidian.scm
(load "../misc/scheme-test.scm") (define (accumulate-n op init seqs) (if (null? (car seqs)) null (cons (foldr op init (map car seqs)) (accumulate-n op init (map cdr seqs))))) (run (make-testcase '(assert-equal? (+ 1 1) 2) '(assert-equal? (accumulate-n + 0 '((1 2 3) (4 5 6) (7 8 9) (10 11 12))) '(22 26 30)) ))
false
6ab6cc808522de51170be1b9dc3176f502beeccb
defeada37d39bca09ef76f66f38683754c0a6aa0
/mscorlib/system/io/path.sls
6af2afe67552a597092e03644d5ead502e4b0d0d
[]
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
3,280
sls
path.sls
(library (system io path) (export is? path? change-extension get-directory-name combine get-invalid-file-name-chars get-full-path get-file-name get-invalid-path-chars get-file-name-without-extension get-path-root get-extension is-path-rooted? get-random-file-name get-temp-path has-extension? get-temp-file-name invalid-path-chars alt-directory-separator-char directory-separator-char path-separator volume-separator-char) (import (ironscheme-clr-port)) (define (is? a) (clr-is System.IO.Path a)) (define (path? a) (clr-is System.IO.Path a)) (define-method-port change-extension System.IO.Path ChangeExtension (static: System.String System.String System.String)) (define-method-port get-directory-name System.IO.Path GetDirectoryName (static: System.String System.String)) (define-method-port combine System.IO.Path Combine (static: System.String System.String System.String)) (define-method-port get-invalid-file-name-chars System.IO.Path GetInvalidFileNameChars (static: System.Char[])) (define-method-port get-full-path System.IO.Path GetFullPath (static: System.String System.String)) (define-method-port get-file-name System.IO.Path GetFileName (static: System.String System.String)) (define-method-port get-invalid-path-chars System.IO.Path GetInvalidPathChars (static: System.Char[])) (define-method-port get-file-name-without-extension System.IO.Path GetFileNameWithoutExtension (static: System.String System.String)) (define-method-port get-path-root System.IO.Path GetPathRoot (static: System.String System.String)) (define-method-port get-extension System.IO.Path GetExtension (static: System.String System.String)) (define-method-port is-path-rooted? System.IO.Path IsPathRooted (static: System.Boolean System.String)) (define-method-port get-random-file-name System.IO.Path GetRandomFileName (static: System.String)) (define-method-port get-temp-path System.IO.Path GetTempPath (static: System.String)) (define-method-port has-extension? System.IO.Path HasExtension (static: System.Boolean System.String)) (define-method-port get-temp-file-name System.IO.Path GetTempFileName (static: System.String)) (define-field-port invalid-path-chars #f #f (static:) System.IO.Path InvalidPathChars System.Char[]) (define-field-port alt-directory-separator-char #f #f (static:) System.IO.Path AltDirectorySeparatorChar System.Char) (define-field-port directory-separator-char #f #f (static:) System.IO.Path DirectorySeparatorChar System.Char) (define-field-port path-separator #f #f (static:) System.IO.Path PathSeparator System.Char) (define-field-port volume-separator-char #f #f (static:) System.IO.Path VolumeSeparatorChar System.Char))
false
3a2530a5758849f03bddf1b782ff1720a2bc0a3e
defeada37d39bca09ef76f66f38683754c0a6aa0
/System.Core/system/io/pipes/unix-named-pipe-server.sls
db1664b13a95562df8862025a7bf5a0b5bfcd341
[]
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
917
sls
unix-named-pipe-server.sls
(library (system io pipes unix-named-pipe-server) (export new is? unix-named-pipe-server? wait-for-connection disconnect handle) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.IO.Pipes.UnixNamedPipeServer a ...))))) (define (is? a) (clr-is System.IO.Pipes.UnixNamedPipeServer a)) (define (unix-named-pipe-server? a) (clr-is System.IO.Pipes.UnixNamedPipeServer a)) (define-method-port wait-for-connection System.IO.Pipes.UnixNamedPipeServer WaitForConnection (System.Void)) (define-method-port disconnect System.IO.Pipes.UnixNamedPipeServer Disconnect (System.Void)) (define-field-port handle #f #f (property:) System.IO.Pipes.UnixNamedPipeServer Handle Microsoft.Win32.SafeHandles.SafePipeHandle))
true
600532f245d4e418594bf8d867aaaa6d94a3ae60
52a4d282f6ecaf3e68d798798099d2286a9daa4f
/cp1/scheme-experiments/model.ss
10298b2e4316ec84e4bc26d6b9fe2d267382400f
[ "MIT" ]
permissive
bkovitz/FARGish
f0d1c05f5caf9901f520c8665d35780502b67dcc
3dbf99d44a6e43ae4d9bba32272e0d618ee4aa21
refs/heads/master
2023-07-10T15:20:57.479172
2023-06-25T19:06:33
2023-06-25T19:06:33
124,162,924
5
1
null
null
null
null
UTF-8
Scheme
false
false
1,279
ss
model.ss
; model.ss -- Simplest possible Scheme implementation of ; canvases-and-painters (define (run-painter env painter) (pmatch painter [(,source ,target ,func) (let** ([I (eval-as 'det-addr source)] [J (eval-as 'det-addr target)] [F (eval-as 'func func)] [V (apply-func F (eval-as 'value-at I))]) (paint J V))])) (define (eval-as env what-as x) (cond [(eq? what-as 'det-addr) ( ; What are all the possibilities for x? ; If x is a number, what are all the possibilities for ; supplying the container? ; How do we store containers and evaluators in the env? ; The default (simplest) way to map an addr to a det-addr. (define (eval-as/det-addr/default env x) (cond x [(det-addr? x) x] [(integer? x) (det-addr (default-container env) x)] [(char? x) (matching-cells (default-container env) x)] [(painter-template? x) (matching-painters (default-soup env) x)] [(soup? x) x] [else fizzle(x)])) (define (default-container env) (env-main-canvas env)) ; No flexibility in this version (define (default-soup env) (env-working-soup env)) ; No flexibility in this version ; TODO ; det-addr? ; det-addr (ctor) ; matching-cells ; matching-painters ; soup? ; fizzle
false
864ef88b9d35287899c3d3a9377a8dcbbb5c365d
ac2a3544b88444eabf12b68a9bce08941cd62581
/lib/_prim-f64vector#.scm
7eb4e6e42425624dcaa5c890d7eb2ed05937750d
[ "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
418
scm
_prim-f64vector#.scm
;;;============================================================================ ;;; File: "_prim-f64vector#.scm" ;;; Copyright (c) 1994-2019 by Marc Feeley, All Rights Reserved. ;;;============================================================================ ;;; F64vector operations. (##include "~~lib/_prim-f64vector-gambit#.scm") ;;;============================================================================
false
1f9131fef6b1712c3e81c1235b62291bda0fa416
47457420b9a1eddf69e2b2f426570567258f3afd
/3/33-35-37.scm
29ce9b63160b3f4bde0dceeb92d210e231ca0b3f
[]
no_license
adromaryn/sicp
797496916620e85b8d85760dc3f5739c4cc63437
342b56d233cc309ffb59dd13b2d3cf9cd22af6c9
refs/heads/master
2021-08-30T06:55:04.560128
2021-08-29T12:47:28
2021-08-29T12:47:28
162,965,433
0
0
null
null
null
null
UTF-8
Scheme
false
false
8,075
scm
33-35-37.scm
#lang sicp ;;; Connector realization (define (inform-about-value constraint) (constraint 'I-have-a-value)) (define (inform-about-no-value constraint) (constraint 'I-lost-my-value)) (define (make-connector) (let ((value false) (informant false) (constraints '())) (define (set-my-value newval setter) (cond ((not (has-value? me)) (set! value newval) (set! informant setter) (for-each-except setter inform-about-value constraints)) ((not (= value newval)) (error "Противоречие" (list value newval))) (else 'ignored))) (define (forget-my-value refactor) (if (eq? refactor informant) (begin (set! informant false) (for-each-except refactor inform-about-no-value constraints)) 'ignored)) (define (connect new-constraint) (if (not (memq new-constraint constraints)) (set! constraints (cons new-constraint constraints))) (if (has-value? me) (inform-about-value new-constraint)) 'done) (define (me request) (cond ((eq? request 'has-value?) (if informant true false)) ((eq? request 'value) value) ((eq? request 'set-value!) set-my-value) ((eq? request 'forget) forget-my-value) ((eq? request 'connect) connect) (else (error "НЕИЗВЕСТНАЯ ОПЕРАЦИЯ -- CONNECTOR" request)))) me)) (define (for-each-except exception procedure list) (define (loop items) (cond ((null? items) 'done) ((eq? (car items) exception) (loop (cdr items))) (else (procedure (car items)) (loop (cdr items))))) (loop list)) (define (has-value? connector) (connector 'has-value?)) (define (get-value connector) (connector 'value)) (define (set-value! connector new-value informant) ((connector 'set-value!) new-value informant)) (define (forget-value! connector retractor) ((connector 'forget) retractor)) (define (connect connector new-constraint) ((connector 'connect) new-constraint)) ;;; Operators (define (adder a1 a2 sum) (define (process-new-value) (cond ((and (has-value? a1) (has-value? a2)) (set-value! sum (+ (get-value a1) (get-value a2)) me)) ((and (has-value? a1) (has-value? sum)) (set-value! a2 (- (get-value sum) (get-value a1)) me)) ((and (has-value? a2) (has-value? sum)) (set-value! a1 (- (get-value sum) (get-value a2)) me)))) (define (process-forget-value) (forget-value! sum me) (forget-value! a1 me) (forget-value! a2 me) (process-new-value)) (define (me request) (cond ((eq? request 'I-have-a-value) (process-new-value)) ((eq? request 'I-lost-my-value) (process-forget-value)) (else (error "Неизвестный запрос -- ADDER" request)))) (connect a1 me) (connect a2 me) (connect sum me) me) (define (multiplier m1 m2 product) (define (process-new-value) (cond ((or (and (has-value? m1) (= (get-value m1) 0)) (and (has-value? m2) (= (get-value m2) 0))) (set-value! product 0 me)) ((and (has-value? m1) (has-value? m2)) (set-value! product (* (get-value m1) (get-value m2)) me)) ((and (has-value? product) (has-value? m1)) (set-value! m2 (/ (get-value product) (get-value m1)) me)) ((and (has-value? product) (has-value? m2)) (set-value! m1 (/ (get-value product) (get-value m2)) me)))) (define (process-forget-value) (forget-value! product me) (forget-value! m1 me) (forget-value! m2 me) (process-new-value)) (define (me request) (cond ((eq? request 'I-have-a-value) (process-new-value)) ((eq? request 'I-lost-my-value) (process-forget-value)) (else (error "Неизвестный запрос -- MULTIPLIER" request)))) (connect m1 me) (connect m2 me) (connect product me) me) (define (constant value connector) (define (me request) (error "Неизвестный запрос -- CONSTANT")) (connect connector me) (set-value! connector value me) me) ;;; PROBE (define (probe name connector) (define (print-probe value) (newline) (display "Тестер: ") (display name) (display " = ") (display value)) (define (process-new-value) (print-probe (get-value connector))) (define (process-forget-value) (print-probe "?")) (define (me request) (cond ((eq? request 'I-have-a-value) (process-new-value)) ((eq? request 'I-lost-my-value) (process-forget-value)) (else (error "Неизвестный запрос -- PROBE" request)))) (connect connector me) me) ;;; Temperature example (define (celsius-farenheit-converter c f) (let ((u (make-connector)) (v (make-connector)) (w (make-connector)) (x (make-connector)) (y (make-connector))) (multiplier c w u) (multiplier v x u) (adder v y f) (constant 9 w) (constant 5 x) (constant 32 y) 'ok)) (define C (make-connector)) (define F (make-connector)) (celsius-farenheit-converter C F) (probe "по Цельсию" C) (probe "по Фаренгейту" F) (set-value! C 25 'user) ;;(set-value! F 212 'user) (display "Averager test:") (newline) (define (averager a b c) (let ((d (make-connector)) (e (make-connector))) (constant 2 d) (adder a b e) (multiplier c d e) 'ok)) (define a (make-connector)) (define b (make-connector)) (define c (make-connector)) (averager a b c) (probe "1 слагаемое" a) (probe "2 слагаемое" b) (probe "Сумма" c) (set-value! a 3 'user) (set-value! b 5 'user) (forget-value! a 'user) (set-value! c 5 'user) ;; Связь - квадратный кореньы (display "Squarer test:") (newline) (define (squarer a b) (define (process-new-value) (if (has-value? b) (if (< (get-value b) 0) (error "квадрат меньше 0 -- SQUARER" (get-value b)) (set-value! a (sqrt (get-value b)) me)) (if (has-value? a) (let ((a-value (get-value a))) (set-value! b (* a-value a-value) me)) 'done))) (define (process-forget-value) (forget-value! b me) (forget-value! a me) (process-new-value)) (define (me request) (cond ((eq? request 'I-have-a-value) (process-new-value)) ((eq? request 'I-lost-my-value) (process-forget-value)) (else (error "Неизвестный запрос -- SQUARER" request)))) (connect a me) (connect b me) me) (define a1 (make-connector)) (define b1 (make-connector)) (squarer a1 b1) (probe "Корень" a1) (probe "Квадрат" b1) (set-value! b1 10 'user) (forget-value! b1 'user) (set-value! a1 10 'user) ;; Перезадание конвертера градусовы (display "Redefine Cels-Farht") (define (c+ x y) (let ((z (make-connector))) (adder x y z) z)) (define (c* x y) (let ((z (make-connector))) (multiplier x y z) z)) (define (c/ x y) (let ((z (make-connector))) (multiplier y z x) z)) (define (cv value) (let ((z (make-connector))) (constant value z) z)) (define (celsius-fahrenheit-converter x) (c+ (c* (c/ (cv 9) (cv 5)) x) (cv 32))) (define C1 (make-connector)) (define F1 (celsius-fahrenheit-converter C1)) (probe "Celsius" C1) (probe "Fahrenheit" F1) (set-value! C1 25 'user)
false
5b7fc2459439f67c1cac4ab572a720cf2344845f
a74932f6308722180c9b89c35fda4139333703b8
/edwin48/scsh/io-support.scm
7767661beebef46f5d0dd80f486d3268c495ed4e
[]
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
729
scm
io-support.scm
;;; -*- mode: scheme; scheme48-package: io-support -*- (define (input-available-on-port? port block?) (receive (rvec wvec evec) (select (vector port) (vector) (vector) (if block? #f 0)) (> 0 (vector-length rvec)))) (define (file-eq? filename1 filename2) (let ((info1 (file-info filename1)) (info2 (file-info filename2))) (= (file-info:inode info1) (file-info:inode info2)))) (define (file-modification-time filename) (file-info:mtime (file-info filename))) (define (call-with-binary-input-file filename thunk) (call-with-input-file filename thunk)) (define (call-with-binary-output-file filename thunk) (call-with-output-file filename thunk))
false
a68020ab952449d2ea5f09bbae44b65d8a102679
defeada37d39bca09ef76f66f38683754c0a6aa0
/System.Data/system/data/ole-db/ole-db-command.sls
6d86f4c7296a4aebfedc131db673c1f31bf847bc
[]
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
3,777
sls
ole-db-command.sls
(library (system data ole-db ole-db-command) (export new is? ole-db-command? prepare execute-scalar reset-command-timeout cancel execute-reader create-parameter clone execute-non-query command-text-get command-text-set! command-text-update! command-timeout-get command-timeout-set! command-timeout-update! command-type-get command-type-set! command-type-update! connection-get connection-set! connection-update! design-time-visible?-get design-time-visible?-set! design-time-visible?-update! parameters transaction-get transaction-set! transaction-update! updated-row-source-get updated-row-source-set! updated-row-source-update!) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Data.OleDb.OleDbCommand a ...))))) (define (is? a) (clr-is System.Data.OleDb.OleDbCommand a)) (define (ole-db-command? a) (clr-is System.Data.OleDb.OleDbCommand a)) (define-method-port prepare System.Data.OleDb.OleDbCommand Prepare (System.Void)) (define-method-port execute-scalar System.Data.OleDb.OleDbCommand ExecuteScalar (System.Object)) (define-method-port reset-command-timeout System.Data.OleDb.OleDbCommand ResetCommandTimeout (System.Void)) (define-method-port cancel System.Data.OleDb.OleDbCommand Cancel (System.Void)) (define-method-port execute-reader System.Data.OleDb.OleDbCommand ExecuteReader (System.Data.OleDb.OleDbDataReader System.Data.CommandBehavior) (System.Data.OleDb.OleDbDataReader)) (define-method-port create-parameter System.Data.OleDb.OleDbCommand CreateParameter (System.Data.OleDb.OleDbParameter)) (define-method-port clone System.Data.OleDb.OleDbCommand Clone (System.Data.OleDb.OleDbCommand)) (define-method-port execute-non-query System.Data.OleDb.OleDbCommand ExecuteNonQuery (System.Int32)) (define-field-port command-text-get command-text-set! command-text-update! (property:) System.Data.OleDb.OleDbCommand CommandText System.String) (define-field-port command-timeout-get command-timeout-set! command-timeout-update! (property:) System.Data.OleDb.OleDbCommand CommandTimeout System.Int32) (define-field-port command-type-get command-type-set! command-type-update! (property:) System.Data.OleDb.OleDbCommand CommandType System.Data.CommandType) (define-field-port connection-get connection-set! connection-update! (property:) System.Data.OleDb.OleDbCommand Connection System.Data.OleDb.OleDbConnection) (define-field-port design-time-visible?-get design-time-visible?-set! design-time-visible?-update! (property:) System.Data.OleDb.OleDbCommand DesignTimeVisible System.Boolean) (define-field-port parameters #f #f (property:) System.Data.OleDb.OleDbCommand Parameters System.Data.OleDb.OleDbParameterCollection) (define-field-port transaction-get transaction-set! transaction-update! (property:) System.Data.OleDb.OleDbCommand Transaction System.Data.OleDb.OleDbTransaction) (define-field-port updated-row-source-get updated-row-source-set! updated-row-source-update! (property:) System.Data.OleDb.OleDbCommand UpdatedRowSource System.Data.UpdateRowSource))
true
512f9722240e93943aa1d0b85ddd2eda6775836e
98fd12cbf428dda4c673987ff64ace5e558874c4
/sicp/v1/chapter-5.2/ndpar-5.2.scm
5172fc40808cb8281a6eaf18fb1a57ae998223f8
[ "Unlicense" ]
permissive
CompSciCabal/SMRTYPRTY
397645d909ff1c3d1517b44a1bb0173195b0616e
a8e2c5049199635fecce7b7f70a2225cda6558d8
refs/heads/master
2021-12-30T04:50:30.599471
2021-12-27T23:50:16
2021-12-27T23:50:16
13,666,108
66
11
Unlicense
2019-05-13T03:45:42
2013-10-18T01:26:44
Racket
UTF-8
Scheme
false
false
18,378
scm
ndpar-5.2.scm
#lang racket (require r5rs) ;; ------------------------------------------------------- ;; Utility functions ;; ------------------------------------------------------- (define (print . x) (apply display x) (newline)) (define (tagged-list? exp tag) (and (pair? exp) (eq? (car exp) tag))) (define (unique key lst) (define (u l acc) (if (null? l) acc (let* ((i (car l)) (k (key i))) (if (assoc k acc) (u (cdr l) acc) (u (cdr l) (cons (cons k i) acc)))))) (map car (u lst null))) (define (sort compare key lst) (define (partition pivot ls before after) (if (null? ls) (cons before after) (if (compare (key (car ls)) (key pivot)) (partition pivot (cdr ls) (cons (car ls) before) after) (partition pivot (cdr ls) before (cons (car ls) after))))) (if (or (null? lst) (null? (cdr lst))) lst (let* ((pivot (car lst)) (parts (partition pivot (cdr lst) null null))) (append (sort compare key (car parts)) (list pivot) (sort compare key (cdr parts)))))) (define (map-filter mapf pred lst) (if (null? lst) lst (if (pred (car lst)) (cons (mapf (car lst)) (map-filter mapf pred (cdr lst))) (map-filter mapf pred (cdr lst))))) (define (group-by keyf valuef coll) (define (iter ls acc) (if (null? ls) acc (let* ((key (keyf (car ls))) (entry (assoc key acc))) (if entry (begin (set-cdr! entry (cons (valuef (car ls)) (cdr entry))) (iter (cdr ls) acc)) (iter (cdr ls) (cons (cons key (list (valuef (car ls)))) acc)))))) (iter coll null)) ;; ------------------------------------------------------- ;; A Register-Machine Simulator ;; ------------------------------------------------------- (define (make-machine ops controller-text) (let ((machine (make-new-machine))) ((machine 'install-operations) ops) ((machine 'install-instruction-sequence) (assemble controller-text machine)) machine)) ;; Registers (define (make-register name) (let ((contents '*unassigned*) (trace false)) (define (set-contents val) (if trace (print (list "REG:" name ":" contents "->" val))) (set! contents val)) (define (dispatch message) (cond ((eq? message 'get) contents) ((eq? message 'set) set-contents) ((eq? message 'trace) (λ (val) (set! trace val))) (else (error "Unknown request -- REGISTER" message)))) dispatch)) (define (reg-get-contents register) (register 'get)) (define (reg-set-contents! register val) ((register 'set) val)) (define (reg-trace-on register) ((register 'trace) true)) (define (reg-trace-off register) ((register 'trace) false)) ;; Stack (define (make-stack) (let ((s '()) (number-pushes 0) (max-depth 0) (current-depth 0)) (define (push x) (set! s (cons x s)) (set! number-pushes (+ 1 number-pushes)) (set! current-depth (+ 1 current-depth)) (set! max-depth (max current-depth max-depth))) (define (pop) (if (null? s) (error "Empty stack -- POP") (let ((top (car s))) (set! s (cdr s)) (set! current-depth (- current-depth 1)) top))) (define (initialize) (set! s '()) (set! number-pushes 0) (set! max-depth 0) (set! current-depth 0) 'done) (define (statistics) (list (cons 'total-stack-pushes number-pushes) (cons 'maximum-stack-depth max-depth))) (define (dispatch message) (cond ((eq? message 'push) push) ((eq? message 'pop) (pop)) ((eq? message 'initialize) (initialize)) ((eq? message 'statistics) (statistics)) (else (error "Unknown request -- STACK" message)))) dispatch)) (define (pop stack) (stack 'pop)) (define (push stack val) ((stack 'push) val)) (define (stack-init stack) (stack 'initialize)) (define (stack-stats stack) (stack 'statistics)) ;; Machine (define (make-new-machine) (let* ((pc (make-register 'pc)) (stack (make-stack)) (instruction-sequence '()) (trace false) (instructions-executed 0) (labels '()) (the-ops (list (list 'initialize-stack (lambda () (stack-init stack))) (list 'print-stack-statistics (lambda () (stack-stats stack))))) (register-table (list (list 'pc pc)))) (define (get-all-instructions) (sort string<? (lambda (inst) (symbol->string (car inst))) (unique (lambda (inst) (inst 'text)) instruction-sequence))) (define (get-entry-points insts) (map-filter cadadr (lambda (inst) (and (eq? (car inst) 'goto) (eq? (caadr inst) 'reg))) insts)) (define (get-stack-regs insts) (map-filter cadr (lambda (inst) (or (eq? (car inst) 'save) (eq? (car inst) 'restore))) insts)) (define (get-sources insts) (group-by car cdr (map-filter cdr (lambda (inst) (eq? (car inst) 'assign)) insts))) (define (set-breakpoint label n value) (define (iter insts k) (if (= k 1) (if (car insts) (((car insts) 'set-breakpoint) value) (error "Invalid place for breakpoint" label n)) (iter (cdr insts) (- k 1)))) (iter (cdr (assoc label labels)) n)) (define (cancel-all-breakpoints) (for-each (lambda (label) (for-each (lambda (inst) (inst 'unset-breakpoint)) (cdr label))) labels)) (define (initialize) (set! instructions-executed 0)) (define (info) (let ((insts (get-all-instructions))) (list (cons 'instructions insts) (cons 'entry-points (get-entry-points insts)) (cons 'stack-regs (unique (lambda (x) x) (get-stack-regs insts))) (cons 'sources (get-sources insts))))) (define (print-stats) (print (cons (cons 'instructions-executed instructions-executed) (stack-stats stack)))) (define (allocate-register name) (if (assoc name register-table) (error "Multiply defined register: " name) (let ((register (list name (make-register name)))) (set! register-table (cons register register-table)) register))) (define (lookup-register name) (let ((val (assoc name register-table))) (if val (cadr val) (cadr (allocate-register name))))) (define (execute stop-at-breakpoint) (let ((insts (reg-get-contents pc))) (if (null? insts) 'done (let ((inst (car insts))) (if (and (inst 'breakpoint) stop-at-breakpoint) (print (list "BREAKPOINT:" (inst 'label) (inst 'breakpoint))) (begin (if trace (print (list (inst 'label) ":" (inst 'text)))) ((inst 'procedure)) (set! instructions-executed (+ 1 instructions-executed)) (execute true))))))) (define (dispatch message) (cond ((eq? message 'start) (reg-set-contents! pc instruction-sequence) (execute true)) ((eq? message 'initialize) (initialize)) ((eq? message 'trace-on) (set! trace true)) ((eq? message 'trace-off) (set! trace false)) ((eq? message 'trace-reg-on) (lambda (reg-name) (reg-trace-on (lookup-register reg-name)))) ((eq? message 'trace-reg-off) (lambda (reg-name) ((lookup-register reg-name) 'trace-off))) ((eq? message 'install-instruction-sequence) (lambda (seq) (set! instruction-sequence seq))) ((eq? message 'set-labels) (lambda (ls) (set! labels ls))) ((eq? message 'set-breakpoint) set-breakpoint) ((eq? message 'cancel-breakpoint) (lambda (label n) (set-breakpoint label n false))) ((eq? message 'cancel-all-breakpoints) (cancel-all-breakpoints)) ((eq? message 'proceed) (execute false)) ((eq? message 'info) (info)) ((eq? message 'print-stats) (print-stats)) ((eq? message 'allocate-register) allocate-register) ((eq? message 'get-register) lookup-register) ((eq? message 'install-operations) (lambda (ops) (set! the-ops (append the-ops ops)))) ((eq? message 'stack) stack) ((eq? message 'operations) the-ops) (else (error "Unknown request -- MACHINE" message)))) dispatch)) (define (get-register machine register-name) ((machine 'get-register) register-name)) ;; Assembler (define (assemble controller-text machine) (extract-labels controller-text (lambda (insts labels) (update-insts! insts labels machine) insts))) (define (extract-labels text receive) (if (null? text) (receive '() '()) (extract-labels (cdr text) (lambda (insts labels) (let ((next-inst (car text))) (if (symbol? next-inst) (if (assoc next-inst labels) (error "Duplicate label -- ASSEMBLE" next-inst) (begin (for-each (lambda (inst) (if (inst 'no-label?) ((inst 'set-label) next-inst))) insts) (receive insts (cons (make-label-entry next-inst insts) labels)))) (receive (cons (make-instruction next-inst) insts) labels))))))) (define (make-label-entry label-name insts) (cons label-name insts)) (define (update-insts! insts labels machine) (let ((pc (get-register machine 'pc)) (stack (machine 'stack)) (ops (machine 'operations))) ((machine 'set-labels) labels) (for-each (lambda (inst) ((inst 'set-procedure) (make-execution-procedure (inst 'text) labels machine pc stack ops))) insts))) (define (make-instruction instruction-text) (let ((text instruction-text) (label '()) (breakpoint false) (procedure '())) (define (dispatch message) (cond ((eq? message 'text) text) ((eq? message 'set-label) (lambda (new-label) (set! label new-label))) ((eq? message 'label) label) ((eq? message 'no-label?) (empty? label)) ((eq? message 'set-breakpoint) (lambda (value) (set! breakpoint value))) ((eq? message 'unset-breakpoint) (set! breakpoint false)) ((eq? message 'breakpoint) breakpoint) ((eq? message 'set-procedure) (lambda (proc) (set! procedure proc))) ((eq? message 'procedure) procedure) (else (error "Unknown request -- INSTRUCTION" message)))) dispatch)) ;; Instructions (define (make-execution-procedure inst labels machine pc stack ops) (cond ((eq? (car inst) 'assign) (make-assign inst machine labels ops pc)) ((eq? (car inst) 'if) (make-test inst machine labels ops pc)) ((eq? (car inst) 'goto) (make-goto inst machine labels pc)) ((eq? (car inst) 'save) (make-save inst machine stack pc)) ((eq? (car inst) 'restore) (make-restore inst machine stack pc)) ((eq? (car inst) 'perform) (make-perform inst machine labels ops pc)) (else (error "Unknown instruction type -- ASSEMBLE" inst)))) (define (make-assign inst machine labels operations pc) (let* ((target (get-register machine (assign-reg-name inst))) (value-exp (assign-value-exp inst)) (value-proc (if (operation-exp? value-exp) (make-operation-exp value-exp machine labels operations) (make-primitive-exp (car value-exp) machine labels)))) (lambda () (reg-set-contents! target (value-proc)) (advance-pc pc)))) (define (assign-reg-name assign-instruction) (cadr assign-instruction)) (define (assign-value-exp assign-instruction) (cddr assign-instruction)) (define (advance-pc pc) (reg-set-contents! pc (cdr (reg-get-contents pc)))) (define (lookup-label labels label-name) (let ((val (assoc label-name labels))) (if val (cdr val) (error "Undefined label -- ASSEMBLE" label-name)))) (define (make-test inst machine labels operations pc) (let ((condition (test-condition inst)) (dest (branch-dest inst))) (if (operation-exp? condition) (let ((condition-proc (make-operation-exp condition machine labels operations))) (if (label-exp? dest) (let ((insts (lookup-label labels (label-exp-label dest)))) (lambda () (if (condition-proc) (reg-set-contents! pc insts) (advance-pc pc)))) (error "Bad BRANCH instruction -- ASSEMBLE" inst))) (error "Bad TEST instruction -- ASSEMBLE" inst)))) (define (test-condition test-instruction) (cadr test-instruction)) (define (branch-dest branch-instruction) (caddr branch-instruction)) (define (make-goto inst machine labels pc) (let ((dest (goto-dest inst))) (cond ((label-exp? dest) (let ((insts (lookup-label labels (label-exp-label dest)))) (lambda () (reg-set-contents! pc insts)))) ((register-exp? dest) (let ((reg (get-register machine (register-exp-reg dest)))) (lambda () (reg-set-contents! pc (reg-get-contents reg))))) (else (error "Bad GOTO instruction -- ASSEMBLE" inst))))) (define (goto-dest goto-instruction) (cadr goto-instruction)) (define (make-save inst machine stack pc) (let ((reg (get-register machine (stack-inst-reg-name inst)))) (lambda () (push stack (cons (stack-inst-reg-name inst) (reg-get-contents reg))) (advance-pc pc)))) (define (make-restore inst machine stack pc) (let* ((reg-name (stack-inst-reg-name inst)) (reg (get-register machine reg-name))) (lambda () (let ((head (pop stack))) (if (eq? reg-name (car head)) (begin (reg-set-contents! reg (cdr head)) (advance-pc pc)) (error "Restoring wrong register" reg-name (car head))))))) (define (stack-inst-reg-name stack-instruction) (cadr stack-instruction)) (define (make-perform inst machine labels operations pc) (let ((action (perform-action inst))) (if (operation-exp? action) (let ((action-proc (make-operation-exp action machine labels operations))) (lambda () (action-proc) (advance-pc pc))) (error "Bad PERFORM instruction -- ASSEMBLE" inst)))) (define (perform-action inst) (cdr inst)) (define (make-primitive-exp exp machine labels) (cond ((constant-exp? exp) (let ((c (constant-exp-value exp))) (const c))) ((label-exp? exp) (let ((insts (lookup-label labels (label-exp-label exp)))) (const insts))) ((register-exp? exp) (let ((r (get-register machine (register-exp-reg exp)))) (lambda () (reg-get-contents r)))) (else (error "Unknown expression type -- ASSEMBLE" exp)))) (define (register-exp? exp) (tagged-list? exp 'reg)) (define (register-exp-reg exp) (cadr exp)) (define (constant-exp? exp) (tagged-list? exp 'const)) (define (constant-exp-value exp) (cadr exp)) (define (label-exp? exp) (tagged-list? exp 'label)) (define (label-exp-label exp) (cadr exp)) (define (make-operation-exp exp machine labels operations) (let ((op (lookup-prim (operation-exp-op exp) operations)) (aprocs (map (lambda (e) (make-operand-exp e machine labels)) (operation-exp-operands exp)))) (lambda () (apply op (map (lambda (p) (p)) aprocs))))) (define (operation-exp? exp) (and (pair? exp) (tagged-list? (car exp) 'op))) (define (operation-exp-op operation-exp) (cadr (car operation-exp))) (define (operation-exp-operands operation-exp) (cdr operation-exp)) (define (lookup-prim symbol operations) (let ((val (assoc symbol operations))) (if val (cadr val) (error "Unknown operation -- ASSEMBLE" symbol)))) (define (make-operand-exp exp machine labels) (cond ((constant-exp? exp) (let ((c (constant-exp-value exp))) (const c))) ((register-exp? exp) (let ((r (get-register machine (register-exp-reg exp)))) (lambda () (reg-get-contents r)))) (else (error "Invalid operand expression -- ASSEMBLE" exp)))) ;; ------------------------------------------------------- ;; Client API ;; ------------------------------------------------------- (define (init-machine machine) (machine 'initialize)) (define (start machine) (machine 'start)) (define (set-register-contents! machine register-name val) (reg-set-contents! (get-register machine register-name) val)) (define (get-register-contents machine register-name) (reg-get-contents (get-register machine register-name))) (define (trace-register machine reg-name) ((machine 'trace-reg-on) reg-name)) (define (set-breakpoint machine label n) ((machine 'set-breakpoint) label n n)) (define (cancel-breakpoint machine label n) ((machine 'cancel-breakpoint) label n)) (define (cancel-all-breakpoints machine) (machine 'cancel-all-breakpoints)) (define (proceed-machine machine) (machine 'proceed)) (define (print-statistics machine) (machine 'print-stats)) (define (get-info machine) (machine 'info)) (define (init-stack machine) ((machine 'stack) 'initialize))
false
9dd91b4bb022e17e535de0a49ce9b333235a4b68
ee232691dcbaededacb0778247f895af992442dd
/kirjasto/lib/kaava/aria2.scm
608f86efeb52d5c6b04b95b34501a95159034223
[]
no_license
mytoh/panna
c68ac6c6ef6a6fe79559e568d7a8262a7d626f9f
c6a193085117d12a2ddf26090cacb1c434e3ebf9
refs/heads/master
2020-05-17T02:45:56.542815
2013-02-13T19:18:38
2013-02-13T19:18:38
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
550
scm
aria2.scm
;; -*- coding: utf-8 -*- (use panna.kaava) (kaava "aria2") (homepage "aria2.sourceforge.net/") (repository "git://github.com/tatsuhiro-t/aria2") (define (install tynnyri) (cond ; freebsd ((is-freebsd) (system '(autoreconf "-fi") `("./configure" ,(string-append "--prefix=" tynnyri)) '(gmake) '(gmake install) '(gmake clean))) (else (sys-putenv (string-append "PREFIX=" tynnyri)) (with-clang) (system '(make clean) '(make) '(make install)))))
false
7fe596c56307b19b608a3ff2a0d6fda1ca207da7
4b2aeafb5610b008009b9f4037d42c6e98f8ea73
/11.2/11.2-4.scm
ea3ffd3988eb23c12ec3490a319362be6e0cfab3
[]
no_license
mrinalabrol/clrs
cd461d1a04e6278291f6555273d709f48e48de9c
f85a8f0036f0946c9e64dde3259a19acc62b74a1
refs/heads/master
2021-01-17T23:47:45.261326
2010-09-29T00:43:32
2010-09-29T00:43:32
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
522
scm
11.2-4.scm
(require-extension syntax-case check) (require '../11.2/section) (import section-11.2) (let ((table (make-lh-table 3 modulo-3-hash)) (e1 (make-lh-element 1 1)) (e2 (make-lh-element 4 2)) (e3 (make-lh-element 3 3))) (lh-table-insert! table e1) (lh-table-insert! table e2) (lh-table-insert! table e3) (check (lh-table-key-data table) => '((3 . 3) (1 . 1) (4 . 2))) (lh-table-delete! table e3) (check (lh-table-key-data table) => '(() (1 . 1) (4 . 2))) (check (lh-table-search table 4) => 2))
false
d3db3e905b0255c9e936276e8b85145fce7739c4
f08220a13ec5095557a3132d563a152e718c412f
/logrotate/skel/usr/share/guile/2.0/srfi/srfi-88.scm
043a4a78f95e7813d928ccff7c2bf02d89f4c158
[ "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,755
scm
srfi-88.scm
;;; srfi-88.scm --- Keyword Objects -*- coding: utf-8 -*- ;; Copyright (C) 2008, 2009, 2010 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 ;;; Author: Ludovic Courtès <[email protected]> ;;; Commentary: ;; This is a convenience module providing SRFI-88 "keyword object". All it ;; does is setup the right reader option and export keyword-related ;; convenience procedures. ;;; Code: (define-module (srfi srfi-88) #:re-export (keyword?) #:export (keyword->string string->keyword)) (cond-expand-provide (current-module) '(srfi-88)) ;; Change the keyword syntax both at compile time and run time; the latter is ;; useful at the REPL. (eval-when (expand load eval) (read-set! keywords 'postfix)) (define (keyword->string k) "Return the name of @var{k} as a string." (symbol->string (keyword->symbol k))) (define (string->keyword s) "Return the keyword object whose name is @var{s}." (symbol->keyword (string->symbol s))) ;;; Local Variables: ;;; coding: latin-1 ;;; End: ;;; srfi-88.scm ends here
false
ba796a7da703a82c246665c815fa401b97d15f3e
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
/tools/scripts/unicode-break-test-generator.scm
30088959086a52c2cb1117beac2fde9f8df4406e
[ "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
2,043
scm
unicode-break-test-generator.scm
(import (rnrs) (srfi :1) (srfi :13) (util port) (getopt)) (define (parse-break-test line) (define (parse-test tokens) ;; first must be ÷ (let loop ((tokens (cdr tokens)) (t '()) (r '())) (let ((token (car tokens))) (cond ((and (string=? token "÷") (null? (cdr tokens))) (let ((r (reverse! (cons (list->string (reverse! t)) r)))) (list (string-concatenate r) r))) ((string=? token "÷") (loop (cdr tokens) '() (cons (list->string (reverse! t)) r))) ((string=? token "×") (loop (cdr tokens) t r)) (else (loop (cdr tokens) (cons (integer->char (string->number token 16)) t) r)))))) (and (not (string-null? line)) (parse-test (string-tokenize line)))) (define (parse-break-tests in) (define (read-line in) (define (consume in) (do ((c (lookahead-char in) (lookahead-char in))) ((or (eof-object? c) (eqv? c #\newline))) (get-char in))) (let-values (((out e) (open-string-output-port))) (do ((c (get-char in) (get-char in))) ((or (eof-object? c) (memv c #'(#\newline #\#))) (when (eqv? c #\#) (consume in)) (if (eof-object? c) c (e))) (put-char out c)))) (filter values (port-map parse-break-test (lambda () (read-line in))))) (define (usage args) (print "Usage: ") (print (car args) " [-o {file}] input-file") (print args) (exit -1)) (define (main args) (with-args (cdr args) ((output (#\o "output") #t (current-output-port)) . rest) (when (null? rest) (usage args)) (let ((data (call-with-input-file (car rest) parse-break-tests))) ;; (when (and output (file-exists? output)) (delete-file output)) (let ((out (if (output-port? output) output (open-file-output-port output (file-options no-fail) (buffer-mode block) (native-transcoder))))) (display "#(" out) (newline out) (for-each (lambda (l) (display " " out) (write l out) (newline out)) data) (display #\) out) (newline out) (close-output-port out)))))
false
a15ef13bfc9da0249d078eb43ee52e6c8e851a5f
9b2eb10c34176f47f7f490a4ce8412b7dd42cce7
/lib-r6rs/r7b-impl/lazy.sls
b5a18652601c9ddcae6561cdd1f848d83b17944a
[ "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
207
sls
lazy.sls
(library (r7b-impl lazy) (export delay force (rename (eager make-promise) (lazy delay-force)) promise?) (import (r7b-util s45)) )
false
991c072b63f321c795be2be68522959da8f885d0
ac2a3544b88444eabf12b68a9bce08941cd62581
/lib/_prim-port-r4rs#.scm
789a31fb227ed8cdd618361d42bf78521878a7c4
[ "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
695
scm
_prim-port-r4rs#.scm
;;;============================================================================ ;;; File: "_prim-port-r4rs#.scm" ;;; Copyright (c) 1994-2019 by Marc Feeley, All Rights Reserved. ;;;============================================================================ ;;; Port operations in R4RS. (##namespace ("##" call-with-input-file call-with-output-file char-ready? close-input-port close-output-port current-input-port current-output-port display eof-object? input-port? newline open-input-file open-output-file output-port? peek-char read read-char with-input-from-file with-output-to-file write write-char )) ;;;============================================================================
false
b0c5ea3bca56e9daced9b20f165d92204492bf8f
307481dbdfd91619aa5fd854c0a19cd592408f1b
/node_modules/biwascheme/,/syntax-rules/a.scm
6675b58adfdbc8e8f5bd69149ce655dcf603024c
[ "MIT", "CC-BY-3.0" ]
permissive
yukarigohan/firstrepository
38ff2db62bb8baa85b21daf65b12765e10691d46
2bcdb91cbb6f01033e2e0a987a9dfee9d3a98ac7
refs/heads/master
2020-04-20T10:59:02.600980
2019-02-02T07:08:41
2019-02-02T07:08:41
168,803,970
0
0
null
null
null
null
UTF-8
Scheme
false
false
153
scm
a.scm
(define-syntax test (syntax-rules () ((test name expr) (unless expr (print name " failed: " (quote expr)))))) (test "test 1" (= 1 2))
true
91c74ac49eaf361bbe6f2f1e4c9ca6d1839f9ce7
b3f1b85ae1ce3bc09332b2a2c4f79b10aff2f82b
/C311GitTest/a8.ss
a25aa0b2d70bddc016eb9e6b9dea7ae378e43161
[]
no_license
KingLeper/PlayingWithGit
54a7d9a3abcc0c1fe51a07818f06ffec27213320
629f17bf4d9dba0b9ee707c22d54a47f02b2b324
refs/heads/master
2020-05-17T13:54:12.305323
2011-11-22T18:58:47
2011-11-22T18:58:47
2,829,761
0
0
null
null
null
null
UTF-8
Scheme
false
false
6,455
ss
a8.ss
;Alex Manus ;Assignment 8 ;C311 ;10/17/06 ;1 (define apply-k1 (lambda (k v) (pmatch k [(empty-k ,jumpout) () (jumpout v)] [(other-k ,n ,k) () (apply-k1 k (cons n v))]))) (define other-k1 (lambda (n k) `(other-k ,n ,k))) (define rember (lambda (x ls) (call/cc (lambda (jumpout) (tramp (rembert x ls (empty-kt jumpout))))))) (define rembert (lambda (x ls k) (lambda () (cond ((null? ls) (apply-k1 k '())) ((eq? (car ls) x) (apply-k1 k (cdr ls))) (else (rembert x (cdr ls) (other-k1 (car ls) k))))))) ;2 (define multi-rembero (lambda (x ls k) (cond ((null? ls) (apply-k1 k '())) ((eq? (car ls) x) (multi-rembero x (cdr ls) k)) (else (multi-rembero x (cdr ls) (other-k1 (car ls) k)))))) (define multi-rember (lambda(x ls) (call/cc (lambda (jumpout) (tramp (multi-rembert x ls (empty-kt jumpout))))))) (define multi-rembert (lambda (x ls k) (lambda () (cond ((null? ls) (apply-k1 k '())) ((eq? (car ls) x) (multi-rembert x (cdr ls) k)) (else (multi-rembert x (cdr ls) (other-k1 (car ls) k))))))) ;3 (define inner-k3 (lambda (n k) `(inner-k ,n ,k))) (define outer-k3 (lambda (x ls k) `(outer-k ,x ,ls ,k))) (define rember* (lambda (x ls k) (set! *x x) (set! *ls ls) (set! *k k) (rember*r))) (define rember*r (lambda () ;x ls k (cond [(null? *ls) (set! *v '()) (apply-k3r)] [(pair? (car *ls)) (set! *k (outer-k3 *x (cdr *ls) *k)) (set! *ls (car *ls)) (rember*r)] [(eq? (car *ls) *x) (set! *ls (cdr *ls)) (rember*r)] [else (set! *k (inner-k3 (car *ls) *k)) (set! *ls (cdr *ls)) (rember*r)]))) (define apply-k3r (lambda () (pmatch *k [(empty-k) () *v] [(inner-k ,n ,k) () (set! *k k) (set! *v (cons n *v)) (apply-k3r)] [(outer-k ,x ,ls ,k) () (set! *k (inner-k3 *v k)) (set! *x x) (set! *ls ls) (rember*r)]))) (define *x `0) (define *ls `6) (define *k `2) (define *v `3) ;4 (define apply-k4 (lambda (k v) (pmatch k [(empty-k) () v] [(inner-k ,n ,k) () (let ((dfirst (add1 n)) (drest v)) (apply-k4 k (if (< dfirst drest) drest dfirst)))] [(outer-k ,s ,k) () (depth s (inner-k4 v k))]))) (define inner-k4 (lambda (n k) `(inner-k ,n ,k))) (define outer-k4 (lambda (s k) `(outer-k ,s ,k))) (define deptho (lambda (s k) (cond [(null? s) (apply-k4 k 1)] [(pair? (car s)) (depth (car s) (outer-k4 (cdr s) k))] [else (deptho (cdr s) k)]))) (define depth (lambda (ls k) (set! *ls ls) (set! *k k) (depthr))) (define depthr (lambda () ;ls k (cond [(null? *ls) (set! *v 1) (apply-k4r)] [(pair? (car *ls)) (set! *k (outer-k4 (cdr *ls) *k)) (set! *ls (car *ls)) (depthr)] [else (set! *ls (cdr *ls)) (depthr)]))) (define apply-k4r (lambda () ;k v (pmatch *k [(empty-k) () *v] [(inner-k ,n ,k) () (set! n (add1 n)) (set! *k k) (if (< n *v) (set! *v v) (set! *v n)) (apply-k4r)] [(outer-k ,ls ,k) () (set! *k (inner-k4 *v k)) (set! *ls ls) (depthr)]))) (define *ls `0) (define *v `1) (define *k `2) ;5 (define other-k5 (lambda (n k) `(other-k ,n ,k))) (define A (lambda (n m k) (set! *n n) (set! *m m) (set! *k k) (Ar))) (trace-define Ar ;the pirate function (lambda () ;n m k (cond [(zero? *n) (set! *m (add1 *m)) (apply-k5r)] [(zero? *m) (set! *n (sub1 *n)) (set! *m 1) (Ar)] [else (set! *k (other-k5 (sub1 *n) *k)) (set! *m (sub1 *m)) (Ar)]))) (define apply-k5r (lambda () ;k v? (pmatch *k [(empty-k) () *m] [(other-k ,n ,k) () (set! *k k) (set! *n n) (Ar)]))) (define *n `0) (define *m `1) (define *k `2) ;6 ;This does not appear to ever create new k's. (define apply-k6 (lambda (k v) (pmatch k [(empty-k)() v]))) (define apply-k6r (lambda () ;k v? (pmatch *k [(empty-k)() *n] [(other-k ,n ,k) () n]))) (define C (lambda (n k) (set! *n n) (set! *k k) (Cr))) (define Cr (lambda () ;n k (cond [(zero? (sub1 *n)) (set! *k (other-k6 1 *k)) (apply-k6r)] [(even? *n) (set! *n (quotient *n 2)) (Cr)] [else (set! *n (add1 (* 3 n))) (Cr)]))) (define *n `0) (define *k `1) ;7 (trace-define apply-k7 (lambda (k v) (pmatch k [(empty-k) () v] [(inner-k ,v* ,k) () (apply-k7 k (cons v v*))] [(middle-k ,ls ,k) () (m (car ls) (inner-k7 v k))] [(outer-k ,ls ,k) () (v (cdr ls) (middle-k7 ls k))]))) (define inner-k7 (lambda (v k) `(inner-k ,v ,k))) (define middle-k7 (lambda (ls k) `(middle-k ,ls ,k))) (trace-define outer-k7 (lambda (ls k) `(outer-k ,ls ,k))) (define Mo (lambda (f k) (k (lambda (ls k) (cond [(null? ls) (k '())] [else (Mo f (lambda (p) (p (cdr ls) (lambda (d) (f (car ls) (lambda (a) (k (cons a d))))))))]))))) (define M (lambda (f k) (Mt f k))) (trace-define Mt (lambda (f k) (apply-k7 k (lambda (ls k) (cond [(null? ls) (apply-k7 k '())] [else (Mt f (outer-k7 k ls))]))))) ;Helpers (define empty-k `(empty-k)) (define empty-kt (lambda (j) `(empty-k ,j))) (define tramp (lambda (th) (tramp(th)))) ;END
false
8bc0ff504fd12db38d694f4d721de167351f4344
4f91474d728deb305748dcb7550b6b7f1990e81e
/Chapter1/book1.1.4.scm
1a7a7c761a384996d3cdb02cb9d011bae0446c6a
[]
no_license
CanftIn/sicp
e686c2c87647c372d7a6a0418a5cdb89e19a75aa
92cbd363c143dc0fbf52a90135218f9c2bf3602d
refs/heads/master
2021-06-08T22:29:40.683514
2020-04-20T13:23:59
2020-04-20T13:23:59
85,084,486
2
0
null
null
null
null
UTF-8
Scheme
false
false
359
scm
book1.1.4.scm
(define (square x) (* x x)) (begin (display (square 21)) (newline) (display (square (+ 2 5))) (newline) (display (square (square 3))) (newline)) (define (sum-of-squares x y) (+ (square x) (square y))) (begin (display (sum-of-squares 3 4)) (newline))
false
4b06980015d8a2464477040503c6556d62eb19db
d369542379a3304c109e63641c5e176c360a048f
/brice/Chapter1/exercise-1.18.scm
bcf537bd6de4c5aa35943d4304c4e71ea7c46443
[]
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
405
scm
exercise-1.18.scm
#lang racket (display "\nEXCERCISE 1.18\n") (define (half x) (/ x 2)) (define (double x) (+ x x)) (define (dec x) (- x 1)) (define (multiply-inner x y a) (cond ((= x 0) a) ((odd? x) (multiply-inner (dec x) y (+ a y) )) ((even? x) (multiply-inner (half x) (double y) a )))) (multiply-inner 3 6 0) ;-> 18 (multiply-inner 3 3 0) ;-> 9 (multiply-inner 4 5 0) ;-> 20
false
5869ef720c8957c832824a93f8c6d456eea36b6d
ee10242f047e9b4082a720c48abc7d94fe2b64a8
/run-tests.sch
85ceb9af3976c6acf55d24c1dc2ef5e8c861aaa9
[ "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
431
sch
run-tests.sch
(require "tests/math-test.sch") (require "tests/clos-test.sch") (require "tests/random-test.sch") (require "tests/lang-test.sch") (require "tests/hash-test.sch") (require "tests/list-test.sch") (time (if (combine-results (basic-arith) (clos-test) (lang-test) (mersenne-test) (hash-table-test) (list-test)) (display "all tests pass!\n") (display "there were failures\n"))) (exit 0)
false
8b7675ad8a4651b02696d5c0b61597a9367e591b
defeada37d39bca09ef76f66f38683754c0a6aa0
/System.Xml/mono/xml/xsl/operations/xsl-fallback.sls
bdb917ebba91d68d9295524f4817dca639e4c301
[]
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
559
sls
xsl-fallback.sls
(library (mono xml xsl operations xsl-fallback) (export new is? xsl-fallback? evaluate) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new Mono.Xml.Xsl.Operations.XslFallback a ...))))) (define (is? a) (clr-is Mono.Xml.Xsl.Operations.XslFallback a)) (define (xsl-fallback? a) (clr-is Mono.Xml.Xsl.Operations.XslFallback a)) (define-method-port evaluate Mono.Xml.Xsl.Operations.XslFallback Evaluate (System.Void Mono.Xml.Xsl.XslTransformProcessor)))
true
6ab16b9c525d381b859a3217d57841e7a72441ee
982919bd7728330f3bb6568f22dfd0d4e348affa
/dynamic-scope/utility/eval.ss
786e5df3c0915649f92c8069b3ab3c3de171f49a
[]
no_license
thzt/scheme-interpreter
9fb389ea9146e2a5a8d7fa6ef2808d4c25c035d3
267dc29aec2e02df8f7de4b1072466d12a97248d
refs/heads/master
2021-01-19T17:13:10.368468
2015-10-30T09:40:40
2015-10-30T09:40:40
39,499,402
8
0
null
null
null
null
UTF-8
Scheme
false
false
1,664
ss
eval.ss
(library (utility eval) (export eval-exp) (import (rnrs) (utility tool) (utility datatype)) (define (eval-exp exp) (handle-decision-tree `((,is-symbol? ,eval-symbol) (,is-self-eval-exp? ,eval-self-eval-exp) (,is-list? ((,is-lambda? ,eval-lambda) (,is-function-call-list? ,eval-function-call-list)))) exp)) (define *env* `(,(create-frame))) (define (is-symbol? exp) (display "is-symbol?\n") (symbol? exp)) (define (eval-symbol exp) (display "eval-symbol\n") (get-symbol-value *env* exp)) (define (is-self-eval-exp? exp) (display "is-self-eval-exp?\n") (number? exp)) (define (eval-self-eval-exp exp) (display "eval-self-eval-exp\n") exp) (define (is-list? exp) (display "is-list?\n") (list? exp)) (define (is-lambda? exp) (display "is-lambda?\n") (eq? (car exp) 'lambda)) (define (eval-lambda exp) (display "eval-lambda\n") (let ((param (caadr exp)) (body (caddr exp))) (make-function param body))) (define (is-function-call-list? exp) (display "is-function-call-list?\n") #t) (define (eval-function-call-list exp) (display "eval-function-call-list\n") (let* ((function (eval-exp (car exp))) (arg (eval-exp (cadr exp))) (body (function-body function)) (param (function-param function)) (frame (create-frame))) (extend-frame frame param arg) (let* ((env *env*) (value '())) (set! *env* (extend-env *env* frame)) (set! value (eval-exp body)) (set! *env* env) value))) )
false
489399d420129f0ab6bf56b86d8ae0f033bda807
3508dcd12d0d69fec4d30c50334f8deb24f376eb
/tests/runtime/test-entity.scm
9623d221ccf706e0dc5999f7fb94614550edccbe
[]
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
4,874
scm
test-entity.scm
#| -*-Scheme-*- Copyright (C) 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022 Massachusetts Institute of Technology This file is part of MIT/GNU Scheme. MIT/GNU Scheme is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. MIT/GNU Scheme is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MIT/GNU Scheme; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. |# ;;;; Test of entities and apply hooks (declare (usual-integrations)) (define (some-procedure foo) foo) (define some-extra (list 'FOO 42)) ((lambda (descriptors) ((lambda (f) (for-each (lambda (descriptor) (apply f descriptor)) descriptors)) (lambda (name constructor predicate get-procedure get-extra) (define-test (symbol name '?) (lambda () (assert-true (predicate (constructor some-procedure some-extra))))) (define-test (symbol name '- 'PROCEDURE) (lambda () (assert-eq some-procedure (get-procedure (constructor some-procedure some-extra))))) (define-test (symbol name '- 'EXTRA) (lambda () (assert-eq some-extra (get-extra (constructor some-procedure some-extra))))))) ((lambda (f) (for-each (lambda (descriptor) (for-each (lambda (descriptor*) (if (not (eq? (car descriptor) (car descriptor*))) (apply f (append descriptor descriptor*)))) descriptors)) descriptors)) (lambda (name constructor predicate get-procedure get-extra name* constructor* predicate* get-procedure* get-extra*) constructor predicate* get-procedure* get-extra* (define-test (symbol name '? '/ name*) (lambda () (assert-false (predicate (constructor* some-procedure some-extra))))) (define-test (symbol name '? '/ 'JUNK) (lambda () (assert-false (predicate some-extra)))) (define-test (symbol name '- 'PROCEDURE '/ name*) (lambda () (let ((object* (constructor* some-procedure some-extra))) (assert-error (lambda () (get-procedure object*)) (list condition-type:wrong-type-argument))))) (define-test (symbol name '- 'PROCEDURE '/ 'JUNK) (lambda () (assert-error (lambda () (get-procedure some-extra)) (list condition-type:wrong-type-argument)))) (define-test (symbol name '- 'EXTRA '/ name*) (lambda () (let ((object* (constructor* some-procedure some-extra))) (assert-error (lambda () (get-extra object*)) (list condition-type:wrong-type-argument))))) (define-test (symbol name '- 'EXTRA '/ 'JUNK) (lambda () (assert-error (lambda () (get-extra some-extra)) (list condition-type:wrong-type-argument))))))) `((ENTITY ,make-entity ,entity? ,entity-procedure ,entity-extra) (APPLY-HOOK ,make-apply-hook ,apply-hook? ,apply-hook-procedure ,apply-hook-extra))) (define-test 'ENTITY-APPLICATION/0 (lambda () (let ((entity (make-entity some-procedure some-extra))) (assert-eq entity (entity))))) (define-test 'ENTITY-APPLICATION/1 (lambda () (let ((entity (make-entity some-procedure some-extra))) (assert-error (lambda () (entity 42)) (list condition-type:wrong-number-of-arguments))))) (define-test 'APPLY-HOOK-APPLICATION/0 (lambda () (let ((apply-hook (make-apply-hook some-procedure some-extra))) (assert-error (lambda () (apply-hook)) (list condition-type:wrong-number-of-arguments))))) (define-test 'ENTITY-APPLICATION/1 (lambda () (assert-eqv 42 ((make-apply-hook some-procedure some-extra) 42)))) (define-test 'ENTITY-CHAIN (lambda () (let* ((e0 (make-entity some-procedure some-extra)) (e1 (make-entity e0 'ZARQUON)) (e2 (make-entity e1 'QUAGGA))) (assert-error (lambda () (set-entity-procedure! e0 e2)) (list condition-type:bad-range-argument)))))
false
3988dac0669bd903d45e7262c1a64ae41775360a
ef4a98e8994ab0af95e5e6b18eae25c26e49eae3
/forthqk.ss
cdc734b8391803a4adcd2ebfec65e3cb8e1259fb
[ "MIT" ]
permissive
tojoqk/forthqk
8257ca084792d09c68435d62adab4549b36af4e2
a46e08b2c9e9e487e1507dd8326e4dbb8d0054a8
refs/heads/master
2020-04-02T17:39:25.793989
2019-02-04T15:00:19
2019-02-04T15:00:19
154,666,159
2
0
Apache-2.0
2019-02-04T15:00:20
2018-10-25T12:21:39
Scheme
UTF-8
Scheme
false
false
9,052
ss
forthqk.ss
#!r6rs (import (except (rnrs) read)) (define-record-type (stack %make-stack stack?) (fields [mutable index] [immutable data])) (define (make-stack n) (%make-stack 0 (make-vector n))) (define (stack-pop! st) (let ([idx (stack-index st)] [dat (stack-data st)]) (stack-index-set! st (- idx 1)) (vector-ref dat (- idx 1)))) (define (stack-push! st x) (let ([idx (stack-index st)] [vec (stack-data st)]) (vector-set! vec idx x) (stack-index-set! st (+ idx 1)))) (define (stack-top st) (vector-ref (stack-data st) (- (stack-index st) 1))) (define (stack-empty? st) (zero? (stack-index st))) (define (stack->list st) (let ([idx (stack-index st)] [data (stack-data st)]) (let loop ([i (- idx 1)] [acc '()]) (if (< i 0) acc (loop (- i 1) (cons (vector-ref data i) acc)))))) (define-record-type (state make-state state?) (fields [immutable word-table] [immutable stack])) (define (empty-word-table) (make-eq-hashtable)) (define-syntax define/forthqk (lambda (x) (syntax-case x () [(_ (name args ...) wt n body ...) (let ([n (syntax->datum #'n)]) (with-syntax ([(g ...) (generate-temporaries #'(args ...))] [(r ...) (generate-temporaries (let loop ([i 0]) (if (= i n) '() (cons #t (loop (+ i 1))))))]) #`(let () (define (sym z) (if (string? z) (string->symbol z) z)) (hashtable-set! wt (sym 'name) (lambda (s) (let* ([st (state-stack s)] [g (stack-pop! st)] ...) (let-values ([(r ...) (#,@(cons #'(lambda (args ...) body ...) (reverse #'(g ...))))]) (stack-push! st r) ... s)))))))]))) (define (primitive-word-table) (let ([wt (empty-word-table)]) (define/forthqk (+ x y) wt 1 (+ x y)) (define/forthqk (+ x y) wt 1 (+ x y)) (define/forthqk (* x y) wt 1 (* x y)) (define/forthqk (- x y) wt 1 (- x y)) (define/forthqk (= x y) wt 1 (if (= x y) 1 0)) (define/forthqk (< x y) wt 1 (if (< x y) 1 0)) (define/forthqk (> x y) wt 1 (if (> x y) 1 0)) (define/forthqk (swap x y) wt 2 (values y x)) (define/forthqk (rot x y z) wt 3 (values z x y)) (define/forthqk (over x y) wt 3 (values x y x)) (define/forthqk (dup x) wt 2 (values x x)) (define/forthqk (drop x) wt 0 (values)) (define/forthqk (cr) wt 0 (newline) (values)) (define/forthqk ("." x) wt 0 (display x) (values)) (hashtable-set! wt 'dump (lambda (s) (let ([st (state-stack s)]) (display (reverse (stack->list st))) (newline) s))) wt)) (define (token->value token) (cond [(string->number token) => (lambda (x) x)] [(string=? token "#t") #t] [(string=? token "#f") #f] [else (string->symbol token)])) (define (read in) (define tokens (tokenize in)) (if (eof-object? tokens) (eof-object) (let-values ([(tokens exprs) (read-tokens in (map token->value tokens) '() (make-stack 4096))]) (if (null? tokens) (reverse exprs) (error 'read "error"))))) (define (next-token in tokens st) (cond [(null? tokens) (cond [(not (stack-empty? st)) (let ([tokens (tokenize in)]) (cond [(eof-object? tokens) (error 'read "unexpected eof")] [(null? tokens) (next-token in tokens st)] [else (values (car tokens) (cdr tokens))]))] [else (values (eof-object) '())])] [else (values (car tokens) (cdr tokens))])) (define (read-tokens in tokens exprs st) (let-values ([(token tokens) (next-token in tokens st)]) (cond [(eof-object? token) (values tokens exprs)] [(eq? token ':) (read-define in tokens exprs st)] [(eq? token (string->symbol ";")) (if (eq? (stack-top st) ':) (values tokens exprs) (error 'read "unexpected \";\""))] [(eq? token 'if) (read-if in tokens exprs st)] [(eq? token 'else) (if (eq? (stack-top st) 'if) (values tokens exprs) (error 'read "unexpected \"else\""))] [(eq? token 'then) (if (eq? (stack-top st) 'else) (values tokens exprs) (error 'read "unexpected \"then\""))] [else (read-tokens in tokens (cons token exprs) st)]))) (define (read-define in tokens exprs st) (let-values ([(tokens word exprs*) (begin (stack-push! st ':) (let*-values ([(word tokens) (next-token in tokens st)] [(tokens exprs*) (read-tokens in tokens '() st)]) (stack-pop! st) (values tokens word exprs*)))]) (read-tokens in tokens (cons `(: ,word ,@(reverse exprs*)) exprs) st))) (define (read-if in tokens exprs st) (stack-push! st 'if) (let-values ([(tokens then-exprs) (read-tokens in tokens '() st)]) (stack-pop! st) (stack-push! st 'else) (let-values ([(tokens else-exprs) (read-tokens in tokens '() st)]) (stack-pop! st) (read-tokens in tokens (cons `(if ,(reverse then-exprs) ,(reverse else-exprs)) exprs) st)))) (define (tokenize in) (let-values ([(port get) (open-string-output-port)]) (define tokens (parse-token in port get '())) (if (eof-object? tokens) (eof-object) (reverse tokens)))) (define (parse-token in port get tokens) (define c (read-char in)) (define (get-token) (let ([str (get)]) (if (zero? (string-length str)) #f str))) (cond [(eof-object? c) (if (and (null? tokens) (not (get-token))) (eof-object) (error 'parse-token "unexpected eof"))] [(char=? c #\newline) (cond [(get-token) => (lambda (token) (cons token tokens))] [else tokens])] [(char-whitespace? c) (skip-whitespace in get (cond [(get-token) => (lambda (token) (cons token tokens))] [else tokens]))] [else (write-char c port) (parse-token in port get tokens)])) (define (skip-whitespace in get tokens) (define c (peek-char in)) (cond [(eof-object? c) (eof-object)] [(char=? c #\newline) (read-char in) tokens] [(char-whitespace? c) (read-char in) (skip-whitespace in get tokens)] [else (let-values ([(port get) (open-string-output-port)]) (parse-token in port get tokens))])) (define eval (case-lambda [(es s) (if (null? es) s (let ([e (car es)] [es (cdr es)]) (cond [(symbol? e) (eval-word e es s)] [(not (pair? e)) (stack-push! (state-stack s) e) (eval es s)] [(eq? 'if (car e)) (eval-if e es s)] [(eq? ': (car e)) (eval-: e es s)] [else (error 'error "?")])))] [(es) (eval es (initial-state))])) (define (eval-word e es s) (eval es ((hashtable-ref (state-word-table s) e (lambda (s) (error 'forthqk (string-append "undefine word (" (symbol->string e) ")")))) s))) (define (eval-if e es s) (if (= 0 (stack-pop! (state-stack s))) (eval (caddr e) s) (eval (cadr e) s))) (define (eval-: e es s) (hashtable-set! (state-word-table s) (car (cdr e)) (let ([body (cdr (cdr e))]) (lambda (s) (eval body s)))) (eval es s)) (define (initial-state) (make-state (primitive-word-table) (make-stack 4096))) (define repl (case-lambda [(in) (let loop ([state (initial-state)]) (flush-output-port (current-output-port)) (let ([result (read in)]) (cond [(eof-object? result) 'done] [else (loop (eval result state))])))] [() (repl (current-input-port))])) (repl)
true
964002d07be623c4a43fa92fc76d61c5ea976c2d
120324bbbf63c54de0b7f1ca48d5dcbbc5cfb193
/packages/dharmalab/records/define-method.sls
1e883cd892133344793bce8233dbe3768bbe1457
[ "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
1,528
sls
define-method.sls
;; Copyright 2016 Eduardo Cavazos ;; ;; 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. (library (dharmalab records define-method) (export define-method) (import (rnrs) (dharmalab misc gen-id) (dharmalab records define-record-type)) (define-syntax define-method (lambda (stx) (syntax-case stx () ( (define-method class (method-name param ...) expr ...) (with-syntax ( ( import-type (gen-id #'class "import-" #'class) ) ( class::method (gen-id #'class #'class "::" #'method-name) ) ( self (gen-id #'class "self") ) ( (param ...) (map (lambda (x) (gen-id #'class x)) #'(param ...)) ) ) (syntax (define (class::method self param ...) (import-type self) expr ...))))))))
true
1593b8f08fcb004f7f10c8477d9e83c171d3d90b
dd4cc30a2e4368c0d350ced7218295819e102fba
/vendored_parsers/vendor/tree-sitter-javascript/queries/tags.scm
a7bbd311a4ea318a541e07e160daefe6ab459697
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
Wilfred/difftastic
49c87b4feea6ef1b5ab97abdfa823aff6aa7f354
a4ee2cf99e760562c3ffbd016a996ff50ef99442
refs/heads/master
2023-08-28T17:28:55.097192
2023-08-27T04:41:41
2023-08-27T04:41:41
162,276,894
14,748
287
MIT
2023-08-26T15:44:44
2018-12-18T11:19:45
Rust
UTF-8
Scheme
false
false
1,940
scm
tags.scm
( (comment)* @doc . (method_definition name: (property_identifier) @name) @definition.method (#not-eq? @name "constructor") (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") (#select-adjacent! @doc @definition.method) ) ( (comment)* @doc . [ (class name: (_) @name) (class_declaration name: (_) @name) ] @definition.class (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") (#select-adjacent! @doc @definition.class) ) ( (comment)* @doc . [ (function name: (identifier) @name) (function_declaration name: (identifier) @name) (generator_function name: (identifier) @name) (generator_function_declaration name: (identifier) @name) ] @definition.function (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") (#select-adjacent! @doc @definition.function) ) ( (comment)* @doc . (lexical_declaration (variable_declarator name: (identifier) @name value: [(arrow_function) (function)]) @definition.function) (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") (#select-adjacent! @doc @definition.function) ) ( (comment)* @doc . (variable_declaration (variable_declarator name: (identifier) @name value: [(arrow_function) (function)]) @definition.function) (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") (#select-adjacent! @doc @definition.function) ) (assignment_expression left: [ (identifier) @name (member_expression property: (property_identifier) @name) ] right: [(arrow_function) (function)] ) @definition.function (pair key: (property_identifier) @name value: [(arrow_function) (function)]) @definition.function ( (call_expression function: (identifier) @name) @reference.call (#not-match? @name "^(require)$") ) (call_expression function: (member_expression property: (property_identifier) @name) arguments: (_) @reference.call) (new_expression constructor: (_) @name) @reference.class
false
1f71da052da5ccec80e6bcc4ae9963c4b272cd85
a7163e66395accd24b83f783ffa6253c5ac263f0
/wsi
2aee981fc6e2fb2762a92b3c3a397254b81ebbb9
[ "MIT" ]
permissive
athos/white-scheme
4a85b0d48bf4fbe2d6c7e2cdb2cbfc01a0b0765d
6f6887eef0c1939e5265d99d1afd3f941f8170d8
refs/heads/master
2021-01-02T22:30:52.819612
2010-12-24T16:30:56
2010-12-24T16:30:56
1,191,614
1
1
null
null
null
null
UTF-8
Scheme
false
false
5,450
wsi
#!/usr/bin/env gosh ;; -*- mode: scheme -*- (define-module white-scheme.interpreter (use util.match) (use srfi-1) (use file.util) (export run-interpreter)) (select-module white-scheme.interpreter) (define (tokenize c) (case c [(#\space) 'S] [(#\tab) 'T] [(#\x0a) 'L])) (define-syntax define-insn-parsers (syntax-rules () [(_ def0 def1 ...) (begin (define-insn-parser def0) (define-insn-parser def1) ...)])) (define-syntax define-insn-parser (syntax-rules (N L) [(_ (name)) (define (name code) (values '(name) code))] [(_ (name N)) (define (name code) (receive (n code) (parse-number code) (values `(name ,n) code)))] [(_ (name L)) (define (name code) (receive (l code) (parse-label code) (values `(name ,l) code)))])) (define-insn-parsers (PUSH N) (COPY N) (SLIDE N) (DUP) (SWAP) (POP) (ADD) (SUB) (MUL) (DIV) (MOD) (STORE) (RETR) (PUTC) (PUTN) (GETC) (GETN) (LABEL L) (CALL L) (JUMP L) (BZERO L) (BNEG L) (RET) (QUIT)) (define *tokens->insn-parser* `((S (S . ,PUSH) (T (S . ,COPY) (L . ,SLIDE)) (L (S . ,DUP) (T . ,SWAP) (L . ,POP))) (T (S (S (S . ,ADD) (T . ,SUB) (L . ,MUL)) (T (S . ,DIV) (T . ,MOD))) (T (S . ,STORE) (T . ,RETR)) (L (S (S . ,PUTC) (T . ,PUTN)) (T (S . ,GETC) (T . ,GETN)))) (L (S (S . ,LABEL) (T . ,CALL) (L . ,JUMP)) (T (S . ,BZERO) (T . ,BNEG) (L . ,RET)) (L (L . ,QUIT))))) ;; Parser: tokens -> instructions (define (parse code insns) (define (rec code is) (match code [() (if (eq? is insns) '() (error "unexpected EOF"))] [(token . code) (if-let1 v (assq token is) (if (pair? (cdr v)) (rec code (cdr v)) (let1 parser (cdr v) (receive (insn code) (parser code) (cons insn (rec code insns))))) (error "unexpected token" token))])) (rec code insns)) (define (parse-number code) (define (rec code sign n) (match code [('S . code) (rec code sign (* n 2))] [('T . code) (rec code sign (+ (* n 2) 1))] [('L . code) (values (sign n) code)] [() (error "unexpected EOF")])) (let* ([sign (car code)] [code (cdr code)]) (case sign [(S) (rec code identity 0)] [(T) (rec code - 0)] [else (error "unexpected token" sign)]))) (define (parse-label code) (define (rec code ts) (match code [(t . code) (if (or (eq? t 'S) (eq? t 'T)) (rec code (cons t ts)) (values (string->symbol (string-join (reverse (map symbol->string ts)) "")) code))] [() (error "unexpected EOF")])) (rec code '())) ;; Assembler: resolves labels (define (assemble code) (define (copy-tree t) (if (pair? t) (cons (copy-tree (car t)) (copy-tree (cdr t))) t)) (define (scan code insns labels) (match code [() (values insns labels)] [((and (command . args) insn) . code*) (case command [(LABEL) (if (assq (car args) labels) (error "duplicate label") (scan code* insns (acons (car args) code labels)))] [(CALL JUMP BZERO BNEG) (scan code* (cons insn insns) labels)] [else (scan code* insns labels)])])) (let1 code (copy-tree code) (receive (insns labels) (scan code '() '()) (dolist (insn insns) (if-let1 label (assq (cadr insn) labels) (set-cdr! insn (cdr label)) (error "unknown label")))) code)) ;; Executor: executes instructions (define (execute code heap) (define (step code vstack heap rstack) (define (next vstack) (step (cdr code) vstack heap rstack)) (define (arith op) (next (cons (op (cadr vstack) (car vstack)) (cddr vstack)))) (match code [() #t] [((comm . args) . code) (case comm [(PUSH) (next (cons (car args) vstack))] [(COPY) (next (cons (list-ref vstack (car args)) vstack))] [(SLIDE) (next (cons (car vstack) (drop vstack (car args))))] [(DUP) (next (cons (car vstack) vstack))] [(SWAP) (next (cons* (cadr vstack) (car vstack) (cddr vstack)))] [(POP) (next (cdr vstack))] [(ADD) (arith +)] [(SUB) (arith -)] [(MUL) (arith *)] [(DIV) (arith quotient)] [(MOD) (arith remainder)] [(STORE) (vector-set! heap (cadr vstack) (car vstack)) (next (cddr vstack))] [(RETR) (next (cons (vector-ref heap (car vstack)) (cdr vstack)))] [(PUTC) (display (integer->char (car vstack))) (flush) (next (cdr vstack))] [(PUTN) (display (car vstack)) (flush) (next (cdr vstack))] [(GETC) (let1 c (read-char) (next (cons (char->integer c) vstack)))] [(GETN) (let1 n (read) (next (cons n vstack)))] [(LABEL) (next vstack)] [(CALL) (step args vstack heap (cons code rstack))] [(JUMP L) (step args vstack heap rstack)] [(BZERO L) (if (zero? (car vstack)) (step args (cdr vstack) heap rstack) (next (cdr vstack)))] [(BNEG L) (if (negative? (car vstack)) (step args (cdr vstack) heap rstack) (next (cdr vstack)))] [(RET) (step (car rstack) vstack heap (cdr rstack))] [(QUIT) #t])])) (step code '() heap '())) (define (run-interpreter args) (let1 code (string->list (file->string (cadr args))) (execute (assemble (parse (map tokenize code) *tokens->insn-parser*)) '#())) 0) (select-module user) (import white-scheme.interpreter) (define main run-interpreter)
true
a17adeabf4c759a7ca104b2198fe85ecbd4d07fb
6f86602ac19983fcdfcb2710de6e95b60bfb0e02
/exercises/practice/pascals-triangle/test.scm
d5f17aee0127d36f1dd8a0be066409fe41268ab6
[ "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
1,003
scm
test.scm
(load "test-util.ss") (define test-cases `((test-success "zero rows" equal? pascals-triangle '(0) '()) (test-success "single row" equal? pascals-triangle '(1) '((1))) (test-success "two rows" equal? pascals-triangle '(2) '((1) (1 1))) (test-success "three rows" equal? pascals-triangle '(3) '((1) (1 1) (1 2 1))) (test-success "four rows" equal? pascals-triangle '(4) '((1) (1 1) (1 2 1) (1 3 3 1))) (test-success "five rows" equal? pascals-triangle '(5) '((1) (1 1) (1 2 1) (1 3 3 1) (1 4 6 4 1))) (test-success "six rows" equal? pascals-triangle '(6) '((1) (1 1) (1 2 1) (1 3 3 1) (1 4 6 4 1) (1 5 10 10 5 1))) (test-success "ten rows" equal? pascals-triangle '(10) '((1) (1 1) (1 2 1) (1 3 3 1) (1 4 6 4 1) (1 5 10 10 5 1) (1 6 15 20 15 6 1) (1 7 21 35 35 21 7 1) (1 8 28 56 70 56 28 8 1) (1 9 36 84 126 126 84 36 9 1))))) (run-with-cli "pascals-triangle.scm" (list test-cases))
false
f2a545c03d550d8c8b8b02fedec3c14dbdca7b0b
1645add1bc3f780e0deaf3ca323b263037065c8f
/chicken-ext-jbogensamselpla.scm
96111dd7e212d96b5dce58c9c2868f82c45c6efb
[ "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
12,603
scm
chicken-ext-jbogensamselpla.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. ;;;; (module jbogensamselpla (a e i o u y l m n r b d g v j z s c x k f p t h digit final-syllable any-syllable syllable consonantal-syllable coda onset diphthong cluster initial-pair initial affricate brivla-gismu brivla-fuhivla brivla-lujvo zifcme jbocme CVCy-lujvo-brivla-core CVCy-lujvo-short-final-rafsi cmavo-form cmavo-form-y lujvo brivla-core fuhivla stressed-brivla-rafsi brivla-rafsi stressed-fuhivla-rafsi fuhivla-rafsi brivla-head slinkuhi rafsi-string rafsi-string-short-final rafsi-string-initial-pair gismu CVV-final-rafsi short-final-rafsi stressed-y-rafsi stressed-long-rafsi-CCVC stressed-long-rafsi-CVCC stressed-CVC-rafsi stressed-CCV-rafsi stressed-CVV-rafsi stressed-CVV-rafsi-VhV y-rafsi long-rafsi-CCVC long-rafsi-CVCC CVC-rafsi CCV-rafsi CVV-rafsi CVV-rafsi-VhV non-lojban-word ybu cmavo A BAI BAhE BE BEI BEhO BIhE BIhI BO BOI BU BY CAhA CAI CEI CEhE CO COI CU CUhE DAhO DOI DOhU FA FAhA FAhO FEhE FEhU FIhO FOI FUhA FUhE FUhO GA GAhO GEhU GI GIhA GOI GOhA GUhA I JA JAI JOhI JOI KE KEhE KEI KI KOhA KU KUhE KUhO LA LAU LAhE LE LEhU LI LIhU LOhO LOhU LU LUhU MAhO MAI ME MEhU MOhE MOhI MOI NA NAI NAhE NAhU NIhE NIhO NOI NU NUhA NUhI NUhU PA PEhE PEhO PU RAhO ROI SA SE SEI SEhU SI SOI SU TAhE TEhU TEI TO TOI TUhE TUhU UI VA VAU VEI VEhO VEhA VIhA VUhO VUhU XI Y ZAhO ZEhA ZEI ZI ZIhE ZO ZOI ZOhU text intro-null text-part-2 intro-si-clause faho-clause text-1-I text-1-NIhO text-1-paragraphs paragraphs paragraph statement statement-prenex statement-1 statement-2 statement-3 statement-3-TUhE fragment-prenex fragment-terms fragment-ek fragment-gihek fragment-quantifier fragment-NA fragment-relative-clauses fragment-links fragment-linkargs prenex sentence sentence-sa sentence-start-I sentence-start-NIhO subsentence subsentence-prenex bridi-tail bridi-tail-sa bridi-tail-start-ME bridi-tail-start-NUhA bridi-tail-start-NU bridi-tail-start-NA bridi-tail-start-NAhE bridi-tail-start-selbri bridi-tail-start-tag bridi-tail-start-KE bridi-tail-start bridi-tail-1 bridi-tail-2 bridi-tail-3-selbri bridi-tail-3-gek gek-sentence gek-sentence-KE gek-sentence-NA tail-terms terms terms-1 terms-2 pehe-sa cehe-sa term term-1-sumti term-1-FA term-1-FA-tag term-1-FA-clause term-1-FA-sumti term-1-FA-KU term-1-termset term-1-NA term-sa term-start term-start-LA term-start-LE term-start-LI term-start-LU term-start-LAhE term-start-quantifier term-start-gek term-start-FA term-start-tag termset termset-gek terms-gik-terms gek-termset termset-terms sumti sumti-1 sumti-2 sumti-3 sumti-4 sumti-4-gek sumti-5 sumti-5-selbri sumti-6-ZO sumti-6-ZOI sumti-6-LOhU sumti-6-BOI sumti-6-LU sumti-6-LAhE-clause sumti-6-LAhE-NAhE sumti-6-LAhE sumti-6-KOhA sumti-6-LA sumti-6-LE sumti-6-LI sumti-tail-sumti-6 sumti-tail sumti-tail-1-selbri sumti-tail-1-sumti relative-clauses relative-clause relative-clause-sa relative-clause-1-GOI relative-clause-1-NOI relative-clause-start selbri selbri-1 selbri-1-NA selbri-2 selbri-3 selbri-4 selbri-4-joik-jek selbri-4-joik selbri-5 selbri-6 selbri-6-NAhE tanru-unit tanru-unit-1 tanru-unit-2-BRIVLA tanru-unit-2-GOhA tanru-unit-2-KE tanru-unit-2-ME tanru-unit-2-MOI tanru-unit-2-NUhA tanru-unit-2-SE tanru-unit-2-JAI tanru-unit-2-NAhE tanru-unit-2-NU linkargs linkargs-1 linkargs-sa linkargs-start links links-sa links-1 links-start quantifier-BOI quantifier-VEI mex mex-sa mex-0 mex-0-rp mex-start-FUhA mex-start-PEhO mex-start rp-clause mex-1 mex-2 mex-forethought fore-operands rp-expression rp-expression-tail operator operator-0 operator-0-joik-jek operator-0-joik operator-sa operator-start operator-start-KE operator-start-NAhE operator-start-MAhO operator-start-VUhU operator-1 operator-gukek operator-jek operator-2 operator-2-KE mex-operator mex-operator-NAhE mex-operator-MAhO mex-operator-NAhU mex-operator-VUhU operand operand-sa operand-0 operand-start-quantifier operand-start-lerfu-word operand-start-NIhE operand-start-MOhE operand-start-JOhI operand-start-gek operand-start-LAhE operand-start-NAhE operand-1 operand-2 operand-3 operand-3-BOI operand-3-NIhE operand-3-MOhE operand-3-JOhI operand-3-gek operand-3-LAhE operand-3-NAhE operand-BOI number lerfu-string lerfu-word-BY lerfu-word-LAU lerfu-word-TEI ek gihek gihek-sa gihek-1 jek joik-JOI joik-interval joik-GAhO interval joik-ek joik-ek-sa joik-ek-1-joik joik-ek-1-ek joik-jek gek-GA gek-GI gek-gik guhek gik tag stag-tense stag-simple-tense tense-modal-simple-tense tense-modal-FIhO simple-tense-modal-BAI simple-tense-modal-time-space-CAhA simple-tense-modal-time-space simple-tense-modal-CAhA simple-tense-modal simple-tense-modal-KI simple-tense-modal-CUhE time-ZI time-offset space space-offset space-interval-VEhA space-interval-VIhA space-interval-VEhA-VIhA space-interval space-int-props interval-property interval-property-TAhE interval-property-ZAhO free-SEI free-SOI free-vocative-selbri free-vocative-cmene free-vocative-sumti free-MAI free-TO xi-clause-BOI xi-clause-VEI vocative indicators indicator zei-clause zei-clause-no-pre bu-clause bu-clause-no-pre zei-tail bu-tail pre-zei-bu post-clause pre-clause any-word-SA-LOhU any-word-SA-ZO any-word-SA-ZOI su-clause si-clause erasable-clause-zei erasable-clause-bu sa-word si-word su-word BRIVLA-clause BRIVLA-clause-zei BRIVLA-pre BRIVLA-post CMENE-clause CMENE-pre CMENE-post CMAVO-clause A-clause A-pre A-post BAI-clause BAI-pre BAI-post BAhE-clause BAhE-pre BAhE-post BE-clause BE-pre BE-post BEI-clause BEI-pre BEI-post BEhO-clause BEhO-pre BEhO-post BIhE-clause BIhE-pre BIhE-post BIhI-clause BIhI-pre BIhI-post BO-clause BO-pre BO-post BOI-clause BOI-pre BOI-post BU-clause BY-clause BY-pre BY-post BY-clause BY-clause-bu BY-pre BY-post CAhA-clause CAhA-pre CAhA-post CAI-clause CAI-pre CAI-post CEI-clause CEI-pre CEI-post CEhE-clause CEhE-pre CEhE-post CO-clause CO-pre CO-post COI-clause COI-pre COI-post CU-clause CU-pre CU-post CUhE-clause CUhE-pre CUhE-post DAhO-clause DAhO-pre DAhO-post DOI-clause DOI-pre DOI-post DOhU-clause DOhU-pre DOhU-post FA-clause FA-pre FA-post FAhA-clause FAhA-pre FAhA-post FAhO-clause FEhE-clause FEhE-pre FEhE-post FEhU-clause FEhU-pre FEhU-post FIhO-clause FIhO-pre FIhO-post FOI-clause FOI-pre FOI-post FUhA-clause FUhA-pre FUhA-post FUhE-clause FUhE-pre FUhE-post FUhO-clause FUhO-pre FUhO-post GA-clause GA-pre GA-post GAhO-clause GAhO-pre GAhO-post GEhU-clause GEhU-pre GEhU-post GI-clause GI-pre GI-post GIhA-clause GIhA-pre GIhA-post GOI-clause GOI-pre GOI-post GOhA-clause GOhA-pre GOhA-post GUhA-clause GUhA-pre GUhA-post I-clause I-pre I-post JA-clause JA-pre JA-post JAI-clause JAI-pre JAI-post JOhI-clause JOhI-pre JOhI-post JOI-clause JOI-pre JOI-post KE-clause KE-pre KE-post KEhE-clause KEhE-pre KEhE-post KEI-clause KEI-pre KEI-post KI-clause KI-pre KI-post KOhA-clause KOhA-pre KOhA-post KU-clause KU-pre KU-post KUhE-clause KUhE-pre KUhE-post KUhO-clause KUhO-pre KUhO-post LA-clause LA-pre LA-post LAU-clause LAU-pre LAU-post LAhE-clause LAhE-pre LAhE-post LE-clause LE-pre LE-post LEhU-clause LEhU-pre LI-clause LI-pre LI-post LIhU-clause LIhU-pre LIhU-post LOhO-clause LOhO-pre LOhO-post LOhU-clause LOhU-pre LOhU-post LU-clause LU-pre LU-post LUhU-clause LUhU-pre LUhU-post MAhO-clause MAhO-pre MAhO-post MAI-clause MAI-pre MAI-post ME-clause ME-pre ME-post MEhU-clause MEhU-pre MEhU-post MOhE-clause MOhE-pre MOhE-post MOhI-clause MOhI-pre MOhI-post MOI-clause MOI-pre MOI-post NA-clause NA-pre NA-post NAI-clause NAI-pre NAI-post NAhE-clause NAhE-pre NAhE-post NAhU-clause NAhU-pre NAhU-post NIhE-clause NIhE-pre NIhE-post NIhO-clause NIhO-pre NIhO-post NOI-clause NOI-pre NOI-post NU-clause NU-pre NU-post NUhA-clause NUhA-pre NUhA-post NUhI-clause NUhI-pre NUhI-post NUhU-clause NUhU-pre NUhU-post PA-clause PA-pre PA-post PEhE-clause PEhE-pre PEhE-post PEhO-clause PEhO-pre PEhO-post PU-clause PU-pre PU-post RAhO-clause RAhO-pre RAhO-post ROI-clause ROI-pre ROI-post SA-clause SA-pre SE-clause SE-pre SE-post SEI-clause SEI-pre SEI-post SEhU-clause SEhU-pre SEhU-post SI-clause SI-pre SI-post SOI-clause SOI-pre SOI-post SU-clause SU-pre SU-post TAhE-clause TAhE-pre TAhE-post TEhU-clause TEhU-pre TEhU-post TEI-clause TEI-pre TEI-post TO-clause TO-pre TO-post TOI-clause TOI-pre TOI-post TUhE-clause TUhE-pre TUhE-post TUhU-clause TUhU-pre TUhU-post UI-clause UI-pre UI-post VA-clause VA-pre VA-post VAU-clause VAU-pre VAU-post VEI-clause VEI-pre VEI-post VEhO-clause VEhO-pre VEhO-post VUhU-clause VUhU-pre VUhU-post VEhA-clause VEhA-pre VEhA-post VIhA-clause VIhA-pre VIhA-post VUhO-clause VUhO-pre VUhO-post XI-clause XI-pre XI-post ;Y-clause ZAhO-clause ZAhO-pre ZAhO-post ZEhA-clause ZEhA-pre ZEhA-post ZEI-clause ZEI-pre ZI-clause ZI-pre ZI-post ZIhE-clause ZIhE-pre ZIhE-post ZO-clause ZO-pre ZO-post ZO-pre ZOI-clause ZOI-pre ZOI-post ZOhU-clause ZOhU-pre ZOhU-post zoi-open zoi-word zoi-close) (import chicken) (import scheme) (require-library genturfahi) (import genturfahi) (include "c0re.scm") (include "samselpla.scm"))
false
7b90365dd08a99df45238b20d8b6701bdc7c389a
7c7e1a9237182a1c45aa8729df1ec04abb9373f0
/sicp/1/2-2.scm
05b0be2513327cb1dc7a3f5c1659c18990fcf665
[ "MIT" ]
permissive
coolsun/heist
ef12a65beb553cfd61d93a6691386f6850c9d065
3f372b2463407505dad7359c1e84bf4f32de3142
refs/heads/master
2020-04-21T15:17:08.505754
2012-06-29T07:18:49
2012-06-29T07:18:49
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
780
scm
2-2.scm
; Section 1.2.2 ; http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_sec_1.2.2 (load "../helpers") (exercise "1.11") ; f(n) = | n if n < 3 ; | f(n - 1) + 2f(n - 2) + 3f(n - 3) if n >= 3 ; Recursive solution (define (f n) (if (< n 3) n (+ (f (- n 1)) (* 2 (f (- n 2))) (* 3 (f (- n 3)))))) (output '(f 6)) ; Iterative solution (define (f n) (define (iter count x y z) (if (< count 3) z (iter (- count 1) y z (+ z (* 2 y) (* 3 x))))) (iter n 0 1 2)) (output '(f 6)) (exercise "1.12") ; Pascal's triangle (define (pascal line n) (if (or (= n 1) (= n line)) 1 (+ (pascal (- line 1) (- n 1)) (pascal (- line 1) n)))) (output '(pascal 5 3))
false
bfbe53129c77249f1dc63836ac71d6c7ee5f7d5c
4e2bb57118132e64e450671470c132205457d937
/weinholt/net/ssh/private.sls
27763e2b63cb6e861f3502531afcbaab11ff0558
[ "MIT" ]
permissive
theschemer/industria
8c4d01d018c885c0437e2575787ec987d800514f
9c9e8c2b44280d3b6bda72154a5b48461aa2aba5
refs/heads/master
2021-08-31T23:32:29.440167
2017-12-01T23:24:01
2017-12-01T23:24:01
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
12,096
sls
private.sls
;; -*- mode: scheme; coding: utf-8 -*- ;; Copyright © 2010, 2011, 2012 Göran Weinholt <[email protected]> ;; Permission is hereby granted, free of charge, to any person obtaining a ;; copy of this software and associated documentation files (the "Software"), ;; to deal in the Software without restriction, including without limitation ;; the rights to use, copy, modify, merge, publish, distribute, sublicense, ;; and/or sell copies of the Software, and to permit persons to whom the ;; Software is furnished to do so, subject to the following conditions: ;; The above copyright notice and this permission notice shall be included in ;; all copies or substantial portions of the Software. ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ;; THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;; DEALINGS IN THE SOFTWARE. #!r6rs ;; Private parsing, formatting, public key algorithms, stuff (library (weinholt net ssh private) (export ssh-packet? ssh-packet-type ssh-packet parse-signature make-signature verify-signature hash-kex-data algorithm-can-sign? algorithm-can-verify? private->public prf-sha-1 prf-sha-256 get-record read-byte read-uint32 read-bytevector read-string read-name-list read-mpint put-record put-bvstring put-name-list put-mpint integer->mpint) (import (rnrs) (only (srfi :13 strings) string-join string-prefix?) (srfi :26 cut) (weinholt bytevectors) (weinholt crypto dsa) (weinholt crypto ec) (weinholt crypto ec dsa) (weinholt crypto rsa) (weinholt crypto sha-1) (weinholt crypto sha-2) (weinholt crypto ssh-public-key) (weinholt net buffer) (weinholt struct pack) (weinholt text strings)) (define (private->public key) (cond ((rsa-private-key? key) (rsa-private->public key)) ((dsa-private-key? key) (dsa-private->public key)) ((ecdsa-private-key? key) (ecdsa-private->public key)) (else (error 'private->public "Unimplemented public key algorithm" key)))) (define (algorithm-can-sign? algorithm) (member algorithm '("ecdsa-sha2-nistp256" "ecdsa-sha2-nistp384" "ecdsa-sha2-nistp521" #;"ssh-rsa" "ssh-dss"))) (define (algorithm-can-verify? algorithm) (member algorithm '("ecdsa-sha2-nistp256" "ecdsa-sha2-nistp384" "ecdsa-sha2-nistp521" "ssh-rsa" "ssh-dss"))) (define (parse-signature sig) (define (get p) (get-bytevector-n p (get-unpack p "!L"))) (let ((p (open-bytevector-input-port sig))) (let ((type (utf8->string (get p)))) (cond ((string=? type "ssh-rsa") (list type (bytevector->uint (get p)))) ((string=? type "ssh-dss") (let* ((bv (get p)) (r (subbytevector bv 0 160/8)) (s (subbytevector bv 160/8 (* 160/8 2)))) (list type (bytevector->uint r) (bytevector->uint s)))) ((string-prefix? "ecdsa-sha2-" type) (let* ((blob (open-bytevector-input-port (get p))) (r (bytevector->uint (get blob))) (s (bytevector->uint (get blob)))) (list type r s))) (else (error 'parse-signature "Unimplemented signature algorithm" type)))))) (define (make-signature msg key) (call-with-bytevector-output-port (lambda (p) ;; TODO: RSA (cond #;((rsa-private-key? key) ) ((dsa-private-key? key) (let-values (((r s) (dsa-create-signature (sha-1->bytevector (sha-1 msg)) key))) (let ((sig (make-bytevector (* 160/8 2) 0))) (bytevector-uint-set! sig 0 r (endianness big) 160/8) (bytevector-uint-set! sig 160/8 s (endianness big) 160/8) (put-bvstring p "ssh-dss") (put-bytevector p (pack "!L" (bytevector-length sig))) (put-bytevector p sig)))) ((ecdsa-sha-2-private-key? key) (let-values (((r s) (ecdsa-sha-2-create-signature msg key)) ((blob extract) (open-bytevector-output-port))) (put-mpint blob r) (put-mpint blob s) (put-bvstring p (ssh-public-key-algorithm (private->public key))) (let ((sig (extract))) (put-bytevector p (pack "!L" (bytevector-length sig))) (put-bytevector p sig)))) (else (error 'make-signature "Unimplemented public key algorithm" key)))))) (define (verify-signature H keyalg key sig-bv) (let ((signature (parse-signature sig-bv))) (if (not (string=? keyalg (ssh-public-key-algorithm key) (car signature))) (error 'verify-signature "The algorithms do not match" keyalg key signature) (cond ((rsa-public-key? key) (let ((sig (cadr (rsa-pkcs1-decrypt-digest (cadr signature) key)))) (if (sha-1-hash=? (sha-1 H) sig) 'ok 'bad))) ((dsa-public-key? key) (if (dsa-verify-signature (sha-1->bytevector (sha-1 H)) key (cadr signature) (caddr signature)) 'ok 'bad)) ((ecdsa-sha-2-public-key? key) (if (ecdsa-sha-2-verify-signature H key (cadr signature) (caddr signature)) 'ok 'bad)) (else (error 'verify-signature "Unimplemented public key algorithm" keyalg key signature)))))) ;; Used by kexdh and kex-dh-gex. The server signs this digest to ;; prove it owns the key it sent. (define (hash-kex-data hash ->bytevector . data) ;; For kexdh: ;; H = hash(V_C || V_S || I_C || I_S || K_S || e || f || K) ;; For kex-dh-gex: ;; H = hash(V_C || V_S || I_C || I_S || K_S || min || n || ;; max || p || g || e || f || K) (->bytevector (hash (call-with-bytevector-output-port (lambda (p) (for-each (lambda (k) (put-bvstring p (cadr (memq k data)))) '(V_C V_S I_C I_S K_S)) (for-each (lambda (k) (cond ((memq k data) => (lambda (v) (put-bytevector p (pack "!L" (cadr v))))))) '(min n max)) (for-each (lambda (k) (cond ((memq k data) => (lambda (v) (put-mpint p (cadr v)))))) '(p g e f K))))))) (define (make-prf make length update! copy finish! finish ->bytevector) (lambda (X len session-id K H) ;; Generate LEN bytes of key material. Section 7.2 in RFC 4253. (call-with-bytevector-output-port (lambda (p) (let ((s (make))) (update! s K) (update! s H) (let ((s* (copy s))) (update! s* (pack "C" (char->integer X))) (update! s* session-id) (finish! s*) (do ((Kn (->bytevector s*) (->bytevector (finish s))) (len len (- len (length)))) ((<= len 0)) (update! s Kn) (put-bytevector p Kn 0 (min len (bytevector-length Kn)))))))))) (define prf-sha-1 (make-prf make-sha-1 sha-1-length sha-1-update! sha-1-copy sha-1-finish! sha-1-finish sha-1->bytevector)) (define prf-sha-256 (make-prf make-sha-256 sha-256-length sha-256-update! sha-256-copy sha-256-finish! sha-256-finish sha-256->bytevector)) ;; The parent of all record abstractions of ssh packets (define-record-type ssh-packet (fields type)) (define (get-record b make field-types) (define (read b type) (case type ((string) (read-string b)) ((bytevector) (read-bytevector b)) ((uint32) (read-uint32 b)) ((mpint) (read-mpint b)) ((name-list) (read-name-list b)) ((boolean) (positive? (read-byte b))) ((byte) (read-byte b)) ((cookie) (when (< (buffer-length b) 16) (error 'get-record "short record" (buffer-length b))) (let ((bv (subbytevector (buffer-data b) (buffer-top b) (+ (buffer-top b) 16)))) (buffer-seek! b 16) bv)) (else (error 'get-record "bug: unknown type" type)))) (do ((field 0 (+ field 1)) (types field-types (cdr types)) (ret '() (cons (read b (car types)) ret))) ((null? types) (apply make (reverse ret))))) (define (read-byte b) (let ((x (read-u8 b 0))) (buffer-seek! b 1) x)) (define (read-uint32 b) (let ((x (read-u32 b 0))) (buffer-seek! b 4) x)) (define (read-bytevector b) (let ((len (read-u32 b 0))) (when (> len (buffer-length b)) (error 'read-bytevector "overlong string" len)) (buffer-seek! b 4) (let ((bv (subbytevector (buffer-data b) (buffer-top b) (+ (buffer-top b) len)))) (buffer-seek! b len) bv))) (define (read-string b) (utf8->string (read-bytevector b))) (define (read-name-list b) (let ((str (read-string b))) (if (string=? str "") '() (string-split str #\,)))) (define (read-mpint b) (let ((bv (read-bytevector b))) (bytevector-sint-ref bv 0 (endianness big) (bytevector-length bv)))) ;;; Formatting (define (put-record p msg rtd field-types) (do ((rtd (or rtd (record-rtd msg))) (field 0 (+ field 1)) (types field-types (cdr types))) ((null? types)) (let ((v ((record-accessor rtd field) msg))) (case (car types) ((string bytevector) (put-bvstring p v)) ((uint32) (put-bytevector p (pack "!L" v))) ((mpint) (put-mpint p v)) ((name-list) (put-name-list p v)) ((boolean) (put-u8 p (if v 1 0))) ((byte) (put-u8 p v)) ((cookie) (put-bytevector p v 0 16)) (else (error 'put-record "bug: unknown type" (car types))))))) (define (put-bvstring p s) (let ((bv (if (string? s) (string->utf8 s) s))) (put-bytevector p (pack "!L" (bytevector-length bv))) (put-bytevector p bv))) (define (put-name-list p l) (put-bvstring p (string-join l ","))) (define (mpnegative? bv) (and (> (bytevector-length bv) 1) (fxbit-set? (bytevector-u8-ref bv 0) 7))) (define (put-mpint p i) (let ((bv (uint->bytevector i))) (cond ((mpnegative? bv) ;; Prevent this from being considered a negative number (put-bytevector p (pack "!L" (+ 1 (bytevector-length bv)))) (put-u8 p 0) (put-bytevector p bv)) (else (put-bytevector p (pack "!L" (bytevector-length bv))) (put-bytevector p bv))))) (define (integer->mpint int) (call-with-bytevector-output-port (cut put-mpint <> int))))
false
704bfd6baf4b9eb8e1ca9e5a1ff904f67c1a1cf4
0011048749c119b688ec878ec47dad7cd8dd00ec
/src/066/solution.scm
fa1f1dfa607a213250396752fa080f1eec3d8aa7
[ "0BSD" ]
permissive
turquoise-hexagon/euler
e1fb355a44d9d5f9aef168afdf6d7cd72bd5bfa5
852ae494770d1c70cd2621d51d6f1b8bd249413c
refs/heads/master
2023-08-08T21:01:01.408876
2023-07-28T21:30:54
2023-07-28T21:30:54
240,263,031
8
0
null
null
null
null
UTF-8
Scheme
false
false
771
scm
solution.scm
(import (euler)) (define // quotient) (define (solve-pell n) (let ((x (inexact->exact (floor (sqrt n))))) (if (= (* x x) n) '(1 . 0) (let loop ((y x) (z 1) (r (* 2 x)) (e '(1 . 0)) (f '(0 . 1)) (a 0) (b 0)) (let* ((y (- (* r z) y)) (z (// (- n (* y y)) z)) (r (// (+ x y) z)) (e (cons (cdr e) (+ (* r (cdr e)) (car e)))) (f (cons (cdr f) (+ (* r (cdr f)) (car f)))) (a (+ (cdr e) (* x (cdr f)))) (b (cdr f))) (if (= (- (* a a) (* n b b)) 1) (cons a b) (loop y z r e f a b))))))) (define (solve n) (extremum (range 1 n) (lambda (_) (car (solve-pell _))) >)) (let ((_ (solve 1000))) (print _) (assert (= _ 661)))
false
7e46d9e2992f4cd235de56a359f0926271ef937c
ac2a3544b88444eabf12b68a9bce08941cd62581
/gsc/_sourceadt.scm
10e433eb2a3ac4ec9578d65391b09dc0eb31ac90
[ "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
613
scm
_sourceadt.scm
'(;;;;;;;;;;;;;;;;; (define (make-source code locat) (vector code (vector-ref locat 0) (vector-ref locat 1))) (define (source-code x) (vector-ref x 0)) (define (source-locat x) (vector (vector-ref x 1) (vector-ref x 2))) ) (define (make-source code locat) (##make-source code locat)) (define (source? x) (##source? x)) (define (source-code x) (##source-code x)) (define (source-locat x) (##source-locat x)) (define (source-path src) (##source-path src)) (define (sourcify x src) (##sourcify x src)) (define (sourcify-deep x src) (##sourcify-deep x src))
false
d24e797fa9e7e83e2bd8bd850ab8e559089b1b2c
ea4e27735dd34917b1cf62dc6d8c887059dd95a9
/projects/backup/test.scm
be706d0368f3c08a25bea5ed8e3923af3c69c160
[ "MIT" ]
permissive
feliposz/sicp-solutions
1f347d4a8f79fca69ef4d596884d07dc39d5d1ba
5de85722b2a780e8c83d75bbdc90d654eb094272
refs/heads/master
2022-04-26T18:44:32.025903
2022-03-12T04:27:25
2022-03-12T04:27:25
36,837,364
1
0
null
null
null
null
UTF-8
Scheme
false
false
1,842
scm
test.scm
(begin (setup 'felipo) (create-ring-of-obfuscation 'my-precious (ask me 'location)) (ask me 'take (thing-named 'my-precious)) (ask me 'feel-the-force) (ask me 'drop (thing-named 'my-precious)) (ask me 'feel-the-force) (newline) (define alyssa (car (filter (lambda (p) (eq? 'alyssa-hacker (ask p 'name))) (all-people)))) (define m2 (create-ring-of-obfuscation 'my-precious-2 (ask alyssa 'location))) (ask alyssa 'take m2) (ask me 'feel-the-force)) (begin (setup 'felipo) (newline)(display "wand") (newline) (create-wand 'my-wand (ask me 'location)) (ask (thing-named 'my-wand) 'zap me) (ask me 'take (thing-named 'my-wand)) (newline)(display "spell") (newline) (clone-spell (pick-random (ask chamber-of-stata 'THINGS)) (ask me 'location)) (ask me 'look-around) (ask me 'take (pick-random (ask me 'stuff-around))) (newline)(display "thing") (newline) (create-thing 'thing (ask me 'location)) (newline)(display "zap wand") (newline) (ask (thing-named 'my-wand) 'zap me) (ask (thing-named 'my-wand) 'zap (thing-named 'thing)) (ask (thing-named 'my-wand) 'zap (car (all-people))) ) (begin (setup 'felipo) (newline)(display "wand") (newline) (create-wand 'my-wand (ask me 'location)) (ask (thing-named 'my-wand) 'zap me) (ask me 'take (thing-named 'my-wand)) (ask (thing-named 'my-wand) 'zap me) (clone-spell (pick-random (ask chamber-of-stata 'THINGS)) (ask me 'location)) (ask me 'take (pick-random (ask me 'stuff-around))) (ask (thing-named 'my-wand) 'zap me) (ask (thing-named 'my-wand) 'wave) ) (setup 'felipo) (create-wand 'my-wand (ask me 'location)) (ask me 'take (thing-named 'my-wand)) (clone-spell (car (ask chamber-of-stata 'THINGS)) (ask me 'location)) (ask me 'take (thing-named 'winds-of-doom-spell)) (ask (thing-named 'my-wand) 'zap me)
false
0737583d9be6d42cab7c87ee4778632854db9340
84c9e7520891b609bff23c6fa3267a0f7f2b6c2e
/2.1-rational.scm
8a32835e5a0e4edab9a84c3b0aa74a84b1417342
[]
no_license
masaedw/sicp
047a4577cd137ec973dd9a7bb0d4f58d29ef9cb0
11a8adf49897465c4d8bddb7e1afef04876a805d
refs/heads/master
2020-12-24T18:04:01.909864
2014-01-23T11:10:11
2014-01-23T11:17:38
6,839,863
1
0
null
null
null
null
UTF-8
Scheme
false
false
950
scm
2.1-rational.scm
(define (add-rat x y) (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (sub-rat x y) (make-rat (- (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (mul-rat x y) (make-rat (* (numer x) (numer y)) (* (denom x) (denom y)))) (define (div-rat x y) (make-rat (* (numer x) (numer y)) (* (denom x) (numer y)))) (define (equal-rat? x y) (= (* (numer x) (denom y)) (* (numer y) (denom x)))) (define (make-rat n d) (letrec ((g (gcd n d)) (h (if (< d 0) (- g) g))) (cons (/ n h) (/ d h)))) (define (numer x) (car x)) (define (denom x) (cdr x)) (define (print-rat x) (display (numer x)) (display "/") (display (denom x)) (newline)) (define (main args) (print-rat (make-rat (- 1) (- 3))) (print-rat (make-rat (- 3) 9)) (print-rat (make-rat 1 (- 5))))
false
6b0ed7ccf3758dbd3f15b0b2483292c6b448c26c
a5d31dc29c25d1f2c0dab633459de05f5996679a
/benchmark-verification/foldr.sch
969e88a4f5c8d39d723bd77793bd01e905cf65cb
[]
no_license
jebcat1982/soft-contract
250461a231b150b803df9275f33ee150de043f00
4df509a75475843a2caeb7e235301f277446e06c
refs/heads/master
2021-01-21T22:06:10.092109
2014-05-26T11:51:00
2014-05-26T11:51:00
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
216
sch
foldr.sch
(module foldr (provide [foldr ((any any . -> . any) any (listof any) . -> . any)]) (define (foldr f z xs) (if (empty? xs) z (f (car xs) (foldr f z (cdr xs)))))) (require foldr) (foldr • • •)
false
caa86f1507a19889175bdc60cca93987bc1ab157
4b5dddfd00099e79cff58fcc05465b2243161094
/chapter_3/exercise_3_61.scm
ec9c3834197f5c35d417c843e378f9d3f96f7b41
[ "MIT" ]
permissive
hjcapple/reading-sicp
c9b4ef99d75cc85b3758c269b246328122964edc
f54d54e4fc1448a8c52f0e4e07a7ff7356fc0bf0
refs/heads/master
2023-05-27T08:34:05.882703
2023-05-14T04:33:04
2023-05-14T04:33:04
198,552,668
269
41
MIT
2022-12-20T10:08:59
2019-07-24T03:37:47
Scheme
UTF-8
Scheme
false
false
733
scm
exercise_3_61.scm
#lang racket ;; P232 - [练习 3.61] (require "stream.scm") (require "infinite_stream.scm") (require "exercise_3_59.scm") ; for cosine-series、exp-series (require "exercise_3_60.scm") ; for mul-series (provide invert-unit-series) (define (neg-stream s) (scale-stream s -1)) (define (invert-unit-series s) (cons-stream 1 (neg-stream (mul-series (stream-cdr s) (invert-unit-series s))))) ;;;;;;;;;;;;;;;;; (module* main #f (define a (invert-unit-series cosine-series)) (stream-head->list (mul-series a cosine-series) 20) ; (1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) (define b (invert-unit-series exp-series)) (stream-head->list (mul-series b exp-series) 20) ; (1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) )
false
3b9820b5d8c31e914c1f1584e5ea9a1b28d9fd64
2ad98a56db786f1155d81cf455d37072af2bcb61
/fp/scheme/bonus-hw1/task2_count_num.scm
23a2cde15fe42c91428f4ce7ffc3c30890cd24d1
[]
no_license
valentinvstoyanov/fmi
aa5a7d9a59f1f45238b04e6bcbad16d25ee8ade3
64f8ff2ae1cc889edfcf429ce0ca5353e4e23265
refs/heads/master
2023-01-05T05:57:37.300292
2020-11-06T21:47:27
2020-11-06T21:47:27
110,866,065
0
1
null
2019-12-14T13:36:10
2017-11-15T17:40:41
C++
UTF-8
Scheme
false
false
1,938
scm
task2_count_num.scm
;Зад.2. Намерете броя на двуцифрените нечетни съставни числа, които не могат да се представят ;като сбор на някое просто число и два пъти по някой точен квадрат ;(напр. 39 не е такова число, т.к. може да се представи като 7 + 2*42). (define (1+ n) (+ 1 n)) (define (square n) (* n n)) (define (accumulate op nv a b term next) (if (> a b) nv (accumulate op (op nv (term a)) (next a) b term next))) (define (meets-criteria? n p s) (= n (+ p (* 2 (square s))))) (define (prime? n) (define (loop i) (cond ((= i n) #t) ((= 0 (remainder n i)) #f) (else (loop (1+ i))))) (loop 2)) (define (next-prime n) (define (loop i) (if (prime? i) i (loop (1+ i)))) (loop (1+ n))) (define (square-iter n p i) (let* ((s (square i)) (res (+ p (* 2 s)))) (cond ((< n res) #t) ;продължи търсенето, но със следващото просто число ((= n res) #f) ;може да се представи по този начин -> спираме да търсим (else (square-iter n p (1+ i)))))) ;продължи търсенето, но със следващият квадрат (define (prime-iter n p) (cond ((> p n) 1) ;не сме открили начин да се представи по желания начин -> броим го ((square-iter n p 0) (prime-iter n (next-prime p))) (else 0))) ;открили сме начин да се представи -> не го броим ;0 ако n може да се представи по този начин, 1 иначе (define (good n) (if (prime? n) 0 ;не е съставно -> не го броим (prime-iter n 2))) (define (count-2-digits) (accumulate + 0 11 99 good (lambda(x) (+ 2 x))))
false
dca699ee39d17891c9e55784ba6518dcb3969f7d
9b2eb10c34176f47f7f490a4ce8412b7dd42cce7
/lib-compat/gauche-yuni/compat/macro/primitives.sls
90854e0039c530c3351f86ac0f9dca4e38131cfe
[ "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
144
sls
primitives.sls
(library (gauche-yuni compat macro primitives) (export define-inject-syntax) (import (yuni-runtime gauche macro-primitives)))
false
a2b61d0d112920f933c90db2f2fb5144676e3a3b
01a7d3740477d33d84a574a909571d0128b31e43
/c43-staticchain-test.scm
1126af032a08ef3e6e77eee812358ad04a11b063
[]
no_license
propella/3imp-westwood
7a19f2113555d7d531d6a6acd087f96fb9eb93d4
9c7912ac1b2596e62dc7736d10ef73362296c001
refs/heads/master
2021-01-23T13:23:04.505262
2010-01-12T19:51:58
2010-01-12T19:51:58
456,584
1
0
null
null
null
null
UTF-8
Scheme
false
false
4,083
scm
c43-staticchain-test.scm
#!/usr/bin/env gosh (require "./c43-staticchain") (require "./check") ;;; Tests for compile (check (compile 7 '() '_) => '(constant 7 _)) (check (compile 'hello '((hello)) '_) => '(refer 0 0 _)) (check (compile '(quote hello) '() '_) => '(constant hello _)) (check (compile '(lambda (c) c) '() '(halt)) => '(close (refer 0 0 (return 2)) (halt))) (check (compile '(if #t 3 4) '() '_) => '(constant #t (test (constant 3 _) (constant 4 _)))) (check (compile '(call/cc (lambda (c) c)) '() '(halt)) => '(frame (halt) (conti (argument (close (refer 0 0 (return 2)) (apply)))))) (check (compile '(call/cc (lambda (c) c)) '() '(return)) => '(frame (return) ;; no tail call (conti (argument (close (refer 0 0 (return 2)) (apply)))))) (check (compile '(func 1 2) '((func)) '(halt)) => '(frame (halt) (constant 2 (argument (constant 1 (argument (refer 0 0 (apply)))))))) (check (compile '(func 1 2) '((func)) '(return)) => '(frame (return) (constant 2 (argument (constant 1 (argument (refer 0 0 (apply)))))))) ;; ;;; Tests for the dynamic chain (set! stack #(some stack values)) (check (continuation 3) => `((refer 0 0 (nuate ,#(some stack values) (return 0))) ())) ;;; Tests for VM ;; halt, refer, and constant test ; 0 1 2 3 4 5 6 7 8 9 10 11 12 ; | | | | | (set! stack #(f 0 1 e d c 2 b a 6 () () ())) (check (VM 7 '(halt) '_ 0) => 7) (check (VM 0 '(refer 1 1 (halt)) 9 10) => 'd) (check (VM '() '(constant 7 (halt)) '_ 0) => 7) ;; close test (check (VM '() '(close (refer (0 . 0) (return)) (halt)) 0 0) => '((refer (0 . 0) (return)) 0)) ;; test test (check (VM #t '(test (constant 1 (halt)) (constant 2 (halt))) '_ 0) => 1) (check (VM #f '(test (constant 1 (halt)) (constant 2 (halt))) '_ 0) => 2) ;; conti test (check (VM '_ '(conti (halt)) '_ 0) => '((refer 0 0 (nuate #() (return 0))) ())) ;; nuate test (set! stack #(_ _ _)) (check (VM 7 `(nuate ,#(some stack values) (halt)) 1 1) => 7) (check stack => #(some stack values)) ;; frame test (set! stack #(_ _)) (VM '() '(frame (*resume-inst*) (halt)) 0 0) (check stack => #(0 (*resume-inst*))) ;; argument test (set! stack #(_ _)) (check (VM 7 '(argument (halt)) 0 0) => 7) (check stack => #(7 _)) ;; apply test (set! stack #(*dynamic* (halt) *arg1* *arg0* _)) (check (VM '((refer 0 1 (return 3)) 0) '(apply) '*env* 4) => '*arg1*) ;; return test (set! stack #(*dynamic* (halt) *arg2* *arg1* *arg0* *static*)) (check (VM 7 '(return 4) '*env* 6) => 7) ;; Trace a behavior of ((lambda (a) a) 7) ;; *dynamic* and *static* are real numbers in real situation, but they ;; are not recognized by the VM. ;(set! *debug-flag* #t) ;(check (evaluate '((lambda (a) a) 7)) => 7) ;(set! *debug-flag* #f) (set! stack #(_ _ _ _)) (check (VM '_ '(frame (halt) (constant 7 (argument (close (refer 0 0 (return 2)) (apply))))) 0 0) => 7) (set! stack #(*dynamic* (halt) _ _)) (check (VM '_ '(constant 7 (argument (close (refer 0 0 (return 2)) (apply)))) 0 2) => 7) (set! stack #(*dynamic* (halt) _ _)) (check (VM 7 '(argument (close (refer 0 0 (return 2)) (apply))) 0 2) => 7) (set! stack #(*dynamic* (halt) 7 _)) (check (VM '_ '(close (refer 0 0 (return 2)) (apply)) 0 3) => 7) (set! stack #(*dynamic* (halt) 7 _)) (check (VM '((refer 0 0 (return 2)) 0) '(apply) 0 3) => 7) (set! stack #(*dynamic* (halt) 7 *static*)) (check (VM '_ '(refer 0 0 (return 2)) 3 4) => 7) (set! stack #(*dynamnic* (halt) 7 *static*)) (check (VM 7 '(return 2) 3 4) => 7) (set! stack #()) (check (VM 7 '(halt) 0 0) => 7) ;; ;;; Tests for evaluate (set! stack (make-vector 1000)) (check (evaluate 7) => 7) (check (evaluate '(quote hello)) => 'hello) (check (evaluate '((lambda () 7))) => 7) (check (evaluate '((lambda (x y) y) 6 7)) => 7) (check (evaluate '(if #t 7 0)) => 7) (check (evaluate '(if #f 0 7)) => 7) ;; (check (evaluate '((lambda (t) ((lambda (x) t) (set! t 7))) 0)) => 7) (check (evaluate '(call/cc (lambda (c) (0 3 (c 7))))) => 7) (check (evaluate '((lambda (f x) (f x)) (lambda (x) x) 7)) => 7)
false
73dc059a2874460b16c345e679a3432f6b974b2d
4678ab3f30bdca67feeb16453afc8ae26b162e51
/object.ss
262a0650c129836b52c29e16c276a2fb67001ac1
[ "Apache-2.0" ]
permissive
atship/thunderchez
93fd847a18a6543ed2f654d7dbfe1354e6b54c3d
717d8702f8c49ee0442300ebc042cb5982b3809b
refs/heads/trunk
2021-07-09T14:17:36.708601
2021-04-25T03:13:24
2021-04-25T03:13:24
97,306,402
0
0
null
2017-07-15T09:42:04
2017-07-15T09:42:04
null
UTF-8
Scheme
false
false
2,195
ss
object.ss
(library (object) (export obj obj->list obj-has?; o k obj-ref; o k obj-set! ; o k v obj-rm! ; o k obj-for ; o (lambda (p) ...) obj-map ; o (lambda (p) ...) array array-map ; a (lambda (i v)) array-for ; a (lambda (i v)) array-size array-ref array-set! array-push array-pop array-in array-out array->list empty? ) (import (chezscheme) (script)) (define (empty? ao) (or (not ao) (= 1 (length ao)))) (define (obj) (make-list 1 '$obj$)) (define (obj->list o) (cdr o)) (define (array->list a) (cdr a)) (define array (case-lambda [() (make-list 1 '$array$)] [(l) (array l 0)] [(l v) (let ([a (make-list (+ 1 l) v)]) (set-car! a '$array$) a)])) (define (array-for a f) (for-each f (iota (length (cdr a))) (cdr a))) (define (array-map a f) (for f (iota (length (cdr a))) (cdr a))) (define (array-size a) (- (length a) 1)) (define (array-ref a i) (list-ref a (+ 1 i))) (define (array-set! a i v) (list-set! a (+ 1 i) v)) (define (array-push a v) (list-append! a v)) (define (array-pop a) (if (empty? a) (eof) (let ([v (list-ref a (- (length a) 1))]) (list-remove! a -1) v))) (define-syntax array-in (identifier-syntax array-push)) (define (array-out a) (if (empty? a) (eof) (let ([v (list-ref a 1)]) (list-remove! a 1) v))) (define (obj-has? o k) (if (assq k (cdr o)) #t #f)) (define (obj-ref o k) (let ([f (assoc k (cdr o))]) (if f (cadr f) #f))) (define (obj-for o l) (for-each l (cdr o))) (define (obj-map o l) (map l (cdr o))) (define (obj-set! o k v) (let ([f (assoc k (cdr o))]) (if f (set-cdr! f (cons v '())) (let ([f (list k v)]) (set-cdr! (list-tail o (- (length o) 1)) (list f)))))) (define (obj-rm! o k) (let ([idx (find (lambda (i) (equal? k (car (list-ref o (+ 1 i))))) (iota (length (cdr o))))]) (if idx (list-remove! o (+ 1 idx))))) )
true
2a163631793d066aba0ad5013c6cdc7a0e14cca0
665da87f9fefd8678b0635e31df3f3ff28a1d48c
/scheme/cyclone/cps-optimizations.sld
c79b6f20ef970addd89c2d292e292cf3262cf200
[ "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
97,872
sld
cps-optimizations.sld
;;;; Cyclone Scheme ;;;; https://github.com/justinethier/cyclone ;;;; ;;;; Copyright (c) 2014-2016, Justin Ethier ;;;; All rights reserved. ;;;; ;;;; This module performs CPS analysis and optimizations. ;;;; ;(define-library (cps-optimizations) ;; For debugging via local unit tests (define-library (scheme cyclone cps-optimizations) (import (scheme base) (scheme eval) (scheme write) (scheme cyclone util) (scheme cyclone ast) (scheme cyclone primitives) (scheme cyclone transforms) (srfi 2) (srfi 69)) (export closure-convert analyze:cc-ast->vars pos-in-list inlinable-top-level-lambda? optimize-cps analyze-cps analyze-find-lambdas analyze:find-named-lets analyze:find-direct-recursive-calls analyze:find-known-lambdas analyze:find-inlinable-vars ;analyze-lambda-side-effects opt:renumber-lambdas! opt:add-inlinable-functions opt:contract opt:inline-prims opt:beta-expand opt:local-var-reduction adb:clear! adb:get adb:get/default adb:set! adb:get-db adb:lambda-ids adb:max-lambda-id simple-lambda? one-instance-of-new-mutable-obj? ;; Analysis - well-known lambdas well-known-lambda analyze:find-known-lambdas ;; Analysis - validation validate:num-function-args ;; Analyze variables adb:make-var %adb:make-var adb:variable? adbv:global? adbv:set-global! adbv:defined-by adbv:set-defined-by! adbv:mutated-by-set? adbv:set-mutated-by-set! adbv:reassigned? adbv:set-reassigned! adbv:assigned-value adbv:set-assigned-value! adbv:const? adbv:set-const! adbv:const-value adbv:set-const-value! adbv:ref-count adbv:set-ref-by-and-count! adbv:ref-by adbv:def-in-loop? adbv:set-def-in-loop! adbv:ref-in-loop? adbv:set-ref-in-loop! adbv:direct-rec-call? adbv:set-direct-rec-call! adbv:self-rec-call? adbv:set-self-rec-call! adbv:app-fnc-count adbv:set-app-fnc-count! adbv:app-arg-count adbv:set-app-arg-count! adbv:cannot-inline adbv:set-cannot-inline! adbv:inlinable adbv:set-inlinable! adbv:mutated-indirectly adbv:set-mutated-indirectly! adbv:cont? adbv:set-cont! with-var with-var! ;; Analyze functions adb:make-fnc %adb:make-fnc adb:function? adbf:simple adbf:set-simple! adbf:all-params adbf:set-all-params! adbf:unused-params adbf:set-unused-params! adbf:assigned-to-var adbf:set-assigned-to-var! adbf:side-effects adbf:set-side-effects! adbf:well-known adbf:set-well-known! adbf:cgen-id adbf:set-cgen-id! adbf:closure-size adbf:set-closure-size! adbf:self-closure-index adbf:set-self-closure-index! adbf:calls-self? adbf:set-calls-self! adbf:vars-mutated-by-set adbf:set-vars-mutated-by-set! with-fnc with-fnc! ) (include "cps-opt-local-var-redux.scm") (include "cps-opt-analyze-call-graph.scm") (include "cps-opt-memoize-pure-fncs.scm") (begin (define *beta-expand-threshold* 4) (define *inline-unsafe* #f) ;; The following two defines allow non-CPS functions to still be considered ;; for certain inlining optimizations. (define *inlinable-functions* '()) (define (opt:add-inlinable-functions lis) (set! *inlinable-functions* lis)) (define *contract-env* (let ((env (create-environment '() '()))) (eval '(define Cyc-fast-plus +) env) (eval '(define Cyc-fast-sub -) env) (eval '(define Cyc-fast-mul *) env) (eval '(define Cyc-fast-div /) env) (eval '(define Cyc-fast-eq =) env) (eval '(define Cyc-fast-gt >) env) (eval '(define Cyc-fast-lt <) env) (eval '(define Cyc-fast-gte >=) env) (eval '(define Cyc-fast-lte <=) env) env)) (define *adb* (make-hash-table)) (define *adb-call-graph* (make-hash-table)) (define (adb:get-db) *adb*) (define (adb:clear!) (set! *adb* (make-hash-table)) (set! *adb-call-graph* (make-hash-table)) ) (define (adb:get key) (hash-table-ref *adb* key)) (define (adb:get/default key default) (hash-table-ref/default *adb* key default)) (define (adb:lambda-ids) (filter number? (hash-table-keys *adb*))) (define (adb:max-lambda-id) (foldl max 0 (adb:lambda-ids))) (define (adb:set! key val) (hash-table-set! *adb* key val)) (define-record-type <analysis-db-variable> (%adb:make-var global defined-by defines-lambda-id const const-value ref-count ref-by mutated-by-set reassigned assigned-value app-fnc-count app-arg-count cannot-inline inlinable mutated-indirectly cont def-in-loop ref-in-loop direct-rec-call self-rec-call ) adb:variable? (global adbv:global? adbv:set-global!) (defined-by adbv:defined-by adbv:set-defined-by!) (defines-lambda-id adbv:defines-lambda-id adbv:set-defines-lambda-id!) (const adbv:const? adbv:set-const!) (const-value adbv:const-value adbv:set-const-value!) (ref-count adbv:ref-count %adbv:set-ref-count!) (ref-by adbv:ref-by %adbv:set-ref-by!) (mutated-by-set adbv:mutated-by-set? adbv:set-mutated-by-set!) ;; TODO: need to set reassigned flag if variable is SET, however there is at least ;; one exception for local define's, which are initialized to #f and then assigned ;; a single time via set (reassigned adbv:reassigned? adbv:set-reassigned!) (assigned-value adbv:assigned-value adbv:set-assigned-value!) ;; Number of times variable appears as an app-function (app-fnc-count adbv:app-fnc-count adbv:set-app-fnc-count!) ;; Number of times variable is passed as an app-argument (app-arg-count adbv:app-arg-count adbv:set-app-arg-count!) ;; Variable cannot be inlined (cannot-inline adbv:cannot-inline adbv:set-cannot-inline!) ;; Can a ref be safely inlined? (inlinable adbv:inlinable adbv:set-inlinable!) ;; Is the variable mutated indirectly? (EG: set-car! of a cdr) (mutated-indirectly adbv:mutated-indirectly adbv:set-mutated-indirectly!) (cont adbv:cont? adbv:set-cont!) ;; Following two indicate if a variable is defined/referenced in a loop (def-in-loop adbv:def-in-loop? adbv:set-def-in-loop!) (ref-in-loop adbv:ref-in-loop? adbv:set-ref-in-loop!) ;; Does a top-level function directly call itself? (direct-rec-call adbv:direct-rec-call? adbv:set-direct-rec-call!) ;; Does a function call itself? (self-rec-call adbv:self-rec-call? adbv:set-self-rec-call!) ) (define (adbv:set-ref-by-and-count! var lambda-id) (let ((ref-bys (adbv:ref-by var))) ;(when (not (member lambda-id ref-bys)) ;; Assume low ref-by count (%adbv:set-ref-count! var (+ 1 (adbv:ref-count var))) (%adbv:set-ref-by! var (cons lambda-id ref-bys)))) ;) (define (adbv-set-assigned-value-helper! sym var value) (define (update-lambda-atv! syms value) ;(trace:error `(update-lambda-atv! ,syms ,value)) (cond ((ast:lambda? value) (let ((id (ast:lambda-id value))) (with-fnc! id (lambda (fnc) (adbf:set-assigned-to-var! fnc (append syms (adbf:assigned-to-var fnc))))))) ;; Follow references ((ref? value) (with-var! value (lambda (var) (if (not (member value syms)) (update-lambda-atv! (cons value syms) (adbv:assigned-value var)))))) (else #f)) ) (adbv:set-assigned-value! var value) ;; TODO: if value is a lambda, update the lambda's var ref's ;; BUT, what if other vars point to var? do we need to add ;; them to the lambda's list as well? (update-lambda-atv! (list sym) value) ) (define (adb:make-var) (%adb:make-var '? ; global '? ; defined-by #f ; defines-lambda-id #f ; const #f ; const-value 0 ; ref-count '() ; ref-by #f ; mutated-by-set #f ; reassigned #f ; assigned-value 0 ; app-fnc-count 0 ; app-arg-count #f ; cannot-inline #t ; inlinable '() ; mutated-indirectly #f ; cont #f ; def-in-loop #f ; ref-in-loop #f ; direct-rec-call #f ; self-rec-call )) (define-record-type <analysis-db-function> (%adb:make-fnc simple all-params unused-params assigned-to-var side-effects well-known cgen-id closure-size self-closure-index calls-self vars-mutated-by-set ) adb:function? (simple adbf:simple adbf:set-simple!) (all-params adbf:all-params adbf:set-all-params!) (unused-params adbf:unused-params adbf:set-unused-params!) (assigned-to-var adbf:assigned-to-var adbf:set-assigned-to-var!) (side-effects adbf:side-effects adbf:set-side-effects!) ;; From Dybvig's Optimizing Closures in O(0) Time paper: ;; A procedure is known at a call site if the call site provably invokes ;; that procedure's lambda-expression and only that lambda-expression. A ;; well-known procedure is one whose value is never used except at call ;; sites where it is known. (well-known adbf:well-known adbf:set-well-known!) ;; Store internal ID generated for the lambda by the cgen module (cgen-id adbf:cgen-id adbf:set-cgen-id!) ;; Number of elements in the function's closure (closure-size adbf:closure-size adbf:set-closure-size!) ;; Index of the function in its closure, if applicable (self-closure-index adbf:self-closure-index adbf:set-self-closure-index!) ;; Does this function call itself? (calls-self adbf:calls-self? adbf:set-calls-self!) ;; Variables this function mutates via (set!) (vars-mutated-by-set adbf:vars-mutated-by-set adbf:set-vars-mutated-by-set!) ) (define (adb:make-fnc) (%adb:make-fnc '? ;; simple #f ;; all-params '? ;; unused-params '() ;; assigned-to-var #f ;; side-effects #f ;; well-known #f ;; cgen-id -1 ;; closure-size -1 ;; self-closure-index #f ;; calls-self '() ;; vars-mutated-by-set )) ;; A constant value that cannot be mutated ;; A variable only ever assigned to one of these could have all ;; instances of itself replaced with the value. (define (const-atomic? exp) (or (integer? exp) (real? exp) (complex? exp) ;(string? exp) ;(vector? exp) ;(bytevector? exp) (char? exp) (boolean? exp))) ;; Helper to retrieve the Analysis DB Variable referenced ;; by sym (or use a default if none is found), and call ;; fnc with that ADBV. ;; ;; The analysis DB is updated with the variable, in case ;; it was not found. (define (with-var! sym fnc) (let ((var (adb:get/default sym (adb:make-var)))) (fnc var) (adb:set! sym var))) ;; Non-mutating version, returns results of fnc (define (with-var sym fnc) (let ((var (adb:get/default sym (adb:make-var)))) (fnc var))) ;; If var found in adb pass to callback and return result, else return #f (define (if-var sym callback) (let* ((var (adb:get/default sym #f)) (result (if var (callback var) #f))) result)) (define (with-fnc id callback) (let ((fnc (adb:get/default id (adb:make-fnc)))) (callback fnc))) (define (with-fnc! id callback) (let ((fnc (adb:get/default id (adb:make-fnc)))) (callback fnc) (adb:set! id fnc))) ;; Determine if the given top-level function can be freed from CPS, due ;; to it only containing calls to code that itself can be inlined. (define (inlinable-top-level-lambda? expr) (define (scan expr fail) (cond ((string? expr) (fail)) ((bytevector? expr) (fail)) ((const? expr) #t) ;; Good enough? what about large vectors or anything requiring alloca (strings, bytevectors, what else?) ((ref? expr) #t) ((if? expr) (scan (if->condition expr) fail) (scan (if->then expr) fail) (scan (if->else expr) fail)) ((app? expr) (let ((fnc (car expr))) ;; If function needs CPS, fail right away (if (or (not (prim? fnc)) ;; Eventually need to handle user functions, too (prim:cont? fnc) ;; Needs CPS (prim:mutates? fnc) ;; This is too conservative, but basically ;; there are restrictions about optimizing ;; args to a mutator, so reject them for now (prim-creates-mutable-obj? fnc) ;; Again, probably more conservative ;; than necessary ) (fail)) ;; Otherwise, check for valid args (for-each (lambda (e) (scan e fail)) (cdr expr)))) ;; prim-app - OK only if prim does not require CPS. ;; still need to check all its args ;; app - same as prim, only OK if function does not require CPS. ;; probably safe to return #t if calling self, since if no ;; CPS it will be rejected anyway ;; NOTE: would not be able to detect all functions in this module immediately. ;; would probably have to find some, then run this function successively to find others. ;; ;; Reject everything else - define, set, lambda (else (fail)))) (cond ((and (define? expr) (lambda? (car (define->exp expr))) (equal? 'args:fixed (lambda-formals-type (car (define->exp expr))))) (call/cc (lambda (k) (let* ((define-body (car (define->exp expr))) (lambda-body (lambda->exp define-body)) (fv (filter (lambda (v) (and (not (equal? 'Cyc-seq v)) (not (prim? v)))) (free-vars expr))) ) ;(trace:error `(JAE DEBUG ,(define->var expr) ,fv)) (cond ((> (length lambda-body) 1) (k #f)) ;; Fail with more than one expression in lambda body, ;; because CPS is required to compile that. ((> (length fv) 1) ;; Reject any free variables to attempt to prevent (k #f)) ;; cases where there is a variable that may be ;; mutated outside the scope of this function. (else (scan (car lambda-body) (lambda () (k #f))) ;; Fail with #f (k #t))))))) ;; Scanned fine, return #t (else #f))) ;; Scan given if expression to determine if an inline is safe. ;; Returns #f if not, the new if expression otherwise. (define (inline-if:scan-and-replace expr kont) (define (scan expr fail) ;(trace:error `(inline-if:scan-and-replace:scan ,expr)) (cond ((ast:lambda? expr) (fail)) ((string? expr) (fail)) ((bytevector? expr) (fail)) ((const? expr) expr) ;; Good enough? what about large vectors or anything requiring alloca (strings, bytevectors, what else?) ((ref? expr) expr) ((if? expr) `(Cyc-if ,(scan (if->condition expr) fail) ,(scan (if->then expr) fail) ,(scan (if->else expr) fail))) ((app? expr) (let ((fnc (car expr))) ;; If function needs CPS, fail right away (cond ((equal? (car expr) kont) ;; Get rid of the continuation (scan (cadr expr) fail)) ((or (not (prim? fnc)) (prim:cont? fnc) (prim:mutates? fnc) (prim-creates-mutable-obj? fnc) ) (fail)) (else ;; Otherwise, check for valid args (cons (car expr) (map (lambda (e) (scan e fail)) (cdr expr))))))) ;; Reject everything else - define, set, lambda (else (fail)))) (call/cc (lambda (return) (scan expr (lambda () (return #f)))))) (define (analyze-find-lambdas exp lid) (cond ((ast:lambda? exp) (let* ((id (ast:lambda-id exp)) (fnc (adb:get/default id (adb:make-fnc)))) (adb:set! id fnc) ;; Flag continuation variable, if present (if (ast:lambda-has-cont exp) (let ((k (car (ast:lambda-args exp)))) (with-var! k (lambda (var) (adbv:set-cont! var #t))))) (for-each (lambda (expr) (analyze-find-lambdas expr id)) (ast:lambda-body exp)))) ((const? exp) #f) ((quote? exp) #f) ((ref? exp) #f) ((define? exp) (let ((val (define->exp exp))) (if (ast:lambda? (car val)) (with-var! (define->var exp) (lambda (var) (adbv:set-defines-lambda-id! var (ast:lambda-id (car val))))))) (analyze-find-lambdas (define->exp exp) lid)) ((set!? exp) (analyze-find-lambdas (set!->exp exp) lid)) ((if? exp) (analyze-find-lambdas (if->condition exp) lid) (analyze-find-lambdas (if->then exp) lid) (analyze-find-lambdas (if->else exp) lid)) ((app? exp) (for-each (lambda (e) (analyze-find-lambdas e lid)) exp)) (else #f))) ;; Mark each lambda that has side effects. ;; For nested lambdas, if a child has side effects also mark the parent (define (analyze-lambda-side-effects exp lid) (cond ((ast:lambda? exp) (let* ((id (ast:lambda-id exp)) (fnc (adb:get/default id (adb:make-fnc)))) (adb:set! id fnc) (for-each (lambda (expr) (analyze-lambda-side-effects expr id)) (ast:lambda-body exp)) ;; If id has side effects, mark parent lid, too (if (and (> lid -1) (adbf:side-effects fnc)) (with-fnc! lid (lambda (f) (adbf:set-side-effects! f #t)))))) ((const? exp) #f) ((quote? exp) #f) ((ref? exp) #f) ((define? exp) (analyze-lambda-side-effects (define->exp exp) lid)) ((set!? exp) (with-fnc! lid (lambda (fnc) (adbf:set-side-effects! fnc #t))) (analyze-lambda-side-effects (set!->exp exp) lid)) ((if? exp) (analyze-lambda-side-effects (if->condition exp) lid) (analyze-lambda-side-effects (if->then exp) lid) (analyze-lambda-side-effects (if->else exp) lid)) ((app? exp) (let ((pure-ref #t)) ;; Check if ref is pure. Note this may give wrong results ;; if ref's lambda has not been scanned yet. One solution is ;; to make 2 top-level passes of analyze-lambda-side-effects. (if (ref? (car exp)) (with-var (car exp) (lambda (var) (if (adbv:defines-lambda-id var) (with-fnc! (adbv:defines-lambda-id var) (lambda (fnc) (if (adbf:side-effects fnc) (set! pure-ref #f)))))))) ;; This lambda has side effects if it calls a mutating prim or ;; a function not explicitly marked as having no side effects. (if (or (prim:mutates? (car exp)) (and (ref? (car exp)) (not pure-ref))) (with-fnc! lid (lambda (fnc) (adbf:set-side-effects! fnc #t)))) (for-each (lambda (e) (analyze-lambda-side-effects e lid)) exp))) (else #f))) ;; TODO: check app for const/const-value, also (for now) reset them ;; if the variable is modified via set/define (define (analyze exp scope-sym lid) ;(trace:error `(analyze ,scope-sym ,lid ,exp ,(app? exp))) (cond ; Core forms: ((ast:lambda? exp) (let* ((id (ast:lambda-id exp)) (fnc (adb:get/default id (adb:make-fnc)))) ;; save lambda to adb (adb:set! id fnc) ;; Analyze the lambda ;(trace:error `(DEBUG-exp ,exp)) ;(trace:error `(DEUBG-ast ,(ast:lambda-formals->list exp))) (for-each (lambda (arg) ;(let ((var (adb:get/default arg (adb:make-var)))) (with-var! arg (lambda (var) (adbv:set-global! var #f) (adbv:set-defined-by! var id)))) (ast:lambda-formals->list exp)) (for-each (lambda (expr) (analyze expr scope-sym id)) (ast:lambda-body exp)) ;; Keep track of mutations made by child lambda's (when (> lid 0) (with-fnc id (lambda (inner-fnc) (let ((vars-set (adbf:vars-mutated-by-set inner-fnc))) (when (pair? vars-set) (with-fnc! lid (lambda (outer-fnc) (adbf:set-vars-mutated-by-set! outer-fnc (append vars-set (adbf:vars-mutated-by-set outer-fnc)))))))))) )) ((const? exp) #f) ((quote? exp) #f) ((ref? exp) (let ((var (adb:get/default exp (adb:make-var)))) (adbv:set-ref-by-and-count! var lid) )) ((define? exp) ;(let ((var (adb:get/default (define->var exp) (adb:make-var)))) (with-var! (define->var exp) (lambda (var) (adbv:set-defined-by! var lid) (adbv:set-ref-by-and-count! var lid) (adbv-set-assigned-value-helper! (define->var exp) var (define->exp exp)) (adbv:set-const! var #f) (adbv:set-const-value! var #f))) (analyze (define->exp exp) (define->var exp) lid)) ((set!? exp) (when (ref? (set!->var exp)) (with-fnc! lid (lambda (fnc) (adbf:set-vars-mutated-by-set! fnc (cons (set!->var exp) (adbf:vars-mutated-by-set fnc)))))) ;(let ((var (adb:get/default (set!->var exp) (adb:make-var)))) (with-var! (set!->var exp) (lambda (var) (if (adbv:assigned-value var) (adbv:set-reassigned! var #t)) (adbv:set-mutated-by-set! var #t) (adbv-set-assigned-value-helper! (set!->var exp) var (set!->exp exp)) (adbv:set-ref-by-and-count! var lid) (adbv:set-const! var #f) (adbv:set-const-value! var #f))) (analyze (set!->exp exp) scope-sym lid)) ((if? exp) `(if ,(analyze (if->condition exp) scope-sym lid) ,(analyze (if->then exp) scope-sym lid) ,(analyze (if->else exp) scope-sym lid))) ; Application: ((app? exp) (if (ref? (car exp)) (with-var! (car exp) (lambda (var) (adbv:set-app-fnc-count! var (+ 1 (adbv:app-fnc-count var)))))) (for-each (lambda (arg) (if (ref? arg) (with-var! arg (lambda (var) (adbv:set-app-arg-count! var (+ 1 (adbv:app-arg-count var))))))) (app->args exp)) ;; Identify indirect mutations. That is, the result of a function call ;; is what is mutated (cond ((and (prim:mutates? (car exp)) ;; loop3-dev WIP step #1 - do not immediately reject these prims ;(not (member (car exp) '(vector-set!))) ;; TODO: experimental ) (let ((e (cadr exp))) (when (ref? e) (with-var! e (lambda (var) (adbv:set-cannot-inline! var #t))) (with-var e (lambda (var) (if (adbv:assigned-value var) (set! e (adbv:assigned-value var)))))) ;(trace:error `(find-indirect-mutations ,e)) (find-indirect-mutations e scope-sym)))) ;; TODO: if ast-lambda (car), ;; for each arg ;; if arg is const-atomic ;; mark the parameter (variable) as const and give it const-val ;; ;; obviously need to add code later on to reset const if mutated (cond ((and (ast:lambda? (car exp)) (list? (ast:lambda-args (car exp)))) ;; For now, avoid complications with optional/extra args (let ((params (ast:lambda-args (car exp)))) (for-each (lambda (arg) ;(trace:error `(app check arg ,arg ,(car params) ,(const-atomic? arg))) (with-var! (car params) (lambda (var) (adbv-set-assigned-value-helper! (car params) var arg) (cond ((const-atomic? arg) (adbv:set-const! var #t) (adbv:set-const-value! var arg))))) ;; Walk this list, too (set! params (cdr params))) (app->args exp))))) (for-each (lambda (e) (analyze e scope-sym lid)) exp)) ;TODO ((app? exp) (map (lambda (e) (wrap-mutables e globals)) exp)) ; Nothing to analyze for these? ;((prim? exp) exp) ;((quote? exp) exp) ; Should never see vanilla lambda's in this function, only AST's ;((lambda? exp) ;; Nothing to analyze for expressions that fall into this branch (else #f))) (define (analyze2 exp) (cond ; Core forms: ((ast:lambda? exp) (let* ((id (ast:lambda-id exp)) (fnc (adb:get id))) ;(trace:error `(adb:get ,id ,fnc)) (adbf:set-simple! fnc (simple-lambda? exp)) (for-each (lambda (expr) (analyze2 expr)) (ast:lambda-body exp)))) ((const? exp) #f) ((quote? exp) #f) ;; TODO: ; ((ref? exp) ; (let ((var (adb:get/default exp (adb:make-var)))) ; (adbv:set-ref-by-and-count! var lid) ; )) ((define? exp) ;(let ((var (adb:get/default (define->var exp) (adb:make-var)))) (analyze2 (define->exp exp))) ((set!? exp) ;(let ((var (adb:get/default (set!->var exp) (adb:make-var)))) (analyze2 (set!->exp exp))) ((if? exp) `(if ,(analyze2 (if->condition exp)) ,(analyze2 (if->then exp)) ,(analyze2 (if->else exp)))) ; Application: ((app? exp) (validate:num-function-args exp) ;; Extra validation (for-each (lambda (e) (analyze2 e)) exp)) (else #f))) (define (find-indirect-mutations exp scope-sym) (cond ; Core forms: ;((ast:lambda? exp) ; (let* ((id (ast:lambda-id exp)) ; (fnc (adb:get id))) ; (adbf:set-simple! fnc (simple-lambda? exp)) ; (for-each ; (lambda (expr) ; (analyze2 expr)) ; (ast:lambda-body exp)))) ((const? exp) #f) ((quote? exp) #f) ((ref? exp) (with-var! exp (lambda (var) (adbv:set-mutated-indirectly! var (cons scope-sym (adbv:mutated-indirectly var)))))) ;((define? exp) ; ;(let ((var (adb:get/default (define->var exp) (adb:make-var)))) ; (analyze2 (define->exp exp))) ;((set!? exp) ; ;(let ((var (adb:get/default (set!->var exp) (adb:make-var)))) ; (analyze2 (set!->exp exp))) ((if? exp) `(if ,(find-indirect-mutations (if->condition exp) scope-sym) ,(find-indirect-mutations (if->then exp) scope-sym) ,(find-indirect-mutations (if->else exp) scope-sym))) ; Application: ((app? exp) (for-each (lambda (e) (find-indirect-mutations e scope-sym)) (cdr exp))) (else #f))) ;; TODO: make another pass for simple lambda's ;can use similar logic to cps-optimize-01: ;- body is a lambda app ;- no lambda args are referenced in the body of that lambda app ; (ref-by is empty or the defining lid) ; ; Need to check analysis DB against CPS generated and make sure ; things like ref-by make sense (ref by seems like its only -1 right now??) ;; Does ref-by list contains references to lambdas other than owner? ;; int -> ast-variable -> boolean (define (nonlocal-ref? owner-id adb-var) (define (loop ref-by-ids) (cond ((null? ref-by-ids) #f) ((not (pair? ref-by-ids)) #f) (else (let ((ref (car ref-by-ids))) (if (and (number? ref) (not (= owner-id ref))) #t ;; Another lambda uses this variable (loop (cdr ref-by-ids))))))) (loop (adbv:ref-by adb-var))) ;; int -> [symbol] -> boolean (define (any-nonlocal-refs? owner-id vars) (call/cc (lambda (return) (for-each (lambda (var) (if (nonlocal-ref? owner-id (adb:get var)) (return #t))) vars) (return #f)))) ;; ast-function -> boolean (define (simple-lambda? ast) (let ((body (ast:lambda-body ast)) (formals (ast:lambda-formals->list ast)) (id (ast:lambda-id ast))) (if (pair? body) (set! body (car body))) ;(trace:error `(simple-lambda? ,id ,formals ;,(and (pair? body) ; (app? body) ; (ast:lambda? (car body))) ;,(length formals) ;;,body ;)) (and (pair? body) (app? body) (ast:lambda? (car body)) (> (length formals) 0) (equal? (app->args body) formals) (not (any-nonlocal-refs? id formals)) ))) ;; Perform contraction phase of CPS optimizations (define (opt:contract exp) (cond ; Core forms: ((ast:lambda? exp) (let* ((id (ast:lambda-id exp)) (fnc (adb:get/default id #f))) (if (and fnc (adbf:simple fnc)) (opt:contract (caar (ast:lambda-body exp))) ;; Optimize-out the lambda (ast:%make-lambda (ast:lambda-id exp) (ast:lambda-args exp) (opt:contract (ast:lambda-body exp)) (ast:lambda-has-cont exp))))) ((const? exp) exp) ((ref? exp) (let ((var (adb:get/default exp #f))) (if (and var (adbv:const? var)) (adbv:const-value var) exp))) ((prim? exp) exp) ((quote? exp) exp) ((define? exp) `(define ,(opt:contract (define->var exp)) ,@(opt:contract (define->exp exp)))) ((set!? exp) `(set! ,(opt:contract (set!->var exp)) ,(opt:contract (set!->exp exp)))) ((if? exp) (cond ((not (if->condition exp)) (opt:contract (if->else exp))) (else `(if ,(opt:contract (if->condition exp)) ,(opt:contract (if->then exp)) ,(opt:contract (if->else exp)))))) ; Application: ((app? exp) ;; Beta expansion of functions only called once, from CWC (if (beta-expand/called-once? exp) (set! exp (beta-expand-app exp #f))) ;; END (let* ((fnc (opt:contract (car exp)))) (cond ((and (ast:lambda? fnc) (list? (ast:lambda-args fnc)) ;; Avoid optional/extra args (= (length (ast:lambda-args fnc)) (length (app->args exp)))) (let ((new-params '()) (new-args '()) (args (cdr exp))) (for-each (lambda (param) (let ((var (adb:get/default param #f))) (cond ((and var (adbv:const? var)) #f) (else ;; Collect the params/args not optimized-out (set! new-args (cons (car args) new-args)) (set! new-params (cons param new-params)))) (set! args (cdr args)))) (ast:lambda-args fnc)) ;(trace:e rror `(DEBUG contract args ,(app->args exp) ; new-args ,new-args ; params ,(ast:lambda-args fnc) ; new-params ,new-params)) (cons (ast:%make-lambda (ast:lambda-id fnc) (reverse new-params) (ast:lambda-body fnc) (ast:lambda-has-cont fnc)) (map opt:contract (reverse new-args))))) (else (let ((result (cons fnc (map (lambda (e) (opt:contract e)) (cdr exp))))) ;; Perform constant folding if possible (if (and (prim-call? exp) (precompute-prim-app? result)) (with-handler ;; Safety check, keep going if eval fails (lambda (err) result) (eval result *contract-env*)) result)) )))) (else (error "CPS optimize [1] - Unknown expression" exp)))) ;; Inline primtives ;; Uses analysis DB, so must be executed after analysis phase ;; ;; TBD: better to enhance CPS conversion to do this?? (define (opt:inline-prims exp scope-sym . refs*) (let ((refs (if (null? refs*) (make-hash-table) (car refs*)))) ;(trace:error `(opt:inline-prims ,exp ,scope-sym)) (cond ((ref? exp) ;; Replace lambda variables, if necessary (let ((key (hash-table-ref/default refs exp #f))) (if key (opt:inline-prims key scope-sym refs) exp))) ((ast:lambda? exp) (ast:%make-lambda (ast:lambda-id exp) (ast:lambda-args exp) (map (lambda (b) (opt:inline-prims b scope-sym refs)) (ast:lambda-body exp)) (ast:lambda-has-cont exp))) ((const? exp) exp) ((quote? exp) exp) ((define? exp) `(define ,(define->var exp) ,@(opt:inline-prims (define->exp exp) (define->var exp) refs))) ;; TODO: map???? ((set!? exp) `(set! ,(set!->var exp) ,(opt:inline-prims (set!->exp exp) scope-sym refs))) ((if? exp) (cond ((not (if->condition exp)) (opt:inline-prims (if->else exp) scope-sym refs)) ;; Always false, so replace with else ((const? (if->condition exp)) (opt:inline-prims (if->then exp) scope-sym refs)) ;; Always true, replace with then (else `(if ,(opt:inline-prims (if->condition exp) scope-sym refs) ,(opt:inline-prims (if->then exp) scope-sym refs) ,(opt:inline-prims (if->else exp) scope-sym refs))))) ; Application: ((app? exp) ;(trace:error `(app? ,exp ,(ast:lambda? (car exp)) ; ,(length (cdr exp)) ; ,(length (ast:lambda-formals->list (car exp))) ; ,(all-prim-calls? (cdr exp)))) (cond ((and (ast:lambda? (car exp)) ;; TODO: check for more than one arg?? (equal? (length (cdr exp)) (length (ast:lambda-formals->list (car exp)))) (or ;; This "and" is not for primitives, but rather checking ;; for constants to optimize out. This just happens to be ;; a convenient place since the optimization is the same. (and ;; Check each parameter (every (lambda (param) (with-var param (lambda (var) (and ;; At least for now, do not replace if referenced by multiple functions (<= (length (adbv:ref-by var)) 1) ;; Need to keep variable because it is mutated (not (adbv:reassigned? var)) )))) (ast:lambda-formals->list (car exp))) ;; Args are all constants (every (lambda (arg) (and arg ;; #f is a special value for init, so do not optimize it for now (or (const? arg) ;;(ref? arg) ;; DEBUG (quote? arg)))) (cdr exp)) ) ;; Check for primitive calls that can be optimized out (and #;(begin (trace:error `(DEBUG ,exp ,(every (lambda (param) (with-var param (lambda (var) ;(trace:error `(DEBUG ,param ,(adbv:ref-by var))) (and ;; If param is never referenced, then prim is being ;; called for side effects, possibly on a global (not (null? (adbv:ref-by var))) ;; Need to keep variable because it is mutated (not (adbv:reassigned? var)) )))) (ast:lambda-formals->list (car exp))) ;; Check all args are valid primitives that can be inlined ,(every (lambda (arg) (and (prim-call? arg) (not (prim:cont? (car arg))))) (cdr exp)) ;; Disallow primitives that allocate a new obj, ;; because if the object is mutated all copies ;; must be modified. ,(one-instance-of-new-mutable-obj? (cdr exp) (ast:lambda-formals->list (car exp))) ,(inline-prim-call? (ast:lambda-body (car exp)) scope-sym (prim-calls->arg-variables (cdr exp)) (ast:lambda-formals->list (car exp))))) #t) ;; Double-check parameter can be optimized-out (every (lambda (param) (with-var param (lambda (var) ;(trace:error `(DEBUG ,param ,(adbv:ref-by var))) (and ;; If param is referenced in a loop (but defined outside) ;; do not inline function into the loop (or (not (adbv:ref-in-loop? var)) (adbv:def-in-loop? var)) ;; If param is never referenced, then prim is being ;; called for side effects, possibly on a global (not (null? (adbv:ref-by var))) ;; Need to keep variable because it is mutated (not (adbv:reassigned? var)) ;; Make sure param is not computed by vars that may be mutated (inline-ok-from-call-graph? param *adb-call-graph*) )))) (ast:lambda-formals->list (car exp))) ;; Check all args are valid primitives that can be inlined (every (lambda (arg) (and (prim-call? arg) ;; Do not inline functions that are looping over lists, seems counter-productive ;; Or functions that may be harmful to call more than once such as system (not (member (car arg) '( member assoc Cyc-fast-member Cyc-fast-assoc assq assv memq memv system))) (not (prim:cont? (car arg))))) (cdr exp)) ;; Disallow primitives that allocate a new obj, ;; because if the object is mutated all copies ;; must be modified. (one-instance-of-new-mutable-obj? (cdr exp) (ast:lambda-formals->list (car exp))) (or (prim-calls-inlinable? (cdr exp)) ;; Testing - every arg only used once ;(and ; (every ; (lambda (param) ; (with-var param (lambda (var) ; (equal? 1 (adbv:ref-count var))))) ; (ast:lambda-formals->list (car exp))) ; ;; Do not inline if prim mutates, to avoid cases where ; ;; a var may be modified out-of-order. May be possible ; ;; to be more intelligent about this in the future. ; (every ; (lambda (arg) ; (and (prim-call? arg) ; (not (equal? 'cell (car arg))) ; (not (prim:mutates? (car arg))))) ; (cdr exp))) (inline-prim-call? (ast:lambda-body (car exp)) scope-sym (prim-calls->arg-variables (cdr exp)) (ast:lambda-formals->list (car exp)))))) ) (let ((args (cdr exp))) (for-each (lambda (param) (hash-table-set! refs param (car args)) (set! args (cdr args))) (ast:lambda-formals->list (car exp)))) (opt:inline-prims (car (ast:lambda-body (car exp))) scope-sym refs)) ;; Lambda with a parameter that is never used; sequence code instead to avoid lambda ((and (ast:lambda? (car exp)) (every (lambda (arg) (and (not (set!? arg)) (or (not (prim-call? arg)) (not (prim:cont? (car arg))) ))) (cdr exp)) (every (lambda (param) (with-var param (lambda (var) (null? (adbv:ref-by var))))) (ast:lambda-formals->list (car exp))) ) (opt:inline-prims `(Cyc-seq ,@(cdr exp) ,@(ast:lambda-body (car exp))) scope-sym refs)) (else (map (lambda (e) (opt:inline-prims e scope-sym refs)) exp)))) (else (error `(Unexpected expression passed to opt:inline-prims ,exp)))))) ;; Do all the expressions contain prim calls? (define (all-prim-calls? exps) (cond ((null? exps) #t) ((prim-call? (car exps)) (all-prim-calls? (cdr exps))) (else #f))) ;; Find all variables passed to all prim calls (define (prim-calls->arg-variables exps) (apply append (map (lambda (exp) (cond ((pair? exp) (filter symbol? (cdr exp))) (else '()))) exps))) ;; Does the given primitive return a new instance of an object that ;; can be mutated? ;; ;; TODO: strings are a problem because there are ;; a lot of primitives that allocate them fresh! (define (prim-creates-mutable-obj? prim) (member prim '( apply ;; ?? cons make-vector make-bytevector bytevector bytevector-append bytevector-copy string->utf8 number->string symbol->string list->string utf8->string read-line string-append string substring Cyc-installation-dir Cyc-compilation-environment Cyc-bytevector-copy Cyc-utf8->string Cyc-string->utf8 list->vector Cyc-fast-list-1 Cyc-fast-list-2 Cyc-fast-list-3 Cyc-fast-list-4 Cyc-fast-vector-2 Cyc-fast-vector-3 Cyc-fast-vector-4 Cyc-fast-vector-5 open-input-file open-output-file open-binary-input-file open-binary-output-file ))) (define (prim-calls-inlinable? prim-calls) (every (lambda (prim-call) (and (prim:immutable-args/result? (car prim-call)) ; Issue #172 - Cannot assume that just because a primitive ; deals with immutable objects that it is safe to inline. ; A (set!) could still mutate variables the primitive is ; using, causing invalid behavior. ; ; So, make sure none of the args is mutated via (set!) (every (lambda (arg) (or (not (ref? arg)) (with-var arg (lambda (var) (not (adbv:mutated-by-set? var)))))) (cdr prim-call))) ) prim-calls)) ;; Check each pair of primitive call / corresponding lambda arg, ;; and verify that if the primitive call creates a new mutable ;; object, that only one instance of the object will be created. (define (one-instance-of-new-mutable-obj? prim-calls lam-formals) (let ((calls/args (map list prim-calls lam-formals))) (call/cc (lambda (return) (for-each (lambda (call/arg) (let ((call (car call/arg)) (arg (cadr call/arg))) ;; Cannot inline prim call if the arg is used ;; more than once and it creates a new mutable object, ;; because otherwise if the object is mutated then ;; only one of the instances will be affected. (if (and (prim-call? call) (prim-creates-mutable-obj? (car call)) ;; Make sure arg is not used more than once (with-var arg (lambda (var) (> (adbv:app-arg-count var) 1))) ) (return #f)))) calls/args) #t)))) ;; Find variables passed to a primitive (define (prim-call->arg-variables exp) (filter symbol? (cdr exp))) ;; Helper for the next function (define (inline-prim-call? exp scope-sym ivars args) (let ((fast-inline #t) (cannot-inline #f)) ;; TODO: causes problems doing this here??? ;(for-each ; (lambda (v) ; (with-var v (lambda (var) ; (if (adbv:mutated-by-set? var) ; (set! cannot-inline #t))))) ; args) (for-each (lambda (v) (with-var v (lambda (var) (if (and (not *inline-unsafe*) (or (member scope-sym (adbv:mutated-indirectly var)) ;(adbv:mutated-by-set? var) ;; TOO restrictive, only matters if set! occurs in body we )) ;; are inlining to. Also, does not catch cases where the ;; var might be mutated by a function call outside this ;; module (but hopefully we already catch that elsewhere). (set! cannot-inline #t)) (if (not (adbv:inlinable var)) (set! fast-inline #f))))) ivars) ;(trace:error `(DEBUG inline-prim-call ,exp ,ivars ,args ,cannot-inline ,fast-inline)) (cond (cannot-inline #f) (else (if fast-inline ;; Fast path, no need for more analysis ;; faster and safer but (at least for now) misses some ;; opportunities for optimization because it takes a global ;; approach rather than considering the specific variables ;; involved for any given optimization. That's why we call ;; inline-ok? below if this is false. fast-inline ;; Fast path failed, see if we can inline anyway (call/cc (lambda (return) ;(trace:error `(inline-ok? ,exp ,ivars ,args)) (inline-ok? exp ivars args (list #f) return) (return #t)))))))) ;; Make sure inlining a primitive call will not cause out-of-order execution ;; exp - expression to search ;; ivars - vars to be inlined ;; args - list of variable args (should be small) ;; arg-used - has a variable been used? if this is true and we find an ivar, ;; it cannot be optimized-out and we have to bail. ;; This is a cons "box" so it can be mutated. ;; return - call into this continuation to return early (define (inline-ok? exp ivars args arg-used return) ;(trace:error `(inline-ok? ,exp ,ivars ,args ,arg-used)) (cond ((ref? exp) (cond ((member exp args) (set-car! arg-used #t)) ((member exp ivars) ;(trace:error `(inline-ok? return #f ,exp ,ivars ,args)) (return #f)) (else #t))) ((ast:lambda? exp) (for-each (lambda (e) (inline-ok? e ivars args arg-used return)) (ast:lambda-formals->list exp)) (for-each (lambda (e) (inline-ok? e ivars args arg-used return)) (ast:lambda-body exp))) ((const? exp) #t) ((quote? exp) #t) ((define? exp) (inline-ok? (define->var exp) ivars args arg-used return) (inline-ok? (define->exp exp) ivars args arg-used return)) ((set!? exp) (inline-ok? (set!->var exp) ivars args arg-used return) (inline-ok? (set!->exp exp) ivars args arg-used return)) ((if? exp) (if (not (ref? (if->condition exp))) (inline-ok? (if->condition exp) ivars args arg-used return)) (inline-ok? (if->then exp) ivars args arg-used return) (inline-ok? (if->else exp) ivars args arg-used return)) ((app? exp) (cond ((and (prim? (car exp)) (not (prim:mutates? (car exp)))) ;; If primitive does not mutate its args, ignore if ivar is used (for-each (lambda (e) (if (not (ref? e)) (inline-ok? e ivars args arg-used return))) (reverse (cdr exp)))) ;; loop3-dev WIP step #2 - some args can be safely ignored ;((and (prim? (car exp)) ; (prim:mutates? (car exp)) ; (member (car exp) '(vector-set!)) ; ) ; ;; with vector-set, only arg 1 (the vector) is actually mutated ; ;; TODO: is this always true? do we have problems with self-recursive vecs?? ; (inline-ok? (cadr exp) ivars args arg-used return) ;) (else (when (ref? (car exp)) (with-var (car exp) (lambda (var) (when (adbv:defines-lambda-id var) ;TODO: return #f if any ivars are members of vars-mutated-by-set from the adbf (with-fnc (adbv:defines-lambda-id var) (lambda (fnc) (for-each (lambda (ivar) (if (member ivar (adbf:vars-mutated-by-set fnc)) (return #f)) ) ivars)))) ))) (for-each (lambda (e) (inline-ok? e ivars args arg-used return)) (reverse exp))))) ;; Ensure args are examined before function (else (error `(Unexpected expression passed to inline prim check ,exp))))) ;; Similar to (inline-ok?) above, but this makes a single pass to ;; figure out which refs can be inlined and which ones are mutated or ;; otherwise used in such a way that they cannot be safely inlined. ;; ;; exp - expression to analyze ;; args - list of formals for the current lambda (define (analyze:find-inlinable-vars exp args) ;(trace:error `(inline-ok? ,exp ,ivars ,args ,arg-used)) (cond ((ref? exp) ;; Ignore the current lambda's formals (when (not (member exp args)) ;; If the code gets this far, assume we came from a place ;; that does not allow the var to be inlined. We need to ;; explicitly white-list variables that can be inlined. ; (trace:error `(DEBUG not inlinable ,exp ,args)) (with-var exp (lambda (var) (adbv:set-inlinable! var #f))))) ((ast:lambda? exp) ;; Pass along immediate lambda args, and ignore if they ;; are used??? sort of makes sense because we want to inline ;; function arguments by replacing lambda args with the actual ;; arguments. ;; ;; This may still need some work to match what is going on ;; in inline-ok. (let ((formals (ast:lambda-formals->list exp))) (for-each (lambda (e) ;; TODO: experimental change, append args to formals instead ;; of just passing formals along ;(analyze:find-inlinable-vars e (append formals args))) ;; try this for now, do a full make then re-make and verify everything works (analyze:find-inlinable-vars e formals)) (ast:lambda-body exp)))) ((const? exp) #t) ((quote? exp) #t) ((define? exp) (analyze:find-inlinable-vars (define->var exp) args) (analyze:find-inlinable-vars (define->exp exp) args)) ((set!? exp) (analyze:find-inlinable-vars (set!->var exp) args) (analyze:find-inlinable-vars (set!->exp exp) args)) ((if? exp) (if (not (ref? (if->condition exp))) (analyze:find-inlinable-vars (if->condition exp) args)) (analyze:find-inlinable-vars (if->then exp) args) (analyze:find-inlinable-vars (if->else exp) args)) ((app? exp) (cond ((or (member (car exp) *inlinable-functions*) (and (prim? (car exp)) (not (prim:mutates? (car exp))))) ;; If primitive does not mutate its args, ignore if ivar is used (for-each (lambda (e) (if (not (ref? e)) (analyze:find-inlinable-vars e args))) (cdr exp))) ;(reverse (cdr exp)))) ;; If primitive mutates its args, ignore ivar if it is not mutated ((and (prim? (car exp)) (prim:mutates? (car exp)) (> (length exp) 1)) (analyze:find-inlinable-vars (cadr exp) args) ;; First param is always mutated (for-each (lambda (e) (if (not (ref? e)) (analyze:find-inlinable-vars e args))) (cddr exp))) ((and (not (prim? (car exp))) (ref? (car exp))) (define pure-fnc #f) (define calling-cont #f) (define ref-formals '()) ;; Does ref refer to a pure function (no side effects)? (let ((var (adb:get/default (car exp) #f))) (if var (let ((lid (adbv:defines-lambda-id var)) (assigned-val (adbv:assigned-value var))) (cond (lid (with-fnc! lid (lambda (fnc) (if (not (adbf:side-effects fnc)) (set! pure-fnc #t))))) ((ast:lambda? assigned-val) (with-fnc! (ast:lambda-id assigned-val) (lambda (fnc) (if (not (adbf:side-effects fnc)) (set! pure-fnc #t))))) ;; Experimental - if a cont, execution will leave fnc anyway, ;; so inlines there should be safe ((adbv:cont? var) (set! calling-cont #t)) )))) ;; (with-var (car exp) (lambda (var) (let ((val (adbv:assigned-value var))) (cond ((ast:lambda? val) (set! ref-formals (ast:lambda-formals->list val))) ((and (pair? val) (ast:lambda? (car val)) (null? (cdr val))) (set! ref-formals (ast:lambda-formals->list (car val)))) )))) ;(trace:error `(DEBUG ref app ,(car exp) ,(cdr exp) ,ref-formals)) (cond ((or pure-fnc calling-cont) (for-each (lambda (e) ;; Skip refs since fnc is pure and cannot change them (if (not (ref? e)) (analyze:find-inlinable-vars e args))) exp)) ;; TODO: how do you know if it is the same function, or just ;; another function with the same formals? ((= (length ref-formals) (length (cdr exp))) (analyze:find-inlinable-vars (car exp) args) (for-each (lambda (e a) ;; Optimization: ;; Ignore if an argument to a function is passed back ;; to another call to the function as the same parameter. (if (not (equal? e a)) (analyze:find-inlinable-vars e args))) (cdr exp) ref-formals)) (else (for-each (lambda (e) (analyze:find-inlinable-vars e args)) exp)))) (else (for-each (lambda (e) (analyze:find-inlinable-vars e args)) exp)))) ;(reverse exp))))) ;; Ensure args are examined before function (else (error `(Unexpected expression passed to find inlinable vars ,exp))))) (define (beta-expand/called-once? exp) (beta-expand/opts? exp #t)) (define (beta-expand? exp) (beta-expand/opts? exp #f)) (define (beta-expand/opts? exp called-once?) (cond ((and (app? exp) (ref? (car exp))) (with-var (car exp) (lambda (var) (let* ((fnc* (adbv:assigned-value var)) (fnc (if (and (pair? fnc*) (ast:lambda? (car fnc*))) (car fnc*) fnc*))) (and (ast:lambda? fnc) (or (not called-once?) (= 1 (adbv:app-fnc-count var))) (not (adbv:reassigned? var)) (not (adbv:self-rec-call? var)) (not (fnc-depth>? (ast:lambda-body fnc) *beta-expand-threshold*)) ;(not (fnc-depth>? (ast:lambda-body fnc) 5)) ;; Issue here is we can run into code that calls the ;; same continuation from both if branches. In this ;; case we do not want to beta-expand as a contraction ;; because duplicate instances of the same code may be ;; introduced, causing problems downstream. (or (not called-once?) (and called-once? (not (contains-if? (ast:lambda-body fnc))))) )) ))) (else #f))) (define (fnc-depth>? exp depth) (call/cc (lambda (return) (define (scan exp depth) (if (zero? depth) (return #t)) (cond ((ast:lambda? exp) (scan (ast:lambda-body exp) (- depth 1))) ((quote? exp) #f) ((app? exp) (for-each (lambda (e) (scan e (- depth 1))) exp)) (else #f))) (scan exp depth) (return #f)))) (define (contains-if? exp) (call/cc (lambda (return) (define (scan exp) (cond ((ast:lambda? exp) (scan (ast:lambda-body exp))) ((quote? exp) #f) ((if? exp) (return #t)) ((app? exp) (for-each scan exp)) (else #f))) (scan exp) (return #f)))) ;; Check app and beta expand if possible, else just return given code (define (beta-expand-app exp rename-lambdas) (let* ((args (cdr exp)) (var (adb:get/default (car exp) #f)) ;; Function definition, or #f if none (fnc* (if var (adbv:assigned-value var) #f)) (fnc (if (and (pair? fnc*) (ast:lambda? (car fnc*))) (car fnc*) fnc*)) (formals (if (ast:lambda? fnc) (ast:lambda-args fnc) '())) ;;; First formal, or #f if none ;(maybe-cont (if (and (list? formals) (pair? formals)) ; (car formals) ; #f)) ;;; function's continuation symbol, or #f if none ;(cont (if maybe-cont ; (with-var maybe-cont (lambda (var) ; (if (adbv:cont? var) maybe-cont #f))) ; #f)) ) ;(trace:error `(JAE beta expand ,exp ,var ,fnc ,formals )) (cond ;; TODO: what if fnc has no cont? do we need to handle differently? ((and (ast:lambda? fnc) (not (adbv:reassigned? var)) ;; Failsafe (not (equal? fnc (adbv:assigned-value var))) ;; Do not expand recursive func (not (adbv:cont? var)) ;; TEST, don't delete a continuation (list? formals) (= (length args) (length formals))) ;(trace:error `(JAE DEBUG beta expand ,exp)) (beta-expansion-app exp fnc rename-lambdas) ; exp ) (else exp)))) ;; beta expansion failed ;; Replace function call with body of fnc (define (beta-expansion-app exp fnc rename-lambdas) ;(write `(beta-expansion-app ,exp)) ;(newline) ;; Mapping from a formal => actual arg (define formals/actuals (map cons (ast:lambda-args fnc) (cdr exp))) ;; Replace ref with corresponding argument from function call being replaced (define (replace ref renamed) (let ((r (assoc ref formals/actuals))) ;(write `(DEBUG2 replace ,ref ,renamed ,r)) ;(newline) (if (and r (not (eq? (car r) (cdr r)))) ;; Prevent an inf loop (scan (cdr r) renamed) ;ref (let ((rn (assoc ref renamed))) (if rn (cdr rn) ref))))) (define (scan exp renamed) (cond ((ast:lambda? exp) (if rename-lambdas (let* ((args (ast:lambda-formals->list exp)) (ltype (ast:lambda-formals-type exp)) (a-lookup (map (lambda (a) (cons a (gensym a))) args))) (ast:%make-lambda ;; if rename-lambdas also need to rename lambda formals here and ;; setup and a-lookup to replace any refs with the renamed formal. the ;; problem is, if we don't do this, there will be multiple lambda's with ;; the same arg, which causes problems when the optimizer tries to replace ;; one with its value, since different instances will have different values (ast:get-next-lambda-id!) (list->lambda-formals (map (lambda (p) (cdr p)) a-lookup) ltype) (scan (ast:lambda-body exp) (append a-lookup renamed)) (ast:lambda-has-cont exp))) (ast:%make-lambda (ast:lambda-id exp) (ast:lambda-args exp) (scan (ast:lambda-body exp) renamed) (ast:lambda-has-cont exp)))) ((ref? exp) (replace exp renamed)) ((quote? exp) exp) ((app? exp) (map (lambda (e) (scan e renamed)) exp)) (else exp))) (scan (car (ast:lambda-body fnc)) '())) ;; Full beta expansion phase, make a pass over all of the program's AST (define (opt:beta-expand exp) ;(write `(DEBUG opt:beta-expand ,exp)) (newline) (cond ((ast:lambda? exp) (ast:%make-lambda (ast:lambda-id exp) (ast:lambda-args exp) (opt:beta-expand (ast:lambda-body exp)) (ast:lambda-has-cont exp))) ((quote? exp) exp) ((const? exp) exp) ((ref? exp) exp) ((define? exp) `(define ,(define->var exp) ,@(opt:beta-expand (define->exp exp)))) ((set!? exp) `(set! ,(set!->var exp) ,(opt:beta-expand (set!->exp exp)))) ((if? exp) `(if ,(opt:beta-expand (if->condition exp)) ,(opt:beta-expand (if->then exp)) ,(opt:beta-expand (if->else exp)))) ((app? exp) (let ((code (if (beta-expand? exp) (beta-expand-app exp #t) exp))) (map opt:beta-expand code))) (else exp))) (define (analyze-cps exp) (analyze:find-named-lets exp) (analyze:find-direct-recursive-calls exp) (analyze:find-recursive-calls exp) (analyze-find-lambdas exp -1) (analyze-lambda-side-effects exp -1) (analyze-lambda-side-effects exp -1) ;; 2nd pass guarantees lambda purity (analyze exp -1 -1) ;; Top-level is lambda ID -1 (analyze2 exp) ;; Second pass (analyze:find-inlinable-vars exp '()) ;; Identify variables safe to inline (set! *adb-call-graph* (analyze:build-call-graph exp)) (analyze:find-recursive-calls2 exp) ;(analyze:set-calls-self) ) (define (analyze:set-calls-self) (let ((idents (filter symbol? (hash-table-keys *adb*)))) (for-each (lambda (id) (let ((var (adb:get/default id #f))) (when (and var (adbv:self-rec-call? var)) (and-let* ((a-value (adbv:assigned-value var)) ((pair? a-value)) ((ast:lambda? (car a-value))) (lid (ast:lambda-id (car a-value)))) (trace:info `(TODO ,id ,lid ,a-value)) (with-fnc! lid (lambda (fnc) (adbf:set-calls-self! fnc #t)))) )) ) idents))) ;; NOTES: ;; ;; TODO: run CPS optimization (not all of these phases may apply) ;; phase 1 - constant folding, function-argument expansion, beta-contraction of functions called once, ;; and other "contractions". some of this is already done in previous phases. we will leave ;; that alone for now ;; phase 2 - beta expansion ;; phase 3 - eta reduction ;; phase 4 - hoisting ;; phase 5 - common subexpression elimination ;; TODO: re-run phases again until program is stable (less than n opts made, more than r rounds performed, etc) ;; END notes (define (optimize-cps ast add-globals! flag-set?) ;; Handle any modified settings from caller (if (flag-set? 'beta-expand-threshold) (set! *beta-expand-threshold* (flag-set? 'beta-expand-threshold))) (if (flag-set? 'inline-unsafe) (set! *inline-unsafe* #t)) ;; Analysis phase (adb:clear!) (analyze-cps ast) (trace:info "---------------- cps analysis db:") (trace:info (adb:get-db)) ;; Optimization phase (let ((new-ast (opt:inline-prims (opt:contract ast) -1))) ;; Just a hack for now, need to fix beta expand in compiler benchmark (when (< (length (filter define? new-ast)) 1000) (set! new-ast (opt:beta-expand new-ast)) ;; TODO: temporarily disabled, causes problems with massive expansions ;; in compiler benchmark, need to revist how to throttle/limit this ;; (program size? heuristics? what else??) ) ;; Memoize pure functions, if instructed (when (and (procedure? flag-set?) (flag-set? 'memoize-pure-functions)) (set! new-ast (opt:memoize-pure-fncs new-ast add-globals!)) ) new-ast ) ) ;; Renumber lambdas and re-run analysis (define (opt:renumber-lambdas! exp) (define (scan exp) (cond ((ast:lambda? exp) (ast:%make-lambda (ast:get-next-lambda-id!) (ast:lambda-args exp) (scan (ast:lambda-body exp)) (ast:lambda-has-cont exp))) ((quote? exp) exp) ((app? exp) (map (lambda (e) (scan e)) exp)) (else exp))) (ast:reset-lambda-ids!) ;; Convenient to start back from 1 (let ((result (scan exp))) (adb:clear!) (analyze-cps result) result)) ;; Closure-conversion. ;; ;; Closure conversion eliminates all of the free variables from every ;; lambda term. ;; ;; The code below is based on a fusion of a port of the 90-min-scc code by ;; Marc Feeley and the closure conversion code in Matt Might's scheme->c ;; compiler. (define (pos-in-list x lst) (let loop ((lst lst) (i 0)) (cond ((not (pair? lst)) #f) ((eq? (car lst) x) i) (else (loop (cdr lst) (+ i 1)))))) (define (let->vars exp) (map car (cadr exp))) (define (closure-convert exp globals . opts) (let ((optimization-level 2)) (if (pair? opts) (set! optimization-level (car opts))) (_closure-convert exp globals optimization-level))) (define (_closure-convert exp globals optimization-level) (define (set-adb-info! id formals size) (with-fnc! id (lambda (fnc) (adbf:set-all-params! fnc formals) (adbf:set-closure-size! fnc size)))) (define (convert exp self-var free-var-lst) (define (cc exp) ;(trace:error `(cc ,exp)) (cond ((ast:lambda? exp) (let* ((new-self-var (gensym 'self)) (body (ast:lambda-body exp)) (new-free-vars (difference (difference (free-vars body) (cons 'Cyc-seq (cons 'Cyc-local-set! (ast:lambda-formals->list exp)))) globals)) (formals (list->lambda-formals (cons new-self-var (ast:lambda-formals->list exp)) (ast:lambda-formals-type exp))) ) (set-adb-info! (ast:lambda-id exp) formals (length new-free-vars)) `(%closure ,(ast:%make-lambda (ast:lambda-id exp) formals (list (convert (car body) new-self-var new-free-vars)) (ast:lambda-has-cont exp)) ,@(map (lambda (v) ;; TODO: splice here? (cc v)) new-free-vars)))) ((const? exp) exp) ((quote? exp) exp) ((ref? exp) (let ((i (pos-in-list exp free-var-lst))) (if i `(%closure-ref ,self-var ,(+ i 1)) exp))) ((or (tagged-list? '%closure-ref exp) (tagged-list? '%closure exp) (prim-call? exp)) `(,(car exp) ,@(map cc (cdr exp)))) ;; TODO: need to splice? ((set!? exp) `(set! ,(set!->var exp) ,(cc (set!->exp exp)))) ;; Special case now with local var redux ((tagged-list? 'let exp) `(let ,(map (lambda (var/val) (let ((var (car var/val)) (val (cadr var/val))) `(,var ,(cc val)))) (cadr exp)) ,(convert (caddr exp) self-var ;; Do not closure convert the let's variables because ;; the previous code guarantees they are locals (filter (lambda (v) (not (member v (let->vars exp)))) free-var-lst))) ) ((lambda? exp) (error `(Unexpected lambda in closure-convert ,exp))) ((if? exp) `(if ,@(map cc (cdr exp)))) ((cell? exp) `(cell ,(cc (cell->value exp)))) ((cell-get? exp) `(cell-get ,(cc (cell-get->cell exp)))) ((set-cell!? exp) `(set-cell! ,(cc (set-cell!->cell exp)) ,(cc (set-cell!->value exp)))) ((app? exp) (let ((fn (car exp)) (args (map cc (cdr exp)))) (cond ;TODO: what about application of cyc-seq? does this only occur as a nested form? can we combine here or earlier?? ; I think that is what is causing cc printing to explode exponentially! ;((tagged-list? 'Cyc-seq fnc) ; (foldl (lambda (sexp acc) (cons sexp acc)) '() (reverse '(a b c (cyc-seq 1) (cyc-seq 2 ((cyc-seq 3)))))) ; TODO: maybe just call a function to 'flatten' seq's ((equal? 'Cyc-seq fn) `(Cyc-seq ,@args)) ((equal? 'Cyc-local-set! fn) `(Cyc-local-set! ,@args)) ((ast:lambda? fn) (cond ;; If the lambda argument is not used, flag so the C code is ;; all generated within the same function ((and #f (> optimization-level 0) (eq? (ast:lambda-formals-type fn) 'args:fixed) (pair? (ast:lambda-formals->list fn)) (with-var (car (ast:lambda-formals->list fn)) (lambda (var) (zero? (adbv:ref-count var)))) ;; Non-CPS args (every (lambda (x) (or (not (pair? x)) ;; Should never happen (and (prim-call? x) ;; TODO: necessary for gcbench stability??? (not (prim:mutates? (car x))) (not (prim:cont? (car x)))))) args)) `(Cyc-seq ,@args ,@(map cc (ast:lambda-body fn)))) (else (let* ((body (ast:lambda-body fn)) (new-free-vars (difference (difference (free-vars body) (cons 'Cyc-seq (cons 'Cyc-local-set! (ast:lambda-formals->list fn)))) globals)) (new-free-vars? (> (length new-free-vars) 0))) (if new-free-vars? ; Free vars, create a closure for them (let* ((new-self-var (gensym 'self)) (formals (list->lambda-formals (cons new-self-var (ast:lambda-formals->list fn)) (ast:lambda-formals-type fn))) ) (set-adb-info! (ast:lambda-id fn) formals (length new-free-vars)) `((%closure ,(ast:%make-lambda (ast:lambda-id fn) formals (list (convert (car body) new-self-var new-free-vars)) (ast:lambda-has-cont fn) ) ,@(map (lambda (v) (cc v)) new-free-vars)) ,@args)) ; No free vars, just create simple lambda `(,(ast:%make-lambda (ast:lambda-id fn) (ast:lambda-args fn) (map cc body) (ast:lambda-has-cont fn) ) ,@args) ))))) ((lambda? fn) (error `(Unexpected lambda in closure-convert ,exp))) (else (let ((f (cc fn))) `((%closure-ref ,f 0 ;; Indicate if closure refers to a compiled continuation ,@(if (and (symbol? fn) (or (if-var fn adbv:cont?) (if-var fn adbv:global?))) (list #t) (list))) ,f ,@args)))))) (else (error "unhandled exp: " exp)))) (cc exp)) (ast:make-lambda (list) (list (convert exp #f '())) #f)) (define (analyze:find-named-lets exp) (define (scan exp lp) (cond ((ast:lambda? exp) (let* ((id (ast:lambda-id exp)) (has-cont (ast:lambda-has-cont exp)) (sym (string->symbol (string-append "lambda-" (number->string id) (if has-cont "-cont" "")))) (args* (ast:lambda-args exp)) (args (if (null? args*) '() (formals->list args*))) ) (when lp (for-each (lambda (a) (with-var! a (lambda (var) (adbv:set-def-in-loop! var #t)))) args)) `(,sym ,(ast:lambda-args exp) ,@(map (lambda (e) (scan e lp)) (ast:lambda-body exp)))) ) ((quote? exp) exp) ((const? exp) exp) ((ref? exp) (when lp ;(trace:error `(found var ref ,exp in loop)) (with-var! exp (lambda (var) (adbv:set-ref-in-loop! var #t)))) exp) ((define? exp) `(define ,(define->var exp) ,@(scan (define->exp exp) lp))) ((set!? exp) `(set! ,(set!->var exp) ,(scan (set!->exp exp) lp))) ((if? exp) `(if ,(scan (if->condition exp) lp) ,(scan (if->then exp) lp) ,(scan (if->else exp) lp))) ((app? exp) (cond ;; Detect CPS pattern without any optimizations ((and-let* ( ;; Find lambda with initial #f assignment ((ast:lambda? (car exp))) ((pair? (cdr exp))) ((not (cadr exp))) ((list? (ast:lambda-args (car exp)))) (= 1 (length (ast:lambda-args (car exp)))) ;; Get information for continuation (loop-sym (car (ast:lambda-args (car exp)))) (inner-exp (car (ast:lambda-body (car exp)))) ((app? inner-exp)) ((ast:lambda? (car inner-exp))) ;; Find the set (assumes CPS conversion) ((pair? (cdr inner-exp))) ((ast:lambda? (car inner-exp))) (lambda/set (car (ast:lambda-body (car inner-exp)))) ((app? lambda/set)) ((ast:lambda? (car lambda/set))) ((pair? (cdr lambda/set))) ((set!? (cadr lambda/set))) ((equal? (set!->var (cadr lambda/set)) loop-sym)) ; (unused (begin (newline) (newline) (write loop-sym) (write (ast:ast->pp-sexp (cadr lambda/set))) (newline)(newline))) ;; Check the set's continuation ((app? (car (ast:lambda-body (car lambda/set))))) ; (unused2 (begin (newline) (newline) (write (ast:ast->pp-sexp (car lambda/set))) (newline)(newline))) ((equal? (caar (ast:lambda-body (car lambda/set))) loop-sym)) ) ;(trace:error `(found loop in ,exp)) ;; TODO: do we want to record the lambda that is a loop? ;; Continue scanning, indicating we are in a loop (map (lambda (e) (scan e #t)) exp) )) ;; Detect optimized CPS pattern ((and-let* ( ;; Find lambda with initial #f assignment ((ast:lambda? (car exp))) ((pair? (cdr exp))) ((not (cadr exp))) (= 1 (length (ast:lambda-args (car exp)))) ;; Get information for continuation (loop-sym (car (ast:lambda-args (car exp)))) (inner-exp (car (ast:lambda-body (car exp)))) ((app? inner-exp)) ((ast:lambda? (car inner-exp))) ;; Find the set (assumes CPS conversion) ((pair? (cdr inner-exp))) ((set!? (cadr inner-exp))) ((equal? (set!->var (cadr inner-exp)) loop-sym)) ;; Check the set's continuation ((app? (car (ast:lambda-body (car inner-exp))))) ((equal? (caar (ast:lambda-body (car inner-exp))) loop-sym)) ) ;;(trace:error `(found loop in ,exp)) ;; TODO: do we want to record the lambda that is a loop? ;; Continue scanning, indicating we are in a loop (map (lambda (e) (scan e #t)) exp) )) (else (map (lambda (e) (scan e lp)) exp)))) (else exp))) (scan exp #f)) ;;; This function walks over a Closure-converted expression and ;;; builds a table of all variable references. This can be used ;;; to determine with certainty what variables are actually used. ;;; ;;; Returns a hash table where each key/var is a referenced var. (define (analyze:cc-ast->vars sexp) (define %ht (make-hash-table)) (define (add! ref) (hash-table-set! %ht ref ref)) (define (scan exp) (cond ((ast:lambda? exp) (scan `(%closure ,exp) )) ((const? exp) #f) ((prim? exp) #f) ((ref? exp) (add! exp)) ((quote? exp) #f) ((if? exp) (scan (if->condition exp)) (scan (if->then exp)) (scan (if->else exp))) ((tagged-list? '%closure exp) (let* ((lam (closure->lam exp)) (body (car (ast:lambda-body lam)))) (scan body) (for-each scan (closure->fv exp)))) ;; Global definition ((define? exp) (scan (car (define->exp exp)))) ((define-c? exp) #f) ;; Application: ((app? exp) (for-each scan exp)) (else (error "unknown exp in analyze-cc-vars " exp)))) (for-each scan sexp) %ht) ;; Find any top-level functions that call themselves directly (define (analyze:find-direct-recursive-calls exp) ;; Verify the continuation is simple and there is no closure allocation (define (check-cont k) (cond ((ref? k) #t) (else #f))) ;; Check arguments to the top level function to make sure ;; they are "safe" for further optimizations. ;; Right now this is very conservative. (define (check-args args) (define (check exp) (cond ((quote? exp) #t) ((const? exp) #t) ((ref? exp) #t) ((app? exp) (and ;; TODO: Very conservative right now, could include more (member (car exp) '(car cdr)) (check-args (cdr exp)))) (else #f))) (every check args)) (define (scan exp def-sym) ;(trace:info `(analyze:find-direct-recursive-calls scan ,def-sym ,exp)) (cond ((ast:lambda? exp) ;; Reject if there are nested functions #f) ((quote? exp) exp) ((const? exp) exp) ((ref? exp) exp) ((define? exp) #f) ((set!? exp) #f) ((if? exp) (scan (if->condition exp) def-sym) ;; OK to check?? (scan (if->then exp) def-sym) (scan (if->else exp) def-sym)) ((app? exp) (when (equal? (car exp) def-sym) (cond ((and (check-cont (cadr exp)) (check-args (cddr exp))) (trace:info `("direct recursive call" ,exp ,(cadr exp) ,(check-cont (cadr exp)))) (with-var! def-sym (lambda (var) (adbv:set-direct-rec-call! var #t)))) (else (trace:info `("not a direct recursive call" ,exp)))))) (else #f))) (if (pair? exp) (for-each (lambda (exp) ;;(write exp) (newline) (and-let* (((define? exp)) (def-exps (define->exp exp)) ((record? (car def-exps))) ((ast:lambda? (car def-exps))) ) (scan (car (ast:lambda-body (car def-exps))) (define->var exp)))) exp)) ) ;; Find functions that call themselves. This is not as restrictive ;; as finding "direct" calls. (define (analyze:find-recursive-calls exp) (define (scan exp def-sym) ;(trace:info `(analyze:find-recursive-calls scan ,def-sym ,exp)) (cond ((ast:lambda? exp) (for-each (lambda (e) (scan e def-sym)) (ast:lambda-body exp))) ((quote? exp) exp) ((const? exp) exp) ((ref? exp) exp) ((define? exp) #f) ;; TODO ?? ((set!? exp) #f) ;; TODO ?? ((if? exp) (scan (if->condition exp) def-sym) (scan (if->then exp) def-sym) (scan (if->else exp) def-sym)) ((app? exp) (when (equal? (car exp) def-sym) (trace:info `("recursive call" ,exp)) (with-var! def-sym (lambda (var) (adbv:set-self-rec-call! var #t))) )) (else #f))) ;; TODO: probably not good enough, what about recursive functions that are not top-level?? (if (pair? exp) (for-each (lambda (exp) ;;(write exp) (newline) (and-let* (((define? exp)) (def-exps (define->exp exp)) ((record? (car def-exps))) ((ast:lambda? (car def-exps))) ) (scan (car (ast:lambda-body (car def-exps))) (define->var exp)))) exp)) ) ;; Does given symbol refer to a recursive call to given lambda ID? (define (rec-call? sym lid) (cond ((ref? sym) (let ((var (adb:get/default sym #f))) ;(trace:info ; `(rec-call? ,sym ,lid ; ;; TODO: crap, these are not set yet!!! ; ;; may need to consider keeping out original version of find-recursive-calls and ; ;; adding a new version that does a deeper analysis ; ,(if var (not (adbv:reassigned? var)) #f) ; ,(if var (adbv:assigned-value var) #f) ; ;,((ast:lambda? var-lam)) ; ,(adb:get/default lid #f) ; ) ; ) (and-let* ( ((not (equal? var #f))) ((not (adbv:reassigned? var))) (var-lam (adbv:assigned-value var)) ((ast:lambda? var-lam)) (fnc (adb:get/default lid #f)) ) ;(trace:info `(equal? ,lid ,(ast:lambda-id var-lam))) (equal? lid (ast:lambda-id var-lam))))) (else #f))) ;; Same as the original function, but this one is called at the end of analysis and ;; uses data that was previously not available. ;; ;; The reason for having two versions of this is that the original is necessary for ;; beta expansion (and must remain, at least for now) and this one will provide useful ;; data for code generation. ;; ;; TODO: is the above true? not so sure anymore, need to verify that, look at optimize-cps (define (analyze:find-recursive-calls2 exp) (define (scan exp def-sym lid) ;(trace:info `(analyze:find-recursive-calls2 scan ,def-sym ,exp ,lid)) (cond ((ast:lambda? exp) (for-each (lambda (e) (scan e def-sym (ast:lambda-id exp))) (ast:lambda-body exp))) ((quote? exp) exp) ((const? exp) exp) ((ref? exp) exp) ((define? exp) #f) ;; TODO ?? ((set!? exp) (for-each (lambda (e) (scan e def-sym lid)) (cdr exp)) ) ((if? exp) (scan (if->condition exp) def-sym lid) (scan (if->then exp) def-sym lid) (scan (if->else exp) def-sym lid)) ((app? exp) (when (or ;(equal? (car exp) def-sym) TODO: def-sym is obsolete, remove it (rec-call? (car exp) lid)) ;(trace:info `("recursive call" ,exp)) (with-fnc! lid (lambda (fnc) (adbf:set-calls-self! fnc #t))) (with-var! (car exp) (lambda (var) (adbv:set-self-rec-call! var #t)))) (for-each (lambda (e) (scan e def-sym lid)) exp) ) (else #f))) ;; TODO: probably not good enough, what about recursive functions that are not top-level?? ;TODO: need to address those now, I think we have the support now via (rec-call?) (if (pair? exp) (for-each (lambda (exp) ;(trace:info `(analyze:find-recursive-calls ,exp)) (and-let* (((define? exp)) (def-exps (define->exp exp)) ((record? (car def-exps))) ((ast:lambda? (car def-exps))) (id (ast:lambda-id (car def-exps))) ) (scan (car (ast:lambda-body (car def-exps))) (define->var exp) id) )) exp)) ) ;; well-known-lambda :: symbol -> Either (AST Lambda | Boolean) ;; Does the given symbol refer to a well-known lambda? ;; If so the corresponding lambda object is returned, else #f. (define (well-known-lambda sym) (and *well-known-lambda-sym-lookup-tbl* (hash-table-ref/default *well-known-lambda-sym-lookup-tbl* sym #f))) (define *well-known-lambda-sym-lookup-tbl* #f) ;; Scan for well-known lambdas: ;; - app of a lambda is well-known, that's easy ;; - lambda passed as a cont. If we can identify all the places the cont is ;; called and it is not used for anything but calls, then I suppose that ;; also qualifies as well-known. ;; - ?? must be other cases (define (analyze:find-known-lambdas exp) ;; Lambda conts that are candidates for well-known functions, ;; we won't know until we check exactly how the cont is used... (define candidates (make-hash-table)) (define scopes (make-hash-table)) ;; Add given lambda to candidate table ;; ast:lam - AST Lambda object ;; scope-ast:lam - Lambda that is calling ast:lam ;; param-sym - Symbol of the parameter that the lambda is passed as (define (add-candidate! ast:lam scope-ast:lam param-sym) (hash-table-set! candidates param-sym ast:lam) (hash-table-set! scopes param-sym scope-ast:lam) ) ;; Remove given lambda from candidate table ;; param-sym - Symbol representing the lambda to remove (define (remove-candidate param-sym) (hash-table-delete! candidates param-sym) (hash-table-delete! scopes param-sym) ) ;; Determine if the expression is a call to a primitive that receives ;; a continuation. This is important since well-known functions cannot ;; be passed as such a cont. (define (prim-call/cont? exp) (let ((result (and (app? exp) (prim:cont? (car exp))))) ;(trace:info `(prim-call/cont? ,exp ,result)) result)) (define (found exp . sym) (let ((lid (ast:lambda-id exp))) (if (null? sym) (trace:info `(found known lambda with id ,lid)) (trace:info `(found known lambda with id ,lid sym ,(car sym)))) (with-fnc! lid (lambda (fnc) (adbf:set-well-known! fnc #t))))) (define (scan exp scope) (cond ((ast:lambda? exp) (for-each (lambda (e) (scan e (ast:lambda-id exp))) (ast:lambda-body exp))) ((quote? exp) exp) ((const? exp) exp) ((ref? exp) (remove-candidate exp) exp) ((define? exp) (for-each (lambda (e) (scan e -1)) (define->exp exp))) ;((set!? exp) #f) ;; TODO ?? ((if? exp) (scan (if->condition exp) scope) (scan (if->then exp) scope) (scan (if->else exp) scope)) ((app? exp) (cond ((ast:lambda? (car exp)) (when (not (any prim-call/cont? (cdr exp))) (found (car exp))) ;; We immediately know these lambdas are well-known (let ((formals (ast:lambda-formals->list (car exp)))) (when (and (pair? formals) (pair? (cdr exp)) (ast:lambda? (cadr exp)) ;; Lambda is not well-known when called from a runtime prim ;;(not (any prim-call/cont? (cdr exp))) ) (add-candidate! (cadr exp) (car exp) (car formals))) ) ;; Scan the rest of the args (for-each (lambda (e) (scan e scope)) exp)) (else (for-each (lambda (e) (scan e scope)) (cond ((ref? (car exp)) (let ((cand (hash-table-ref/default scopes (car exp) #f))) (cond ;; Allow candidates to remain if they are just function calls ;; and they are called by the same function that defines them ((and cand (equal? (ast:lambda-id cand) scope) (not (any prim-call/cont? (cdr exp))) ) (cdr exp)) (else exp)))) (else exp)))))) (else #f))) ;(trace:error `(update-lambda-atv! ,syms ,value)) (scan exp -1) ;; Record all well-known lambdas that were found indirectly (for-each (lambda (sym/lamb) (found (cdr sym/lamb) (car sym/lamb))) (hash-table->alist candidates)) ;; Save the candidate list so we can use it to lookup ;; well-known lambda's by var references to them. (set! *well-known-lambda-sym-lookup-tbl* candidates) ) ;; Analysis - validation section ;; FUTURE (?): Does given symbol define a procedure? ;(define (avld:procedure? sym) #f) ;; Predicate: Does given symbol refer to a macro? (define (is-macro? sym) (and-let* ((val (env:lookup sym (macro:get-env) #f))) (or (tagged-list? 'macro val) (Cyc-macro? val)))) ;; Does the given function call pass enough arguments? (define (validate:num-function-args ast) ;;(trace:error `(validate:num-function-args ,(car ast) ,ast ,(env:lookup (car ast) (macro:get-env) #f))) (and-let* (((app? ast)) ;; Prims are checked elsewhere ((not (prim? (car ast)))) ((ref? (car ast))) ;; Do not validate macros ((not (is-macro? (car ast)))) ;; Extract lambda definition (var (adb:get/default (car ast) #f)) (lam* (adbv:assigned-value var)) ;; If assigned value is boxed in a cell, extract it (lam (if (pair? lam*) (car lam*) lam*)) ((ast:lambda? lam)) (formals-type (ast:lambda-formals-type lam)) ((equal? 'args:fixed formals-type)) ;; Could validate fixed-with-varargs, too (expected-argc (length (ast:lambda-args lam))) (argc (- (length ast) 1)) ) (when (not (= argc expected-argc)) (compiler-msg "Compiler Error: ") (compiler-msg (cons (car ast) (cddr ast))) (compiler-error "Expected " (number->string (- expected-argc 1)) ;; One less for continuation " arguments to " (symbol->string (car ast)) " but received " (number->string (- argc 1)))) )) ;; One less for cont ;; Declare a compiler error and quit ;; Preferable to (error) since a stack trace is meaningless here. ;; Ideally want to supplement this with original line number data and such. (define (compiler-error . strs) (display (apply string-append strs) (current-error-port)) (newline (current-error-port)) (exit 1)) ;; Display a compilation message to the user (define (compiler-msg . sexp) (display (apply sexp->string sexp) (current-error-port)) (newline (current-error-port))) ;; Convert given scheme expressions to a string, via (display) ;; TODO: move to util module (define (sexp->string . sexps) (let ((p (open-output-string))) (for-each (lambda (sexp) (apply display (cons sexp (list p)))) sexps) (let ((result (get-output-string p))) (close-port p) result))) ))
false
177c20118dc5a3a71a9cd9a106a0643be404296e
58381f6c0b3def1720ca7a14a7c6f0f350f89537
/Chapter 2/2.2/Ex2.32.scm
794253f6091502db2acf22bf97a1c789f4ade4ef
[]
no_license
yaowenqiang/SICPBook
ef559bcd07301b40d92d8ad698d60923b868f992
c8a0228ebf66d9c1ddc5ef1fcc1d05d8684f090a
refs/heads/master
2020-04-19T04:03:15.888492
2015-11-02T15:35:46
2015-11-02T15:35:46
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
794
scm
Ex2.32.scm
#lang planet neil/sicp ;;helpers (define (append list1 list2) (if (null? list1) list2 (cons (car list1) (append (cdr list1) list2)))) (define (subsets s) (if (null? s) (list nil) (let ((rest (subsets (cdr s)))) (append rest (map (lambda (x) (cons (car s) x)) rest))))) (subsets '(1 2 3)) ;; This is the power expansion of a set and it works as follows ;; The 'rest' is the list of all possible subsets that do not ;; include the car of the set ;; The lambda function is the list of all possible subsets that ;; do include the car of set (achieved by mapping the cons to all of rest ;; The union of these two sets will give the power set, see algorithm on ;; wikipedia - http://en.wikipedia.org/wiki/Power_set
false
9756efe7946a40ffc1126583ef21d154376edc70
4b2aeafb5610b008009b9f4037d42c6e98f8ea73
/7/7-3.scm
5dcbae87ad74132521f257a80c9988fc3d5c7c5b
[]
no_license
mrinalabrol/clrs
cd461d1a04e6278291f6555273d709f48e48de9c
f85a8f0036f0946c9e64dde3259a19acc62b74a1
refs/heads/master
2021-01-17T23:47:45.261326
2010-09-29T00:43:32
2010-09-29T00:43:32
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
251
scm
7-3.scm
(require-extension syntax-case) (require '../7/chapter) (import* chapter-7 stooge-sort!) (let ((vector ;; (vector 13 19 9 5 12 8 7 4 11 2 6 21) (vector 1 2 3))) (stooge-sort! vector 0 (- (vector-length vector) 1)) vector)
false
34c569fb7b6d6e72652d6e6992c950872144044f
b1939ca2ae84f5c82cc3bbbe04b3b75e4b2d421f
/t/t3.scm
b9a98a5cf2181be60eecd0ce6fbacad457baaf72
[]
no_license
orchid-hybrid/scheme-testing-code
d47f2b08087a4130c808043100890d8857b27753
b5afbebb4b6f04f95b18ed39e1bf92658b34db4a
refs/heads/master
2016-09-05T16:36:09.782517
2014-09-20T02:15:37
2014-09-20T02:15:37
24,111,238
3
1
null
null
null
null
UTF-8
Scheme
false
false
57
scm
t3.scm
(let ((a (f)) (b (g)) (c (h))) (go a b c))
false
28a82f7b40c1badb1f5be8375a302bb948b330cc
a6c4b839754b01e1b94a70ec558b631313c9df34
/dot-processing.ss
000b67b654e7bb4e106f4852a6bfc8e7a471c1a7
[]
no_license
dyoo/divascheme
b6a05f625397670b179a51e13d3cd9aac0b2e7d5
f1a8d82989115e0d0714ce8fdbd452487de12535
refs/heads/master
2021-01-17T09:39:14.664809
2008-08-19T01:46:33
2008-08-19T01:46:33
3,205,925
0
1
null
2018-01-22T01:27:19
2012-01-18T04:11:36
Scheme
UTF-8
Scheme
false
false
1,726
ss
dot-processing.ss
(module dot-processing mzscheme (require "semi-read-syntax/semi-read-syntax.ss" (only "utilities.ss" print-mem* make-voice-exn print-time*) (lib "contract.ss") (lib "etc.ss") "rope.ss") (provide/contract [rope-parse-syntax (rope? . -> . (listof syntax?))]) ;; parse-syntax: input-port -> (listof syntax) (define (parse-syntax ip) (print-mem* 'parse-syntax/dot (with-handlers ([(lambda args #t) (lambda (exn) #;(printf "~s~n" exn) (raise (make-voice-exn (format "The parenthesis of the definitions text are not correctly balanced: ~a" (exn-message exn)))))]) (port-count-lines! ip) (semi-read-syntax-list 'voice:action:get-syntax ip)))) (define (parse-syntax/no-specials ip) (print-mem* 'parse-syntax/dot (with-handlers ([(lambda args #t) (lambda (exn) #;(printf "~s~n" exn) (raise (make-voice-exn (format "The parenthesis of the definitions text are not correctly balanced: ~a" (exn-message exn)))))]) (port-count-lines! ip) (semi-read-syntax-list/no-specials 'voice:action:get-syntax ip)))) ;; rope-parse-syntax: rope -> (listof syntax) ;; Parses a rope. ;; FIXME: this function can be potentially expensive. We may need ;; to do something smarter to make this work fast on larger files. (define (rope-parse-syntax a-rope) (cond [(rope-has-special? a-rope) (parse-syntax (open-input-rope a-rope))] [else (parse-syntax/no-specials (open-input-rope a-rope))])))
false
e9a895d93d9d04b72f8c2b3b026f9ce5fb0e616a
e430d3d93c2156fafff0cf3a4fd6da4d42b98225
/sublevel.scm
ba1b40d9c46e4ad3efd1b43105545c326448b0ec
[]
no_license
caolan/chicken-sublevel
336e449817a2bb1bae24573df3534c7abbcda652
7dea6da2d733da66a2ff339f940832ddda249b7d
refs/heads/master
2023-09-01T10:44:49.915334
2016-07-04T19:04:47
2016-07-04T19:04:47
22,309,255
1
0
null
null
null
null
UTF-8
Scheme
false
false
5,909
scm
sublevel.scm
(module sublevel ;; exports (sublevel sublevel-delimiter sublevel-split-key expand-sublevels multilevel-expand multilevel-batch) (import scheme chicken) (use level interfaces srfi-1 srfi-13 lazy-seq data-structures) (define sublevel-delimiter "\x00") ;; nul character (define (key->string prefix key) (string-join (append prefix (if (list? key) key (list key))) sublevel-delimiter)) ;; converts the key part of an operation to a string (define (convert-key prefix op) (if (eq? (length op) 3) (list (car op) (key->string prefix (cadr op)) (caddr op)) (list (car op) (key->string prefix (cadr op))))) (define (sublevel-split-key key) (string-split key sublevel-delimiter)) (define (key->list key) (if (list? key) key (sublevel-split-key key))) (define (remove-prefix prefix key) (define (without-prefix a b) (if (null? a) (string-join b sublevel-delimiter) (if (string=? (car a) (car b)) (without-prefix (cdr a) (cdr b)) key))) (without-prefix prefix (key->list key))) (define (make-startkey prefix start #!key (reverse #f)) (if (null? prefix) start (if start (if reverse (string-join (append prefix (if start (list start) '())) sublevel-delimiter) (string-join (append prefix (if start (list start) '())) sublevel-delimiter)) (if reverse (string-append (string-join prefix sublevel-delimiter) sublevel-delimiter "\xff") (string-append (string-join prefix sublevel-delimiter) sublevel-delimiter))))) (define (make-endkey prefix end #!key (reverse #f)) (if (null? prefix) end (if end (if reverse (string-join (append prefix (if end (list end) '())) sublevel-delimiter) (string-join (append prefix (if end (list end) '())) sublevel-delimiter)) (if reverse (string-append (string-join prefix sublevel-delimiter) sublevel-delimiter) (string-append (string-join prefix sublevel-delimiter) sublevel-delimiter "\xff"))))) (define-record sublevel prefix db) (define sublevel-implementation (implementation level-api (define (level-get resource key) (db-get (sublevel-db resource) (key->string (sublevel-prefix resource) key))) (define (level-get/default resource key default) (db-get/default (sublevel-db resource) (key->string (sublevel-prefix resource) key) default)) (define (level-put resource key value #!key (sync #f)) (db-put (sublevel-db resource) (key->string (sublevel-prefix resource) key) value sync: sync)) (define (level-delete resource key #!key (sync #f)) (db-delete (sublevel-db resource) (key->string (sublevel-prefix resource) key) sync: sync)) (define (level-batch resource ops #!key (sync #f)) (db-batch (sublevel-db resource) (map (cut convert-key (sublevel-prefix resource) <>) ops) sync: sync)) (define (level-keys resource #!key start end limit reverse fillcache) (let* ((prefix (sublevel-prefix resource)) (start2 (make-startkey prefix start reverse: reverse)) (end2 (make-endkey prefix end reverse: reverse))) (lazy-map (lambda (x) (remove-prefix prefix (key->list x))) (db-keys (sublevel-db resource) start: start2 end: end2 limit: limit reverse: reverse fillcache: fillcache)))) (define (level-values resource #!key start end limit reverse fillcache) (let* ((prefix (sublevel-prefix resource)) (start2 (make-startkey prefix start reverse: reverse)) (end2 (make-endkey prefix end reverse: reverse))) (db-values (sublevel-db resource) start: start2 end: end2 limit: limit reverse: reverse fillcache: fillcache))) (define (level-pairs resource #!key start end limit reverse fillcache) (let* ((prefix (sublevel-prefix resource)) (start2 (make-startkey prefix start reverse: reverse)) (end2 (make-endkey prefix end reverse: reverse))) (lazy-map (lambda (x) (let ((k (key->list (car x))) (v (cdr x))) (cons (remove-prefix prefix k) v))) (db-pairs (sublevel-db resource) start: start2 end: end2 limit: limit reverse: reverse fillcache: fillcache)))) )) (define (sublevel db prefix) (make-level 'sublevel sublevel-implementation (make-sublevel prefix db))) (define (full-prefix root db) (cond ((eq? root db) '()) ((level? db) (full-prefix root (level-resource db))) ((sublevel? db) (append (full-prefix root (sublevel-db db)) (sublevel-prefix db))) (else '()))) (define (expand-sublevels root db ops) (let ((prefix (full-prefix root db))) (map (lambda (op) (let ((type (car op)) (key (key->string prefix (cadr op))) (rest (cddr op))) (cons type (cons key rest)))) ops))) (define-syntax multilevel-expand (syntax-rules () ((_ db) '()) ((_ db (s1 o1) (s2 o2) ...) (append (expand-sublevels db s1 o1) (multilevel-expand db (s2 o2) ...))))) (define-syntax multilevel-batch (syntax-rules () ((_ db) '()) ((_ db (s1 o1) (s2 o2) ...) (db-batch db (multilevel-expand db (s1 o1) (s2 o2) ...))))) )
true
27e2d8f56f0349b419ec4c31bd12b9bdf3aba97b
5355071004ad420028a218457c14cb8f7aa52fe4
/2.1/e-2.2.scm
5fc485b5895f06c00a64970b10818a4176190f17
[]
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,871
scm
e-2.2.scm
; Exercise 2.2. ; ; Consider the problem of representing line segments in a plane. Each segment is ; represented as a pair of points: a starting point and an ending point. Define a constructor ; make-segment and selectors start-segment and end-segment that define the representation of ; segments in terms of points. Furthermore, a point can be represented as a pair of numbers: the x ; coordinate and the y coordinate. Accordingly, specify a constructor make-point and selectors ; x-point and y-point that define this representation. Finally, using your selectors and constructors, ; define a procedure midpoint-segment that takes a line segment as argument and returns its midpoint ; (the point whose coordinates are the average of the coordinates of the endpoints). To try your procedures, ; you'll need a way to print points: ; needing average procedure (load "../common.scm") (define (print-point p) (display "(") (display (x-point p)) (display ",") (display (y-point p)) (display ")") (newline)) ; In the terms of wishful thinking we start by designing higher levels ; of abstraction first, so we do not deal with details of implementation ; yet and just implement them when needed. (define (make-segment sp ep) (cons sp ep)) (define (start-segment s) (car s)) (define (end-segment s) (cdr s)) ; Now we need points in fact (define (make-point x y) (cons x y)) (define (x-point p) (car p)) (define (y-point p) (cdr p)) (define start (make-point 0 0)) (define end (make-point 2 2)) ; (print-point start) ; (print-point end) ; now we calculate midpoint which itself is a point with calculated ; coordinates. It receives segment as param (define (mid-point s) (make-point (average (x-point (car s)) (x-point (cdr s))) (average (y-point (car s)) (y-point (cdr s))))) ; (print-point (mid-point (make-segment start end)))
false
3ec327f26be3d990e5e7435c11890a75f7fea617
4b66fbd639d5d882b2d5c1c3c851abc7e8123690
/seasoned-schemer/take-cover.scm
e7e1d8be48fe2174f9eed3703ff164e660b21cf0
[]
no_license
jwhiteman/FP
39531fa32a590ec79da75aa893f8dccecd425cdd
2b9681ccb9030b98eab5efe0d57c33b9d38737c9
refs/heads/master
2021-06-09T12:10:18.893253
2016-12-16T15:43:19
2016-12-16T15:43:19
191,805
1
0
null
null
null
null
UTF-8
Scheme
false
false
6,262
scm
take-cover.scm
(define atom? (lambda (x) (not (or (pair? x) (null? x))))) (define multirember (lambda (a lat) (cond ((null? lat) '()) ((eq? (car lat) a) (multirember a (cdr lat))) (else (cons (car lat) (multirember a (cdr lat))))))) ;; TEST ; (multirember 'tuna '(shrimp salad tuna salad and tuna)) (define multirember (lambda (a lat) ((letrec ((mr (lambda (lat) (cond ((null? lat) '()) ((eq? (car lat) a) (mr (cdr lat))) (else (cons (car lat) (mr (cdr lat)))))))) mr) lat))) ;; TEST ; (multirember 'tuna '(shrimp salad tuna salad and tuna)) (define multirember-f (lambda (test?) (lambda (a lat) (cond ((null? lat)'()) ((test? (car lat) a) ((multirember-f test?) a (cdr lat))) (else (cons (car lat) ((multirember-f test?) a (cdr lat)))))))) ;; TEST ; ((multirember-f eq?) 'c '(a c d c)) (define multirember-f (lambda (test?) (letrec ((m-f (lambda (a lat) (cond ((null? lat) '()) ((test? (car lat) a) (m-f a (cdr lat))) (else (cons (car lat) (m-f a (cdr lat)))))))) m-f))) ;; TEST ;; ((multirember-f eq?) 'c '(a c d c)) (define member? (lambda (a lat) (cond ((null? lat) #f) (else (or (eq? (car lat) a) (member a (cdr lat))))))) ;; TEST ; (member? 'd '(a c d c)) (define member? (lambda (a lat) (letrec ((M (lambda (lat) (cond ((null? lat) #f) (else (or (eq? (car lat) a) (M (cdr lat)))))))) (M lat)))) ;; TEST ;(member? 'd '(a c d c)) ;(member? 'x '(a c d c)) (define union (lambda (set1 set2) (cond ((null? set1) set2) ((member? (car set1) set2) (union (cdr set1) set2)) (else (cons (car set1) (union (cdr set1) set2)))))) ;; TEST ;; (union '(tomatoes and macaroni casserole) '(macaroni and cheese)) (define union (lambda (set1 set2) (letrec ((U (lambda (set1) (cond ((null? set1) set2) ((member? (car set1) set2) (U (cdr set1))) (else (cons (car set1) (U (cdr set1)))))))) (U set1)))) ;; TEST ; (union '(tomatoes and macaroni casserole) '(macaroni and cheese)) (define union (lambda (set1 set2) (letrec ((U (lambda (set1) (cond ((null? set1) set2) ((M? (car set1) set2) (U (cdr set1))) (else (cons (car set1) (U (cdr set1))))))) (M? (lambda (a lat) (cond ((null? lat) #f) (else (or (eq? (car lat) a) (M? a (cdr lat)))))))) (U set1)))) ;; TEST ; (union '(tomatoes and macaroni casserole) '(macaroni and cheese)) (define union (lambda (set1 set2) (letrec ((U (lambda (set1) (cond ((null? set1) set2) ((M? (car set1) set2) (U (cdr set1))) (else (cons (car set1) (U (cdr set1))))))) (M? (lambda (a lat) (letrec ((m? (lambda (lat) (cond ((null? lat) #f) (else (or (eq? (car lat) a) (m? (cdr lat)))))))) (m? lat))))) (U set1)))) ;; TEST ; (union '(tomatoes and macaroni casserole) '(macaroni and cheese)) (define two-in-a-row? (lambda (lat) (cond ((null? lat) #f) (else (letrec ((T (lambda (pre lis) (cond ((null? lis) #f) (else (or (eq? (car lis) pre) (T (car lis) (cdr lis)))))))) (T (car lat) (cdr lat))))))) (define two-in-a-row? (lambda (lat) (letrec ((W (lambda (pre lat) (cond ((null? lat) #f) (else (or (eq? (car lat) pre) (W (car lat) (cdr lat)))))))) (cond ((null? lat) #f) (else (W (car lat) (cdr lat))))))) (define two-in-a-row? (letrec ((W (lambda (a lat) (cond ((null? lat) #f) (else (or (eq? (car lat) a) (W (car lat) (cdr lat)))))))) (lambda (lat) (cond ((null? lat) #f) (else (W (car lat) (cdr lat))))))) ;; TEST ;; (two-in-a-row? '()) ;; (two-in-a-row? '(a)) ;; (two-in-a-row? '(a b c d e)) ;; (two-in-a-row? '(a b c d d e)) (define sum-of-prefixes (lambda (tup) (letrec ((S (lambda (sonssf tup) (cond ((null? tup) '()) (else (cons (+ sonssf (car tup)) (S (+ sonssf (car tup)) (cdr tup)))))))) (S 0 tup)))) ;; TEST ; (sum-of-prefixes '()) ; (sum-of-prefixes '(1)) ; (sum-of-prefixes '(1 1 1 1 1)) ; (sum-of-prefixes '(1 2 3 4 5)) (define scramble (lambda (tup) (letrec ((P (lambda (n lat) (cond ((= 1 n)(car lat)) (else (P (sub1 n) (cdr lat)))))) (S (lambda (pre tup) (cond ((null? tup) '()) (else (cons (P (car tup) (cons (car tup) pre)) (S (cons (car tup) pre) (cdr tup)))))))) (S '() tup)))) ;; TEST ; (scramble '(1 2 3 4 5 6 7 8 9 10)) ; (scramble '(1 1 1 1 1 1 1 1 9 2))
false
5dcdab4903017be87787ac507d61b585f9013923
ece1c4300b543df96cd22f63f55c09143989549c
/Chapter1/Exercise 1.29.scm
a135e0d6451e021fe5c1e6d763354820de3d678f
[]
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,628
scm
Exercise 1.29.scm
; Exercise 1.29: Simpson’s Rule is a more accurate method of numerical integration than the method illustrated above. Using Simpson’s Rule, the integral of a function ff between aa and bb is approximated as ; h3(y0+4y1+2y2+4y3+2y4+⋯+2yn−2+4yn−1+yn), ; h3(y0+4y1+2y2+4y3+2y4+⋯+2yn−2+4yn−1+yn), ; where h=(b−a)/nh=(b−a)/n, for some even integer nn, and yk=f(a+kh)yk=f(a+kh). (Increasing nn increases the accuracy of the approximation.) Define a procedure that takes as arguments ff, aa, bb, and nn and returns the value of the integral, computed using Simpson’s Rule. Use your procedure to integrate cube between 0 and 1 (with n=100n=100 and n=1000n=1000), and compare the results to those of the integral procedure shown above. #lang planet neil/sicp (define (sum term a next b) (if (> a b) 0 (+ (term a) (sum term (next a) next b)))) (define (cube x) (* x x x) ) (define (integral f a b dx) (define (add-dx x) (+ x dx)) (* (sum f (+ a (/ dx 2.0)) add-dx b) dx)) (define (integralEnhance f a b n) (define h (/ (- b a) n)) (define (get-k x) (/ (- x a) h)) (define (get-ratio k) (cond ((= (remainder k n) 0) 1) ((= (remainder k 2) 0) 2) (else 4) )) (define (fx x) (* (/ h 3) (get-ratio (get-k x)) (f x))) (define (get-next x) (+ x h)) (sum fx a get-next b) ) (integral cube 0 1 0.01) (integralEnhance cube 0 1 100) (integral cube 0 1 0.001) (integralEnhance cube 0 1 1000) (integralEnhance cube 0 1 2) 0.24998750000000042 1/4 0.249999875000001 1/4 1/4
false
97899ee2bfac9bb58cbdc2487630cf3fa74edd66
86092887e6e28ebc92875339a38271319a87ea0d
/Ch3/3_80.scm
56d5d9e41bb485e1c24f758760628b9f78c2d0ba
[]
no_license
a2lin/sicp
5637a172ae15cd1f27ffcfba79d460329ec52730
eeb8df9188f2a32f49695074a81a2c684fe6e0a1
refs/heads/master
2021-01-16T23:55:38.885463
2016-12-25T07:52:07
2016-12-25T07:52:07
57,107,602
1
0
null
null
null
null
UTF-8
Scheme
false
false
1,084
scm
3_80.scm
(load "stream_lib.scm") (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) ; |-------------[ 1/L ] <------- ; | | ; | -->[integral] |---> Vc ; | | ^--Vc0 ; | | ; | |-[scale: -1/C]<----| ; |-| diL | ; |-> [Add] --------->[integral]-|---------> iL ; |-| ^--iL0 | ; | | ; |--------------[scale: -R/L]<----| (define (RLC R L C Vc0 iL0 dt) (define iL (integral (delay (add-streams (scale-stream Vc (/ 1 L)) (scale-stream iL (/ (* -1 R) L))) ) iL0 dt) ) (define Vc (integral (delay (scale-stream iL (/ -1 C))) Vc0 dt)) (define state (stream-map cons iL Vc)) state ) (take (RLC 1000 1 0.001 100 1000 0.001) 7)
false
2a3fdb9399200f01c0a2c37c3a6904621c7f5a64
2c26fa75726aa0465bd4a024d9d19a0e75768794
/tests/path-components.scm
20d547f6927eaa2e17929794462f1c3a7bcd9cca
[ "BSD-2-Clause" ]
permissive
shirok/Gauche-makiki
20129c8b886be2f09c356aff78a6a5ca65299c90
afdfd17c3966a221a5cd6738ed4c8e634a8ec9d6
refs/heads/master
2023-08-17T10:29:22.791262
2023-08-17T04:08:03
2023-08-17T04:08:03
642,571
28
8
null
2019-01-16T23:59:14
2010-05-02T13:57:40
Scheme
UTF-8
Scheme
false
false
1,840
scm
path-components.scm
(use gauche.parseopt) (use makiki) (define (main args) (let-args (cdr args) ([p "port=i"]) (start-http-server :access-log #t :error-log #t :port p)) 0) (define-http-handler ("foo" "bar") (^[req app] (respond/ok req "foo bar"))) (define-http-handler ("foo" var) (^[req app] (respond/ok req #"foo var=~(request-path-ref req 'var)"))) (define-http-handler ("foo" var "bar") (^[req app] (respond/ok req #"foo var=~(request-path-ref req 'var) bar"))) (define-http-handler (POST) ("boo" x) (^[req app] (respond/ok req #"POST:boo x=~(request-path-ref req 'x)"))) (define-http-handler (GET) ("boo" x) (^[req app] (respond/ok req #"GET:boo x=~(request-path-ref req 'x)"))) (define-http-handler ("hoo" (#/^\d+-(\d+)$/ x y)) (^[req app] (respond/ok req #"hoo x=~(request-path-ref req 'x) y=~(request-path-ref req 'y)"))) (define-http-handler ("hoo" z) (^[req app] (respond/ok req #"hoo z=~(request-path-ref req 'z)"))) (define-http-handler ("int" (path:int n)) (^[req app] (respond/ok req #"int n=~(request-path-ref req 'n)"))) (define-http-handler ("int" x) (^[req app] (respond/ok req #"int x=~(request-path-ref req 'x)"))) (define-http-handler ("hex" (path:hex n)) (^[req app] (respond/ok req #"hex n=~(request-path-ref req 'n)"))) (define-http-handler ("hex" x) (^[req app] (respond/ok req #"hex x=~(request-path-ref req 'x)"))) (define-http-handler ("sym" ((path:symbol #/^\w+$/) y)) (^[req app] (respond/ok req #"sym y=~(request-path-ref req 'y)"))) (define-http-handler ("sym" _) (^[req app] (respond/ok req #"sym #f"))) (cond-expand [(library rfc.uuid) (use rfc.uuid) (define-http-handler ("uuid" (path:uuid u)) (^[req app] (respond/ok req #"uuid u=~(uuid->string (request-path-ref req 'u))"))) (define-http-handler ("uuid" _) (^[req app] (respond/ok req #"uuid #f")))] [else])
false
0bdc44270c35efca934decb1433d4330756ee5fd
4a1ff5a0f674ff41bd384301ab82b3197f5ca0c8
/problems/0057/main.scm
8f1c944f96d52571d3a2f93ebf63d64b0cc10167
[]
no_license
MiyamonY/yukicoder
e0a323d68c4d3b41bdb42fb3ed6ab105619ca7e9
1bb8882ac76cc302428ab0417f90cfa94f7380c8
refs/heads/master
2020-05-09T12:13:31.627382
2019-10-06T17:01:45
2019-10-06T17:01:45
181,105,911
0
0
null
null
null
null
UTF-8
Scheme
false
false
54
scm
main.scm
(let ((n (read))) (print (/. (+ (* n) (* n 6)) 2)))
false
3c1d8dee54ba29b15c2ad8b1f931abd57fc9502a
893a879c6b61735ebbd213fbac7e916fcb77b341
/notes/callcc-interpreter.ss
367253d240769860f15ba37cc9120880f96c5575
[]
no_license
trittimo/PLC-Assignments
e5353c9276e93bca711b684c955d6c1df7cc6c82
666c2521f1bfe1896281e06f0da9a7ca315579bb
refs/heads/master
2016-08-31T04:52:26.143152
2016-06-05T01:00:18
2016-06-05T01:00:18
54,284,286
0
0
null
null
null
null
UTF-8
Scheme
false
false
556
ss
callcc-interpreter.ss
(define-datatype proc-val proc-val? (prim-proc (name symbol?)) (closure (params (list-of symbol?)) (varargs ...) (bodies (list-of expression?)) (env environment?)) (c-proc (k continuation?))) (define (apply-prim-proc prim-proc-name vals k) (case prim-proc-name ((call/cc) (apply-proc (car vals) (list (c-proc k)) k)))) (define (apply-proc proc args k) (cases proc-val proc (c-proc (k) (apply-k k (car args))) (prim-proc ...) (closure ...))) ; call/cc has to be added to list of procs ; should know how this works enough for final exam
false
af27c0058719ec758e49f93d2a6f0682e3be5a90
2d868c9428b8f4772d2ede375a3492b3b6885e1d
/Metacircular Evaluator, Part 1/4.2.scm
c70022c19afbbb3d1117c658132591c60b22b847
[]
no_license
transducer/sicp
2428223945da87836fa2a82c02d965061717ae95
2cec377aa7805edfd7760c643c14127e344ee962
refs/heads/master
2021-06-06T20:06:47.156461
2016-09-16T22:05:02
2016-09-16T22:05:02
25,219,798
1
0
null
null
null
null
UTF-8
Scheme
false
false
1,249
scm
4.2.scm
#lang scheme ;; Louis Reasoner plans to reorder the cond clauses in eval so that the ;; clause for procedure applications appears before the clause for ;; assignments. He argues that this will make the interpreter more efficient: ;; Since programs usually contain more applications than assignments, ;; definitions, and so on, his modified eval will usually check fewer clauses ;; than the original eval before identifying the type of an expression. ;; a. What is wrong with Louis's plan? (Hint: What will Louis's evaluator ;; do with the expression (define x 3)?) ; Expressions like (define x 3) will be regarded as an application, ; while they are an assignment. ;; b. Louis is upset that his plan didn't work. He is willing to go to any ;; lengths to make his evaluator recognize procedure applications before it ;; checks for most other kinds of expressions. Help him by changing the ;; syntax of the evaluated language so that procedure applications start ;; with call. For example, instead of (factorial 3) we will now have to ;; write (call factorial 3) and instead of (+ 1 2) we will have to write ;; (call + 1 2). (define (eval exp env) (cond ((eq? (car exp) 'call) (apply (cadr exp) (cddr exp)))) ; ... )
false
08d45e9b8a48b05a616c27cab006d1308a941648
12fc725f8273ebfd9ece9ec19af748036823f495
/daemon/src/sa_sensor_list_make.ss
abdd9def93d69569883c1e24e00501593c0e7a5d
[]
no_license
contextlogger/contextlogger2
538e80c120f206553c4c88c5fc51546ae848785e
8af400c3da088f25fd1420dd63889aff5feb1102
refs/heads/master
2020-05-05T05:03:47.896638
2011-10-05T23:50:14
2011-10-05T23:50:14
1,675,623
1
0
null
null
null
null
UTF-8
Scheme
false
false
23,014
ss
sa_sensor_list_make.ss
#lang scheme ;; Here we deal with cross-cutting concerns related to our sensor ;; array, by generating some or all of the cross-cutting code. Join ;; points are defined simply as C function or macro invocations. (require (lib "usual-4.ss" "common")) (require (lib "ast-util.scm" "wg")) (require (lib "file-util.scm" "wg")) (require (lib "compact.scm" "wg")) (require (lib "cxx-syntax.ss" "wg")) (require (lib "settings.scm" "wg")) ;; for in-c-mode (require (lib "string-util.scm" "wg")) (require (lib "local-util.scm" "codegen")) (require "sa_sensor_list_dsl.ss") (define* (generate sensor-spec dump? gen?) (define sensor-list (begin (unless (sensor-list? sensor-spec) (error "sensor list syntax error")) (cdr sensor-spec))) (define (get-sensor-list) sensor-list) (define active-sensors (filter (lambda (sensor) (not (fget-opt-nlist-elem-1 sensor 'inactive))) sensor-list)) ;;(pretty-nl sensors) (exit) ;;(define program-name (find-system-path 'run-file)) ;;(write-nl program-name) ;;(write-nl (path-drop-extension (path-basename program-name) ".scm")) (define (capture-output f) (let ((output (open-output-string))) (parameterize ((current-output-port output)) (f)) (get-output-string output))) (define (get-sensor-name sensor) (fget-reqd-nlist-elem-1 sensor 'name)) (define (get-sensor-cpp-condition sensor) (fget-opt-nlist-elem-1 sensor 'cpp-condition)) (define (for-each-statement f) (for-each (lambda (sensor) (let* ((sensor-name (fget-reqd-nlist-elem-1 sensor 'name)) (cpp-condition (fget-opt-nlist-elem-1 sensor 'cpp-condition)) (stmt-list (fget-opt-nlist-elem-1up-e sensor 'sql-statements))) (for-each (lambda (stmt) (let* ((stmt-name (if (string? stmt) "" (first stmt))) (stmt-sql (if (string? stmt) stmt (second stmt)))) (f sensor-name cpp-condition stmt-name stmt-sql))) stmt-list))) (get-sensor-list))) (define (with-cpp-condition-harness cpp-condition f) (if cpp-condition (begin (display "#if ") (display-nl cpp-condition) (f) (display-nl "#endif")) (f))) (define create-tables-sql-def (capture-output (thunk (display-nl "static const char create_tables_sql[] =") (write-nl "begin transaction;") (for-each (lambda (sensor) ;; During database initialization, we do output code for ;; creating tables for all the sensors, even those ones not ;; in the particular build, as this will make it easier to ;; change the configuration. (let* ((cpp-condition #f) ;;(fget-opt-nlist-elem-1 sensor 'cpp-condition) (schema (fget-opt-nlist-elem-1up-e sensor 'sql-schema)) (write-schema (thunk (for-each write-nl schema)))) (when schema (if cpp-condition (begin (display "#if ") (display-nl cpp-condition) (write-schema) (display-nl "#endif")) (write-schema))))) (get-sensor-list)) (write-nl "commit;") (display "\"\";")))) (define prepared-statements-def (capture-output (thunk (display-nl "struct _PreparedStmts {") (for-each (lambda (sensor) (let* ((sensor-name (fget-reqd-nlist-elem-1 sensor 'name)) (cpp-condition (fget-opt-nlist-elem-1 sensor 'cpp-condition)) (stmt-list (fget-opt-nlist-elem-1up-e sensor 'sql-statements)) (write-them (thunk (for-each (lambda (stmt) (display-nl (format "sqlite3_stmt* ~a~aStmt;" sensor-name (if (string? stmt) "" (first stmt))))) stmt-list)))) (when stmt-list (if cpp-condition (begin (display "#if ") (display-nl cpp-condition) (write-them) (display-nl "#endif")) (write-them))))) (get-sensor-list)) (display-nl "};") (display "typedef struct _PreparedStmts PreparedStmts;")))) (define sql-statement-preparation (capture-output (thunk (for-each-statement (lambda (sensor-name cpp-condition stmt-name stmt-sql) (alet write-them (thunk (display-nl (format "if (sqlite_prepare(self->db, ~s, -1, &(self->stmts.~a~aStmt), 0)) { goto fail; }" stmt-sql sensor-name stmt-name))) (with-cpp-condition-harness cpp-condition write-them)))) (display-nl "return TRUE;") (display-nl "fail:") (display-nl "if (error) *error = gx_error_new(domain_cl2app, code_database_state_init, \"error preparing statements for database '%s': %s (%d)\", LOGDB_FILE, sqlite3_errmsg(self->db), sqlite3_errcode(self->db));") (display "return FALSE;")))) (define sql-statement-destruction (capture-output (thunk (for-each-statement (lambda (sensor-name cpp-condition stmt-name stmt-sql) (alet write-them (thunk (display-nl (format "if (self->stmts.~a~aStmt) { sqlite3_finalize(self->stmts.~a~aStmt); self->stmts.~a~aStmt = NULL; }" sensor-name stmt-name sensor-name stmt-name sensor-name stmt-name))) (with-cpp-condition-harness cpp-condition write-them)))) (display "return;")))) (define (ast-with-cpp-condition-harness cpp-condition ast) (if cpp-condition ;; Some trickery here, relying on ordering being preserved. (sc (cpp-if cpp-condition) ast (cpp-end) ) ast)) (define (bind-func-by-type type) (case-eq type ('int 'sqlite3_bind_int) ('int?-neqz 'sqlite3_bind_int_neqz) ('int?-ltez 'sqlite3_bind_int_ltez) ('int?-gtez 'sqlite3_bind_int_gtez) ('int64 'sqlite3_bind_int64) ('text 'sqlite3_bind_text) ('text? 'sqlite3_bind_text_or_null) ('double 'sqlite3_bind_double) (else (error "bind-func-by-type unsupported type" type)))) ;; When using 'static rather than 'transient, the string "has to ;; remain valid during all subsequent calls to sqlite3_step() on the ;; statement handle. Or until you bind a different value to the same ;; parameter." ;; ;; Below we always bind all the values and then proceed to step. If ;; at any point we fail, we will not step before binding all the ;; values (next time). So should be safe. (define (maybe-dispose type dispose) (if dispose (string-append ", " (case-eq dispose ('static "SQLITE_STATIC") ('transient "SQLITE_TRANSIENT") (else dispose))) "")) (define log-db-insert-functions (sc-list (compact (map (lambda (sensor) (aand* api (fget-opt-nlist-elem sensor 'log-insert-api) (let* ((sensor-name (fget-reqd-nlist-elem-1 sensor 'name)) (cpp-condition (fget-opt-nlist-elem-1 sensor 'cpp-condition)) (func-name (format "log_db_log_~a" sensor-name)) (specific-args (fget-opt-nlist-elem-1up-e api 'args)) (stmt-id (fget-opt-nlist-elem-1 api 'statement)) (stmt-var (format "self->stmts.~a~aStmt" sensor-name (or stmt-id ""))) (binding-list (fget-opt-nlist-elem-1up-e api 'bindings)) (body-text (capture-output (thunk (display-nl "time_t now = time(NULL); if (now == -1) { goto posix_fail; }") (display-nl (format "if (sqlite3_bind_int(~a, 1, now)) { goto sql_fail; }" stmt-var)) (for-each (lambda (binding) (let* ((index (fget-reqd-nlist-elem-1 binding 'index)) (type (fget-reqd-nlist-elem-1 binding 'type)) (value (fget-reqd-nlist-elem-1 binding 'value)) (dispose (fget-opt-nlist-elem-1 binding 'dispose)) (func-name (bind-func-by-type type))) (display-nl (format "if (~a(~a, ~a, ~a~a)) { goto sql_fail; }" func-name stmt-var index value (maybe-dispose type dispose))))) binding-list) (display-nl (format "if (sqlite3_step(~a) != SQLITE_DONE) { goto sql_fail; }" stmt-var)) (display-nl (format "if (sqlite3_reset(~a)) goto sql_fail;" stmt-var)) (display-nl "return TRUE;") (display-nl "posix_fail: if (error) *error = gx_error_new(domain_cl2app, code_time_query, \"failed to access current time: %s (%d)\", strerror(errno), errno); return FALSE;") (display (format "sql_fail: if (error) *error = gx_error_new(domain_cl2app, code_database_command, \"failed to log ~a event: %s (%d)\", sqlite3_errmsg(self->db), sqlite3_errcode(self->db)); return FALSE;" sensor-name)) ))) (func-decl (func (name func-name) cexport (returns (type 'gboolean)) (apply args (append (list (arg (name 'self) (type (ptr-to 'LogDb)))) specific-args (list (arg (name 'error) (type (ptr-to (ptr-to 'GError))))))) (block (cxx-line body-text))))) (ast-with-cpp-condition-harness cpp-condition func-decl)))) (get-sensor-list))))) (define program-1 (cunit (basename "sa_sensor_list_log_db") (includes (system-include "glib.h") (local-include "application_config.h") (local-include "ld_log_db.h") (local-include "sqlite_cl2.h") (local-include "common/utilities.h") ) (body (cxx-internal-declarations "#include \"ld_private.h\"" ) (cxx-internal-declarations "#include \"ac_app_context.h\"" "#include <errno.h>" "#include \"common/logging.h\"" "#include \"common/assertions.h\"" "#include \"common/threading.h\"" "#include \"common/error_list.h\"" ) (cxx-exported-declarations "G_BEGIN_DECLS") ;;(cxx-exported-declarations "struct LogDb;") (cxx-internal-declarations create-tables-sql-def) (func (name "get_create_tables_sql") cexport ;;(verbatim-modifier "EXTERN_C") (returns (type (ptr-to (cconst 'char)))) (block (return 'create_tables_sql))) (cxx-exported-declarations prepared-statements-def) (func (name "prepare_sql_statements") cexport ;;(verbatim-modifier "EXTERN_C") (returns (type 'gboolean)) (args (arg (name 'self) (type (ptr-to 'LogDb))) (arg (name 'error) (type (ptr-to (ptr-to 'GError))))) (block (cxx-line sql-statement-preparation) )) (func (name "destroy_sql_statements") cexport ;;(verbatim-modifier "EXTERN_C") (args (arg (name 'self) (type (ptr-to 'LogDb)))) (block (cxx-line sql-statement-destruction) )) log-db-insert-functions (cxx-exported-declarations "G_END_DECLS") ))) ;; end program-1 (define (symbol-upcase s) (string->symbol (string-upcase (symbol->string s)))) (define (for-each/sep elem-f sep-f lst) (unless (null? lst) (elem-f (car lst)) (for-each (lambda (x) (sep-f) (elem-f x)) (cdr lst)))) (define (make-supported-sensor-definitions) (define (g) (map (lambda (sensor) (let* ((sensor-name (fget-reqd-nlist-elem-1 sensor 'name)) (cpp-condition (fget-opt-nlist-elem-1 sensor 'cpp-condition))) (capture-output (thunk (display-nl (format "#if ~a" cpp-condition)) (display-nl (format "#define SENSOR_~a_IS_SUPPORTED 1" (symbol-upcase sensor-name))) (display-nl (format "#define WHEN_SENSOR_~a_SUPPORTED_BLOCK(x) { x ; }" (symbol-upcase sensor-name))) (display-nl (format "#define WHEN_SENSOR_~a_SUPPORTED_NOTHING(x) x" (symbol-upcase sensor-name))) (display-nl "#else") (display-nl (format "#define SENSOR_~a_IS_SUPPORTED 0" (symbol-upcase sensor-name))) (display-nl (format "#define WHEN_SENSOR_~a_SUPPORTED_BLOCK(x) {}" (symbol-upcase sensor-name))) (display-nl (format "#define WHEN_SENSOR_~a_SUPPORTED_NOTHING(x) " (symbol-upcase sensor-name))) (display "#endif"))))) active-sensors)) (define (f) (display "#define RETURN_WHETHER_NAMED_SENSOR_IS_SUPPORTED(name) {") (for-each (lambda (sensor) (let* ((sensor-name (fget-reqd-nlist-elem-1 sensor 'name))) (display-nl " \\") (display " if (strcmp(name,") (write (symbol->string sensor-name)) (display ") == 0) { ") (display (format "return SENSOR_~a_IS_SUPPORTED;" (symbol-upcase sensor-name))) (display " }"))) active-sensors) (display-nl " \\") (display "}")) (define (h) (display-nl (format "#define NUM_ALL_SENSORS ~a" (length active-sensors))) (display "#define NUM_SUPPORTED_SENSORS (0") (for-each (lambda (sensor) (let* ((sensor-name (fget-reqd-nlist-elem-1 sensor 'name))) (display " + ") (display (format "SENSOR_~a_IS_SUPPORTED" (symbol-upcase sensor-name))))) active-sensors) (display ")")) (define (hh) (display "#define ALL_SENSOR_NAMES_LITERAL_LIST {") (for-each/sep (lambda (sensor) (let* ((sensor-name (fget-reqd-nlist-elem-1 sensor 'name))) (write (symbol->string sensor-name)))) (thunk (display ", ")) active-sensors) (display ", NULL}")) (sc (apply cxx-exported-declarations (g)) (cxx-exported-declarations (capture-output h)) (cxx-exported-declarations (capture-output hh)) (cxx-exported-declarations (capture-output f)) )) (define (make-stop-named-sensor) (define (f) (display "#define STOP_NAMED_SENSOR(name) {") (for-each (lambda (sensor) (let* ((sensor-name (fget-reqd-nlist-elem-1 sensor 'name)) (upcase-name (symbol-upcase sensor-name))) (display-nl " \\") (display (format " WHEN_SENSOR_~a_SUPPORTED_NOTHING({" (symbol-upcase sensor-name))) (display "if (strcmp(name,") (write (symbol->string sensor-name)) (display ") == 0) { ") (display (format "if (SENSOR_~a_IS_RUNNING) { SENSOR_~a_STOP; } return;" upcase-name upcase-name)) (display " }") ;; end if (display "})") ;; end when supported )) active-sensors) (display-nl " \\") (display "}")) (cxx-exported-declarations (capture-output f))) (define (make-start-named-sensor) (define (f) (display "#define START_NAMED_SENSOR_OR_FAIL(name) {") (for-each (lambda (sensor) (let* ((sensor-name (fget-reqd-nlist-elem-1 sensor 'name)) (upcase-name (symbol-upcase sensor-name))) (display-nl " \\") (display (format " WHEN_SENSOR_~a_SUPPORTED_NOTHING({" (symbol-upcase sensor-name))) (display "if (strcmp(name,") (write (symbol->string sensor-name)) (display ") == 0) { ") (display (format "if (SENSOR_~a_IS_RUNNING) return TRUE; SENSOR_~a_START; return success;" upcase-name upcase-name)) (display " }") ;; end if (display "})") ;; end when supported )) active-sensors) (display-nl " \\") (display "}")) (cxx-exported-declarations (capture-output f))) (define (make-named-sensor-running) (define (f) (display "#define RETURN_WHETHER_NAMED_SENSOR_IS_RUNNING(name) {") (for-each (lambda (sensor) (let* ((sensor-name (fget-reqd-nlist-elem-1 sensor 'name)) (upcase-name (symbol-upcase sensor-name))) (display-nl " \\") (display (format " WHEN_SENSOR_~a_SUPPORTED_NOTHING({" (symbol-upcase sensor-name))) (display "if (strcmp(name,") (write (symbol->string sensor-name)) (display ") == 0) { ") (display (format "return (SENSOR_~a_IS_RUNNING);" upcase-name)) (display " }") ;; end if (display "})") ;; end when supported )) active-sensors) (display-nl " \\") (display "}")) (cxx-exported-declarations (capture-output f))) (define (make-reconfigure-matching-sensor) (define (f) (display "#define RECONFIGURE_MATCHING_SENSOR(key,value) {") (for-each (lambda (sensor) (let* ((sensor-name (fget-reqd-nlist-elem-1 sensor 'name)) (upcase-name (symbol-upcase sensor-name))) (display-nl " \\") (display (format " WHEN_SENSOR_~a_SUPPORTED_NOTHING({" (symbol-upcase sensor-name))) (display (format "if (strncmp(key, \"sensor.~a.\", ~a) == 0) { " sensor-name (+ (string-length (symbol->string sensor-name)) 8))) (display (format "(SENSOR_~a_RECONFIGURE(key, value)); return success;" upcase-name)) (display " }") ;; end if (display "})") ;; end when supported )) active-sensors) (display-nl " \\") (display "}")) (cxx-exported-declarations (capture-output f))) (define (make-stop-all-sensors) (define (f) (display "#define STOP_ALL_SUPPORTED_SENSORS {") (for-each (lambda (sensor) (let* ((sensor-name (fget-reqd-nlist-elem-1 sensor 'name)) (upcase-name (symbol-upcase sensor-name))) (display-nl " \\") (display (format "WHEN_SENSOR_~a_SUPPORTED_NOTHING({if (SENSOR_~a_IS_RUNNING) { SENSOR_~a_STOP }})" (symbol-upcase sensor-name) upcase-name upcase-name)) )) active-sensors) (display-nl " \\") (display "}")) (cxx-exported-declarations (capture-output f))) (define (make-start-all-sensors) (define (f) (display "#define TRY_START_ALL_SUPPORTED_SENSORS {") (for-each (lambda (sensor) (let* ((sensor-name (fget-reqd-nlist-elem-1 sensor 'name)) (upcase-name (symbol-upcase sensor-name))) (display-nl " \\") (display (format "WHEN_SENSOR_~a_SUPPORTED_NOTHING({if (!(SENSOR_~a_IS_RUNNING) && SENSOR_AUTOSTART_IS_ALLOWED(~a)) { SENSOR_~a_START; handle_any_sensor_start_failure; }})" (symbol-upcase sensor-name) upcase-name sensor-name upcase-name)) )) active-sensors) (display-nl " \\") (display "}")) (cxx-exported-declarations (capture-output f))) (define (make-create-all-sensors) (define (f) (display "#define CREATE_ALL_SENSORS_OR_FAIL {") (for-each (lambda (sensor) (let* ((sensor-name (fget-reqd-nlist-elem-1 sensor 'name)) (upcase-name (symbol-upcase sensor-name))) (display-nl " \\") (display (format "WHEN_SENSOR_~a_SUPPORTED_NOTHING({SENSOR_~a_CREATE; if (!success) { goto fail; }})" (symbol-upcase sensor-name) upcase-name)) )) active-sensors) (display-nl " \\") (display "}")) (cxx-exported-declarations (capture-output f))) (define (make-destroy-all-sensors) (define (f) (display "#define DESTROY_ALL_SENSORS {") (for-each (lambda (sensor) (let* ((sensor-name (fget-reqd-nlist-elem-1 sensor 'name)) (upcase-name (symbol-upcase sensor-name))) (display-nl " \\") (display (format "WHEN_SENSOR_~a_SUPPORTED_NOTHING(SENSOR_~a_DESTROY)" (symbol-upcase sensor-name) upcase-name)) )) active-sensors) (display-nl " \\") (display "}")) (cxx-exported-declarations (capture-output f))) ;; Here we generate definitions for ensuring that all of the listed ;; sensors are indeed included in the sensor array. There are no ;; public declarations, the .cpp file is directly included. This ;; means that there are no makefiles to adjust. (define program-2 (cunit (basename "sa_sensor_list_integration") (includes (system-include "string.h")) (body (make-supported-sensor-definitions) (make-named-sensor-running) (make-stop-named-sensor) (make-start-named-sensor) (make-stop-all-sensors) (make-start-all-sensors) (make-create-all-sensors) (make-destroy-all-sensors) (make-reconfigure-matching-sensor) ))) ;; end program-2 (let ((do-program (lambda (ast) ;;(pretty-nl ast) (when dump? (dump-h-and-cpp ast)) (when gen? (generate-h-and-cpp ast)) ;;(dump-analyzed-ast ast) ;;(dump-compiled-ast ast) ))) (do-program program-2) (parameterize ((in-c-mode #t)) (do-program program-1))) ;; To avoid the invocation of this function from having a value when ;; invoked in a REPL or with mzscheme --eval. (void)) ;; end generate function #| sa_sensor_list_make.ss Copyright 2009 Helsinki Institute for Information Technology (HIIT) and the authors. All rights reserved. Authors: Tero Hasu <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |#
false
d9a87a1f14aa9b8d5aec7ae64aa8161acb57cb67
00466b7744f0fa2fb42e76658d04387f3aa839d8
/sicp/chapter3/3.5/ex3.52.scm
115bc70584c1ff7ea02b1399de941f2914a5e289
[ "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
829
scm
ex3.52.scm
#lang scheme (require "streams.scm") (define sum 0) (define (accum x) (set! sum (+ x sum)) (display "Accum being processed, input param: ") (display x) (display " sum: ") (display sum) (newline) sum ) sum (define seq (stream-map accum (stream-enumerate-interval 1 20))) sum seq (define y (stream-filter even? seq)) (define z (stream-filter (lambda (x) (= (remainder x 5) 0)) seq)) (stream-ref y 7) sum (display-stream z) sum ; What is the value of sum after each of the above expressions is evaluated? ; What is the printed response to evaluating the stream-ref and display-stream ; expressions? Would these responses differ if we had implemented (delay <exp>) ; simply as (lambda () <exp>) without using the optimization provided by memo- ; proc ? Explain.
false
7255eaec9c33b1e920d5a15fd13b4521c517136c
41648be07e8803784690d9b4f6f08091e322b193
/core-string.ss
132be222fc77ea63416c33000be271783e7966ec
[]
no_license
samth/not-a-box
dad25a9ea65debf318a14f2a5f5788b331b62a76
9fa61e07b278be52148612fb5a77f4058eca5a9f
refs/heads/master
2021-01-19T12:51:12.457049
2017-03-02T19:57:20
2017-03-03T19:59:37
82,343,642
0
0
null
2017-02-17T22:27:36
2017-02-17T22:27:36
null
UTF-8
Scheme
false
false
1,487
ss
core-string.ss
(define string-copy! (case-lambda [(dest dest-start src) (unless (and (string? dest) (unsafe-mutable? dest)) (raise-argument-error 'string-set! "(and/c string? (not/c immutable?))" dest)) (chez:string-copy! src 0 dest dest-start (if (string? src) (string-length src) 0))] [(dest dest-start src src-start) (unless (and (string? dest) (unsafe-mutable? dest)) (raise-argument-error 'string-set! "(and/c string? (not/c immutable?))" dest)) (chez:string-copy! src src-start dest dest-start (if (and (string? src) (number? src-start)) (- (string-length src) src-start) 0))] [(dest dest-start src src-start src-end) (unless (and (string? dest) (unsafe-mutable? dest)) (raise-argument-error 'string-set! "(and/c string? (not/c immutable?))" dest)) (chez:string-copy! src src-start dest dest-start (if (and (number? src-start) (number? src-end)) (- src-end src-start) 0))])) (define (string-set! s pos c) (unless (and (string? s) (unsafe-mutable? s)) (raise-argument-error 'string-set! "(and/c string? (not/c immutable?))" s)) (chez:string-set! s pos c)) (define (string->immutable-string x) x) (define substring (case-lambda [(s start) (chez:substring s start (if (string? s) (string-length s) 0))] [(s start end) (chez:substring s start end)]))
false
14ea12b69075a9ca63aeb8ee25d756b6daec272d
2bcf33718a53f5a938fd82bd0d484a423ff308d3
/programming/sicp/ch2/set-as-unordered-list.scm
6d15e7b2ffe64ccee4dceb1cdfca71dfa3f83268
[]
no_license
prurph/teach-yourself-cs
50e598a0c781d79ff294434db0430f7f2c12ff53
4ce98ebab5a905ea1808b8785949ecb52eee0736
refs/heads/main
2023-08-30T06:28:22.247659
2021-10-17T18:27:26
2021-10-17T18:27:26
345,412,092
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,120
scm
set-as-unordered-list.scm
#lang scheme ;; Operations on sets represented as unordered lists (define (element-of-set? x set) (cond ((null? set) #f) ((eq? x (car set)) #t) (else (element-of-set? x (cdr set))))) (define (adjoin-set x set) (if (element-of-set? x set) set (cons x set))) ;; Note this is a streamlined implemntation that only calls `element-of-set?` ;; once per element in set1 by using `cons` to construct the intersection ;; directly if it is. An alternate implementation could use adjoin-set instead. (define (intersection-set set1 set2) (cond ((or (null? set1) (null? set2)) '()) ((element-of-set? (car set1) set2) (cons (car set1) (intersection-set (cdr set1) set2))) (else (intersection-set (cdr set1) set2)))) ;; Implemnted in ex-2.59.scm (define (union-set set1 set2) (cond ((null? set1) set2) ((null? set2) set1) ((element-of-set? (car set1) set2) (union-set (cdr set1) set2)) (else (cons (car set1) (union-set (cdr set1) set2))))) (provide element-of-set?) (provide adjoin-set) (provide intersection-set) (provide union-set)
false
d721404f1c678a0f66c33010546d0336f5933a38
1b771524ff0a6fb71a8f1af8c7555e528a004b5e
/ex408.scm
3ae7cdecefd14fdb6447e0acfac626259de0ffa9
[]
no_license
yujiorama/sicp
6872f3e7ec4cf18ae62bb41f169dae50a2550972
d106005648b2710469067def5fefd44dae53ad58
refs/heads/master
2020-05-31T00:36:06.294314
2011-05-04T14:35:52
2011-05-04T14:35:52
315,072
0
0
null
null
null
null
UTF-8
Scheme
false
false
619
scm
ex408.scm
;; 名前付き let は let でシンボルに手続きを束縛できるもの ;; let->combination を修正する (define (let->combination exp) (make-lambda (map (lambda (x) (car x)) (cadr exp)) (cddr exp))) (define (let->combination exp) (if (list? (cadr exp)) ; 普通の let (make-lambda (map (lambda (x) (car x)) (cadr exp)) (cddr exp)) (let ((name (cadr exp)) (procbody (caddr exp)) (letbody (cdddr exp))) (let ((newproc (cons 'define (cons name procbody)))) (let->combination (cons '() letbody))))))
false
e1def42c254bf6d1b7b95af5afbdfd660a9e3c21
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
/test/tests/peg.scm
93fca99293a70d50c25c93e7c1e4555418a1c34f
[ "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "MIT", "BSD-2-Clause" ]
permissive
ktakashi/sagittarius-scheme
0a6d23a9004e8775792ebe27a395366457daba81
285e84f7c48b65d6594ff4fbbe47a1b499c9fec0
refs/heads/master
2023-09-01T23:45:52.702741
2023-08-31T10:36:08
2023-08-31T10:36:08
41,153,733
48
7
NOASSERTION
2022-07-13T18:04:42
2015-08-21T12:07:54
Scheme
UTF-8
Scheme
false
false
4,208
scm
peg.scm
(import (rnrs) (peg) (sagittarius generators) (srfi :127) (srfi :64)) (test-begin "PEG") (let () (define %simple1 ($do (a ($satisfy (lambda (v) (eq? (car v) 'num)))) ($return (cdr a)))) (define %simple2 ($do ($satisfy (lambda (v) (eq? (car v) 'oparen))) (a %expr) ($satisfy (lambda (v) (eq? (car v) 'cparen))) ($return (cdr a)))) (define %simple ($or %simple1 %simple2)) (define %mulexp1 ($do (a %simple) (($satisfy (lambda (v) (eq? (car v) '*))) ) (b %simple) ($return (* a b)))) (define %mulexp2 ($do (a %simple) ($return a))) (define %mulexp ($or %mulexp1 %mulexp2)) (define %expr1 ($do (a %mulexp) (($satisfy (lambda (v) (eq? (car v) '+)))) (b %mulexp) ($return (+ a b)))) (define %expr2 ($do (a %mulexp) ($return a))) (define %expr ($or %expr1 %expr2)) (let ((l (generator->lseq (list->generator '((num . 1) (+) (num . 2) (*) (num . 3)))))) (let-values (((s v nl) (%expr l))) (test-assert (parse-success? s)) (test-assert (null? nl)) (test-equal 7 v)))) (let () (define (test-a parser input expected first-remain) (let ((l (generator->lseq (list->generator (string->list input))))) (let-values (((s v nl) (parser l))) (test-assert (parse-success? s)) (test-equal first-remain (lseq-car nl)) (test-equal input expected v)))) (define (test-a-fail parser input expected) (define in-list (string->list input)) (let ((l (generator->lseq (list->generator in-list)))) (let-values (((s v nl) (parser l))) (test-assert (parse-expect? s)) (test-equal in-list (lseq-realize nl)) (test-equal `(,input ,v) expected v)))) (test-a ($many ($satisfy (lambda (v) (eqv? #\a v)))) "aaab" '(#\a #\a #\a) #\b) (test-a ($many ($satisfy (lambda (v) (eqv? #\a v))) 2 2) "aaab" '(#\a #\a) #\a) (test-a ($many ($satisfy (lambda (v) (eqv? #\a v))) 1 3) "aaaab" '(#\a #\a #\a) #\a) (test-a-fail ($many ($satisfy (lambda (v) (eqv? #\a v)) "more than 3 As") 3) "aa" "more than 3 As")) (test-error assertion-violation? ($many ($fail "incorrect happen") 5 2)) (let-values (((s v n) (($do (c* ($many $any 3 3)) ($return (list->string c*))) (generator->lseq (string->generator "abcdef"))))) (test-equal "abc" v)) (define (test-$cond condition expected) (let-values (((s v n) (($cond ((eq? condition 'fail) ($many $any 3 3)) ((eq? condition 'ok) ($return 'ok)) (else ($return '??))) (generator->lseq (string->generator "abcdef"))))) (test-equal expected v))) (test-$cond 'ok 'ok) (test-$cond 'fail '(#\a #\b #\c)) (test-$cond 'unknown '??) (let ((seq (generator->lseq (string->generator "abcdef")))) (let-values (((s v l) (($peek $any) seq))) (test-assert (parse-success? s)) (test-equal seq l)) (let-values (((s v l) (($seq ($eqv? #\a) ($peek $any)) seq))) (test-assert (parse-success? s)) (test-equal #\b v) (test-equal (lseq-cdr seq) l)) (let-values (((s v l) (($or ($do (($eqv? #\a)) (($peek ($eqv? #\z))) ($return 'ng)) ($do (($eqv? #\a)) (($peek ($eqv? #\b))) ($return 'ok))) seq))) (test-assert (parse-success? s)) (test-equal 'ok v) (test-equal (lseq-cdr seq) l))) (let ((seq (generator->lseq (string->generator "abcdef")))) (let-values (((s v l) (($peek-match ($eqv? #\a) ($many $any 3 3) ($fail "unexpected")) seq))) (test-assert (parse-success? s)) (test-equal '(#\a #\b #\c) v)) (let-values (((s v l) (($peek-match ($eqv? #\b) ($fail "unexpected") ($many $any 3 3)) seq))) (test-assert (parse-success? s)) (test-equal '(#\a #\b #\c) v))) ;; $fail let entire $or expression fail (let () (define failure ($or ($fail "stop!") ($eqv? #\a))) (let ((seq (generator->lseq (string->generator "abcdef")))) (let-values (((s v nl) (failure seq))) (test-assert (parse-fail? s)) (test-equal "stop!" v)))) ;; $let* (let ((seq (generator->lseq (string->generator "abcdef")))) (let-values (((s v l) (($let* ((a ($eqv? #\a)) (a* ($many $any 3 3))) ($return (cons a a*))) seq))) (test-assert (parse-success? s)) (test-equal '(#\a #\b #\c #\d) v))) (test-end)
false
e169d4ebe37c5ebc3e4b0af57bb7b312e83c9969
ac2a3544b88444eabf12b68a9bce08941cd62581
/gsc/tests/01-boolean/if.scm
ce0cf0fbc17445bf770c2aa2dd124b141b780604
[ "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
169
scm
if.scm
(declare (extended-bindings) (not constant-fold) (not safe)) (define f (##not 123)) (define t (##not f)) (define (test x) (println (if x 11 22))) (test f) (test t)
false
99aea2d1a7be94a28f9fe9f8d2220e2ea71dd760
804e0b7ef83b4fd12899ba472efc823a286ca52d
/old/FeedReader/serf/widgets/tagcloud-test.scm
d4bc338700c4c9f493fc113a027257aa4a9b21f0
[ "Apache-2.0" ]
permissive
cha63506/CRESTaceans
6ec436d1bcb0256e17499ea9eccd5c034e9158bf
a0d24fd3e93fc39eaf25a0b5df90ce1c4a96ec9b
refs/heads/master
2017-05-06T16:59:57.189426
2013-10-17T15:22:35
2013-10-17T15:22:35
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
725
scm
tagcloud-test.scm
(define :words: (list "Spurs" "Out" "Interview" "Yao" "Rockets" "Celtics" "Gorlick" "Injury" "League" "Sign" "Zheng" "Contract" "Championship" "Kevin Garnett" "NBA" "Salary" "Kobe" "Basketball" "Justin" "Source" "Duncan" "Nike")) (define (random-cloud words n) (map (lambda (word) (cons word (random-integer n))) words)) (define (cloud-to-json cloud) (let* ((counts (map (lambda (pair) (format "\t{name:\"~a\", count:~d}" (car pair) (cdr pair))) cloud)) (intermediate (string-join counts ",\n")) (final (string-append "{items:[\n" intermediate "\n]}"))) final)) (define (cloud/json) (cloud-to-json (random-cloud :words: 30)))
false
8d92dcb6a748deba69f548f52c2c7fb568961038
f0747cba9d52d5e82772fd5a1caefbc074237e77
/plat/droplet.scm
60e13156d45364cc67b58807fa9aaee1d3979036
[]
no_license
philhofer/distill
a3b024de260dca13d90e23ecbab4a8781fa47340
152cb447cf9eef3cabe18ccf7645eb597414f484
refs/heads/master
2023-08-27T21:44:28.214377
2023-04-20T03:20:55
2023-04-20T03:20:55
267,761,972
3
0
null
2021-10-13T19:06:55
2020-05-29T04:06:55
Scheme
UTF-8
Scheme
false
false
5,512
scm
droplet.scm
(import scheme (chicken module) (distill base) (distill execline) (distill unix) (distill plan) (distill memo) (distill fs) (distill package) (distill service) (distill image) (distill kvector) (distill system) (pkg linux-virt-x86_64) (pkg curl) (pkg jq) (svc sshd) (plat qemu-system-x86_64)) ;; notes on the digital ocean qemu configuration: ;; ;; - QEMU is started in graphical mode, so the ;; recovery console is on tty0, not ttyS0 ;; - eth0 is the "public" interface; eth1 is the "private" interface ;; - volumes are attached as scsi disks (sda, sdb, etc.) rather than virtio disks ;; - BUT the root disk is attached as a virtio disk (/dev/vda) ;; - The "recovery ISO" appears to live on /dev/vdb ;; - The 169.254/16 link-local network with the metadata instance ;; is on eth0 (the *public* interface!), not eth1 (define d.o.meta-user (adduser 'dometa group: 'dometa)) (define d.o.meta-group (addgroup 'dometa '(dometa))) ;; create /tmp/dometa.json on each boot from instance metadata (define d.o.metadata (let ((maddr "http://169.254.169.254/metadata/v1.json")) (make-service name: 'd.o.metadata inputs: (list curl iproute2) users: (list d.o.meta-user) groups: (list d.o.meta-group) spec: (oneshot* up: `(fdmove -c 2 1 if (ip link set dev lo up) if (ip link set dev eth0 up) if (ip link set dev eth1 up) ;; make the metadata endpoint reachable if (ip addr add 169.254.169.1/16 dev eth0 scope link) ;; create the metadata in a root-owned directory; ;; its contents are critically important to the ;; integrity of the system ;; (but drop privs here on principle anyway) if (/bin/umask "077" redirfd -w 1 /run/dometa.json s6-setuidgid dometa curl ,maddr) ;; drop the link local address so that ;; unprivileged software cannot access the ;; metadata instance via SSRF, etc. ip addr del 169.254.169.1/16 dev eth0))))) ;; create sshd authorized keys from instance metadata (define d.o.pubkeys (make-service name: 'd.o.pubkeys inputs: (list jq (interned-symlink "/root/.ssh/authorized_keys" "/run/pubkeys")) after: (list 'd.o.metadata) spec: (oneshot* up: '(fdmove -c 2 1 /bin/umask "077" redirfd -r 0 /run/dometa.json redirfd -w 1 /run/pubkeys jq -r ".public_keys[]")))) ;; a jq(1) script to convert droplet metadata ;; to an iproute(8) batch mode script ;; ;; note: custom images don't support public IPv6 (???) ;; so we don't bother looking for .interfaces.public[0].ipv6 (define jq-ifup-script "# convert a netmask string to cidr mask: def cidr: {\"255\": 8, \"254\" : 7, \"252\": 6, \"248\": 5, \"240\": 4, \"224\" : 3, \"192\": 2, \"128\": 1, \"0\": 0} as $btable | split(\".\") | map($btable[.]) | add; # convert an object to addr/cidr notation def addrmask: \"\\(.ip_address)/\\(.netmask | cidr)\"; .interfaces.private[0] as $private | .interfaces.public[0] as $public | $public.ipv4 as $pubv4 | $private.ipv4 as $privv4 | \"addr add \\($privv4 | addrmask) dev eth1\", \"addr add \\($pubv4 | addrmask) dev eth0\", \"addr add \\($public.anchor_ipv4 | addrmask) dev eth0\", \"route add default via inet \\($pubv4.gateway) dev eth0 src \\($pubv4.ip_address)\" ") ;; bring up networking using instance metadata (define d.o.networking (make-service name: 'net.d.o inputs: (list jq iproute2 (interned "/etc/digital-ocean/ifup.jq" #o644 jq-ifup-script)) after: (list 'd.o.metadata) users: (list d.o.meta-user) groups: (list d.o.meta-group) spec: (oneshot* up: '(pipeline (redirfd -r 0 /run/dometa.json s6-setuidgid dometa jq -r -f /etc/digital-ocean/ifup.jq) ip -b -)))) ;; set /etc/resolv.conf from instance metadata ;; (by symlinking it to /run/resolv.conf and writing to that...) (define d.o.resolv.conf (make-service name: 'd.o.resolv.conf inputs: (list jq (interned-symlink "/etc/resolv.conf" "/run/resolv.conf")) after: (list 'd.o.metadata) users: (list d.o.meta-user) groups: (list d.o.meta-group) spec: (oneshot* up: '(redirfd -w 1 /run/resolv.conf if (echo "# generated by d.o.resolv.conf") forbacktickx -n server (redirfd -r 0 /run/dometa.json s6-setuidgid dometa jq -r ".dns.nameservers[]") importas -u |-i| server server echo nameserver $server)))) (define droplet (kwith qemu-system-x86_64 ;; we need tty0 instead of ttyS0 because the DO recovery console ;; is attached as if it were a VGA screen cmdline: (:= '("root=/dev/vda2" "rootfstype=squashfs" "console=tty0")) services: (+= (list d.o.metadata d.o.pubkeys d.o.resolv.conf d.o.networking))))
false
c03d97c658ca8c57890e492c281059fab72d5184
d074b9a2169d667227f0642c76d332c6d517f1ba
/sicp/ch_3/exercise.3.38.scm
56d1593dcfcc2fda54ecf8aaae5f98049cb45d50
[]
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,143
scm
exercise.3.38.scm
#lang racket/base ;;; Exercise 3.38 ;; Suppose that Peter, Paul, and Mary share a joint ;; bank account that initially contains $100. Concurrently, Peter ;; deposits $10, Paul withdraws $20, and Mary withdraws half the ;; money in the account, by executing the following commands: ;; ;; Peter: (set! balance (+ balance 10)) ;; Paul: (set! balance (- balance 20)) ;; Mary: (set! balance (- balance (/ balance 2))) ;; ;; a. List all the different possible values for `balance' after ;; these three transactions have been completed, assuming that ;; the banking system forces the three processes to run ;; sequentially in some order. ;; a b c = 100 + 10 - 20 - half = 45 ;; a c b = 100 + 10 - half - 20 = 35 ;; b a c = 100 - 20 + 10 - half = 45 ;; b c a = 100 - 20 - half + 10 = 50 ;; c a b = 100 - half + 10 - 20 = 40 ;; c b a = 100 - half - 20 + 10 = 40 ;; b. What are some other values that could be produced if the ;; system allows the processes to be interleaved? Draw timing ;; diagrams like the one in *Note Figure 3-29:: to explain how ;; these values can occur. ;; no. tedious.
false
bb2efc6bf40ff907896fe264f28aec7f39c99c2f
97b9e4b5623c1e3d201fa0f0e624852c276e8cc6
/compiler.scm
9973716661f6acdbc638ed7f05380778e2189186
[]
no_license
seckcoder/seck-scheme
89556794e7834058269058569695997ead50c4b6
787814a2042e38762a73f126aaa03ca2702cd9db
refs/heads/master
2021-01-23T06:49:31.735249
2015-08-15T03:17:54
2015-08-15T03:17:54
40,744,969
6
0
null
null
null
null
UTF-8
Scheme
false
false
29,156
scm
compiler.scm
(load "tests-driver.scm") #|(load "tests-1.1-req.scm") (load "tests-1.2-req.scm")|# (require racket/match (prefix-in env: "env.rkt") "../../base/utils.rkt" "base.rkt" "macro-expand.rkt" "constants.rkt" "closure-conversion.rkt" "alpha-conversion.rkt" "assign.rkt" "global.rkt") (define (clj-cvt e) (closure-conversion e 'bottom-up)) (define (assign-cvt e) (car (assign-conversion e))) (define (alpha-cvt e) ((alpha-conversion (env:empty)) e)) (define (compile-program x) (init-global!) (~> x macro-expand lift-constant ;alpha-cvt assign-cvt clj-cvt emit-program)) (define (emit-global-proc n code) (match code [`(proc (,v* ...) ,body) (emit-fn-header n) (let* ([v*-num (length v*)] [env (env:init v* (range (- wordsize) (- wordsize) (- (* v*-num wordsize))))]) ((emit-exp (- (- (* v*-num wordsize)) wordsize) env #t) body) (emit " ret") )] [_ (void)])) (define (emit-global-constant n code) (match code [`(datum ,v) (emit "# global constant") (emit " .local ~a" n) (emit " .comm ~a,~a,~a" n wordsize wordsize) ((emit-exp (- wordsize) (env:empty) #t) v) (emit-save-eax-to-global) (emit " movl %eax, ~a # move global constant pointer value" n)] [_ (void)] )) (define (emit-save-eax-to-global) ; save eax register value to global memory, ; so that the value pointed by it can be handled by garbage collection (emit " movl ~a(%ebp), %ecx # fetch global pointer" global-offset) (emit " movl %eax, (%ecx) # save eax to global memory") (emit " addl $~a, ~a(%ebp) # increase global pointer" wordsize global-offset) (emit " movl %ecx, %eax # return global pointer as result")) (define (emit-load-global-to-eax v) (emit " movl ~a, %eax" v)) (define (global-proc? code) (match code [`(proc (,v* ...) ,body) #t] [_ #f])) (define (global-constant? code) (match code [`(datum ,v) #t] [_ #f])) (define (emit-global-proc*) (for-each (match-lambda [(list n (? global-proc? code)) (emit-global-proc n code)] [_ (void)]) *global*)) (define (emit-global-constant*) (for-each (match-lambda [(list n (? global-constant? code)) (emit-global-constant n code)] [_ (void)]) *global*)) ; lift lambda (define-syntax def-lifted-lambda (syntax-rules () [(_ (lambda (v* ...) body)) (env!:ext! *proc* (gensym 'proc) `(proc (v* ...) body))])) (define (emit-program x) (print x)(newline) (emit " .text") ; We need L_scheme_entry since we need to make sure that when starting ; to emit-exp, the value above %esp is a return address. Otherwise, ; the tail-optimization will not work. (emit-fn-header 'L_scheme_entry) (emit-global-constant*) ((emit-exp (- wordsize) (env:empty) #t) x) (emit " ret # ret from L_scheme_entry") ; if program is tail-optimized, ret will be ignored (emit-fn-header 'scheme_entry) (emit-preserve-regs) (emit " movl %esp, %ecx # store esp temporarily") ; heap : low->high ; stack : high->low (emit " movl 12(%ecx), %ebp # set mem pointer") (emit " movl 8(%ecx), %esp # set stack pointer") (emit " pushl 4(%ecx) # store ctx") ; It's an assumption that physical addresses on Intel's ; 32bit processors have 8-byte boundaries. So we don't ; need to aligh the heap address when start. ;(emit-align-heap) ; aligh the start address of heap (emit " call L_scheme_entry") (emit-restore-regs) (emit " ret # return from scheme_entry") (emit-global-proc*) ) (define (emit-preserve-regs) (define (si-of-i i) (* wordsize i)) (emit " movl 4(%esp), %ecx") ; ctx ptr (let loop ([regs registers] [i 0]) (cond [(null? regs) 'ok] [(scratch? (car regs)) (loop (cdr regs) (add1 i))] [else (match (car regs) [(cons n _) (emit " movl %~a, ~a(%ecx)" n (si-of-i i)) (loop (cdr regs) (add1 i))])]))) (define (emit-restore-regs) (define (si-of-i i) (* wordsize i)) (emit " popl %ecx") ; get ctx ptr (let loop ([regs registers] [i 0]) (cond [(null? regs) 'ok] [(scratch? (car regs)) (loop (cdr regs) (add1 i))] [else (match (car regs) [(cons n _) (emit " movl ~a(%ecx), %~a" (si-of-i i) n) (loop (cdr regs) (add1 i))])]))) (define (emit-fn-header lbl) (emit " .globl ~a" lbl) (emit " .type ~a, @function" lbl) (emit "~a:" lbl)) (define-syntax gen-pairs (syntax-rules () [(_) (list)] [(_ (op0 p* ...) pair* ...) (cons (cons `op0 (lambda () p* ...)) (gen-pairs pair* ...))])) (define-syntax biop-emit-pairs (syntax-rules () [(_ p0 p* ...) (make-hasheq (gen-pairs p0 p* ...))])) (define emit-exp (lambda (si env tail?) (define (emit-unop op v) ((emit-exp si env #f) v) (match op ['number->char ; shift left (emit " shll $~s, %eax" (- charshift fxshift)) ; change the shifted to char tag (emit " orl $~s, %eax" chartag)] ['char->number (emit " sarl $~s, %eax" (- charshift fxshift))] ['number? (emit " andb $~s, %al" fxmask) (emit " cmpb $~s, %al" fxtag) (emit " sete %al") (emit-eax-0/1->bool)] ['null? (emit " cmpw $~s, %ax" null_v) (emit " sete %al") (emit-eax-0/1->bool)] ['boolean? (emit " andb $~s, %al" boolmask) (emit " cmpb $~s, %al" booltag) (emit " sete %al") (emit-eax-0/1->bool)] ['char? (emit " andb $~s, %al" charmask) (emit " cmpb $~s, %al" chartag) (emit " sete %al") (emit-eax-0/1->bool)] ['not (emit " cmpw $~s, %ax" bool-f) ; if equal=#f, we set al to 1, then we transform it to #t. ; if equal to other value, we set al to 0, then transformed to #f. (emit " sete %al") (emit-eax-0/1->bool)] ['zero? (emit " cmpl $~s, %eax" (immediate-rep 0)) (emit " sete %al") (emit-eax-0/1->bool)] ['car ; It's -1, because tag of pair is 0x1, so the tagger pointer ; is just one byte bigger (emit " movl -1(%eax), %eax # car of pair. Think about -1!")] ['cdr (emit " movl ~s(%eax), %eax # cdr of pair. Think about (sub1 wordsize)" (sub1 wordsize))] ['pair? (emit " andb $~s, %al" pairmask) (emit " cmpb $~s, %al" pairtag) (emit " sete %al") (emit-eax-0/1->bool)] ['string-length (emit-remove-strtag 'eax) (emit " movl (%eax), %eax # move string length to eax")] ['vector? (emit " andb $~s, %al" vecmask) (emit " cmpb $~s, %al" vectag) (emit " sete %al") (emit-eax-0/1->bool)] ['vector-length (emit-remove-vectag 'eax) (emit " movl (%eax), %eax # move vec length to eax")] ['string? (emit " andb $~s, %al" strmask) (emit " cmpb $~s, %al" strtag) (emit " sete %al") (emit-eax-0/1->bool)] ['fixnum->char (emit-remove-fxtag 'eax) (emit-add-chartag 'eax)] ['char->fixnum (emit-remove-chartag 'eax) (emit-add-fxtag 'eax)] ['procedure? (emit " andb $~s, %al" cljmask) (emit " cmpb $~s, %al" cljtag) (emit " sete %al") (emit-eax-0/1->bool)] [_ (error 'emit-unop "~a is not an unary operator" op)])) (define (emit-biop op a b) (define (emit-biv) (emit-exps-leave-last si env (list a b))) (define (emit-*) (emit-biv) (emit " movl ~s(%esp), %ecx # get a" si) (emit-remove-fxtag 'ecx) (emit-remove-fxtag 'eax) (emit " imull %ecx, %eax # a * b") (emit-add-fxtag 'eax)) (define (emit-cmp op) (emit-biv) (emit " cmpl ~s(%esp), %eax" si) (case op ['= (emit " sete %al")] ['< (emit " setg %al")] ['<= (emit " setge %al")] ['> (emit " setl %al")] ['>= (emit " setle %al")] ['char= (emit " sete %al")] [else (report-not-found)]) (emit-eax-0/1->bool)) (define op->emitter (biop-emit-pairs [* (emit-*)] [fx* (emit-exp1 `(* ,a ,b))] [+ (emit-biv) ; b = a + b (emit " addl ~s(%esp), %eax" si)] [fx+ (emit-exp1 `(+ ,a ,b))] [- (emit-biv) ; b = a - b (emit " movl %eax, %ecx") (emit " movl ~s(%esp), %eax" si) (emit " subl %ecx, %eax")] [quotient (emit-divide (emit-exps-push-all si env (list a b)))] [remainder (emit-divide (emit-exps-push-all si env (list a b))) (emit " movl %edx, %eax")] [fx- (emit-exp1 `(- ,a ,b))] [= (emit-cmp '=)] [fx= (emit-exp1 `(= ,a ,b))] [< (emit-cmp '<)] [fx< (emit-exp1 `(< ,a ,b))] [<= (emit-cmp '<=)] [fx<= (emit-exp1 `(<= ,a ,b))] [> (emit-cmp '>)] [fx> (emit-exp1 `(> ,a ,b))] [>= (emit-cmp '>=)] [fx>= (emit-exp1 `(>= ,a ,b))] [char= (emit-cmp 'char=)] [cons (emit-cons a b)] [eq? ; simple treatment (emit-exp1 `(= ,a ,b))] [set-car! (emit-set-car! a b)] [set-cdr! (emit-set-cdr! a b)] )) (define (report-not-found) (error 'emit-biop "~a is not a binary operator" op)) ;(printf "emit-op ~a ~a\n" op (hash-ref op->emitter op)) ((hash-ref op->emitter op report-not-found))) (define (emit-rands rands) (let ([new-si (emit-exps-push-all si env rands)]) ; swap the rands order ; rand-0 : si(%esp) ; rand-n : (+ new-si wordsize)(%esp) ;(printf "~a ~a ~a\n" si new-si (length rands)) (unless (= (+ new-si (* (length rands) wordsize)) si) ; for debuggin purpose (error 'emit-rands "some error happened")) (emit-swap-rands-range si new-si) new-si)) (define (emit-make-vec n) ((emit-exp si env #f) n) (emit " movl %eax, ~s(%esp) #store vec length to stack" si) (emit-remove-fxtag 'eax) ; %eax store length (emit-calc-vector-size) (emit-alloc-heap (- si wordsize) #t) ; vec length on stack (emit-stack->heap si 0) (emit-add-vectag 'eax)) (define (emit-vec-ref v i) ; TODO: out-of-bounds check? (emit-exps-leave-last si env (list v i)) ; remove i's flag (emit-remove-fxtag 'eax) (emit " movl ~s(%esp), %ecx # transfer vec to ecx" si) ; v (emit-remove-vectag 'ecx) ; %ecx + %eax*wordsize + wordsize. extra wordsize is for vector length (emit " movl ~s(%ecx, %eax, ~s), %eax # get ith(in eax) value of vec" wordsize wordsize) ) (define (emit-vec-set! v i val) (emit-exps-leave-last si env (list v i val)) (emit " movl ~s(%esp), %ecx" si) ; v (emit-remove-vectag 'ecx) (emit " movl ~s(%esp), %edx" (- si wordsize)) ; i ; i should be fxnum, we should remove its flags (emit-remove-fxtag 'edx) ; %ecx + %edx*wordsize + wordsize. extra wordsize is for vector length (emit " movl %eax, ~s(%ecx, %edx, ~s)" wordsize wordsize) ) (define (emit-vec-from-values vs) ; why we shouldn't evaluate one value and move it to heap? ; Since when evaluate the value, it may change ebp (emit "# emit-vec-from-values") (let* ([len (length vs)] [new-si (emit-exps-push-all si env vs)]) (emit-alloc-heap new-si (* (add1 len) wordsize)) (emit " movl $~s, (%eax) # move length to vector" (immediate-rep len)) (let loop ([i 0]) (unless (>= i len) ; move the ith item from stack to heap (emit-stack->heap (- si (* i wordsize)) (* (add1 i) wordsize)) (loop (add1 i)))) (emit-add-vectag 'eax) ) (emit "# emit-vec-from-values end") ) (define (emit-make-string n) ((emit-exp si env #f) n) (emit " movl %eax, ~s(%esp) # store str len" si) (emit-remove-fxtag 'eax) (emit-calc-string-size) (emit-alloc-heap (- si wordsize) #t) (emit-stack->heap si 0) ; move length to heap (emit-add-strtag 'eax)) (define (emit-string-ref s i) (emit-exps-leave-last si env (list s i)) (emit-remove-fxtag 'eax) (emit " movl ~s(%esp), %ecx # str pointer" si) (emit-remove-strtag 'ecx) (emit " movl $0, %edx # reset edx") (emit " movb ~s(%ecx, %eax), %dl # ith value in str" wordsize) (emit " movl %edx, %eax") (emit-add-chartag 'eax) ) (define (emit-string-set s i c) (emit-exps-leave-last si env (list s i c)) (emit " movl ~s(%esp), %ecx # get string pointer" si) ; s (emit " movl ~s(%esp), %edx # get idx:i" (- si wordsize)) ; i (emit-remove-chartag 'eax) (emit-remove-strtag 'ecx) (emit-remove-fxtag 'edx) (emit " movb %al, ~a(%ecx, %edx) # string-set!" wordsize) ) (define (emit-string-from-values cs) (let* ([len (length cs)] [new-si (emit-exps-push-all si env cs)]) ;(printf "~a ~a ~a\n" len si new-si) (emit-alloc-heap new-si (+ wordsize len)) (emit " movl $~s, (%eax) # move len to str" (immediate-rep len)) (for ([i (in-range 0 len)]) (emit-stack->heap-by-char (- si (* i wordsize)) (+ wordsize i))) (emit-add-strtag 'eax))) (define (emit-make-symbol s) ; make symbol from str s ) (define (emit-void) (emit " movl $~s, %eax" void-v)) (define (emit-constant-ref v) (emit-load-global-to-eax v) (emit " movl (%eax), %eax # constant-ref")) (define (emit-cons a d) (let ([new-si (emit-exps-push-all si env (list a d))]) (emit-alloc-heap new-si (* 2 wordsize)) (emit-stack->heap si 0) ; move a to heap (emit-stack->heap (- si wordsize) wordsize) ; move d to heap (emit-add-pairtag 'eax))) (define (emit-set-car! pair v) (emit-exps-leave-last si env (list pair v)) (emit " movl ~s(%esp), %ecx # get pair ptr" si) (emit-remove-pairtag 'ecx) (emit " movl %eax, (%ecx) # set car")) (define (emit-set-cdr! pair v) (emit-exps-leave-last si env (list pair v)) (emit " movl ~s(%esp), %ecx # get pair ptr" si) (emit-remove-pairtag 'ecx) (emit " movl %eax, ~a(%ecx) # set cdr" wordsize)) (define (emit-closure f rv) (emit "# emit-closure") ((emit-exp si env #f) rv) (let ([new-si (emit-eax->stack si)]) (emit-alloc-heap new-si (* 2 wordsize)) ; store label and fvs env (emit " leal ~s, %ecx # get address of closure label" f) ;(emit-add-fxtag 'ecx) ; we represent address as fxnum (emit " movl %ecx, (%eax) # move label address to heap") (emit-stack->heap si wordsize) ; move fvs env to heap (emit-add-cljtag 'eax) (emit "# emit-closure end"))) (define (emit-app rator rands) (emit "# emit-app") ;(printf "emit-app: is tail call? ~a" tail?) (if tail? (begin (emit "# tail-optimization") (let ([new-si (emit-exps-push-all (- si wordsize) env rands)]) ((emit-exp new-si env #f) rator) (emit-remove-cljtag 'eax) (emit " movl (%eax), %ecx # move label to stack") (emit " movl %ecx, ~s(%esp)" new-si) (emit " movl ~s(%eax), %edx # move clojure env to stack" wordsize) (emit " movl %edx, ~s(%esp)" si) (emit-stack-move-range si (- wordsize) (+ new-si wordsize) (- wordsize)) (emit " jmp *~s(%esp) # tail jump" new-si) )) (begin (emit "#no tail optmization") (let ([new-si (emit-exps-push-all (- si (* 2 wordsize)) env rands)]) ((emit-exp new-si env #f) rator) ; get closure (emit-remove-cljtag 'eax) (emit " movl (%eax), %ecx") ; move label to ecx (emit " movl ~s(%eax), %edx" wordsize) ; movel clojure env to stack (emit " movl %edx, ~s(%esp)" (- si wordsize)) (emit " addl $~s, %esp" (+ si wordsize)) (emit " call *%ecx") (emit " subl $~s, %esp" (+ si wordsize))))) (emit "# emit-app end")) (define (emit-let vs es body) (match (emit-decls si env #f vs es) [(list si env) ((emit-exp si env tail?) body)])) (define (emit-char-seq s reg start) ; chars to heap, reg as pointer to heap, ; start is the si of heap pointer (for ([c (in-string s)] [i (in-naturals start)]) (emit " movb $~a, ~a(%eax)" (char->integer c) i) )) (define (emit-string s) (emit-alloc-heap si (+ wordsize (string-length s))) (emit " movl $~a, (%eax) # str len" (immediate-rep (string-length s))) (emit-char-seq s 'eax wordsize) (emit-add-strtag 'eax)) ; ## emit-exp1 ## (define emit-exp1 (lambda (exp) (match exp [(? immediate? x) (emit " movl $~s, %eax # emit immediate:~a" (immediate-rep x) x)] [(? string? s) (emit-string s)] [(? symbol? v) ; variable (let ([pos (env:app env v)]) ;(printf "emit-var: ~a ~a\n" v pos) (emit " movl ~s(%esp), %eax # var:~s" pos v))] [`(make-vec ,n) (emit-make-vec n)] [`(vec-ref ,v ,i) (emit-vec-ref v i)] [`(vec-set! ,v ,i ,val) (emit-vec-set! v i val)] [`(vec ,v* ...) (emit-vec-from-values v*)] [`(make-string ,n) (emit-make-string n)] [`(string-ref ,s ,i) (emit-string-ref s i)] [`(string-set! ,s ,i ,c) (emit-string-set s i c)] [`(string ,c* ...) (emit-string-from-values c*)] [`(make-symbol ,s) (emit-make-symbol s)] [`(constant-ref ,v) (emit-constant-ref v)] [`(void ,v* ...) (emit-void)] [(list (? unop? op) v) (emit-unop op v)] [(list (? biop? op) a b) (emit-biop op a b)] [`(if ,test ,then ,else) ((emit-exp si env #f) test) (let ((else-lbl (gen-label)) (endif-lbl (gen-label))) ; jump to else if equal to false ; Que: how to optimize this? (emit " cmpl $~s, %eax" bool-f) (emit " je ~a" else-lbl) (emit-exp1 then) (emit " jmp ~s" endif-lbl) (emit "~s:" else-lbl) (emit-exp1 else) (emit "~s:" endif-lbl))] [`(let ((,v* ,e*) ...) ,body) (emit-let v* e* body)] [`(lambda (,v* ...) ,body) (error 'emit-exp "lambda should be converted to procedure")] [`(begin ,exp* ...) (let loop ([exps exp*]) (cond [(null? exps) (error 'begin "empty body")] [(null? (cdr exps)) (printf "~a\n" (car exps)) (emit-exp1 (car exps))] [else ((emit-exp si env #f) (car exps)) (loop (cdr exps))]))] [`(labels ([,f* ,proc*] ...) ,exp) (for-each (lambda (f proc) (add-global! f proc)) f* proc*) (emit-exp1 exp)] [`(closure ,f ,rv) (emit-closure f rv)] [`(app ,rator ,rand* ...) (emit-app rator rand*)] [_ (error 'emit-exp "~a not matched" exp)] ))) emit-exp1)) ; eval(e) could be an address or label (define (emit-decl si env v e) ((emit-exp si env) e) (emit " movl %eax, ~s(%esp)" si) (list (- si wordsize) (env:ext env v si))) ; for let (define (emit-decls si env tail? vs es) (let loop [(si si) (cur-vs vs) (cur-es es) (si-acc '())] (cond [(and (null? cur-vs) (null? cur-es)) (list si (env:exts env vs (reverse si-acc)))] [(or (null? cur-vs) (null? cur-es)) (error 'emit-decls "vs and es have different length")] [else ((emit-exp si env tail?) (car cur-es)) (emit " movl %eax, ~s(%esp) # move declared value to stack" si) (loop (- si wordsize) (cdr cur-vs) (cdr cur-es) (cons si si-acc))]))) ; for let* (define (emit-decl* si env vs es) (foldl (match-lambda* [(list v e (list si env)) (emit-decl si env v e)]) (list si env) vs es)) (define (emit-remove-fxtag reg) (emit " sar $~s, %~a # remove fx tag" fxshift reg)) (define (emit-add-fxtag reg) ; sign extension (emit " sal $~s, %~a # add fxtag" fxshift reg)) (define (emit-remove-cljtag reg) (emit " subl $~s, %~a # remove cljtag" cljtag reg)) (define (emit-add-cljtag reg) ; we don't need to shift (emit " orl $~s, %~a # add cljtag" cljtag reg)) (define (emit-remove-vectag reg) (emit " subl $~s, %~a" vectag reg)) (define (emit-add-vectag reg) (emit " orl $~s, %~a # add vectag" vectag reg)) (define (emit-add-pairtag reg) (emit " orl $~s, %~a # add pairtag" pairtag reg)) (define (emit-remove-pairtag reg) (emit " subl $~s, %~a # remove pairtag" pairtag reg)) (define (emit-add-strtag reg) (emit " orl $~s, %~a # add strtag" strtag reg)) (define (emit-remove-strtag reg) (emit " subl $~s, %~a # remove strtag" strtag reg)) (define (emit-add-chartag reg) (emit " shl $~s, %~a # add chartag" charshift reg) (emit " orl $~s, %~a" chartag reg) ) (define (emit-remove-chartag reg) (emit " shr $~s, %~a # remove chartag" charshift reg)) (define gen-label (let ([count 0]) (lambda () (let ([L (format "L_~s" count)]) (set! count (add1 count)) (string->symbol L))))) ; after cmp operation, we can set eax to bool value according ; to the flags (define (emit-eax-0/1->bool) (emit " movzbl %al, %eax") ; movzbl set eax high-order 24bits to zero (emit " sal $~s, %al" boolshift) ; transform the result to bool (emit " or $~s, %al" bool-f)) ; move eax to stack; return next si (define (emit-eax->stack si) (emit " movl %eax, ~s(%esp) # save eax value to stack" si) (- si wordsize)) ; move ah to stack; return next si ; this is used for move characters (define (emit-al->stack si) (emit " movb %al, ~s(%esp) # save ah to stack" si) (- si 1)) ; return si (define (emit-exps-leave-last si env exps) ; emit multi exps, leave the last in %eax) (cond [(null? exps) (error 'emit-exps-leav-last "need at least one exp")] [(null? (cdr exps)) ((emit-exp si env #f) (car exps)) si] [else (let-values ([(first rest) (split-at-right exps 1)]) (let ([si (emit-exps-push-all si env first)]) (emit-exps-leave-last si env rest) si))])) (define (emit-exps-push-all si env exps [tail? #f]) ; emit mutli exps, all pushed to stack (emit "# emit-exps-push-all") (let ([new-si (foldl (match-lambda* [(list exp si) ((emit-exp si env tail?) exp) (emit-eax->stack si)]) si exps)]) (emit "# emit-exps-push-all end") new-si) ) (define (emit-exps-push-all-by-char si env exps [tail? #f]) (emit "# emit-exps-push-all-by-char") (let ([new-si (foldl (match-lambda* [(list exp si) ((emit-exp si env tail?) exp) (emit-remove-chartag 'eax) (emit-al->stack si)]) si exps)]) (emit "# emit-exps-push-all-by-char end") (align new-si wordsize))) ; swap i(%base) j(%base) (define (emit-swap i j [base 'esp]) (emit " movl ~s(%~s), %ecx" i base) (emit " movl ~s(%~s), %edx" j base) (emit " movl %ecx, ~s(%~s)" j base) (emit " movl %edx, ~s(%~s)" i base)) ; swap pos in [start end] (define (emit-swap-range start end [step wordsize] [base 'esp]) (emit "# emit-swap-range") (let* ([l (range-len start step end)] [l-1 (sub1 l)] [range-get (range-of-i start step end)] [n (quotient l 2)]) (let loop ([i 0] ) (cond [(>= i n) (void)] [else #|(printf "~a ~a\n" (range-get i) (range-get (- l-1 i)))|# (emit-swap (range-get i) (range-get (- l-1 i)) base) (loop (add1 i))]))) (emit "# emit-swap-range end") ) (define (emit-swap-rands-range si new-si) ; swap (+ new-si wordsize)(%esp) -> si(%esp) ;(printf "emit-swap-rands-range ~a ~a\n" si new-si) (emit-swap-range (+ new-si wordsize) si)) (define (emit-stack->heap stack-pos heap-pos) ; heap ptr stored in eax (emit " movl ~s(%esp), %ecx # move stack value to heap" stack-pos) (emit " movl %ecx, ~s(%eax)" heap-pos)) (define (emit-stack->heap-by-char stack-pos heap-pos) (emit " movl ~s(%esp), %ecx # move stack char value to ecx" stack-pos) (emit-remove-chartag 'ecx) (emit " movb %cl, ~s(%eax) # move char to heap" heap-pos)) ; move [start ... end] to [to_start ...] (define (emit-stack-move-range start step end to_start) (emit "# emit-stack-move-range ~a ~a ~a ~a" start step end to_start) (let ([cmp (range-param-check start step end)]) (let loop ([from start] [to to_start]) (cond [(cmp from end) (void)] [else ;(printf "move ~a to ~a\n" from end) (emit-swap from to) (loop (+ from step) (+ to step))]))) (emit "# emit-stack-move-range end") ) (define (emit-divide si) ; value stores on stack (emit " movl ~s(%esp), %edx # dividend to [edx,eax]" (+ si (* 2 wordsize))) (emit-remove-fxtag 'edx) (emit " movl %edx, %eax") (emit " sarl $~s, %edx # set edx as 0 or all 1" (sub1 (* 8 wordsize))) (emit " movl ~s(%esp), %ecx #divisor" (+ si wordsize)) (emit-remove-fxtag 'ecx) (emit " idivl %ecx") (emit-add-fxtag 'eax) (emit-add-fxtag 'edx) ;(emit " movl ~s(%esp), %eax" (+ si (* 1 wordsize))) ) (define (emit-calc-vector-size) ; length in %eax (emit " addl $1, %eax # calculate vector size with %eax store length") (emit " imull $~s, %eax" wordsize)) (define (emit-calc-string-size) ; length in %eax (emit " addl $~a, %eax # calc str byte size" wordsize)) (define (emit-foreign-call si funcname) (emit " addl $~s, %esp" (+ si wordsize)) (emit " call ~a" funcname) (emit " subl $~s, %esp" (+ si wordsize))) (define (emit-alloc-heap1 si) ; heap-aligned size in eax ; heap_alloc(mem, stack, size) (emit " movl %eax, ~s(%esp) # size to stack" si) (emit " leal ~s(%esp), %ecx # stack base pointer" (+ si wordsize)) (emit " movl %ecx, ~s(%esp)" (- si wordsize)) (emit " movl %ebp, ~s(%esp) # mem to stack" (- si (* 2 wordsize))) (emit-foreign-call (- si (* 3 wordsize)) 'heap_alloc) ;(emit " movl ~s(%esp), %ebp # recover mem ptr" (- si (* 2 wordsize))) ) (define emit-alloc-heap (match-lambda* [(list si (? boolean? align?)) ; %eax store the size, (when align? (emit " addl $~s, %eax # heap align calculation" (sub1 heap-align)) (emit " andl $~s, %eax" (- heap-align))) (emit-alloc-heap1 si)] [(list si (? number? size)) ; size is the num of bytes to allocate (let ([aligned-size (align-heap-size size)]) (emit " movl $~s, %eax # aligned size to eax" aligned-size) (emit-alloc-heap1 si))])) #|(load "tests-1.3-req1.scm") (load "tests-1.4-req.scm") (load "tests-1.6-req.scm") (load "tests-1.6-opt.scm") (load "tests-1.5-req.scm") (load "tests-1.5-opt.scm")|# ;(load "tests-1.8-opt.scm") ; test pair ;(load "tests-print.scm") ;(load "tests-proc.scm") ;(load "tests-constant.scm") ;(load "tests-1.8-req.scm") ;(load "tests-1.9-req.scm") ; test begin, vector, string, set-car!/set-cdr! ;(load "tests-2.1-req.scm") ; closure test ;(load "tests-2.2-req.scm") ; test set! ;(load "tests-2.3-req.scm") ; test constants (load "tests-2.4-req.scm") ;(load "seck-tests.scm")
true
dc050b9b8f62bb31f70cca7bc160a1b72f17a35e
75b421a734cb2751facfc27799f2384729432a2c
/lisp/SICP/main.scm
e4ff6ca6716dff80349676fb0ee196971176364f
[]
no_license
udonyang/docs
da7d207cc6e5e5cc81573e8e3757f4ebd44d4235
ce6c4127662a9db4f79d65bf25a2b9fea41f529f
refs/heads/master
2021-09-07T13:34:46.937066
2018-02-23T15:26:27
2018-02-23T15:26:27
20,750,531
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,987
scm
main.scm
'(display "hello sicp") '(newline) (define (ex1.5) (define (p) (p)) (define (test x y) (if (= x 0) 0 y)) (display (test 0 (p)))) '(ex1.5) (define EPS 1e-5) (define SQRT-TEST 0.0001000009) (define (gen-iter good-enough? improve guess x) (if (good-enough? guess x) guess (gen-iter good-enough? improve (improve guess x) x))) (define (sqrt-iter-g good-enough? guess x) (gen-iter good-enough? improve guess x)) (define (sqrt-iter guess x) (sqrt-iter-g good-enough? guess x)) (define (improve guess x) (average guess (/ x guess))) (define (average x y) (/ (+ x y) 2)) (define (sqrt-diff guess x) (abs (- (square guess) x))) (define (good-enough? guess x) (< (sqrt-diff guess x) EPS)) (define (square x) (* x x)) (define (sqrt x) (sqrt-iter 1.0 x)) (define (eg1.1.7) (display (sqrt SQRT-TEST)) (display " ") (display (sqrt-diff (sqrt SQRT-TEST) SQRT-TEST)) (newline)) '(eg1.1.7) (define (ex1.6) (define (new-if predicate then-clause else-clause) (cond (predicate then-clause) (else else-clause))) (define (sqrt-iter guess x) (new-if (good-enough? guess x) guess (sqrt-iter (improve guess x) x))) (define (sqrt x) (sqrt-iter 1.0 x)) (display (sqrt 2)) (newline)) '(ex1.6) (define (ex1.7) (define (good-enough? guess x) (< (abs (- (improve guess x) guess)) EPS)) (define (sqrt-iter guess x) (sqrt-iter-g good-enough? guess x)) (define (sqrt x) (sqrt-iter 1.0 x)) (display (sqrt SQRT-TEST)) (display " ") (display (sqrt-diff (sqrt SQRT-TEST) SQRT-TEST)) (newline)) '(eg1.1.7) '(ex1.7) (define (ex1.8) (display "ex1.8\n") (define (good-enough? guess x) (< (abs (- (* guess guess guess) x)) EPS)) (define (improve guess x) (/ (+ (/ x (* guess guess)) (* 2 guess)) 3)) (define (curt-iter guess x) (gen-iter good-enough? improve guess x)) (define (curt x) (curt-iter 1.0 x)) (display (curt 27))) (ex1.8)
false
7def7c22e1354d48258a3e743ce00b840cf585d1
ab1c64392121b3d38b42f43fe16d4ca98eed6b10
/nodes.scm
f376a189f16c14fe6a4994a9589078db476465f9
[]
no_license
vgeddes/scheme-compiler
c94cf68151944aecaa9635849376fe583dcea514
a2ac2d15e96a06d6d50133f516f424856e055cab
refs/heads/master
2020-05-17T23:59:32.592405
2012-11-27T09:41:33
2012-11-27T09:41:33
283,093
5
0
null
null
null
null
UTF-8
Scheme
false
false
1,411
scm
nodes.scm
;; ;; node types ;; (declare (unit nodes)) (include "struct-syntax") ;; HLIL: A basic lambda language (define-struct if (test conseq altern)) (define-struct lambda (name args body free-vars)) (define-struct comb (args)) (define-struct constant (value)) (define-struct variable (name)) (define-struct fix (defs body)) (define-struct prim (name args result cexp)) (define-struct nil ()) ;; LLIL: A mc executable language ;;; this language borrows <constant>, <variable> , and <if> from HLIL, for they have the same semantics at this level. ;;; A label for a block of code (define-struct label (name)) ;;; Function application. The compiler overloads this operation for primitive application. ;;; This operation never returns, but merely passes control to its continuation (define-struct app (name args)) ;;; Selects a value from a record and binds it to 'name in the continuation expression 'cexp (define-struct select (index record name cexp)) ;;; Creates a record from a list of values and binds it to 'name in cexp (define-struct record (values name cexp)) (define-struct block (label code)) (define-struct module (contexts)) (define-struct context (formals start blocks)) (define-struct arch-descriptor (make-context operand-format vregs-read vregs-written generate-bridge-context emit-statement))
false
cd848672cd705cbf427fd15d8419f24e3ace1fb2
958488bc7f3c2044206e0358e56d7690b6ae696c
/scheme/grammar.scm
c14ccac20c63345ced22ae9b159560291588061f
[]
no_license
possientis/Prog
a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4
d4b3debc37610a88e0dac3ac5914903604fd1d1f
refs/heads/master
2023-08-17T09:15:17.723600
2023-08-11T12:32:59
2023-08-11T12:32:59
40,361,602
3
0
null
2023-03-27T05:53:58
2015-08-07T13:24:19
Coq
UTF-8
Scheme
false
false
59
scm
grammar.scm
(require 'parse) (set! *syn-defs* *syn-ignore-whitespace*)
false
c25179bb539aa0ee9a4ac9d67c4a14172d28f7de
8f0c7a999b0cc7fdebd7df062aa5b14c8a809a08
/util/compat.chezscheme.sls
5d1ea5defb49711c5226f37fefff1a3a23bb0fdc
[ "BSD-3-Clause-Open-MPI" ]
permissive
sarvex/harlan-lang
7ab0eb7d0982848f68d0e5e67b12c27b91fdb34c
a361a1dc1312b3f4a46cb81c8d07852a70f67233
refs/heads/master
2023-06-13T03:07:01.753792
2023-05-30T16:03:27
2023-05-30T16:03:27
32,276,436
0
0
NOASSERTION
2023-05-30T16:03:28
2015-03-15T18:22:04
Scheme
UTF-8
Scheme
false
false
766
sls
compat.chezscheme.sls
;; -*- scheme -*- (library (util compat) (export directory-list format printf system unlink path-last path-root path-parent time with-output-to-string pretty-print make-parameter parameterize get-os) (import (chezscheme)) ;; Like system, but returns a string containing what the process ;; printed to stdout. (define (shell command) (let-values (((to-stdin from-stdout from-stderr proccess-id) (open-process-ports command 'block (native-transcoder)))) (get-string-all from-stdout))) (define (get-os) (let ((uname (shell "uname"))) (cond ((string=? uname "Darwin\n") 'darwin) ((string=? uname "Linux\n") 'linux) (else 'unknown)))) (define unlink delete-file))
false
b30267a537bbbaa73bc03c2824ab62ee9dc1ba00
ae4938300d7eea07cbcb32ea4a7b0ead9ac18e82
/iter/pipeline-extra.ss
e0a1a3ff1e87b49e5816b4e183e4973e90bd53fc
[]
no_license
keenbug/imi-libs
05eb294190be6f612d5020d510e194392e268421
b78a238f03f31e10420ea27c3ea67c077ea951bc
refs/heads/master
2021-01-01T19:19:45.036035
2012-03-04T21:46:28
2012-03-04T21:46:28
1,900,111
0
1
null
null
null
null
UTF-8
Scheme
false
false
320
ss
pipeline-extra.ss
#!r6rs (library (imi iter pipeline-extra) (export pipe-getn) (import (rnrs) (imi math) (imi iter pipeline)) (define (pipe-getn n) (if (zero? n) (pipeline '()) (pipeline x <- (pipe-get) rest <- (pipe-getn (sub1 n)) (cons x rest)))) )
false
e535a50bd04609eee263678c02dda98133c26502
defeada37d39bca09ef76f66f38683754c0a6aa0
/mscorlib/system/string.sls
58097f95557c80b8aef2e7996bb155f8b4374f62
[]
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
10,662
sls
string.sls
(library (system string) (export new is? string? intern to-lower-invariant get-hash-code trim insert index-of compare-ordinal last-index-of normalize replace index-of-any is-null-or-empty? to-string to-char-array split compare-to get-enumerator join to-upper-invariant last-index-of-any to-upper get-type-code contains? remove trim-start substring concat trim-end pad-right starts-with? is-normalized? is-interned to-lower format compare clone copy-to copy equals? pad-left ends-with? empty length) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.String a ...))))) (define (is? a) (clr-is System.String a)) (define (string? a) (clr-is System.String a)) (define-method-port intern System.String Intern (static: System.String System.String)) (define-method-port to-lower-invariant System.String ToLowerInvariant (System.String)) (define-method-port get-hash-code System.String GetHashCode (System.Int32)) (define-method-port trim System.String Trim (System.String System.Char[]) (System.String)) (define-method-port insert System.String Insert (System.String System.Int32 System.String)) (define-method-port index-of System.String IndexOf (System.Int32 System.String System.Int32 System.Int32) (System.Int32 System.String System.Int32) (System.Int32 System.String) (System.Int32 System.Char System.Int32 System.Int32) (System.Int32 System.Char System.Int32) (System.Int32 System.Char) (System.Int32 System.String System.Int32 System.Int32 System.StringComparison) (System.Int32 System.String System.Int32 System.StringComparison) (System.Int32 System.String System.StringComparison)) (define-method-port compare-ordinal System.String CompareOrdinal (static: System.Int32 System.String System.Int32 System.String System.Int32 System.Int32) (static: System.Int32 System.String System.String)) (define-method-port last-index-of System.String LastIndexOf (System.Int32 System.String System.Int32 System.Int32) (System.Int32 System.String System.Int32) (System.Int32 System.String) (System.Int32 System.Char System.Int32 System.Int32) (System.Int32 System.Char System.Int32) (System.Int32 System.Char) (System.Int32 System.String System.Int32 System.Int32 System.StringComparison) (System.Int32 System.String System.Int32 System.StringComparison) (System.Int32 System.String System.StringComparison)) (define-method-port normalize System.String Normalize (System.String System.Text.NormalizationForm) (System.String)) (define-method-port replace System.String Replace (System.String System.String System.String) (System.String System.Char System.Char)) (define-method-port index-of-any System.String IndexOfAny (System.Int32 System.Char[] System.Int32 System.Int32) (System.Int32 System.Char[] System.Int32) (System.Int32 System.Char[])) (define-method-port is-null-or-empty? System.String IsNullOrEmpty (static: System.Boolean System.String)) (define-method-port to-string System.String ToString (System.String System.IFormatProvider) (System.String)) (define-method-port to-char-array System.String ToCharArray (System.Char[] System.Int32 System.Int32) (System.Char[])) (define-method-port split System.String Split (System.String[] System.String[] System.StringSplitOptions) (System.String[] System.Char[] System.StringSplitOptions) (System.String[] System.String[] System.Int32 System.StringSplitOptions) (System.String[] System.Char[] System.Int32 System.StringSplitOptions) (System.String[] System.Char[] System.Int32) (System.String[] System.Char[])) (define-method-port compare-to System.String CompareTo (System.Int32 System.String) (System.Int32 System.Object)) (define-method-port get-enumerator System.String GetEnumerator (System.CharEnumerator)) (define-method-port join System.String Join (static: System.String System.String System.String[] System.Int32 System.Int32) (static: System.String System.String System.String[])) (define-method-port to-upper-invariant System.String ToUpperInvariant (System.String)) (define-method-port last-index-of-any System.String LastIndexOfAny (System.Int32 System.Char[] System.Int32 System.Int32) (System.Int32 System.Char[] System.Int32) (System.Int32 System.Char[])) (define-method-port to-upper System.String ToUpper (System.String System.Globalization.CultureInfo) (System.String)) (define-method-port get-type-code System.String GetTypeCode (System.TypeCode)) (define-method-port contains? System.String Contains (System.Boolean System.String)) (define-method-port remove System.String Remove (System.String System.Int32 System.Int32) (System.String System.Int32)) (define-method-port trim-start System.String TrimStart (System.String System.Char[])) (define-method-port substring System.String Substring (System.String System.Int32 System.Int32) (System.String System.Int32)) (define-method-port concat System.String Concat (static: System.String System.String[]) (static: System.String System.Object[]) (static: System.String System.String System.String System.String System.String) (static: System.String System.String System.String System.String) (static: System.String System.String System.String) (static: System.String System.Object System.Object System.Object) (static: System.String System.Object System.Object) (static: System.String System.Object)) (define-method-port trim-end System.String TrimEnd (System.String System.Char[])) (define-method-port pad-right System.String PadRight (System.String System.Int32 System.Char) (System.String System.Int32)) (define-method-port starts-with? System.String StartsWith (System.Boolean System.String System.Boolean System.Globalization.CultureInfo) (System.Boolean System.String System.StringComparison) (System.Boolean System.String)) (define-method-port is-normalized? System.String IsNormalized (System.Boolean System.Text.NormalizationForm) (System.Boolean)) (define-method-port is-interned System.String IsInterned (static: System.String System.String)) (define-method-port to-lower System.String ToLower (System.String System.Globalization.CultureInfo) (System.String)) (define-method-port format System.String Format (static: System.String System.IFormatProvider System.String System.Object[]) (static: System.String System.String System.Object[]) (static: System.String System.String System.Object System.Object System.Object) (static: System.String System.String System.Object System.Object) (static: System.String System.String System.Object)) (define-method-port compare System.String Compare (static: System.Int32 System.String System.Int32 System.String System.Int32 System.Int32 System.Globalization.CultureInfo System.Globalization.CompareOptions) (static: System.Int32 System.String System.String System.Globalization.CultureInfo System.Globalization.CompareOptions) (static: System.Int32 System.String System.Int32 System.String System.Int32 System.Int32 System.StringComparison) (static: System.Int32 System.String System.String System.StringComparison) (static: System.Int32 System.String System.Int32 System.String System.Int32 System.Int32 System.Boolean System.Globalization.CultureInfo) (static: System.Int32 System.String System.Int32 System.String System.Int32 System.Int32 System.Boolean) (static: System.Int32 System.String System.Int32 System.String System.Int32 System.Int32) (static: System.Int32 System.String System.String System.Boolean System.Globalization.CultureInfo) (static: System.Int32 System.String System.String System.Boolean) (static: System.Int32 System.String System.String)) (define-method-port clone System.String Clone (System.Object)) (define-method-port copy-to System.String CopyTo (System.Void System.Int32 System.Char[] System.Int32 System.Int32)) (define-method-port copy System.String Copy (static: System.String System.String)) (define-method-port equals? System.String Equals (System.Boolean System.String System.StringComparison) (static: System.Boolean System.String System.String System.StringComparison) (System.Boolean System.String) (System.Boolean System.Object) (static: System.Boolean System.String System.String)) (define-method-port pad-left System.String PadLeft (System.String System.Int32 System.Char) (System.String System.Int32)) (define-method-port ends-with? System.String EndsWith (System.Boolean System.String System.StringComparison) (System.Boolean System.String System.Boolean System.Globalization.CultureInfo) (System.Boolean System.String)) (define-field-port empty #f #f (static:) System.String Empty System.String) (define-field-port length #f #f (property:) System.String Length System.Int32))
true
fc3f6a771d639e82772c1efceb98b93016674bad
bdcc255b5af12d070214fb288112c48bf343c7f6
/slib-tests/rationalize-test.sps
bf569a71de69345da5d585c87ff165bb15e1568e
[]
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
491
sps
rationalize-test.sps
#!chezscheme (import (scheme base) (robin constants) (slib rationalize) (surfage s64 testing)) (test-begin "slib-rationalize") (test-equal '(22 7) (find-ratio PI 0.01)) (test-equal '(201 64) (find-ratio PI 0.001)) (test-equal '(333 106) (find-ratio PI 0.0001)) (test-equal '(355 113) (find-ratio PI 0.00001)) (test-equal '(3 97) (find-ratio 3/97 0.0001)) (test-equal '(1 32) (find-ratio 3/97 0.001)) (test-equal '(1 2) (find-ratio-between 2/7 3/5)) (test-end)
false
ddfb79691863db934fd9b839a615d575eeaaccb1
41463d53f24660cae8b0212349ead9eae590e79e
/scheme/19/15.ss
9a5a6143ee4c9f400582011e251e1c7178573aa0
[]
no_license
jitwit/aoc
a3bc02ca43af6ac23bf2e5ea0a422ecd236c466f
473af1d25919514f423c2937e088d549421fe045
refs/heads/a
2023-02-05T08:15:21.340125
2023-01-30T01:41:50
2023-01-30T01:41:50
222,753,516
23
5
null
2020-12-08T19:36:52
2019-11-19T17:37:10
Scheme
UTF-8
Scheme
false
false
2,443
ss
15.ss
(load "~/code/aoc/load.ss") (advent-year 19) (advent-day 15) (define program (with-input-from-file (advent-file) parse-intcode)) (define proggl (with-input-from-file "gl15.txt" parse-intcode)) (define-values (north south east west) (values 1 2 4 3)) (define-values (wall moved oxygen-system) (values 0 1 2)) (define (dir->instr z) (match z (1 east) (-1 west) (0+i north) (0-i south))) (define (fps->duration fps) (make-time 'time-duration (ceiling (/ (expt 10 9) fps)) 0)) (define (explore program animated? fps) (define world (make-eqv-hashtable)) (define part-a #f) (define tank #f) (let walk ((Q (q:snocq q:empty (list 0 0 (intcode program))))) (if (q:empty? Q) (values part-a (apply max (vector->list (hashtable-values (bfs-result-distances (bfs tank (lambda (z) (filter (lambda (z) (memq (hashtable-ref world z 'idk) '(open tank))) (grid4 z))))))))) (match (q:headq Q) ((d x droid) (when animated? (newline) (showme world x) (newline) (sleep (fps->duration fps))) (let ((d (+ d 1))) (let adj ((zs (grid4 x)) (Q (q:tailq Q))) (match zs (() (walk Q)) ((z zs ...) (if (hashtable-ref world z #f) (adj zs Q) (let ((droid (fork-intcode droid))) (send-input droid (dir->instr (- z x))) (run-until-halt droid) (match (read-output droid) ((0) (hashtable-set! world z 'wall) (adj zs Q)) ((1) (hashtable-set! world z 'open) (adj zs (q:snocq Q (list d z droid)))) ((2) (hashtable-set! world z 'tank) (set! part-a d) (set! tank z) (adj zs (q:snocq Q (list d z droid)))) (else (error 'oops "no output or something" out)))))))))))))) (define (showme g loc) (define-values (xlo xhi ylo yhi) (bounding-box-C (cons 0 (vector->list (hashtable-keys g))))) (do ((i (1- xlo) (1+ i))) ((> i (1+ xhi))) (do ((j (1- ylo) (1+ j))) ((> j (1+ yhi)) (newline)) (let ((z (make-rectangular i j))) (cond ((eqv? z loc) (display-with-foreground 'red #\@)) (else (match (hashtable-ref g (make-rectangular i j) 'idk) ('idk (display-with-foreground 'blue #\?)) ('wall (display-with-foreground 'green #\#)) ('open (display #\space)) ('tank (display-with-foreground 'red #\O)))))))))
false
e5e0b1a4c25777a3a360b9d736c85bebecf8eea2
2c01a6143d8630044e3629f2ca8adf1455f25801
/xitomatl/ssax/tree-trans.sls
554e56651826f0b5eba7db6d1c1eca87deb3b276
[ "X11-distribute-modifications-variant" ]
permissive
stuhlmueller/scheme-tools
e103fac13cfcb6d45e54e4f27e409adbc0125fe1
6e82e873d29b34b0de69b768c5a0317446867b3c
refs/heads/master
2021-01-25T10:06:33.054510
2017-05-09T19:44:12
2017-05-09T19:44:12
1,092,490
5
1
null
null
null
null
UTF-8
Scheme
false
false
18
sls
tree-trans.sls
tree-trans-5-1.sls
false
9ac87636e608970b7e30f5700af6393704770124
d14c5f2658ea33cf9c83b249f8560a8657377767
/lib/chibi/base64.sld
fe43b20209286806eeea2e73156731223a163f03
[ "BSD-3-Clause" ]
permissive
gypified/chibi-scheme
1a805420c835a24b2a2ab71309e7b386c3f64e6c
2e9a701b8c46c279514e565776bbe83b637fff06
refs/heads/master
2021-01-19T14:33:54.664110
2013-10-05T19:14:38
2013-10-05T19:58:51
13,280,620
2
0
null
null
null
null
UTF-8
Scheme
false
false
220
sld
base64.sld
(define-library (chibi base64) (export base64-encode base64-encode-string base64-decode base64-decode-string base64-encode-header) (import (chibi) (srfi 33) (chibi io)) (include "base64.scm"))
false
c704f7098944960d3c58bb638280a7d64c5bb5cf
aa0102609ec43e4bd4319b90b65a3125e5c2162a
/6.ss
0f3f4cf0059429d6655f8a8e3e23daf2675cc5da
[]
no_license
Joycexuy2/Code
9d91dfb9a745d0b9ec51428444e6a4e4491470ec
ed82f0a2cc7b6acf7787e86906f9e2bc5b0142f2
refs/heads/master
2021-05-03T18:19:42.294545
2016-10-25T22:28:35
2016-10-25T22:28:35
71,944,295
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,106
ss
6.ss
;Name: Fangyuan Wang ;Assignment 6 ;#1 (define curry2 [lambda (p) (lambda (x) (lambda (y) (p x y)))]) ;#2 (define curried-compose [lambda (p) (lambda (x) (lambda (y) (p (x y))))]) ;#3 (define compose [lambda L (lambda (x) (if [null? (cdr L)] [(car L) x] [(car L) ((apply compose (cdr L)) x)]))]) ;#4 (define make-list-c [lambda (n) (lambda (ls) (if [zero? n] '() (cons ls ((make-list-c (- n 1)) ls))))]) ;#5 helper method ;to get the list of the value of input parameters (define get-list-of-values [lambda (ls) (map cadr ls)]) ;#5 helper method ;to get the list of variables (define get-list-of-variables [lambda (ls) (map car ls)]) ;#5 helper method (define get-application [lambda (ls) (append '(lambda) (cons (get-list-of-variables (cadr ls)) (cddr ls)))]) ;#5 (define let->application [lambda (ls) (cons (get-application ls) (get-list-of-values (cadr ls)))]) ;#6 helper method (define expand-let [lambda (ls newls) (if [null? (cdr ls)] (list 'let ls newls) (list 'let (list (car ls)) (expand-let (cdr ls) newls)))]) ;#6 (define let*->let [lambda (ls) (expand-let (cadr ls) (caddr ls))]) ;#7 (define filter-in [lambda (pred? ls) (if [null? ls] '() (filter pred? ls))]) ;#8 (define filter-out [lambda (pred? ls) (remp pred? ls)]) ;#9 (define sort-list-of-symbols [lambda (ls) (map string->symbol (list-sort string<? (map symbol->string ls)))]) ;#10 helper method ;return the new list (define invert-helper [lambda (ls newls) (if [null? ls] newls (let ((first (caar ls)) (second (cadar ls))) (invert-helper (cdr ls) (append newls (list (cons second (list first)))))))]) ;#10 (define invert [lambda (ls) (invert-helper ls '())]) ;#11 helper method (define get-vec-index [lambda (i pro ls) (if [null? ls] #f (if [pro (car ls)] i (get-vec-index (+ 1 i) pro (cdr ls))))]) ;#11 (define vector-index [lambda (pro vec) (get-vec-index 0 pro (vector->list vec))])
false
53b2d591938aab2006b441646a3a3e5dfcc9f442
defeada37d39bca09ef76f66f38683754c0a6aa0
/System.Xml/mono/xml/dtdatt-list-declaration-collection.sls
6d8af190a53ba19485f75fdbd40ced76615b39f3
[]
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
780
sls
dtdatt-list-declaration-collection.sls
(library (mono xml dtdatt-list-declaration-collection) (export new is? dtdatt-list-declaration-collection? add item) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new Mono.Xml.DTDAttListDeclarationCollection a ...))))) (define (is? a) (clr-is Mono.Xml.DTDAttListDeclarationCollection a)) (define (dtdatt-list-declaration-collection? a) (clr-is Mono.Xml.DTDAttListDeclarationCollection a)) (define-method-port add Mono.Xml.DTDAttListDeclarationCollection Add (System.Void System.String Mono.Xml.DTDAttListDeclaration)) (define-field-port item #f #f (property:) Mono.Xml.DTDAttListDeclarationCollection Item Mono.Xml.DTDAttListDeclaration))
true
16efe928da18c44bf9222eef8dd85068284042c1
614f19affc17608380f8c9306b1b9abc2639bae4
/packages/gxjs-tests/gambit-scheme-usage.scm
fe1d5beb371ba3b0d3a23a9cb05df6901aaccceb
[ "Apache-2.0" ]
permissive
drewc/gxjs
04e744310b79fef437c7ca76deedf67a25fb067a
4987bc66bb301b2d1d006a433888c5ad04e3f978
refs/heads/main
2023-04-21T01:09:10.810675
2021-05-09T18:48:31
2021-05-09T18:48:31
324,202,474
16
2
null
null
null
null
UTF-8
Scheme
false
false
558
scm
gambit-scheme-usage.scm
(declare (extended-bindings)) (##inline-host-declaration "console.log('Started Gambit loaded file!')") (define gambit-vector (##vector 42 'this "is how we hake the moonshine")) (define (this-is-gambit! #!optional (val 42)) (let ((three (##inline-host-expression "{ answer: 42 };"))) (##inline-host-statement "console.log('This is Gambit!', (@1@), (@2@), (@3@))" val gambit-vector three))) (##inline-host-statement "console.log('finished Gambit-loaded file'); module.exports = RTS.scm2host(@1@);" this-is-gambit!)
false
b5590c374768ea0fc01efdcb0204bdebecd2b0a9
0bdfa3fdb0467776e4e06a41c683b01d2b8902fd
/src/beginner-to-java.ss
c839f970e25ae6532a5338d80204d912cf6ca9e2
[]
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
19,011
ss
beginner-to-java.ss
#lang scheme/base ;; This program translates beginner-level languages into Java source. ;; We pattern match against the language given by: ;; ;; http://docs.plt-scheme.org/htdp-langs/beginner.html (require scheme/match scheme/list scheme/string scheme/contract "env.ss" "toplevel.ss" "pinfo.ss" "helpers.ss") ;; A compiled program is a: (define-struct compiled-program (defns ;; (listof string) toplevel-exprs ;; (listof string) pinfo ;; pinfo )) ;; program->java-string: program -> compiled-program ;; Consumes a program and returns a compiled program. (define (program->java-string program) (let* ([a-pinfo (program-analyze program)] [toplevel-env (pinfo-env a-pinfo)]) (let loop ([program program] [defns ""] [tops ""]) (cond [(empty? program) (make-compiled-program defns tops a-pinfo)] [else (cond [(defn? (first program)) (let-values ([(defn-string expr-string) (definition->java-strings (first program) toplevel-env)]) (loop (rest program) (string-append defns "\n" defn-string) (string-append tops "\n" expr-string)))] [(test-case? (first program)) (loop (rest program) (string-append defns "\n" "// Test case erased\n") tops)] [(library-require? (first program)) (loop (rest program) (string-append defns "\n" "// Module require erased\n") tops)] [(expression? (first program)) (loop (rest program) defns (string-append tops "\n" "org.plt.Kernel.identity(" (expression->java-string (first program) toplevel-env) ");"))])])))) ;; definition->java-string: definition env -> (values string string) ;; Consumes a definition (define or define-struct) and produces two strings. ;; The first maps a definitions string. ;; The second value is the expression that will be evaluated at the toplevel. ;; ;; Structure definitions map to static inner classes with transparent fields. (define (definition->java-strings defn env) (match defn [(list 'define (list fun args ...) body) (values (function-definition->java-string fun args body env) "")] [(list 'define (? symbol? fun) (list 'lambda (list args ...) body)) (values (function-definition->java-string fun args body env) "")] [(list 'define (? symbol? id) body) (variable-definition->java-strings id body env)] [(list 'define-struct id (list fields ...)) (values (struct-definition->java-string id fields env) "")])) ;; function-definition->java-string: symbol (listof symbol) expr env -> string ;; Converts the function definition into a static function declaration whose ;; return value is an object. (define (function-definition->java-string fun args body env) (let* ([munged-fun-id (identifier->munged-java-identifier fun)] [munged-arg-ids (map identifier->munged-java-identifier args)] [new-env (env-extend env (make-binding:function fun #f (length args) #f (symbol->string munged-fun-id) empty))] [new-env (foldl (lambda (arg-id env) (env-extend env (make-binding:constant arg-id (symbol->string (identifier->munged-java-identifier arg-id)) empty))) new-env args)]) (format "static public Object ~a(~a) { return ~a; }" munged-fun-id (string-join (map (lambda (arg-id) (string-append "Object " (symbol->string arg-id))) munged-arg-ids) ", ") (expression->java-string body new-env)))) ;; variable-definition->java-string: symbol expr env -> (values string string) ;; Converts the variable definition into a static variable declaration and its ;; initializer at the toplevel. (define (variable-definition->java-strings id body env) (let* ([munged-id (identifier->munged-java-identifier id)] [new-env (env-extend env (make-binding:constant id (symbol->string munged-id) empty))]) (values (format "static Object ~a; " munged-id) (format "~a = ~a;" munged-id (expression->java-string body new-env))))) ;; struct-definition->java-string: symbol (listof symbol) env -> string (define (struct-definition->java-string id fields env) ;; field->accessor-name: symbol symbol -> symbol ;; Given a structure name and a field, return the accessor. (define (field->accessor-name struct-name field-name) (string->symbol (string-append (symbol->string struct-name) "-" (symbol->string field-name)))) (format "static public class ~a implements org.plt.types.Struct { ~a \n ~a\n ~a\n}\n~a \n ~a\n ~a" (identifier->munged-java-identifier id) (string-join (map (lambda (a-field) (format "public Object ~a;" (identifier->munged-java-identifier a-field))) fields) "\n") ;; default constructor (format "public ~a(~a) { ~a }" (identifier->munged-java-identifier id) (string-join (map (lambda (i) (format "Object ~a" (identifier->munged-java-identifier i))) fields) ",") (string-join (map (lambda (i) (format "this.~a = ~a;" (identifier->munged-java-identifier i) (identifier->munged-java-identifier i))) fields) "\n")) ;; equality (format "public boolean equals(Object other) { if (other instanceof ~a) { return ~a.isTrue(); } else { return false; } } " (identifier->munged-java-identifier id) (expression->java-string (foldl (lambda (a-field acc) (let ([acc-id (field->accessor-name id a-field)]) `(and (equal? (,acc-id this) (,acc-id other)) ,acc))) 'true fields) (let* ([new-env (env-extend env (make-binding:constant 'this (symbol->string (identifier->munged-java-identifier 'this)) empty))] [new-env (env-extend new-env (make-binding:constant 'other (symbol->string (identifier->munged-java-identifier 'other)) empty))]) new-env))) ;; make-id (format "static public Object ~a(~a) { return new ~a(~a); }" (let ([make-id (string->symbol (string-append "make-" (symbol->string id)))]) (identifier->munged-java-identifier make-id)) (string-join (build-list (length fields) (lambda (i) (format "Object id~a" i))) ",") (identifier->munged-java-identifier id) (string-join (build-list (length fields) (lambda (i) (format "id~a" i))) ",")) ;; accessors (string-join (map (lambda (a-field) (format "static public Object ~a(Object obj) { return ((~a)obj).~a; }" (let ([acc-id (string->symbol (string-append (symbol->string id) "-" (symbol->string a-field)))]) (identifier->munged-java-identifier acc-id)) (identifier->munged-java-identifier id) (identifier->munged-java-identifier a-field))) fields) "\n") ;; predicate (format "static public org.plt.types.Logic ~a(Object obj) { return obj instanceof ~a ? org.plt.types.Logic.TRUE : org.plt.types.Logic.FALSE; }" (identifier->munged-java-identifier (string->symbol (format "~a?" id))) (identifier->munged-java-identifier id)))) ;; expression->java-string: expr env -> string ;; Translates an expression into a Java expression string whose evaluation ;; should produce an Object. (define (expression->java-string expr env) (match expr [(list 'cond [list questions answers] ... [list 'else answer-last]) (let loop ([questions questions] [answers answers]) (cond [(empty? questions) (expression->java-string answer-last env)] [else (format "(((org.plt.types.Logic)(~a)).isTrue() ? (~a) : (~a))" (expression->java-string (first questions) env) (expression->java-string (first answers) env) (loop (rest questions) (rest answers)))]))] [(list 'cond [list questions answers] ... [list question-last answer-last]) (let loop ([questions questions] [answers answers]) (cond [(empty? questions) (format "(((org.plt.types.Logic)(~a)).isTrue() ? (~a) : org.plt.Kernel.error(org.plt.types.Symbol.makeInstance(\"cond\"), \"Fell out of cond\"))" (expression->java-string question-last env) (expression->java-string answer-last env))] [else (format "(((org.plt.types.Logic)(~a)).isTrue() ? (~a) : (~a))" (expression->java-string (first questions) env) (expression->java-string (first answers) env) (loop (rest questions) (rest answers)))]))] [(list 'if test consequent alternative) (format "(((org.plt.types.Logic)(~a)).isTrue() ? (~a) : (~a))" (expression->java-string test env) (expression->java-string consequent env) (expression->java-string alternative env))] [(list 'and expr ...) (string-append "((" (string-join (map (lambda (e) (format "(((org.plt.types.Logic)~a).isTrue())" (expression->java-string e env))) expr) "&&") ") ? org.plt.types.Logic.TRUE : org.plt.types.Logic.FALSE)")] [(list 'or expr ...) (string-append "((" (string-join (map (lambda (e) (format "(((org.plt.types.Logic)~a).isTrue())" (expression->java-string e env))) expr) "||") ") ? org.plt.types.Logic.TRUE : org.plt.types.Logic.FALSE)")] ;; Numbers [(? number?) (number->java-string expr)] ;; Strings [(? string?) (format "(new String(~s))" expr)] ;; Characters [(? char?) (string-append "(new Character(\"" (if (char=? expr #\") "\\" (string expr)) "\"))")] ;; Identifiers [(? symbol?) (identifier-expression->java-string expr env)] ;; Quoted symbols [(list 'quote datum) (format "(org.plt.types.Symbol.makeInstance(\"~a\"))" datum)] ;; Function call/primitive operation call [(list (? symbol? id) exprs ...) (application-expression->java-string id exprs env)])) ;; application-expression->java-string: symbol (listof expr) env -> string ;; Converts the function application to a string. (define (application-expression->java-string id exprs env) (let ([operator-binding (env-lookup env id)] [operand-strings (map (lambda (e) (expression->java-string e env)) exprs)]) (match operator-binding ['#f (error 'application-expression->java-string "Moby doesn't know about ~s" id)] [(struct binding:constant (name java-string permissions)) (format "(((org.plt.types.Callable) ~a).call(new Object[] {~a}))" java-string (string-join operand-strings ", "))] [(struct binding:function (name module-path min-arity var-arity? java-string permissions)) (unless (>= (length exprs) min-arity) (error 'application-expression->java-string "Minimal arity of ~s not met. Operands were ~s" id exprs)) (cond [var-arity? (cond [(> min-arity 0) (format "~a(~a, new Object[] {~a})" java-string (string-join (take operand-strings min-arity) ",") (string-join (list-tail operand-strings min-arity) ","))] [else (format "~a(new Object[] {~a})" java-string (string-join (list-tail operand-strings min-arity) ","))])] [else (format "(~a(~a))" java-string (string-join operand-strings ","))])]))) ;; identifier-expression->java-string: symbol -> string ;; Translates the use of a toplevel identifier to the appropriate ;; Java code. (define (identifier-expression->java-string an-id an-env) (match (env-lookup an-env an-id) ['#f (error 'translate-toplevel-id "Moby doesn't know about ~s." an-id)] [(struct binding:constant (name java-string permissions)) java-string] [(struct binding:function (name module-path min-arity var-arity? java-string permissions)) (cond [var-arity? (format "(new org.plt.types.Callable() { public Object call(Object[] args) { return ~a(args); } })" java-string)] [else (format "(new org.plt.types.Callable() { public Object call(Object[] args) { return ~a(~a); } })" java-string (string-join (for/list ([i (in-range min-arity)]) (format "args[~a]" i)) ", "))]) #;(error 'translate-toplevel-id "Moby doesn't yet allow higher-order use of ~s." an-id)])) ;; number->java-string: number -> string (define (number->java-string a-num) (cond [(integer? a-num) ;; Fixme: we need to handle exact/vs/inexact issue. ;; We probably need the numeric tower. (format "(new org.plt.types.Rational(~a, 1))" (inexact->exact a-num))] [(and (inexact? a-num) (real? a-num)) (format "(org.plt.types.FloatPoint.fromString(\"~s\"))" a-num)] [(rational? a-num) (format "(new org.plt.types.Rational(~s, ~s))" (numerator a-num) (denominator a-num))] [(complex? a-num) (format "(new org.plt.types.Complex(~a, ~a))" (number->java-string (real-part a-num)) (number->java-string (imag-part a-num)))] [else (error 'number->java-string "Don't know how to handle ~s yet" a-num)])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (provide/contract [struct compiled-program ([defns string?] [toplevel-exprs string?] [pinfo pinfo?])] [program->java-string (program? . -> . compiled-program?)] [expression->java-string (expression? env? . -> . string?)])
false
42e0fc46dc7d629716e7f4dfbe4fa0cf4e23e514
d074b9a2169d667227f0642c76d332c6d517f1ba
/sicp/ch_5/exercise.5.50.scm
361d88e458e5c3005f05bebbc951ed0a45dc2564
[]
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
4,386
scm
exercise.5.50.scm
#!/usr/bin/env csi -s (require rackunit) (require-library compiler) (import compiler) ;;; Exercise 5.50 ;; Use the compiler to compile the metacircular evaluator of section ;; *Note 4-1:: and run this program using the register-machine ;; simulator. (To compile more than one definition at a time, you can ;; package the definitions in a `begin'.) The resulting interpreter ;; will run very slowly because of the multiple levels of ;; interpretation, but getting all the details to work is an ;; instructive exercise. (define eval-sexp #f) (with-input-from-file "lib/eval.scm" (lambda () (set! eval-sexp (drop (read) 5)))) (append-primitive-procedures '< < 'caar caar 'cadddr cadddr 'caddr caddr 'cadr cadr 'cddr cddr 'eof-object? eof-object? 'error error 'list list 'not not 'number? number? 'pair? pair? 'set-car! set-car! 'set-cdr! set-cdr! 'string? string? 'symbol? symbol? 'zip zip) (define (test-sexp exp) (append '(begin) (append eval-sexp `((define my-env (setup-environment)) (eval ,exp my-env))))) (test-group "holy crap I'm done!" (assert-compile 42 (test-sexp '42)) (assert-compile 24 (test-sexp '24)) (assert-compile #t (test-sexp 'true)) (assert-compile #f (test-sexp 'false)) (assert-compile 3 (test-sexp '(+ 1 2))) (assert-compile 120 (test-sexp '(* 1 2 3 4 5))) (assert-compile "good" (test-sexp '(begin (define (append x y) (if (null? x) y (cons (car x) (append (cdr x) y)))) (let ((l (append '(a b c) '(d e f)))) (cond ((eq? (length l) 5) "bad") ((eq? (length l) 6) "good") (else 'else)))))) ;; HACK; prolly should be '*undefined* or somesuch (assert-compile #f (test-sexp '(begin (define (append x y) (if (null? x) y (cons (car x) (append (cdr x) y)))) (let ((l (append '(a b c) '(d)))) (cond ((eq? (length l) 5) "bad") ((eq? (length l) 6) "good")))))) (assert-compile "else" (test-sexp '(begin (define (append x y) (if (null? x) y (cons (car x) (append (cdr x) y)))) (let ((l (append '(a b c) '(d)))) (cond ((eq? (length l) 5) "bad") ((eq? (length l) 6) "good") (else "else")))))) (assert-compile 120 (test-sexp '(begin (define (factorial-r n) (if (= n 1) 1 (* (factorial-r (- n 1)) n))) (factorial-r 5)))) (assert-compile 120 (test-sexp '(begin (define (factorial-i n) (define (iter product counter) (if (> counter n) product (iter (* counter product) (+ counter 1)))) (iter 1 1)) (factorial-i 5)))) (assert-compile 55 (test-sexp '(begin (define (fib n) (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))) (fib 10)))))
false
aa15bae9662e961006343e79a58c5cb2ec0a2df0
f05faa71d7fef7301d30fb8c752f726c8b8c77d4
/src/exercises/ex-1.10.scm
bd9da3c2b7dec6ced2c5039c4b44939336b623c4
[]
no_license
yamad/sicp
c9e8a53799f0ca6f02b47acd23189b2ca91fe419
11e3a59f41ed411814411e80f17606e49ba1545a
refs/heads/master
2021-01-21T09:53:44.834639
2017-02-27T19:32:23
2017-02-27T19:32:23
83,348,438
1
0
null
null
null
null
UTF-8
Scheme
false
false
2,027
scm
ex-1.10.scm
#!/usr/bin/env mzscheme #lang scheme ;; ex 1.10 ;; ------- ;; Given: Ackerman's function (define (A x y) (cond ((= y 0) 0) ((= x 0) (* 2 y)) ((= y 1) 2) (else (A (- x 1) (A x (- y 1)))))) (A 1 10) (A 0 (A 1 9)) (A 0 (A 0 (A 1 8))) (A 0 (A 0 (A 0 (A 1 7)))) (A 0 (A 0 (A 0 (A 0 (A 1 6))))) (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 5)))))) (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 4))))))) (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 3)))))))) (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 2))))))))) (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 1)))))))))) (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 2))))))))) (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (* 2 2))))))))) (* 2 (* 2 (* 2 (* 2 (* 2 (* 2 (* 2 (* 2 (* 2 2))))))))) (* 2 (* 2 (* 2 (* 2 (* 2 (* 2 (* 2 (* 2 4)))))))) (* 2 (* 2 (* 2 (* 2 (* 2 (* 2 (* 2 8))))))) (* 2 (* 2 (* 2 (* 2 (* 2 (* 2 16)))))) (* 2 (* 2 (* 2 (* 2 (* 2 32))))) (* 2 (* 2 (* 2 (* 2 64)))) (* 2 (* 2 (* 2 128))) (* 2 (* 2 256)) (* 2 512) 1024 (A 2 4) (A 1 (A 2 3)) (A 1 (A 1 (A 2 2))) (A 1 (A 1 (A 1 (A 2 1)))) (A 1 (A 1 (A 1 2))) (A 1 (A 1 (A 0 (A 1 1)))) (A 1 (A 1 (A 0 2))) (A 1 (A 1 (* 2 2))) (A 1 (A 1 4)) (A 1 (A 0 (A 1 3))) (A 1 (A 0 (A 0 (A 1 2)))) (A 1 (A 0 (A 0 (A 0 (A 1 1))))) (A 1 (A 0 (A 0 (A 0 2)))) (A 1 (A 0 (A 0 (* 2 2)))) (A 1 (A 0 (A 0 4))) (A 1 (A 0 (* 2 4))) (A 1 (A 0 8)) (A 1 (* 2 8)) (A 1 16) 65536 (A 3 3) (A 2 (A 3 2)) (A 2 (A 2 (A 3 1))) (A 2 (A 2 2)) (A 2 (A 1 (A 2 1))) (A 2 (A 1 2)) (A 2 (A 0 (A 1 1))) (A 2 (A 0 2)) (A 2 (* 2 2)) (A 2 4) (A 1 (A 2 3)) (A 1 (A 1 (A 2 2))) (A 1 (A 1 (A 1 (A 2 1)))) (A 1 (A 1 (A 1 2))) (A 1 (A 1 (A 0 (A 1 1)))) (A 1 (A 1 (A 0 2))) (A 1 (A 1 (* 2 2))) (A 1 (A 1 4)) (A 1 (A 0 (A 1 3))) (A 1 (A 0 (A 0 (A 1 2)))) (A 1 (A 0 (A 0 (A 0 (A 1 1))))) (A 1 (A 0 (A 0 (A 0 2)))) (A 1 (A 0 (A 0 (* 2 2)))) (A 1 (A 0 (* 2 4))) (A 1 (* 2 8)) (A 1 16) 65536 (define (f n) (A 0 n)) ;; calculates 2n (define (g n) (A 1 n)) ;; calculates 2^{n} (define (h n) (A 2 n)) ;; calculates 2^{h(n-1)} or 2^2^\ldots (n times)
false
74dfc79a3c254baad35af5f313f345295f847f15
d8bdd07d7fff442a028ca9edbb4d66660621442d
/scam/tests/10-scheme/00-base/pred/type-check/char.scm
e6caeeca22d7fb382d161753d0a737cbb5f2e018
[]
no_license
xprime480/scam
0257dc2eae4aede8594b3a3adf0a109e230aae7d
a567d7a3a981979d929be53fce0a5fb5669ab294
refs/heads/master
2020-03-31T23:03:19.143250
2020-02-10T20:58:59
2020-02-10T20:58:59
152,641,151
0
0
null
null
null
null
UTF-8
Scheme
false
false
244
scm
char.scm
(import (only (scheme base) char?) (test narc)) (narc-label "Type Checker of Characters") (narc-expect (#t (char? #\a)) (#f (char? "a-string")) (#f (char? 2))) (narc-catch (:args (char?)) (:args (char? #\a #\b))) (narc-report)
false
f1c94afb76a11b69ae1bdc363cad6ebcb5adafdc
62e965102ca2309ff17693466e5c57eba4c5624f
/unused/tests-2.8-req.scm
ef7e05a586c286cd21bf044f903e0236b422ee85
[]
no_license
goelankitt/inc
e398a25087abf687de929e569103f3dc45bac27a
bd5b0533df78f0967b34bc4a0c9f3ac44b01255b
refs/heads/master
2021-08-23T01:46:14.157357
2017-12-02T07:57:01
2017-12-02T07:59:48
112,823,030
1
0
null
null
null
null
UTF-8
Scheme
false
false
602
scm
tests-2.8-req.scm
(add-tests-with-string-output "symbols" [(symbol? 'foo) => "#t"] [(symbol? '()) => "#f"] [(symbol? "") => "#f"] [(symbol? '(1 2)) => "#f"] [(symbol? '#()) => "#f"] [(symbol? (lambda (x) x)) => "#f"] [(symbol? 'foo) => "#t"] [(string? 'foo) => "#f"] [(pair? 'foo) => "#f"] [(vector? 'foo) => "#f"] [(null? 'foo) => "#f"] [(boolean? 'foo) => "#f"] [(procedure? 'foo) => "#f"] [(eq? 'foo 'bar) => "#f"] [(eq? 'foo 'foo) => "#t"] ['foo => "foo"] ['(foo bar baz) => "(foo bar baz)"] ['(foo foo foo foo foo foo foo foo foo foo foo) => "(foo foo foo foo foo foo foo foo foo foo foo)"] )
false
6701d9c29ec157738987925959caded1a0bde7d4
b14c18fa7a4067706bd19df10f846fce5a24c169
/Chapter2/2.49.scm
a9366abf117de279fd4b077834b1aaf45efb1b1e
[]
no_license
silvesthu/LearningSICP
eceed6267c349ff143506b28cf27c8be07e28ee9
b5738f7a22c9e7967a1c8f0b1b9a180210051397
refs/heads/master
2021-01-17T00:30:29.035210
2016-11-29T17:57:16
2016-11-29T17:57:16
19,287,764
3
0
null
null
null
null
UTF-8
Scheme
false
false
2,712
scm
2.49.scm
#lang scheme ;(require (planet "sicp.ss" ("soegaard" "sicp.plt" 2 1))) (define (make-vect x y) (cons x y)) (define (xcor-vect v) (car v)) (define (ycor-vect v) (cdr v)) (define (add-vect v1 v2) (make-vect (+ (xcor-vect v1) (xcor-vect v2)) (+ (ycor-vect v1) (ycor-vect v2)))) (define (sub-vect v1 v2) (make-vect (- (xcor-vect v1) (xcor-vect v2)) (- (ycor-vect v1) (ycor-vect v2)))) (define (scale-vect s v) (make-vect (* (xcor-vect v) s) (* (ycor-vect v) s))) (define (make-segment v1 v2) (cons v1 v2)) (define (start-segment s) (car s)) (define (end-segment s) (cdr s)) (define (make-frame origin edge1 edge2) (list origin edge1 edge2)) (define (origin-frame frame) (car frame)) (define (edge1-frame frame) (cadr frame)) (define (edge2-frame frame) (caddr frame)) (define (frame-coord-map frame) (lambda (v) (add-vect (origin-frame frame) (add-vect (scale-vect (xcor-vect v) (edge1-frame frame)) (scale-vect (ycor-vect v) (edge2-frame frame)))))) (define (draw-line v1 v2) (display "drawing ") (display v1) (display "\t->\t") (display v2) (newline)) (define (segments->painter segment-list) (lambda (frame) (for-each (lambda (segment) (draw-line ((frame-coord-map frame) (start-segment segment)) ((frame-coord-map frame) (end-segment segment)))) segment-list))) ; helper (define (p0) (make-vect 0 0)) (define (p1) (make-vect 1 0)) (define (p2) (make-vect 0 1)) (define (p3) (make-vect 1 1)) (define (mid-vect v1 v2) (scale-vect (add-vect v1 v2) 0.5)) (define (draw-frame frame) ((segments->painter (list (make-segment (p0) (p1)) (make-segment (p0) (p2)) (make-segment (p3) (p1)) (make-segment (p3) (p2)) ) ) frame) ) (define (draw-x frame) ((segments->painter (list (make-segment (p0) (p3)) (make-segment (p1) (p2)) ) ) frame) ) (define (mid01) (mid-vect (p0) (p1))) (define (mid02) (mid-vect (p0) (p2))) (define (mid31) (mid-vect (p3) (p1))) (define (mid32) (mid-vect (p3) (p2))) (define (draw-diamond frame) (segments->painter (list (make-segment (mid01) (mid02)) (make-segment (mid01) (mid31)) (make-segment (mid02) (mid32)) (make-segment (mid31) (mid32)) ) ) ) (define (make-segment-xy x1 y1 x2 y2) (make-segment (make-vect x1 y1) (make-vect x2 y2) ) ) (define (draw-wave frame) ((segments->painter (list ; left arm (make-segment-xy 0 0.6 0.1 0.4) (make-segment-xy 0.3 0.56 0.1 0.4) (make-segment-xy 0.3 0.56 0.4 0.5) (make-segment-xy 0 0.85 0.1 0.6) (make-segment-xy 0.3 0.6 0.1 0.6) (make-segment-xy 0.3 0.6 0.45 0.6) ; blabla.. ) ) frame) ) (draw-wave (make-frame (make-vect 0 0) (make-vect 1 0) (make-vect 0 1)))
false
bbba3da9851f013890707f27a339df48f4549cbf
a66514d577470329b9f0bf39e5c3a32a6d01a70d
/sdl2/ttf-functions.ss
1417c74abd157a5fc4c0885e9d23cae69ced55c7
[ "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
5,264
ss
ttf-functions.ss
(define-sdl-func (* sdl-version-t) ttf-linked-version () "TTF_Linked_Version") (define-sdl-func void ttf-byte-swapped-unicode ((swapped int)) "TTF_ByteSwappedUNICODE") (define-sdl-func int ttf-init () "TTF_Init") (define-sdl-func (* ttf-font) ttf-open-font ((file string) (ptsize int)) "TTF_OpenFont") (define-sdl-func (* ttf-font) ttf-open-font-index ((file string) (ptsize int) (index long)) "TTF_OpenFontIndex") (define-sdl-func (* ttf-font) ttf-open-font-rw ((src (* sdl-rw-ops-t)) (freesrc int) (ptsize int)) "TTF_OpenFontRW") (define-sdl-func (* ttf-font) ttf-open-font-index-rw ((src (* sdl-rw-ops-t)) (freesrc int) (ptsize int) (index long)) "TTF_OpenFontIndexRW") (define-sdl-func int ttf-get-font-style ((font (* ttf-font))) "TTF_GetFontStyle") (define-sdl-func void ttf-set-font-style ((font (* ttf-font)) (style int)) "TTF_SetFontStyle") (define-sdl-func int ttf-get-font-outline ((font (* ttf-font))) "TTF_GetFontOutline") (define-sdl-func void ttf-set-font-outline ((font (* ttf-font)) (outline int)) "TTF_SetFontOutline") (define-sdl-func int ttf-get-font-hinting ((font (* ttf-font))) "TTF_GetFontHinting") (define-sdl-func void ttf-set-font-hinting ((font (* ttf-font)) (hinting int)) "TTF_SetFontHinting") (define-sdl-func int ttf-font-height ((font (* ttf-font))) "TTF_FontHeight") (define-sdl-func int ttf-font-ascent ((font (* ttf-font))) "TTF_FontAscent") (define-sdl-func int ttf-font-descent ((font (* ttf-font))) "TTF_FontDescent") (define-sdl-func int ttf-font-line-skip ((font (* ttf-font))) "TTF_FontLineSkip") (define-sdl-func int ttf-get-font-kerning ((font (* ttf-font))) "TTF_GetFontKerning") (define-sdl-func void ttf-set-font-kerning ((font (* ttf-font)) (allowed int)) "TTF_SetFontKerning") (define-sdl-func long ttf-font-faces ((font (* ttf-font))) "TTF_FontFaces") (define-sdl-func int ttf-font-face-is-fixed-width ((font (* ttf-font))) "TTF_FontFaceIsFixedWidth") (define-sdl-func string ttf-font-face-family-name ((font (* ttf-font))) "TTF_FontFaceFamilyName") (define-sdl-func string ttf-font-face-style-name ((font (* ttf-font))) "TTF_FontFaceStyleName") (define-sdl-func int ttf-glyph-is-provided ((font (* ttf-font)) (ch uint16)) "TTF_GlyphIsProvided") (define-sdl-func int ttf-glyph-metrics ((font (* ttf-font)) (ch uint16) (minx (* int)) (maxx (* int)) (miny (* int)) (maxy (* int)) (advance (* int))) "TTF_GlyphMetrics") (define-sdl-func int ttf-size-text ((font (* ttf-font)) (text string) (w (* int)) (h (* int))) "TTF_SizeText") (define-sdl-func int ttf-size-ut-f8 ((font (* ttf-font)) (text string) (w (* int)) (h (* int))) "TTF_SizeUTF8") (define-sdl-func int ttf-size-unicode ((font (* ttf-font)) (text (* uint16)) (w (* int)) (h (* int))) "TTF_SizeUNICODE") (define-sdl-func (* sdl-surface-t) ttf-render-text-solid ((font (* ttf-font)) (text string) (fg int)) "TTF_RenderText_Solid") (define-sdl-func (* sdl-surface-t) ttf-render-ut-f8-solid ((font (* ttf-font)) (text string) (fg int)) "TTF_RenderUTF8_Solid") (define-sdl-func (* sdl-surface-t) ttf-render-unicode-solid ((font (* ttf-font)) (text (* uint16)) (fg int)) "TTF_RenderUNICODE_Solid") (define-sdl-func (* sdl-surface-t) ttf-render-glyph-solid ((font (* ttf-font)) (ch uint16) (fg int)) "TTF_RenderGlyph_Solid") (define-sdl-func (* sdl-surface-t) ttf-render-text-shaded ((font (* ttf-font)) (text string) (fg int) (bg int)) "TTF_RenderText_Shaded") (define-sdl-func (* sdl-surface-t) ttf-render-ut-f8-shaded ((font (* ttf-font)) (text string) (fg int) (bg int)) "TTF_RenderUTF8_Shaded") (define-sdl-func (* sdl-surface-t) ttf-render-unicode-shaded ((font (* ttf-font)) (text (* uint16)) (fg int) (bg int)) "TTF_RenderUNICODE_Shaded") (define-sdl-func (* sdl-surface-t) ttf-render-glyph-shaded ((font (* ttf-font)) (ch uint16) (fg int) (bg int)) "TTF_RenderGlyph_Shaded") (define-sdl-func (* sdl-surface-t) ttf-render-text-blended ((font (* ttf-font)) (text string) (fg int)) "TTF_RenderText_Blended") (define-sdl-func (* sdl-surface-t) ttf-render-ut-f8-blended ((font (* ttf-font)) (text string) (fg int)) "TTF_RenderUTF8_Blended") (define-sdl-func (* sdl-surface-t) ttf-render-unicode-blended ((font (* ttf-font)) (text (* uint16)) (fg int)) "TTF_RenderUNICODE_Blended") (define-sdl-func (* sdl-surface-t) ttf-render-text-blended-wrapped ((font (* ttf-font)) (text string) (fg int) (wrapLength uint32)) "TTF_RenderText_Blended_Wrapped") (define-sdl-func (* sdl-surface-t) ttf-render-ut-f8-blended-wrapped ((font (* ttf-font)) (text string) (fg int) (wrapLength uint32)) "TTF_RenderUTF8_Blended_Wrapped") (define-sdl-func (* sdl-surface-t) ttf-render-unicode-blended-wrapped ((font (* ttf-font)) (text (* uint16)) (fg int) (wrapLength uint32)) "TTF_RenderUNICODE_Blended_Wrapped") (define-sdl-func (* sdl-surface-t) ttf-render-glyph-blended ((font (* ttf-font)) (ch uint16) (fg int)) "TTF_RenderGlyph_Blended") (define-sdl-func void ttf-close-font ((font (* ttf-font))) "TTF_CloseFont") (define-sdl-func void ttf-quit () "TTF_Quit") (define-sdl-func int ttf-was-init () "TTF_WasInit") (define-sdl-func int ttf-get-font-kerning-size ((font (* ttf-font)) (prev_index int) (index int)) "TTF_GetFontKerningSize") (define-sdl-func int ttf-get-font-kerning-size-glyphs ((font (* ttf-font)) (previous_ch uint16) (ch uint16)) "TTF_GetFontKerningSizeGlyphs")
false
6d858e26113e4f73db6dd9d8df690a8460be6298
235b9cee2c18c6288b24d9fa71669a7ee1ee45eb
/compiler/remove-complex-opera*.ss
21bc414401e13c44f4a4c1b49624c2d859b959a0
[]
no_license
Tianji-Zhang/p423
f627046935a58c16a714b230d4a528bdcda41057
f66fc2167539615a9cd776343e48664b902d98b1
refs/heads/master
2021-01-18T04:33:38.905963
2013-05-18T05:56:41
2013-05-18T05:56:41
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
4,756
ss
remove-complex-opera*.ss
;; remove-complex-opera*.ss ;; ;; part of p423-sp12/srwaggon-p423 A6 ;; http://github.iu.edu/p423-sp12/srwaggon-p423 ;; introduced in A6 ;; 2012 / 3 / 21 ;; ;; Samuel Waggoner ;; [email protected] ;; 2012 / 3 / 23 #!chezscheme (library (compiler remove-complex-opera*) (export remove-complex-opera* ) (import ;; Load Chez Scheme primitives: (chezscheme) ;; Load compiler framework: (framework match) (framework helpers) (compiler helpers) ) #| || This pass removes nested primitive calls from within procedure || calls and other primitive calls, making the argument values || "trivial." Programs produced by this pass are in the language || described by the grammar below. || || Program ---> (letrec ([<label> (lambda (<uvar>*) <Body>)]*) <Body>) || Body ---> (locals (<uvar>*) <Tail>) || Tail ---> <Triv> || | (alloc <Value>) || | (<binop> <Triv> <Triv>) || | (<Triv> <Triv>*) || | (if <Pred> <Tail> <Tail>) || | (mref <Value> <Value>) || | (begin <Effect>* <Tail>) || Pred ---> (true) || | (false) || | (<relop> <Triv> <Triv>) || | (if <Pred> <Pred> <Pred>) || | (begin <Effect>* <Pred>) || Effect ---> (nop) || | (set! <uvar> <Value>) || | (if <Pred> <Effect> <Effect>) || | (begin <Effect>+) || Value ---> <Triv> || | (<binop> <Triv> <Triv>) || | (if <Pred> <Value> <Value>) || | (begin <Effect>* <Value>) || Triv ---> <uvar> | <int64> | <label> || |# (define-who (remove-complex-opera* program) (define (Body b) (define new-local* '()) (define (new-t) (let ([t (unique-name 't)]) (set! new-local* (cons t new-local*)) t)) (define (simple? xpr) (or (and (integer? xpr) (exact? xpr)) (label? xpr) (uvar? xpr) (binop? xpr) (relop? xpr) (eq? 'alloc xpr) (eq? 'mref xpr) (eq? 'mset! xpr) )) (define (trivialize xpr) (let-values ([(code set!*) (simplify xpr)]) (make-begin `(,@set!* ,code)))) (define (simplify xpr) (match xpr [() (values '() '())] [(,simple . ,[rem set!*]) (guard (simple? simple)) (values `(,simple ,rem ...) set!*)] [(,[Value -> v] . ,[rem set!*]) (let ([t (new-t)]) (values `(,t ,rem ...) `((set! ,t ,v) ,set!* ...)))] [,x (invalid who 'Complex-Opera* x)] )) (define (Value v) (match v [(alloc ,v^) (trivialize `(alloc ,v^))] [(if ,[Pred -> p] ,[c] ,[a]) `(if ,p ,c ,a)] [(begin ,[Effect -> e*] ... ,[v^]) (make-begin `(,e* ... ,v^))] [(mref ,v^ ,v&) (trivialize `(mref ,v^ ,v&))] [(,binop ,v^ ,v&) (guard (binop? binop)) (trivialize `(,binop ,v^ ,v&))] [(,v^ ,v* ...) (trivialize `(,v^ ,v* ...))] [,t (guard (triv? t)) t] [,else (invalid who 'Value else)] )) (define (Effect e) (match e [(mset! ,v ,v^ ,v&) (trivialize `(mset! ,v ,v^ ,v&))] [(nop) '(nop)] [(set! ,uvar ,[Value -> v]) `(set! ,uvar ,v)] [(if ,[Pred -> p] ,[c] ,[a]) `(if ,p ,c ,a)] [(begin ,[e*] ... ,[e]) (make-begin `(,e* ... ,e))] [(,v^ ,v* ...) (trivialize `(,v^ ,v* ...))] [,else (invalid who 'Effect else)] )) (define (Pred p) (match p [(true) '(true)] [(false) '(false)] [(if ,[t] ,[c] ,[a]) `(if ,t ,c ,a)] [(begin ,[Effect -> e*] ... ,[p]) (make-begin `(,e* ... ,p))] [(,relop ,v ,v^) (guard (relop? relop)) (trivialize `(,relop ,v ,v^))] [,else (invalid who 'Pred else)] )) (define (Tail t) (match t [(alloc ,v) (trivialize `(alloc ,v))] [(if ,[Pred -> p] ,[c] ,[a]) `(if ,p ,c ,a)] [(begin ,[Effect -> e*] ... ,[t]) (make-begin `(,e* ... ,t))] [(mref ,v ,v^) (trivialize `(mref ,v ,v^))] [(,binop ,v ,v^) (guard (binop? binop)) (trivialize `(,binop ,v ,v^))] [(,v ,v* ...) (trivialize `(,v ,v* ...))] [,t (guard (triv? t)) t] [,else (invalid who 'Tail else)] )) (match b [(locals (,local* ...) ,[Tail -> t]) `(locals (,local* ... ,new-local* ...) ,t)] [,else (invalid who 'Body else)] )) (define (Program p) (match p [(letrec ([,label (lambda (,uvar* ...) ,[Body -> b*])] ...) ,[Body -> b]) `(letrec ([,label (lambda (,uvar* ...) ,b*)] ...) ,b)] [,else (invalid who 'Program else)] )) (begin (Program program) ) )) ;; end library
false
03a33a49dd521e58f7774e092a1ac18cf1614403
a002d513cdb50dbf7c247cd894d73d0ba25e9181
/continuation2.ss
17901b9fe1c6e8087fd9970b36c2f83ec6a20865
[]
no_license
rahulkmr/chicken_musings
5bc325bad4a8e8fdb79580ba57b76ada9ed055b7
ec03e102088a7d3e5e20bd3722e5c97bcdc4f87e
refs/heads/master
2021-01-01T15:40:55.236050
2014-12-14T09:23:09
2014-12-14T09:23:09
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,055
ss
continuation2.ss
(define fail-stack '()) (define (fail) (if (not (pair? fail-stack)) (error "back-tracking stack exhausted") (begin (let ([back-track-point (car fail-stack)]) (set! fail-stack (cdr fail-stack)) (back-track-point back-track-point))))) (define (amb choices) (let ([cc (call/cc (lambda (cc) cc))]) (cond ([null? choices] (fail)) ([pair? choices] (let ([choice (car choices)]) (set! choices (cdr choices)) (set! fail-stack (cons cc fail-stack)) choice))))) (let ([a (amb (list 9 12 33 49 4 16 77))] [b (amb (list 1 22 3 47 51 65 17))] [c (amb (list 11 2 93 5 25 36 47))]) (if (not (and ; We're looking for dimensions of a legal right ; triangle using the Pythagorean theorem: (= (* c c) (+ (* a a) (* b b))) ; And, we want the second side to be the shorter one: (< b a))) (fail) #t) ; Print out the answer: (display (list a b c)) (newline))
false
52c0770432650be49b584b9a97c5e922c70fe706
3604661d960fac0f108f260525b90b0afc57ce55
/SICP-solutions/2/2.3-ret-1.scm
1736c922e92c189ce8012767572291fb65b58efa
[]
no_license
rythmE/SICP-solutions
b58a789f9cc90f10681183c8807fcc6a09837138
7386aa8188b51b3d28a663958b807dfaf4ee0c92
refs/heads/master
2021-01-13T08:09:23.217285
2016-09-27T11:33:11
2016-09-27T11:33:11
69,350,592
0
0
null
null
null
null
UTF-8
Scheme
false
false
537
scm
2.3-ret-1.scm
(define (make-ret start height width) (cons start (cons height width))) (define (get-height r) (car (cdr r))) (define (get-width r) (cdr (cdr r))) (define (start-point r) (car r)) (define (make-point x y) (cons x y)) (define (x-point p) (car p)) (define (y-point p) (cdr p)) (define (perimeter r) (* 2 (+ (get-height r) (get-width r)))) (define (area r) (* (get-height r) (get-width r))) (define (print-ret r) (newline) (display "peremeter is ") (display (perimeter r)) (newline) (display "area is ") (display (area r)))
false
2172b2c05afba96225b19d2e91cc758f5a6af98a
be06d133af3757958ac6ca43321d0327e3e3d477
/my-map/my-map.scm
2fa0b126628a48f6322131aa8ed51270bf18f8b4
[]
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
162
scm
my-map.scm
(define (my-map f lis) (cond ((null? lis) '()) (else (cons (f (car lis)) (my-map f (cdr lis)))))) (display (my-map (lambda (x) (* x x)) '(1 2 3))) (newline)
false
3b4bee2559af01a1cc5324b73b0cdfb620292a0f
665da87f9fefd8678b0635e31df3f3ff28a1d48c
/tests/debug/compilation/nqueens-chicken-cps-after-opt.scm
0a931efebfa613cd72ae8a013049f85eaec67288
[ "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
8,117
scm
nqueens-chicken-cps-after-opt.scm
[optimized] (lambda (k28) (let ((k29 (##core#lambda (r30) (let ((k32 (##core#lambda (r33) (let ((t35 (set! nqueens (lambda (k37 n1) (let ((try3 (##core#undefined))) (let ((ok?4 (##core#undefined))) (let ((t64 (set! try3 (lambda (k66 x10 y11 z12) (if (##core#inline "C_i_nullp" x10) (let ((r77 (##core#inline "C_i_nullp" y11))) (k66 (##core#cond r77 '1 '0))) (let ((k83 (##core#lambda (r84) (let ((k87 (##core#lambda (r88) (k66 (##core#inline_allocate ("C_a_i_plus" 4) r84 r88))))) (let ((r92 (##core#inline "C_i_cdr" x10))) (let ((r100 (##core#inline "C_i_car" x10))) (let ((r96 (##core#inline_allocate ("C_a_i_cons" 3) r100 y11))) (try3 k87 r92 r96 z12)))))))) (let ((k102 (##core#lambda (r103) (if r103 (let ((k109 (##core#lambda (r110) (let ((r118 (##core#inline "C_i_car" x10))) (let ((r114 (##core#inline_allocate ("C_a_i_cons" 3) r118 z12))) (try3 k83 r110 '() r114)))))) (let ((r122 (##core#inline "C_i_cdr" x10))) (append k109 r122 y11))) (k83 '0))))) (let ((r126 (##core#inline "C_i_car" x10))) (ok?4 k102 r126 '1 z12))))))))) (let ((t128 (set! ok?4 (lambda (k130 row13 dist14 placed15) (if (##core#inline "C_i_nullp" placed15) (k130 '#t) (let ((r178 (##core#inline "C_i_car" placed15))) (let ((r182 (##core#inline_allocate ("C_a_i_plus" 4) row13 dist14))) (if (##core#inline "C_i_nequalp" r178 r182) (k130 '#f) (let ((r166 (##core#inline "C_i_car" placed15))) (let ((r170 (##core#inline_allocate ("C_a_i_minus" 4) row13 dist14))) (if (##core#inline "C_i_nequalp" r166 r170) (k130 '#f) (let ((r154 (##core#inline_allocate ("C_a_i_plus" 4) dist14 '1))) (let ((r158 (##core#inline "C_i_cdr" placed15))) (ok?4 k130 row13 r154 r158)))))))))))))) (let ((k188 (##core#lambda (r189) (try3 k37 r189 '() '())))) (let ((loop6 (##core#undefined))) (let ((t44 (set! loop6 (lambda (k46 i7 l8) (if (##core#inline "C_i_nequalp" i7 '0) (k46 l8) (let ((r58 (##core#inline_allocate ("C_a_i_minus" 4) i7 '1))) (let ((r62 (##core#inline_allocate ("C_a_i_cons" 3) i7 l8))) (loop6 k46 r58 r62)))))))) (loop6 k188 n1 '())))))))))))) (let ((k191 (##core#lambda (r192) (let ((k194 (##core#lambda (r195) (k28 (##core#undefined))))) (let ((k197 (##core#lambda (r198) (r198 k194)))) (##sys#implicit-exit-handler k197)))))) (let ((k201 (##core#lambda (r202) (write k191 r202)))) (nqueens k201 '8))))))) (##core#callunit "eval" k32))))) (##core#callunit "library" k29)))
false
dc9ef317f73c9ceed598fa014f35b5562dcb1556
b43e36967e36167adcb4cc94f2f8adfb7281dbf1
/sicp/ch2/exercises/2.33.scm
ded9760e21b2a3a4cd82445241419718ba1a4c32
[]
no_license
ktosiu/snippets
79c58416117fa646ae06a8fd590193c9dd89f414
08e0655361695ed90e1b901d75f184c52bb72f35
refs/heads/master
2021-01-17T08:13:34.067768
2016-01-29T15:42:14
2016-01-29T15:42:14
53,054,819
1
0
null
2016-03-03T14:06:53
2016-03-03T14:06:53
null
UTF-8
Scheme
false
false
544
scm
2.33.scm
(define (accumulate op initial sequence) (if (null? sequence) initial (op (car sequence) (accumulate op initial (cdr sequence))))) (define (my-map p sequence) (accumulate (lambda (x y) (cons (p x) y)) '() sequence)) (define (my-append seq1 seq2) (accumulate cons seq2 seq1)) (define (len seq) (accumulate (lambda (x y) (+ 1 y) ) 0 seq)) (accumulate + 0 (list 1 2 3 4)) (my-map abs (list -1 -2 -3)) (my-append (list 1 2 3) (list 4 5 6)) (len (list 1 2 3 4 5 6 7 8 9))
false
1c2881f5fb6609ce05140a9b2d3109262db05ce5
d9426bff964eead8fb4c45a016cac45799ecb404
/file-server.ss
9eb1514fab4944ad3928619f9d59dd2322940c4e
[]
no_license
Glow-Lang/gloui
f4093a2fc94e94f1576957cd42e4595b88977928
bac31fab2ff8394cf8d5e727df49baf2bb3b66a1
refs/heads/main
2023-07-27T19:42:13.164645
2021-09-09T23:21:16
2021-09-09T23:21:16
404,895,672
3
0
null
2021-09-09T23:21:16
2021-09-09T23:17:37
JavaScript
UTF-8
Scheme
false
false
576
ss
file-server.ss
(import :mukn/gloui/server :std/net/httpd :std/srfi/13) (export #t) (def public_html #f) (def (static-file-directory) (or public_html (current-directory))) (def (static-file-request? req) (def path (http-request-path req)) (when (string=? path "/") (set! path "/index.html")) (let ((file (path-expand (string-copy path 1) (static-file-directory)))) (if (not (file-exists? file)) #f (list file)))) (define-endpoint static-file (cut static-file-request? <>)) (def (static-file/GET path) (http-response-file (current-http-response) [] path))
false
8ca62bac324fcd8214bb3e19a4e0c257491f2a57
d6910224fa09f702ff00eda6d83ba0631dd36e13
/2-3.scm
43260a6442029bda278fae4429d73db09b07f6aa
[]
no_license
jeffgyf/sicp_homework
786dd9f5eed315018279d79ad8a1c73662d9f4ce
f2564b06e19362af78206b51cd963ff34787a8e8
refs/heads/master
2020-04-12T14:17:03.342146
2019-05-06T05:54:27
2019-05-06T05:54:27
162,547,609
1
0
null
null
null
null
UTF-8
Scheme
false
false
2,292
scm
2-3.scm
;2.85 ;complex (put 'project 'complex (lambda (c) ((get 'make 'real) (real-part c)))) ;real (put 'project 'real (lambda (r) ((get 'make 'scheme-number) (round r)) ;rational (put 'project 'rational (lambda (r) ((get 'make 'scheme-number) (/ (numer r) (denom r))))) (define (drop d) (let ((project (get 'project (list (tag d)))) (cond (project (let ((projected (project d))) (cond ((equ? (raise projected) d) (drop projected)) (else d)))) (else d))))) ;2.86 (define (install-complex-package) ;; imported procedures from rectangular and polar packages (define (make-from-real-imag x y) ((get 'make-from-real-imag 'rectangular) x y)) (define (make-from-mag-ang r a) ((get 'make-from-mag-ang 'polar) r a)) ;; internal procedures (define (add-complex z1 z2) (make-from-real-imag (apply-generic 'add (real-part z1) (real-part z2)) (apply-generic 'add (imag-part z1) (imag-part z2)))) (define (sub-complex z1 z2) (make-from-real-imag (apply-generic 'sub (real-part z1) (real-part z2)) (- (imag-part z1) (imag-part z2)))) (define (mul-complex z1 z2) (make-from-mag-ang (apply-generic 'mul (magnitude z1) (magnitude z2)) (apply-generic 'add (angle z1) (angle z2)))) (define (div-complex z1 z2) (make-from-mag-ang (apply-generic 'div (magnitude z1) (magnitude z2)) (- (angle z1) (angle z2)))) ;; interface to rest of the system (define (tag z) (attach-tag 'complex z)) (put 'add '(complex complex) (lambda (z1 z2) (tag (add-complex z1 z2)))) (put 'sub '(complex complex) (lambda (z1 z2) (tag (sub-complex z1 z2)))) (put 'mul '(complex complex) (lambda (z1 z2) (tag (mul-complex z1 z2)))) (put 'div '(complex complex) (lambda (z1 z2) (tag (div-complex z1 z2)))) (put 'make-from-real-imag 'complex (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'complex (lambda (r a) (tag (make-from-mag-ang r a)))) 'done)
false
49117931e1eefa6b0bb0668c7a021ef8b37ac43d
defeada37d39bca09ef76f66f38683754c0a6aa0
/mscorlib/mono/security/asn1-convert.sls
fd887f456e7b2779d34eb3cb8e1caff6b53aeedc
[]
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,320
sls
asn1-convert.sls
(library (mono security asn1-convert) (export is? asn1-convert? to-int32 from-int32 to-date-time to-oid from-date-time from-unsigned-big-integer from-oid) (import (ironscheme-clr-port)) (define (is? a) (clr-is Mono.Security.ASN1Convert a)) (define (asn1-convert? a) (clr-is Mono.Security.ASN1Convert a)) (define-method-port to-int32 Mono.Security.ASN1Convert ToInt32 (static: System.Int32 Mono.Security.ASN1)) (define-method-port from-int32 Mono.Security.ASN1Convert FromInt32 (static: Mono.Security.ASN1 System.Int32)) (define-method-port to-date-time Mono.Security.ASN1Convert ToDateTime (static: System.DateTime Mono.Security.ASN1)) (define-method-port to-oid Mono.Security.ASN1Convert ToOid (static: System.String Mono.Security.ASN1)) (define-method-port from-date-time Mono.Security.ASN1Convert FromDateTime (static: Mono.Security.ASN1 System.DateTime)) (define-method-port from-unsigned-big-integer Mono.Security.ASN1Convert FromUnsignedBigInteger (static: Mono.Security.ASN1 System.Byte[])) (define-method-port from-oid Mono.Security.ASN1Convert FromOid (static: Mono.Security.ASN1 System.String)))
false
31d08e290b7d53fb5f97a0a2de7f2041137e386f
6b961ef37ff7018c8449d3fa05c04ffbda56582b
/bbn_cl/mach/cl/clchap7e.scm
d7c9abfd395d6093e3686afc9ac005f856696de5
[]
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
7,998
scm
clchap7e.scm
;;; ******** ;;; ;;; Copyright 1992 by BBN Systems and Technologies, A division of Bolt, ;;; Beranek and Newman Inc. ;;; ;;; Permission to use, copy, modify and distribute this software and its ;;; documentation is hereby granted without fee, provided that the above ;;; copyright notice and this permission appear in all copies and in ;;; supporting documentation, and that the name Bolt, Beranek and Newman ;;; Inc. not be used in advertising or publicity pertaining to distribution ;;; of the software without specific, written prior permission. In ;;; addition, BBN makes no respresentation about the suitability of this ;;; software for any purposes. It is provided "AS IS" without express or ;;; implied warranties including (but not limited to) all implied warranties ;;; of merchantability and fitness. In no event shall BBN be liable for any ;;; special, indirect or consequential damages whatsoever resulting from ;;; loss of use, data or profits, whether in an action of contract, ;;; negligence or other tortuous action, arising out of or in connection ;;; with the use or performance of this software. ;;; ;;; ******** ;;; ;;; ;; Chapter 7 -- Control Structure (proclaim '(insert-touches nil)) (export '(define-setf-method)) ;;define-setf-method (defparameter defsetf-error-string "Setf expander for ~S cannot be called with ~S args.") (defmacro define-setf-method (access-fn lambda-list &body body) "Syntax like DEFMACRO, but creates a Setf-Method generator. The body must be a form that returns the five magical values." (unless (symbolp access-fn) (error "~S -- Access-function name not a symbol in DEFINE-SETF-METHOD." access-fn)) (let ((whole (gensym)) (environment (gensym))) (multiple-value-bind (body local-decs doc) (parse-defmacro lambda-list whole body access-fn :environment environment :error-string 'defsetf-error-string) `(eval-when (load compile eval) (system-remprop ',access-fn 'setf-inverse) (setf (system-get ',access-fn 'setf-method-expander) (function (lambda (,whole ,environment) ,@local-decs (block ,access-fn ,body)))) ,@(when doc `((setf (documentation ',access-fn 'setf) ,doc))) ',access-fn)))) (define-setf-method getf (place prop &optional default &environment env) (multiple-value-bind (temps values stores set get) (get-setf-method place env) (let ((newval (gensym)) (ptemp (gensym)) (def-temp (gensym))) (values `(,@temps ,(car stores) ,ptemp ,@(if default `(,def-temp))) `(,@values ,get ,prop ,@(if default `(,default))) `(,newval) `(progn (setq ,(car stores) (putf ,(car stores) ,ptemp ,newval)) ,set ,newval) `(getf ,(car stores) ,ptemp ,@(if default `(,def-temp))))))) (define-setf-method get (symbol prop &optional default) "Get turns into %put. Don't put in the default unless it really is supplied and non-nil, so that we can transform into the get instruction whenever possible." (let ((symbol-temp (gensym)) (prop-temp (gensym)) (def-temp (gensym)) (newval (gensym))) (values `(,symbol-temp ,prop-temp ,@(if default `(,def-temp))) `(,symbol ,prop ,@(if default `(,default))) (list newval) `(%put ,symbol-temp ,prop-temp ,newval) `(get ,symbol-temp ,prop-temp ,@(if default `(,def-temp)))))) (define-setf-method system-get (symbol prop &optional default) "System-get turns into %system-put. Don't put in the default unless it really is supplied and non-nil, so that we can transform into the get instruction whenever possible." (let ((symbol-temp (gensym)) (prop-temp (gensym)) (def-temp (gensym)) (newval (gensym))) (values `(,symbol-temp ,prop-temp ,@(if default `(,def-temp))) `(,symbol ,prop ,@(if default `(,default))) (list newval) `(%system-put ,symbol-temp ,prop-temp ,newval) `(system-get ,symbol-temp ,prop-temp ,@(if default `(,def-temp)))))) (define-setf-method gethash (key hashtable &optional default) (let ((key-temp (gensym)) (hashtable-temp (gensym)) (default-temp (gensym)) (new-value-temp (gensym))) (values `(,key-temp ,hashtable-temp ,@(if default `(,default-temp))) `(,key ,hashtable ,@(if default `(,default))) `(,new-value-temp) `(%puthash ,key-temp ,hashtable-temp ,new-value-temp) `(gethash ,key-temp ,hashtable-temp ,@(if default `(,default-temp)))))) (defsetf subseq (sequence start &optional (end nil)) (v) `(progn (replace ,sequence ,v :start1 ,start :end1 ,end) ,v)) ;;; Evil hack invented by the gnomes of Vassar Street. The function ;;; arg must be constant. Get a setf method for this function, pretending ;;; that the final (list) arg to apply is just a normal arg. If the ;;; setting and access forms produced in this way reference this arg at ;;; the end, then just splice the APPLY back onto the front and the right ;;; thing happens. (define-setf-method apply (function &rest args &environment env) (if (and (listp function) (= (list-length function) 2) (eq (first function) 'function) (symbolp (second function))) (setq function (second function)) (error "Setf of Apply is only defined for function args of form #'symbol.")) (multiple-value-bind (dummies vals newval setter getter) (get-setf-method (cons function args) env) ;; Make sure the place is one that we can handle. (unless (and (eq (car (last args)) (car (last vals))) (eq (car (last getter)) (car (last dummies))) (eq (car (last setter)) (car (last dummies)))) (error "Apply of ~S not understood as a location for Setf." function)) (values dummies vals newval `(apply (function ,(car setter)) ,@(cdr setter)) `(apply (function ,(car getter)) ,@(cdr setter))))) '$split-file (define-setf-method ldb (bytespec place &environment env) "The first argument is a byte specifier. The second is any place form acceptable to SETF. Replaces the specified byte of the number in this place with bits from the low-order end of the new value." (multiple-value-bind (dummies vals newval setter getter) (get-setf-method place env) (let ((btemp (gensym)) (gnuval (gensym))) (values (cons btemp dummies) (cons bytespec vals) (list gnuval) `(let ((,(car newval) (dpb ,gnuval ,btemp ,getter))) ,setter ,gnuval) `(ldb ,btemp ,getter))))) (define-setf-method mask-field (bytespec place &environment env) "The first argument is a byte specifier. The second is any place form acceptable to SETF. Replaces the specified byte of the number in this place with bits from the corresponding position in the new value." (multiple-value-bind (dummies vals newval setter getter) (get-setf-method place env) (let ((btemp (gensym)) (gnuval (gensym))) (values (cons btemp dummies) (cons bytespec vals) (list gnuval) `(let ((,(car newval) (deposit-field ,gnuval ,btemp ,getter))) ,setter ,gnuval) `(mask-field ,btemp ,getter))))) (define-setf-method char-bit (place bit-name &environment env) "The first argument is any place form acceptable to SETF. Replaces the specified bit of the character in this place with the new value." (multiple-value-bind (dummies vals newval setter getter) (get-setf-method place env) (let ((btemp (gensym)) (gnuval (gensym))) (values `(,@dummies ,btemp) `(,@vals ,bit-name) (list gnuval) `(let ((,(car newval) (set-char-bit ,getter ,btemp ,gnuval))) ,setter ,gnuval) `(char-bit ,getter ,btemp))))) (define-setf-method the (type place &environment env) (multiple-value-bind (dummies vals newval setter getter) (get-setf-method place env) (values dummies vals newval (subst `(the ,type ,(car newval)) (car newval) setter) `(the ,type ,getter))))
false